Passed
Push — master ( 62403d...0c3e2f )
by Joas
14:50 queued 14s
created
apps/dav/lib/Connector/Sabre/Directory.php 1 patch
Indentation   +401 added lines, -401 removed lines patch added patch discarded remove patch
@@ -50,405 +50,405 @@
 block discarded – undo
50 50
 use Sabre\DAV\INode;
51 51
 
52 52
 class Directory extends \OCA\DAV\Connector\Sabre\Node
53
-	implements \Sabre\DAV\ICollection, \Sabre\DAV\IQuota, \Sabre\DAV\IMoveTarget {
54
-
55
-	/**
56
-	 * Cached directory content
57
-	 *
58
-	 * @var \OCP\Files\FileInfo[]
59
-	 */
60
-	private $dirContent;
61
-
62
-	/**
63
-	 * Cached quota info
64
-	 *
65
-	 * @var array
66
-	 */
67
-	private $quotaInfo;
68
-
69
-	/**
70
-	 * @var ObjectTree|null
71
-	 */
72
-	private $tree;
73
-
74
-	/**
75
-	 * Sets up the node, expects a full path name
76
-	 *
77
-	 * @param \OC\Files\View $view
78
-	 * @param \OCP\Files\FileInfo $info
79
-	 * @param ObjectTree|null $tree
80
-	 * @param \OCP\Share\IManager $shareManager
81
-	 */
82
-	public function __construct(View $view, FileInfo $info, $tree = null, $shareManager = null) {
83
-		parent::__construct($view, $info, $shareManager);
84
-		$this->tree = $tree;
85
-	}
86
-
87
-	/**
88
-	 * Creates a new file in the directory
89
-	 *
90
-	 * Data will either be supplied as a stream resource, or in certain cases
91
-	 * as a string. Keep in mind that you may have to support either.
92
-	 *
93
-	 * After successful creation of the file, you may choose to return the ETag
94
-	 * of the new file here.
95
-	 *
96
-	 * The returned ETag must be surrounded by double-quotes (The quotes should
97
-	 * be part of the actual string).
98
-	 *
99
-	 * If you cannot accurately determine the ETag, you should not return it.
100
-	 * If you don't store the file exactly as-is (you're transforming it
101
-	 * somehow) you should also not return an ETag.
102
-	 *
103
-	 * This means that if a subsequent GET to this new file does not exactly
104
-	 * return the same contents of what was submitted here, you are strongly
105
-	 * recommended to omit the ETag.
106
-	 *
107
-	 * @param string $name Name of the file
108
-	 * @param resource|string $data Initial payload
109
-	 * @return null|string
110
-	 * @throws Exception\EntityTooLarge
111
-	 * @throws Exception\UnsupportedMediaType
112
-	 * @throws FileLocked
113
-	 * @throws InvalidPath
114
-	 * @throws \Sabre\DAV\Exception
115
-	 * @throws \Sabre\DAV\Exception\BadRequest
116
-	 * @throws \Sabre\DAV\Exception\Forbidden
117
-	 * @throws \Sabre\DAV\Exception\ServiceUnavailable
118
-	 */
119
-	public function createFile($name, $data = null) {
120
-
121
-		try {
122
-			// for chunked upload also updating a existing file is a "createFile"
123
-			// because we create all the chunks before re-assemble them to the existing file.
124
-			if (isset($_SERVER['HTTP_OC_CHUNKED'])) {
125
-
126
-				// exit if we can't create a new file and we don't updatable existing file
127
-				$chunkInfo = \OC_FileChunking::decodeName($name);
128
-				if (!$this->fileView->isCreatable($this->path) &&
129
-					!$this->fileView->isUpdatable($this->path . '/' . $chunkInfo['name'])
130
-				) {
131
-					throw new \Sabre\DAV\Exception\Forbidden();
132
-				}
133
-
134
-			} else {
135
-				// For non-chunked upload it is enough to check if we can create a new file
136
-				if (!$this->fileView->isCreatable($this->path)) {
137
-					throw new \Sabre\DAV\Exception\Forbidden();
138
-				}
139
-			}
140
-
141
-			$this->fileView->verifyPath($this->path, $name);
142
-
143
-			$path = $this->fileView->getAbsolutePath($this->path) . '/' . $name;
144
-			// in case the file already exists/overwriting
145
-			$info = $this->fileView->getFileInfo($this->path . '/' . $name);
146
-			if (!$info) {
147
-				// use a dummy FileInfo which is acceptable here since it will be refreshed after the put is complete
148
-				$info = new \OC\Files\FileInfo($path, null, null, [], null);
149
-			}
150
-			$node = new \OCA\DAV\Connector\Sabre\File($this->fileView, $info);
151
-
152
-			// only allow 1 process to upload a file at once but still allow reading the file while writing the part file
153
-			$node->acquireLock(ILockingProvider::LOCK_SHARED);
154
-			$this->fileView->lockFile($path . '.upload.part', ILockingProvider::LOCK_EXCLUSIVE);
155
-
156
-			$result = $node->put($data);
157
-
158
-			$this->fileView->unlockFile($path . '.upload.part', ILockingProvider::LOCK_EXCLUSIVE);
159
-			$node->releaseLock(ILockingProvider::LOCK_SHARED);
160
-			return $result;
161
-		} catch (\OCP\Files\StorageNotAvailableException $e) {
162
-			throw new \Sabre\DAV\Exception\ServiceUnavailable($e->getMessage(), $e->getCode(), $e);
163
-		} catch (InvalidPathException $ex) {
164
-			throw new InvalidPath($ex->getMessage(), false, $ex);
165
-		} catch (ForbiddenException $ex) {
166
-			throw new Forbidden($ex->getMessage(), $ex->getRetry(), $ex);
167
-		} catch (LockedException $e) {
168
-			throw new FileLocked($e->getMessage(), $e->getCode(), $e);
169
-		}
170
-	}
171
-
172
-	/**
173
-	 * Creates a new subdirectory
174
-	 *
175
-	 * @param string $name
176
-	 * @throws FileLocked
177
-	 * @throws InvalidPath
178
-	 * @throws \Sabre\DAV\Exception\Forbidden
179
-	 * @throws \Sabre\DAV\Exception\ServiceUnavailable
180
-	 */
181
-	public function createDirectory($name) {
182
-		try {
183
-			if (!$this->info->isCreatable()) {
184
-				throw new \Sabre\DAV\Exception\Forbidden();
185
-			}
186
-
187
-			$this->fileView->verifyPath($this->path, $name);
188
-			$newPath = $this->path . '/' . $name;
189
-			if (!$this->fileView->mkdir($newPath)) {
190
-				throw new \Sabre\DAV\Exception\Forbidden('Could not create directory ' . $newPath);
191
-			}
192
-		} catch (\OCP\Files\StorageNotAvailableException $e) {
193
-			throw new \Sabre\DAV\Exception\ServiceUnavailable($e->getMessage());
194
-		} catch (InvalidPathException $ex) {
195
-			throw new InvalidPath($ex->getMessage());
196
-		} catch (ForbiddenException $ex) {
197
-			throw new Forbidden($ex->getMessage(), $ex->getRetry());
198
-		} catch (LockedException $e) {
199
-			throw new FileLocked($e->getMessage(), $e->getCode(), $e);
200
-		}
201
-	}
202
-
203
-	/**
204
-	 * Returns a specific child node, referenced by its name
205
-	 *
206
-	 * @param string $name
207
-	 * @param \OCP\Files\FileInfo $info
208
-	 * @return \Sabre\DAV\INode
209
-	 * @throws InvalidPath
210
-	 * @throws \Sabre\DAV\Exception\NotFound
211
-	 * @throws \Sabre\DAV\Exception\ServiceUnavailable
212
-	 */
213
-	public function getChild($name, $info = null) {
214
-		if (!$this->info->isReadable()) {
215
-			// avoid detecting files through this way
216
-			throw new NotFound();
217
-		}
218
-
219
-		$path = $this->path . '/' . $name;
220
-		if (is_null($info)) {
221
-			try {
222
-				$this->fileView->verifyPath($this->path, $name);
223
-				$info = $this->fileView->getFileInfo($path);
224
-			} catch (\OCP\Files\StorageNotAvailableException $e) {
225
-				throw new \Sabre\DAV\Exception\ServiceUnavailable($e->getMessage());
226
-			} catch (InvalidPathException $ex) {
227
-				throw new InvalidPath($ex->getMessage());
228
-			} catch (ForbiddenException $e) {
229
-				throw new \Sabre\DAV\Exception\Forbidden();
230
-			}
231
-		}
232
-
233
-		if (!$info) {
234
-			throw new \Sabre\DAV\Exception\NotFound('File with name ' . $path . ' could not be located');
235
-		}
236
-
237
-		if ($info['mimetype'] === 'httpd/unix-directory') {
238
-			$node = new \OCA\DAV\Connector\Sabre\Directory($this->fileView, $info, $this->tree, $this->shareManager);
239
-		} else {
240
-			$node = new \OCA\DAV\Connector\Sabre\File($this->fileView, $info, $this->shareManager);
241
-		}
242
-		if ($this->tree) {
243
-			$this->tree->cacheNode($node);
244
-		}
245
-		return $node;
246
-	}
247
-
248
-	/**
249
-	 * Returns an array with all the child nodes
250
-	 *
251
-	 * @return \Sabre\DAV\INode[]
252
-	 * @throws \Sabre\DAV\Exception\Locked
253
-	 * @throws \OCA\DAV\Connector\Sabre\Exception\Forbidden
254
-	 */
255
-	public function getChildren() {
256
-		if (!is_null($this->dirContent)) {
257
-			return $this->dirContent;
258
-		}
259
-		try {
260
-			if (!$this->info->isReadable()) {
261
-				// return 403 instead of 404 because a 404 would make
262
-				// the caller believe that the collection itself does not exist
263
-				throw new Forbidden('No read permissions');
264
-			}
265
-			$folderContent = $this->fileView->getDirectoryContent($this->path);
266
-		} catch (LockedException $e) {
267
-			throw new Locked();
268
-		}
269
-
270
-		$nodes = [];
271
-		foreach ($folderContent as $info) {
272
-			$node = $this->getChild($info->getName(), $info);
273
-			$nodes[] = $node;
274
-		}
275
-		$this->dirContent = $nodes;
276
-		return $this->dirContent;
277
-	}
278
-
279
-	/**
280
-	 * Checks if a child exists.
281
-	 *
282
-	 * @param string $name
283
-	 * @return bool
284
-	 */
285
-	public function childExists($name) {
286
-		// note: here we do NOT resolve the chunk file name to the real file name
287
-		// to make sure we return false when checking for file existence with a chunk
288
-		// file name.
289
-		// This is to make sure that "createFile" is still triggered
290
-		// (required old code) instead of "updateFile".
291
-		//
292
-		// TODO: resolve chunk file name here and implement "updateFile"
293
-		$path = $this->path . '/' . $name;
294
-		return $this->fileView->file_exists($path);
295
-
296
-	}
297
-
298
-	/**
299
-	 * Deletes all files in this directory, and then itself
300
-	 *
301
-	 * @return void
302
-	 * @throws FileLocked
303
-	 * @throws \Sabre\DAV\Exception\Forbidden
304
-	 */
305
-	public function delete() {
306
-
307
-		if ($this->path === '' || $this->path === '/' || !$this->info->isDeletable()) {
308
-			throw new \Sabre\DAV\Exception\Forbidden();
309
-		}
310
-
311
-		try {
312
-			if (!$this->fileView->rmdir($this->path)) {
313
-				// assume it wasn't possible to remove due to permission issue
314
-				throw new \Sabre\DAV\Exception\Forbidden();
315
-			}
316
-		} catch (ForbiddenException $ex) {
317
-			throw new Forbidden($ex->getMessage(), $ex->getRetry());
318
-		} catch (LockedException $e) {
319
-			throw new FileLocked($e->getMessage(), $e->getCode(), $e);
320
-		}
321
-	}
322
-
323
-	/**
324
-	 * Returns available diskspace information
325
-	 *
326
-	 * @return array
327
-	 */
328
-	public function getQuotaInfo() {
329
-		if ($this->quotaInfo) {
330
-			return $this->quotaInfo;
331
-		}
332
-		try {
333
-			$storageInfo = \OC_Helper::getStorageInfo($this->info->getPath(), $this->info);
334
-			if ($storageInfo['quota'] === \OCP\Files\FileInfo::SPACE_UNLIMITED) {
335
-				$free = \OCP\Files\FileInfo::SPACE_UNLIMITED;
336
-			} else {
337
-				$free = $storageInfo['free'];
338
-			}
339
-			$this->quotaInfo = [
340
-				$storageInfo['used'],
341
-				$free
342
-			];
343
-			return $this->quotaInfo;
344
-		} catch (\OCP\Files\StorageNotAvailableException $e) {
345
-			return [0, 0];
346
-		}
347
-	}
348
-
349
-	/**
350
-	 * Moves a node into this collection.
351
-	 *
352
-	 * It is up to the implementors to:
353
-	 *   1. Create the new resource.
354
-	 *   2. Remove the old resource.
355
-	 *   3. Transfer any properties or other data.
356
-	 *
357
-	 * Generally you should make very sure that your collection can easily move
358
-	 * the move.
359
-	 *
360
-	 * If you don't, just return false, which will trigger sabre/dav to handle
361
-	 * the move itself. If you return true from this function, the assumption
362
-	 * is that the move was successful.
363
-	 *
364
-	 * @param string $targetName New local file/collection name.
365
-	 * @param string $fullSourcePath Full path to source node
366
-	 * @param INode $sourceNode Source node itself
367
-	 * @return bool
368
-	 * @throws BadRequest
369
-	 * @throws ServiceUnavailable
370
-	 * @throws Forbidden
371
-	 * @throws FileLocked
372
-	 * @throws \Sabre\DAV\Exception\Forbidden
373
-	 */
374
-	public function moveInto($targetName, $fullSourcePath, INode $sourceNode) {
375
-		if (!$sourceNode instanceof Node) {
376
-			// it's a file of another kind, like FutureFile
377
-			if ($sourceNode instanceof IFile) {
378
-				// fallback to default copy+delete handling
379
-				return false;
380
-			}
381
-			throw new BadRequest('Incompatible node types');
382
-		}
383
-
384
-		if (!$this->fileView) {
385
-			throw new ServiceUnavailable('filesystem not setup');
386
-		}
387
-
388
-		$destinationPath = $this->getPath() . '/' . $targetName;
389
-
390
-
391
-		$targetNodeExists = $this->childExists($targetName);
392
-
393
-		// at getNodeForPath we also check the path for isForbiddenFileOrDir
394
-		// with that we have covered both source and destination
395
-		if ($sourceNode instanceof Directory && $targetNodeExists) {
396
-			throw new \Sabre\DAV\Exception\Forbidden('Could not copy directory ' . $sourceNode->getName() . ', target exists');
397
-		}
398
-
399
-		list($sourceDir,) = \Sabre\Uri\split($sourceNode->getPath());
400
-		$destinationDir = $this->getPath();
401
-
402
-		$sourcePath = $sourceNode->getPath();
403
-
404
-		$isMovableMount = false;
405
-		$sourceMount = \OC::$server->getMountManager()->find($this->fileView->getAbsolutePath($sourcePath));
406
-		$internalPath = $sourceMount->getInternalPath($this->fileView->getAbsolutePath($sourcePath));
407
-		if ($sourceMount instanceof MoveableMount && $internalPath === '') {
408
-			$isMovableMount = true;
409
-		}
410
-
411
-		try {
412
-			$sameFolder = ($sourceDir === $destinationDir);
413
-			// if we're overwriting or same folder
414
-			if ($targetNodeExists || $sameFolder) {
415
-				// note that renaming a share mount point is always allowed
416
-				if (!$this->fileView->isUpdatable($destinationDir) && !$isMovableMount) {
417
-					throw new \Sabre\DAV\Exception\Forbidden();
418
-				}
419
-			} else {
420
-				if (!$this->fileView->isCreatable($destinationDir)) {
421
-					throw new \Sabre\DAV\Exception\Forbidden();
422
-				}
423
-			}
424
-
425
-			if (!$sameFolder) {
426
-				// moving to a different folder, source will be gone, like a deletion
427
-				// note that moving a share mount point is always allowed
428
-				if (!$this->fileView->isDeletable($sourcePath) && !$isMovableMount) {
429
-					throw new \Sabre\DAV\Exception\Forbidden();
430
-				}
431
-			}
432
-
433
-			$fileName = basename($destinationPath);
434
-			try {
435
-				$this->fileView->verifyPath($destinationDir, $fileName);
436
-			} catch (InvalidPathException $ex) {
437
-				throw new InvalidPath($ex->getMessage());
438
-			}
439
-
440
-			$renameOkay = $this->fileView->rename($sourcePath, $destinationPath);
441
-			if (!$renameOkay) {
442
-				throw new \Sabre\DAV\Exception\Forbidden('');
443
-			}
444
-		} catch (StorageNotAvailableException $e) {
445
-			throw new ServiceUnavailable($e->getMessage());
446
-		} catch (ForbiddenException $ex) {
447
-			throw new Forbidden($ex->getMessage(), $ex->getRetry());
448
-		} catch (LockedException $e) {
449
-			throw new FileLocked($e->getMessage(), $e->getCode(), $e);
450
-		}
451
-
452
-		return true;
453
-	}
53
+    implements \Sabre\DAV\ICollection, \Sabre\DAV\IQuota, \Sabre\DAV\IMoveTarget {
54
+
55
+    /**
56
+     * Cached directory content
57
+     *
58
+     * @var \OCP\Files\FileInfo[]
59
+     */
60
+    private $dirContent;
61
+
62
+    /**
63
+     * Cached quota info
64
+     *
65
+     * @var array
66
+     */
67
+    private $quotaInfo;
68
+
69
+    /**
70
+     * @var ObjectTree|null
71
+     */
72
+    private $tree;
73
+
74
+    /**
75
+     * Sets up the node, expects a full path name
76
+     *
77
+     * @param \OC\Files\View $view
78
+     * @param \OCP\Files\FileInfo $info
79
+     * @param ObjectTree|null $tree
80
+     * @param \OCP\Share\IManager $shareManager
81
+     */
82
+    public function __construct(View $view, FileInfo $info, $tree = null, $shareManager = null) {
83
+        parent::__construct($view, $info, $shareManager);
84
+        $this->tree = $tree;
85
+    }
86
+
87
+    /**
88
+     * Creates a new file in the directory
89
+     *
90
+     * Data will either be supplied as a stream resource, or in certain cases
91
+     * as a string. Keep in mind that you may have to support either.
92
+     *
93
+     * After successful creation of the file, you may choose to return the ETag
94
+     * of the new file here.
95
+     *
96
+     * The returned ETag must be surrounded by double-quotes (The quotes should
97
+     * be part of the actual string).
98
+     *
99
+     * If you cannot accurately determine the ETag, you should not return it.
100
+     * If you don't store the file exactly as-is (you're transforming it
101
+     * somehow) you should also not return an ETag.
102
+     *
103
+     * This means that if a subsequent GET to this new file does not exactly
104
+     * return the same contents of what was submitted here, you are strongly
105
+     * recommended to omit the ETag.
106
+     *
107
+     * @param string $name Name of the file
108
+     * @param resource|string $data Initial payload
109
+     * @return null|string
110
+     * @throws Exception\EntityTooLarge
111
+     * @throws Exception\UnsupportedMediaType
112
+     * @throws FileLocked
113
+     * @throws InvalidPath
114
+     * @throws \Sabre\DAV\Exception
115
+     * @throws \Sabre\DAV\Exception\BadRequest
116
+     * @throws \Sabre\DAV\Exception\Forbidden
117
+     * @throws \Sabre\DAV\Exception\ServiceUnavailable
118
+     */
119
+    public function createFile($name, $data = null) {
120
+
121
+        try {
122
+            // for chunked upload also updating a existing file is a "createFile"
123
+            // because we create all the chunks before re-assemble them to the existing file.
124
+            if (isset($_SERVER['HTTP_OC_CHUNKED'])) {
125
+
126
+                // exit if we can't create a new file and we don't updatable existing file
127
+                $chunkInfo = \OC_FileChunking::decodeName($name);
128
+                if (!$this->fileView->isCreatable($this->path) &&
129
+                    !$this->fileView->isUpdatable($this->path . '/' . $chunkInfo['name'])
130
+                ) {
131
+                    throw new \Sabre\DAV\Exception\Forbidden();
132
+                }
133
+
134
+            } else {
135
+                // For non-chunked upload it is enough to check if we can create a new file
136
+                if (!$this->fileView->isCreatable($this->path)) {
137
+                    throw new \Sabre\DAV\Exception\Forbidden();
138
+                }
139
+            }
140
+
141
+            $this->fileView->verifyPath($this->path, $name);
142
+
143
+            $path = $this->fileView->getAbsolutePath($this->path) . '/' . $name;
144
+            // in case the file already exists/overwriting
145
+            $info = $this->fileView->getFileInfo($this->path . '/' . $name);
146
+            if (!$info) {
147
+                // use a dummy FileInfo which is acceptable here since it will be refreshed after the put is complete
148
+                $info = new \OC\Files\FileInfo($path, null, null, [], null);
149
+            }
150
+            $node = new \OCA\DAV\Connector\Sabre\File($this->fileView, $info);
151
+
152
+            // only allow 1 process to upload a file at once but still allow reading the file while writing the part file
153
+            $node->acquireLock(ILockingProvider::LOCK_SHARED);
154
+            $this->fileView->lockFile($path . '.upload.part', ILockingProvider::LOCK_EXCLUSIVE);
155
+
156
+            $result = $node->put($data);
157
+
158
+            $this->fileView->unlockFile($path . '.upload.part', ILockingProvider::LOCK_EXCLUSIVE);
159
+            $node->releaseLock(ILockingProvider::LOCK_SHARED);
160
+            return $result;
161
+        } catch (\OCP\Files\StorageNotAvailableException $e) {
162
+            throw new \Sabre\DAV\Exception\ServiceUnavailable($e->getMessage(), $e->getCode(), $e);
163
+        } catch (InvalidPathException $ex) {
164
+            throw new InvalidPath($ex->getMessage(), false, $ex);
165
+        } catch (ForbiddenException $ex) {
166
+            throw new Forbidden($ex->getMessage(), $ex->getRetry(), $ex);
167
+        } catch (LockedException $e) {
168
+            throw new FileLocked($e->getMessage(), $e->getCode(), $e);
169
+        }
170
+    }
171
+
172
+    /**
173
+     * Creates a new subdirectory
174
+     *
175
+     * @param string $name
176
+     * @throws FileLocked
177
+     * @throws InvalidPath
178
+     * @throws \Sabre\DAV\Exception\Forbidden
179
+     * @throws \Sabre\DAV\Exception\ServiceUnavailable
180
+     */
181
+    public function createDirectory($name) {
182
+        try {
183
+            if (!$this->info->isCreatable()) {
184
+                throw new \Sabre\DAV\Exception\Forbidden();
185
+            }
186
+
187
+            $this->fileView->verifyPath($this->path, $name);
188
+            $newPath = $this->path . '/' . $name;
189
+            if (!$this->fileView->mkdir($newPath)) {
190
+                throw new \Sabre\DAV\Exception\Forbidden('Could not create directory ' . $newPath);
191
+            }
192
+        } catch (\OCP\Files\StorageNotAvailableException $e) {
193
+            throw new \Sabre\DAV\Exception\ServiceUnavailable($e->getMessage());
194
+        } catch (InvalidPathException $ex) {
195
+            throw new InvalidPath($ex->getMessage());
196
+        } catch (ForbiddenException $ex) {
197
+            throw new Forbidden($ex->getMessage(), $ex->getRetry());
198
+        } catch (LockedException $e) {
199
+            throw new FileLocked($e->getMessage(), $e->getCode(), $e);
200
+        }
201
+    }
202
+
203
+    /**
204
+     * Returns a specific child node, referenced by its name
205
+     *
206
+     * @param string $name
207
+     * @param \OCP\Files\FileInfo $info
208
+     * @return \Sabre\DAV\INode
209
+     * @throws InvalidPath
210
+     * @throws \Sabre\DAV\Exception\NotFound
211
+     * @throws \Sabre\DAV\Exception\ServiceUnavailable
212
+     */
213
+    public function getChild($name, $info = null) {
214
+        if (!$this->info->isReadable()) {
215
+            // avoid detecting files through this way
216
+            throw new NotFound();
217
+        }
218
+
219
+        $path = $this->path . '/' . $name;
220
+        if (is_null($info)) {
221
+            try {
222
+                $this->fileView->verifyPath($this->path, $name);
223
+                $info = $this->fileView->getFileInfo($path);
224
+            } catch (\OCP\Files\StorageNotAvailableException $e) {
225
+                throw new \Sabre\DAV\Exception\ServiceUnavailable($e->getMessage());
226
+            } catch (InvalidPathException $ex) {
227
+                throw new InvalidPath($ex->getMessage());
228
+            } catch (ForbiddenException $e) {
229
+                throw new \Sabre\DAV\Exception\Forbidden();
230
+            }
231
+        }
232
+
233
+        if (!$info) {
234
+            throw new \Sabre\DAV\Exception\NotFound('File with name ' . $path . ' could not be located');
235
+        }
236
+
237
+        if ($info['mimetype'] === 'httpd/unix-directory') {
238
+            $node = new \OCA\DAV\Connector\Sabre\Directory($this->fileView, $info, $this->tree, $this->shareManager);
239
+        } else {
240
+            $node = new \OCA\DAV\Connector\Sabre\File($this->fileView, $info, $this->shareManager);
241
+        }
242
+        if ($this->tree) {
243
+            $this->tree->cacheNode($node);
244
+        }
245
+        return $node;
246
+    }
247
+
248
+    /**
249
+     * Returns an array with all the child nodes
250
+     *
251
+     * @return \Sabre\DAV\INode[]
252
+     * @throws \Sabre\DAV\Exception\Locked
253
+     * @throws \OCA\DAV\Connector\Sabre\Exception\Forbidden
254
+     */
255
+    public function getChildren() {
256
+        if (!is_null($this->dirContent)) {
257
+            return $this->dirContent;
258
+        }
259
+        try {
260
+            if (!$this->info->isReadable()) {
261
+                // return 403 instead of 404 because a 404 would make
262
+                // the caller believe that the collection itself does not exist
263
+                throw new Forbidden('No read permissions');
264
+            }
265
+            $folderContent = $this->fileView->getDirectoryContent($this->path);
266
+        } catch (LockedException $e) {
267
+            throw new Locked();
268
+        }
269
+
270
+        $nodes = [];
271
+        foreach ($folderContent as $info) {
272
+            $node = $this->getChild($info->getName(), $info);
273
+            $nodes[] = $node;
274
+        }
275
+        $this->dirContent = $nodes;
276
+        return $this->dirContent;
277
+    }
278
+
279
+    /**
280
+     * Checks if a child exists.
281
+     *
282
+     * @param string $name
283
+     * @return bool
284
+     */
285
+    public function childExists($name) {
286
+        // note: here we do NOT resolve the chunk file name to the real file name
287
+        // to make sure we return false when checking for file existence with a chunk
288
+        // file name.
289
+        // This is to make sure that "createFile" is still triggered
290
+        // (required old code) instead of "updateFile".
291
+        //
292
+        // TODO: resolve chunk file name here and implement "updateFile"
293
+        $path = $this->path . '/' . $name;
294
+        return $this->fileView->file_exists($path);
295
+
296
+    }
297
+
298
+    /**
299
+     * Deletes all files in this directory, and then itself
300
+     *
301
+     * @return void
302
+     * @throws FileLocked
303
+     * @throws \Sabre\DAV\Exception\Forbidden
304
+     */
305
+    public function delete() {
306
+
307
+        if ($this->path === '' || $this->path === '/' || !$this->info->isDeletable()) {
308
+            throw new \Sabre\DAV\Exception\Forbidden();
309
+        }
310
+
311
+        try {
312
+            if (!$this->fileView->rmdir($this->path)) {
313
+                // assume it wasn't possible to remove due to permission issue
314
+                throw new \Sabre\DAV\Exception\Forbidden();
315
+            }
316
+        } catch (ForbiddenException $ex) {
317
+            throw new Forbidden($ex->getMessage(), $ex->getRetry());
318
+        } catch (LockedException $e) {
319
+            throw new FileLocked($e->getMessage(), $e->getCode(), $e);
320
+        }
321
+    }
322
+
323
+    /**
324
+     * Returns available diskspace information
325
+     *
326
+     * @return array
327
+     */
328
+    public function getQuotaInfo() {
329
+        if ($this->quotaInfo) {
330
+            return $this->quotaInfo;
331
+        }
332
+        try {
333
+            $storageInfo = \OC_Helper::getStorageInfo($this->info->getPath(), $this->info);
334
+            if ($storageInfo['quota'] === \OCP\Files\FileInfo::SPACE_UNLIMITED) {
335
+                $free = \OCP\Files\FileInfo::SPACE_UNLIMITED;
336
+            } else {
337
+                $free = $storageInfo['free'];
338
+            }
339
+            $this->quotaInfo = [
340
+                $storageInfo['used'],
341
+                $free
342
+            ];
343
+            return $this->quotaInfo;
344
+        } catch (\OCP\Files\StorageNotAvailableException $e) {
345
+            return [0, 0];
346
+        }
347
+    }
348
+
349
+    /**
350
+     * Moves a node into this collection.
351
+     *
352
+     * It is up to the implementors to:
353
+     *   1. Create the new resource.
354
+     *   2. Remove the old resource.
355
+     *   3. Transfer any properties or other data.
356
+     *
357
+     * Generally you should make very sure that your collection can easily move
358
+     * the move.
359
+     *
360
+     * If you don't, just return false, which will trigger sabre/dav to handle
361
+     * the move itself. If you return true from this function, the assumption
362
+     * is that the move was successful.
363
+     *
364
+     * @param string $targetName New local file/collection name.
365
+     * @param string $fullSourcePath Full path to source node
366
+     * @param INode $sourceNode Source node itself
367
+     * @return bool
368
+     * @throws BadRequest
369
+     * @throws ServiceUnavailable
370
+     * @throws Forbidden
371
+     * @throws FileLocked
372
+     * @throws \Sabre\DAV\Exception\Forbidden
373
+     */
374
+    public function moveInto($targetName, $fullSourcePath, INode $sourceNode) {
375
+        if (!$sourceNode instanceof Node) {
376
+            // it's a file of another kind, like FutureFile
377
+            if ($sourceNode instanceof IFile) {
378
+                // fallback to default copy+delete handling
379
+                return false;
380
+            }
381
+            throw new BadRequest('Incompatible node types');
382
+        }
383
+
384
+        if (!$this->fileView) {
385
+            throw new ServiceUnavailable('filesystem not setup');
386
+        }
387
+
388
+        $destinationPath = $this->getPath() . '/' . $targetName;
389
+
390
+
391
+        $targetNodeExists = $this->childExists($targetName);
392
+
393
+        // at getNodeForPath we also check the path for isForbiddenFileOrDir
394
+        // with that we have covered both source and destination
395
+        if ($sourceNode instanceof Directory && $targetNodeExists) {
396
+            throw new \Sabre\DAV\Exception\Forbidden('Could not copy directory ' . $sourceNode->getName() . ', target exists');
397
+        }
398
+
399
+        list($sourceDir,) = \Sabre\Uri\split($sourceNode->getPath());
400
+        $destinationDir = $this->getPath();
401
+
402
+        $sourcePath = $sourceNode->getPath();
403
+
404
+        $isMovableMount = false;
405
+        $sourceMount = \OC::$server->getMountManager()->find($this->fileView->getAbsolutePath($sourcePath));
406
+        $internalPath = $sourceMount->getInternalPath($this->fileView->getAbsolutePath($sourcePath));
407
+        if ($sourceMount instanceof MoveableMount && $internalPath === '') {
408
+            $isMovableMount = true;
409
+        }
410
+
411
+        try {
412
+            $sameFolder = ($sourceDir === $destinationDir);
413
+            // if we're overwriting or same folder
414
+            if ($targetNodeExists || $sameFolder) {
415
+                // note that renaming a share mount point is always allowed
416
+                if (!$this->fileView->isUpdatable($destinationDir) && !$isMovableMount) {
417
+                    throw new \Sabre\DAV\Exception\Forbidden();
418
+                }
419
+            } else {
420
+                if (!$this->fileView->isCreatable($destinationDir)) {
421
+                    throw new \Sabre\DAV\Exception\Forbidden();
422
+                }
423
+            }
424
+
425
+            if (!$sameFolder) {
426
+                // moving to a different folder, source will be gone, like a deletion
427
+                // note that moving a share mount point is always allowed
428
+                if (!$this->fileView->isDeletable($sourcePath) && !$isMovableMount) {
429
+                    throw new \Sabre\DAV\Exception\Forbidden();
430
+                }
431
+            }
432
+
433
+            $fileName = basename($destinationPath);
434
+            try {
435
+                $this->fileView->verifyPath($destinationDir, $fileName);
436
+            } catch (InvalidPathException $ex) {
437
+                throw new InvalidPath($ex->getMessage());
438
+            }
439
+
440
+            $renameOkay = $this->fileView->rename($sourcePath, $destinationPath);
441
+            if (!$renameOkay) {
442
+                throw new \Sabre\DAV\Exception\Forbidden('');
443
+            }
444
+        } catch (StorageNotAvailableException $e) {
445
+            throw new ServiceUnavailable($e->getMessage());
446
+        } catch (ForbiddenException $ex) {
447
+            throw new Forbidden($ex->getMessage(), $ex->getRetry());
448
+        } catch (LockedException $e) {
449
+            throw new FileLocked($e->getMessage(), $e->getCode(), $e);
450
+        }
451
+
452
+        return true;
453
+    }
454 454
 }
Please login to merge, or discard this patch.
apps/dav/lib/Connector/Sabre/File.php 1 patch
Indentation   +601 added lines, -601 removed lines patch added patch discarded remove patch
@@ -70,605 +70,605 @@
 block discarded – undo
70 70
 
71 71
 class File extends Node implements IFile {
72 72
 
73
-	protected $request;
74
-
75
-	/**
76
-	 * Sets up the node, expects a full path name
77
-	 *
78
-	 * @param \OC\Files\View $view
79
-	 * @param \OCP\Files\FileInfo $info
80
-	 * @param \OCP\Share\IManager $shareManager
81
-	 * @param \OC\AppFramework\Http\Request $request
82
-	 */
83
-	public function __construct(View $view, FileInfo $info, IManager $shareManager = null, Request $request = null) {
84
-		parent::__construct($view, $info, $shareManager);
85
-
86
-		if (isset($request)) {
87
-			$this->request = $request;
88
-		} else {
89
-			$this->request = \OC::$server->getRequest();
90
-		}
91
-	}
92
-
93
-	/**
94
-	 * Updates the data
95
-	 *
96
-	 * The data argument is a readable stream resource.
97
-	 *
98
-	 * After a successful put operation, you may choose to return an ETag. The
99
-	 * etag must always be surrounded by double-quotes. These quotes must
100
-	 * appear in the actual string you're returning.
101
-	 *
102
-	 * Clients may use the ETag from a PUT request to later on make sure that
103
-	 * when they update the file, the contents haven't changed in the mean
104
-	 * time.
105
-	 *
106
-	 * If you don't plan to store the file byte-by-byte, and you return a
107
-	 * different object on a subsequent GET you are strongly recommended to not
108
-	 * return an ETag, and just return null.
109
-	 *
110
-	 * @param resource $data
111
-	 *
112
-	 * @throws Forbidden
113
-	 * @throws UnsupportedMediaType
114
-	 * @throws BadRequest
115
-	 * @throws Exception
116
-	 * @throws EntityTooLarge
117
-	 * @throws ServiceUnavailable
118
-	 * @throws FileLocked
119
-	 * @return string|null
120
-	 */
121
-	public function put($data) {
122
-		try {
123
-			$exists = $this->fileView->file_exists($this->path);
124
-			if ($this->info && $exists && !$this->info->isUpdateable()) {
125
-				throw new Forbidden();
126
-			}
127
-		} catch (StorageNotAvailableException $e) {
128
-			throw new ServiceUnavailable("File is not updatable: " . $e->getMessage());
129
-		}
130
-
131
-		// verify path of the target
132
-		$this->verifyPath();
133
-
134
-		// chunked handling
135
-		if (isset($_SERVER['HTTP_OC_CHUNKED'])) {
136
-			try {
137
-				return $this->createFileChunked($data);
138
-			} catch (\Exception $e) {
139
-				$this->convertToSabreException($e);
140
-			}
141
-		}
142
-
143
-		/** @var Storage $partStorage */
144
-		list($partStorage) = $this->fileView->resolvePath($this->path);
145
-		$needsPartFile = $partStorage->needsPartFile() && (strlen($this->path) > 1);
146
-
147
-		$view = \OC\Files\Filesystem::getView();
148
-
149
-		if ($needsPartFile) {
150
-			// mark file as partial while uploading (ignored by the scanner)
151
-			$partFilePath = $this->getPartFileBasePath($this->path) . '.ocTransferId' . rand() . '.part';
152
-
153
-			if (!$view->isCreatable($partFilePath) && $view->isUpdatable($this->path)) {
154
-				$needsPartFile = false;
155
-			}
156
-		}
157
-		if (!$needsPartFile) {
158
-			// upload file directly as the final path
159
-			$partFilePath = $this->path;
160
-
161
-			if ($view && !$this->emitPreHooks($exists)) {
162
-				throw new Exception('Could not write to final file, canceled by hook');
163
-			}
164
-		}
165
-
166
-		// the part file and target file might be on a different storage in case of a single file storage (e.g. single file share)
167
-		/** @var \OC\Files\Storage\Storage $partStorage */
168
-		list($partStorage, $internalPartPath) = $this->fileView->resolvePath($partFilePath);
169
-		/** @var \OC\Files\Storage\Storage $storage */
170
-		list($storage, $internalPath) = $this->fileView->resolvePath($this->path);
171
-		try {
172
-			if (!$needsPartFile) {
173
-				$this->changeLock(ILockingProvider::LOCK_EXCLUSIVE);
174
-			}
175
-
176
-			if ($partStorage->instanceOfStorage(Storage\IWriteStreamStorage::class)) {
177
-
178
-				if (!is_resource($data)) {
179
-					$tmpData = fopen('php://temp', 'r+');
180
-					if ($data !== null) {
181
-						fwrite($tmpData, $data);
182
-						rewind($tmpData);
183
-					}
184
-					$data = $tmpData;
185
-				}
186
-
187
-				$isEOF = false;
188
-				$wrappedData = CallbackWrapper::wrap($data, null, null, null, null, function ($stream) use (&$isEOF) {
189
-					$isEOF = feof($stream);
190
-				});
191
-
192
-				$count = $partStorage->writeStream($internalPartPath, $wrappedData);
193
-				$result = $count > 0;
194
-
195
-				if ($result === false) {
196
-					$result = $isEOF;
197
-					if (is_resource($wrappedData)) {
198
-						$result = feof($wrappedData);
199
-					}
200
-				}
201
-
202
-			} else {
203
-				$target = $partStorage->fopen($internalPartPath, 'wb');
204
-				if ($target === false) {
205
-					\OC::$server->getLogger()->error('\OC\Files\Filesystem::fopen() failed', ['app' => 'webdav']);
206
-					// because we have no clue about the cause we can only throw back a 500/Internal Server Error
207
-					throw new Exception('Could not write file contents');
208
-				}
209
-				list($count, $result) = \OC_Helper::streamCopy($data, $target);
210
-				fclose($target);
211
-			}
212
-
213
-			if ($result === false) {
214
-				$expected = -1;
215
-				if (isset($_SERVER['CONTENT_LENGTH'])) {
216
-					$expected = $_SERVER['CONTENT_LENGTH'];
217
-				}
218
-				if ($expected !== "0") {
219
-					throw new Exception('Error while copying file to target location (copied bytes: ' . $count . ', expected filesize: ' . $expected . ' )');
220
-				}
221
-			}
222
-
223
-			// if content length is sent by client:
224
-			// double check if the file was fully received
225
-			// compare expected and actual size
226
-			if (isset($_SERVER['CONTENT_LENGTH']) && $_SERVER['REQUEST_METHOD'] === 'PUT') {
227
-				$expected = (int)$_SERVER['CONTENT_LENGTH'];
228
-				if ($count !== $expected) {
229
-					throw new BadRequest('Expected filesize of ' . $expected . ' bytes but read (from Nextcloud client) and wrote (to Nextcloud storage) ' . $count . ' bytes. Could either be a network problem on the sending side or a problem writing to the storage on the server side.');
230
-				}
231
-			}
232
-
233
-		} catch (\Exception $e) {
234
-			$context = [];
235
-
236
-			if ($e instanceof LockedException) {
237
-				$context['level'] = ILogger::DEBUG;
238
-			}
239
-
240
-			\OC::$server->getLogger()->logException($e, $context);
241
-			if ($needsPartFile) {
242
-				$partStorage->unlink($internalPartPath);
243
-			}
244
-			$this->convertToSabreException($e);
245
-		}
246
-
247
-		try {
248
-			if ($needsPartFile) {
249
-				if ($view && !$this->emitPreHooks($exists)) {
250
-					$partStorage->unlink($internalPartPath);
251
-					throw new Exception('Could not rename part file to final file, canceled by hook');
252
-				}
253
-				try {
254
-					$this->changeLock(ILockingProvider::LOCK_EXCLUSIVE);
255
-				} catch (LockedException $e) {
256
-					// during very large uploads, the shared lock we got at the start might have been expired
257
-					// meaning that the above lock can fail not just only because somebody else got a shared lock
258
-					// or because there is no existing shared lock to make exclusive
259
-					//
260
-					// Thus we try to get a new exclusive lock, if the original lock failed because of a different shared
261
-					// lock this will still fail, if our original shared lock expired the new lock will be successful and
262
-					// the entire operation will be safe
263
-
264
-					try {
265
-						$this->acquireLock(ILockingProvider::LOCK_EXCLUSIVE);
266
-					} catch (LockedException $ex) {
267
-						if ($needsPartFile) {
268
-							$partStorage->unlink($internalPartPath);
269
-						}
270
-						throw new FileLocked($e->getMessage(), $e->getCode(), $e);
271
-					}
272
-				}
273
-
274
-				// rename to correct path
275
-				try {
276
-					$renameOkay = $storage->moveFromStorage($partStorage, $internalPartPath, $internalPath);
277
-					$fileExists = $storage->file_exists($internalPath);
278
-					if ($renameOkay === false || $fileExists === false) {
279
-						\OC::$server->getLogger()->error('renaming part file to final file failed $renameOkay: ' . ($renameOkay ? 'true' : 'false') . ', $fileExists: ' . ($fileExists ? 'true' : 'false') . ')', ['app' => 'webdav']);
280
-						throw new Exception('Could not rename part file to final file');
281
-					}
282
-				} catch (ForbiddenException $ex) {
283
-					throw new DAVForbiddenException($ex->getMessage(), $ex->getRetry());
284
-				} catch (\Exception $e) {
285
-					$partStorage->unlink($internalPartPath);
286
-					$this->convertToSabreException($e);
287
-				}
288
-			}
289
-
290
-			// since we skipped the view we need to scan and emit the hooks ourselves
291
-			$storage->getUpdater()->update($internalPath);
292
-
293
-			try {
294
-				$this->changeLock(ILockingProvider::LOCK_SHARED);
295
-			} catch (LockedException $e) {
296
-				throw new FileLocked($e->getMessage(), $e->getCode(), $e);
297
-			}
298
-
299
-			// allow sync clients to send the mtime along in a header
300
-			if (isset($this->request->server['HTTP_X_OC_MTIME'])) {
301
-				$mtime = $this->sanitizeMtime($this->request->server['HTTP_X_OC_MTIME']);
302
-				if ($this->fileView->touch($this->path, $mtime)) {
303
-					$this->header('X-OC-MTime: accepted');
304
-				}
305
-			}
306
-
307
-			$fileInfoUpdate = [
308
-				'upload_time' => time()
309
-			];
310
-
311
-			// allow sync clients to send the creation time along in a header
312
-			if (isset($this->request->server['HTTP_X_OC_CTIME'])) {
313
-				$ctime = $this->sanitizeMtime($this->request->server['HTTP_X_OC_CTIME']);
314
-				$fileInfoUpdate['creation_time'] = $ctime;
315
-				$this->header('X-OC-CTime: accepted');
316
-			}
317
-
318
-			$this->fileView->putFileInfo($this->path, $fileInfoUpdate);
319
-
320
-			if ($view) {
321
-				$this->emitPostHooks($exists);
322
-			}
323
-
324
-			$this->refreshInfo();
325
-
326
-			if (isset($this->request->server['HTTP_OC_CHECKSUM'])) {
327
-				$checksum = trim($this->request->server['HTTP_OC_CHECKSUM']);
328
-				$this->fileView->putFileInfo($this->path, ['checksum' => $checksum]);
329
-				$this->refreshInfo();
330
-			} else if ($this->getChecksum() !== null && $this->getChecksum() !== '') {
331
-				$this->fileView->putFileInfo($this->path, ['checksum' => '']);
332
-				$this->refreshInfo();
333
-			}
334
-
335
-		} catch (StorageNotAvailableException $e) {
336
-			throw new ServiceUnavailable("Failed to check file size: " . $e->getMessage(), 0, $e);
337
-		}
338
-
339
-		return '"' . $this->info->getEtag() . '"';
340
-	}
341
-
342
-	private function getPartFileBasePath($path) {
343
-		$partFileInStorage = \OC::$server->getConfig()->getSystemValue('part_file_in_storage', true);
344
-		if ($partFileInStorage) {
345
-			return $path;
346
-		} else {
347
-			return md5($path); // will place it in the root of the view with a unique name
348
-		}
349
-	}
350
-
351
-	/**
352
-	 * @param string $path
353
-	 */
354
-	private function emitPreHooks($exists, $path = null) {
355
-		if (is_null($path)) {
356
-			$path = $this->path;
357
-		}
358
-		$hookPath = Filesystem::getView()->getRelativePath($this->fileView->getAbsolutePath($path));
359
-		$run = true;
360
-
361
-		if (!$exists) {
362
-			\OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_create, [
363
-				\OC\Files\Filesystem::signal_param_path => $hookPath,
364
-				\OC\Files\Filesystem::signal_param_run => &$run,
365
-			]);
366
-		} else {
367
-			\OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_update, [
368
-				\OC\Files\Filesystem::signal_param_path => $hookPath,
369
-				\OC\Files\Filesystem::signal_param_run => &$run,
370
-			]);
371
-		}
372
-		\OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_write, [
373
-			\OC\Files\Filesystem::signal_param_path => $hookPath,
374
-			\OC\Files\Filesystem::signal_param_run => &$run,
375
-		]);
376
-		return $run;
377
-	}
378
-
379
-	/**
380
-	 * @param string $path
381
-	 */
382
-	private function emitPostHooks($exists, $path = null) {
383
-		if (is_null($path)) {
384
-			$path = $this->path;
385
-		}
386
-		$hookPath = Filesystem::getView()->getRelativePath($this->fileView->getAbsolutePath($path));
387
-		if (!$exists) {
388
-			\OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_post_create, [
389
-				\OC\Files\Filesystem::signal_param_path => $hookPath
390
-			]);
391
-		} else {
392
-			\OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_post_update, [
393
-				\OC\Files\Filesystem::signal_param_path => $hookPath
394
-			]);
395
-		}
396
-		\OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_post_write, [
397
-			\OC\Files\Filesystem::signal_param_path => $hookPath
398
-		]);
399
-	}
400
-
401
-	/**
402
-	 * Returns the data
403
-	 *
404
-	 * @return resource
405
-	 * @throws Forbidden
406
-	 * @throws ServiceUnavailable
407
-	 */
408
-	public function get() {
409
-		//throw exception if encryption is disabled but files are still encrypted
410
-		try {
411
-			if (!$this->info->isReadable()) {
412
-				// do a if the file did not exist
413
-				throw new NotFound();
414
-			}
415
-			try {
416
-				$res = $this->fileView->fopen(ltrim($this->path, '/'), 'rb');
417
-			} catch (\Exception $e) {
418
-				$this->convertToSabreException($e);
419
-			}
420
-			if ($res === false) {
421
-				throw new ServiceUnavailable("Could not open file");
422
-			}
423
-			return $res;
424
-		} catch (GenericEncryptionException $e) {
425
-			// returning 503 will allow retry of the operation at a later point in time
426
-			throw new ServiceUnavailable("Encryption not ready: " . $e->getMessage());
427
-		} catch (StorageNotAvailableException $e) {
428
-			throw new ServiceUnavailable("Failed to open file: " . $e->getMessage());
429
-		} catch (ForbiddenException $ex) {
430
-			throw new DAVForbiddenException($ex->getMessage(), $ex->getRetry());
431
-		} catch (LockedException $e) {
432
-			throw new FileLocked($e->getMessage(), $e->getCode(), $e);
433
-		}
434
-	}
435
-
436
-	/**
437
-	 * Delete the current file
438
-	 *
439
-	 * @throws Forbidden
440
-	 * @throws ServiceUnavailable
441
-	 */
442
-	public function delete() {
443
-		if (!$this->info->isDeletable()) {
444
-			throw new Forbidden();
445
-		}
446
-
447
-		try {
448
-			if (!$this->fileView->unlink($this->path)) {
449
-				// assume it wasn't possible to delete due to permissions
450
-				throw new Forbidden();
451
-			}
452
-		} catch (StorageNotAvailableException $e) {
453
-			throw new ServiceUnavailable("Failed to unlink: " . $e->getMessage());
454
-		} catch (ForbiddenException $ex) {
455
-			throw new DAVForbiddenException($ex->getMessage(), $ex->getRetry());
456
-		} catch (LockedException $e) {
457
-			throw new FileLocked($e->getMessage(), $e->getCode(), $e);
458
-		}
459
-	}
460
-
461
-	/**
462
-	 * Returns the mime-type for a file
463
-	 *
464
-	 * If null is returned, we'll assume application/octet-stream
465
-	 *
466
-	 * @return string
467
-	 */
468
-	public function getContentType() {
469
-		$mimeType = $this->info->getMimetype();
470
-
471
-		// PROPFIND needs to return the correct mime type, for consistency with the web UI
472
-		if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PROPFIND') {
473
-			return $mimeType;
474
-		}
475
-		return \OC::$server->getMimeTypeDetector()->getSecureMimeType($mimeType);
476
-	}
477
-
478
-	/**
479
-	 * @return array|false
480
-	 */
481
-	public function getDirectDownload() {
482
-		if (\OCP\App::isEnabled('encryption')) {
483
-			return [];
484
-		}
485
-		/** @var \OCP\Files\Storage $storage */
486
-		list($storage, $internalPath) = $this->fileView->resolvePath($this->path);
487
-		if (is_null($storage)) {
488
-			return [];
489
-		}
490
-
491
-		return $storage->getDirectDownload($internalPath);
492
-	}
493
-
494
-	/**
495
-	 * @param resource $data
496
-	 * @return null|string
497
-	 * @throws Exception
498
-	 * @throws BadRequest
499
-	 * @throws NotImplemented
500
-	 * @throws ServiceUnavailable
501
-	 */
502
-	private function createFileChunked($data) {
503
-		list($path, $name) = \Sabre\Uri\split($this->path);
504
-
505
-		$info = \OC_FileChunking::decodeName($name);
506
-		if (empty($info)) {
507
-			throw new NotImplemented('Invalid chunk name');
508
-		}
509
-
510
-		$chunk_handler = new \OC_FileChunking($info);
511
-		$bytesWritten = $chunk_handler->store($info['index'], $data);
512
-
513
-		//detect aborted upload
514
-		if (isset ($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PUT') {
515
-			if (isset($_SERVER['CONTENT_LENGTH'])) {
516
-				$expected = (int)$_SERVER['CONTENT_LENGTH'];
517
-				if ($bytesWritten !== $expected) {
518
-					$chunk_handler->remove($info['index']);
519
-					throw new BadRequest('Expected filesize of ' . $expected . ' bytes but read (from Nextcloud client) and wrote (to Nextcloud storage) ' . $bytesWritten . ' bytes. Could either be a network problem on the sending side or a problem writing to the storage on the server side.');
520
-				}
521
-			}
522
-		}
523
-
524
-		if ($chunk_handler->isComplete()) {
525
-			/** @var Storage $storage */
526
-			list($storage,) = $this->fileView->resolvePath($path);
527
-			$needsPartFile = $storage->needsPartFile();
528
-			$partFile = null;
529
-
530
-			$targetPath = $path . '/' . $info['name'];
531
-			/** @var \OC\Files\Storage\Storage $targetStorage */
532
-			list($targetStorage, $targetInternalPath) = $this->fileView->resolvePath($targetPath);
533
-
534
-			$exists = $this->fileView->file_exists($targetPath);
535
-
536
-			try {
537
-				$this->fileView->lockFile($targetPath, ILockingProvider::LOCK_SHARED);
538
-
539
-				$this->emitPreHooks($exists, $targetPath);
540
-				$this->fileView->changeLock($targetPath, ILockingProvider::LOCK_EXCLUSIVE);
541
-				/** @var \OC\Files\Storage\Storage $targetStorage */
542
-				list($targetStorage, $targetInternalPath) = $this->fileView->resolvePath($targetPath);
543
-
544
-				if ($needsPartFile) {
545
-					// we first assembly the target file as a part file
546
-					$partFile = $this->getPartFileBasePath($path . '/' . $info['name']) . '.ocTransferId' . $info['transferid'] . '.part';
547
-					/** @var \OC\Files\Storage\Storage $targetStorage */
548
-					list($partStorage, $partInternalPath) = $this->fileView->resolvePath($partFile);
549
-
550
-
551
-					$chunk_handler->file_assemble($partStorage, $partInternalPath);
552
-
553
-					// here is the final atomic rename
554
-					$renameOkay = $targetStorage->moveFromStorage($partStorage, $partInternalPath, $targetInternalPath);
555
-					$fileExists = $targetStorage->file_exists($targetInternalPath);
556
-					if ($renameOkay === false || $fileExists === false) {
557
-						\OC::$server->getLogger()->error('\OC\Files\Filesystem::rename() failed', ['app' => 'webdav']);
558
-						// only delete if an error occurred and the target file was already created
559
-						if ($fileExists) {
560
-							// set to null to avoid double-deletion when handling exception
561
-							// stray part file
562
-							$partFile = null;
563
-							$targetStorage->unlink($targetInternalPath);
564
-						}
565
-						$this->fileView->changeLock($targetPath, ILockingProvider::LOCK_SHARED);
566
-						throw new Exception('Could not rename part file assembled from chunks');
567
-					}
568
-				} else {
569
-					// assemble directly into the final file
570
-					$chunk_handler->file_assemble($targetStorage, $targetInternalPath);
571
-				}
572
-
573
-				// allow sync clients to send the mtime along in a header
574
-				if (isset($this->request->server['HTTP_X_OC_MTIME'])) {
575
-					$mtime = $this->sanitizeMtime($this->request->server['HTTP_X_OC_MTIME']);
576
-					if ($targetStorage->touch($targetInternalPath, $mtime)) {
577
-						$this->header('X-OC-MTime: accepted');
578
-					}
579
-				}
580
-
581
-				// since we skipped the view we need to scan and emit the hooks ourselves
582
-				$targetStorage->getUpdater()->update($targetInternalPath);
583
-
584
-				$this->fileView->changeLock($targetPath, ILockingProvider::LOCK_SHARED);
585
-
586
-				$this->emitPostHooks($exists, $targetPath);
587
-
588
-				// FIXME: should call refreshInfo but can't because $this->path is not the of the final file
589
-				$info = $this->fileView->getFileInfo($targetPath);
590
-
591
-				if (isset($this->request->server['HTTP_OC_CHECKSUM'])) {
592
-					$checksum = trim($this->request->server['HTTP_OC_CHECKSUM']);
593
-					$this->fileView->putFileInfo($targetPath, ['checksum' => $checksum]);
594
-				} else if ($info->getChecksum() !== null && $info->getChecksum() !== '') {
595
-					$this->fileView->putFileInfo($this->path, ['checksum' => '']);
596
-				}
597
-
598
-				$this->fileView->unlockFile($targetPath, ILockingProvider::LOCK_SHARED);
599
-
600
-				return $info->getEtag();
601
-			} catch (\Exception $e) {
602
-				if ($partFile !== null) {
603
-					$targetStorage->unlink($targetInternalPath);
604
-				}
605
-				$this->convertToSabreException($e);
606
-			}
607
-		}
608
-
609
-		return null;
610
-	}
611
-
612
-	/**
613
-	 * Convert the given exception to a SabreException instance
614
-	 *
615
-	 * @param \Exception $e
616
-	 *
617
-	 * @throws \Sabre\DAV\Exception
618
-	 */
619
-	private function convertToSabreException(\Exception $e) {
620
-		if ($e instanceof \Sabre\DAV\Exception) {
621
-			throw $e;
622
-		}
623
-		if ($e instanceof NotPermittedException) {
624
-			// a more general case - due to whatever reason the content could not be written
625
-			throw new Forbidden($e->getMessage(), 0, $e);
626
-		}
627
-		if ($e instanceof ForbiddenException) {
628
-			// the path for the file was forbidden
629
-			throw new DAVForbiddenException($e->getMessage(), $e->getRetry(), $e);
630
-		}
631
-		if ($e instanceof EntityTooLargeException) {
632
-			// the file is too big to be stored
633
-			throw new EntityTooLarge($e->getMessage(), 0, $e);
634
-		}
635
-		if ($e instanceof InvalidContentException) {
636
-			// the file content is not permitted
637
-			throw new UnsupportedMediaType($e->getMessage(), 0, $e);
638
-		}
639
-		if ($e instanceof InvalidPathException) {
640
-			// the path for the file was not valid
641
-			// TODO: find proper http status code for this case
642
-			throw new Forbidden($e->getMessage(), 0, $e);
643
-		}
644
-		if ($e instanceof LockedException || $e instanceof LockNotAcquiredException) {
645
-			// the file is currently being written to by another process
646
-			throw new FileLocked($e->getMessage(), $e->getCode(), $e);
647
-		}
648
-		if ($e instanceof GenericEncryptionException) {
649
-			// returning 503 will allow retry of the operation at a later point in time
650
-			throw new ServiceUnavailable('Encryption not ready: ' . $e->getMessage(), 0, $e);
651
-		}
652
-		if ($e instanceof StorageNotAvailableException) {
653
-			throw new ServiceUnavailable('Failed to write file contents: ' . $e->getMessage(), 0, $e);
654
-		}
655
-		if ($e instanceof NotFoundException) {
656
-			throw new NotFound('File not found: ' . $e->getMessage(), 0, $e);
657
-		}
658
-
659
-		throw new \Sabre\DAV\Exception($e->getMessage(), 0, $e);
660
-	}
661
-
662
-	/**
663
-	 * Get the checksum for this file
664
-	 *
665
-	 * @return string
666
-	 */
667
-	public function getChecksum() {
668
-		return $this->info->getChecksum();
669
-	}
670
-
671
-	protected function header($string) {
672
-		\header($string);
673
-	}
73
+    protected $request;
74
+
75
+    /**
76
+     * Sets up the node, expects a full path name
77
+     *
78
+     * @param \OC\Files\View $view
79
+     * @param \OCP\Files\FileInfo $info
80
+     * @param \OCP\Share\IManager $shareManager
81
+     * @param \OC\AppFramework\Http\Request $request
82
+     */
83
+    public function __construct(View $view, FileInfo $info, IManager $shareManager = null, Request $request = null) {
84
+        parent::__construct($view, $info, $shareManager);
85
+
86
+        if (isset($request)) {
87
+            $this->request = $request;
88
+        } else {
89
+            $this->request = \OC::$server->getRequest();
90
+        }
91
+    }
92
+
93
+    /**
94
+     * Updates the data
95
+     *
96
+     * The data argument is a readable stream resource.
97
+     *
98
+     * After a successful put operation, you may choose to return an ETag. The
99
+     * etag must always be surrounded by double-quotes. These quotes must
100
+     * appear in the actual string you're returning.
101
+     *
102
+     * Clients may use the ETag from a PUT request to later on make sure that
103
+     * when they update the file, the contents haven't changed in the mean
104
+     * time.
105
+     *
106
+     * If you don't plan to store the file byte-by-byte, and you return a
107
+     * different object on a subsequent GET you are strongly recommended to not
108
+     * return an ETag, and just return null.
109
+     *
110
+     * @param resource $data
111
+     *
112
+     * @throws Forbidden
113
+     * @throws UnsupportedMediaType
114
+     * @throws BadRequest
115
+     * @throws Exception
116
+     * @throws EntityTooLarge
117
+     * @throws ServiceUnavailable
118
+     * @throws FileLocked
119
+     * @return string|null
120
+     */
121
+    public function put($data) {
122
+        try {
123
+            $exists = $this->fileView->file_exists($this->path);
124
+            if ($this->info && $exists && !$this->info->isUpdateable()) {
125
+                throw new Forbidden();
126
+            }
127
+        } catch (StorageNotAvailableException $e) {
128
+            throw new ServiceUnavailable("File is not updatable: " . $e->getMessage());
129
+        }
130
+
131
+        // verify path of the target
132
+        $this->verifyPath();
133
+
134
+        // chunked handling
135
+        if (isset($_SERVER['HTTP_OC_CHUNKED'])) {
136
+            try {
137
+                return $this->createFileChunked($data);
138
+            } catch (\Exception $e) {
139
+                $this->convertToSabreException($e);
140
+            }
141
+        }
142
+
143
+        /** @var Storage $partStorage */
144
+        list($partStorage) = $this->fileView->resolvePath($this->path);
145
+        $needsPartFile = $partStorage->needsPartFile() && (strlen($this->path) > 1);
146
+
147
+        $view = \OC\Files\Filesystem::getView();
148
+
149
+        if ($needsPartFile) {
150
+            // mark file as partial while uploading (ignored by the scanner)
151
+            $partFilePath = $this->getPartFileBasePath($this->path) . '.ocTransferId' . rand() . '.part';
152
+
153
+            if (!$view->isCreatable($partFilePath) && $view->isUpdatable($this->path)) {
154
+                $needsPartFile = false;
155
+            }
156
+        }
157
+        if (!$needsPartFile) {
158
+            // upload file directly as the final path
159
+            $partFilePath = $this->path;
160
+
161
+            if ($view && !$this->emitPreHooks($exists)) {
162
+                throw new Exception('Could not write to final file, canceled by hook');
163
+            }
164
+        }
165
+
166
+        // the part file and target file might be on a different storage in case of a single file storage (e.g. single file share)
167
+        /** @var \OC\Files\Storage\Storage $partStorage */
168
+        list($partStorage, $internalPartPath) = $this->fileView->resolvePath($partFilePath);
169
+        /** @var \OC\Files\Storage\Storage $storage */
170
+        list($storage, $internalPath) = $this->fileView->resolvePath($this->path);
171
+        try {
172
+            if (!$needsPartFile) {
173
+                $this->changeLock(ILockingProvider::LOCK_EXCLUSIVE);
174
+            }
175
+
176
+            if ($partStorage->instanceOfStorage(Storage\IWriteStreamStorage::class)) {
177
+
178
+                if (!is_resource($data)) {
179
+                    $tmpData = fopen('php://temp', 'r+');
180
+                    if ($data !== null) {
181
+                        fwrite($tmpData, $data);
182
+                        rewind($tmpData);
183
+                    }
184
+                    $data = $tmpData;
185
+                }
186
+
187
+                $isEOF = false;
188
+                $wrappedData = CallbackWrapper::wrap($data, null, null, null, null, function ($stream) use (&$isEOF) {
189
+                    $isEOF = feof($stream);
190
+                });
191
+
192
+                $count = $partStorage->writeStream($internalPartPath, $wrappedData);
193
+                $result = $count > 0;
194
+
195
+                if ($result === false) {
196
+                    $result = $isEOF;
197
+                    if (is_resource($wrappedData)) {
198
+                        $result = feof($wrappedData);
199
+                    }
200
+                }
201
+
202
+            } else {
203
+                $target = $partStorage->fopen($internalPartPath, 'wb');
204
+                if ($target === false) {
205
+                    \OC::$server->getLogger()->error('\OC\Files\Filesystem::fopen() failed', ['app' => 'webdav']);
206
+                    // because we have no clue about the cause we can only throw back a 500/Internal Server Error
207
+                    throw new Exception('Could not write file contents');
208
+                }
209
+                list($count, $result) = \OC_Helper::streamCopy($data, $target);
210
+                fclose($target);
211
+            }
212
+
213
+            if ($result === false) {
214
+                $expected = -1;
215
+                if (isset($_SERVER['CONTENT_LENGTH'])) {
216
+                    $expected = $_SERVER['CONTENT_LENGTH'];
217
+                }
218
+                if ($expected !== "0") {
219
+                    throw new Exception('Error while copying file to target location (copied bytes: ' . $count . ', expected filesize: ' . $expected . ' )');
220
+                }
221
+            }
222
+
223
+            // if content length is sent by client:
224
+            // double check if the file was fully received
225
+            // compare expected and actual size
226
+            if (isset($_SERVER['CONTENT_LENGTH']) && $_SERVER['REQUEST_METHOD'] === 'PUT') {
227
+                $expected = (int)$_SERVER['CONTENT_LENGTH'];
228
+                if ($count !== $expected) {
229
+                    throw new BadRequest('Expected filesize of ' . $expected . ' bytes but read (from Nextcloud client) and wrote (to Nextcloud storage) ' . $count . ' bytes. Could either be a network problem on the sending side or a problem writing to the storage on the server side.');
230
+                }
231
+            }
232
+
233
+        } catch (\Exception $e) {
234
+            $context = [];
235
+
236
+            if ($e instanceof LockedException) {
237
+                $context['level'] = ILogger::DEBUG;
238
+            }
239
+
240
+            \OC::$server->getLogger()->logException($e, $context);
241
+            if ($needsPartFile) {
242
+                $partStorage->unlink($internalPartPath);
243
+            }
244
+            $this->convertToSabreException($e);
245
+        }
246
+
247
+        try {
248
+            if ($needsPartFile) {
249
+                if ($view && !$this->emitPreHooks($exists)) {
250
+                    $partStorage->unlink($internalPartPath);
251
+                    throw new Exception('Could not rename part file to final file, canceled by hook');
252
+                }
253
+                try {
254
+                    $this->changeLock(ILockingProvider::LOCK_EXCLUSIVE);
255
+                } catch (LockedException $e) {
256
+                    // during very large uploads, the shared lock we got at the start might have been expired
257
+                    // meaning that the above lock can fail not just only because somebody else got a shared lock
258
+                    // or because there is no existing shared lock to make exclusive
259
+                    //
260
+                    // Thus we try to get a new exclusive lock, if the original lock failed because of a different shared
261
+                    // lock this will still fail, if our original shared lock expired the new lock will be successful and
262
+                    // the entire operation will be safe
263
+
264
+                    try {
265
+                        $this->acquireLock(ILockingProvider::LOCK_EXCLUSIVE);
266
+                    } catch (LockedException $ex) {
267
+                        if ($needsPartFile) {
268
+                            $partStorage->unlink($internalPartPath);
269
+                        }
270
+                        throw new FileLocked($e->getMessage(), $e->getCode(), $e);
271
+                    }
272
+                }
273
+
274
+                // rename to correct path
275
+                try {
276
+                    $renameOkay = $storage->moveFromStorage($partStorage, $internalPartPath, $internalPath);
277
+                    $fileExists = $storage->file_exists($internalPath);
278
+                    if ($renameOkay === false || $fileExists === false) {
279
+                        \OC::$server->getLogger()->error('renaming part file to final file failed $renameOkay: ' . ($renameOkay ? 'true' : 'false') . ', $fileExists: ' . ($fileExists ? 'true' : 'false') . ')', ['app' => 'webdav']);
280
+                        throw new Exception('Could not rename part file to final file');
281
+                    }
282
+                } catch (ForbiddenException $ex) {
283
+                    throw new DAVForbiddenException($ex->getMessage(), $ex->getRetry());
284
+                } catch (\Exception $e) {
285
+                    $partStorage->unlink($internalPartPath);
286
+                    $this->convertToSabreException($e);
287
+                }
288
+            }
289
+
290
+            // since we skipped the view we need to scan and emit the hooks ourselves
291
+            $storage->getUpdater()->update($internalPath);
292
+
293
+            try {
294
+                $this->changeLock(ILockingProvider::LOCK_SHARED);
295
+            } catch (LockedException $e) {
296
+                throw new FileLocked($e->getMessage(), $e->getCode(), $e);
297
+            }
298
+
299
+            // allow sync clients to send the mtime along in a header
300
+            if (isset($this->request->server['HTTP_X_OC_MTIME'])) {
301
+                $mtime = $this->sanitizeMtime($this->request->server['HTTP_X_OC_MTIME']);
302
+                if ($this->fileView->touch($this->path, $mtime)) {
303
+                    $this->header('X-OC-MTime: accepted');
304
+                }
305
+            }
306
+
307
+            $fileInfoUpdate = [
308
+                'upload_time' => time()
309
+            ];
310
+
311
+            // allow sync clients to send the creation time along in a header
312
+            if (isset($this->request->server['HTTP_X_OC_CTIME'])) {
313
+                $ctime = $this->sanitizeMtime($this->request->server['HTTP_X_OC_CTIME']);
314
+                $fileInfoUpdate['creation_time'] = $ctime;
315
+                $this->header('X-OC-CTime: accepted');
316
+            }
317
+
318
+            $this->fileView->putFileInfo($this->path, $fileInfoUpdate);
319
+
320
+            if ($view) {
321
+                $this->emitPostHooks($exists);
322
+            }
323
+
324
+            $this->refreshInfo();
325
+
326
+            if (isset($this->request->server['HTTP_OC_CHECKSUM'])) {
327
+                $checksum = trim($this->request->server['HTTP_OC_CHECKSUM']);
328
+                $this->fileView->putFileInfo($this->path, ['checksum' => $checksum]);
329
+                $this->refreshInfo();
330
+            } else if ($this->getChecksum() !== null && $this->getChecksum() !== '') {
331
+                $this->fileView->putFileInfo($this->path, ['checksum' => '']);
332
+                $this->refreshInfo();
333
+            }
334
+
335
+        } catch (StorageNotAvailableException $e) {
336
+            throw new ServiceUnavailable("Failed to check file size: " . $e->getMessage(), 0, $e);
337
+        }
338
+
339
+        return '"' . $this->info->getEtag() . '"';
340
+    }
341
+
342
+    private function getPartFileBasePath($path) {
343
+        $partFileInStorage = \OC::$server->getConfig()->getSystemValue('part_file_in_storage', true);
344
+        if ($partFileInStorage) {
345
+            return $path;
346
+        } else {
347
+            return md5($path); // will place it in the root of the view with a unique name
348
+        }
349
+    }
350
+
351
+    /**
352
+     * @param string $path
353
+     */
354
+    private function emitPreHooks($exists, $path = null) {
355
+        if (is_null($path)) {
356
+            $path = $this->path;
357
+        }
358
+        $hookPath = Filesystem::getView()->getRelativePath($this->fileView->getAbsolutePath($path));
359
+        $run = true;
360
+
361
+        if (!$exists) {
362
+            \OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_create, [
363
+                \OC\Files\Filesystem::signal_param_path => $hookPath,
364
+                \OC\Files\Filesystem::signal_param_run => &$run,
365
+            ]);
366
+        } else {
367
+            \OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_update, [
368
+                \OC\Files\Filesystem::signal_param_path => $hookPath,
369
+                \OC\Files\Filesystem::signal_param_run => &$run,
370
+            ]);
371
+        }
372
+        \OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_write, [
373
+            \OC\Files\Filesystem::signal_param_path => $hookPath,
374
+            \OC\Files\Filesystem::signal_param_run => &$run,
375
+        ]);
376
+        return $run;
377
+    }
378
+
379
+    /**
380
+     * @param string $path
381
+     */
382
+    private function emitPostHooks($exists, $path = null) {
383
+        if (is_null($path)) {
384
+            $path = $this->path;
385
+        }
386
+        $hookPath = Filesystem::getView()->getRelativePath($this->fileView->getAbsolutePath($path));
387
+        if (!$exists) {
388
+            \OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_post_create, [
389
+                \OC\Files\Filesystem::signal_param_path => $hookPath
390
+            ]);
391
+        } else {
392
+            \OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_post_update, [
393
+                \OC\Files\Filesystem::signal_param_path => $hookPath
394
+            ]);
395
+        }
396
+        \OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_post_write, [
397
+            \OC\Files\Filesystem::signal_param_path => $hookPath
398
+        ]);
399
+    }
400
+
401
+    /**
402
+     * Returns the data
403
+     *
404
+     * @return resource
405
+     * @throws Forbidden
406
+     * @throws ServiceUnavailable
407
+     */
408
+    public function get() {
409
+        //throw exception if encryption is disabled but files are still encrypted
410
+        try {
411
+            if (!$this->info->isReadable()) {
412
+                // do a if the file did not exist
413
+                throw new NotFound();
414
+            }
415
+            try {
416
+                $res = $this->fileView->fopen(ltrim($this->path, '/'), 'rb');
417
+            } catch (\Exception $e) {
418
+                $this->convertToSabreException($e);
419
+            }
420
+            if ($res === false) {
421
+                throw new ServiceUnavailable("Could not open file");
422
+            }
423
+            return $res;
424
+        } catch (GenericEncryptionException $e) {
425
+            // returning 503 will allow retry of the operation at a later point in time
426
+            throw new ServiceUnavailable("Encryption not ready: " . $e->getMessage());
427
+        } catch (StorageNotAvailableException $e) {
428
+            throw new ServiceUnavailable("Failed to open file: " . $e->getMessage());
429
+        } catch (ForbiddenException $ex) {
430
+            throw new DAVForbiddenException($ex->getMessage(), $ex->getRetry());
431
+        } catch (LockedException $e) {
432
+            throw new FileLocked($e->getMessage(), $e->getCode(), $e);
433
+        }
434
+    }
435
+
436
+    /**
437
+     * Delete the current file
438
+     *
439
+     * @throws Forbidden
440
+     * @throws ServiceUnavailable
441
+     */
442
+    public function delete() {
443
+        if (!$this->info->isDeletable()) {
444
+            throw new Forbidden();
445
+        }
446
+
447
+        try {
448
+            if (!$this->fileView->unlink($this->path)) {
449
+                // assume it wasn't possible to delete due to permissions
450
+                throw new Forbidden();
451
+            }
452
+        } catch (StorageNotAvailableException $e) {
453
+            throw new ServiceUnavailable("Failed to unlink: " . $e->getMessage());
454
+        } catch (ForbiddenException $ex) {
455
+            throw new DAVForbiddenException($ex->getMessage(), $ex->getRetry());
456
+        } catch (LockedException $e) {
457
+            throw new FileLocked($e->getMessage(), $e->getCode(), $e);
458
+        }
459
+    }
460
+
461
+    /**
462
+     * Returns the mime-type for a file
463
+     *
464
+     * If null is returned, we'll assume application/octet-stream
465
+     *
466
+     * @return string
467
+     */
468
+    public function getContentType() {
469
+        $mimeType = $this->info->getMimetype();
470
+
471
+        // PROPFIND needs to return the correct mime type, for consistency with the web UI
472
+        if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PROPFIND') {
473
+            return $mimeType;
474
+        }
475
+        return \OC::$server->getMimeTypeDetector()->getSecureMimeType($mimeType);
476
+    }
477
+
478
+    /**
479
+     * @return array|false
480
+     */
481
+    public function getDirectDownload() {
482
+        if (\OCP\App::isEnabled('encryption')) {
483
+            return [];
484
+        }
485
+        /** @var \OCP\Files\Storage $storage */
486
+        list($storage, $internalPath) = $this->fileView->resolvePath($this->path);
487
+        if (is_null($storage)) {
488
+            return [];
489
+        }
490
+
491
+        return $storage->getDirectDownload($internalPath);
492
+    }
493
+
494
+    /**
495
+     * @param resource $data
496
+     * @return null|string
497
+     * @throws Exception
498
+     * @throws BadRequest
499
+     * @throws NotImplemented
500
+     * @throws ServiceUnavailable
501
+     */
502
+    private function createFileChunked($data) {
503
+        list($path, $name) = \Sabre\Uri\split($this->path);
504
+
505
+        $info = \OC_FileChunking::decodeName($name);
506
+        if (empty($info)) {
507
+            throw new NotImplemented('Invalid chunk name');
508
+        }
509
+
510
+        $chunk_handler = new \OC_FileChunking($info);
511
+        $bytesWritten = $chunk_handler->store($info['index'], $data);
512
+
513
+        //detect aborted upload
514
+        if (isset ($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PUT') {
515
+            if (isset($_SERVER['CONTENT_LENGTH'])) {
516
+                $expected = (int)$_SERVER['CONTENT_LENGTH'];
517
+                if ($bytesWritten !== $expected) {
518
+                    $chunk_handler->remove($info['index']);
519
+                    throw new BadRequest('Expected filesize of ' . $expected . ' bytes but read (from Nextcloud client) and wrote (to Nextcloud storage) ' . $bytesWritten . ' bytes. Could either be a network problem on the sending side or a problem writing to the storage on the server side.');
520
+                }
521
+            }
522
+        }
523
+
524
+        if ($chunk_handler->isComplete()) {
525
+            /** @var Storage $storage */
526
+            list($storage,) = $this->fileView->resolvePath($path);
527
+            $needsPartFile = $storage->needsPartFile();
528
+            $partFile = null;
529
+
530
+            $targetPath = $path . '/' . $info['name'];
531
+            /** @var \OC\Files\Storage\Storage $targetStorage */
532
+            list($targetStorage, $targetInternalPath) = $this->fileView->resolvePath($targetPath);
533
+
534
+            $exists = $this->fileView->file_exists($targetPath);
535
+
536
+            try {
537
+                $this->fileView->lockFile($targetPath, ILockingProvider::LOCK_SHARED);
538
+
539
+                $this->emitPreHooks($exists, $targetPath);
540
+                $this->fileView->changeLock($targetPath, ILockingProvider::LOCK_EXCLUSIVE);
541
+                /** @var \OC\Files\Storage\Storage $targetStorage */
542
+                list($targetStorage, $targetInternalPath) = $this->fileView->resolvePath($targetPath);
543
+
544
+                if ($needsPartFile) {
545
+                    // we first assembly the target file as a part file
546
+                    $partFile = $this->getPartFileBasePath($path . '/' . $info['name']) . '.ocTransferId' . $info['transferid'] . '.part';
547
+                    /** @var \OC\Files\Storage\Storage $targetStorage */
548
+                    list($partStorage, $partInternalPath) = $this->fileView->resolvePath($partFile);
549
+
550
+
551
+                    $chunk_handler->file_assemble($partStorage, $partInternalPath);
552
+
553
+                    // here is the final atomic rename
554
+                    $renameOkay = $targetStorage->moveFromStorage($partStorage, $partInternalPath, $targetInternalPath);
555
+                    $fileExists = $targetStorage->file_exists($targetInternalPath);
556
+                    if ($renameOkay === false || $fileExists === false) {
557
+                        \OC::$server->getLogger()->error('\OC\Files\Filesystem::rename() failed', ['app' => 'webdav']);
558
+                        // only delete if an error occurred and the target file was already created
559
+                        if ($fileExists) {
560
+                            // set to null to avoid double-deletion when handling exception
561
+                            // stray part file
562
+                            $partFile = null;
563
+                            $targetStorage->unlink($targetInternalPath);
564
+                        }
565
+                        $this->fileView->changeLock($targetPath, ILockingProvider::LOCK_SHARED);
566
+                        throw new Exception('Could not rename part file assembled from chunks');
567
+                    }
568
+                } else {
569
+                    // assemble directly into the final file
570
+                    $chunk_handler->file_assemble($targetStorage, $targetInternalPath);
571
+                }
572
+
573
+                // allow sync clients to send the mtime along in a header
574
+                if (isset($this->request->server['HTTP_X_OC_MTIME'])) {
575
+                    $mtime = $this->sanitizeMtime($this->request->server['HTTP_X_OC_MTIME']);
576
+                    if ($targetStorage->touch($targetInternalPath, $mtime)) {
577
+                        $this->header('X-OC-MTime: accepted');
578
+                    }
579
+                }
580
+
581
+                // since we skipped the view we need to scan and emit the hooks ourselves
582
+                $targetStorage->getUpdater()->update($targetInternalPath);
583
+
584
+                $this->fileView->changeLock($targetPath, ILockingProvider::LOCK_SHARED);
585
+
586
+                $this->emitPostHooks($exists, $targetPath);
587
+
588
+                // FIXME: should call refreshInfo but can't because $this->path is not the of the final file
589
+                $info = $this->fileView->getFileInfo($targetPath);
590
+
591
+                if (isset($this->request->server['HTTP_OC_CHECKSUM'])) {
592
+                    $checksum = trim($this->request->server['HTTP_OC_CHECKSUM']);
593
+                    $this->fileView->putFileInfo($targetPath, ['checksum' => $checksum]);
594
+                } else if ($info->getChecksum() !== null && $info->getChecksum() !== '') {
595
+                    $this->fileView->putFileInfo($this->path, ['checksum' => '']);
596
+                }
597
+
598
+                $this->fileView->unlockFile($targetPath, ILockingProvider::LOCK_SHARED);
599
+
600
+                return $info->getEtag();
601
+            } catch (\Exception $e) {
602
+                if ($partFile !== null) {
603
+                    $targetStorage->unlink($targetInternalPath);
604
+                }
605
+                $this->convertToSabreException($e);
606
+            }
607
+        }
608
+
609
+        return null;
610
+    }
611
+
612
+    /**
613
+     * Convert the given exception to a SabreException instance
614
+     *
615
+     * @param \Exception $e
616
+     *
617
+     * @throws \Sabre\DAV\Exception
618
+     */
619
+    private function convertToSabreException(\Exception $e) {
620
+        if ($e instanceof \Sabre\DAV\Exception) {
621
+            throw $e;
622
+        }
623
+        if ($e instanceof NotPermittedException) {
624
+            // a more general case - due to whatever reason the content could not be written
625
+            throw new Forbidden($e->getMessage(), 0, $e);
626
+        }
627
+        if ($e instanceof ForbiddenException) {
628
+            // the path for the file was forbidden
629
+            throw new DAVForbiddenException($e->getMessage(), $e->getRetry(), $e);
630
+        }
631
+        if ($e instanceof EntityTooLargeException) {
632
+            // the file is too big to be stored
633
+            throw new EntityTooLarge($e->getMessage(), 0, $e);
634
+        }
635
+        if ($e instanceof InvalidContentException) {
636
+            // the file content is not permitted
637
+            throw new UnsupportedMediaType($e->getMessage(), 0, $e);
638
+        }
639
+        if ($e instanceof InvalidPathException) {
640
+            // the path for the file was not valid
641
+            // TODO: find proper http status code for this case
642
+            throw new Forbidden($e->getMessage(), 0, $e);
643
+        }
644
+        if ($e instanceof LockedException || $e instanceof LockNotAcquiredException) {
645
+            // the file is currently being written to by another process
646
+            throw new FileLocked($e->getMessage(), $e->getCode(), $e);
647
+        }
648
+        if ($e instanceof GenericEncryptionException) {
649
+            // returning 503 will allow retry of the operation at a later point in time
650
+            throw new ServiceUnavailable('Encryption not ready: ' . $e->getMessage(), 0, $e);
651
+        }
652
+        if ($e instanceof StorageNotAvailableException) {
653
+            throw new ServiceUnavailable('Failed to write file contents: ' . $e->getMessage(), 0, $e);
654
+        }
655
+        if ($e instanceof NotFoundException) {
656
+            throw new NotFound('File not found: ' . $e->getMessage(), 0, $e);
657
+        }
658
+
659
+        throw new \Sabre\DAV\Exception($e->getMessage(), 0, $e);
660
+    }
661
+
662
+    /**
663
+     * Get the checksum for this file
664
+     *
665
+     * @return string
666
+     */
667
+    public function getChecksum() {
668
+        return $this->info->getChecksum();
669
+    }
670
+
671
+    protected function header($string) {
672
+        \header($string);
673
+    }
674 674
 }
