Completed
Push — stable9 ( 11047b...318578 )
by Lukas
20:03 queued 09:36
created
lib/private/files/cache/wrapper/cachejail.php 3 patches
Doc Comments   +4 added lines, -1 removed lines patch added patch discarded remove patch
@@ -71,7 +71,7 @@  discard block
 block discarded – undo
71 71
 
72 72
 	/**
73 73
 	 * @param array $entry
74
-	 * @return array
74
+	 * @return string
75 75
 	 */
76 76
 	protected function formatCacheEntry($entry) {
77 77
 		if (isset($entry['path'])) {
@@ -190,6 +190,9 @@  discard block
 block discarded – undo
190 190
 		return $this->cache->getStatus($this->getSourcePath($file));
191 191
 	}
192 192
 
193
+	/**
194
+	 * @param \OCP\Files\Cache\ICacheEntry[] $results
195
+	 */
193 196
 	private function formatSearchResults($results) {
194 197
 		$results = array_filter($results, array($this, 'filterCacheEntry'));
195 198
 		$results = array_values($results);
Please login to merge, or discard this patch.
Indentation   +238 added lines, -238 removed lines patch added patch discarded remove patch
@@ -31,269 +31,269 @@
 block discarded – undo
31 31
  * Jail to a subdirectory of the wrapped cache
32 32
  */
33 33
 class CacheJail extends CacheWrapper {
34
-	/**
35
-	 * @var string
36
-	 */
37
-	protected $root;
34
+    /**
35
+     * @var string
36
+     */
37
+    protected $root;
38 38
 
39
-	/**
40
-	 * @param \OCP\Files\Cache\ICache $cache
41
-	 * @param string $root
42
-	 */
43
-	public function __construct($cache, $root) {
44
-		parent::__construct($cache);
45
-		$this->root = $root;
46
-	}
39
+    /**
40
+     * @param \OCP\Files\Cache\ICache $cache
41
+     * @param string $root
42
+     */
43
+    public function __construct($cache, $root) {
44
+        parent::__construct($cache);
45
+        $this->root = $root;
46
+    }
47 47
 
48
-	protected function getSourcePath($path) {
49
-		if ($path === '') {
50
-			return $this->root;
51
-		} else {
52
-			return $this->root . '/' . ltrim($path, '/');
53
-		}
54
-	}
48
+    protected function getSourcePath($path) {
49
+        if ($path === '') {
50
+            return $this->root;
51
+        } else {
52
+            return $this->root . '/' . ltrim($path, '/');
53
+        }
54
+    }
55 55
 
56
-	/**
57
-	 * @param string $path
58
-	 * @return null|string the jailed path or null if the path is outside the jail
59
-	 */
60
-	protected function getJailedPath($path) {
56
+    /**
57
+     * @param string $path
58
+     * @return null|string the jailed path or null if the path is outside the jail
59
+     */
60
+    protected function getJailedPath($path) {
61 61
 
62
-		if ($this->root === '') {
63
-			return $path;
64
-		}
62
+        if ($this->root === '') {
63
+            return $path;
64
+        }
65 65
 
66
-		$rootLength = strlen($this->root) + 1;
67
-		if ($path === $this->root) {
68
-			return '';
69
-		} else if (substr($path, 0, $rootLength) === $this->root . '/') {
70
-			return substr($path, $rootLength);
71
-		} else {
72
-			return null;
73
-		}
74
-	}
66
+        $rootLength = strlen($this->root) + 1;
67
+        if ($path === $this->root) {
68
+            return '';
69
+        } else if (substr($path, 0, $rootLength) === $this->root . '/') {
70
+            return substr($path, $rootLength);
71
+        } else {
72
+            return null;
73
+        }
74
+    }
75 75
 
76
-	/**
77
-	 * @param array $entry
78
-	 * @return array
79
-	 */
80
-	protected function formatCacheEntry($entry) {
81
-		if (isset($entry['path'])) {
82
-			$entry['path'] = $this->getJailedPath($entry['path']);
83
-		}
84
-		return $entry;
85
-	}
76
+    /**
77
+     * @param array $entry
78
+     * @return array
79
+     */
80
+    protected function formatCacheEntry($entry) {
81
+        if (isset($entry['path'])) {
82
+            $entry['path'] = $this->getJailedPath($entry['path']);
83
+        }
84
+        return $entry;
85
+    }
86 86
 
87
-	protected function filterCacheEntry($entry) {
88
-		$rootLength = strlen($this->root) + 1;
89
-		return ($entry['path'] === $this->root) or (substr($entry['path'], 0, $rootLength) === $this->root . '/');
90
-	}
87
+    protected function filterCacheEntry($entry) {
88
+        $rootLength = strlen($this->root) + 1;
89
+        return ($entry['path'] === $this->root) or (substr($entry['path'], 0, $rootLength) === $this->root . '/');
90
+    }
91 91
 
92
-	/**
93
-	 * get the stored metadata of a file or folder
94
-	 *
95
-	 * @param string /int $file
96
-	 * @return array|false
97
-	 */
98
-	public function get($file) {
99
-		if (is_string($file) or $file == '') {
100
-			$file = $this->getSourcePath($file);
101
-		}
102
-		return parent::get($file);
103
-	}
92
+    /**
93
+     * get the stored metadata of a file or folder
94
+     *
95
+     * @param string /int $file
96
+     * @return array|false
97
+     */
98
+    public function get($file) {
99
+        if (is_string($file) or $file == '') {
100
+            $file = $this->getSourcePath($file);
101
+        }
102
+        return parent::get($file);
103
+    }
104 104
 
105
-	/**
106
-	 * insert meta data for a new file or folder
107
-	 *
108
-	 * @param string $file
109
-	 * @param array $data
110
-	 *
111
-	 * @return int file id
112
-	 * @throws \RuntimeException
113
-	 */
114
-	public function insert($file, array $data) {
115
-		return $this->cache->insert($this->getSourcePath($file), $data);
116
-	}
105
+    /**
106
+     * insert meta data for a new file or folder
107
+     *
108
+     * @param string $file
109
+     * @param array $data
110
+     *
111
+     * @return int file id
112
+     * @throws \RuntimeException
113
+     */
114
+    public function insert($file, array $data) {
115
+        return $this->cache->insert($this->getSourcePath($file), $data);
116
+    }
117 117
 
118
-	/**
119
-	 * update the metadata in the cache
120
-	 *
121
-	 * @param int $id
122
-	 * @param array $data
123
-	 */
124
-	public function update($id, array $data) {
125
-		$this->cache->update($id, $data);
126
-	}
118
+    /**
119
+     * update the metadata in the cache
120
+     *
121
+     * @param int $id
122
+     * @param array $data
123
+     */
124
+    public function update($id, array $data) {
125
+        $this->cache->update($id, $data);
126
+    }
127 127
 
128
-	/**
129
-	 * get the file id for a file
130
-	 *
131
-	 * @param string $file
132
-	 * @return int
133
-	 */
134
-	public function getId($file) {
135
-		return $this->cache->getId($this->getSourcePath($file));
136
-	}
128
+    /**
129
+     * get the file id for a file
130
+     *
131
+     * @param string $file
132
+     * @return int
133
+     */
134
+    public function getId($file) {
135
+        return $this->cache->getId($this->getSourcePath($file));
136
+    }
137 137
 
138
-	/**
139
-	 * get the id of the parent folder of a file
140
-	 *
141
-	 * @param string $file
142
-	 * @return int
143
-	 */
144
-	public function getParentId($file) {
145
-		if ($file === '') {
146
-			return -1;
147
-		} else {
148
-			return $this->cache->getParentId($this->getSourcePath($file));
149
-		}
150
-	}
138
+    /**
139
+     * get the id of the parent folder of a file
140
+     *
141
+     * @param string $file
142
+     * @return int
143
+     */
144
+    public function getParentId($file) {
145
+        if ($file === '') {
146
+            return -1;
147
+        } else {
148
+            return $this->cache->getParentId($this->getSourcePath($file));
149
+        }
150
+    }
151 151
 
152
-	/**
153
-	 * check if a file is available in the cache
154
-	 *
155
-	 * @param string $file
156
-	 * @return bool
157
-	 */
158
-	public function inCache($file) {
159
-		return $this->cache->inCache($this->getSourcePath($file));
160
-	}
152
+    /**
153
+     * check if a file is available in the cache
154
+     *
155
+     * @param string $file
156
+     * @return bool
157
+     */
158
+    public function inCache($file) {
159
+        return $this->cache->inCache($this->getSourcePath($file));
160
+    }
161 161
 
162
-	/**
163
-	 * remove a file or folder from the cache
164
-	 *
165
-	 * @param string $file
166
-	 */
167
-	public function remove($file) {
168
-		$this->cache->remove($this->getSourcePath($file));
169
-	}
162
+    /**
163
+     * remove a file or folder from the cache
164
+     *
165
+     * @param string $file
166
+     */
167
+    public function remove($file) {
168
+        $this->cache->remove($this->getSourcePath($file));
169
+    }
170 170
 
171
-	/**
172
-	 * Move a file or folder in the cache
173
-	 *
174
-	 * @param string $source
175
-	 * @param string $target
176
-	 */
177
-	public function move($source, $target) {
178
-		$this->cache->move($this->getSourcePath($source), $this->getSourcePath($target));
179
-	}
171
+    /**
172
+     * Move a file or folder in the cache
173
+     *
174
+     * @param string $source
175
+     * @param string $target
176
+     */
177
+    public function move($source, $target) {
178
+        $this->cache->move($this->getSourcePath($source), $this->getSourcePath($target));
179
+    }
180 180
 
181
-	/**
182
-	 * remove all entries for files that are stored on the storage from the cache
183
-	 */
184
-	public function clear() {
185
-		$this->cache->remove($this->root);
186
-	}
181
+    /**
182
+     * remove all entries for files that are stored on the storage from the cache
183
+     */
184
+    public function clear() {
185
+        $this->cache->remove($this->root);
186
+    }
187 187
 
188
-	/**
189
-	 * @param string $file
190
-	 *
191
-	 * @return int Cache::NOT_FOUND, Cache::PARTIAL, Cache::SHALLOW or Cache::COMPLETE
192
-	 */
193
-	public function getStatus($file) {
194
-		return $this->cache->getStatus($this->getSourcePath($file));
195
-	}
188
+    /**
189
+     * @param string $file
190
+     *
191
+     * @return int Cache::NOT_FOUND, Cache::PARTIAL, Cache::SHALLOW or Cache::COMPLETE
192
+     */
193
+    public function getStatus($file) {
194
+        return $this->cache->getStatus($this->getSourcePath($file));
195
+    }
196 196
 
197
-	private function formatSearchResults($results) {
198
-		$results = array_filter($results, array($this, 'filterCacheEntry'));
199
-		$results = array_values($results);
200
-		return array_map(array($this, 'formatCacheEntry'), $results);
201
-	}
197
+    private function formatSearchResults($results) {
198
+        $results = array_filter($results, array($this, 'filterCacheEntry'));
199
+        $results = array_values($results);
200
+        return array_map(array($this, 'formatCacheEntry'), $results);
201
+    }
202 202
 
203
-	/**
204
-	 * search for files matching $pattern
205
-	 *
206
-	 * @param string $pattern
207
-	 * @return array an array of file data
208
-	 */
209
-	public function search($pattern) {
210
-		$results = $this->cache->search($pattern);
211
-		return $this->formatSearchResults($results);
212
-	}
203
+    /**
204
+     * search for files matching $pattern
205
+     *
206
+     * @param string $pattern
207
+     * @return array an array of file data
208
+     */
209
+    public function search($pattern) {
210
+        $results = $this->cache->search($pattern);
211
+        return $this->formatSearchResults($results);
212
+    }
213 213
 
214
-	/**
215
-	 * search for files by mimetype
216
-	 *
217
-	 * @param string $mimetype
218
-	 * @return array
219
-	 */
220
-	public function searchByMime($mimetype) {
221
-		$results = $this->cache->searchByMime($mimetype);
222
-		return $this->formatSearchResults($results);
223
-	}
214
+    /**
215
+     * search for files by mimetype
216
+     *
217
+     * @param string $mimetype
218
+     * @return array
219
+     */
220
+    public function searchByMime($mimetype) {
221
+        $results = $this->cache->searchByMime($mimetype);
222
+        return $this->formatSearchResults($results);
223
+    }
224 224
 
225
-	/**
226
-	 * search for files by mimetype
227
-	 *
228
-	 * @param string|int $tag name or tag id
229
-	 * @param string $userId owner of the tags
230
-	 * @return array
231
-	 */
232
-	public function searchByTag($tag, $userId) {
233
-		$results = $this->cache->searchByTag($tag, $userId);
234
-		return $this->formatSearchResults($results);
235
-	}
225
+    /**
226
+     * search for files by mimetype
227
+     *
228
+     * @param string|int $tag name or tag id
229
+     * @param string $userId owner of the tags
230
+     * @return array
231
+     */
232
+    public function searchByTag($tag, $userId) {
233
+        $results = $this->cache->searchByTag($tag, $userId);
234
+        return $this->formatSearchResults($results);
235
+    }
236 236
 
237
-	/**
238
-	 * update the folder size and the size of all parent folders
239
-	 *
240
-	 * @param string|boolean $path
241
-	 * @param array $data (optional) meta data of the folder
242
-	 */
243
-	public function correctFolderSize($path, $data = null) {
244
-		if ($this->cache instanceof Cache) {
245
-			$this->cache->correctFolderSize($this->getSourcePath($path), $data);
246
-		}
247
-	}
237
+    /**
238
+     * update the folder size and the size of all parent folders
239
+     *
240
+     * @param string|boolean $path
241
+     * @param array $data (optional) meta data of the folder
242
+     */
243
+    public function correctFolderSize($path, $data = null) {
244
+        if ($this->cache instanceof Cache) {
245
+            $this->cache->correctFolderSize($this->getSourcePath($path), $data);
246
+        }
247
+    }
248 248
 
249
-	/**
250
-	 * get the size of a folder and set it in the cache
251
-	 *
252
-	 * @param string $path
253
-	 * @param array $entry (optional) meta data of the folder
254
-	 * @return int
255
-	 */
256
-	public function calculateFolderSize($path, $entry = null) {
257
-		if ($this->cache instanceof Cache) {
258
-			return $this->cache->calculateFolderSize($this->getSourcePath($path), $entry);
259
-		} else {
260
-			return 0;
261
-		}
249
+    /**
250
+     * get the size of a folder and set it in the cache
251
+     *
252
+     * @param string $path
253
+     * @param array $entry (optional) meta data of the folder
254
+     * @return int
255
+     */
256
+    public function calculateFolderSize($path, $entry = null) {
257
+        if ($this->cache instanceof Cache) {
258
+            return $this->cache->calculateFolderSize($this->getSourcePath($path), $entry);
259
+        } else {
260
+            return 0;
261
+        }
262 262
 
263
-	}
263
+    }
264 264
 
265
-	/**
266
-	 * get all file ids on the files on the storage
267
-	 *
268
-	 * @return int[]
269
-	 */
270
-	public function getAll() {
271
-		// not supported
272
-		return array();
273
-	}
265
+    /**
266
+     * get all file ids on the files on the storage
267
+     *
268
+     * @return int[]
269
+     */
270
+    public function getAll() {
271
+        // not supported
272
+        return array();
273
+    }
274 274
 
275
-	/**
276
-	 * find a folder in the cache which has not been fully scanned
277
-	 *
278
-	 * If multiply incomplete folders are in the cache, the one with the highest id will be returned,
279
-	 * use the one with the highest id gives the best result with the background scanner, since that is most
280
-	 * likely the folder where we stopped scanning previously
281
-	 *
282
-	 * @return string|bool the path of the folder or false when no folder matched
283
-	 */
284
-	public function getIncomplete() {
285
-		// not supported
286
-		return false;
287
-	}
275
+    /**
276
+     * find a folder in the cache which has not been fully scanned
277
+     *
278
+     * If multiply incomplete folders are in the cache, the one with the highest id will be returned,
279
+     * use the one with the highest id gives the best result with the background scanner, since that is most
280
+     * likely the folder where we stopped scanning previously
281
+     *
282
+     * @return string|bool the path of the folder or false when no folder matched
283
+     */
284
+    public function getIncomplete() {
285
+        // not supported
286
+        return false;
287
+    }
288 288
 
289
-	/**
290
-	 * get the path of a file on this storage by it's id
291
-	 *
292
-	 * @param int $id
293
-	 * @return string|null
294
-	 */
295
-	public function getPathById($id) {
296
-		$path = $this->cache->getPathById($id);
297
-		return $this->getJailedPath($path);
298
-	}
289
+    /**
290
+     * get the path of a file on this storage by it's id
291
+     *
292
+     * @param int $id
293
+     * @return string|null
294
+     */
295
+    public function getPathById($id) {
296
+        $path = $this->cache->getPathById($id);
297
+        return $this->getJailedPath($path);
298
+    }
299 299
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -51,7 +51,7 @@  discard block
 block discarded – undo
51 51
 		if ($path === '') {
52 52
 			return $this->root;
53 53
 		} else {
54
-			return $this->root . '/' . ltrim($path, '/');
54
+			return $this->root.'/'.ltrim($path, '/');
55 55
 		}
56 56
 	}
57 57
 
@@ -66,7 +66,7 @@  discard block
 block discarded – undo
66 66
 		$rootLength = strlen($this->root) + 1;
67 67
 		if ($path === $this->root) {
68 68
 			return '';
69
-		} else if (substr($path, 0, $rootLength) === $this->root . '/') {
69
+		} else if (substr($path, 0, $rootLength) === $this->root.'/') {
70 70
 			return substr($path, $rootLength);
71 71
 		} else {
72 72
 			return null;
@@ -86,7 +86,7 @@  discard block
 block discarded – undo
86 86
 
87 87
 	protected function filterCacheEntry($entry) {
88 88
 		$rootLength = strlen($this->root) + 1;
89
-		return ($entry['path'] === $this->root) or (substr($entry['path'], 0, $rootLength) === $this->root . '/');
89
+		return ($entry['path'] === $this->root) or (substr($entry['path'], 0, $rootLength) === $this->root.'/');
90 90
 	}
91 91
 
92 92
 	/**
Please login to merge, or discard this patch.
lib/private/integritycheck/helpers/fileaccesshelper.php 2 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -53,7 +53,7 @@
 block discarded – undo
53 53
 	 * Wrapper around file_put_contents($filename, $data)
54 54
 	 *
55 55
 	 * @param string $filename
56
-	 * @param $data
56
+	 * @param string $data
57 57
 	 * @return int|false
58 58
 	 */
59 59
 	public function file_put_contents($filename, $data) {
Please login to merge, or discard this patch.
Indentation   +28 added lines, -28 removed lines patch added patch discarded remove patch
@@ -29,34 +29,34 @@
 block discarded – undo
29 29
  * @package OC\IntegrityCheck\Helpers
30 30
  */
31 31
 class FileAccessHelper {
32
-	/**
33
-	 * Wrapper around file_get_contents($filename, $data)
34
-	 *
35
-	 * @param string $filename
36
-	 * @return string|false
37
-	 */
38
-	public function file_get_contents($filename) {
39
-		return file_get_contents($filename);
40
-	}
32
+    /**
33
+     * Wrapper around file_get_contents($filename, $data)
34
+     *
35
+     * @param string $filename
36
+     * @return string|false
37
+     */
38
+    public function file_get_contents($filename) {
39
+        return file_get_contents($filename);
40
+    }
41 41
 
42
-	/**
43
-	 * Wrapper around file_exists($filename)
44
-	 *
45
-	 * @param string $filename
46
-	 * @return bool
47
-	 */
48
-	public function file_exists($filename) {
49
-		return file_exists($filename);
50
-	}
42
+    /**
43
+     * Wrapper around file_exists($filename)
44
+     *
45
+     * @param string $filename
46
+     * @return bool
47
+     */
48
+    public function file_exists($filename) {
49
+        return file_exists($filename);
50
+    }
51 51
 
52
-	/**
53
-	 * Wrapper around file_put_contents($filename, $data)
54
-	 *
55
-	 * @param string $filename
56
-	 * @param $data
57
-	 * @return int|false
58
-	 */
59
-	public function file_put_contents($filename, $data) {
60
-		return file_put_contents($filename, $data);
61
-	}
52
+    /**
53
+     * Wrapper around file_put_contents($filename, $data)
54
+     *
55
+     * @param string $filename
56
+     * @param $data
57
+     * @return int|false
58
+     */
59
+    public function file_put_contents($filename, $data) {
60
+        return file_put_contents($filename, $data);
61
+    }
62 62
 }
Please login to merge, or discard this patch.
lib/private/user/user.php 3 patches
Doc Comments   +4 added lines patch added patch discarded remove patch
@@ -413,6 +413,10 @@
 block discarded – undo
413 413
 		return $url;
414 414
 	}
415 415
 
416
+	/**
417
+	 * @param string $feature
418
+	 * @param string $value
419
+	 */
416 420
 	public function triggerChange($feature, $value = null) {
417 421
 		if ($this->emitter) {
418 422
 			$this->emitter->emit('\OC\User', 'changeUser', array($this, $feature, $value));
Please login to merge, or discard this patch.
Indentation   +382 added lines, -382 removed lines patch added patch discarded remove patch
@@ -40,387 +40,387 @@
 block discarded – undo
40 40
 use OCP\UserInterface;
41 41
 
42 42
 class User implements IUser {
43
-	/** @var string $uid */
44
-	private $uid;
45
-
46
-	/** @var string $displayName */
47
-	private $displayName;
48
-
49
-	/** @var UserInterface $backend */
50
-	private $backend;
51
-
52
-	/** @var bool $enabled */
53
-	private $enabled;
54
-
55
-	/** @var Emitter|Manager $emitter */
56
-	private $emitter;
57
-
58
-	/** @var string $home */
59
-	private $home;
60
-
61
-	/** @var int $lastLogin */
62
-	private $lastLogin;
63
-
64
-	/** @var \OCP\IConfig $config */
65
-	private $config;
66
-
67
-	/** @var IAvatarManager */
68
-	private $avatarManager;
69
-
70
-	/** @var IURLGenerator */
71
-	private $urlGenerator;
72
-
73
-	/**
74
-	 * @param string $uid
75
-	 * @param UserInterface $backend
76
-	 * @param \OC\Hooks\Emitter $emitter
77
-	 * @param IConfig|null $config
78
-	 * @param IURLGenerator $urlGenerator
79
-	 */
80
-	public function __construct($uid, $backend, $emitter = null, IConfig $config = null, $urlGenerator = null) {
81
-		$this->uid = $uid;
82
-		$this->backend = $backend;
83
-		$this->emitter = $emitter;
84
-		if(is_null($config)) {
85
-			$config = \OC::$server->getConfig();
86
-		}
87
-		$this->config = $config;
88
-		$this->urlGenerator = $urlGenerator;
89
-		$enabled = $this->config->getUserValue($uid, 'core', 'enabled', 'true');
90
-		$this->enabled = ($enabled === 'true');
91
-		$this->lastLogin = $this->config->getUserValue($uid, 'login', 'lastLogin', 0);
92
-		if (is_null($this->urlGenerator)) {
93
-			$this->urlGenerator = \OC::$server->getURLGenerator();
94
-		}
95
-	}
96
-
97
-	/**
98
-	 * get the user id
99
-	 *
100
-	 * @return string
101
-	 */
102
-	public function getUID() {
103
-		return $this->uid;
104
-	}
105
-
106
-	/**
107
-	 * get the display name for the user, if no specific display name is set it will fallback to the user id
108
-	 *
109
-	 * @return string
110
-	 */
111
-	public function getDisplayName() {
112
-		if (!isset($this->displayName)) {
113
-			$displayName = '';
114
-			if ($this->backend and $this->backend->implementsActions(\OC_User_Backend::GET_DISPLAYNAME)) {
115
-				// get display name and strip whitespace from the beginning and end of it
116
-				$backendDisplayName = $this->backend->getDisplayName($this->uid);
117
-				if (is_string($backendDisplayName)) {
118
-					$displayName = trim($backendDisplayName);
119
-				}
120
-			}
121
-
122
-			if (!empty($displayName)) {
123
-				$this->displayName = $displayName;
124
-			} else {
125
-				$this->displayName = $this->uid;
126
-			}
127
-		}
128
-		return $this->displayName;
129
-	}
130
-
131
-	/**
132
-	 * set the displayname for the user
133
-	 *
134
-	 * @param string $displayName
135
-	 * @return bool
136
-	 */
137
-	public function setDisplayName($displayName) {
138
-		$displayName = trim($displayName);
139
-		if ($this->backend->implementsActions(\OC_User_Backend::SET_DISPLAYNAME) && !empty($displayName)) {
140
-			$result = $this->backend->setDisplayName($this->uid, $displayName);
141
-			if ($result) {
142
-				$this->displayName = $displayName;
143
-				$this->triggerChange('displayName', $displayName);
144
-			}
145
-			return $result !== false;
146
-		} else {
147
-			return false;
148
-		}
149
-	}
150
-
151
-	/**
152
-	 * set the email address of the user
153
-	 *
154
-	 * @param string|null $mailAddress
155
-	 * @return void
156
-	 * @since 9.0.0
157
-	 */
158
-	public function setEMailAddress($mailAddress) {
159
-		if($mailAddress === '') {
160
-			$this->config->deleteUserValue($this->uid, 'settings', 'email');
161
-		} else {
162
-			$this->config->setUserValue($this->uid, 'settings', 'email', $mailAddress);
163
-		}
164
-		$this->triggerChange('eMailAddress', $mailAddress);
165
-	}
166
-
167
-	/**
168
-	 * returns the timestamp of the user's last login or 0 if the user did never
169
-	 * login
170
-	 *
171
-	 * @return int
172
-	 */
173
-	public function getLastLogin() {
174
-		return $this->lastLogin;
175
-	}
176
-
177
-	/**
178
-	 * updates the timestamp of the most recent login of this user
179
-	 */
180
-	public function updateLastLoginTimestamp() {
181
-		$this->lastLogin = time();
182
-		\OC::$server->getConfig()->setUserValue(
183
-			$this->uid, 'login', 'lastLogin', $this->lastLogin);
184
-	}
185
-
186
-	/**
187
-	 * Delete the user
188
-	 *
189
-	 * @return bool
190
-	 */
191
-	public function delete() {
192
-		if ($this->emitter) {
193
-			$this->emitter->emit('\OC\User', 'preDelete', array($this));
194
-		}
195
-		$result = $this->backend->deleteUser($this->uid);
196
-		if ($result) {
197
-
198
-			// FIXME: Feels like an hack - suggestions?
199
-
200
-			// We have to delete the user from all groups
201
-			foreach (\OC_Group::getUserGroups($this->uid) as $i) {
202
-				\OC_Group::removeFromGroup($this->uid, $i);
203
-			}
204
-			// Delete the user's keys in preferences
205
-			\OC::$server->getConfig()->deleteAllUserValues($this->uid);
206
-
207
-			// Delete user files in /data/
208
-			\OC_Helper::rmdirr(\OC_User::getHome($this->uid));
209
-
210
-			// Delete the users entry in the storage table
211
-			\OC\Files\Cache\Storage::remove('home::' . $this->uid);
212
-
213
-			\OC::$server->getCommentsManager()->deleteReferencesOfActor('users', $this->uid);
214
-			\OC::$server->getCommentsManager()->deleteReadMarksFromUser($this);
215
-
216
-			$notification = \OC::$server->getNotificationManager()->createNotification();
217
-			$notification->setUser($this->uid);
218
-			\OC::$server->getNotificationManager()->markProcessed($notification);
219
-
220
-			if ($this->emitter) {
221
-				$this->emitter->emit('\OC\User', 'postDelete', array($this));
222
-			}
223
-		}
224
-		return !($result === false);
225
-	}
226
-
227
-	/**
228
-	 * Set the password of the user
229
-	 *
230
-	 * @param string $password
231
-	 * @param string $recoveryPassword for the encryption app to reset encryption keys
232
-	 * @return bool
233
-	 */
234
-	public function setPassword($password, $recoveryPassword = null) {
235
-		if ($this->emitter) {
236
-			$this->emitter->emit('\OC\User', 'preSetPassword', array($this, $password, $recoveryPassword));
237
-		}
238
-		if ($this->backend->implementsActions(\OC_User_Backend::SET_PASSWORD)) {
239
-			$result = $this->backend->setPassword($this->uid, $password);
240
-			if ($this->emitter) {
241
-				$this->emitter->emit('\OC\User', 'postSetPassword', array($this, $password, $recoveryPassword));
242
-			}
243
-			return !($result === false);
244
-		} else {
245
-			return false;
246
-		}
247
-	}
248
-
249
-	/**
250
-	 * get the users home folder to mount
251
-	 *
252
-	 * @return string
253
-	 */
254
-	public function getHome() {
255
-		if (!$this->home) {
256
-			if ($this->backend->implementsActions(\OC_User_Backend::GET_HOME) and $home = $this->backend->getHome($this->uid)) {
257
-				$this->home = $home;
258
-			} elseif ($this->config) {
259
-				$this->home = $this->config->getSystemValue('datadirectory') . '/' . $this->uid;
260
-			} else {
261
-				$this->home = \OC::$SERVERROOT . '/data/' . $this->uid;
262
-			}
263
-		}
264
-		return $this->home;
265
-	}
266
-
267
-	/**
268
-	 * Get the name of the backend class the user is connected with
269
-	 *
270
-	 * @return string
271
-	 */
272
-	public function getBackendClassName() {
273
-		if($this->backend instanceof \OCP\IUserBackend) {
274
-			return $this->backend->getBackendName();
275
-		}
276
-		return get_class($this->backend);
277
-	}
278
-
279
-	/**
280
-	 * check if the backend allows the user to change his avatar on Personal page
281
-	 *
282
-	 * @return bool
283
-	 */
284
-	public function canChangeAvatar() {
285
-		if ($this->backend->implementsActions(\OC_User_Backend::PROVIDE_AVATAR)) {
286
-			return $this->backend->canChangeAvatar($this->uid);
287
-		}
288
-		return true;
289
-	}
290
-
291
-	/**
292
-	 * check if the backend supports changing passwords
293
-	 *
294
-	 * @return bool
295
-	 */
296
-	public function canChangePassword() {
297
-		return $this->backend->implementsActions(\OC_User_Backend::SET_PASSWORD);
298
-	}
299
-
300
-	/**
301
-	 * check if the backend supports changing display names
302
-	 *
303
-	 * @return bool
304
-	 */
305
-	public function canChangeDisplayName() {
306
-		if ($this->config->getSystemValue('allow_user_to_change_display_name') === false) {
307
-			return false;
308
-		}
309
-		return $this->backend->implementsActions(\OC_User_Backend::SET_DISPLAYNAME);
310
-	}
311
-
312
-	/**
313
-	 * check if the user is enabled
314
-	 *
315
-	 * @return bool
316
-	 */
317
-	public function isEnabled() {
318
-		return $this->enabled;
319
-	}
320
-
321
-	/**
322
-	 * set the enabled status for the user
323
-	 *
324
-	 * @param bool $enabled
325
-	 */
326
-	public function setEnabled($enabled) {
327
-		$this->enabled = $enabled;
328
-		$enabled = ($enabled) ? 'true' : 'false';
329
-		$this->config->setUserValue($this->uid, 'core', 'enabled', $enabled);
330
-	}
331
-
332
-	/**
333
-	 * get the users email address
334
-	 *
335
-	 * @return string|null
336
-	 * @since 9.0.0
337
-	 */
338
-	public function getEMailAddress() {
339
-		return $this->config->getUserValue($this->uid, 'settings', 'email', null);
340
-	}
341
-
342
-	/**
343
-	 * get the users' quota
344
-	 *
345
-	 * @return string
346
-	 * @since 9.0.0
347
-	 */
348
-	public function getQuota() {
349
-		$quota = $this->config->getUserValue($this->uid, 'files', 'quota', 'default');
350
-		if($quota === 'default') {
351
-			$quota = $this->config->getAppValue('files', 'default_quota', 'none');
352
-		}
353
-		return $quota;
354
-	}
355
-
356
-	/**
357
-	 * set the users' quota
358
-	 *
359
-	 * @param string $quota
360
-	 * @return void
361
-	 * @since 9.0.0
362
-	 */
363
-	public function setQuota($quota) {
364
-		if($quota !== 'none' and $quota !== 'default') {
365
-			$quota = OC_Helper::computerFileSize($quota);
366
-			$quota = OC_Helper::humanFileSize($quota);
367
-		}
368
-		$this->config->setUserValue($this->uid, 'files', 'quota', $quota);
369
-		$this->triggerChange('quota', $quota);
370
-	}
371
-
372
-	/**
373
-	 * get the avatar image if it exists
374
-	 *
375
-	 * @param int $size
376
-	 * @return IImage|null
377
-	 * @since 9.0.0
378
-	 */
379
-	public function getAvatarImage($size) {
380
-		// delay the initialization
381
-		if (is_null($this->avatarManager)) {
382
-			$this->avatarManager = \OC::$server->getAvatarManager();
383
-		}
384
-
385
-		$avatar = $this->avatarManager->getAvatar($this->uid);
386
-		$image = $avatar->get(-1);
387
-		if ($image) {
388
-			return $image;
389
-		}
390
-
391
-		return null;
392
-	}
393
-
394
-	/**
395
-	 * get the federation cloud id
396
-	 *
397
-	 * @return string
398
-	 * @since 9.0.0
399
-	 */
400
-	public function getCloudId() {
401
-		$uid = $this->getUID();
402
-		$server = $this->urlGenerator->getAbsoluteURL('/');
403
-		return $uid . '@' . rtrim( $this->removeProtocolFromUrl($server), '/');
404
-	}
405
-
406
-	/**
407
-	 * @param string $url
408
-	 * @return string
409
-	 */
410
-	private function removeProtocolFromUrl($url) {
411
-		if (strpos($url, 'https://') === 0) {
412
-			return substr($url, strlen('https://'));
413
-		} else if (strpos($url, 'http://') === 0) {
414
-			return substr($url, strlen('http://'));
415
-		}
416
-
417
-		return $url;
418
-	}
419
-
420
-	public function triggerChange($feature, $value = null) {
421
-		if ($this->emitter) {
422
-			$this->emitter->emit('\OC\User', 'changeUser', array($this, $feature, $value));
423
-		}
424
-	}
43
+    /** @var string $uid */
44
+    private $uid;
45
+
46
+    /** @var string $displayName */
47
+    private $displayName;
48
+
49
+    /** @var UserInterface $backend */
50
+    private $backend;
51
+
52
+    /** @var bool $enabled */
53
+    private $enabled;
54
+
55
+    /** @var Emitter|Manager $emitter */
56
+    private $emitter;
57
+
58
+    /** @var string $home */
59
+    private $home;
60
+
61
+    /** @var int $lastLogin */
62
+    private $lastLogin;
63
+
64
+    /** @var \OCP\IConfig $config */
65
+    private $config;
66
+
67
+    /** @var IAvatarManager */
68
+    private $avatarManager;
69
+
70
+    /** @var IURLGenerator */
71
+    private $urlGenerator;
72
+
73
+    /**
74
+     * @param string $uid
75
+     * @param UserInterface $backend
76
+     * @param \OC\Hooks\Emitter $emitter
77
+     * @param IConfig|null $config
78
+     * @param IURLGenerator $urlGenerator
79
+     */
80
+    public function __construct($uid, $backend, $emitter = null, IConfig $config = null, $urlGenerator = null) {
81
+        $this->uid = $uid;
82
+        $this->backend = $backend;
83
+        $this->emitter = $emitter;
84
+        if(is_null($config)) {
85
+            $config = \OC::$server->getConfig();
86
+        }
87
+        $this->config = $config;
88
+        $this->urlGenerator = $urlGenerator;
89
+        $enabled = $this->config->getUserValue($uid, 'core', 'enabled', 'true');
90
+        $this->enabled = ($enabled === 'true');
91
+        $this->lastLogin = $this->config->getUserValue($uid, 'login', 'lastLogin', 0);
92
+        if (is_null($this->urlGenerator)) {
93
+            $this->urlGenerator = \OC::$server->getURLGenerator();
94
+        }
95
+    }
96
+
97
+    /**
98
+     * get the user id
99
+     *
100
+     * @return string
101
+     */
102
+    public function getUID() {
103
+        return $this->uid;
104
+    }
105
+
106
+    /**
107
+     * get the display name for the user, if no specific display name is set it will fallback to the user id
108
+     *
109
+     * @return string
110
+     */
111
+    public function getDisplayName() {
112
+        if (!isset($this->displayName)) {
113
+            $displayName = '';
114
+            if ($this->backend and $this->backend->implementsActions(\OC_User_Backend::GET_DISPLAYNAME)) {
115
+                // get display name and strip whitespace from the beginning and end of it
116
+                $backendDisplayName = $this->backend->getDisplayName($this->uid);
117
+                if (is_string($backendDisplayName)) {
118
+                    $displayName = trim($backendDisplayName);
119
+                }
120
+            }
121
+
122
+            if (!empty($displayName)) {
123
+                $this->displayName = $displayName;
124
+            } else {
125
+                $this->displayName = $this->uid;
126
+            }
127
+        }
128
+        return $this->displayName;
129
+    }
130
+
131
+    /**
132
+     * set the displayname for the user
133
+     *
134
+     * @param string $displayName
135
+     * @return bool
136
+     */
137
+    public function setDisplayName($displayName) {
138
+        $displayName = trim($displayName);
139
+        if ($this->backend->implementsActions(\OC_User_Backend::SET_DISPLAYNAME) && !empty($displayName)) {
140
+            $result = $this->backend->setDisplayName($this->uid, $displayName);
141
+            if ($result) {
142
+                $this->displayName = $displayName;
143
+                $this->triggerChange('displayName', $displayName);
144
+            }
145
+            return $result !== false;
146
+        } else {
147
+            return false;
148
+        }
149
+    }
150
+
151
+    /**
152
+     * set the email address of the user
153
+     *
154
+     * @param string|null $mailAddress
155
+     * @return void
156
+     * @since 9.0.0
157
+     */
158
+    public function setEMailAddress($mailAddress) {
159
+        if($mailAddress === '') {
160
+            $this->config->deleteUserValue($this->uid, 'settings', 'email');
161
+        } else {
162
+            $this->config->setUserValue($this->uid, 'settings', 'email', $mailAddress);
163
+        }
164
+        $this->triggerChange('eMailAddress', $mailAddress);
165
+    }
166
+
167
+    /**
168
+     * returns the timestamp of the user's last login or 0 if the user did never
169
+     * login
170
+     *
171
+     * @return int
172
+     */
173
+    public function getLastLogin() {
174
+        return $this->lastLogin;
175
+    }
176
+
177
+    /**
178
+     * updates the timestamp of the most recent login of this user
179
+     */
180
+    public function updateLastLoginTimestamp() {
181
+        $this->lastLogin = time();
182
+        \OC::$server->getConfig()->setUserValue(
183
+            $this->uid, 'login', 'lastLogin', $this->lastLogin);
184
+    }
185
+
186
+    /**
187
+     * Delete the user
188
+     *
189
+     * @return bool
190
+     */
191
+    public function delete() {
192
+        if ($this->emitter) {
193
+            $this->emitter->emit('\OC\User', 'preDelete', array($this));
194
+        }
195
+        $result = $this->backend->deleteUser($this->uid);
196
+        if ($result) {
197
+
198
+            // FIXME: Feels like an hack - suggestions?
199
+
200
+            // We have to delete the user from all groups
201
+            foreach (\OC_Group::getUserGroups($this->uid) as $i) {
202
+                \OC_Group::removeFromGroup($this->uid, $i);
203
+            }
204
+            // Delete the user's keys in preferences
205
+            \OC::$server->getConfig()->deleteAllUserValues($this->uid);
206
+
207
+            // Delete user files in /data/
208
+            \OC_Helper::rmdirr(\OC_User::getHome($this->uid));
209
+
210
+            // Delete the users entry in the storage table
211
+            \OC\Files\Cache\Storage::remove('home::' . $this->uid);
212
+
213
+            \OC::$server->getCommentsManager()->deleteReferencesOfActor('users', $this->uid);
214
+            \OC::$server->getCommentsManager()->deleteReadMarksFromUser($this);
215
+
216
+            $notification = \OC::$server->getNotificationManager()->createNotification();
217
+            $notification->setUser($this->uid);
218
+            \OC::$server->getNotificationManager()->markProcessed($notification);
219
+
220
+            if ($this->emitter) {
221
+                $this->emitter->emit('\OC\User', 'postDelete', array($this));
222
+            }
223
+        }
224
+        return !($result === false);
225
+    }
226
+
227
+    /**
228
+     * Set the password of the user
229
+     *
230
+     * @param string $password
231
+     * @param string $recoveryPassword for the encryption app to reset encryption keys
232
+     * @return bool
233
+     */
234
+    public function setPassword($password, $recoveryPassword = null) {
235
+        if ($this->emitter) {
236
+            $this->emitter->emit('\OC\User', 'preSetPassword', array($this, $password, $recoveryPassword));
237
+        }
238
+        if ($this->backend->implementsActions(\OC_User_Backend::SET_PASSWORD)) {
239
+            $result = $this->backend->setPassword($this->uid, $password);
240
+            if ($this->emitter) {
241
+                $this->emitter->emit('\OC\User', 'postSetPassword', array($this, $password, $recoveryPassword));
242
+            }
243
+            return !($result === false);
244
+        } else {
245
+            return false;
246
+        }
247
+    }
248
+
249
+    /**
250
+     * get the users home folder to mount
251
+     *
252
+     * @return string
253
+     */
254
+    public function getHome() {
255
+        if (!$this->home) {
256
+            if ($this->backend->implementsActions(\OC_User_Backend::GET_HOME) and $home = $this->backend->getHome($this->uid)) {
257
+                $this->home = $home;
258
+            } elseif ($this->config) {
259
+                $this->home = $this->config->getSystemValue('datadirectory') . '/' . $this->uid;
260
+            } else {
261
+                $this->home = \OC::$SERVERROOT . '/data/' . $this->uid;
262
+            }
263
+        }
264
+        return $this->home;
265
+    }
266
+
267
+    /**
268
+     * Get the name of the backend class the user is connected with
269
+     *
270
+     * @return string
271
+     */
272
+    public function getBackendClassName() {
273
+        if($this->backend instanceof \OCP\IUserBackend) {
274
+            return $this->backend->getBackendName();
275
+        }
276
+        return get_class($this->backend);
277
+    }
278
+
279
+    /**
280
+     * check if the backend allows the user to change his avatar on Personal page
281
+     *
282
+     * @return bool
283
+     */
284
+    public function canChangeAvatar() {
285
+        if ($this->backend->implementsActions(\OC_User_Backend::PROVIDE_AVATAR)) {
286
+            return $this->backend->canChangeAvatar($this->uid);
287
+        }
288
+        return true;
289
+    }
290
+
291
+    /**
292
+     * check if the backend supports changing passwords
293
+     *
294
+     * @return bool
295
+     */
296
+    public function canChangePassword() {
297
+        return $this->backend->implementsActions(\OC_User_Backend::SET_PASSWORD);
298
+    }
299
+
300
+    /**
301
+     * check if the backend supports changing display names
302
+     *
303
+     * @return bool
304
+     */
305
+    public function canChangeDisplayName() {
306
+        if ($this->config->getSystemValue('allow_user_to_change_display_name') === false) {
307
+            return false;
308
+        }
309
+        return $this->backend->implementsActions(\OC_User_Backend::SET_DISPLAYNAME);
310
+    }
311
+
312
+    /**
313
+     * check if the user is enabled
314
+     *
315
+     * @return bool
316
+     */
317
+    public function isEnabled() {
318
+        return $this->enabled;
319
+    }
320
+
321
+    /**
322
+     * set the enabled status for the user
323
+     *
324
+     * @param bool $enabled
325
+     */
326
+    public function setEnabled($enabled) {
327
+        $this->enabled = $enabled;
328
+        $enabled = ($enabled) ? 'true' : 'false';
329
+        $this->config->setUserValue($this->uid, 'core', 'enabled', $enabled);
330
+    }
331
+
332
+    /**
333
+     * get the users email address
334
+     *
335
+     * @return string|null
336
+     * @since 9.0.0
337
+     */
338
+    public function getEMailAddress() {
339
+        return $this->config->getUserValue($this->uid, 'settings', 'email', null);
340
+    }
341
+
342
+    /**
343
+     * get the users' quota
344
+     *
345
+     * @return string
346
+     * @since 9.0.0
347
+     */
348
+    public function getQuota() {
349
+        $quota = $this->config->getUserValue($this->uid, 'files', 'quota', 'default');
350
+        if($quota === 'default') {
351
+            $quota = $this->config->getAppValue('files', 'default_quota', 'none');
352
+        }
353
+        return $quota;
354
+    }
355
+
356
+    /**
357
+     * set the users' quota
358
+     *
359
+     * @param string $quota
360
+     * @return void
361
+     * @since 9.0.0
362
+     */
363
+    public function setQuota($quota) {
364
+        if($quota !== 'none' and $quota !== 'default') {
365
+            $quota = OC_Helper::computerFileSize($quota);
366
+            $quota = OC_Helper::humanFileSize($quota);
367
+        }
368
+        $this->config->setUserValue($this->uid, 'files', 'quota', $quota);
369
+        $this->triggerChange('quota', $quota);
370
+    }
371
+
372
+    /**
373
+     * get the avatar image if it exists
374
+     *
375
+     * @param int $size
376
+     * @return IImage|null
377
+     * @since 9.0.0
378
+     */
379
+    public function getAvatarImage($size) {
380
+        // delay the initialization
381
+        if (is_null($this->avatarManager)) {
382
+            $this->avatarManager = \OC::$server->getAvatarManager();
383
+        }
384
+
385
+        $avatar = $this->avatarManager->getAvatar($this->uid);
386
+        $image = $avatar->get(-1);
387
+        if ($image) {
388
+            return $image;
389
+        }
390
+
391
+        return null;
392
+    }
393
+
394
+    /**
395
+     * get the federation cloud id
396
+     *
397
+     * @return string
398
+     * @since 9.0.0
399
+     */
400
+    public function getCloudId() {
401
+        $uid = $this->getUID();
402
+        $server = $this->urlGenerator->getAbsoluteURL('/');
403
+        return $uid . '@' . rtrim( $this->removeProtocolFromUrl($server), '/');
404
+    }
405
+
406
+    /**
407
+     * @param string $url
408
+     * @return string
409
+     */
410
+    private function removeProtocolFromUrl($url) {
411
+        if (strpos($url, 'https://') === 0) {
412
+            return substr($url, strlen('https://'));
413
+        } else if (strpos($url, 'http://') === 0) {
414
+            return substr($url, strlen('http://'));
415
+        }
416
+
417
+        return $url;
418
+    }
419
+
420
+    public function triggerChange($feature, $value = null) {
421
+        if ($this->emitter) {
422
+            $this->emitter->emit('\OC\User', 'changeUser', array($this, $feature, $value));
423
+        }
424
+    }
425 425
 
426 426
 }
Please login to merge, or discard this patch.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -81,7 +81,7 @@  discard block
 block discarded – undo
81 81
 		$this->uid = $uid;
82 82
 		$this->backend = $backend;
83 83
 		$this->emitter = $emitter;
84
-		if(is_null($config)) {
84
+		if (is_null($config)) {
85 85
 			$config = \OC::$server->getConfig();
86 86
 		}
87 87
 		$this->config = $config;
@@ -156,7 +156,7 @@  discard block
 block discarded – undo
156 156
 	 * @since 9.0.0
157 157
 	 */
158 158
 	public function setEMailAddress($mailAddress) {
159
-		if($mailAddress === '') {
159
+		if ($mailAddress === '') {
160 160
 			$this->config->deleteUserValue($this->uid, 'settings', 'email');
161 161
 		} else {
162 162
 			$this->config->setUserValue($this->uid, 'settings', 'email', $mailAddress);
@@ -208,7 +208,7 @@  discard block
 block discarded – undo
208 208
 			\OC_Helper::rmdirr(\OC_User::getHome($this->uid));
209 209
 
210 210
 			// Delete the users entry in the storage table
211
-			\OC\Files\Cache\Storage::remove('home::' . $this->uid);
211
+			\OC\Files\Cache\Storage::remove('home::'.$this->uid);
212 212
 
213 213
 			\OC::$server->getCommentsManager()->deleteReferencesOfActor('users', $this->uid);
214 214
 			\OC::$server->getCommentsManager()->deleteReadMarksFromUser($this);
@@ -256,9 +256,9 @@  discard block
 block discarded – undo
256 256
 			if ($this->backend->implementsActions(\OC_User_Backend::GET_HOME) and $home = $this->backend->getHome($this->uid)) {
257 257
 				$this->home = $home;
258 258
 			} elseif ($this->config) {
259
-				$this->home = $this->config->getSystemValue('datadirectory') . '/' . $this->uid;
259
+				$this->home = $this->config->getSystemValue('datadirectory').'/'.$this->uid;
260 260
 			} else {
261
-				$this->home = \OC::$SERVERROOT . '/data/' . $this->uid;
261
+				$this->home = \OC::$SERVERROOT.'/data/'.$this->uid;
262 262
 			}
263 263
 		}
264 264
 		return $this->home;
@@ -270,7 +270,7 @@  discard block
 block discarded – undo
270 270
 	 * @return string
271 271
 	 */
272 272
 	public function getBackendClassName() {
273
-		if($this->backend instanceof \OCP\IUserBackend) {
273
+		if ($this->backend instanceof \OCP\IUserBackend) {
274 274
 			return $this->backend->getBackendName();
275 275
 		}
276 276
 		return get_class($this->backend);
@@ -347,7 +347,7 @@  discard block
 block discarded – undo
347 347
 	 */
348 348
 	public function getQuota() {
349 349
 		$quota = $this->config->getUserValue($this->uid, 'files', 'quota', 'default');
350
-		if($quota === 'default') {
350
+		if ($quota === 'default') {
351 351
 			$quota = $this->config->getAppValue('files', 'default_quota', 'none');
352 352
 		}
353 353
 		return $quota;
@@ -361,7 +361,7 @@  discard block
 block discarded – undo
361 361
 	 * @since 9.0.0
362 362
 	 */
363 363
 	public function setQuota($quota) {
364
-		if($quota !== 'none' and $quota !== 'default') {
364
+		if ($quota !== 'none' and $quota !== 'default') {
365 365
 			$quota = OC_Helper::computerFileSize($quota);
366 366
 			$quota = OC_Helper::humanFileSize($quota);
367 367
 		}
@@ -400,7 +400,7 @@  discard block
 block discarded – undo
400 400
 	public function getCloudId() {
401 401
 		$uid = $this->getUID();
402 402
 		$server = $this->urlGenerator->getAbsoluteURL('/');
403
-		return $uid . '@' . rtrim( $this->removeProtocolFromUrl($server), '/');
403
+		return $uid.'@'.rtrim($this->removeProtocolFromUrl($server), '/');
404 404
 	}
405 405
 
406 406
 	/**
Please login to merge, or discard this patch.
apps/dav/lib/carddav/xml/groups.php 3 patches
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -21,7 +21,6 @@
 block discarded – undo
21 21
 namespace OCA\DAV\CardDAV\Xml;
22 22
 
23 23
 use Sabre\Xml\XmlSerializable;
24
-use Sabre\Xml\Element;
25 24
 use Sabre\Xml\Writer;
26 25
 
27 26
 class Groups implements XmlSerializable {
Please login to merge, or discard this patch.
Indentation   +14 added lines, -14 removed lines patch added patch discarded remove patch
@@ -26,21 +26,21 @@
 block discarded – undo
26 26
 use Sabre\Xml\Writer;
27 27
 
28 28
 class Groups implements XmlSerializable {
29
-	const NS_OWNCLOUD = 'http://owncloud.org/ns';
29
+    const NS_OWNCLOUD = 'http://owncloud.org/ns';
30 30
 
31
-	/** @var string[] of TYPE:CHECKSUM */
32
-	private $groups;
31
+    /** @var string[] of TYPE:CHECKSUM */
32
+    private $groups;
33 33
 
34
-	/**
35
-	 * @param string $groups
36
-	 */
37
-	public function __construct($groups) {
38
-		$this->groups = $groups;
39
-	}
34
+    /**
35
+     * @param string $groups
36
+     */
37
+    public function __construct($groups) {
38
+        $this->groups = $groups;
39
+    }
40 40
 
41
-	function xmlSerialize(Writer $writer) {
42
-		foreach ($this->groups as $group) {
43
-			$writer->writeElement('{' . self::NS_OWNCLOUD . '}group', $group);
44
-		}
45
-	}
41
+    function xmlSerialize(Writer $writer) {
42
+        foreach ($this->groups as $group) {
43
+            $writer->writeElement('{' . self::NS_OWNCLOUD . '}group', $group);
44
+        }
45
+    }
46 46
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -40,7 +40,7 @@
 block discarded – undo
40 40
 
41 41
 	function xmlSerialize(Writer $writer) {
42 42
 		foreach ($this->groups as $group) {
43
-			$writer->writeElement('{' . self::NS_OWNCLOUD . '}group', $group);
43
+			$writer->writeElement('{'.self::NS_OWNCLOUD.'}group', $group);
44 44
 		}
45 45
 	}
46 46
 }
Please login to merge, or discard this patch.
apps/dav/lib/comments/commentnode.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -93,7 +93,7 @@
 block discarded – undo
93 93
 	/**
94 94
 	 * returns a list of all possible property names
95 95
 	 *
96
-	 * @return array
96
+	 * @return string[]
97 97
 	 */
98 98
 	static public function getPropertyNames() {
99 99
 		return [
Please login to merge, or discard this patch.
Indentation   +202 added lines, -202 removed lines patch added patch discarded remove patch
@@ -35,228 +35,228 @@
 block discarded – undo
35 35
 use Sabre\DAV\PropPatch;
36 36
 
37 37
 class CommentNode implements \Sabre\DAV\INode, \Sabre\DAV\IProperties {
38
-	const NS_OWNCLOUD = 'http://owncloud.org/ns';
38
+    const NS_OWNCLOUD = 'http://owncloud.org/ns';
39 39
 
40
-	const PROPERTY_NAME_UNREAD = '{http://owncloud.org/ns}isUnread';
41
-	const PROPERTY_NAME_MESSAGE = '{http://owncloud.org/ns}message';
42
-	const PROPERTY_NAME_ACTOR_DISPLAYNAME = '{http://owncloud.org/ns}actorDisplayName';
40
+    const PROPERTY_NAME_UNREAD = '{http://owncloud.org/ns}isUnread';
41
+    const PROPERTY_NAME_MESSAGE = '{http://owncloud.org/ns}message';
42
+    const PROPERTY_NAME_ACTOR_DISPLAYNAME = '{http://owncloud.org/ns}actorDisplayName';
43 43
 
44
-	/** @var  IComment */
45
-	public $comment;
44
+    /** @var  IComment */
45
+    public $comment;
46 46
 
47
-	/** @var ICommentsManager */
48
-	protected $commentsManager;
47
+    /** @var ICommentsManager */
48
+    protected $commentsManager;
49 49
 
50
-	/** @var  ILogger */
51
-	protected $logger;
50
+    /** @var  ILogger */
51
+    protected $logger;
52 52
 
53
-	/** @var array list of properties with key being their name and value their setter */
54
-	protected $properties = [];
53
+    /** @var array list of properties with key being their name and value their setter */
54
+    protected $properties = [];
55 55
 
56
-	/** @var IUserManager */
57
-	protected $userManager;
56
+    /** @var IUserManager */
57
+    protected $userManager;
58 58
 
59
-	/** @var IUserSession */
60
-	protected $userSession;
59
+    /** @var IUserSession */
60
+    protected $userSession;
61 61
 
62
-	/**
63
-	 * CommentNode constructor.
64
-	 *
65
-	 * @param ICommentsManager $commentsManager
66
-	 * @param IComment $comment
67
-	 * @param IUserManager $userManager
68
-	 * @param IUserSession $userSession
69
-	 * @param ILogger $logger
70
-	 */
71
-	public function __construct(
72
-		ICommentsManager $commentsManager,
73
-		IComment $comment,
74
-		IUserManager $userManager,
75
-		IUserSession $userSession,
76
-		ILogger $logger
77
-	) {
78
-		$this->commentsManager = $commentsManager;
79
-		$this->comment = $comment;
80
-		$this->logger = $logger;
62
+    /**
63
+     * CommentNode constructor.
64
+     *
65
+     * @param ICommentsManager $commentsManager
66
+     * @param IComment $comment
67
+     * @param IUserManager $userManager
68
+     * @param IUserSession $userSession
69
+     * @param ILogger $logger
70
+     */
71
+    public function __construct(
72
+        ICommentsManager $commentsManager,
73
+        IComment $comment,
74
+        IUserManager $userManager,
75
+        IUserSession $userSession,
76
+        ILogger $logger
77
+    ) {
78
+        $this->commentsManager = $commentsManager;
79
+        $this->comment = $comment;
80
+        $this->logger = $logger;
81 81
 
82
-		$methods = get_class_methods($this->comment);
83
-		$methods = array_filter($methods, function($name){
84
-			return strpos($name, 'get') === 0;
85
-		});
86
-		foreach($methods as $getter) {
87
-			$name = '{'.self::NS_OWNCLOUD.'}' . lcfirst(substr($getter, 3));
88
-			$this->properties[$name] = $getter;
89
-		}
90
-		$this->userManager = $userManager;
91
-		$this->userSession = $userSession;
92
-	}
82
+        $methods = get_class_methods($this->comment);
83
+        $methods = array_filter($methods, function($name){
84
+            return strpos($name, 'get') === 0;
85
+        });
86
+        foreach($methods as $getter) {
87
+            $name = '{'.self::NS_OWNCLOUD.'}' . lcfirst(substr($getter, 3));
88
+            $this->properties[$name] = $getter;
89
+        }
90
+        $this->userManager = $userManager;
91
+        $this->userSession = $userSession;
92
+    }
93 93
 
94
-	/**
95
-	 * returns a list of all possible property names
96
-	 *
97
-	 * @return array
98
-	 */
99
-	static public function getPropertyNames() {
100
-		return [
101
-			'{http://owncloud.org/ns}id',
102
-			'{http://owncloud.org/ns}parentId',
103
-			'{http://owncloud.org/ns}topmostParentId',
104
-			'{http://owncloud.org/ns}childrenCount',
105
-			'{http://owncloud.org/ns}verb',
106
-			'{http://owncloud.org/ns}actorType',
107
-			'{http://owncloud.org/ns}actorId',
108
-			'{http://owncloud.org/ns}creationDateTime',
109
-			'{http://owncloud.org/ns}latestChildDateTime',
110
-			'{http://owncloud.org/ns}objectType',
111
-			'{http://owncloud.org/ns}objectId',
112
-			// re-used property names are defined as constants
113
-			self::PROPERTY_NAME_MESSAGE,
114
-			self::PROPERTY_NAME_ACTOR_DISPLAYNAME,
115
-			self::PROPERTY_NAME_UNREAD
116
-		];
117
-	}
94
+    /**
95
+     * returns a list of all possible property names
96
+     *
97
+     * @return array
98
+     */
99
+    static public function getPropertyNames() {
100
+        return [
101
+            '{http://owncloud.org/ns}id',
102
+            '{http://owncloud.org/ns}parentId',
103
+            '{http://owncloud.org/ns}topmostParentId',
104
+            '{http://owncloud.org/ns}childrenCount',
105
+            '{http://owncloud.org/ns}verb',
106
+            '{http://owncloud.org/ns}actorType',
107
+            '{http://owncloud.org/ns}actorId',
108
+            '{http://owncloud.org/ns}creationDateTime',
109
+            '{http://owncloud.org/ns}latestChildDateTime',
110
+            '{http://owncloud.org/ns}objectType',
111
+            '{http://owncloud.org/ns}objectId',
112
+            // re-used property names are defined as constants
113
+            self::PROPERTY_NAME_MESSAGE,
114
+            self::PROPERTY_NAME_ACTOR_DISPLAYNAME,
115
+            self::PROPERTY_NAME_UNREAD
116
+        ];
117
+    }
118 118
 
119
-	protected function checkWriteAccessOnComment() {
120
-		$user = $this->userSession->getUser();
121
-		if(    $this->comment->getActorType() !== 'users'
122
-			|| is_null($user)
123
-			|| $this->comment->getActorId() !== $user->getUID()
124
-		) {
125
-			throw new Forbidden('Only authors are allowed to edit their comment.');
126
-		}
127
-	}
119
+    protected function checkWriteAccessOnComment() {
120
+        $user = $this->userSession->getUser();
121
+        if(    $this->comment->getActorType() !== 'users'
122
+            || is_null($user)
123
+            || $this->comment->getActorId() !== $user->getUID()
124
+        ) {
125
+            throw new Forbidden('Only authors are allowed to edit their comment.');
126
+        }
127
+    }
128 128
 
129
-	/**
130
-	 * Deleted the current node
131
-	 *
132
-	 * @return void
133
-	 */
134
-	function delete() {
135
-		$this->checkWriteAccessOnComment();
136
-		$this->commentsManager->delete($this->comment->getId());
137
-	}
129
+    /**
130
+     * Deleted the current node
131
+     *
132
+     * @return void
133
+     */
134
+    function delete() {
135
+        $this->checkWriteAccessOnComment();
136
+        $this->commentsManager->delete($this->comment->getId());
137
+    }
138 138
 
139
-	/**
140
-	 * Returns the name of the node.
141
-	 *
142
-	 * This is used to generate the url.
143
-	 *
144
-	 * @return string
145
-	 */
146
-	function getName() {
147
-		return $this->comment->getId();
148
-	}
139
+    /**
140
+     * Returns the name of the node.
141
+     *
142
+     * This is used to generate the url.
143
+     *
144
+     * @return string
145
+     */
146
+    function getName() {
147
+        return $this->comment->getId();
148
+    }
149 149
 
150
-	/**
151
-	 * Renames the node
152
-	 *
153
-	 * @param string $name The new name
154
-	 * @throws MethodNotAllowed
155
-	 */
156
-	function setName($name) {
157
-		throw new MethodNotAllowed();
158
-	}
150
+    /**
151
+     * Renames the node
152
+     *
153
+     * @param string $name The new name
154
+     * @throws MethodNotAllowed
155
+     */
156
+    function setName($name) {
157
+        throw new MethodNotAllowed();
158
+    }
159 159
 
160
-	/**
161
-	 * Returns the last modification time, as a unix timestamp
162
-	 *
163
-	 * @return int
164
-	 */
165
-	function getLastModified() {
166
-		return null;
167
-	}
160
+    /**
161
+     * Returns the last modification time, as a unix timestamp
162
+     *
163
+     * @return int
164
+     */
165
+    function getLastModified() {
166
+        return null;
167
+    }
168 168
 
169
-	/**
170
-	 * update the comment's message
171
-	 *
172
-	 * @param $propertyValue
173
-	 * @return bool
174
-	 * @throws BadRequest
175
-	 * @throws Forbidden
176
-	 */
177
-	public function updateComment($propertyValue) {
178
-		$this->checkWriteAccessOnComment();
179
-		try {
180
-			$this->comment->setMessage($propertyValue);
181
-			$this->commentsManager->save($this->comment);
182
-			return true;
183
-		} catch (\Exception $e) {
184
-			$this->logger->logException($e, ['app' => 'dav/comments']);
185
-			if($e instanceof MessageTooLongException) {
186
-				$msg = 'Message exceeds allowed character limit of ';
187
-				throw new BadRequest($msg . IComment::MAX_MESSAGE_LENGTH, 0, $e);
188
-			}
189
-			return false;
190
-		}
191
-	}
169
+    /**
170
+     * update the comment's message
171
+     *
172
+     * @param $propertyValue
173
+     * @return bool
174
+     * @throws BadRequest
175
+     * @throws Forbidden
176
+     */
177
+    public function updateComment($propertyValue) {
178
+        $this->checkWriteAccessOnComment();
179
+        try {
180
+            $this->comment->setMessage($propertyValue);
181
+            $this->commentsManager->save($this->comment);
182
+            return true;
183
+        } catch (\Exception $e) {
184
+            $this->logger->logException($e, ['app' => 'dav/comments']);
185
+            if($e instanceof MessageTooLongException) {
186
+                $msg = 'Message exceeds allowed character limit of ';
187
+                throw new BadRequest($msg . IComment::MAX_MESSAGE_LENGTH, 0, $e);
188
+            }
189
+            return false;
190
+        }
191
+    }
192 192
 
193
-	/**
194
-	 * Updates properties on this node.
195
-	 *
196
-	 * This method received a PropPatch object, which contains all the
197
-	 * information about the update.
198
-	 *
199
-	 * To update specific properties, call the 'handle' method on this object.
200
-	 * Read the PropPatch documentation for more information.
201
-	 *
202
-	 * @param PropPatch $propPatch
203
-	 * @return void
204
-	 */
205
-	function propPatch(PropPatch $propPatch) {
206
-		// other properties than 'message' are read only
207
-		$propPatch->handle(self::PROPERTY_NAME_MESSAGE, [$this, 'updateComment']);
208
-	}
193
+    /**
194
+     * Updates properties on this node.
195
+     *
196
+     * This method received a PropPatch object, which contains all the
197
+     * information about the update.
198
+     *
199
+     * To update specific properties, call the 'handle' method on this object.
200
+     * Read the PropPatch documentation for more information.
201
+     *
202
+     * @param PropPatch $propPatch
203
+     * @return void
204
+     */
205
+    function propPatch(PropPatch $propPatch) {
206
+        // other properties than 'message' are read only
207
+        $propPatch->handle(self::PROPERTY_NAME_MESSAGE, [$this, 'updateComment']);
208
+    }
209 209
 
210
-	/**
211
-	 * Returns a list of properties for this nodes.
212
-	 *
213
-	 * The properties list is a list of propertynames the client requested,
214
-	 * encoded in clark-notation {xmlnamespace}tagname
215
-	 *
216
-	 * If the array is empty, it means 'all properties' were requested.
217
-	 *
218
-	 * Note that it's fine to liberally give properties back, instead of
219
-	 * conforming to the list of requested properties.
220
-	 * The Server class will filter out the extra.
221
-	 *
222
-	 * @param array $properties
223
-	 * @return array
224
-	 */
225
-	function getProperties($properties) {
226
-		$properties = array_keys($this->properties);
210
+    /**
211
+     * Returns a list of properties for this nodes.
212
+     *
213
+     * The properties list is a list of propertynames the client requested,
214
+     * encoded in clark-notation {xmlnamespace}tagname
215
+     *
216
+     * If the array is empty, it means 'all properties' were requested.
217
+     *
218
+     * Note that it's fine to liberally give properties back, instead of
219
+     * conforming to the list of requested properties.
220
+     * The Server class will filter out the extra.
221
+     *
222
+     * @param array $properties
223
+     * @return array
224
+     */
225
+    function getProperties($properties) {
226
+        $properties = array_keys($this->properties);
227 227
 
228
-		$result = [];
229
-		foreach($properties as $property) {
230
-			$getter = $this->properties[$property];
231
-			if(method_exists($this->comment, $getter)) {
232
-				$result[$property] = $this->comment->$getter();
233
-			}
234
-		}
228
+        $result = [];
229
+        foreach($properties as $property) {
230
+            $getter = $this->properties[$property];
231
+            if(method_exists($this->comment, $getter)) {
232
+                $result[$property] = $this->comment->$getter();
233
+            }
234
+        }
235 235
 
236
-		if($this->comment->getActorType() === 'users') {
237
-			$user = $this->userManager->get($this->comment->getActorId());
238
-			$displayName = is_null($user) ? null : $user->getDisplayName();
239
-			$result[self::PROPERTY_NAME_ACTOR_DISPLAYNAME] = $displayName;
240
-		}
236
+        if($this->comment->getActorType() === 'users') {
237
+            $user = $this->userManager->get($this->comment->getActorId());
238
+            $displayName = is_null($user) ? null : $user->getDisplayName();
239
+            $result[self::PROPERTY_NAME_ACTOR_DISPLAYNAME] = $displayName;
240
+        }
241 241
 
242
-		$unread = null;
243
-		$user =  $this->userSession->getUser();
244
-		if(!is_null($user)) {
245
-			$readUntil = $this->commentsManager->getReadMark(
246
-				$this->comment->getObjectType(),
247
-				$this->comment->getObjectId(),
248
-				$user
249
-			);
250
-			if(is_null($readUntil)) {
251
-				$unread = 'true';
252
-			} else {
253
-				$unread = $this->comment->getCreationDateTime() > $readUntil;
254
-				// re-format for output
255
-				$unread = $unread ? 'true' : 'false';
256
-			}
257
-		}
258
-		$result[self::PROPERTY_NAME_UNREAD] = $unread;
242
+        $unread = null;
243
+        $user =  $this->userSession->getUser();
244
+        if(!is_null($user)) {
245
+            $readUntil = $this->commentsManager->getReadMark(
246
+                $this->comment->getObjectType(),
247
+                $this->comment->getObjectId(),
248
+                $user
249
+            );
250
+            if(is_null($readUntil)) {
251
+                $unread = 'true';
252
+            } else {
253
+                $unread = $this->comment->getCreationDateTime() > $readUntil;
254
+                // re-format for output
255
+                $unread = $unread ? 'true' : 'false';
256
+            }
257
+        }
258
+        $result[self::PROPERTY_NAME_UNREAD] = $unread;
259 259
 
260
-		return $result;
261
-	}
260
+        return $result;
261
+    }
262 262
 }
Please login to merge, or discard this patch.
Spacing   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -80,11 +80,11 @@  discard block
 block discarded – undo
80 80
 		$this->logger = $logger;
81 81
 
82 82
 		$methods = get_class_methods($this->comment);
83
-		$methods = array_filter($methods, function($name){
83
+		$methods = array_filter($methods, function($name) {
84 84
 			return strpos($name, 'get') === 0;
85 85
 		});
86
-		foreach($methods as $getter) {
87
-			$name = '{'.self::NS_OWNCLOUD.'}' . lcfirst(substr($getter, 3));
86
+		foreach ($methods as $getter) {
87
+			$name = '{'.self::NS_OWNCLOUD.'}'.lcfirst(substr($getter, 3));
88 88
 			$this->properties[$name] = $getter;
89 89
 		}
90 90
 		$this->userManager = $userManager;
@@ -118,7 +118,7 @@  discard block
 block discarded – undo
118 118
 
119 119
 	protected function checkWriteAccessOnComment() {
120 120
 		$user = $this->userSession->getUser();
121
-		if(    $this->comment->getActorType() !== 'users'
121
+		if ($this->comment->getActorType() !== 'users'
122 122
 			|| is_null($user)
123 123
 			|| $this->comment->getActorId() !== $user->getUID()
124 124
 		) {
@@ -182,9 +182,9 @@  discard block
 block discarded – undo
182 182
 			return true;
183 183
 		} catch (\Exception $e) {
184 184
 			$this->logger->logException($e, ['app' => 'dav/comments']);
185
-			if($e instanceof MessageTooLongException) {
185
+			if ($e instanceof MessageTooLongException) {
186 186
 				$msg = 'Message exceeds allowed character limit of ';
187
-				throw new BadRequest($msg . IComment::MAX_MESSAGE_LENGTH, 0, $e);
187
+				throw new BadRequest($msg.IComment::MAX_MESSAGE_LENGTH, 0, $e);
188 188
 			}
189 189
 			return false;
190 190
 		}
@@ -226,28 +226,28 @@  discard block
 block discarded – undo
226 226
 		$properties = array_keys($this->properties);
227 227
 
228 228
 		$result = [];
229
-		foreach($properties as $property) {
229
+		foreach ($properties as $property) {
230 230
 			$getter = $this->properties[$property];
231
-			if(method_exists($this->comment, $getter)) {
231
+			if (method_exists($this->comment, $getter)) {
232 232
 				$result[$property] = $this->comment->$getter();
233 233
 			}
234 234
 		}
235 235
 
236
-		if($this->comment->getActorType() === 'users') {
236
+		if ($this->comment->getActorType() === 'users') {
237 237
 			$user = $this->userManager->get($this->comment->getActorId());
238 238
 			$displayName = is_null($user) ? null : $user->getDisplayName();
239 239
 			$result[self::PROPERTY_NAME_ACTOR_DISPLAYNAME] = $displayName;
240 240
 		}
241 241
 
242 242
 		$unread = null;
243
-		$user =  $this->userSession->getUser();
244
-		if(!is_null($user)) {
243
+		$user = $this->userSession->getUser();
244
+		if (!is_null($user)) {
245 245
 			$readUntil = $this->commentsManager->getReadMark(
246 246
 				$this->comment->getObjectType(),
247 247
 				$this->comment->getObjectId(),
248 248
 				$user
249 249
 			);
250
-			if(is_null($readUntil)) {
250
+			if (is_null($readUntil)) {
251 251
 				$unread = 'true';
252 252
 			} else {
253 253
 				$unread = $this->comment->getCreationDateTime() > $readUntil;
Please login to merge, or discard this patch.
apps/dav/lib/comments/commentsplugin.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -138,7 +138,7 @@
 block discarded – undo
138 138
 	 * This will be used in the {DAV:}supported-report-set property.
139 139
 	 *
140 140
 	 * @param string $uri
141
-	 * @return array
141
+	 * @return string[]
142 142
 	 */
143 143
 	public function getSupportedReportSet($uri) {
144 144
 		return [self::REPORT_NAME];
Please login to merge, or discard this patch.
Indentation   +207 added lines, -207 removed lines patch added patch discarded remove patch
@@ -43,213 +43,213 @@
 block discarded – undo
43 43
  * Sabre plugin to handle comments:
44 44
  */
45 45
 class CommentsPlugin extends ServerPlugin {
46
-	// namespace
47
-	const NS_OWNCLOUD = 'http://owncloud.org/ns';
48
-
49
-	const REPORT_NAME            = '{http://owncloud.org/ns}filter-comments';
50
-	const REPORT_PARAM_LIMIT     = '{http://owncloud.org/ns}limit';
51
-	const REPORT_PARAM_OFFSET    = '{http://owncloud.org/ns}offset';
52
-	const REPORT_PARAM_TIMESTAMP = '{http://owncloud.org/ns}datetime';
53
-
54
-	/** @var ICommentsManager  */
55
-	protected $commentsManager;
56
-
57
-	/** @var \Sabre\DAV\Server $server */
58
-	private $server;
59
-
60
-	/** @var  \OCP\IUserSession */
61
-	protected $userSession;
62
-
63
-	/**
64
-	 * Comments plugin
65
-	 *
66
-	 * @param ICommentsManager $commentsManager
67
-	 * @param IUserSession $userSession
68
-	 */
69
-	public function __construct(ICommentsManager $commentsManager, IUserSession $userSession) {
70
-		$this->commentsManager = $commentsManager;
71
-		$this->userSession = $userSession;
72
-	}
73
-
74
-	/**
75
-	 * This initializes the plugin.
76
-	 *
77
-	 * This function is called by Sabre\DAV\Server, after
78
-	 * addPlugin is called.
79
-	 *
80
-	 * This method should set up the required event subscriptions.
81
-	 *
82
-	 * @param Server $server
83
-	 * @return void
84
-	 */
85
-	function initialize(Server $server) {
86
-		$this->server = $server;
87
-		if(strpos($this->server->getRequestUri(), 'comments/') !== 0) {
88
-			return;
89
-		}
90
-
91
-		$this->server->xml->namespaceMap[self::NS_OWNCLOUD] = 'oc';
92
-
93
-		$this->server->xml->classMap['DateTime'] = function(Writer $writer, \DateTime $value) {
94
-			$writer->write(\Sabre\HTTP\toDate($value));
95
-		};
96
-
97
-		$this->server->on('report', [$this, 'onReport']);
98
-		$this->server->on('method:POST', [$this, 'httpPost']);
99
-	}
100
-
101
-	/**
102
-	 * POST operation on Comments collections
103
-	 *
104
-	 * @param RequestInterface $request request object
105
-	 * @param ResponseInterface $response response object
106
-	 * @return null|false
107
-	 */
108
-	public function httpPost(RequestInterface $request, ResponseInterface $response) {
109
-		$path = $request->getPath();
110
-		$node = $this->server->tree->getNodeForPath($path);
111
-		if (!$node instanceof EntityCollection) {
112
-			return null;
113
-		}
114
-
115
-		$data = $request->getBodyAsString();
116
-		$comment = $this->createComment(
117
-			$node->getName(),
118
-			$node->getId(),
119
-			$data,
120
-			$request->getHeader('Content-Type')
121
-		);
122
-
123
-		// update read marker for the current user/poster to avoid
124
-		// having their own comments marked as unread
125
-		$node->setReadMarker(null);
126
-
127
-		$url = rtrim($request->getUrl(), '/') . '/' . urlencode($comment->getId());
128
-
129
-		$response->setHeader('Content-Location', $url);
130
-
131
-		// created
132
-		$response->setStatus(201);
133
-		return false;
134
-	}
135
-
136
-	/**
137
-	 * Returns a list of reports this plugin supports.
138
-	 *
139
-	 * This will be used in the {DAV:}supported-report-set property.
140
-	 *
141
-	 * @param string $uri
142
-	 * @return array
143
-	 */
144
-	public function getSupportedReportSet($uri) {
145
-		return [self::REPORT_NAME];
146
-	}
147
-
148
-	/**
149
-	 * REPORT operations to look for comments
150
-	 *
151
-	 * @param string $reportName
152
-	 * @param [] $report
153
-	 * @param string $uri
154
-	 * @return bool
155
-	 * @throws NotFound
156
-	 * @throws ReportNotSupported
157
-	 */
158
-	public function onReport($reportName, $report, $uri) {
159
-		$node = $this->server->tree->getNodeForPath($uri);
160
-		if(!$node instanceof EntityCollection || $reportName !== self::REPORT_NAME) {
161
-			throw new ReportNotSupported();
162
-		}
163
-		$args = ['limit' => 0, 'offset' => 0, 'datetime' => null];
164
-		$acceptableParameters = [
165
-			$this::REPORT_PARAM_LIMIT,
166
-			$this::REPORT_PARAM_OFFSET,
167
-			$this::REPORT_PARAM_TIMESTAMP
168
-		];
169
-		$ns = '{' . $this::NS_OWNCLOUD . '}';
170
-		foreach($report as $parameter) {
171
-			if(!in_array($parameter['name'], $acceptableParameters) || empty($parameter['value'])) {
172
-				continue;
173
-			}
174
-			$args[str_replace($ns, '', $parameter['name'])] = $parameter['value'];
175
-		}
176
-
177
-		if(!is_null($args['datetime'])) {
178
-			$args['datetime'] = new \DateTime($args['datetime']);
179
-		}
180
-
181
-		$results = $node->findChildren($args['limit'], $args['offset'], $args['datetime']);
182
-
183
-		$responses = [];
184
-		foreach($results as $node) {
185
-			$nodePath = $this->server->getRequestUri() . '/' . $node->comment->getId();
186
-			$resultSet = $this->server->getPropertiesForPath($nodePath, CommentNode::getPropertyNames());
187
-			if(isset($resultSet[0]) && isset($resultSet[0][200])) {
188
-				$responses[] = new Response(
189
-					$this->server->getBaseUri() . $nodePath,
190
-					[200 => $resultSet[0][200]],
191
-					200
192
-				);
193
-			}
194
-
195
-		}
196
-
197
-		$xml = $this->server->xml->write(
198
-			'{DAV:}multistatus',
199
-			new MultiStatus($responses)
200
-		);
201
-
202
-		$this->server->httpResponse->setStatus(207);
203
-		$this->server->httpResponse->setHeader('Content-Type', 'application/xml; charset=utf-8');
204
-		$this->server->httpResponse->setBody($xml);
205
-
206
-		return false;
207
-	}
208
-
209
-	/**
210
-	 * Creates a new comment
211
-	 *
212
-	 * @param string $objectType e.g. "files"
213
-	 * @param string $objectId e.g. the file id
214
-	 * @param string $data JSON encoded string containing the properties of the tag to create
215
-	 * @param string $contentType content type of the data
216
-	 * @return IComment newly created comment
217
-	 *
218
-	 * @throws BadRequest if a field was missing
219
-	 * @throws UnsupportedMediaType if the content type is not supported
220
-	 */
221
-	private function createComment($objectType, $objectId, $data, $contentType = 'application/json') {
222
-		if (explode(';', $contentType)[0] === 'application/json') {
223
-			$data = json_decode($data, true);
224
-		} else {
225
-			throw new UnsupportedMediaType();
226
-		}
227
-
228
-		$actorType = $data['actorType'];
229
-		$actorId = null;
230
-		if($actorType === 'users') {
231
-			$user = $this->userSession->getUser();
232
-			if(!is_null($user)) {
233
-				$actorId = $user->getUID();
234
-			}
235
-		}
236
-		if(is_null($actorId)) {
237
-			throw new BadRequest('Invalid actor "' .  $actorType .'"');
238
-		}
239
-
240
-		try {
241
-			$comment = $this->commentsManager->create($actorType, $actorId, $objectType, $objectId);
242
-			$comment->setMessage($data['message']);
243
-			$comment->setVerb($data['verb']);
244
-			$this->commentsManager->save($comment);
245
-			return $comment;
246
-		} catch (\InvalidArgumentException $e) {
247
-			throw new BadRequest('Invalid input values', 0, $e);
248
-		} catch (\OCP\Comments\MessageTooLongException $e) {
249
-			$msg = 'Message exceeds allowed character limit of ';
250
-			throw new BadRequest($msg . \OCP\Comments\IComment::MAX_MESSAGE_LENGTH, 0,	$e);
251
-		}
252
-	}
46
+    // namespace
47
+    const NS_OWNCLOUD = 'http://owncloud.org/ns';
48
+
49
+    const REPORT_NAME            = '{http://owncloud.org/ns}filter-comments';
50
+    const REPORT_PARAM_LIMIT     = '{http://owncloud.org/ns}limit';
51
+    const REPORT_PARAM_OFFSET    = '{http://owncloud.org/ns}offset';
52
+    const REPORT_PARAM_TIMESTAMP = '{http://owncloud.org/ns}datetime';
53
+
54
+    /** @var ICommentsManager  */
55
+    protected $commentsManager;
56
+
57
+    /** @var \Sabre\DAV\Server $server */
58
+    private $server;
59
+
60
+    /** @var  \OCP\IUserSession */
61
+    protected $userSession;
62
+
63
+    /**
64
+     * Comments plugin
65
+     *
66
+     * @param ICommentsManager $commentsManager
67
+     * @param IUserSession $userSession
68
+     */
69
+    public function __construct(ICommentsManager $commentsManager, IUserSession $userSession) {
70
+        $this->commentsManager = $commentsManager;
71
+        $this->userSession = $userSession;
72
+    }
73
+
74
+    /**
75
+     * This initializes the plugin.
76
+     *
77
+     * This function is called by Sabre\DAV\Server, after
78
+     * addPlugin is called.
79
+     *
80
+     * This method should set up the required event subscriptions.
81
+     *
82
+     * @param Server $server
83
+     * @return void
84
+     */
85
+    function initialize(Server $server) {
86
+        $this->server = $server;
87
+        if(strpos($this->server->getRequestUri(), 'comments/') !== 0) {
88
+            return;
89
+        }
90
+
91
+        $this->server->xml->namespaceMap[self::NS_OWNCLOUD] = 'oc';
92
+
93
+        $this->server->xml->classMap['DateTime'] = function(Writer $writer, \DateTime $value) {
94
+            $writer->write(\Sabre\HTTP\toDate($value));
95
+        };
96
+
97
+        $this->server->on('report', [$this, 'onReport']);
98
+        $this->server->on('method:POST', [$this, 'httpPost']);
99
+    }
100
+
101
+    /**
102
+     * POST operation on Comments collections
103
+     *
104
+     * @param RequestInterface $request request object
105
+     * @param ResponseInterface $response response object
106
+     * @return null|false
107
+     */
108
+    public function httpPost(RequestInterface $request, ResponseInterface $response) {
109
+        $path = $request->getPath();
110
+        $node = $this->server->tree->getNodeForPath($path);
111
+        if (!$node instanceof EntityCollection) {
112
+            return null;
113
+        }
114
+
115
+        $data = $request->getBodyAsString();
116
+        $comment = $this->createComment(
117
+            $node->getName(),
118
+            $node->getId(),
119
+            $data,
120
+            $request->getHeader('Content-Type')
121
+        );
122
+
123
+        // update read marker for the current user/poster to avoid
124
+        // having their own comments marked as unread
125
+        $node->setReadMarker(null);
126
+
127
+        $url = rtrim($request->getUrl(), '/') . '/' . urlencode($comment->getId());
128
+
129
+        $response->setHeader('Content-Location', $url);
130
+
131
+        // created
132
+        $response->setStatus(201);
133
+        return false;
134
+    }
135
+
136
+    /**
137
+     * Returns a list of reports this plugin supports.
138
+     *
139
+     * This will be used in the {DAV:}supported-report-set property.
140
+     *
141
+     * @param string $uri
142
+     * @return array
143
+     */
144
+    public function getSupportedReportSet($uri) {
145
+        return [self::REPORT_NAME];
146
+    }
147
+
148
+    /**
149
+     * REPORT operations to look for comments
150
+     *
151
+     * @param string $reportName
152
+     * @param [] $report
153
+     * @param string $uri
154
+     * @return bool
155
+     * @throws NotFound
156
+     * @throws ReportNotSupported
157
+     */
158
+    public function onReport($reportName, $report, $uri) {
159
+        $node = $this->server->tree->getNodeForPath($uri);
160
+        if(!$node instanceof EntityCollection || $reportName !== self::REPORT_NAME) {
161
+            throw new ReportNotSupported();
162
+        }
163
+        $args = ['limit' => 0, 'offset' => 0, 'datetime' => null];
164
+        $acceptableParameters = [
165
+            $this::REPORT_PARAM_LIMIT,
166
+            $this::REPORT_PARAM_OFFSET,
167
+            $this::REPORT_PARAM_TIMESTAMP
168
+        ];
169
+        $ns = '{' . $this::NS_OWNCLOUD . '}';
170
+        foreach($report as $parameter) {
171
+            if(!in_array($parameter['name'], $acceptableParameters) || empty($parameter['value'])) {
172
+                continue;
173
+            }
174
+            $args[str_replace($ns, '', $parameter['name'])] = $parameter['value'];
175
+        }
176
+
177
+        if(!is_null($args['datetime'])) {
178
+            $args['datetime'] = new \DateTime($args['datetime']);
179
+        }
180
+
181
+        $results = $node->findChildren($args['limit'], $args['offset'], $args['datetime']);
182
+
183
+        $responses = [];
184
+        foreach($results as $node) {
185
+            $nodePath = $this->server->getRequestUri() . '/' . $node->comment->getId();
186
+            $resultSet = $this->server->getPropertiesForPath($nodePath, CommentNode::getPropertyNames());
187
+            if(isset($resultSet[0]) && isset($resultSet[0][200])) {
188
+                $responses[] = new Response(
189
+                    $this->server->getBaseUri() . $nodePath,
190
+                    [200 => $resultSet[0][200]],
191
+                    200
192
+                );
193
+            }
194
+
195
+        }
196
+
197
+        $xml = $this->server->xml->write(
198
+            '{DAV:}multistatus',
199
+            new MultiStatus($responses)
200
+        );
201
+
202
+        $this->server->httpResponse->setStatus(207);
203
+        $this->server->httpResponse->setHeader('Content-Type', 'application/xml; charset=utf-8');
204
+        $this->server->httpResponse->setBody($xml);
205
+
206
+        return false;
207
+    }
208
+
209
+    /**
210
+     * Creates a new comment
211
+     *
212
+     * @param string $objectType e.g. "files"
213
+     * @param string $objectId e.g. the file id
214
+     * @param string $data JSON encoded string containing the properties of the tag to create
215
+     * @param string $contentType content type of the data
216
+     * @return IComment newly created comment
217
+     *
218
+     * @throws BadRequest if a field was missing
219
+     * @throws UnsupportedMediaType if the content type is not supported
220
+     */
221
+    private function createComment($objectType, $objectId, $data, $contentType = 'application/json') {
222
+        if (explode(';', $contentType)[0] === 'application/json') {
223
+            $data = json_decode($data, true);
224
+        } else {
225
+            throw new UnsupportedMediaType();
226
+        }
227
+
228
+        $actorType = $data['actorType'];
229
+        $actorId = null;
230
+        if($actorType === 'users') {
231
+            $user = $this->userSession->getUser();
232
+            if(!is_null($user)) {
233
+                $actorId = $user->getUID();
234
+            }
235
+        }
236
+        if(is_null($actorId)) {
237
+            throw new BadRequest('Invalid actor "' .  $actorType .'"');
238
+        }
239
+
240
+        try {
241
+            $comment = $this->commentsManager->create($actorType, $actorId, $objectType, $objectId);
242
+            $comment->setMessage($data['message']);
243
+            $comment->setVerb($data['verb']);
244
+            $this->commentsManager->save($comment);
245
+            return $comment;
246
+        } catch (\InvalidArgumentException $e) {
247
+            throw new BadRequest('Invalid input values', 0, $e);
248
+        } catch (\OCP\Comments\MessageTooLongException $e) {
249
+            $msg = 'Message exceeds allowed character limit of ';
250
+            throw new BadRequest($msg . \OCP\Comments\IComment::MAX_MESSAGE_LENGTH, 0,	$e);
251
+        }
252
+    }
253 253
 
254 254
 
255 255
 
Please login to merge, or discard this patch.
Spacing   +16 added lines, -16 removed lines patch added patch discarded remove patch
@@ -84,7 +84,7 @@  discard block
 block discarded – undo
84 84
 	 */
85 85
 	function initialize(Server $server) {
86 86
 		$this->server = $server;
87
-		if(strpos($this->server->getRequestUri(), 'comments/') !== 0) {
87
+		if (strpos($this->server->getRequestUri(), 'comments/') !== 0) {
88 88
 			return;
89 89
 		}
90 90
 
@@ -124,7 +124,7 @@  discard block
 block discarded – undo
124 124
 		// having their own comments marked as unread
125 125
 		$node->setReadMarker(null);
126 126
 
127
-		$url = rtrim($request->getUrl(), '/') . '/' . urlencode($comment->getId());
127
+		$url = rtrim($request->getUrl(), '/').'/'.urlencode($comment->getId());
128 128
 
129 129
 		$response->setHeader('Content-Location', $url);
130 130
 
@@ -157,7 +157,7 @@  discard block
 block discarded – undo
157 157
 	 */
158 158
 	public function onReport($reportName, $report, $uri) {
159 159
 		$node = $this->server->tree->getNodeForPath($uri);
160
-		if(!$node instanceof EntityCollection || $reportName !== self::REPORT_NAME) {
160
+		if (!$node instanceof EntityCollection || $reportName !== self::REPORT_NAME) {
161 161
 			throw new ReportNotSupported();
162 162
 		}
163 163
 		$args = ['limit' => 0, 'offset' => 0, 'datetime' => null];
@@ -166,27 +166,27 @@  discard block
 block discarded – undo
166 166
 			$this::REPORT_PARAM_OFFSET,
167 167
 			$this::REPORT_PARAM_TIMESTAMP
168 168
 		];
169
-		$ns = '{' . $this::NS_OWNCLOUD . '}';
170
-		foreach($report as $parameter) {
171
-			if(!in_array($parameter['name'], $acceptableParameters) || empty($parameter['value'])) {
169
+		$ns = '{'.$this::NS_OWNCLOUD.'}';
170
+		foreach ($report as $parameter) {
171
+			if (!in_array($parameter['name'], $acceptableParameters) || empty($parameter['value'])) {
172 172
 				continue;
173 173
 			}
174 174
 			$args[str_replace($ns, '', $parameter['name'])] = $parameter['value'];
175 175
 		}
176 176
 
177
-		if(!is_null($args['datetime'])) {
177
+		if (!is_null($args['datetime'])) {
178 178
 			$args['datetime'] = new \DateTime($args['datetime']);
179 179
 		}
180 180
 
181 181
 		$results = $node->findChildren($args['limit'], $args['offset'], $args['datetime']);
182 182
 
183 183
 		$responses = [];
184
-		foreach($results as $node) {
185
-			$nodePath = $this->server->getRequestUri() . '/' . $node->comment->getId();
184
+		foreach ($results as $node) {
185
+			$nodePath = $this->server->getRequestUri().'/'.$node->comment->getId();
186 186
 			$resultSet = $this->server->getPropertiesForPath($nodePath, CommentNode::getPropertyNames());
187
-			if(isset($resultSet[0]) && isset($resultSet[0][200])) {
187
+			if (isset($resultSet[0]) && isset($resultSet[0][200])) {
188 188
 				$responses[] = new Response(
189
-					$this->server->getBaseUri() . $nodePath,
189
+					$this->server->getBaseUri().$nodePath,
190 190
 					[200 => $resultSet[0][200]],
191 191
 					200
192 192
 				);
@@ -227,14 +227,14 @@  discard block
 block discarded – undo
227 227
 
228 228
 		$actorType = $data['actorType'];
229 229
 		$actorId = null;
230
-		if($actorType === 'users') {
230
+		if ($actorType === 'users') {
231 231
 			$user = $this->userSession->getUser();
232
-			if(!is_null($user)) {
232
+			if (!is_null($user)) {
233 233
 				$actorId = $user->getUID();
234 234
 			}
235 235
 		}
236
-		if(is_null($actorId)) {
237
-			throw new BadRequest('Invalid actor "' .  $actorType .'"');
236
+		if (is_null($actorId)) {
237
+			throw new BadRequest('Invalid actor "'.$actorType.'"');
238 238
 		}
239 239
 
240 240
 		try {
@@ -247,7 +247,7 @@  discard block
 block discarded – undo
247 247
 			throw new BadRequest('Invalid input values', 0, $e);
248 248
 		} catch (\OCP\Comments\MessageTooLongException $e) {
249 249
 			$msg = 'Message exceeds allowed character limit of ';
250
-			throw new BadRequest($msg . \OCP\Comments\IComment::MAX_MESSAGE_LENGTH, 0,	$e);
250
+			throw new BadRequest($msg.\OCP\Comments\IComment::MAX_MESSAGE_LENGTH, 0, $e);
251 251
 		}
252 252
 	}
253 253
 
Please login to merge, or discard this patch.
apps/dav/lib/connector/sabre/file.php 3 patches
Doc Comments   +3 added lines patch added patch discarded remove patch
@@ -232,6 +232,9 @@
 block discarded – undo
232 232
 		return '"' . $this->info->getEtag() . '"';
233 233
 	}
234 234
 
235
+	/**
236
+	 * @param string $path
237
+	 */
235 238
 	private function getPartFileBasePath($path) {
236 239
 		$partFileInStorage = \OC::$server->getConfig()->getSystemValue('part_file_in_storage', true);
237 240
 		if ($partFileInStorage) {
Please login to merge, or discard this patch.
Indentation   +508 added lines, -508 removed lines patch added patch discarded remove patch
@@ -57,512 +57,512 @@
 block discarded – undo
57 57
 
58 58
 class File extends Node implements IFile {
59 59
 
60
-	/**
61
-	 * Updates the data
62
-	 *
63
-	 * The data argument is a readable stream resource.
64
-	 *
65
-	 * After a successful put operation, you may choose to return an ETag. The
66
-	 * etag must always be surrounded by double-quotes. These quotes must
67
-	 * appear in the actual string you're returning.
68
-	 *
69
-	 * Clients may use the ETag from a PUT request to later on make sure that
70
-	 * when they update the file, the contents haven't changed in the mean
71
-	 * time.
72
-	 *
73
-	 * If you don't plan to store the file byte-by-byte, and you return a
74
-	 * different object on a subsequent GET you are strongly recommended to not
75
-	 * return an ETag, and just return null.
76
-	 *
77
-	 * @param resource $data
78
-	 *
79
-	 * @throws Forbidden
80
-	 * @throws UnsupportedMediaType
81
-	 * @throws BadRequest
82
-	 * @throws Exception
83
-	 * @throws EntityTooLarge
84
-	 * @throws ServiceUnavailable
85
-	 * @throws FileLocked
86
-	 * @return string|null
87
-	 */
88
-	public function put($data) {
89
-		try {
90
-			$exists = $this->fileView->file_exists($this->path);
91
-			if ($this->info && $exists && !$this->info->isUpdateable()) {
92
-				throw new Forbidden();
93
-			}
94
-		} catch (StorageNotAvailableException $e) {
95
-			throw new ServiceUnavailable("File is not updatable: " . $e->getMessage());
96
-		}
97
-
98
-		// verify path of the target
99
-		$this->verifyPath();
100
-
101
-		// chunked handling
102
-		if (isset($_SERVER['HTTP_OC_CHUNKED'])) {
103
-			try {
104
-				return $this->createFileChunked($data);
105
-			} catch (\Exception $e) {
106
-				$this->convertToSabreException($e);
107
-			}
108
-		}
109
-
110
-		list($partStorage) = $this->fileView->resolvePath($this->path);
111
-		$needsPartFile = $this->needsPartFile($partStorage) && (strlen($this->path) > 1);
112
-
113
-		if ($needsPartFile) {
114
-			// mark file as partial while uploading (ignored by the scanner)
115
-			$partFilePath = $this->getPartFileBasePath($this->path) . '.ocTransferId' . rand() . '.part';
116
-		} else {
117
-			// upload file directly as the final path
118
-			$partFilePath = $this->path;
119
-		}
120
-
121
-		// the part file and target file might be on a different storage in case of a single file storage (e.g. single file share)
122
-		/** @var \OC\Files\Storage\Storage $partStorage */
123
-		list($partStorage, $internalPartPath) = $this->fileView->resolvePath($partFilePath);
124
-		/** @var \OC\Files\Storage\Storage $storage */
125
-		list($storage, $internalPath) = $this->fileView->resolvePath($this->path);
126
-		try {
127
-			$target = $partStorage->fopen($internalPartPath, 'wb');
128
-			if ($target === false) {
129
-				\OCP\Util::writeLog('webdav', '\OC\Files\Filesystem::fopen() failed', \OCP\Util::ERROR);
130
-				// because we have no clue about the cause we can only throw back a 500/Internal Server Error
131
-				throw new Exception('Could not write file contents');
132
-			}
133
-			list($count, $result) = \OC_Helper::streamCopy($data, $target);
134
-			fclose($target);
135
-
136
-			if ($result === false) {
137
-				$expected = -1;
138
-				if (isset($_SERVER['CONTENT_LENGTH'])) {
139
-					$expected = $_SERVER['CONTENT_LENGTH'];
140
-				}
141
-				throw new Exception('Error while copying file to target location (copied bytes: ' . $count . ', expected filesize: ' . $expected . ' )');
142
-			}
143
-
144
-			// if content length is sent by client:
145
-			// double check if the file was fully received
146
-			// compare expected and actual size
147
-			if (isset($_SERVER['CONTENT_LENGTH']) && $_SERVER['REQUEST_METHOD'] !== 'LOCK') {
148
-				$expected = $_SERVER['CONTENT_LENGTH'];
149
-				if ($count != $expected) {
150
-					throw new BadRequest('expected filesize ' . $expected . ' got ' . $count);
151
-				}
152
-			}
153
-
154
-		} catch (\Exception $e) {
155
-			if ($needsPartFile) {
156
-				$partStorage->unlink($internalPartPath);
157
-			}
158
-			$this->convertToSabreException($e);
159
-		}
160
-
161
-		try {
162
-			$view = \OC\Files\Filesystem::getView();
163
-			if ($view) {
164
-				$run = $this->emitPreHooks($exists);
165
-			} else {
166
-				$run = true;
167
-			}
168
-
169
-			try {
170
-				$this->changeLock(ILockingProvider::LOCK_EXCLUSIVE);
171
-			} catch (LockedException $e) {
172
-				if ($needsPartFile) {
173
-					$partStorage->unlink($internalPartPath);
174
-				}
175
-				throw new FileLocked($e->getMessage(), $e->getCode(), $e);
176
-			}
177
-
178
-			if ($needsPartFile) {
179
-				// rename to correct path
180
-				try {
181
-					if ($run) {
182
-						$renameOkay = $storage->moveFromStorage($partStorage, $internalPartPath, $internalPath);
183
-						$fileExists = $storage->file_exists($internalPath);
184
-					}
185
-					if (!$run || $renameOkay === false || $fileExists === false) {
186
-						\OCP\Util::writeLog('webdav', 'renaming part file to final file failed', \OCP\Util::ERROR);
187
-						throw new Exception('Could not rename part file to final file');
188
-					}
189
-				} catch (ForbiddenException $ex) {
190
-					throw new DAVForbiddenException($ex->getMessage(), $ex->getRetry());
191
-				} catch (\Exception $e) {
192
-					$partStorage->unlink($internalPartPath);
193
-					$this->convertToSabreException($e);
194
-				}
195
-			}
196
-
197
-			// since we skipped the view we need to scan and emit the hooks ourselves
198
-			$storage->getUpdater()->update($internalPath);
199
-
200
-			try {
201
-				$this->changeLock(ILockingProvider::LOCK_SHARED);
202
-			} catch (LockedException $e) {
203
-				throw new FileLocked($e->getMessage(), $e->getCode(), $e);
204
-			}
205
-
206
-			if ($view) {
207
-				$this->emitPostHooks($exists);
208
-			}
209
-
210
-			// allow sync clients to send the mtime along in a header
211
-			$request = \OC::$server->getRequest();
212
-			if (isset($request->server['HTTP_X_OC_MTIME'])) {
213
-				if ($this->fileView->touch($this->path, $request->server['HTTP_X_OC_MTIME'])) {
214
-					header('X-OC-MTime: accepted');
215
-				}
216
-			}
217
-
218
-			$this->refreshInfo();
219
-
220
-			if (isset($request->server['HTTP_OC_CHECKSUM'])) {
221
-				$checksum = trim($request->server['HTTP_OC_CHECKSUM']);
222
-				$this->fileView->putFileInfo($this->path, ['checksum' => $checksum]);
223
-				$this->refreshInfo();
224
-			} else if ($this->getChecksum() !== null && $this->getChecksum() !== '') {
225
-				$this->fileView->putFileInfo($this->path, ['checksum' => '']);
226
-				$this->refreshInfo();
227
-			}
228
-
229
-		} catch (StorageNotAvailableException $e) {
230
-			throw new ServiceUnavailable("Failed to check file size: " . $e->getMessage());
231
-		}
232
-
233
-		return '"' . $this->info->getEtag() . '"';
234
-	}
235
-
236
-	private function getPartFileBasePath($path) {
237
-		$partFileInStorage = \OC::$server->getConfig()->getSystemValue('part_file_in_storage', true);
238
-		if ($partFileInStorage) {
239
-			return $path;
240
-		} else {
241
-			return md5($path); // will place it in the root of the view with a unique name
242
-		}
243
-	}
244
-
245
-	/**
246
-	 * @param string $path
247
-	 */
248
-	private function emitPreHooks($exists, $path = null) {
249
-		if (is_null($path)) {
250
-			$path = $this->path;
251
-		}
252
-		$hookPath = Filesystem::getView()->getRelativePath($this->fileView->getAbsolutePath($path));
253
-		$run = true;
254
-
255
-		if (!$exists) {
256
-			\OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_create, array(
257
-				\OC\Files\Filesystem::signal_param_path => $hookPath,
258
-				\OC\Files\Filesystem::signal_param_run => &$run,
259
-			));
260
-		} else {
261
-			\OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_update, array(
262
-				\OC\Files\Filesystem::signal_param_path => $hookPath,
263
-				\OC\Files\Filesystem::signal_param_run => &$run,
264
-			));
265
-		}
266
-		\OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_write, array(
267
-			\OC\Files\Filesystem::signal_param_path => $hookPath,
268
-			\OC\Files\Filesystem::signal_param_run => &$run,
269
-		));
270
-		return $run;
271
-	}
272
-
273
-	/**
274
-	 * @param string $path
275
-	 */
276
-	private function emitPostHooks($exists, $path = null) {
277
-		if (is_null($path)) {
278
-			$path = $this->path;
279
-		}
280
-		$hookPath = Filesystem::getView()->getRelativePath($this->fileView->getAbsolutePath($path));
281
-		if (!$exists) {
282
-			\OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_post_create, array(
283
-				\OC\Files\Filesystem::signal_param_path => $hookPath
284
-			));
285
-		} else {
286
-			\OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_post_update, array(
287
-				\OC\Files\Filesystem::signal_param_path => $hookPath
288
-			));
289
-		}
290
-		\OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_post_write, array(
291
-			\OC\Files\Filesystem::signal_param_path => $hookPath
292
-		));
293
-	}
294
-
295
-	/**
296
-	 * Returns the data
297
-	 *
298
-	 * @return resource
299
-	 * @throws Forbidden
300
-	 * @throws ServiceUnavailable
301
-	 */
302
-	public function get() {
303
-		//throw exception if encryption is disabled but files are still encrypted
304
-		try {
305
-			$res = $this->fileView->fopen(ltrim($this->path, '/'), 'rb');
306
-			if ($res === false) {
307
-				throw new ServiceUnavailable("Could not open file");
308
-			}
309
-			return $res;
310
-		} catch (GenericEncryptionException $e) {
311
-			// returning 503 will allow retry of the operation at a later point in time
312
-			throw new ServiceUnavailable("Encryption not ready: " . $e->getMessage());
313
-		} catch (StorageNotAvailableException $e) {
314
-			throw new ServiceUnavailable("Failed to open file: " . $e->getMessage());
315
-		} catch (ForbiddenException $ex) {
316
-			throw new DAVForbiddenException($ex->getMessage(), $ex->getRetry());
317
-		} catch (LockedException $e) {
318
-			throw new FileLocked($e->getMessage(), $e->getCode(), $e);
319
-		}
320
-	}
321
-
322
-	/**
323
-	 * Delete the current file
324
-	 *
325
-	 * @throws Forbidden
326
-	 * @throws ServiceUnavailable
327
-	 */
328
-	public function delete() {
329
-		if (!$this->info->isDeletable()) {
330
-			throw new Forbidden();
331
-		}
332
-
333
-		try {
334
-			if (!$this->fileView->unlink($this->path)) {
335
-				// assume it wasn't possible to delete due to permissions
336
-				throw new Forbidden();
337
-			}
338
-		} catch (StorageNotAvailableException $e) {
339
-			throw new ServiceUnavailable("Failed to unlink: " . $e->getMessage());
340
-		} catch (ForbiddenException $ex) {
341
-			throw new DAVForbiddenException($ex->getMessage(), $ex->getRetry());
342
-		} catch (LockedException $e) {
343
-			throw new FileLocked($e->getMessage(), $e->getCode(), $e);
344
-		}
345
-	}
346
-
347
-	/**
348
-	 * Returns the mime-type for a file
349
-	 *
350
-	 * If null is returned, we'll assume application/octet-stream
351
-	 *
352
-	 * @return string
353
-	 */
354
-	public function getContentType() {
355
-		$mimeType = $this->info->getMimetype();
356
-
357
-		// PROPFIND needs to return the correct mime type, for consistency with the web UI
358
-		if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PROPFIND') {
359
-			return $mimeType;
360
-		}
361
-		return \OC::$server->getMimeTypeDetector()->getSecureMimeType($mimeType);
362
-	}
363
-
364
-	/**
365
-	 * @return array|false
366
-	 */
367
-	public function getDirectDownload() {
368
-		if (\OCP\App::isEnabled('encryption')) {
369
-			return [];
370
-		}
371
-		/** @var \OCP\Files\Storage $storage */
372
-		list($storage, $internalPath) = $this->fileView->resolvePath($this->path);
373
-		if (is_null($storage)) {
374
-			return [];
375
-		}
376
-
377
-		return $storage->getDirectDownload($internalPath);
378
-	}
379
-
380
-	/**
381
-	 * @param resource $data
382
-	 * @return null|string
383
-	 * @throws Exception
384
-	 * @throws BadRequest
385
-	 * @throws NotImplemented
386
-	 * @throws ServiceUnavailable
387
-	 */
388
-	private function createFileChunked($data) {
389
-		list($path, $name) = \Sabre\HTTP\URLUtil::splitPath($this->path);
390
-
391
-		$info = \OC_FileChunking::decodeName($name);
392
-		if (empty($info)) {
393
-			throw new NotImplemented('Invalid chunk name');
394
-		}
395
-
396
-		$chunk_handler = new \OC_FileChunking($info);
397
-		$bytesWritten = $chunk_handler->store($info['index'], $data);
398
-
399
-		//detect aborted upload
400
-		if (isset ($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PUT') {
401
-			if (isset($_SERVER['CONTENT_LENGTH'])) {
402
-				$expected = $_SERVER['CONTENT_LENGTH'];
403
-				if ($bytesWritten != $expected) {
404
-					$chunk_handler->remove($info['index']);
405
-					throw new BadRequest(
406
-						'expected filesize ' . $expected . ' got ' . $bytesWritten);
407
-				}
408
-			}
409
-		}
410
-
411
-		if ($chunk_handler->isComplete()) {
412
-			list($storage,) = $this->fileView->resolvePath($path);
413
-			$needsPartFile = $this->needsPartFile($storage);
414
-			$partFile = null;
415
-
416
-			$targetPath = $path . '/' . $info['name'];
417
-			/** @var \OC\Files\Storage\Storage $targetStorage */
418
-			list($targetStorage, $targetInternalPath) = $this->fileView->resolvePath($targetPath);
419
-
420
-			$exists = $this->fileView->file_exists($targetPath);
421
-
422
-			try {
423
-				$this->fileView->lockFile($targetPath, ILockingProvider::LOCK_SHARED);
424
-
425
-				$this->emitPreHooks($exists, $targetPath);
426
-				$this->fileView->changeLock($targetPath, ILockingProvider::LOCK_EXCLUSIVE);
427
-				/** @var \OC\Files\Storage\Storage $targetStorage */
428
-				list($targetStorage, $targetInternalPath) = $this->fileView->resolvePath($targetPath);
429
-
430
-				if ($needsPartFile) {
431
-					// we first assembly the target file as a part file
432
-					$partFile = $this->getPartFileBasePath($path . '/' . $info['name']) . '.ocTransferId' . $info['transferid'] . '.part';
433
-					/** @var \OC\Files\Storage\Storage $targetStorage */
434
-					list($partStorage, $partInternalPath) = $this->fileView->resolvePath($partFile);
435
-
436
-
437
-					$chunk_handler->file_assemble($partStorage, $partInternalPath, $this->fileView->getAbsolutePath($targetPath));
438
-
439
-					// here is the final atomic rename
440
-					$renameOkay = $targetStorage->moveFromStorage($partStorage, $partInternalPath, $targetInternalPath);
441
-					$fileExists = $targetStorage->file_exists($targetInternalPath);
442
-					if ($renameOkay === false || $fileExists === false) {
443
-						\OCP\Util::writeLog('webdav', '\OC\Files\Filesystem::rename() failed', \OCP\Util::ERROR);
444
-						// only delete if an error occurred and the target file was already created
445
-						if ($fileExists) {
446
-							// set to null to avoid double-deletion when handling exception
447
-							// stray part file
448
-							$partFile = null;
449
-							$targetStorage->unlink($targetInternalPath);
450
-						}
451
-						$this->fileView->changeLock($targetPath, ILockingProvider::LOCK_SHARED);
452
-						throw new Exception('Could not rename part file assembled from chunks');
453
-					}
454
-				} else {
455
-					// assemble directly into the final file
456
-					$chunk_handler->file_assemble($targetStorage, $targetInternalPath, $this->fileView->getAbsolutePath($targetPath));
457
-				}
458
-
459
-				// allow sync clients to send the mtime along in a header
460
-				$request = \OC::$server->getRequest();
461
-				if (isset($request->server['HTTP_X_OC_MTIME'])) {
462
-					if ($targetStorage->touch($targetInternalPath, $request->server['HTTP_X_OC_MTIME'])) {
463
-						header('X-OC-MTime: accepted');
464
-					}
465
-				}
466
-
467
-				// since we skipped the view we need to scan and emit the hooks ourselves
468
-				$targetStorage->getUpdater()->update($targetInternalPath);
469
-
470
-				$this->fileView->changeLock($targetPath, ILockingProvider::LOCK_SHARED);
471
-
472
-				$this->emitPostHooks($exists, $targetPath);
473
-
474
-				// FIXME: should call refreshInfo but can't because $this->path is not the of the final file
475
-				$info = $this->fileView->getFileInfo($targetPath);
476
-
477
-				if (isset($request->server['HTTP_OC_CHECKSUM'])) {
478
-					$checksum = trim($request->server['HTTP_OC_CHECKSUM']);
479
-					$this->fileView->putFileInfo($targetPath, ['checksum' => $checksum]);
480
-				} else if ($info->getChecksum() !== null && $info->getChecksum() !== '') {
481
-					$this->fileView->putFileInfo($this->path, ['checksum' => '']);
482
-				}
483
-
484
-				$this->fileView->unlockFile($targetPath, ILockingProvider::LOCK_SHARED);
485
-
486
-				return $info->getEtag();
487
-			} catch (\Exception $e) {
488
-				if ($partFile !== null) {
489
-					$targetStorage->unlink($targetInternalPath);
490
-				}
491
-				$this->convertToSabreException($e);
492
-			}
493
-		}
494
-
495
-		return null;
496
-	}
497
-
498
-	/**
499
-	 * Returns whether a part file is needed for the given storage
500
-	 * or whether the file can be assembled/uploaded directly on the
501
-	 * target storage.
502
-	 *
503
-	 * @param \OCP\Files\Storage $storage
504
-	 * @return bool true if the storage needs part file handling
505
-	 */
506
-	private function needsPartFile($storage) {
507
-		// TODO: in the future use ChunkHandler provided by storage
508
-		// and/or add method on Storage called "needsPartFile()"
509
-		return !$storage->instanceOfStorage('OCA\Files_Sharing\External\Storage') &&
510
-		!$storage->instanceOfStorage('OC\Files\Storage\OwnCloud');
511
-	}
512
-
513
-	/**
514
-	 * Convert the given exception to a SabreException instance
515
-	 *
516
-	 * @param \Exception $e
517
-	 *
518
-	 * @throws \Sabre\DAV\Exception
519
-	 */
520
-	private function convertToSabreException(\Exception $e) {
521
-		if ($e instanceof \Sabre\DAV\Exception) {
522
-			throw $e;
523
-		}
524
-		if ($e instanceof NotPermittedException) {
525
-			// a more general case - due to whatever reason the content could not be written
526
-			throw new Forbidden($e->getMessage(), 0, $e);
527
-		}
528
-		if ($e instanceof ForbiddenException) {
529
-			// the path for the file was forbidden
530
-			throw new DAVForbiddenException($e->getMessage(), $e->getRetry(), $e);
531
-		}
532
-		if ($e instanceof EntityTooLargeException) {
533
-			// the file is too big to be stored
534
-			throw new EntityTooLarge($e->getMessage(), 0, $e);
535
-		}
536
-		if ($e instanceof InvalidContentException) {
537
-			// the file content is not permitted
538
-			throw new UnsupportedMediaType($e->getMessage(), 0, $e);
539
-		}
540
-		if ($e instanceof InvalidPathException) {
541
-			// the path for the file was not valid
542
-			// TODO: find proper http status code for this case
543
-			throw new Forbidden($e->getMessage(), 0, $e);
544
-		}
545
-		if ($e instanceof LockedException || $e instanceof LockNotAcquiredException) {
546
-			// the file is currently being written to by another process
547
-			throw new FileLocked($e->getMessage(), $e->getCode(), $e);
548
-		}
549
-		if ($e instanceof GenericEncryptionException) {
550
-			// returning 503 will allow retry of the operation at a later point in time
551
-			throw new ServiceUnavailable('Encryption not ready: ' . $e->getMessage(), 0, $e);
552
-		}
553
-		if ($e instanceof StorageNotAvailableException) {
554
-			throw new ServiceUnavailable('Failed to write file contents: ' . $e->getMessage(), 0, $e);
555
-		}
556
-
557
-		throw new \Sabre\DAV\Exception($e->getMessage(), 0, $e);
558
-	}
559
-
560
-	/**
561
-	 * Get the checksum for this file
562
-	 *
563
-	 * @return string
564
-	 */
565
-	public function getChecksum() {
566
-		return $this->info->getChecksum();
567
-	}
60
+    /**
61
+     * Updates the data
62
+     *
63
+     * The data argument is a readable stream resource.
64
+     *
65
+     * After a successful put operation, you may choose to return an ETag. The
66
+     * etag must always be surrounded by double-quotes. These quotes must
67
+     * appear in the actual string you're returning.
68
+     *
69
+     * Clients may use the ETag from a PUT request to later on make sure that
70
+     * when they update the file, the contents haven't changed in the mean
71
+     * time.
72
+     *
73
+     * If you don't plan to store the file byte-by-byte, and you return a
74
+     * different object on a subsequent GET you are strongly recommended to not
75
+     * return an ETag, and just return null.
76
+     *
77
+     * @param resource $data
78
+     *
79
+     * @throws Forbidden
80
+     * @throws UnsupportedMediaType
81
+     * @throws BadRequest
82
+     * @throws Exception
83
+     * @throws EntityTooLarge
84
+     * @throws ServiceUnavailable
85
+     * @throws FileLocked
86
+     * @return string|null
87
+     */
88
+    public function put($data) {
89
+        try {
90
+            $exists = $this->fileView->file_exists($this->path);
91
+            if ($this->info && $exists && !$this->info->isUpdateable()) {
92
+                throw new Forbidden();
93
+            }
94
+        } catch (StorageNotAvailableException $e) {
95
+            throw new ServiceUnavailable("File is not updatable: " . $e->getMessage());
96
+        }
97
+
98
+        // verify path of the target
99
+        $this->verifyPath();
100
+
101
+        // chunked handling
102
+        if (isset($_SERVER['HTTP_OC_CHUNKED'])) {
103
+            try {
104
+                return $this->createFileChunked($data);
105
+            } catch (\Exception $e) {
106
+                $this->convertToSabreException($e);
107
+            }
108
+        }
109
+
110
+        list($partStorage) = $this->fileView->resolvePath($this->path);
111
+        $needsPartFile = $this->needsPartFile($partStorage) && (strlen($this->path) > 1);
112
+
113
+        if ($needsPartFile) {
114
+            // mark file as partial while uploading (ignored by the scanner)
115
+            $partFilePath = $this->getPartFileBasePath($this->path) . '.ocTransferId' . rand() . '.part';
116
+        } else {
117
+            // upload file directly as the final path
118
+            $partFilePath = $this->path;
119
+        }
120
+
121
+        // the part file and target file might be on a different storage in case of a single file storage (e.g. single file share)
122
+        /** @var \OC\Files\Storage\Storage $partStorage */
123
+        list($partStorage, $internalPartPath) = $this->fileView->resolvePath($partFilePath);
124
+        /** @var \OC\Files\Storage\Storage $storage */
125
+        list($storage, $internalPath) = $this->fileView->resolvePath($this->path);
126
+        try {
127
+            $target = $partStorage->fopen($internalPartPath, 'wb');
128
+            if ($target === false) {
129
+                \OCP\Util::writeLog('webdav', '\OC\Files\Filesystem::fopen() failed', \OCP\Util::ERROR);
130
+                // because we have no clue about the cause we can only throw back a 500/Internal Server Error
131
+                throw new Exception('Could not write file contents');
132
+            }
133
+            list($count, $result) = \OC_Helper::streamCopy($data, $target);
134
+            fclose($target);
135
+
136
+            if ($result === false) {
137
+                $expected = -1;
138
+                if (isset($_SERVER['CONTENT_LENGTH'])) {
139
+                    $expected = $_SERVER['CONTENT_LENGTH'];
140
+                }
141
+                throw new Exception('Error while copying file to target location (copied bytes: ' . $count . ', expected filesize: ' . $expected . ' )');
142
+            }
143
+
144
+            // if content length is sent by client:
145
+            // double check if the file was fully received
146
+            // compare expected and actual size
147
+            if (isset($_SERVER['CONTENT_LENGTH']) && $_SERVER['REQUEST_METHOD'] !== 'LOCK') {
148
+                $expected = $_SERVER['CONTENT_LENGTH'];
149
+                if ($count != $expected) {
150
+                    throw new BadRequest('expected filesize ' . $expected . ' got ' . $count);
151
+                }
152
+            }
153
+
154
+        } catch (\Exception $e) {
155
+            if ($needsPartFile) {
156
+                $partStorage->unlink($internalPartPath);
157
+            }
158
+            $this->convertToSabreException($e);
159
+        }
160
+
161
+        try {
162
+            $view = \OC\Files\Filesystem::getView();
163
+            if ($view) {
164
+                $run = $this->emitPreHooks($exists);
165
+            } else {
166
+                $run = true;
167
+            }
168
+
169
+            try {
170
+                $this->changeLock(ILockingProvider::LOCK_EXCLUSIVE);
171
+            } catch (LockedException $e) {
172
+                if ($needsPartFile) {
173
+                    $partStorage->unlink($internalPartPath);
174
+                }
175
+                throw new FileLocked($e->getMessage(), $e->getCode(), $e);
176
+            }
177
+
178
+            if ($needsPartFile) {
179
+                // rename to correct path
180
+                try {
181
+                    if ($run) {
182
+                        $renameOkay = $storage->moveFromStorage($partStorage, $internalPartPath, $internalPath);
183
+                        $fileExists = $storage->file_exists($internalPath);
184
+                    }
185
+                    if (!$run || $renameOkay === false || $fileExists === false) {
186
+                        \OCP\Util::writeLog('webdav', 'renaming part file to final file failed', \OCP\Util::ERROR);
187
+                        throw new Exception('Could not rename part file to final file');
188
+                    }
189
+                } catch (ForbiddenException $ex) {
190
+                    throw new DAVForbiddenException($ex->getMessage(), $ex->getRetry());
191
+                } catch (\Exception $e) {
192
+                    $partStorage->unlink($internalPartPath);
193
+                    $this->convertToSabreException($e);
194
+                }
195
+            }
196
+
197
+            // since we skipped the view we need to scan and emit the hooks ourselves
198
+            $storage->getUpdater()->update($internalPath);
199
+
200
+            try {
201
+                $this->changeLock(ILockingProvider::LOCK_SHARED);
202
+            } catch (LockedException $e) {
203
+                throw new FileLocked($e->getMessage(), $e->getCode(), $e);
204
+            }
205
+
206
+            if ($view) {
207
+                $this->emitPostHooks($exists);
208
+            }
209
+
210
+            // allow sync clients to send the mtime along in a header
211
+            $request = \OC::$server->getRequest();
212
+            if (isset($request->server['HTTP_X_OC_MTIME'])) {
213
+                if ($this->fileView->touch($this->path, $request->server['HTTP_X_OC_MTIME'])) {
214
+                    header('X-OC-MTime: accepted');
215
+                }
216
+            }
217
+
218
+            $this->refreshInfo();
219
+
220
+            if (isset($request->server['HTTP_OC_CHECKSUM'])) {
221
+                $checksum = trim($request->server['HTTP_OC_CHECKSUM']);
222
+                $this->fileView->putFileInfo($this->path, ['checksum' => $checksum]);
223
+                $this->refreshInfo();
224
+            } else if ($this->getChecksum() !== null && $this->getChecksum() !== '') {
225
+                $this->fileView->putFileInfo($this->path, ['checksum' => '']);
226
+                $this->refreshInfo();
227
+            }
228
+
229
+        } catch (StorageNotAvailableException $e) {
230
+            throw new ServiceUnavailable("Failed to check file size: " . $e->getMessage());
231
+        }
232
+
233
+        return '"' . $this->info->getEtag() . '"';
234
+    }
235
+
236
+    private function getPartFileBasePath($path) {
237
+        $partFileInStorage = \OC::$server->getConfig()->getSystemValue('part_file_in_storage', true);
238
+        if ($partFileInStorage) {
239
+            return $path;
240
+        } else {
241
+            return md5($path); // will place it in the root of the view with a unique name
242
+        }
243
+    }
244
+
245
+    /**
246
+     * @param string $path
247
+     */
248
+    private function emitPreHooks($exists, $path = null) {
249
+        if (is_null($path)) {
250
+            $path = $this->path;
251
+        }
252
+        $hookPath = Filesystem::getView()->getRelativePath($this->fileView->getAbsolutePath($path));
253
+        $run = true;
254
+
255
+        if (!$exists) {
256
+            \OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_create, array(
257
+                \OC\Files\Filesystem::signal_param_path => $hookPath,
258
+                \OC\Files\Filesystem::signal_param_run => &$run,
259
+            ));
260
+        } else {
261
+            \OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_update, array(
262
+                \OC\Files\Filesystem::signal_param_path => $hookPath,
263
+                \OC\Files\Filesystem::signal_param_run => &$run,
264
+            ));
265
+        }
266
+        \OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_write, array(
267
+            \OC\Files\Filesystem::signal_param_path => $hookPath,
268
+            \OC\Files\Filesystem::signal_param_run => &$run,
269
+        ));
270
+        return $run;
271
+    }
272
+
273
+    /**
274
+     * @param string $path
275
+     */
276
+    private function emitPostHooks($exists, $path = null) {
277
+        if (is_null($path)) {
278
+            $path = $this->path;
279
+        }
280
+        $hookPath = Filesystem::getView()->getRelativePath($this->fileView->getAbsolutePath($path));
281
+        if (!$exists) {
282
+            \OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_post_create, array(
283
+                \OC\Files\Filesystem::signal_param_path => $hookPath
284
+            ));
285
+        } else {
286
+            \OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_post_update, array(
287
+                \OC\Files\Filesystem::signal_param_path => $hookPath
288
+            ));
289
+        }
290
+        \OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_post_write, array(
291
+            \OC\Files\Filesystem::signal_param_path => $hookPath
292
+        ));
293
+    }
294
+
295
+    /**
296
+     * Returns the data
297
+     *
298
+     * @return resource
299
+     * @throws Forbidden
300
+     * @throws ServiceUnavailable
301
+     */
302
+    public function get() {
303
+        //throw exception if encryption is disabled but files are still encrypted
304
+        try {
305
+            $res = $this->fileView->fopen(ltrim($this->path, '/'), 'rb');
306
+            if ($res === false) {
307
+                throw new ServiceUnavailable("Could not open file");
308
+            }
309
+            return $res;
310
+        } catch (GenericEncryptionException $e) {
311
+            // returning 503 will allow retry of the operation at a later point in time
312
+            throw new ServiceUnavailable("Encryption not ready: " . $e->getMessage());
313
+        } catch (StorageNotAvailableException $e) {
314
+            throw new ServiceUnavailable("Failed to open file: " . $e->getMessage());
315
+        } catch (ForbiddenException $ex) {
316
+            throw new DAVForbiddenException($ex->getMessage(), $ex->getRetry());
317
+        } catch (LockedException $e) {
318
+            throw new FileLocked($e->getMessage(), $e->getCode(), $e);
319
+        }
320
+    }
321
+
322
+    /**
323
+     * Delete the current file
324
+     *
325
+     * @throws Forbidden
326
+     * @throws ServiceUnavailable
327
+     */
328
+    public function delete() {
329
+        if (!$this->info->isDeletable()) {
330
+            throw new Forbidden();
331
+        }
332
+
333
+        try {
334
+            if (!$this->fileView->unlink($this->path)) {
335
+                // assume it wasn't possible to delete due to permissions
336
+                throw new Forbidden();
337
+            }
338
+        } catch (StorageNotAvailableException $e) {
339
+            throw new ServiceUnavailable("Failed to unlink: " . $e->getMessage());
340
+        } catch (ForbiddenException $ex) {
341
+            throw new DAVForbiddenException($ex->getMessage(), $ex->getRetry());
342
+        } catch (LockedException $e) {
343
+            throw new FileLocked($e->getMessage(), $e->getCode(), $e);
344
+        }
345
+    }
346
+
347
+    /**
348
+     * Returns the mime-type for a file
349
+     *
350
+     * If null is returned, we'll assume application/octet-stream
351
+     *
352
+     * @return string
353
+     */
354
+    public function getContentType() {
355
+        $mimeType = $this->info->getMimetype();
356
+
357
+        // PROPFIND needs to return the correct mime type, for consistency with the web UI
358
+        if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PROPFIND') {
359
+            return $mimeType;
360
+        }
361
+        return \OC::$server->getMimeTypeDetector()->getSecureMimeType($mimeType);
362
+    }
363
+
364
+    /**
365
+     * @return array|false
366
+     */
367
+    public function getDirectDownload() {
368
+        if (\OCP\App::isEnabled('encryption')) {
369
+            return [];
370
+        }
371
+        /** @var \OCP\Files\Storage $storage */
372
+        list($storage, $internalPath) = $this->fileView->resolvePath($this->path);
373
+        if (is_null($storage)) {
374
+            return [];
375
+        }
376
+
377
+        return $storage->getDirectDownload($internalPath);
378
+    }
379
+
380
+    /**
381
+     * @param resource $data
382
+     * @return null|string
383
+     * @throws Exception
384
+     * @throws BadRequest
385
+     * @throws NotImplemented
386
+     * @throws ServiceUnavailable
387
+     */
388
+    private function createFileChunked($data) {
389
+        list($path, $name) = \Sabre\HTTP\URLUtil::splitPath($this->path);
390
+
391
+        $info = \OC_FileChunking::decodeName($name);
392
+        if (empty($info)) {
393
+            throw new NotImplemented('Invalid chunk name');
394
+        }
395
+
396
+        $chunk_handler = new \OC_FileChunking($info);
397
+        $bytesWritten = $chunk_handler->store($info['index'], $data);
398
+
399
+        //detect aborted upload
400
+        if (isset ($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PUT') {
401
+            if (isset($_SERVER['CONTENT_LENGTH'])) {
402
+                $expected = $_SERVER['CONTENT_LENGTH'];
403
+                if ($bytesWritten != $expected) {
404
+                    $chunk_handler->remove($info['index']);
405
+                    throw new BadRequest(
406
+                        'expected filesize ' . $expected . ' got ' . $bytesWritten);
407
+                }
408
+            }
409
+        }
410
+
411
+        if ($chunk_handler->isComplete()) {
412
+            list($storage,) = $this->fileView->resolvePath($path);
413
+            $needsPartFile = $this->needsPartFile($storage);
414
+            $partFile = null;
415
+
416
+            $targetPath = $path . '/' . $info['name'];
417
+            /** @var \OC\Files\Storage\Storage $targetStorage */
418
+            list($targetStorage, $targetInternalPath) = $this->fileView->resolvePath($targetPath);
419
+
420
+            $exists = $this->fileView->file_exists($targetPath);
421
+
422
+            try {
423
+                $this->fileView->lockFile($targetPath, ILockingProvider::LOCK_SHARED);
424
+
425
+                $this->emitPreHooks($exists, $targetPath);
426
+                $this->fileView->changeLock($targetPath, ILockingProvider::LOCK_EXCLUSIVE);
427
+                /** @var \OC\Files\Storage\Storage $targetStorage */
428
+                list($targetStorage, $targetInternalPath) = $this->fileView->resolvePath($targetPath);
429
+
430
+                if ($needsPartFile) {
431
+                    // we first assembly the target file as a part file
432
+                    $partFile = $this->getPartFileBasePath($path . '/' . $info['name']) . '.ocTransferId' . $info['transferid'] . '.part';
433
+                    /** @var \OC\Files\Storage\Storage $targetStorage */
434
+                    list($partStorage, $partInternalPath) = $this->fileView->resolvePath($partFile);
435
+
436
+
437
+                    $chunk_handler->file_assemble($partStorage, $partInternalPath, $this->fileView->getAbsolutePath($targetPath));
438
+
439
+                    // here is the final atomic rename
440
+                    $renameOkay = $targetStorage->moveFromStorage($partStorage, $partInternalPath, $targetInternalPath);
441
+                    $fileExists = $targetStorage->file_exists($targetInternalPath);
442
+                    if ($renameOkay === false || $fileExists === false) {
443
+                        \OCP\Util::writeLog('webdav', '\OC\Files\Filesystem::rename() failed', \OCP\Util::ERROR);
444
+                        // only delete if an error occurred and the target file was already created
445
+                        if ($fileExists) {
446
+                            // set to null to avoid double-deletion when handling exception
447
+                            // stray part file
448
+                            $partFile = null;
449
+                            $targetStorage->unlink($targetInternalPath);
450
+                        }
451
+                        $this->fileView->changeLock($targetPath, ILockingProvider::LOCK_SHARED);
452
+                        throw new Exception('Could not rename part file assembled from chunks');
453
+                    }
454
+                } else {
455
+                    // assemble directly into the final file
456
+                    $chunk_handler->file_assemble($targetStorage, $targetInternalPath, $this->fileView->getAbsolutePath($targetPath));
457
+                }
458
+
459
+                // allow sync clients to send the mtime along in a header
460
+                $request = \OC::$server->getRequest();
461
+                if (isset($request->server['HTTP_X_OC_MTIME'])) {
462
+                    if ($targetStorage->touch($targetInternalPath, $request->server['HTTP_X_OC_MTIME'])) {
463
+                        header('X-OC-MTime: accepted');
464
+                    }
465
+                }
466
+
467
+                // since we skipped the view we need to scan and emit the hooks ourselves
468
+                $targetStorage->getUpdater()->update($targetInternalPath);
469
+
470
+                $this->fileView->changeLock($targetPath, ILockingProvider::LOCK_SHARED);
471
+
472
+                $this->emitPostHooks($exists, $targetPath);
473
+
474
+                // FIXME: should call refreshInfo but can't because $this->path is not the of the final file
475
+                $info = $this->fileView->getFileInfo($targetPath);
476
+
477
+                if (isset($request->server['HTTP_OC_CHECKSUM'])) {
478
+                    $checksum = trim($request->server['HTTP_OC_CHECKSUM']);
479
+                    $this->fileView->putFileInfo($targetPath, ['checksum' => $checksum]);
480
+                } else if ($info->getChecksum() !== null && $info->getChecksum() !== '') {
481
+                    $this->fileView->putFileInfo($this->path, ['checksum' => '']);
482
+                }
483
+
484
+                $this->fileView->unlockFile($targetPath, ILockingProvider::LOCK_SHARED);
485
+
486
+                return $info->getEtag();
487
+            } catch (\Exception $e) {
488
+                if ($partFile !== null) {
489
+                    $targetStorage->unlink($targetInternalPath);
490
+                }
491
+                $this->convertToSabreException($e);
492
+            }
493
+        }
494
+
495
+        return null;
496
+    }
497
+
498
+    /**
499
+     * Returns whether a part file is needed for the given storage
500
+     * or whether the file can be assembled/uploaded directly on the
501
+     * target storage.
502
+     *
503
+     * @param \OCP\Files\Storage $storage
504
+     * @return bool true if the storage needs part file handling
505
+     */
506
+    private function needsPartFile($storage) {
507
+        // TODO: in the future use ChunkHandler provided by storage
508
+        // and/or add method on Storage called "needsPartFile()"
509
+        return !$storage->instanceOfStorage('OCA\Files_Sharing\External\Storage') &&
510
+        !$storage->instanceOfStorage('OC\Files\Storage\OwnCloud');
511
+    }
512
+
513
+    /**
514
+     * Convert the given exception to a SabreException instance
515
+     *
516
+     * @param \Exception $e
517
+     *
518
+     * @throws \Sabre\DAV\Exception
519
+     */
520
+    private function convertToSabreException(\Exception $e) {
521
+        if ($e instanceof \Sabre\DAV\Exception) {
522
+            throw $e;
523
+        }
524
+        if ($e instanceof NotPermittedException) {
525
+            // a more general case - due to whatever reason the content could not be written
526
+            throw new Forbidden($e->getMessage(), 0, $e);
527
+        }
528
+        if ($e instanceof ForbiddenException) {
529
+            // the path for the file was forbidden
530
+            throw new DAVForbiddenException($e->getMessage(), $e->getRetry(), $e);
531
+        }
532
+        if ($e instanceof EntityTooLargeException) {
533
+            // the file is too big to be stored
534
+            throw new EntityTooLarge($e->getMessage(), 0, $e);
535
+        }
536
+        if ($e instanceof InvalidContentException) {
537
+            // the file content is not permitted
538
+            throw new UnsupportedMediaType($e->getMessage(), 0, $e);
539
+        }
540
+        if ($e instanceof InvalidPathException) {
541
+            // the path for the file was not valid
542
+            // TODO: find proper http status code for this case
543
+            throw new Forbidden($e->getMessage(), 0, $e);
544
+        }
545
+        if ($e instanceof LockedException || $e instanceof LockNotAcquiredException) {
546
+            // the file is currently being written to by another process
547
+            throw new FileLocked($e->getMessage(), $e->getCode(), $e);
548
+        }
549
+        if ($e instanceof GenericEncryptionException) {
550
+            // returning 503 will allow retry of the operation at a later point in time
551
+            throw new ServiceUnavailable('Encryption not ready: ' . $e->getMessage(), 0, $e);
552
+        }
553
+        if ($e instanceof StorageNotAvailableException) {
554
+            throw new ServiceUnavailable('Failed to write file contents: ' . $e->getMessage(), 0, $e);
555
+        }
556
+
557
+        throw new \Sabre\DAV\Exception($e->getMessage(), 0, $e);
558
+    }
559
+
560
+    /**
561
+     * Get the checksum for this file
562
+     *
563
+     * @return string
564
+     */
565
+    public function getChecksum() {
566
+        return $this->info->getChecksum();
567
+    }
568 568
 }
Please login to merge, or discard this patch.
Spacing   +14 added lines, -14 removed lines patch added patch discarded remove patch
@@ -92,7 +92,7 @@  discard block
 block discarded – undo
92 92
 				throw new Forbidden();
93 93
 			}
94 94
 		} catch (StorageNotAvailableException $e) {
95
-			throw new ServiceUnavailable("File is not updatable: " . $e->getMessage());
95
+			throw new ServiceUnavailable("File is not updatable: ".$e->getMessage());
96 96
 		}
97 97
 
98 98
 		// verify path of the target
@@ -112,7 +112,7 @@  discard block
 block discarded – undo
112 112
 
113 113
 		if ($needsPartFile) {
114 114
 			// mark file as partial while uploading (ignored by the scanner)
115
-			$partFilePath = $this->getPartFileBasePath($this->path) . '.ocTransferId' . rand() . '.part';
115
+			$partFilePath = $this->getPartFileBasePath($this->path).'.ocTransferId'.rand().'.part';
116 116
 		} else {
117 117
 			// upload file directly as the final path
118 118
 			$partFilePath = $this->path;
@@ -138,7 +138,7 @@  discard block
 block discarded – undo
138 138
 				if (isset($_SERVER['CONTENT_LENGTH'])) {
139 139
 					$expected = $_SERVER['CONTENT_LENGTH'];
140 140
 				}
141
-				throw new Exception('Error while copying file to target location (copied bytes: ' . $count . ', expected filesize: ' . $expected . ' )');
141
+				throw new Exception('Error while copying file to target location (copied bytes: '.$count.', expected filesize: '.$expected.' )');
142 142
 			}
143 143
 
144 144
 			// if content length is sent by client:
@@ -147,7 +147,7 @@  discard block
 block discarded – undo
147 147
 			if (isset($_SERVER['CONTENT_LENGTH']) && $_SERVER['REQUEST_METHOD'] !== 'LOCK') {
148 148
 				$expected = $_SERVER['CONTENT_LENGTH'];
149 149
 				if ($count != $expected) {
150
-					throw new BadRequest('expected filesize ' . $expected . ' got ' . $count);
150
+					throw new BadRequest('expected filesize '.$expected.' got '.$count);
151 151
 				}
152 152
 			}
153 153
 
@@ -227,10 +227,10 @@  discard block
 block discarded – undo
227 227
 			}
228 228
 
229 229
 		} catch (StorageNotAvailableException $e) {
230
-			throw new ServiceUnavailable("Failed to check file size: " . $e->getMessage());
230
+			throw new ServiceUnavailable("Failed to check file size: ".$e->getMessage());
231 231
 		}
232 232
 
233
-		return '"' . $this->info->getEtag() . '"';
233
+		return '"'.$this->info->getEtag().'"';
234 234
 	}
235 235
 
236 236
 	private function getPartFileBasePath($path) {
@@ -309,9 +309,9 @@  discard block
 block discarded – undo
309 309
 			return $res;
310 310
 		} catch (GenericEncryptionException $e) {
311 311
 			// returning 503 will allow retry of the operation at a later point in time
312
-			throw new ServiceUnavailable("Encryption not ready: " . $e->getMessage());
312
+			throw new ServiceUnavailable("Encryption not ready: ".$e->getMessage());
313 313
 		} catch (StorageNotAvailableException $e) {
314
-			throw new ServiceUnavailable("Failed to open file: " . $e->getMessage());
314
+			throw new ServiceUnavailable("Failed to open file: ".$e->getMessage());
315 315
 		} catch (ForbiddenException $ex) {
316 316
 			throw new DAVForbiddenException($ex->getMessage(), $ex->getRetry());
317 317
 		} catch (LockedException $e) {
@@ -336,7 +336,7 @@  discard block
 block discarded – undo
336 336
 				throw new Forbidden();
337 337
 			}
338 338
 		} catch (StorageNotAvailableException $e) {
339
-			throw new ServiceUnavailable("Failed to unlink: " . $e->getMessage());
339
+			throw new ServiceUnavailable("Failed to unlink: ".$e->getMessage());
340 340
 		} catch (ForbiddenException $ex) {
341 341
 			throw new DAVForbiddenException($ex->getMessage(), $ex->getRetry());
342 342
 		} catch (LockedException $e) {
@@ -403,7 +403,7 @@  discard block
 block discarded – undo
403 403
 				if ($bytesWritten != $expected) {
404 404
 					$chunk_handler->remove($info['index']);
405 405
 					throw new BadRequest(
406
-						'expected filesize ' . $expected . ' got ' . $bytesWritten);
406
+						'expected filesize '.$expected.' got '.$bytesWritten);
407 407
 				}
408 408
 			}
409 409
 		}
@@ -413,7 +413,7 @@  discard block
 block discarded – undo
413 413
 			$needsPartFile = $this->needsPartFile($storage);
414 414
 			$partFile = null;
415 415
 
416
-			$targetPath = $path . '/' . $info['name'];
416
+			$targetPath = $path.'/'.$info['name'];
417 417
 			/** @var \OC\Files\Storage\Storage $targetStorage */
418 418
 			list($targetStorage, $targetInternalPath) = $this->fileView->resolvePath($targetPath);
419 419
 
@@ -429,7 +429,7 @@  discard block
 block discarded – undo
429 429
 
430 430
 				if ($needsPartFile) {
431 431
 					// we first assembly the target file as a part file
432
-					$partFile = $this->getPartFileBasePath($path . '/' . $info['name']) . '.ocTransferId' . $info['transferid'] . '.part';
432
+					$partFile = $this->getPartFileBasePath($path.'/'.$info['name']).'.ocTransferId'.$info['transferid'].'.part';
433 433
 					/** @var \OC\Files\Storage\Storage $targetStorage */
434 434
 					list($partStorage, $partInternalPath) = $this->fileView->resolvePath($partFile);
435 435
 
@@ -548,10 +548,10 @@  discard block
 block discarded – undo
548 548
 		}
549 549
 		if ($e instanceof GenericEncryptionException) {
550 550
 			// returning 503 will allow retry of the operation at a later point in time
551
-			throw new ServiceUnavailable('Encryption not ready: ' . $e->getMessage(), 0, $e);
551
+			throw new ServiceUnavailable('Encryption not ready: '.$e->getMessage(), 0, $e);
552 552
 		}
553 553
 		if ($e instanceof StorageNotAvailableException) {
554
-			throw new ServiceUnavailable('Failed to write file contents: ' . $e->getMessage(), 0, $e);
554
+			throw new ServiceUnavailable('Failed to write file contents: '.$e->getMessage(), 0, $e);
555 555
 		}
556 556
 
557 557
 		throw new \Sabre\DAV\Exception($e->getMessage(), 0, $e);
Please login to merge, or discard this patch.
apps/dav/lib/connector/sabre/sharesplugin.php 2 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -68,7 +68,7 @@
 block discarded – undo
68 68
 	private $cachedShareTypes;
69 69
 
70 70
 	/**
71
-	 * @param \Sabre\DAV\Tree $tree tree
71
+	 * @param ObjectTree $tree tree
72 72
 	 * @param IUserSession $userSession user session
73 73
 	 * @param \OCP\Files\Folder $userFolder user home folder
74 74
 	 * @param \OCP\Share\IManager $shareManager share manager
Please login to merge, or discard this patch.
Indentation   +143 added lines, -143 removed lines patch added patch discarded remove patch
@@ -32,147 +32,147 @@
 block discarded – undo
32 32
  */
33 33
 class SharesPlugin extends \Sabre\DAV\ServerPlugin {
34 34
 
35
-	const NS_OWNCLOUD = 'http://owncloud.org/ns';
36
-	const SHARETYPES_PROPERTYNAME = '{http://owncloud.org/ns}share-types';
37
-
38
-	/**
39
-	 * Reference to main server object
40
-	 *
41
-	 * @var \Sabre\DAV\Server
42
-	 */
43
-	private $server;
44
-
45
-	/**
46
-	 * @var \OCP\Share\IManager
47
-	 */
48
-	private $shareManager;
49
-
50
-	/**
51
-	 * @var \Sabre\DAV\Tree
52
-	 */
53
-	private $tree;
54
-
55
-	/**
56
-	 * @var string
57
-	 */
58
-	private $userId;
59
-
60
-	/**
61
-	 * @var \OCP\Files\Folder
62
-	 */
63
-	private $userFolder;
64
-
65
-	/**
66
-	 * @var IShare[]
67
-	 */
68
-	private $cachedShareTypes;
69
-
70
-	/**
71
-	 * @param \Sabre\DAV\Tree $tree tree
72
-	 * @param IUserSession $userSession user session
73
-	 * @param \OCP\Files\Folder $userFolder user home folder
74
-	 * @param \OCP\Share\IManager $shareManager share manager
75
-	 */
76
-	public function __construct(
77
-		\Sabre\DAV\Tree $tree,
78
-		IUserSession $userSession,
79
-		\OCP\Files\Folder $userFolder,
80
-		\OCP\Share\IManager $shareManager
81
-	) {
82
-		$this->tree = $tree;
83
-		$this->shareManager = $shareManager;
84
-		$this->userFolder = $userFolder;
85
-		$this->userId = $userSession->getUser()->getUID();
86
-		$this->cachedShareTypes = [];
87
-	}
88
-
89
-	/**
90
-	 * This initializes the plugin.
91
-	 *
92
-	 * This function is called by \Sabre\DAV\Server, after
93
-	 * addPlugin is called.
94
-	 *
95
-	 * This method should set up the required event subscriptions.
96
-	 *
97
-	 * @param \Sabre\DAV\Server $server
98
-	 */
99
-	public function initialize(\Sabre\DAV\Server $server) {
100
-		$server->xml->namespacesMap[self::NS_OWNCLOUD] = 'oc';
101
-		$server->xml->elementMap[self::SHARETYPES_PROPERTYNAME] = 'OCA\\DAV\\Connector\\Sabre\\ShareTypeList';
102
-		$server->protectedProperties[] = self::SHARETYPES_PROPERTYNAME;
103
-
104
-		$this->server = $server;
105
-		$this->server->on('propFind', array($this, 'handleGetProperties'));
106
-	}
107
-
108
-	/**
109
-	 * Return a list of share types for outgoing shares
110
-	 *
111
-	 * @param \OCP\Files\Node $node file node
112
-	 *
113
-	 * @return int[] array of share types
114
-	 */
115
-	private function getShareTypes(\OCP\Files\Node $node) {
116
-		$shareTypes = [];
117
-		$requestedShareTypes = [
118
-			\OCP\Share::SHARE_TYPE_USER,
119
-			\OCP\Share::SHARE_TYPE_GROUP,
120
-			\OCP\Share::SHARE_TYPE_LINK,
121
-			\OCP\Share::SHARE_TYPE_REMOTE
122
-		];
123
-		foreach ($requestedShareTypes as $requestedShareType) {
124
-			// one of each type is enough to find out about the types
125
-			$shares = $this->shareManager->getSharesBy(
126
-				$this->userId,
127
-				$requestedShareType,
128
-				$node,
129
-				false,
130
-				1
131
-			);
132
-			if (!empty($shares)) {
133
-				$shareTypes[] = $requestedShareType;
134
-			}
135
-		}
136
-		return $shareTypes;
137
-	}
138
-
139
-	/**
140
-	 * Adds shares to propfind response
141
-	 *
142
-	 * @param PropFind $propFind propfind object
143
-	 * @param \Sabre\DAV\INode $sabreNode sabre node
144
-	 */
145
-	public function handleGetProperties(
146
-		PropFind $propFind,
147
-		\Sabre\DAV\INode $sabreNode
148
-	) {
149
-		if (!($sabreNode instanceof \OCA\DAV\Connector\Sabre\Node)) {
150
-			return;
151
-		}
152
-
153
-		// need prefetch ?
154
-		if ($sabreNode instanceof \OCA\DAV\Connector\Sabre\Directory
155
-			&& $propFind->getDepth() !== 0
156
-			&& !is_null($propFind->getStatus(self::SHARETYPES_PROPERTYNAME))
157
-		) {
158
-			$folderNode = $this->userFolder->get($propFind->getPath());
159
-			$children = $folderNode->getDirectoryListing();
160
-
161
-			$this->cachedShareTypes[$folderNode->getId()] = $this->getShareTypes($folderNode);
162
-			foreach ($children as $childNode) {
163
-				$this->cachedShareTypes[$childNode->getId()] = $this->getShareTypes($childNode);
164
-			}
165
-		}
166
-
167
-		$propFind->handle(self::SHARETYPES_PROPERTYNAME, function() use ($sabreNode) {
168
-			if (isset($this->cachedShareTypes[$sabreNode->getId()])) {
169
-				$shareTypes = $this->cachedShareTypes[$sabreNode->getId()];
170
-			} else {
171
-				$node = $this->userFolder->get($sabreNode->getPath());
172
-				$shareTypes = $this->getShareTypes($node);
173
-			}
174
-
175
-			return new ShareTypeList($shareTypes);
176
-		});
177
-	}
35
+    const NS_OWNCLOUD = 'http://owncloud.org/ns';
36
+    const SHARETYPES_PROPERTYNAME = '{http://owncloud.org/ns}share-types';
37
+
38
+    /**
39
+     * Reference to main server object
40
+     *
41
+     * @var \Sabre\DAV\Server
42
+     */
43
+    private $server;
44
+
45
+    /**
46
+     * @var \OCP\Share\IManager
47
+     */
48
+    private $shareManager;
49
+
50
+    /**
51
+     * @var \Sabre\DAV\Tree
52
+     */
53
+    private $tree;
54
+
55
+    /**
56
+     * @var string
57
+     */
58
+    private $userId;
59
+
60
+    /**
61
+     * @var \OCP\Files\Folder
62
+     */
63
+    private $userFolder;
64
+
65
+    /**
66
+     * @var IShare[]
67
+     */
68
+    private $cachedShareTypes;
69
+
70
+    /**
71
+     * @param \Sabre\DAV\Tree $tree tree
72
+     * @param IUserSession $userSession user session
73
+     * @param \OCP\Files\Folder $userFolder user home folder
74
+     * @param \OCP\Share\IManager $shareManager share manager
75
+     */
76
+    public function __construct(
77
+        \Sabre\DAV\Tree $tree,
78
+        IUserSession $userSession,
79
+        \OCP\Files\Folder $userFolder,
80
+        \OCP\Share\IManager $shareManager
81
+    ) {
82
+        $this->tree = $tree;
83
+        $this->shareManager = $shareManager;
84
+        $this->userFolder = $userFolder;
85
+        $this->userId = $userSession->getUser()->getUID();
86
+        $this->cachedShareTypes = [];
87
+    }
88
+
89
+    /**
90
+     * This initializes the plugin.
91
+     *
92
+     * This function is called by \Sabre\DAV\Server, after
93
+     * addPlugin is called.
94
+     *
95
+     * This method should set up the required event subscriptions.
96
+     *
97
+     * @param \Sabre\DAV\Server $server
98
+     */
99
+    public function initialize(\Sabre\DAV\Server $server) {
100
+        $server->xml->namespacesMap[self::NS_OWNCLOUD] = 'oc';
101
+        $server->xml->elementMap[self::SHARETYPES_PROPERTYNAME] = 'OCA\\DAV\\Connector\\Sabre\\ShareTypeList';
102
+        $server->protectedProperties[] = self::SHARETYPES_PROPERTYNAME;
103
+
104
+        $this->server = $server;
105
+        $this->server->on('propFind', array($this, 'handleGetProperties'));
106
+    }
107
+
108
+    /**
109
+     * Return a list of share types for outgoing shares
110
+     *
111
+     * @param \OCP\Files\Node $node file node
112
+     *
113
+     * @return int[] array of share types
114
+     */
115
+    private function getShareTypes(\OCP\Files\Node $node) {
116
+        $shareTypes = [];
117
+        $requestedShareTypes = [
118
+            \OCP\Share::SHARE_TYPE_USER,
119
+            \OCP\Share::SHARE_TYPE_GROUP,
120
+            \OCP\Share::SHARE_TYPE_LINK,
121
+            \OCP\Share::SHARE_TYPE_REMOTE
122
+        ];
123
+        foreach ($requestedShareTypes as $requestedShareType) {
124
+            // one of each type is enough to find out about the types
125
+            $shares = $this->shareManager->getSharesBy(
126
+                $this->userId,
127
+                $requestedShareType,
128
+                $node,
129
+                false,
130
+                1
131
+            );
132
+            if (!empty($shares)) {
133
+                $shareTypes[] = $requestedShareType;
134
+            }
135
+        }
136
+        return $shareTypes;
137
+    }
138
+
139
+    /**
140
+     * Adds shares to propfind response
141
+     *
142
+     * @param PropFind $propFind propfind object
143
+     * @param \Sabre\DAV\INode $sabreNode sabre node
144
+     */
145
+    public function handleGetProperties(
146
+        PropFind $propFind,
147
+        \Sabre\DAV\INode $sabreNode
148
+    ) {
149
+        if (!($sabreNode instanceof \OCA\DAV\Connector\Sabre\Node)) {
150
+            return;
151
+        }
152
+
153
+        // need prefetch ?
154
+        if ($sabreNode instanceof \OCA\DAV\Connector\Sabre\Directory
155
+            && $propFind->getDepth() !== 0
156
+            && !is_null($propFind->getStatus(self::SHARETYPES_PROPERTYNAME))
157
+        ) {
158
+            $folderNode = $this->userFolder->get($propFind->getPath());
159
+            $children = $folderNode->getDirectoryListing();
160
+
161
+            $this->cachedShareTypes[$folderNode->getId()] = $this->getShareTypes($folderNode);
162
+            foreach ($children as $childNode) {
163
+                $this->cachedShareTypes[$childNode->getId()] = $this->getShareTypes($childNode);
164
+            }
165
+        }
166
+
167
+        $propFind->handle(self::SHARETYPES_PROPERTYNAME, function() use ($sabreNode) {
168
+            if (isset($this->cachedShareTypes[$sabreNode->getId()])) {
169
+                $shareTypes = $this->cachedShareTypes[$sabreNode->getId()];
170
+            } else {
171
+                $node = $this->userFolder->get($sabreNode->getPath());
172
+                $shareTypes = $this->getShareTypes($node);
173
+            }
174
+
175
+            return new ShareTypeList($shareTypes);
176
+        });
177
+    }
178 178
 }
Please login to merge, or discard this patch.
apps/dav/lib/dav/systemprincipalbackend.php 2 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -132,7 +132,7 @@
 block discarded – undo
132 132
 	 * Returns the list of members for a group-principal
133 133
 	 *
134 134
 	 * @param string $principal
135
-	 * @return array
135
+	 * @return string[]
136 136
 	 */
137 137
 	function getGroupMemberSet($principal) {
138 138
 		// TODO: for now the group principal has only one member, the user itself
Please login to merge, or discard this patch.
Indentation   +150 added lines, -150 removed lines patch added patch discarded remove patch
@@ -27,154 +27,154 @@
 block discarded – undo
27 27
 
28 28
 class SystemPrincipalBackend extends AbstractBackend {
29 29
 
30
-	/**
31
-	 * Returns a list of principals based on a prefix.
32
-	 *
33
-	 * This prefix will often contain something like 'principals'. You are only
34
-	 * expected to return principals that are in this base path.
35
-	 *
36
-	 * You are expected to return at least a 'uri' for every user, you can
37
-	 * return any additional properties if you wish so. Common properties are:
38
-	 *   {DAV:}displayname
39
-	 *   {http://sabredav.org/ns}email-address - This is a custom SabreDAV
40
-	 *     field that's actually injected in a number of other properties. If
41
-	 *     you have an email address, use this property.
42
-	 *
43
-	 * @param string $prefixPath
44
-	 * @return array
45
-	 */
46
-	function getPrincipalsByPrefix($prefixPath) {
47
-		$principals = [];
48
-
49
-		if ($prefixPath === 'principals/system') {
50
-			$principals[] = [
51
-				'uri' => 'principals/system/system',
52
-				'{DAV:}displayname' => 'system',
53
-			];
54
-		}
55
-
56
-		return $principals;
57
-	}
58
-
59
-	/**
60
-	 * Returns a specific principal, specified by it's path.
61
-	 * The returned structure should be the exact same as from
62
-	 * getPrincipalsByPrefix.
63
-	 *
64
-	 * @param string $path
65
-	 * @return array
66
-	 */
67
-	function getPrincipalByPath($path) {
68
-
69
-		if ($path === 'principals/system/system') {
70
-			$principal = [
71
-				'uri' => 'principals/system/system',
72
-				'{DAV:}displayname' => 'system',
73
-			];
74
-			return $principal;
75
-		}
76
-
77
-		return null;
78
-	}
79
-
80
-	/**
81
-	 * Updates one ore more webdav properties on a principal.
82
-	 *
83
-	 * The list of mutations is stored in a Sabre\DAV\PropPatch object.
84
-	 * To do the actual updates, you must tell this object which properties
85
-	 * you're going to process with the handle() method.
86
-	 *
87
-	 * Calling the handle method is like telling the PropPatch object "I
88
-	 * promise I can handle updating this property".
89
-	 *
90
-	 * Read the PropPatch documentation for more info and examples.
91
-	 *
92
-	 * @param string $path
93
-	 * @param \Sabre\DAV\PropPatch $propPatch
94
-	 * @return void
95
-	 */
96
-	function updatePrincipal($path, \Sabre\DAV\PropPatch $propPatch) {
97
-	}
98
-
99
-	/**
100
-	 * This method is used to search for principals matching a set of
101
-	 * properties.
102
-	 *
103
-	 * This search is specifically used by RFC3744's principal-property-search
104
-	 * REPORT.
105
-	 *
106
-	 * The actual search should be a unicode-non-case-sensitive search. The
107
-	 * keys in searchProperties are the WebDAV property names, while the values
108
-	 * are the property values to search on.
109
-	 *
110
-	 * By default, if multiple properties are submitted to this method, the
111
-	 * various properties should be combined with 'AND'. If $test is set to
112
-	 * 'anyof', it should be combined using 'OR'.
113
-	 *
114
-	 * This method should simply return an array with full principal uri's.
115
-	 *
116
-	 * If somebody attempted to search on a property the backend does not
117
-	 * support, you should simply return 0 results.
118
-	 *
119
-	 * You can also just return 0 results if you choose to not support
120
-	 * searching at all, but keep in mind that this may stop certain features
121
-	 * from working.
122
-	 *
123
-	 * @param string $prefixPath
124
-	 * @param array $searchProperties
125
-	 * @param string $test
126
-	 * @return array
127
-	 */
128
-	function searchPrincipals($prefixPath, array $searchProperties, $test = 'allof') {
129
-		return [];
130
-	}
131
-
132
-	/**
133
-	 * Returns the list of members for a group-principal
134
-	 *
135
-	 * @param string $principal
136
-	 * @return array
137
-	 */
138
-	function getGroupMemberSet($principal) {
139
-		// TODO: for now the group principal has only one member, the user itself
140
-		$principal = $this->getPrincipalByPath($principal);
141
-		if (!$principal) {
142
-			throw new \Sabre\DAV\Exception('Principal not found');
143
-		}
144
-
145
-		return [$principal['uri']];
146
-	}
147
-
148
-	/**
149
-	 * Returns the list of groups a principal is a member of
150
-	 *
151
-	 * @param string $principal
152
-	 * @return array
153
-	 */
154
-	function getGroupMembership($principal) {
155
-		list($prefix, $name) = URLUtil::splitPath($principal);
156
-
157
-		if ($prefix === 'principals/system') {
158
-			$principal = $this->getPrincipalByPath($principal);
159
-			if (!$principal) {
160
-				throw new \Sabre\DAV\Exception('Principal not found');
161
-			}
162
-
163
-			return [];
164
-		}
165
-		return [];
166
-	}
167
-
168
-	/**
169
-	 * Updates the list of group members for a group principal.
170
-	 *
171
-	 * The principals should be passed as a list of uri's.
172
-	 *
173
-	 * @param string $principal
174
-	 * @param array $members
175
-	 * @return void
176
-	 */
177
-	function setGroupMemberSet($principal, array $members) {
178
-		throw new \Sabre\DAV\Exception('Setting members of the group is not supported yet');
179
-	}
30
+    /**
31
+     * Returns a list of principals based on a prefix.
32
+     *
33
+     * This prefix will often contain something like 'principals'. You are only
34
+     * expected to return principals that are in this base path.
35
+     *
36
+     * You are expected to return at least a 'uri' for every user, you can
37
+     * return any additional properties if you wish so. Common properties are:
38
+     *   {DAV:}displayname
39
+     *   {http://sabredav.org/ns}email-address - This is a custom SabreDAV
40
+     *     field that's actually injected in a number of other properties. If
41
+     *     you have an email address, use this property.
42
+     *
43
+     * @param string $prefixPath
44
+     * @return array
45
+     */
46
+    function getPrincipalsByPrefix($prefixPath) {
47
+        $principals = [];
48
+
49
+        if ($prefixPath === 'principals/system') {
50
+            $principals[] = [
51
+                'uri' => 'principals/system/system',
52
+                '{DAV:}displayname' => 'system',
53
+            ];
54
+        }
55
+
56
+        return $principals;
57
+    }
58
+
59
+    /**
60
+     * Returns a specific principal, specified by it's path.
61
+     * The returned structure should be the exact same as from
62
+     * getPrincipalsByPrefix.
63
+     *
64
+     * @param string $path
65
+     * @return array
66
+     */
67
+    function getPrincipalByPath($path) {
68
+
69
+        if ($path === 'principals/system/system') {
70
+            $principal = [
71
+                'uri' => 'principals/system/system',
72
+                '{DAV:}displayname' => 'system',
73
+            ];
74
+            return $principal;
75
+        }
76
+
77
+        return null;
78
+    }
79
+
80
+    /**
81
+     * Updates one ore more webdav properties on a principal.
82
+     *
83
+     * The list of mutations is stored in a Sabre\DAV\PropPatch object.
84
+     * To do the actual updates, you must tell this object which properties
85
+     * you're going to process with the handle() method.
86
+     *
87
+     * Calling the handle method is like telling the PropPatch object "I
88
+     * promise I can handle updating this property".
89
+     *
90
+     * Read the PropPatch documentation for more info and examples.
91
+     *
92
+     * @param string $path
93
+     * @param \Sabre\DAV\PropPatch $propPatch
94
+     * @return void
95
+     */
96
+    function updatePrincipal($path, \Sabre\DAV\PropPatch $propPatch) {
97
+    }
98
+
99
+    /**
100
+     * This method is used to search for principals matching a set of
101
+     * properties.
102
+     *
103
+     * This search is specifically used by RFC3744's principal-property-search
104
+     * REPORT.
105
+     *
106
+     * The actual search should be a unicode-non-case-sensitive search. The
107
+     * keys in searchProperties are the WebDAV property names, while the values
108
+     * are the property values to search on.
109
+     *
110
+     * By default, if multiple properties are submitted to this method, the
111
+     * various properties should be combined with 'AND'. If $test is set to
112
+     * 'anyof', it should be combined using 'OR'.
113
+     *
114
+     * This method should simply return an array with full principal uri's.
115
+     *
116
+     * If somebody attempted to search on a property the backend does not
117
+     * support, you should simply return 0 results.
118
+     *
119
+     * You can also just return 0 results if you choose to not support
120
+     * searching at all, but keep in mind that this may stop certain features
121
+     * from working.
122
+     *
123
+     * @param string $prefixPath
124
+     * @param array $searchProperties
125
+     * @param string $test
126
+     * @return array
127
+     */
128
+    function searchPrincipals($prefixPath, array $searchProperties, $test = 'allof') {
129
+        return [];
130
+    }
131
+
132
+    /**
133
+     * Returns the list of members for a group-principal
134
+     *
135
+     * @param string $principal
136
+     * @return array
137
+     */
138
+    function getGroupMemberSet($principal) {
139
+        // TODO: for now the group principal has only one member, the user itself
140
+        $principal = $this->getPrincipalByPath($principal);
141
+        if (!$principal) {
142
+            throw new \Sabre\DAV\Exception('Principal not found');
143
+        }
144
+
145
+        return [$principal['uri']];
146
+    }
147
+
148
+    /**
149
+     * Returns the list of groups a principal is a member of
150
+     *
151
+     * @param string $principal
152
+     * @return array
153
+     */
154
+    function getGroupMembership($principal) {
155
+        list($prefix, $name) = URLUtil::splitPath($principal);
156
+
157
+        if ($prefix === 'principals/system') {
158
+            $principal = $this->getPrincipalByPath($principal);
159
+            if (!$principal) {
160
+                throw new \Sabre\DAV\Exception('Principal not found');
161
+            }
162
+
163
+            return [];
164
+        }
165
+        return [];
166
+    }
167
+
168
+    /**
169
+     * Updates the list of group members for a group principal.
170
+     *
171
+     * The principals should be passed as a list of uri's.
172
+     *
173
+     * @param string $principal
174
+     * @param array $members
175
+     * @return void
176
+     */
177
+    function setGroupMemberSet($principal, array $members) {
178
+        throw new \Sabre\DAV\Exception('Setting members of the group is not supported yet');
179
+    }
180 180
 }
Please login to merge, or discard this patch.