Passed
Push — master ( b2c2f3...b900d6 )
by Julius
18:38 queued 13s
created
lib/private/Files/ObjectStore/ObjectStoreStorage.php 1 patch
Indentation   +555 added lines, -555 removed lines patch added patch discarded remove patch
@@ -43,562 +43,562 @@
 block discarded – undo
43 43
 use OCP\Files\Storage\IStorage;
44 44
 
45 45
 class ObjectStoreStorage extends \OC\Files\Storage\Common {
46
-	use CopyDirectory;
47
-
48
-	/**
49
-	 * @var \OCP\Files\ObjectStore\IObjectStore $objectStore
50
-	 */
51
-	protected $objectStore;
52
-	/**
53
-	 * @var string $id
54
-	 */
55
-	protected $id;
56
-	/**
57
-	 * @var \OC\User\User $user
58
-	 */
59
-	protected $user;
60
-
61
-	private $objectPrefix = 'urn:oid:';
62
-
63
-	private $logger;
64
-
65
-	public function __construct($params) {
66
-		if (isset($params['objectstore']) && $params['objectstore'] instanceof IObjectStore) {
67
-			$this->objectStore = $params['objectstore'];
68
-		} else {
69
-			throw new \Exception('missing IObjectStore instance');
70
-		}
71
-		if (isset($params['storageid'])) {
72
-			$this->id = 'object::store:' . $params['storageid'];
73
-		} else {
74
-			$this->id = 'object::store:' . $this->objectStore->getStorageId();
75
-		}
76
-		if (isset($params['objectPrefix'])) {
77
-			$this->objectPrefix = $params['objectPrefix'];
78
-		}
79
-		//initialize cache with root directory in cache
80
-		if (!$this->is_dir('/')) {
81
-			$this->mkdir('/');
82
-		}
83
-
84
-		$this->logger = \OC::$server->getLogger();
85
-	}
86
-
87
-	public function mkdir($path) {
88
-		$path = $this->normalizePath($path);
89
-
90
-		if ($this->file_exists($path)) {
91
-			return false;
92
-		}
93
-
94
-		$mTime = time();
95
-		$data = [
96
-			'mimetype' => 'httpd/unix-directory',
97
-			'size' => 0,
98
-			'mtime' => $mTime,
99
-			'storage_mtime' => $mTime,
100
-			'permissions' => \OCP\Constants::PERMISSION_ALL,
101
-		];
102
-		if ($path === '') {
103
-			//create root on the fly
104
-			$data['etag'] = $this->getETag('');
105
-			$this->getCache()->put('', $data);
106
-			return true;
107
-		} else {
108
-			// if parent does not exist, create it
109
-			$parent = $this->normalizePath(dirname($path));
110
-			$parentType = $this->filetype($parent);
111
-			if ($parentType === false) {
112
-				if (!$this->mkdir($parent)) {
113
-					// something went wrong
114
-					return false;
115
-				}
116
-			} elseif ($parentType === 'file') {
117
-				// parent is a file
118
-				return false;
119
-			}
120
-			// finally create the new dir
121
-			$mTime = time(); // update mtime
122
-			$data['mtime'] = $mTime;
123
-			$data['storage_mtime'] = $mTime;
124
-			$data['etag'] = $this->getETag($path);
125
-			$this->getCache()->put($path, $data);
126
-			return true;
127
-		}
128
-	}
129
-
130
-	/**
131
-	 * @param string $path
132
-	 * @return string
133
-	 */
134
-	private function normalizePath($path) {
135
-		$path = trim($path, '/');
136
-		//FIXME why do we sometimes get a path like 'files//username'?
137
-		$path = str_replace('//', '/', $path);
138
-
139
-		// dirname('/folder') returns '.' but internally (in the cache) we store the root as ''
140
-		if (!$path || $path === '.') {
141
-			$path = '';
142
-		}
143
-
144
-		return $path;
145
-	}
146
-
147
-	/**
148
-	 * Object Stores use a NoopScanner because metadata is directly stored in
149
-	 * the file cache and cannot really scan the filesystem. The storage passed in is not used anywhere.
150
-	 *
151
-	 * @param string $path
152
-	 * @param \OC\Files\Storage\Storage (optional) the storage to pass to the scanner
153
-	 * @return \OC\Files\ObjectStore\NoopScanner
154
-	 */
155
-	public function getScanner($path = '', $storage = null) {
156
-		if (!$storage) {
157
-			$storage = $this;
158
-		}
159
-		if (!isset($this->scanner)) {
160
-			$this->scanner = new NoopScanner($storage);
161
-		}
162
-		return $this->scanner;
163
-	}
164
-
165
-	public function getId() {
166
-		return $this->id;
167
-	}
168
-
169
-	public function rmdir($path) {
170
-		$path = $this->normalizePath($path);
171
-
172
-		if (!$this->is_dir($path)) {
173
-			return false;
174
-		}
175
-
176
-		if (!$this->rmObjects($path)) {
177
-			return false;
178
-		}
179
-
180
-		$this->getCache()->remove($path);
181
-
182
-		return true;
183
-	}
184
-
185
-	private function rmObjects($path) {
186
-		$children = $this->getCache()->getFolderContents($path);
187
-		foreach ($children as $child) {
188
-			if ($child['mimetype'] === 'httpd/unix-directory') {
189
-				if (!$this->rmObjects($child['path'])) {
190
-					return false;
191
-				}
192
-			} else {
193
-				if (!$this->unlink($child['path'])) {
194
-					return false;
195
-				}
196
-			}
197
-		}
198
-
199
-		return true;
200
-	}
201
-
202
-	public function unlink($path) {
203
-		$path = $this->normalizePath($path);
204
-		$stat = $this->stat($path);
205
-
206
-		if ($stat && isset($stat['fileid'])) {
207
-			if ($stat['mimetype'] === 'httpd/unix-directory') {
208
-				return $this->rmdir($path);
209
-			}
210
-			try {
211
-				$this->objectStore->deleteObject($this->getURN($stat['fileid']));
212
-			} catch (\Exception $ex) {
213
-				if ($ex->getCode() !== 404) {
214
-					$this->logger->logException($ex, [
215
-						'app' => 'objectstore',
216
-						'message' => 'Could not delete object ' . $this->getURN($stat['fileid']) . ' for ' . $path,
217
-					]);
218
-					return false;
219
-				}
220
-				//removing from cache is ok as it does not exist in the objectstore anyway
221
-			}
222
-			$this->getCache()->remove($path);
223
-			return true;
224
-		}
225
-		return false;
226
-	}
227
-
228
-	public function stat($path) {
229
-		$path = $this->normalizePath($path);
230
-		$cacheEntry = $this->getCache()->get($path);
231
-		if ($cacheEntry instanceof CacheEntry) {
232
-			return $cacheEntry->getData();
233
-		} else {
234
-			return false;
235
-		}
236
-	}
237
-
238
-	public function getPermissions($path) {
239
-		$stat = $this->stat($path);
240
-
241
-		if (is_array($stat) && isset($stat['permissions'])) {
242
-			return $stat['permissions'];
243
-		}
244
-
245
-		return parent::getPermissions($path);
246
-	}
247
-
248
-	/**
249
-	 * Override this method if you need a different unique resource identifier for your object storage implementation.
250
-	 * The default implementations just appends the fileId to 'urn:oid:'. Make sure the URN is unique over all users.
251
-	 * You may need a mapping table to store your URN if it cannot be generated from the fileid.
252
-	 *
253
-	 * @param int $fileId the fileid
254
-	 * @return null|string the unified resource name used to identify the object
255
-	 */
256
-	public function getURN($fileId) {
257
-		if (is_numeric($fileId)) {
258
-			return $this->objectPrefix . $fileId;
259
-		}
260
-		return null;
261
-	}
262
-
263
-	public function opendir($path) {
264
-		$path = $this->normalizePath($path);
265
-
266
-		try {
267
-			$files = [];
268
-			$folderContents = $this->getCache()->getFolderContents($path);
269
-			foreach ($folderContents as $file) {
270
-				$files[] = $file['name'];
271
-			}
272
-
273
-			return IteratorDirectory::wrap($files);
274
-		} catch (\Exception $e) {
275
-			$this->logger->logException($e);
276
-			return false;
277
-		}
278
-	}
279
-
280
-	public function filetype($path) {
281
-		$path = $this->normalizePath($path);
282
-		$stat = $this->stat($path);
283
-		if ($stat) {
284
-			if ($stat['mimetype'] === 'httpd/unix-directory') {
285
-				return 'dir';
286
-			}
287
-			return 'file';
288
-		} else {
289
-			return false;
290
-		}
291
-	}
292
-
293
-	public function fopen($path, $mode) {
294
-		$path = $this->normalizePath($path);
295
-
296
-		if (strrpos($path, '.') !== false) {
297
-			$ext = substr($path, strrpos($path, '.'));
298
-		} else {
299
-			$ext = '';
300
-		}
301
-
302
-		switch ($mode) {
303
-			case 'r':
304
-			case 'rb':
305
-				$stat = $this->stat($path);
306
-				if (is_array($stat)) {
307
-					// Reading 0 sized files is a waste of time
308
-					if (isset($stat['size']) && $stat['size'] === 0) {
309
-						return fopen('php://memory', $mode);
310
-					}
311
-
312
-					try {
313
-						return $this->objectStore->readObject($this->getURN($stat['fileid']));
314
-					} catch (NotFoundException $e) {
315
-						$this->logger->logException($e, [
316
-							'app' => 'objectstore',
317
-							'message' => 'Could not get object ' . $this->getURN($stat['fileid']) . ' for file ' . $path,
318
-						]);
319
-						throw $e;
320
-					} catch (\Exception $ex) {
321
-						$this->logger->logException($ex, [
322
-							'app' => 'objectstore',
323
-							'message' => 'Could not get object ' . $this->getURN($stat['fileid']) . ' for file ' . $path,
324
-						]);
325
-						return false;
326
-					}
327
-				} else {
328
-					return false;
329
-				}
330
-			// no break
331
-			case 'w':
332
-			case 'wb':
333
-			case 'w+':
334
-			case 'wb+':
335
-				$tmpFile = \OC::$server->getTempManager()->getTemporaryFile($ext);
336
-				$handle = fopen($tmpFile, $mode);
337
-				return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
338
-					$this->writeBack($tmpFile, $path);
339
-				});
340
-			case 'a':
341
-			case 'ab':
342
-			case 'r+':
343
-			case 'a+':
344
-			case 'x':
345
-			case 'x+':
346
-			case 'c':
347
-			case 'c+':
348
-				$tmpFile = \OC::$server->getTempManager()->getTemporaryFile($ext);
349
-				if ($this->file_exists($path)) {
350
-					$source = $this->fopen($path, 'r');
351
-					file_put_contents($tmpFile, $source);
352
-				}
353
-				$handle = fopen($tmpFile, $mode);
354
-				return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
355
-					$this->writeBack($tmpFile, $path);
356
-				});
357
-		}
358
-		return false;
359
-	}
360
-
361
-	public function file_exists($path) {
362
-		$path = $this->normalizePath($path);
363
-		return (bool)$this->stat($path);
364
-	}
365
-
366
-	public function rename($source, $target) {
367
-		$source = $this->normalizePath($source);
368
-		$target = $this->normalizePath($target);
369
-		$this->remove($target);
370
-		$this->getCache()->move($source, $target);
371
-		$this->touch(dirname($target));
372
-		return true;
373
-	}
374
-
375
-	public function getMimeType($path) {
376
-		$path = $this->normalizePath($path);
377
-		return parent::getMimeType($path);
378
-	}
379
-
380
-	public function touch($path, $mtime = null) {
381
-		if (is_null($mtime)) {
382
-			$mtime = time();
383
-		}
384
-
385
-		$path = $this->normalizePath($path);
386
-		$dirName = dirname($path);
387
-		$parentExists = $this->is_dir($dirName);
388
-		if (!$parentExists) {
389
-			return false;
390
-		}
391
-
392
-		$stat = $this->stat($path);
393
-		if (is_array($stat)) {
394
-			// update existing mtime in db
395
-			$stat['mtime'] = $mtime;
396
-			$this->getCache()->update($stat['fileid'], $stat);
397
-		} else {
398
-			try {
399
-				//create a empty file, need to have at least on char to make it
400
-				// work with all object storage implementations
401
-				$this->file_put_contents($path, ' ');
402
-				$mimeType = \OC::$server->getMimeTypeDetector()->detectPath($path);
403
-				$stat = [
404
-					'etag' => $this->getETag($path),
405
-					'mimetype' => $mimeType,
406
-					'size' => 0,
407
-					'mtime' => $mtime,
408
-					'storage_mtime' => $mtime,
409
-					'permissions' => \OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_CREATE,
410
-				];
411
-				$this->getCache()->put($path, $stat);
412
-			} catch (\Exception $ex) {
413
-				$this->logger->logException($ex, [
414
-					'app' => 'objectstore',
415
-					'message' => 'Could not create object for ' . $path,
416
-				]);
417
-				throw $ex;
418
-			}
419
-		}
420
-		return true;
421
-	}
422
-
423
-	public function writeBack($tmpFile, $path) {
424
-		$size = filesize($tmpFile);
425
-		$this->writeStream($path, fopen($tmpFile, 'r'), $size);
426
-	}
427
-
428
-	/**
429
-	 * external changes are not supported, exclusive access to the object storage is assumed
430
-	 *
431
-	 * @param string $path
432
-	 * @param int $time
433
-	 * @return false
434
-	 */
435
-	public function hasUpdated($path, $time) {
436
-		return false;
437
-	}
438
-
439
-	public function needsPartFile() {
440
-		return false;
441
-	}
442
-
443
-	public function file_put_contents($path, $data) {
444
-		$handle = $this->fopen($path, 'w+');
445
-		$result = fwrite($handle, $data);
446
-		fclose($handle);
447
-		return $result;
448
-	}
449
-
450
-	public function writeStream(string $path, $stream, int $size = null): int {
451
-		$stat = $this->stat($path);
452
-		if (empty($stat)) {
453
-			// create new file
454
-			$stat = [
455
-				'permissions' => \OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_CREATE,
456
-			];
457
-		}
458
-		// update stat with new data
459
-		$mTime = time();
460
-		$stat['size'] = (int)$size;
461
-		$stat['mtime'] = $mTime;
462
-		$stat['storage_mtime'] = $mTime;
463
-
464
-		$mimetypeDetector = \OC::$server->getMimeTypeDetector();
465
-		$mimetype = $mimetypeDetector->detectPath($path);
466
-
467
-		$stat['mimetype'] = $mimetype;
468
-		$stat['etag'] = $this->getETag($path);
469
-
470
-		$exists = $this->getCache()->inCache($path);
471
-		$uploadPath = $exists ? $path : $path . '.part';
472
-
473
-		if ($exists) {
474
-			$fileId = $stat['fileid'];
475
-		} else {
476
-			$fileId = $this->getCache()->put($uploadPath, $stat);
477
-		}
478
-
479
-		$urn = $this->getURN($fileId);
480
-		try {
481
-			//upload to object storage
482
-			if ($size === null) {
483
-				$countStream = CountWrapper::wrap($stream, function ($writtenSize) use ($fileId, &$size) {
484
-					$this->getCache()->update($fileId, [
485
-						'size' => $writtenSize,
486
-					]);
487
-					$size = $writtenSize;
488
-				});
489
-				$this->objectStore->writeObject($urn, $countStream, $mimetype);
490
-				if (is_resource($countStream)) {
491
-					fclose($countStream);
492
-				}
493
-				$stat['size'] = $size;
494
-			} else {
495
-				$this->objectStore->writeObject($urn, $stream, $mimetype);
496
-				if (is_resource($stream)) {
497
-					fclose($stream);
498
-				}
499
-			}
500
-		} catch (\Exception $ex) {
501
-			if (!$exists) {
502
-				/*
46
+    use CopyDirectory;
47
+
48
+    /**
49
+     * @var \OCP\Files\ObjectStore\IObjectStore $objectStore
50
+     */
51
+    protected $objectStore;
52
+    /**
53
+     * @var string $id
54
+     */
55
+    protected $id;
56
+    /**
57
+     * @var \OC\User\User $user
58
+     */
59
+    protected $user;
60
+
61
+    private $objectPrefix = 'urn:oid:';
62
+
63
+    private $logger;
64
+
65
+    public function __construct($params) {
66
+        if (isset($params['objectstore']) && $params['objectstore'] instanceof IObjectStore) {
67
+            $this->objectStore = $params['objectstore'];
68
+        } else {
69
+            throw new \Exception('missing IObjectStore instance');
70
+        }
71
+        if (isset($params['storageid'])) {
72
+            $this->id = 'object::store:' . $params['storageid'];
73
+        } else {
74
+            $this->id = 'object::store:' . $this->objectStore->getStorageId();
75
+        }
76
+        if (isset($params['objectPrefix'])) {
77
+            $this->objectPrefix = $params['objectPrefix'];
78
+        }
79
+        //initialize cache with root directory in cache
80
+        if (!$this->is_dir('/')) {
81
+            $this->mkdir('/');
82
+        }
83
+
84
+        $this->logger = \OC::$server->getLogger();
85
+    }
86
+
87
+    public function mkdir($path) {
88
+        $path = $this->normalizePath($path);
89
+
90
+        if ($this->file_exists($path)) {
91
+            return false;
92
+        }
93
+
94
+        $mTime = time();
95
+        $data = [
96
+            'mimetype' => 'httpd/unix-directory',
97
+            'size' => 0,
98
+            'mtime' => $mTime,
99
+            'storage_mtime' => $mTime,
100
+            'permissions' => \OCP\Constants::PERMISSION_ALL,
101
+        ];
102
+        if ($path === '') {
103
+            //create root on the fly
104
+            $data['etag'] = $this->getETag('');
105
+            $this->getCache()->put('', $data);
106
+            return true;
107
+        } else {
108
+            // if parent does not exist, create it
109
+            $parent = $this->normalizePath(dirname($path));
110
+            $parentType = $this->filetype($parent);
111
+            if ($parentType === false) {
112
+                if (!$this->mkdir($parent)) {
113
+                    // something went wrong
114
+                    return false;
115
+                }
116
+            } elseif ($parentType === 'file') {
117
+                // parent is a file
118
+                return false;
119
+            }
120
+            // finally create the new dir
121
+            $mTime = time(); // update mtime
122
+            $data['mtime'] = $mTime;
123
+            $data['storage_mtime'] = $mTime;
124
+            $data['etag'] = $this->getETag($path);
125
+            $this->getCache()->put($path, $data);
126
+            return true;
127
+        }
128
+    }
129
+
130
+    /**
131
+     * @param string $path
132
+     * @return string
133
+     */
134
+    private function normalizePath($path) {
135
+        $path = trim($path, '/');
136
+        //FIXME why do we sometimes get a path like 'files//username'?
137
+        $path = str_replace('//', '/', $path);
138
+
139
+        // dirname('/folder') returns '.' but internally (in the cache) we store the root as ''
140
+        if (!$path || $path === '.') {
141
+            $path = '';
142
+        }
143
+
144
+        return $path;
145
+    }
146
+
147
+    /**
148
+     * Object Stores use a NoopScanner because metadata is directly stored in
149
+     * the file cache and cannot really scan the filesystem. The storage passed in is not used anywhere.
150
+     *
151
+     * @param string $path
152
+     * @param \OC\Files\Storage\Storage (optional) the storage to pass to the scanner
153
+     * @return \OC\Files\ObjectStore\NoopScanner
154
+     */
155
+    public function getScanner($path = '', $storage = null) {
156
+        if (!$storage) {
157
+            $storage = $this;
158
+        }
159
+        if (!isset($this->scanner)) {
160
+            $this->scanner = new NoopScanner($storage);
161
+        }
162
+        return $this->scanner;
163
+    }
164
+
165
+    public function getId() {
166
+        return $this->id;
167
+    }
168
+
169
+    public function rmdir($path) {
170
+        $path = $this->normalizePath($path);
171
+
172
+        if (!$this->is_dir($path)) {
173
+            return false;
174
+        }
175
+
176
+        if (!$this->rmObjects($path)) {
177
+            return false;
178
+        }
179
+
180
+        $this->getCache()->remove($path);
181
+
182
+        return true;
183
+    }
184
+
185
+    private function rmObjects($path) {
186
+        $children = $this->getCache()->getFolderContents($path);
187
+        foreach ($children as $child) {
188
+            if ($child['mimetype'] === 'httpd/unix-directory') {
189
+                if (!$this->rmObjects($child['path'])) {
190
+                    return false;
191
+                }
192
+            } else {
193
+                if (!$this->unlink($child['path'])) {
194
+                    return false;
195
+                }
196
+            }
197
+        }
198
+
199
+        return true;
200
+    }
201
+
202
+    public function unlink($path) {
203
+        $path = $this->normalizePath($path);
204
+        $stat = $this->stat($path);
205
+
206
+        if ($stat && isset($stat['fileid'])) {
207
+            if ($stat['mimetype'] === 'httpd/unix-directory') {
208
+                return $this->rmdir($path);
209
+            }
210
+            try {
211
+                $this->objectStore->deleteObject($this->getURN($stat['fileid']));
212
+            } catch (\Exception $ex) {
213
+                if ($ex->getCode() !== 404) {
214
+                    $this->logger->logException($ex, [
215
+                        'app' => 'objectstore',
216
+                        'message' => 'Could not delete object ' . $this->getURN($stat['fileid']) . ' for ' . $path,
217
+                    ]);
218
+                    return false;
219
+                }
220
+                //removing from cache is ok as it does not exist in the objectstore anyway
221
+            }
222
+            $this->getCache()->remove($path);
223
+            return true;
224
+        }
225
+        return false;
226
+    }
227
+
228
+    public function stat($path) {
229
+        $path = $this->normalizePath($path);
230
+        $cacheEntry = $this->getCache()->get($path);
231
+        if ($cacheEntry instanceof CacheEntry) {
232
+            return $cacheEntry->getData();
233
+        } else {
234
+            return false;
235
+        }
236
+    }
237
+
238
+    public function getPermissions($path) {
239
+        $stat = $this->stat($path);
240
+
241
+        if (is_array($stat) && isset($stat['permissions'])) {
242
+            return $stat['permissions'];
243
+        }
244
+
245
+        return parent::getPermissions($path);
246
+    }
247
+
248
+    /**
249
+     * Override this method if you need a different unique resource identifier for your object storage implementation.
250
+     * The default implementations just appends the fileId to 'urn:oid:'. Make sure the URN is unique over all users.
251
+     * You may need a mapping table to store your URN if it cannot be generated from the fileid.
252
+     *
253
+     * @param int $fileId the fileid
254
+     * @return null|string the unified resource name used to identify the object
255
+     */
256
+    public function getURN($fileId) {
257
+        if (is_numeric($fileId)) {
258
+            return $this->objectPrefix . $fileId;
259
+        }
260
+        return null;
261
+    }
262
+
263
+    public function opendir($path) {
264
+        $path = $this->normalizePath($path);
265
+
266
+        try {
267
+            $files = [];
268
+            $folderContents = $this->getCache()->getFolderContents($path);
269
+            foreach ($folderContents as $file) {
270
+                $files[] = $file['name'];
271
+            }
272
+
273
+            return IteratorDirectory::wrap($files);
274
+        } catch (\Exception $e) {
275
+            $this->logger->logException($e);
276
+            return false;
277
+        }
278
+    }
279
+
280
+    public function filetype($path) {
281
+        $path = $this->normalizePath($path);
282
+        $stat = $this->stat($path);
283
+        if ($stat) {
284
+            if ($stat['mimetype'] === 'httpd/unix-directory') {
285
+                return 'dir';
286
+            }
287
+            return 'file';
288
+        } else {
289
+            return false;
290
+        }
291
+    }
292
+
293
+    public function fopen($path, $mode) {
294
+        $path = $this->normalizePath($path);
295
+
296
+        if (strrpos($path, '.') !== false) {
297
+            $ext = substr($path, strrpos($path, '.'));
298
+        } else {
299
+            $ext = '';
300
+        }
301
+
302
+        switch ($mode) {
303
+            case 'r':
304
+            case 'rb':
305
+                $stat = $this->stat($path);
306
+                if (is_array($stat)) {
307
+                    // Reading 0 sized files is a waste of time
308
+                    if (isset($stat['size']) && $stat['size'] === 0) {
309
+                        return fopen('php://memory', $mode);
310
+                    }
311
+
312
+                    try {
313
+                        return $this->objectStore->readObject($this->getURN($stat['fileid']));
314
+                    } catch (NotFoundException $e) {
315
+                        $this->logger->logException($e, [
316
+                            'app' => 'objectstore',
317
+                            'message' => 'Could not get object ' . $this->getURN($stat['fileid']) . ' for file ' . $path,
318
+                        ]);
319
+                        throw $e;
320
+                    } catch (\Exception $ex) {
321
+                        $this->logger->logException($ex, [
322
+                            'app' => 'objectstore',
323
+                            'message' => 'Could not get object ' . $this->getURN($stat['fileid']) . ' for file ' . $path,
324
+                        ]);
325
+                        return false;
326
+                    }
327
+                } else {
328
+                    return false;
329
+                }
330
+            // no break
331
+            case 'w':
332
+            case 'wb':
333
+            case 'w+':
334
+            case 'wb+':
335
+                $tmpFile = \OC::$server->getTempManager()->getTemporaryFile($ext);
336
+                $handle = fopen($tmpFile, $mode);
337
+                return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
338
+                    $this->writeBack($tmpFile, $path);
339
+                });
340
+            case 'a':
341
+            case 'ab':
342
+            case 'r+':
343
+            case 'a+':
344
+            case 'x':
345
+            case 'x+':
346
+            case 'c':
347
+            case 'c+':
348
+                $tmpFile = \OC::$server->getTempManager()->getTemporaryFile($ext);
349
+                if ($this->file_exists($path)) {
350
+                    $source = $this->fopen($path, 'r');
351
+                    file_put_contents($tmpFile, $source);
352
+                }
353
+                $handle = fopen($tmpFile, $mode);
354
+                return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
355
+                    $this->writeBack($tmpFile, $path);
356
+                });
357
+        }
358
+        return false;
359
+    }
360
+
361
+    public function file_exists($path) {
362
+        $path = $this->normalizePath($path);
363
+        return (bool)$this->stat($path);
364
+    }
365
+
366
+    public function rename($source, $target) {
367
+        $source = $this->normalizePath($source);
368
+        $target = $this->normalizePath($target);
369
+        $this->remove($target);
370
+        $this->getCache()->move($source, $target);
371
+        $this->touch(dirname($target));
372
+        return true;
373
+    }
374
+
375
+    public function getMimeType($path) {
376
+        $path = $this->normalizePath($path);
377
+        return parent::getMimeType($path);
378
+    }
379
+
380
+    public function touch($path, $mtime = null) {
381
+        if (is_null($mtime)) {
382
+            $mtime = time();
383
+        }
384
+
385
+        $path = $this->normalizePath($path);
386
+        $dirName = dirname($path);
387
+        $parentExists = $this->is_dir($dirName);
388
+        if (!$parentExists) {
389
+            return false;
390
+        }
391
+
392
+        $stat = $this->stat($path);
393
+        if (is_array($stat)) {
394
+            // update existing mtime in db
395
+            $stat['mtime'] = $mtime;
396
+            $this->getCache()->update($stat['fileid'], $stat);
397
+        } else {
398
+            try {
399
+                //create a empty file, need to have at least on char to make it
400
+                // work with all object storage implementations
401
+                $this->file_put_contents($path, ' ');
402
+                $mimeType = \OC::$server->getMimeTypeDetector()->detectPath($path);
403
+                $stat = [
404
+                    'etag' => $this->getETag($path),
405
+                    'mimetype' => $mimeType,
406
+                    'size' => 0,
407
+                    'mtime' => $mtime,
408
+                    'storage_mtime' => $mtime,
409
+                    'permissions' => \OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_CREATE,
410
+                ];
411
+                $this->getCache()->put($path, $stat);
412
+            } catch (\Exception $ex) {
413
+                $this->logger->logException($ex, [
414
+                    'app' => 'objectstore',
415
+                    'message' => 'Could not create object for ' . $path,
416
+                ]);
417
+                throw $ex;
418
+            }
419
+        }
420
+        return true;
421
+    }
422
+
423
+    public function writeBack($tmpFile, $path) {
424
+        $size = filesize($tmpFile);
425
+        $this->writeStream($path, fopen($tmpFile, 'r'), $size);
426
+    }
427
+
428
+    /**
429
+     * external changes are not supported, exclusive access to the object storage is assumed
430
+     *
431
+     * @param string $path
432
+     * @param int $time
433
+     * @return false
434
+     */
435
+    public function hasUpdated($path, $time) {
436
+        return false;
437
+    }
438
+
439
+    public function needsPartFile() {
440
+        return false;
441
+    }
442
+
443
+    public function file_put_contents($path, $data) {
444
+        $handle = $this->fopen($path, 'w+');
445
+        $result = fwrite($handle, $data);
446
+        fclose($handle);
447
+        return $result;
448
+    }
449
+
450
+    public function writeStream(string $path, $stream, int $size = null): int {
451
+        $stat = $this->stat($path);
452
+        if (empty($stat)) {
453
+            // create new file
454
+            $stat = [
455
+                'permissions' => \OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_CREATE,
456
+            ];
457
+        }
458
+        // update stat with new data
459
+        $mTime = time();
460
+        $stat['size'] = (int)$size;
461
+        $stat['mtime'] = $mTime;
462
+        $stat['storage_mtime'] = $mTime;
463
+
464
+        $mimetypeDetector = \OC::$server->getMimeTypeDetector();
465
+        $mimetype = $mimetypeDetector->detectPath($path);
466
+
467
+        $stat['mimetype'] = $mimetype;
468
+        $stat['etag'] = $this->getETag($path);
469
+
470
+        $exists = $this->getCache()->inCache($path);
471
+        $uploadPath = $exists ? $path : $path . '.part';
472
+
473
+        if ($exists) {
474
+            $fileId = $stat['fileid'];
475
+        } else {
476
+            $fileId = $this->getCache()->put($uploadPath, $stat);
477
+        }
478
+
479
+        $urn = $this->getURN($fileId);
480
+        try {
481
+            //upload to object storage
482
+            if ($size === null) {
483
+                $countStream = CountWrapper::wrap($stream, function ($writtenSize) use ($fileId, &$size) {
484
+                    $this->getCache()->update($fileId, [
485
+                        'size' => $writtenSize,
486
+                    ]);
487
+                    $size = $writtenSize;
488
+                });
489
+                $this->objectStore->writeObject($urn, $countStream, $mimetype);
490
+                if (is_resource($countStream)) {
491
+                    fclose($countStream);
492
+                }
493
+                $stat['size'] = $size;
494
+            } else {
495
+                $this->objectStore->writeObject($urn, $stream, $mimetype);
496
+                if (is_resource($stream)) {
497
+                    fclose($stream);
498
+                }
499
+            }
500
+        } catch (\Exception $ex) {
501
+            if (!$exists) {
502
+                /*
503 503
 				 * Only remove the entry if we are dealing with a new file.
504 504
 				 * Else people lose access to existing files
505 505
 				 */
506
-				$this->getCache()->remove($uploadPath);
507
-				$this->logger->logException($ex, [
508
-					'app' => 'objectstore',
509
-					'message' => 'Could not create object ' . $urn . ' for ' . $path,
510
-				]);
511
-			} else {
512
-				$this->logger->logException($ex, [
513
-					'app' => 'objectstore',
514
-					'message' => 'Could not update object ' . $urn . ' for ' . $path,
515
-				]);
516
-			}
517
-			throw $ex; // make this bubble up
518
-		}
519
-
520
-		if ($exists) {
521
-			$this->getCache()->update($fileId, $stat);
522
-		} else {
523
-			if ($this->objectStore->objectExists($urn)) {
524
-				$this->getCache()->move($uploadPath, $path);
525
-			} else {
526
-				$this->getCache()->remove($uploadPath);
527
-				throw new \Exception("Object not found after writing (urn: $urn, path: $path)", 404);
528
-			}
529
-		}
530
-
531
-		return $size;
532
-	}
533
-
534
-	public function getObjectStore(): IObjectStore {
535
-		return $this->objectStore;
536
-	}
537
-
538
-	public function copyFromStorage(IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime = false) {
539
-		if ($sourceStorage->instanceOfStorage(ObjectStoreStorage::class)) {
540
-			/** @var ObjectStoreStorage $sourceStorage */
541
-			if ($sourceStorage->getObjectStore()->getStorageId() === $this->getObjectStore()->getStorageId()) {
542
-				$sourceEntry = $sourceStorage->getCache()->get($sourceInternalPath);
543
-				$this->copyInner($sourceEntry, $targetInternalPath);
544
-				return true;
545
-			}
546
-		}
547
-
548
-		return parent::copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
549
-	}
550
-
551
-	public function copy($path1, $path2) {
552
-		$path1 = $this->normalizePath($path1);
553
-		$path2 = $this->normalizePath($path2);
554
-
555
-		$cache = $this->getCache();
556
-		$sourceEntry = $cache->get($path1);
557
-		if (!$sourceEntry) {
558
-			throw new NotFoundException('Source object not found');
559
-		}
560
-
561
-		$this->copyInner($sourceEntry, $path2);
562
-
563
-		return true;
564
-	}
565
-
566
-	private function copyInner(ICacheEntry $sourceEntry, string $to) {
567
-		$cache = $this->getCache();
568
-
569
-		if ($sourceEntry->getMimeType() === FileInfo::MIMETYPE_FOLDER) {
570
-			if ($cache->inCache($to)) {
571
-				$cache->remove($to);
572
-			}
573
-			$this->mkdir($to);
574
-
575
-			foreach ($cache->getFolderContentsById($sourceEntry->getId()) as $child) {
576
-				$this->copyInner($child, $to . '/' . $child->getName());
577
-			}
578
-		} else {
579
-			$this->copyFile($sourceEntry, $to);
580
-		}
581
-	}
582
-
583
-	private function copyFile(ICacheEntry $sourceEntry, string $to) {
584
-		$cache = $this->getCache();
585
-
586
-		$sourceUrn = $this->getURN($sourceEntry->getId());
587
-
588
-		if (!$cache instanceof Cache) {
589
-			throw new \Exception("Invalid source cache for object store copy");
590
-		}
591
-
592
-		$targetId = $cache->copyFromCache($cache, $sourceEntry, $to);
593
-
594
-		$targetUrn = $this->getURN($targetId);
595
-
596
-		try {
597
-			$this->objectStore->copyObject($sourceUrn, $targetUrn);
598
-		} catch (\Exception $e) {
599
-			$cache->remove($to);
600
-
601
-			throw $e;
602
-		}
603
-	}
506
+                $this->getCache()->remove($uploadPath);
507
+                $this->logger->logException($ex, [
508
+                    'app' => 'objectstore',
509
+                    'message' => 'Could not create object ' . $urn . ' for ' . $path,
510
+                ]);
511
+            } else {
512
+                $this->logger->logException($ex, [
513
+                    'app' => 'objectstore',
514
+                    'message' => 'Could not update object ' . $urn . ' for ' . $path,
515
+                ]);
516
+            }
517
+            throw $ex; // make this bubble up
518
+        }
519
+
520
+        if ($exists) {
521
+            $this->getCache()->update($fileId, $stat);
522
+        } else {
523
+            if ($this->objectStore->objectExists($urn)) {
524
+                $this->getCache()->move($uploadPath, $path);
525
+            } else {
526
+                $this->getCache()->remove($uploadPath);
527
+                throw new \Exception("Object not found after writing (urn: $urn, path: $path)", 404);
528
+            }
529
+        }
530
+
531
+        return $size;
532
+    }
533
+
534
+    public function getObjectStore(): IObjectStore {
535
+        return $this->objectStore;
536
+    }
537
+
538
+    public function copyFromStorage(IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime = false) {
539
+        if ($sourceStorage->instanceOfStorage(ObjectStoreStorage::class)) {
540
+            /** @var ObjectStoreStorage $sourceStorage */
541
+            if ($sourceStorage->getObjectStore()->getStorageId() === $this->getObjectStore()->getStorageId()) {
542
+                $sourceEntry = $sourceStorage->getCache()->get($sourceInternalPath);
543
+                $this->copyInner($sourceEntry, $targetInternalPath);
544
+                return true;
545
+            }
546
+        }
547
+
548
+        return parent::copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
549
+    }
550
+
551
+    public function copy($path1, $path2) {
552
+        $path1 = $this->normalizePath($path1);
553
+        $path2 = $this->normalizePath($path2);
554
+
555
+        $cache = $this->getCache();
556
+        $sourceEntry = $cache->get($path1);
557
+        if (!$sourceEntry) {
558
+            throw new NotFoundException('Source object not found');
559
+        }
560
+
561
+        $this->copyInner($sourceEntry, $path2);
562
+
563
+        return true;
564
+    }
565
+
566
+    private function copyInner(ICacheEntry $sourceEntry, string $to) {
567
+        $cache = $this->getCache();
568
+
569
+        if ($sourceEntry->getMimeType() === FileInfo::MIMETYPE_FOLDER) {
570
+            if ($cache->inCache($to)) {
571
+                $cache->remove($to);
572
+            }
573
+            $this->mkdir($to);
574
+
575
+            foreach ($cache->getFolderContentsById($sourceEntry->getId()) as $child) {
576
+                $this->copyInner($child, $to . '/' . $child->getName());
577
+            }
578
+        } else {
579
+            $this->copyFile($sourceEntry, $to);
580
+        }
581
+    }
582
+
583
+    private function copyFile(ICacheEntry $sourceEntry, string $to) {
584
+        $cache = $this->getCache();
585
+
586
+        $sourceUrn = $this->getURN($sourceEntry->getId());
587
+
588
+        if (!$cache instanceof Cache) {
589
+            throw new \Exception("Invalid source cache for object store copy");
590
+        }
591
+
592
+        $targetId = $cache->copyFromCache($cache, $sourceEntry, $to);
593
+
594
+        $targetUrn = $this->getURN($targetId);
595
+
596
+        try {
597
+            $this->objectStore->copyObject($sourceUrn, $targetUrn);
598
+        } catch (\Exception $e) {
599
+            $cache->remove($to);
600
+
601
+            throw $e;
602
+        }
603
+    }
604 604
 }
Please login to merge, or discard this patch.