Please login to merge, or discard this patch.
apps/dav/lib/Connector/Sabre/CommentPropertiesPlugin.php 1 patch
Indentation   +127 added lines, -127 removed lines patch added patch discarded remove patch
@@ -32,132 +32,132 @@
 block discarded – undo
32 32
 
33 33
 class CommentPropertiesPlugin extends ServerPlugin {
34 34
 
35
-	const PROPERTY_NAME_HREF   = '{http://owncloud.org/ns}comments-href';
36
-	const PROPERTY_NAME_COUNT  = '{http://owncloud.org/ns}comments-count';
37
-	const PROPERTY_NAME_UNREAD = '{http://owncloud.org/ns}comments-unread';
38
-
39
-	/** @var  \Sabre\DAV\Server */
40
-	protected $server;
41
-
42
-	/** @var ICommentsManager */
43
-	private $commentsManager;
44
-
45
-	/** @var IUserSession */
46
-	private $userSession;
47
-
48
-	private $cachedUnreadCount = [];
49
-
50
-	private $cachedFolders = [];
51
-
52
-	public function __construct(ICommentsManager $commentsManager, IUserSession $userSession) {
53
-		$this->commentsManager = $commentsManager;
54
-		$this->userSession = $userSession;
55
-	}
56
-
57
-	/**
58
-	 * This initializes the plugin.
59
-	 *
60
-	 * This function is called by Sabre\DAV\Server, after
61
-	 * addPlugin is called.
62
-	 *
63
-	 * This method should set up the required event subscriptions.
64
-	 *
65
-	 * @param \Sabre\DAV\Server $server
66
-	 * @return void
67
-	 */
68
-	function initialize(\Sabre\DAV\Server $server) {
69
-		$this->server = $server;
70
-		$this->server->on('propFind', [$this, 'handleGetProperties']);
71
-	}
72
-
73
-	/**
74
-	 * Adds tags and favorites properties to the response,
75
-	 * if requested.
76
-	 *
77
-	 * @param PropFind $propFind
78
-	 * @param \Sabre\DAV\INode $node
79
-	 * @return void
80
-	 */
81
-	public function handleGetProperties(
82
-		PropFind $propFind,
83
-		\Sabre\DAV\INode $node
84
-	) {
85
-		if (!($node instanceof File) && !($node instanceof Directory)) {
86
-			return;
87
-		}
88
-
89
-		// need prefetch ?
90
-		if ($node instanceof \OCA\DAV\Connector\Sabre\Directory
91
-			&& $propFind->getDepth() !== 0
92
-			&& !is_null($propFind->getStatus(self::PROPERTY_NAME_UNREAD))
93
-		) {
94
-			$unreadCounts = $this->commentsManager->getNumberOfUnreadCommentsForFolder($node->getId(), $this->userSession->getUser());
95
-			$this->cachedFolders[] = $node->getPath();
96
-			foreach ($unreadCounts as $id => $count) {
97
-				$this->cachedUnreadCount[$id] = $count;
98
-			}
99
-		}
100
-
101
-		$propFind->handle(self::PROPERTY_NAME_COUNT, function() use ($node) {
102
-			return $this->commentsManager->getNumberOfCommentsForObject('files', (string)$node->getId());
103
-		});
104
-
105
-		$propFind->handle(self::PROPERTY_NAME_HREF, function() use ($node) {
106
-			return $this->getCommentsLink($node);
107
-		});
108
-
109
-		$propFind->handle(self::PROPERTY_NAME_UNREAD, function() use ($node) {
110
-			if (isset($this->cachedUnreadCount[$node->getId()])) {
111
-				return $this->cachedUnreadCount[$node->getId()];
112
-			} else {
113
-				list($parentPath,) = \Sabre\Uri\split($node->getPath());
114
-				if ($parentPath === '') {
115
-					$parentPath = '/';
116
-				}
117
-				// if we already cached the folder this file is in we know there are no comments for this file
118
-				if (array_search($parentPath, $this->cachedFolders) === false) {
119
-					return 0;
120
-				} else {
121
-					return $this->getUnreadCount($node);
122
-				}
123
-			}
124
-		});
125
-	}
126
-
127
-	/**
128
-	 * returns a reference to the comments node
129
-	 *
130
-	 * @param Node $node
131
-	 * @return mixed|string
132
-	 */
133
-	public function getCommentsLink(Node $node) {
134
-		$href =  $this->server->getBaseUri();
135
-		$entryPoint = strpos($href, '/remote.php/');
136
-		if($entryPoint === false) {
137
-			// in case we end up somewhere else, unexpectedly.
138
-			return null;
139
-		}
140
-		$commentsPart = 'dav/comments/files/' . rawurldecode($node->getId());
141
-		$href = substr_replace($href, $commentsPart, $entryPoint + strlen('/remote.php/'));
142
-		return $href;
143
-	}
144
-
145
-	/**
146
-	 * returns the number of unread comments for the currently logged in user
147
-	 * on the given file or directory node
148
-	 *
149
-	 * @param Node $node
150
-	 * @return Int|null
151
-	 */
152
-	public function getUnreadCount(Node $node) {
153
-		$user = $this->userSession->getUser();
154
-		if(is_null($user)) {
155
-			return null;
156
-		}
157
-
158
-		$lastRead = $this->commentsManager->getReadMark('files', (string)$node->getId(), $user);
159
-
160
-		return $this->commentsManager->getNumberOfCommentsForObject('files', (string)$node->getId(), $lastRead);
161
-	}
35
+    const PROPERTY_NAME_HREF   = '{http://owncloud.org/ns}comments-href';
36
+    const PROPERTY_NAME_COUNT  = '{http://owncloud.org/ns}comments-count';
37
+    const PROPERTY_NAME_UNREAD = '{http://owncloud.org/ns}comments-unread';
38
+
39
+    /** @var  \Sabre\DAV\Server */
40
+    protected $server;
41
+
42
+    /** @var ICommentsManager */
43
+    private $commentsManager;
44
+
45
+    /** @var IUserSession */
46
+    private $userSession;
47
+
48
+    private $cachedUnreadCount = [];
49
+
50
+    private $cachedFolders = [];
51
+
52
+    public function __construct(ICommentsManager $commentsManager, IUserSession $userSession) {
53
+        $this->commentsManager = $commentsManager;
54
+        $this->userSession = $userSession;
55
+    }
56
+
57
+    /**
58
+     * This initializes the plugin.
59
+     *
60
+     * This function is called by Sabre\DAV\Server, after
61
+     * addPlugin is called.
62
+     *
63
+     * This method should set up the required event subscriptions.
64
+     *
65
+     * @param \Sabre\DAV\Server $server
66
+     * @return void
67
+     */
68
+    function initialize(\Sabre\DAV\Server $server) {
69
+        $this->server = $server;
70
+        $this->server->on('propFind', [$this, 'handleGetProperties']);
71
+    }
72
+
73
+    /**
74
+     * Adds tags and favorites properties to the response,
75
+     * if requested.
76
+     *
77
+     * @param PropFind $propFind
78
+     * @param \Sabre\DAV\INode $node
79
+     * @return void
80
+     */
81
+    public function handleGetProperties(
82
+        PropFind $propFind,
83
+        \Sabre\DAV\INode $node
84
+    ) {
85
+        if (!($node instanceof File) && !($node instanceof Directory)) {
86
+            return;
87
+        }
88
+
89
+        // need prefetch ?
90
+        if ($node instanceof \OCA\DAV\Connector\Sabre\Directory
91
+            && $propFind->getDepth() !== 0
92
+            && !is_null($propFind->getStatus(self::PROPERTY_NAME_UNREAD))
93
+        ) {
94
+            $unreadCounts = $this->commentsManager->getNumberOfUnreadCommentsForFolder($node->getId(), $this->userSession->getUser());
95
+            $this->cachedFolders[] = $node->getPath();
96
+            foreach ($unreadCounts as $id => $count) {
97
+                $this->cachedUnreadCount[$id] = $count;
98
+            }
99
+        }
100
+
101
+        $propFind->handle(self::PROPERTY_NAME_COUNT, function() use ($node) {
102
+            return $this->commentsManager->getNumberOfCommentsForObject('files', (string)$node->getId());
103
+        });
104
+
105
+        $propFind->handle(self::PROPERTY_NAME_HREF, function() use ($node) {
106
+            return $this->getCommentsLink($node);
107
+        });
108
+
109
+        $propFind->handle(self::PROPERTY_NAME_UNREAD, function() use ($node) {
110
+            if (isset($this->cachedUnreadCount[$node->getId()])) {
111
+                return $this->cachedUnreadCount[$node->getId()];
112
+            } else {
113
+                list($parentPath,) = \Sabre\Uri\split($node->getPath());
114
+                if ($parentPath === '') {
115
+                    $parentPath = '/';
116
+                }
117
+                // if we already cached the folder this file is in we know there are no comments for this file
118
+                if (array_search($parentPath, $this->cachedFolders) === false) {
119
+                    return 0;
120
+                } else {
121
+                    return $this->getUnreadCount($node);
122
+                }
123
+            }
124
+        });
125
+    }
126
+
127
+    /**
128
+     * returns a reference to the comments node
129
+     *
130
+     * @param Node $node
131
+     * @return mixed|string
132
+     */
133
+    public function getCommentsLink(Node $node) {
134
+        $href =  $this->server->getBaseUri();
135
+        $entryPoint = strpos($href, '/remote.php/');
136
+        if($entryPoint === false) {
137
+            // in case we end up somewhere else, unexpectedly.
138
+            return null;
139
+        }
140
+        $commentsPart = 'dav/comments/files/' . rawurldecode($node->getId());
141
+        $href = substr_replace($href, $commentsPart, $entryPoint + strlen('/remote.php/'));
142
+        return $href;
143
+    }
144
+
145
+    /**
146
+     * returns the number of unread comments for the currently logged in user
147
+     * on the given file or directory node
148
+     *
149
+     * @param Node $node
150
+     * @return Int|null
151
+     */
152
+    public function getUnreadCount(Node $node) {
153
+        $user = $this->userSession->getUser();
154
+        if(is_null($user)) {
155
+            return null;
156
+        }
157
+
158
+        $lastRead = $this->commentsManager->getReadMark('files', (string)$node->getId(), $user);
159
+
160
+        return $this->commentsManager->getNumberOfCommentsForObject('files', (string)$node->getId(), $lastRead);
161
+    }
162 162
 
163 163
 }
