Completed
Pull Request — master (#3838)
by Vars
12:18
created
apps/dav/lib/Connector/Sabre/Exception/UnsupportedMediaType.php 1 patch
Indentation   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -31,15 +31,15 @@
 block discarded – undo
31 31
  */
32 32
 class UnsupportedMediaType extends \Sabre\DAV\Exception {
33 33
 
34
-	/**
35
-	 * Returns the HTTP status code for this exception
36
-	 *
37
-	 * @return int
38
-	 */
39
-	public function getHTTPCode() {
34
+    /**
35
+     * Returns the HTTP status code for this exception
36
+     *
37
+     * @return int
38
+     */
39
+    public function getHTTPCode() {
40 40
 
41
-		return 415;
41
+        return 415;
42 42
 
43
-	}
43
+    }
44 44
 
45 45
 }
Please login to merge, or discard this patch.
apps/dav/lib/Connector/Sabre/Exception/EntityTooLarge.php 1 patch
Indentation   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -31,15 +31,15 @@
 block discarded – undo
31 31
  */
32 32
 class EntityTooLarge extends \Sabre\DAV\Exception {
33 33
 
34
-	/**
35
-	 * Returns the HTTP status code for this exception
36
-	 *
37
-	 * @return int
38
-	 */
39
-	public function getHTTPCode() {
34
+    /**
35
+     * Returns the HTTP status code for this exception
36
+     *
37
+     * @return int
38
+     */
39
+    public function getHTTPCode() {
40 40
 
41
-		return 413;
41
+        return 413;
42 42
 
43
-	}
43
+    }
44 44
 
45 45
 }
Please login to merge, or discard this patch.
apps/dav/lib/Connector/Sabre/ServerFactory.php 1 patch
Indentation   +145 added lines, -145 removed lines patch added patch discarded remove patch
@@ -42,158 +42,158 @@
 block discarded – undo
42 42
 use Sabre\DAV\Auth\Backend\BackendInterface;
43 43
 
44 44
 class ServerFactory {
45
-	/** @var IConfig */
46
-	private $config;
47
-	/** @var ILogger */
48
-	private $logger;
49
-	/** @var IDBConnection */
50
-	private $databaseConnection;
51
-	/** @var IUserSession */
52
-	private $userSession;
53
-	/** @var IMountManager */
54
-	private $mountManager;
55
-	/** @var ITagManager */
56
-	private $tagManager;
57
-	/** @var IRequest */
58
-	private $request;
59
-	/** @var IPreview  */
60
-	private $previewManager;
45
+    /** @var IConfig */
46
+    private $config;
47
+    /** @var ILogger */
48
+    private $logger;
49
+    /** @var IDBConnection */
50
+    private $databaseConnection;
51
+    /** @var IUserSession */
52
+    private $userSession;
53
+    /** @var IMountManager */
54
+    private $mountManager;
55
+    /** @var ITagManager */
56
+    private $tagManager;
57
+    /** @var IRequest */
58
+    private $request;
59
+    /** @var IPreview  */
60
+    private $previewManager;
61 61
 
62
-	/**
63
-	 * @param IConfig $config
64
-	 * @param ILogger $logger
65
-	 * @param IDBConnection $databaseConnection
66
-	 * @param IUserSession $userSession
67
-	 * @param IMountManager $mountManager
68
-	 * @param ITagManager $tagManager
69
-	 * @param IRequest $request
70
-	 * @param IPreview $previewManager
71
-	 */
72
-	public function __construct(
73
-		IConfig $config,
74
-		ILogger $logger,
75
-		IDBConnection $databaseConnection,
76
-		IUserSession $userSession,
77
-		IMountManager $mountManager,
78
-		ITagManager $tagManager,
79
-		IRequest $request,
80
-		IPreview $previewManager
81
-	) {
82
-		$this->config = $config;
83
-		$this->logger = $logger;
84
-		$this->databaseConnection = $databaseConnection;
85
-		$this->userSession = $userSession;
86
-		$this->mountManager = $mountManager;
87
-		$this->tagManager = $tagManager;
88
-		$this->request = $request;
89
-		$this->previewManager = $previewManager;
90
-	}
62
+    /**
63
+     * @param IConfig $config
64
+     * @param ILogger $logger
65
+     * @param IDBConnection $databaseConnection
66
+     * @param IUserSession $userSession
67
+     * @param IMountManager $mountManager
68
+     * @param ITagManager $tagManager
69
+     * @param IRequest $request
70
+     * @param IPreview $previewManager
71
+     */
72
+    public function __construct(
73
+        IConfig $config,
74
+        ILogger $logger,
75
+        IDBConnection $databaseConnection,
76
+        IUserSession $userSession,
77
+        IMountManager $mountManager,
78
+        ITagManager $tagManager,
79
+        IRequest $request,
80
+        IPreview $previewManager
81
+    ) {
82
+        $this->config = $config;
83
+        $this->logger = $logger;
84
+        $this->databaseConnection = $databaseConnection;
85
+        $this->userSession = $userSession;
86
+        $this->mountManager = $mountManager;
87
+        $this->tagManager = $tagManager;
88
+        $this->request = $request;
89
+        $this->previewManager = $previewManager;
90
+    }
91 91
 
92
-	/**
93
-	 * @param string $baseUri
94
-	 * @param string $requestUri
95
-	 * @param BackendInterface $authBackend
96
-	 * @param callable $viewCallBack callback that should return the view for the dav endpoint
97
-	 * @return Server
98
-	 */
99
-	public function createServer($baseUri,
100
-								 $requestUri,
101
-								 BackendInterface $authBackend,
102
-								 callable $viewCallBack) {
103
-		// Fire up server
104
-		$objectTree = new \OCA\DAV\Connector\Sabre\ObjectTree();
105
-		$server = new \OCA\DAV\Connector\Sabre\Server($objectTree);
106
-		// Set URL explicitly due to reverse-proxy situations
107
-		$server->httpRequest->setUrl($requestUri);
108
-		$server->setBaseUri($baseUri);
92
+    /**
93
+     * @param string $baseUri
94
+     * @param string $requestUri
95
+     * @param BackendInterface $authBackend
96
+     * @param callable $viewCallBack callback that should return the view for the dav endpoint
97
+     * @return Server
98
+     */
99
+    public function createServer($baseUri,
100
+                                    $requestUri,
101
+                                    BackendInterface $authBackend,
102
+                                    callable $viewCallBack) {
103
+        // Fire up server
104
+        $objectTree = new \OCA\DAV\Connector\Sabre\ObjectTree();
105
+        $server = new \OCA\DAV\Connector\Sabre\Server($objectTree);
106
+        // Set URL explicitly due to reverse-proxy situations
107
+        $server->httpRequest->setUrl($requestUri);
108
+        $server->setBaseUri($baseUri);
109 109
 
110
-		// Load plugins
111
-		$server->addPlugin(new \OCA\DAV\Connector\Sabre\MaintenancePlugin($this->config));
112
-		$server->addPlugin(new \OCA\DAV\Connector\Sabre\BlockLegacyClientPlugin($this->config));
113
-		$server->addPlugin(new \Sabre\DAV\Auth\Plugin($authBackend));
114
-		// FIXME: The following line is a workaround for legacy components relying on being able to send a GET to /
115
-		$server->addPlugin(new \OCA\DAV\Connector\Sabre\DummyGetResponsePlugin());
116
-		$server->addPlugin(new \OCA\DAV\Connector\Sabre\ExceptionLoggerPlugin('webdav', $this->logger));
117
-		$server->addPlugin(new \OCA\DAV\Connector\Sabre\LockPlugin());
118
-		// Some WebDAV clients do require Class 2 WebDAV support (locking), since
119
-		// we do not provide locking we emulate it using a fake locking plugin.
120
-		if($this->request->isUserAgent([
121
-				'/WebDAVFS/',
122
-				'/Microsoft Office OneNote 2013/',
123
-				'/Microsoft-WebDAV-MiniRedir/',
124
-		])) {
125
-			$server->addPlugin(new \OCA\DAV\Connector\Sabre\FakeLockerPlugin());
126
-		}
110
+        // Load plugins
111
+        $server->addPlugin(new \OCA\DAV\Connector\Sabre\MaintenancePlugin($this->config));
112
+        $server->addPlugin(new \OCA\DAV\Connector\Sabre\BlockLegacyClientPlugin($this->config));
113
+        $server->addPlugin(new \Sabre\DAV\Auth\Plugin($authBackend));
114
+        // FIXME: The following line is a workaround for legacy components relying on being able to send a GET to /
115
+        $server->addPlugin(new \OCA\DAV\Connector\Sabre\DummyGetResponsePlugin());
116
+        $server->addPlugin(new \OCA\DAV\Connector\Sabre\ExceptionLoggerPlugin('webdav', $this->logger));
117
+        $server->addPlugin(new \OCA\DAV\Connector\Sabre\LockPlugin());
118
+        // Some WebDAV clients do require Class 2 WebDAV support (locking), since
119
+        // we do not provide locking we emulate it using a fake locking plugin.
120
+        if($this->request->isUserAgent([
121
+                '/WebDAVFS/',
122
+                '/Microsoft Office OneNote 2013/',
123
+                '/Microsoft-WebDAV-MiniRedir/',
124
+        ])) {
125
+            $server->addPlugin(new \OCA\DAV\Connector\Sabre\FakeLockerPlugin());
126
+        }
127 127
 
128
-		if (BrowserErrorPagePlugin::isBrowserRequest($this->request)) {
129
-			$server->addPlugin(new BrowserErrorPagePlugin());
130
-		}
128
+        if (BrowserErrorPagePlugin::isBrowserRequest($this->request)) {
129
+            $server->addPlugin(new BrowserErrorPagePlugin());
130
+        }
131 131
 
132
-		// wait with registering these until auth is handled and the filesystem is setup
133
-		$server->on('beforeMethod', function () use ($server, $objectTree, $viewCallBack) {
134
-			// ensure the skeleton is copied
135
-			$userFolder = \OC::$server->getUserFolder();
132
+        // wait with registering these until auth is handled and the filesystem is setup
133
+        $server->on('beforeMethod', function () use ($server, $objectTree, $viewCallBack) {
134
+            // ensure the skeleton is copied
135
+            $userFolder = \OC::$server->getUserFolder();
136 136
 			
137
-			/** @var \OC\Files\View $view */
138
-			$view = $viewCallBack($server);
139
-			if ($userFolder instanceof Folder && $userFolder->getPath() === $view->getRoot()) {
140
-				$rootInfo = $userFolder;
141
-			} else {
142
-				$rootInfo = $view->getFileInfo('');
143
-			}
137
+            /** @var \OC\Files\View $view */
138
+            $view = $viewCallBack($server);
139
+            if ($userFolder instanceof Folder && $userFolder->getPath() === $view->getRoot()) {
140
+                $rootInfo = $userFolder;
141
+            } else {
142
+                $rootInfo = $view->getFileInfo('');
143
+            }
144 144
 
145
-			// Create ownCloud Dir
146
-			if ($rootInfo->getType() === 'dir') {
147
-				$root = new \OCA\DAV\Connector\Sabre\Directory($view, $rootInfo, $objectTree);
148
-			} else {
149
-				$root = new \OCA\DAV\Connector\Sabre\File($view, $rootInfo);
150
-			}
151
-			$objectTree->init($root, $view, $this->mountManager);
145
+            // Create ownCloud Dir
146
+            if ($rootInfo->getType() === 'dir') {
147
+                $root = new \OCA\DAV\Connector\Sabre\Directory($view, $rootInfo, $objectTree);
148
+            } else {
149
+                $root = new \OCA\DAV\Connector\Sabre\File($view, $rootInfo);
150
+            }
151
+            $objectTree->init($root, $view, $this->mountManager);
152 152
 
153
-			$server->addPlugin(
154
-				new \OCA\DAV\Connector\Sabre\FilesPlugin(
155
-					$objectTree,
156
-					$this->config,
157
-					$this->request,
158
-					$this->previewManager,
159
-					false,
160
-					!$this->config->getSystemValue('debug', false)
161
-				)
162
-			);
163
-			$server->addPlugin(new \OCA\DAV\Connector\Sabre\QuotaPlugin($view));
153
+            $server->addPlugin(
154
+                new \OCA\DAV\Connector\Sabre\FilesPlugin(
155
+                    $objectTree,
156
+                    $this->config,
157
+                    $this->request,
158
+                    $this->previewManager,
159
+                    false,
160
+                    !$this->config->getSystemValue('debug', false)
161
+                )
162
+            );
163
+            $server->addPlugin(new \OCA\DAV\Connector\Sabre\QuotaPlugin($view));
164 164
 
165
-			if($this->userSession->isLoggedIn()) {
166
-				$server->addPlugin(new \OCA\DAV\Connector\Sabre\TagsPlugin($objectTree, $this->tagManager));
167
-				$server->addPlugin(new \OCA\DAV\Connector\Sabre\SharesPlugin(
168
-					$objectTree,
169
-					$this->userSession,
170
-					$userFolder,
171
-					\OC::$server->getShareManager()
172
-				));
173
-				$server->addPlugin(new \OCA\DAV\Connector\Sabre\CommentPropertiesPlugin(\OC::$server->getCommentsManager(), $this->userSession));
174
-				$server->addPlugin(new \OCA\DAV\Connector\Sabre\FilesReportPlugin(
175
-					$objectTree,
176
-					$view,
177
-					\OC::$server->getSystemTagManager(),
178
-					\OC::$server->getSystemTagObjectMapper(),
179
-					\OC::$server->getTagManager(),
180
-					$this->userSession,
181
-					\OC::$server->getGroupManager(),
182
-					$userFolder
183
-				));
184
-				// custom properties plugin must be the last one
185
-				$server->addPlugin(
186
-					new \Sabre\DAV\PropertyStorage\Plugin(
187
-						new \OCA\DAV\Connector\Sabre\CustomPropertiesBackend(
188
-							$objectTree,
189
-							$this->databaseConnection,
190
-							$this->userSession->getUser()
191
-						)
192
-					)
193
-				);
194
-			}
195
-			$server->addPlugin(new \OCA\DAV\Connector\Sabre\CopyEtagHeaderPlugin());
196
-		}, 30); // priority 30: after auth (10) and acl(20), before lock(50) and handling the request
197
-		return $server;
198
-	}
165
+            if($this->userSession->isLoggedIn()) {
166
+                $server->addPlugin(new \OCA\DAV\Connector\Sabre\TagsPlugin($objectTree, $this->tagManager));
167
+                $server->addPlugin(new \OCA\DAV\Connector\Sabre\SharesPlugin(
168
+                    $objectTree,
169
+                    $this->userSession,
170
+                    $userFolder,
171
+                    \OC::$server->getShareManager()
172
+                ));
173
+                $server->addPlugin(new \OCA\DAV\Connector\Sabre\CommentPropertiesPlugin(\OC::$server->getCommentsManager(), $this->userSession));
174
+                $server->addPlugin(new \OCA\DAV\Connector\Sabre\FilesReportPlugin(
175
+                    $objectTree,
176
+                    $view,
177
+                    \OC::$server->getSystemTagManager(),
178
+                    \OC::$server->getSystemTagObjectMapper(),
179
+                    \OC::$server->getTagManager(),
180
+                    $this->userSession,
181
+                    \OC::$server->getGroupManager(),
182
+                    $userFolder
183
+                ));
184
+                // custom properties plugin must be the last one
185
+                $server->addPlugin(
186
+                    new \Sabre\DAV\PropertyStorage\Plugin(
187
+                        new \OCA\DAV\Connector\Sabre\CustomPropertiesBackend(
188
+                            $objectTree,
189
+                            $this->databaseConnection,
190
+                            $this->userSession->getUser()
191
+                        )
192
+                    )
193
+                );
194
+            }
195
+            $server->addPlugin(new \OCA\DAV\Connector\Sabre\CopyEtagHeaderPlugin());
196
+        }, 30); // priority 30: after auth (10) and acl(20), before lock(50) and handling the request
197
+        return $server;
198
+    }
199 199
 }
Please login to merge, or discard this patch.
apps/dav/lib/Connector/Sabre/CustomPropertiesBackend.php 1 patch
Indentation   +317 added lines, -317 removed lines patch added patch discarded remove patch
@@ -36,322 +36,322 @@
 block discarded – undo
36 36
 
37 37
 class CustomPropertiesBackend implements BackendInterface {
38 38
 
39
-	/**
40
-	 * Ignored properties
41
-	 *
42
-	 * @var array
43
-	 */
44
-	private $ignoredProperties = array(
45
-		'{DAV:}getcontentlength',
46
-		'{DAV:}getcontenttype',
47
-		'{DAV:}getetag',
48
-		'{DAV:}quota-used-bytes',
49
-		'{DAV:}quota-available-bytes',
50
-		'{DAV:}quota-available-bytes',
51
-		'{http://owncloud.org/ns}permissions',
52
-		'{http://owncloud.org/ns}downloadURL',
53
-		'{http://owncloud.org/ns}dDC',
54
-		'{http://owncloud.org/ns}size',
55
-	);
56
-
57
-	/**
58
-	 * @var Tree
59
-	 */
60
-	private $tree;
61
-
62
-	/**
63
-	 * @var IDBConnection
64
-	 */
65
-	private $connection;
66
-
67
-	/**
68
-	 * @var IUser
69
-	 */
70
-	private $user;
71
-
72
-	/**
73
-	 * Properties cache
74
-	 *
75
-	 * @var array
76
-	 */
77
-	private $cache = [];
78
-
79
-	/**
80
-	 * @param Tree $tree node tree
81
-	 * @param IDBConnection $connection database connection
82
-	 * @param IUser $user owner of the tree and properties
83
-	 */
84
-	public function __construct(
85
-		Tree $tree,
86
-		IDBConnection $connection,
87
-		IUser $user) {
88
-		$this->tree = $tree;
89
-		$this->connection = $connection;
90
-		$this->user = $user->getUID();
91
-	}
92
-
93
-	/**
94
-	 * Fetches properties for a path.
95
-	 *
96
-	 * @param string $path
97
-	 * @param PropFind $propFind
98
-	 * @return void
99
-	 */
100
-	public function propFind($path, PropFind $propFind) {
101
-		try {
102
-			$node = $this->tree->getNodeForPath($path);
103
-			if (!($node instanceof Node)) {
104
-				return;
105
-			}
106
-		} catch (ServiceUnavailable $e) {
107
-			// might happen for unavailable mount points, skip
108
-			return;
109
-		} catch (NotFound $e) {
110
-			// in some rare (buggy) cases the node might not be found,
111
-			// we catch the exception to prevent breaking the whole list with a 404
112
-			// (soft fail)
113
-			\OC::$server->getLogger()->warning(
114
-				'Could not get node for path: \"' . $path . '\" : ' . $e->getMessage(),
115
-				array('app' => 'files')
116
-			);
117
-			return;
118
-		}
119
-
120
-		$requestedProps = $propFind->get404Properties();
121
-
122
-		// these might appear
123
-		$requestedProps = array_diff(
124
-			$requestedProps,
125
-			$this->ignoredProperties
126
-		);
127
-
128
-		if (empty($requestedProps)) {
129
-			return;
130
-		}
131
-
132
-		if ($node instanceof Directory
133
-			&& $propFind->getDepth() !== 0
134
-		) {
135
-			// note: pre-fetching only supported for depth <= 1
136
-			$this->loadChildrenProperties($node, $requestedProps);
137
-		}
138
-
139
-		$props = $this->getProperties($node, $requestedProps);
140
-		foreach ($props as $propName => $propValue) {
141
-			$propFind->set($propName, $propValue);
142
-		}
143
-	}
144
-
145
-	/**
146
-	 * Updates properties for a path
147
-	 *
148
-	 * @param string $path
149
-	 * @param PropPatch $propPatch
150
-	 *
151
-	 * @return void
152
-	 */
153
-	public function propPatch($path, PropPatch $propPatch) {
154
-		$node = $this->tree->getNodeForPath($path);
155
-		if (!($node instanceof Node)) {
156
-			return;
157
-		}
158
-
159
-		$propPatch->handleRemaining(function($changedProps) use ($node) {
160
-			return $this->updateProperties($node, $changedProps);
161
-		});
162
-	}
163
-
164
-	/**
165
-	 * This method is called after a node is deleted.
166
-	 *
167
-	 * @param string $path path of node for which to delete properties
168
-	 */
169
-	public function delete($path) {
170
-		$statement = $this->connection->prepare(
171
-			'DELETE FROM `*PREFIX*properties` WHERE `userid` = ? AND `propertypath` = ?'
172
-		);
173
-		$statement->execute(array($this->user, '/' . $path));
174
-		$statement->closeCursor();
175
-
176
-		unset($this->cache[$path]);
177
-	}
178
-
179
-	/**
180
-	 * This method is called after a successful MOVE
181
-	 *
182
-	 * @param string $source
183
-	 * @param string $destination
184
-	 *
185
-	 * @return void
186
-	 */
187
-	public function move($source, $destination) {
188
-		$statement = $this->connection->prepare(
189
-			'UPDATE `*PREFIX*properties` SET `propertypath` = ?' .
190
-			' WHERE `userid` = ? AND `propertypath` = ?'
191
-		);
192
-		$statement->execute(array('/' . $destination, $this->user, '/' . $source));
193
-		$statement->closeCursor();
194
-	}
195
-
196
-	/**
197
-	 * Returns a list of properties for this nodes.;
198
-	 * @param Node $node
199
-	 * @param array $requestedProperties requested properties or empty array for "all"
200
-	 * @return array
201
-	 * @note The properties list is a list of propertynames the client
202
-	 * requested, encoded as xmlnamespace#tagName, for example:
203
-	 * http://www.example.org/namespace#author If the array is empty, all
204
-	 * properties should be returned
205
-	 */
206
-	private function getProperties(Node $node, array $requestedProperties) {
207
-		$path = $node->getPath();
208
-		if (isset($this->cache[$path])) {
209
-			return $this->cache[$path];
210
-		}
211
-
212
-		// TODO: chunking if more than 1000 properties
213
-		$sql = 'SELECT * FROM `*PREFIX*properties` WHERE `userid` = ? AND `propertypath` = ?';
214
-
215
-		$whereValues = array($this->user, $path);
216
-		$whereTypes = array(null, null);
217
-
218
-		if (!empty($requestedProperties)) {
219
-			// request only a subset
220
-			$sql .= ' AND `propertyname` in (?)';
221
-			$whereValues[] = $requestedProperties;
222
-			$whereTypes[] = \Doctrine\DBAL\Connection::PARAM_STR_ARRAY;
223
-		}
224
-
225
-		$result = $this->connection->executeQuery(
226
-			$sql,
227
-			$whereValues,
228
-			$whereTypes
229
-		);
230
-
231
-		$props = [];
232
-		while ($row = $result->fetch()) {
233
-			$props[$row['propertyname']] = $row['propertyvalue'];
234
-		}
235
-
236
-		$result->closeCursor();
237
-
238
-		$this->cache[$path] = $props;
239
-		return $props;
240
-	}
241
-
242
-	/**
243
-	 * Update properties
244
-	 *
245
-	 * @param Node $node node for which to update properties
246
-	 * @param array $properties array of properties to update
247
-	 *
248
-	 * @return bool
249
-	 */
250
-	private function updateProperties($node, $properties) {
251
-		$path = $node->getPath();
252
-
253
-		$deleteStatement = 'DELETE FROM `*PREFIX*properties`' .
254
-			' WHERE `userid` = ? AND `propertypath` = ? AND `propertyname` = ?';
255
-
256
-		$insertStatement = 'INSERT INTO `*PREFIX*properties`' .
257
-			' (`userid`,`propertypath`,`propertyname`,`propertyvalue`) VALUES(?,?,?,?)';
258
-
259
-		$updateStatement = 'UPDATE `*PREFIX*properties` SET `propertyvalue` = ?' .
260
-			' WHERE `userid` = ? AND `propertypath` = ? AND `propertyname` = ?';
261
-
262
-		// TODO: use "insert or update" strategy ?
263
-		$existing = $this->getProperties($node, array());
264
-		$this->connection->beginTransaction();
265
-		foreach ($properties as $propertyName => $propertyValue) {
266
-			// If it was null, we need to delete the property
267
-			if (is_null($propertyValue)) {
268
-				if (array_key_exists($propertyName, $existing)) {
269
-					$this->connection->executeUpdate($deleteStatement,
270
-						array(
271
-							$this->user,
272
-							$path,
273
-							$propertyName
274
-						)
275
-					);
276
-				}
277
-			} else {
278
-				if (!array_key_exists($propertyName, $existing)) {
279
-					$this->connection->executeUpdate($insertStatement,
280
-						array(
281
-							$this->user,
282
-							$path,
283
-							$propertyName,
284
-							$propertyValue
285
-						)
286
-					);
287
-				} else {
288
-					$this->connection->executeUpdate($updateStatement,
289
-						array(
290
-							$propertyValue,
291
-							$this->user,
292
-							$path,
293
-							$propertyName
294
-						)
295
-					);
296
-				}
297
-			}
298
-		}
299
-
300
-		$this->connection->commit();
301
-		unset($this->cache[$path]);
302
-
303
-		return true;
304
-	}
305
-
306
-	/**
307
-	 * Bulk load properties for directory children
308
-	 *
309
-	 * @param Directory $node
310
-	 * @param array $requestedProperties requested properties
311
-	 *
312
-	 * @return void
313
-	 */
314
-	private function loadChildrenProperties(Directory $node, $requestedProperties) {
315
-		$path = $node->getPath();
316
-		if (isset($this->cache[$path])) {
317
-			// we already loaded them at some point
318
-			return;
319
-		}
320
-
321
-		$childNodes = $node->getChildren();
322
-		// pre-fill cache
323
-		foreach ($childNodes as $childNode) {
324
-			$this->cache[$childNode->getPath()] = [];
325
-		}
326
-
327
-		$sql = 'SELECT * FROM `*PREFIX*properties` WHERE `userid` = ? AND `propertypath` LIKE ?';
328
-		$sql .= ' AND `propertyname` in (?) ORDER BY `propertypath`, `propertyname`';
329
-
330
-		$result = $this->connection->executeQuery(
331
-			$sql,
332
-			array($this->user, $this->connection->escapeLikeParameter(rtrim($path, '/')) . '/%', $requestedProperties),
333
-			array(null, null, \Doctrine\DBAL\Connection::PARAM_STR_ARRAY)
334
-		);
335
-
336
-		$oldPath = null;
337
-		$props = [];
338
-		while ($row = $result->fetch()) {
339
-			$path = $row['propertypath'];
340
-			if ($oldPath !== $path) {
341
-				// save previously gathered props
342
-				$this->cache[$oldPath] = $props;
343
-				$oldPath = $path;
344
-				// prepare props for next path
345
-				$props = [];
346
-			}
347
-			$props[$row['propertyname']] = $row['propertyvalue'];
348
-		}
349
-		if (!is_null($oldPath)) {
350
-			// save props from last run
351
-			$this->cache[$oldPath] = $props;
352
-		}
353
-
354
-		$result->closeCursor();
355
-	}
39
+    /**
40
+     * Ignored properties
41
+     *
42
+     * @var array
43
+     */
44
+    private $ignoredProperties = array(
45
+        '{DAV:}getcontentlength',
46
+        '{DAV:}getcontenttype',
47
+        '{DAV:}getetag',
48
+        '{DAV:}quota-used-bytes',
49
+        '{DAV:}quota-available-bytes',
50
+        '{DAV:}quota-available-bytes',
51
+        '{http://owncloud.org/ns}permissions',
52
+        '{http://owncloud.org/ns}downloadURL',
53
+        '{http://owncloud.org/ns}dDC',
54
+        '{http://owncloud.org/ns}size',
55
+    );
56
+
57
+    /**
58
+     * @var Tree
59
+     */
60
+    private $tree;
61
+
62
+    /**
63
+     * @var IDBConnection
64
+     */
65
+    private $connection;
66
+
67
+    /**
68
+     * @var IUser
69
+     */
70
+    private $user;
71
+
72
+    /**
73
+     * Properties cache
74
+     *
75
+     * @var array
76
+     */
77
+    private $cache = [];
78
+
79
+    /**
80
+     * @param Tree $tree node tree
81
+     * @param IDBConnection $connection database connection
82
+     * @param IUser $user owner of the tree and properties
83
+     */
84
+    public function __construct(
85
+        Tree $tree,
86
+        IDBConnection $connection,
87
+        IUser $user) {
88
+        $this->tree = $tree;
89
+        $this->connection = $connection;
90
+        $this->user = $user->getUID();
91
+    }
92
+
93
+    /**
94
+     * Fetches properties for a path.
95
+     *
96
+     * @param string $path
97
+     * @param PropFind $propFind
98
+     * @return void
99
+     */
100
+    public function propFind($path, PropFind $propFind) {
101
+        try {
102
+            $node = $this->tree->getNodeForPath($path);
103
+            if (!($node instanceof Node)) {
104
+                return;
105
+            }
106
+        } catch (ServiceUnavailable $e) {
107
+            // might happen for unavailable mount points, skip
108
+            return;
109
+        } catch (NotFound $e) {
110
+            // in some rare (buggy) cases the node might not be found,
111
+            // we catch the exception to prevent breaking the whole list with a 404
112
+            // (soft fail)
113
+            \OC::$server->getLogger()->warning(
114
+                'Could not get node for path: \"' . $path . '\" : ' . $e->getMessage(),
115
+                array('app' => 'files')
116
+            );
117
+            return;
118
+        }
119
+
120
+        $requestedProps = $propFind->get404Properties();
121
+
122
+        // these might appear
123
+        $requestedProps = array_diff(
124
+            $requestedProps,
125
+            $this->ignoredProperties
126
+        );
127
+
128
+        if (empty($requestedProps)) {
129
+            return;
130
+        }
131
+
132
+        if ($node instanceof Directory
133
+            && $propFind->getDepth() !== 0
134
+        ) {
135
+            // note: pre-fetching only supported for depth <= 1
136
+            $this->loadChildrenProperties($node, $requestedProps);
137
+        }
138
+
139
+        $props = $this->getProperties($node, $requestedProps);
140
+        foreach ($props as $propName => $propValue) {
141
+            $propFind->set($propName, $propValue);
142
+        }
143
+    }
144
+
145
+    /**
146
+     * Updates properties for a path
147
+     *
148
+     * @param string $path
149
+     * @param PropPatch $propPatch
150
+     *
151
+     * @return void
152
+     */
153
+    public function propPatch($path, PropPatch $propPatch) {
154
+        $node = $this->tree->getNodeForPath($path);
155
+        if (!($node instanceof Node)) {
156
+            return;
157
+        }
158
+
159
+        $propPatch->handleRemaining(function($changedProps) use ($node) {
160
+            return $this->updateProperties($node, $changedProps);
161
+        });
162
+    }
163
+
164
+    /**
165
+     * This method is called after a node is deleted.
166
+     *
167
+     * @param string $path path of node for which to delete properties
168
+     */
169
+    public function delete($path) {
170
+        $statement = $this->connection->prepare(
171
+            'DELETE FROM `*PREFIX*properties` WHERE `userid` = ? AND `propertypath` = ?'
172
+        );
173
+        $statement->execute(array($this->user, '/' . $path));
174
+        $statement->closeCursor();
175
+
176
+        unset($this->cache[$path]);
177
+    }
178
+
179
+    /**
180
+     * This method is called after a successful MOVE
181
+     *
182
+     * @param string $source
183
+     * @param string $destination
184
+     *
185
+     * @return void
186
+     */
187
+    public function move($source, $destination) {
188
+        $statement = $this->connection->prepare(
189
+            'UPDATE `*PREFIX*properties` SET `propertypath` = ?' .
190
+            ' WHERE `userid` = ? AND `propertypath` = ?'
191
+        );
192
+        $statement->execute(array('/' . $destination, $this->user, '/' . $source));
193
+        $statement->closeCursor();
194
+    }
195
+
196
+    /**
197
+     * Returns a list of properties for this nodes.;
198
+     * @param Node $node
199
+     * @param array $requestedProperties requested properties or empty array for "all"
200
+     * @return array
201
+     * @note The properties list is a list of propertynames the client
202
+     * requested, encoded as xmlnamespace#tagName, for example:
203
+     * http://www.example.org/namespace#author If the array is empty, all
204
+     * properties should be returned
205
+     */
206
+    private function getProperties(Node $node, array $requestedProperties) {
207
+        $path = $node->getPath();
208
+        if (isset($this->cache[$path])) {
209
+            return $this->cache[$path];
210
+        }
211
+
212
+        // TODO: chunking if more than 1000 properties
213
+        $sql = 'SELECT * FROM `*PREFIX*properties` WHERE `userid` = ? AND `propertypath` = ?';
214
+
215
+        $whereValues = array($this->user, $path);
216
+        $whereTypes = array(null, null);
217
+
218
+        if (!empty($requestedProperties)) {
219
+            // request only a subset
220
+            $sql .= ' AND `propertyname` in (?)';
221
+            $whereValues[] = $requestedProperties;
222
+            $whereTypes[] = \Doctrine\DBAL\Connection::PARAM_STR_ARRAY;
223
+        }
224
+
225
+        $result = $this->connection->executeQuery(
226
+            $sql,
227
+            $whereValues,
228
+            $whereTypes
229
+        );
230
+
231
+        $props = [];
232
+        while ($row = $result->fetch()) {
233
+            $props[$row['propertyname']] = $row['propertyvalue'];
234
+        }
235
+
236
+        $result->closeCursor();
237
+
238
+        $this->cache[$path] = $props;
239
+        return $props;
240
+    }
241
+
242
+    /**
243
+     * Update properties
244
+     *
245
+     * @param Node $node node for which to update properties
246
+     * @param array $properties array of properties to update
247
+     *
248
+     * @return bool
249
+     */
250
+    private function updateProperties($node, $properties) {
251
+        $path = $node->getPath();
252
+
253
+        $deleteStatement = 'DELETE FROM `*PREFIX*properties`' .
254
+            ' WHERE `userid` = ? AND `propertypath` = ? AND `propertyname` = ?';
255
+
256
+        $insertStatement = 'INSERT INTO `*PREFIX*properties`' .
257
+            ' (`userid`,`propertypath`,`propertyname`,`propertyvalue`) VALUES(?,?,?,?)';
258
+
259
+        $updateStatement = 'UPDATE `*PREFIX*properties` SET `propertyvalue` = ?' .
260
+            ' WHERE `userid` = ? AND `propertypath` = ? AND `propertyname` = ?';
261
+
262
+        // TODO: use "insert or update" strategy ?
263
+        $existing = $this->getProperties($node, array());
264
+        $this->connection->beginTransaction();
265
+        foreach ($properties as $propertyName => $propertyValue) {
266
+            // If it was null, we need to delete the property
267
+            if (is_null($propertyValue)) {
268
+                if (array_key_exists($propertyName, $existing)) {
269
+                    $this->connection->executeUpdate($deleteStatement,
270
+                        array(
271
+                            $this->user,
272
+                            $path,
273
+                            $propertyName
274
+                        )
275
+                    );
276
+                }
277
+            } else {
278
+                if (!array_key_exists($propertyName, $existing)) {
279
+                    $this->connection->executeUpdate($insertStatement,
280
+                        array(
281
+                            $this->user,
282
+                            $path,
283
+                            $propertyName,
284
+                            $propertyValue
285
+                        )
286
+                    );
287
+                } else {
288
+                    $this->connection->executeUpdate($updateStatement,
289
+                        array(
290
+                            $propertyValue,
291
+                            $this->user,
292
+                            $path,
293
+                            $propertyName
294
+                        )
295
+                    );
296
+                }
297
+            }
298
+        }
299
+
300
+        $this->connection->commit();
301
+        unset($this->cache[$path]);
302
+
303
+        return true;
304
+    }
305
+
306
+    /**
307
+     * Bulk load properties for directory children
308
+     *
309
+     * @param Directory $node
310
+     * @param array $requestedProperties requested properties
311
+     *
312
+     * @return void
313
+     */
314
+    private function loadChildrenProperties(Directory $node, $requestedProperties) {
315
+        $path = $node->getPath();
316
+        if (isset($this->cache[$path])) {
317
+            // we already loaded them at some point
318
+            return;
319
+        }
320
+
321
+        $childNodes = $node->getChildren();
322
+        // pre-fill cache
323
+        foreach ($childNodes as $childNode) {
324
+            $this->cache[$childNode->getPath()] = [];
325
+        }
326
+
327
+        $sql = 'SELECT * FROM `*PREFIX*properties` WHERE `userid` = ? AND `propertypath` LIKE ?';
328
+        $sql .= ' AND `propertyname` in (?) ORDER BY `propertypath`, `propertyname`';
329
+
330
+        $result = $this->connection->executeQuery(
331
+            $sql,
332
+            array($this->user, $this->connection->escapeLikeParameter(rtrim($path, '/')) . '/%', $requestedProperties),
333
+            array(null, null, \Doctrine\DBAL\Connection::PARAM_STR_ARRAY)
334
+        );
335
+
336
+        $oldPath = null;
337
+        $props = [];
338
+        while ($row = $result->fetch()) {
339
+            $path = $row['propertypath'];
340
+            if ($oldPath !== $path) {
341
+                // save previously gathered props
342
+                $this->cache[$oldPath] = $props;
343
+                $oldPath = $path;
344
+                // prepare props for next path
345
+                $props = [];
346
+            }
347
+            $props[$row['propertyname']] = $row['propertyvalue'];
348
+        }
349
+        if (!is_null($oldPath)) {
350
+            // save props from last run
351
+            $this->cache[$oldPath] = $props;
352
+        }
353
+
354
+        $result->closeCursor();
355
+    }
356 356
 
357 357
 }
Please login to merge, or discard this patch.
apps/dav/lib/Connector/Sabre/Node.php 1 patch
Indentation   +306 added lines, -306 removed lines patch added patch discarded remove patch
@@ -41,315 +41,315 @@
 block discarded – undo
41 41
 
42 42
 abstract class Node implements \Sabre\DAV\INode {
43 43
 
44
-	/**
45
-	 * @var \OC\Files\View
46
-	 */
47
-	protected $fileView;
48
-
49
-	/**
50
-	 * The path to the current node
51
-	 *
52
-	 * @var string
53
-	 */
54
-	protected $path;
55
-
56
-	/**
57
-	 * node properties cache
58
-	 *
59
-	 * @var array
60
-	 */
61
-	protected $property_cache = null;
62
-
63
-	/**
64
-	 * @var \OCP\Files\FileInfo
65
-	 */
66
-	protected $info;
67
-
68
-	/**
69
-	 * @var IManager
70
-	 */
71
-	protected $shareManager;
72
-
73
-	/**
74
-	 * Sets up the node, expects a full path name
75
-	 *
76
-	 * @param \OC\Files\View $view
77
-	 * @param \OCP\Files\FileInfo $info
78
-	 * @param IManager $shareManager
79
-	 */
80
-	public function __construct($view, $info, IManager $shareManager = null) {
81
-		$this->fileView = $view;
82
-		$this->path = $this->fileView->getRelativePath($info->getPath());
83
-		$this->info = $info;
84
-		if ($shareManager) {
85
-			$this->shareManager = $shareManager;
86
-		} else {
87
-			$this->shareManager = \OC::$server->getShareManager();
88
-		}
89
-	}
90
-
91
-	protected function refreshInfo() {
92
-		$this->info = $this->fileView->getFileInfo($this->path);
93
-	}
94
-
95
-	/**
96
-	 *  Returns the name of the node
97
-	 *
98
-	 * @return string
99
-	 */
100
-	public function getName() {
101
-		return $this->info->getName();
102
-	}
103
-
104
-	/**
105
-	 * Returns the full path
106
-	 *
107
-	 * @return string
108
-	 */
109
-	public function getPath() {
110
-		return $this->path;
111
-	}
112
-
113
-	/**
114
-	 * Renames the node
115
-	 *
116
-	 * @param string $name The new name
117
-	 * @throws \Sabre\DAV\Exception\BadRequest
118
-	 * @throws \Sabre\DAV\Exception\Forbidden
119
-	 */
120
-	public function setName($name) {
121
-
122
-		// rename is only allowed if the update privilege is granted
123
-		if (!$this->info->isUpdateable()) {
124
-			throw new \Sabre\DAV\Exception\Forbidden();
125
-		}
126
-
127
-		list($parentPath,) = \Sabre\HTTP\URLUtil::splitPath($this->path);
128
-		list(, $newName) = \Sabre\HTTP\URLUtil::splitPath($name);
129
-
130
-		// verify path of the target
131
-		$this->verifyPath();
132
-
133
-		$newPath = $parentPath . '/' . $newName;
134
-
135
-		$this->fileView->rename($this->path, $newPath);
136
-
137
-		$this->path = $newPath;
138
-
139
-		$this->refreshInfo();
140
-	}
141
-
142
-	public function setPropertyCache($property_cache) {
143
-		$this->property_cache = $property_cache;
144
-	}
145
-
146
-	/**
147
-	 * Returns the last modification time, as a unix timestamp
148
-	 *
149
-	 * @return int timestamp as integer
150
-	 */
151
-	public function getLastModified() {
152
-		$timestamp = $this->info->getMtime();
153
-		if (!empty($timestamp)) {
154
-			return (int)$timestamp;
155
-		}
156
-		return $timestamp;
157
-	}
158
-
159
-	/**
160
-	 *  sets the last modification time of the file (mtime) to the value given
161
-	 *  in the second parameter or to now if the second param is empty.
162
-	 *  Even if the modification time is set to a custom value the access time is set to now.
163
-	 */
164
-	public function touch($mtime) {
165
-		$this->fileView->touch($this->path, $mtime);
166
-		$this->refreshInfo();
167
-	}
168
-
169
-	/**
170
-	 * Returns the ETag for a file
171
-	 *
172
-	 * An ETag is a unique identifier representing the current version of the
173
-	 * file. If the file changes, the ETag MUST change.  The ETag is an
174
-	 * arbitrary string, but MUST be surrounded by double-quotes.
175
-	 *
176
-	 * Return null if the ETag can not effectively be determined
177
-	 *
178
-	 * @return string
179
-	 */
180
-	public function getETag() {
181
-		return '"' . $this->info->getEtag() . '"';
182
-	}
183
-
184
-	/**
185
-	 * Sets the ETag
186
-	 *
187
-	 * @param string $etag
188
-	 *
189
-	 * @return int file id of updated file or -1 on failure
190
-	 */
191
-	public function setETag($etag) {
192
-		return $this->fileView->putFileInfo($this->path, array('etag' => $etag));
193
-	}
194
-
195
-	/**
196
-	 * Returns the size of the node, in bytes
197
-	 *
198
-	 * @return integer
199
-	 */
200
-	public function getSize() {
201
-		return $this->info->getSize();
202
-	}
203
-
204
-	/**
205
-	 * Returns the cache's file id
206
-	 *
207
-	 * @return int
208
-	 */
209
-	public function getId() {
210
-		return $this->info->getId();
211
-	}
212
-
213
-	/**
214
-	 * @return string|null
215
-	 */
216
-	public function getFileId() {
217
-		if ($this->info->getId()) {
218
-			$instanceId = \OC_Util::getInstanceId();
219
-			$id = sprintf('%08d', $this->info->getId());
220
-			return $id . $instanceId;
221
-		}
222
-
223
-		return null;
224
-	}
225
-
226
-	/**
227
-	 * @return integer
228
-	 */
229
-	public function getInternalFileId() {
230
-		return $this->info->getId();
231
-	}
232
-
233
-	/**
234
-	 * @param string $user
235
-	 * @return int
236
-	 */
237
-	public function getSharePermissions($user) {
238
-
239
-		// check of we access a federated share
240
-		if ($user !== null) {
241
-			try {
242
-				$share = $this->shareManager->getShareByToken($user);
243
-				return $share->getPermissions();
244
-			} catch (ShareNotFound $e) {
245
-				// ignore
246
-			}
247
-		}
248
-
249
-		$storage = $this->info->getStorage();
250
-
251
-		$path = $this->info->getInternalPath();
252
-
253
-		if ($storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage')) {
254
-			/** @var \OCA\Files_Sharing\SharedStorage $storage */
255
-			$permissions = (int)$storage->getShare()->getPermissions();
256
-		} else {
257
-			$permissions = $storage->getPermissions($path);
258
-		}
259
-
260
-		/*
44
+    /**
45
+     * @var \OC\Files\View
46
+     */
47
+    protected $fileView;
48
+
49
+    /**
50
+     * The path to the current node
51
+     *
52
+     * @var string
53
+     */
54
+    protected $path;
55
+
56
+    /**
57
+     * node properties cache
58
+     *
59
+     * @var array
60
+     */
61
+    protected $property_cache = null;
62
+
63
+    /**
64
+     * @var \OCP\Files\FileInfo
65
+     */
66
+    protected $info;
67
+
68
+    /**
69
+     * @var IManager
70
+     */
71
+    protected $shareManager;
72
+
73
+    /**
74
+     * Sets up the node, expects a full path name
75
+     *
76
+     * @param \OC\Files\View $view
77
+     * @param \OCP\Files\FileInfo $info
78
+     * @param IManager $shareManager
79
+     */
80
+    public function __construct($view, $info, IManager $shareManager = null) {
81
+        $this->fileView = $view;
82
+        $this->path = $this->fileView->getRelativePath($info->getPath());
83
+        $this->info = $info;
84
+        if ($shareManager) {
85
+            $this->shareManager = $shareManager;
86
+        } else {
87
+            $this->shareManager = \OC::$server->getShareManager();
88
+        }
89
+    }
90
+
91
+    protected function refreshInfo() {
92
+        $this->info = $this->fileView->getFileInfo($this->path);
93
+    }
94
+
95
+    /**
96
+     *  Returns the name of the node
97
+     *
98
+     * @return string
99
+     */
100
+    public function getName() {
101
+        return $this->info->getName();
102
+    }
103
+
104
+    /**
105
+     * Returns the full path
106
+     *
107
+     * @return string
108
+     */
109
+    public function getPath() {
110
+        return $this->path;
111
+    }
112
+
113
+    /**
114
+     * Renames the node
115
+     *
116
+     * @param string $name The new name
117
+     * @throws \Sabre\DAV\Exception\BadRequest
118
+     * @throws \Sabre\DAV\Exception\Forbidden
119
+     */
120
+    public function setName($name) {
121
+
122
+        // rename is only allowed if the update privilege is granted
123
+        if (!$this->info->isUpdateable()) {
124
+            throw new \Sabre\DAV\Exception\Forbidden();
125
+        }
126
+
127
+        list($parentPath,) = \Sabre\HTTP\URLUtil::splitPath($this->path);
128
+        list(, $newName) = \Sabre\HTTP\URLUtil::splitPath($name);
129
+
130
+        // verify path of the target
131
+        $this->verifyPath();
132
+
133
+        $newPath = $parentPath . '/' . $newName;
134
+
135
+        $this->fileView->rename($this->path, $newPath);
136
+
137
+        $this->path = $newPath;
138
+
139
+        $this->refreshInfo();
140
+    }
141
+
142
+    public function setPropertyCache($property_cache) {
143
+        $this->property_cache = $property_cache;
144
+    }
145
+
146
+    /**
147
+     * Returns the last modification time, as a unix timestamp
148
+     *
149
+     * @return int timestamp as integer
150
+     */
151
+    public function getLastModified() {
152
+        $timestamp = $this->info->getMtime();
153
+        if (!empty($timestamp)) {
154
+            return (int)$timestamp;
155
+        }
156
+        return $timestamp;
157
+    }
158
+
159
+    /**
160
+     *  sets the last modification time of the file (mtime) to the value given
161
+     *  in the second parameter or to now if the second param is empty.
162
+     *  Even if the modification time is set to a custom value the access time is set to now.
163
+     */
164
+    public function touch($mtime) {
165
+        $this->fileView->touch($this->path, $mtime);
166
+        $this->refreshInfo();
167
+    }
168
+
169
+    /**
170
+     * Returns the ETag for a file
171
+     *
172
+     * An ETag is a unique identifier representing the current version of the
173
+     * file. If the file changes, the ETag MUST change.  The ETag is an
174
+     * arbitrary string, but MUST be surrounded by double-quotes.
175
+     *
176
+     * Return null if the ETag can not effectively be determined
177
+     *
178
+     * @return string
179
+     */
180
+    public function getETag() {
181
+        return '"' . $this->info->getEtag() . '"';
182
+    }
183
+
184
+    /**
185
+     * Sets the ETag
186
+     *
187
+     * @param string $etag
188
+     *
189
+     * @return int file id of updated file or -1 on failure
190
+     */
191
+    public function setETag($etag) {
192
+        return $this->fileView->putFileInfo($this->path, array('etag' => $etag));
193
+    }
194
+
195
+    /**
196
+     * Returns the size of the node, in bytes
197
+     *
198
+     * @return integer
199
+     */
200
+    public function getSize() {
201
+        return $this->info->getSize();
202
+    }
203
+
204
+    /**
205
+     * Returns the cache's file id
206
+     *
207
+     * @return int
208
+     */
209
+    public function getId() {
210
+        return $this->info->getId();
211
+    }
212
+
213
+    /**
214
+     * @return string|null
215
+     */
216
+    public function getFileId() {
217
+        if ($this->info->getId()) {
218
+            $instanceId = \OC_Util::getInstanceId();
219
+            $id = sprintf('%08d', $this->info->getId());
220
+            return $id . $instanceId;
221
+        }
222
+
223
+        return null;
224
+    }
225
+
226
+    /**
227
+     * @return integer
228
+     */
229
+    public function getInternalFileId() {
230
+        return $this->info->getId();
231
+    }
232
+
233
+    /**
234
+     * @param string $user
235
+     * @return int
236
+     */
237
+    public function getSharePermissions($user) {
238
+
239
+        // check of we access a federated share
240
+        if ($user !== null) {
241
+            try {
242
+                $share = $this->shareManager->getShareByToken($user);
243
+                return $share->getPermissions();
244
+            } catch (ShareNotFound $e) {
245
+                // ignore
246
+            }
247
+        }
248
+
249
+        $storage = $this->info->getStorage();
250
+
251
+        $path = $this->info->getInternalPath();
252
+
253
+        if ($storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage')) {
254
+            /** @var \OCA\Files_Sharing\SharedStorage $storage */
255
+            $permissions = (int)$storage->getShare()->getPermissions();
256
+        } else {
257
+            $permissions = $storage->getPermissions($path);
258
+        }
259
+
260
+        /*
261 261
 		 * We can always share non moveable mount points with DELETE and UPDATE
262 262
 		 * Eventually we need to do this properly
263 263
 		 */
264
-		$mountpoint = $this->info->getMountPoint();
265
-		if (!($mountpoint instanceof MoveableMount)) {
266
-			$mountpointpath = $mountpoint->getMountPoint();
267
-			if (substr($mountpointpath, -1) === '/') {
268
-				$mountpointpath = substr($mountpointpath, 0, -1);
269
-			}
270
-
271
-			if ($mountpointpath === $this->info->getPath()) {
272
-				$permissions |= \OCP\Constants::PERMISSION_DELETE | \OCP\Constants::PERMISSION_UPDATE;
273
-			}
274
-		}
275
-
276
-		/*
264
+        $mountpoint = $this->info->getMountPoint();
265
+        if (!($mountpoint instanceof MoveableMount)) {
266
+            $mountpointpath = $mountpoint->getMountPoint();
267
+            if (substr($mountpointpath, -1) === '/') {
268
+                $mountpointpath = substr($mountpointpath, 0, -1);
269
+            }
270
+
271
+            if ($mountpointpath === $this->info->getPath()) {
272
+                $permissions |= \OCP\Constants::PERMISSION_DELETE | \OCP\Constants::PERMISSION_UPDATE;
273
+            }
274
+        }
275
+
276
+        /*
277 277
 		 * Files can't have create or delete permissions
278 278
 		 */
279
-		if ($this->info->getType() === \OCP\Files\FileInfo::TYPE_FILE) {
280
-			$permissions &= ~(\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_DELETE);
281
-		}
282
-
283
-		return $permissions;
284
-	}
285
-
286
-	/**
287
-	 * @return string
288
-	 */
289
-	public function getDavPermissions() {
290
-		$p = '';
291
-		if ($this->info->isShared()) {
292
-			$p .= 'S';
293
-		}
294
-		if ($this->info->isShareable()) {
295
-			$p .= 'R';
296
-		}
297
-		if ($this->info->isMounted()) {
298
-			$p .= 'M';
299
-		}
300
-		if ($this->info->isDeletable()) {
301
-			$p .= 'D';
302
-		}
303
-		if ($this->info->isUpdateable()) {
304
-			$p .= 'NV'; // Renameable, Moveable
305
-		}
306
-		if ($this->info->getType() === \OCP\Files\FileInfo::TYPE_FILE) {
307
-			if ($this->info->isUpdateable()) {
308
-				$p .= 'W';
309
-			}
310
-		} else {
311
-			if ($this->info->isCreatable()) {
312
-				$p .= 'CK';
313
-			}
314
-		}
315
-		return $p;
316
-	}
317
-
318
-	public function getOwner() {
319
-		return $this->info->getOwner();
320
-	}
321
-
322
-	protected function verifyPath() {
323
-		try {
324
-			$fileName = basename($this->info->getPath());
325
-			$this->fileView->verifyPath($this->path, $fileName);
326
-		} catch (\OCP\Files\InvalidPathException $ex) {
327
-			throw new InvalidPath($ex->getMessage());
328
-		}
329
-	}
330
-
331
-	/**
332
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
333
-	 */
334
-	public function acquireLock($type) {
335
-		$this->fileView->lockFile($this->path, $type);
336
-	}
337
-
338
-	/**
339
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
340
-	 */
341
-	public function releaseLock($type) {
342
-		$this->fileView->unlockFile($this->path, $type);
343
-	}
344
-
345
-	/**
346
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
347
-	 */
348
-	public function changeLock($type) {
349
-		$this->fileView->changeLock($this->path, $type);
350
-	}
351
-
352
-	public function getFileInfo() {
353
-		return $this->info;
354
-	}
279
+        if ($this->info->getType() === \OCP\Files\FileInfo::TYPE_FILE) {
280
+            $permissions &= ~(\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_DELETE);
281
+        }
282
+
283
+        return $permissions;
284
+    }
285
+
286
+    /**
287
+     * @return string
288
+     */
289
+    public function getDavPermissions() {
290
+        $p = '';
291
+        if ($this->info->isShared()) {
292
+            $p .= 'S';
293
+        }
294
+        if ($this->info->isShareable()) {
295
+            $p .= 'R';
296
+        }
297
+        if ($this->info->isMounted()) {
298
+            $p .= 'M';
299
+        }
300
+        if ($this->info->isDeletable()) {
301
+            $p .= 'D';
302
+        }
303
+        if ($this->info->isUpdateable()) {
304
+            $p .= 'NV'; // Renameable, Moveable
305
+        }
306
+        if ($this->info->getType() === \OCP\Files\FileInfo::TYPE_FILE) {
307
+            if ($this->info->isUpdateable()) {
308
+                $p .= 'W';
309
+            }
310
+        } else {
311
+            if ($this->info->isCreatable()) {
312
+                $p .= 'CK';
313
+            }
314
+        }
315
+        return $p;
316
+    }
317
+
318
+    public function getOwner() {
319
+        return $this->info->getOwner();
320
+    }
321
+
322
+    protected function verifyPath() {
323
+        try {
324
+            $fileName = basename($this->info->getPath());
325
+            $this->fileView->verifyPath($this->path, $fileName);
326
+        } catch (\OCP\Files\InvalidPathException $ex) {
327
+            throw new InvalidPath($ex->getMessage());
328
+        }
329
+    }
330
+
331
+    /**
332
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
333
+     */
334
+    public function acquireLock($type) {
335
+        $this->fileView->lockFile($this->path, $type);
336
+    }
337
+
338
+    /**
339
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
340
+     */
341
+    public function releaseLock($type) {
342
+        $this->fileView->unlockFile($this->path, $type);
343
+    }
344
+
345
+    /**
346
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
347
+     */
348
+    public function changeLock($type) {
349
+        $this->fileView->changeLock($this->path, $type);
350
+    }
351
+
352
+    public function getFileInfo() {
353
+        return $this->info;
354
+    }
355 355
 }
Please login to merge, or discard this patch.
apps/dav/lib/Connector/Sabre/TagList.php 1 patch
Indentation   +79 added lines, -79 removed lines patch added patch discarded remove patch
@@ -34,92 +34,92 @@
 block discarded – undo
34 34
  * This property contains multiple "tag" elements, each containing a tag name.
35 35
  */
36 36
 class TagList implements Element {
37
-	const NS_OWNCLOUD = 'http://owncloud.org/ns';
37
+    const NS_OWNCLOUD = 'http://owncloud.org/ns';
38 38
 
39
-	/**
40
-	 * tags
41
-	 *
42
-	 * @var array
43
-	 */
44
-	private $tags;
39
+    /**
40
+     * tags
41
+     *
42
+     * @var array
43
+     */
44
+    private $tags;
45 45
 
46
-	/**
47
-	 * @param array $tags
48
-	 */
49
-	public function __construct(array $tags) {
50
-		$this->tags = $tags;
51
-	}
46
+    /**
47
+     * @param array $tags
48
+     */
49
+    public function __construct(array $tags) {
50
+        $this->tags = $tags;
51
+    }
52 52
 
53
-	/**
54
-	 * Returns the tags
55
-	 *
56
-	 * @return array
57
-	 */
58
-	public function getTags() {
53
+    /**
54
+     * Returns the tags
55
+     *
56
+     * @return array
57
+     */
58
+    public function getTags() {
59 59
 
60
-		return $this->tags;
60
+        return $this->tags;
61 61
 
62
-	}
62
+    }
63 63
 
64
-	/**
65
-	 * The deserialize method is called during xml parsing.
66
-	 *
67
-	 * This method is called statictly, this is because in theory this method
68
-	 * may be used as a type of constructor, or factory method.
69
-	 *
70
-	 * Often you want to return an instance of the current class, but you are
71
-	 * free to return other data as well.
72
-	 *
73
-	 * You are responsible for advancing the reader to the next element. Not
74
-	 * doing anything will result in a never-ending loop.
75
-	 *
76
-	 * If you just want to skip parsing for this element altogether, you can
77
-	 * just call $reader->next();
78
-	 *
79
-	 * $reader->parseInnerTree() will parse the entire sub-tree, and advance to
80
-	 * the next element.
81
-	 *
82
-	 * @param Reader $reader
83
-	 * @return mixed
84
-	 */
85
-	static function xmlDeserialize(Reader $reader) {
86
-		$tags = [];
64
+    /**
65
+     * The deserialize method is called during xml parsing.
66
+     *
67
+     * This method is called statictly, this is because in theory this method
68
+     * may be used as a type of constructor, or factory method.
69
+     *
70
+     * Often you want to return an instance of the current class, but you are
71
+     * free to return other data as well.
72
+     *
73
+     * You are responsible for advancing the reader to the next element. Not
74
+     * doing anything will result in a never-ending loop.
75
+     *
76
+     * If you just want to skip parsing for this element altogether, you can
77
+     * just call $reader->next();
78
+     *
79
+     * $reader->parseInnerTree() will parse the entire sub-tree, and advance to
80
+     * the next element.
81
+     *
82
+     * @param Reader $reader
83
+     * @return mixed
84
+     */
85
+    static function xmlDeserialize(Reader $reader) {
86
+        $tags = [];
87 87
 
88
-		$tree = $reader->parseInnerTree();
89
-		if ($tree === null) {
90
-			return null;
91
-		}
92
-		foreach ($tree as $elem) {
93
-			if ($elem['name'] === '{' . self::NS_OWNCLOUD . '}tag') {
94
-				$tags[] = $elem['value'];
95
-			}
96
-		}
97
-		return new self($tags);
98
-	}
88
+        $tree = $reader->parseInnerTree();
89
+        if ($tree === null) {
90
+            return null;
91
+        }
92
+        foreach ($tree as $elem) {
93
+            if ($elem['name'] === '{' . self::NS_OWNCLOUD . '}tag') {
94
+                $tags[] = $elem['value'];
95
+            }
96
+        }
97
+        return new self($tags);
98
+    }
99 99
 
100
-	/**
101
-	 * The xmlSerialize metod is called during xml writing.
102
-	 *
103
-	 * Use the $writer argument to write its own xml serialization.
104
-	 *
105
-	 * An important note: do _not_ create a parent element. Any element
106
-	 * implementing XmlSerializble should only ever write what's considered
107
-	 * its 'inner xml'.
108
-	 *
109
-	 * The parent of the current element is responsible for writing a
110
-	 * containing element.
111
-	 *
112
-	 * This allows serializers to be re-used for different element names.
113
-	 *
114
-	 * If you are opening new elements, you must also close them again.
115
-	 *
116
-	 * @param Writer $writer
117
-	 * @return void
118
-	 */
119
-	function xmlSerialize(Writer $writer) {
100
+    /**
101
+     * The xmlSerialize metod is called during xml writing.
102
+     *
103
+     * Use the $writer argument to write its own xml serialization.
104
+     *
105
+     * An important note: do _not_ create a parent element. Any element
106
+     * implementing XmlSerializble should only ever write what's considered
107
+     * its 'inner xml'.
108
+     *
109
+     * The parent of the current element is responsible for writing a
110
+     * containing element.
111
+     *
112
+     * This allows serializers to be re-used for different element names.
113
+     *
114
+     * If you are opening new elements, you must also close them again.
115
+     *
116
+     * @param Writer $writer
117
+     * @return void
118
+     */
119
+    function xmlSerialize(Writer $writer) {
120 120
 
121
-		foreach ($this->tags as $tag) {
122
-			$writer->writeElement('{' . self::NS_OWNCLOUD . '}tag', $tag);
123
-		}
124
-	}
121
+        foreach ($this->tags as $tag) {
122
+            $writer->writeElement('{' . self::NS_OWNCLOUD . '}tag', $tag);
123
+        }
124
+    }
125 125
 }
Please login to merge, or discard this patch.
apps/dav/lib/Connector/Sabre/QuotaPlugin.php 1 patch
Indentation   +99 added lines, -99 removed lines patch added patch discarded remove patch
@@ -40,114 +40,114 @@
 block discarded – undo
40 40
  */
41 41
 class QuotaPlugin extends \Sabre\DAV\ServerPlugin {
42 42
 
43
-	/**
44
-	 * @var \OC\Files\View
45
-	 */
46
-	private $view;
43
+    /**
44
+     * @var \OC\Files\View
45
+     */
46
+    private $view;
47 47
 
48
-	/**
49
-	 * Reference to main server object
50
-	 *
51
-	 * @var \Sabre\DAV\Server
52
-	 */
53
-	private $server;
48
+    /**
49
+     * Reference to main server object
50
+     *
51
+     * @var \Sabre\DAV\Server
52
+     */
53
+    private $server;
54 54
 
55
-	/**
56
-	 * @param \OC\Files\View $view
57
-	 */
58
-	public function __construct($view) {
59
-		$this->view = $view;
60
-	}
55
+    /**
56
+     * @param \OC\Files\View $view
57
+     */
58
+    public function __construct($view) {
59
+        $this->view = $view;
60
+    }
61 61
 
62
-	/**
63
-	 * This initializes the plugin.
64
-	 *
65
-	 * This function is called by \Sabre\DAV\Server, after
66
-	 * addPlugin is called.
67
-	 *
68
-	 * This method should set up the requires event subscriptions.
69
-	 *
70
-	 * @param \Sabre\DAV\Server $server
71
-	 * @return void
72
-	 */
73
-	public function initialize(\Sabre\DAV\Server $server) {
62
+    /**
63
+     * This initializes the plugin.
64
+     *
65
+     * This function is called by \Sabre\DAV\Server, after
66
+     * addPlugin is called.
67
+     *
68
+     * This method should set up the requires event subscriptions.
69
+     *
70
+     * @param \Sabre\DAV\Server $server
71
+     * @return void
72
+     */
73
+    public function initialize(\Sabre\DAV\Server $server) {
74 74
 
75
-		$this->server = $server;
75
+        $this->server = $server;
76 76
 
77
-		$server->on('beforeWriteContent', array($this, 'checkQuota'), 10);
78
-		$server->on('beforeCreateFile', array($this, 'checkQuota'), 10);
79
-	}
77
+        $server->on('beforeWriteContent', array($this, 'checkQuota'), 10);
78
+        $server->on('beforeCreateFile', array($this, 'checkQuota'), 10);
79
+    }
80 80
 
81
-	/**
82
-	 * This method is called before any HTTP method and validates there is enough free space to store the file
83
-	 *
84
-	 * @param string $uri
85
-	 * @throws InsufficientStorage
86
-	 * @return bool
87
-	 */
88
-	public function checkQuota($uri) {
89
-		$length = $this->getLength();
90
-		if ($length) {
91
-			if (substr($uri, 0, 1) !== '/') {
92
-				$uri = '/' . $uri;
93
-			}
94
-			list($parentUri, $newName) = URLUtil::splitPath($uri);
95
-			if(is_null($parentUri)) {
96
-				$parentUri = '';
97
-			}
98
-			$req = $this->server->httpRequest;
99
-			if ($req->getHeader('OC-Chunked')) {
100
-				$info = \OC_FileChunking::decodeName($newName);
101
-				$chunkHandler = $this->getFileChunking($info);
102
-				// subtract the already uploaded size to see whether
103
-				// there is still enough space for the remaining chunks
104
-				$length -= $chunkHandler->getCurrentSize();
105
-				// use target file name for free space check in case of shared files
106
-				$uri = rtrim($parentUri, '/') . '/' . $info['name'];
107
-			}
108
-			$freeSpace = $this->getFreeSpace($uri);
109
-			if ($freeSpace !== FileInfo::SPACE_UNKNOWN && $length > $freeSpace) {
110
-				if (isset($chunkHandler)) {
111
-					$chunkHandler->cleanup();
112
-				}
113
-				throw new InsufficientStorage();
114
-			}
115
-		}
116
-		return true;
117
-	}
81
+    /**
82
+     * This method is called before any HTTP method and validates there is enough free space to store the file
83
+     *
84
+     * @param string $uri
85
+     * @throws InsufficientStorage
86
+     * @return bool
87
+     */
88
+    public function checkQuota($uri) {
89
+        $length = $this->getLength();
90
+        if ($length) {
91
+            if (substr($uri, 0, 1) !== '/') {
92
+                $uri = '/' . $uri;
93
+            }
94
+            list($parentUri, $newName) = URLUtil::splitPath($uri);
95
+            if(is_null($parentUri)) {
96
+                $parentUri = '';
97
+            }
98
+            $req = $this->server->httpRequest;
99
+            if ($req->getHeader('OC-Chunked')) {
100
+                $info = \OC_FileChunking::decodeName($newName);
101
+                $chunkHandler = $this->getFileChunking($info);
102
+                // subtract the already uploaded size to see whether
103
+                // there is still enough space for the remaining chunks
104
+                $length -= $chunkHandler->getCurrentSize();
105
+                // use target file name for free space check in case of shared files
106
+                $uri = rtrim($parentUri, '/') . '/' . $info['name'];
107
+            }
108
+            $freeSpace = $this->getFreeSpace($uri);
109
+            if ($freeSpace !== FileInfo::SPACE_UNKNOWN && $length > $freeSpace) {
110
+                if (isset($chunkHandler)) {
111
+                    $chunkHandler->cleanup();
112
+                }
113
+                throw new InsufficientStorage();
114
+            }
115
+        }
116
+        return true;
117
+    }
118 118
 
119
-	public function getFileChunking($info) {
120
-		// FIXME: need a factory for better mocking support
121
-		return new \OC_FileChunking($info);
122
-	}
119
+    public function getFileChunking($info) {
120
+        // FIXME: need a factory for better mocking support
121
+        return new \OC_FileChunking($info);
122
+    }
123 123
 
124
-	public function getLength() {
125
-		$req = $this->server->httpRequest;
126
-		$length = $req->getHeader('X-Expected-Entity-Length');
127
-		if (!is_numeric($length)) {
128
-			$length = $req->getHeader('Content-Length');
129
-			$length = is_numeric($length) ? $length : null;
130
-		}
124
+    public function getLength() {
125
+        $req = $this->server->httpRequest;
126
+        $length = $req->getHeader('X-Expected-Entity-Length');
127
+        if (!is_numeric($length)) {
128
+            $length = $req->getHeader('Content-Length');
129
+            $length = is_numeric($length) ? $length : null;
130
+        }
131 131
 
132
-		$ocLength = $req->getHeader('OC-Total-Length');
133
-		if (is_numeric($length) && is_numeric($ocLength)) {
134
-			return max($length, $ocLength);
135
-		}
132
+        $ocLength = $req->getHeader('OC-Total-Length');
133
+        if (is_numeric($length) && is_numeric($ocLength)) {
134
+            return max($length, $ocLength);
135
+        }
136 136
 
137
-		return $length;
138
-	}
137
+        return $length;
138
+    }
139 139
 
140
-	/**
141
-	 * @param string $uri
142
-	 * @return mixed
143
-	 * @throws ServiceUnavailable
144
-	 */
145
-	public function getFreeSpace($uri) {
146
-		try {
147
-			$freeSpace = $this->view->free_space(ltrim($uri, '/'));
148
-			return $freeSpace;
149
-		} catch (StorageNotAvailableException $e) {
150
-			throw new ServiceUnavailable($e->getMessage());
151
-		}
152
-	}
140
+    /**
141
+     * @param string $uri
142
+     * @return mixed
143
+     * @throws ServiceUnavailable
144
+     */
145
+    public function getFreeSpace($uri) {
146
+        try {
147
+            $freeSpace = $this->view->free_space(ltrim($uri, '/'));
148
+            return $freeSpace;
149
+        } catch (StorageNotAvailableException $e) {
150
+            throw new ServiceUnavailable($e->getMessage());
151
+        }
152
+    }
153 153
 }
Please login to merge, or discard this patch.
apps/dav/lib/Connector/Sabre/ExceptionLoggerPlugin.php 1 patch
Indentation   +75 added lines, -75 removed lines patch added patch discarded remove patch
@@ -32,88 +32,88 @@
 block discarded – undo
32 32
 use Sabre\HTTP\Response;
33 33
 
34 34
 class ExceptionLoggerPlugin extends \Sabre\DAV\ServerPlugin {
35
-	protected $nonFatalExceptions = [
36
-		'Sabre\DAV\Exception\NotAuthenticated' => true,
37
-		// If tokenauth can throw this exception (which is basically as
38
-		// NotAuthenticated. So not fatal.
39
-		'OCA\DAV\Connector\Sabre\Exception\PasswordLoginForbidden' => true,
40
-		// the sync client uses this to find out whether files exist,
41
-		// so it is not always an error, log it as debug
42
-		'Sabre\DAV\Exception\NotFound' => true,
43
-		// this one mostly happens when the same file is uploaded at
44
-		// exactly the same time from two clients, only one client
45
-		// wins, the second one gets "Precondition failed"
46
-		'Sabre\DAV\Exception\PreconditionFailed' => true,
47
-		// forbidden can be expected when trying to upload to
48
-		// read-only folders for example
49
-		'Sabre\DAV\Exception\Forbidden' => true,
50
-		// Happens when an external storage or federated share is temporarily
51
-		// not available
52
-		'Sabre\DAV\Exception\StorageNotAvailableException' => true,
53
-	];
35
+    protected $nonFatalExceptions = [
36
+        'Sabre\DAV\Exception\NotAuthenticated' => true,
37
+        // If tokenauth can throw this exception (which is basically as
38
+        // NotAuthenticated. So not fatal.
39
+        'OCA\DAV\Connector\Sabre\Exception\PasswordLoginForbidden' => true,
40
+        // the sync client uses this to find out whether files exist,
41
+        // so it is not always an error, log it as debug
42
+        'Sabre\DAV\Exception\NotFound' => true,
43
+        // this one mostly happens when the same file is uploaded at
44
+        // exactly the same time from two clients, only one client
45
+        // wins, the second one gets "Precondition failed"
46
+        'Sabre\DAV\Exception\PreconditionFailed' => true,
47
+        // forbidden can be expected when trying to upload to
48
+        // read-only folders for example
49
+        'Sabre\DAV\Exception\Forbidden' => true,
50
+        // Happens when an external storage or federated share is temporarily
51
+        // not available
52
+        'Sabre\DAV\Exception\StorageNotAvailableException' => true,
53
+    ];
54 54
 
55
-	/** @var string */
56
-	private $appName;
55
+    /** @var string */
56
+    private $appName;
57 57
 
58
-	/** @var ILogger */
59
-	private $logger;
58
+    /** @var ILogger */
59
+    private $logger;
60 60
 
61
-	/**
62
-	 * @param string $loggerAppName app name to use when logging
63
-	 * @param ILogger $logger
64
-	 */
65
-	public function __construct($loggerAppName, $logger) {
66
-		$this->appName = $loggerAppName;
67
-		$this->logger = $logger;
68
-	}
61
+    /**
62
+     * @param string $loggerAppName app name to use when logging
63
+     * @param ILogger $logger
64
+     */
65
+    public function __construct($loggerAppName, $logger) {
66
+        $this->appName = $loggerAppName;
67
+        $this->logger = $logger;
68
+    }
69 69
 
70
-	/**
71
-	 * This initializes the plugin.
72
-	 *
73
-	 * This function is called by \Sabre\DAV\Server, after
74
-	 * addPlugin is called.
75
-	 *
76
-	 * This method should set up the required event subscriptions.
77
-	 *
78
-	 * @param \Sabre\DAV\Server $server
79
-	 * @return void
80
-	 */
81
-	public function initialize(\Sabre\DAV\Server $server) {
70
+    /**
71
+     * This initializes the plugin.
72
+     *
73
+     * This function is called by \Sabre\DAV\Server, after
74
+     * addPlugin is called.
75
+     *
76
+     * This method should set up the required event subscriptions.
77
+     *
78
+     * @param \Sabre\DAV\Server $server
79
+     * @return void
80
+     */
81
+    public function initialize(\Sabre\DAV\Server $server) {
82 82
 
83
-		$server->on('exception', array($this, 'logException'), 10);
84
-	}
83
+        $server->on('exception', array($this, 'logException'), 10);
84
+    }
85 85
 
86
-	/**
87
-	 * Log exception
88
-	 *
89
-	 */
90
-	public function logException(\Exception $ex) {
91
-		$exceptionClass = get_class($ex);
92
-		$level = \OCP\Util::FATAL;
93
-		if (isset($this->nonFatalExceptions[$exceptionClass])) {
94
-			$level = \OCP\Util::DEBUG;
95
-		}
86
+    /**
87
+     * Log exception
88
+     *
89
+     */
90
+    public function logException(\Exception $ex) {
91
+        $exceptionClass = get_class($ex);
92
+        $level = \OCP\Util::FATAL;
93
+        if (isset($this->nonFatalExceptions[$exceptionClass])) {
94
+            $level = \OCP\Util::DEBUG;
95
+        }
96 96
 
97
-		$message = $ex->getMessage();
98
-		if ($ex instanceof Exception) {
99
-			if (empty($message)) {
100
-				$response = new Response($ex->getHTTPCode());
101
-				$message = $response->getStatusText();
102
-			}
103
-			$message = "HTTP/1.1 {$ex->getHTTPCode()} $message";
104
-		}
97
+        $message = $ex->getMessage();
98
+        if ($ex instanceof Exception) {
99
+            if (empty($message)) {
100
+                $response = new Response($ex->getHTTPCode());
101
+                $message = $response->getStatusText();
102
+            }
103
+            $message = "HTTP/1.1 {$ex->getHTTPCode()} $message";
104
+        }
105 105
 
106
-		$user = \OC_User::getUser();
106
+        $user = \OC_User::getUser();
107 107
 
108
-		$exception = [
109
-			'Message' => $message,
110
-			'Exception' => $exceptionClass,
111
-			'Code' => $ex->getCode(),
112
-			'Trace' => $ex->getTraceAsString(),
113
-			'File' => $ex->getFile(),
114
-			'Line' => $ex->getLine(),
115
-			'User' => $user,
116
-		];
117
-		$this->logger->log($level, 'Exception: ' . json_encode($exception), ['app' => $this->appName]);
118
-	}
108
+        $exception = [
109
+            'Message' => $message,
110
+            'Exception' => $exceptionClass,
111
+            'Code' => $ex->getCode(),
112
+            'Trace' => $ex->getTraceAsString(),
113
+            'File' => $ex->getFile(),
114
+            'Line' => $ex->getLine(),
115
+            'User' => $user,
116
+        ];
117
+        $this->logger->log($level, 'Exception: ' . json_encode($exception), ['app' => $this->appName]);
118
+    }
119 119
 }
Please login to merge, or discard this patch.
apps/dav/lib/Connector/Sabre/SharesPlugin.php 1 patch
Indentation   +177 added lines, -177 removed lines patch added patch discarded remove patch
@@ -32,181 +32,181 @@
 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
-	private $cachedFolders = [];
71
-
72
-	/**
73
-	 * @param \Sabre\DAV\Tree $tree tree
74
-	 * @param IUserSession $userSession user session
75
-	 * @param \OCP\Files\Folder $userFolder user home folder
76
-	 * @param \OCP\Share\IManager $shareManager share manager
77
-	 */
78
-	public function __construct(
79
-		\Sabre\DAV\Tree $tree,
80
-		IUserSession $userSession,
81
-		\OCP\Files\Folder $userFolder,
82
-		\OCP\Share\IManager $shareManager
83
-	) {
84
-		$this->tree = $tree;
85
-		$this->shareManager = $shareManager;
86
-		$this->userFolder = $userFolder;
87
-		$this->userId = $userSession->getUser()->getUID();
88
-		$this->cachedShareTypes = [];
89
-	}
90
-
91
-	/**
92
-	 * This initializes the plugin.
93
-	 *
94
-	 * This function is called by \Sabre\DAV\Server, after
95
-	 * addPlugin is called.
96
-	 *
97
-	 * This method should set up the required event subscriptions.
98
-	 *
99
-	 * @param \Sabre\DAV\Server $server
100
-	 */
101
-	public function initialize(\Sabre\DAV\Server $server) {
102
-		$server->xml->namespacesMap[self::NS_OWNCLOUD] = 'oc';
103
-		$server->xml->elementMap[self::SHARETYPES_PROPERTYNAME] = 'OCA\\DAV\\Connector\\Sabre\\ShareTypeList';
104
-		$server->protectedProperties[] = self::SHARETYPES_PROPERTYNAME;
105
-
106
-		$this->server = $server;
107
-		$this->server->on('propFind', array($this, 'handleGetProperties'));
108
-	}
109
-
110
-	/**
111
-	 * Return a list of share types for outgoing shares
112
-	 *
113
-	 * @param \OCP\Files\Node $node file node
114
-	 *
115
-	 * @return int[] array of share types
116
-	 */
117
-	private function getShareTypes(\OCP\Files\Node $node) {
118
-		$shareTypes = [];
119
-		$requestedShareTypes = [
120
-			\OCP\Share::SHARE_TYPE_USER,
121
-			\OCP\Share::SHARE_TYPE_GROUP,
122
-			\OCP\Share::SHARE_TYPE_LINK,
123
-			\OCP\Share::SHARE_TYPE_REMOTE,
124
-			\OCP\Share::SHARE_TYPE_EMAIL,
125
-		];
126
-		foreach ($requestedShareTypes as $requestedShareType) {
127
-			// one of each type is enough to find out about the types
128
-			$shares = $this->shareManager->getSharesBy(
129
-				$this->userId,
130
-				$requestedShareType,
131
-				$node,
132
-				false,
133
-				1
134
-			);
135
-			if (!empty($shares)) {
136
-				$shareTypes[] = $requestedShareType;
137
-			}
138
-		}
139
-		return $shareTypes;
140
-	}
141
-
142
-	private function getSharesTypesInFolder(\OCP\Files\Folder $node) {
143
-		$shares = $this->shareManager->getSharesInFolder(
144
-			$this->userId,
145
-			$node,
146
-			false
147
-		);
148
-
149
-		$shareTypesByFileId = [];
150
-
151
-		foreach($shares as $fileId => $sharesForFile) {
152
-			$types = array_map(function(IShare $share) {
153
-				return $share->getShareType();
154
-			}, $sharesForFile);
155
-			$types = array_unique($types);
156
-			sort($types);
157
-			$shareTypesByFileId[$fileId] = $types;
158
-		}
159
-
160
-		return $shareTypesByFileId;
161
-	}
162
-
163
-	/**
164
-	 * Adds shares to propfind response
165
-	 *
166
-	 * @param PropFind $propFind propfind object
167
-	 * @param \Sabre\DAV\INode $sabreNode sabre node
168
-	 */
169
-	public function handleGetProperties(
170
-		PropFind $propFind,
171
-		\Sabre\DAV\INode $sabreNode
172
-	) {
173
-		if (!($sabreNode instanceof \OCA\DAV\Connector\Sabre\Node)) {
174
-			return;
175
-		}
176
-
177
-		// need prefetch ?
178
-		if ($sabreNode instanceof \OCA\DAV\Connector\Sabre\Directory
179
-			&& $propFind->getDepth() !== 0
180
-			&& !is_null($propFind->getStatus(self::SHARETYPES_PROPERTYNAME))
181
-		) {
182
-			$folderNode = $this->userFolder->get($sabreNode->getPath());
183
-
184
-			$childShares = $this->getSharesTypesInFolder($folderNode);
185
-			$this->cachedFolders[] = $sabreNode->getPath();
186
-			$this->cachedShareTypes[$folderNode->getId()] = $this->getShareTypes($folderNode);
187
-			foreach ($childShares as $id => $shares) {
188
-				$this->cachedShareTypes[$id] = $shares;
189
-			}
190
-		}
191
-
192
-		$propFind->handle(self::SHARETYPES_PROPERTYNAME, function () use ($sabreNode) {
193
-			if (isset($this->cachedShareTypes[$sabreNode->getId()])) {
194
-				$shareTypes = $this->cachedShareTypes[$sabreNode->getId()];
195
-			} else {
196
-				list($parentPath,) = \Sabre\Uri\split($sabreNode->getPath());
197
-				if ($parentPath === '') {
198
-					$parentPath = '/';
199
-				}
200
-				// if we already cached the folder this file is in we know there are no shares for this file
201
-				if (array_search($parentPath, $this->cachedFolders) === false) {
202
-					$node = $this->userFolder->get($sabreNode->getPath());
203
-					$shareTypes = $this->getShareTypes($node);
204
-				} else {
205
-					return [];
206
-				}
207
-			}
208
-
209
-			return new ShareTypeList($shareTypes);
210
-		});
211
-	}
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
+    private $cachedFolders = [];
71
+
72
+    /**
73
+     * @param \Sabre\DAV\Tree $tree tree
74
+     * @param IUserSession $userSession user session
75
+     * @param \OCP\Files\Folder $userFolder user home folder
76
+     * @param \OCP\Share\IManager $shareManager share manager
77
+     */
78
+    public function __construct(
79
+        \Sabre\DAV\Tree $tree,
80
+        IUserSession $userSession,
81
+        \OCP\Files\Folder $userFolder,
82
+        \OCP\Share\IManager $shareManager
83
+    ) {
84
+        $this->tree = $tree;
85
+        $this->shareManager = $shareManager;
86
+        $this->userFolder = $userFolder;
87
+        $this->userId = $userSession->getUser()->getUID();
88
+        $this->cachedShareTypes = [];
89
+    }
90
+
91
+    /**
92
+     * This initializes the plugin.
93
+     *
94
+     * This function is called by \Sabre\DAV\Server, after
95
+     * addPlugin is called.
96
+     *
97
+     * This method should set up the required event subscriptions.
98
+     *
99
+     * @param \Sabre\DAV\Server $server
100
+     */
101
+    public function initialize(\Sabre\DAV\Server $server) {
102
+        $server->xml->namespacesMap[self::NS_OWNCLOUD] = 'oc';
103
+        $server->xml->elementMap[self::SHARETYPES_PROPERTYNAME] = 'OCA\\DAV\\Connector\\Sabre\\ShareTypeList';
104
+        $server->protectedProperties[] = self::SHARETYPES_PROPERTYNAME;
105
+
106
+        $this->server = $server;
107
+        $this->server->on('propFind', array($this, 'handleGetProperties'));
108
+    }
109
+
110
+    /**
111
+     * Return a list of share types for outgoing shares
112
+     *
113
+     * @param \OCP\Files\Node $node file node
114
+     *
115
+     * @return int[] array of share types
116
+     */
117
+    private function getShareTypes(\OCP\Files\Node $node) {
118
+        $shareTypes = [];
119
+        $requestedShareTypes = [
120
+            \OCP\Share::SHARE_TYPE_USER,
121
+            \OCP\Share::SHARE_TYPE_GROUP,
122
+            \OCP\Share::SHARE_TYPE_LINK,
123
+            \OCP\Share::SHARE_TYPE_REMOTE,
124
+            \OCP\Share::SHARE_TYPE_EMAIL,
125
+        ];
126
+        foreach ($requestedShareTypes as $requestedShareType) {
127
+            // one of each type is enough to find out about the types
128
+            $shares = $this->shareManager->getSharesBy(
129
+                $this->userId,
130
+                $requestedShareType,
131
+                $node,
132
+                false,
133
+                1
134
+            );
135
+            if (!empty($shares)) {
136
+                $shareTypes[] = $requestedShareType;
137
+            }
138
+        }
139
+        return $shareTypes;
140
+    }
141
+
142
+    private function getSharesTypesInFolder(\OCP\Files\Folder $node) {
143
+        $shares = $this->shareManager->getSharesInFolder(
144
+            $this->userId,
145
+            $node,
146
+            false
147
+        );
148
+
149
+        $shareTypesByFileId = [];
150
+
151
+        foreach($shares as $fileId => $sharesForFile) {
152
+            $types = array_map(function(IShare $share) {
153
+                return $share->getShareType();
154
+            }, $sharesForFile);
155
+            $types = array_unique($types);
156
+            sort($types);
157
+            $shareTypesByFileId[$fileId] = $types;
158
+        }
159
+
160
+        return $shareTypesByFileId;
161
+    }
162
+
163
+    /**
164
+     * Adds shares to propfind response
165
+     *
166
+     * @param PropFind $propFind propfind object
167
+     * @param \Sabre\DAV\INode $sabreNode sabre node
168
+     */
169
+    public function handleGetProperties(
170
+        PropFind $propFind,
171
+        \Sabre\DAV\INode $sabreNode
172
+    ) {
173
+        if (!($sabreNode instanceof \OCA\DAV\Connector\Sabre\Node)) {
174
+            return;
175
+        }
176
+
177
+        // need prefetch ?
178
+        if ($sabreNode instanceof \OCA\DAV\Connector\Sabre\Directory
179
+            && $propFind->getDepth() !== 0
180
+            && !is_null($propFind->getStatus(self::SHARETYPES_PROPERTYNAME))
181
+        ) {
182
+            $folderNode = $this->userFolder->get($sabreNode->getPath());
183
+
184
+            $childShares = $this->getSharesTypesInFolder($folderNode);
185
+            $this->cachedFolders[] = $sabreNode->getPath();
186
+            $this->cachedShareTypes[$folderNode->getId()] = $this->getShareTypes($folderNode);
187
+            foreach ($childShares as $id => $shares) {
188
+                $this->cachedShareTypes[$id] = $shares;
189
+            }
190
+        }
191
+
192
+        $propFind->handle(self::SHARETYPES_PROPERTYNAME, function () use ($sabreNode) {
193
+            if (isset($this->cachedShareTypes[$sabreNode->getId()])) {
194
+                $shareTypes = $this->cachedShareTypes[$sabreNode->getId()];
195
+            } else {
196
+                list($parentPath,) = \Sabre\Uri\split($sabreNode->getPath());
197
+                if ($parentPath === '') {
198
+                    $parentPath = '/';
199
+                }
200
+                // if we already cached the folder this file is in we know there are no shares for this file
201
+                if (array_search($parentPath, $this->cachedFolders) === false) {
202
+                    $node = $this->userFolder->get($sabreNode->getPath());
203
+                    $shareTypes = $this->getShareTypes($node);
204
+                } else {
205
+                    return [];
206
+                }
207
+            }
208
+
209
+            return new ShareTypeList($shareTypes);
210
+        });
211
+    }
212 212
 }
Please login to merge, or discard this patch.