Completed
Pull Request — master (#3676)
by Individual IT
12:49
created
lib/private/L10N/Factory.php 3 patches
Doc Comments   +5 added lines patch added patch discarded remove patch
@@ -318,6 +318,11 @@
 block discarded – undo
318 318
 	 */
319 319
 	// FIXME This method is only public, until OC_L10N does not need it anymore,
320 320
 	// FIXME This is also the reason, why it is not in the public interface
321
+
322
+	/**
323
+	 * @param string $app
324
+	 * @param string $lang
325
+	 */
321 326
 	public function getL10nFilesForApp($app, $lang) {
322 327
 		$languageFiles = [];
323 328
 
Please login to merge, or discard this patch.
Indentation   +387 added lines, -387 removed lines patch added patch discarded remove patch
@@ -40,391 +40,391 @@
 block discarded – undo
40 40
  */
41 41
 class Factory implements IFactory {
42 42
 
43
-	/** @var string */
44
-	protected $requestLanguage = '';
45
-
46
-	/**
47
-	 * cached instances
48
-	 * @var array Structure: Lang => App => \OCP\IL10N
49
-	 */
50
-	protected $instances = [];
51
-
52
-	/**
53
-	 * @var array Structure: App => string[]
54
-	 */
55
-	protected $availableLanguages = [];
56
-
57
-	/**
58
-	 * @var array Structure: string => callable
59
-	 */
60
-	protected $pluralFunctions = [];
61
-
62
-	/** @var IConfig */
63
-	protected $config;
64
-
65
-	/** @var IRequest */
66
-	protected $request;
67
-
68
-	/** @var IUserSession */
69
-	protected $userSession;
70
-
71
-	/** @var string */
72
-	protected $serverRoot;
73
-
74
-	/**
75
-	 * @param IConfig $config
76
-	 * @param IRequest $request
77
-	 * @param IUserSession $userSession
78
-	 * @param string $serverRoot
79
-	 */
80
-	public function __construct(IConfig $config,
81
-								IRequest $request,
82
-								IUserSession $userSession,
83
-								$serverRoot) {
84
-		$this->config = $config;
85
-		$this->request = $request;
86
-		$this->userSession = $userSession;
87
-		$this->serverRoot = $serverRoot;
88
-	}
89
-
90
-	/**
91
-	 * Get a language instance
92
-	 *
93
-	 * @param string $app
94
-	 * @param string|null $lang
95
-	 * @return \OCP\IL10N
96
-	 */
97
-	public function get($app, $lang = null) {
98
-		$app = \OC_App::cleanAppId($app);
99
-		if ($lang !== null) {
100
-			$lang = str_replace(array('\0', '/', '\\', '..'), '', (string) $lang);
101
-		}
102
-		if ($lang === null || !$this->languageExists($app, $lang)) {
103
-			$lang = $this->findLanguage($app);
104
-		}
105
-
106
-		if (!isset($this->instances[$lang][$app])) {
107
-			$this->instances[$lang][$app] = new L10N(
108
-				$this, $app, $lang,
109
-				$this->getL10nFilesForApp($app, $lang)
110
-			);
111
-		}
112
-
113
-		return $this->instances[$lang][$app];
114
-	}
115
-
116
-	/**
117
-	 * Find the best language
118
-	 *
119
-	 * @param string|null $app App id or null for core
120
-	 * @return string language If nothing works it returns 'en'
121
-	 */
122
-	public function findLanguage($app = null) {
123
-		if ($this->requestLanguage !== '' && $this->languageExists($app, $this->requestLanguage)) {
124
-			return $this->requestLanguage;
125
-		}
126
-
127
-		/**
128
-		 * At this point ownCloud might not yet be installed and thus the lookup
129
-		 * in the preferences table might fail. For this reason we need to check
130
-		 * whether the instance has already been installed
131
-		 *
132
-		 * @link https://github.com/owncloud/core/issues/21955
133
-		 */
134
-		if($this->config->getSystemValue('installed', false)) {
135
-			$userId = !is_null($this->userSession->getUser()) ? $this->userSession->getUser()->getUID() :  null;
136
-			if(!is_null($userId)) {
137
-				$userLang = $this->config->getUserValue($userId, 'core', 'lang', null);
138
-			} else {
139
-				$userLang = null;
140
-			}
141
-		} else {
142
-			$userId = null;
143
-			$userLang = null;
144
-		}
145
-
146
-		if ($userLang) {
147
-			$this->requestLanguage = $userLang;
148
-			if ($this->languageExists($app, $userLang)) {
149
-				return $userLang;
150
-			}
151
-		}
152
-
153
-		try {
154
-			// Try to get the language from the Request
155
-			$lang = $this->getLanguageFromRequest($app);
156
-			if ($userId !== null && $app === null && !$userLang) {
157
-				$this->config->setUserValue($userId, 'core', 'lang', $lang);
158
-			}
159
-			return $lang;
160
-		} catch (LanguageNotFoundException $e) {
161
-			// Finding language from request failed fall back to default language
162
-			$defaultLanguage = $this->config->getSystemValue('default_language', false);
163
-			if ($defaultLanguage !== false && $this->languageExists($app, $defaultLanguage)) {
164
-				return $defaultLanguage;
165
-			}
166
-		}
167
-
168
-		// We could not find any language so fall back to english
169
-		return 'en';
170
-	}
171
-
172
-	/**
173
-	 * Find all available languages for an app
174
-	 *
175
-	 * @param string|null $app App id or null for core
176
-	 * @return array an array of available languages
177
-	 */
178
-	public function findAvailableLanguages($app = null) {
179
-		$key = $app;
180
-		if ($key === null) {
181
-			$key = 'null';
182
-		}
183
-
184
-		// also works with null as key
185
-		if (!empty($this->availableLanguages[$key])) {
186
-			return $this->availableLanguages[$key];
187
-		}
188
-
189
-		$available = ['en']; //english is always available
190
-		$dir = $this->findL10nDir($app);
191
-		if (is_dir($dir)) {
192
-			$files = scandir($dir);
193
-			if ($files !== false) {
194
-				foreach ($files as $file) {
195
-					if (substr($file, -5) === '.json' && substr($file, 0, 4) !== 'l10n') {
196
-						$available[] = substr($file, 0, -5);
197
-					}
198
-				}
199
-			}
200
-		}
201
-
202
-		// merge with translations from theme
203
-		$theme = $this->config->getSystemValue('theme');
204
-		if (!empty($theme)) {
205
-			$themeDir = $this->serverRoot . '/themes/' . $theme . substr($dir, strlen($this->serverRoot));
206
-
207
-			if (is_dir($themeDir)) {
208
-				$files = scandir($themeDir);
209
-				if ($files !== false) {
210
-					foreach ($files as $file) {
211
-						if (substr($file, -5) === '.json' && substr($file, 0, 4) !== 'l10n') {
212
-							$available[] = substr($file, 0, -5);
213
-						}
214
-					}
215
-				}
216
-			}
217
-		}
218
-
219
-		$this->availableLanguages[$key] = $available;
220
-		return $available;
221
-	}
222
-
223
-	/**
224
-	 * @param string|null $app App id or null for core
225
-	 * @param string $lang
226
-	 * @return bool
227
-	 */
228
-	public function languageExists($app, $lang) {
229
-		if ($lang === 'en') {//english is always available
230
-			return true;
231
-		}
232
-
233
-		$languages = $this->findAvailableLanguages($app);
234
-		return array_search($lang, $languages) !== false;
235
-	}
236
-
237
-	/**
238
-	 * @param string|null $app
239
-	 * @return string
240
-	 * @throws LanguageNotFoundException
241
-	 */
242
-	private function getLanguageFromRequest($app) {
243
-		$header = $this->request->getHeader('ACCEPT_LANGUAGE');
244
-		if ($header) {
245
-			$available = $this->findAvailableLanguages($app);
246
-
247
-			// E.g. make sure that 'de' is before 'de_DE'.
248
-			sort($available);
249
-
250
-			$preferences = preg_split('/,\s*/', strtolower($header));
251
-			foreach ($preferences as $preference) {
252
-				list($preferred_language) = explode(';', $preference);
253
-				$preferred_language = str_replace('-', '_', $preferred_language);
254
-
255
-				foreach ($available as $available_language) {
256
-					if ($preferred_language === strtolower($available_language)) {
257
-						return $available_language;
258
-					}
259
-				}
260
-
261
-				// Fallback from de_De to de
262
-				foreach ($available as $available_language) {
263
-					if (substr($preferred_language, 0, 2) === $available_language) {
264
-						return $available_language;
265
-					}
266
-				}
267
-			}
268
-		}
269
-
270
-		throw new LanguageNotFoundException();
271
-	}
272
-
273
-	/**
274
-	 * @param string|null $app App id or null for core
275
-	 * @return string
276
-	 */
277
-	public function setLanguageFromRequest($app = null) {
278
-
279
-		try {
280
-			$requestLanguage = $this->getLanguageFromRequest($app);
281
-		} catch (LanguageNotFoundException $e) {
282
-			$requestLanguage = 'en';
283
-		}
284
-
285
-		if ($app === null && !$this->requestLanguage) {
286
-			$this->requestLanguage = $requestLanguage;
287
-		}
288
-		return $requestLanguage;
289
-	}
290
-
291
-	/**
292
-	 * Checks if $sub is a subdirectory of $parent
293
-	 *
294
-	 * @param string $sub
295
-	 * @param string $parent
296
-	 * @return bool
297
-	 */
298
-	private function isSubDirectory($sub, $parent) {
299
-		// Check whether $sub contains no ".."
300
-		if(strpos($sub, '..') !== false) {
301
-			return false;
302
-		}
303
-
304
-		// Check whether $sub is a subdirectory of $parent
305
-		if (strpos($sub, $parent) === 0) {
306
-			return true;
307
-		}
308
-
309
-		return false;
310
-	}
311
-
312
-	/**
313
-	 * Get a list of language files that should be loaded
314
-	 *
315
-	 * @param string $app
316
-	 * @param string $lang
317
-	 * @return string[]
318
-	 */
319
-	// FIXME This method is only public, until OC_L10N does not need it anymore,
320
-	// FIXME This is also the reason, why it is not in the public interface
321
-	public function getL10nFilesForApp($app, $lang) {
322
-		$languageFiles = [];
323
-
324
-		$i18nDir = $this->findL10nDir($app);
325
-		$transFile = strip_tags($i18nDir) . strip_tags($lang) . '.json';
326
-
327
-		if (($this->isSubDirectory($transFile, $this->serverRoot . '/core/l10n/')
328
-				|| $this->isSubDirectory($transFile, $this->serverRoot . '/lib/l10n/')
329
-				|| $this->isSubDirectory($transFile, $this->serverRoot . '/settings/l10n/')
330
-				|| $this->isSubDirectory($transFile, \OC_App::getAppPath($app) . '/l10n/')
331
-			)
332
-			&& file_exists($transFile)) {
333
-			// load the translations file
334
-			$languageFiles[] = $transFile;
335
-		}
336
-
337
-		// merge with translations from theme
338
-		$theme = $this->config->getSystemValue('theme');
339
-		if (!empty($theme)) {
340
-			$transFile = $this->serverRoot . '/themes/' . $theme . substr($transFile, strlen($this->serverRoot));
341
-			if (file_exists($transFile)) {
342
-				$languageFiles[] = $transFile;
343
-			}
344
-		}
345
-
346
-		return $languageFiles;
347
-	}
348
-
349
-	/**
350
-	 * find the l10n directory
351
-	 *
352
-	 * @param string $app App id or empty string for core
353
-	 * @return string directory
354
-	 */
355
-	protected function findL10nDir($app = null) {
356
-		if (in_array($app, ['core', 'lib', 'settings'])) {
357
-			if (file_exists($this->serverRoot . '/' . $app . '/l10n/')) {
358
-				return $this->serverRoot . '/' . $app . '/l10n/';
359
-			}
360
-		} else if ($app && \OC_App::getAppPath($app) !== false) {
361
-			// Check if the app is in the app folder
362
-			return \OC_App::getAppPath($app) . '/l10n/';
363
-		}
364
-		return $this->serverRoot . '/core/l10n/';
365
-	}
366
-
367
-
368
-	/**
369
-	 * Creates a function from the plural string
370
-	 *
371
-	 * Parts of the code is copied from Habari:
372
-	 * https://github.com/habari/system/blob/master/classes/locale.php
373
-	 * @param string $string
374
-	 * @return string
375
-	 */
376
-	public function createPluralFunction($string) {
377
-		if (isset($this->pluralFunctions[$string])) {
378
-			return $this->pluralFunctions[$string];
379
-		}
380
-
381
-		if (preg_match( '/^\s*nplurals\s*=\s*(\d+)\s*;\s*plural=(.*)$/u', $string, $matches)) {
382
-			// sanitize
383
-			$nplurals = preg_replace( '/[^0-9]/', '', $matches[1] );
384
-			$plural = preg_replace( '#[^n0-9:\(\)\?\|\&=!<>+*/\%-]#', '', $matches[2] );
385
-
386
-			$body = str_replace(
387
-				array( 'plural', 'n', '$n$plurals', ),
388
-				array( '$plural', '$n', '$nplurals', ),
389
-				'nplurals='. $nplurals . '; plural=' . $plural
390
-			);
391
-
392
-			// add parents
393
-			// important since PHP's ternary evaluates from left to right
394
-			$body .= ';';
395
-			$res = '';
396
-			$p = 0;
397
-			for($i = 0; $i < strlen($body); $i++) {
398
-				$ch = $body[$i];
399
-				switch ( $ch ) {
400
-					case '?':
401
-						$res .= ' ? (';
402
-						$p++;
403
-						break;
404
-					case ':':
405
-						$res .= ') : (';
406
-						break;
407
-					case ';':
408
-						$res .= str_repeat( ')', $p ) . ';';
409
-						$p = 0;
410
-						break;
411
-					default:
412
-						$res .= $ch;
413
-				}
414
-			}
415
-
416
-			$body = $res . 'return ($plural>=$nplurals?$nplurals-1:$plural);';
417
-			$function = create_function('$n', $body);
418
-			$this->pluralFunctions[$string] = $function;
419
-			return $function;
420
-		} else {
421
-			// default: one plural form for all cases but n==1 (english)
422
-			$function = create_function(
423
-				'$n',
424
-				'$nplurals=2;$plural=($n==1?0:1);return ($plural>=$nplurals?$nplurals-1:$plural);'
425
-			);
426
-			$this->pluralFunctions[$string] = $function;
427
-			return $function;
428
-		}
429
-	}
43
+    /** @var string */
44
+    protected $requestLanguage = '';
45
+
46
+    /**
47
+     * cached instances
48
+     * @var array Structure: Lang => App => \OCP\IL10N
49
+     */
50
+    protected $instances = [];
51
+
52
+    /**
53
+     * @var array Structure: App => string[]
54
+     */
55
+    protected $availableLanguages = [];
56
+
57
+    /**
58
+     * @var array Structure: string => callable
59
+     */
60
+    protected $pluralFunctions = [];
61
+
62
+    /** @var IConfig */
63
+    protected $config;
64
+
65
+    /** @var IRequest */
66
+    protected $request;
67
+
68
+    /** @var IUserSession */
69
+    protected $userSession;
70
+
71
+    /** @var string */
72
+    protected $serverRoot;
73
+
74
+    /**
75
+     * @param IConfig $config
76
+     * @param IRequest $request
77
+     * @param IUserSession $userSession
78
+     * @param string $serverRoot
79
+     */
80
+    public function __construct(IConfig $config,
81
+                                IRequest $request,
82
+                                IUserSession $userSession,
83
+                                $serverRoot) {
84
+        $this->config = $config;
85
+        $this->request = $request;
86
+        $this->userSession = $userSession;
87
+        $this->serverRoot = $serverRoot;
88
+    }
89
+
90
+    /**
91
+     * Get a language instance
92
+     *
93
+     * @param string $app
94
+     * @param string|null $lang
95
+     * @return \OCP\IL10N
96
+     */
97
+    public function get($app, $lang = null) {
98
+        $app = \OC_App::cleanAppId($app);
99
+        if ($lang !== null) {
100
+            $lang = str_replace(array('\0', '/', '\\', '..'), '', (string) $lang);
101
+        }
102
+        if ($lang === null || !$this->languageExists($app, $lang)) {
103
+            $lang = $this->findLanguage($app);
104
+        }
105
+
106
+        if (!isset($this->instances[$lang][$app])) {
107
+            $this->instances[$lang][$app] = new L10N(
108
+                $this, $app, $lang,
109
+                $this->getL10nFilesForApp($app, $lang)
110
+            );
111
+        }
112
+
113
+        return $this->instances[$lang][$app];
114
+    }
115
+
116
+    /**
117
+     * Find the best language
118
+     *
119
+     * @param string|null $app App id or null for core
120
+     * @return string language If nothing works it returns 'en'
121
+     */
122
+    public function findLanguage($app = null) {
123
+        if ($this->requestLanguage !== '' && $this->languageExists($app, $this->requestLanguage)) {
124
+            return $this->requestLanguage;
125
+        }
126
+
127
+        /**
128
+         * At this point ownCloud might not yet be installed and thus the lookup
129
+         * in the preferences table might fail. For this reason we need to check
130
+         * whether the instance has already been installed
131
+         *
132
+         * @link https://github.com/owncloud/core/issues/21955
133
+         */
134
+        if($this->config->getSystemValue('installed', false)) {
135
+            $userId = !is_null($this->userSession->getUser()) ? $this->userSession->getUser()->getUID() :  null;
136
+            if(!is_null($userId)) {
137
+                $userLang = $this->config->getUserValue($userId, 'core', 'lang', null);
138
+            } else {
139
+                $userLang = null;
140
+            }
141
+        } else {
142
+            $userId = null;
143
+            $userLang = null;
144
+        }
145
+
146
+        if ($userLang) {
147
+            $this->requestLanguage = $userLang;
148
+            if ($this->languageExists($app, $userLang)) {
149
+                return $userLang;
150
+            }
151
+        }
152
+
153
+        try {
154
+            // Try to get the language from the Request
155
+            $lang = $this->getLanguageFromRequest($app);
156
+            if ($userId !== null && $app === null && !$userLang) {
157
+                $this->config->setUserValue($userId, 'core', 'lang', $lang);
158
+            }
159
+            return $lang;
160
+        } catch (LanguageNotFoundException $e) {
161
+            // Finding language from request failed fall back to default language
162
+            $defaultLanguage = $this->config->getSystemValue('default_language', false);
163
+            if ($defaultLanguage !== false && $this->languageExists($app, $defaultLanguage)) {
164
+                return $defaultLanguage;
165
+            }
166
+        }
167
+
168
+        // We could not find any language so fall back to english
169
+        return 'en';
170
+    }
171
+
172
+    /**
173
+     * Find all available languages for an app
174
+     *
175
+     * @param string|null $app App id or null for core
176
+     * @return array an array of available languages
177
+     */
178
+    public function findAvailableLanguages($app = null) {
179
+        $key = $app;
180
+        if ($key === null) {
181
+            $key = 'null';
182
+        }
183
+
184
+        // also works with null as key
185
+        if (!empty($this->availableLanguages[$key])) {
186
+            return $this->availableLanguages[$key];
187
+        }
188
+
189
+        $available = ['en']; //english is always available
190
+        $dir = $this->findL10nDir($app);
191
+        if (is_dir($dir)) {
192
+            $files = scandir($dir);
193
+            if ($files !== false) {
194
+                foreach ($files as $file) {
195
+                    if (substr($file, -5) === '.json' && substr($file, 0, 4) !== 'l10n') {
196
+                        $available[] = substr($file, 0, -5);
197
+                    }
198
+                }
199
+            }
200
+        }
201
+
202
+        // merge with translations from theme
203
+        $theme = $this->config->getSystemValue('theme');
204
+        if (!empty($theme)) {
205
+            $themeDir = $this->serverRoot . '/themes/' . $theme . substr($dir, strlen($this->serverRoot));
206
+
207
+            if (is_dir($themeDir)) {
208
+                $files = scandir($themeDir);
209
+                if ($files !== false) {
210
+                    foreach ($files as $file) {
211
+                        if (substr($file, -5) === '.json' && substr($file, 0, 4) !== 'l10n') {
212
+                            $available[] = substr($file, 0, -5);
213
+                        }
214
+                    }
215
+                }
216
+            }
217
+        }
218
+
219
+        $this->availableLanguages[$key] = $available;
220
+        return $available;
221
+    }
222
+
223
+    /**
224
+     * @param string|null $app App id or null for core
225
+     * @param string $lang
226
+     * @return bool
227
+     */
228
+    public function languageExists($app, $lang) {
229
+        if ($lang === 'en') {//english is always available
230
+            return true;
231
+        }
232
+
233
+        $languages = $this->findAvailableLanguages($app);
234
+        return array_search($lang, $languages) !== false;
235
+    }
236
+
237
+    /**
238
+     * @param string|null $app
239
+     * @return string
240
+     * @throws LanguageNotFoundException
241
+     */
242
+    private function getLanguageFromRequest($app) {
243
+        $header = $this->request->getHeader('ACCEPT_LANGUAGE');
244
+        if ($header) {
245
+            $available = $this->findAvailableLanguages($app);
246
+
247
+            // E.g. make sure that 'de' is before 'de_DE'.
248
+            sort($available);
249
+
250
+            $preferences = preg_split('/,\s*/', strtolower($header));
251
+            foreach ($preferences as $preference) {
252
+                list($preferred_language) = explode(';', $preference);
253
+                $preferred_language = str_replace('-', '_', $preferred_language);
254
+
255
+                foreach ($available as $available_language) {
256
+                    if ($preferred_language === strtolower($available_language)) {
257
+                        return $available_language;
258
+                    }
259
+                }
260
+
261
+                // Fallback from de_De to de
262
+                foreach ($available as $available_language) {
263
+                    if (substr($preferred_language, 0, 2) === $available_language) {
264
+                        return $available_language;
265
+                    }
266
+                }
267
+            }
268
+        }
269
+
270
+        throw new LanguageNotFoundException();
271
+    }
272
+
273
+    /**
274
+     * @param string|null $app App id or null for core
275
+     * @return string
276
+     */
277
+    public function setLanguageFromRequest($app = null) {
278
+
279
+        try {
280
+            $requestLanguage = $this->getLanguageFromRequest($app);
281
+        } catch (LanguageNotFoundException $e) {
282
+            $requestLanguage = 'en';
283
+        }
284
+
285
+        if ($app === null && !$this->requestLanguage) {
286
+            $this->requestLanguage = $requestLanguage;
287
+        }
288
+        return $requestLanguage;
289
+    }
290
+
291
+    /**
292
+     * Checks if $sub is a subdirectory of $parent
293
+     *
294
+     * @param string $sub
295
+     * @param string $parent
296
+     * @return bool
297
+     */
298
+    private function isSubDirectory($sub, $parent) {
299
+        // Check whether $sub contains no ".."
300
+        if(strpos($sub, '..') !== false) {
301
+            return false;
302
+        }
303
+
304
+        // Check whether $sub is a subdirectory of $parent
305
+        if (strpos($sub, $parent) === 0) {
306
+            return true;
307
+        }
308
+
309
+        return false;
310
+    }
311
+
312
+    /**
313
+     * Get a list of language files that should be loaded
314
+     *
315
+     * @param string $app
316
+     * @param string $lang
317
+     * @return string[]
318
+     */
319
+    // FIXME This method is only public, until OC_L10N does not need it anymore,
320
+    // FIXME This is also the reason, why it is not in the public interface
321
+    public function getL10nFilesForApp($app, $lang) {
322
+        $languageFiles = [];
323
+
324
+        $i18nDir = $this->findL10nDir($app);
325
+        $transFile = strip_tags($i18nDir) . strip_tags($lang) . '.json';
326
+
327
+        if (($this->isSubDirectory($transFile, $this->serverRoot . '/core/l10n/')
328
+                || $this->isSubDirectory($transFile, $this->serverRoot . '/lib/l10n/')
329
+                || $this->isSubDirectory($transFile, $this->serverRoot . '/settings/l10n/')
330
+                || $this->isSubDirectory($transFile, \OC_App::getAppPath($app) . '/l10n/')
331
+            )
332
+            && file_exists($transFile)) {
333
+            // load the translations file
334
+            $languageFiles[] = $transFile;
335
+        }
336
+
337
+        // merge with translations from theme
338
+        $theme = $this->config->getSystemValue('theme');
339
+        if (!empty($theme)) {
340
+            $transFile = $this->serverRoot . '/themes/' . $theme . substr($transFile, strlen($this->serverRoot));
341
+            if (file_exists($transFile)) {
342
+                $languageFiles[] = $transFile;
343
+            }
344
+        }
345
+
346
+        return $languageFiles;
347
+    }
348
+
349
+    /**
350
+     * find the l10n directory
351
+     *
352
+     * @param string $app App id or empty string for core
353
+     * @return string directory
354
+     */
355
+    protected function findL10nDir($app = null) {
356
+        if (in_array($app, ['core', 'lib', 'settings'])) {
357
+            if (file_exists($this->serverRoot . '/' . $app . '/l10n/')) {
358
+                return $this->serverRoot . '/' . $app . '/l10n/';
359
+            }
360
+        } else if ($app && \OC_App::getAppPath($app) !== false) {
361
+            // Check if the app is in the app folder
362
+            return \OC_App::getAppPath($app) . '/l10n/';
363
+        }
364
+        return $this->serverRoot . '/core/l10n/';
365
+    }
366
+
367
+
368
+    /**
369
+     * Creates a function from the plural string
370
+     *
371
+     * Parts of the code is copied from Habari:
372
+     * https://github.com/habari/system/blob/master/classes/locale.php
373
+     * @param string $string
374
+     * @return string
375
+     */
376
+    public function createPluralFunction($string) {
377
+        if (isset($this->pluralFunctions[$string])) {
378
+            return $this->pluralFunctions[$string];
379
+        }
380
+
381
+        if (preg_match( '/^\s*nplurals\s*=\s*(\d+)\s*;\s*plural=(.*)$/u', $string, $matches)) {
382
+            // sanitize
383
+            $nplurals = preg_replace( '/[^0-9]/', '', $matches[1] );
384
+            $plural = preg_replace( '#[^n0-9:\(\)\?\|\&=!<>+*/\%-]#', '', $matches[2] );
385
+
386
+            $body = str_replace(
387
+                array( 'plural', 'n', '$n$plurals', ),
388
+                array( '$plural', '$n', '$nplurals', ),
389
+                'nplurals='. $nplurals . '; plural=' . $plural
390
+            );
391
+
392
+            // add parents
393
+            // important since PHP's ternary evaluates from left to right
394
+            $body .= ';';
395
+            $res = '';
396
+            $p = 0;
397
+            for($i = 0; $i < strlen($body); $i++) {
398
+                $ch = $body[$i];
399
+                switch ( $ch ) {
400
+                    case '?':
401
+                        $res .= ' ? (';
402
+                        $p++;
403
+                        break;
404
+                    case ':':
405
+                        $res .= ') : (';
406
+                        break;
407
+                    case ';':
408
+                        $res .= str_repeat( ')', $p ) . ';';
409
+                        $p = 0;
410
+                        break;
411
+                    default:
412
+                        $res .= $ch;
413
+                }
414
+            }
415
+
416
+            $body = $res . 'return ($plural>=$nplurals?$nplurals-1:$plural);';
417
+            $function = create_function('$n', $body);
418
+            $this->pluralFunctions[$string] = $function;
419
+            return $function;
420
+        } else {
421
+            // default: one plural form for all cases but n==1 (english)
422
+            $function = create_function(
423
+                '$n',
424
+                '$nplurals=2;$plural=($n==1?0:1);return ($plural>=$nplurals?$nplurals-1:$plural);'
425
+            );
426
+            $this->pluralFunctions[$string] = $function;
427
+            return $function;
428
+        }
429
+    }
430 430
 }
Please login to merge, or discard this patch.
Spacing   +25 added lines, -25 removed lines patch added patch discarded remove patch
@@ -131,9 +131,9 @@  discard block
 block discarded – undo
131 131
 		 *
132 132
 		 * @link https://github.com/owncloud/core/issues/21955
133 133
 		 */
134
-		if($this->config->getSystemValue('installed', false)) {
135
-			$userId = !is_null($this->userSession->getUser()) ? $this->userSession->getUser()->getUID() :  null;
136
-			if(!is_null($userId)) {
134
+		if ($this->config->getSystemValue('installed', false)) {
135
+			$userId = !is_null($this->userSession->getUser()) ? $this->userSession->getUser()->getUID() : null;
136
+			if (!is_null($userId)) {
137 137
 				$userLang = $this->config->getUserValue($userId, 'core', 'lang', null);
138 138
 			} else {
139 139
 				$userLang = null;
@@ -202,7 +202,7 @@  discard block
 block discarded – undo
202 202
 		// merge with translations from theme
203 203
 		$theme = $this->config->getSystemValue('theme');
204 204
 		if (!empty($theme)) {
205
-			$themeDir = $this->serverRoot . '/themes/' . $theme . substr($dir, strlen($this->serverRoot));
205
+			$themeDir = $this->serverRoot.'/themes/'.$theme.substr($dir, strlen($this->serverRoot));
206 206
 
207 207
 			if (is_dir($themeDir)) {
208 208
 				$files = scandir($themeDir);
@@ -297,7 +297,7 @@  discard block
 block discarded – undo
297 297
 	 */
298 298
 	private function isSubDirectory($sub, $parent) {
299 299
 		// Check whether $sub contains no ".."
300
-		if(strpos($sub, '..') !== false) {
300
+		if (strpos($sub, '..') !== false) {
301 301
 			return false;
302 302
 		}
303 303
 
@@ -322,12 +322,12 @@  discard block
 block discarded – undo
322 322
 		$languageFiles = [];
323 323
 
324 324
 		$i18nDir = $this->findL10nDir($app);
325
-		$transFile = strip_tags($i18nDir) . strip_tags($lang) . '.json';
325
+		$transFile = strip_tags($i18nDir).strip_tags($lang).'.json';
326 326
 
327
-		if (($this->isSubDirectory($transFile, $this->serverRoot . '/core/l10n/')
328
-				|| $this->isSubDirectory($transFile, $this->serverRoot . '/lib/l10n/')
329
-				|| $this->isSubDirectory($transFile, $this->serverRoot . '/settings/l10n/')
330
-				|| $this->isSubDirectory($transFile, \OC_App::getAppPath($app) . '/l10n/')
327
+		if (($this->isSubDirectory($transFile, $this->serverRoot.'/core/l10n/')
328
+				|| $this->isSubDirectory($transFile, $this->serverRoot.'/lib/l10n/')
329
+				|| $this->isSubDirectory($transFile, $this->serverRoot.'/settings/l10n/')
330
+				|| $this->isSubDirectory($transFile, \OC_App::getAppPath($app).'/l10n/')
331 331
 			)
332 332
 			&& file_exists($transFile)) {
333 333
 			// load the translations file
@@ -337,7 +337,7 @@  discard block
 block discarded – undo
337 337
 		// merge with translations from theme
338 338
 		$theme = $this->config->getSystemValue('theme');
339 339
 		if (!empty($theme)) {
340
-			$transFile = $this->serverRoot . '/themes/' . $theme . substr($transFile, strlen($this->serverRoot));
340
+			$transFile = $this->serverRoot.'/themes/'.$theme.substr($transFile, strlen($this->serverRoot));
341 341
 			if (file_exists($transFile)) {
342 342
 				$languageFiles[] = $transFile;
343 343
 			}
@@ -354,14 +354,14 @@  discard block
 block discarded – undo
354 354
 	 */
355 355
 	protected function findL10nDir($app = null) {
356 356
 		if (in_array($app, ['core', 'lib', 'settings'])) {
357
-			if (file_exists($this->serverRoot . '/' . $app . '/l10n/')) {
358
-				return $this->serverRoot . '/' . $app . '/l10n/';
357
+			if (file_exists($this->serverRoot.'/'.$app.'/l10n/')) {
358
+				return $this->serverRoot.'/'.$app.'/l10n/';
359 359
 			}
360 360
 		} else if ($app && \OC_App::getAppPath($app) !== false) {
361 361
 			// Check if the app is in the app folder
362
-			return \OC_App::getAppPath($app) . '/l10n/';
362
+			return \OC_App::getAppPath($app).'/l10n/';
363 363
 		}
364
-		return $this->serverRoot . '/core/l10n/';
364
+		return $this->serverRoot.'/core/l10n/';
365 365
 	}
366 366
 
367 367
 
@@ -378,15 +378,15 @@  discard block
 block discarded – undo
378 378
 			return $this->pluralFunctions[$string];
379 379
 		}
380 380
 
381
-		if (preg_match( '/^\s*nplurals\s*=\s*(\d+)\s*;\s*plural=(.*)$/u', $string, $matches)) {
381
+		if (preg_match('/^\s*nplurals\s*=\s*(\d+)\s*;\s*plural=(.*)$/u', $string, $matches)) {
382 382
 			// sanitize
383
-			$nplurals = preg_replace( '/[^0-9]/', '', $matches[1] );
384
-			$plural = preg_replace( '#[^n0-9:\(\)\?\|\&=!<>+*/\%-]#', '', $matches[2] );
383
+			$nplurals = preg_replace('/[^0-9]/', '', $matches[1]);
384
+			$plural = preg_replace('#[^n0-9:\(\)\?\|\&=!<>+*/\%-]#', '', $matches[2]);
385 385
 
386 386
 			$body = str_replace(
387
-				array( 'plural', 'n', '$n$plurals', ),
388
-				array( '$plural', '$n', '$nplurals', ),
389
-				'nplurals='. $nplurals . '; plural=' . $plural
387
+				array('plural', 'n', '$n$plurals',),
388
+				array('$plural', '$n', '$nplurals',),
389
+				'nplurals='.$nplurals.'; plural='.$plural
390 390
 			);
391 391
 
392 392
 			// add parents
@@ -394,9 +394,9 @@  discard block
 block discarded – undo
394 394
 			$body .= ';';
395 395
 			$res = '';
396 396
 			$p = 0;
397
-			for($i = 0; $i < strlen($body); $i++) {
397
+			for ($i = 0; $i < strlen($body); $i++) {
398 398
 				$ch = $body[$i];
399
-				switch ( $ch ) {
399
+				switch ($ch) {
400 400
 					case '?':
401 401
 						$res .= ' ? (';
402 402
 						$p++;
@@ -405,7 +405,7 @@  discard block
 block discarded – undo
405 405
 						$res .= ') : (';
406 406
 						break;
407 407
 					case ';':
408
-						$res .= str_repeat( ')', $p ) . ';';
408
+						$res .= str_repeat(')', $p).';';
409 409
 						$p = 0;
410 410
 						break;
411 411
 					default:
@@ -413,7 +413,7 @@  discard block
 block discarded – undo
413 413
 				}
414 414
 			}
415 415
 
416
-			$body = $res . 'return ($plural>=$nplurals?$nplurals-1:$plural);';
416
+			$body = $res.'return ($plural>=$nplurals?$nplurals-1:$plural);';
417 417
 			$function = create_function('$n', $body);
418 418
 			$this->pluralFunctions[$string] = $function;
419 419
 			return $function;
Please login to merge, or discard this patch.
lib/private/Installer.php 4 patches
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -45,7 +45,6 @@
 block discarded – undo
45 45
 use OC\App\CodeChecker\CodeChecker;
46 46
 use OC\App\CodeChecker\EmptyCheck;
47 47
 use OC\App\CodeChecker\PrivateCheck;
48
-use OC\Archive\Archive;
49 48
 use OC\Archive\TAR;
50 49
 use OC_App;
51 50
 use OC_DB;
Please login to merge, or discard this patch.
Indentation   +489 added lines, -489 removed lines patch added patch discarded remove patch
@@ -60,493 +60,493 @@
 block discarded – undo
60 60
  * This class provides the functionality needed to install, update and remove apps
61 61
  */
62 62
 class Installer {
63
-	/** @var AppFetcher */
64
-	private $appFetcher;
65
-	/** @var IClientService */
66
-	private $clientService;
67
-	/** @var ITempManager */
68
-	private $tempManager;
69
-	/** @var ILogger */
70
-	private $logger;
71
-
72
-	/**
73
-	 * @param AppFetcher $appFetcher
74
-	 * @param IClientService $clientService
75
-	 * @param ITempManager $tempManager
76
-	 * @param ILogger $logger
77
-	 */
78
-	public function __construct(AppFetcher $appFetcher,
79
-								IClientService $clientService,
80
-								ITempManager $tempManager,
81
-								ILogger $logger) {
82
-		$this->appFetcher = $appFetcher;
83
-		$this->clientService = $clientService;
84
-		$this->tempManager = $tempManager;
85
-		$this->logger = $logger;
86
-	}
87
-
88
-	/**
89
-	 * Installs an app that is located in one of the app folders already
90
-	 *
91
-	 * @param string $appId App to install
92
-	 * @throws \Exception
93
-	 * @return integer
94
-	 */
95
-	public function installApp($appId) {
96
-		$app = \OC_App::findAppInDirectories($appId);
97
-		if($app === false) {
98
-			throw new \Exception('App not found in any app directory');
99
-		}
100
-
101
-		$basedir = $app['path'].'/'.$appId;
102
-		$info = OC_App::getAppInfo($basedir.'/appinfo/info.xml', true);
103
-
104
-		//install the database
105
-		if(is_file($basedir.'/appinfo/database.xml')) {
106
-			if (\OC::$server->getAppConfig()->getValue($info['id'], 'installed_version') === null) {
107
-				OC_DB::createDbFromStructure($basedir.'/appinfo/database.xml');
108
-			} else {
109
-				OC_DB::updateDbFromStructure($basedir.'/appinfo/database.xml');
110
-			}
111
-		}
112
-
113
-		\OC_App::setupBackgroundJobs($info['background-jobs']);
114
-
115
-		//run appinfo/install.php
116
-		if((!isset($data['noinstall']) or $data['noinstall']==false)) {
117
-			self::includeAppScript($basedir . '/appinfo/install.php');
118
-		}
119
-
120
-		$appData = OC_App::getAppInfo($appId);
121
-		OC_App::executeRepairSteps($appId, $appData['repair-steps']['install']);
122
-
123
-		//set the installed version
124
-		\OC::$server->getConfig()->setAppValue($info['id'], 'installed_version', OC_App::getAppVersion($info['id'], false));
125
-		\OC::$server->getConfig()->setAppValue($info['id'], 'enabled', 'no');
126
-
127
-		//set remote/public handlers
128
-		foreach($info['remote'] as $name=>$path) {
129
-			\OC::$server->getConfig()->setAppValue('core', 'remote_'.$name, $info['id'].'/'.$path);
130
-		}
131
-		foreach($info['public'] as $name=>$path) {
132
-			\OC::$server->getConfig()->setAppValue('core', 'public_'.$name, $info['id'].'/'.$path);
133
-		}
134
-
135
-		OC_App::setAppTypes($info['id']);
136
-
137
-		return $info['id'];
138
-	}
139
-
140
-	/**
141
-	 * @brief checks whether or not an app is installed
142
-	 * @param string $app app
143
-	 * @returns bool
144
-	 *
145
-	 * Checks whether or not an app is installed, i.e. registered in apps table.
146
-	 */
147
-	public static function isInstalled( $app ) {
148
-		return (\OC::$server->getConfig()->getAppValue($app, "installed_version", null) !== null);
149
-	}
150
-
151
-	/**
152
-	 * Updates the specified app from the appstore
153
-	 *
154
-	 * @param string $appId
155
-	 * @return bool
156
-	 */
157
-	public function updateAppstoreApp($appId) {
158
-		if(self::isUpdateAvailable($appId, $this->appFetcher)) {
159
-			try {
160
-				$this->downloadApp($appId);
161
-			} catch (\Exception $e) {
162
-				$this->logger->error($e->getMessage(), ['app' => 'core']);
163
-				return false;
164
-			}
165
-			return OC_App::updateApp($appId);
166
-		}
167
-
168
-		return false;
169
-	}
170
-
171
-	/**
172
-	 * Downloads an app and puts it into the app directory
173
-	 *
174
-	 * @param string $appId
175
-	 *
176
-	 * @throws \Exception If the installation was not successful
177
-	 */
178
-	public function downloadApp($appId) {
179
-		$appId = strtolower($appId);
180
-
181
-		$apps = $this->appFetcher->get();
182
-		foreach($apps as $app) {
183
-			if($app['id'] === $appId) {
184
-				// Load the certificate
185
-				$certificate = new X509();
186
-				$certificate->loadCA(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crt'));
187
-				$loadedCertificate = $certificate->loadX509($app['certificate']);
188
-
189
-				// Verify if the certificate has been revoked
190
-				$crl = new X509();
191
-				$crl->loadCA(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crt'));
192
-				$crl->loadCRL(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crl'));
193
-				if($crl->validateSignature() !== true) {
194
-					throw new \Exception('Could not validate CRL signature');
195
-				}
196
-				$csn = $loadedCertificate['tbsCertificate']['serialNumber']->toString();
197
-				$revoked = $crl->getRevoked($csn);
198
-				if ($revoked !== false) {
199
-					throw new \Exception(
200
-						sprintf(
201
-							'Certificate "%s" has been revoked',
202
-							$csn
203
-						)
204
-					);
205
-				}
206
-
207
-				// Verify if the certificate has been issued by the Nextcloud Code Authority CA
208
-				if($certificate->validateSignature() !== true) {
209
-					throw new \Exception(
210
-						sprintf(
211
-							'App with id %s has a certificate not issued by a trusted Code Signing Authority',
212
-							$appId
213
-						)
214
-					);
215
-				}
216
-
217
-				// Verify if the certificate is issued for the requested app id
218
-				$certInfo = openssl_x509_parse($app['certificate']);
219
-				if(!isset($certInfo['subject']['CN'])) {
220
-					throw new \Exception(
221
-						sprintf(
222
-							'App with id %s has a cert with no CN',
223
-							$appId
224
-						)
225
-					);
226
-				}
227
-				if($certInfo['subject']['CN'] !== $appId) {
228
-					throw new \Exception(
229
-						sprintf(
230
-							'App with id %s has a cert issued to %s',
231
-							$appId,
232
-							$certInfo['subject']['CN']
233
-						)
234
-					);
235
-				}
236
-
237
-				// Download the release
238
-				$tempFile = $this->tempManager->getTemporaryFile('.tar.gz');
239
-				$client = $this->clientService->newClient();
240
-				$client->get($app['releases'][0]['download'], ['save_to' => $tempFile]);
241
-
242
-				// Check if the signature actually matches the downloaded content
243
-				$certificate = openssl_get_publickey($app['certificate']);
244
-				$verified = (bool)openssl_verify(file_get_contents($tempFile), base64_decode($app['releases'][0]['signature']), $certificate, OPENSSL_ALGO_SHA512);
245
-				openssl_free_key($certificate);
246
-
247
-				if($verified === true) {
248
-					// Seems to match, let's proceed
249
-					$extractDir = $this->tempManager->getTemporaryFolder();
250
-					$archive = new TAR($tempFile);
251
-
252
-					if($archive) {
253
-						$archive->extract($extractDir);
254
-						$allFiles = scandir($extractDir);
255
-						$folders = array_diff($allFiles, ['.', '..']);
256
-						$folders = array_values($folders);
257
-
258
-						if(count($folders) > 1) {
259
-							throw new \Exception(
260
-								sprintf(
261
-									'Extracted app %s has more than 1 folder',
262
-									$appId
263
-								)
264
-							);
265
-						}
266
-
267
-						// Check if appinfo/info.xml has the same app ID as well
268
-						$loadEntities = libxml_disable_entity_loader(false);
269
-						$xml = simplexml_load_file($extractDir . '/' . $folders[0] . '/appinfo/info.xml');
270
-						libxml_disable_entity_loader($loadEntities);
271
-						if((string)$xml->id !== $appId) {
272
-							throw new \Exception(
273
-								sprintf(
274
-									'App for id %s has a wrong app ID in info.xml: %s',
275
-									$appId,
276
-									(string)$xml->id
277
-								)
278
-							);
279
-						}
280
-
281
-						// Check if the version is lower than before
282
-						$currentVersion = OC_App::getAppVersion($appId);
283
-						$newVersion = (string)$xml->version;
284
-						if(version_compare($currentVersion, $newVersion) === 1) {
285
-							throw new \Exception(
286
-								sprintf(
287
-									'App for id %s has version %s and tried to update to lower version %s',
288
-									$appId,
289
-									$currentVersion,
290
-									$newVersion
291
-								)
292
-							);
293
-						}
294
-
295
-						$baseDir = OC_App::getInstallPath() . '/' . $appId;
296
-						// Remove old app with the ID if existent
297
-						OC_Helper::rmdirr($baseDir);
298
-						// Move to app folder
299
-						if(@mkdir($baseDir)) {
300
-							$extractDir .= '/' . $folders[0];
301
-							OC_Helper::copyr($extractDir, $baseDir);
302
-						}
303
-						OC_Helper::copyr($extractDir, $baseDir);
304
-						OC_Helper::rmdirr($extractDir);
305
-						return;
306
-					} else {
307
-						throw new \Exception(
308
-							sprintf(
309
-								'Could not extract app with ID %s to %s',
310
-								$appId,
311
-								$extractDir
312
-							)
313
-						);
314
-					}
315
-				} else {
316
-					// Signature does not match
317
-					throw new \Exception(
318
-						sprintf(
319
-							'App with id %s has invalid signature',
320
-							$appId
321
-						)
322
-					);
323
-				}
324
-			}
325
-		}
326
-
327
-		throw new \Exception(
328
-			sprintf(
329
-				'Could not download app %s',
330
-				$appId
331
-			)
332
-		);
333
-	}
334
-
335
-	/**
336
-	 * Check if an update for the app is available
337
-	 *
338
-	 * @param string $appId
339
-	 * @param AppFetcher $appFetcher
340
-	 * @return string|false false or the version number of the update
341
-	 */
342
-	public static function isUpdateAvailable($appId,
343
-									  AppFetcher $appFetcher) {
344
-		static $isInstanceReadyForUpdates = null;
345
-
346
-		if ($isInstanceReadyForUpdates === null) {
347
-			$installPath = OC_App::getInstallPath();
348
-			if ($installPath === false || $installPath === null) {
349
-				$isInstanceReadyForUpdates = false;
350
-			} else {
351
-				$isInstanceReadyForUpdates = true;
352
-			}
353
-		}
354
-
355
-		if ($isInstanceReadyForUpdates === false) {
356
-			return false;
357
-		}
358
-
359
-		$apps = $appFetcher->get();
360
-		foreach($apps as $app) {
361
-			if($app['id'] === $appId) {
362
-				$currentVersion = OC_App::getAppVersion($appId);
363
-				$newestVersion = $app['releases'][0]['version'];
364
-				if (version_compare($newestVersion, $currentVersion, '>')) {
365
-					return $newestVersion;
366
-				} else {
367
-					return false;
368
-				}
369
-			}
370
-		}
371
-
372
-		return false;
373
-	}
374
-
375
-	/**
376
-	 * Check if app is already downloaded
377
-	 * @param string $name name of the application to remove
378
-	 * @return boolean
379
-	 *
380
-	 * The function will check if the app is already downloaded in the apps repository
381
-	 */
382
-	public function isDownloaded($name) {
383
-		foreach(\OC::$APPSROOTS as $dir) {
384
-			$dirToTest  = $dir['path'];
385
-			$dirToTest .= '/';
386
-			$dirToTest .= $name;
387
-			$dirToTest .= '/';
388
-
389
-			if (is_dir($dirToTest)) {
390
-				return true;
391
-			}
392
-		}
393
-
394
-		return false;
395
-	}
396
-
397
-	/**
398
-	 * Removes an app
399
-	 * @param string $appId ID of the application to remove
400
-	 * @return boolean
401
-	 *
402
-	 *
403
-	 * This function works as follows
404
-	 *   -# call uninstall repair steps
405
-	 *   -# removing the files
406
-	 *
407
-	 * The function will not delete preferences, tables and the configuration,
408
-	 * this has to be done by the function oc_app_uninstall().
409
-	 */
410
-	public function removeApp($appId) {
411
-		if($this->isDownloaded( $appId )) {
412
-			$appDir = OC_App::getInstallPath() . '/' . $appId;
413
-			OC_Helper::rmdirr($appDir);
414
-			return true;
415
-		}else{
416
-			\OCP\Util::writeLog('core', 'can\'t remove app '.$appId.'. It is not installed.', \OCP\Util::ERROR);
417
-
418
-			return false;
419
-		}
420
-
421
-	}
422
-
423
-	/**
424
-	 * Installs shipped apps
425
-	 *
426
-	 * This function installs all apps found in the 'apps' directory that should be enabled by default;
427
-	 * @param bool $softErrors When updating we ignore errors and simply log them, better to have a
428
-	 *                         working ownCloud at the end instead of an aborted update.
429
-	 * @return array Array of error messages (appid => Exception)
430
-	 */
431
-	public static function installShippedApps($softErrors = false) {
432
-		$errors = [];
433
-		foreach(\OC::$APPSROOTS as $app_dir) {
434
-			if($dir = opendir( $app_dir['path'] )) {
435
-				while( false !== ( $filename = readdir( $dir ))) {
436
-					if( substr( $filename, 0, 1 ) != '.' and is_dir($app_dir['path']."/$filename") ) {
437
-						if( file_exists( $app_dir['path']."/$filename/appinfo/info.xml" )) {
438
-							if(!Installer::isInstalled($filename)) {
439
-								$info=OC_App::getAppInfo($filename);
440
-								$enabled = isset($info['default_enable']);
441
-								if (($enabled || in_array($filename, \OC::$server->getAppManager()->getAlwaysEnabledApps()))
442
-									  && \OC::$server->getConfig()->getAppValue($filename, 'enabled') !== 'no') {
443
-									if ($softErrors) {
444
-										try {
445
-											Installer::installShippedApp($filename);
446
-										} catch (HintException $e) {
447
-											if ($e->getPrevious() instanceof TableExistsException) {
448
-												$errors[$filename] = $e;
449
-												continue;
450
-											}
451
-											throw $e;
452
-										}
453
-									} else {
454
-										Installer::installShippedApp($filename);
455
-									}
456
-									\OC::$server->getConfig()->setAppValue($filename, 'enabled', 'yes');
457
-								}
458
-							}
459
-						}
460
-					}
461
-				}
462
-				closedir( $dir );
463
-			}
464
-		}
465
-
466
-		return $errors;
467
-	}
468
-
469
-	/**
470
-	 * install an app already placed in the app folder
471
-	 * @param string $app id of the app to install
472
-	 * @return integer
473
-	 */
474
-	public static function installShippedApp($app) {
475
-		//install the database
476
-		$appPath = OC_App::getAppPath($app);
477
-		if(is_file("$appPath/appinfo/database.xml")) {
478
-			try {
479
-				OC_DB::createDbFromStructure("$appPath/appinfo/database.xml");
480
-			} catch (TableExistsException $e) {
481
-				throw new HintException(
482
-					'Failed to enable app ' . $app,
483
-					'Please ask for help via one of our <a href="https://nextcloud.com/support/" target="_blank" rel="noreferrer">support channels</a>.',
484
-					0, $e
485
-				);
486
-			}
487
-		}
488
-
489
-		//run appinfo/install.php
490
-		\OC_App::registerAutoloading($app, $appPath);
491
-		self::includeAppScript("$appPath/appinfo/install.php");
492
-
493
-		$info = OC_App::getAppInfo($app);
494
-		if (is_null($info)) {
495
-			return false;
496
-		}
497
-		\OC_App::setupBackgroundJobs($info['background-jobs']);
498
-
499
-		OC_App::executeRepairSteps($app, $info['repair-steps']['install']);
500
-
501
-		$config = \OC::$server->getConfig();
502
-
503
-		$config->setAppValue($app, 'installed_version', OC_App::getAppVersion($app));
504
-		if (array_key_exists('ocsid', $info)) {
505
-			$config->setAppValue($app, 'ocsid', $info['ocsid']);
506
-		}
507
-
508
-		//set remote/public handlers
509
-		foreach($info['remote'] as $name=>$path) {
510
-			$config->setAppValue('core', 'remote_'.$name, $app.'/'.$path);
511
-		}
512
-		foreach($info['public'] as $name=>$path) {
513
-			$config->setAppValue('core', 'public_'.$name, $app.'/'.$path);
514
-		}
515
-
516
-		OC_App::setAppTypes($info['id']);
517
-
518
-		if(isset($info['settings']) && is_array($info['settings'])) {
519
-			// requires that autoloading was registered for the app,
520
-			// as happens before running the install.php some lines above
521
-			\OC::$server->getSettingsManager()->setupSettings($info['settings']);
522
-		}
523
-
524
-		return $info['id'];
525
-	}
526
-
527
-	/**
528
-	 * check the code of an app with some static code checks
529
-	 * @param string $folder the folder of the app to check
530
-	 * @return boolean true for app is o.k. and false for app is not o.k.
531
-	 */
532
-	public static function checkCode($folder) {
533
-		// is the code checker enabled?
534
-		if(!\OC::$server->getConfig()->getSystemValue('appcodechecker', false)) {
535
-			return true;
536
-		}
537
-
538
-		$codeChecker = new CodeChecker(new PrivateCheck(new EmptyCheck()));
539
-		$errors = $codeChecker->analyseFolder(basename($folder), $folder);
540
-
541
-		return empty($errors);
542
-	}
543
-
544
-	/**
545
-	 * @param string $script
546
-	 */
547
-	private static function includeAppScript($script) {
548
-		if ( file_exists($script) ){
549
-			include $script;
550
-		}
551
-	}
63
+    /** @var AppFetcher */
64
+    private $appFetcher;
65
+    /** @var IClientService */
66
+    private $clientService;
67
+    /** @var ITempManager */
68
+    private $tempManager;
69
+    /** @var ILogger */
70
+    private $logger;
71
+
72
+    /**
73
+     * @param AppFetcher $appFetcher
74
+     * @param IClientService $clientService
75
+     * @param ITempManager $tempManager
76
+     * @param ILogger $logger
77
+     */
78
+    public function __construct(AppFetcher $appFetcher,
79
+                                IClientService $clientService,
80
+                                ITempManager $tempManager,
81
+                                ILogger $logger) {
82
+        $this->appFetcher = $appFetcher;
83
+        $this->clientService = $clientService;
84
+        $this->tempManager = $tempManager;
85
+        $this->logger = $logger;
86
+    }
87
+
88
+    /**
89
+     * Installs an app that is located in one of the app folders already
90
+     *
91
+     * @param string $appId App to install
92
+     * @throws \Exception
93
+     * @return integer
94
+     */
95
+    public function installApp($appId) {
96
+        $app = \OC_App::findAppInDirectories($appId);
97
+        if($app === false) {
98
+            throw new \Exception('App not found in any app directory');
99
+        }
100
+
101
+        $basedir = $app['path'].'/'.$appId;
102
+        $info = OC_App::getAppInfo($basedir.'/appinfo/info.xml', true);
103
+
104
+        //install the database
105
+        if(is_file($basedir.'/appinfo/database.xml')) {
106
+            if (\OC::$server->getAppConfig()->getValue($info['id'], 'installed_version') === null) {
107
+                OC_DB::createDbFromStructure($basedir.'/appinfo/database.xml');
108
+            } else {
109
+                OC_DB::updateDbFromStructure($basedir.'/appinfo/database.xml');
110
+            }
111
+        }
112
+
113
+        \OC_App::setupBackgroundJobs($info['background-jobs']);
114
+
115
+        //run appinfo/install.php
116
+        if((!isset($data['noinstall']) or $data['noinstall']==false)) {
117
+            self::includeAppScript($basedir . '/appinfo/install.php');
118
+        }
119
+
120
+        $appData = OC_App::getAppInfo($appId);
121
+        OC_App::executeRepairSteps($appId, $appData['repair-steps']['install']);
122
+
123
+        //set the installed version
124
+        \OC::$server->getConfig()->setAppValue($info['id'], 'installed_version', OC_App::getAppVersion($info['id'], false));
125
+        \OC::$server->getConfig()->setAppValue($info['id'], 'enabled', 'no');
126
+
127
+        //set remote/public handlers
128
+        foreach($info['remote'] as $name=>$path) {
129
+            \OC::$server->getConfig()->setAppValue('core', 'remote_'.$name, $info['id'].'/'.$path);
130
+        }
131
+        foreach($info['public'] as $name=>$path) {
132
+            \OC::$server->getConfig()->setAppValue('core', 'public_'.$name, $info['id'].'/'.$path);
133
+        }
134
+
135
+        OC_App::setAppTypes($info['id']);
136
+
137
+        return $info['id'];
138
+    }
139
+
140
+    /**
141
+     * @brief checks whether or not an app is installed
142
+     * @param string $app app
143
+     * @returns bool
144
+     *
145
+     * Checks whether or not an app is installed, i.e. registered in apps table.
146
+     */
147
+    public static function isInstalled( $app ) {
148
+        return (\OC::$server->getConfig()->getAppValue($app, "installed_version", null) !== null);
149
+    }
150
+
151
+    /**
152
+     * Updates the specified app from the appstore
153
+     *
154
+     * @param string $appId
155
+     * @return bool
156
+     */
157
+    public function updateAppstoreApp($appId) {
158
+        if(self::isUpdateAvailable($appId, $this->appFetcher)) {
159
+            try {
160
+                $this->downloadApp($appId);
161
+            } catch (\Exception $e) {
162
+                $this->logger->error($e->getMessage(), ['app' => 'core']);
163
+                return false;
164
+            }
165
+            return OC_App::updateApp($appId);
166
+        }
167
+
168
+        return false;
169
+    }
170
+
171
+    /**
172
+     * Downloads an app and puts it into the app directory
173
+     *
174
+     * @param string $appId
175
+     *
176
+     * @throws \Exception If the installation was not successful
177
+     */
178
+    public function downloadApp($appId) {
179
+        $appId = strtolower($appId);
180
+
181
+        $apps = $this->appFetcher->get();
182
+        foreach($apps as $app) {
183
+            if($app['id'] === $appId) {
184
+                // Load the certificate
185
+                $certificate = new X509();
186
+                $certificate->loadCA(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crt'));
187
+                $loadedCertificate = $certificate->loadX509($app['certificate']);
188
+
189
+                // Verify if the certificate has been revoked
190
+                $crl = new X509();
191
+                $crl->loadCA(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crt'));
192
+                $crl->loadCRL(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crl'));
193
+                if($crl->validateSignature() !== true) {
194
+                    throw new \Exception('Could not validate CRL signature');
195
+                }
196
+                $csn = $loadedCertificate['tbsCertificate']['serialNumber']->toString();
197
+                $revoked = $crl->getRevoked($csn);
198
+                if ($revoked !== false) {
199
+                    throw new \Exception(
200
+                        sprintf(
201
+                            'Certificate "%s" has been revoked',
202
+                            $csn
203
+                        )
204
+                    );
205
+                }
206
+
207
+                // Verify if the certificate has been issued by the Nextcloud Code Authority CA
208
+                if($certificate->validateSignature() !== true) {
209
+                    throw new \Exception(
210
+                        sprintf(
211
+                            'App with id %s has a certificate not issued by a trusted Code Signing Authority',
212
+                            $appId
213
+                        )
214
+                    );
215
+                }
216
+
217
+                // Verify if the certificate is issued for the requested app id
218
+                $certInfo = openssl_x509_parse($app['certificate']);
219
+                if(!isset($certInfo['subject']['CN'])) {
220
+                    throw new \Exception(
221
+                        sprintf(
222
+                            'App with id %s has a cert with no CN',
223
+                            $appId
224
+                        )
225
+                    );
226
+                }
227
+                if($certInfo['subject']['CN'] !== $appId) {
228
+                    throw new \Exception(
229
+                        sprintf(
230
+                            'App with id %s has a cert issued to %s',
231
+                            $appId,
232
+                            $certInfo['subject']['CN']
233
+                        )
234
+                    );
235
+                }
236
+
237
+                // Download the release
238
+                $tempFile = $this->tempManager->getTemporaryFile('.tar.gz');
239
+                $client = $this->clientService->newClient();
240
+                $client->get($app['releases'][0]['download'], ['save_to' => $tempFile]);
241
+
242
+                // Check if the signature actually matches the downloaded content
243
+                $certificate = openssl_get_publickey($app['certificate']);
244
+                $verified = (bool)openssl_verify(file_get_contents($tempFile), base64_decode($app['releases'][0]['signature']), $certificate, OPENSSL_ALGO_SHA512);
245
+                openssl_free_key($certificate);
246
+
247
+                if($verified === true) {
248
+                    // Seems to match, let's proceed
249
+                    $extractDir = $this->tempManager->getTemporaryFolder();
250
+                    $archive = new TAR($tempFile);
251
+
252
+                    if($archive) {
253
+                        $archive->extract($extractDir);
254
+                        $allFiles = scandir($extractDir);
255
+                        $folders = array_diff($allFiles, ['.', '..']);
256
+                        $folders = array_values($folders);
257
+
258
+                        if(count($folders) > 1) {
259
+                            throw new \Exception(
260
+                                sprintf(
261
+                                    'Extracted app %s has more than 1 folder',
262
+                                    $appId
263
+                                )
264
+                            );
265
+                        }
266
+
267
+                        // Check if appinfo/info.xml has the same app ID as well
268
+                        $loadEntities = libxml_disable_entity_loader(false);
269
+                        $xml = simplexml_load_file($extractDir . '/' . $folders[0] . '/appinfo/info.xml');
270
+                        libxml_disable_entity_loader($loadEntities);
271
+                        if((string)$xml->id !== $appId) {
272
+                            throw new \Exception(
273
+                                sprintf(
274
+                                    'App for id %s has a wrong app ID in info.xml: %s',
275
+                                    $appId,
276
+                                    (string)$xml->id
277
+                                )
278
+                            );
279
+                        }
280
+
281
+                        // Check if the version is lower than before
282
+                        $currentVersion = OC_App::getAppVersion($appId);
283
+                        $newVersion = (string)$xml->version;
284
+                        if(version_compare($currentVersion, $newVersion) === 1) {
285
+                            throw new \Exception(
286
+                                sprintf(
287
+                                    'App for id %s has version %s and tried to update to lower version %s',
288
+                                    $appId,
289
+                                    $currentVersion,
290
+                                    $newVersion
291
+                                )
292
+                            );
293
+                        }
294
+
295
+                        $baseDir = OC_App::getInstallPath() . '/' . $appId;
296
+                        // Remove old app with the ID if existent
297
+                        OC_Helper::rmdirr($baseDir);
298
+                        // Move to app folder
299
+                        if(@mkdir($baseDir)) {
300
+                            $extractDir .= '/' . $folders[0];
301
+                            OC_Helper::copyr($extractDir, $baseDir);
302
+                        }
303
+                        OC_Helper::copyr($extractDir, $baseDir);
304
+                        OC_Helper::rmdirr($extractDir);
305
+                        return;
306
+                    } else {
307
+                        throw new \Exception(
308
+                            sprintf(
309
+                                'Could not extract app with ID %s to %s',
310
+                                $appId,
311
+                                $extractDir
312
+                            )
313
+                        );
314
+                    }
315
+                } else {
316
+                    // Signature does not match
317
+                    throw new \Exception(
318
+                        sprintf(
319
+                            'App with id %s has invalid signature',
320
+                            $appId
321
+                        )
322
+                    );
323
+                }
324
+            }
325
+        }
326
+
327
+        throw new \Exception(
328
+            sprintf(
329
+                'Could not download app %s',
330
+                $appId
331
+            )
332
+        );
333
+    }
334
+
335
+    /**
336
+     * Check if an update for the app is available
337
+     *
338
+     * @param string $appId
339
+     * @param AppFetcher $appFetcher
340
+     * @return string|false false or the version number of the update
341
+     */
342
+    public static function isUpdateAvailable($appId,
343
+                                        AppFetcher $appFetcher) {
344
+        static $isInstanceReadyForUpdates = null;
345
+
346
+        if ($isInstanceReadyForUpdates === null) {
347
+            $installPath = OC_App::getInstallPath();
348
+            if ($installPath === false || $installPath === null) {
349
+                $isInstanceReadyForUpdates = false;
350
+            } else {
351
+                $isInstanceReadyForUpdates = true;
352
+            }
353
+        }
354
+
355
+        if ($isInstanceReadyForUpdates === false) {
356
+            return false;
357
+        }
358
+
359
+        $apps = $appFetcher->get();
360
+        foreach($apps as $app) {
361
+            if($app['id'] === $appId) {
362
+                $currentVersion = OC_App::getAppVersion($appId);
363
+                $newestVersion = $app['releases'][0]['version'];
364
+                if (version_compare($newestVersion, $currentVersion, '>')) {
365
+                    return $newestVersion;
366
+                } else {
367
+                    return false;
368
+                }
369
+            }
370
+        }
371
+
372
+        return false;
373
+    }
374
+
375
+    /**
376
+     * Check if app is already downloaded
377
+     * @param string $name name of the application to remove
378
+     * @return boolean
379
+     *
380
+     * The function will check if the app is already downloaded in the apps repository
381
+     */
382
+    public function isDownloaded($name) {
383
+        foreach(\OC::$APPSROOTS as $dir) {
384
+            $dirToTest  = $dir['path'];
385
+            $dirToTest .= '/';
386
+            $dirToTest .= $name;
387
+            $dirToTest .= '/';
388
+
389
+            if (is_dir($dirToTest)) {
390
+                return true;
391
+            }
392
+        }
393
+
394
+        return false;
395
+    }
396
+
397
+    /**
398
+     * Removes an app
399
+     * @param string $appId ID of the application to remove
400
+     * @return boolean
401
+     *
402
+     *
403
+     * This function works as follows
404
+     *   -# call uninstall repair steps
405
+     *   -# removing the files
406
+     *
407
+     * The function will not delete preferences, tables and the configuration,
408
+     * this has to be done by the function oc_app_uninstall().
409
+     */
410
+    public function removeApp($appId) {
411
+        if($this->isDownloaded( $appId )) {
412
+            $appDir = OC_App::getInstallPath() . '/' . $appId;
413
+            OC_Helper::rmdirr($appDir);
414
+            return true;
415
+        }else{
416
+            \OCP\Util::writeLog('core', 'can\'t remove app '.$appId.'. It is not installed.', \OCP\Util::ERROR);
417
+
418
+            return false;
419
+        }
420
+
421
+    }
422
+
423
+    /**
424
+     * Installs shipped apps
425
+     *
426
+     * This function installs all apps found in the 'apps' directory that should be enabled by default;
427
+     * @param bool $softErrors When updating we ignore errors and simply log them, better to have a
428
+     *                         working ownCloud at the end instead of an aborted update.
429
+     * @return array Array of error messages (appid => Exception)
430
+     */
431
+    public static function installShippedApps($softErrors = false) {
432
+        $errors = [];
433
+        foreach(\OC::$APPSROOTS as $app_dir) {
434
+            if($dir = opendir( $app_dir['path'] )) {
435
+                while( false !== ( $filename = readdir( $dir ))) {
436
+                    if( substr( $filename, 0, 1 ) != '.' and is_dir($app_dir['path']."/$filename") ) {
437
+                        if( file_exists( $app_dir['path']."/$filename/appinfo/info.xml" )) {
438
+                            if(!Installer::isInstalled($filename)) {
439
+                                $info=OC_App::getAppInfo($filename);
440
+                                $enabled = isset($info['default_enable']);
441
+                                if (($enabled || in_array($filename, \OC::$server->getAppManager()->getAlwaysEnabledApps()))
442
+                                      && \OC::$server->getConfig()->getAppValue($filename, 'enabled') !== 'no') {
443
+                                    if ($softErrors) {
444
+                                        try {
445
+                                            Installer::installShippedApp($filename);
446
+                                        } catch (HintException $e) {
447
+                                            if ($e->getPrevious() instanceof TableExistsException) {
448
+                                                $errors[$filename] = $e;
449
+                                                continue;
450
+                                            }
451
+                                            throw $e;
452
+                                        }
453
+                                    } else {
454
+                                        Installer::installShippedApp($filename);
455
+                                    }
456
+                                    \OC::$server->getConfig()->setAppValue($filename, 'enabled', 'yes');
457
+                                }
458
+                            }
459
+                        }
460
+                    }
461
+                }
462
+                closedir( $dir );
463
+            }
464
+        }
465
+
466
+        return $errors;
467
+    }
468
+
469
+    /**
470
+     * install an app already placed in the app folder
471
+     * @param string $app id of the app to install
472
+     * @return integer
473
+     */
474
+    public static function installShippedApp($app) {
475
+        //install the database
476
+        $appPath = OC_App::getAppPath($app);
477
+        if(is_file("$appPath/appinfo/database.xml")) {
478
+            try {
479
+                OC_DB::createDbFromStructure("$appPath/appinfo/database.xml");
480
+            } catch (TableExistsException $e) {
481
+                throw new HintException(
482
+                    'Failed to enable app ' . $app,
483
+                    'Please ask for help via one of our <a href="https://nextcloud.com/support/" target="_blank" rel="noreferrer">support channels</a>.',
484
+                    0, $e
485
+                );
486
+            }
487
+        }
488
+
489
+        //run appinfo/install.php
490
+        \OC_App::registerAutoloading($app, $appPath);
491
+        self::includeAppScript("$appPath/appinfo/install.php");
492
+
493
+        $info = OC_App::getAppInfo($app);
494
+        if (is_null($info)) {
495
+            return false;
496
+        }
497
+        \OC_App::setupBackgroundJobs($info['background-jobs']);
498
+
499
+        OC_App::executeRepairSteps($app, $info['repair-steps']['install']);
500
+
501
+        $config = \OC::$server->getConfig();
502
+
503
+        $config->setAppValue($app, 'installed_version', OC_App::getAppVersion($app));
504
+        if (array_key_exists('ocsid', $info)) {
505
+            $config->setAppValue($app, 'ocsid', $info['ocsid']);
506
+        }
507
+
508
+        //set remote/public handlers
509
+        foreach($info['remote'] as $name=>$path) {
510
+            $config->setAppValue('core', 'remote_'.$name, $app.'/'.$path);
511
+        }
512
+        foreach($info['public'] as $name=>$path) {
513
+            $config->setAppValue('core', 'public_'.$name, $app.'/'.$path);
514
+        }
515
+
516
+        OC_App::setAppTypes($info['id']);
517
+
518
+        if(isset($info['settings']) && is_array($info['settings'])) {
519
+            // requires that autoloading was registered for the app,
520
+            // as happens before running the install.php some lines above
521
+            \OC::$server->getSettingsManager()->setupSettings($info['settings']);
522
+        }
523
+
524
+        return $info['id'];
525
+    }
526
+
527
+    /**
528
+     * check the code of an app with some static code checks
529
+     * @param string $folder the folder of the app to check
530
+     * @return boolean true for app is o.k. and false for app is not o.k.
531
+     */
532
+    public static function checkCode($folder) {
533
+        // is the code checker enabled?
534
+        if(!\OC::$server->getConfig()->getSystemValue('appcodechecker', false)) {
535
+            return true;
536
+        }
537
+
538
+        $codeChecker = new CodeChecker(new PrivateCheck(new EmptyCheck()));
539
+        $errors = $codeChecker->analyseFolder(basename($folder), $folder);
540
+
541
+        return empty($errors);
542
+    }
543
+
544
+    /**
545
+     * @param string $script
546
+     */
547
+    private static function includeAppScript($script) {
548
+        if ( file_exists($script) ){
549
+            include $script;
550
+        }
551
+    }
552 552
 }
Please login to merge, or discard this patch.
Spacing   +50 added lines, -50 removed lines patch added patch discarded remove patch
@@ -94,7 +94,7 @@  discard block
 block discarded – undo
94 94
 	 */
95 95
 	public function installApp($appId) {
96 96
 		$app = \OC_App::findAppInDirectories($appId);
97
-		if($app === false) {
97
+		if ($app === false) {
98 98
 			throw new \Exception('App not found in any app directory');
99 99
 		}
100 100
 
@@ -102,7 +102,7 @@  discard block
 block discarded – undo
102 102
 		$info = OC_App::getAppInfo($basedir.'/appinfo/info.xml', true);
103 103
 
104 104
 		//install the database
105
-		if(is_file($basedir.'/appinfo/database.xml')) {
105
+		if (is_file($basedir.'/appinfo/database.xml')) {
106 106
 			if (\OC::$server->getAppConfig()->getValue($info['id'], 'installed_version') === null) {
107 107
 				OC_DB::createDbFromStructure($basedir.'/appinfo/database.xml');
108 108
 			} else {
@@ -113,8 +113,8 @@  discard block
 block discarded – undo
113 113
 		\OC_App::setupBackgroundJobs($info['background-jobs']);
114 114
 
115 115
 		//run appinfo/install.php
116
-		if((!isset($data['noinstall']) or $data['noinstall']==false)) {
117
-			self::includeAppScript($basedir . '/appinfo/install.php');
116
+		if ((!isset($data['noinstall']) or $data['noinstall'] == false)) {
117
+			self::includeAppScript($basedir.'/appinfo/install.php');
118 118
 		}
119 119
 
120 120
 		$appData = OC_App::getAppInfo($appId);
@@ -125,10 +125,10 @@  discard block
 block discarded – undo
125 125
 		\OC::$server->getConfig()->setAppValue($info['id'], 'enabled', 'no');
126 126
 
127 127
 		//set remote/public handlers
128
-		foreach($info['remote'] as $name=>$path) {
128
+		foreach ($info['remote'] as $name=>$path) {
129 129
 			\OC::$server->getConfig()->setAppValue('core', 'remote_'.$name, $info['id'].'/'.$path);
130 130
 		}
131
-		foreach($info['public'] as $name=>$path) {
131
+		foreach ($info['public'] as $name=>$path) {
132 132
 			\OC::$server->getConfig()->setAppValue('core', 'public_'.$name, $info['id'].'/'.$path);
133 133
 		}
134 134
 
@@ -144,7 +144,7 @@  discard block
 block discarded – undo
144 144
 	 *
145 145
 	 * Checks whether or not an app is installed, i.e. registered in apps table.
146 146
 	 */
147
-	public static function isInstalled( $app ) {
147
+	public static function isInstalled($app) {
148 148
 		return (\OC::$server->getConfig()->getAppValue($app, "installed_version", null) !== null);
149 149
 	}
150 150
 
@@ -155,7 +155,7 @@  discard block
 block discarded – undo
155 155
 	 * @return bool
156 156
 	 */
157 157
 	public function updateAppstoreApp($appId) {
158
-		if(self::isUpdateAvailable($appId, $this->appFetcher)) {
158
+		if (self::isUpdateAvailable($appId, $this->appFetcher)) {
159 159
 			try {
160 160
 				$this->downloadApp($appId);
161 161
 			} catch (\Exception $e) {
@@ -179,18 +179,18 @@  discard block
 block discarded – undo
179 179
 		$appId = strtolower($appId);
180 180
 
181 181
 		$apps = $this->appFetcher->get();
182
-		foreach($apps as $app) {
183
-			if($app['id'] === $appId) {
182
+		foreach ($apps as $app) {
183
+			if ($app['id'] === $appId) {
184 184
 				// Load the certificate
185 185
 				$certificate = new X509();
186
-				$certificate->loadCA(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crt'));
186
+				$certificate->loadCA(file_get_contents(__DIR__.'/../../resources/codesigning/root.crt'));
187 187
 				$loadedCertificate = $certificate->loadX509($app['certificate']);
188 188
 
189 189
 				// Verify if the certificate has been revoked
190 190
 				$crl = new X509();
191
-				$crl->loadCA(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crt'));
192
-				$crl->loadCRL(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crl'));
193
-				if($crl->validateSignature() !== true) {
191
+				$crl->loadCA(file_get_contents(__DIR__.'/../../resources/codesigning/root.crt'));
192
+				$crl->loadCRL(file_get_contents(__DIR__.'/../../resources/codesigning/root.crl'));
193
+				if ($crl->validateSignature() !== true) {
194 194
 					throw new \Exception('Could not validate CRL signature');
195 195
 				}
196 196
 				$csn = $loadedCertificate['tbsCertificate']['serialNumber']->toString();
@@ -205,7 +205,7 @@  discard block
 block discarded – undo
205 205
 				}
206 206
 
207 207
 				// Verify if the certificate has been issued by the Nextcloud Code Authority CA
208
-				if($certificate->validateSignature() !== true) {
208
+				if ($certificate->validateSignature() !== true) {
209 209
 					throw new \Exception(
210 210
 						sprintf(
211 211
 							'App with id %s has a certificate not issued by a trusted Code Signing Authority',
@@ -216,7 +216,7 @@  discard block
 block discarded – undo
216 216
 
217 217
 				// Verify if the certificate is issued for the requested app id
218 218
 				$certInfo = openssl_x509_parse($app['certificate']);
219
-				if(!isset($certInfo['subject']['CN'])) {
219
+				if (!isset($certInfo['subject']['CN'])) {
220 220
 					throw new \Exception(
221 221
 						sprintf(
222 222
 							'App with id %s has a cert with no CN',
@@ -224,7 +224,7 @@  discard block
 block discarded – undo
224 224
 						)
225 225
 					);
226 226
 				}
227
-				if($certInfo['subject']['CN'] !== $appId) {
227
+				if ($certInfo['subject']['CN'] !== $appId) {
228 228
 					throw new \Exception(
229 229
 						sprintf(
230 230
 							'App with id %s has a cert issued to %s',
@@ -241,21 +241,21 @@  discard block
 block discarded – undo
241 241
 
242 242
 				// Check if the signature actually matches the downloaded content
243 243
 				$certificate = openssl_get_publickey($app['certificate']);
244
-				$verified = (bool)openssl_verify(file_get_contents($tempFile), base64_decode($app['releases'][0]['signature']), $certificate, OPENSSL_ALGO_SHA512);
244
+				$verified = (bool) openssl_verify(file_get_contents($tempFile), base64_decode($app['releases'][0]['signature']), $certificate, OPENSSL_ALGO_SHA512);
245 245
 				openssl_free_key($certificate);
246 246
 
247
-				if($verified === true) {
247
+				if ($verified === true) {
248 248
 					// Seems to match, let's proceed
249 249
 					$extractDir = $this->tempManager->getTemporaryFolder();
250 250
 					$archive = new TAR($tempFile);
251 251
 
252
-					if($archive) {
252
+					if ($archive) {
253 253
 						$archive->extract($extractDir);
254 254
 						$allFiles = scandir($extractDir);
255 255
 						$folders = array_diff($allFiles, ['.', '..']);
256 256
 						$folders = array_values($folders);
257 257
 
258
-						if(count($folders) > 1) {
258
+						if (count($folders) > 1) {
259 259
 							throw new \Exception(
260 260
 								sprintf(
261 261
 									'Extracted app %s has more than 1 folder',
@@ -266,22 +266,22 @@  discard block
 block discarded – undo
266 266
 
267 267
 						// Check if appinfo/info.xml has the same app ID as well
268 268
 						$loadEntities = libxml_disable_entity_loader(false);
269
-						$xml = simplexml_load_file($extractDir . '/' . $folders[0] . '/appinfo/info.xml');
269
+						$xml = simplexml_load_file($extractDir.'/'.$folders[0].'/appinfo/info.xml');
270 270
 						libxml_disable_entity_loader($loadEntities);
271
-						if((string)$xml->id !== $appId) {
271
+						if ((string) $xml->id !== $appId) {
272 272
 							throw new \Exception(
273 273
 								sprintf(
274 274
 									'App for id %s has a wrong app ID in info.xml: %s',
275 275
 									$appId,
276
-									(string)$xml->id
276
+									(string) $xml->id
277 277
 								)
278 278
 							);
279 279
 						}
280 280
 
281 281
 						// Check if the version is lower than before
282 282
 						$currentVersion = OC_App::getAppVersion($appId);
283
-						$newVersion = (string)$xml->version;
284
-						if(version_compare($currentVersion, $newVersion) === 1) {
283
+						$newVersion = (string) $xml->version;
284
+						if (version_compare($currentVersion, $newVersion) === 1) {
285 285
 							throw new \Exception(
286 286
 								sprintf(
287 287
 									'App for id %s has version %s and tried to update to lower version %s',
@@ -292,12 +292,12 @@  discard block
 block discarded – undo
292 292
 							);
293 293
 						}
294 294
 
295
-						$baseDir = OC_App::getInstallPath() . '/' . $appId;
295
+						$baseDir = OC_App::getInstallPath().'/'.$appId;
296 296
 						// Remove old app with the ID if existent
297 297
 						OC_Helper::rmdirr($baseDir);
298 298
 						// Move to app folder
299
-						if(@mkdir($baseDir)) {
300
-							$extractDir .= '/' . $folders[0];
299
+						if (@mkdir($baseDir)) {
300
+							$extractDir .= '/'.$folders[0];
301 301
 							OC_Helper::copyr($extractDir, $baseDir);
302 302
 						}
303 303
 						OC_Helper::copyr($extractDir, $baseDir);
@@ -357,8 +357,8 @@  discard block
 block discarded – undo
357 357
 		}
358 358
 
359 359
 		$apps = $appFetcher->get();
360
-		foreach($apps as $app) {
361
-			if($app['id'] === $appId) {
360
+		foreach ($apps as $app) {
361
+			if ($app['id'] === $appId) {
362 362
 				$currentVersion = OC_App::getAppVersion($appId);
363 363
 				$newestVersion = $app['releases'][0]['version'];
364 364
 				if (version_compare($newestVersion, $currentVersion, '>')) {
@@ -380,7 +380,7 @@  discard block
 block discarded – undo
380 380
 	 * The function will check if the app is already downloaded in the apps repository
381 381
 	 */
382 382
 	public function isDownloaded($name) {
383
-		foreach(\OC::$APPSROOTS as $dir) {
383
+		foreach (\OC::$APPSROOTS as $dir) {
384 384
 			$dirToTest  = $dir['path'];
385 385
 			$dirToTest .= '/';
386 386
 			$dirToTest .= $name;
@@ -408,11 +408,11 @@  discard block
 block discarded – undo
408 408
 	 * this has to be done by the function oc_app_uninstall().
409 409
 	 */
410 410
 	public function removeApp($appId) {
411
-		if($this->isDownloaded( $appId )) {
412
-			$appDir = OC_App::getInstallPath() . '/' . $appId;
411
+		if ($this->isDownloaded($appId)) {
412
+			$appDir = OC_App::getInstallPath().'/'.$appId;
413 413
 			OC_Helper::rmdirr($appDir);
414 414
 			return true;
415
-		}else{
415
+		} else {
416 416
 			\OCP\Util::writeLog('core', 'can\'t remove app '.$appId.'. It is not installed.', \OCP\Util::ERROR);
417 417
 
418 418
 			return false;
@@ -430,13 +430,13 @@  discard block
 block discarded – undo
430 430
 	 */
431 431
 	public static function installShippedApps($softErrors = false) {
432 432
 		$errors = [];
433
-		foreach(\OC::$APPSROOTS as $app_dir) {
434
-			if($dir = opendir( $app_dir['path'] )) {
435
-				while( false !== ( $filename = readdir( $dir ))) {
436
-					if( substr( $filename, 0, 1 ) != '.' and is_dir($app_dir['path']."/$filename") ) {
437
-						if( file_exists( $app_dir['path']."/$filename/appinfo/info.xml" )) {
438
-							if(!Installer::isInstalled($filename)) {
439
-								$info=OC_App::getAppInfo($filename);
433
+		foreach (\OC::$APPSROOTS as $app_dir) {
434
+			if ($dir = opendir($app_dir['path'])) {
435
+				while (false !== ($filename = readdir($dir))) {
436
+					if (substr($filename, 0, 1) != '.' and is_dir($app_dir['path']."/$filename")) {
437
+						if (file_exists($app_dir['path']."/$filename/appinfo/info.xml")) {
438
+							if (!Installer::isInstalled($filename)) {
439
+								$info = OC_App::getAppInfo($filename);
440 440
 								$enabled = isset($info['default_enable']);
441 441
 								if (($enabled || in_array($filename, \OC::$server->getAppManager()->getAlwaysEnabledApps()))
442 442
 									  && \OC::$server->getConfig()->getAppValue($filename, 'enabled') !== 'no') {
@@ -459,7 +459,7 @@  discard block
 block discarded – undo
459 459
 						}
460 460
 					}
461 461
 				}
462
-				closedir( $dir );
462
+				closedir($dir);
463 463
 			}
464 464
 		}
465 465
 
@@ -474,12 +474,12 @@  discard block
 block discarded – undo
474 474
 	public static function installShippedApp($app) {
475 475
 		//install the database
476 476
 		$appPath = OC_App::getAppPath($app);
477
-		if(is_file("$appPath/appinfo/database.xml")) {
477
+		if (is_file("$appPath/appinfo/database.xml")) {
478 478
 			try {
479 479
 				OC_DB::createDbFromStructure("$appPath/appinfo/database.xml");
480 480
 			} catch (TableExistsException $e) {
481 481
 				throw new HintException(
482
-					'Failed to enable app ' . $app,
482
+					'Failed to enable app '.$app,
483 483
 					'Please ask for help via one of our <a href="https://nextcloud.com/support/" target="_blank" rel="noreferrer">support channels</a>.',
484 484
 					0, $e
485 485
 				);
@@ -506,16 +506,16 @@  discard block
 block discarded – undo
506 506
 		}
507 507
 
508 508
 		//set remote/public handlers
509
-		foreach($info['remote'] as $name=>$path) {
509
+		foreach ($info['remote'] as $name=>$path) {
510 510
 			$config->setAppValue('core', 'remote_'.$name, $app.'/'.$path);
511 511
 		}
512
-		foreach($info['public'] as $name=>$path) {
512
+		foreach ($info['public'] as $name=>$path) {
513 513
 			$config->setAppValue('core', 'public_'.$name, $app.'/'.$path);
514 514
 		}
515 515
 
516 516
 		OC_App::setAppTypes($info['id']);
517 517
 
518
-		if(isset($info['settings']) && is_array($info['settings'])) {
518
+		if (isset($info['settings']) && is_array($info['settings'])) {
519 519
 			// requires that autoloading was registered for the app,
520 520
 			// as happens before running the install.php some lines above
521 521
 			\OC::$server->getSettingsManager()->setupSettings($info['settings']);
@@ -531,7 +531,7 @@  discard block
 block discarded – undo
531 531
 	 */
532 532
 	public static function checkCode($folder) {
533 533
 		// is the code checker enabled?
534
-		if(!\OC::$server->getConfig()->getSystemValue('appcodechecker', false)) {
534
+		if (!\OC::$server->getConfig()->getSystemValue('appcodechecker', false)) {
535 535
 			return true;
536 536
 		}
537 537
 
@@ -545,7 +545,7 @@  discard block
 block discarded – undo
545 545
 	 * @param string $script
546 546
 	 */
547 547
 	private static function includeAppScript($script) {
548
-		if ( file_exists($script) ){
548
+		if (file_exists($script)) {
549 549
 			include $script;
550 550
 		}
551 551
 	}
Please login to merge, or discard this patch.
Braces   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -412,7 +412,7 @@
 block discarded – undo
412 412
 			$appDir = OC_App::getInstallPath() . '/' . $appId;
413 413
 			OC_Helper::rmdirr($appDir);
414 414
 			return true;
415
-		}else{
415
+		} else{
416 416
 			\OCP\Util::writeLog('core', 'can\'t remove app '.$appId.'. It is not installed.', \OCP\Util::ERROR);
417 417
 
418 418
 			return false;
Please login to merge, or discard this patch.
apps/dav/lib/HookManager.php 3 patches
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -28,7 +28,6 @@
 block discarded – undo
28 28
 use OCP\IUserManager;
29 29
 use OCP\Util;
30 30
 use Symfony\Component\EventDispatcher\EventDispatcher;
31
-use Symfony\Component\EventDispatcher\GenericEvent;
32 31
 
33 32
 class HookManager {
34 33
 
Please login to merge, or discard this patch.
Indentation   +111 added lines, -111 removed lines patch added patch discarded remove patch
@@ -32,115 +32,115 @@
 block discarded – undo
32 32
 
33 33
 class HookManager {
34 34
 
35
-	/** @var IUserManager */
36
-	private $userManager;
37
-
38
-	/** @var SyncService */
39
-	private $syncService;
40
-
41
-	/** @var IUser[] */
42
-	private $usersToDelete;
43
-
44
-	/** @var CalDavBackend */
45
-	private $calDav;
46
-
47
-	/** @var CardDavBackend */
48
-	private $cardDav;
49
-
50
-	/** @var array */
51
-	private $calendarsToDelete;
52
-
53
-	/** @var array */
54
-	private $addressBooksToDelete;
55
-
56
-	/** @var EventDispatcher */
57
-	private $eventDispatcher;
58
-
59
-	public function __construct(IUserManager $userManager,
60
-								SyncService $syncService,
61
-								CalDavBackend $calDav,
62
-								CardDavBackend $cardDav,
63
-								EventDispatcher $eventDispatcher) {
64
-		$this->userManager = $userManager;
65
-		$this->syncService = $syncService;
66
-		$this->calDav = $calDav;
67
-		$this->cardDav = $cardDav;
68
-		$this->eventDispatcher = $eventDispatcher;
69
-	}
70
-
71
-	public function setup() {
72
-		Util::connectHook('OC_User',
73
-			'post_createUser',
74
-			$this,
75
-			'postCreateUser');
76
-		Util::connectHook('OC_User',
77
-			'pre_deleteUser',
78
-			$this,
79
-			'preDeleteUser');
80
-		Util::connectHook('OC_User',
81
-			'post_deleteUser',
82
-			$this,
83
-			'postDeleteUser');
84
-		Util::connectHook('OC_User',
85
-			'changeUser',
86
-			$this,
87
-			'changeUser');
88
-	}
89
-
90
-	public function postCreateUser($params) {
91
-		$user = $this->userManager->get($params['uid']);
92
-		$this->syncService->updateUser($user);
93
-	}
94
-
95
-	public function preDeleteUser($params) {
96
-		$uid = $params['uid'];
97
-		$this->usersToDelete[$uid] = $this->userManager->get($uid);
98
-		$this->calendarsToDelete = $this->calDav->getUsersOwnCalendars('principals/users/' . $uid);
99
-		$this->addressBooksToDelete = $this->cardDav->getUsersOwnAddressBooks('principals/users/' . $uid);
100
-	}
101
-
102
-	public function postDeleteUser($params) {
103
-		$uid = $params['uid'];
104
-		if (isset($this->usersToDelete[$uid])){
105
-			$this->syncService->deleteUser($this->usersToDelete[$uid]);
106
-		}
107
-
108
-		foreach ($this->calendarsToDelete as $calendar) {
109
-			$this->calDav->deleteCalendar($calendar['id']);
110
-		}
111
-		$this->calDav->deleteAllSharesByUser('principals/users/' . $uid);
112
-
113
-		foreach ($this->addressBooksToDelete as $addressBook) {
114
-			$this->cardDav->deleteAddressBook($addressBook['id']);
115
-		}
116
-	}
117
-
118
-	public function changeUser($params) {
119
-		$user = $params['user'];
120
-		$this->syncService->updateUser($user);
121
-	}
122
-
123
-	public function firstLogin(IUser $user = null) {
124
-		if (!is_null($user)) {
125
-			$principal = 'principals/users/' . $user->getUID();
126
-			if ($this->calDav->getCalendarsForUserCount($principal) === 0) {
127
-				try {
128
-					$this->calDav->createCalendar($principal, CalDavBackend::PERSONAL_CALENDAR_URI, [
129
-						'{DAV:}displayname' => CalDavBackend::PERSONAL_CALENDAR_NAME,
130
-					]);
131
-				} catch (\Exception $ex) {
132
-					\OC::$server->getLogger()->logException($ex);
133
-				}
134
-			}
135
-			if ($this->cardDav->getAddressBooksForUserCount($principal) === 0) {
136
-				try {
137
-					$this->cardDav->createAddressBook($principal, CardDavBackend::PERSONAL_ADDRESSBOOK_URI, [
138
-						'{DAV:}displayname' => CardDavBackend::PERSONAL_ADDRESSBOOK_NAME,
139
-					]);
140
-				} catch (\Exception $ex) {
141
-					\OC::$server->getLogger()->logException($ex);
142
-				}
143
-			}
144
-		}
145
-	}
35
+    /** @var IUserManager */
36
+    private $userManager;
37
+
38
+    /** @var SyncService */
39
+    private $syncService;
40
+
41
+    /** @var IUser[] */
42
+    private $usersToDelete;
43
+
44
+    /** @var CalDavBackend */
45
+    private $calDav;
46
+
47
+    /** @var CardDavBackend */
48
+    private $cardDav;
49
+
50
+    /** @var array */
51
+    private $calendarsToDelete;
52
+
53
+    /** @var array */
54
+    private $addressBooksToDelete;
55
+
56
+    /** @var EventDispatcher */
57
+    private $eventDispatcher;
58
+
59
+    public function __construct(IUserManager $userManager,
60
+                                SyncService $syncService,
61
+                                CalDavBackend $calDav,
62
+                                CardDavBackend $cardDav,
63
+                                EventDispatcher $eventDispatcher) {
64
+        $this->userManager = $userManager;
65
+        $this->syncService = $syncService;
66
+        $this->calDav = $calDav;
67
+        $this->cardDav = $cardDav;
68
+        $this->eventDispatcher = $eventDispatcher;
69
+    }
70
+
71
+    public function setup() {
72
+        Util::connectHook('OC_User',
73
+            'post_createUser',
74
+            $this,
75
+            'postCreateUser');
76
+        Util::connectHook('OC_User',
77
+            'pre_deleteUser',
78
+            $this,
79
+            'preDeleteUser');
80
+        Util::connectHook('OC_User',
81
+            'post_deleteUser',
82
+            $this,
83
+            'postDeleteUser');
84
+        Util::connectHook('OC_User',
85
+            'changeUser',
86
+            $this,
87
+            'changeUser');
88
+    }
89
+
90
+    public function postCreateUser($params) {
91
+        $user = $this->userManager->get($params['uid']);
92
+        $this->syncService->updateUser($user);
93
+    }
94
+
95
+    public function preDeleteUser($params) {
96
+        $uid = $params['uid'];
97
+        $this->usersToDelete[$uid] = $this->userManager->get($uid);
98
+        $this->calendarsToDelete = $this->calDav->getUsersOwnCalendars('principals/users/' . $uid);
99
+        $this->addressBooksToDelete = $this->cardDav->getUsersOwnAddressBooks('principals/users/' . $uid);
100
+    }
101
+
102
+    public function postDeleteUser($params) {
103
+        $uid = $params['uid'];
104
+        if (isset($this->usersToDelete[$uid])){
105
+            $this->syncService->deleteUser($this->usersToDelete[$uid]);
106
+        }
107
+
108
+        foreach ($this->calendarsToDelete as $calendar) {
109
+            $this->calDav->deleteCalendar($calendar['id']);
110
+        }
111
+        $this->calDav->deleteAllSharesByUser('principals/users/' . $uid);
112
+
113
+        foreach ($this->addressBooksToDelete as $addressBook) {
114
+            $this->cardDav->deleteAddressBook($addressBook['id']);
115
+        }
116
+    }
117
+
118
+    public function changeUser($params) {
119
+        $user = $params['user'];
120
+        $this->syncService->updateUser($user);
121
+    }
122
+
123
+    public function firstLogin(IUser $user = null) {
124
+        if (!is_null($user)) {
125
+            $principal = 'principals/users/' . $user->getUID();
126
+            if ($this->calDav->getCalendarsForUserCount($principal) === 0) {
127
+                try {
128
+                    $this->calDav->createCalendar($principal, CalDavBackend::PERSONAL_CALENDAR_URI, [
129
+                        '{DAV:}displayname' => CalDavBackend::PERSONAL_CALENDAR_NAME,
130
+                    ]);
131
+                } catch (\Exception $ex) {
132
+                    \OC::$server->getLogger()->logException($ex);
133
+                }
134
+            }
135
+            if ($this->cardDav->getAddressBooksForUserCount($principal) === 0) {
136
+                try {
137
+                    $this->cardDav->createAddressBook($principal, CardDavBackend::PERSONAL_ADDRESSBOOK_URI, [
138
+                        '{DAV:}displayname' => CardDavBackend::PERSONAL_ADDRESSBOOK_NAME,
139
+                    ]);
140
+                } catch (\Exception $ex) {
141
+                    \OC::$server->getLogger()->logException($ex);
142
+                }
143
+            }
144
+        }
145
+    }
146 146
 }
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -95,20 +95,20 @@  discard block
 block discarded – undo
95 95
 	public function preDeleteUser($params) {
96 96
 		$uid = $params['uid'];
97 97
 		$this->usersToDelete[$uid] = $this->userManager->get($uid);
98
-		$this->calendarsToDelete = $this->calDav->getUsersOwnCalendars('principals/users/' . $uid);
99
-		$this->addressBooksToDelete = $this->cardDav->getUsersOwnAddressBooks('principals/users/' . $uid);
98
+		$this->calendarsToDelete = $this->calDav->getUsersOwnCalendars('principals/users/'.$uid);
99
+		$this->addressBooksToDelete = $this->cardDav->getUsersOwnAddressBooks('principals/users/'.$uid);
100 100
 	}
101 101
 
102 102
 	public function postDeleteUser($params) {
103 103
 		$uid = $params['uid'];
104
-		if (isset($this->usersToDelete[$uid])){
104
+		if (isset($this->usersToDelete[$uid])) {
105 105
 			$this->syncService->deleteUser($this->usersToDelete[$uid]);
106 106
 		}
107 107
 
108 108
 		foreach ($this->calendarsToDelete as $calendar) {
109 109
 			$this->calDav->deleteCalendar($calendar['id']);
110 110
 		}
111
-		$this->calDav->deleteAllSharesByUser('principals/users/' . $uid);
111
+		$this->calDav->deleteAllSharesByUser('principals/users/'.$uid);
112 112
 
113 113
 		foreach ($this->addressBooksToDelete as $addressBook) {
114 114
 			$this->cardDav->deleteAddressBook($addressBook['id']);
@@ -122,7 +122,7 @@  discard block
 block discarded – undo
122 122
 
123 123
 	public function firstLogin(IUser $user = null) {
124 124
 		if (!is_null($user)) {
125
-			$principal = 'principals/users/' . $user->getUID();
125
+			$principal = 'principals/users/'.$user->getUID();
126 126
 			if ($this->calDav->getCalendarsForUserCount($principal) === 0) {
127 127
 				try {
128 128
 					$this->calDav->createCalendar($principal, CalDavBackend::PERSONAL_CALENDAR_URI, [
Please login to merge, or discard this patch.
apps/files_sharing/lib/Cache.php 3 patches
Doc Comments   +3 added lines patch added patch discarded remove patch
@@ -110,6 +110,9 @@
 block discarded – undo
110 110
 		return parent::moveFromCache($sourceCache, $sourcePath, $targetPath);
111 111
 	}
112 112
 
113
+	/**
114
+	 * @param ICacheEntry $entry
115
+	 */
113 116
 	protected function formatCacheEntry($entry) {
114 117
 		$path = isset($entry['path']) ? $entry['path'] : '';
115 118
 		$entry = parent::formatCacheEntry($entry);
Please login to merge, or discard this patch.
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -29,7 +29,6 @@
 block discarded – undo
29 29
 
30 30
 use OC\Files\Cache\Wrapper\CacheJail;
31 31
 use OCP\Files\Cache\ICacheEntry;
32
-use OCP\Files\Storage\IStorage;
33 32
 
34 33
 /**
35 34
  * Metadata cache for shared files
Please login to merge, or discard this patch.
Indentation   +99 added lines, -99 removed lines patch added patch discarded remove patch
@@ -37,103 +37,103 @@
 block discarded – undo
37 37
  * don't use this class directly if you need to get metadata, use \OC\Files\Filesystem::getFileInfo instead
38 38
  */
39 39
 class Cache extends CacheJail {
40
-	/**
41
-	 * @var \OCA\Files_Sharing\SharedStorage
42
-	 */
43
-	private $storage;
44
-
45
-	/**
46
-	 * @var ICacheEntry
47
-	 */
48
-	private $sourceRootInfo;
49
-
50
-	private $rootUnchanged = true;
51
-
52
-	private $ownerDisplayName;
53
-
54
-	/**
55
-	 * @param \OCA\Files_Sharing\SharedStorage $storage
56
-	 * @param ICacheEntry $sourceRootInfo
57
-	 */
58
-	public function __construct($storage, ICacheEntry $sourceRootInfo) {
59
-		$this->storage = $storage;
60
-		$this->sourceRootInfo = $sourceRootInfo;
61
-		parent::__construct(
62
-			null,
63
-			$this->sourceRootInfo->getPath()
64
-		);
65
-	}
66
-
67
-	public function getCache() {
68
-		if (is_null($this->cache)) {
69
-			$this->cache = $this->storage->getSourceStorage()->getCache();
70
-		}
71
-		return $this->cache;
72
-	}
73
-
74
-	public function getNumericStorageId() {
75
-		if (isset($this->numericId)) {
76
-			return $this->numericId;
77
-		} else {
78
-			return false;
79
-		}
80
-	}
81
-
82
-	public function get($file) {
83
-		if ($this->rootUnchanged && ($file === '' || $file === $this->sourceRootInfo->getId())) {
84
-			return $this->formatCacheEntry(clone $this->sourceRootInfo);
85
-		}
86
-		return parent::get($file);
87
-	}
88
-
89
-	public function update($id, array $data) {
90
-		$this->rootUnchanged = false;
91
-		parent::update($id, $data);
92
-	}
93
-
94
-	public function insert($file, array $data) {
95
-		$this->rootUnchanged = false;
96
-		return parent::insert($file, $data);
97
-	}
98
-
99
-	public function remove($file) {
100
-		$this->rootUnchanged = false;
101
-		parent::remove($file);
102
-	}
103
-
104
-	public function moveFromCache(\OCP\Files\Cache\ICache $sourceCache, $sourcePath, $targetPath) {
105
-		$this->rootUnchanged = false;
106
-		return parent::moveFromCache($sourceCache, $sourcePath, $targetPath);
107
-	}
108
-
109
-	protected function formatCacheEntry($entry) {
110
-		$path = isset($entry['path']) ? $entry['path'] : '';
111
-		$entry = parent::formatCacheEntry($entry);
112
-		$sharePermissions = $this->storage->getPermissions($path);
113
-		if (isset($entry['permissions'])) {
114
-			$entry['permissions'] &= $sharePermissions;
115
-		} else {
116
-			$entry['permissions'] = $sharePermissions;
117
-		}
118
-		$entry['uid_owner'] = $this->storage->getOwner($path);
119
-		$entry['displayname_owner'] = $this->getOwnerDisplayName();
120
-		if ($path === '') {
121
-			$entry['is_share_mount_point'] = true;
122
-		}
123
-		return $entry;
124
-	}
125
-
126
-	private function getOwnerDisplayName() {
127
-		if (!$this->ownerDisplayName) {
128
-			$this->ownerDisplayName = \OC_User::getDisplayName($this->storage->getOwner(''));
129
-		}
130
-		return $this->ownerDisplayName;
131
-	}
132
-
133
-	/**
134
-	 * remove all entries for files that are stored on the storage from the cache
135
-	 */
136
-	public function clear() {
137
-		// Not a valid action for Shared Cache
138
-	}
40
+    /**
41
+     * @var \OCA\Files_Sharing\SharedStorage
42
+     */
43
+    private $storage;
44
+
45
+    /**
46
+     * @var ICacheEntry
47
+     */
48
+    private $sourceRootInfo;
49
+
50
+    private $rootUnchanged = true;
51
+
52
+    private $ownerDisplayName;
53
+
54
+    /**
55
+     * @param \OCA\Files_Sharing\SharedStorage $storage
56
+     * @param ICacheEntry $sourceRootInfo
57
+     */
58
+    public function __construct($storage, ICacheEntry $sourceRootInfo) {
59
+        $this->storage = $storage;
60
+        $this->sourceRootInfo = $sourceRootInfo;
61
+        parent::__construct(
62
+            null,
63
+            $this->sourceRootInfo->getPath()
64
+        );
65
+    }
66
+
67
+    public function getCache() {
68
+        if (is_null($this->cache)) {
69
+            $this->cache = $this->storage->getSourceStorage()->getCache();
70
+        }
71
+        return $this->cache;
72
+    }
73
+
74
+    public function getNumericStorageId() {
75
+        if (isset($this->numericId)) {
76
+            return $this->numericId;
77
+        } else {
78
+            return false;
79
+        }
80
+    }
81
+
82
+    public function get($file) {
83
+        if ($this->rootUnchanged && ($file === '' || $file === $this->sourceRootInfo->getId())) {
84
+            return $this->formatCacheEntry(clone $this->sourceRootInfo);
85
+        }
86
+        return parent::get($file);
87
+    }
88
+
89
+    public function update($id, array $data) {
90
+        $this->rootUnchanged = false;
91
+        parent::update($id, $data);
92
+    }
93
+
94
+    public function insert($file, array $data) {
95
+        $this->rootUnchanged = false;
96
+        return parent::insert($file, $data);
97
+    }
98
+
99
+    public function remove($file) {
100
+        $this->rootUnchanged = false;
101
+        parent::remove($file);
102
+    }
103
+
104
+    public function moveFromCache(\OCP\Files\Cache\ICache $sourceCache, $sourcePath, $targetPath) {
105
+        $this->rootUnchanged = false;
106
+        return parent::moveFromCache($sourceCache, $sourcePath, $targetPath);
107
+    }
108
+
109
+    protected function formatCacheEntry($entry) {
110
+        $path = isset($entry['path']) ? $entry['path'] : '';
111
+        $entry = parent::formatCacheEntry($entry);
112
+        $sharePermissions = $this->storage->getPermissions($path);
113
+        if (isset($entry['permissions'])) {
114
+            $entry['permissions'] &= $sharePermissions;
115
+        } else {
116
+            $entry['permissions'] = $sharePermissions;
117
+        }
118
+        $entry['uid_owner'] = $this->storage->getOwner($path);
119
+        $entry['displayname_owner'] = $this->getOwnerDisplayName();
120
+        if ($path === '') {
121
+            $entry['is_share_mount_point'] = true;
122
+        }
123
+        return $entry;
124
+    }
125
+
126
+    private function getOwnerDisplayName() {
127
+        if (!$this->ownerDisplayName) {
128
+            $this->ownerDisplayName = \OC_User::getDisplayName($this->storage->getOwner(''));
129
+        }
130
+        return $this->ownerDisplayName;
131
+    }
132
+
133
+    /**
134
+     * remove all entries for files that are stored on the storage from the cache
135
+     */
136
+    public function clear() {
137
+        // Not a valid action for Shared Cache
138
+    }
139 139
 }
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/CalDavBackend.php 4 patches
Doc Comments   +9 added lines, -3 removed lines patch added patch discarded remove patch
@@ -158,7 +158,7 @@  discard block
 block discarded – undo
158 158
 	 *
159 159
 	 * By default this excludes the automatically generated birthday calendar
160 160
 	 *
161
-	 * @param $principalUri
161
+	 * @param string $principalUri
162 162
 	 * @param bool $excludeBirthday
163 163
 	 * @return int
164 164
 	 */
@@ -304,6 +304,9 @@  discard block
 block discarded – undo
304 304
 		return array_values($calendars);
305 305
 	}
306 306
 
307
+	/**
308
+	 * @param string $principalUri
309
+	 */
307 310
 	public function getUsersOwnCalendars($principalUri) {
308 311
 		$principalUri = $this->convertPrincipal($principalUri, true);
309 312
 		$fields = array_values($this->propertyMap);
@@ -878,7 +881,7 @@  discard block
 block discarded – undo
878 881
 	 * calendar-data. If the result of a subsequent GET to this object is not
879 882
 	 * the exact same as this request body, you should omit the ETag.
880 883
 	 *
881
-	 * @param mixed $calendarId
884
+	 * @param integer $calendarId
882 885
 	 * @param string $objectUri
883 886
 	 * @param string $calendarData
884 887
 	 * @return string
@@ -1370,7 +1373,7 @@  discard block
 block discarded – undo
1370 1373
 	 * @param string $principalUri
1371 1374
 	 * @param string $uri
1372 1375
 	 * @param array $properties
1373
-	 * @return mixed
1376
+	 * @return integer
1374 1377
 	 */
1375 1378
 	function createSubscription($principalUri, $uri, array $properties) {
1376 1379
 
@@ -1783,6 +1786,9 @@  discard block
 block discarded – undo
1783 1786
 		return $this->sharingBackend->applyShareAcl($resourceId, $acl);
1784 1787
 	}
1785 1788
 
1789
+	/**
1790
+	 * @param boolean $toV2
1791
+	 */
1786 1792
 	private function convertPrincipal($principalUri, $toV2) {
1787 1793
 		if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
1788 1794
 			list(, $name) = URLUtil::splitPath($principalUri);
Please login to merge, or discard this patch.
Indentation   +1739 added lines, -1739 removed lines patch added patch discarded remove patch
@@ -59,1744 +59,1744 @@
 block discarded – undo
59 59
  */
60 60
 class CalDavBackend extends AbstractBackend implements SyncSupport, SubscriptionSupport, SchedulingSupport {
61 61
 
62
-	const PERSONAL_CALENDAR_URI = 'personal';
63
-	const PERSONAL_CALENDAR_NAME = 'Personal';
64
-
65
-	/**
66
-	 * We need to specify a max date, because we need to stop *somewhere*
67
-	 *
68
-	 * On 32 bit system the maximum for a signed integer is 2147483647, so
69
-	 * MAX_DATE cannot be higher than date('Y-m-d', 2147483647) which results
70
-	 * in 2038-01-19 to avoid problems when the date is converted
71
-	 * to a unix timestamp.
72
-	 */
73
-	const MAX_DATE = '2038-01-01';
74
-
75
-	const ACCESS_PUBLIC = 4;
76
-	const CLASSIFICATION_PUBLIC = 0;
77
-	const CLASSIFICATION_PRIVATE = 1;
78
-	const CLASSIFICATION_CONFIDENTIAL = 2;
79
-
80
-	/**
81
-	 * List of CalDAV properties, and how they map to database field names
82
-	 * Add your own properties by simply adding on to this array.
83
-	 *
84
-	 * Note that only string-based properties are supported here.
85
-	 *
86
-	 * @var array
87
-	 */
88
-	public $propertyMap = [
89
-		'{DAV:}displayname'                          => 'displayname',
90
-		'{urn:ietf:params:xml:ns:caldav}calendar-description' => 'description',
91
-		'{urn:ietf:params:xml:ns:caldav}calendar-timezone'    => 'timezone',
92
-		'{http://apple.com/ns/ical/}calendar-order'  => 'calendarorder',
93
-		'{http://apple.com/ns/ical/}calendar-color'  => 'calendarcolor',
94
-	];
95
-
96
-	/**
97
-	 * List of subscription properties, and how they map to database field names.
98
-	 *
99
-	 * @var array
100
-	 */
101
-	public $subscriptionPropertyMap = [
102
-		'{DAV:}displayname'                                           => 'displayname',
103
-		'{http://apple.com/ns/ical/}refreshrate'                      => 'refreshrate',
104
-		'{http://apple.com/ns/ical/}calendar-order'                   => 'calendarorder',
105
-		'{http://apple.com/ns/ical/}calendar-color'                   => 'calendarcolor',
106
-		'{http://calendarserver.org/ns/}subscribed-strip-todos'       => 'striptodos',
107
-		'{http://calendarserver.org/ns/}subscribed-strip-alarms'      => 'stripalarms',
108
-		'{http://calendarserver.org/ns/}subscribed-strip-attachments' => 'stripattachments',
109
-	];
110
-
111
-	/**
112
-	 * @var string[] Map of uid => display name
113
-	 */
114
-	protected $userDisplayNames;
115
-
116
-	/** @var IDBConnection */
117
-	private $db;
118
-
119
-	/** @var Backend */
120
-	private $sharingBackend;
121
-
122
-	/** @var Principal */
123
-	private $principalBackend;
124
-
125
-	/** @var IUserManager */
126
-	private $userManager;
127
-
128
-	/** @var ISecureRandom */
129
-	private $random;
130
-
131
-	/** @var EventDispatcherInterface */
132
-	private $dispatcher;
133
-
134
-	/** @var bool */
135
-	private $legacyEndpoint;
136
-
137
-	/**
138
-	 * CalDavBackend constructor.
139
-	 *
140
-	 * @param IDBConnection $db
141
-	 * @param Principal $principalBackend
142
-	 * @param IUserManager $userManager
143
-	 * @param ISecureRandom $random
144
-	 * @param EventDispatcherInterface $dispatcher
145
-	 * @param bool $legacyEndpoint
146
-	 */
147
-	public function __construct(IDBConnection $db,
148
-								Principal $principalBackend,
149
-								IUserManager $userManager,
150
-								ISecureRandom $random,
151
-								EventDispatcherInterface $dispatcher,
152
-								$legacyEndpoint = false) {
153
-		$this->db = $db;
154
-		$this->principalBackend = $principalBackend;
155
-		$this->userManager = $userManager;
156
-		$this->sharingBackend = new Backend($this->db, $principalBackend, 'calendar');
157
-		$this->random = $random;
158
-		$this->dispatcher = $dispatcher;
159
-		$this->legacyEndpoint = $legacyEndpoint;
160
-	}
161
-
162
-	/**
163
-	 * Return the number of calendars for a principal
164
-	 *
165
-	 * By default this excludes the automatically generated birthday calendar
166
-	 *
167
-	 * @param $principalUri
168
-	 * @param bool $excludeBirthday
169
-	 * @return int
170
-	 */
171
-	public function getCalendarsForUserCount($principalUri, $excludeBirthday = true) {
172
-		$principalUri = $this->convertPrincipal($principalUri, true);
173
-		$query = $this->db->getQueryBuilder();
174
-		$query->select($query->createFunction('COUNT(*)'))
175
-			->from('calendars')
176
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
177
-
178
-		if ($excludeBirthday) {
179
-			$query->andWhere($query->expr()->neq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)));
180
-		}
181
-
182
-		return (int)$query->execute()->fetchColumn();
183
-	}
184
-
185
-	/**
186
-	 * Returns a list of calendars for a principal.
187
-	 *
188
-	 * Every project is an array with the following keys:
189
-	 *  * id, a unique id that will be used by other functions to modify the
190
-	 *    calendar. This can be the same as the uri or a database key.
191
-	 *  * uri, which the basename of the uri with which the calendar is
192
-	 *    accessed.
193
-	 *  * principaluri. The owner of the calendar. Almost always the same as
194
-	 *    principalUri passed to this method.
195
-	 *
196
-	 * Furthermore it can contain webdav properties in clark notation. A very
197
-	 * common one is '{DAV:}displayname'.
198
-	 *
199
-	 * Many clients also require:
200
-	 * {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
201
-	 * For this property, you can just return an instance of
202
-	 * Sabre\CalDAV\Property\SupportedCalendarComponentSet.
203
-	 *
204
-	 * If you return {http://sabredav.org/ns}read-only and set the value to 1,
205
-	 * ACL will automatically be put in read-only mode.
206
-	 *
207
-	 * @param string $principalUri
208
-	 * @return array
209
-	 */
210
-	function getCalendarsForUser($principalUri) {
211
-		$principalUriOriginal = $principalUri;
212
-		$principalUri = $this->convertPrincipal($principalUri, true);
213
-		$fields = array_values($this->propertyMap);
214
-		$fields[] = 'id';
215
-		$fields[] = 'uri';
216
-		$fields[] = 'synctoken';
217
-		$fields[] = 'components';
218
-		$fields[] = 'principaluri';
219
-		$fields[] = 'transparent';
220
-
221
-		// Making fields a comma-delimited list
222
-		$query = $this->db->getQueryBuilder();
223
-		$query->select($fields)->from('calendars')
224
-				->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
225
-				->orderBy('calendarorder', 'ASC');
226
-		$stmt = $query->execute();
227
-
228
-		$calendars = [];
229
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
230
-
231
-			$components = [];
232
-			if ($row['components']) {
233
-				$components = explode(',',$row['components']);
234
-			}
235
-
236
-			$calendar = [
237
-				'id' => $row['id'],
238
-				'uri' => $row['uri'],
239
-				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
240
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
241
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
242
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
243
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
244
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
245
-			];
246
-
247
-			foreach($this->propertyMap as $xmlName=>$dbName) {
248
-				$calendar[$xmlName] = $row[$dbName];
249
-			}
250
-
251
-			if (!isset($calendars[$calendar['id']])) {
252
-				$calendars[$calendar['id']] = $calendar;
253
-			}
254
-		}
255
-
256
-		$stmt->closeCursor();
257
-
258
-		// query for shared calendars
259
-		$principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
260
-		$principals[]= $principalUri;
261
-
262
-		$fields = array_values($this->propertyMap);
263
-		$fields[] = 'a.id';
264
-		$fields[] = 'a.uri';
265
-		$fields[] = 'a.synctoken';
266
-		$fields[] = 'a.components';
267
-		$fields[] = 'a.principaluri';
268
-		$fields[] = 'a.transparent';
269
-		$fields[] = 's.access';
270
-		$query = $this->db->getQueryBuilder();
271
-		$result = $query->select($fields)
272
-			->from('dav_shares', 's')
273
-			->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
274
-			->where($query->expr()->in('s.principaluri', $query->createParameter('principaluri')))
275
-			->andWhere($query->expr()->eq('s.type', $query->createParameter('type')))
276
-			->setParameter('type', 'calendar')
277
-			->setParameter('principaluri', $principals, \Doctrine\DBAL\Connection::PARAM_STR_ARRAY)
278
-			->execute();
279
-
280
-		while($row = $result->fetch()) {
281
-			list(, $name) = URLUtil::splitPath($row['principaluri']);
282
-			$uri = $row['uri'] . '_shared_by_' . $name;
283
-			$row['displayname'] = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
284
-			$components = [];
285
-			if ($row['components']) {
286
-				$components = explode(',',$row['components']);
287
-			}
288
-			$calendar = [
289
-				'id' => $row['id'],
290
-				'uri' => $uri,
291
-				'principaluri' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
292
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
293
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
294
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
295
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
296
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
297
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
298
-			];
299
-
300
-			foreach($this->propertyMap as $xmlName=>$dbName) {
301
-				$calendar[$xmlName] = $row[$dbName];
302
-			}
303
-
304
-			if (!isset($calendars[$calendar['id']])) {
305
-				$calendars[$calendar['id']] = $calendar;
306
-			}
307
-		}
308
-		$result->closeCursor();
309
-
310
-		return array_values($calendars);
311
-	}
312
-
313
-	public function getUsersOwnCalendars($principalUri) {
314
-		$principalUri = $this->convertPrincipal($principalUri, true);
315
-		$fields = array_values($this->propertyMap);
316
-		$fields[] = 'id';
317
-		$fields[] = 'uri';
318
-		$fields[] = 'synctoken';
319
-		$fields[] = 'components';
320
-		$fields[] = 'principaluri';
321
-		$fields[] = 'transparent';
322
-		// Making fields a comma-delimited list
323
-		$query = $this->db->getQueryBuilder();
324
-		$query->select($fields)->from('calendars')
325
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
326
-			->orderBy('calendarorder', 'ASC');
327
-		$stmt = $query->execute();
328
-		$calendars = [];
329
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
330
-			$components = [];
331
-			if ($row['components']) {
332
-				$components = explode(',',$row['components']);
333
-			}
334
-			$calendar = [
335
-				'id' => $row['id'],
336
-				'uri' => $row['uri'],
337
-				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
338
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
339
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
340
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
341
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
342
-			];
343
-			foreach($this->propertyMap as $xmlName=>$dbName) {
344
-				$calendar[$xmlName] = $row[$dbName];
345
-			}
346
-			if (!isset($calendars[$calendar['id']])) {
347
-				$calendars[$calendar['id']] = $calendar;
348
-			}
349
-		}
350
-		$stmt->closeCursor();
351
-		return array_values($calendars);
352
-	}
353
-
354
-
355
-	private function getUserDisplayName($uid) {
356
-		if (!isset($this->userDisplayNames[$uid])) {
357
-			$user = $this->userManager->get($uid);
358
-
359
-			if ($user instanceof IUser) {
360
-				$this->userDisplayNames[$uid] = $user->getDisplayName();
361
-			} else {
362
-				$this->userDisplayNames[$uid] = $uid;
363
-			}
364
-		}
365
-
366
-		return $this->userDisplayNames[$uid];
367
-	}
62
+    const PERSONAL_CALENDAR_URI = 'personal';
63
+    const PERSONAL_CALENDAR_NAME = 'Personal';
64
+
65
+    /**
66
+     * We need to specify a max date, because we need to stop *somewhere*
67
+     *
68
+     * On 32 bit system the maximum for a signed integer is 2147483647, so
69
+     * MAX_DATE cannot be higher than date('Y-m-d', 2147483647) which results
70
+     * in 2038-01-19 to avoid problems when the date is converted
71
+     * to a unix timestamp.
72
+     */
73
+    const MAX_DATE = '2038-01-01';
74
+
75
+    const ACCESS_PUBLIC = 4;
76
+    const CLASSIFICATION_PUBLIC = 0;
77
+    const CLASSIFICATION_PRIVATE = 1;
78
+    const CLASSIFICATION_CONFIDENTIAL = 2;
79
+
80
+    /**
81
+     * List of CalDAV properties, and how they map to database field names
82
+     * Add your own properties by simply adding on to this array.
83
+     *
84
+     * Note that only string-based properties are supported here.
85
+     *
86
+     * @var array
87
+     */
88
+    public $propertyMap = [
89
+        '{DAV:}displayname'                          => 'displayname',
90
+        '{urn:ietf:params:xml:ns:caldav}calendar-description' => 'description',
91
+        '{urn:ietf:params:xml:ns:caldav}calendar-timezone'    => 'timezone',
92
+        '{http://apple.com/ns/ical/}calendar-order'  => 'calendarorder',
93
+        '{http://apple.com/ns/ical/}calendar-color'  => 'calendarcolor',
94
+    ];
95
+
96
+    /**
97
+     * List of subscription properties, and how they map to database field names.
98
+     *
99
+     * @var array
100
+     */
101
+    public $subscriptionPropertyMap = [
102
+        '{DAV:}displayname'                                           => 'displayname',
103
+        '{http://apple.com/ns/ical/}refreshrate'                      => 'refreshrate',
104
+        '{http://apple.com/ns/ical/}calendar-order'                   => 'calendarorder',
105
+        '{http://apple.com/ns/ical/}calendar-color'                   => 'calendarcolor',
106
+        '{http://calendarserver.org/ns/}subscribed-strip-todos'       => 'striptodos',
107
+        '{http://calendarserver.org/ns/}subscribed-strip-alarms'      => 'stripalarms',
108
+        '{http://calendarserver.org/ns/}subscribed-strip-attachments' => 'stripattachments',
109
+    ];
110
+
111
+    /**
112
+     * @var string[] Map of uid => display name
113
+     */
114
+    protected $userDisplayNames;
115
+
116
+    /** @var IDBConnection */
117
+    private $db;
118
+
119
+    /** @var Backend */
120
+    private $sharingBackend;
121
+
122
+    /** @var Principal */
123
+    private $principalBackend;
124
+
125
+    /** @var IUserManager */
126
+    private $userManager;
127
+
128
+    /** @var ISecureRandom */
129
+    private $random;
130
+
131
+    /** @var EventDispatcherInterface */
132
+    private $dispatcher;
133
+
134
+    /** @var bool */
135
+    private $legacyEndpoint;
136
+
137
+    /**
138
+     * CalDavBackend constructor.
139
+     *
140
+     * @param IDBConnection $db
141
+     * @param Principal $principalBackend
142
+     * @param IUserManager $userManager
143
+     * @param ISecureRandom $random
144
+     * @param EventDispatcherInterface $dispatcher
145
+     * @param bool $legacyEndpoint
146
+     */
147
+    public function __construct(IDBConnection $db,
148
+                                Principal $principalBackend,
149
+                                IUserManager $userManager,
150
+                                ISecureRandom $random,
151
+                                EventDispatcherInterface $dispatcher,
152
+                                $legacyEndpoint = false) {
153
+        $this->db = $db;
154
+        $this->principalBackend = $principalBackend;
155
+        $this->userManager = $userManager;
156
+        $this->sharingBackend = new Backend($this->db, $principalBackend, 'calendar');
157
+        $this->random = $random;
158
+        $this->dispatcher = $dispatcher;
159
+        $this->legacyEndpoint = $legacyEndpoint;
160
+    }
161
+
162
+    /**
163
+     * Return the number of calendars for a principal
164
+     *
165
+     * By default this excludes the automatically generated birthday calendar
166
+     *
167
+     * @param $principalUri
168
+     * @param bool $excludeBirthday
169
+     * @return int
170
+     */
171
+    public function getCalendarsForUserCount($principalUri, $excludeBirthday = true) {
172
+        $principalUri = $this->convertPrincipal($principalUri, true);
173
+        $query = $this->db->getQueryBuilder();
174
+        $query->select($query->createFunction('COUNT(*)'))
175
+            ->from('calendars')
176
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
177
+
178
+        if ($excludeBirthday) {
179
+            $query->andWhere($query->expr()->neq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)));
180
+        }
181
+
182
+        return (int)$query->execute()->fetchColumn();
183
+    }
184
+
185
+    /**
186
+     * Returns a list of calendars for a principal.
187
+     *
188
+     * Every project is an array with the following keys:
189
+     *  * id, a unique id that will be used by other functions to modify the
190
+     *    calendar. This can be the same as the uri or a database key.
191
+     *  * uri, which the basename of the uri with which the calendar is
192
+     *    accessed.
193
+     *  * principaluri. The owner of the calendar. Almost always the same as
194
+     *    principalUri passed to this method.
195
+     *
196
+     * Furthermore it can contain webdav properties in clark notation. A very
197
+     * common one is '{DAV:}displayname'.
198
+     *
199
+     * Many clients also require:
200
+     * {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
201
+     * For this property, you can just return an instance of
202
+     * Sabre\CalDAV\Property\SupportedCalendarComponentSet.
203
+     *
204
+     * If you return {http://sabredav.org/ns}read-only and set the value to 1,
205
+     * ACL will automatically be put in read-only mode.
206
+     *
207
+     * @param string $principalUri
208
+     * @return array
209
+     */
210
+    function getCalendarsForUser($principalUri) {
211
+        $principalUriOriginal = $principalUri;
212
+        $principalUri = $this->convertPrincipal($principalUri, true);
213
+        $fields = array_values($this->propertyMap);
214
+        $fields[] = 'id';
215
+        $fields[] = 'uri';
216
+        $fields[] = 'synctoken';
217
+        $fields[] = 'components';
218
+        $fields[] = 'principaluri';
219
+        $fields[] = 'transparent';
220
+
221
+        // Making fields a comma-delimited list
222
+        $query = $this->db->getQueryBuilder();
223
+        $query->select($fields)->from('calendars')
224
+                ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
225
+                ->orderBy('calendarorder', 'ASC');
226
+        $stmt = $query->execute();
227
+
228
+        $calendars = [];
229
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
230
+
231
+            $components = [];
232
+            if ($row['components']) {
233
+                $components = explode(',',$row['components']);
234
+            }
235
+
236
+            $calendar = [
237
+                'id' => $row['id'],
238
+                'uri' => $row['uri'],
239
+                'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
240
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
241
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
242
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
243
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
244
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
245
+            ];
246
+
247
+            foreach($this->propertyMap as $xmlName=>$dbName) {
248
+                $calendar[$xmlName] = $row[$dbName];
249
+            }
250
+
251
+            if (!isset($calendars[$calendar['id']])) {
252
+                $calendars[$calendar['id']] = $calendar;
253
+            }
254
+        }
255
+
256
+        $stmt->closeCursor();
257
+
258
+        // query for shared calendars
259
+        $principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
260
+        $principals[]= $principalUri;
261
+
262
+        $fields = array_values($this->propertyMap);
263
+        $fields[] = 'a.id';
264
+        $fields[] = 'a.uri';
265
+        $fields[] = 'a.synctoken';
266
+        $fields[] = 'a.components';
267
+        $fields[] = 'a.principaluri';
268
+        $fields[] = 'a.transparent';
269
+        $fields[] = 's.access';
270
+        $query = $this->db->getQueryBuilder();
271
+        $result = $query->select($fields)
272
+            ->from('dav_shares', 's')
273
+            ->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
274
+            ->where($query->expr()->in('s.principaluri', $query->createParameter('principaluri')))
275
+            ->andWhere($query->expr()->eq('s.type', $query->createParameter('type')))
276
+            ->setParameter('type', 'calendar')
277
+            ->setParameter('principaluri', $principals, \Doctrine\DBAL\Connection::PARAM_STR_ARRAY)
278
+            ->execute();
279
+
280
+        while($row = $result->fetch()) {
281
+            list(, $name) = URLUtil::splitPath($row['principaluri']);
282
+            $uri = $row['uri'] . '_shared_by_' . $name;
283
+            $row['displayname'] = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
284
+            $components = [];
285
+            if ($row['components']) {
286
+                $components = explode(',',$row['components']);
287
+            }
288
+            $calendar = [
289
+                'id' => $row['id'],
290
+                'uri' => $uri,
291
+                'principaluri' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
292
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
293
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
294
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
295
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
296
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
297
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
298
+            ];
299
+
300
+            foreach($this->propertyMap as $xmlName=>$dbName) {
301
+                $calendar[$xmlName] = $row[$dbName];
302
+            }
303
+
304
+            if (!isset($calendars[$calendar['id']])) {
305
+                $calendars[$calendar['id']] = $calendar;
306
+            }
307
+        }
308
+        $result->closeCursor();
309
+
310
+        return array_values($calendars);
311
+    }
312
+
313
+    public function getUsersOwnCalendars($principalUri) {
314
+        $principalUri = $this->convertPrincipal($principalUri, true);
315
+        $fields = array_values($this->propertyMap);
316
+        $fields[] = 'id';
317
+        $fields[] = 'uri';
318
+        $fields[] = 'synctoken';
319
+        $fields[] = 'components';
320
+        $fields[] = 'principaluri';
321
+        $fields[] = 'transparent';
322
+        // Making fields a comma-delimited list
323
+        $query = $this->db->getQueryBuilder();
324
+        $query->select($fields)->from('calendars')
325
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
326
+            ->orderBy('calendarorder', 'ASC');
327
+        $stmt = $query->execute();
328
+        $calendars = [];
329
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
330
+            $components = [];
331
+            if ($row['components']) {
332
+                $components = explode(',',$row['components']);
333
+            }
334
+            $calendar = [
335
+                'id' => $row['id'],
336
+                'uri' => $row['uri'],
337
+                'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
338
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
339
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
340
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
341
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
342
+            ];
343
+            foreach($this->propertyMap as $xmlName=>$dbName) {
344
+                $calendar[$xmlName] = $row[$dbName];
345
+            }
346
+            if (!isset($calendars[$calendar['id']])) {
347
+                $calendars[$calendar['id']] = $calendar;
348
+            }
349
+        }
350
+        $stmt->closeCursor();
351
+        return array_values($calendars);
352
+    }
353
+
354
+
355
+    private function getUserDisplayName($uid) {
356
+        if (!isset($this->userDisplayNames[$uid])) {
357
+            $user = $this->userManager->get($uid);
358
+
359
+            if ($user instanceof IUser) {
360
+                $this->userDisplayNames[$uid] = $user->getDisplayName();
361
+            } else {
362
+                $this->userDisplayNames[$uid] = $uid;
363
+            }
364
+        }
365
+
366
+        return $this->userDisplayNames[$uid];
367
+    }
368 368
 	
369
-	/**
370
-	 * @return array
371
-	 */
372
-	public function getPublicCalendars() {
373
-		$fields = array_values($this->propertyMap);
374
-		$fields[] = 'a.id';
375
-		$fields[] = 'a.uri';
376
-		$fields[] = 'a.synctoken';
377
-		$fields[] = 'a.components';
378
-		$fields[] = 'a.principaluri';
379
-		$fields[] = 'a.transparent';
380
-		$fields[] = 's.access';
381
-		$fields[] = 's.publicuri';
382
-		$calendars = [];
383
-		$query = $this->db->getQueryBuilder();
384
-		$result = $query->select($fields)
385
-			->from('dav_shares', 's')
386
-			->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
387
-			->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
388
-			->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
389
-			->execute();
390
-
391
-		while($row = $result->fetch()) {
392
-			list(, $name) = URLUtil::splitPath($row['principaluri']);
393
-			$row['displayname'] = $row['displayname'] . "($name)";
394
-			$components = [];
395
-			if ($row['components']) {
396
-				$components = explode(',',$row['components']);
397
-			}
398
-			$calendar = [
399
-				'id' => $row['id'],
400
-				'uri' => $row['publicuri'],
401
-				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
402
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
403
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
404
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
405
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
406
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
407
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
408
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
409
-			];
410
-
411
-			foreach($this->propertyMap as $xmlName=>$dbName) {
412
-				$calendar[$xmlName] = $row[$dbName];
413
-			}
414
-
415
-			if (!isset($calendars[$calendar['id']])) {
416
-				$calendars[$calendar['id']] = $calendar;
417
-			}
418
-		}
419
-		$result->closeCursor();
420
-
421
-		return array_values($calendars);
422
-	}
423
-
424
-	/**
425
-	 * @param string $uri
426
-	 * @return array
427
-	 * @throws NotFound
428
-	 */
429
-	public function getPublicCalendar($uri) {
430
-		$fields = array_values($this->propertyMap);
431
-		$fields[] = 'a.id';
432
-		$fields[] = 'a.uri';
433
-		$fields[] = 'a.synctoken';
434
-		$fields[] = 'a.components';
435
-		$fields[] = 'a.principaluri';
436
-		$fields[] = 'a.transparent';
437
-		$fields[] = 's.access';
438
-		$fields[] = 's.publicuri';
439
-		$query = $this->db->getQueryBuilder();
440
-		$result = $query->select($fields)
441
-			->from('dav_shares', 's')
442
-			->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
443
-			->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
444
-			->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
445
-			->andWhere($query->expr()->eq('s.publicuri', $query->createNamedParameter($uri)))
446
-			->execute();
447
-
448
-		$row = $result->fetch(\PDO::FETCH_ASSOC);
449
-
450
-		$result->closeCursor();
451
-
452
-		if ($row === false) {
453
-			throw new NotFound('Node with name \'' . $uri . '\' could not be found');
454
-		}
455
-
456
-		list(, $name) = URLUtil::splitPath($row['principaluri']);
457
-		$row['displayname'] = $row['displayname'] . ' ' . "($name)";
458
-		$components = [];
459
-		if ($row['components']) {
460
-			$components = explode(',',$row['components']);
461
-		}
462
-		$calendar = [
463
-			'id' => $row['id'],
464
-			'uri' => $row['publicuri'],
465
-			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
466
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
467
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
468
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
469
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
470
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
471
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
472
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
473
-		];
474
-
475
-		foreach($this->propertyMap as $xmlName=>$dbName) {
476
-			$calendar[$xmlName] = $row[$dbName];
477
-		}
478
-
479
-		return $calendar;
480
-
481
-	}
482
-
483
-	/**
484
-	 * @param string $principal
485
-	 * @param string $uri
486
-	 * @return array|null
487
-	 */
488
-	public function getCalendarByUri($principal, $uri) {
489
-		$fields = array_values($this->propertyMap);
490
-		$fields[] = 'id';
491
-		$fields[] = 'uri';
492
-		$fields[] = 'synctoken';
493
-		$fields[] = 'components';
494
-		$fields[] = 'principaluri';
495
-		$fields[] = 'transparent';
496
-
497
-		// Making fields a comma-delimited list
498
-		$query = $this->db->getQueryBuilder();
499
-		$query->select($fields)->from('calendars')
500
-			->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
501
-			->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
502
-			->setMaxResults(1);
503
-		$stmt = $query->execute();
504
-
505
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
506
-		$stmt->closeCursor();
507
-		if ($row === false) {
508
-			return null;
509
-		}
510
-
511
-		$components = [];
512
-		if ($row['components']) {
513
-			$components = explode(',',$row['components']);
514
-		}
515
-
516
-		$calendar = [
517
-			'id' => $row['id'],
518
-			'uri' => $row['uri'],
519
-			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
520
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
521
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
522
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
523
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
524
-		];
525
-
526
-		foreach($this->propertyMap as $xmlName=>$dbName) {
527
-			$calendar[$xmlName] = $row[$dbName];
528
-		}
529
-
530
-		return $calendar;
531
-	}
532
-
533
-	public function getCalendarById($calendarId) {
534
-		$fields = array_values($this->propertyMap);
535
-		$fields[] = 'id';
536
-		$fields[] = 'uri';
537
-		$fields[] = 'synctoken';
538
-		$fields[] = 'components';
539
-		$fields[] = 'principaluri';
540
-		$fields[] = 'transparent';
541
-
542
-		// Making fields a comma-delimited list
543
-		$query = $this->db->getQueryBuilder();
544
-		$query->select($fields)->from('calendars')
545
-			->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)))
546
-			->setMaxResults(1);
547
-		$stmt = $query->execute();
548
-
549
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
550
-		$stmt->closeCursor();
551
-		if ($row === false) {
552
-			return null;
553
-		}
554
-
555
-		$components = [];
556
-		if ($row['components']) {
557
-			$components = explode(',',$row['components']);
558
-		}
559
-
560
-		$calendar = [
561
-			'id' => $row['id'],
562
-			'uri' => $row['uri'],
563
-			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
564
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
565
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
566
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
567
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
568
-		];
569
-
570
-		foreach($this->propertyMap as $xmlName=>$dbName) {
571
-			$calendar[$xmlName] = $row[$dbName];
572
-		}
573
-
574
-		return $calendar;
575
-	}
576
-
577
-	/**
578
-	 * Creates a new calendar for a principal.
579
-	 *
580
-	 * If the creation was a success, an id must be returned that can be used to reference
581
-	 * this calendar in other methods, such as updateCalendar.
582
-	 *
583
-	 * @param string $principalUri
584
-	 * @param string $calendarUri
585
-	 * @param array $properties
586
-	 * @return int
587
-	 */
588
-	function createCalendar($principalUri, $calendarUri, array $properties) {
589
-		$values = [
590
-			'principaluri' => $this->convertPrincipal($principalUri, true),
591
-			'uri'          => $calendarUri,
592
-			'synctoken'    => 1,
593
-			'transparent'  => 0,
594
-			'components'   => 'VEVENT,VTODO',
595
-			'displayname'  => $calendarUri
596
-		];
597
-
598
-		// Default value
599
-		$sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
600
-		if (isset($properties[$sccs])) {
601
-			if (!($properties[$sccs] instanceof SupportedCalendarComponentSet)) {
602
-				throw new DAV\Exception('The ' . $sccs . ' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
603
-			}
604
-			$values['components'] = implode(',',$properties[$sccs]->getValue());
605
-		}
606
-		$transp = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
607
-		if (isset($properties[$transp])) {
608
-			$values['transparent'] = $properties[$transp]->getValue()==='transparent';
609
-		}
610
-
611
-		foreach($this->propertyMap as $xmlName=>$dbName) {
612
-			if (isset($properties[$xmlName])) {
613
-				$values[$dbName] = $properties[$xmlName];
614
-			}
615
-		}
616
-
617
-		$query = $this->db->getQueryBuilder();
618
-		$query->insert('calendars');
619
-		foreach($values as $column => $value) {
620
-			$query->setValue($column, $query->createNamedParameter($value));
621
-		}
622
-		$query->execute();
623
-		$calendarId = $query->getLastInsertId();
624
-
625
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendar', new GenericEvent(
626
-			'\OCA\DAV\CalDAV\CalDavBackend::createCalendar',
627
-			[
628
-				'calendarId' => $calendarId,
629
-				'calendarData' => $this->getCalendarById($calendarId),
630
-		]));
631
-
632
-		return $calendarId;
633
-	}
634
-
635
-	/**
636
-	 * Updates properties for a calendar.
637
-	 *
638
-	 * The list of mutations is stored in a Sabre\DAV\PropPatch object.
639
-	 * To do the actual updates, you must tell this object which properties
640
-	 * you're going to process with the handle() method.
641
-	 *
642
-	 * Calling the handle method is like telling the PropPatch object "I
643
-	 * promise I can handle updating this property".
644
-	 *
645
-	 * Read the PropPatch documentation for more info and examples.
646
-	 *
647
-	 * @param PropPatch $propPatch
648
-	 * @return void
649
-	 */
650
-	function updateCalendar($calendarId, PropPatch $propPatch) {
651
-		$supportedProperties = array_keys($this->propertyMap);
652
-		$supportedProperties[] = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
653
-
654
-		$propPatch->handle($supportedProperties, function($mutations) use ($calendarId) {
655
-			$newValues = [];
656
-			foreach ($mutations as $propertyName => $propertyValue) {
657
-
658
-				switch ($propertyName) {
659
-					case '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' :
660
-						$fieldName = 'transparent';
661
-						$newValues[$fieldName] = $propertyValue->getValue() === 'transparent';
662
-						break;
663
-					default :
664
-						$fieldName = $this->propertyMap[$propertyName];
665
-						$newValues[$fieldName] = $propertyValue;
666
-						break;
667
-				}
668
-
669
-			}
670
-			$query = $this->db->getQueryBuilder();
671
-			$query->update('calendars');
672
-			foreach ($newValues as $fieldName => $value) {
673
-				$query->set($fieldName, $query->createNamedParameter($value));
674
-			}
675
-			$query->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
676
-			$query->execute();
677
-
678
-			$this->addChange($calendarId, "", 2);
679
-
680
-			$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendar', new GenericEvent(
681
-				'\OCA\DAV\CalDAV\CalDavBackend::updateCalendar',
682
-				[
683
-					'calendarId' => $calendarId,
684
-					'calendarData' => $this->getCalendarById($calendarId),
685
-					'shares' => $this->getShares($calendarId),
686
-					'propertyMutations' => $mutations,
687
-			]));
688
-
689
-			return true;
690
-		});
691
-	}
692
-
693
-	/**
694
-	 * Delete a calendar and all it's objects
695
-	 *
696
-	 * @param mixed $calendarId
697
-	 * @return void
698
-	 */
699
-	function deleteCalendar($calendarId) {
700
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar', new GenericEvent(
701
-			'\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar',
702
-			[
703
-				'calendarId' => $calendarId,
704
-				'calendarData' => $this->getCalendarById($calendarId),
705
-				'shares' => $this->getShares($calendarId),
706
-		]));
707
-
708
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ?');
709
-		$stmt->execute([$calendarId]);
710
-
711
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendars` WHERE `id` = ?');
712
-		$stmt->execute([$calendarId]);
713
-
714
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarchanges` WHERE `calendarid` = ?');
715
-		$stmt->execute([$calendarId]);
716
-
717
-		$this->sharingBackend->deleteAllShares($calendarId);
718
-	}
719
-
720
-	/**
721
-	 * Delete all of an user's shares
722
-	 *
723
-	 * @param string $principaluri
724
-	 * @return void
725
-	 */
726
-	function deleteAllSharesByUser($principaluri) {
727
-		$this->sharingBackend->deleteAllSharesByUser($principaluri);
728
-	}
729
-
730
-	/**
731
-	 * Returns all calendar objects within a calendar.
732
-	 *
733
-	 * Every item contains an array with the following keys:
734
-	 *   * calendardata - The iCalendar-compatible calendar data
735
-	 *   * uri - a unique key which will be used to construct the uri. This can
736
-	 *     be any arbitrary string, but making sure it ends with '.ics' is a
737
-	 *     good idea. This is only the basename, or filename, not the full
738
-	 *     path.
739
-	 *   * lastmodified - a timestamp of the last modification time
740
-	 *   * etag - An arbitrary string, surrounded by double-quotes. (e.g.:
741
-	 *   '"abcdef"')
742
-	 *   * size - The size of the calendar objects, in bytes.
743
-	 *   * component - optional, a string containing the type of object, such
744
-	 *     as 'vevent' or 'vtodo'. If specified, this will be used to populate
745
-	 *     the Content-Type header.
746
-	 *
747
-	 * Note that the etag is optional, but it's highly encouraged to return for
748
-	 * speed reasons.
749
-	 *
750
-	 * The calendardata is also optional. If it's not returned
751
-	 * 'getCalendarObject' will be called later, which *is* expected to return
752
-	 * calendardata.
753
-	 *
754
-	 * If neither etag or size are specified, the calendardata will be
755
-	 * used/fetched to determine these numbers. If both are specified the
756
-	 * amount of times this is needed is reduced by a great degree.
757
-	 *
758
-	 * @param mixed $calendarId
759
-	 * @return array
760
-	 */
761
-	function getCalendarObjects($calendarId) {
762
-		$query = $this->db->getQueryBuilder();
763
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'componenttype', 'classification'])
764
-			->from('calendarobjects')
765
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
766
-		$stmt = $query->execute();
767
-
768
-		$result = [];
769
-		foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
770
-			$result[] = [
771
-					'id'           => $row['id'],
772
-					'uri'          => $row['uri'],
773
-					'lastmodified' => $row['lastmodified'],
774
-					'etag'         => '"' . $row['etag'] . '"',
775
-					'calendarid'   => $row['calendarid'],
776
-					'size'         => (int)$row['size'],
777
-					'component'    => strtolower($row['componenttype']),
778
-					'classification'=> (int)$row['classification']
779
-			];
780
-		}
781
-
782
-		return $result;
783
-	}
784
-
785
-	/**
786
-	 * Returns information from a single calendar object, based on it's object
787
-	 * uri.
788
-	 *
789
-	 * The object uri is only the basename, or filename and not a full path.
790
-	 *
791
-	 * The returned array must have the same keys as getCalendarObjects. The
792
-	 * 'calendardata' object is required here though, while it's not required
793
-	 * for getCalendarObjects.
794
-	 *
795
-	 * This method must return null if the object did not exist.
796
-	 *
797
-	 * @param mixed $calendarId
798
-	 * @param string $objectUri
799
-	 * @return array|null
800
-	 */
801
-	function getCalendarObject($calendarId, $objectUri) {
802
-
803
-		$query = $this->db->getQueryBuilder();
804
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
805
-				->from('calendarobjects')
806
-				->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
807
-				->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)));
808
-		$stmt = $query->execute();
809
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
810
-
811
-		if(!$row) return null;
812
-
813
-		return [
814
-				'id'            => $row['id'],
815
-				'uri'           => $row['uri'],
816
-				'lastmodified'  => $row['lastmodified'],
817
-				'etag'          => '"' . $row['etag'] . '"',
818
-				'calendarid'    => $row['calendarid'],
819
-				'size'          => (int)$row['size'],
820
-				'calendardata'  => $this->readBlob($row['calendardata']),
821
-				'component'     => strtolower($row['componenttype']),
822
-				'classification'=> (int)$row['classification']
823
-		];
824
-	}
825
-
826
-	/**
827
-	 * Returns a list of calendar objects.
828
-	 *
829
-	 * This method should work identical to getCalendarObject, but instead
830
-	 * return all the calendar objects in the list as an array.
831
-	 *
832
-	 * If the backend supports this, it may allow for some speed-ups.
833
-	 *
834
-	 * @param mixed $calendarId
835
-	 * @param string[] $uris
836
-	 * @return array
837
-	 */
838
-	function getMultipleCalendarObjects($calendarId, array $uris) {
839
-		if (empty($uris)) {
840
-			return [];
841
-		}
842
-
843
-		$chunks = array_chunk($uris, 100);
844
-		$objects = [];
845
-
846
-		$query = $this->db->getQueryBuilder();
847
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
848
-			->from('calendarobjects')
849
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
850
-			->andWhere($query->expr()->in('uri', $query->createParameter('uri')));
851
-
852
-		foreach ($chunks as $uris) {
853
-			$query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
854
-			$result = $query->execute();
855
-
856
-			while ($row = $result->fetch()) {
857
-				$objects[] = [
858
-					'id'           => $row['id'],
859
-					'uri'          => $row['uri'],
860
-					'lastmodified' => $row['lastmodified'],
861
-					'etag'         => '"' . $row['etag'] . '"',
862
-					'calendarid'   => $row['calendarid'],
863
-					'size'         => (int)$row['size'],
864
-					'calendardata' => $this->readBlob($row['calendardata']),
865
-					'component'    => strtolower($row['componenttype']),
866
-					'classification' => (int)$row['classification']
867
-				];
868
-			}
869
-			$result->closeCursor();
870
-		}
871
-		return $objects;
872
-	}
873
-
874
-	/**
875
-	 * Creates a new calendar object.
876
-	 *
877
-	 * The object uri is only the basename, or filename and not a full path.
878
-	 *
879
-	 * It is possible return an etag from this function, which will be used in
880
-	 * the response to this PUT request. Note that the ETag must be surrounded
881
-	 * by double-quotes.
882
-	 *
883
-	 * However, you should only really return this ETag if you don't mangle the
884
-	 * calendar-data. If the result of a subsequent GET to this object is not
885
-	 * the exact same as this request body, you should omit the ETag.
886
-	 *
887
-	 * @param mixed $calendarId
888
-	 * @param string $objectUri
889
-	 * @param string $calendarData
890
-	 * @return string
891
-	 */
892
-	function createCalendarObject($calendarId, $objectUri, $calendarData) {
893
-		$extraData = $this->getDenormalizedData($calendarData);
894
-
895
-		$query = $this->db->getQueryBuilder();
896
-		$query->insert('calendarobjects')
897
-			->values([
898
-				'calendarid' => $query->createNamedParameter($calendarId),
899
-				'uri' => $query->createNamedParameter($objectUri),
900
-				'calendardata' => $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB),
901
-				'lastmodified' => $query->createNamedParameter(time()),
902
-				'etag' => $query->createNamedParameter($extraData['etag']),
903
-				'size' => $query->createNamedParameter($extraData['size']),
904
-				'componenttype' => $query->createNamedParameter($extraData['componentType']),
905
-				'firstoccurence' => $query->createNamedParameter($extraData['firstOccurence']),
906
-				'lastoccurence' => $query->createNamedParameter($extraData['lastOccurence']),
907
-				'classification' => $query->createNamedParameter($extraData['classification']),
908
-				'uid' => $query->createNamedParameter($extraData['uid']),
909
-			])
910
-			->execute();
911
-
912
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject', new GenericEvent(
913
-			'\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject',
914
-			[
915
-				'calendarId' => $calendarId,
916
-				'calendarData' => $this->getCalendarById($calendarId),
917
-				'shares' => $this->getShares($calendarId),
918
-				'objectData' => $this->getCalendarObject($calendarId, $objectUri),
919
-			]
920
-		));
921
-		$this->addChange($calendarId, $objectUri, 1);
922
-
923
-		return '"' . $extraData['etag'] . '"';
924
-	}
925
-
926
-	/**
927
-	 * Updates an existing calendarobject, based on it's uri.
928
-	 *
929
-	 * The object uri is only the basename, or filename and not a full path.
930
-	 *
931
-	 * It is possible return an etag from this function, which will be used in
932
-	 * the response to this PUT request. Note that the ETag must be surrounded
933
-	 * by double-quotes.
934
-	 *
935
-	 * However, you should only really return this ETag if you don't mangle the
936
-	 * calendar-data. If the result of a subsequent GET to this object is not
937
-	 * the exact same as this request body, you should omit the ETag.
938
-	 *
939
-	 * @param mixed $calendarId
940
-	 * @param string $objectUri
941
-	 * @param string $calendarData
942
-	 * @return string
943
-	 */
944
-	function updateCalendarObject($calendarId, $objectUri, $calendarData) {
945
-		$extraData = $this->getDenormalizedData($calendarData);
946
-
947
-		$query = $this->db->getQueryBuilder();
948
-		$query->update('calendarobjects')
949
-				->set('calendardata', $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB))
950
-				->set('lastmodified', $query->createNamedParameter(time()))
951
-				->set('etag', $query->createNamedParameter($extraData['etag']))
952
-				->set('size', $query->createNamedParameter($extraData['size']))
953
-				->set('componenttype', $query->createNamedParameter($extraData['componentType']))
954
-				->set('firstoccurence', $query->createNamedParameter($extraData['firstOccurence']))
955
-				->set('lastoccurence', $query->createNamedParameter($extraData['lastOccurence']))
956
-				->set('classification', $query->createNamedParameter($extraData['classification']))
957
-				->set('uid', $query->createNamedParameter($extraData['uid']))
958
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
959
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
960
-			->execute();
961
-
962
-		$data = $this->getCalendarObject($calendarId, $objectUri);
963
-		if (is_array($data)) {
964
-			$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject', new GenericEvent(
965
-				'\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject',
966
-				[
967
-					'calendarId' => $calendarId,
968
-					'calendarData' => $this->getCalendarById($calendarId),
969
-					'shares' => $this->getShares($calendarId),
970
-					'objectData' => $data,
971
-				]
972
-			));
973
-		}
974
-		$this->addChange($calendarId, $objectUri, 2);
975
-
976
-		return '"' . $extraData['etag'] . '"';
977
-	}
978
-
979
-	/**
980
-	 * @param int $calendarObjectId
981
-	 * @param int $classification
982
-	 */
983
-	public function setClassification($calendarObjectId, $classification) {
984
-		if (!in_array($classification, [
985
-			self::CLASSIFICATION_PUBLIC, self::CLASSIFICATION_PRIVATE, self::CLASSIFICATION_CONFIDENTIAL
986
-		])) {
987
-			throw new \InvalidArgumentException();
988
-		}
989
-		$query = $this->db->getQueryBuilder();
990
-		$query->update('calendarobjects')
991
-			->set('classification', $query->createNamedParameter($classification))
992
-			->where($query->expr()->eq('id', $query->createNamedParameter($calendarObjectId)))
993
-			->execute();
994
-	}
995
-
996
-	/**
997
-	 * Deletes an existing calendar object.
998
-	 *
999
-	 * The object uri is only the basename, or filename and not a full path.
1000
-	 *
1001
-	 * @param mixed $calendarId
1002
-	 * @param string $objectUri
1003
-	 * @return void
1004
-	 */
1005
-	function deleteCalendarObject($calendarId, $objectUri) {
1006
-		$data = $this->getCalendarObject($calendarId, $objectUri);
1007
-		if (is_array($data)) {
1008
-			$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject', new GenericEvent(
1009
-				'\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject',
1010
-				[
1011
-					'calendarId' => $calendarId,
1012
-					'calendarData' => $this->getCalendarById($calendarId),
1013
-					'shares' => $this->getShares($calendarId),
1014
-					'objectData' => $data,
1015
-				]
1016
-			));
1017
-		}
1018
-
1019
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `uri` = ?');
1020
-		$stmt->execute([$calendarId, $objectUri]);
1021
-
1022
-		$this->addChange($calendarId, $objectUri, 3);
1023
-	}
1024
-
1025
-	/**
1026
-	 * Performs a calendar-query on the contents of this calendar.
1027
-	 *
1028
-	 * The calendar-query is defined in RFC4791 : CalDAV. Using the
1029
-	 * calendar-query it is possible for a client to request a specific set of
1030
-	 * object, based on contents of iCalendar properties, date-ranges and
1031
-	 * iCalendar component types (VTODO, VEVENT).
1032
-	 *
1033
-	 * This method should just return a list of (relative) urls that match this
1034
-	 * query.
1035
-	 *
1036
-	 * The list of filters are specified as an array. The exact array is
1037
-	 * documented by Sabre\CalDAV\CalendarQueryParser.
1038
-	 *
1039
-	 * Note that it is extremely likely that getCalendarObject for every path
1040
-	 * returned from this method will be called almost immediately after. You
1041
-	 * may want to anticipate this to speed up these requests.
1042
-	 *
1043
-	 * This method provides a default implementation, which parses *all* the
1044
-	 * iCalendar objects in the specified calendar.
1045
-	 *
1046
-	 * This default may well be good enough for personal use, and calendars
1047
-	 * that aren't very large. But if you anticipate high usage, big calendars
1048
-	 * or high loads, you are strongly advised to optimize certain paths.
1049
-	 *
1050
-	 * The best way to do so is override this method and to optimize
1051
-	 * specifically for 'common filters'.
1052
-	 *
1053
-	 * Requests that are extremely common are:
1054
-	 *   * requests for just VEVENTS
1055
-	 *   * requests for just VTODO
1056
-	 *   * requests with a time-range-filter on either VEVENT or VTODO.
1057
-	 *
1058
-	 * ..and combinations of these requests. It may not be worth it to try to
1059
-	 * handle every possible situation and just rely on the (relatively
1060
-	 * easy to use) CalendarQueryValidator to handle the rest.
1061
-	 *
1062
-	 * Note that especially time-range-filters may be difficult to parse. A
1063
-	 * time-range filter specified on a VEVENT must for instance also handle
1064
-	 * recurrence rules correctly.
1065
-	 * A good example of how to interprete all these filters can also simply
1066
-	 * be found in Sabre\CalDAV\CalendarQueryFilter. This class is as correct
1067
-	 * as possible, so it gives you a good idea on what type of stuff you need
1068
-	 * to think of.
1069
-	 *
1070
-	 * @param mixed $calendarId
1071
-	 * @param array $filters
1072
-	 * @return array
1073
-	 */
1074
-	function calendarQuery($calendarId, array $filters) {
1075
-		$componentType = null;
1076
-		$requirePostFilter = true;
1077
-		$timeRange = null;
1078
-
1079
-		// if no filters were specified, we don't need to filter after a query
1080
-		if (!$filters['prop-filters'] && !$filters['comp-filters']) {
1081
-			$requirePostFilter = false;
1082
-		}
1083
-
1084
-		// Figuring out if there's a component filter
1085
-		if (count($filters['comp-filters']) > 0 && !$filters['comp-filters'][0]['is-not-defined']) {
1086
-			$componentType = $filters['comp-filters'][0]['name'];
1087
-
1088
-			// Checking if we need post-filters
1089
-			if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['time-range'] && !$filters['comp-filters'][0]['prop-filters']) {
1090
-				$requirePostFilter = false;
1091
-			}
1092
-			// There was a time-range filter
1093
-			if ($componentType == 'VEVENT' && isset($filters['comp-filters'][0]['time-range'])) {
1094
-				$timeRange = $filters['comp-filters'][0]['time-range'];
1095
-
1096
-				// If start time OR the end time is not specified, we can do a
1097
-				// 100% accurate mysql query.
1098
-				if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['prop-filters'] && (!$timeRange['start'] || !$timeRange['end'])) {
1099
-					$requirePostFilter = false;
1100
-				}
1101
-			}
1102
-
1103
-		}
1104
-		$columns = ['uri'];
1105
-		if ($requirePostFilter) {
1106
-			$columns = ['uri', 'calendardata'];
1107
-		}
1108
-		$query = $this->db->getQueryBuilder();
1109
-		$query->select($columns)
1110
-			->from('calendarobjects')
1111
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
1112
-
1113
-		if ($componentType) {
1114
-			$query->andWhere($query->expr()->eq('componenttype', $query->createNamedParameter($componentType)));
1115
-		}
1116
-
1117
-		if ($timeRange && $timeRange['start']) {
1118
-			$query->andWhere($query->expr()->gt('lastoccurence', $query->createNamedParameter($timeRange['start']->getTimeStamp())));
1119
-		}
1120
-		if ($timeRange && $timeRange['end']) {
1121
-			$query->andWhere($query->expr()->lt('firstoccurence', $query->createNamedParameter($timeRange['end']->getTimeStamp())));
1122
-		}
1123
-
1124
-		$stmt = $query->execute();
1125
-
1126
-		$result = [];
1127
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1128
-			if ($requirePostFilter) {
1129
-				if (!$this->validateFilterForObject($row, $filters)) {
1130
-					continue;
1131
-				}
1132
-			}
1133
-			$result[] = $row['uri'];
1134
-		}
1135
-
1136
-		return $result;
1137
-	}
1138
-
1139
-	/**
1140
-	 * Searches through all of a users calendars and calendar objects to find
1141
-	 * an object with a specific UID.
1142
-	 *
1143
-	 * This method should return the path to this object, relative to the
1144
-	 * calendar home, so this path usually only contains two parts:
1145
-	 *
1146
-	 * calendarpath/objectpath.ics
1147
-	 *
1148
-	 * If the uid is not found, return null.
1149
-	 *
1150
-	 * This method should only consider * objects that the principal owns, so
1151
-	 * any calendars owned by other principals that also appear in this
1152
-	 * collection should be ignored.
1153
-	 *
1154
-	 * @param string $principalUri
1155
-	 * @param string $uid
1156
-	 * @return string|null
1157
-	 */
1158
-	function getCalendarObjectByUID($principalUri, $uid) {
1159
-
1160
-		$query = $this->db->getQueryBuilder();
1161
-		$query->selectAlias('c.uri', 'calendaruri')->selectAlias('co.uri', 'objecturi')
1162
-			->from('calendarobjects', 'co')
1163
-			->leftJoin('co', 'calendars', 'c', $query->expr()->eq('co.calendarid', 'c.id'))
1164
-			->where($query->expr()->eq('c.principaluri', $query->createNamedParameter($principalUri)))
1165
-			->andWhere($query->expr()->eq('co.uid', $query->createNamedParameter($uid)));
1166
-
1167
-		$stmt = $query->execute();
1168
-
1169
-		if ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1170
-			return $row['calendaruri'] . '/' . $row['objecturi'];
1171
-		}
1172
-
1173
-		return null;
1174
-	}
1175
-
1176
-	/**
1177
-	 * The getChanges method returns all the changes that have happened, since
1178
-	 * the specified syncToken in the specified calendar.
1179
-	 *
1180
-	 * This function should return an array, such as the following:
1181
-	 *
1182
-	 * [
1183
-	 *   'syncToken' => 'The current synctoken',
1184
-	 *   'added'   => [
1185
-	 *      'new.txt',
1186
-	 *   ],
1187
-	 *   'modified'   => [
1188
-	 *      'modified.txt',
1189
-	 *   ],
1190
-	 *   'deleted' => [
1191
-	 *      'foo.php.bak',
1192
-	 *      'old.txt'
1193
-	 *   ]
1194
-	 * );
1195
-	 *
1196
-	 * The returned syncToken property should reflect the *current* syncToken
1197
-	 * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
1198
-	 * property This is * needed here too, to ensure the operation is atomic.
1199
-	 *
1200
-	 * If the $syncToken argument is specified as null, this is an initial
1201
-	 * sync, and all members should be reported.
1202
-	 *
1203
-	 * The modified property is an array of nodenames that have changed since
1204
-	 * the last token.
1205
-	 *
1206
-	 * The deleted property is an array with nodenames, that have been deleted
1207
-	 * from collection.
1208
-	 *
1209
-	 * The $syncLevel argument is basically the 'depth' of the report. If it's
1210
-	 * 1, you only have to report changes that happened only directly in
1211
-	 * immediate descendants. If it's 2, it should also include changes from
1212
-	 * the nodes below the child collections. (grandchildren)
1213
-	 *
1214
-	 * The $limit argument allows a client to specify how many results should
1215
-	 * be returned at most. If the limit is not specified, it should be treated
1216
-	 * as infinite.
1217
-	 *
1218
-	 * If the limit (infinite or not) is higher than you're willing to return,
1219
-	 * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
1220
-	 *
1221
-	 * If the syncToken is expired (due to data cleanup) or unknown, you must
1222
-	 * return null.
1223
-	 *
1224
-	 * The limit is 'suggestive'. You are free to ignore it.
1225
-	 *
1226
-	 * @param string $calendarId
1227
-	 * @param string $syncToken
1228
-	 * @param int $syncLevel
1229
-	 * @param int $limit
1230
-	 * @return array
1231
-	 */
1232
-	function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null) {
1233
-		// Current synctoken
1234
-		$stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*calendars` WHERE `id` = ?');
1235
-		$stmt->execute([ $calendarId ]);
1236
-		$currentToken = $stmt->fetchColumn(0);
1237
-
1238
-		if (is_null($currentToken)) {
1239
-			return null;
1240
-		}
1241
-
1242
-		$result = [
1243
-			'syncToken' => $currentToken,
1244
-			'added'     => [],
1245
-			'modified'  => [],
1246
-			'deleted'   => [],
1247
-		];
1248
-
1249
-		if ($syncToken) {
1250
-
1251
-			$query = "SELECT `uri`, `operation` FROM `*PREFIX*calendarchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `calendarid` = ? ORDER BY `synctoken`";
1252
-			if ($limit>0) {
1253
-				$query.= " `LIMIT` " . (int)$limit;
1254
-			}
1255
-
1256
-			// Fetching all changes
1257
-			$stmt = $this->db->prepare($query);
1258
-			$stmt->execute([$syncToken, $currentToken, $calendarId]);
1259
-
1260
-			$changes = [];
1261
-
1262
-			// This loop ensures that any duplicates are overwritten, only the
1263
-			// last change on a node is relevant.
1264
-			while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1265
-
1266
-				$changes[$row['uri']] = $row['operation'];
1267
-
1268
-			}
1269
-
1270
-			foreach($changes as $uri => $operation) {
1271
-
1272
-				switch($operation) {
1273
-					case 1 :
1274
-						$result['added'][] = $uri;
1275
-						break;
1276
-					case 2 :
1277
-						$result['modified'][] = $uri;
1278
-						break;
1279
-					case 3 :
1280
-						$result['deleted'][] = $uri;
1281
-						break;
1282
-				}
1283
-
1284
-			}
1285
-		} else {
1286
-			// No synctoken supplied, this is the initial sync.
1287
-			$query = "SELECT `uri` FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ?";
1288
-			$stmt = $this->db->prepare($query);
1289
-			$stmt->execute([$calendarId]);
1290
-
1291
-			$result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
1292
-		}
1293
-		return $result;
1294
-
1295
-	}
1296
-
1297
-	/**
1298
-	 * Returns a list of subscriptions for a principal.
1299
-	 *
1300
-	 * Every subscription is an array with the following keys:
1301
-	 *  * id, a unique id that will be used by other functions to modify the
1302
-	 *    subscription. This can be the same as the uri or a database key.
1303
-	 *  * uri. This is just the 'base uri' or 'filename' of the subscription.
1304
-	 *  * principaluri. The owner of the subscription. Almost always the same as
1305
-	 *    principalUri passed to this method.
1306
-	 *
1307
-	 * Furthermore, all the subscription info must be returned too:
1308
-	 *
1309
-	 * 1. {DAV:}displayname
1310
-	 * 2. {http://apple.com/ns/ical/}refreshrate
1311
-	 * 3. {http://calendarserver.org/ns/}subscribed-strip-todos (omit if todos
1312
-	 *    should not be stripped).
1313
-	 * 4. {http://calendarserver.org/ns/}subscribed-strip-alarms (omit if alarms
1314
-	 *    should not be stripped).
1315
-	 * 5. {http://calendarserver.org/ns/}subscribed-strip-attachments (omit if
1316
-	 *    attachments should not be stripped).
1317
-	 * 6. {http://calendarserver.org/ns/}source (Must be a
1318
-	 *     Sabre\DAV\Property\Href).
1319
-	 * 7. {http://apple.com/ns/ical/}calendar-color
1320
-	 * 8. {http://apple.com/ns/ical/}calendar-order
1321
-	 * 9. {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
1322
-	 *    (should just be an instance of
1323
-	 *    Sabre\CalDAV\Property\SupportedCalendarComponentSet, with a bunch of
1324
-	 *    default components).
1325
-	 *
1326
-	 * @param string $principalUri
1327
-	 * @return array
1328
-	 */
1329
-	function getSubscriptionsForUser($principalUri) {
1330
-		$fields = array_values($this->subscriptionPropertyMap);
1331
-		$fields[] = 'id';
1332
-		$fields[] = 'uri';
1333
-		$fields[] = 'source';
1334
-		$fields[] = 'principaluri';
1335
-		$fields[] = 'lastmodified';
1336
-
1337
-		$query = $this->db->getQueryBuilder();
1338
-		$query->select($fields)
1339
-			->from('calendarsubscriptions')
1340
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1341
-			->orderBy('calendarorder', 'asc');
1342
-		$stmt =$query->execute();
1343
-
1344
-		$subscriptions = [];
1345
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1346
-
1347
-			$subscription = [
1348
-				'id'           => $row['id'],
1349
-				'uri'          => $row['uri'],
1350
-				'principaluri' => $row['principaluri'],
1351
-				'source'       => $row['source'],
1352
-				'lastmodified' => $row['lastmodified'],
1353
-
1354
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
1355
-			];
1356
-
1357
-			foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1358
-				if (!is_null($row[$dbName])) {
1359
-					$subscription[$xmlName] = $row[$dbName];
1360
-				}
1361
-			}
1362
-
1363
-			$subscriptions[] = $subscription;
1364
-
1365
-		}
1366
-
1367
-		return $subscriptions;
1368
-	}
1369
-
1370
-	/**
1371
-	 * Creates a new subscription for a principal.
1372
-	 *
1373
-	 * If the creation was a success, an id must be returned that can be used to reference
1374
-	 * this subscription in other methods, such as updateSubscription.
1375
-	 *
1376
-	 * @param string $principalUri
1377
-	 * @param string $uri
1378
-	 * @param array $properties
1379
-	 * @return mixed
1380
-	 */
1381
-	function createSubscription($principalUri, $uri, array $properties) {
1382
-
1383
-		if (!isset($properties['{http://calendarserver.org/ns/}source'])) {
1384
-			throw new Forbidden('The {http://calendarserver.org/ns/}source property is required when creating subscriptions');
1385
-		}
1386
-
1387
-		$values = [
1388
-			'principaluri' => $principalUri,
1389
-			'uri'          => $uri,
1390
-			'source'       => $properties['{http://calendarserver.org/ns/}source']->getHref(),
1391
-			'lastmodified' => time(),
1392
-		];
1393
-
1394
-		$propertiesBoolean = ['striptodos', 'stripalarms', 'stripattachments'];
1395
-
1396
-		foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1397
-			if (array_key_exists($xmlName, $properties)) {
1398
-					$values[$dbName] = $properties[$xmlName];
1399
-					if (in_array($dbName, $propertiesBoolean)) {
1400
-						$values[$dbName] = true;
1401
-				}
1402
-			}
1403
-		}
1404
-
1405
-		$valuesToInsert = array();
1406
-
1407
-		$query = $this->db->getQueryBuilder();
1408
-
1409
-		foreach (array_keys($values) as $name) {
1410
-			$valuesToInsert[$name] = $query->createNamedParameter($values[$name]);
1411
-		}
1412
-
1413
-		$query->insert('calendarsubscriptions')
1414
-			->values($valuesToInsert)
1415
-			->execute();
1416
-
1417
-		return $this->db->lastInsertId('*PREFIX*calendarsubscriptions');
1418
-	}
1419
-
1420
-	/**
1421
-	 * Updates a subscription
1422
-	 *
1423
-	 * The list of mutations is stored in a Sabre\DAV\PropPatch object.
1424
-	 * To do the actual updates, you must tell this object which properties
1425
-	 * you're going to process with the handle() method.
1426
-	 *
1427
-	 * Calling the handle method is like telling the PropPatch object "I
1428
-	 * promise I can handle updating this property".
1429
-	 *
1430
-	 * Read the PropPatch documentation for more info and examples.
1431
-	 *
1432
-	 * @param mixed $subscriptionId
1433
-	 * @param PropPatch $propPatch
1434
-	 * @return void
1435
-	 */
1436
-	function updateSubscription($subscriptionId, PropPatch $propPatch) {
1437
-		$supportedProperties = array_keys($this->subscriptionPropertyMap);
1438
-		$supportedProperties[] = '{http://calendarserver.org/ns/}source';
1439
-
1440
-		$propPatch->handle($supportedProperties, function($mutations) use ($subscriptionId) {
1441
-
1442
-			$newValues = [];
1443
-
1444
-			foreach($mutations as $propertyName=>$propertyValue) {
1445
-				if ($propertyName === '{http://calendarserver.org/ns/}source') {
1446
-					$newValues['source'] = $propertyValue->getHref();
1447
-				} else {
1448
-					$fieldName = $this->subscriptionPropertyMap[$propertyName];
1449
-					$newValues[$fieldName] = $propertyValue;
1450
-				}
1451
-			}
1452
-
1453
-			$query = $this->db->getQueryBuilder();
1454
-			$query->update('calendarsubscriptions')
1455
-				->set('lastmodified', $query->createNamedParameter(time()));
1456
-			foreach($newValues as $fieldName=>$value) {
1457
-				$query->set($fieldName, $query->createNamedParameter($value));
1458
-			}
1459
-			$query->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
1460
-				->execute();
1461
-
1462
-			return true;
1463
-
1464
-		});
1465
-	}
1466
-
1467
-	/**
1468
-	 * Deletes a subscription.
1469
-	 *
1470
-	 * @param mixed $subscriptionId
1471
-	 * @return void
1472
-	 */
1473
-	function deleteSubscription($subscriptionId) {
1474
-		$query = $this->db->getQueryBuilder();
1475
-		$query->delete('calendarsubscriptions')
1476
-			->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
1477
-			->execute();
1478
-	}
1479
-
1480
-	/**
1481
-	 * Returns a single scheduling object for the inbox collection.
1482
-	 *
1483
-	 * The returned array should contain the following elements:
1484
-	 *   * uri - A unique basename for the object. This will be used to
1485
-	 *           construct a full uri.
1486
-	 *   * calendardata - The iCalendar object
1487
-	 *   * lastmodified - The last modification date. Can be an int for a unix
1488
-	 *                    timestamp, or a PHP DateTime object.
1489
-	 *   * etag - A unique token that must change if the object changed.
1490
-	 *   * size - The size of the object, in bytes.
1491
-	 *
1492
-	 * @param string $principalUri
1493
-	 * @param string $objectUri
1494
-	 * @return array
1495
-	 */
1496
-	function getSchedulingObject($principalUri, $objectUri) {
1497
-		$query = $this->db->getQueryBuilder();
1498
-		$stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
1499
-			->from('schedulingobjects')
1500
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1501
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1502
-			->execute();
1503
-
1504
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
1505
-
1506
-		if(!$row) {
1507
-			return null;
1508
-		}
1509
-
1510
-		return [
1511
-				'uri'          => $row['uri'],
1512
-				'calendardata' => $row['calendardata'],
1513
-				'lastmodified' => $row['lastmodified'],
1514
-				'etag'         => '"' . $row['etag'] . '"',
1515
-				'size'         => (int)$row['size'],
1516
-		];
1517
-	}
1518
-
1519
-	/**
1520
-	 * Returns all scheduling objects for the inbox collection.
1521
-	 *
1522
-	 * These objects should be returned as an array. Every item in the array
1523
-	 * should follow the same structure as returned from getSchedulingObject.
1524
-	 *
1525
-	 * The main difference is that 'calendardata' is optional.
1526
-	 *
1527
-	 * @param string $principalUri
1528
-	 * @return array
1529
-	 */
1530
-	function getSchedulingObjects($principalUri) {
1531
-		$query = $this->db->getQueryBuilder();
1532
-		$stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
1533
-				->from('schedulingobjects')
1534
-				->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1535
-				->execute();
1536
-
1537
-		$result = [];
1538
-		foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
1539
-			$result[] = [
1540
-					'calendardata' => $row['calendardata'],
1541
-					'uri'          => $row['uri'],
1542
-					'lastmodified' => $row['lastmodified'],
1543
-					'etag'         => '"' . $row['etag'] . '"',
1544
-					'size'         => (int)$row['size'],
1545
-			];
1546
-		}
1547
-
1548
-		return $result;
1549
-	}
1550
-
1551
-	/**
1552
-	 * Deletes a scheduling object from the inbox collection.
1553
-	 *
1554
-	 * @param string $principalUri
1555
-	 * @param string $objectUri
1556
-	 * @return void
1557
-	 */
1558
-	function deleteSchedulingObject($principalUri, $objectUri) {
1559
-		$query = $this->db->getQueryBuilder();
1560
-		$query->delete('schedulingobjects')
1561
-				->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1562
-				->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1563
-				->execute();
1564
-	}
1565
-
1566
-	/**
1567
-	 * Creates a new scheduling object. This should land in a users' inbox.
1568
-	 *
1569
-	 * @param string $principalUri
1570
-	 * @param string $objectUri
1571
-	 * @param string $objectData
1572
-	 * @return void
1573
-	 */
1574
-	function createSchedulingObject($principalUri, $objectUri, $objectData) {
1575
-		$query = $this->db->getQueryBuilder();
1576
-		$query->insert('schedulingobjects')
1577
-			->values([
1578
-				'principaluri' => $query->createNamedParameter($principalUri),
1579
-				'calendardata' => $query->createNamedParameter($objectData),
1580
-				'uri' => $query->createNamedParameter($objectUri),
1581
-				'lastmodified' => $query->createNamedParameter(time()),
1582
-				'etag' => $query->createNamedParameter(md5($objectData)),
1583
-				'size' => $query->createNamedParameter(strlen($objectData))
1584
-			])
1585
-			->execute();
1586
-	}
1587
-
1588
-	/**
1589
-	 * Adds a change record to the calendarchanges table.
1590
-	 *
1591
-	 * @param mixed $calendarId
1592
-	 * @param string $objectUri
1593
-	 * @param int $operation 1 = add, 2 = modify, 3 = delete.
1594
-	 * @return void
1595
-	 */
1596
-	protected function addChange($calendarId, $objectUri, $operation) {
1597
-
1598
-		$stmt = $this->db->prepare('INSERT INTO `*PREFIX*calendarchanges` (`uri`, `synctoken`, `calendarid`, `operation`) SELECT ?, `synctoken`, ?, ? FROM `*PREFIX*calendars` WHERE `id` = ?');
1599
-		$stmt->execute([
1600
-			$objectUri,
1601
-			$calendarId,
1602
-			$operation,
1603
-			$calendarId
1604
-		]);
1605
-		$stmt = $this->db->prepare('UPDATE `*PREFIX*calendars` SET `synctoken` = `synctoken` + 1 WHERE `id` = ?');
1606
-		$stmt->execute([
1607
-			$calendarId
1608
-		]);
1609
-
1610
-	}
1611
-
1612
-	/**
1613
-	 * Parses some information from calendar objects, used for optimized
1614
-	 * calendar-queries.
1615
-	 *
1616
-	 * Returns an array with the following keys:
1617
-	 *   * etag - An md5 checksum of the object without the quotes.
1618
-	 *   * size - Size of the object in bytes
1619
-	 *   * componentType - VEVENT, VTODO or VJOURNAL
1620
-	 *   * firstOccurence
1621
-	 *   * lastOccurence
1622
-	 *   * uid - value of the UID property
1623
-	 *
1624
-	 * @param string $calendarData
1625
-	 * @return array
1626
-	 */
1627
-	public function getDenormalizedData($calendarData) {
1628
-
1629
-		$vObject = Reader::read($calendarData);
1630
-		$componentType = null;
1631
-		$component = null;
1632
-		$firstOccurrence = null;
1633
-		$lastOccurrence = null;
1634
-		$uid = null;
1635
-		$classification = self::CLASSIFICATION_PUBLIC;
1636
-		foreach($vObject->getComponents() as $component) {
1637
-			if ($component->name!=='VTIMEZONE') {
1638
-				$componentType = $component->name;
1639
-				$uid = (string)$component->UID;
1640
-				break;
1641
-			}
1642
-		}
1643
-		if (!$componentType) {
1644
-			throw new \Sabre\DAV\Exception\BadRequest('Calendar objects must have a VJOURNAL, VEVENT or VTODO component');
1645
-		}
1646
-		if ($componentType === 'VEVENT' && $component->DTSTART) {
1647
-			$firstOccurrence = $component->DTSTART->getDateTime()->getTimeStamp();
1648
-			// Finding the last occurrence is a bit harder
1649
-			if (!isset($component->RRULE)) {
1650
-				if (isset($component->DTEND)) {
1651
-					$lastOccurrence = $component->DTEND->getDateTime()->getTimeStamp();
1652
-				} elseif (isset($component->DURATION)) {
1653
-					$endDate = clone $component->DTSTART->getDateTime();
1654
-					$endDate->add(DateTimeParser::parse($component->DURATION->getValue()));
1655
-					$lastOccurrence = $endDate->getTimeStamp();
1656
-				} elseif (!$component->DTSTART->hasTime()) {
1657
-					$endDate = clone $component->DTSTART->getDateTime();
1658
-					$endDate->modify('+1 day');
1659
-					$lastOccurrence = $endDate->getTimeStamp();
1660
-				} else {
1661
-					$lastOccurrence = $firstOccurrence;
1662
-				}
1663
-			} else {
1664
-				$it = new EventIterator($vObject, (string)$component->UID);
1665
-				$maxDate = new \DateTime(self::MAX_DATE);
1666
-				if ($it->isInfinite()) {
1667
-					$lastOccurrence = $maxDate->getTimestamp();
1668
-				} else {
1669
-					$end = $it->getDtEnd();
1670
-					while($it->valid() && $end < $maxDate) {
1671
-						$end = $it->getDtEnd();
1672
-						$it->next();
1673
-
1674
-					}
1675
-					$lastOccurrence = $end->getTimestamp();
1676
-				}
1677
-
1678
-			}
1679
-		}
1680
-
1681
-		if ($component->CLASS) {
1682
-			$classification = CalDavBackend::CLASSIFICATION_PRIVATE;
1683
-			switch ($component->CLASS->getValue()) {
1684
-				case 'PUBLIC':
1685
-					$classification = CalDavBackend::CLASSIFICATION_PUBLIC;
1686
-					break;
1687
-				case 'CONFIDENTIAL':
1688
-					$classification = CalDavBackend::CLASSIFICATION_CONFIDENTIAL;
1689
-					break;
1690
-			}
1691
-		}
1692
-		return [
1693
-			'etag' => md5($calendarData),
1694
-			'size' => strlen($calendarData),
1695
-			'componentType' => $componentType,
1696
-			'firstOccurence' => is_null($firstOccurrence) ? null : max(0, $firstOccurrence),
1697
-			'lastOccurence'  => $lastOccurrence,
1698
-			'uid' => $uid,
1699
-			'classification' => $classification
1700
-		];
1701
-
1702
-	}
1703
-
1704
-	private function readBlob($cardData) {
1705
-		if (is_resource($cardData)) {
1706
-			return stream_get_contents($cardData);
1707
-		}
1708
-
1709
-		return $cardData;
1710
-	}
1711
-
1712
-	/**
1713
-	 * @param IShareable $shareable
1714
-	 * @param array $add
1715
-	 * @param array $remove
1716
-	 */
1717
-	public function updateShares($shareable, $add, $remove) {
1718
-		$calendarId = $shareable->getResourceId();
1719
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateShares', new GenericEvent(
1720
-			'\OCA\DAV\CalDAV\CalDavBackend::updateShares',
1721
-			[
1722
-				'calendarId' => $calendarId,
1723
-				'calendarData' => $this->getCalendarById($calendarId),
1724
-				'shares' => $this->getShares($calendarId),
1725
-				'add' => $add,
1726
-				'remove' => $remove,
1727
-			]));
1728
-		$this->sharingBackend->updateShares($shareable, $add, $remove);
1729
-	}
1730
-
1731
-	/**
1732
-	 * @param int $resourceId
1733
-	 * @return array
1734
-	 */
1735
-	public function getShares($resourceId) {
1736
-		return $this->sharingBackend->getShares($resourceId);
1737
-	}
1738
-
1739
-	/**
1740
-	 * @param boolean $value
1741
-	 * @param \OCA\DAV\CalDAV\Calendar $calendar
1742
-	 * @return string|null
1743
-	 */
1744
-	public function setPublishStatus($value, $calendar) {
1745
-		$query = $this->db->getQueryBuilder();
1746
-		if ($value) {
1747
-			$publicUri = $this->random->generate(16, ISecureRandom::CHAR_UPPER.ISecureRandom::CHAR_DIGITS);
1748
-			$query->insert('dav_shares')
1749
-				->values([
1750
-					'principaluri' => $query->createNamedParameter($calendar->getPrincipalURI()),
1751
-					'type' => $query->createNamedParameter('calendar'),
1752
-					'access' => $query->createNamedParameter(self::ACCESS_PUBLIC),
1753
-					'resourceid' => $query->createNamedParameter($calendar->getResourceId()),
1754
-					'publicuri' => $query->createNamedParameter($publicUri)
1755
-				]);
1756
-			$query->execute();
1757
-			return $publicUri;
1758
-		}
1759
-		$query->delete('dav_shares')
1760
-			->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
1761
-			->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)));
1762
-		$query->execute();
1763
-		return null;
1764
-	}
1765
-
1766
-	/**
1767
-	 * @param \OCA\DAV\CalDAV\Calendar $calendar
1768
-	 * @return mixed
1769
-	 */
1770
-	public function getPublishStatus($calendar) {
1771
-		$query = $this->db->getQueryBuilder();
1772
-		$result = $query->select('publicuri')
1773
-			->from('dav_shares')
1774
-			->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
1775
-			->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
1776
-			->execute();
1777
-
1778
-		$row = $result->fetch();
1779
-		$result->closeCursor();
1780
-		return $row ? reset($row) : false;
1781
-	}
1782
-
1783
-	/**
1784
-	 * @param int $resourceId
1785
-	 * @param array $acl
1786
-	 * @return array
1787
-	 */
1788
-	public function applyShareAcl($resourceId, $acl) {
1789
-		return $this->sharingBackend->applyShareAcl($resourceId, $acl);
1790
-	}
1791
-
1792
-	private function convertPrincipal($principalUri, $toV2) {
1793
-		if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
1794
-			list(, $name) = URLUtil::splitPath($principalUri);
1795
-			if ($toV2 === true) {
1796
-				return "principals/users/$name";
1797
-			}
1798
-			return "principals/$name";
1799
-		}
1800
-		return $principalUri;
1801
-	}
369
+    /**
370
+     * @return array
371
+     */
372
+    public function getPublicCalendars() {
373
+        $fields = array_values($this->propertyMap);
374
+        $fields[] = 'a.id';
375
+        $fields[] = 'a.uri';
376
+        $fields[] = 'a.synctoken';
377
+        $fields[] = 'a.components';
378
+        $fields[] = 'a.principaluri';
379
+        $fields[] = 'a.transparent';
380
+        $fields[] = 's.access';
381
+        $fields[] = 's.publicuri';
382
+        $calendars = [];
383
+        $query = $this->db->getQueryBuilder();
384
+        $result = $query->select($fields)
385
+            ->from('dav_shares', 's')
386
+            ->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
387
+            ->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
388
+            ->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
389
+            ->execute();
390
+
391
+        while($row = $result->fetch()) {
392
+            list(, $name) = URLUtil::splitPath($row['principaluri']);
393
+            $row['displayname'] = $row['displayname'] . "($name)";
394
+            $components = [];
395
+            if ($row['components']) {
396
+                $components = explode(',',$row['components']);
397
+            }
398
+            $calendar = [
399
+                'id' => $row['id'],
400
+                'uri' => $row['publicuri'],
401
+                'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
402
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
403
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
404
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
405
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
406
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
407
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
408
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
409
+            ];
410
+
411
+            foreach($this->propertyMap as $xmlName=>$dbName) {
412
+                $calendar[$xmlName] = $row[$dbName];
413
+            }
414
+
415
+            if (!isset($calendars[$calendar['id']])) {
416
+                $calendars[$calendar['id']] = $calendar;
417
+            }
418
+        }
419
+        $result->closeCursor();
420
+
421
+        return array_values($calendars);
422
+    }
423
+
424
+    /**
425
+     * @param string $uri
426
+     * @return array
427
+     * @throws NotFound
428
+     */
429
+    public function getPublicCalendar($uri) {
430
+        $fields = array_values($this->propertyMap);
431
+        $fields[] = 'a.id';
432
+        $fields[] = 'a.uri';
433
+        $fields[] = 'a.synctoken';
434
+        $fields[] = 'a.components';
435
+        $fields[] = 'a.principaluri';
436
+        $fields[] = 'a.transparent';
437
+        $fields[] = 's.access';
438
+        $fields[] = 's.publicuri';
439
+        $query = $this->db->getQueryBuilder();
440
+        $result = $query->select($fields)
441
+            ->from('dav_shares', 's')
442
+            ->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
443
+            ->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
444
+            ->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
445
+            ->andWhere($query->expr()->eq('s.publicuri', $query->createNamedParameter($uri)))
446
+            ->execute();
447
+
448
+        $row = $result->fetch(\PDO::FETCH_ASSOC);
449
+
450
+        $result->closeCursor();
451
+
452
+        if ($row === false) {
453
+            throw new NotFound('Node with name \'' . $uri . '\' could not be found');
454
+        }
455
+
456
+        list(, $name) = URLUtil::splitPath($row['principaluri']);
457
+        $row['displayname'] = $row['displayname'] . ' ' . "($name)";
458
+        $components = [];
459
+        if ($row['components']) {
460
+            $components = explode(',',$row['components']);
461
+        }
462
+        $calendar = [
463
+            'id' => $row['id'],
464
+            'uri' => $row['publicuri'],
465
+            'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
466
+            '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
467
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
468
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
469
+            '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
470
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
471
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
472
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
473
+        ];
474
+
475
+        foreach($this->propertyMap as $xmlName=>$dbName) {
476
+            $calendar[$xmlName] = $row[$dbName];
477
+        }
478
+
479
+        return $calendar;
480
+
481
+    }
482
+
483
+    /**
484
+     * @param string $principal
485
+     * @param string $uri
486
+     * @return array|null
487
+     */
488
+    public function getCalendarByUri($principal, $uri) {
489
+        $fields = array_values($this->propertyMap);
490
+        $fields[] = 'id';
491
+        $fields[] = 'uri';
492
+        $fields[] = 'synctoken';
493
+        $fields[] = 'components';
494
+        $fields[] = 'principaluri';
495
+        $fields[] = 'transparent';
496
+
497
+        // Making fields a comma-delimited list
498
+        $query = $this->db->getQueryBuilder();
499
+        $query->select($fields)->from('calendars')
500
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
501
+            ->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
502
+            ->setMaxResults(1);
503
+        $stmt = $query->execute();
504
+
505
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
506
+        $stmt->closeCursor();
507
+        if ($row === false) {
508
+            return null;
509
+        }
510
+
511
+        $components = [];
512
+        if ($row['components']) {
513
+            $components = explode(',',$row['components']);
514
+        }
515
+
516
+        $calendar = [
517
+            'id' => $row['id'],
518
+            'uri' => $row['uri'],
519
+            'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
520
+            '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
521
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
522
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
523
+            '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
524
+        ];
525
+
526
+        foreach($this->propertyMap as $xmlName=>$dbName) {
527
+            $calendar[$xmlName] = $row[$dbName];
528
+        }
529
+
530
+        return $calendar;
531
+    }
532
+
533
+    public function getCalendarById($calendarId) {
534
+        $fields = array_values($this->propertyMap);
535
+        $fields[] = 'id';
536
+        $fields[] = 'uri';
537
+        $fields[] = 'synctoken';
538
+        $fields[] = 'components';
539
+        $fields[] = 'principaluri';
540
+        $fields[] = 'transparent';
541
+
542
+        // Making fields a comma-delimited list
543
+        $query = $this->db->getQueryBuilder();
544
+        $query->select($fields)->from('calendars')
545
+            ->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)))
546
+            ->setMaxResults(1);
547
+        $stmt = $query->execute();
548
+
549
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
550
+        $stmt->closeCursor();
551
+        if ($row === false) {
552
+            return null;
553
+        }
554
+
555
+        $components = [];
556
+        if ($row['components']) {
557
+            $components = explode(',',$row['components']);
558
+        }
559
+
560
+        $calendar = [
561
+            'id' => $row['id'],
562
+            'uri' => $row['uri'],
563
+            'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
564
+            '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
565
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
566
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
567
+            '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
568
+        ];
569
+
570
+        foreach($this->propertyMap as $xmlName=>$dbName) {
571
+            $calendar[$xmlName] = $row[$dbName];
572
+        }
573
+
574
+        return $calendar;
575
+    }
576
+
577
+    /**
578
+     * Creates a new calendar for a principal.
579
+     *
580
+     * If the creation was a success, an id must be returned that can be used to reference
581
+     * this calendar in other methods, such as updateCalendar.
582
+     *
583
+     * @param string $principalUri
584
+     * @param string $calendarUri
585
+     * @param array $properties
586
+     * @return int
587
+     */
588
+    function createCalendar($principalUri, $calendarUri, array $properties) {
589
+        $values = [
590
+            'principaluri' => $this->convertPrincipal($principalUri, true),
591
+            'uri'          => $calendarUri,
592
+            'synctoken'    => 1,
593
+            'transparent'  => 0,
594
+            'components'   => 'VEVENT,VTODO',
595
+            'displayname'  => $calendarUri
596
+        ];
597
+
598
+        // Default value
599
+        $sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
600
+        if (isset($properties[$sccs])) {
601
+            if (!($properties[$sccs] instanceof SupportedCalendarComponentSet)) {
602
+                throw new DAV\Exception('The ' . $sccs . ' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
603
+            }
604
+            $values['components'] = implode(',',$properties[$sccs]->getValue());
605
+        }
606
+        $transp = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
607
+        if (isset($properties[$transp])) {
608
+            $values['transparent'] = $properties[$transp]->getValue()==='transparent';
609
+        }
610
+
611
+        foreach($this->propertyMap as $xmlName=>$dbName) {
612
+            if (isset($properties[$xmlName])) {
613
+                $values[$dbName] = $properties[$xmlName];
614
+            }
615
+        }
616
+
617
+        $query = $this->db->getQueryBuilder();
618
+        $query->insert('calendars');
619
+        foreach($values as $column => $value) {
620
+            $query->setValue($column, $query->createNamedParameter($value));
621
+        }
622
+        $query->execute();
623
+        $calendarId = $query->getLastInsertId();
624
+
625
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendar', new GenericEvent(
626
+            '\OCA\DAV\CalDAV\CalDavBackend::createCalendar',
627
+            [
628
+                'calendarId' => $calendarId,
629
+                'calendarData' => $this->getCalendarById($calendarId),
630
+        ]));
631
+
632
+        return $calendarId;
633
+    }
634
+
635
+    /**
636
+     * Updates properties for a calendar.
637
+     *
638
+     * The list of mutations is stored in a Sabre\DAV\PropPatch object.
639
+     * To do the actual updates, you must tell this object which properties
640
+     * you're going to process with the handle() method.
641
+     *
642
+     * Calling the handle method is like telling the PropPatch object "I
643
+     * promise I can handle updating this property".
644
+     *
645
+     * Read the PropPatch documentation for more info and examples.
646
+     *
647
+     * @param PropPatch $propPatch
648
+     * @return void
649
+     */
650
+    function updateCalendar($calendarId, PropPatch $propPatch) {
651
+        $supportedProperties = array_keys($this->propertyMap);
652
+        $supportedProperties[] = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
653
+
654
+        $propPatch->handle($supportedProperties, function($mutations) use ($calendarId) {
655
+            $newValues = [];
656
+            foreach ($mutations as $propertyName => $propertyValue) {
657
+
658
+                switch ($propertyName) {
659
+                    case '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' :
660
+                        $fieldName = 'transparent';
661
+                        $newValues[$fieldName] = $propertyValue->getValue() === 'transparent';
662
+                        break;
663
+                    default :
664
+                        $fieldName = $this->propertyMap[$propertyName];
665
+                        $newValues[$fieldName] = $propertyValue;
666
+                        break;
667
+                }
668
+
669
+            }
670
+            $query = $this->db->getQueryBuilder();
671
+            $query->update('calendars');
672
+            foreach ($newValues as $fieldName => $value) {
673
+                $query->set($fieldName, $query->createNamedParameter($value));
674
+            }
675
+            $query->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
676
+            $query->execute();
677
+
678
+            $this->addChange($calendarId, "", 2);
679
+
680
+            $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendar', new GenericEvent(
681
+                '\OCA\DAV\CalDAV\CalDavBackend::updateCalendar',
682
+                [
683
+                    'calendarId' => $calendarId,
684
+                    'calendarData' => $this->getCalendarById($calendarId),
685
+                    'shares' => $this->getShares($calendarId),
686
+                    'propertyMutations' => $mutations,
687
+            ]));
688
+
689
+            return true;
690
+        });
691
+    }
692
+
693
+    /**
694
+     * Delete a calendar and all it's objects
695
+     *
696
+     * @param mixed $calendarId
697
+     * @return void
698
+     */
699
+    function deleteCalendar($calendarId) {
700
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar', new GenericEvent(
701
+            '\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar',
702
+            [
703
+                'calendarId' => $calendarId,
704
+                'calendarData' => $this->getCalendarById($calendarId),
705
+                'shares' => $this->getShares($calendarId),
706
+        ]));
707
+
708
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ?');
709
+        $stmt->execute([$calendarId]);
710
+
711
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendars` WHERE `id` = ?');
712
+        $stmt->execute([$calendarId]);
713
+
714
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarchanges` WHERE `calendarid` = ?');
715
+        $stmt->execute([$calendarId]);
716
+
717
+        $this->sharingBackend->deleteAllShares($calendarId);
718
+    }
719
+
720
+    /**
721
+     * Delete all of an user's shares
722
+     *
723
+     * @param string $principaluri
724
+     * @return void
725
+     */
726
+    function deleteAllSharesByUser($principaluri) {
727
+        $this->sharingBackend->deleteAllSharesByUser($principaluri);
728
+    }
729
+
730
+    /**
731
+     * Returns all calendar objects within a calendar.
732
+     *
733
+     * Every item contains an array with the following keys:
734
+     *   * calendardata - The iCalendar-compatible calendar data
735
+     *   * uri - a unique key which will be used to construct the uri. This can
736
+     *     be any arbitrary string, but making sure it ends with '.ics' is a
737
+     *     good idea. This is only the basename, or filename, not the full
738
+     *     path.
739
+     *   * lastmodified - a timestamp of the last modification time
740
+     *   * etag - An arbitrary string, surrounded by double-quotes. (e.g.:
741
+     *   '"abcdef"')
742
+     *   * size - The size of the calendar objects, in bytes.
743
+     *   * component - optional, a string containing the type of object, such
744
+     *     as 'vevent' or 'vtodo'. If specified, this will be used to populate
745
+     *     the Content-Type header.
746
+     *
747
+     * Note that the etag is optional, but it's highly encouraged to return for
748
+     * speed reasons.
749
+     *
750
+     * The calendardata is also optional. If it's not returned
751
+     * 'getCalendarObject' will be called later, which *is* expected to return
752
+     * calendardata.
753
+     *
754
+     * If neither etag or size are specified, the calendardata will be
755
+     * used/fetched to determine these numbers. If both are specified the
756
+     * amount of times this is needed is reduced by a great degree.
757
+     *
758
+     * @param mixed $calendarId
759
+     * @return array
760
+     */
761
+    function getCalendarObjects($calendarId) {
762
+        $query = $this->db->getQueryBuilder();
763
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'componenttype', 'classification'])
764
+            ->from('calendarobjects')
765
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
766
+        $stmt = $query->execute();
767
+
768
+        $result = [];
769
+        foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
770
+            $result[] = [
771
+                    'id'           => $row['id'],
772
+                    'uri'          => $row['uri'],
773
+                    'lastmodified' => $row['lastmodified'],
774
+                    'etag'         => '"' . $row['etag'] . '"',
775
+                    'calendarid'   => $row['calendarid'],
776
+                    'size'         => (int)$row['size'],
777
+                    'component'    => strtolower($row['componenttype']),
778
+                    'classification'=> (int)$row['classification']
779
+            ];
780
+        }
781
+
782
+        return $result;
783
+    }
784
+
785
+    /**
786
+     * Returns information from a single calendar object, based on it's object
787
+     * uri.
788
+     *
789
+     * The object uri is only the basename, or filename and not a full path.
790
+     *
791
+     * The returned array must have the same keys as getCalendarObjects. The
792
+     * 'calendardata' object is required here though, while it's not required
793
+     * for getCalendarObjects.
794
+     *
795
+     * This method must return null if the object did not exist.
796
+     *
797
+     * @param mixed $calendarId
798
+     * @param string $objectUri
799
+     * @return array|null
800
+     */
801
+    function getCalendarObject($calendarId, $objectUri) {
802
+
803
+        $query = $this->db->getQueryBuilder();
804
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
805
+                ->from('calendarobjects')
806
+                ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
807
+                ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)));
808
+        $stmt = $query->execute();
809
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
810
+
811
+        if(!$row) return null;
812
+
813
+        return [
814
+                'id'            => $row['id'],
815
+                'uri'           => $row['uri'],
816
+                'lastmodified'  => $row['lastmodified'],
817
+                'etag'          => '"' . $row['etag'] . '"',
818
+                'calendarid'    => $row['calendarid'],
819
+                'size'          => (int)$row['size'],
820
+                'calendardata'  => $this->readBlob($row['calendardata']),
821
+                'component'     => strtolower($row['componenttype']),
822
+                'classification'=> (int)$row['classification']
823
+        ];
824
+    }
825
+
826
+    /**
827
+     * Returns a list of calendar objects.
828
+     *
829
+     * This method should work identical to getCalendarObject, but instead
830
+     * return all the calendar objects in the list as an array.
831
+     *
832
+     * If the backend supports this, it may allow for some speed-ups.
833
+     *
834
+     * @param mixed $calendarId
835
+     * @param string[] $uris
836
+     * @return array
837
+     */
838
+    function getMultipleCalendarObjects($calendarId, array $uris) {
839
+        if (empty($uris)) {
840
+            return [];
841
+        }
842
+
843
+        $chunks = array_chunk($uris, 100);
844
+        $objects = [];
845
+
846
+        $query = $this->db->getQueryBuilder();
847
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
848
+            ->from('calendarobjects')
849
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
850
+            ->andWhere($query->expr()->in('uri', $query->createParameter('uri')));
851
+
852
+        foreach ($chunks as $uris) {
853
+            $query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
854
+            $result = $query->execute();
855
+
856
+            while ($row = $result->fetch()) {
857
+                $objects[] = [
858
+                    'id'           => $row['id'],
859
+                    'uri'          => $row['uri'],
860
+                    'lastmodified' => $row['lastmodified'],
861
+                    'etag'         => '"' . $row['etag'] . '"',
862
+                    'calendarid'   => $row['calendarid'],
863
+                    'size'         => (int)$row['size'],
864
+                    'calendardata' => $this->readBlob($row['calendardata']),
865
+                    'component'    => strtolower($row['componenttype']),
866
+                    'classification' => (int)$row['classification']
867
+                ];
868
+            }
869
+            $result->closeCursor();
870
+        }
871
+        return $objects;
872
+    }
873
+
874
+    /**
875
+     * Creates a new calendar object.
876
+     *
877
+     * The object uri is only the basename, or filename and not a full path.
878
+     *
879
+     * It is possible return an etag from this function, which will be used in
880
+     * the response to this PUT request. Note that the ETag must be surrounded
881
+     * by double-quotes.
882
+     *
883
+     * However, you should only really return this ETag if you don't mangle the
884
+     * calendar-data. If the result of a subsequent GET to this object is not
885
+     * the exact same as this request body, you should omit the ETag.
886
+     *
887
+     * @param mixed $calendarId
888
+     * @param string $objectUri
889
+     * @param string $calendarData
890
+     * @return string
891
+     */
892
+    function createCalendarObject($calendarId, $objectUri, $calendarData) {
893
+        $extraData = $this->getDenormalizedData($calendarData);
894
+
895
+        $query = $this->db->getQueryBuilder();
896
+        $query->insert('calendarobjects')
897
+            ->values([
898
+                'calendarid' => $query->createNamedParameter($calendarId),
899
+                'uri' => $query->createNamedParameter($objectUri),
900
+                'calendardata' => $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB),
901
+                'lastmodified' => $query->createNamedParameter(time()),
902
+                'etag' => $query->createNamedParameter($extraData['etag']),
903
+                'size' => $query->createNamedParameter($extraData['size']),
904
+                'componenttype' => $query->createNamedParameter($extraData['componentType']),
905
+                'firstoccurence' => $query->createNamedParameter($extraData['firstOccurence']),
906
+                'lastoccurence' => $query->createNamedParameter($extraData['lastOccurence']),
907
+                'classification' => $query->createNamedParameter($extraData['classification']),
908
+                'uid' => $query->createNamedParameter($extraData['uid']),
909
+            ])
910
+            ->execute();
911
+
912
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject', new GenericEvent(
913
+            '\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject',
914
+            [
915
+                'calendarId' => $calendarId,
916
+                'calendarData' => $this->getCalendarById($calendarId),
917
+                'shares' => $this->getShares($calendarId),
918
+                'objectData' => $this->getCalendarObject($calendarId, $objectUri),
919
+            ]
920
+        ));
921
+        $this->addChange($calendarId, $objectUri, 1);
922
+
923
+        return '"' . $extraData['etag'] . '"';
924
+    }
925
+
926
+    /**
927
+     * Updates an existing calendarobject, based on it's uri.
928
+     *
929
+     * The object uri is only the basename, or filename and not a full path.
930
+     *
931
+     * It is possible return an etag from this function, which will be used in
932
+     * the response to this PUT request. Note that the ETag must be surrounded
933
+     * by double-quotes.
934
+     *
935
+     * However, you should only really return this ETag if you don't mangle the
936
+     * calendar-data. If the result of a subsequent GET to this object is not
937
+     * the exact same as this request body, you should omit the ETag.
938
+     *
939
+     * @param mixed $calendarId
940
+     * @param string $objectUri
941
+     * @param string $calendarData
942
+     * @return string
943
+     */
944
+    function updateCalendarObject($calendarId, $objectUri, $calendarData) {
945
+        $extraData = $this->getDenormalizedData($calendarData);
946
+
947
+        $query = $this->db->getQueryBuilder();
948
+        $query->update('calendarobjects')
949
+                ->set('calendardata', $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB))
950
+                ->set('lastmodified', $query->createNamedParameter(time()))
951
+                ->set('etag', $query->createNamedParameter($extraData['etag']))
952
+                ->set('size', $query->createNamedParameter($extraData['size']))
953
+                ->set('componenttype', $query->createNamedParameter($extraData['componentType']))
954
+                ->set('firstoccurence', $query->createNamedParameter($extraData['firstOccurence']))
955
+                ->set('lastoccurence', $query->createNamedParameter($extraData['lastOccurence']))
956
+                ->set('classification', $query->createNamedParameter($extraData['classification']))
957
+                ->set('uid', $query->createNamedParameter($extraData['uid']))
958
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
959
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
960
+            ->execute();
961
+
962
+        $data = $this->getCalendarObject($calendarId, $objectUri);
963
+        if (is_array($data)) {
964
+            $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject', new GenericEvent(
965
+                '\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject',
966
+                [
967
+                    'calendarId' => $calendarId,
968
+                    'calendarData' => $this->getCalendarById($calendarId),
969
+                    'shares' => $this->getShares($calendarId),
970
+                    'objectData' => $data,
971
+                ]
972
+            ));
973
+        }
974
+        $this->addChange($calendarId, $objectUri, 2);
975
+
976
+        return '"' . $extraData['etag'] . '"';
977
+    }
978
+
979
+    /**
980
+     * @param int $calendarObjectId
981
+     * @param int $classification
982
+     */
983
+    public function setClassification($calendarObjectId, $classification) {
984
+        if (!in_array($classification, [
985
+            self::CLASSIFICATION_PUBLIC, self::CLASSIFICATION_PRIVATE, self::CLASSIFICATION_CONFIDENTIAL
986
+        ])) {
987
+            throw new \InvalidArgumentException();
988
+        }
989
+        $query = $this->db->getQueryBuilder();
990
+        $query->update('calendarobjects')
991
+            ->set('classification', $query->createNamedParameter($classification))
992
+            ->where($query->expr()->eq('id', $query->createNamedParameter($calendarObjectId)))
993
+            ->execute();
994
+    }
995
+
996
+    /**
997
+     * Deletes an existing calendar object.
998
+     *
999
+     * The object uri is only the basename, or filename and not a full path.
1000
+     *
1001
+     * @param mixed $calendarId
1002
+     * @param string $objectUri
1003
+     * @return void
1004
+     */
1005
+    function deleteCalendarObject($calendarId, $objectUri) {
1006
+        $data = $this->getCalendarObject($calendarId, $objectUri);
1007
+        if (is_array($data)) {
1008
+            $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject', new GenericEvent(
1009
+                '\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject',
1010
+                [
1011
+                    'calendarId' => $calendarId,
1012
+                    'calendarData' => $this->getCalendarById($calendarId),
1013
+                    'shares' => $this->getShares($calendarId),
1014
+                    'objectData' => $data,
1015
+                ]
1016
+            ));
1017
+        }
1018
+
1019
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `uri` = ?');
1020
+        $stmt->execute([$calendarId, $objectUri]);
1021
+
1022
+        $this->addChange($calendarId, $objectUri, 3);
1023
+    }
1024
+
1025
+    /**
1026
+     * Performs a calendar-query on the contents of this calendar.
1027
+     *
1028
+     * The calendar-query is defined in RFC4791 : CalDAV. Using the
1029
+     * calendar-query it is possible for a client to request a specific set of
1030
+     * object, based on contents of iCalendar properties, date-ranges and
1031
+     * iCalendar component types (VTODO, VEVENT).
1032
+     *
1033
+     * This method should just return a list of (relative) urls that match this
1034
+     * query.
1035
+     *
1036
+     * The list of filters are specified as an array. The exact array is
1037
+     * documented by Sabre\CalDAV\CalendarQueryParser.
1038
+     *
1039
+     * Note that it is extremely likely that getCalendarObject for every path
1040
+     * returned from this method will be called almost immediately after. You
1041
+     * may want to anticipate this to speed up these requests.
1042
+     *
1043
+     * This method provides a default implementation, which parses *all* the
1044
+     * iCalendar objects in the specified calendar.
1045
+     *
1046
+     * This default may well be good enough for personal use, and calendars
1047
+     * that aren't very large. But if you anticipate high usage, big calendars
1048
+     * or high loads, you are strongly advised to optimize certain paths.
1049
+     *
1050
+     * The best way to do so is override this method and to optimize
1051
+     * specifically for 'common filters'.
1052
+     *
1053
+     * Requests that are extremely common are:
1054
+     *   * requests for just VEVENTS
1055
+     *   * requests for just VTODO
1056
+     *   * requests with a time-range-filter on either VEVENT or VTODO.
1057
+     *
1058
+     * ..and combinations of these requests. It may not be worth it to try to
1059
+     * handle every possible situation and just rely on the (relatively
1060
+     * easy to use) CalendarQueryValidator to handle the rest.
1061
+     *
1062
+     * Note that especially time-range-filters may be difficult to parse. A
1063
+     * time-range filter specified on a VEVENT must for instance also handle
1064
+     * recurrence rules correctly.
1065
+     * A good example of how to interprete all these filters can also simply
1066
+     * be found in Sabre\CalDAV\CalendarQueryFilter. This class is as correct
1067
+     * as possible, so it gives you a good idea on what type of stuff you need
1068
+     * to think of.
1069
+     *
1070
+     * @param mixed $calendarId
1071
+     * @param array $filters
1072
+     * @return array
1073
+     */
1074
+    function calendarQuery($calendarId, array $filters) {
1075
+        $componentType = null;
1076
+        $requirePostFilter = true;
1077
+        $timeRange = null;
1078
+
1079
+        // if no filters were specified, we don't need to filter after a query
1080
+        if (!$filters['prop-filters'] && !$filters['comp-filters']) {
1081
+            $requirePostFilter = false;
1082
+        }
1083
+
1084
+        // Figuring out if there's a component filter
1085
+        if (count($filters['comp-filters']) > 0 && !$filters['comp-filters'][0]['is-not-defined']) {
1086
+            $componentType = $filters['comp-filters'][0]['name'];
1087
+
1088
+            // Checking if we need post-filters
1089
+            if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['time-range'] && !$filters['comp-filters'][0]['prop-filters']) {
1090
+                $requirePostFilter = false;
1091
+            }
1092
+            // There was a time-range filter
1093
+            if ($componentType == 'VEVENT' && isset($filters['comp-filters'][0]['time-range'])) {
1094
+                $timeRange = $filters['comp-filters'][0]['time-range'];
1095
+
1096
+                // If start time OR the end time is not specified, we can do a
1097
+                // 100% accurate mysql query.
1098
+                if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['prop-filters'] && (!$timeRange['start'] || !$timeRange['end'])) {
1099
+                    $requirePostFilter = false;
1100
+                }
1101
+            }
1102
+
1103
+        }
1104
+        $columns = ['uri'];
1105
+        if ($requirePostFilter) {
1106
+            $columns = ['uri', 'calendardata'];
1107
+        }
1108
+        $query = $this->db->getQueryBuilder();
1109
+        $query->select($columns)
1110
+            ->from('calendarobjects')
1111
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
1112
+
1113
+        if ($componentType) {
1114
+            $query->andWhere($query->expr()->eq('componenttype', $query->createNamedParameter($componentType)));
1115
+        }
1116
+
1117
+        if ($timeRange && $timeRange['start']) {
1118
+            $query->andWhere($query->expr()->gt('lastoccurence', $query->createNamedParameter($timeRange['start']->getTimeStamp())));
1119
+        }
1120
+        if ($timeRange && $timeRange['end']) {
1121
+            $query->andWhere($query->expr()->lt('firstoccurence', $query->createNamedParameter($timeRange['end']->getTimeStamp())));
1122
+        }
1123
+
1124
+        $stmt = $query->execute();
1125
+
1126
+        $result = [];
1127
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1128
+            if ($requirePostFilter) {
1129
+                if (!$this->validateFilterForObject($row, $filters)) {
1130
+                    continue;
1131
+                }
1132
+            }
1133
+            $result[] = $row['uri'];
1134
+        }
1135
+
1136
+        return $result;
1137
+    }
1138
+
1139
+    /**
1140
+     * Searches through all of a users calendars and calendar objects to find
1141
+     * an object with a specific UID.
1142
+     *
1143
+     * This method should return the path to this object, relative to the
1144
+     * calendar home, so this path usually only contains two parts:
1145
+     *
1146
+     * calendarpath/objectpath.ics
1147
+     *
1148
+     * If the uid is not found, return null.
1149
+     *
1150
+     * This method should only consider * objects that the principal owns, so
1151
+     * any calendars owned by other principals that also appear in this
1152
+     * collection should be ignored.
1153
+     *
1154
+     * @param string $principalUri
1155
+     * @param string $uid
1156
+     * @return string|null
1157
+     */
1158
+    function getCalendarObjectByUID($principalUri, $uid) {
1159
+
1160
+        $query = $this->db->getQueryBuilder();
1161
+        $query->selectAlias('c.uri', 'calendaruri')->selectAlias('co.uri', 'objecturi')
1162
+            ->from('calendarobjects', 'co')
1163
+            ->leftJoin('co', 'calendars', 'c', $query->expr()->eq('co.calendarid', 'c.id'))
1164
+            ->where($query->expr()->eq('c.principaluri', $query->createNamedParameter($principalUri)))
1165
+            ->andWhere($query->expr()->eq('co.uid', $query->createNamedParameter($uid)));
1166
+
1167
+        $stmt = $query->execute();
1168
+
1169
+        if ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1170
+            return $row['calendaruri'] . '/' . $row['objecturi'];
1171
+        }
1172
+
1173
+        return null;
1174
+    }
1175
+
1176
+    /**
1177
+     * The getChanges method returns all the changes that have happened, since
1178
+     * the specified syncToken in the specified calendar.
1179
+     *
1180
+     * This function should return an array, such as the following:
1181
+     *
1182
+     * [
1183
+     *   'syncToken' => 'The current synctoken',
1184
+     *   'added'   => [
1185
+     *      'new.txt',
1186
+     *   ],
1187
+     *   'modified'   => [
1188
+     *      'modified.txt',
1189
+     *   ],
1190
+     *   'deleted' => [
1191
+     *      'foo.php.bak',
1192
+     *      'old.txt'
1193
+     *   ]
1194
+     * );
1195
+     *
1196
+     * The returned syncToken property should reflect the *current* syncToken
1197
+     * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
1198
+     * property This is * needed here too, to ensure the operation is atomic.
1199
+     *
1200
+     * If the $syncToken argument is specified as null, this is an initial
1201
+     * sync, and all members should be reported.
1202
+     *
1203
+     * The modified property is an array of nodenames that have changed since
1204
+     * the last token.
1205
+     *
1206
+     * The deleted property is an array with nodenames, that have been deleted
1207
+     * from collection.
1208
+     *
1209
+     * The $syncLevel argument is basically the 'depth' of the report. If it's
1210
+     * 1, you only have to report changes that happened only directly in
1211
+     * immediate descendants. If it's 2, it should also include changes from
1212
+     * the nodes below the child collections. (grandchildren)
1213
+     *
1214
+     * The $limit argument allows a client to specify how many results should
1215
+     * be returned at most. If the limit is not specified, it should be treated
1216
+     * as infinite.
1217
+     *
1218
+     * If the limit (infinite or not) is higher than you're willing to return,
1219
+     * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
1220
+     *
1221
+     * If the syncToken is expired (due to data cleanup) or unknown, you must
1222
+     * return null.
1223
+     *
1224
+     * The limit is 'suggestive'. You are free to ignore it.
1225
+     *
1226
+     * @param string $calendarId
1227
+     * @param string $syncToken
1228
+     * @param int $syncLevel
1229
+     * @param int $limit
1230
+     * @return array
1231
+     */
1232
+    function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null) {
1233
+        // Current synctoken
1234
+        $stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*calendars` WHERE `id` = ?');
1235
+        $stmt->execute([ $calendarId ]);
1236
+        $currentToken = $stmt->fetchColumn(0);
1237
+
1238
+        if (is_null($currentToken)) {
1239
+            return null;
1240
+        }
1241
+
1242
+        $result = [
1243
+            'syncToken' => $currentToken,
1244
+            'added'     => [],
1245
+            'modified'  => [],
1246
+            'deleted'   => [],
1247
+        ];
1248
+
1249
+        if ($syncToken) {
1250
+
1251
+            $query = "SELECT `uri`, `operation` FROM `*PREFIX*calendarchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `calendarid` = ? ORDER BY `synctoken`";
1252
+            if ($limit>0) {
1253
+                $query.= " `LIMIT` " . (int)$limit;
1254
+            }
1255
+
1256
+            // Fetching all changes
1257
+            $stmt = $this->db->prepare($query);
1258
+            $stmt->execute([$syncToken, $currentToken, $calendarId]);
1259
+
1260
+            $changes = [];
1261
+
1262
+            // This loop ensures that any duplicates are overwritten, only the
1263
+            // last change on a node is relevant.
1264
+            while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1265
+
1266
+                $changes[$row['uri']] = $row['operation'];
1267
+
1268
+            }
1269
+
1270
+            foreach($changes as $uri => $operation) {
1271
+
1272
+                switch($operation) {
1273
+                    case 1 :
1274
+                        $result['added'][] = $uri;
1275
+                        break;
1276
+                    case 2 :
1277
+                        $result['modified'][] = $uri;
1278
+                        break;
1279
+                    case 3 :
1280
+                        $result['deleted'][] = $uri;
1281
+                        break;
1282
+                }
1283
+
1284
+            }
1285
+        } else {
1286
+            // No synctoken supplied, this is the initial sync.
1287
+            $query = "SELECT `uri` FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ?";
1288
+            $stmt = $this->db->prepare($query);
1289
+            $stmt->execute([$calendarId]);
1290
+
1291
+            $result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
1292
+        }
1293
+        return $result;
1294
+
1295
+    }
1296
+
1297
+    /**
1298
+     * Returns a list of subscriptions for a principal.
1299
+     *
1300
+     * Every subscription is an array with the following keys:
1301
+     *  * id, a unique id that will be used by other functions to modify the
1302
+     *    subscription. This can be the same as the uri or a database key.
1303
+     *  * uri. This is just the 'base uri' or 'filename' of the subscription.
1304
+     *  * principaluri. The owner of the subscription. Almost always the same as
1305
+     *    principalUri passed to this method.
1306
+     *
1307
+     * Furthermore, all the subscription info must be returned too:
1308
+     *
1309
+     * 1. {DAV:}displayname
1310
+     * 2. {http://apple.com/ns/ical/}refreshrate
1311
+     * 3. {http://calendarserver.org/ns/}subscribed-strip-todos (omit if todos
1312
+     *    should not be stripped).
1313
+     * 4. {http://calendarserver.org/ns/}subscribed-strip-alarms (omit if alarms
1314
+     *    should not be stripped).
1315
+     * 5. {http://calendarserver.org/ns/}subscribed-strip-attachments (omit if
1316
+     *    attachments should not be stripped).
1317
+     * 6. {http://calendarserver.org/ns/}source (Must be a
1318
+     *     Sabre\DAV\Property\Href).
1319
+     * 7. {http://apple.com/ns/ical/}calendar-color
1320
+     * 8. {http://apple.com/ns/ical/}calendar-order
1321
+     * 9. {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
1322
+     *    (should just be an instance of
1323
+     *    Sabre\CalDAV\Property\SupportedCalendarComponentSet, with a bunch of
1324
+     *    default components).
1325
+     *
1326
+     * @param string $principalUri
1327
+     * @return array
1328
+     */
1329
+    function getSubscriptionsForUser($principalUri) {
1330
+        $fields = array_values($this->subscriptionPropertyMap);
1331
+        $fields[] = 'id';
1332
+        $fields[] = 'uri';
1333
+        $fields[] = 'source';
1334
+        $fields[] = 'principaluri';
1335
+        $fields[] = 'lastmodified';
1336
+
1337
+        $query = $this->db->getQueryBuilder();
1338
+        $query->select($fields)
1339
+            ->from('calendarsubscriptions')
1340
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1341
+            ->orderBy('calendarorder', 'asc');
1342
+        $stmt =$query->execute();
1343
+
1344
+        $subscriptions = [];
1345
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1346
+
1347
+            $subscription = [
1348
+                'id'           => $row['id'],
1349
+                'uri'          => $row['uri'],
1350
+                'principaluri' => $row['principaluri'],
1351
+                'source'       => $row['source'],
1352
+                'lastmodified' => $row['lastmodified'],
1353
+
1354
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
1355
+            ];
1356
+
1357
+            foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1358
+                if (!is_null($row[$dbName])) {
1359
+                    $subscription[$xmlName] = $row[$dbName];
1360
+                }
1361
+            }
1362
+
1363
+            $subscriptions[] = $subscription;
1364
+
1365
+        }
1366
+
1367
+        return $subscriptions;
1368
+    }
1369
+
1370
+    /**
1371
+     * Creates a new subscription for a principal.
1372
+     *
1373
+     * If the creation was a success, an id must be returned that can be used to reference
1374
+     * this subscription in other methods, such as updateSubscription.
1375
+     *
1376
+     * @param string $principalUri
1377
+     * @param string $uri
1378
+     * @param array $properties
1379
+     * @return mixed
1380
+     */
1381
+    function createSubscription($principalUri, $uri, array $properties) {
1382
+
1383
+        if (!isset($properties['{http://calendarserver.org/ns/}source'])) {
1384
+            throw new Forbidden('The {http://calendarserver.org/ns/}source property is required when creating subscriptions');
1385
+        }
1386
+
1387
+        $values = [
1388
+            'principaluri' => $principalUri,
1389
+            'uri'          => $uri,
1390
+            'source'       => $properties['{http://calendarserver.org/ns/}source']->getHref(),
1391
+            'lastmodified' => time(),
1392
+        ];
1393
+
1394
+        $propertiesBoolean = ['striptodos', 'stripalarms', 'stripattachments'];
1395
+
1396
+        foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1397
+            if (array_key_exists($xmlName, $properties)) {
1398
+                    $values[$dbName] = $properties[$xmlName];
1399
+                    if (in_array($dbName, $propertiesBoolean)) {
1400
+                        $values[$dbName] = true;
1401
+                }
1402
+            }
1403
+        }
1404
+
1405
+        $valuesToInsert = array();
1406
+
1407
+        $query = $this->db->getQueryBuilder();
1408
+
1409
+        foreach (array_keys($values) as $name) {
1410
+            $valuesToInsert[$name] = $query->createNamedParameter($values[$name]);
1411
+        }
1412
+
1413
+        $query->insert('calendarsubscriptions')
1414
+            ->values($valuesToInsert)
1415
+            ->execute();
1416
+
1417
+        return $this->db->lastInsertId('*PREFIX*calendarsubscriptions');
1418
+    }
1419
+
1420
+    /**
1421
+     * Updates a subscription
1422
+     *
1423
+     * The list of mutations is stored in a Sabre\DAV\PropPatch object.
1424
+     * To do the actual updates, you must tell this object which properties
1425
+     * you're going to process with the handle() method.
1426
+     *
1427
+     * Calling the handle method is like telling the PropPatch object "I
1428
+     * promise I can handle updating this property".
1429
+     *
1430
+     * Read the PropPatch documentation for more info and examples.
1431
+     *
1432
+     * @param mixed $subscriptionId
1433
+     * @param PropPatch $propPatch
1434
+     * @return void
1435
+     */
1436
+    function updateSubscription($subscriptionId, PropPatch $propPatch) {
1437
+        $supportedProperties = array_keys($this->subscriptionPropertyMap);
1438
+        $supportedProperties[] = '{http://calendarserver.org/ns/}source';
1439
+
1440
+        $propPatch->handle($supportedProperties, function($mutations) use ($subscriptionId) {
1441
+
1442
+            $newValues = [];
1443
+
1444
+            foreach($mutations as $propertyName=>$propertyValue) {
1445
+                if ($propertyName === '{http://calendarserver.org/ns/}source') {
1446
+                    $newValues['source'] = $propertyValue->getHref();
1447
+                } else {
1448
+                    $fieldName = $this->subscriptionPropertyMap[$propertyName];
1449
+                    $newValues[$fieldName] = $propertyValue;
1450
+                }
1451
+            }
1452
+
1453
+            $query = $this->db->getQueryBuilder();
1454
+            $query->update('calendarsubscriptions')
1455
+                ->set('lastmodified', $query->createNamedParameter(time()));
1456
+            foreach($newValues as $fieldName=>$value) {
1457
+                $query->set($fieldName, $query->createNamedParameter($value));
1458
+            }
1459
+            $query->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
1460
+                ->execute();
1461
+
1462
+            return true;
1463
+
1464
+        });
1465
+    }
1466
+
1467
+    /**
1468
+     * Deletes a subscription.
1469
+     *
1470
+     * @param mixed $subscriptionId
1471
+     * @return void
1472
+     */
1473
+    function deleteSubscription($subscriptionId) {
1474
+        $query = $this->db->getQueryBuilder();
1475
+        $query->delete('calendarsubscriptions')
1476
+            ->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
1477
+            ->execute();
1478
+    }
1479
+
1480
+    /**
1481
+     * Returns a single scheduling object for the inbox collection.
1482
+     *
1483
+     * The returned array should contain the following elements:
1484
+     *   * uri - A unique basename for the object. This will be used to
1485
+     *           construct a full uri.
1486
+     *   * calendardata - The iCalendar object
1487
+     *   * lastmodified - The last modification date. Can be an int for a unix
1488
+     *                    timestamp, or a PHP DateTime object.
1489
+     *   * etag - A unique token that must change if the object changed.
1490
+     *   * size - The size of the object, in bytes.
1491
+     *
1492
+     * @param string $principalUri
1493
+     * @param string $objectUri
1494
+     * @return array
1495
+     */
1496
+    function getSchedulingObject($principalUri, $objectUri) {
1497
+        $query = $this->db->getQueryBuilder();
1498
+        $stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
1499
+            ->from('schedulingobjects')
1500
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1501
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1502
+            ->execute();
1503
+
1504
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
1505
+
1506
+        if(!$row) {
1507
+            return null;
1508
+        }
1509
+
1510
+        return [
1511
+                'uri'          => $row['uri'],
1512
+                'calendardata' => $row['calendardata'],
1513
+                'lastmodified' => $row['lastmodified'],
1514
+                'etag'         => '"' . $row['etag'] . '"',
1515
+                'size'         => (int)$row['size'],
1516
+        ];
1517
+    }
1518
+
1519
+    /**
1520
+     * Returns all scheduling objects for the inbox collection.
1521
+     *
1522
+     * These objects should be returned as an array. Every item in the array
1523
+     * should follow the same structure as returned from getSchedulingObject.
1524
+     *
1525
+     * The main difference is that 'calendardata' is optional.
1526
+     *
1527
+     * @param string $principalUri
1528
+     * @return array
1529
+     */
1530
+    function getSchedulingObjects($principalUri) {
1531
+        $query = $this->db->getQueryBuilder();
1532
+        $stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
1533
+                ->from('schedulingobjects')
1534
+                ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1535
+                ->execute();
1536
+
1537
+        $result = [];
1538
+        foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
1539
+            $result[] = [
1540
+                    'calendardata' => $row['calendardata'],
1541
+                    'uri'          => $row['uri'],
1542
+                    'lastmodified' => $row['lastmodified'],
1543
+                    'etag'         => '"' . $row['etag'] . '"',
1544
+                    'size'         => (int)$row['size'],
1545
+            ];
1546
+        }
1547
+
1548
+        return $result;
1549
+    }
1550
+
1551
+    /**
1552
+     * Deletes a scheduling object from the inbox collection.
1553
+     *
1554
+     * @param string $principalUri
1555
+     * @param string $objectUri
1556
+     * @return void
1557
+     */
1558
+    function deleteSchedulingObject($principalUri, $objectUri) {
1559
+        $query = $this->db->getQueryBuilder();
1560
+        $query->delete('schedulingobjects')
1561
+                ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1562
+                ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1563
+                ->execute();
1564
+    }
1565
+
1566
+    /**
1567
+     * Creates a new scheduling object. This should land in a users' inbox.
1568
+     *
1569
+     * @param string $principalUri
1570
+     * @param string $objectUri
1571
+     * @param string $objectData
1572
+     * @return void
1573
+     */
1574
+    function createSchedulingObject($principalUri, $objectUri, $objectData) {
1575
+        $query = $this->db->getQueryBuilder();
1576
+        $query->insert('schedulingobjects')
1577
+            ->values([
1578
+                'principaluri' => $query->createNamedParameter($principalUri),
1579
+                'calendardata' => $query->createNamedParameter($objectData),
1580
+                'uri' => $query->createNamedParameter($objectUri),
1581
+                'lastmodified' => $query->createNamedParameter(time()),
1582
+                'etag' => $query->createNamedParameter(md5($objectData)),
1583
+                'size' => $query->createNamedParameter(strlen($objectData))
1584
+            ])
1585
+            ->execute();
1586
+    }
1587
+
1588
+    /**
1589
+     * Adds a change record to the calendarchanges table.
1590
+     *
1591
+     * @param mixed $calendarId
1592
+     * @param string $objectUri
1593
+     * @param int $operation 1 = add, 2 = modify, 3 = delete.
1594
+     * @return void
1595
+     */
1596
+    protected function addChange($calendarId, $objectUri, $operation) {
1597
+
1598
+        $stmt = $this->db->prepare('INSERT INTO `*PREFIX*calendarchanges` (`uri`, `synctoken`, `calendarid`, `operation`) SELECT ?, `synctoken`, ?, ? FROM `*PREFIX*calendars` WHERE `id` = ?');
1599
+        $stmt->execute([
1600
+            $objectUri,
1601
+            $calendarId,
1602
+            $operation,
1603
+            $calendarId
1604
+        ]);
1605
+        $stmt = $this->db->prepare('UPDATE `*PREFIX*calendars` SET `synctoken` = `synctoken` + 1 WHERE `id` = ?');
1606
+        $stmt->execute([
1607
+            $calendarId
1608
+        ]);
1609
+
1610
+    }
1611
+
1612
+    /**
1613
+     * Parses some information from calendar objects, used for optimized
1614
+     * calendar-queries.
1615
+     *
1616
+     * Returns an array with the following keys:
1617
+     *   * etag - An md5 checksum of the object without the quotes.
1618
+     *   * size - Size of the object in bytes
1619
+     *   * componentType - VEVENT, VTODO or VJOURNAL
1620
+     *   * firstOccurence
1621
+     *   * lastOccurence
1622
+     *   * uid - value of the UID property
1623
+     *
1624
+     * @param string $calendarData
1625
+     * @return array
1626
+     */
1627
+    public function getDenormalizedData($calendarData) {
1628
+
1629
+        $vObject = Reader::read($calendarData);
1630
+        $componentType = null;
1631
+        $component = null;
1632
+        $firstOccurrence = null;
1633
+        $lastOccurrence = null;
1634
+        $uid = null;
1635
+        $classification = self::CLASSIFICATION_PUBLIC;
1636
+        foreach($vObject->getComponents() as $component) {
1637
+            if ($component->name!=='VTIMEZONE') {
1638
+                $componentType = $component->name;
1639
+                $uid = (string)$component->UID;
1640
+                break;
1641
+            }
1642
+        }
1643
+        if (!$componentType) {
1644
+            throw new \Sabre\DAV\Exception\BadRequest('Calendar objects must have a VJOURNAL, VEVENT or VTODO component');
1645
+        }
1646
+        if ($componentType === 'VEVENT' && $component->DTSTART) {
1647
+            $firstOccurrence = $component->DTSTART->getDateTime()->getTimeStamp();
1648
+            // Finding the last occurrence is a bit harder
1649
+            if (!isset($component->RRULE)) {
1650
+                if (isset($component->DTEND)) {
1651
+                    $lastOccurrence = $component->DTEND->getDateTime()->getTimeStamp();
1652
+                } elseif (isset($component->DURATION)) {
1653
+                    $endDate = clone $component->DTSTART->getDateTime();
1654
+                    $endDate->add(DateTimeParser::parse($component->DURATION->getValue()));
1655
+                    $lastOccurrence = $endDate->getTimeStamp();
1656
+                } elseif (!$component->DTSTART->hasTime()) {
1657
+                    $endDate = clone $component->DTSTART->getDateTime();
1658
+                    $endDate->modify('+1 day');
1659
+                    $lastOccurrence = $endDate->getTimeStamp();
1660
+                } else {
1661
+                    $lastOccurrence = $firstOccurrence;
1662
+                }
1663
+            } else {
1664
+                $it = new EventIterator($vObject, (string)$component->UID);
1665
+                $maxDate = new \DateTime(self::MAX_DATE);
1666
+                if ($it->isInfinite()) {
1667
+                    $lastOccurrence = $maxDate->getTimestamp();
1668
+                } else {
1669
+                    $end = $it->getDtEnd();
1670
+                    while($it->valid() && $end < $maxDate) {
1671
+                        $end = $it->getDtEnd();
1672
+                        $it->next();
1673
+
1674
+                    }
1675
+                    $lastOccurrence = $end->getTimestamp();
1676
+                }
1677
+
1678
+            }
1679
+        }
1680
+
1681
+        if ($component->CLASS) {
1682
+            $classification = CalDavBackend::CLASSIFICATION_PRIVATE;
1683
+            switch ($component->CLASS->getValue()) {
1684
+                case 'PUBLIC':
1685
+                    $classification = CalDavBackend::CLASSIFICATION_PUBLIC;
1686
+                    break;
1687
+                case 'CONFIDENTIAL':
1688
+                    $classification = CalDavBackend::CLASSIFICATION_CONFIDENTIAL;
1689
+                    break;
1690
+            }
1691
+        }
1692
+        return [
1693
+            'etag' => md5($calendarData),
1694
+            'size' => strlen($calendarData),
1695
+            'componentType' => $componentType,
1696
+            'firstOccurence' => is_null($firstOccurrence) ? null : max(0, $firstOccurrence),
1697
+            'lastOccurence'  => $lastOccurrence,
1698
+            'uid' => $uid,
1699
+            'classification' => $classification
1700
+        ];
1701
+
1702
+    }
1703
+
1704
+    private function readBlob($cardData) {
1705
+        if (is_resource($cardData)) {
1706
+            return stream_get_contents($cardData);
1707
+        }
1708
+
1709
+        return $cardData;
1710
+    }
1711
+
1712
+    /**
1713
+     * @param IShareable $shareable
1714
+     * @param array $add
1715
+     * @param array $remove
1716
+     */
1717
+    public function updateShares($shareable, $add, $remove) {
1718
+        $calendarId = $shareable->getResourceId();
1719
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateShares', new GenericEvent(
1720
+            '\OCA\DAV\CalDAV\CalDavBackend::updateShares',
1721
+            [
1722
+                'calendarId' => $calendarId,
1723
+                'calendarData' => $this->getCalendarById($calendarId),
1724
+                'shares' => $this->getShares($calendarId),
1725
+                'add' => $add,
1726
+                'remove' => $remove,
1727
+            ]));
1728
+        $this->sharingBackend->updateShares($shareable, $add, $remove);
1729
+    }
1730
+
1731
+    /**
1732
+     * @param int $resourceId
1733
+     * @return array
1734
+     */
1735
+    public function getShares($resourceId) {
1736
+        return $this->sharingBackend->getShares($resourceId);
1737
+    }
1738
+
1739
+    /**
1740
+     * @param boolean $value
1741
+     * @param \OCA\DAV\CalDAV\Calendar $calendar
1742
+     * @return string|null
1743
+     */
1744
+    public function setPublishStatus($value, $calendar) {
1745
+        $query = $this->db->getQueryBuilder();
1746
+        if ($value) {
1747
+            $publicUri = $this->random->generate(16, ISecureRandom::CHAR_UPPER.ISecureRandom::CHAR_DIGITS);
1748
+            $query->insert('dav_shares')
1749
+                ->values([
1750
+                    'principaluri' => $query->createNamedParameter($calendar->getPrincipalURI()),
1751
+                    'type' => $query->createNamedParameter('calendar'),
1752
+                    'access' => $query->createNamedParameter(self::ACCESS_PUBLIC),
1753
+                    'resourceid' => $query->createNamedParameter($calendar->getResourceId()),
1754
+                    'publicuri' => $query->createNamedParameter($publicUri)
1755
+                ]);
1756
+            $query->execute();
1757
+            return $publicUri;
1758
+        }
1759
+        $query->delete('dav_shares')
1760
+            ->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
1761
+            ->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)));
1762
+        $query->execute();
1763
+        return null;
1764
+    }
1765
+
1766
+    /**
1767
+     * @param \OCA\DAV\CalDAV\Calendar $calendar
1768
+     * @return mixed
1769
+     */
1770
+    public function getPublishStatus($calendar) {
1771
+        $query = $this->db->getQueryBuilder();
1772
+        $result = $query->select('publicuri')
1773
+            ->from('dav_shares')
1774
+            ->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
1775
+            ->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
1776
+            ->execute();
1777
+
1778
+        $row = $result->fetch();
1779
+        $result->closeCursor();
1780
+        return $row ? reset($row) : false;
1781
+    }
1782
+
1783
+    /**
1784
+     * @param int $resourceId
1785
+     * @param array $acl
1786
+     * @return array
1787
+     */
1788
+    public function applyShareAcl($resourceId, $acl) {
1789
+        return $this->sharingBackend->applyShareAcl($resourceId, $acl);
1790
+    }
1791
+
1792
+    private function convertPrincipal($principalUri, $toV2) {
1793
+        if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
1794
+            list(, $name) = URLUtil::splitPath($principalUri);
1795
+            if ($toV2 === true) {
1796
+                return "principals/users/$name";
1797
+            }
1798
+            return "principals/$name";
1799
+        }
1800
+        return $principalUri;
1801
+    }
1802 1802
 }
Please login to merge, or discard this patch.
Spacing   +109 added lines, -109 removed lines patch added patch discarded remove patch
@@ -179,7 +179,7 @@  discard block
 block discarded – undo
179 179
 			$query->andWhere($query->expr()->neq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)));
180 180
 		}
181 181
 
182
-		return (int)$query->execute()->fetchColumn();
182
+		return (int) $query->execute()->fetchColumn();
183 183
 	}
184 184
 
185 185
 	/**
@@ -226,25 +226,25 @@  discard block
 block discarded – undo
226 226
 		$stmt = $query->execute();
227 227
 
228 228
 		$calendars = [];
229
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
229
+		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
230 230
 
231 231
 			$components = [];
232 232
 			if ($row['components']) {
233
-				$components = explode(',',$row['components']);
233
+				$components = explode(',', $row['components']);
234 234
 			}
235 235
 
236 236
 			$calendar = [
237 237
 				'id' => $row['id'],
238 238
 				'uri' => $row['uri'],
239 239
 				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
240
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
241
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
242
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
243
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
244
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
240
+				'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
241
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
242
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
243
+				'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
244
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
245 245
 			];
246 246
 
247
-			foreach($this->propertyMap as $xmlName=>$dbName) {
247
+			foreach ($this->propertyMap as $xmlName=>$dbName) {
248 248
 				$calendar[$xmlName] = $row[$dbName];
249 249
 			}
250 250
 
@@ -257,7 +257,7 @@  discard block
 block discarded – undo
257 257
 
258 258
 		// query for shared calendars
259 259
 		$principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
260
-		$principals[]= $principalUri;
260
+		$principals[] = $principalUri;
261 261
 
262 262
 		$fields = array_values($this->propertyMap);
263 263
 		$fields[] = 'a.id';
@@ -277,27 +277,27 @@  discard block
 block discarded – undo
277 277
 			->setParameter('principaluri', $principals, \Doctrine\DBAL\Connection::PARAM_STR_ARRAY)
278 278
 			->execute();
279 279
 
280
-		while($row = $result->fetch()) {
280
+		while ($row = $result->fetch()) {
281 281
 			list(, $name) = URLUtil::splitPath($row['principaluri']);
282
-			$uri = $row['uri'] . '_shared_by_' . $name;
283
-			$row['displayname'] = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
282
+			$uri = $row['uri'].'_shared_by_'.$name;
283
+			$row['displayname'] = $row['displayname'].' ('.$this->getUserDisplayName($name).')';
284 284
 			$components = [];
285 285
 			if ($row['components']) {
286
-				$components = explode(',',$row['components']);
286
+				$components = explode(',', $row['components']);
287 287
 			}
288 288
 			$calendar = [
289 289
 				'id' => $row['id'],
290 290
 				'uri' => $uri,
291 291
 				'principaluri' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
292
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
293
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
294
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
295
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
296
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
297
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
292
+				'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
293
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
294
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
295
+				'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
296
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
297
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}read-only' => (int) $row['access'] === Backend::ACCESS_READ,
298 298
 			];
299 299
 
300
-			foreach($this->propertyMap as $xmlName=>$dbName) {
300
+			foreach ($this->propertyMap as $xmlName=>$dbName) {
301 301
 				$calendar[$xmlName] = $row[$dbName];
302 302
 			}
303 303
 
@@ -326,21 +326,21 @@  discard block
 block discarded – undo
326 326
 			->orderBy('calendarorder', 'ASC');
327 327
 		$stmt = $query->execute();
328 328
 		$calendars = [];
329
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
329
+		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
330 330
 			$components = [];
331 331
 			if ($row['components']) {
332
-				$components = explode(',',$row['components']);
332
+				$components = explode(',', $row['components']);
333 333
 			}
334 334
 			$calendar = [
335 335
 				'id' => $row['id'],
336 336
 				'uri' => $row['uri'],
337 337
 				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
338
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
339
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
340
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
341
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
338
+				'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
339
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
340
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
341
+				'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
342 342
 			];
343
-			foreach($this->propertyMap as $xmlName=>$dbName) {
343
+			foreach ($this->propertyMap as $xmlName=>$dbName) {
344 344
 				$calendar[$xmlName] = $row[$dbName];
345 345
 			}
346 346
 			if (!isset($calendars[$calendar['id']])) {
@@ -388,27 +388,27 @@  discard block
 block discarded – undo
388 388
 			->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
389 389
 			->execute();
390 390
 
391
-		while($row = $result->fetch()) {
391
+		while ($row = $result->fetch()) {
392 392
 			list(, $name) = URLUtil::splitPath($row['principaluri']);
393
-			$row['displayname'] = $row['displayname'] . "($name)";
393
+			$row['displayname'] = $row['displayname']."($name)";
394 394
 			$components = [];
395 395
 			if ($row['components']) {
396
-				$components = explode(',',$row['components']);
396
+				$components = explode(',', $row['components']);
397 397
 			}
398 398
 			$calendar = [
399 399
 				'id' => $row['id'],
400 400
 				'uri' => $row['publicuri'],
401 401
 				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
402
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
403
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
404
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
405
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
406
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
407
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
408
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
402
+				'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
403
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
404
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
405
+				'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
406
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
407
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}read-only' => (int) $row['access'] === Backend::ACCESS_READ,
408
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}public' => (int) $row['access'] === self::ACCESS_PUBLIC,
409 409
 			];
410 410
 
411
-			foreach($this->propertyMap as $xmlName=>$dbName) {
411
+			foreach ($this->propertyMap as $xmlName=>$dbName) {
412 412
 				$calendar[$xmlName] = $row[$dbName];
413 413
 			}
414 414
 
@@ -450,29 +450,29 @@  discard block
 block discarded – undo
450 450
 		$result->closeCursor();
451 451
 
452 452
 		if ($row === false) {
453
-			throw new NotFound('Node with name \'' . $uri . '\' could not be found');
453
+			throw new NotFound('Node with name \''.$uri.'\' could not be found');
454 454
 		}
455 455
 
456 456
 		list(, $name) = URLUtil::splitPath($row['principaluri']);
457
-		$row['displayname'] = $row['displayname'] . ' ' . "($name)";
457
+		$row['displayname'] = $row['displayname'].' '."($name)";
458 458
 		$components = [];
459 459
 		if ($row['components']) {
460
-			$components = explode(',',$row['components']);
460
+			$components = explode(',', $row['components']);
461 461
 		}
462 462
 		$calendar = [
463 463
 			'id' => $row['id'],
464 464
 			'uri' => $row['publicuri'],
465 465
 			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
466
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
467
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
468
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
469
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
470
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
471
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
472
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
466
+			'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
467
+			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
468
+			'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
469
+			'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
470
+			'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
471
+			'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}read-only' => (int) $row['access'] === Backend::ACCESS_READ,
472
+			'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}public' => (int) $row['access'] === self::ACCESS_PUBLIC,
473 473
 		];
474 474
 
475
-		foreach($this->propertyMap as $xmlName=>$dbName) {
475
+		foreach ($this->propertyMap as $xmlName=>$dbName) {
476 476
 			$calendar[$xmlName] = $row[$dbName];
477 477
 		}
478 478
 
@@ -510,20 +510,20 @@  discard block
 block discarded – undo
510 510
 
511 511
 		$components = [];
512 512
 		if ($row['components']) {
513
-			$components = explode(',',$row['components']);
513
+			$components = explode(',', $row['components']);
514 514
 		}
515 515
 
516 516
 		$calendar = [
517 517
 			'id' => $row['id'],
518 518
 			'uri' => $row['uri'],
519 519
 			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
520
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
521
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
522
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
523
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
520
+			'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
521
+			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
522
+			'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
523
+			'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
524 524
 		];
525 525
 
526
-		foreach($this->propertyMap as $xmlName=>$dbName) {
526
+		foreach ($this->propertyMap as $xmlName=>$dbName) {
527 527
 			$calendar[$xmlName] = $row[$dbName];
528 528
 		}
529 529
 
@@ -554,20 +554,20 @@  discard block
 block discarded – undo
554 554
 
555 555
 		$components = [];
556 556
 		if ($row['components']) {
557
-			$components = explode(',',$row['components']);
557
+			$components = explode(',', $row['components']);
558 558
 		}
559 559
 
560 560
 		$calendar = [
561 561
 			'id' => $row['id'],
562 562
 			'uri' => $row['uri'],
563 563
 			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
564
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
565
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
566
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
567
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
564
+			'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
565
+			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
566
+			'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
567
+			'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
568 568
 		];
569 569
 
570
-		foreach($this->propertyMap as $xmlName=>$dbName) {
570
+		foreach ($this->propertyMap as $xmlName=>$dbName) {
571 571
 			$calendar[$xmlName] = $row[$dbName];
572 572
 		}
573 573
 
@@ -599,16 +599,16 @@  discard block
 block discarded – undo
599 599
 		$sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
600 600
 		if (isset($properties[$sccs])) {
601 601
 			if (!($properties[$sccs] instanceof SupportedCalendarComponentSet)) {
602
-				throw new DAV\Exception('The ' . $sccs . ' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
602
+				throw new DAV\Exception('The '.$sccs.' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
603 603
 			}
604
-			$values['components'] = implode(',',$properties[$sccs]->getValue());
604
+			$values['components'] = implode(',', $properties[$sccs]->getValue());
605 605
 		}
606
-		$transp = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
606
+		$transp = '{'.Plugin::NS_CALDAV.'}schedule-calendar-transp';
607 607
 		if (isset($properties[$transp])) {
608
-			$values['transparent'] = $properties[$transp]->getValue()==='transparent';
608
+			$values['transparent'] = $properties[$transp]->getValue() === 'transparent';
609 609
 		}
610 610
 
611
-		foreach($this->propertyMap as $xmlName=>$dbName) {
611
+		foreach ($this->propertyMap as $xmlName=>$dbName) {
612 612
 			if (isset($properties[$xmlName])) {
613 613
 				$values[$dbName] = $properties[$xmlName];
614 614
 			}
@@ -616,7 +616,7 @@  discard block
 block discarded – undo
616 616
 
617 617
 		$query = $this->db->getQueryBuilder();
618 618
 		$query->insert('calendars');
619
-		foreach($values as $column => $value) {
619
+		foreach ($values as $column => $value) {
620 620
 			$query->setValue($column, $query->createNamedParameter($value));
621 621
 		}
622 622
 		$query->execute();
@@ -649,14 +649,14 @@  discard block
 block discarded – undo
649 649
 	 */
650 650
 	function updateCalendar($calendarId, PropPatch $propPatch) {
651 651
 		$supportedProperties = array_keys($this->propertyMap);
652
-		$supportedProperties[] = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
652
+		$supportedProperties[] = '{'.Plugin::NS_CALDAV.'}schedule-calendar-transp';
653 653
 
654 654
 		$propPatch->handle($supportedProperties, function($mutations) use ($calendarId) {
655 655
 			$newValues = [];
656 656
 			foreach ($mutations as $propertyName => $propertyValue) {
657 657
 
658 658
 				switch ($propertyName) {
659
-					case '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' :
659
+					case '{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' :
660 660
 						$fieldName = 'transparent';
661 661
 						$newValues[$fieldName] = $propertyValue->getValue() === 'transparent';
662 662
 						break;
@@ -766,16 +766,16 @@  discard block
 block discarded – undo
766 766
 		$stmt = $query->execute();
767 767
 
768 768
 		$result = [];
769
-		foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
769
+		foreach ($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
770 770
 			$result[] = [
771 771
 					'id'           => $row['id'],
772 772
 					'uri'          => $row['uri'],
773 773
 					'lastmodified' => $row['lastmodified'],
774
-					'etag'         => '"' . $row['etag'] . '"',
774
+					'etag'         => '"'.$row['etag'].'"',
775 775
 					'calendarid'   => $row['calendarid'],
776
-					'size'         => (int)$row['size'],
776
+					'size'         => (int) $row['size'],
777 777
 					'component'    => strtolower($row['componenttype']),
778
-					'classification'=> (int)$row['classification']
778
+					'classification'=> (int) $row['classification']
779 779
 			];
780 780
 		}
781 781
 
@@ -808,18 +808,18 @@  discard block
 block discarded – undo
808 808
 		$stmt = $query->execute();
809 809
 		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
810 810
 
811
-		if(!$row) return null;
811
+		if (!$row) return null;
812 812
 
813 813
 		return [
814 814
 				'id'            => $row['id'],
815 815
 				'uri'           => $row['uri'],
816 816
 				'lastmodified'  => $row['lastmodified'],
817
-				'etag'          => '"' . $row['etag'] . '"',
817
+				'etag'          => '"'.$row['etag'].'"',
818 818
 				'calendarid'    => $row['calendarid'],
819
-				'size'          => (int)$row['size'],
819
+				'size'          => (int) $row['size'],
820 820
 				'calendardata'  => $this->readBlob($row['calendardata']),
821 821
 				'component'     => strtolower($row['componenttype']),
822
-				'classification'=> (int)$row['classification']
822
+				'classification'=> (int) $row['classification']
823 823
 		];
824 824
 	}
825 825
 
@@ -858,12 +858,12 @@  discard block
 block discarded – undo
858 858
 					'id'           => $row['id'],
859 859
 					'uri'          => $row['uri'],
860 860
 					'lastmodified' => $row['lastmodified'],
861
-					'etag'         => '"' . $row['etag'] . '"',
861
+					'etag'         => '"'.$row['etag'].'"',
862 862
 					'calendarid'   => $row['calendarid'],
863
-					'size'         => (int)$row['size'],
863
+					'size'         => (int) $row['size'],
864 864
 					'calendardata' => $this->readBlob($row['calendardata']),
865 865
 					'component'    => strtolower($row['componenttype']),
866
-					'classification' => (int)$row['classification']
866
+					'classification' => (int) $row['classification']
867 867
 				];
868 868
 			}
869 869
 			$result->closeCursor();
@@ -920,7 +920,7 @@  discard block
 block discarded – undo
920 920
 		));
921 921
 		$this->addChange($calendarId, $objectUri, 1);
922 922
 
923
-		return '"' . $extraData['etag'] . '"';
923
+		return '"'.$extraData['etag'].'"';
924 924
 	}
925 925
 
926 926
 	/**
@@ -973,7 +973,7 @@  discard block
 block discarded – undo
973 973
 		}
974 974
 		$this->addChange($calendarId, $objectUri, 2);
975 975
 
976
-		return '"' . $extraData['etag'] . '"';
976
+		return '"'.$extraData['etag'].'"';
977 977
 	}
978 978
 
979 979
 	/**
@@ -1124,7 +1124,7 @@  discard block
 block discarded – undo
1124 1124
 		$stmt = $query->execute();
1125 1125
 
1126 1126
 		$result = [];
1127
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1127
+		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1128 1128
 			if ($requirePostFilter) {
1129 1129
 				if (!$this->validateFilterForObject($row, $filters)) {
1130 1130
 					continue;
@@ -1167,7 +1167,7 @@  discard block
 block discarded – undo
1167 1167
 		$stmt = $query->execute();
1168 1168
 
1169 1169
 		if ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1170
-			return $row['calendaruri'] . '/' . $row['objecturi'];
1170
+			return $row['calendaruri'].'/'.$row['objecturi'];
1171 1171
 		}
1172 1172
 
1173 1173
 		return null;
@@ -1232,7 +1232,7 @@  discard block
 block discarded – undo
1232 1232
 	function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null) {
1233 1233
 		// Current synctoken
1234 1234
 		$stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*calendars` WHERE `id` = ?');
1235
-		$stmt->execute([ $calendarId ]);
1235
+		$stmt->execute([$calendarId]);
1236 1236
 		$currentToken = $stmt->fetchColumn(0);
1237 1237
 
1238 1238
 		if (is_null($currentToken)) {
@@ -1249,8 +1249,8 @@  discard block
 block discarded – undo
1249 1249
 		if ($syncToken) {
1250 1250
 
1251 1251
 			$query = "SELECT `uri`, `operation` FROM `*PREFIX*calendarchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `calendarid` = ? ORDER BY `synctoken`";
1252
-			if ($limit>0) {
1253
-				$query.= " `LIMIT` " . (int)$limit;
1252
+			if ($limit > 0) {
1253
+				$query .= " `LIMIT` ".(int) $limit;
1254 1254
 			}
1255 1255
 
1256 1256
 			// Fetching all changes
@@ -1261,15 +1261,15 @@  discard block
 block discarded – undo
1261 1261
 
1262 1262
 			// This loop ensures that any duplicates are overwritten, only the
1263 1263
 			// last change on a node is relevant.
1264
-			while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1264
+			while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1265 1265
 
1266 1266
 				$changes[$row['uri']] = $row['operation'];
1267 1267
 
1268 1268
 			}
1269 1269
 
1270
-			foreach($changes as $uri => $operation) {
1270
+			foreach ($changes as $uri => $operation) {
1271 1271
 
1272
-				switch($operation) {
1272
+				switch ($operation) {
1273 1273
 					case 1 :
1274 1274
 						$result['added'][] = $uri;
1275 1275
 						break;
@@ -1339,10 +1339,10 @@  discard block
 block discarded – undo
1339 1339
 			->from('calendarsubscriptions')
1340 1340
 			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1341 1341
 			->orderBy('calendarorder', 'asc');
1342
-		$stmt =$query->execute();
1342
+		$stmt = $query->execute();
1343 1343
 
1344 1344
 		$subscriptions = [];
1345
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1345
+		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1346 1346
 
1347 1347
 			$subscription = [
1348 1348
 				'id'           => $row['id'],
@@ -1351,10 +1351,10 @@  discard block
 block discarded – undo
1351 1351
 				'source'       => $row['source'],
1352 1352
 				'lastmodified' => $row['lastmodified'],
1353 1353
 
1354
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
1354
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
1355 1355
 			];
1356 1356
 
1357
-			foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1357
+			foreach ($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1358 1358
 				if (!is_null($row[$dbName])) {
1359 1359
 					$subscription[$xmlName] = $row[$dbName];
1360 1360
 				}
@@ -1393,7 +1393,7 @@  discard block
 block discarded – undo
1393 1393
 
1394 1394
 		$propertiesBoolean = ['striptodos', 'stripalarms', 'stripattachments'];
1395 1395
 
1396
-		foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1396
+		foreach ($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1397 1397
 			if (array_key_exists($xmlName, $properties)) {
1398 1398
 					$values[$dbName] = $properties[$xmlName];
1399 1399
 					if (in_array($dbName, $propertiesBoolean)) {
@@ -1441,7 +1441,7 @@  discard block
 block discarded – undo
1441 1441
 
1442 1442
 			$newValues = [];
1443 1443
 
1444
-			foreach($mutations as $propertyName=>$propertyValue) {
1444
+			foreach ($mutations as $propertyName=>$propertyValue) {
1445 1445
 				if ($propertyName === '{http://calendarserver.org/ns/}source') {
1446 1446
 					$newValues['source'] = $propertyValue->getHref();
1447 1447
 				} else {
@@ -1453,7 +1453,7 @@  discard block
 block discarded – undo
1453 1453
 			$query = $this->db->getQueryBuilder();
1454 1454
 			$query->update('calendarsubscriptions')
1455 1455
 				->set('lastmodified', $query->createNamedParameter(time()));
1456
-			foreach($newValues as $fieldName=>$value) {
1456
+			foreach ($newValues as $fieldName=>$value) {
1457 1457
 				$query->set($fieldName, $query->createNamedParameter($value));
1458 1458
 			}
1459 1459
 			$query->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
@@ -1503,7 +1503,7 @@  discard block
 block discarded – undo
1503 1503
 
1504 1504
 		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
1505 1505
 
1506
-		if(!$row) {
1506
+		if (!$row) {
1507 1507
 			return null;
1508 1508
 		}
1509 1509
 
@@ -1511,8 +1511,8 @@  discard block
 block discarded – undo
1511 1511
 				'uri'          => $row['uri'],
1512 1512
 				'calendardata' => $row['calendardata'],
1513 1513
 				'lastmodified' => $row['lastmodified'],
1514
-				'etag'         => '"' . $row['etag'] . '"',
1515
-				'size'         => (int)$row['size'],
1514
+				'etag'         => '"'.$row['etag'].'"',
1515
+				'size'         => (int) $row['size'],
1516 1516
 		];
1517 1517
 	}
1518 1518
 
@@ -1535,13 +1535,13 @@  discard block
 block discarded – undo
1535 1535
 				->execute();
1536 1536
 
1537 1537
 		$result = [];
1538
-		foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
1538
+		foreach ($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
1539 1539
 			$result[] = [
1540 1540
 					'calendardata' => $row['calendardata'],
1541 1541
 					'uri'          => $row['uri'],
1542 1542
 					'lastmodified' => $row['lastmodified'],
1543
-					'etag'         => '"' . $row['etag'] . '"',
1544
-					'size'         => (int)$row['size'],
1543
+					'etag'         => '"'.$row['etag'].'"',
1544
+					'size'         => (int) $row['size'],
1545 1545
 			];
1546 1546
 		}
1547 1547
 
@@ -1633,10 +1633,10 @@  discard block
 block discarded – undo
1633 1633
 		$lastOccurrence = null;
1634 1634
 		$uid = null;
1635 1635
 		$classification = self::CLASSIFICATION_PUBLIC;
1636
-		foreach($vObject->getComponents() as $component) {
1637
-			if ($component->name!=='VTIMEZONE') {
1636
+		foreach ($vObject->getComponents() as $component) {
1637
+			if ($component->name !== 'VTIMEZONE') {
1638 1638
 				$componentType = $component->name;
1639
-				$uid = (string)$component->UID;
1639
+				$uid = (string) $component->UID;
1640 1640
 				break;
1641 1641
 			}
1642 1642
 		}
@@ -1661,13 +1661,13 @@  discard block
 block discarded – undo
1661 1661
 					$lastOccurrence = $firstOccurrence;
1662 1662
 				}
1663 1663
 			} else {
1664
-				$it = new EventIterator($vObject, (string)$component->UID);
1664
+				$it = new EventIterator($vObject, (string) $component->UID);
1665 1665
 				$maxDate = new \DateTime(self::MAX_DATE);
1666 1666
 				if ($it->isInfinite()) {
1667 1667
 					$lastOccurrence = $maxDate->getTimestamp();
1668 1668
 				} else {
1669 1669
 					$end = $it->getDtEnd();
1670
-					while($it->valid() && $end < $maxDate) {
1670
+					while ($it->valid() && $end < $maxDate) {
1671 1671
 						$end = $it->getDtEnd();
1672 1672
 						$it->next();
1673 1673
 
Please login to merge, or discard this patch.
Braces   +3 added lines, -1 removed lines patch added patch discarded remove patch
@@ -808,7 +808,9 @@
 block discarded – undo
808 808
 		$stmt = $query->execute();
809 809
 		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
810 810
 
811
-		if(!$row) return null;
811
+		if(!$row) {
812
+		    return null;
813
+		}
812 814
 
813 815
 		return [
814 816
 				'id'            => $row['id'],
Please login to merge, or discard this patch.
lib/private/Files/Filesystem.php 4 patches
Doc Comments   +31 added lines, -2 removed lines patch added patch discarded remove patch
@@ -360,6 +360,9 @@  discard block
 block discarded – undo
360 360
 		}
361 361
 	}
362 362
 
363
+	/**
364
+	 * @param string $root
365
+	 */
363 366
 	static public function init($user, $root) {
364 367
 		if (self::$defaultInstance) {
365 368
 			return false;
@@ -528,7 +531,7 @@  discard block
 block discarded – undo
528 531
 	/**
529 532
 	 * mount an \OC\Files\Storage\Storage in our virtual filesystem
530 533
 	 *
531
-	 * @param \OC\Files\Storage\Storage|string $class
534
+	 * @param string $class
532 535
 	 * @param array $arguments
533 536
 	 * @param string $mountpoint
534 537
 	 */
@@ -660,6 +663,9 @@  discard block
 block discarded – undo
660 663
 		return self::$defaultInstance->is_dir($path);
661 664
 	}
662 665
 
666
+	/**
667
+	 * @param string $path
668
+	 */
663 669
 	static public function is_file($path) {
664 670
 		return self::$defaultInstance->is_file($path);
665 671
 	}
@@ -672,6 +678,9 @@  discard block
 block discarded – undo
672 678
 		return self::$defaultInstance->filetype($path);
673 679
 	}
674 680
 
681
+	/**
682
+	 * @param string $path
683
+	 */
675 684
 	static public function filesize($path) {
676 685
 		return self::$defaultInstance->filesize($path);
677 686
 	}
@@ -684,6 +693,9 @@  discard block
 block discarded – undo
684 693
 		return self::$defaultInstance->isCreatable($path);
685 694
 	}
686 695
 
696
+	/**
697
+	 * @param string $path
698
+	 */
687 699
 	static public function isReadable($path) {
688 700
 		return self::$defaultInstance->isReadable($path);
689 701
 	}
@@ -696,6 +708,9 @@  discard block
 block discarded – undo
696 708
 		return self::$defaultInstance->isDeletable($path);
697 709
 	}
698 710
 
711
+	/**
712
+	 * @param string $path
713
+	 */
699 714
 	static public function isSharable($path) {
700 715
 		return self::$defaultInstance->isSharable($path);
701 716
 	}
@@ -704,6 +719,9 @@  discard block
 block discarded – undo
704 719
 		return self::$defaultInstance->file_exists($path);
705 720
 	}
706 721
 
722
+	/**
723
+	 * @param string $path
724
+	 */
707 725
 	static public function filemtime($path) {
708 726
 		return self::$defaultInstance->filemtime($path);
709 727
 	}
@@ -713,6 +731,7 @@  discard block
 block discarded – undo
713 731
 	}
714 732
 
715 733
 	/**
734
+	 * @param string $path
716 735
 	 * @return string
717 736
 	 */
718 737
 	static public function file_get_contents($path) {
@@ -735,6 +754,10 @@  discard block
 block discarded – undo
735 754
 		return self::$defaultInstance->copy($path1, $path2);
736 755
 	}
737 756
 
757
+	/**
758
+	 * @param string $path
759
+	 * @param string $mode
760
+	 */
738 761
 	static public function fopen($path, $mode) {
739 762
 		return self::$defaultInstance->fopen($path, $mode);
740 763
 	}
@@ -750,6 +773,9 @@  discard block
 block discarded – undo
750 773
 		return self::$defaultInstance->fromTmpFile($tmpFile, $path);
751 774
 	}
752 775
 
776
+	/**
777
+	 * @param string $path
778
+	 */
753 779
 	static public function getMimeType($path) {
754 780
 		return self::$defaultInstance->getMimeType($path);
755 781
 	}
@@ -762,6 +788,9 @@  discard block
 block discarded – undo
762 788
 		return self::$defaultInstance->free_space($path);
763 789
 	}
764 790
 
791
+	/**
792
+	 * @param string $query
793
+	 */
765 794
 	static public function search($query) {
766 795
 		return self::$defaultInstance->search($query);
767 796
 	}
@@ -870,7 +899,7 @@  discard block
 block discarded – undo
870 899
 	 * @param string $path
871 900
 	 * @param boolean $includeMountPoints whether to add mountpoint sizes,
872 901
 	 * defaults to true
873
-	 * @return \OC\Files\FileInfo|bool False if file does not exist
902
+	 * @return \OCP\Files\FileInfo|null False if file does not exist
874 903
 	 */
875 904
 	public static function getFileInfo($path, $includeMountPoints = true) {
876 905
 		return self::$defaultInstance->getFileInfo($path, $includeMountPoints);
Please login to merge, or discard this patch.
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -64,7 +64,6 @@
 block discarded – undo
64 64
 use OC\Files\Storage\StorageFactory;
65 65
 use OC\Lockdown\Filesystem\NullStorage;
66 66
 use OCP\Files\Config\IMountProvider;
67
-use OCP\Files\Mount\IMountPoint;
68 67
 use OCP\Files\NotFoundException;
69 68
 use OCP\IUserManager;
70 69
 
Please login to merge, or discard this patch.
Indentation   +862 added lines, -862 removed lines patch added patch discarded remove patch
@@ -70,866 +70,866 @@
 block discarded – undo
70 70
 
71 71
 class Filesystem {
72 72
 
73
-	/**
74
-	 * @var Mount\Manager $mounts
75
-	 */
76
-	private static $mounts;
77
-
78
-	public static $loaded = false;
79
-	/**
80
-	 * @var \OC\Files\View $defaultInstance
81
-	 */
82
-	static private $defaultInstance;
83
-
84
-	static private $usersSetup = array();
85
-
86
-	static private $normalizedPathCache = null;
87
-
88
-	static private $listeningForProviders = false;
89
-
90
-	/**
91
-	 * classname which used for hooks handling
92
-	 * used as signalclass in OC_Hooks::emit()
93
-	 */
94
-	const CLASSNAME = 'OC_Filesystem';
95
-
96
-	/**
97
-	 * signalname emitted before file renaming
98
-	 *
99
-	 * @param string $oldpath
100
-	 * @param string $newpath
101
-	 */
102
-	const signal_rename = 'rename';
103
-
104
-	/**
105
-	 * signal emitted after file renaming
106
-	 *
107
-	 * @param string $oldpath
108
-	 * @param string $newpath
109
-	 */
110
-	const signal_post_rename = 'post_rename';
111
-
112
-	/**
113
-	 * signal emitted before file/dir creation
114
-	 *
115
-	 * @param string $path
116
-	 * @param bool $run changing this flag to false in hook handler will cancel event
117
-	 */
118
-	const signal_create = 'create';
119
-
120
-	/**
121
-	 * signal emitted after file/dir creation
122
-	 *
123
-	 * @param string $path
124
-	 * @param bool $run changing this flag to false in hook handler will cancel event
125
-	 */
126
-	const signal_post_create = 'post_create';
127
-
128
-	/**
129
-	 * signal emits before file/dir copy
130
-	 *
131
-	 * @param string $oldpath
132
-	 * @param string $newpath
133
-	 * @param bool $run changing this flag to false in hook handler will cancel event
134
-	 */
135
-	const signal_copy = 'copy';
136
-
137
-	/**
138
-	 * signal emits after file/dir copy
139
-	 *
140
-	 * @param string $oldpath
141
-	 * @param string $newpath
142
-	 */
143
-	const signal_post_copy = 'post_copy';
144
-
145
-	/**
146
-	 * signal emits before file/dir save
147
-	 *
148
-	 * @param string $path
149
-	 * @param bool $run changing this flag to false in hook handler will cancel event
150
-	 */
151
-	const signal_write = 'write';
152
-
153
-	/**
154
-	 * signal emits after file/dir save
155
-	 *
156
-	 * @param string $path
157
-	 */
158
-	const signal_post_write = 'post_write';
159
-
160
-	/**
161
-	 * signal emitted before file/dir update
162
-	 *
163
-	 * @param string $path
164
-	 * @param bool $run changing this flag to false in hook handler will cancel event
165
-	 */
166
-	const signal_update = 'update';
167
-
168
-	/**
169
-	 * signal emitted after file/dir update
170
-	 *
171
-	 * @param string $path
172
-	 * @param bool $run changing this flag to false in hook handler will cancel event
173
-	 */
174
-	const signal_post_update = 'post_update';
175
-
176
-	/**
177
-	 * signal emits when reading file/dir
178
-	 *
179
-	 * @param string $path
180
-	 */
181
-	const signal_read = 'read';
182
-
183
-	/**
184
-	 * signal emits when removing file/dir
185
-	 *
186
-	 * @param string $path
187
-	 */
188
-	const signal_delete = 'delete';
189
-
190
-	/**
191
-	 * parameters definitions for signals
192
-	 */
193
-	const signal_param_path = 'path';
194
-	const signal_param_oldpath = 'oldpath';
195
-	const signal_param_newpath = 'newpath';
196
-
197
-	/**
198
-	 * run - changing this flag to false in hook handler will cancel event
199
-	 */
200
-	const signal_param_run = 'run';
201
-
202
-	const signal_create_mount = 'create_mount';
203
-	const signal_delete_mount = 'delete_mount';
204
-	const signal_param_mount_type = 'mounttype';
205
-	const signal_param_users = 'users';
206
-
207
-	/**
208
-	 * @var \OC\Files\Storage\StorageFactory $loader
209
-	 */
210
-	private static $loader;
211
-
212
-	/** @var bool */
213
-	private static $logWarningWhenAddingStorageWrapper = true;
214
-
215
-	/**
216
-	 * @param bool $shouldLog
217
-	 * @return bool previous value
218
-	 * @internal
219
-	 */
220
-	public static function logWarningWhenAddingStorageWrapper($shouldLog) {
221
-		$previousValue = self::$logWarningWhenAddingStorageWrapper;
222
-		self::$logWarningWhenAddingStorageWrapper = (bool) $shouldLog;
223
-		return $previousValue;
224
-	}
225
-
226
-	/**
227
-	 * @param string $wrapperName
228
-	 * @param callable $wrapper
229
-	 * @param int $priority
230
-	 */
231
-	public static function addStorageWrapper($wrapperName, $wrapper, $priority = 50) {
232
-		if (self::$logWarningWhenAddingStorageWrapper) {
233
-			\OC::$server->getLogger()->warning("Storage wrapper '{wrapper}' was not registered via the 'OC_Filesystem - preSetup' hook which could cause potential problems.", [
234
-				'wrapper' => $wrapperName,
235
-				'app' => 'filesystem',
236
-			]);
237
-		}
238
-
239
-		$mounts = self::getMountManager()->getAll();
240
-		if (!self::getLoader()->addStorageWrapper($wrapperName, $wrapper, $priority, $mounts)) {
241
-			// do not re-wrap if storage with this name already existed
242
-			return;
243
-		}
244
-	}
245
-
246
-	/**
247
-	 * Returns the storage factory
248
-	 *
249
-	 * @return \OCP\Files\Storage\IStorageFactory
250
-	 */
251
-	public static function getLoader() {
252
-		if (!self::$loader) {
253
-			self::$loader = new StorageFactory();
254
-		}
255
-		return self::$loader;
256
-	}
257
-
258
-	/**
259
-	 * Returns the mount manager
260
-	 *
261
-	 * @return \OC\Files\Mount\Manager
262
-	 */
263
-	public static function getMountManager($user = '') {
264
-		if (!self::$mounts) {
265
-			\OC_Util::setupFS($user);
266
-		}
267
-		return self::$mounts;
268
-	}
269
-
270
-	/**
271
-	 * get the mountpoint of the storage object for a path
272
-	 * ( note: because a storage is not always mounted inside the fakeroot, the
273
-	 * returned mountpoint is relative to the absolute root of the filesystem
274
-	 * and doesn't take the chroot into account )
275
-	 *
276
-	 * @param string $path
277
-	 * @return string
278
-	 */
279
-	static public function getMountPoint($path) {
280
-		if (!self::$mounts) {
281
-			\OC_Util::setupFS();
282
-		}
283
-		$mount = self::$mounts->find($path);
284
-		if ($mount) {
285
-			return $mount->getMountPoint();
286
-		} else {
287
-			return '';
288
-		}
289
-	}
290
-
291
-	/**
292
-	 * get a list of all mount points in a directory
293
-	 *
294
-	 * @param string $path
295
-	 * @return string[]
296
-	 */
297
-	static public function getMountPoints($path) {
298
-		if (!self::$mounts) {
299
-			\OC_Util::setupFS();
300
-		}
301
-		$result = array();
302
-		$mounts = self::$mounts->findIn($path);
303
-		foreach ($mounts as $mount) {
304
-			$result[] = $mount->getMountPoint();
305
-		}
306
-		return $result;
307
-	}
308
-
309
-	/**
310
-	 * get the storage mounted at $mountPoint
311
-	 *
312
-	 * @param string $mountPoint
313
-	 * @return \OC\Files\Storage\Storage
314
-	 */
315
-	public static function getStorage($mountPoint) {
316
-		if (!self::$mounts) {
317
-			\OC_Util::setupFS();
318
-		}
319
-		$mount = self::$mounts->find($mountPoint);
320
-		return $mount->getStorage();
321
-	}
322
-
323
-	/**
324
-	 * @param string $id
325
-	 * @return Mount\MountPoint[]
326
-	 */
327
-	public static function getMountByStorageId($id) {
328
-		if (!self::$mounts) {
329
-			\OC_Util::setupFS();
330
-		}
331
-		return self::$mounts->findByStorageId($id);
332
-	}
333
-
334
-	/**
335
-	 * @param int $id
336
-	 * @return Mount\MountPoint[]
337
-	 */
338
-	public static function getMountByNumericId($id) {
339
-		if (!self::$mounts) {
340
-			\OC_Util::setupFS();
341
-		}
342
-		return self::$mounts->findByNumericId($id);
343
-	}
344
-
345
-	/**
346
-	 * resolve a path to a storage and internal path
347
-	 *
348
-	 * @param string $path
349
-	 * @return array an array consisting of the storage and the internal path
350
-	 */
351
-	static public function resolvePath($path) {
352
-		if (!self::$mounts) {
353
-			\OC_Util::setupFS();
354
-		}
355
-		$mount = self::$mounts->find($path);
356
-		if ($mount) {
357
-			return array($mount->getStorage(), rtrim($mount->getInternalPath($path), '/'));
358
-		} else {
359
-			return array(null, null);
360
-		}
361
-	}
362
-
363
-	static public function init($user, $root) {
364
-		if (self::$defaultInstance) {
365
-			return false;
366
-		}
367
-		self::getLoader();
368
-		self::$defaultInstance = new View($root);
369
-
370
-		if (!self::$mounts) {
371
-			self::$mounts = \OC::$server->getMountManager();
372
-		}
373
-
374
-		//load custom mount config
375
-		self::initMountPoints($user);
376
-
377
-		self::$loaded = true;
378
-
379
-		return true;
380
-	}
381
-
382
-	static public function initMountManager() {
383
-		if (!self::$mounts) {
384
-			self::$mounts = \OC::$server->getMountManager();
385
-		}
386
-	}
387
-
388
-	/**
389
-	 * Initialize system and personal mount points for a user
390
-	 *
391
-	 * @param string $user
392
-	 * @throws \OC\User\NoUserException if the user is not available
393
-	 */
394
-	public static function initMountPoints($user = '') {
395
-		if ($user == '') {
396
-			$user = \OC_User::getUser();
397
-		}
398
-		if ($user === null || $user === false || $user === '') {
399
-			throw new \OC\User\NoUserException('Attempted to initialize mount points for null user and no user in session');
400
-		}
401
-
402
-		if (isset(self::$usersSetup[$user])) {
403
-			return;
404
-		}
405
-
406
-		self::$usersSetup[$user] = true;
407
-
408
-		$userManager = \OC::$server->getUserManager();
409
-		$userObject = $userManager->get($user);
410
-
411
-		if (is_null($userObject)) {
412
-			\OCP\Util::writeLog('files', ' Backends provided no user object for ' . $user, \OCP\Util::ERROR);
413
-			// reset flag, this will make it possible to rethrow the exception if called again
414
-			unset(self::$usersSetup[$user]);
415
-			throw new \OC\User\NoUserException('Backends provided no user object for ' . $user);
416
-		}
417
-
418
-		$realUid = $userObject->getUID();
419
-		// workaround in case of different casings
420
-		if ($user !== $realUid) {
421
-			$stack = json_encode(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 50));
422
-			\OCP\Util::writeLog('files', 'initMountPoints() called with wrong user casing. This could be a bug. Expected: "' . $realUid . '" got "' . $user . '". Stack: ' . $stack, \OCP\Util::WARN);
423
-			$user = $realUid;
424
-
425
-			// again with the correct casing
426
-			if (isset(self::$usersSetup[$user])) {
427
-				return;
428
-			}
429
-
430
-			self::$usersSetup[$user] = true;
431
-		}
432
-
433
-		if (\OC::$server->getLockdownManager()->canAccessFilesystem()) {
434
-			/** @var \OC\Files\Config\MountProviderCollection $mountConfigManager */
435
-			$mountConfigManager = \OC::$server->getMountProviderCollection();
436
-
437
-			// home mounts are handled seperate since we need to ensure this is mounted before we call the other mount providers
438
-			$homeMount = $mountConfigManager->getHomeMountForUser($userObject);
439
-
440
-			self::getMountManager()->addMount($homeMount);
441
-
442
-			\OC\Files\Filesystem::getStorage($user);
443
-
444
-			// Chance to mount for other storages
445
-			if ($userObject) {
446
-				$mounts = $mountConfigManager->getMountsForUser($userObject);
447
-				array_walk($mounts, array(self::$mounts, 'addMount'));
448
-				$mounts[] = $homeMount;
449
-				$mountConfigManager->registerMounts($userObject, $mounts);
450
-			}
451
-
452
-			self::listenForNewMountProviders($mountConfigManager, $userManager);
453
-		} else {
454
-			self::getMountManager()->addMount(new MountPoint(
455
-				new NullStorage([]),
456
-				'/' . $user
457
-			));
458
-			self::getMountManager()->addMount(new MountPoint(
459
-				new NullStorage([]),
460
-				'/' . $user . '/files'
461
-			));
462
-		}
463
-		\OC_Hook::emit('OC_Filesystem', 'post_initMountPoints', array('user' => $user));
464
-	}
465
-
466
-	/**
467
-	 * Get mounts from mount providers that are registered after setup
468
-	 *
469
-	 * @param MountProviderCollection $mountConfigManager
470
-	 * @param IUserManager $userManager
471
-	 */
472
-	private static function listenForNewMountProviders(MountProviderCollection $mountConfigManager, IUserManager $userManager) {
473
-		if (!self::$listeningForProviders) {
474
-			self::$listeningForProviders = true;
475
-			$mountConfigManager->listen('\OC\Files\Config', 'registerMountProvider', function (IMountProvider $provider) use ($userManager) {
476
-				foreach (Filesystem::$usersSetup as $user => $setup) {
477
-					$userObject = $userManager->get($user);
478
-					if ($userObject) {
479
-						$mounts = $provider->getMountsForUser($userObject, Filesystem::getLoader());
480
-						array_walk($mounts, array(self::$mounts, 'addMount'));
481
-					}
482
-				}
483
-			});
484
-		}
485
-	}
486
-
487
-	/**
488
-	 * get the default filesystem view
489
-	 *
490
-	 * @return View
491
-	 */
492
-	static public function getView() {
493
-		return self::$defaultInstance;
494
-	}
495
-
496
-	/**
497
-	 * tear down the filesystem, removing all storage providers
498
-	 */
499
-	static public function tearDown() {
500
-		self::clearMounts();
501
-		self::$defaultInstance = null;
502
-	}
503
-
504
-	/**
505
-	 * get the relative path of the root data directory for the current user
506
-	 *
507
-	 * @return string
508
-	 *
509
-	 * Returns path like /admin/files
510
-	 */
511
-	static public function getRoot() {
512
-		if (!self::$defaultInstance) {
513
-			return null;
514
-		}
515
-		return self::$defaultInstance->getRoot();
516
-	}
517
-
518
-	/**
519
-	 * clear all mounts and storage backends
520
-	 */
521
-	public static function clearMounts() {
522
-		if (self::$mounts) {
523
-			self::$usersSetup = array();
524
-			self::$mounts->clear();
525
-		}
526
-	}
527
-
528
-	/**
529
-	 * mount an \OC\Files\Storage\Storage in our virtual filesystem
530
-	 *
531
-	 * @param \OC\Files\Storage\Storage|string $class
532
-	 * @param array $arguments
533
-	 * @param string $mountpoint
534
-	 */
535
-	static public function mount($class, $arguments, $mountpoint) {
536
-		if (!self::$mounts) {
537
-			\OC_Util::setupFS();
538
-		}
539
-		$mount = new Mount\MountPoint($class, $mountpoint, $arguments, self::getLoader());
540
-		self::$mounts->addMount($mount);
541
-	}
542
-
543
-	/**
544
-	 * return the path to a local version of the file
545
-	 * we need this because we can't know if a file is stored local or not from
546
-	 * outside the filestorage and for some purposes a local file is needed
547
-	 *
548
-	 * @param string $path
549
-	 * @return string
550
-	 */
551
-	static public function getLocalFile($path) {
552
-		return self::$defaultInstance->getLocalFile($path);
553
-	}
554
-
555
-	/**
556
-	 * @param string $path
557
-	 * @return string
558
-	 */
559
-	static public function getLocalFolder($path) {
560
-		return self::$defaultInstance->getLocalFolder($path);
561
-	}
562
-
563
-	/**
564
-	 * return path to file which reflects one visible in browser
565
-	 *
566
-	 * @param string $path
567
-	 * @return string
568
-	 */
569
-	static public function getLocalPath($path) {
570
-		$datadir = \OC_User::getHome(\OC_User::getUser()) . '/files';
571
-		$newpath = $path;
572
-		if (strncmp($newpath, $datadir, strlen($datadir)) == 0) {
573
-			$newpath = substr($path, strlen($datadir));
574
-		}
575
-		return $newpath;
576
-	}
577
-
578
-	/**
579
-	 * check if the requested path is valid
580
-	 *
581
-	 * @param string $path
582
-	 * @return bool
583
-	 */
584
-	static public function isValidPath($path) {
585
-		$path = self::normalizePath($path);
586
-		if (!$path || $path[0] !== '/') {
587
-			$path = '/' . $path;
588
-		}
589
-		if (strpos($path, '/../') !== false || strrchr($path, '/') === '/..') {
590
-			return false;
591
-		}
592
-		return true;
593
-	}
594
-
595
-	/**
596
-	 * checks if a file is blacklisted for storage in the filesystem
597
-	 * Listens to write and rename hooks
598
-	 *
599
-	 * @param array $data from hook
600
-	 */
601
-	static public function isBlacklisted($data) {
602
-		if (isset($data['path'])) {
603
-			$path = $data['path'];
604
-		} else if (isset($data['newpath'])) {
605
-			$path = $data['newpath'];
606
-		}
607
-		if (isset($path)) {
608
-			if (self::isFileBlacklisted($path)) {
609
-				$data['run'] = false;
610
-			}
611
-		}
612
-	}
613
-
614
-	/**
615
-	 * @param string $filename
616
-	 * @return bool
617
-	 */
618
-	static public function isFileBlacklisted($filename) {
619
-		$filename = self::normalizePath($filename);
620
-
621
-		$blacklist = \OC::$server->getConfig()->getSystemValue('blacklisted_files', array('.htaccess'));
622
-		$filename = strtolower(basename($filename));
623
-		return in_array($filename, $blacklist);
624
-	}
625
-
626
-	/**
627
-	 * check if the directory should be ignored when scanning
628
-	 * NOTE: the special directories . and .. would cause never ending recursion
629
-	 *
630
-	 * @param String $dir
631
-	 * @return boolean
632
-	 */
633
-	static public function isIgnoredDir($dir) {
634
-		if ($dir === '.' || $dir === '..') {
635
-			return true;
636
-		}
637
-		return false;
638
-	}
639
-
640
-	/**
641
-	 * following functions are equivalent to their php builtin equivalents for arguments/return values.
642
-	 */
643
-	static public function mkdir($path) {
644
-		return self::$defaultInstance->mkdir($path);
645
-	}
646
-
647
-	static public function rmdir($path) {
648
-		return self::$defaultInstance->rmdir($path);
649
-	}
650
-
651
-	static public function opendir($path) {
652
-		return self::$defaultInstance->opendir($path);
653
-	}
654
-
655
-	static public function readdir($path) {
656
-		return self::$defaultInstance->readdir($path);
657
-	}
658
-
659
-	static public function is_dir($path) {
660
-		return self::$defaultInstance->is_dir($path);
661
-	}
662
-
663
-	static public function is_file($path) {
664
-		return self::$defaultInstance->is_file($path);
665
-	}
666
-
667
-	static public function stat($path) {
668
-		return self::$defaultInstance->stat($path);
669
-	}
670
-
671
-	static public function filetype($path) {
672
-		return self::$defaultInstance->filetype($path);
673
-	}
674
-
675
-	static public function filesize($path) {
676
-		return self::$defaultInstance->filesize($path);
677
-	}
678
-
679
-	static public function readfile($path) {
680
-		return self::$defaultInstance->readfile($path);
681
-	}
682
-
683
-	static public function isCreatable($path) {
684
-		return self::$defaultInstance->isCreatable($path);
685
-	}
686
-
687
-	static public function isReadable($path) {
688
-		return self::$defaultInstance->isReadable($path);
689
-	}
690
-
691
-	static public function isUpdatable($path) {
692
-		return self::$defaultInstance->isUpdatable($path);
693
-	}
694
-
695
-	static public function isDeletable($path) {
696
-		return self::$defaultInstance->isDeletable($path);
697
-	}
698
-
699
-	static public function isSharable($path) {
700
-		return self::$defaultInstance->isSharable($path);
701
-	}
702
-
703
-	static public function file_exists($path) {
704
-		return self::$defaultInstance->file_exists($path);
705
-	}
706
-
707
-	static public function filemtime($path) {
708
-		return self::$defaultInstance->filemtime($path);
709
-	}
710
-
711
-	static public function touch($path, $mtime = null) {
712
-		return self::$defaultInstance->touch($path, $mtime);
713
-	}
714
-
715
-	/**
716
-	 * @return string
717
-	 */
718
-	static public function file_get_contents($path) {
719
-		return self::$defaultInstance->file_get_contents($path);
720
-	}
721
-
722
-	static public function file_put_contents($path, $data) {
723
-		return self::$defaultInstance->file_put_contents($path, $data);
724
-	}
725
-
726
-	static public function unlink($path) {
727
-		return self::$defaultInstance->unlink($path);
728
-	}
729
-
730
-	static public function rename($path1, $path2) {
731
-		return self::$defaultInstance->rename($path1, $path2);
732
-	}
733
-
734
-	static public function copy($path1, $path2) {
735
-		return self::$defaultInstance->copy($path1, $path2);
736
-	}
737
-
738
-	static public function fopen($path, $mode) {
739
-		return self::$defaultInstance->fopen($path, $mode);
740
-	}
741
-
742
-	/**
743
-	 * @return string
744
-	 */
745
-	static public function toTmpFile($path) {
746
-		return self::$defaultInstance->toTmpFile($path);
747
-	}
748
-
749
-	static public function fromTmpFile($tmpFile, $path) {
750
-		return self::$defaultInstance->fromTmpFile($tmpFile, $path);
751
-	}
752
-
753
-	static public function getMimeType($path) {
754
-		return self::$defaultInstance->getMimeType($path);
755
-	}
756
-
757
-	static public function hash($type, $path, $raw = false) {
758
-		return self::$defaultInstance->hash($type, $path, $raw);
759
-	}
760
-
761
-	static public function free_space($path = '/') {
762
-		return self::$defaultInstance->free_space($path);
763
-	}
764
-
765
-	static public function search($query) {
766
-		return self::$defaultInstance->search($query);
767
-	}
768
-
769
-	/**
770
-	 * @param string $query
771
-	 */
772
-	static public function searchByMime($query) {
773
-		return self::$defaultInstance->searchByMime($query);
774
-	}
775
-
776
-	/**
777
-	 * @param string|int $tag name or tag id
778
-	 * @param string $userId owner of the tags
779
-	 * @return FileInfo[] array or file info
780
-	 */
781
-	static public function searchByTag($tag, $userId) {
782
-		return self::$defaultInstance->searchByTag($tag, $userId);
783
-	}
784
-
785
-	/**
786
-	 * check if a file or folder has been updated since $time
787
-	 *
788
-	 * @param string $path
789
-	 * @param int $time
790
-	 * @return bool
791
-	 */
792
-	static public function hasUpdated($path, $time) {
793
-		return self::$defaultInstance->hasUpdated($path, $time);
794
-	}
795
-
796
-	/**
797
-	 * Fix common problems with a file path
798
-	 *
799
-	 * @param string $path
800
-	 * @param bool $stripTrailingSlash whether to strip the trailing slash
801
-	 * @param bool $isAbsolutePath whether the given path is absolute
802
-	 * @param bool $keepUnicode true to disable unicode normalization
803
-	 * @return string
804
-	 */
805
-	public static function normalizePath($path, $stripTrailingSlash = true, $isAbsolutePath = false, $keepUnicode = false) {
806
-		if (is_null(self::$normalizedPathCache)) {
807
-			self::$normalizedPathCache = new CappedMemoryCache();
808
-		}
809
-
810
-		/**
811
-		 * FIXME: This is a workaround for existing classes and files which call
812
-		 *        this function with another type than a valid string. This
813
-		 *        conversion should get removed as soon as all existing
814
-		 *        function calls have been fixed.
815
-		 */
816
-		$path = (string)$path;
817
-
818
-		$cacheKey = json_encode([$path, $stripTrailingSlash, $isAbsolutePath, $keepUnicode]);
819
-
820
-		if (isset(self::$normalizedPathCache[$cacheKey])) {
821
-			return self::$normalizedPathCache[$cacheKey];
822
-		}
823
-
824
-		if ($path == '') {
825
-			return '/';
826
-		}
827
-
828
-		//normalize unicode if possible
829
-		if (!$keepUnicode) {
830
-			$path = \OC_Util::normalizeUnicode($path);
831
-		}
832
-
833
-		//no windows style slashes
834
-		$path = str_replace('\\', '/', $path);
835
-
836
-		//add leading slash
837
-		if ($path[0] !== '/') {
838
-			$path = '/' . $path;
839
-		}
840
-
841
-		// remove '/./'
842
-		// ugly, but str_replace() can't replace them all in one go
843
-		// as the replacement itself is part of the search string
844
-		// which will only be found during the next iteration
845
-		while (strpos($path, '/./') !== false) {
846
-			$path = str_replace('/./', '/', $path);
847
-		}
848
-		// remove sequences of slashes
849
-		$path = preg_replace('#/{2,}#', '/', $path);
850
-
851
-		//remove trailing slash
852
-		if ($stripTrailingSlash and strlen($path) > 1 and substr($path, -1, 1) === '/') {
853
-			$path = substr($path, 0, -1);
854
-		}
855
-
856
-		// remove trailing '/.'
857
-		if (substr($path, -2) == '/.') {
858
-			$path = substr($path, 0, -2);
859
-		}
860
-
861
-		$normalizedPath = $path;
862
-		self::$normalizedPathCache[$cacheKey] = $normalizedPath;
863
-
864
-		return $normalizedPath;
865
-	}
866
-
867
-	/**
868
-	 * get the filesystem info
869
-	 *
870
-	 * @param string $path
871
-	 * @param boolean $includeMountPoints whether to add mountpoint sizes,
872
-	 * defaults to true
873
-	 * @return \OC\Files\FileInfo|bool False if file does not exist
874
-	 */
875
-	public static function getFileInfo($path, $includeMountPoints = true) {
876
-		return self::$defaultInstance->getFileInfo($path, $includeMountPoints);
877
-	}
878
-
879
-	/**
880
-	 * change file metadata
881
-	 *
882
-	 * @param string $path
883
-	 * @param array $data
884
-	 * @return int
885
-	 *
886
-	 * returns the fileid of the updated file
887
-	 */
888
-	public static function putFileInfo($path, $data) {
889
-		return self::$defaultInstance->putFileInfo($path, $data);
890
-	}
891
-
892
-	/**
893
-	 * get the content of a directory
894
-	 *
895
-	 * @param string $directory path under datadirectory
896
-	 * @param string $mimetype_filter limit returned content to this mimetype or mimepart
897
-	 * @return \OC\Files\FileInfo[]
898
-	 */
899
-	public static function getDirectoryContent($directory, $mimetype_filter = '') {
900
-		return self::$defaultInstance->getDirectoryContent($directory, $mimetype_filter);
901
-	}
902
-
903
-	/**
904
-	 * Get the path of a file by id
905
-	 *
906
-	 * Note that the resulting path is not guaranteed to be unique for the id, multiple paths can point to the same file
907
-	 *
908
-	 * @param int $id
909
-	 * @throws NotFoundException
910
-	 * @return string
911
-	 */
912
-	public static function getPath($id) {
913
-		return self::$defaultInstance->getPath($id);
914
-	}
915
-
916
-	/**
917
-	 * Get the owner for a file or folder
918
-	 *
919
-	 * @param string $path
920
-	 * @return string
921
-	 */
922
-	public static function getOwner($path) {
923
-		return self::$defaultInstance->getOwner($path);
924
-	}
925
-
926
-	/**
927
-	 * get the ETag for a file or folder
928
-	 *
929
-	 * @param string $path
930
-	 * @return string
931
-	 */
932
-	static public function getETag($path) {
933
-		return self::$defaultInstance->getETag($path);
934
-	}
73
+    /**
74
+     * @var Mount\Manager $mounts
75
+     */
76
+    private static $mounts;
77
+
78
+    public static $loaded = false;
79
+    /**
80
+     * @var \OC\Files\View $defaultInstance
81
+     */
82
+    static private $defaultInstance;
83
+
84
+    static private $usersSetup = array();
85
+
86
+    static private $normalizedPathCache = null;
87
+
88
+    static private $listeningForProviders = false;
89
+
90
+    /**
91
+     * classname which used for hooks handling
92
+     * used as signalclass in OC_Hooks::emit()
93
+     */
94
+    const CLASSNAME = 'OC_Filesystem';
95
+
96
+    /**
97
+     * signalname emitted before file renaming
98
+     *
99
+     * @param string $oldpath
100
+     * @param string $newpath
101
+     */
102
+    const signal_rename = 'rename';
103
+
104
+    /**
105
+     * signal emitted after file renaming
106
+     *
107
+     * @param string $oldpath
108
+     * @param string $newpath
109
+     */
110
+    const signal_post_rename = 'post_rename';
111
+
112
+    /**
113
+     * signal emitted before file/dir creation
114
+     *
115
+     * @param string $path
116
+     * @param bool $run changing this flag to false in hook handler will cancel event
117
+     */
118
+    const signal_create = 'create';
119
+
120
+    /**
121
+     * signal emitted after file/dir creation
122
+     *
123
+     * @param string $path
124
+     * @param bool $run changing this flag to false in hook handler will cancel event
125
+     */
126
+    const signal_post_create = 'post_create';
127
+
128
+    /**
129
+     * signal emits before file/dir copy
130
+     *
131
+     * @param string $oldpath
132
+     * @param string $newpath
133
+     * @param bool $run changing this flag to false in hook handler will cancel event
134
+     */
135
+    const signal_copy = 'copy';
136
+
137
+    /**
138
+     * signal emits after file/dir copy
139
+     *
140
+     * @param string $oldpath
141
+     * @param string $newpath
142
+     */
143
+    const signal_post_copy = 'post_copy';
144
+
145
+    /**
146
+     * signal emits before file/dir save
147
+     *
148
+     * @param string $path
149
+     * @param bool $run changing this flag to false in hook handler will cancel event
150
+     */
151
+    const signal_write = 'write';
152
+
153
+    /**
154
+     * signal emits after file/dir save
155
+     *
156
+     * @param string $path
157
+     */
158
+    const signal_post_write = 'post_write';
159
+
160
+    /**
161
+     * signal emitted before file/dir update
162
+     *
163
+     * @param string $path
164
+     * @param bool $run changing this flag to false in hook handler will cancel event
165
+     */
166
+    const signal_update = 'update';
167
+
168
+    /**
169
+     * signal emitted after file/dir update
170
+     *
171
+     * @param string $path
172
+     * @param bool $run changing this flag to false in hook handler will cancel event
173
+     */
174
+    const signal_post_update = 'post_update';
175
+
176
+    /**
177
+     * signal emits when reading file/dir
178
+     *
179
+     * @param string $path
180
+     */
181
+    const signal_read = 'read';
182
+
183
+    /**
184
+     * signal emits when removing file/dir
185
+     *
186
+     * @param string $path
187
+     */
188
+    const signal_delete = 'delete';
189
+
190
+    /**
191
+     * parameters definitions for signals
192
+     */
193
+    const signal_param_path = 'path';
194
+    const signal_param_oldpath = 'oldpath';
195
+    const signal_param_newpath = 'newpath';
196
+
197
+    /**
198
+     * run - changing this flag to false in hook handler will cancel event
199
+     */
200
+    const signal_param_run = 'run';
201
+
202
+    const signal_create_mount = 'create_mount';
203
+    const signal_delete_mount = 'delete_mount';
204
+    const signal_param_mount_type = 'mounttype';
205
+    const signal_param_users = 'users';
206
+
207
+    /**
208
+     * @var \OC\Files\Storage\StorageFactory $loader
209
+     */
210
+    private static $loader;
211
+
212
+    /** @var bool */
213
+    private static $logWarningWhenAddingStorageWrapper = true;
214
+
215
+    /**
216
+     * @param bool $shouldLog
217
+     * @return bool previous value
218
+     * @internal
219
+     */
220
+    public static function logWarningWhenAddingStorageWrapper($shouldLog) {
221
+        $previousValue = self::$logWarningWhenAddingStorageWrapper;
222
+        self::$logWarningWhenAddingStorageWrapper = (bool) $shouldLog;
223
+        return $previousValue;
224
+    }
225
+
226
+    /**
227
+     * @param string $wrapperName
228
+     * @param callable $wrapper
229
+     * @param int $priority
230
+     */
231
+    public static function addStorageWrapper($wrapperName, $wrapper, $priority = 50) {
232
+        if (self::$logWarningWhenAddingStorageWrapper) {
233
+            \OC::$server->getLogger()->warning("Storage wrapper '{wrapper}' was not registered via the 'OC_Filesystem - preSetup' hook which could cause potential problems.", [
234
+                'wrapper' => $wrapperName,
235
+                'app' => 'filesystem',
236
+            ]);
237
+        }
238
+
239
+        $mounts = self::getMountManager()->getAll();
240
+        if (!self::getLoader()->addStorageWrapper($wrapperName, $wrapper, $priority, $mounts)) {
241
+            // do not re-wrap if storage with this name already existed
242
+            return;
243
+        }
244
+    }
245
+
246
+    /**
247
+     * Returns the storage factory
248
+     *
249
+     * @return \OCP\Files\Storage\IStorageFactory
250
+     */
251
+    public static function getLoader() {
252
+        if (!self::$loader) {
253
+            self::$loader = new StorageFactory();
254
+        }
255
+        return self::$loader;
256
+    }
257
+
258
+    /**
259
+     * Returns the mount manager
260
+     *
261
+     * @return \OC\Files\Mount\Manager
262
+     */
263
+    public static function getMountManager($user = '') {
264
+        if (!self::$mounts) {
265
+            \OC_Util::setupFS($user);
266
+        }
267
+        return self::$mounts;
268
+    }
269
+
270
+    /**
271
+     * get the mountpoint of the storage object for a path
272
+     * ( note: because a storage is not always mounted inside the fakeroot, the
273
+     * returned mountpoint is relative to the absolute root of the filesystem
274
+     * and doesn't take the chroot into account )
275
+     *
276
+     * @param string $path
277
+     * @return string
278
+     */
279
+    static public function getMountPoint($path) {
280
+        if (!self::$mounts) {
281
+            \OC_Util::setupFS();
282
+        }
283
+        $mount = self::$mounts->find($path);
284
+        if ($mount) {
285
+            return $mount->getMountPoint();
286
+        } else {
287
+            return '';
288
+        }
289
+    }
290
+
291
+    /**
292
+     * get a list of all mount points in a directory
293
+     *
294
+     * @param string $path
295
+     * @return string[]
296
+     */
297
+    static public function getMountPoints($path) {
298
+        if (!self::$mounts) {
299
+            \OC_Util::setupFS();
300
+        }
301
+        $result = array();
302
+        $mounts = self::$mounts->findIn($path);
303
+        foreach ($mounts as $mount) {
304
+            $result[] = $mount->getMountPoint();
305
+        }
306
+        return $result;
307
+    }
308
+
309
+    /**
310
+     * get the storage mounted at $mountPoint
311
+     *
312
+     * @param string $mountPoint
313
+     * @return \OC\Files\Storage\Storage
314
+     */
315
+    public static function getStorage($mountPoint) {
316
+        if (!self::$mounts) {
317
+            \OC_Util::setupFS();
318
+        }
319
+        $mount = self::$mounts->find($mountPoint);
320
+        return $mount->getStorage();
321
+    }
322
+
323
+    /**
324
+     * @param string $id
325
+     * @return Mount\MountPoint[]
326
+     */
327
+    public static function getMountByStorageId($id) {
328
+        if (!self::$mounts) {
329
+            \OC_Util::setupFS();
330
+        }
331
+        return self::$mounts->findByStorageId($id);
332
+    }
333
+
334
+    /**
335
+     * @param int $id
336
+     * @return Mount\MountPoint[]
337
+     */
338
+    public static function getMountByNumericId($id) {
339
+        if (!self::$mounts) {
340
+            \OC_Util::setupFS();
341
+        }
342
+        return self::$mounts->findByNumericId($id);
343
+    }
344
+
345
+    /**
346
+     * resolve a path to a storage and internal path
347
+     *
348
+     * @param string $path
349
+     * @return array an array consisting of the storage and the internal path
350
+     */
351
+    static public function resolvePath($path) {
352
+        if (!self::$mounts) {
353
+            \OC_Util::setupFS();
354
+        }
355
+        $mount = self::$mounts->find($path);
356
+        if ($mount) {
357
+            return array($mount->getStorage(), rtrim($mount->getInternalPath($path), '/'));
358
+        } else {
359
+            return array(null, null);
360
+        }
361
+    }
362
+
363
+    static public function init($user, $root) {
364
+        if (self::$defaultInstance) {
365
+            return false;
366
+        }
367
+        self::getLoader();
368
+        self::$defaultInstance = new View($root);
369
+
370
+        if (!self::$mounts) {
371
+            self::$mounts = \OC::$server->getMountManager();
372
+        }
373
+
374
+        //load custom mount config
375
+        self::initMountPoints($user);
376
+
377
+        self::$loaded = true;
378
+
379
+        return true;
380
+    }
381
+
382
+    static public function initMountManager() {
383
+        if (!self::$mounts) {
384
+            self::$mounts = \OC::$server->getMountManager();
385
+        }
386
+    }
387
+
388
+    /**
389
+     * Initialize system and personal mount points for a user
390
+     *
391
+     * @param string $user
392
+     * @throws \OC\User\NoUserException if the user is not available
393
+     */
394
+    public static function initMountPoints($user = '') {
395
+        if ($user == '') {
396
+            $user = \OC_User::getUser();
397
+        }
398
+        if ($user === null || $user === false || $user === '') {
399
+            throw new \OC\User\NoUserException('Attempted to initialize mount points for null user and no user in session');
400
+        }
401
+
402
+        if (isset(self::$usersSetup[$user])) {
403
+            return;
404
+        }
405
+
406
+        self::$usersSetup[$user] = true;
407
+
408
+        $userManager = \OC::$server->getUserManager();
409
+        $userObject = $userManager->get($user);
410
+
411
+        if (is_null($userObject)) {
412
+            \OCP\Util::writeLog('files', ' Backends provided no user object for ' . $user, \OCP\Util::ERROR);
413
+            // reset flag, this will make it possible to rethrow the exception if called again
414
+            unset(self::$usersSetup[$user]);
415
+            throw new \OC\User\NoUserException('Backends provided no user object for ' . $user);
416
+        }
417
+
418
+        $realUid = $userObject->getUID();
419
+        // workaround in case of different casings
420
+        if ($user !== $realUid) {
421
+            $stack = json_encode(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 50));
422
+            \OCP\Util::writeLog('files', 'initMountPoints() called with wrong user casing. This could be a bug. Expected: "' . $realUid . '" got "' . $user . '". Stack: ' . $stack, \OCP\Util::WARN);
423
+            $user = $realUid;
424
+
425
+            // again with the correct casing
426
+            if (isset(self::$usersSetup[$user])) {
427
+                return;
428
+            }
429
+
430
+            self::$usersSetup[$user] = true;
431
+        }
432
+
433
+        if (\OC::$server->getLockdownManager()->canAccessFilesystem()) {
434
+            /** @var \OC\Files\Config\MountProviderCollection $mountConfigManager */
435
+            $mountConfigManager = \OC::$server->getMountProviderCollection();
436
+
437
+            // home mounts are handled seperate since we need to ensure this is mounted before we call the other mount providers
438
+            $homeMount = $mountConfigManager->getHomeMountForUser($userObject);
439
+
440
+            self::getMountManager()->addMount($homeMount);
441
+
442
+            \OC\Files\Filesystem::getStorage($user);
443
+
444
+            // Chance to mount for other storages
445
+            if ($userObject) {
446
+                $mounts = $mountConfigManager->getMountsForUser($userObject);
447
+                array_walk($mounts, array(self::$mounts, 'addMount'));
448
+                $mounts[] = $homeMount;
449
+                $mountConfigManager->registerMounts($userObject, $mounts);
450
+            }
451
+
452
+            self::listenForNewMountProviders($mountConfigManager, $userManager);
453
+        } else {
454
+            self::getMountManager()->addMount(new MountPoint(
455
+                new NullStorage([]),
456
+                '/' . $user
457
+            ));
458
+            self::getMountManager()->addMount(new MountPoint(
459
+                new NullStorage([]),
460
+                '/' . $user . '/files'
461
+            ));
462
+        }
463
+        \OC_Hook::emit('OC_Filesystem', 'post_initMountPoints', array('user' => $user));
464
+    }
465
+
466
+    /**
467
+     * Get mounts from mount providers that are registered after setup
468
+     *
469
+     * @param MountProviderCollection $mountConfigManager
470
+     * @param IUserManager $userManager
471
+     */
472
+    private static function listenForNewMountProviders(MountProviderCollection $mountConfigManager, IUserManager $userManager) {
473
+        if (!self::$listeningForProviders) {
474
+            self::$listeningForProviders = true;
475
+            $mountConfigManager->listen('\OC\Files\Config', 'registerMountProvider', function (IMountProvider $provider) use ($userManager) {
476
+                foreach (Filesystem::$usersSetup as $user => $setup) {
477
+                    $userObject = $userManager->get($user);
478
+                    if ($userObject) {
479
+                        $mounts = $provider->getMountsForUser($userObject, Filesystem::getLoader());
480
+                        array_walk($mounts, array(self::$mounts, 'addMount'));
481
+                    }
482
+                }
483
+            });
484
+        }
485
+    }
486
+
487
+    /**
488
+     * get the default filesystem view
489
+     *
490
+     * @return View
491
+     */
492
+    static public function getView() {
493
+        return self::$defaultInstance;
494
+    }
495
+
496
+    /**
497
+     * tear down the filesystem, removing all storage providers
498
+     */
499
+    static public function tearDown() {
500
+        self::clearMounts();
501
+        self::$defaultInstance = null;
502
+    }
503
+
504
+    /**
505
+     * get the relative path of the root data directory for the current user
506
+     *
507
+     * @return string
508
+     *
509
+     * Returns path like /admin/files
510
+     */
511
+    static public function getRoot() {
512
+        if (!self::$defaultInstance) {
513
+            return null;
514
+        }
515
+        return self::$defaultInstance->getRoot();
516
+    }
517
+
518
+    /**
519
+     * clear all mounts and storage backends
520
+     */
521
+    public static function clearMounts() {
522
+        if (self::$mounts) {
523
+            self::$usersSetup = array();
524
+            self::$mounts->clear();
525
+        }
526
+    }
527
+
528
+    /**
529
+     * mount an \OC\Files\Storage\Storage in our virtual filesystem
530
+     *
531
+     * @param \OC\Files\Storage\Storage|string $class
532
+     * @param array $arguments
533
+     * @param string $mountpoint
534
+     */
535
+    static public function mount($class, $arguments, $mountpoint) {
536
+        if (!self::$mounts) {
537
+            \OC_Util::setupFS();
538
+        }
539
+        $mount = new Mount\MountPoint($class, $mountpoint, $arguments, self::getLoader());
540
+        self::$mounts->addMount($mount);
541
+    }
542
+
543
+    /**
544
+     * return the path to a local version of the file
545
+     * we need this because we can't know if a file is stored local or not from
546
+     * outside the filestorage and for some purposes a local file is needed
547
+     *
548
+     * @param string $path
549
+     * @return string
550
+     */
551
+    static public function getLocalFile($path) {
552
+        return self::$defaultInstance->getLocalFile($path);
553
+    }
554
+
555
+    /**
556
+     * @param string $path
557
+     * @return string
558
+     */
559
+    static public function getLocalFolder($path) {
560
+        return self::$defaultInstance->getLocalFolder($path);
561
+    }
562
+
563
+    /**
564
+     * return path to file which reflects one visible in browser
565
+     *
566
+     * @param string $path
567
+     * @return string
568
+     */
569
+    static public function getLocalPath($path) {
570
+        $datadir = \OC_User::getHome(\OC_User::getUser()) . '/files';
571
+        $newpath = $path;
572
+        if (strncmp($newpath, $datadir, strlen($datadir)) == 0) {
573
+            $newpath = substr($path, strlen($datadir));
574
+        }
575
+        return $newpath;
576
+    }
577
+
578
+    /**
579
+     * check if the requested path is valid
580
+     *
581
+     * @param string $path
582
+     * @return bool
583
+     */
584
+    static public function isValidPath($path) {
585
+        $path = self::normalizePath($path);
586
+        if (!$path || $path[0] !== '/') {
587
+            $path = '/' . $path;
588
+        }
589
+        if (strpos($path, '/../') !== false || strrchr($path, '/') === '/..') {
590
+            return false;
591
+        }
592
+        return true;
593
+    }
594
+
595
+    /**
596
+     * checks if a file is blacklisted for storage in the filesystem
597
+     * Listens to write and rename hooks
598
+     *
599
+     * @param array $data from hook
600
+     */
601
+    static public function isBlacklisted($data) {
602
+        if (isset($data['path'])) {
603
+            $path = $data['path'];
604
+        } else if (isset($data['newpath'])) {
605
+            $path = $data['newpath'];
606
+        }
607
+        if (isset($path)) {
608
+            if (self::isFileBlacklisted($path)) {
609
+                $data['run'] = false;
610
+            }
611
+        }
612
+    }
613
+
614
+    /**
615
+     * @param string $filename
616
+     * @return bool
617
+     */
618
+    static public function isFileBlacklisted($filename) {
619
+        $filename = self::normalizePath($filename);
620
+
621
+        $blacklist = \OC::$server->getConfig()->getSystemValue('blacklisted_files', array('.htaccess'));
622
+        $filename = strtolower(basename($filename));
623
+        return in_array($filename, $blacklist);
624
+    }
625
+
626
+    /**
627
+     * check if the directory should be ignored when scanning
628
+     * NOTE: the special directories . and .. would cause never ending recursion
629
+     *
630
+     * @param String $dir
631
+     * @return boolean
632
+     */
633
+    static public function isIgnoredDir($dir) {
634
+        if ($dir === '.' || $dir === '..') {
635
+            return true;
636
+        }
637
+        return false;
638
+    }
639
+
640
+    /**
641
+     * following functions are equivalent to their php builtin equivalents for arguments/return values.
642
+     */
643
+    static public function mkdir($path) {
644
+        return self::$defaultInstance->mkdir($path);
645
+    }
646
+
647
+    static public function rmdir($path) {
648
+        return self::$defaultInstance->rmdir($path);
649
+    }
650
+
651
+    static public function opendir($path) {
652
+        return self::$defaultInstance->opendir($path);
653
+    }
654
+
655
+    static public function readdir($path) {
656
+        return self::$defaultInstance->readdir($path);
657
+    }
658
+
659
+    static public function is_dir($path) {
660
+        return self::$defaultInstance->is_dir($path);
661
+    }
662
+
663
+    static public function is_file($path) {
664
+        return self::$defaultInstance->is_file($path);
665
+    }
666
+
667
+    static public function stat($path) {
668
+        return self::$defaultInstance->stat($path);
669
+    }
670
+
671
+    static public function filetype($path) {
672
+        return self::$defaultInstance->filetype($path);
673
+    }
674
+
675
+    static public function filesize($path) {
676
+        return self::$defaultInstance->filesize($path);
677
+    }
678
+
679
+    static public function readfile($path) {
680
+        return self::$defaultInstance->readfile($path);
681
+    }
682
+
683
+    static public function isCreatable($path) {
684
+        return self::$defaultInstance->isCreatable($path);
685
+    }
686
+
687
+    static public function isReadable($path) {
688
+        return self::$defaultInstance->isReadable($path);
689
+    }
690
+
691
+    static public function isUpdatable($path) {
692
+        return self::$defaultInstance->isUpdatable($path);
693
+    }
694
+
695
+    static public function isDeletable($path) {
696
+        return self::$defaultInstance->isDeletable($path);
697
+    }
698
+
699
+    static public function isSharable($path) {
700
+        return self::$defaultInstance->isSharable($path);
701
+    }
702
+
703
+    static public function file_exists($path) {
704
+        return self::$defaultInstance->file_exists($path);
705
+    }
706
+
707
+    static public function filemtime($path) {
708
+        return self::$defaultInstance->filemtime($path);
709
+    }
710
+
711
+    static public function touch($path, $mtime = null) {
712
+        return self::$defaultInstance->touch($path, $mtime);
713
+    }
714
+
715
+    /**
716
+     * @return string
717
+     */
718
+    static public function file_get_contents($path) {
719
+        return self::$defaultInstance->file_get_contents($path);
720
+    }
721
+
722
+    static public function file_put_contents($path, $data) {
723
+        return self::$defaultInstance->file_put_contents($path, $data);
724
+    }
725
+
726
+    static public function unlink($path) {
727
+        return self::$defaultInstance->unlink($path);
728
+    }
729
+
730
+    static public function rename($path1, $path2) {
731
+        return self::$defaultInstance->rename($path1, $path2);
732
+    }
733
+
734
+    static public function copy($path1, $path2) {
735
+        return self::$defaultInstance->copy($path1, $path2);
736
+    }
737
+
738
+    static public function fopen($path, $mode) {
739
+        return self::$defaultInstance->fopen($path, $mode);
740
+    }
741
+
742
+    /**
743
+     * @return string
744
+     */
745
+    static public function toTmpFile($path) {
746
+        return self::$defaultInstance->toTmpFile($path);
747
+    }
748
+
749
+    static public function fromTmpFile($tmpFile, $path) {
750
+        return self::$defaultInstance->fromTmpFile($tmpFile, $path);
751
+    }
752
+
753
+    static public function getMimeType($path) {
754
+        return self::$defaultInstance->getMimeType($path);
755
+    }
756
+
757
+    static public function hash($type, $path, $raw = false) {
758
+        return self::$defaultInstance->hash($type, $path, $raw);
759
+    }
760
+
761
+    static public function free_space($path = '/') {
762
+        return self::$defaultInstance->free_space($path);
763
+    }
764
+
765
+    static public function search($query) {
766
+        return self::$defaultInstance->search($query);
767
+    }
768
+
769
+    /**
770
+     * @param string $query
771
+     */
772
+    static public function searchByMime($query) {
773
+        return self::$defaultInstance->searchByMime($query);
774
+    }
775
+
776
+    /**
777
+     * @param string|int $tag name or tag id
778
+     * @param string $userId owner of the tags
779
+     * @return FileInfo[] array or file info
780
+     */
781
+    static public function searchByTag($tag, $userId) {
782
+        return self::$defaultInstance->searchByTag($tag, $userId);
783
+    }
784
+
785
+    /**
786
+     * check if a file or folder has been updated since $time
787
+     *
788
+     * @param string $path
789
+     * @param int $time
790
+     * @return bool
791
+     */
792
+    static public function hasUpdated($path, $time) {
793
+        return self::$defaultInstance->hasUpdated($path, $time);
794
+    }
795
+
796
+    /**
797
+     * Fix common problems with a file path
798
+     *
799
+     * @param string $path
800
+     * @param bool $stripTrailingSlash whether to strip the trailing slash
801
+     * @param bool $isAbsolutePath whether the given path is absolute
802
+     * @param bool $keepUnicode true to disable unicode normalization
803
+     * @return string
804
+     */
805
+    public static function normalizePath($path, $stripTrailingSlash = true, $isAbsolutePath = false, $keepUnicode = false) {
806
+        if (is_null(self::$normalizedPathCache)) {
807
+            self::$normalizedPathCache = new CappedMemoryCache();
808
+        }
809
+
810
+        /**
811
+         * FIXME: This is a workaround for existing classes and files which call
812
+         *        this function with another type than a valid string. This
813
+         *        conversion should get removed as soon as all existing
814
+         *        function calls have been fixed.
815
+         */
816
+        $path = (string)$path;
817
+
818
+        $cacheKey = json_encode([$path, $stripTrailingSlash, $isAbsolutePath, $keepUnicode]);
819
+
820
+        if (isset(self::$normalizedPathCache[$cacheKey])) {
821
+            return self::$normalizedPathCache[$cacheKey];
822
+        }
823
+
824
+        if ($path == '') {
825
+            return '/';
826
+        }
827
+
828
+        //normalize unicode if possible
829
+        if (!$keepUnicode) {
830
+            $path = \OC_Util::normalizeUnicode($path);
831
+        }
832
+
833
+        //no windows style slashes
834
+        $path = str_replace('\\', '/', $path);
835
+
836
+        //add leading slash
837
+        if ($path[0] !== '/') {
838
+            $path = '/' . $path;
839
+        }
840
+
841
+        // remove '/./'
842
+        // ugly, but str_replace() can't replace them all in one go
843
+        // as the replacement itself is part of the search string
844
+        // which will only be found during the next iteration
845
+        while (strpos($path, '/./') !== false) {
846
+            $path = str_replace('/./', '/', $path);
847
+        }
848
+        // remove sequences of slashes
849
+        $path = preg_replace('#/{2,}#', '/', $path);
850
+
851
+        //remove trailing slash
852
+        if ($stripTrailingSlash and strlen($path) > 1 and substr($path, -1, 1) === '/') {
853
+            $path = substr($path, 0, -1);
854
+        }
855
+
856
+        // remove trailing '/.'
857
+        if (substr($path, -2) == '/.') {
858
+            $path = substr($path, 0, -2);
859
+        }
860
+
861
+        $normalizedPath = $path;
862
+        self::$normalizedPathCache[$cacheKey] = $normalizedPath;
863
+
864
+        return $normalizedPath;
865
+    }
866
+
867
+    /**
868
+     * get the filesystem info
869
+     *
870
+     * @param string $path
871
+     * @param boolean $includeMountPoints whether to add mountpoint sizes,
872
+     * defaults to true
873
+     * @return \OC\Files\FileInfo|bool False if file does not exist
874
+     */
875
+    public static function getFileInfo($path, $includeMountPoints = true) {
876
+        return self::$defaultInstance->getFileInfo($path, $includeMountPoints);
877
+    }
878
+
879
+    /**
880
+     * change file metadata
881
+     *
882
+     * @param string $path
883
+     * @param array $data
884
+     * @return int
885
+     *
886
+     * returns the fileid of the updated file
887
+     */
888
+    public static function putFileInfo($path, $data) {
889
+        return self::$defaultInstance->putFileInfo($path, $data);
890
+    }
891
+
892
+    /**
893
+     * get the content of a directory
894
+     *
895
+     * @param string $directory path under datadirectory
896
+     * @param string $mimetype_filter limit returned content to this mimetype or mimepart
897
+     * @return \OC\Files\FileInfo[]
898
+     */
899
+    public static function getDirectoryContent($directory, $mimetype_filter = '') {
900
+        return self::$defaultInstance->getDirectoryContent($directory, $mimetype_filter);
901
+    }
902
+
903
+    /**
904
+     * Get the path of a file by id
905
+     *
906
+     * Note that the resulting path is not guaranteed to be unique for the id, multiple paths can point to the same file
907
+     *
908
+     * @param int $id
909
+     * @throws NotFoundException
910
+     * @return string
911
+     */
912
+    public static function getPath($id) {
913
+        return self::$defaultInstance->getPath($id);
914
+    }
915
+
916
+    /**
917
+     * Get the owner for a file or folder
918
+     *
919
+     * @param string $path
920
+     * @return string
921
+     */
922
+    public static function getOwner($path) {
923
+        return self::$defaultInstance->getOwner($path);
924
+    }
925
+
926
+    /**
927
+     * get the ETag for a file or folder
928
+     *
929
+     * @param string $path
930
+     * @return string
931
+     */
932
+    static public function getETag($path) {
933
+        return self::$defaultInstance->getETag($path);
934
+    }
935 935
 }
Please login to merge, or discard this patch.
Spacing   +10 added lines, -10 removed lines patch added patch discarded remove patch
@@ -409,17 +409,17 @@  discard block
 block discarded – undo
409 409
 		$userObject = $userManager->get($user);
410 410
 
411 411
 		if (is_null($userObject)) {
412
-			\OCP\Util::writeLog('files', ' Backends provided no user object for ' . $user, \OCP\Util::ERROR);
412
+			\OCP\Util::writeLog('files', ' Backends provided no user object for '.$user, \OCP\Util::ERROR);
413 413
 			// reset flag, this will make it possible to rethrow the exception if called again
414 414
 			unset(self::$usersSetup[$user]);
415
-			throw new \OC\User\NoUserException('Backends provided no user object for ' . $user);
415
+			throw new \OC\User\NoUserException('Backends provided no user object for '.$user);
416 416
 		}
417 417
 
418 418
 		$realUid = $userObject->getUID();
419 419
 		// workaround in case of different casings
420 420
 		if ($user !== $realUid) {
421 421
 			$stack = json_encode(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 50));
422
-			\OCP\Util::writeLog('files', 'initMountPoints() called with wrong user casing. This could be a bug. Expected: "' . $realUid . '" got "' . $user . '". Stack: ' . $stack, \OCP\Util::WARN);
422
+			\OCP\Util::writeLog('files', 'initMountPoints() called with wrong user casing. This could be a bug. Expected: "'.$realUid.'" got "'.$user.'". Stack: '.$stack, \OCP\Util::WARN);
423 423
 			$user = $realUid;
424 424
 
425 425
 			// again with the correct casing
@@ -453,11 +453,11 @@  discard block
 block discarded – undo
453 453
 		} else {
454 454
 			self::getMountManager()->addMount(new MountPoint(
455 455
 				new NullStorage([]),
456
-				'/' . $user
456
+				'/'.$user
457 457
 			));
458 458
 			self::getMountManager()->addMount(new MountPoint(
459 459
 				new NullStorage([]),
460
-				'/' . $user . '/files'
460
+				'/'.$user.'/files'
461 461
 			));
462 462
 		}
463 463
 		\OC_Hook::emit('OC_Filesystem', 'post_initMountPoints', array('user' => $user));
@@ -472,7 +472,7 @@  discard block
 block discarded – undo
472 472
 	private static function listenForNewMountProviders(MountProviderCollection $mountConfigManager, IUserManager $userManager) {
473 473
 		if (!self::$listeningForProviders) {
474 474
 			self::$listeningForProviders = true;
475
-			$mountConfigManager->listen('\OC\Files\Config', 'registerMountProvider', function (IMountProvider $provider) use ($userManager) {
475
+			$mountConfigManager->listen('\OC\Files\Config', 'registerMountProvider', function(IMountProvider $provider) use ($userManager) {
476 476
 				foreach (Filesystem::$usersSetup as $user => $setup) {
477 477
 					$userObject = $userManager->get($user);
478 478
 					if ($userObject) {
@@ -567,7 +567,7 @@  discard block
 block discarded – undo
567 567
 	 * @return string
568 568
 	 */
569 569
 	static public function getLocalPath($path) {
570
-		$datadir = \OC_User::getHome(\OC_User::getUser()) . '/files';
570
+		$datadir = \OC_User::getHome(\OC_User::getUser()).'/files';
571 571
 		$newpath = $path;
572 572
 		if (strncmp($newpath, $datadir, strlen($datadir)) == 0) {
573 573
 			$newpath = substr($path, strlen($datadir));
@@ -584,7 +584,7 @@  discard block
 block discarded – undo
584 584
 	static public function isValidPath($path) {
585 585
 		$path = self::normalizePath($path);
586 586
 		if (!$path || $path[0] !== '/') {
587
-			$path = '/' . $path;
587
+			$path = '/'.$path;
588 588
 		}
589 589
 		if (strpos($path, '/../') !== false || strrchr($path, '/') === '/..') {
590 590
 			return false;
@@ -813,7 +813,7 @@  discard block
 block discarded – undo
813 813
 		 *        conversion should get removed as soon as all existing
814 814
 		 *        function calls have been fixed.
815 815
 		 */
816
-		$path = (string)$path;
816
+		$path = (string) $path;
817 817
 
818 818
 		$cacheKey = json_encode([$path, $stripTrailingSlash, $isAbsolutePath, $keepUnicode]);
819 819
 
@@ -835,7 +835,7 @@  discard block
 block discarded – undo
835 835
 
836 836
 		//add leading slash
837 837
 		if ($path[0] !== '/') {
838
-			$path = '/' . $path;
838
+			$path = '/'.$path;
839 839
 		}
840 840
 
841 841
 		// remove '/./'
Please login to merge, or discard this patch.
lib/private/Files/Storage/Wrapper/Encryption.php 3 patches
Doc Comments   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -984,7 +984,7 @@  discard block
 block discarded – undo
984 984
 	/**
985 985
 	 * check if path points to a files version
986 986
 	 *
987
-	 * @param $path
987
+	 * @param string $path
988 988
 	 * @return bool
989 989
 	 */
990 990
 	protected function isVersion($path) {
@@ -995,7 +995,7 @@  discard block
 block discarded – undo
995 995
 	/**
996 996
 	 * check if the given storage should be encrypted or not
997 997
 	 *
998
-	 * @param $path
998
+	 * @param string $path
999 999
 	 * @return bool
1000 1000
 	 */
1001 1001
 	protected function shouldEncrypt($path) {
Please login to merge, or discard this patch.
Indentation   +972 added lines, -972 removed lines patch added patch discarded remove patch
@@ -46,977 +46,977 @@
 block discarded – undo
46 46
 
47 47
 class Encryption extends Wrapper {
48 48
 
49
-	use LocalTempFileTrait;
50
-
51
-	/** @var string */
52
-	private $mountPoint;
53
-
54
-	/** @var \OC\Encryption\Util */
55
-	private $util;
56
-
57
-	/** @var \OCP\Encryption\IManager */
58
-	private $encryptionManager;
59
-
60
-	/** @var \OCP\ILogger */
61
-	private $logger;
62
-
63
-	/** @var string */
64
-	private $uid;
65
-
66
-	/** @var array */
67
-	protected $unencryptedSize;
68
-
69
-	/** @var \OCP\Encryption\IFile */
70
-	private $fileHelper;
71
-
72
-	/** @var IMountPoint */
73
-	private $mount;
74
-
75
-	/** @var IStorage */
76
-	private $keyStorage;
77
-
78
-	/** @var Update */
79
-	private $update;
80
-
81
-	/** @var Manager */
82
-	private $mountManager;
83
-
84
-	/** @var array remember for which path we execute the repair step to avoid recursions */
85
-	private $fixUnencryptedSizeOf = array();
86
-
87
-	/** @var  ArrayCache */
88
-	private $arrayCache;
89
-
90
-	/**
91
-	 * @param array $parameters
92
-	 * @param IManager $encryptionManager
93
-	 * @param Util $util
94
-	 * @param ILogger $logger
95
-	 * @param IFile $fileHelper
96
-	 * @param string $uid
97
-	 * @param IStorage $keyStorage
98
-	 * @param Update $update
99
-	 * @param Manager $mountManager
100
-	 * @param ArrayCache $arrayCache
101
-	 */
102
-	public function __construct(
103
-			$parameters,
104
-			IManager $encryptionManager = null,
105
-			Util $util = null,
106
-			ILogger $logger = null,
107
-			IFile $fileHelper = null,
108
-			$uid = null,
109
-			IStorage $keyStorage = null,
110
-			Update $update = null,
111
-			Manager $mountManager = null,
112
-			ArrayCache $arrayCache = null
113
-		) {
114
-
115
-		$this->mountPoint = $parameters['mountPoint'];
116
-		$this->mount = $parameters['mount'];
117
-		$this->encryptionManager = $encryptionManager;
118
-		$this->util = $util;
119
-		$this->logger = $logger;
120
-		$this->uid = $uid;
121
-		$this->fileHelper = $fileHelper;
122
-		$this->keyStorage = $keyStorage;
123
-		$this->unencryptedSize = array();
124
-		$this->update = $update;
125
-		$this->mountManager = $mountManager;
126
-		$this->arrayCache = $arrayCache;
127
-		parent::__construct($parameters);
128
-	}
129
-
130
-	/**
131
-	 * see http://php.net/manual/en/function.filesize.php
132
-	 * The result for filesize when called on a folder is required to be 0
133
-	 *
134
-	 * @param string $path
135
-	 * @return int
136
-	 */
137
-	public function filesize($path) {
138
-		$fullPath = $this->getFullPath($path);
139
-
140
-		/** @var CacheEntry $info */
141
-		$info = $this->getCache()->get($path);
142
-		if (isset($this->unencryptedSize[$fullPath])) {
143
-			$size = $this->unencryptedSize[$fullPath];
144
-			// update file cache
145
-			if ($info instanceof ICacheEntry) {
146
-				$info = $info->getData();
147
-				$info['encrypted'] = $info['encryptedVersion'];
148
-			} else {
149
-				if (!is_array($info)) {
150
-					$info = [];
151
-				}
152
-				$info['encrypted'] = true;
153
-			}
154
-
155
-			$info['size'] = $size;
156
-			$this->getCache()->put($path, $info);
157
-
158
-			return $size;
159
-		}
160
-
161
-		if (isset($info['fileid']) && $info['encrypted']) {
162
-			return $this->verifyUnencryptedSize($path, $info['size']);
163
-		}
164
-
165
-		return $this->storage->filesize($path);
166
-	}
167
-
168
-	/**
169
-	 * @param string $path
170
-	 * @return array
171
-	 */
172
-	public function getMetaData($path) {
173
-		$data = $this->storage->getMetaData($path);
174
-		if (is_null($data)) {
175
-			return null;
176
-		}
177
-		$fullPath = $this->getFullPath($path);
178
-		$info = $this->getCache()->get($path);
179
-
180
-		if (isset($this->unencryptedSize[$fullPath])) {
181
-			$data['encrypted'] = true;
182
-			$data['size'] = $this->unencryptedSize[$fullPath];
183
-		} else {
184
-			if (isset($info['fileid']) && $info['encrypted']) {
185
-				$data['size'] = $this->verifyUnencryptedSize($path, $info['size']);
186
-				$data['encrypted'] = true;
187
-			}
188
-		}
189
-
190
-		if (isset($info['encryptedVersion']) && $info['encryptedVersion'] > 1) {
191
-			$data['encryptedVersion'] = $info['encryptedVersion'];
192
-		}
193
-
194
-		return $data;
195
-	}
196
-
197
-	/**
198
-	 * see http://php.net/manual/en/function.file_get_contents.php
199
-	 *
200
-	 * @param string $path
201
-	 * @return string
202
-	 */
203
-	public function file_get_contents($path) {
204
-
205
-		$encryptionModule = $this->getEncryptionModule($path);
206
-
207
-		if ($encryptionModule) {
208
-			$handle = $this->fopen($path, "r");
209
-			if (!$handle) {
210
-				return false;
211
-			}
212
-			$data = stream_get_contents($handle);
213
-			fclose($handle);
214
-			return $data;
215
-		}
216
-		return $this->storage->file_get_contents($path);
217
-	}
218
-
219
-	/**
220
-	 * see http://php.net/manual/en/function.file_put_contents.php
221
-	 *
222
-	 * @param string $path
223
-	 * @param string $data
224
-	 * @return bool
225
-	 */
226
-	public function file_put_contents($path, $data) {
227
-		// file put content will always be translated to a stream write
228
-		$handle = $this->fopen($path, 'w');
229
-		if (is_resource($handle)) {
230
-			$written = fwrite($handle, $data);
231
-			fclose($handle);
232
-			return $written;
233
-		}
234
-
235
-		return false;
236
-	}
237
-
238
-	/**
239
-	 * see http://php.net/manual/en/function.unlink.php
240
-	 *
241
-	 * @param string $path
242
-	 * @return bool
243
-	 */
244
-	public function unlink($path) {
245
-		$fullPath = $this->getFullPath($path);
246
-		if ($this->util->isExcluded($fullPath)) {
247
-			return $this->storage->unlink($path);
248
-		}
249
-
250
-		$encryptionModule = $this->getEncryptionModule($path);
251
-		if ($encryptionModule) {
252
-			$this->keyStorage->deleteAllFileKeys($this->getFullPath($path));
253
-		}
254
-
255
-		return $this->storage->unlink($path);
256
-	}
257
-
258
-	/**
259
-	 * see http://php.net/manual/en/function.rename.php
260
-	 *
261
-	 * @param string $path1
262
-	 * @param string $path2
263
-	 * @return bool
264
-	 */
265
-	public function rename($path1, $path2) {
266
-
267
-		$result = $this->storage->rename($path1, $path2);
268
-
269
-		if ($result &&
270
-			// versions always use the keys from the original file, so we can skip
271
-			// this step for versions
272
-			$this->isVersion($path2) === false &&
273
-			$this->encryptionManager->isEnabled()) {
274
-			$source = $this->getFullPath($path1);
275
-			if (!$this->util->isExcluded($source)) {
276
-				$target = $this->getFullPath($path2);
277
-				if (isset($this->unencryptedSize[$source])) {
278
-					$this->unencryptedSize[$target] = $this->unencryptedSize[$source];
279
-				}
280
-				$this->keyStorage->renameKeys($source, $target);
281
-				$module = $this->getEncryptionModule($path2);
282
-				if ($module) {
283
-					$module->update($target, $this->uid, []);
284
-				}
285
-			}
286
-		}
287
-
288
-		return $result;
289
-	}
290
-
291
-	/**
292
-	 * see http://php.net/manual/en/function.rmdir.php
293
-	 *
294
-	 * @param string $path
295
-	 * @return bool
296
-	 */
297
-	public function rmdir($path) {
298
-		$result = $this->storage->rmdir($path);
299
-		$fullPath = $this->getFullPath($path);
300
-		if ($result &&
301
-			$this->util->isExcluded($fullPath) === false &&
302
-			$this->encryptionManager->isEnabled()
303
-		) {
304
-			$this->keyStorage->deleteAllFileKeys($fullPath);
305
-		}
306
-
307
-		return $result;
308
-	}
309
-
310
-	/**
311
-	 * check if a file can be read
312
-	 *
313
-	 * @param string $path
314
-	 * @return bool
315
-	 */
316
-	public function isReadable($path) {
317
-
318
-		$isReadable = true;
319
-
320
-		$metaData = $this->getMetaData($path);
321
-		if (
322
-			!$this->is_dir($path) &&
323
-			isset($metaData['encrypted']) &&
324
-			$metaData['encrypted'] === true
325
-		) {
326
-			$fullPath = $this->getFullPath($path);
327
-			$module = $this->getEncryptionModule($path);
328
-			$isReadable = $module->isReadable($fullPath, $this->uid);
329
-		}
330
-
331
-		return $this->storage->isReadable($path) && $isReadable;
332
-	}
333
-
334
-	/**
335
-	 * see http://php.net/manual/en/function.copy.php
336
-	 *
337
-	 * @param string $path1
338
-	 * @param string $path2
339
-	 * @return bool
340
-	 */
341
-	public function copy($path1, $path2) {
342
-
343
-		$source = $this->getFullPath($path1);
344
-
345
-		if ($this->util->isExcluded($source)) {
346
-			return $this->storage->copy($path1, $path2);
347
-		}
348
-
349
-		// need to stream copy file by file in case we copy between a encrypted
350
-		// and a unencrypted storage
351
-		$this->unlink($path2);
352
-		$result = $this->copyFromStorage($this, $path1, $path2);
353
-
354
-		return $result;
355
-	}
356
-
357
-	/**
358
-	 * see http://php.net/manual/en/function.fopen.php
359
-	 *
360
-	 * @param string $path
361
-	 * @param string $mode
362
-	 * @return resource|bool
363
-	 * @throws GenericEncryptionException
364
-	 * @throws ModuleDoesNotExistsException
365
-	 */
366
-	public function fopen($path, $mode) {
367
-
368
-		// check if the file is stored in the array cache, this means that we
369
-		// copy a file over to the versions folder, in this case we don't want to
370
-		// decrypt it
371
-		if ($this->arrayCache->hasKey('encryption_copy_version_' . $path)) {
372
-			$this->arrayCache->remove('encryption_copy_version_' . $path);
373
-			return $this->storage->fopen($path, $mode);
374
-		}
375
-
376
-		$encryptionEnabled = $this->encryptionManager->isEnabled();
377
-		$shouldEncrypt = false;
378
-		$encryptionModule = null;
379
-		$header = $this->getHeader($path);
380
-		$signed = (isset($header['signed']) && $header['signed'] === 'true') ? true : false;
381
-		$fullPath = $this->getFullPath($path);
382
-		$encryptionModuleId = $this->util->getEncryptionModuleId($header);
383
-
384
-		if ($this->util->isExcluded($fullPath) === false) {
385
-
386
-			$size = $unencryptedSize = 0;
387
-			$realFile = $this->util->stripPartialFileExtension($path);
388
-			$targetExists = $this->file_exists($realFile) || $this->file_exists($path);
389
-			$targetIsEncrypted = false;
390
-			if ($targetExists) {
391
-				// in case the file exists we require the explicit module as
392
-				// specified in the file header - otherwise we need to fail hard to
393
-				// prevent data loss on client side
394
-				if (!empty($encryptionModuleId)) {
395
-					$targetIsEncrypted = true;
396
-					$encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
397
-				}
398
-
399
-				if ($this->file_exists($path)) {
400
-					$size = $this->storage->filesize($path);
401
-					$unencryptedSize = $this->filesize($path);
402
-				} else {
403
-					$size = $unencryptedSize = 0;
404
-				}
405
-			}
406
-
407
-			try {
408
-
409
-				if (
410
-					$mode === 'w'
411
-					|| $mode === 'w+'
412
-					|| $mode === 'wb'
413
-					|| $mode === 'wb+'
414
-				) {
415
-					// don't overwrite encrypted files if encryption is not enabled
416
-					if ($targetIsEncrypted && $encryptionEnabled === false) {
417
-						throw new GenericEncryptionException('Tried to access encrypted file but encryption is not enabled');
418
-					}
419
-					if ($encryptionEnabled) {
420
-						// if $encryptionModuleId is empty, the default module will be used
421
-						$encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
422
-						$shouldEncrypt = $encryptionModule->shouldEncrypt($fullPath);
423
-						$signed = true;
424
-					}
425
-				} else {
426
-					$info = $this->getCache()->get($path);
427
-					// only get encryption module if we found one in the header
428
-					// or if file should be encrypted according to the file cache
429
-					if (!empty($encryptionModuleId)) {
430
-						$encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
431
-						$shouldEncrypt = true;
432
-					} else if (empty($encryptionModuleId) && $info['encrypted'] === true) {
433
-						// we come from a old installation. No header and/or no module defined
434
-						// but the file is encrypted. In this case we need to use the
435
-						// OC_DEFAULT_MODULE to read the file
436
-						$encryptionModule = $this->encryptionManager->getEncryptionModule('OC_DEFAULT_MODULE');
437
-						$shouldEncrypt = true;
438
-						$targetIsEncrypted = true;
439
-					}
440
-				}
441
-			} catch (ModuleDoesNotExistsException $e) {
442
-				$this->logger->warning('Encryption module "' . $encryptionModuleId .
443
-					'" not found, file will be stored unencrypted (' . $e->getMessage() . ')');
444
-			}
445
-
446
-			// encryption disabled on write of new file and write to existing unencrypted file -> don't encrypt
447
-			if (!$encryptionEnabled || !$this->shouldEncrypt($path)) {
448
-				if (!$targetExists || !$targetIsEncrypted) {
449
-					$shouldEncrypt = false;
450
-				}
451
-			}
452
-
453
-			if ($shouldEncrypt === true && $encryptionModule !== null) {
454
-				$headerSize = $this->getHeaderSize($path);
455
-				$source = $this->storage->fopen($path, $mode);
456
-				if (!is_resource($source)) {
457
-					return false;
458
-				}
459
-				$handle = \OC\Files\Stream\Encryption::wrap($source, $path, $fullPath, $header,
460
-					$this->uid, $encryptionModule, $this->storage, $this, $this->util, $this->fileHelper, $mode,
461
-					$size, $unencryptedSize, $headerSize, $signed);
462
-				return $handle;
463
-			}
464
-
465
-		}
466
-
467
-		return $this->storage->fopen($path, $mode);
468
-	}
469
-
470
-
471
-	/**
472
-	 * perform some plausibility checks if the the unencrypted size is correct.
473
-	 * If not, we calculate the correct unencrypted size and return it
474
-	 *
475
-	 * @param string $path internal path relative to the storage root
476
-	 * @param int $unencryptedSize size of the unencrypted file
477
-	 *
478
-	 * @return int unencrypted size
479
-	 */
480
-	protected function verifyUnencryptedSize($path, $unencryptedSize) {
481
-
482
-		$size = $this->storage->filesize($path);
483
-		$result = $unencryptedSize;
484
-
485
-		if ($unencryptedSize < 0 ||
486
-			($size > 0 && $unencryptedSize === $size)
487
-		) {
488
-			// check if we already calculate the unencrypted size for the
489
-			// given path to avoid recursions
490
-			if (isset($this->fixUnencryptedSizeOf[$this->getFullPath($path)]) === false) {
491
-				$this->fixUnencryptedSizeOf[$this->getFullPath($path)] = true;
492
-				try {
493
-					$result = $this->fixUnencryptedSize($path, $size, $unencryptedSize);
494
-				} catch (\Exception $e) {
495
-					$this->logger->error('Couldn\'t re-calculate unencrypted size for '. $path);
496
-					$this->logger->logException($e);
497
-				}
498
-				unset($this->fixUnencryptedSizeOf[$this->getFullPath($path)]);
499
-			}
500
-		}
501
-
502
-		return $result;
503
-	}
504
-
505
-	/**
506
-	 * calculate the unencrypted size
507
-	 *
508
-	 * @param string $path internal path relative to the storage root
509
-	 * @param int $size size of the physical file
510
-	 * @param int $unencryptedSize size of the unencrypted file
511
-	 *
512
-	 * @return int calculated unencrypted size
513
-	 */
514
-	protected function fixUnencryptedSize($path, $size, $unencryptedSize) {
515
-
516
-		$headerSize = $this->getHeaderSize($path);
517
-		$header = $this->getHeader($path);
518
-		$encryptionModule = $this->getEncryptionModule($path);
519
-
520
-		$stream = $this->storage->fopen($path, 'r');
521
-
522
-		// if we couldn't open the file we return the old unencrypted size
523
-		if (!is_resource($stream)) {
524
-			$this->logger->error('Could not open ' . $path . '. Recalculation of unencrypted size aborted.');
525
-			return $unencryptedSize;
526
-		}
527
-
528
-		$newUnencryptedSize = 0;
529
-		$size -= $headerSize;
530
-		$blockSize = $this->util->getBlockSize();
531
-
532
-		// if a header exists we skip it
533
-		if ($headerSize > 0) {
534
-			fread($stream, $headerSize);
535
-		}
536
-
537
-		// fast path, else the calculation for $lastChunkNr is bogus
538
-		if ($size === 0) {
539
-			return 0;
540
-		}
541
-
542
-		$signed = (isset($header['signed']) && $header['signed'] === 'true') ? true : false;
543
-		$unencryptedBlockSize = $encryptionModule->getUnencryptedBlockSize($signed);
544
-
545
-		// calculate last chunk nr
546
-		// next highest is end of chunks, one subtracted is last one
547
-		// we have to read the last chunk, we can't just calculate it (because of padding etc)
548
-
549
-		$lastChunkNr = ceil($size/ $blockSize)-1;
550
-		// calculate last chunk position
551
-		$lastChunkPos = ($lastChunkNr * $blockSize);
552
-		// try to fseek to the last chunk, if it fails we have to read the whole file
553
-		if (@fseek($stream, $lastChunkPos, SEEK_CUR) === 0) {
554
-			$newUnencryptedSize += $lastChunkNr * $unencryptedBlockSize;
555
-		}
556
-
557
-		$lastChunkContentEncrypted='';
558
-		$count = $blockSize;
559
-
560
-		while ($count > 0) {
561
-			$data=fread($stream, $blockSize);
562
-			$count=strlen($data);
563
-			$lastChunkContentEncrypted .= $data;
564
-			if(strlen($lastChunkContentEncrypted) > $blockSize) {
565
-				$newUnencryptedSize += $unencryptedBlockSize;
566
-				$lastChunkContentEncrypted=substr($lastChunkContentEncrypted, $blockSize);
567
-			}
568
-		}
569
-
570
-		fclose($stream);
571
-
572
-		// we have to decrypt the last chunk to get it actual size
573
-		$encryptionModule->begin($this->getFullPath($path), $this->uid, 'r', $header, []);
574
-		$decryptedLastChunk = $encryptionModule->decrypt($lastChunkContentEncrypted, $lastChunkNr . 'end');
575
-		$decryptedLastChunk .= $encryptionModule->end($this->getFullPath($path), $lastChunkNr . 'end');
576
-
577
-		// calc the real file size with the size of the last chunk
578
-		$newUnencryptedSize += strlen($decryptedLastChunk);
579
-
580
-		$this->updateUnencryptedSize($this->getFullPath($path), $newUnencryptedSize);
581
-
582
-		// write to cache if applicable
583
-		$cache = $this->storage->getCache();
584
-		if ($cache) {
585
-			$entry = $cache->get($path);
586
-			$cache->update($entry['fileid'], ['size' => $newUnencryptedSize]);
587
-		}
588
-
589
-		return $newUnencryptedSize;
590
-	}
591
-
592
-	/**
593
-	 * @param Storage $sourceStorage
594
-	 * @param string $sourceInternalPath
595
-	 * @param string $targetInternalPath
596
-	 * @param bool $preserveMtime
597
-	 * @return bool
598
-	 */
599
-	public function moveFromStorage(Storage $sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime = true) {
600
-		if ($sourceStorage === $this) {
601
-			return $this->rename($sourceInternalPath, $targetInternalPath);
602
-		}
603
-
604
-		// TODO clean this up once the underlying moveFromStorage in OC\Files\Storage\Wrapper\Common is fixed:
605
-		// - call $this->storage->moveFromStorage() instead of $this->copyBetweenStorage
606
-		// - copy the file cache update from  $this->copyBetweenStorage to this method
607
-		// - copy the copyKeys() call from  $this->copyBetweenStorage to this method
608
-		// - remove $this->copyBetweenStorage
609
-
610
-		if (!$sourceStorage->isDeletable($sourceInternalPath)) {
611
-			return false;
612
-		}
613
-
614
-		$result = $this->copyBetweenStorage($sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime, true);
615
-		if ($result) {
616
-			if ($sourceStorage->is_dir($sourceInternalPath)) {
617
-				$result &= $sourceStorage->rmdir($sourceInternalPath);
618
-			} else {
619
-				$result &= $sourceStorage->unlink($sourceInternalPath);
620
-			}
621
-		}
622
-		return $result;
623
-	}
624
-
625
-
626
-	/**
627
-	 * @param Storage $sourceStorage
628
-	 * @param string $sourceInternalPath
629
-	 * @param string $targetInternalPath
630
-	 * @param bool $preserveMtime
631
-	 * @param bool $isRename
632
-	 * @return bool
633
-	 */
634
-	public function copyFromStorage(Storage $sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime = false, $isRename = false) {
635
-
636
-		// TODO clean this up once the underlying moveFromStorage in OC\Files\Storage\Wrapper\Common is fixed:
637
-		// - call $this->storage->copyFromStorage() instead of $this->copyBetweenStorage
638
-		// - copy the file cache update from  $this->copyBetweenStorage to this method
639
-		// - copy the copyKeys() call from  $this->copyBetweenStorage to this method
640
-		// - remove $this->copyBetweenStorage
641
-
642
-		return $this->copyBetweenStorage($sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime, $isRename);
643
-	}
644
-
645
-	/**
646
-	 * Update the encrypted cache version in the database
647
-	 *
648
-	 * @param Storage $sourceStorage
649
-	 * @param string $sourceInternalPath
650
-	 * @param string $targetInternalPath
651
-	 * @param bool $isRename
652
-	 */
653
-	private function updateEncryptedVersion(Storage $sourceStorage, $sourceInternalPath, $targetInternalPath, $isRename) {
654
-		$isEncrypted = $this->encryptionManager->isEnabled() && $this->shouldEncrypt($targetInternalPath) ? 1 : 0;
655
-		$cacheInformation = [
656
-			'encrypted' => (bool)$isEncrypted,
657
-		];
658
-		if($isEncrypted === 1) {
659
-			$encryptedVersion = $sourceStorage->getCache()->get($sourceInternalPath)['encryptedVersion'];
660
-
661
-			// In case of a move operation from an unencrypted to an encrypted
662
-			// storage the old encrypted version would stay with "0" while the
663
-			// correct value would be "1". Thus we manually set the value to "1"
664
-			// for those cases.
665
-			// See also https://github.com/owncloud/core/issues/23078
666
-			if($encryptedVersion === 0) {
667
-				$encryptedVersion = 1;
668
-			}
669
-
670
-			$cacheInformation['encryptedVersion'] = $encryptedVersion;
671
-		}
672
-
673
-		// in case of a rename we need to manipulate the source cache because
674
-		// this information will be kept for the new target
675
-		if ($isRename) {
676
-			$sourceStorage->getCache()->put($sourceInternalPath, $cacheInformation);
677
-		} else {
678
-			$this->getCache()->put($targetInternalPath, $cacheInformation);
679
-		}
680
-	}
681
-
682
-	/**
683
-	 * copy file between two storages
684
-	 *
685
-	 * @param Storage $sourceStorage
686
-	 * @param string $sourceInternalPath
687
-	 * @param string $targetInternalPath
688
-	 * @param bool $preserveMtime
689
-	 * @param bool $isRename
690
-	 * @return bool
691
-	 * @throws \Exception
692
-	 */
693
-	private function copyBetweenStorage(Storage $sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime, $isRename) {
694
-
695
-		// for versions we have nothing to do, because versions should always use the
696
-		// key from the original file. Just create a 1:1 copy and done
697
-		if ($this->isVersion($targetInternalPath) ||
698
-			$this->isVersion($sourceInternalPath)) {
699
-			// remember that we try to create a version so that we can detect it during
700
-			// fopen($sourceInternalPath) and by-pass the encryption in order to
701
-			// create a 1:1 copy of the file
702
-			$this->arrayCache->set('encryption_copy_version_' . $sourceInternalPath, true);
703
-			$result = $this->storage->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
704
-			$this->arrayCache->remove('encryption_copy_version_' . $sourceInternalPath);
705
-			if ($result) {
706
-				$info = $this->getCache('', $sourceStorage)->get($sourceInternalPath);
707
-				// make sure that we update the unencrypted size for the version
708
-				if (isset($info['encrypted']) && $info['encrypted'] === true) {
709
-					$this->updateUnencryptedSize(
710
-						$this->getFullPath($targetInternalPath),
711
-						$info['size']
712
-					);
713
-				}
714
-				$this->updateEncryptedVersion($sourceStorage, $sourceInternalPath, $targetInternalPath, $isRename);
715
-			}
716
-			return $result;
717
-		}
718
-
719
-		// first copy the keys that we reuse the existing file key on the target location
720
-		// and don't create a new one which would break versions for example.
721
-		$mount = $this->mountManager->findByStorageId($sourceStorage->getId());
722
-		if (count($mount) === 1) {
723
-			$mountPoint = $mount[0]->getMountPoint();
724
-			$source = $mountPoint . '/' . $sourceInternalPath;
725
-			$target = $this->getFullPath($targetInternalPath);
726
-			$this->copyKeys($source, $target);
727
-		} else {
728
-			$this->logger->error('Could not find mount point, can\'t keep encryption keys');
729
-		}
730
-
731
-		if ($sourceStorage->is_dir($sourceInternalPath)) {
732
-			$dh = $sourceStorage->opendir($sourceInternalPath);
733
-			$result = $this->mkdir($targetInternalPath);
734
-			if (is_resource($dh)) {
735
-				while ($result and ($file = readdir($dh)) !== false) {
736
-					if (!Filesystem::isIgnoredDir($file)) {
737
-						$result &= $this->copyFromStorage($sourceStorage, $sourceInternalPath . '/' . $file, $targetInternalPath . '/' . $file, false, $isRename);
738
-					}
739
-				}
740
-			}
741
-		} else {
742
-			try {
743
-				$source = $sourceStorage->fopen($sourceInternalPath, 'r');
744
-				$target = $this->fopen($targetInternalPath, 'w');
745
-				list(, $result) = \OC_Helper::streamCopy($source, $target);
746
-				fclose($source);
747
-				fclose($target);
748
-			} catch (\Exception $e) {
749
-				fclose($source);
750
-				fclose($target);
751
-				throw $e;
752
-			}
753
-			if($result) {
754
-				if ($preserveMtime) {
755
-					$this->touch($targetInternalPath, $sourceStorage->filemtime($sourceInternalPath));
756
-				}
757
-				$this->updateEncryptedVersion($sourceStorage, $sourceInternalPath, $targetInternalPath, $isRename);
758
-			} else {
759
-				// delete partially written target file
760
-				$this->unlink($targetInternalPath);
761
-				// delete cache entry that was created by fopen
762
-				$this->getCache()->remove($targetInternalPath);
763
-			}
764
-		}
765
-		return (bool)$result;
766
-
767
-	}
768
-
769
-	/**
770
-	 * get the path to a local version of the file.
771
-	 * The local version of the file can be temporary and doesn't have to be persistent across requests
772
-	 *
773
-	 * @param string $path
774
-	 * @return string
775
-	 */
776
-	public function getLocalFile($path) {
777
-		if ($this->encryptionManager->isEnabled()) {
778
-			$cachedFile = $this->getCachedFile($path);
779
-			if (is_string($cachedFile)) {
780
-				return $cachedFile;
781
-			}
782
-		}
783
-		return $this->storage->getLocalFile($path);
784
-	}
785
-
786
-	/**
787
-	 * Returns the wrapped storage's value for isLocal()
788
-	 *
789
-	 * @return bool wrapped storage's isLocal() value
790
-	 */
791
-	public function isLocal() {
792
-		if ($this->encryptionManager->isEnabled()) {
793
-			return false;
794
-		}
795
-		return $this->storage->isLocal();
796
-	}
797
-
798
-	/**
799
-	 * see http://php.net/manual/en/function.stat.php
800
-	 * only the following keys are required in the result: size and mtime
801
-	 *
802
-	 * @param string $path
803
-	 * @return array
804
-	 */
805
-	public function stat($path) {
806
-		$stat = $this->storage->stat($path);
807
-		$fileSize = $this->filesize($path);
808
-		$stat['size'] = $fileSize;
809
-		$stat[7] = $fileSize;
810
-		return $stat;
811
-	}
812
-
813
-	/**
814
-	 * see http://php.net/manual/en/function.hash.php
815
-	 *
816
-	 * @param string $type
817
-	 * @param string $path
818
-	 * @param bool $raw
819
-	 * @return string
820
-	 */
821
-	public function hash($type, $path, $raw = false) {
822
-		$fh = $this->fopen($path, 'rb');
823
-		$ctx = hash_init($type);
824
-		hash_update_stream($ctx, $fh);
825
-		fclose($fh);
826
-		return hash_final($ctx, $raw);
827
-	}
828
-
829
-	/**
830
-	 * return full path, including mount point
831
-	 *
832
-	 * @param string $path relative to mount point
833
-	 * @return string full path including mount point
834
-	 */
835
-	protected function getFullPath($path) {
836
-		return Filesystem::normalizePath($this->mountPoint . '/' . $path);
837
-	}
838
-
839
-	/**
840
-	 * read first block of encrypted file, typically this will contain the
841
-	 * encryption header
842
-	 *
843
-	 * @param string $path
844
-	 * @return string
845
-	 */
846
-	protected function readFirstBlock($path) {
847
-		$firstBlock = '';
848
-		if ($this->storage->file_exists($path)) {
849
-			$handle = $this->storage->fopen($path, 'r');
850
-			$firstBlock = fread($handle, $this->util->getHeaderSize());
851
-			fclose($handle);
852
-		}
853
-		return $firstBlock;
854
-	}
855
-
856
-	/**
857
-	 * return header size of given file
858
-	 *
859
-	 * @param string $path
860
-	 * @return int
861
-	 */
862
-	protected function getHeaderSize($path) {
863
-		$headerSize = 0;
864
-		$realFile = $this->util->stripPartialFileExtension($path);
865
-		if ($this->storage->file_exists($realFile)) {
866
-			$path = $realFile;
867
-		}
868
-		$firstBlock = $this->readFirstBlock($path);
869
-
870
-		if (substr($firstBlock, 0, strlen(Util::HEADER_START)) === Util::HEADER_START) {
871
-			$headerSize = $this->util->getHeaderSize();
872
-		}
873
-
874
-		return $headerSize;
875
-	}
876
-
877
-	/**
878
-	 * parse raw header to array
879
-	 *
880
-	 * @param string $rawHeader
881
-	 * @return array
882
-	 */
883
-	protected function parseRawHeader($rawHeader) {
884
-		$result = array();
885
-		if (substr($rawHeader, 0, strlen(Util::HEADER_START)) === Util::HEADER_START) {
886
-			$header = $rawHeader;
887
-			$endAt = strpos($header, Util::HEADER_END);
888
-			if ($endAt !== false) {
889
-				$header = substr($header, 0, $endAt + strlen(Util::HEADER_END));
890
-
891
-				// +1 to not start with an ':' which would result in empty element at the beginning
892
-				$exploded = explode(':', substr($header, strlen(Util::HEADER_START)+1));
893
-
894
-				$element = array_shift($exploded);
895
-				while ($element !== Util::HEADER_END) {
896
-					$result[$element] = array_shift($exploded);
897
-					$element = array_shift($exploded);
898
-				}
899
-			}
900
-		}
901
-
902
-		return $result;
903
-	}
904
-
905
-	/**
906
-	 * read header from file
907
-	 *
908
-	 * @param string $path
909
-	 * @return array
910
-	 */
911
-	protected function getHeader($path) {
912
-		$realFile = $this->util->stripPartialFileExtension($path);
913
-		if ($this->storage->file_exists($realFile)) {
914
-			$path = $realFile;
915
-		}
916
-
917
-		$firstBlock = $this->readFirstBlock($path);
918
-		$result = $this->parseRawHeader($firstBlock);
919
-
920
-		// if the header doesn't contain a encryption module we check if it is a
921
-		// legacy file. If true, we add the default encryption module
922
-		if (!isset($result[Util::HEADER_ENCRYPTION_MODULE_KEY])) {
923
-			if (!empty($result)) {
924
-				$result[Util::HEADER_ENCRYPTION_MODULE_KEY] = 'OC_DEFAULT_MODULE';
925
-			} else {
926
-				// if the header was empty we have to check first if it is a encrypted file at all
927
-				$info = $this->getCache()->get($path);
928
-				if (isset($info['encrypted']) && $info['encrypted'] === true) {
929
-					$result[Util::HEADER_ENCRYPTION_MODULE_KEY] = 'OC_DEFAULT_MODULE';
930
-				}
931
-			}
932
-		}
933
-
934
-		return $result;
935
-	}
936
-
937
-	/**
938
-	 * read encryption module needed to read/write the file located at $path
939
-	 *
940
-	 * @param string $path
941
-	 * @return null|\OCP\Encryption\IEncryptionModule
942
-	 * @throws ModuleDoesNotExistsException
943
-	 * @throws \Exception
944
-	 */
945
-	protected function getEncryptionModule($path) {
946
-		$encryptionModule = null;
947
-		$header = $this->getHeader($path);
948
-		$encryptionModuleId = $this->util->getEncryptionModuleId($header);
949
-		if (!empty($encryptionModuleId)) {
950
-			try {
951
-				$encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
952
-			} catch (ModuleDoesNotExistsException $e) {
953
-				$this->logger->critical('Encryption module defined in "' . $path . '" not loaded!');
954
-				throw $e;
955
-			}
956
-		}
957
-
958
-		return $encryptionModule;
959
-	}
960
-
961
-	/**
962
-	 * @param string $path
963
-	 * @param int $unencryptedSize
964
-	 */
965
-	public function updateUnencryptedSize($path, $unencryptedSize) {
966
-		$this->unencryptedSize[$path] = $unencryptedSize;
967
-	}
968
-
969
-	/**
970
-	 * copy keys to new location
971
-	 *
972
-	 * @param string $source path relative to data/
973
-	 * @param string $target path relative to data/
974
-	 * @return bool
975
-	 */
976
-	protected function copyKeys($source, $target) {
977
-		if (!$this->util->isExcluded($source)) {
978
-			return $this->keyStorage->copyKeys($source, $target);
979
-		}
980
-
981
-		return false;
982
-	}
983
-
984
-	/**
985
-	 * check if path points to a files version
986
-	 *
987
-	 * @param $path
988
-	 * @return bool
989
-	 */
990
-	protected function isVersion($path) {
991
-		$normalized = Filesystem::normalizePath($path);
992
-		return substr($normalized, 0, strlen('/files_versions/')) === '/files_versions/';
993
-	}
994
-
995
-	/**
996
-	 * check if the given storage should be encrypted or not
997
-	 *
998
-	 * @param $path
999
-	 * @return bool
1000
-	 */
1001
-	protected function shouldEncrypt($path) {
1002
-		$fullPath = $this->getFullPath($path);
1003
-		$mountPointConfig = $this->mount->getOption('encrypt', true);
1004
-		if ($mountPointConfig === false) {
1005
-			return false;
1006
-		}
1007
-
1008
-		try {
1009
-			$encryptionModule = $this->getEncryptionModule($fullPath);
1010
-		} catch (ModuleDoesNotExistsException $e) {
1011
-			return false;
1012
-		}
1013
-
1014
-		if ($encryptionModule === null) {
1015
-			$encryptionModule = $this->encryptionManager->getEncryptionModule();
1016
-		}
1017
-
1018
-		return $encryptionModule->shouldEncrypt($fullPath);
1019
-
1020
-	}
49
+    use LocalTempFileTrait;
50
+
51
+    /** @var string */
52
+    private $mountPoint;
53
+
54
+    /** @var \OC\Encryption\Util */
55
+    private $util;
56
+
57
+    /** @var \OCP\Encryption\IManager */
58
+    private $encryptionManager;
59
+
60
+    /** @var \OCP\ILogger */
61
+    private $logger;
62
+
63
+    /** @var string */
64
+    private $uid;
65
+
66
+    /** @var array */
67
+    protected $unencryptedSize;
68
+
69
+    /** @var \OCP\Encryption\IFile */
70
+    private $fileHelper;
71
+
72
+    /** @var IMountPoint */
73
+    private $mount;
74
+
75
+    /** @var IStorage */
76
+    private $keyStorage;
77
+
78
+    /** @var Update */
79
+    private $update;
80
+
81
+    /** @var Manager */
82
+    private $mountManager;
83
+
84
+    /** @var array remember for which path we execute the repair step to avoid recursions */
85
+    private $fixUnencryptedSizeOf = array();
86
+
87
+    /** @var  ArrayCache */
88
+    private $arrayCache;
89
+
90
+    /**
91
+     * @param array $parameters
92
+     * @param IManager $encryptionManager
93
+     * @param Util $util
94
+     * @param ILogger $logger
95
+     * @param IFile $fileHelper
96
+     * @param string $uid
97
+     * @param IStorage $keyStorage
98
+     * @param Update $update
99
+     * @param Manager $mountManager
100
+     * @param ArrayCache $arrayCache
101
+     */
102
+    public function __construct(
103
+            $parameters,
104
+            IManager $encryptionManager = null,
105
+            Util $util = null,
106
+            ILogger $logger = null,
107
+            IFile $fileHelper = null,
108
+            $uid = null,
109
+            IStorage $keyStorage = null,
110
+            Update $update = null,
111
+            Manager $mountManager = null,
112
+            ArrayCache $arrayCache = null
113
+        ) {
114
+
115
+        $this->mountPoint = $parameters['mountPoint'];
116
+        $this->mount = $parameters['mount'];
117
+        $this->encryptionManager = $encryptionManager;
118
+        $this->util = $util;
119
+        $this->logger = $logger;
120
+        $this->uid = $uid;
121
+        $this->fileHelper = $fileHelper;
122
+        $this->keyStorage = $keyStorage;
123
+        $this->unencryptedSize = array();
124
+        $this->update = $update;
125
+        $this->mountManager = $mountManager;
126
+        $this->arrayCache = $arrayCache;
127
+        parent::__construct($parameters);
128
+    }
129
+
130
+    /**
131
+     * see http://php.net/manual/en/function.filesize.php
132
+     * The result for filesize when called on a folder is required to be 0
133
+     *
134
+     * @param string $path
135
+     * @return int
136
+     */
137
+    public function filesize($path) {
138
+        $fullPath = $this->getFullPath($path);
139
+
140
+        /** @var CacheEntry $info */
141
+        $info = $this->getCache()->get($path);
142
+        if (isset($this->unencryptedSize[$fullPath])) {
143
+            $size = $this->unencryptedSize[$fullPath];
144
+            // update file cache
145
+            if ($info instanceof ICacheEntry) {
146
+                $info = $info->getData();
147
+                $info['encrypted'] = $info['encryptedVersion'];
148
+            } else {
149
+                if (!is_array($info)) {
150
+                    $info = [];
151
+                }
152
+                $info['encrypted'] = true;
153
+            }
154
+
155
+            $info['size'] = $size;
156
+            $this->getCache()->put($path, $info);
157
+
158
+            return $size;
159
+        }
160
+
161
+        if (isset($info['fileid']) && $info['encrypted']) {
162
+            return $this->verifyUnencryptedSize($path, $info['size']);
163
+        }
164
+
165
+        return $this->storage->filesize($path);
166
+    }
167
+
168
+    /**
169
+     * @param string $path
170
+     * @return array
171
+     */
172
+    public function getMetaData($path) {
173
+        $data = $this->storage->getMetaData($path);
174
+        if (is_null($data)) {
175
+            return null;
176
+        }
177
+        $fullPath = $this->getFullPath($path);
178
+        $info = $this->getCache()->get($path);
179
+
180
+        if (isset($this->unencryptedSize[$fullPath])) {
181
+            $data['encrypted'] = true;
182
+            $data['size'] = $this->unencryptedSize[$fullPath];
183
+        } else {
184
+            if (isset($info['fileid']) && $info['encrypted']) {
185
+                $data['size'] = $this->verifyUnencryptedSize($path, $info['size']);
186
+                $data['encrypted'] = true;
187
+            }
188
+        }
189
+
190
+        if (isset($info['encryptedVersion']) && $info['encryptedVersion'] > 1) {
191
+            $data['encryptedVersion'] = $info['encryptedVersion'];
192
+        }
193
+
194
+        return $data;
195
+    }
196
+
197
+    /**
198
+     * see http://php.net/manual/en/function.file_get_contents.php
199
+     *
200
+     * @param string $path
201
+     * @return string
202
+     */
203
+    public function file_get_contents($path) {
204
+
205
+        $encryptionModule = $this->getEncryptionModule($path);
206
+
207
+        if ($encryptionModule) {
208
+            $handle = $this->fopen($path, "r");
209
+            if (!$handle) {
210
+                return false;
211
+            }
212
+            $data = stream_get_contents($handle);
213
+            fclose($handle);
214
+            return $data;
215
+        }
216
+        return $this->storage->file_get_contents($path);
217
+    }
218
+
219
+    /**
220
+     * see http://php.net/manual/en/function.file_put_contents.php
221
+     *
222
+     * @param string $path
223
+     * @param string $data
224
+     * @return bool
225
+     */
226
+    public function file_put_contents($path, $data) {
227
+        // file put content will always be translated to a stream write
228
+        $handle = $this->fopen($path, 'w');
229
+        if (is_resource($handle)) {
230
+            $written = fwrite($handle, $data);
231
+            fclose($handle);
232
+            return $written;
233
+        }
234
+
235
+        return false;
236
+    }
237
+
238
+    /**
239
+     * see http://php.net/manual/en/function.unlink.php
240
+     *
241
+     * @param string $path
242
+     * @return bool
243
+     */
244
+    public function unlink($path) {
245
+        $fullPath = $this->getFullPath($path);
246
+        if ($this->util->isExcluded($fullPath)) {
247
+            return $this->storage->unlink($path);
248
+        }
249
+
250
+        $encryptionModule = $this->getEncryptionModule($path);
251
+        if ($encryptionModule) {
252
+            $this->keyStorage->deleteAllFileKeys($this->getFullPath($path));
253
+        }
254
+
255
+        return $this->storage->unlink($path);
256
+    }
257
+
258
+    /**
259
+     * see http://php.net/manual/en/function.rename.php
260
+     *
261
+     * @param string $path1
262
+     * @param string $path2
263
+     * @return bool
264
+     */
265
+    public function rename($path1, $path2) {
266
+
267
+        $result = $this->storage->rename($path1, $path2);
268
+
269
+        if ($result &&
270
+            // versions always use the keys from the original file, so we can skip
271
+            // this step for versions
272
+            $this->isVersion($path2) === false &&
273
+            $this->encryptionManager->isEnabled()) {
274
+            $source = $this->getFullPath($path1);
275
+            if (!$this->util->isExcluded($source)) {
276
+                $target = $this->getFullPath($path2);
277
+                if (isset($this->unencryptedSize[$source])) {
278
+                    $this->unencryptedSize[$target] = $this->unencryptedSize[$source];
279
+                }
280
+                $this->keyStorage->renameKeys($source, $target);
281
+                $module = $this->getEncryptionModule($path2);
282
+                if ($module) {
283
+                    $module->update($target, $this->uid, []);
284
+                }
285
+            }
286
+        }
287
+
288
+        return $result;
289
+    }
290
+
291
+    /**
292
+     * see http://php.net/manual/en/function.rmdir.php
293
+     *
294
+     * @param string $path
295
+     * @return bool
296
+     */
297
+    public function rmdir($path) {
298
+        $result = $this->storage->rmdir($path);
299
+        $fullPath = $this->getFullPath($path);
300
+        if ($result &&
301
+            $this->util->isExcluded($fullPath) === false &&
302
+            $this->encryptionManager->isEnabled()
303
+        ) {
304
+            $this->keyStorage->deleteAllFileKeys($fullPath);
305
+        }
306
+
307
+        return $result;
308
+    }
309
+
310
+    /**
311
+     * check if a file can be read
312
+     *
313
+     * @param string $path
314
+     * @return bool
315
+     */
316
+    public function isReadable($path) {
317
+
318
+        $isReadable = true;
319
+
320
+        $metaData = $this->getMetaData($path);
321
+        if (
322
+            !$this->is_dir($path) &&
323
+            isset($metaData['encrypted']) &&
324
+            $metaData['encrypted'] === true
325
+        ) {
326
+            $fullPath = $this->getFullPath($path);
327
+            $module = $this->getEncryptionModule($path);
328
+            $isReadable = $module->isReadable($fullPath, $this->uid);
329
+        }
330
+
331
+        return $this->storage->isReadable($path) && $isReadable;
332
+    }
333
+
334
+    /**
335
+     * see http://php.net/manual/en/function.copy.php
336
+     *
337
+     * @param string $path1
338
+     * @param string $path2
339
+     * @return bool
340
+     */
341
+    public function copy($path1, $path2) {
342
+
343
+        $source = $this->getFullPath($path1);
344
+
345
+        if ($this->util->isExcluded($source)) {
346
+            return $this->storage->copy($path1, $path2);
347
+        }
348
+
349
+        // need to stream copy file by file in case we copy between a encrypted
350
+        // and a unencrypted storage
351
+        $this->unlink($path2);
352
+        $result = $this->copyFromStorage($this, $path1, $path2);
353
+
354
+        return $result;
355
+    }
356
+
357
+    /**
358
+     * see http://php.net/manual/en/function.fopen.php
359
+     *
360
+     * @param string $path
361
+     * @param string $mode
362
+     * @return resource|bool
363
+     * @throws GenericEncryptionException
364
+     * @throws ModuleDoesNotExistsException
365
+     */
366
+    public function fopen($path, $mode) {
367
+
368
+        // check if the file is stored in the array cache, this means that we
369
+        // copy a file over to the versions folder, in this case we don't want to
370
+        // decrypt it
371
+        if ($this->arrayCache->hasKey('encryption_copy_version_' . $path)) {
372
+            $this->arrayCache->remove('encryption_copy_version_' . $path);
373
+            return $this->storage->fopen($path, $mode);
374
+        }
375
+
376
+        $encryptionEnabled = $this->encryptionManager->isEnabled();
377
+        $shouldEncrypt = false;
378
+        $encryptionModule = null;
379
+        $header = $this->getHeader($path);
380
+        $signed = (isset($header['signed']) && $header['signed'] === 'true') ? true : false;
381
+        $fullPath = $this->getFullPath($path);
382
+        $encryptionModuleId = $this->util->getEncryptionModuleId($header);
383
+
384
+        if ($this->util->isExcluded($fullPath) === false) {
385
+
386
+            $size = $unencryptedSize = 0;
387
+            $realFile = $this->util->stripPartialFileExtension($path);
388
+            $targetExists = $this->file_exists($realFile) || $this->file_exists($path);
389
+            $targetIsEncrypted = false;
390
+            if ($targetExists) {
391
+                // in case the file exists we require the explicit module as
392
+                // specified in the file header - otherwise we need to fail hard to
393
+                // prevent data loss on client side
394
+                if (!empty($encryptionModuleId)) {
395
+                    $targetIsEncrypted = true;
396
+                    $encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
397
+                }
398
+
399
+                if ($this->file_exists($path)) {
400
+                    $size = $this->storage->filesize($path);
401
+                    $unencryptedSize = $this->filesize($path);
402
+                } else {
403
+                    $size = $unencryptedSize = 0;
404
+                }
405
+            }
406
+
407
+            try {
408
+
409
+                if (
410
+                    $mode === 'w'
411
+                    || $mode === 'w+'
412
+                    || $mode === 'wb'
413
+                    || $mode === 'wb+'
414
+                ) {
415
+                    // don't overwrite encrypted files if encryption is not enabled
416
+                    if ($targetIsEncrypted && $encryptionEnabled === false) {
417
+                        throw new GenericEncryptionException('Tried to access encrypted file but encryption is not enabled');
418
+                    }
419
+                    if ($encryptionEnabled) {
420
+                        // if $encryptionModuleId is empty, the default module will be used
421
+                        $encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
422
+                        $shouldEncrypt = $encryptionModule->shouldEncrypt($fullPath);
423
+                        $signed = true;
424
+                    }
425
+                } else {
426
+                    $info = $this->getCache()->get($path);
427
+                    // only get encryption module if we found one in the header
428
+                    // or if file should be encrypted according to the file cache
429
+                    if (!empty($encryptionModuleId)) {
430
+                        $encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
431
+                        $shouldEncrypt = true;
432
+                    } else if (empty($encryptionModuleId) && $info['encrypted'] === true) {
433
+                        // we come from a old installation. No header and/or no module defined
434
+                        // but the file is encrypted. In this case we need to use the
435
+                        // OC_DEFAULT_MODULE to read the file
436
+                        $encryptionModule = $this->encryptionManager->getEncryptionModule('OC_DEFAULT_MODULE');
437
+                        $shouldEncrypt = true;
438
+                        $targetIsEncrypted = true;
439
+                    }
440
+                }
441
+            } catch (ModuleDoesNotExistsException $e) {
442
+                $this->logger->warning('Encryption module "' . $encryptionModuleId .
443
+                    '" not found, file will be stored unencrypted (' . $e->getMessage() . ')');
444
+            }
445
+
446
+            // encryption disabled on write of new file and write to existing unencrypted file -> don't encrypt
447
+            if (!$encryptionEnabled || !$this->shouldEncrypt($path)) {
448
+                if (!$targetExists || !$targetIsEncrypted) {
449
+                    $shouldEncrypt = false;
450
+                }
451
+            }
452
+
453
+            if ($shouldEncrypt === true && $encryptionModule !== null) {
454
+                $headerSize = $this->getHeaderSize($path);
455
+                $source = $this->storage->fopen($path, $mode);
456
+                if (!is_resource($source)) {
457
+                    return false;
458
+                }
459
+                $handle = \OC\Files\Stream\Encryption::wrap($source, $path, $fullPath, $header,
460
+                    $this->uid, $encryptionModule, $this->storage, $this, $this->util, $this->fileHelper, $mode,
461
+                    $size, $unencryptedSize, $headerSize, $signed);
462
+                return $handle;
463
+            }
464
+
465
+        }
466
+
467
+        return $this->storage->fopen($path, $mode);
468
+    }
469
+
470
+
471
+    /**
472
+     * perform some plausibility checks if the the unencrypted size is correct.
473
+     * If not, we calculate the correct unencrypted size and return it
474
+     *
475
+     * @param string $path internal path relative to the storage root
476
+     * @param int $unencryptedSize size of the unencrypted file
477
+     *
478
+     * @return int unencrypted size
479
+     */
480
+    protected function verifyUnencryptedSize($path, $unencryptedSize) {
481
+
482
+        $size = $this->storage->filesize($path);
483
+        $result = $unencryptedSize;
484
+
485
+        if ($unencryptedSize < 0 ||
486
+            ($size > 0 && $unencryptedSize === $size)
487
+        ) {
488
+            // check if we already calculate the unencrypted size for the
489
+            // given path to avoid recursions
490
+            if (isset($this->fixUnencryptedSizeOf[$this->getFullPath($path)]) === false) {
491
+                $this->fixUnencryptedSizeOf[$this->getFullPath($path)] = true;
492
+                try {
493
+                    $result = $this->fixUnencryptedSize($path, $size, $unencryptedSize);
494
+                } catch (\Exception $e) {
495
+                    $this->logger->error('Couldn\'t re-calculate unencrypted size for '. $path);
496
+                    $this->logger->logException($e);
497
+                }
498
+                unset($this->fixUnencryptedSizeOf[$this->getFullPath($path)]);
499
+            }
500
+        }
501
+
502
+        return $result;
503
+    }
504
+
505
+    /**
506
+     * calculate the unencrypted size
507
+     *
508
+     * @param string $path internal path relative to the storage root
509
+     * @param int $size size of the physical file
510
+     * @param int $unencryptedSize size of the unencrypted file
511
+     *
512
+     * @return int calculated unencrypted size
513
+     */
514
+    protected function fixUnencryptedSize($path, $size, $unencryptedSize) {
515
+
516
+        $headerSize = $this->getHeaderSize($path);
517
+        $header = $this->getHeader($path);
518
+        $encryptionModule = $this->getEncryptionModule($path);
519
+
520
+        $stream = $this->storage->fopen($path, 'r');
521
+
522
+        // if we couldn't open the file we return the old unencrypted size
523
+        if (!is_resource($stream)) {
524
+            $this->logger->error('Could not open ' . $path . '. Recalculation of unencrypted size aborted.');
525
+            return $unencryptedSize;
526
+        }
527
+
528
+        $newUnencryptedSize = 0;
529
+        $size -= $headerSize;
530
+        $blockSize = $this->util->getBlockSize();
531
+
532
+        // if a header exists we skip it
533
+        if ($headerSize > 0) {
534
+            fread($stream, $headerSize);
535
+        }
536
+
537
+        // fast path, else the calculation for $lastChunkNr is bogus
538
+        if ($size === 0) {
539
+            return 0;
540
+        }
541
+
542
+        $signed = (isset($header['signed']) && $header['signed'] === 'true') ? true : false;
543
+        $unencryptedBlockSize = $encryptionModule->getUnencryptedBlockSize($signed);
544
+
545
+        // calculate last chunk nr
546
+        // next highest is end of chunks, one subtracted is last one
547
+        // we have to read the last chunk, we can't just calculate it (because of padding etc)
548
+
549
+        $lastChunkNr = ceil($size/ $blockSize)-1;
550
+        // calculate last chunk position
551
+        $lastChunkPos = ($lastChunkNr * $blockSize);
552
+        // try to fseek to the last chunk, if it fails we have to read the whole file
553
+        if (@fseek($stream, $lastChunkPos, SEEK_CUR) === 0) {
554
+            $newUnencryptedSize += $lastChunkNr * $unencryptedBlockSize;
555
+        }
556
+
557
+        $lastChunkContentEncrypted='';
558
+        $count = $blockSize;
559
+
560
+        while ($count > 0) {
561
+            $data=fread($stream, $blockSize);
562
+            $count=strlen($data);
563
+            $lastChunkContentEncrypted .= $data;
564
+            if(strlen($lastChunkContentEncrypted) > $blockSize) {
565
+                $newUnencryptedSize += $unencryptedBlockSize;
566
+                $lastChunkContentEncrypted=substr($lastChunkContentEncrypted, $blockSize);
567
+            }
568
+        }
569
+
570
+        fclose($stream);
571
+
572
+        // we have to decrypt the last chunk to get it actual size
573
+        $encryptionModule->begin($this->getFullPath($path), $this->uid, 'r', $header, []);
574
+        $decryptedLastChunk = $encryptionModule->decrypt($lastChunkContentEncrypted, $lastChunkNr . 'end');
575
+        $decryptedLastChunk .= $encryptionModule->end($this->getFullPath($path), $lastChunkNr . 'end');
576
+
577
+        // calc the real file size with the size of the last chunk
578
+        $newUnencryptedSize += strlen($decryptedLastChunk);
579
+
580
+        $this->updateUnencryptedSize($this->getFullPath($path), $newUnencryptedSize);
581
+
582
+        // write to cache if applicable
583
+        $cache = $this->storage->getCache();
584
+        if ($cache) {
585
+            $entry = $cache->get($path);
586
+            $cache->update($entry['fileid'], ['size' => $newUnencryptedSize]);
587
+        }
588
+
589
+        return $newUnencryptedSize;
590
+    }
591
+
592
+    /**
593
+     * @param Storage $sourceStorage
594
+     * @param string $sourceInternalPath
595
+     * @param string $targetInternalPath
596
+     * @param bool $preserveMtime
597
+     * @return bool
598
+     */
599
+    public function moveFromStorage(Storage $sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime = true) {
600
+        if ($sourceStorage === $this) {
601
+            return $this->rename($sourceInternalPath, $targetInternalPath);
602
+        }
603
+
604
+        // TODO clean this up once the underlying moveFromStorage in OC\Files\Storage\Wrapper\Common is fixed:
605
+        // - call $this->storage->moveFromStorage() instead of $this->copyBetweenStorage
606
+        // - copy the file cache update from  $this->copyBetweenStorage to this method
607
+        // - copy the copyKeys() call from  $this->copyBetweenStorage to this method
608
+        // - remove $this->copyBetweenStorage
609
+
610
+        if (!$sourceStorage->isDeletable($sourceInternalPath)) {
611
+            return false;
612
+        }
613
+
614
+        $result = $this->copyBetweenStorage($sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime, true);
615
+        if ($result) {
616
+            if ($sourceStorage->is_dir($sourceInternalPath)) {
617
+                $result &= $sourceStorage->rmdir($sourceInternalPath);
618
+            } else {
619
+                $result &= $sourceStorage->unlink($sourceInternalPath);
620
+            }
621
+        }
622
+        return $result;
623
+    }
624
+
625
+
626
+    /**
627
+     * @param Storage $sourceStorage
628
+     * @param string $sourceInternalPath
629
+     * @param string $targetInternalPath
630
+     * @param bool $preserveMtime
631
+     * @param bool $isRename
632
+     * @return bool
633
+     */
634
+    public function copyFromStorage(Storage $sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime = false, $isRename = false) {
635
+
636
+        // TODO clean this up once the underlying moveFromStorage in OC\Files\Storage\Wrapper\Common is fixed:
637
+        // - call $this->storage->copyFromStorage() instead of $this->copyBetweenStorage
638
+        // - copy the file cache update from  $this->copyBetweenStorage to this method
639
+        // - copy the copyKeys() call from  $this->copyBetweenStorage to this method
640
+        // - remove $this->copyBetweenStorage
641
+
642
+        return $this->copyBetweenStorage($sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime, $isRename);
643
+    }
644
+
645
+    /**
646
+     * Update the encrypted cache version in the database
647
+     *
648
+     * @param Storage $sourceStorage
649
+     * @param string $sourceInternalPath
650
+     * @param string $targetInternalPath
651
+     * @param bool $isRename
652
+     */
653
+    private function updateEncryptedVersion(Storage $sourceStorage, $sourceInternalPath, $targetInternalPath, $isRename) {
654
+        $isEncrypted = $this->encryptionManager->isEnabled() && $this->shouldEncrypt($targetInternalPath) ? 1 : 0;
655
+        $cacheInformation = [
656
+            'encrypted' => (bool)$isEncrypted,
657
+        ];
658
+        if($isEncrypted === 1) {
659
+            $encryptedVersion = $sourceStorage->getCache()->get($sourceInternalPath)['encryptedVersion'];
660
+
661
+            // In case of a move operation from an unencrypted to an encrypted
662
+            // storage the old encrypted version would stay with "0" while the
663
+            // correct value would be "1". Thus we manually set the value to "1"
664
+            // for those cases.
665
+            // See also https://github.com/owncloud/core/issues/23078
666
+            if($encryptedVersion === 0) {
667
+                $encryptedVersion = 1;
668
+            }
669
+
670
+            $cacheInformation['encryptedVersion'] = $encryptedVersion;
671
+        }
672
+
673
+        // in case of a rename we need to manipulate the source cache because
674
+        // this information will be kept for the new target
675
+        if ($isRename) {
676
+            $sourceStorage->getCache()->put($sourceInternalPath, $cacheInformation);
677
+        } else {
678
+            $this->getCache()->put($targetInternalPath, $cacheInformation);
679
+        }
680
+    }
681
+
682
+    /**
683
+     * copy file between two storages
684
+     *
685
+     * @param Storage $sourceStorage
686
+     * @param string $sourceInternalPath
687
+     * @param string $targetInternalPath
688
+     * @param bool $preserveMtime
689
+     * @param bool $isRename
690
+     * @return bool
691
+     * @throws \Exception
692
+     */
693
+    private function copyBetweenStorage(Storage $sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime, $isRename) {
694
+
695
+        // for versions we have nothing to do, because versions should always use the
696
+        // key from the original file. Just create a 1:1 copy and done
697
+        if ($this->isVersion($targetInternalPath) ||
698
+            $this->isVersion($sourceInternalPath)) {
699
+            // remember that we try to create a version so that we can detect it during
700
+            // fopen($sourceInternalPath) and by-pass the encryption in order to
701
+            // create a 1:1 copy of the file
702
+            $this->arrayCache->set('encryption_copy_version_' . $sourceInternalPath, true);
703
+            $result = $this->storage->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
704
+            $this->arrayCache->remove('encryption_copy_version_' . $sourceInternalPath);
705
+            if ($result) {
706
+                $info = $this->getCache('', $sourceStorage)->get($sourceInternalPath);
707
+                // make sure that we update the unencrypted size for the version
708
+                if (isset($info['encrypted']) && $info['encrypted'] === true) {
709
+                    $this->updateUnencryptedSize(
710
+                        $this->getFullPath($targetInternalPath),
711
+                        $info['size']
712
+                    );
713
+                }
714
+                $this->updateEncryptedVersion($sourceStorage, $sourceInternalPath, $targetInternalPath, $isRename);
715
+            }
716
+            return $result;
717
+        }
718
+
719
+        // first copy the keys that we reuse the existing file key on the target location
720
+        // and don't create a new one which would break versions for example.
721
+        $mount = $this->mountManager->findByStorageId($sourceStorage->getId());
722
+        if (count($mount) === 1) {
723
+            $mountPoint = $mount[0]->getMountPoint();
724
+            $source = $mountPoint . '/' . $sourceInternalPath;
725
+            $target = $this->getFullPath($targetInternalPath);
726
+            $this->copyKeys($source, $target);
727
+        } else {
728
+            $this->logger->error('Could not find mount point, can\'t keep encryption keys');
729
+        }
730
+
731
+        if ($sourceStorage->is_dir($sourceInternalPath)) {
732
+            $dh = $sourceStorage->opendir($sourceInternalPath);
733
+            $result = $this->mkdir($targetInternalPath);
734
+            if (is_resource($dh)) {
735
+                while ($result and ($file = readdir($dh)) !== false) {
736
+                    if (!Filesystem::isIgnoredDir($file)) {
737
+                        $result &= $this->copyFromStorage($sourceStorage, $sourceInternalPath . '/' . $file, $targetInternalPath . '/' . $file, false, $isRename);
738
+                    }
739
+                }
740
+            }
741
+        } else {
742
+            try {
743
+                $source = $sourceStorage->fopen($sourceInternalPath, 'r');
744
+                $target = $this->fopen($targetInternalPath, 'w');
745
+                list(, $result) = \OC_Helper::streamCopy($source, $target);
746
+                fclose($source);
747
+                fclose($target);
748
+            } catch (\Exception $e) {
749
+                fclose($source);
750
+                fclose($target);
751
+                throw $e;
752
+            }
753
+            if($result) {
754
+                if ($preserveMtime) {
755
+                    $this->touch($targetInternalPath, $sourceStorage->filemtime($sourceInternalPath));
756
+                }
757
+                $this->updateEncryptedVersion($sourceStorage, $sourceInternalPath, $targetInternalPath, $isRename);
758
+            } else {
759
+                // delete partially written target file
760
+                $this->unlink($targetInternalPath);
761
+                // delete cache entry that was created by fopen
762
+                $this->getCache()->remove($targetInternalPath);
763
+            }
764
+        }
765
+        return (bool)$result;
766
+
767
+    }
768
+
769
+    /**
770
+     * get the path to a local version of the file.
771
+     * The local version of the file can be temporary and doesn't have to be persistent across requests
772
+     *
773
+     * @param string $path
774
+     * @return string
775
+     */
776
+    public function getLocalFile($path) {
777
+        if ($this->encryptionManager->isEnabled()) {
778
+            $cachedFile = $this->getCachedFile($path);
779
+            if (is_string($cachedFile)) {
780
+                return $cachedFile;
781
+            }
782
+        }
783
+        return $this->storage->getLocalFile($path);
784
+    }
785
+
786
+    /**
787
+     * Returns the wrapped storage's value for isLocal()
788
+     *
789
+     * @return bool wrapped storage's isLocal() value
790
+     */
791
+    public function isLocal() {
792
+        if ($this->encryptionManager->isEnabled()) {
793
+            return false;
794
+        }
795
+        return $this->storage->isLocal();
796
+    }
797
+
798
+    /**
799
+     * see http://php.net/manual/en/function.stat.php
800
+     * only the following keys are required in the result: size and mtime
801
+     *
802
+     * @param string $path
803
+     * @return array
804
+     */
805
+    public function stat($path) {
806
+        $stat = $this->storage->stat($path);
807
+        $fileSize = $this->filesize($path);
808
+        $stat['size'] = $fileSize;
809
+        $stat[7] = $fileSize;
810
+        return $stat;
811
+    }
812
+
813
+    /**
814
+     * see http://php.net/manual/en/function.hash.php
815
+     *
816
+     * @param string $type
817
+     * @param string $path
818
+     * @param bool $raw
819
+     * @return string
820
+     */
821
+    public function hash($type, $path, $raw = false) {
822
+        $fh = $this->fopen($path, 'rb');
823
+        $ctx = hash_init($type);
824
+        hash_update_stream($ctx, $fh);
825
+        fclose($fh);
826
+        return hash_final($ctx, $raw);
827
+    }
828
+
829
+    /**
830
+     * return full path, including mount point
831
+     *
832
+     * @param string $path relative to mount point
833
+     * @return string full path including mount point
834
+     */
835
+    protected function getFullPath($path) {
836
+        return Filesystem::normalizePath($this->mountPoint . '/' . $path);
837
+    }
838
+
839
+    /**
840
+     * read first block of encrypted file, typically this will contain the
841
+     * encryption header
842
+     *
843
+     * @param string $path
844
+     * @return string
845
+     */
846
+    protected function readFirstBlock($path) {
847
+        $firstBlock = '';
848
+        if ($this->storage->file_exists($path)) {
849
+            $handle = $this->storage->fopen($path, 'r');
850
+            $firstBlock = fread($handle, $this->util->getHeaderSize());
851
+            fclose($handle);
852
+        }
853
+        return $firstBlock;
854
+    }
855
+
856
+    /**
857
+     * return header size of given file
858
+     *
859
+     * @param string $path
860
+     * @return int
861
+     */
862
+    protected function getHeaderSize($path) {
863
+        $headerSize = 0;
864
+        $realFile = $this->util->stripPartialFileExtension($path);
865
+        if ($this->storage->file_exists($realFile)) {
866
+            $path = $realFile;
867
+        }
868
+        $firstBlock = $this->readFirstBlock($path);
869
+
870
+        if (substr($firstBlock, 0, strlen(Util::HEADER_START)) === Util::HEADER_START) {
871
+            $headerSize = $this->util->getHeaderSize();
872
+        }
873
+
874
+        return $headerSize;
875
+    }
876
+
877
+    /**
878
+     * parse raw header to array
879
+     *
880
+     * @param string $rawHeader
881
+     * @return array
882
+     */
883
+    protected function parseRawHeader($rawHeader) {
884
+        $result = array();
885
+        if (substr($rawHeader, 0, strlen(Util::HEADER_START)) === Util::HEADER_START) {
886
+            $header = $rawHeader;
887
+            $endAt = strpos($header, Util::HEADER_END);
888
+            if ($endAt !== false) {
889
+                $header = substr($header, 0, $endAt + strlen(Util::HEADER_END));
890
+
891
+                // +1 to not start with an ':' which would result in empty element at the beginning
892
+                $exploded = explode(':', substr($header, strlen(Util::HEADER_START)+1));
893
+
894
+                $element = array_shift($exploded);
895
+                while ($element !== Util::HEADER_END) {
896
+                    $result[$element] = array_shift($exploded);
897
+                    $element = array_shift($exploded);
898
+                }
899
+            }
900
+        }
901
+
902
+        return $result;
903
+    }
904
+
905
+    /**
906
+     * read header from file
907
+     *
908
+     * @param string $path
909
+     * @return array
910
+     */
911
+    protected function getHeader($path) {
912
+        $realFile = $this->util->stripPartialFileExtension($path);
913
+        if ($this->storage->file_exists($realFile)) {
914
+            $path = $realFile;
915
+        }
916
+
917
+        $firstBlock = $this->readFirstBlock($path);
918
+        $result = $this->parseRawHeader($firstBlock);
919
+
920
+        // if the header doesn't contain a encryption module we check if it is a
921
+        // legacy file. If true, we add the default encryption module
922
+        if (!isset($result[Util::HEADER_ENCRYPTION_MODULE_KEY])) {
923
+            if (!empty($result)) {
924
+                $result[Util::HEADER_ENCRYPTION_MODULE_KEY] = 'OC_DEFAULT_MODULE';
925
+            } else {
926
+                // if the header was empty we have to check first if it is a encrypted file at all
927
+                $info = $this->getCache()->get($path);
928
+                if (isset($info['encrypted']) && $info['encrypted'] === true) {
929
+                    $result[Util::HEADER_ENCRYPTION_MODULE_KEY] = 'OC_DEFAULT_MODULE';
930
+                }
931
+            }
932
+        }
933
+
934
+        return $result;
935
+    }
936
+
937
+    /**
938
+     * read encryption module needed to read/write the file located at $path
939
+     *
940
+     * @param string $path
941
+     * @return null|\OCP\Encryption\IEncryptionModule
942
+     * @throws ModuleDoesNotExistsException
943
+     * @throws \Exception
944
+     */
945
+    protected function getEncryptionModule($path) {
946
+        $encryptionModule = null;
947
+        $header = $this->getHeader($path);
948
+        $encryptionModuleId = $this->util->getEncryptionModuleId($header);
949
+        if (!empty($encryptionModuleId)) {
950
+            try {
951
+                $encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
952
+            } catch (ModuleDoesNotExistsException $e) {
953
+                $this->logger->critical('Encryption module defined in "' . $path . '" not loaded!');
954
+                throw $e;
955
+            }
956
+        }
957
+
958
+        return $encryptionModule;
959
+    }
960
+
961
+    /**
962
+     * @param string $path
963
+     * @param int $unencryptedSize
964
+     */
965
+    public function updateUnencryptedSize($path, $unencryptedSize) {
966
+        $this->unencryptedSize[$path] = $unencryptedSize;
967
+    }
968
+
969
+    /**
970
+     * copy keys to new location
971
+     *
972
+     * @param string $source path relative to data/
973
+     * @param string $target path relative to data/
974
+     * @return bool
975
+     */
976
+    protected function copyKeys($source, $target) {
977
+        if (!$this->util->isExcluded($source)) {
978
+            return $this->keyStorage->copyKeys($source, $target);
979
+        }
980
+
981
+        return false;
982
+    }
983
+
984
+    /**
985
+     * check if path points to a files version
986
+     *
987
+     * @param $path
988
+     * @return bool
989
+     */
990
+    protected function isVersion($path) {
991
+        $normalized = Filesystem::normalizePath($path);
992
+        return substr($normalized, 0, strlen('/files_versions/')) === '/files_versions/';
993
+    }
994
+
995
+    /**
996
+     * check if the given storage should be encrypted or not
997
+     *
998
+     * @param $path
999
+     * @return bool
1000
+     */
1001
+    protected function shouldEncrypt($path) {
1002
+        $fullPath = $this->getFullPath($path);
1003
+        $mountPointConfig = $this->mount->getOption('encrypt', true);
1004
+        if ($mountPointConfig === false) {
1005
+            return false;
1006
+        }
1007
+
1008
+        try {
1009
+            $encryptionModule = $this->getEncryptionModule($fullPath);
1010
+        } catch (ModuleDoesNotExistsException $e) {
1011
+            return false;
1012
+        }
1013
+
1014
+        if ($encryptionModule === null) {
1015
+            $encryptionModule = $this->encryptionManager->getEncryptionModule();
1016
+        }
1017
+
1018
+        return $encryptionModule->shouldEncrypt($fullPath);
1019
+
1020
+    }
1021 1021
 
1022 1022
 }
Please login to merge, or discard this patch.
Spacing   +26 added lines, -26 removed lines patch added patch discarded remove patch
@@ -368,8 +368,8 @@  discard block
 block discarded – undo
368 368
 		// check if the file is stored in the array cache, this means that we
369 369
 		// copy a file over to the versions folder, in this case we don't want to
370 370
 		// decrypt it
371
-		if ($this->arrayCache->hasKey('encryption_copy_version_' . $path)) {
372
-			$this->arrayCache->remove('encryption_copy_version_' . $path);
371
+		if ($this->arrayCache->hasKey('encryption_copy_version_'.$path)) {
372
+			$this->arrayCache->remove('encryption_copy_version_'.$path);
373 373
 			return $this->storage->fopen($path, $mode);
374 374
 		}
375 375
 
@@ -439,8 +439,8 @@  discard block
 block discarded – undo
439 439
 					}
440 440
 				}
441 441
 			} catch (ModuleDoesNotExistsException $e) {
442
-				$this->logger->warning('Encryption module "' . $encryptionModuleId .
443
-					'" not found, file will be stored unencrypted (' . $e->getMessage() . ')');
442
+				$this->logger->warning('Encryption module "'.$encryptionModuleId.
443
+					'" not found, file will be stored unencrypted ('.$e->getMessage().')');
444 444
 			}
445 445
 
446 446
 			// encryption disabled on write of new file and write to existing unencrypted file -> don't encrypt
@@ -492,7 +492,7 @@  discard block
 block discarded – undo
492 492
 				try {
493 493
 					$result = $this->fixUnencryptedSize($path, $size, $unencryptedSize);
494 494
 				} catch (\Exception $e) {
495
-					$this->logger->error('Couldn\'t re-calculate unencrypted size for '. $path);
495
+					$this->logger->error('Couldn\'t re-calculate unencrypted size for '.$path);
496 496
 					$this->logger->logException($e);
497 497
 				}
498 498
 				unset($this->fixUnencryptedSizeOf[$this->getFullPath($path)]);
@@ -521,7 +521,7 @@  discard block
 block discarded – undo
521 521
 
522 522
 		// if we couldn't open the file we return the old unencrypted size
523 523
 		if (!is_resource($stream)) {
524
-			$this->logger->error('Could not open ' . $path . '. Recalculation of unencrypted size aborted.');
524
+			$this->logger->error('Could not open '.$path.'. Recalculation of unencrypted size aborted.');
525 525
 			return $unencryptedSize;
526 526
 		}
527 527
 
@@ -546,7 +546,7 @@  discard block
 block discarded – undo
546 546
 		// next highest is end of chunks, one subtracted is last one
547 547
 		// we have to read the last chunk, we can't just calculate it (because of padding etc)
548 548
 
549
-		$lastChunkNr = ceil($size/ $blockSize)-1;
549
+		$lastChunkNr = ceil($size / $blockSize) - 1;
550 550
 		// calculate last chunk position
551 551
 		$lastChunkPos = ($lastChunkNr * $blockSize);
552 552
 		// try to fseek to the last chunk, if it fails we have to read the whole file
@@ -554,16 +554,16 @@  discard block
 block discarded – undo
554 554
 			$newUnencryptedSize += $lastChunkNr * $unencryptedBlockSize;
555 555
 		}
556 556
 
557
-		$lastChunkContentEncrypted='';
557
+		$lastChunkContentEncrypted = '';
558 558
 		$count = $blockSize;
559 559
 
560 560
 		while ($count > 0) {
561
-			$data=fread($stream, $blockSize);
562
-			$count=strlen($data);
561
+			$data = fread($stream, $blockSize);
562
+			$count = strlen($data);
563 563
 			$lastChunkContentEncrypted .= $data;
564
-			if(strlen($lastChunkContentEncrypted) > $blockSize) {
564
+			if (strlen($lastChunkContentEncrypted) > $blockSize) {
565 565
 				$newUnencryptedSize += $unencryptedBlockSize;
566
-				$lastChunkContentEncrypted=substr($lastChunkContentEncrypted, $blockSize);
566
+				$lastChunkContentEncrypted = substr($lastChunkContentEncrypted, $blockSize);
567 567
 			}
568 568
 		}
569 569
 
@@ -571,8 +571,8 @@  discard block
 block discarded – undo
571 571
 
572 572
 		// we have to decrypt the last chunk to get it actual size
573 573
 		$encryptionModule->begin($this->getFullPath($path), $this->uid, 'r', $header, []);
574
-		$decryptedLastChunk = $encryptionModule->decrypt($lastChunkContentEncrypted, $lastChunkNr . 'end');
575
-		$decryptedLastChunk .= $encryptionModule->end($this->getFullPath($path), $lastChunkNr . 'end');
574
+		$decryptedLastChunk = $encryptionModule->decrypt($lastChunkContentEncrypted, $lastChunkNr.'end');
575
+		$decryptedLastChunk .= $encryptionModule->end($this->getFullPath($path), $lastChunkNr.'end');
576 576
 
577 577
 		// calc the real file size with the size of the last chunk
578 578
 		$newUnencryptedSize += strlen($decryptedLastChunk);
@@ -653,9 +653,9 @@  discard block
 block discarded – undo
653 653
 	private function updateEncryptedVersion(Storage $sourceStorage, $sourceInternalPath, $targetInternalPath, $isRename) {
654 654
 		$isEncrypted = $this->encryptionManager->isEnabled() && $this->shouldEncrypt($targetInternalPath) ? 1 : 0;
655 655
 		$cacheInformation = [
656
-			'encrypted' => (bool)$isEncrypted,
656
+			'encrypted' => (bool) $isEncrypted,
657 657
 		];
658
-		if($isEncrypted === 1) {
658
+		if ($isEncrypted === 1) {
659 659
 			$encryptedVersion = $sourceStorage->getCache()->get($sourceInternalPath)['encryptedVersion'];
660 660
 
661 661
 			// In case of a move operation from an unencrypted to an encrypted
@@ -663,7 +663,7 @@  discard block
 block discarded – undo
663 663
 			// correct value would be "1". Thus we manually set the value to "1"
664 664
 			// for those cases.
665 665
 			// See also https://github.com/owncloud/core/issues/23078
666
-			if($encryptedVersion === 0) {
666
+			if ($encryptedVersion === 0) {
667 667
 				$encryptedVersion = 1;
668 668
 			}
669 669
 
@@ -699,9 +699,9 @@  discard block
 block discarded – undo
699 699
 			// remember that we try to create a version so that we can detect it during
700 700
 			// fopen($sourceInternalPath) and by-pass the encryption in order to
701 701
 			// create a 1:1 copy of the file
702
-			$this->arrayCache->set('encryption_copy_version_' . $sourceInternalPath, true);
702
+			$this->arrayCache->set('encryption_copy_version_'.$sourceInternalPath, true);
703 703
 			$result = $this->storage->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
704
-			$this->arrayCache->remove('encryption_copy_version_' . $sourceInternalPath);
704
+			$this->arrayCache->remove('encryption_copy_version_'.$sourceInternalPath);
705 705
 			if ($result) {
706 706
 				$info = $this->getCache('', $sourceStorage)->get($sourceInternalPath);
707 707
 				// make sure that we update the unencrypted size for the version
@@ -721,7 +721,7 @@  discard block
 block discarded – undo
721 721
 		$mount = $this->mountManager->findByStorageId($sourceStorage->getId());
722 722
 		if (count($mount) === 1) {
723 723
 			$mountPoint = $mount[0]->getMountPoint();
724
-			$source = $mountPoint . '/' . $sourceInternalPath;
724
+			$source = $mountPoint.'/'.$sourceInternalPath;
725 725
 			$target = $this->getFullPath($targetInternalPath);
726 726
 			$this->copyKeys($source, $target);
727 727
 		} else {
@@ -734,7 +734,7 @@  discard block
 block discarded – undo
734 734
 			if (is_resource($dh)) {
735 735
 				while ($result and ($file = readdir($dh)) !== false) {
736 736
 					if (!Filesystem::isIgnoredDir($file)) {
737
-						$result &= $this->copyFromStorage($sourceStorage, $sourceInternalPath . '/' . $file, $targetInternalPath . '/' . $file, false, $isRename);
737
+						$result &= $this->copyFromStorage($sourceStorage, $sourceInternalPath.'/'.$file, $targetInternalPath.'/'.$file, false, $isRename);
738 738
 					}
739 739
 				}
740 740
 			}
@@ -750,7 +750,7 @@  discard block
 block discarded – undo
750 750
 				fclose($target);
751 751
 				throw $e;
752 752
 			}
753
-			if($result) {
753
+			if ($result) {
754 754
 				if ($preserveMtime) {
755 755
 					$this->touch($targetInternalPath, $sourceStorage->filemtime($sourceInternalPath));
756 756
 				}
@@ -762,7 +762,7 @@  discard block
 block discarded – undo
762 762
 				$this->getCache()->remove($targetInternalPath);
763 763
 			}
764 764
 		}
765
-		return (bool)$result;
765
+		return (bool) $result;
766 766
 
767 767
 	}
768 768
 
@@ -833,7 +833,7 @@  discard block
 block discarded – undo
833 833
 	 * @return string full path including mount point
834 834
 	 */
835 835
 	protected function getFullPath($path) {
836
-		return Filesystem::normalizePath($this->mountPoint . '/' . $path);
836
+		return Filesystem::normalizePath($this->mountPoint.'/'.$path);
837 837
 	}
838 838
 
839 839
 	/**
@@ -889,7 +889,7 @@  discard block
 block discarded – undo
889 889
 				$header = substr($header, 0, $endAt + strlen(Util::HEADER_END));
890 890
 
891 891
 				// +1 to not start with an ':' which would result in empty element at the beginning
892
-				$exploded = explode(':', substr($header, strlen(Util::HEADER_START)+1));
892
+				$exploded = explode(':', substr($header, strlen(Util::HEADER_START) + 1));
893 893
 
894 894
 				$element = array_shift($exploded);
895 895
 				while ($element !== Util::HEADER_END) {
@@ -950,7 +950,7 @@  discard block
 block discarded – undo
950 950
 			try {
951 951
 				$encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
952 952
 			} catch (ModuleDoesNotExistsException $e) {
953
-				$this->logger->critical('Encryption module defined in "' . $path . '" not loaded!');
953
+				$this->logger->critical('Encryption module defined in "'.$path.'" not loaded!');
954 954
 				throw $e;
955 955
 			}
956 956
 		}
Please login to merge, or discard this patch.
apps/dav/lib/AppInfo/Application.php 3 patches
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -25,7 +25,6 @@
 block discarded – undo
25 25
 namespace OCA\DAV\AppInfo;
26 26
 
27 27
 use OCA\DAV\CalDAV\Activity\Backend;
28
-use OCA\DAV\CalDAV\Activity\Extension;
29 28
 use OCA\DAV\CalDAV\Activity\Provider\Event;
30 29
 use OCA\DAV\CalDAV\BirthdayService;
31 30
 use OCA\DAV\Capabilities;
Please login to merge, or discard this patch.
Indentation   +126 added lines, -126 removed lines patch added patch discarded remove patch
@@ -39,134 +39,134 @@
 block discarded – undo
39 39
 
40 40
 class Application extends App {
41 41
 
42
-	/**
43
-	 * Application constructor.
44
-	 */
45
-	public function __construct() {
46
-		parent::__construct('dav');
42
+    /**
43
+     * Application constructor.
44
+     */
45
+    public function __construct() {
46
+        parent::__construct('dav');
47 47
 
48
-		/*
48
+        /*
49 49
 		 * Register capabilities
50 50
 		 */
51
-		$this->getContainer()->registerCapability(Capabilities::class);
52
-	}
53
-
54
-	/**
55
-	 * @param IManager $contactsManager
56
-	 * @param string $userID
57
-	 */
58
-	public function setupContactsProvider(IManager $contactsManager, $userID) {
59
-		/** @var ContactsManager $cm */
60
-		$cm = $this->getContainer()->query(ContactsManager::class);
61
-		$urlGenerator = $this->getContainer()->getServer()->getURLGenerator();
62
-		$cm->setupContactsProvider($contactsManager, $userID, $urlGenerator);
63
-	}
64
-
65
-	public function registerHooks() {
66
-		/** @var HookManager $hm */
67
-		$hm = $this->getContainer()->query(HookManager::class);
68
-		$hm->setup();
69
-
70
-		$dispatcher = $this->getContainer()->getServer()->getEventDispatcher();
71
-
72
-		// first time login event setup
73
-		$dispatcher->addListener(IUser::class . '::firstLogin', function ($event) use ($hm) {
74
-			if ($event instanceof GenericEvent) {
75
-				$hm->firstLogin($event->getSubject());
76
-			}
77
-		});
78
-
79
-		// carddav/caldav sync event setup
80
-		$listener = function($event) {
81
-			if ($event instanceof GenericEvent) {
82
-				/** @var BirthdayService $b */
83
-				$b = $this->getContainer()->query(BirthdayService::class);
84
-				$b->onCardChanged(
85
-					$event->getArgument('addressBookId'),
86
-					$event->getArgument('cardUri'),
87
-					$event->getArgument('cardData')
88
-				);
89
-			}
90
-		};
91
-
92
-		$dispatcher->addListener('\OCA\DAV\CardDAV\CardDavBackend::createCard', $listener);
93
-		$dispatcher->addListener('\OCA\DAV\CardDAV\CardDavBackend::updateCard', $listener);
94
-		$dispatcher->addListener('\OCA\DAV\CardDAV\CardDavBackend::deleteCard', function($event) {
95
-			if ($event instanceof GenericEvent) {
96
-				/** @var BirthdayService $b */
97
-				$b = $this->getContainer()->query(BirthdayService::class);
98
-				$b->onCardDeleted(
99
-					$event->getArgument('addressBookId'),
100
-					$event->getArgument('cardUri')
101
-				);
102
-			}
103
-		});
104
-
105
-		$dispatcher->addListener('OC\AccountManager::userUpdated', function(GenericEvent $event) {
106
-			$user = $event->getSubject();
107
-			$syncService = $this->getContainer()->query(SyncService::class);
108
-			$syncService->updateUser($user);
109
-		});
110
-
111
-		$dispatcher->addListener('\OCA\DAV\CalDAV\CalDavBackend::createCalendar', function(GenericEvent $event) {
112
-			/** @var Backend $backend */
113
-			$backend = $this->getContainer()->query(Backend::class);
114
-			$backend->onCalendarAdd(
115
-				$event->getArgument('calendarData')
116
-			);
117
-		});
118
-		$dispatcher->addListener('\OCA\DAV\CalDAV\CalDavBackend::updateCalendar', function(GenericEvent $event) {
119
-			/** @var Backend $backend */
120
-			$backend = $this->getContainer()->query(Backend::class);
121
-			$backend->onCalendarUpdate(
122
-				$event->getArgument('calendarData'),
123
-				$event->getArgument('shares'),
124
-				$event->getArgument('propertyMutations')
125
-			);
126
-		});
127
-		$dispatcher->addListener('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar', function(GenericEvent $event) {
128
-			/** @var Backend $backend */
129
-			$backend = $this->getContainer()->query(Backend::class);
130
-			$backend->onCalendarDelete(
131
-				$event->getArgument('calendarData'),
132
-				$event->getArgument('shares')
133
-			);
134
-		});
135
-		$dispatcher->addListener('\OCA\DAV\CalDAV\CalDavBackend::updateShares', function(GenericEvent $event) {
136
-			/** @var Backend $backend */
137
-			$backend = $this->getContainer()->query(Backend::class);
138
-			$backend->onCalendarUpdateShares(
139
-				$event->getArgument('calendarData'),
140
-				$event->getArgument('shares'),
141
-				$event->getArgument('add'),
142
-				$event->getArgument('remove')
143
-			);
144
-		});
145
-
146
-		$listener = function(GenericEvent $event, $eventName) {
147
-			/** @var Backend $backend */
148
-			$backend = $this->getContainer()->query(Backend::class);
149
-
150
-			$subject = Event::SUBJECT_OBJECT_ADD;
151
-			if ($eventName === '\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject') {
152
-				$subject = Event::SUBJECT_OBJECT_UPDATE;
153
-			} else if ($eventName === '\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject') {
154
-				$subject = Event::SUBJECT_OBJECT_DELETE;
155
-			}
156
-			$backend->onTouchCalendarObject(
157
-				$subject,
158
-				$event->getArgument('calendarData'),
159
-				$event->getArgument('shares'),
160
-				$event->getArgument('objectData')
161
-			);
162
-		};
163
-		$dispatcher->addListener('\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject', $listener);
164
-		$dispatcher->addListener('\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject', $listener);
165
-		$dispatcher->addListener('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject', $listener);
166
-	}
167
-
168
-	public function getSyncService() {
169
-		return $this->getContainer()->query(SyncService::class);
170
-	}
51
+        $this->getContainer()->registerCapability(Capabilities::class);
52
+    }
53
+
54
+    /**
55
+     * @param IManager $contactsManager
56
+     * @param string $userID
57
+     */
58
+    public function setupContactsProvider(IManager $contactsManager, $userID) {
59
+        /** @var ContactsManager $cm */
60
+        $cm = $this->getContainer()->query(ContactsManager::class);
61
+        $urlGenerator = $this->getContainer()->getServer()->getURLGenerator();
62
+        $cm->setupContactsProvider($contactsManager, $userID, $urlGenerator);
63
+    }
64
+
65
+    public function registerHooks() {
66
+        /** @var HookManager $hm */
67
+        $hm = $this->getContainer()->query(HookManager::class);
68
+        $hm->setup();
69
+
70
+        $dispatcher = $this->getContainer()->getServer()->getEventDispatcher();
71
+
72
+        // first time login event setup
73
+        $dispatcher->addListener(IUser::class . '::firstLogin', function ($event) use ($hm) {
74
+            if ($event instanceof GenericEvent) {
75
+                $hm->firstLogin($event->getSubject());
76
+            }
77
+        });
78
+
79
+        // carddav/caldav sync event setup
80
+        $listener = function($event) {
81
+            if ($event instanceof GenericEvent) {
82
+                /** @var BirthdayService $b */
83
+                $b = $this->getContainer()->query(BirthdayService::class);
84
+                $b->onCardChanged(
85
+                    $event->getArgument('addressBookId'),
86
+                    $event->getArgument('cardUri'),
87
+                    $event->getArgument('cardData')
88
+                );
89
+            }
90
+        };
91
+
92
+        $dispatcher->addListener('\OCA\DAV\CardDAV\CardDavBackend::createCard', $listener);
93
+        $dispatcher->addListener('\OCA\DAV\CardDAV\CardDavBackend::updateCard', $listener);
94
+        $dispatcher->addListener('\OCA\DAV\CardDAV\CardDavBackend::deleteCard', function($event) {
95
+            if ($event instanceof GenericEvent) {
96
+                /** @var BirthdayService $b */
97
+                $b = $this->getContainer()->query(BirthdayService::class);
98
+                $b->onCardDeleted(
99
+                    $event->getArgument('addressBookId'),
100
+                    $event->getArgument('cardUri')
101
+                );
102
+            }
103
+        });
104
+
105
+        $dispatcher->addListener('OC\AccountManager::userUpdated', function(GenericEvent $event) {
106
+            $user = $event->getSubject();
107
+            $syncService = $this->getContainer()->query(SyncService::class);
108
+            $syncService->updateUser($user);
109
+        });
110
+
111
+        $dispatcher->addListener('\OCA\DAV\CalDAV\CalDavBackend::createCalendar', function(GenericEvent $event) {
112
+            /** @var Backend $backend */
113
+            $backend = $this->getContainer()->query(Backend::class);
114
+            $backend->onCalendarAdd(
115
+                $event->getArgument('calendarData')
116
+            );
117
+        });
118
+        $dispatcher->addListener('\OCA\DAV\CalDAV\CalDavBackend::updateCalendar', function(GenericEvent $event) {
119
+            /** @var Backend $backend */
120
+            $backend = $this->getContainer()->query(Backend::class);
121
+            $backend->onCalendarUpdate(
122
+                $event->getArgument('calendarData'),
123
+                $event->getArgument('shares'),
124
+                $event->getArgument('propertyMutations')
125
+            );
126
+        });
127
+        $dispatcher->addListener('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar', function(GenericEvent $event) {
128
+            /** @var Backend $backend */
129
+            $backend = $this->getContainer()->query(Backend::class);
130
+            $backend->onCalendarDelete(
131
+                $event->getArgument('calendarData'),
132
+                $event->getArgument('shares')
133
+            );
134
+        });
135
+        $dispatcher->addListener('\OCA\DAV\CalDAV\CalDavBackend::updateShares', function(GenericEvent $event) {
136
+            /** @var Backend $backend */
137
+            $backend = $this->getContainer()->query(Backend::class);
138
+            $backend->onCalendarUpdateShares(
139
+                $event->getArgument('calendarData'),
140
+                $event->getArgument('shares'),
141
+                $event->getArgument('add'),
142
+                $event->getArgument('remove')
143
+            );
144
+        });
145
+
146
+        $listener = function(GenericEvent $event, $eventName) {
147
+            /** @var Backend $backend */
148
+            $backend = $this->getContainer()->query(Backend::class);
149
+
150
+            $subject = Event::SUBJECT_OBJECT_ADD;
151
+            if ($eventName === '\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject') {
152
+                $subject = Event::SUBJECT_OBJECT_UPDATE;
153
+            } else if ($eventName === '\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject') {
154
+                $subject = Event::SUBJECT_OBJECT_DELETE;
155
+            }
156
+            $backend->onTouchCalendarObject(
157
+                $subject,
158
+                $event->getArgument('calendarData'),
159
+                $event->getArgument('shares'),
160
+                $event->getArgument('objectData')
161
+            );
162
+        };
163
+        $dispatcher->addListener('\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject', $listener);
164
+        $dispatcher->addListener('\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject', $listener);
165
+        $dispatcher->addListener('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject', $listener);
166
+    }
167
+
168
+    public function getSyncService() {
169
+        return $this->getContainer()->query(SyncService::class);
170
+    }
171 171
 
172 172
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -70,7 +70,7 @@
 block discarded – undo
70 70
 		$dispatcher = $this->getContainer()->getServer()->getEventDispatcher();
71 71
 
72 72
 		// first time login event setup
73
-		$dispatcher->addListener(IUser::class . '::firstLogin', function ($event) use ($hm) {
73
+		$dispatcher->addListener(IUser::class.'::firstLogin', function($event) use ($hm) {
74 74
 			if ($event instanceof GenericEvent) {
75 75
 				$hm->firstLogin($event->getSubject());
76 76
 			}
Please login to merge, or discard this patch.
apps/files_external/lib/Lib/Storage/AmazonS3.php 3 patches
Doc Comments   +6 added lines patch added patch discarded remove patch
@@ -191,6 +191,9 @@  discard block
 block discarded – undo
191 191
 		return false;
192 192
 	}
193 193
 
194
+	/**
195
+	 * @param string $path
196
+	 */
194 197
 	private function batchDelete ($path = null) {
195 198
 		$params = array(
196 199
 			'Bucket' => $this->bucket
@@ -516,6 +519,9 @@  discard block
 block discarded – undo
516 519
 		return $this->id;
517 520
 	}
518 521
 
522
+	/**
523
+	 * @param string $path
524
+	 */
519 525
 	public function writeBack($tmpFile, $path) {
520 526
 		try {
521 527
 			$this->getConnection()->putObject(array(
Please login to merge, or discard this patch.
Indentation   +494 added lines, -494 removed lines patch added patch discarded remove patch
@@ -37,7 +37,7 @@  discard block
 block discarded – undo
37 37
 namespace OCA\Files_External\Lib\Storage;
38 38
 
39 39
 set_include_path(get_include_path() . PATH_SEPARATOR .
40
-	\OC_App::getAppPath('files_external') . '/3rdparty/aws-sdk-php');
40
+    \OC_App::getAppPath('files_external') . '/3rdparty/aws-sdk-php');
41 41
 require_once 'aws-autoloader.php';
42 42
 
43 43
 use Aws\S3\S3Client;
@@ -47,498 +47,498 @@  discard block
 block discarded – undo
47 47
 use OC\Files\ObjectStore\S3ConnectionTrait;
48 48
 
49 49
 class AmazonS3 extends \OC\Files\Storage\Common {
50
-	use S3ConnectionTrait;
51
-
52
-	/**
53
-	 * @var array
54
-	 */
55
-	private static $tmpFiles = array();
56
-
57
-	/**
58
-	 * @var int in seconds
59
-	 */
60
-	private $rescanDelay = 10;
61
-
62
-	public function __construct($parameters) {
63
-		parent::__construct($parameters);
64
-		$this->parseParams($parameters);
65
-	}
66
-
67
-	/**
68
-	 * @param string $path
69
-	 * @return string correctly encoded path
70
-	 */
71
-	private function normalizePath($path) {
72
-		$path = trim($path, '/');
73
-
74
-		if (!$path) {
75
-			$path = '.';
76
-		}
77
-
78
-		return $path;
79
-	}
80
-
81
-	private function isRoot($path) {
82
-		return $path === '.';
83
-	}
84
-
85
-	private function cleanKey($path) {
86
-		if ($this->isRoot($path)) {
87
-			return '/';
88
-		}
89
-		return $path;
90
-	}
91
-
92
-	/**
93
-	 * Updates old storage ids (v0.2.1 and older) that are based on key and secret to new ones based on the bucket name.
94
-	 * TODO Do this in an update.php. requires iterating over all users and loading the mount.json from their home
95
-	 *
96
-	 * @param array $params
97
-	 */
98
-	public function updateLegacyId (array $params) {
99
-		$oldId = 'amazon::' . $params['key'] . md5($params['secret']);
100
-
101
-		// find by old id or bucket
102
-		$stmt = \OC::$server->getDatabaseConnection()->prepare(
103
-			'SELECT `numeric_id`, `id` FROM `*PREFIX*storages` WHERE `id` IN (?, ?)'
104
-		);
105
-		$stmt->execute(array($oldId, $this->id));
106
-		while ($row = $stmt->fetch()) {
107
-			$storages[$row['id']] = $row['numeric_id'];
108
-		}
109
-
110
-		if (isset($storages[$this->id]) && isset($storages[$oldId])) {
111
-			// if both ids exist, delete the old storage and corresponding filecache entries
112
-			\OC\Files\Cache\Storage::remove($oldId);
113
-		} else if (isset($storages[$oldId])) {
114
-			// if only the old id exists do an update
115
-			$stmt = \OC::$server->getDatabaseConnection()->prepare(
116
-				'UPDATE `*PREFIX*storages` SET `id` = ? WHERE `id` = ?'
117
-			);
118
-			$stmt->execute(array($this->id, $oldId));
119
-		}
120
-		// only the bucket based id may exist, do nothing
121
-	}
122
-
123
-	/**
124
-	 * Remove a file or folder
125
-	 *
126
-	 * @param string $path
127
-	 * @return bool
128
-	 */
129
-	protected function remove($path) {
130
-		// remember fileType to reduce http calls
131
-		$fileType = $this->filetype($path);
132
-		if ($fileType === 'dir') {
133
-			return $this->rmdir($path);
134
-		} else if ($fileType === 'file') {
135
-			return $this->unlink($path);
136
-		} else {
137
-			return false;
138
-		}
139
-	}
140
-
141
-	public function mkdir($path) {
142
-		$path = $this->normalizePath($path);
143
-
144
-		if ($this->is_dir($path)) {
145
-			return false;
146
-		}
147
-
148
-		try {
149
-			$this->getConnection()->putObject(array(
150
-				'Bucket' => $this->bucket,
151
-				'Key' => $path . '/',
152
-				'Body' => '',
153
-				'ContentType' => 'httpd/unix-directory'
154
-			));
155
-			$this->testTimeout();
156
-		} catch (S3Exception $e) {
157
-			\OCP\Util::logException('files_external', $e);
158
-			return false;
159
-		}
160
-
161
-		return true;
162
-	}
163
-
164
-	public function file_exists($path) {
165
-		return $this->filetype($path) !== false;
166
-	}
167
-
168
-
169
-	public function rmdir($path) {
170
-		$path = $this->normalizePath($path);
171
-
172
-		if ($this->isRoot($path)) {
173
-			return $this->clearBucket();
174
-		}
175
-
176
-		if (!$this->file_exists($path)) {
177
-			return false;
178
-		}
179
-
180
-		return $this->batchDelete($path);
181
-	}
182
-
183
-	protected function clearBucket() {
184
-		try {
185
-			$this->getConnection()->clearBucket($this->bucket);
186
-			return true;
187
-			// clearBucket() is not working with Ceph, so if it fails we try the slower approach
188
-		} catch (\Exception $e) {
189
-			return $this->batchDelete();
190
-		}
191
-		return false;
192
-	}
193
-
194
-	private function batchDelete ($path = null) {
195
-		$params = array(
196
-			'Bucket' => $this->bucket
197
-		);
198
-		if ($path !== null) {
199
-			$params['Prefix'] = $path . '/';
200
-		}
201
-		try {
202
-			// Since there are no real directories on S3, we need
203
-			// to delete all objects prefixed with the path.
204
-			do {
205
-				// instead of the iterator, manually loop over the list ...
206
-				$objects = $this->getConnection()->listObjects($params);
207
-				// ... so we can delete the files in batches
208
-				$this->getConnection()->deleteObjects(array(
209
-					'Bucket' => $this->bucket,
210
-					'Objects' => $objects['Contents']
211
-				));
212
-				$this->testTimeout();
213
-				// we reached the end when the list is no longer truncated
214
-			} while ($objects['IsTruncated']);
215
-		} catch (S3Exception $e) {
216
-			\OCP\Util::logException('files_external', $e);
217
-			return false;
218
-		}
219
-		return true;
220
-	}
221
-
222
-	public function opendir($path) {
223
-		$path = $this->normalizePath($path);
224
-
225
-		if ($this->isRoot($path)) {
226
-			$path = '';
227
-		} else {
228
-			$path .= '/';
229
-		}
230
-
231
-		try {
232
-			$files = array();
233
-			$result = $this->getConnection()->getIterator('ListObjects', array(
234
-				'Bucket' => $this->bucket,
235
-				'Delimiter' => '/',
236
-				'Prefix' => $path
237
-			), array('return_prefixes' => true));
238
-
239
-			foreach ($result as $object) {
240
-				if (isset($object['Key']) && $object['Key'] === $path) {
241
-					// it's the directory itself, skip
242
-					continue;
243
-				}
244
-				$file = basename(
245
-					isset($object['Key']) ? $object['Key'] : $object['Prefix']
246
-				);
247
-				$files[] = $file;
248
-			}
249
-
250
-			return IteratorDirectory::wrap($files);
251
-		} catch (S3Exception $e) {
252
-			\OCP\Util::logException('files_external', $e);
253
-			return false;
254
-		}
255
-	}
256
-
257
-	public function stat($path) {
258
-		$path = $this->normalizePath($path);
259
-
260
-		try {
261
-			$stat = array();
262
-			if ($this->is_dir($path)) {
263
-				//folders don't really exist
264
-				$stat['size'] = -1; //unknown
265
-				$stat['mtime'] = time() - $this->rescanDelay * 1000;
266
-			} else {
267
-				$result = $this->getConnection()->headObject(array(
268
-					'Bucket' => $this->bucket,
269
-					'Key' => $path
270
-				));
271
-
272
-				$stat['size'] = $result['ContentLength'] ? $result['ContentLength'] : 0;
273
-				if ($result['Metadata']['lastmodified']) {
274
-					$stat['mtime'] = strtotime($result['Metadata']['lastmodified']);
275
-				} else {
276
-					$stat['mtime'] = strtotime($result['LastModified']);
277
-				}
278
-			}
279
-			$stat['atime'] = time();
280
-
281
-			return $stat;
282
-		} catch(S3Exception $e) {
283
-			\OCP\Util::logException('files_external', $e);
284
-			return false;
285
-		}
286
-	}
287
-
288
-	public function filetype($path) {
289
-		$path = $this->normalizePath($path);
290
-
291
-		if ($this->isRoot($path)) {
292
-			return 'dir';
293
-		}
294
-
295
-		try {
296
-			if ($this->getConnection()->doesObjectExist($this->bucket, $path)) {
297
-				return 'file';
298
-			}
299
-			if ($this->getConnection()->doesObjectExist($this->bucket, $path.'/')) {
300
-				return 'dir';
301
-			}
302
-		} catch (S3Exception $e) {
303
-			\OCP\Util::logException('files_external', $e);
304
-			return false;
305
-		}
306
-
307
-		return false;
308
-	}
309
-
310
-	public function unlink($path) {
311
-		$path = $this->normalizePath($path);
312
-
313
-		if ($this->is_dir($path)) {
314
-			return $this->rmdir($path);
315
-		}
316
-
317
-		try {
318
-			$this->getConnection()->deleteObject(array(
319
-				'Bucket' => $this->bucket,
320
-				'Key' => $path
321
-			));
322
-			$this->testTimeout();
323
-		} catch (S3Exception $e) {
324
-			\OCP\Util::logException('files_external', $e);
325
-			return false;
326
-		}
327
-
328
-		return true;
329
-	}
330
-
331
-	public function fopen($path, $mode) {
332
-		$path = $this->normalizePath($path);
333
-
334
-		switch ($mode) {
335
-			case 'r':
336
-			case 'rb':
337
-				$tmpFile = \OCP\Files::tmpFile();
338
-				self::$tmpFiles[$tmpFile] = $path;
339
-
340
-				try {
341
-					$this->getConnection()->getObject(array(
342
-						'Bucket' => $this->bucket,
343
-						'Key' => $path,
344
-						'SaveAs' => $tmpFile
345
-					));
346
-				} catch (S3Exception $e) {
347
-					\OCP\Util::logException('files_external', $e);
348
-					return false;
349
-				}
350
-
351
-				return fopen($tmpFile, 'r');
352
-			case 'w':
353
-			case 'wb':
354
-			case 'a':
355
-			case 'ab':
356
-			case 'r+':
357
-			case 'w+':
358
-			case 'wb+':
359
-			case 'a+':
360
-			case 'x':
361
-			case 'x+':
362
-			case 'c':
363
-			case 'c+':
364
-				if (strrpos($path, '.') !== false) {
365
-					$ext = substr($path, strrpos($path, '.'));
366
-				} else {
367
-					$ext = '';
368
-				}
369
-				$tmpFile = \OCP\Files::tmpFile($ext);
370
-				if ($this->file_exists($path)) {
371
-					$source = $this->fopen($path, 'r');
372
-					file_put_contents($tmpFile, $source);
373
-				}
374
-
375
-				$handle = fopen($tmpFile, $mode);
376
-				return CallbackWrapper::wrap($handle, null, null, function() use ($path, $tmpFile) {
377
-					$this->writeBack($tmpFile, $path);
378
-				});
379
-		}
380
-		return false;
381
-	}
382
-
383
-	public function touch($path, $mtime = null) {
384
-		$path = $this->normalizePath($path);
385
-
386
-		$metadata = array();
387
-		if (is_null($mtime)) {
388
-			$mtime = time();
389
-		}
390
-		$metadata = [
391
-			'lastmodified' => gmdate(\Aws\Common\Enum\DateFormat::RFC1123, $mtime)
392
-		];
393
-
394
-		$fileType = $this->filetype($path);
395
-		try {
396
-			if ($fileType !== false) {
397
-				if ($fileType === 'dir' && ! $this->isRoot($path)) {
398
-					$path .= '/';
399
-				}
400
-				$this->getConnection()->copyObject([
401
-					'Bucket' => $this->bucket,
402
-					'Key' => $this->cleanKey($path),
403
-					'Metadata' => $metadata,
404
-					'CopySource' => $this->bucket . '/' . $path,
405
-					'MetadataDirective' => 'REPLACE',
406
-				]);
407
-				$this->testTimeout();
408
-			} else {
409
-				$mimeType = \OC::$server->getMimeTypeDetector()->detectPath($path);
410
-				$this->getConnection()->putObject([
411
-					'Bucket' => $this->bucket,
412
-					'Key' => $this->cleanKey($path),
413
-					'Metadata' => $metadata,
414
-					'Body' => '',
415
-					'ContentType' => $mimeType,
416
-					'MetadataDirective' => 'REPLACE',
417
-				]);
418
-				$this->testTimeout();
419
-			}
420
-		} catch (S3Exception $e) {
421
-			\OCP\Util::logException('files_external', $e);
422
-			return false;
423
-		}
424
-
425
-		return true;
426
-	}
427
-
428
-	public function copy($path1, $path2) {
429
-		$path1 = $this->normalizePath($path1);
430
-		$path2 = $this->normalizePath($path2);
431
-
432
-		if ($this->is_file($path1)) {
433
-			try {
434
-				$this->getConnection()->copyObject(array(
435
-					'Bucket' => $this->bucket,
436
-					'Key' => $this->cleanKey($path2),
437
-					'CopySource' => S3Client::encodeKey($this->bucket . '/' . $path1)
438
-				));
439
-				$this->testTimeout();
440
-			} catch (S3Exception $e) {
441
-				\OCP\Util::logException('files_external', $e);
442
-				return false;
443
-			}
444
-		} else {
445
-			$this->remove($path2);
446
-
447
-			try {
448
-				$this->getConnection()->copyObject(array(
449
-					'Bucket' => $this->bucket,
450
-					'Key' => $path2 . '/',
451
-					'CopySource' => S3Client::encodeKey($this->bucket . '/' . $path1 . '/')
452
-				));
453
-				$this->testTimeout();
454
-			} catch (S3Exception $e) {
455
-				\OCP\Util::logException('files_external', $e);
456
-				return false;
457
-			}
458
-
459
-			$dh = $this->opendir($path1);
460
-			if (is_resource($dh)) {
461
-				while (($file = readdir($dh)) !== false) {
462
-					if (\OC\Files\Filesystem::isIgnoredDir($file)) {
463
-						continue;
464
-					}
465
-
466
-					$source = $path1 . '/' . $file;
467
-					$target = $path2 . '/' . $file;
468
-					$this->copy($source, $target);
469
-				}
470
-			}
471
-		}
472
-
473
-		return true;
474
-	}
475
-
476
-	public function rename($path1, $path2) {
477
-		$path1 = $this->normalizePath($path1);
478
-		$path2 = $this->normalizePath($path2);
479
-
480
-		if ($this->is_file($path1)) {
481
-
482
-			if ($this->copy($path1, $path2) === false) {
483
-				return false;
484
-			}
485
-
486
-			if ($this->unlink($path1) === false) {
487
-				$this->unlink($path2);
488
-				return false;
489
-			}
490
-		} else {
491
-
492
-			if ($this->copy($path1, $path2) === false) {
493
-				return false;
494
-			}
495
-
496
-			if ($this->rmdir($path1) === false) {
497
-				$this->rmdir($path2);
498
-				return false;
499
-			}
500
-		}
501
-
502
-		return true;
503
-	}
504
-
505
-	public function test() {
506
-		$test = $this->getConnection()->getBucketAcl(array(
507
-			'Bucket' => $this->bucket,
508
-		));
509
-		if (isset($test) && !is_null($test->getPath('Owner/ID'))) {
510
-			return true;
511
-		}
512
-		return false;
513
-	}
514
-
515
-	public function getId() {
516
-		return $this->id;
517
-	}
518
-
519
-	public function writeBack($tmpFile, $path) {
520
-		try {
521
-			$this->getConnection()->putObject(array(
522
-				'Bucket' => $this->bucket,
523
-				'Key' => $this->cleanKey($path),
524
-				'SourceFile' => $tmpFile,
525
-				'ContentType' => \OC::$server->getMimeTypeDetector()->detect($tmpFile),
526
-				'ContentLength' => filesize($tmpFile)
527
-			));
528
-			$this->testTimeout();
529
-
530
-			unlink($tmpFile);
531
-		} catch (S3Exception $e) {
532
-			\OCP\Util::logException('files_external', $e);
533
-			return false;
534
-		}
535
-	}
536
-
537
-	/**
538
-	 * check if curl is installed
539
-	 */
540
-	public static function checkDependencies() {
541
-		return true;
542
-	}
50
+    use S3ConnectionTrait;
51
+
52
+    /**
53
+     * @var array
54
+     */
55
+    private static $tmpFiles = array();
56
+
57
+    /**
58
+     * @var int in seconds
59
+     */
60
+    private $rescanDelay = 10;
61
+
62
+    public function __construct($parameters) {
63
+        parent::__construct($parameters);
64
+        $this->parseParams($parameters);
65
+    }
66
+
67
+    /**
68
+     * @param string $path
69
+     * @return string correctly encoded path
70
+     */
71
+    private function normalizePath($path) {
72
+        $path = trim($path, '/');
73
+
74
+        if (!$path) {
75
+            $path = '.';
76
+        }
77
+
78
+        return $path;
79
+    }
80
+
81
+    private function isRoot($path) {
82
+        return $path === '.';
83
+    }
84
+
85
+    private function cleanKey($path) {
86
+        if ($this->isRoot($path)) {
87
+            return '/';
88
+        }
89
+        return $path;
90
+    }
91
+
92
+    /**
93
+     * Updates old storage ids (v0.2.1 and older) that are based on key and secret to new ones based on the bucket name.
94
+     * TODO Do this in an update.php. requires iterating over all users and loading the mount.json from their home
95
+     *
96
+     * @param array $params
97
+     */
98
+    public function updateLegacyId (array $params) {
99
+        $oldId = 'amazon::' . $params['key'] . md5($params['secret']);
100
+
101
+        // find by old id or bucket
102
+        $stmt = \OC::$server->getDatabaseConnection()->prepare(
103
+            'SELECT `numeric_id`, `id` FROM `*PREFIX*storages` WHERE `id` IN (?, ?)'
104
+        );
105
+        $stmt->execute(array($oldId, $this->id));
106
+        while ($row = $stmt->fetch()) {
107
+            $storages[$row['id']] = $row['numeric_id'];
108
+        }
109
+
110
+        if (isset($storages[$this->id]) && isset($storages[$oldId])) {
111
+            // if both ids exist, delete the old storage and corresponding filecache entries
112
+            \OC\Files\Cache\Storage::remove($oldId);
113
+        } else if (isset($storages[$oldId])) {
114
+            // if only the old id exists do an update
115
+            $stmt = \OC::$server->getDatabaseConnection()->prepare(
116
+                'UPDATE `*PREFIX*storages` SET `id` = ? WHERE `id` = ?'
117
+            );
118
+            $stmt->execute(array($this->id, $oldId));
119
+        }
120
+        // only the bucket based id may exist, do nothing
121
+    }
122
+
123
+    /**
124
+     * Remove a file or folder
125
+     *
126
+     * @param string $path
127
+     * @return bool
128
+     */
129
+    protected function remove($path) {
130
+        // remember fileType to reduce http calls
131
+        $fileType = $this->filetype($path);
132
+        if ($fileType === 'dir') {
133
+            return $this->rmdir($path);
134
+        } else if ($fileType === 'file') {
135
+            return $this->unlink($path);
136
+        } else {
137
+            return false;
138
+        }
139
+    }
140
+
141
+    public function mkdir($path) {
142
+        $path = $this->normalizePath($path);
143
+
144
+        if ($this->is_dir($path)) {
145
+            return false;
146
+        }
147
+
148
+        try {
149
+            $this->getConnection()->putObject(array(
150
+                'Bucket' => $this->bucket,
151
+                'Key' => $path . '/',
152
+                'Body' => '',
153
+                'ContentType' => 'httpd/unix-directory'
154
+            ));
155
+            $this->testTimeout();
156
+        } catch (S3Exception $e) {
157
+            \OCP\Util::logException('files_external', $e);
158
+            return false;
159
+        }
160
+
161
+        return true;
162
+    }
163
+
164
+    public function file_exists($path) {
165
+        return $this->filetype($path) !== false;
166
+    }
167
+
168
+
169
+    public function rmdir($path) {
170
+        $path = $this->normalizePath($path);
171
+
172
+        if ($this->isRoot($path)) {
173
+            return $this->clearBucket();
174
+        }
175
+
176
+        if (!$this->file_exists($path)) {
177
+            return false;
178
+        }
179
+
180
+        return $this->batchDelete($path);
181
+    }
182
+
183
+    protected function clearBucket() {
184
+        try {
185
+            $this->getConnection()->clearBucket($this->bucket);
186
+            return true;
187
+            // clearBucket() is not working with Ceph, so if it fails we try the slower approach
188
+        } catch (\Exception $e) {
189
+            return $this->batchDelete();
190
+        }
191
+        return false;
192
+    }
193
+
194
+    private function batchDelete ($path = null) {
195
+        $params = array(
196
+            'Bucket' => $this->bucket
197
+        );
198
+        if ($path !== null) {
199
+            $params['Prefix'] = $path . '/';
200
+        }
201
+        try {
202
+            // Since there are no real directories on S3, we need
203
+            // to delete all objects prefixed with the path.
204
+            do {
205
+                // instead of the iterator, manually loop over the list ...
206
+                $objects = $this->getConnection()->listObjects($params);
207
+                // ... so we can delete the files in batches
208
+                $this->getConnection()->deleteObjects(array(
209
+                    'Bucket' => $this->bucket,
210
+                    'Objects' => $objects['Contents']
211
+                ));
212
+                $this->testTimeout();
213
+                // we reached the end when the list is no longer truncated
214
+            } while ($objects['IsTruncated']);
215
+        } catch (S3Exception $e) {
216
+            \OCP\Util::logException('files_external', $e);
217
+            return false;
218
+        }
219
+        return true;
220
+    }
221
+
222
+    public function opendir($path) {
223
+        $path = $this->normalizePath($path);
224
+
225
+        if ($this->isRoot($path)) {
226
+            $path = '';
227
+        } else {
228
+            $path .= '/';
229
+        }
230
+
231
+        try {
232
+            $files = array();
233
+            $result = $this->getConnection()->getIterator('ListObjects', array(
234
+                'Bucket' => $this->bucket,
235
+                'Delimiter' => '/',
236
+                'Prefix' => $path
237
+            ), array('return_prefixes' => true));
238
+
239
+            foreach ($result as $object) {
240
+                if (isset($object['Key']) && $object['Key'] === $path) {
241
+                    // it's the directory itself, skip
242
+                    continue;
243
+                }
244
+                $file = basename(
245
+                    isset($object['Key']) ? $object['Key'] : $object['Prefix']
246
+                );
247
+                $files[] = $file;
248
+            }
249
+
250
+            return IteratorDirectory::wrap($files);
251
+        } catch (S3Exception $e) {
252
+            \OCP\Util::logException('files_external', $e);
253
+            return false;
254
+        }
255
+    }
256
+
257
+    public function stat($path) {
258
+        $path = $this->normalizePath($path);
259
+
260
+        try {
261
+            $stat = array();
262
+            if ($this->is_dir($path)) {
263
+                //folders don't really exist
264
+                $stat['size'] = -1; //unknown
265
+                $stat['mtime'] = time() - $this->rescanDelay * 1000;
266
+            } else {
267
+                $result = $this->getConnection()->headObject(array(
268
+                    'Bucket' => $this->bucket,
269
+                    'Key' => $path
270
+                ));
271
+
272
+                $stat['size'] = $result['ContentLength'] ? $result['ContentLength'] : 0;
273
+                if ($result['Metadata']['lastmodified']) {
274
+                    $stat['mtime'] = strtotime($result['Metadata']['lastmodified']);
275
+                } else {
276
+                    $stat['mtime'] = strtotime($result['LastModified']);
277
+                }
278
+            }
279
+            $stat['atime'] = time();
280
+
281
+            return $stat;
282
+        } catch(S3Exception $e) {
283
+            \OCP\Util::logException('files_external', $e);
284
+            return false;
285
+        }
286
+    }
287
+
288
+    public function filetype($path) {
289
+        $path = $this->normalizePath($path);
290
+
291
+        if ($this->isRoot($path)) {
292
+            return 'dir';
293
+        }
294
+
295
+        try {
296
+            if ($this->getConnection()->doesObjectExist($this->bucket, $path)) {
297
+                return 'file';
298
+            }
299
+            if ($this->getConnection()->doesObjectExist($this->bucket, $path.'/')) {
300
+                return 'dir';
301
+            }
302
+        } catch (S3Exception $e) {
303
+            \OCP\Util::logException('files_external', $e);
304
+            return false;
305
+        }
306
+
307
+        return false;
308
+    }
309
+
310
+    public function unlink($path) {
311
+        $path = $this->normalizePath($path);
312
+
313
+        if ($this->is_dir($path)) {
314
+            return $this->rmdir($path);
315
+        }
316
+
317
+        try {
318
+            $this->getConnection()->deleteObject(array(
319
+                'Bucket' => $this->bucket,
320
+                'Key' => $path
321
+            ));
322
+            $this->testTimeout();
323
+        } catch (S3Exception $e) {
324
+            \OCP\Util::logException('files_external', $e);
325
+            return false;
326
+        }
327
+
328
+        return true;
329
+    }
330
+
331
+    public function fopen($path, $mode) {
332
+        $path = $this->normalizePath($path);
333
+
334
+        switch ($mode) {
335
+            case 'r':
336
+            case 'rb':
337
+                $tmpFile = \OCP\Files::tmpFile();
338
+                self::$tmpFiles[$tmpFile] = $path;
339
+
340
+                try {
341
+                    $this->getConnection()->getObject(array(
342
+                        'Bucket' => $this->bucket,
343
+                        'Key' => $path,
344
+                        'SaveAs' => $tmpFile
345
+                    ));
346
+                } catch (S3Exception $e) {
347
+                    \OCP\Util::logException('files_external', $e);
348
+                    return false;
349
+                }
350
+
351
+                return fopen($tmpFile, 'r');
352
+            case 'w':
353
+            case 'wb':
354
+            case 'a':
355
+            case 'ab':
356
+            case 'r+':
357
+            case 'w+':
358
+            case 'wb+':
359
+            case 'a+':
360
+            case 'x':
361
+            case 'x+':
362
+            case 'c':
363
+            case 'c+':
364
+                if (strrpos($path, '.') !== false) {
365
+                    $ext = substr($path, strrpos($path, '.'));
366
+                } else {
367
+                    $ext = '';
368
+                }
369
+                $tmpFile = \OCP\Files::tmpFile($ext);
370
+                if ($this->file_exists($path)) {
371
+                    $source = $this->fopen($path, 'r');
372
+                    file_put_contents($tmpFile, $source);
373
+                }
374
+
375
+                $handle = fopen($tmpFile, $mode);
376
+                return CallbackWrapper::wrap($handle, null, null, function() use ($path, $tmpFile) {
377
+                    $this->writeBack($tmpFile, $path);
378
+                });
379
+        }
380
+        return false;
381
+    }
382
+
383
+    public function touch($path, $mtime = null) {
384
+        $path = $this->normalizePath($path);
385
+
386
+        $metadata = array();
387
+        if (is_null($mtime)) {
388
+            $mtime = time();
389
+        }
390
+        $metadata = [
391
+            'lastmodified' => gmdate(\Aws\Common\Enum\DateFormat::RFC1123, $mtime)
392
+        ];
393
+
394
+        $fileType = $this->filetype($path);
395
+        try {
396
+            if ($fileType !== false) {
397
+                if ($fileType === 'dir' && ! $this->isRoot($path)) {
398
+                    $path .= '/';
399
+                }
400
+                $this->getConnection()->copyObject([
401
+                    'Bucket' => $this->bucket,
402
+                    'Key' => $this->cleanKey($path),
403
+                    'Metadata' => $metadata,
404
+                    'CopySource' => $this->bucket . '/' . $path,
405
+                    'MetadataDirective' => 'REPLACE',
406
+                ]);
407
+                $this->testTimeout();
408
+            } else {
409
+                $mimeType = \OC::$server->getMimeTypeDetector()->detectPath($path);
410
+                $this->getConnection()->putObject([
411
+                    'Bucket' => $this->bucket,
412
+                    'Key' => $this->cleanKey($path),
413
+                    'Metadata' => $metadata,
414
+                    'Body' => '',
415
+                    'ContentType' => $mimeType,
416
+                    'MetadataDirective' => 'REPLACE',
417
+                ]);
418
+                $this->testTimeout();
419
+            }
420
+        } catch (S3Exception $e) {
421
+            \OCP\Util::logException('files_external', $e);
422
+            return false;
423
+        }
424
+
425
+        return true;
426
+    }
427
+
428
+    public function copy($path1, $path2) {
429
+        $path1 = $this->normalizePath($path1);
430
+        $path2 = $this->normalizePath($path2);
431
+
432
+        if ($this->is_file($path1)) {
433
+            try {
434
+                $this->getConnection()->copyObject(array(
435
+                    'Bucket' => $this->bucket,
436
+                    'Key' => $this->cleanKey($path2),
437
+                    'CopySource' => S3Client::encodeKey($this->bucket . '/' . $path1)
438
+                ));
439
+                $this->testTimeout();
440
+            } catch (S3Exception $e) {
441
+                \OCP\Util::logException('files_external', $e);
442
+                return false;
443
+            }
444
+        } else {
445
+            $this->remove($path2);
446
+
447
+            try {
448
+                $this->getConnection()->copyObject(array(
449
+                    'Bucket' => $this->bucket,
450
+                    'Key' => $path2 . '/',
451
+                    'CopySource' => S3Client::encodeKey($this->bucket . '/' . $path1 . '/')
452
+                ));
453
+                $this->testTimeout();
454
+            } catch (S3Exception $e) {
455
+                \OCP\Util::logException('files_external', $e);
456
+                return false;
457
+            }
458
+
459
+            $dh = $this->opendir($path1);
460
+            if (is_resource($dh)) {
461
+                while (($file = readdir($dh)) !== false) {
462
+                    if (\OC\Files\Filesystem::isIgnoredDir($file)) {
463
+                        continue;
464
+                    }
465
+
466
+                    $source = $path1 . '/' . $file;
467
+                    $target = $path2 . '/' . $file;
468
+                    $this->copy($source, $target);
469
+                }
470
+            }
471
+        }
472
+
473
+        return true;
474
+    }
475
+
476
+    public function rename($path1, $path2) {
477
+        $path1 = $this->normalizePath($path1);
478
+        $path2 = $this->normalizePath($path2);
479
+
480
+        if ($this->is_file($path1)) {
481
+
482
+            if ($this->copy($path1, $path2) === false) {
483
+                return false;
484
+            }
485
+
486
+            if ($this->unlink($path1) === false) {
487
+                $this->unlink($path2);
488
+                return false;
489
+            }
490
+        } else {
491
+
492
+            if ($this->copy($path1, $path2) === false) {
493
+                return false;
494
+            }
495
+
496
+            if ($this->rmdir($path1) === false) {
497
+                $this->rmdir($path2);
498
+                return false;
499
+            }
500
+        }
501
+
502
+        return true;
503
+    }
504
+
505
+    public function test() {
506
+        $test = $this->getConnection()->getBucketAcl(array(
507
+            'Bucket' => $this->bucket,
508
+        ));
509
+        if (isset($test) && !is_null($test->getPath('Owner/ID'))) {
510
+            return true;
511
+        }
512
+        return false;
513
+    }
514
+
515
+    public function getId() {
516
+        return $this->id;
517
+    }
518
+
519
+    public function writeBack($tmpFile, $path) {
520
+        try {
521
+            $this->getConnection()->putObject(array(
522
+                'Bucket' => $this->bucket,
523
+                'Key' => $this->cleanKey($path),
524
+                'SourceFile' => $tmpFile,
525
+                'ContentType' => \OC::$server->getMimeTypeDetector()->detect($tmpFile),
526
+                'ContentLength' => filesize($tmpFile)
527
+            ));
528
+            $this->testTimeout();
529
+
530
+            unlink($tmpFile);
531
+        } catch (S3Exception $e) {
532
+            \OCP\Util::logException('files_external', $e);
533
+            return false;
534
+        }
535
+    }
536
+
537
+    /**
538
+     * check if curl is installed
539
+     */
540
+    public static function checkDependencies() {
541
+        return true;
542
+    }
543 543
 
544 544
 }
Please login to merge, or discard this patch.
Spacing   +15 added lines, -15 removed lines patch added patch discarded remove patch
@@ -36,8 +36,8 @@  discard block
 block discarded – undo
36 36
 
37 37
 namespace OCA\Files_External\Lib\Storage;
38 38
 
39
-set_include_path(get_include_path() . PATH_SEPARATOR .
40
-	\OC_App::getAppPath('files_external') . '/3rdparty/aws-sdk-php');
39
+set_include_path(get_include_path().PATH_SEPARATOR.
40
+	\OC_App::getAppPath('files_external').'/3rdparty/aws-sdk-php');
41 41
 require_once 'aws-autoloader.php';
42 42
 
43 43
 use Aws\S3\S3Client;
@@ -95,8 +95,8 @@  discard block
 block discarded – undo
95 95
 	 *
96 96
 	 * @param array $params
97 97
 	 */
98
-	public function updateLegacyId (array $params) {
99
-		$oldId = 'amazon::' . $params['key'] . md5($params['secret']);
98
+	public function updateLegacyId(array $params) {
99
+		$oldId = 'amazon::'.$params['key'].md5($params['secret']);
100 100
 
101 101
 		// find by old id or bucket
102 102
 		$stmt = \OC::$server->getDatabaseConnection()->prepare(
@@ -148,7 +148,7 @@  discard block
 block discarded – undo
148 148
 		try {
149 149
 			$this->getConnection()->putObject(array(
150 150
 				'Bucket' => $this->bucket,
151
-				'Key' => $path . '/',
151
+				'Key' => $path.'/',
152 152
 				'Body' => '',
153 153
 				'ContentType' => 'httpd/unix-directory'
154 154
 			));
@@ -191,12 +191,12 @@  discard block
 block discarded – undo
191 191
 		return false;
192 192
 	}
193 193
 
194
-	private function batchDelete ($path = null) {
194
+	private function batchDelete($path = null) {
195 195
 		$params = array(
196 196
 			'Bucket' => $this->bucket
197 197
 		);
198 198
 		if ($path !== null) {
199
-			$params['Prefix'] = $path . '/';
199
+			$params['Prefix'] = $path.'/';
200 200
 		}
201 201
 		try {
202 202
 			// Since there are no real directories on S3, we need
@@ -279,7 +279,7 @@  discard block
 block discarded – undo
279 279
 			$stat['atime'] = time();
280 280
 
281 281
 			return $stat;
282
-		} catch(S3Exception $e) {
282
+		} catch (S3Exception $e) {
283 283
 			\OCP\Util::logException('files_external', $e);
284 284
 			return false;
285 285
 		}
@@ -394,14 +394,14 @@  discard block
 block discarded – undo
394 394
 		$fileType = $this->filetype($path);
395 395
 		try {
396 396
 			if ($fileType !== false) {
397
-				if ($fileType === 'dir' && ! $this->isRoot($path)) {
397
+				if ($fileType === 'dir' && !$this->isRoot($path)) {
398 398
 					$path .= '/';
399 399
 				}
400 400
 				$this->getConnection()->copyObject([
401 401
 					'Bucket' => $this->bucket,
402 402
 					'Key' => $this->cleanKey($path),
403 403
 					'Metadata' => $metadata,
404
-					'CopySource' => $this->bucket . '/' . $path,
404
+					'CopySource' => $this->bucket.'/'.$path,
405 405
 					'MetadataDirective' => 'REPLACE',
406 406
 				]);
407 407
 				$this->testTimeout();
@@ -434,7 +434,7 @@  discard block
 block discarded – undo
434 434
 				$this->getConnection()->copyObject(array(
435 435
 					'Bucket' => $this->bucket,
436 436
 					'Key' => $this->cleanKey($path2),
437
-					'CopySource' => S3Client::encodeKey($this->bucket . '/' . $path1)
437
+					'CopySource' => S3Client::encodeKey($this->bucket.'/'.$path1)
438 438
 				));
439 439
 				$this->testTimeout();
440 440
 			} catch (S3Exception $e) {
@@ -447,8 +447,8 @@  discard block
 block discarded – undo
447 447
 			try {
448 448
 				$this->getConnection()->copyObject(array(
449 449
 					'Bucket' => $this->bucket,
450
-					'Key' => $path2 . '/',
451
-					'CopySource' => S3Client::encodeKey($this->bucket . '/' . $path1 . '/')
450
+					'Key' => $path2.'/',
451
+					'CopySource' => S3Client::encodeKey($this->bucket.'/'.$path1.'/')
452 452
 				));
453 453
 				$this->testTimeout();
454 454
 			} catch (S3Exception $e) {
@@ -463,8 +463,8 @@  discard block
 block discarded – undo
463 463
 						continue;
464 464
 					}
465 465
 
466
-					$source = $path1 . '/' . $file;
467
-					$target = $path2 . '/' . $file;
466
+					$source = $path1.'/'.$file;
467
+					$target = $path2.'/'.$file;
468 468
 					$this->copy($source, $target);
469 469
 				}
470 470
 			}
Please login to merge, or discard this patch.