Please login to merge, or discard this patch.
apps/dav/lib/Migration/RemoveOrphanEventsAndContacts.php 1 patch
Indentation   +72 added lines, -72 removed lines patch added patch discarded remove patch
@@ -35,76 +35,76 @@
 block discarded – undo
35 35
 
36 36
 class RemoveOrphanEventsAndContacts implements IRepairStep {
37 37
 
38
-	/** @var IDBConnection */
39
-	private $connection;
40
-
41
-	public function __construct(IDBConnection $connection) {
42
-		$this->connection = $connection;
43
-	}
44
-
45
-	/**
46
-	 * @inheritdoc
47
-	 */
48
-	public function getName(): string {
49
-		return 'Clean up orphan event and contact data';
50
-	}
51
-
52
-	/**
53
-	 * @inheritdoc
54
-	 */
55
-	public function run(IOutput $output) {
56
-		$orphanItems = $this->removeOrphanChildren('calendarobjects', 'calendars',  'calendarid');
57
-		$output->info(sprintf('%d events without a calendar have been cleaned up', $orphanItems));
58
-		$orphanItems = $this->removeOrphanChildren('calendarobjects_props', 'calendarobjects',  'objectid');
59
-		$output->info(sprintf('%d properties without an events have been cleaned up', $orphanItems));
60
-		$orphanItems = $this->removeOrphanChildren('calendarchanges', 'calendars',  'calendarid');
61
-		$output->info(sprintf('%d changes without a calendar have been cleaned up', $orphanItems));
62
-
63
-		$orphanItems = $this->removeOrphanChildren('calendarobjects', 'calendarsubscriptions',  'calendarid');
64
-		$output->info(sprintf('%d cached events without a calendar subscription have been cleaned up', $orphanItems));
65
-		$orphanItems = $this->removeOrphanChildren('calendarchanges', 'calendarsubscriptions',  'calendarid');
66
-		$output->info(sprintf('%d changes without a calendar subscription have been cleaned up', $orphanItems));
67
-
68
-		$orphanItems = $this->removeOrphanChildren('cards', 'addressbooks',  'addressbookid');
69
-		$output->info(sprintf('%d contacts without an addressbook have been cleaned up', $orphanItems));
70
-		$orphanItems = $this->removeOrphanChildren('cards_properties', 'cards',  'cardid');
71
-		$output->info(sprintf('%d properties without a contact have been cleaned up', $orphanItems));
72
-		$orphanItems = $this->removeOrphanChildren('addressbookchanges', 'addressbooks',  'addressbookid');
73
-		$output->info(sprintf('%d changes without an addressbook have been cleaned up', $orphanItems));
74
-	}
75
-
76
-	protected function removeOrphanChildren($childTable, $parentTable, $parentId): int {
77
-		$qb = $this->connection->getQueryBuilder();
78
-
79
-		$qb->select('c.id')
80
-			->from($childTable, 'c')
81
-			->leftJoin('c', $parentTable, 'p', $qb->expr()->eq('c.' . $parentId, 'p.id'))
82
-			->where($qb->expr()->isNull('p.id'));
83
-
84
-		if (\in_array($parentTable, ['calendars', 'calendarsubscriptions'], true)) {
85
-			$calendarType = $parentTable === 'calendarsubscriptions' ? CalDavBackend::CALENDAR_TYPE_SUBSCRIPTION : CalDavBackend::CALENDAR_TYPE_CALENDAR;
86
-			$qb->andWhere($qb->expr()->eq('c.calendartype', $qb->createNamedParameter($calendarType, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT));
87
-		}
88
-
89
-		$result = $qb->execute();
90
-
91
-		$orphanItems = [];
92
-		while ($row = $result->fetch()) {
93
-			$orphanItems[] = (int) $row['id'];
94
-		}
95
-		$result->closeCursor();
96
-
97
-		if (!empty($orphanItems)) {
98
-			$qb->delete($childTable)
99
-				->where($qb->expr()->in('id', $qb->createParameter('ids')));
100
-
101
-			$orphanItemsBatch = array_chunk($orphanItems, 200);
102
-			foreach ($orphanItemsBatch as $items) {
103
-				$qb->setParameter('ids', $items, IQueryBuilder::PARAM_INT_ARRAY);
104
-				$qb->execute();
105
-			}
106
-		}
107
-
108
-		return count($orphanItems);
109
-	}
38
+    /** @var IDBConnection */
39
+    private $connection;
40
+
41
+    public function __construct(IDBConnection $connection) {
42
+        $this->connection = $connection;
43
+    }
44
+
45
+    /**
46
+     * @inheritdoc
47
+     */
48
+    public function getName(): string {
49
+        return 'Clean up orphan event and contact data';
50
+    }
51
+
52
+    /**
53
+     * @inheritdoc
54
+     */
55
+    public function run(IOutput $output) {
56
+        $orphanItems = $this->removeOrphanChildren('calendarobjects', 'calendars',  'calendarid');
57
+        $output->info(sprintf('%d events without a calendar have been cleaned up', $orphanItems));
58
+        $orphanItems = $this->removeOrphanChildren('calendarobjects_props', 'calendarobjects',  'objectid');
59
+        $output->info(sprintf('%d properties without an events have been cleaned up', $orphanItems));
60
+        $orphanItems = $this->removeOrphanChildren('calendarchanges', 'calendars',  'calendarid');
61
+        $output->info(sprintf('%d changes without a calendar have been cleaned up', $orphanItems));
62
+
63
+        $orphanItems = $this->removeOrphanChildren('calendarobjects', 'calendarsubscriptions',  'calendarid');
64
+        $output->info(sprintf('%d cached events without a calendar subscription have been cleaned up', $orphanItems));
65
+        $orphanItems = $this->removeOrphanChildren('calendarchanges', 'calendarsubscriptions',  'calendarid');
66
+        $output->info(sprintf('%d changes without a calendar subscription have been cleaned up', $orphanItems));
67
+
68
+        $orphanItems = $this->removeOrphanChildren('cards', 'addressbooks',  'addressbookid');
69
+        $output->info(sprintf('%d contacts without an addressbook have been cleaned up', $orphanItems));
70
+        $orphanItems = $this->removeOrphanChildren('cards_properties', 'cards',  'cardid');
71
+        $output->info(sprintf('%d properties without a contact have been cleaned up', $orphanItems));
72
+        $orphanItems = $this->removeOrphanChildren('addressbookchanges', 'addressbooks',  'addressbookid');
73
+        $output->info(sprintf('%d changes without an addressbook have been cleaned up', $orphanItems));
74
+    }
75
+
76
+    protected function removeOrphanChildren($childTable, $parentTable, $parentId): int {
77
+        $qb = $this->connection->getQueryBuilder();
78
+
79
+        $qb->select('c.id')
80
+            ->from($childTable, 'c')
81
+            ->leftJoin('c', $parentTable, 'p', $qb->expr()->eq('c.' . $parentId, 'p.id'))
82
+            ->where($qb->expr()->isNull('p.id'));
83
+
84
+        if (\in_array($parentTable, ['calendars', 'calendarsubscriptions'], true)) {
85
+            $calendarType = $parentTable === 'calendarsubscriptions' ? CalDavBackend::CALENDAR_TYPE_SUBSCRIPTION : CalDavBackend::CALENDAR_TYPE_CALENDAR;
86
+            $qb->andWhere($qb->expr()->eq('c.calendartype', $qb->createNamedParameter($calendarType, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT));
87
+        }
88
+
89
+        $result = $qb->execute();
90
+
91
+        $orphanItems = [];
92
+        while ($row = $result->fetch()) {
93
+            $orphanItems[] = (int) $row['id'];
94
+        }
95
+        $result->closeCursor();
96
+
97
+        if (!empty($orphanItems)) {
98
+            $qb->delete($childTable)
99
+                ->where($qb->expr()->in('id', $qb->createParameter('ids')));
100
+
101
+            $orphanItemsBatch = array_chunk($orphanItems, 200);
102
+            foreach ($orphanItemsBatch as $items) {
103
+                $qb->setParameter('ids', $items, IQueryBuilder::PARAM_INT_ARRAY);
104
+                $qb->execute();
105
+            }
106
+        }
107
+
108
+        return count($orphanItems);
109
+    }
110 110
 }
Please login to merge, or discard this patch.
apps/dav/lib/CardDAV/CardDavBackend.php 1 patch
Indentation   +1118 added lines, -1118 removed lines patch added patch discarded remove patch
@@ -55,1122 +55,1122 @@
 block discarded – undo
55 55
 
56 56
 class CardDavBackend implements BackendInterface, SyncSupport {
57 57
 
58
-	const PERSONAL_ADDRESSBOOK_URI = 'contacts';
59
-	const PERSONAL_ADDRESSBOOK_NAME = 'Contacts';
60
-
61
-	/** @var Principal */
62
-	private $principalBackend;
63
-
64
-	/** @var string */
65
-	private $dbCardsTable = 'cards';
66
-
67
-	/** @var string */
68
-	private $dbCardsPropertiesTable = 'cards_properties';
69
-
70
-	/** @var IDBConnection */
71
-	private $db;
72
-
73
-	/** @var Backend */
74
-	private $sharingBackend;
75
-
76
-	/** @var array properties to index */
77
-	public static $indexProperties = [
78
-			'BDAY', 'UID', 'N', 'FN', 'TITLE', 'ROLE', 'NOTE', 'NICKNAME',
79
-			'ORG', 'CATEGORIES', 'EMAIL', 'TEL', 'IMPP', 'ADR', 'URL', 'GEO', 'CLOUD'];
80
-
81
-	/**
82
-	 * @var string[] Map of uid => display name
83
-	 */
84
-	protected $userDisplayNames;
85
-
86
-	/** @var IUserManager */
87
-	private $userManager;
88
-
89
-	/** @var EventDispatcherInterface */
90
-	private $dispatcher;
91
-
92
-	/**
93
-	 * CardDavBackend constructor.
94
-	 *
95
-	 * @param IDBConnection $db
96
-	 * @param Principal $principalBackend
97
-	 * @param IUserManager $userManager
98
-	 * @param IGroupManager $groupManager
99
-	 * @param EventDispatcherInterface $dispatcher
100
-	 */
101
-	public function __construct(IDBConnection $db,
102
-								Principal $principalBackend,
103
-								IUserManager $userManager,
104
-								IGroupManager $groupManager,
105
-								EventDispatcherInterface $dispatcher) {
106
-		$this->db = $db;
107
-		$this->principalBackend = $principalBackend;
108
-		$this->userManager = $userManager;
109
-		$this->dispatcher = $dispatcher;
110
-		$this->sharingBackend = new Backend($this->db, $this->userManager, $groupManager, $principalBackend, 'addressbook');
111
-	}
112
-
113
-	/**
114
-	 * Return the number of address books for a principal
115
-	 *
116
-	 * @param $principalUri
117
-	 * @return int
118
-	 */
119
-	public function getAddressBooksForUserCount($principalUri) {
120
-		$principalUri = $this->convertPrincipal($principalUri, true);
121
-		$query = $this->db->getQueryBuilder();
122
-		$query->select($query->func()->count('*'))
123
-			->from('addressbooks')
124
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
125
-
126
-		return (int)$query->execute()->fetchColumn();
127
-	}
128
-
129
-	/**
130
-	 * Returns the list of address books for a specific user.
131
-	 *
132
-	 * Every addressbook should have the following properties:
133
-	 *   id - an arbitrary unique id
134
-	 *   uri - the 'basename' part of the url
135
-	 *   principaluri - Same as the passed parameter
136
-	 *
137
-	 * Any additional clark-notation property may be passed besides this. Some
138
-	 * common ones are :
139
-	 *   {DAV:}displayname
140
-	 *   {urn:ietf:params:xml:ns:carddav}addressbook-description
141
-	 *   {http://calendarserver.org/ns/}getctag
142
-	 *
143
-	 * @param string $principalUri
144
-	 * @return array
145
-	 */
146
-	function getAddressBooksForUser($principalUri) {
147
-		$principalUriOriginal = $principalUri;
148
-		$principalUri = $this->convertPrincipal($principalUri, true);
149
-		$query = $this->db->getQueryBuilder();
150
-		$query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
151
-			->from('addressbooks')
152
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
153
-
154
-		$addressBooks = [];
155
-
156
-		$result = $query->execute();
157
-		while($row = $result->fetch()) {
158
-			$addressBooks[$row['id']] = [
159
-				'id'  => $row['id'],
160
-				'uri' => $row['uri'],
161
-				'principaluri' => $this->convertPrincipal($row['principaluri'], false),
162
-				'{DAV:}displayname' => $row['displayname'],
163
-				'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
164
-				'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
165
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
166
-			];
167
-
168
-			$this->addOwnerPrincipal($addressBooks[$row['id']]);
169
-		}
170
-		$result->closeCursor();
171
-
172
-		// query for shared addressbooks
173
-		$principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
174
-		$principals = array_merge($principals, $this->principalBackend->getCircleMembership($principalUriOriginal));
175
-
176
-		$principals = array_map(function($principal) {
177
-			return urldecode($principal);
178
-		}, $principals);
179
-		$principals[]= $principalUri;
180
-
181
-		$query = $this->db->getQueryBuilder();
182
-		$result = $query->select(['a.id', 'a.uri', 'a.displayname', 'a.principaluri', 'a.description', 'a.synctoken', 's.access'])
183
-			->from('dav_shares', 's')
184
-			->join('s', 'addressbooks', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
185
-			->where($query->expr()->in('s.principaluri', $query->createParameter('principaluri')))
186
-			->andWhere($query->expr()->eq('s.type', $query->createParameter('type')))
187
-			->setParameter('type', 'addressbook')
188
-			->setParameter('principaluri', $principals, IQueryBuilder::PARAM_STR_ARRAY)
189
-			->execute();
190
-
191
-		$readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
192
-		while($row = $result->fetch()) {
193
-			if ($row['principaluri'] === $principalUri) {
194
-				continue;
195
-			}
196
-
197
-			$readOnly = (int) $row['access'] === Backend::ACCESS_READ;
198
-			if (isset($addressBooks[$row['id']])) {
199
-				if ($readOnly) {
200
-					// New share can not have more permissions then the old one.
201
-					continue;
202
-				}
203
-				if (isset($addressBooks[$row['id']][$readOnlyPropertyName]) &&
204
-					$addressBooks[$row['id']][$readOnlyPropertyName] === 0) {
205
-					// Old share is already read-write, no more permissions can be gained
206
-					continue;
207
-				}
208
-			}
209
-
210
-			list(, $name) = \Sabre\Uri\split($row['principaluri']);
211
-			$uri = $row['uri'] . '_shared_by_' . $name;
212
-			$displayName = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
213
-
214
-			$addressBooks[$row['id']] = [
215
-				'id'  => $row['id'],
216
-				'uri' => $uri,
217
-				'principaluri' => $principalUriOriginal,
218
-				'{DAV:}displayname' => $displayName,
219
-				'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
220
-				'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
221
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
222
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $row['principaluri'],
223
-				$readOnlyPropertyName => $readOnly,
224
-			];
225
-
226
-			$this->addOwnerPrincipal($addressBooks[$row['id']]);
227
-		}
228
-		$result->closeCursor();
229
-
230
-		return array_values($addressBooks);
231
-	}
232
-
233
-	public function getUsersOwnAddressBooks($principalUri) {
234
-		$principalUri = $this->convertPrincipal($principalUri, true);
235
-		$query = $this->db->getQueryBuilder();
236
-		$query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
237
-			  ->from('addressbooks')
238
-			  ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
239
-
240
-		$addressBooks = [];
241
-
242
-		$result = $query->execute();
243
-		while($row = $result->fetch()) {
244
-			$addressBooks[$row['id']] = [
245
-				'id'  => $row['id'],
246
-				'uri' => $row['uri'],
247
-				'principaluri' => $this->convertPrincipal($row['principaluri'], false),
248
-				'{DAV:}displayname' => $row['displayname'],
249
-				'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
250
-				'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
251
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
252
-			];
253
-
254
-			$this->addOwnerPrincipal($addressBooks[$row['id']]);
255
-		}
256
-		$result->closeCursor();
257
-
258
-		return array_values($addressBooks);
259
-	}
260
-
261
-	private function getUserDisplayName($uid) {
262
-		if (!isset($this->userDisplayNames[$uid])) {
263
-			$user = $this->userManager->get($uid);
264
-
265
-			if ($user instanceof IUser) {
266
-				$this->userDisplayNames[$uid] = $user->getDisplayName();
267
-			} else {
268
-				$this->userDisplayNames[$uid] = $uid;
269
-			}
270
-		}
271
-
272
-		return $this->userDisplayNames[$uid];
273
-	}
274
-
275
-	/**
276
-	 * @param int $addressBookId
277
-	 */
278
-	public function getAddressBookById($addressBookId) {
279
-		$query = $this->db->getQueryBuilder();
280
-		$result = $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
281
-			->from('addressbooks')
282
-			->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId)))
283
-			->execute();
284
-
285
-		$row = $result->fetch();
286
-		$result->closeCursor();
287
-		if ($row === false) {
288
-			return null;
289
-		}
290
-
291
-		$addressBook = [
292
-			'id'  => $row['id'],
293
-			'uri' => $row['uri'],
294
-			'principaluri' => $row['principaluri'],
295
-			'{DAV:}displayname' => $row['displayname'],
296
-			'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
297
-			'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
298
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
299
-		];
300
-
301
-		$this->addOwnerPrincipal($addressBook);
302
-
303
-		return $addressBook;
304
-	}
305
-
306
-	/**
307
-	 * @param $addressBookUri
308
-	 * @return array|null
309
-	 */
310
-	public function getAddressBooksByUri($principal, $addressBookUri) {
311
-		$query = $this->db->getQueryBuilder();
312
-		$result = $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
313
-			->from('addressbooks')
314
-			->where($query->expr()->eq('uri', $query->createNamedParameter($addressBookUri)))
315
-			->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
316
-			->setMaxResults(1)
317
-			->execute();
318
-
319
-		$row = $result->fetch();
320
-		$result->closeCursor();
321
-		if ($row === false) {
322
-			return null;
323
-		}
324
-
325
-		$addressBook = [
326
-			'id'  => $row['id'],
327
-			'uri' => $row['uri'],
328
-			'principaluri' => $row['principaluri'],
329
-			'{DAV:}displayname' => $row['displayname'],
330
-			'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
331
-			'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
332
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
333
-		];
334
-
335
-		$this->addOwnerPrincipal($addressBook);
336
-
337
-		return $addressBook;
338
-	}
339
-
340
-	/**
341
-	 * Updates properties for an address book.
342
-	 *
343
-	 * The list of mutations is stored in a Sabre\DAV\PropPatch object.
344
-	 * To do the actual updates, you must tell this object which properties
345
-	 * you're going to process with the handle() method.
346
-	 *
347
-	 * Calling the handle method is like telling the PropPatch object "I
348
-	 * promise I can handle updating this property".
349
-	 *
350
-	 * Read the PropPatch documentation for more info and examples.
351
-	 *
352
-	 * @param string $addressBookId
353
-	 * @param \Sabre\DAV\PropPatch $propPatch
354
-	 * @return void
355
-	 */
356
-	function updateAddressBook($addressBookId, \Sabre\DAV\PropPatch $propPatch) {
357
-		$supportedProperties = [
358
-			'{DAV:}displayname',
359
-			'{' . Plugin::NS_CARDDAV . '}addressbook-description',
360
-		];
361
-
362
-		/**
363
-		 * @suppress SqlInjectionChecker
364
-		 */
365
-		$propPatch->handle($supportedProperties, function($mutations) use ($addressBookId) {
366
-
367
-			$updates = [];
368
-			foreach($mutations as $property=>$newValue) {
369
-
370
-				switch($property) {
371
-					case '{DAV:}displayname' :
372
-						$updates['displayname'] = $newValue;
373
-						break;
374
-					case '{' . Plugin::NS_CARDDAV . '}addressbook-description' :
375
-						$updates['description'] = $newValue;
376
-						break;
377
-				}
378
-			}
379
-			$query = $this->db->getQueryBuilder();
380
-			$query->update('addressbooks');
381
-
382
-			foreach($updates as $key=>$value) {
383
-				$query->set($key, $query->createNamedParameter($value));
384
-			}
385
-			$query->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId)))
386
-			->execute();
387
-
388
-			$this->addChange($addressBookId, "", 2);
389
-
390
-			return true;
391
-
392
-		});
393
-	}
394
-
395
-	/**
396
-	 * Creates a new address book
397
-	 *
398
-	 * @param string $principalUri
399
-	 * @param string $url Just the 'basename' of the url.
400
-	 * @param array $properties
401
-	 * @return int
402
-	 * @throws BadRequest
403
-	 */
404
-	function createAddressBook($principalUri, $url, array $properties) {
405
-		$values = [
406
-			'displayname' => null,
407
-			'description' => null,
408
-			'principaluri' => $principalUri,
409
-			'uri' => $url,
410
-			'synctoken' => 1
411
-		];
412
-
413
-		foreach($properties as $property=>$newValue) {
414
-
415
-			switch($property) {
416
-				case '{DAV:}displayname' :
417
-					$values['displayname'] = $newValue;
418
-					break;
419
-				case '{' . Plugin::NS_CARDDAV . '}addressbook-description' :
420
-					$values['description'] = $newValue;
421
-					break;
422
-				default :
423
-					throw new BadRequest('Unknown property: ' . $property);
424
-			}
425
-
426
-		}
427
-
428
-		// Fallback to make sure the displayname is set. Some clients may refuse
429
-		// to work with addressbooks not having a displayname.
430
-		if(is_null($values['displayname'])) {
431
-			$values['displayname'] = $url;
432
-		}
433
-
434
-		$query = $this->db->getQueryBuilder();
435
-		$query->insert('addressbooks')
436
-			->values([
437
-				'uri' => $query->createParameter('uri'),
438
-				'displayname' => $query->createParameter('displayname'),
439
-				'description' => $query->createParameter('description'),
440
-				'principaluri' => $query->createParameter('principaluri'),
441
-				'synctoken' => $query->createParameter('synctoken'),
442
-			])
443
-			->setParameters($values)
444
-			->execute();
445
-
446
-		return $query->getLastInsertId();
447
-	}
448
-
449
-	/**
450
-	 * Deletes an entire addressbook and all its contents
451
-	 *
452
-	 * @param mixed $addressBookId
453
-	 * @return void
454
-	 */
455
-	function deleteAddressBook($addressBookId) {
456
-		$query = $this->db->getQueryBuilder();
457
-		$query->delete('cards')
458
-			->where($query->expr()->eq('addressbookid', $query->createParameter('addressbookid')))
459
-			->setParameter('addressbookid', $addressBookId)
460
-			->execute();
461
-
462
-		$query->delete('addressbookchanges')
463
-			->where($query->expr()->eq('addressbookid', $query->createParameter('addressbookid')))
464
-			->setParameter('addressbookid', $addressBookId)
465
-			->execute();
466
-
467
-		$query->delete('addressbooks')
468
-			->where($query->expr()->eq('id', $query->createParameter('id')))
469
-			->setParameter('id', $addressBookId)
470
-			->execute();
471
-
472
-		$this->sharingBackend->deleteAllShares($addressBookId);
473
-
474
-		$query->delete($this->dbCardsPropertiesTable)
475
-			->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
476
-			->execute();
477
-
478
-	}
479
-
480
-	/**
481
-	 * Returns all cards for a specific addressbook id.
482
-	 *
483
-	 * This method should return the following properties for each card:
484
-	 *   * carddata - raw vcard data
485
-	 *   * uri - Some unique url
486
-	 *   * lastmodified - A unix timestamp
487
-	 *
488
-	 * It's recommended to also return the following properties:
489
-	 *   * etag - A unique etag. This must change every time the card changes.
490
-	 *   * size - The size of the card in bytes.
491
-	 *
492
-	 * If these last two properties are provided, less time will be spent
493
-	 * calculating them. If they are specified, you can also ommit carddata.
494
-	 * This may speed up certain requests, especially with large cards.
495
-	 *
496
-	 * @param mixed $addressBookId
497
-	 * @return array
498
-	 */
499
-	function getCards($addressBookId) {
500
-		$query = $this->db->getQueryBuilder();
501
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata', 'uid'])
502
-			->from('cards')
503
-			->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
504
-
505
-		$cards = [];
506
-
507
-		$result = $query->execute();
508
-		while($row = $result->fetch()) {
509
-			$row['etag'] = '"' . $row['etag'] . '"';
510
-			$row['carddata'] = $this->readBlob($row['carddata']);
511
-			$cards[] = $row;
512
-		}
513
-		$result->closeCursor();
514
-
515
-		return $cards;
516
-	}
517
-
518
-	/**
519
-	 * Returns a specific card.
520
-	 *
521
-	 * The same set of properties must be returned as with getCards. The only
522
-	 * exception is that 'carddata' is absolutely required.
523
-	 *
524
-	 * If the card does not exist, you must return false.
525
-	 *
526
-	 * @param mixed $addressBookId
527
-	 * @param string $cardUri
528
-	 * @return array
529
-	 */
530
-	function getCard($addressBookId, $cardUri) {
531
-		$query = $this->db->getQueryBuilder();
532
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata', 'uid'])
533
-			->from('cards')
534
-			->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
535
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
536
-			->setMaxResults(1);
537
-
538
-		$result = $query->execute();
539
-		$row = $result->fetch();
540
-		if (!$row) {
541
-			return false;
542
-		}
543
-		$row['etag'] = '"' . $row['etag'] . '"';
544
-		$row['carddata'] = $this->readBlob($row['carddata']);
545
-
546
-		return $row;
547
-	}
548
-
549
-	/**
550
-	 * Returns a list of cards.
551
-	 *
552
-	 * This method should work identical to getCard, but instead return all the
553
-	 * cards in the list as an array.
554
-	 *
555
-	 * If the backend supports this, it may allow for some speed-ups.
556
-	 *
557
-	 * @param mixed $addressBookId
558
-	 * @param string[] $uris
559
-	 * @return array
560
-	 */
561
-	function getMultipleCards($addressBookId, array $uris) {
562
-		if (empty($uris)) {
563
-			return [];
564
-		}
565
-
566
-		$chunks = array_chunk($uris, 100);
567
-		$cards = [];
568
-
569
-		$query = $this->db->getQueryBuilder();
570
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata', 'uid'])
571
-			->from('cards')
572
-			->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
573
-			->andWhere($query->expr()->in('uri', $query->createParameter('uri')));
574
-
575
-		foreach ($chunks as $uris) {
576
-			$query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
577
-			$result = $query->execute();
578
-
579
-			while ($row = $result->fetch()) {
580
-				$row['etag'] = '"' . $row['etag'] . '"';
581
-				$row['carddata'] = $this->readBlob($row['carddata']);
582
-				$cards[] = $row;
583
-			}
584
-			$result->closeCursor();
585
-		}
586
-		return $cards;
587
-	}
588
-
589
-	/**
590
-	 * Creates a new card.
591
-	 *
592
-	 * The addressbook id will be passed as the first argument. This is the
593
-	 * same id as it is returned from the getAddressBooksForUser method.
594
-	 *
595
-	 * The cardUri is a base uri, and doesn't include the full path. The
596
-	 * cardData argument is the vcard body, and is passed as a string.
597
-	 *
598
-	 * It is possible to return an ETag from this method. This ETag is for the
599
-	 * newly created resource, and must be enclosed with double quotes (that
600
-	 * is, the string itself must contain the double quotes).
601
-	 *
602
-	 * You should only return the ETag if you store the carddata as-is. If a
603
-	 * subsequent GET request on the same card does not have the same body,
604
-	 * byte-by-byte and you did return an ETag here, clients tend to get
605
-	 * confused.
606
-	 *
607
-	 * If you don't return an ETag, you can just return null.
608
-	 *
609
-	 * @param mixed $addressBookId
610
-	 * @param string $cardUri
611
-	 * @param string $cardData
612
-	 * @return string
613
-	 */
614
-	function createCard($addressBookId, $cardUri, $cardData) {
615
-		$etag = md5($cardData);
616
-		$uid = $this->getUID($cardData);
617
-
618
-		$q = $this->db->getQueryBuilder();
619
-		$q->select('uid')
620
-			->from('cards')
621
-			->where($q->expr()->eq('addressbookid', $q->createNamedParameter($addressBookId)))
622
-			->andWhere($q->expr()->eq('uid', $q->createNamedParameter($uid)))
623
-			->setMaxResults(1);
624
-		$result = $q->execute();
625
-		$count = (bool) $result->fetchColumn();
626
-		$result->closeCursor();
627
-		if ($count) {
628
-			throw new \Sabre\DAV\Exception\BadRequest('VCard object with uid already exists in this addressbook collection.');
629
-		}
630
-
631
-		$query = $this->db->getQueryBuilder();
632
-		$query->insert('cards')
633
-			->values([
634
-				'carddata' => $query->createNamedParameter($cardData, IQueryBuilder::PARAM_LOB),
635
-				'uri' => $query->createNamedParameter($cardUri),
636
-				'lastmodified' => $query->createNamedParameter(time()),
637
-				'addressbookid' => $query->createNamedParameter($addressBookId),
638
-				'size' => $query->createNamedParameter(strlen($cardData)),
639
-				'etag' => $query->createNamedParameter($etag),
640
-				'uid' => $query->createNamedParameter($uid),
641
-			])
642
-			->execute();
643
-
644
-		$this->addChange($addressBookId, $cardUri, 1);
645
-		$this->updateProperties($addressBookId, $cardUri, $cardData);
646
-
647
-		$this->dispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::createCard',
648
-			new GenericEvent(null, [
649
-				'addressBookId' => $addressBookId,
650
-				'cardUri' => $cardUri,
651
-				'cardData' => $cardData]));
652
-
653
-		return '"' . $etag . '"';
654
-	}
655
-
656
-	/**
657
-	 * Updates a card.
658
-	 *
659
-	 * The addressbook id will be passed as the first argument. This is the
660
-	 * same id as it is returned from the getAddressBooksForUser method.
661
-	 *
662
-	 * The cardUri is a base uri, and doesn't include the full path. The
663
-	 * cardData argument is the vcard body, and is passed as a string.
664
-	 *
665
-	 * It is possible to return an ETag from this method. This ETag should
666
-	 * match that of the updated resource, and must be enclosed with double
667
-	 * quotes (that is: the string itself must contain the actual quotes).
668
-	 *
669
-	 * You should only return the ETag if you store the carddata as-is. If a
670
-	 * subsequent GET request on the same card does not have the same body,
671
-	 * byte-by-byte and you did return an ETag here, clients tend to get
672
-	 * confused.
673
-	 *
674
-	 * If you don't return an ETag, you can just return null.
675
-	 *
676
-	 * @param mixed $addressBookId
677
-	 * @param string $cardUri
678
-	 * @param string $cardData
679
-	 * @return string
680
-	 */
681
-	function updateCard($addressBookId, $cardUri, $cardData) {
682
-
683
-		$uid = $this->getUID($cardData);
684
-		$etag = md5($cardData);
685
-		$query = $this->db->getQueryBuilder();
686
-		$query->update('cards')
687
-			->set('carddata', $query->createNamedParameter($cardData, IQueryBuilder::PARAM_LOB))
688
-			->set('lastmodified', $query->createNamedParameter(time()))
689
-			->set('size', $query->createNamedParameter(strlen($cardData)))
690
-			->set('etag', $query->createNamedParameter($etag))
691
-			->set('uid', $query->createNamedParameter($uid))
692
-			->where($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
693
-			->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
694
-			->execute();
695
-
696
-		$this->addChange($addressBookId, $cardUri, 2);
697
-		$this->updateProperties($addressBookId, $cardUri, $cardData);
698
-
699
-		$this->dispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::updateCard',
700
-			new GenericEvent(null, [
701
-				'addressBookId' => $addressBookId,
702
-				'cardUri' => $cardUri,
703
-				'cardData' => $cardData]));
704
-
705
-		return '"' . $etag . '"';
706
-	}
707
-
708
-	/**
709
-	 * Deletes a card
710
-	 *
711
-	 * @param mixed $addressBookId
712
-	 * @param string $cardUri
713
-	 * @return bool
714
-	 */
715
-	function deleteCard($addressBookId, $cardUri) {
716
-		try {
717
-			$cardId = $this->getCardId($addressBookId, $cardUri);
718
-		} catch (\InvalidArgumentException $e) {
719
-			$cardId = null;
720
-		}
721
-		$query = $this->db->getQueryBuilder();
722
-		$ret = $query->delete('cards')
723
-			->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
724
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
725
-			->execute();
726
-
727
-		$this->addChange($addressBookId, $cardUri, 3);
728
-
729
-		$this->dispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::deleteCard',
730
-			new GenericEvent(null, [
731
-				'addressBookId' => $addressBookId,
732
-				'cardUri' => $cardUri]));
733
-
734
-		if ($ret === 1) {
735
-			if ($cardId !== null) {
736
-				$this->purgeProperties($addressBookId, $cardId);
737
-			}
738
-			return true;
739
-		}
740
-
741
-		return false;
742
-	}
743
-
744
-	/**
745
-	 * The getChanges method returns all the changes that have happened, since
746
-	 * the specified syncToken in the specified address book.
747
-	 *
748
-	 * This function should return an array, such as the following:
749
-	 *
750
-	 * [
751
-	 *   'syncToken' => 'The current synctoken',
752
-	 *   'added'   => [
753
-	 *      'new.txt',
754
-	 *   ],
755
-	 *   'modified'   => [
756
-	 *      'modified.txt',
757
-	 *   ],
758
-	 *   'deleted' => [
759
-	 *      'foo.php.bak',
760
-	 *      'old.txt'
761
-	 *   ]
762
-	 * ];
763
-	 *
764
-	 * The returned syncToken property should reflect the *current* syncToken
765
-	 * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
766
-	 * property. This is needed here too, to ensure the operation is atomic.
767
-	 *
768
-	 * If the $syncToken argument is specified as null, this is an initial
769
-	 * sync, and all members should be reported.
770
-	 *
771
-	 * The modified property is an array of nodenames that have changed since
772
-	 * the last token.
773
-	 *
774
-	 * The deleted property is an array with nodenames, that have been deleted
775
-	 * from collection.
776
-	 *
777
-	 * The $syncLevel argument is basically the 'depth' of the report. If it's
778
-	 * 1, you only have to report changes that happened only directly in
779
-	 * immediate descendants. If it's 2, it should also include changes from
780
-	 * the nodes below the child collections. (grandchildren)
781
-	 *
782
-	 * The $limit argument allows a client to specify how many results should
783
-	 * be returned at most. If the limit is not specified, it should be treated
784
-	 * as infinite.
785
-	 *
786
-	 * If the limit (infinite or not) is higher than you're willing to return,
787
-	 * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
788
-	 *
789
-	 * If the syncToken is expired (due to data cleanup) or unknown, you must
790
-	 * return null.
791
-	 *
792
-	 * The limit is 'suggestive'. You are free to ignore it.
793
-	 *
794
-	 * @param string $addressBookId
795
-	 * @param string $syncToken
796
-	 * @param int $syncLevel
797
-	 * @param int $limit
798
-	 * @return array
799
-	 */
800
-	function getChangesForAddressBook($addressBookId, $syncToken, $syncLevel, $limit = null) {
801
-		// Current synctoken
802
-		$stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*addressbooks` WHERE `id` = ?');
803
-		$stmt->execute([ $addressBookId ]);
804
-		$currentToken = $stmt->fetchColumn(0);
805
-
806
-		if (is_null($currentToken)) return null;
807
-
808
-		$result = [
809
-			'syncToken' => $currentToken,
810
-			'added'     => [],
811
-			'modified'  => [],
812
-			'deleted'   => [],
813
-		];
814
-
815
-		if ($syncToken) {
816
-
817
-			$query = "SELECT `uri`, `operation` FROM `*PREFIX*addressbookchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `addressbookid` = ? ORDER BY `synctoken`";
818
-			if ($limit>0) {
819
-				$query .= " LIMIT " . (int)$limit;
820
-			}
821
-
822
-			// Fetching all changes
823
-			$stmt = $this->db->prepare($query);
824
-			$stmt->execute([$syncToken, $currentToken, $addressBookId]);
825
-
826
-			$changes = [];
827
-
828
-			// This loop ensures that any duplicates are overwritten, only the
829
-			// last change on a node is relevant.
830
-			while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
831
-
832
-				$changes[$row['uri']] = $row['operation'];
833
-
834
-			}
835
-
836
-			foreach($changes as $uri => $operation) {
837
-
838
-				switch($operation) {
839
-					case 1:
840
-						$result['added'][] = $uri;
841
-						break;
842
-					case 2:
843
-						$result['modified'][] = $uri;
844
-						break;
845
-					case 3:
846
-						$result['deleted'][] = $uri;
847
-						break;
848
-				}
849
-
850
-			}
851
-		} else {
852
-			// No synctoken supplied, this is the initial sync.
853
-			$query = "SELECT `uri` FROM `*PREFIX*cards` WHERE `addressbookid` = ?";
854
-			$stmt = $this->db->prepare($query);
855
-			$stmt->execute([$addressBookId]);
856
-
857
-			$result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
858
-		}
859
-		return $result;
860
-	}
861
-
862
-	/**
863
-	 * Adds a change record to the addressbookchanges table.
864
-	 *
865
-	 * @param mixed $addressBookId
866
-	 * @param string $objectUri
867
-	 * @param int $operation 1 = add, 2 = modify, 3 = delete
868
-	 * @return void
869
-	 */
870
-	protected function addChange($addressBookId, $objectUri, $operation) {
871
-		$sql = 'INSERT INTO `*PREFIX*addressbookchanges`(`uri`, `synctoken`, `addressbookid`, `operation`) SELECT ?, `synctoken`, ?, ? FROM `*PREFIX*addressbooks` WHERE `id` = ?';
872
-		$stmt = $this->db->prepare($sql);
873
-		$stmt->execute([
874
-			$objectUri,
875
-			$addressBookId,
876
-			$operation,
877
-			$addressBookId
878
-		]);
879
-		$stmt = $this->db->prepare('UPDATE `*PREFIX*addressbooks` SET `synctoken` = `synctoken` + 1 WHERE `id` = ?');
880
-		$stmt->execute([
881
-			$addressBookId
882
-		]);
883
-	}
884
-
885
-	private function readBlob($cardData) {
886
-		if (is_resource($cardData)) {
887
-			return stream_get_contents($cardData);
888
-		}
889
-
890
-		return $cardData;
891
-	}
892
-
893
-	/**
894
-	 * @param IShareable $shareable
895
-	 * @param string[] $add
896
-	 * @param string[] $remove
897
-	 */
898
-	public function updateShares(IShareable $shareable, $add, $remove) {
899
-		$this->sharingBackend->updateShares($shareable, $add, $remove);
900
-	}
901
-
902
-	/**
903
-	 * search contact
904
-	 *
905
-	 * @param int $addressBookId
906
-	 * @param string $pattern which should match within the $searchProperties
907
-	 * @param array $searchProperties defines the properties within the query pattern should match
908
-	 * @param array $options = array() to define the search behavior
909
-	 * 	- 'escape_like_param' - If set to false wildcards _ and % are not escaped, otherwise they are
910
-	 * @return array an array of contacts which are arrays of key-value-pairs
911
-	 */
912
-	public function search($addressBookId, $pattern, $searchProperties, $options = []) {
913
-		$query = $this->db->getQueryBuilder();
914
-		$query2 = $this->db->getQueryBuilder();
915
-
916
-		$query2->selectDistinct('cp.cardid')->from($this->dbCardsPropertiesTable, 'cp');
917
-		$query2->andWhere($query2->expr()->eq('cp.addressbookid', $query->createNamedParameter($addressBookId)));
918
-		$or = $query2->expr()->orX();
919
-		foreach ($searchProperties as $property) {
920
-			$or->add($query2->expr()->eq('cp.name', $query->createNamedParameter($property)));
921
-		}
922
-		$query2->andWhere($or);
923
-
924
-		// No need for like when the pattern is empty
925
-		if ('' !== $pattern) {
926
-			if(\array_key_exists('escape_like_param', $options) && $options['escape_like_param'] === false) {
927
-				$query2->andWhere($query2->expr()->ilike('cp.value', $query->createNamedParameter($pattern)));
928
-			} else {
929
-				$query2->andWhere($query2->expr()->ilike('cp.value', $query->createNamedParameter('%' . $this->db->escapeLikeParameter($pattern) . '%')));
930
-			}
931
-		}
932
-
933
-		$query->select('c.carddata', 'c.uri')->from($this->dbCardsTable, 'c')
934
-			->where($query->expr()->in('c.id', $query->createFunction($query2->getSQL())));
935
-
936
-		$result = $query->execute();
937
-		$cards = $result->fetchAll();
938
-
939
-		$result->closeCursor();
940
-
941
-		return array_map(function($array) {
942
-			$array['carddata'] = $this->readBlob($array['carddata']);
943
-			return $array;
944
-		}, $cards);
945
-	}
946
-
947
-	/**
948
-	 * @param int $bookId
949
-	 * @param string $name
950
-	 * @return array
951
-	 */
952
-	public function collectCardProperties($bookId, $name) {
953
-		$query = $this->db->getQueryBuilder();
954
-		$result = $query->selectDistinct('value')
955
-			->from($this->dbCardsPropertiesTable)
956
-			->where($query->expr()->eq('name', $query->createNamedParameter($name)))
957
-			->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($bookId)))
958
-			->execute();
959
-
960
-		$all = $result->fetchAll(PDO::FETCH_COLUMN);
961
-		$result->closeCursor();
962
-
963
-		return $all;
964
-	}
965
-
966
-	/**
967
-	 * get URI from a given contact
968
-	 *
969
-	 * @param int $id
970
-	 * @return string
971
-	 */
972
-	public function getCardUri($id) {
973
-		$query = $this->db->getQueryBuilder();
974
-		$query->select('uri')->from($this->dbCardsTable)
975
-				->where($query->expr()->eq('id', $query->createParameter('id')))
976
-				->setParameter('id', $id);
977
-
978
-		$result = $query->execute();
979
-		$uri = $result->fetch();
980
-		$result->closeCursor();
981
-
982
-		if (!isset($uri['uri'])) {
983
-			throw new \InvalidArgumentException('Card does not exists: ' . $id);
984
-		}
985
-
986
-		return $uri['uri'];
987
-	}
988
-
989
-	/**
990
-	 * return contact with the given URI
991
-	 *
992
-	 * @param int $addressBookId
993
-	 * @param string $uri
994
-	 * @returns array
995
-	 */
996
-	public function getContact($addressBookId, $uri) {
997
-		$result = [];
998
-		$query = $this->db->getQueryBuilder();
999
-		$query->select('*')->from($this->dbCardsTable)
1000
-				->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
1001
-				->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
1002
-		$queryResult = $query->execute();
1003
-		$contact = $queryResult->fetch();
1004
-		$queryResult->closeCursor();
1005
-
1006
-		if (is_array($contact)) {
1007
-			$result = $contact;
1008
-		}
1009
-
1010
-		return $result;
1011
-	}
1012
-
1013
-	/**
1014
-	 * Returns the list of people whom this address book is shared with.
1015
-	 *
1016
-	 * Every element in this array should have the following properties:
1017
-	 *   * href - Often a mailto: address
1018
-	 *   * commonName - Optional, for example a first + last name
1019
-	 *   * status - See the Sabre\CalDAV\SharingPlugin::STATUS_ constants.
1020
-	 *   * readOnly - boolean
1021
-	 *   * summary - Optional, a description for the share
1022
-	 *
1023
-	 * @return array
1024
-	 */
1025
-	public function getShares($addressBookId) {
1026
-		return $this->sharingBackend->getShares($addressBookId);
1027
-	}
1028
-
1029
-	/**
1030
-	 * update properties table
1031
-	 *
1032
-	 * @param int $addressBookId
1033
-	 * @param string $cardUri
1034
-	 * @param string $vCardSerialized
1035
-	 */
1036
-	protected function updateProperties($addressBookId, $cardUri, $vCardSerialized) {
1037
-		$cardId = $this->getCardId($addressBookId, $cardUri);
1038
-		$vCard = $this->readCard($vCardSerialized);
1039
-
1040
-		$this->purgeProperties($addressBookId, $cardId);
1041
-
1042
-		$query = $this->db->getQueryBuilder();
1043
-		$query->insert($this->dbCardsPropertiesTable)
1044
-			->values(
1045
-				[
1046
-					'addressbookid' => $query->createNamedParameter($addressBookId),
1047
-					'cardid' => $query->createNamedParameter($cardId),
1048
-					'name' => $query->createParameter('name'),
1049
-					'value' => $query->createParameter('value'),
1050
-					'preferred' => $query->createParameter('preferred')
1051
-				]
1052
-			);
1053
-
1054
-		foreach ($vCard->children() as $property) {
1055
-			if(!in_array($property->name, self::$indexProperties)) {
1056
-				continue;
1057
-			}
1058
-			$preferred = 0;
1059
-			foreach($property->parameters as $parameter) {
1060
-				if ($parameter->name === 'TYPE' && strtoupper($parameter->getValue()) === 'PREF') {
1061
-					$preferred = 1;
1062
-					break;
1063
-				}
1064
-			}
1065
-			$query->setParameter('name', $property->name);
1066
-			$query->setParameter('value', mb_substr($property->getValue(), 0, 254));
1067
-			$query->setParameter('preferred', $preferred);
1068
-			$query->execute();
1069
-		}
1070
-	}
1071
-
1072
-	/**
1073
-	 * read vCard data into a vCard object
1074
-	 *
1075
-	 * @param string $cardData
1076
-	 * @return VCard
1077
-	 */
1078
-	protected function readCard($cardData) {
1079
-		return  Reader::read($cardData);
1080
-	}
1081
-
1082
-	/**
1083
-	 * delete all properties from a given card
1084
-	 *
1085
-	 * @param int $addressBookId
1086
-	 * @param int $cardId
1087
-	 */
1088
-	protected function purgeProperties($addressBookId, $cardId) {
1089
-		$query = $this->db->getQueryBuilder();
1090
-		$query->delete($this->dbCardsPropertiesTable)
1091
-			->where($query->expr()->eq('cardid', $query->createNamedParameter($cardId)))
1092
-			->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
1093
-		$query->execute();
1094
-	}
1095
-
1096
-	/**
1097
-	 * get ID from a given contact
1098
-	 *
1099
-	 * @param int $addressBookId
1100
-	 * @param string $uri
1101
-	 * @return int
1102
-	 */
1103
-	protected function getCardId($addressBookId, $uri) {
1104
-		$query = $this->db->getQueryBuilder();
1105
-		$query->select('id')->from($this->dbCardsTable)
1106
-			->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
1107
-			->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
1108
-
1109
-		$result = $query->execute();
1110
-		$cardIds = $result->fetch();
1111
-		$result->closeCursor();
1112
-
1113
-		if (!isset($cardIds['id'])) {
1114
-			throw new \InvalidArgumentException('Card does not exists: ' . $uri);
1115
-		}
1116
-
1117
-		return (int)$cardIds['id'];
1118
-	}
1119
-
1120
-	/**
1121
-	 * For shared address books the sharee is set in the ACL of the address book
1122
-	 * @param $addressBookId
1123
-	 * @param $acl
1124
-	 * @return array
1125
-	 */
1126
-	public function applyShareAcl($addressBookId, $acl) {
1127
-		return $this->sharingBackend->applyShareAcl($addressBookId, $acl);
1128
-	}
1129
-
1130
-	private function convertPrincipal($principalUri, $toV2) {
1131
-		if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
1132
-			list(, $name) = \Sabre\Uri\split($principalUri);
1133
-			if ($toV2 === true) {
1134
-				return "principals/users/$name";
1135
-			}
1136
-			return "principals/$name";
1137
-		}
1138
-		return $principalUri;
1139
-	}
1140
-
1141
-	private function addOwnerPrincipal(&$addressbookInfo) {
1142
-		$ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
1143
-		$displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
1144
-		if (isset($addressbookInfo[$ownerPrincipalKey])) {
1145
-			$uri = $addressbookInfo[$ownerPrincipalKey];
1146
-		} else {
1147
-			$uri = $addressbookInfo['principaluri'];
1148
-		}
1149
-
1150
-		$principalInformation = $this->principalBackend->getPrincipalByPath($uri);
1151
-		if (isset($principalInformation['{DAV:}displayname'])) {
1152
-			$addressbookInfo[$displaynameKey] = $principalInformation['{DAV:}displayname'];
1153
-		}
1154
-	}
1155
-
1156
-	/**
1157
-	 * Extract UID from vcard
1158
-	 *
1159
-	 * @param string $cardData the vcard raw data
1160
-	 * @return string the uid
1161
-	 * @throws BadRequest if no UID is available
1162
-	 */
1163
-	private function getUID($cardData) {
1164
-		if ($cardData != '') {
1165
-			$vCard = Reader::read($cardData);
1166
-			if ($vCard->UID) {
1167
-				$uid = $vCard->UID->getValue();
1168
-				return $uid;
1169
-			}
1170
-			// should already be handled, but just in case
1171
-			throw new BadRequest('vCards on CardDAV servers MUST have a UID property');
1172
-		}
1173
-		// should already be handled, but just in case
1174
-		throw new BadRequest('vCard can not be empty');
1175
-	}
58
+    const PERSONAL_ADDRESSBOOK_URI = 'contacts';
59
+    const PERSONAL_ADDRESSBOOK_NAME = 'Contacts';
60
+
61
+    /** @var Principal */
62
+    private $principalBackend;
63
+
64
+    /** @var string */
65
+    private $dbCardsTable = 'cards';
66
+
67
+    /** @var string */
68
+    private $dbCardsPropertiesTable = 'cards_properties';
69
+
70
+    /** @var IDBConnection */
71
+    private $db;
72
+
73
+    /** @var Backend */
74
+    private $sharingBackend;
75
+
76
+    /** @var array properties to index */
77
+    public static $indexProperties = [
78
+            'BDAY', 'UID', 'N', 'FN', 'TITLE', 'ROLE', 'NOTE', 'NICKNAME',
79
+            'ORG', 'CATEGORIES', 'EMAIL', 'TEL', 'IMPP', 'ADR', 'URL', 'GEO', 'CLOUD'];
80
+
81
+    /**
82
+     * @var string[] Map of uid => display name
83
+     */
84
+    protected $userDisplayNames;
85
+
86
+    /** @var IUserManager */
87
+    private $userManager;
88
+
89
+    /** @var EventDispatcherInterface */
90
+    private $dispatcher;
91
+
92
+    /**
93
+     * CardDavBackend constructor.
94
+     *
95
+     * @param IDBConnection $db
96
+     * @param Principal $principalBackend
97
+     * @param IUserManager $userManager
98
+     * @param IGroupManager $groupManager
99
+     * @param EventDispatcherInterface $dispatcher
100
+     */
101
+    public function __construct(IDBConnection $db,
102
+                                Principal $principalBackend,
103
+                                IUserManager $userManager,
104
+                                IGroupManager $groupManager,
105
+                                EventDispatcherInterface $dispatcher) {
106
+        $this->db = $db;
107
+        $this->principalBackend = $principalBackend;
108
+        $this->userManager = $userManager;
109
+        $this->dispatcher = $dispatcher;
110
+        $this->sharingBackend = new Backend($this->db, $this->userManager, $groupManager, $principalBackend, 'addressbook');
111
+    }
112
+
113
+    /**
114
+     * Return the number of address books for a principal
115
+     *
116
+     * @param $principalUri
117
+     * @return int
118
+     */
119
+    public function getAddressBooksForUserCount($principalUri) {
120
+        $principalUri = $this->convertPrincipal($principalUri, true);
121
+        $query = $this->db->getQueryBuilder();
122
+        $query->select($query->func()->count('*'))
123
+            ->from('addressbooks')
124
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
125
+
126
+        return (int)$query->execute()->fetchColumn();
127
+    }
128
+
129
+    /**
130
+     * Returns the list of address books for a specific user.
131
+     *
132
+     * Every addressbook should have the following properties:
133
+     *   id - an arbitrary unique id
134
+     *   uri - the 'basename' part of the url
135
+     *   principaluri - Same as the passed parameter
136
+     *
137
+     * Any additional clark-notation property may be passed besides this. Some
138
+     * common ones are :
139
+     *   {DAV:}displayname
140
+     *   {urn:ietf:params:xml:ns:carddav}addressbook-description
141
+     *   {http://calendarserver.org/ns/}getctag
142
+     *
143
+     * @param string $principalUri
144
+     * @return array
145
+     */
146
+    function getAddressBooksForUser($principalUri) {
147
+        $principalUriOriginal = $principalUri;
148
+        $principalUri = $this->convertPrincipal($principalUri, true);
149
+        $query = $this->db->getQueryBuilder();
150
+        $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
151
+            ->from('addressbooks')
152
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
153
+
154
+        $addressBooks = [];
155
+
156
+        $result = $query->execute();
157
+        while($row = $result->fetch()) {
158
+            $addressBooks[$row['id']] = [
159
+                'id'  => $row['id'],
160
+                'uri' => $row['uri'],
161
+                'principaluri' => $this->convertPrincipal($row['principaluri'], false),
162
+                '{DAV:}displayname' => $row['displayname'],
163
+                '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
164
+                '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
165
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
166
+            ];
167
+
168
+            $this->addOwnerPrincipal($addressBooks[$row['id']]);
169
+        }
170
+        $result->closeCursor();
171
+
172
+        // query for shared addressbooks
173
+        $principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
174
+        $principals = array_merge($principals, $this->principalBackend->getCircleMembership($principalUriOriginal));
175
+
176
+        $principals = array_map(function($principal) {
177
+            return urldecode($principal);
178
+        }, $principals);
179
+        $principals[]= $principalUri;
180
+
181
+        $query = $this->db->getQueryBuilder();
182
+        $result = $query->select(['a.id', 'a.uri', 'a.displayname', 'a.principaluri', 'a.description', 'a.synctoken', 's.access'])
183
+            ->from('dav_shares', 's')
184
+            ->join('s', 'addressbooks', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
185
+            ->where($query->expr()->in('s.principaluri', $query->createParameter('principaluri')))
186
+            ->andWhere($query->expr()->eq('s.type', $query->createParameter('type')))
187
+            ->setParameter('type', 'addressbook')
188
+            ->setParameter('principaluri', $principals, IQueryBuilder::PARAM_STR_ARRAY)
189
+            ->execute();
190
+
191
+        $readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
192
+        while($row = $result->fetch()) {
193
+            if ($row['principaluri'] === $principalUri) {
194
+                continue;
195
+            }
196
+
197
+            $readOnly = (int) $row['access'] === Backend::ACCESS_READ;
198
+            if (isset($addressBooks[$row['id']])) {
199
+                if ($readOnly) {
200
+                    // New share can not have more permissions then the old one.
201
+                    continue;
202
+                }
203
+                if (isset($addressBooks[$row['id']][$readOnlyPropertyName]) &&
204
+                    $addressBooks[$row['id']][$readOnlyPropertyName] === 0) {
205
+                    // Old share is already read-write, no more permissions can be gained
206
+                    continue;
207
+                }
208
+            }
209
+
210
+            list(, $name) = \Sabre\Uri\split($row['principaluri']);
211
+            $uri = $row['uri'] . '_shared_by_' . $name;
212
+            $displayName = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
213
+
214
+            $addressBooks[$row['id']] = [
215
+                'id'  => $row['id'],
216
+                'uri' => $uri,
217
+                'principaluri' => $principalUriOriginal,
218
+                '{DAV:}displayname' => $displayName,
219
+                '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
220
+                '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
221
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
222
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $row['principaluri'],
223
+                $readOnlyPropertyName => $readOnly,
224
+            ];
225
+
226
+            $this->addOwnerPrincipal($addressBooks[$row['id']]);
227
+        }
228
+        $result->closeCursor();
229
+
230
+        return array_values($addressBooks);
231
+    }
232
+
233
+    public function getUsersOwnAddressBooks($principalUri) {
234
+        $principalUri = $this->convertPrincipal($principalUri, true);
235
+        $query = $this->db->getQueryBuilder();
236
+        $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
237
+                ->from('addressbooks')
238
+                ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
239
+
240
+        $addressBooks = [];
241
+
242
+        $result = $query->execute();
243
+        while($row = $result->fetch()) {
244
+            $addressBooks[$row['id']] = [
245
+                'id'  => $row['id'],
246
+                'uri' => $row['uri'],
247
+                'principaluri' => $this->convertPrincipal($row['principaluri'], false),
248
+                '{DAV:}displayname' => $row['displayname'],
249
+                '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
250
+                '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
251
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
252
+            ];
253
+
254
+            $this->addOwnerPrincipal($addressBooks[$row['id']]);
255
+        }
256
+        $result->closeCursor();
257
+
258
+        return array_values($addressBooks);
259
+    }
260
+
261
+    private function getUserDisplayName($uid) {
262
+        if (!isset($this->userDisplayNames[$uid])) {
263
+            $user = $this->userManager->get($uid);
264
+
265
+            if ($user instanceof IUser) {
266
+                $this->userDisplayNames[$uid] = $user->getDisplayName();
267
+            } else {
268
+                $this->userDisplayNames[$uid] = $uid;
269
+            }
270
+        }
271
+
272
+        return $this->userDisplayNames[$uid];
273
+    }
274
+
275
+    /**
276
+     * @param int $addressBookId
277
+     */
278
+    public function getAddressBookById($addressBookId) {
279
+        $query = $this->db->getQueryBuilder();
280
+        $result = $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
281
+            ->from('addressbooks')
282
+            ->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId)))
283
+            ->execute();
284
+
285
+        $row = $result->fetch();
286
+        $result->closeCursor();
287
+        if ($row === false) {
288
+            return null;
289
+        }
290
+
291
+        $addressBook = [
292
+            'id'  => $row['id'],
293
+            'uri' => $row['uri'],
294
+            'principaluri' => $row['principaluri'],
295
+            '{DAV:}displayname' => $row['displayname'],
296
+            '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
297
+            '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
298
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
299
+        ];
300
+
301
+        $this->addOwnerPrincipal($addressBook);
302
+
303
+        return $addressBook;
304
+    }
305
+
306
+    /**
307
+     * @param $addressBookUri
308
+     * @return array|null
309
+     */
310
+    public function getAddressBooksByUri($principal, $addressBookUri) {
311
+        $query = $this->db->getQueryBuilder();
312
+        $result = $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
313
+            ->from('addressbooks')
314
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($addressBookUri)))
315
+            ->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
316
+            ->setMaxResults(1)
317
+            ->execute();
318
+
319
+        $row = $result->fetch();
320
+        $result->closeCursor();
321
+        if ($row === false) {
322
+            return null;
323
+        }
324
+
325
+        $addressBook = [
326
+            'id'  => $row['id'],
327
+            'uri' => $row['uri'],
328
+            'principaluri' => $row['principaluri'],
329
+            '{DAV:}displayname' => $row['displayname'],
330
+            '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
331
+            '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
332
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
333
+        ];
334
+
335
+        $this->addOwnerPrincipal($addressBook);
336
+
337
+        return $addressBook;
338
+    }
339
+
340
+    /**
341
+     * Updates properties for an address book.
342
+     *
343
+     * The list of mutations is stored in a Sabre\DAV\PropPatch object.
344
+     * To do the actual updates, you must tell this object which properties
345
+     * you're going to process with the handle() method.
346
+     *
347
+     * Calling the handle method is like telling the PropPatch object "I
348
+     * promise I can handle updating this property".
349
+     *
350
+     * Read the PropPatch documentation for more info and examples.
351
+     *
352
+     * @param string $addressBookId
353
+     * @param \Sabre\DAV\PropPatch $propPatch
354
+     * @return void
355
+     */
356
+    function updateAddressBook($addressBookId, \Sabre\DAV\PropPatch $propPatch) {
357
+        $supportedProperties = [
358
+            '{DAV:}displayname',
359
+            '{' . Plugin::NS_CARDDAV . '}addressbook-description',
360
+        ];
361
+
362
+        /**
363
+         * @suppress SqlInjectionChecker
364
+         */
365
+        $propPatch->handle($supportedProperties, function($mutations) use ($addressBookId) {
366
+
367
+            $updates = [];
368
+            foreach($mutations as $property=>$newValue) {
369
+
370
+                switch($property) {
371
+                    case '{DAV:}displayname' :
372
+                        $updates['displayname'] = $newValue;
373
+                        break;
374
+                    case '{' . Plugin::NS_CARDDAV . '}addressbook-description' :
375
+                        $updates['description'] = $newValue;
376
+                        break;
377
+                }
378
+            }
379
+            $query = $this->db->getQueryBuilder();
380
+            $query->update('addressbooks');
381
+
382
+            foreach($updates as $key=>$value) {
383
+                $query->set($key, $query->createNamedParameter($value));
384
+            }
385
+            $query->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId)))
386
+            ->execute();
387
+
388
+            $this->addChange($addressBookId, "", 2);
389
+
390
+            return true;
391
+
392
+        });
393
+    }
394
+
395
+    /**
396
+     * Creates a new address book
397
+     *
398
+     * @param string $principalUri
399
+     * @param string $url Just the 'basename' of the url.
400
+     * @param array $properties
401
+     * @return int
402
+     * @throws BadRequest
403
+     */
404
+    function createAddressBook($principalUri, $url, array $properties) {
405
+        $values = [
406
+            'displayname' => null,
407
+            'description' => null,
408
+            'principaluri' => $principalUri,
409
+            'uri' => $url,
410
+            'synctoken' => 1
411
+        ];
412
+
413
+        foreach($properties as $property=>$newValue) {
414
+
415
+            switch($property) {
416
+                case '{DAV:}displayname' :
417
+                    $values['displayname'] = $newValue;
418
+                    break;
419
+                case '{' . Plugin::NS_CARDDAV . '}addressbook-description' :
420
+                    $values['description'] = $newValue;
421
+                    break;
422
+                default :
423
+                    throw new BadRequest('Unknown property: ' . $property);
424
+            }
425
+
426
+        }
427
+
428
+        // Fallback to make sure the displayname is set. Some clients may refuse
429
+        // to work with addressbooks not having a displayname.
430
+        if(is_null($values['displayname'])) {
431
+            $values['displayname'] = $url;
432
+        }
433
+
434
+        $query = $this->db->getQueryBuilder();
435
+        $query->insert('addressbooks')
436
+            ->values([
437
+                'uri' => $query->createParameter('uri'),
438
+                'displayname' => $query->createParameter('displayname'),
439
+                'description' => $query->createParameter('description'),
440
+                'principaluri' => $query->createParameter('principaluri'),
441
+                'synctoken' => $query->createParameter('synctoken'),
442
+            ])
443
+            ->setParameters($values)
444
+            ->execute();
445
+
446
+        return $query->getLastInsertId();
447
+    }
448
+
449
+    /**
450
+     * Deletes an entire addressbook and all its contents
451
+     *
452
+     * @param mixed $addressBookId
453
+     * @return void
454
+     */
455
+    function deleteAddressBook($addressBookId) {
456
+        $query = $this->db->getQueryBuilder();
457
+        $query->delete('cards')
458
+            ->where($query->expr()->eq('addressbookid', $query->createParameter('addressbookid')))
459
+            ->setParameter('addressbookid', $addressBookId)
460
+            ->execute();
461
+
462
+        $query->delete('addressbookchanges')
463
+            ->where($query->expr()->eq('addressbookid', $query->createParameter('addressbookid')))
464
+            ->setParameter('addressbookid', $addressBookId)
465
+            ->execute();
466
+
467
+        $query->delete('addressbooks')
468
+            ->where($query->expr()->eq('id', $query->createParameter('id')))
469
+            ->setParameter('id', $addressBookId)
470
+            ->execute();
471
+
472
+        $this->sharingBackend->deleteAllShares($addressBookId);
473
+
474
+        $query->delete($this->dbCardsPropertiesTable)
475
+            ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
476
+            ->execute();
477
+
478
+    }
479
+
480
+    /**
481
+     * Returns all cards for a specific addressbook id.
482
+     *
483
+     * This method should return the following properties for each card:
484
+     *   * carddata - raw vcard data
485
+     *   * uri - Some unique url
486
+     *   * lastmodified - A unix timestamp
487
+     *
488
+     * It's recommended to also return the following properties:
489
+     *   * etag - A unique etag. This must change every time the card changes.
490
+     *   * size - The size of the card in bytes.
491
+     *
492
+     * If these last two properties are provided, less time will be spent
493
+     * calculating them. If they are specified, you can also ommit carddata.
494
+     * This may speed up certain requests, especially with large cards.
495
+     *
496
+     * @param mixed $addressBookId
497
+     * @return array
498
+     */
499
+    function getCards($addressBookId) {
500
+        $query = $this->db->getQueryBuilder();
501
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata', 'uid'])
502
+            ->from('cards')
503
+            ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
504
+
505
+        $cards = [];
506
+
507
+        $result = $query->execute();
508
+        while($row = $result->fetch()) {
509
+            $row['etag'] = '"' . $row['etag'] . '"';
510
+            $row['carddata'] = $this->readBlob($row['carddata']);
511
+            $cards[] = $row;
512
+        }
513
+        $result->closeCursor();
514
+
515
+        return $cards;
516
+    }
517
+
518
+    /**
519
+     * Returns a specific card.
520
+     *
521
+     * The same set of properties must be returned as with getCards. The only
522
+     * exception is that 'carddata' is absolutely required.
523
+     *
524
+     * If the card does not exist, you must return false.
525
+     *
526
+     * @param mixed $addressBookId
527
+     * @param string $cardUri
528
+     * @return array
529
+     */
530
+    function getCard($addressBookId, $cardUri) {
531
+        $query = $this->db->getQueryBuilder();
532
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata', 'uid'])
533
+            ->from('cards')
534
+            ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
535
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
536
+            ->setMaxResults(1);
537
+
538
+        $result = $query->execute();
539
+        $row = $result->fetch();
540
+        if (!$row) {
541
+            return false;
542
+        }
543
+        $row['etag'] = '"' . $row['etag'] . '"';
544
+        $row['carddata'] = $this->readBlob($row['carddata']);
545
+
546
+        return $row;
547
+    }
548
+
549
+    /**
550
+     * Returns a list of cards.
551
+     *
552
+     * This method should work identical to getCard, but instead return all the
553
+     * cards in the list as an array.
554
+     *
555
+     * If the backend supports this, it may allow for some speed-ups.
556
+     *
557
+     * @param mixed $addressBookId
558
+     * @param string[] $uris
559
+     * @return array
560
+     */
561
+    function getMultipleCards($addressBookId, array $uris) {
562
+        if (empty($uris)) {
563
+            return [];
564
+        }
565
+
566
+        $chunks = array_chunk($uris, 100);
567
+        $cards = [];
568
+
569
+        $query = $this->db->getQueryBuilder();
570
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata', 'uid'])
571
+            ->from('cards')
572
+            ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
573
+            ->andWhere($query->expr()->in('uri', $query->createParameter('uri')));
574
+
575
+        foreach ($chunks as $uris) {
576
+            $query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
577
+            $result = $query->execute();
578
+
579
+            while ($row = $result->fetch()) {
580
+                $row['etag'] = '"' . $row['etag'] . '"';
581
+                $row['carddata'] = $this->readBlob($row['carddata']);
582
+                $cards[] = $row;
583
+            }
584
+            $result->closeCursor();
585
+        }
586
+        return $cards;
587
+    }
588
+
589
+    /**
590
+     * Creates a new card.
591
+     *
592
+     * The addressbook id will be passed as the first argument. This is the
593
+     * same id as it is returned from the getAddressBooksForUser method.
594
+     *
595
+     * The cardUri is a base uri, and doesn't include the full path. The
596
+     * cardData argument is the vcard body, and is passed as a string.
597
+     *
598
+     * It is possible to return an ETag from this method. This ETag is for the
599
+     * newly created resource, and must be enclosed with double quotes (that
600
+     * is, the string itself must contain the double quotes).
601
+     *
602
+     * You should only return the ETag if you store the carddata as-is. If a
603
+     * subsequent GET request on the same card does not have the same body,
604
+     * byte-by-byte and you did return an ETag here, clients tend to get
605
+     * confused.
606
+     *
607
+     * If you don't return an ETag, you can just return null.
608
+     *
609
+     * @param mixed $addressBookId
610
+     * @param string $cardUri
611
+     * @param string $cardData
612
+     * @return string
613
+     */
614
+    function createCard($addressBookId, $cardUri, $cardData) {
615
+        $etag = md5($cardData);
616
+        $uid = $this->getUID($cardData);
617
+
618
+        $q = $this->db->getQueryBuilder();
619
+        $q->select('uid')
620
+            ->from('cards')
621
+            ->where($q->expr()->eq('addressbookid', $q->createNamedParameter($addressBookId)))
622
+            ->andWhere($q->expr()->eq('uid', $q->createNamedParameter($uid)))
623
+            ->setMaxResults(1);
624
+        $result = $q->execute();
625
+        $count = (bool) $result->fetchColumn();
626
+        $result->closeCursor();
627
+        if ($count) {
628
+            throw new \Sabre\DAV\Exception\BadRequest('VCard object with uid already exists in this addressbook collection.');
629
+        }
630
+
631
+        $query = $this->db->getQueryBuilder();
632
+        $query->insert('cards')
633
+            ->values([
634
+                'carddata' => $query->createNamedParameter($cardData, IQueryBuilder::PARAM_LOB),
635
+                'uri' => $query->createNamedParameter($cardUri),
636
+                'lastmodified' => $query->createNamedParameter(time()),
637
+                'addressbookid' => $query->createNamedParameter($addressBookId),
638
+                'size' => $query->createNamedParameter(strlen($cardData)),
639
+                'etag' => $query->createNamedParameter($etag),
640
+                'uid' => $query->createNamedParameter($uid),
641
+            ])
642
+            ->execute();
643
+
644
+        $this->addChange($addressBookId, $cardUri, 1);
645
+        $this->updateProperties($addressBookId, $cardUri, $cardData);
646
+
647
+        $this->dispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::createCard',
648
+            new GenericEvent(null, [
649
+                'addressBookId' => $addressBookId,
650
+                'cardUri' => $cardUri,
651
+                'cardData' => $cardData]));
652
+
653
+        return '"' . $etag . '"';
654
+    }
655
+
656
+    /**
657
+     * Updates a card.
658
+     *
659
+     * The addressbook id will be passed as the first argument. This is the
660
+     * same id as it is returned from the getAddressBooksForUser method.
661
+     *
662
+     * The cardUri is a base uri, and doesn't include the full path. The
663
+     * cardData argument is the vcard body, and is passed as a string.
664
+     *
665
+     * It is possible to return an ETag from this method. This ETag should
666
+     * match that of the updated resource, and must be enclosed with double
667
+     * quotes (that is: the string itself must contain the actual quotes).
668
+     *
669
+     * You should only return the ETag if you store the carddata as-is. If a
670
+     * subsequent GET request on the same card does not have the same body,
671
+     * byte-by-byte and you did return an ETag here, clients tend to get
672
+     * confused.
673
+     *
674
+     * If you don't return an ETag, you can just return null.
675
+     *
676
+     * @param mixed $addressBookId
677
+     * @param string $cardUri
678
+     * @param string $cardData
679
+     * @return string
680
+     */
681
+    function updateCard($addressBookId, $cardUri, $cardData) {
682
+
683
+        $uid = $this->getUID($cardData);
684
+        $etag = md5($cardData);
685
+        $query = $this->db->getQueryBuilder();
686
+        $query->update('cards')
687
+            ->set('carddata', $query->createNamedParameter($cardData, IQueryBuilder::PARAM_LOB))
688
+            ->set('lastmodified', $query->createNamedParameter(time()))
689
+            ->set('size', $query->createNamedParameter(strlen($cardData)))
690
+            ->set('etag', $query->createNamedParameter($etag))
691
+            ->set('uid', $query->createNamedParameter($uid))
692
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
693
+            ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
694
+            ->execute();
695
+
696
+        $this->addChange($addressBookId, $cardUri, 2);
697
+        $this->updateProperties($addressBookId, $cardUri, $cardData);
698
+
699
+        $this->dispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::updateCard',
700
+            new GenericEvent(null, [
701
+                'addressBookId' => $addressBookId,
702
+                'cardUri' => $cardUri,
703
+                'cardData' => $cardData]));
704
+
705
+        return '"' . $etag . '"';
706
+    }
707
+
708
+    /**
709
+     * Deletes a card
710
+     *
711
+     * @param mixed $addressBookId
712
+     * @param string $cardUri
713
+     * @return bool
714
+     */
715
+    function deleteCard($addressBookId, $cardUri) {
716
+        try {
717
+            $cardId = $this->getCardId($addressBookId, $cardUri);
718
+        } catch (\InvalidArgumentException $e) {
719
+            $cardId = null;
720
+        }
721
+        $query = $this->db->getQueryBuilder();
722
+        $ret = $query->delete('cards')
723
+            ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
724
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
725
+            ->execute();
726
+
727
+        $this->addChange($addressBookId, $cardUri, 3);
728
+
729
+        $this->dispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::deleteCard',
730
+            new GenericEvent(null, [
731
+                'addressBookId' => $addressBookId,
732
+                'cardUri' => $cardUri]));
733
+
734
+        if ($ret === 1) {
735
+            if ($cardId !== null) {
736
+                $this->purgeProperties($addressBookId, $cardId);
737
+            }
738
+            return true;
739
+        }
740
+
741
+        return false;
742
+    }
743
+
744
+    /**
745
+     * The getChanges method returns all the changes that have happened, since
746
+     * the specified syncToken in the specified address book.
747
+     *
748
+     * This function should return an array, such as the following:
749
+     *
750
+     * [
751
+     *   'syncToken' => 'The current synctoken',
752
+     *   'added'   => [
753
+     *      'new.txt',
754
+     *   ],
755
+     *   'modified'   => [
756
+     *      'modified.txt',
757
+     *   ],
758
+     *   'deleted' => [
759
+     *      'foo.php.bak',
760
+     *      'old.txt'
761
+     *   ]
762
+     * ];
763
+     *
764
+     * The returned syncToken property should reflect the *current* syncToken
765
+     * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
766
+     * property. This is needed here too, to ensure the operation is atomic.
767
+     *
768
+     * If the $syncToken argument is specified as null, this is an initial
769
+     * sync, and all members should be reported.
770
+     *
771
+     * The modified property is an array of nodenames that have changed since
772
+     * the last token.
773
+     *
774
+     * The deleted property is an array with nodenames, that have been deleted
775
+     * from collection.
776
+     *
777
+     * The $syncLevel argument is basically the 'depth' of the report. If it's
778
+     * 1, you only have to report changes that happened only directly in
779
+     * immediate descendants. If it's 2, it should also include changes from
780
+     * the nodes below the child collections. (grandchildren)
781
+     *
782
+     * The $limit argument allows a client to specify how many results should
783
+     * be returned at most. If the limit is not specified, it should be treated
784
+     * as infinite.
785
+     *
786
+     * If the limit (infinite or not) is higher than you're willing to return,
787
+     * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
788
+     *
789
+     * If the syncToken is expired (due to data cleanup) or unknown, you must
790
+     * return null.
791
+     *
792
+     * The limit is 'suggestive'. You are free to ignore it.
793
+     *
794
+     * @param string $addressBookId
795
+     * @param string $syncToken
796
+     * @param int $syncLevel
797
+     * @param int $limit
798
+     * @return array
799
+     */
800
+    function getChangesForAddressBook($addressBookId, $syncToken, $syncLevel, $limit = null) {
801
+        // Current synctoken
802
+        $stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*addressbooks` WHERE `id` = ?');
803
+        $stmt->execute([ $addressBookId ]);
804
+        $currentToken = $stmt->fetchColumn(0);
805
+
806
+        if (is_null($currentToken)) return null;
807
+
808
+        $result = [
809
+            'syncToken' => $currentToken,
810
+            'added'     => [],
811
+            'modified'  => [],
812
+            'deleted'   => [],
813
+        ];
814
+
815
+        if ($syncToken) {
816
+
817
+            $query = "SELECT `uri`, `operation` FROM `*PREFIX*addressbookchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `addressbookid` = ? ORDER BY `synctoken`";
818
+            if ($limit>0) {
819
+                $query .= " LIMIT " . (int)$limit;
820
+            }
821
+
822
+            // Fetching all changes
823
+            $stmt = $this->db->prepare($query);
824
+            $stmt->execute([$syncToken, $currentToken, $addressBookId]);
825
+
826
+            $changes = [];
827
+
828
+            // This loop ensures that any duplicates are overwritten, only the
829
+            // last change on a node is relevant.
830
+            while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
831
+
832
+                $changes[$row['uri']] = $row['operation'];
833
+
834
+            }
835
+
836
+            foreach($changes as $uri => $operation) {
837
+
838
+                switch($operation) {
839
+                    case 1:
840
+                        $result['added'][] = $uri;
841
+                        break;
842
+                    case 2:
843
+                        $result['modified'][] = $uri;
844
+                        break;
845
+                    case 3:
846
+                        $result['deleted'][] = $uri;
847
+                        break;
848
+                }
849
+
850
+            }
851
+        } else {
852
+            // No synctoken supplied, this is the initial sync.
853
+            $query = "SELECT `uri` FROM `*PREFIX*cards` WHERE `addressbookid` = ?";
854
+            $stmt = $this->db->prepare($query);
855
+            $stmt->execute([$addressBookId]);
856
+
857
+            $result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
858
+        }
859
+        return $result;
860
+    }
861
+
862
+    /**
863
+     * Adds a change record to the addressbookchanges table.
864
+     *
865
+     * @param mixed $addressBookId
866
+     * @param string $objectUri
867
+     * @param int $operation 1 = add, 2 = modify, 3 = delete
868
+     * @return void
869
+     */
870
+    protected function addChange($addressBookId, $objectUri, $operation) {
871
+        $sql = 'INSERT INTO `*PREFIX*addressbookchanges`(`uri`, `synctoken`, `addressbookid`, `operation`) SELECT ?, `synctoken`, ?, ? FROM `*PREFIX*addressbooks` WHERE `id` = ?';
872
+        $stmt = $this->db->prepare($sql);
873
+        $stmt->execute([
874
+            $objectUri,
875
+            $addressBookId,
876
+            $operation,
877
+            $addressBookId
878
+        ]);
879
+        $stmt = $this->db->prepare('UPDATE `*PREFIX*addressbooks` SET `synctoken` = `synctoken` + 1 WHERE `id` = ?');
880
+        $stmt->execute([
881
+            $addressBookId
882
+        ]);
883
+    }
884
+
885
+    private function readBlob($cardData) {
886
+        if (is_resource($cardData)) {
887
+            return stream_get_contents($cardData);
888
+        }
889
+
890
+        return $cardData;
891
+    }
892
+
893
+    /**
894
+     * @param IShareable $shareable
895
+     * @param string[] $add
896
+     * @param string[] $remove
897
+     */
898
+    public function updateShares(IShareable $shareable, $add, $remove) {
899
+        $this->sharingBackend->updateShares($shareable, $add, $remove);
900
+    }
901
+
902
+    /**
903
+     * search contact
904
+     *
905
+     * @param int $addressBookId
906
+     * @param string $pattern which should match within the $searchProperties
907
+     * @param array $searchProperties defines the properties within the query pattern should match
908
+     * @param array $options = array() to define the search behavior
909
+     * 	- 'escape_like_param' - If set to false wildcards _ and % are not escaped, otherwise they are
910
+     * @return array an array of contacts which are arrays of key-value-pairs
911
+     */
912
+    public function search($addressBookId, $pattern, $searchProperties, $options = []) {
913
+        $query = $this->db->getQueryBuilder();
914
+        $query2 = $this->db->getQueryBuilder();
915
+
916
+        $query2->selectDistinct('cp.cardid')->from($this->dbCardsPropertiesTable, 'cp');
917
+        $query2->andWhere($query2->expr()->eq('cp.addressbookid', $query->createNamedParameter($addressBookId)));
918
+        $or = $query2->expr()->orX();
919
+        foreach ($searchProperties as $property) {
920
+            $or->add($query2->expr()->eq('cp.name', $query->createNamedParameter($property)));
921
+        }
922
+        $query2->andWhere($or);
923
+
924
+        // No need for like when the pattern is empty
925
+        if ('' !== $pattern) {
926
+            if(\array_key_exists('escape_like_param', $options) && $options['escape_like_param'] === false) {
927
+                $query2->andWhere($query2->expr()->ilike('cp.value', $query->createNamedParameter($pattern)));
928
+            } else {
929
+                $query2->andWhere($query2->expr()->ilike('cp.value', $query->createNamedParameter('%' . $this->db->escapeLikeParameter($pattern) . '%')));
930
+            }
931
+        }
932
+
933
+        $query->select('c.carddata', 'c.uri')->from($this->dbCardsTable, 'c')
934
+            ->where($query->expr()->in('c.id', $query->createFunction($query2->getSQL())));
935
+
936
+        $result = $query->execute();
937
+        $cards = $result->fetchAll();
938
+
939
+        $result->closeCursor();
940
+
941
+        return array_map(function($array) {
942
+            $array['carddata'] = $this->readBlob($array['carddata']);
943
+            return $array;
944
+        }, $cards);
945
+    }
946
+
947
+    /**
948
+     * @param int $bookId
949
+     * @param string $name
950
+     * @return array
951
+     */
952
+    public function collectCardProperties($bookId, $name) {
953
+        $query = $this->db->getQueryBuilder();
954
+        $result = $query->selectDistinct('value')
955
+            ->from($this->dbCardsPropertiesTable)
956
+            ->where($query->expr()->eq('name', $query->createNamedParameter($name)))
957
+            ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($bookId)))
958
+            ->execute();
959
+
960
+        $all = $result->fetchAll(PDO::FETCH_COLUMN);
961
+        $result->closeCursor();
962
+
963
+        return $all;
964
+    }
965
+
966
+    /**
967
+     * get URI from a given contact
968
+     *
969
+     * @param int $id
970
+     * @return string
971
+     */
972
+    public function getCardUri($id) {
973
+        $query = $this->db->getQueryBuilder();
974
+        $query->select('uri')->from($this->dbCardsTable)
975
+                ->where($query->expr()->eq('id', $query->createParameter('id')))
976
+                ->setParameter('id', $id);
977
+
978
+        $result = $query->execute();
979
+        $uri = $result->fetch();
980
+        $result->closeCursor();
981
+
982
+        if (!isset($uri['uri'])) {
983
+            throw new \InvalidArgumentException('Card does not exists: ' . $id);
984
+        }
985
+
986
+        return $uri['uri'];
987
+    }
988
+
989
+    /**
990
+     * return contact with the given URI
991
+     *
992
+     * @param int $addressBookId
993
+     * @param string $uri
994
+     * @returns array
995
+     */
996
+    public function getContact($addressBookId, $uri) {
997
+        $result = [];
998
+        $query = $this->db->getQueryBuilder();
999
+        $query->select('*')->from($this->dbCardsTable)
1000
+                ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
1001
+                ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
1002
+        $queryResult = $query->execute();
1003
+        $contact = $queryResult->fetch();
1004
+        $queryResult->closeCursor();
1005
+
1006
+        if (is_array($contact)) {
1007
+            $result = $contact;
1008
+        }
1009
+
1010
+        return $result;
1011
+    }
1012
+
1013
+    /**
1014
+     * Returns the list of people whom this address book is shared with.
1015
+     *
1016
+     * Every element in this array should have the following properties:
1017
+     *   * href - Often a mailto: address
1018
+     *   * commonName - Optional, for example a first + last name
1019
+     *   * status - See the Sabre\CalDAV\SharingPlugin::STATUS_ constants.
1020
+     *   * readOnly - boolean
1021
+     *   * summary - Optional, a description for the share
1022
+     *
1023
+     * @return array
1024
+     */
1025
+    public function getShares($addressBookId) {
1026
+        return $this->sharingBackend->getShares($addressBookId);
1027
+    }
1028
+
1029
+    /**
1030
+     * update properties table
1031
+     *
1032
+     * @param int $addressBookId
1033
+     * @param string $cardUri
1034
+     * @param string $vCardSerialized
1035
+     */
1036
+    protected function updateProperties($addressBookId, $cardUri, $vCardSerialized) {
1037
+        $cardId = $this->getCardId($addressBookId, $cardUri);
1038
+        $vCard = $this->readCard($vCardSerialized);
1039
+
1040
+        $this->purgeProperties($addressBookId, $cardId);
1041
+
1042
+        $query = $this->db->getQueryBuilder();
1043
+        $query->insert($this->dbCardsPropertiesTable)
1044
+            ->values(
1045
+                [
1046
+                    'addressbookid' => $query->createNamedParameter($addressBookId),
1047
+                    'cardid' => $query->createNamedParameter($cardId),
1048
+                    'name' => $query->createParameter('name'),
1049
+                    'value' => $query->createParameter('value'),
1050
+                    'preferred' => $query->createParameter('preferred')
1051
+                ]
1052
+            );
1053
+
1054
+        foreach ($vCard->children() as $property) {
1055
+            if(!in_array($property->name, self::$indexProperties)) {
1056
+                continue;
1057
+            }
1058
+            $preferred = 0;
1059
+            foreach($property->parameters as $parameter) {
1060
+                if ($parameter->name === 'TYPE' && strtoupper($parameter->getValue()) === 'PREF') {
1061
+                    $preferred = 1;
1062
+                    break;
1063
+                }
1064
+            }
1065
+            $query->setParameter('name', $property->name);
1066
+            $query->setParameter('value', mb_substr($property->getValue(), 0, 254));
1067
+            $query->setParameter('preferred', $preferred);
1068
+            $query->execute();
1069
+        }
1070
+    }
1071
+
1072
+    /**
1073
+     * read vCard data into a vCard object
1074
+     *
1075
+     * @param string $cardData
1076
+     * @return VCard
1077
+     */
1078
+    protected function readCard($cardData) {
1079
+        return  Reader::read($cardData);
1080
+    }
1081
+
1082
+    /**
1083
+     * delete all properties from a given card
1084
+     *
1085
+     * @param int $addressBookId
1086
+     * @param int $cardId
1087
+     */
1088
+    protected function purgeProperties($addressBookId, $cardId) {
1089
+        $query = $this->db->getQueryBuilder();
1090
+        $query->delete($this->dbCardsPropertiesTable)
1091
+            ->where($query->expr()->eq('cardid', $query->createNamedParameter($cardId)))
1092
+            ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
1093
+        $query->execute();
1094
+    }
1095
+
1096
+    /**
1097
+     * get ID from a given contact
1098
+     *
1099
+     * @param int $addressBookId
1100
+     * @param string $uri
1101
+     * @return int
1102
+     */
1103
+    protected function getCardId($addressBookId, $uri) {
1104
+        $query = $this->db->getQueryBuilder();
1105
+        $query->select('id')->from($this->dbCardsTable)
1106
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
1107
+            ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
1108
+
1109
+        $result = $query->execute();
1110
+        $cardIds = $result->fetch();
1111
+        $result->closeCursor();
1112
+
1113
+        if (!isset($cardIds['id'])) {
1114
+            throw new \InvalidArgumentException('Card does not exists: ' . $uri);
1115
+        }
1116
+
1117
+        return (int)$cardIds['id'];
1118
+    }
1119
+
1120
+    /**
1121
+     * For shared address books the sharee is set in the ACL of the address book
1122
+     * @param $addressBookId
1123
+     * @param $acl
1124
+     * @return array
1125
+     */
1126
+    public function applyShareAcl($addressBookId, $acl) {
1127
+        return $this->sharingBackend->applyShareAcl($addressBookId, $acl);
1128
+    }
1129
+
1130
+    private function convertPrincipal($principalUri, $toV2) {
1131
+        if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
1132
+            list(, $name) = \Sabre\Uri\split($principalUri);
1133
+            if ($toV2 === true) {
1134
+                return "principals/users/$name";
1135
+            }
1136
+            return "principals/$name";
1137
+        }
1138
+        return $principalUri;
1139
+    }
1140
+
1141
+    private function addOwnerPrincipal(&$addressbookInfo) {
1142
+        $ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
1143
+        $displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
1144
+        if (isset($addressbookInfo[$ownerPrincipalKey])) {
1145
+            $uri = $addressbookInfo[$ownerPrincipalKey];
1146
+        } else {
1147
+            $uri = $addressbookInfo['principaluri'];
1148
+        }
1149
+
1150
+        $principalInformation = $this->principalBackend->getPrincipalByPath($uri);
1151
+        if (isset($principalInformation['{DAV:}displayname'])) {
1152
+            $addressbookInfo[$displaynameKey] = $principalInformation['{DAV:}displayname'];
1153
+        }
1154
+    }
1155
+
1156
+    /**
1157
+     * Extract UID from vcard
1158
+     *
1159
+     * @param string $cardData the vcard raw data
1160
+     * @return string the uid
1161
+     * @throws BadRequest if no UID is available
1162
+     */
1163
+    private function getUID($cardData) {
1164
+        if ($cardData != '') {
1165
+            $vCard = Reader::read($cardData);
1166
+            if ($vCard->UID) {
1167
+                $uid = $vCard->UID->getValue();
1168
+                return $uid;
1169
+            }
1170
+            // should already be handled, but just in case
1171
+            throw new BadRequest('vCards on CardDAV servers MUST have a UID property');
1172
+        }
1173
+        // should already be handled, but just in case
1174
+        throw new BadRequest('vCard can not be empty');
1175
+    }
1176 1176
 }
Please login to merge, or discard this patch.
apps/theming/appinfo/routes.php 1 patch
Indentation   +54 added lines, -54 removed lines patch added patch discarded remove patch
@@ -28,59 +28,59 @@
 block discarded – undo
28 28
  */
29 29
 
30 30
 return ['routes' => [
31
-	[
32
-		'name' => 'Theming#updateStylesheet',
33
-		'url' => '/ajax/updateStylesheet',
34
-		'verb' => 'POST'
35
-	],
36
-	[
37
-		'name' => 'Theming#undo',
38
-		'url' => '/ajax/undoChanges',
39
-		'verb' => 'POST'
40
-	],
41
-	[
42
-		'name' => 'Theming#uploadImage',
43
-		'url' => '/ajax/uploadImage',
44
-		'verb' => 'POST'
45
-	],
46
-	[
47
-		'name' => 'Theming#getStylesheet',
48
-		'url' => '/styles',
49
-		'verb' => 'GET',
50
-	],
51
-	[
52
-		'name' => 'Theming#getImage',
53
-		'url' => '/image/{key}',
54
-		'verb' => 'GET',
55
-	],
56
-	[
57
-		'name' => 'Theming#getJavascript',
58
-		'url' => '/js/theming',
59
-		'verb' => 'GET',
60
-	],
61
-	[
62
-		'name' => 'Theming#getManifest',
63
-		'url' => '/manifest/{app}',
64
-		'verb' => 'GET',
65
-		'defaults' => ['app' => 'core']
66
-	],
67
-	[
68
-		'name'	=> 'Icon#getFavicon',
69
-		'url' => '/favicon/{app}',
70
-		'verb' => 'GET',
71
-		'defaults' => ['app' => 'core'],
72
-	],
73
-	[
74
-		'name'	=> 'Icon#getTouchIcon',
75
-		'url' => '/icon/{app}',
76
-		'verb' => 'GET',
77
-		'defaults' => ['app' => 'core'],
78
-	],
79
-	[
80
-		'name'	=> 'Icon#getThemedIcon',
81
-		'url' => '/img/{app}/{image}',
82
-		'verb' => 'GET',
83
-		'requirements' => ['image' => '.+']
84
-	],
31
+    [
32
+        'name' => 'Theming#updateStylesheet',
33
+        'url' => '/ajax/updateStylesheet',
34
+        'verb' => 'POST'
35
+    ],
36
+    [
37
+        'name' => 'Theming#undo',
38
+        'url' => '/ajax/undoChanges',
39
+        'verb' => 'POST'
40
+    ],
41
+    [
42
+        'name' => 'Theming#uploadImage',
43
+        'url' => '/ajax/uploadImage',
44
+        'verb' => 'POST'
45
+    ],
46
+    [
47
+        'name' => 'Theming#getStylesheet',
48
+        'url' => '/styles',
49
+        'verb' => 'GET',
50
+    ],
51
+    [
52
+        'name' => 'Theming#getImage',
53
+        'url' => '/image/{key}',
54
+        'verb' => 'GET',
55
+    ],
56
+    [
57
+        'name' => 'Theming#getJavascript',
58
+        'url' => '/js/theming',
59
+        'verb' => 'GET',
60
+    ],
61
+    [
62
+        'name' => 'Theming#getManifest',
63
+        'url' => '/manifest/{app}',
64
+        'verb' => 'GET',
65
+        'defaults' => ['app' => 'core']
66
+    ],
67
+    [
68
+        'name'	=> 'Icon#getFavicon',
69
+        'url' => '/favicon/{app}',
70
+        'verb' => 'GET',
71
+        'defaults' => ['app' => 'core'],
72
+    ],
73
+    [
74
+        'name'	=> 'Icon#getTouchIcon',
75
+        'url' => '/icon/{app}',
76
+        'verb' => 'GET',
77
+        'defaults' => ['app' => 'core'],
78
+    ],
79
+    [
80
+        'name'	=> 'Icon#getThemedIcon',
81
+        'url' => '/img/{app}/{image}',
82
+        'verb' => 'GET',
83
+        'requirements' => ['image' => '.+']
84
+    ],
85 85
 ]];
86 86
 
Please login to merge, or discard this patch.
apps/theming/lib/Util.php 2 patches
Indentation   +210 added lines, -210 removed lines patch added patch discarded remove patch
@@ -38,215 +38,215 @@
 block discarded – undo
38 38
 
39 39
 class Util {
40 40
 
41
-	/** @var IConfig */
42
-	private $config;
43
-
44
-	/** @var IAppManager */
45
-	private $appManager;
46
-
47
-	/** @var IAppData */
48
-	private $appData;
49
-
50
-	/**
51
-	 * Util constructor.
52
-	 *
53
-	 * @param IConfig $config
54
-	 * @param IAppManager $appManager
55
-	 * @param IAppData $appData
56
-	 */
57
-	public function __construct(IConfig $config, IAppManager $appManager, IAppData $appData) {
58
-		$this->config = $config;
59
-		$this->appManager = $appManager;
60
-		$this->appData = $appData;
61
-	}
62
-
63
-	/**
64
-	 * @param string $color rgb color value
65
-	 * @return bool
66
-	 */
67
-	public function invertTextColor($color) {
68
-		$l = $this->calculateLuma($color);
69
-		if($l>0.6) {
70
-			return true;
71
-		} else {
72
-			return false;
73
-		}
74
-	}
75
-
76
-	/**
77
-	 * get color for on-page elements:
78
-	 * theme color by default, grey if theme color is to bright
79
-	 * @param $color
80
-	 * @return string
81
-	 */
82
-	public function elementColor($color) {
83
-		$l = $this->calculateLuminance($color);
84
-		if($l>0.8) {
85
-			return '#aaaaaa';
86
-		}
87
-		return $color;
88
-	}
89
-
90
-	/**
91
-	 * @param string $color rgb color value
92
-	 * @return float
93
-	 */
94
-	public function calculateLuminance($color) {
95
-		list($red, $green, $blue) = $this->hexToRGB($color);
96
-		$compiler = new Compiler();
97
-		$hsl = $compiler->toHSL($red, $green, $blue);
98
-		return $hsl[3]/100;
99
-	}
100
-
101
-	/**
102
-	 * @param string $color rgb color value
103
-	 * @return float
104
-	 */
105
-	public function calculateLuma($color) {
106
-		list($red, $green, $blue) = $this->hexToRGB($color);
107
-		return (0.2126 * $red  + 0.7152 * $green + 0.0722 * $blue) / 255;
108
-	}
109
-
110
-	/**
111
-	 * @param string $color rgb color value
112
-	 * @return int[]
113
-	 */
114
-	public function hexToRGB($color) {
115
-		$hex = preg_replace("/[^0-9A-Fa-f]/", '', $color);
116
-		if (strlen($hex) === 3) {
117
-			$hex = $hex[0] . $hex[0] . $hex[1] . $hex[1] . $hex[2] . $hex[2];
118
-		}
119
-		if (strlen($hex) !== 6) {
120
-			return 0;
121
-		}
122
-		return [
123
-			hexdec(substr($hex, 0, 2)),
124
-			hexdec(substr($hex, 2, 2)),
125
-			hexdec(substr($hex, 4, 2))
126
-		];
127
-	}
128
-
129
-	/**
130
-	 * @param $color
131
-	 * @return string base64 encoded radio button svg
132
-	 */
133
-	public function generateRadioButton($color) {
134
-		$radioButtonIcon = '<svg xmlns="http://www.w3.org/2000/svg" height="16" width="16">' .
135
-			'<path d="M8 1a7 7 0 0 0-7 7 7 7 0 0 0 7 7 7 7 0 0 0 7-7 7 7 0 0 0-7-7zm0 1a6 6 0 0 1 6 6 6 6 0 0 1-6 6 6 6 0 0 1-6-6 6 6 0 0 1 6-6zm0 2a4 4 0 1 0 0 8 4 4 0 0 0 0-8z" fill="'.$color.'"/></svg>';
136
-		return base64_encode($radioButtonIcon);
137
-	}
138
-
139
-
140
-	/**
141
-	 * @param $app string app name
142
-	 * @return string|ISimpleFile path to app icon / file of logo
143
-	 */
144
-	public function getAppIcon($app) {
145
-		$app = str_replace(['\0', '/', '\\', '..'], '', $app);
146
-		try {
147
-			$appPath = $this->appManager->getAppPath($app);
148
-			$icon = $appPath . '/img/' . $app . '.svg';
149
-			if (file_exists($icon)) {
150
-				return $icon;
151
-			}
152
-			$icon = $appPath . '/img/app.svg';
153
-			if (file_exists($icon)) {
154
-				return $icon;
155
-			}
156
-		} catch (AppPathNotFoundException $e) {}
157
-
158
-		if ($this->config->getAppValue('theming', 'logoMime', '') !== '') {
159
-			$logoFile = null;
160
-			try {
161
-				$folder = $this->appData->getFolder('images');
162
-				if ($folder !== null) {
163
-					return $folder->getFile('logo');
164
-				}
165
-			} catch (NotFoundException $e) {}
166
-		}
167
-		return \OC::$SERVERROOT . '/core/img/logo/logo.svg';
168
-	}
169
-
170
-	/**
171
-	 * @param $app string app name
172
-	 * @param $image string relative path to image in app folder
173
-	 * @return string|false absolute path to image
174
-	 */
175
-	public function getAppImage($app, $image) {
176
-		$app = str_replace(['\0', '/', '\\', '..'], '', $app);
177
-		$image = str_replace(['\0', '\\', '..'], '', $image);
178
-		if ($app === "core") {
179
-			$icon = \OC::$SERVERROOT . '/core/img/' . $image;
180
-			if (file_exists($icon)) {
181
-				return $icon;
182
-			}
183
-		}
184
-
185
-		try {
186
-			$appPath = $this->appManager->getAppPath($app);
187
-		} catch (AppPathNotFoundException $e) {
188
-			return false;
189
-		}
190
-
191
-		$icon = $appPath . '/img/' . $image;
192
-		if (file_exists($icon)) {
193
-			return $icon;
194
-		}
195
-		$icon = $appPath . '/img/' . $image . '.svg';
196
-		if (file_exists($icon)) {
197
-			return $icon;
198
-		}
199
-		$icon = $appPath . '/img/' . $image . '.png';
200
-		if (file_exists($icon)) {
201
-			return $icon;
202
-		}
203
-		$icon = $appPath . '/img/' . $image . '.gif';
204
-		if (file_exists($icon)) {
205
-			return $icon;
206
-		}
207
-		$icon = $appPath . '/img/' . $image . '.jpg';
208
-		if (file_exists($icon)) {
209
-			return $icon;
210
-		}
211
-
212
-		return false;
213
-	}
214
-
215
-	/**
216
-	 * replace default color with a custom one
217
-	 *
218
-	 * @param $svg string content of a svg file
219
-	 * @param $color string color to match
220
-	 * @return string
221
-	 */
222
-	public function colorizeSvg($svg, $color) {
223
-		$svg = preg_replace('/#0082c9/i', $color, $svg);
224
-		return $svg;
225
-	}
226
-
227
-	/**
228
-	 * Check if a custom theme is set in the server configuration
229
-	 *
230
-	 * @return bool
231
-	 */
232
-	public function isAlreadyThemed() {
233
-		$theme = $this->config->getSystemValue('theme', '');
234
-		if ($theme !== '') {
235
-			return true;
236
-		}
237
-		return false;
238
-	}
239
-
240
-	public function isBackgroundThemed() {
241
-		$backgroundLogo = $this->config->getAppValue('theming', 'backgroundMime',false);
242
-
243
-		$backgroundExists = true;
244
-		try {
245
-			$this->appData->getFolder('images')->getFile('background');
246
-		} catch (\Exception $e) {
247
-			$backgroundExists = false;
248
-		}
249
-		return $backgroundLogo && $backgroundLogo !== 'backgroundColor' && $backgroundExists;
250
-	}
41
+    /** @var IConfig */
42
+    private $config;
43
+
44
+    /** @var IAppManager */
45
+    private $appManager;
46
+
47
+    /** @var IAppData */
48
+    private $appData;
49
+
50
+    /**
51
+     * Util constructor.
52
+     *
53
+     * @param IConfig $config
54
+     * @param IAppManager $appManager
55
+     * @param IAppData $appData
56
+     */
57
+    public function __construct(IConfig $config, IAppManager $appManager, IAppData $appData) {
58
+        $this->config = $config;
59
+        $this->appManager = $appManager;
60
+        $this->appData = $appData;
61
+    }
62
+
63
+    /**
64
+     * @param string $color rgb color value
65
+     * @return bool
66
+     */
67
+    public function invertTextColor($color) {
68
+        $l = $this->calculateLuma($color);
69
+        if($l>0.6) {
70
+            return true;
71
+        } else {
72
+            return false;
73
+        }
74
+    }
75
+
76
+    /**
77
+     * get color for on-page elements:
78
+     * theme color by default, grey if theme color is to bright
79
+     * @param $color
80
+     * @return string
81
+     */
82
+    public function elementColor($color) {
83
+        $l = $this->calculateLuminance($color);
84
+        if($l>0.8) {
85
+            return '#aaaaaa';
86
+        }
87
+        return $color;
88
+    }
89
+
90
+    /**
91
+     * @param string $color rgb color value
92
+     * @return float
93
+     */
94
+    public function calculateLuminance($color) {
95
+        list($red, $green, $blue) = $this->hexToRGB($color);
96
+        $compiler = new Compiler();
97
+        $hsl = $compiler->toHSL($red, $green, $blue);
98
+        return $hsl[3]/100;
99
+    }
100
+
101
+    /**
102
+     * @param string $color rgb color value
103
+     * @return float
104
+     */
105
+    public function calculateLuma($color) {
106
+        list($red, $green, $blue) = $this->hexToRGB($color);
107
+        return (0.2126 * $red  + 0.7152 * $green + 0.0722 * $blue) / 255;
108
+    }
109
+
110
+    /**
111
+     * @param string $color rgb color value
112
+     * @return int[]
113
+     */
114
+    public function hexToRGB($color) {
115
+        $hex = preg_replace("/[^0-9A-Fa-f]/", '', $color);
116
+        if (strlen($hex) === 3) {
117
+            $hex = $hex[0] . $hex[0] . $hex[1] . $hex[1] . $hex[2] . $hex[2];
118
+        }
119
+        if (strlen($hex) !== 6) {
120
+            return 0;
121
+        }
122
+        return [
123
+            hexdec(substr($hex, 0, 2)),
124
+            hexdec(substr($hex, 2, 2)),
125
+            hexdec(substr($hex, 4, 2))
126
+        ];
127
+    }
128
+
129
+    /**
130
+     * @param $color
131
+     * @return string base64 encoded radio button svg
132
+     */
133
+    public function generateRadioButton($color) {
134
+        $radioButtonIcon = '<svg xmlns="http://www.w3.org/2000/svg" height="16" width="16">' .
135
+            '<path d="M8 1a7 7 0 0 0-7 7 7 7 0 0 0 7 7 7 7 0 0 0 7-7 7 7 0 0 0-7-7zm0 1a6 6 0 0 1 6 6 6 6 0 0 1-6 6 6 6 0 0 1-6-6 6 6 0 0 1 6-6zm0 2a4 4 0 1 0 0 8 4 4 0 0 0 0-8z" fill="'.$color.'"/></svg>';
136
+        return base64_encode($radioButtonIcon);
137
+    }
138
+
139
+
140
+    /**
141
+     * @param $app string app name
142
+     * @return string|ISimpleFile path to app icon / file of logo
143
+     */
144
+    public function getAppIcon($app) {
145
+        $app = str_replace(['\0', '/', '\\', '..'], '', $app);
146
+        try {
147
+            $appPath = $this->appManager->getAppPath($app);
148
+            $icon = $appPath . '/img/' . $app . '.svg';
149
+            if (file_exists($icon)) {
150
+                return $icon;
151
+            }
152
+            $icon = $appPath . '/img/app.svg';
153
+            if (file_exists($icon)) {
154
+                return $icon;
155
+            }
156
+        } catch (AppPathNotFoundException $e) {}
157
+
158
+        if ($this->config->getAppValue('theming', 'logoMime', '') !== '') {
159
+            $logoFile = null;
160
+            try {
161
+                $folder = $this->appData->getFolder('images');
162
+                if ($folder !== null) {
163
+                    return $folder->getFile('logo');
164
+                }
165
+            } catch (NotFoundException $e) {}
166
+        }
167
+        return \OC::$SERVERROOT . '/core/img/logo/logo.svg';
168
+    }
169
+
170
+    /**
171
+     * @param $app string app name
172
+     * @param $image string relative path to image in app folder
173
+     * @return string|false absolute path to image
174
+     */
175
+    public function getAppImage($app, $image) {
176
+        $app = str_replace(['\0', '/', '\\', '..'], '', $app);
177
+        $image = str_replace(['\0', '\\', '..'], '', $image);
178
+        if ($app === "core") {
179
+            $icon = \OC::$SERVERROOT . '/core/img/' . $image;
180
+            if (file_exists($icon)) {
181
+                return $icon;
182
+            }
183
+        }
184
+
185
+        try {
186
+            $appPath = $this->appManager->getAppPath($app);
187
+        } catch (AppPathNotFoundException $e) {
188
+            return false;
189
+        }
190
+
191
+        $icon = $appPath . '/img/' . $image;
192
+        if (file_exists($icon)) {
193
+            return $icon;
194
+        }
195
+        $icon = $appPath . '/img/' . $image . '.svg';
196
+        if (file_exists($icon)) {
197
+            return $icon;
198
+        }
199
+        $icon = $appPath . '/img/' . $image . '.png';
200
+        if (file_exists($icon)) {
201
+            return $icon;
202
+        }
203
+        $icon = $appPath . '/img/' . $image . '.gif';
204
+        if (file_exists($icon)) {
205
+            return $icon;
206
+        }
207
+        $icon = $appPath . '/img/' . $image . '.jpg';
208
+        if (file_exists($icon)) {
209
+            return $icon;
210
+        }
211
+
212
+        return false;
213
+    }
214
+
215
+    /**
216
+     * replace default color with a custom one
217
+     *
218
+     * @param $svg string content of a svg file
219
+     * @param $color string color to match
220
+     * @return string
221
+     */
222
+    public function colorizeSvg($svg, $color) {
223
+        $svg = preg_replace('/#0082c9/i', $color, $svg);
224
+        return $svg;
225
+    }
226
+
227
+    /**
228
+     * Check if a custom theme is set in the server configuration
229
+     *
230
+     * @return bool
231
+     */
232
+    public function isAlreadyThemed() {
233
+        $theme = $this->config->getSystemValue('theme', '');
234
+        if ($theme !== '') {
235
+            return true;
236
+        }
237
+        return false;
238
+    }
239
+
240
+    public function isBackgroundThemed() {
241
+        $backgroundLogo = $this->config->getAppValue('theming', 'backgroundMime',false);
242
+
243
+        $backgroundExists = true;
244
+        try {
245
+            $this->appData->getFolder('images')->getFile('background');
246
+        } catch (\Exception $e) {
247
+            $backgroundExists = false;
248
+        }
249
+        return $backgroundLogo && $backgroundLogo !== 'backgroundColor' && $backgroundExists;
250
+    }
251 251
 
252 252
 }
Please login to merge, or discard this patch.
Spacing   +16 added lines, -16 removed lines patch added patch discarded remove patch
@@ -66,7 +66,7 @@  discard block
 block discarded – undo
66 66
 	 */
67 67
 	public function invertTextColor($color) {
68 68
 		$l = $this->calculateLuma($color);
69
-		if($l>0.6) {
69
+		if ($l > 0.6) {
70 70
 			return true;
71 71
 		} else {
72 72
 			return false;
@@ -81,7 +81,7 @@  discard block
 block discarded – undo
81 81
 	 */
82 82
 	public function elementColor($color) {
83 83
 		$l = $this->calculateLuminance($color);
84
-		if($l>0.8) {
84
+		if ($l > 0.8) {
85 85
 			return '#aaaaaa';
86 86
 		}
87 87
 		return $color;
@@ -95,7 +95,7 @@  discard block
 block discarded – undo
95 95
 		list($red, $green, $blue) = $this->hexToRGB($color);
96 96
 		$compiler = new Compiler();
97 97
 		$hsl = $compiler->toHSL($red, $green, $blue);
98
-		return $hsl[3]/100;
98
+		return $hsl[3] / 100;
99 99
 	}
100 100
 
101 101
 	/**
@@ -104,7 +104,7 @@  discard block
 block discarded – undo
104 104
 	 */
105 105
 	public function calculateLuma($color) {
106 106
 		list($red, $green, $blue) = $this->hexToRGB($color);
107
-		return (0.2126 * $red  + 0.7152 * $green + 0.0722 * $blue) / 255;
107
+		return (0.2126 * $red + 0.7152 * $green + 0.0722 * $blue) / 255;
108 108
 	}
109 109
 
110 110
 	/**
@@ -114,7 +114,7 @@  discard block
 block discarded – undo
114 114
 	public function hexToRGB($color) {
115 115
 		$hex = preg_replace("/[^0-9A-Fa-f]/", '', $color);
116 116
 		if (strlen($hex) === 3) {
117
-			$hex = $hex[0] . $hex[0] . $hex[1] . $hex[1] . $hex[2] . $hex[2];
117
+			$hex = $hex[0].$hex[0].$hex[1].$hex[1].$hex[2].$hex[2];
118 118
 		}
119 119
 		if (strlen($hex) !== 6) {
120 120
 			return 0;
@@ -131,7 +131,7 @@  discard block
 block discarded – undo
131 131
 	 * @return string base64 encoded radio button svg
132 132
 	 */
133 133
 	public function generateRadioButton($color) {
134
-		$radioButtonIcon = '<svg xmlns="http://www.w3.org/2000/svg" height="16" width="16">' .
134
+		$radioButtonIcon = '<svg xmlns="http://www.w3.org/2000/svg" height="16" width="16">'.
135 135
 			'<path d="M8 1a7 7 0 0 0-7 7 7 7 0 0 0 7 7 7 7 0 0 0 7-7 7 7 0 0 0-7-7zm0 1a6 6 0 0 1 6 6 6 6 0 0 1-6 6 6 6 0 0 1-6-6 6 6 0 0 1 6-6zm0 2a4 4 0 1 0 0 8 4 4 0 0 0 0-8z" fill="'.$color.'"/></svg>';
136 136
 		return base64_encode($radioButtonIcon);
137 137
 	}
@@ -145,11 +145,11 @@  discard block
 block discarded – undo
145 145
 		$app = str_replace(['\0', '/', '\\', '..'], '', $app);
146 146
 		try {
147 147
 			$appPath = $this->appManager->getAppPath($app);
148
-			$icon = $appPath . '/img/' . $app . '.svg';
148
+			$icon = $appPath.'/img/'.$app.'.svg';
149 149
 			if (file_exists($icon)) {
150 150
 				return $icon;
151 151
 			}
152
-			$icon = $appPath . '/img/app.svg';
152
+			$icon = $appPath.'/img/app.svg';
153 153
 			if (file_exists($icon)) {
154 154
 				return $icon;
155 155
 			}
@@ -164,7 +164,7 @@  discard block
 block discarded – undo
164 164
 				}
165 165
 			} catch (NotFoundException $e) {}
166 166
 		}
167
-		return \OC::$SERVERROOT . '/core/img/logo/logo.svg';
167
+		return \OC::$SERVERROOT.'/core/img/logo/logo.svg';
168 168
 	}
169 169
 
170 170
 	/**
@@ -176,7 +176,7 @@  discard block
 block discarded – undo
176 176
 		$app = str_replace(['\0', '/', '\\', '..'], '', $app);
177 177
 		$image = str_replace(['\0', '\\', '..'], '', $image);
178 178
 		if ($app === "core") {
179
-			$icon = \OC::$SERVERROOT . '/core/img/' . $image;
179
+			$icon = \OC::$SERVERROOT.'/core/img/'.$image;
180 180
 			if (file_exists($icon)) {
181 181
 				return $icon;
182 182
 			}
@@ -188,23 +188,23 @@  discard block
 block discarded – undo
188 188
 			return false;
189 189
 		}
190 190
 
191
-		$icon = $appPath . '/img/' . $image;
191
+		$icon = $appPath.'/img/'.$image;
192 192
 		if (file_exists($icon)) {
193 193
 			return $icon;
194 194
 		}
195
-		$icon = $appPath . '/img/' . $image . '.svg';
195
+		$icon = $appPath.'/img/'.$image.'.svg';
196 196
 		if (file_exists($icon)) {
197 197
 			return $icon;
198 198
 		}
199
-		$icon = $appPath . '/img/' . $image . '.png';
199
+		$icon = $appPath.'/img/'.$image.'.png';
200 200
 		if (file_exists($icon)) {
201 201
 			return $icon;
202 202
 		}
203
-		$icon = $appPath . '/img/' . $image . '.gif';
203
+		$icon = $appPath.'/img/'.$image.'.gif';
204 204
 		if (file_exists($icon)) {
205 205
 			return $icon;
206 206
 		}
207
-		$icon = $appPath . '/img/' . $image . '.jpg';
207
+		$icon = $appPath.'/img/'.$image.'.jpg';
208 208
 		if (file_exists($icon)) {
209 209
 			return $icon;
210 210
 		}
@@ -238,7 +238,7 @@  discard block
 block discarded – undo
238 238
 	}
239 239
 
240 240
 	public function isBackgroundThemed() {
241
-		$backgroundLogo = $this->config->getAppValue('theming', 'backgroundMime',false);
241
+		$backgroundLogo = $this->config->getAppValue('theming', 'backgroundMime', false);
242 242
 
243 243
 		$backgroundExists = true;
244 244
 		try {
Please login to merge, or discard this patch.
apps/encryption/templates/altmail.php 2 patches
Indentation   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -4,8 +4,8 @@
 block discarded – undo
4 4
 
5 5
 print_unescaped($l->t("Hey there,\n\nthe admin enabled server-side-encryption. Your files were encrypted using the password '%s'.\n\nPlease login to the web interface, go to the section 'basic encryption module' of your personal settings and update your encryption password by entering this password into the 'old log-in password' field and your current login-password.\n\n", [$_['password']]));
6 6
 if ( isset($_['expiration']) ) {
7
-	print_unescaped($l->t("The share will expire on %s.", [$_['expiration']]));
8
-	print_unescaped("\n\n");
7
+    print_unescaped($l->t("The share will expire on %s.", [$_['expiration']]));
8
+    print_unescaped("\n\n");
9 9
 }
10 10
 // TRANSLATORS term at the end of a mail
11 11
 p($l->t("Cheers!"));
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -3,7 +3,7 @@  discard block
 block discarded – undo
3 3
 /** @var array $_ */
4 4
 
5 5
 print_unescaped($l->t("Hey there,\n\nthe admin enabled server-side-encryption. Your files were encrypted using the password '%s'.\n\nPlease login to the web interface, go to the section 'basic encryption module' of your personal settings and update your encryption password by entering this password into the 'old log-in password' field and your current login-password.\n\n", [$_['password']]));
6
-if ( isset($_['expiration']) ) {
6
+if (isset($_['expiration'])) {
7 7
 	print_unescaped($l->t("The share will expire on %s.", [$_['expiration']]));
8 8
 	print_unescaped("\n\n");
9 9
 }
@@ -12,5 +12,5 @@  discard block
 block discarded – undo
12 12
 ?>
13 13
 
14 14
 	--
15
-<?php p($theme->getName() . ' - ' . $theme->getSlogan()); ?>
15
+<?php p($theme->getName().' - '.$theme->getSlogan()); ?>
16 16
 <?php print_unescaped("\n".$theme->getBaseUrl());
Please login to merge, or discard this patch.
apps/encryption/lib/Crypto/Encryption.php 1 patch
Indentation   +553 added lines, -553 removed lines patch added patch discarded remove patch
@@ -46,557 +46,557 @@
 block discarded – undo
46 46
 
47 47
 class Encryption implements IEncryptionModule {
48 48
 
49
-	const ID = 'OC_DEFAULT_MODULE';
50
-	const DISPLAY_NAME = 'Default encryption module';
51
-
52
-	/**
53
-	 * @var Crypt
54
-	 */
55
-	private $crypt;
56
-
57
-	/** @var string */
58
-	private $cipher;
59
-
60
-	/** @var string */
61
-	private $path;
62
-
63
-	/** @var string */
64
-	private $user;
65
-
66
-	/** @var  array */
67
-	private $owner;
68
-
69
-	/** @var string */
70
-	private $fileKey;
71
-
72
-	/** @var string */
73
-	private $writeCache;
74
-
75
-	/** @var KeyManager */
76
-	private $keyManager;
77
-
78
-	/** @var array */
79
-	private $accessList;
80
-
81
-	/** @var boolean */
82
-	private $isWriteOperation;
83
-
84
-	/** @var Util */
85
-	private $util;
86
-
87
-	/** @var  Session */
88
-	private $session;
89
-
90
-	/** @var  ILogger */
91
-	private $logger;
92
-
93
-	/** @var IL10N */
94
-	private $l;
95
-
96
-	/** @var EncryptAll */
97
-	private $encryptAll;
98
-
99
-	/** @var  bool */
100
-	private $useMasterPassword;
101
-
102
-	/** @var DecryptAll  */
103
-	private $decryptAll;
104
-
105
-	/** @var int unencrypted block size if block contains signature */
106
-	private $unencryptedBlockSizeSigned = 6072;
107
-
108
-	/** @var int unencrypted block size */
109
-	private $unencryptedBlockSize = 6126;
110
-
111
-	/** @var int Current version of the file */
112
-	private $version = 0;
113
-
114
-	/** @var array remember encryption signature version */
115
-	private static $rememberVersion = [];
116
-
117
-
118
-	/**
119
-	 *
120
-	 * @param Crypt $crypt
121
-	 * @param KeyManager $keyManager
122
-	 * @param Util $util
123
-	 * @param Session $session
124
-	 * @param EncryptAll $encryptAll
125
-	 * @param DecryptAll $decryptAll
126
-	 * @param ILogger $logger
127
-	 * @param IL10N $il10n
128
-	 */
129
-	public function __construct(Crypt $crypt,
130
-								KeyManager $keyManager,
131
-								Util $util,
132
-								Session $session,
133
-								EncryptAll $encryptAll,
134
-								DecryptAll $decryptAll,
135
-								ILogger $logger,
136
-								IL10N $il10n) {
137
-		$this->crypt = $crypt;
138
-		$this->keyManager = $keyManager;
139
-		$this->util = $util;
140
-		$this->session = $session;
141
-		$this->encryptAll = $encryptAll;
142
-		$this->decryptAll = $decryptAll;
143
-		$this->logger = $logger;
144
-		$this->l = $il10n;
145
-		$this->owner = [];
146
-		$this->useMasterPassword = $util->isMasterKeyEnabled();
147
-	}
148
-
149
-	/**
150
-	 * @return string defining the technical unique id
151
-	 */
152
-	public function getId() {
153
-		return self::ID;
154
-	}
155
-
156
-	/**
157
-	 * In comparison to getKey() this function returns a human readable (maybe translated) name
158
-	 *
159
-	 * @return string
160
-	 */
161
-	public function getDisplayName() {
162
-		return self::DISPLAY_NAME;
163
-	}
164
-
165
-	/**
166
-	 * start receiving chunks from a file. This is the place where you can
167
-	 * perform some initial step before starting encrypting/decrypting the
168
-	 * chunks
169
-	 *
170
-	 * @param string $path to the file
171
-	 * @param string $user who read/write the file
172
-	 * @param string $mode php stream open mode
173
-	 * @param array $header contains the header data read from the file
174
-	 * @param array $accessList who has access to the file contains the key 'users' and 'public'
175
-	 *
176
-	 * @return array $header contain data as key-value pairs which should be
177
-	 *                       written to the header, in case of a write operation
178
-	 *                       or if no additional data is needed return a empty array
179
-	 */
180
-	public function begin($path, $user, $mode, array $header, array $accessList) {
181
-		$this->path = $this->getPathToRealFile($path);
182
-		$this->accessList = $accessList;
183
-		$this->user = $user;
184
-		$this->isWriteOperation = false;
185
-		$this->writeCache = '';
186
-
187
-		if($this->session->isReady() === false) {
188
-			// if the master key is enabled we can initialize encryption
189
-			// with a empty password and user name
190
-			if ($this->util->isMasterKeyEnabled()) {
191
-				$this->keyManager->init('', '');
192
-			}
193
-		}
194
-
195
-		if ($this->session->decryptAllModeActivated()) {
196
-			$encryptedFileKey = $this->keyManager->getEncryptedFileKey($this->path);
197
-			$shareKey = $this->keyManager->getShareKey($this->path, $this->session->getDecryptAllUid());
198
-			$this->fileKey = $this->crypt->multiKeyDecrypt($encryptedFileKey,
199
-				$shareKey,
200
-				$this->session->getDecryptAllKey());
201
-		} else {
202
-			$this->fileKey = $this->keyManager->getFileKey($this->path, $this->user);
203
-		}
204
-
205
-		// always use the version from the original file, also part files
206
-		// need to have a correct version number if they get moved over to the
207
-		// final location
208
-		$this->version = (int)$this->keyManager->getVersion($this->stripPartFileExtension($path), new View());
209
-
210
-		if (
211
-			$mode === 'w'
212
-			|| $mode === 'w+'
213
-			|| $mode === 'wb'
214
-			|| $mode === 'wb+'
215
-		) {
216
-			$this->isWriteOperation = true;
217
-			if (empty($this->fileKey)) {
218
-				$this->fileKey = $this->crypt->generateFileKey();
219
-			}
220
-		} else {
221
-			// if we read a part file we need to increase the version by 1
222
-			// because the version number was also increased by writing
223
-			// the part file
224
-			if(Scanner::isPartialFile($path)) {
225
-				$this->version = $this->version + 1;
226
-			}
227
-		}
228
-
229
-		if ($this->isWriteOperation) {
230
-			$this->cipher = $this->crypt->getCipher();
231
-		} elseif (isset($header['cipher'])) {
232
-			$this->cipher = $header['cipher'];
233
-		} else {
234
-			// if we read a file without a header we fall-back to the legacy cipher
235
-			// which was used in <=oC6
236
-			$this->cipher = $this->crypt->getLegacyCipher();
237
-		}
238
-
239
-		return ['cipher' => $this->cipher, 'signed' => 'true'];
240
-	}
241
-
242
-	/**
243
-	 * last chunk received. This is the place where you can perform some final
244
-	 * operation and return some remaining data if something is left in your
245
-	 * buffer.
246
-	 *
247
-	 * @param string $path to the file
248
-	 * @param int $position
249
-	 * @return string remained data which should be written to the file in case
250
-	 *                of a write operation
251
-	 * @throws PublicKeyMissingException
252
-	 * @throws \Exception
253
-	 * @throws \OCA\Encryption\Exceptions\MultiKeyEncryptException
254
-	 */
255
-	public function end($path, $position = 0) {
256
-		$result = '';
257
-		if ($this->isWriteOperation) {
258
-			// in case of a part file we remember the new signature versions
259
-			// the version will be set later on update.
260
-			// This way we make sure that other apps listening to the pre-hooks
261
-			// still get the old version which should be the correct value for them
262
-			if (Scanner::isPartialFile($path)) {
263
-				self::$rememberVersion[$this->stripPartFileExtension($path)] = $this->version + 1;
264
-			}
265
-			if (!empty($this->writeCache)) {
266
-				$result = $this->crypt->symmetricEncryptFileContent($this->writeCache, $this->fileKey, $this->version + 1, $position);
267
-				$this->writeCache = '';
268
-			}
269
-			$publicKeys = [];
270
-			if ($this->useMasterPassword === true) {
271
-				$publicKeys[$this->keyManager->getMasterKeyId()] = $this->keyManager->getPublicMasterKey();
272
-			} else {
273
-				foreach ($this->accessList['users'] as $uid) {
274
-					try {
275
-						$publicKeys[$uid] = $this->keyManager->getPublicKey($uid);
276
-					} catch (PublicKeyMissingException $e) {
277
-						$this->logger->warning(
278
-							'no public key found for user "{uid}", user will not be able to read the file',
279
-							['app' => 'encryption', 'uid' => $uid]
280
-						);
281
-						// if the public key of the owner is missing we should fail
282
-						if ($uid === $this->user) {
283
-							throw $e;
284
-						}
285
-					}
286
-				}
287
-			}
288
-
289
-			$publicKeys = $this->keyManager->addSystemKeys($this->accessList, $publicKeys, $this->getOwner($path));
290
-			$encryptedKeyfiles = $this->crypt->multiKeyEncrypt($this->fileKey, $publicKeys);
291
-			$this->keyManager->setAllFileKeys($this->path, $encryptedKeyfiles);
292
-		}
293
-		return $result;
294
-	}
295
-
296
-
297
-
298
-	/**
299
-	 * encrypt data
300
-	 *
301
-	 * @param string $data you want to encrypt
302
-	 * @param int $position
303
-	 * @return string encrypted data
304
-	 */
305
-	public function encrypt($data, $position = 0) {
306
-		// If extra data is left over from the last round, make sure it
307
-		// is integrated into the next block
308
-		if ($this->writeCache) {
309
-
310
-			// Concat writeCache to start of $data
311
-			$data = $this->writeCache . $data;
312
-
313
-			// Clear the write cache, ready for reuse - it has been
314
-			// flushed and its old contents processed
315
-			$this->writeCache = '';
316
-
317
-		}
318
-
319
-		$encrypted = '';
320
-		// While there still remains some data to be processed & written
321
-		while (strlen($data) > 0) {
322
-
323
-			// Remaining length for this iteration, not of the
324
-			// entire file (may be greater than 8192 bytes)
325
-			$remainingLength = strlen($data);
326
-
327
-			// If data remaining to be written is less than the
328
-			// size of 1 6126 byte block
329
-			if ($remainingLength < $this->unencryptedBlockSizeSigned) {
330
-
331
-				// Set writeCache to contents of $data
332
-				// The writeCache will be carried over to the
333
-				// next write round, and added to the start of
334
-				// $data to ensure that written blocks are
335
-				// always the correct length. If there is still
336
-				// data in writeCache after the writing round
337
-				// has finished, then the data will be written
338
-				// to disk by $this->flush().
339
-				$this->writeCache = $data;
340
-
341
-				// Clear $data ready for next round
342
-				$data = '';
343
-
344
-			} else {
345
-
346
-				// Read the chunk from the start of $data
347
-				$chunk = substr($data, 0, $this->unencryptedBlockSizeSigned);
348
-
349
-				$encrypted .= $this->crypt->symmetricEncryptFileContent($chunk, $this->fileKey, $this->version + 1, $position);
350
-
351
-				// Remove the chunk we just processed from
352
-				// $data, leaving only unprocessed data in $data
353
-				// var, for handling on the next round
354
-				$data = substr($data, $this->unencryptedBlockSizeSigned);
355
-
356
-			}
357
-
358
-		}
359
-
360
-		return $encrypted;
361
-	}
362
-
363
-	/**
364
-	 * decrypt data
365
-	 *
366
-	 * @param string $data you want to decrypt
367
-	 * @param int $position
368
-	 * @return string decrypted data
369
-	 * @throws DecryptionFailedException
370
-	 */
371
-	public function decrypt($data, $position = 0) {
372
-		if (empty($this->fileKey)) {
373
-			$msg = 'Can not decrypt this file, probably this is a shared file. Please ask the file owner to reshare the file with you.';
374
-			$hint = $this->l->t('Can not decrypt this file, probably this is a shared file. Please ask the file owner to reshare the file with you.');
375
-			$this->logger->error($msg);
376
-
377
-			throw new DecryptionFailedException($msg, $hint);
378
-		}
379
-
380
-		return $this->crypt->symmetricDecryptFileContent($data, $this->fileKey, $this->cipher, $this->version, $position);
381
-	}
382
-
383
-	/**
384
-	 * update encrypted file, e.g. give additional users access to the file
385
-	 *
386
-	 * @param string $path path to the file which should be updated
387
-	 * @param string $uid of the user who performs the operation
388
-	 * @param array $accessList who has access to the file contains the key 'users' and 'public'
389
-	 * @return boolean
390
-	 */
391
-	public function update($path, $uid, array $accessList) {
392
-
393
-		if (empty($accessList)) {
394
-			if (isset(self::$rememberVersion[$path])) {
395
-				$this->keyManager->setVersion($path, self::$rememberVersion[$path], new View());
396
-				unset(self::$rememberVersion[$path]);
397
-			}
398
-			return;
399
-		}
400
-
401
-		$fileKey = $this->keyManager->getFileKey($path, $uid);
402
-
403
-		if (!empty($fileKey)) {
404
-
405
-			$publicKeys = [];
406
-			if ($this->useMasterPassword === true) {
407
-				$publicKeys[$this->keyManager->getMasterKeyId()] = $this->keyManager->getPublicMasterKey();
408
-			} else {
409
-				foreach ($accessList['users'] as $user) {
410
-					try {
411
-						$publicKeys[$user] = $this->keyManager->getPublicKey($user);
412
-					} catch (PublicKeyMissingException $e) {
413
-						$this->logger->warning('Could not encrypt file for ' . $user . ': ' . $e->getMessage());
414
-					}
415
-				}
416
-			}
417
-
418
-			$publicKeys = $this->keyManager->addSystemKeys($accessList, $publicKeys, $this->getOwner($path));
419
-
420
-			$encryptedFileKey = $this->crypt->multiKeyEncrypt($fileKey, $publicKeys);
421
-
422
-			$this->keyManager->deleteAllFileKeys($path);
423
-
424
-			$this->keyManager->setAllFileKeys($path, $encryptedFileKey);
425
-
426
-		} else {
427
-			$this->logger->debug('no file key found, we assume that the file "{file}" is not encrypted',
428
-				['file' => $path, 'app' => 'encryption']);
429
-
430
-			return false;
431
-		}
432
-
433
-		return true;
434
-	}
435
-
436
-	/**
437
-	 * should the file be encrypted or not
438
-	 *
439
-	 * @param string $path
440
-	 * @return boolean
441
-	 */
442
-	public function shouldEncrypt($path) {
443
-		if ($this->util->shouldEncryptHomeStorage() === false) {
444
-			$storage = $this->util->getStorage($path);
445
-			if ($storage->instanceOfStorage('\OCP\Files\IHomeStorage')) {
446
-				return false;
447
-			}
448
-		}
449
-		$parts = explode('/', $path);
450
-		if (count($parts) < 4) {
451
-			return false;
452
-		}
453
-
454
-		if ($parts[2] === 'files') {
455
-			return true;
456
-		}
457
-		if ($parts[2] === 'files_versions') {
458
-			return true;
459
-		}
460
-		if ($parts[2] === 'files_trashbin') {
461
-			return true;
462
-		}
463
-
464
-		return false;
465
-	}
466
-
467
-	/**
468
-	 * get size of the unencrypted payload per block.
469
-	 * Nextcloud read/write files with a block size of 8192 byte
470
-	 *
471
-	 * @param bool $signed
472
-	 * @return int
473
-	 */
474
-	public function getUnencryptedBlockSize($signed = false) {
475
-		if ($signed === false) {
476
-			return $this->unencryptedBlockSize;
477
-		}
478
-
479
-		return $this->unencryptedBlockSizeSigned;
480
-	}
481
-
482
-	/**
483
-	 * check if the encryption module is able to read the file,
484
-	 * e.g. if all encryption keys exists
485
-	 *
486
-	 * @param string $path
487
-	 * @param string $uid user for whom we want to check if he can read the file
488
-	 * @return bool
489
-	 * @throws DecryptionFailedException
490
-	 */
491
-	public function isReadable($path, $uid) {
492
-		$fileKey = $this->keyManager->getFileKey($path, $uid);
493
-		if (empty($fileKey)) {
494
-			$owner = $this->util->getOwner($path);
495
-			if ($owner !== $uid) {
496
-				// if it is a shared file we throw a exception with a useful
497
-				// error message because in this case it means that the file was
498
-				// shared with the user at a point where the user didn't had a
499
-				// valid private/public key
500
-				$msg = 'Encryption module "' . $this->getDisplayName() .
501
-					'" is not able to read ' . $path;
502
-				$hint = $this->l->t('Can not read this file, probably this is a shared file. Please ask the file owner to reshare the file with you.');
503
-				$this->logger->warning($msg);
504
-				throw new DecryptionFailedException($msg, $hint);
505
-			}
506
-			return false;
507
-		}
508
-
509
-		return true;
510
-	}
511
-
512
-	/**
513
-	 * Initial encryption of all files
514
-	 *
515
-	 * @param InputInterface $input
516
-	 * @param OutputInterface $output write some status information to the terminal during encryption
517
-	 */
518
-	public function encryptAll(InputInterface $input, OutputInterface $output) {
519
-		$this->encryptAll->encryptAll($input, $output);
520
-	}
521
-
522
-	/**
523
-	 * prepare module to perform decrypt all operation
524
-	 *
525
-	 * @param InputInterface $input
526
-	 * @param OutputInterface $output
527
-	 * @param string $user
528
-	 * @return bool
529
-	 */
530
-	public function prepareDecryptAll(InputInterface $input, OutputInterface $output, $user = '') {
531
-		return $this->decryptAll->prepare($input, $output, $user);
532
-	}
533
-
534
-
535
-	/**
536
-	 * @param string $path
537
-	 * @return string
538
-	 */
539
-	protected function getPathToRealFile($path) {
540
-		$realPath = $path;
541
-		$parts = explode('/', $path);
542
-		if ($parts[2] === 'files_versions') {
543
-			$realPath = '/' . $parts[1] . '/files/' . implode('/', array_slice($parts, 3));
544
-			$length = strrpos($realPath, '.');
545
-			$realPath = substr($realPath, 0, $length);
546
-		}
547
-
548
-		return $realPath;
549
-	}
550
-
551
-	/**
552
-	 * remove .part file extension and the ocTransferId from the file to get the
553
-	 * original file name
554
-	 *
555
-	 * @param string $path
556
-	 * @return string
557
-	 */
558
-	protected function stripPartFileExtension($path) {
559
-		if (pathinfo($path, PATHINFO_EXTENSION) === 'part') {
560
-			$pos = strrpos($path, '.', -6);
561
-			$path = substr($path, 0, $pos);
562
-		}
563
-
564
-		return $path;
565
-	}
566
-
567
-	/**
568
-	 * get owner of a file
569
-	 *
570
-	 * @param string $path
571
-	 * @return string
572
-	 */
573
-	protected function getOwner($path) {
574
-		if (!isset($this->owner[$path])) {
575
-			$this->owner[$path] = $this->util->getOwner($path);
576
-		}
577
-		return $this->owner[$path];
578
-	}
579
-
580
-	/**
581
-	 * Check if the module is ready to be used by that specific user.
582
-	 * In case a module is not ready - because e.g. key pairs have not been generated
583
-	 * upon login this method can return false before any operation starts and might
584
-	 * cause issues during operations.
585
-	 *
586
-	 * @param string $user
587
-	 * @return boolean
588
-	 * @since 9.1.0
589
-	 */
590
-	public function isReadyForUser($user) {
591
-		return $this->keyManager->userHasKeys($user);
592
-	}
593
-
594
-	/**
595
-	 * We only need a detailed access list if the master key is not enabled
596
-	 *
597
-	 * @return bool
598
-	 */
599
-	public function needDetailedAccessList() {
600
-		return !$this->util->isMasterKeyEnabled();
601
-	}
49
+    const ID = 'OC_DEFAULT_MODULE';
50
+    const DISPLAY_NAME = 'Default encryption module';
51
+
52
+    /**
53
+     * @var Crypt
54
+     */
55
+    private $crypt;
56
+
57
+    /** @var string */
58
+    private $cipher;
59
+
60
+    /** @var string */
61
+    private $path;
62
+
63
+    /** @var string */
64
+    private $user;
65
+
66
+    /** @var  array */
67
+    private $owner;
68
+
69
+    /** @var string */
70
+    private $fileKey;
71
+
72
+    /** @var string */
73
+    private $writeCache;
74
+
75
+    /** @var KeyManager */
76
+    private $keyManager;
77
+
78
+    /** @var array */
79
+    private $accessList;
80
+
81
+    /** @var boolean */
82
+    private $isWriteOperation;
83
+
84
+    /** @var Util */
85
+    private $util;
86
+
87
+    /** @var  Session */
88
+    private $session;
89
+
90
+    /** @var  ILogger */
91
+    private $logger;
92
+
93
+    /** @var IL10N */
94
+    private $l;
95
+
96
+    /** @var EncryptAll */
97
+    private $encryptAll;
98
+
99
+    /** @var  bool */
100
+    private $useMasterPassword;
101
+
102
+    /** @var DecryptAll  */
103
+    private $decryptAll;
104
+
105
+    /** @var int unencrypted block size if block contains signature */
106
+    private $unencryptedBlockSizeSigned = 6072;
107
+
108
+    /** @var int unencrypted block size */
109
+    private $unencryptedBlockSize = 6126;
110
+
111
+    /** @var int Current version of the file */
112
+    private $version = 0;
113
+
114
+    /** @var array remember encryption signature version */
115
+    private static $rememberVersion = [];
116
+
117
+
118
+    /**
119
+     *
120
+     * @param Crypt $crypt
121
+     * @param KeyManager $keyManager
122
+     * @param Util $util
123
+     * @param Session $session
124
+     * @param EncryptAll $encryptAll
125
+     * @param DecryptAll $decryptAll
126
+     * @param ILogger $logger
127
+     * @param IL10N $il10n
128
+     */
129
+    public function __construct(Crypt $crypt,
130
+                                KeyManager $keyManager,
131
+                                Util $util,
132
+                                Session $session,
133
+                                EncryptAll $encryptAll,
134
+                                DecryptAll $decryptAll,
135
+                                ILogger $logger,
136
+                                IL10N $il10n) {
137
+        $this->crypt = $crypt;
138
+        $this->keyManager = $keyManager;
139
+        $this->util = $util;
140
+        $this->session = $session;
141
+        $this->encryptAll = $encryptAll;
142
+        $this->decryptAll = $decryptAll;
143
+        $this->logger = $logger;
144
+        $this->l = $il10n;
145
+        $this->owner = [];
146
+        $this->useMasterPassword = $util->isMasterKeyEnabled();
147
+    }
148
+
149
+    /**
150
+     * @return string defining the technical unique id
151
+     */
152
+    public function getId() {
153
+        return self::ID;
154
+    }
155
+
156
+    /**
157
+     * In comparison to getKey() this function returns a human readable (maybe translated) name
158
+     *
159
+     * @return string
160
+     */
161
+    public function getDisplayName() {
162
+        return self::DISPLAY_NAME;
163
+    }
164
+
165
+    /**
166
+     * start receiving chunks from a file. This is the place where you can
167
+     * perform some initial step before starting encrypting/decrypting the
168
+     * chunks
169
+     *
170
+     * @param string $path to the file
171
+     * @param string $user who read/write the file
172
+     * @param string $mode php stream open mode
173
+     * @param array $header contains the header data read from the file
174
+     * @param array $accessList who has access to the file contains the key 'users' and 'public'
175
+     *
176
+     * @return array $header contain data as key-value pairs which should be
177
+     *                       written to the header, in case of a write operation
178
+     *                       or if no additional data is needed return a empty array
179
+     */
180
+    public function begin($path, $user, $mode, array $header, array $accessList) {
181
+        $this->path = $this->getPathToRealFile($path);
182
+        $this->accessList = $accessList;
183
+        $this->user = $user;
184
+        $this->isWriteOperation = false;
185
+        $this->writeCache = '';
186
+
187
+        if($this->session->isReady() === false) {
188
+            // if the master key is enabled we can initialize encryption
189
+            // with a empty password and user name
190
+            if ($this->util->isMasterKeyEnabled()) {
191
+                $this->keyManager->init('', '');
192
+            }
193
+        }
194
+
195
+        if ($this->session->decryptAllModeActivated()) {
196
+            $encryptedFileKey = $this->keyManager->getEncryptedFileKey($this->path);
197
+            $shareKey = $this->keyManager->getShareKey($this->path, $this->session->getDecryptAllUid());
198
+            $this->fileKey = $this->crypt->multiKeyDecrypt($encryptedFileKey,
199
+                $shareKey,
200
+                $this->session->getDecryptAllKey());
201
+        } else {
202
+            $this->fileKey = $this->keyManager->getFileKey($this->path, $this->user);
203
+        }
204
+
205
+        // always use the version from the original file, also part files
206
+        // need to have a correct version number if they get moved over to the
207
+        // final location
208
+        $this->version = (int)$this->keyManager->getVersion($this->stripPartFileExtension($path), new View());
209
+
210
+        if (
211
+            $mode === 'w'
212
+            || $mode === 'w+'
213
+            || $mode === 'wb'
214
+            || $mode === 'wb+'
215
+        ) {
216
+            $this->isWriteOperation = true;
217
+            if (empty($this->fileKey)) {
218
+                $this->fileKey = $this->crypt->generateFileKey();
219
+            }
220
+        } else {
221
+            // if we read a part file we need to increase the version by 1
222
+            // because the version number was also increased by writing
223
+            // the part file
224
+            if(Scanner::isPartialFile($path)) {
225
+                $this->version = $this->version + 1;
226
+            }
227
+        }
228
+
229
+        if ($this->isWriteOperation) {
230
+            $this->cipher = $this->crypt->getCipher();
231
+        } elseif (isset($header['cipher'])) {
232
+            $this->cipher = $header['cipher'];
233
+        } else {
234
+            // if we read a file without a header we fall-back to the legacy cipher
235
+            // which was used in <=oC6
236
+            $this->cipher = $this->crypt->getLegacyCipher();
237
+        }
238
+
239
+        return ['cipher' => $this->cipher, 'signed' => 'true'];
240
+    }
241
+
242
+    /**
243
+     * last chunk received. This is the place where you can perform some final
244
+     * operation and return some remaining data if something is left in your
245
+     * buffer.
246
+     *
247
+     * @param string $path to the file
248
+     * @param int $position
249
+     * @return string remained data which should be written to the file in case
250
+     *                of a write operation
251
+     * @throws PublicKeyMissingException
252
+     * @throws \Exception
253
+     * @throws \OCA\Encryption\Exceptions\MultiKeyEncryptException
254
+     */
255
+    public function end($path, $position = 0) {
256
+        $result = '';
257
+        if ($this->isWriteOperation) {
258
+            // in case of a part file we remember the new signature versions
259
+            // the version will be set later on update.
260
+            // This way we make sure that other apps listening to the pre-hooks
261
+            // still get the old version which should be the correct value for them
262
+            if (Scanner::isPartialFile($path)) {
263
+                self::$rememberVersion[$this->stripPartFileExtension($path)] = $this->version + 1;
264
+            }
265
+            if (!empty($this->writeCache)) {
266
+                $result = $this->crypt->symmetricEncryptFileContent($this->writeCache, $this->fileKey, $this->version + 1, $position);
267
+                $this->writeCache = '';
268
+            }
269
+            $publicKeys = [];
270
+            if ($this->useMasterPassword === true) {
271
+                $publicKeys[$this->keyManager->getMasterKeyId()] = $this->keyManager->getPublicMasterKey();
272
+            } else {
273
+                foreach ($this->accessList['users'] as $uid) {
274
+                    try {
275
+                        $publicKeys[$uid] = $this->keyManager->getPublicKey($uid);
276
+                    } catch (PublicKeyMissingException $e) {
277
+                        $this->logger->warning(
278
+                            'no public key found for user "{uid}", user will not be able to read the file',
279
+                            ['app' => 'encryption', 'uid' => $uid]
280
+                        );
281
+                        // if the public key of the owner is missing we should fail
282
+                        if ($uid === $this->user) {
283
+                            throw $e;
284
+                        }
285
+                    }
286
+                }
287
+            }
288
+
289
+            $publicKeys = $this->keyManager->addSystemKeys($this->accessList, $publicKeys, $this->getOwner($path));
290
+            $encryptedKeyfiles = $this->crypt->multiKeyEncrypt($this->fileKey, $publicKeys);
291
+            $this->keyManager->setAllFileKeys($this->path, $encryptedKeyfiles);
292
+        }
293
+        return $result;
294
+    }
295
+
296
+
297
+
298
+    /**
299
+     * encrypt data
300
+     *
301
+     * @param string $data you want to encrypt
302
+     * @param int $position
303
+     * @return string encrypted data
304
+     */
305
+    public function encrypt($data, $position = 0) {
306
+        // If extra data is left over from the last round, make sure it
307
+        // is integrated into the next block
308
+        if ($this->writeCache) {
309
+
310
+            // Concat writeCache to start of $data
311
+            $data = $this->writeCache . $data;
312
+
313
+            // Clear the write cache, ready for reuse - it has been
314
+            // flushed and its old contents processed
315
+            $this->writeCache = '';
316
+
317
+        }
318
+
319
+        $encrypted = '';
320
+        // While there still remains some data to be processed & written
321
+        while (strlen($data) > 0) {
322
+
323
+            // Remaining length for this iteration, not of the
324
+            // entire file (may be greater than 8192 bytes)
325
+            $remainingLength = strlen($data);
326
+
327
+            // If data remaining to be written is less than the
328
+            // size of 1 6126 byte block
329
+            if ($remainingLength < $this->unencryptedBlockSizeSigned) {
330
+
331
+                // Set writeCache to contents of $data
332
+                // The writeCache will be carried over to the
333
+                // next write round, and added to the start of
334
+                // $data to ensure that written blocks are
335
+                // always the correct length. If there is still
336
+                // data in writeCache after the writing round
337
+                // has finished, then the data will be written
338
+                // to disk by $this->flush().
339
+                $this->writeCache = $data;
340
+
341
+                // Clear $data ready for next round
342
+                $data = '';
343
+
344
+            } else {
345
+
346
+                // Read the chunk from the start of $data
347
+                $chunk = substr($data, 0, $this->unencryptedBlockSizeSigned);
348
+
349
+                $encrypted .= $this->crypt->symmetricEncryptFileContent($chunk, $this->fileKey, $this->version + 1, $position);
350
+
351
+                // Remove the chunk we just processed from
352
+                // $data, leaving only unprocessed data in $data
353
+                // var, for handling on the next round
354
+                $data = substr($data, $this->unencryptedBlockSizeSigned);
355
+
356
+            }
357
+
358
+        }
359
+
360
+        return $encrypted;
361
+    }
362
+
363
+    /**
364
+     * decrypt data
365
+     *
366
+     * @param string $data you want to decrypt
367
+     * @param int $position
368
+     * @return string decrypted data
369
+     * @throws DecryptionFailedException
370
+     */
371
+    public function decrypt($data, $position = 0) {
372
+        if (empty($this->fileKey)) {
373
+            $msg = 'Can not decrypt this file, probably this is a shared file. Please ask the file owner to reshare the file with you.';
374
+            $hint = $this->l->t('Can not decrypt this file, probably this is a shared file. Please ask the file owner to reshare the file with you.');
375
+            $this->logger->error($msg);
376
+
377
+            throw new DecryptionFailedException($msg, $hint);
378
+        }
379
+
380
+        return $this->crypt->symmetricDecryptFileContent($data, $this->fileKey, $this->cipher, $this->version, $position);
381
+    }
382
+
383
+    /**
384
+     * update encrypted file, e.g. give additional users access to the file
385
+     *
386
+     * @param string $path path to the file which should be updated
387
+     * @param string $uid of the user who performs the operation
388
+     * @param array $accessList who has access to the file contains the key 'users' and 'public'
389
+     * @return boolean
390
+     */
391
+    public function update($path, $uid, array $accessList) {
392
+
393
+        if (empty($accessList)) {
394
+            if (isset(self::$rememberVersion[$path])) {
395
+                $this->keyManager->setVersion($path, self::$rememberVersion[$path], new View());
396
+                unset(self::$rememberVersion[$path]);
397
+            }
398
+            return;
399
+        }
400
+
401
+        $fileKey = $this->keyManager->getFileKey($path, $uid);
402
+
403
+        if (!empty($fileKey)) {
404
+
405
+            $publicKeys = [];
406
+            if ($this->useMasterPassword === true) {
407
+                $publicKeys[$this->keyManager->getMasterKeyId()] = $this->keyManager->getPublicMasterKey();
408
+            } else {
409
+                foreach ($accessList['users'] as $user) {
410
+                    try {
411
+                        $publicKeys[$user] = $this->keyManager->getPublicKey($user);
412
+                    } catch (PublicKeyMissingException $e) {
413
+                        $this->logger->warning('Could not encrypt file for ' . $user . ': ' . $e->getMessage());
414
+                    }
415
+                }
416
+            }
417
+
418
+            $publicKeys = $this->keyManager->addSystemKeys($accessList, $publicKeys, $this->getOwner($path));
419
+
420
+            $encryptedFileKey = $this->crypt->multiKeyEncrypt($fileKey, $publicKeys);
421
+
422
+            $this->keyManager->deleteAllFileKeys($path);
423
+
424
+            $this->keyManager->setAllFileKeys($path, $encryptedFileKey);
425
+
426
+        } else {
427
+            $this->logger->debug('no file key found, we assume that the file "{file}" is not encrypted',
428
+                ['file' => $path, 'app' => 'encryption']);
429
+
430
+            return false;
431
+        }
432
+
433
+        return true;
434
+    }
435
+
436
+    /**
437
+     * should the file be encrypted or not
438
+     *
439
+     * @param string $path
440
+     * @return boolean
441
+     */
442
+    public function shouldEncrypt($path) {
443
+        if ($this->util->shouldEncryptHomeStorage() === false) {
444
+            $storage = $this->util->getStorage($path);
445
+            if ($storage->instanceOfStorage('\OCP\Files\IHomeStorage')) {
446
+                return false;
447
+            }
448
+        }
449
+        $parts = explode('/', $path);
450
+        if (count($parts) < 4) {
451
+            return false;
452
+        }
453
+
454
+        if ($parts[2] === 'files') {
455
+            return true;
456
+        }
457
+        if ($parts[2] === 'files_versions') {
458
+            return true;
459
+        }
460
+        if ($parts[2] === 'files_trashbin') {
461
+            return true;
462
+        }
463
+
464
+        return false;
465
+    }
466
+
467
+    /**
468
+     * get size of the unencrypted payload per block.
469
+     * Nextcloud read/write files with a block size of 8192 byte
470
+     *
471
+     * @param bool $signed
472
+     * @return int
473
+     */
474
+    public function getUnencryptedBlockSize($signed = false) {
475
+        if ($signed === false) {
476
+            return $this->unencryptedBlockSize;
477
+        }
478
+
479
+        return $this->unencryptedBlockSizeSigned;
480
+    }
481
+
482
+    /**
483
+     * check if the encryption module is able to read the file,
484
+     * e.g. if all encryption keys exists
485
+     *
486
+     * @param string $path
487
+     * @param string $uid user for whom we want to check if he can read the file
488
+     * @return bool
489
+     * @throws DecryptionFailedException
490
+     */
491
+    public function isReadable($path, $uid) {
492
+        $fileKey = $this->keyManager->getFileKey($path, $uid);
493
+        if (empty($fileKey)) {
494
+            $owner = $this->util->getOwner($path);
495
+            if ($owner !== $uid) {
496
+                // if it is a shared file we throw a exception with a useful
497
+                // error message because in this case it means that the file was
498
+                // shared with the user at a point where the user didn't had a
499
+                // valid private/public key
500
+                $msg = 'Encryption module "' . $this->getDisplayName() .
501
+                    '" is not able to read ' . $path;
502
+                $hint = $this->l->t('Can not read this file, probably this is a shared file. Please ask the file owner to reshare the file with you.');
503
+                $this->logger->warning($msg);
504
+                throw new DecryptionFailedException($msg, $hint);
505
+            }
506
+            return false;
507
+        }
508
+
509
+        return true;
510
+    }
511
+
512
+    /**
513
+     * Initial encryption of all files
514
+     *
515
+     * @param InputInterface $input
516
+     * @param OutputInterface $output write some status information to the terminal during encryption
517
+     */
518
+    public function encryptAll(InputInterface $input, OutputInterface $output) {
519
+        $this->encryptAll->encryptAll($input, $output);
520
+    }
521
+
522
+    /**
523
+     * prepare module to perform decrypt all operation
524
+     *
525
+     * @param InputInterface $input
526
+     * @param OutputInterface $output
527
+     * @param string $user
528
+     * @return bool
529
+     */
530
+    public function prepareDecryptAll(InputInterface $input, OutputInterface $output, $user = '') {
531
+        return $this->decryptAll->prepare($input, $output, $user);
532
+    }
533
+
534
+
535
+    /**
536
+     * @param string $path
537
+     * @return string
538
+     */
539
+    protected function getPathToRealFile($path) {
540
+        $realPath = $path;
541
+        $parts = explode('/', $path);
542
+        if ($parts[2] === 'files_versions') {
543
+            $realPath = '/' . $parts[1] . '/files/' . implode('/', array_slice($parts, 3));
544
+            $length = strrpos($realPath, '.');
545
+            $realPath = substr($realPath, 0, $length);
546
+        }
547
+
548
+        return $realPath;
549
+    }
550
+
551
+    /**
552
+     * remove .part file extension and the ocTransferId from the file to get the
553
+     * original file name
554
+     *
555
+     * @param string $path
556
+     * @return string
557
+     */
558
+    protected function stripPartFileExtension($path) {
559
+        if (pathinfo($path, PATHINFO_EXTENSION) === 'part') {
560
+            $pos = strrpos($path, '.', -6);
561
+            $path = substr($path, 0, $pos);
562
+        }
563
+
564
+        return $path;
565
+    }
566
+
567
+    /**
568
+     * get owner of a file
569
+     *
570
+     * @param string $path
571
+     * @return string
572
+     */
573
+    protected function getOwner($path) {
574
+        if (!isset($this->owner[$path])) {
575
+            $this->owner[$path] = $this->util->getOwner($path);
576
+        }
577
+        return $this->owner[$path];
578
+    }
579
+
580
+    /**
581
+     * Check if the module is ready to be used by that specific user.
582
+     * In case a module is not ready - because e.g. key pairs have not been generated
583
+     * upon login this method can return false before any operation starts and might
584
+     * cause issues during operations.
585
+     *
586
+     * @param string $user
587
+     * @return boolean
588
+     * @since 9.1.0
589
+     */
590
+    public function isReadyForUser($user) {
591
+        return $this->keyManager->userHasKeys($user);
592
+    }
593
+
594
+    /**
595
+     * We only need a detailed access list if the master key is not enabled
596
+     *
597
+     * @return bool
598
+     */
599
+    public function needDetailedAccessList() {
600
+        return !$this->util->isMasterKeyEnabled();
601
+    }
602 602
 }
Please login to merge, or discard this patch.