Completed
Pull Request — master (#3590)
by Individual IT
11:38
created
apps/files_sharing/lib/Updater.php 1 patch
Indentation   +76 added lines, -76 removed lines patch added patch discarded remove patch
@@ -27,81 +27,81 @@
 block discarded – undo
27 27
 
28 28
 class Updater {
29 29
 
30
-	/**
31
-	 * @param array $params
32
-	 */
33
-	static public function renameHook($params) {
34
-		self::renameChildren($params['oldpath'], $params['newpath']);
35
-		self::moveShareToShare($params['newpath']);
36
-	}
37
-
38
-	/**
39
-	 * Fix for https://github.com/owncloud/core/issues/20769
40
-	 *
41
-	 * The owner is allowed to move their files (if they are shared) into a receiving folder
42
-	 * In this case we need to update the parent of the moved share. Since they are
43
-	 * effectively handing over ownership of the file the rest of the code needs to know
44
-	 * they need to build up the reshare tree.
45
-	 *
46
-	 * @param string $path
47
-	 */
48
-	static private function moveShareToShare($path) {
49
-		$userFolder = \OC::$server->getUserFolder();
50
-
51
-		// If the user folder can't be constructed (e.g. link share) just return.
52
-		if ($userFolder === null) {
53
-			return;
54
-		}
55
-
56
-		$src = $userFolder->get($path);
57
-
58
-		$shareManager = \OC::$server->getShareManager();
59
-
60
-		$shares = $shareManager->getSharesBy($userFolder->getOwner()->getUID(), \OCP\Share::SHARE_TYPE_USER, $src, false, -1);
61
-		$shares = array_merge($shares, $shareManager->getSharesBy($userFolder->getOwner()->getUID(), \OCP\Share::SHARE_TYPE_GROUP, $src, false, -1));
62
-
63
-		// If the path we move is not a share we don't care
64
-		if (empty($shares)) {
65
-			return;
66
-		}
67
-
68
-		// Check if the destination is inside a share
69
-		$mountManager = \OC::$server->getMountManager();
70
-		$dstMount = $mountManager->find($src->getPath());
71
-		if (!($dstMount instanceof \OCA\Files_Sharing\SharedMount)) {
72
-			return;
73
-		}
74
-
75
-		$newOwner = $dstMount->getShare()->getShareOwner();
76
-
77
-		//Ownership is moved over
78
-		foreach ($shares as $share) {
79
-			/** @var \OCP\Share\IShare $share */
80
-			$share->setShareOwner($newOwner);
81
-			$shareManager->updateShare($share);
82
-		}
83
-	}
84
-
85
-	/**
86
-	 * rename mount point from the children if the parent was renamed
87
-	 *
88
-	 * @param string $oldPath old path relative to data/user/files
89
-	 * @param string $newPath new path relative to data/user/files
90
-	 */
91
-	static private function renameChildren($oldPath, $newPath) {
92
-
93
-		$absNewPath =  \OC\Files\Filesystem::normalizePath('/' . \OCP\User::getUser() . '/files/' . $newPath);
94
-		$absOldPath =  \OC\Files\Filesystem::normalizePath('/' . \OCP\User::getUser() . '/files/' . $oldPath);
95
-
96
-		$mountManager = \OC\Files\Filesystem::getMountManager();
97
-		$mountedShares = $mountManager->findIn('/' . \OCP\User::getUser() . '/files/' . $oldPath);
98
-		foreach ($mountedShares as $mount) {
99
-			if ($mount->getStorage()->instanceOfStorage('OCA\Files_Sharing\ISharedStorage')) {
100
-				$mountPoint = $mount->getMountPoint();
101
-				$target = str_replace($absOldPath, $absNewPath, $mountPoint);
102
-				$mount->moveMount($target);
103
-			}
104
-		}
105
-	}
30
+    /**
31
+     * @param array $params
32
+     */
33
+    static public function renameHook($params) {
34
+        self::renameChildren($params['oldpath'], $params['newpath']);
35
+        self::moveShareToShare($params['newpath']);
36
+    }
37
+
38
+    /**
39
+     * Fix for https://github.com/owncloud/core/issues/20769
40
+     *
41
+     * The owner is allowed to move their files (if they are shared) into a receiving folder
42
+     * In this case we need to update the parent of the moved share. Since they are
43
+     * effectively handing over ownership of the file the rest of the code needs to know
44
+     * they need to build up the reshare tree.
45
+     *
46
+     * @param string $path
47
+     */
48
+    static private function moveShareToShare($path) {
49
+        $userFolder = \OC::$server->getUserFolder();
50
+
51
+        // If the user folder can't be constructed (e.g. link share) just return.
52
+        if ($userFolder === null) {
53
+            return;
54
+        }
55
+
56
+        $src = $userFolder->get($path);
57
+
58
+        $shareManager = \OC::$server->getShareManager();
59
+
60
+        $shares = $shareManager->getSharesBy($userFolder->getOwner()->getUID(), \OCP\Share::SHARE_TYPE_USER, $src, false, -1);
61
+        $shares = array_merge($shares, $shareManager->getSharesBy($userFolder->getOwner()->getUID(), \OCP\Share::SHARE_TYPE_GROUP, $src, false, -1));
62
+
63
+        // If the path we move is not a share we don't care
64
+        if (empty($shares)) {
65
+            return;
66
+        }
67
+
68
+        // Check if the destination is inside a share
69
+        $mountManager = \OC::$server->getMountManager();
70
+        $dstMount = $mountManager->find($src->getPath());
71
+        if (!($dstMount instanceof \OCA\Files_Sharing\SharedMount)) {
72
+            return;
73
+        }
74
+
75
+        $newOwner = $dstMount->getShare()->getShareOwner();
76
+
77
+        //Ownership is moved over
78
+        foreach ($shares as $share) {
79
+            /** @var \OCP\Share\IShare $share */
80
+            $share->setShareOwner($newOwner);
81
+            $shareManager->updateShare($share);
82
+        }
83
+    }
84
+
85
+    /**
86
+     * rename mount point from the children if the parent was renamed
87
+     *
88
+     * @param string $oldPath old path relative to data/user/files
89
+     * @param string $newPath new path relative to data/user/files
90
+     */
91
+    static private function renameChildren($oldPath, $newPath) {
92
+
93
+        $absNewPath =  \OC\Files\Filesystem::normalizePath('/' . \OCP\User::getUser() . '/files/' . $newPath);
94
+        $absOldPath =  \OC\Files\Filesystem::normalizePath('/' . \OCP\User::getUser() . '/files/' . $oldPath);
95
+
96
+        $mountManager = \OC\Files\Filesystem::getMountManager();
97
+        $mountedShares = $mountManager->findIn('/' . \OCP\User::getUser() . '/files/' . $oldPath);
98
+        foreach ($mountedShares as $mount) {
99
+            if ($mount->getStorage()->instanceOfStorage('OCA\Files_Sharing\ISharedStorage')) {
100
+                $mountPoint = $mount->getMountPoint();
101
+                $target = str_replace($absOldPath, $absNewPath, $mountPoint);
102
+                $mount->moveMount($target);
103
+            }
104
+        }
105
+    }
106 106
 
107 107
 }
Please login to merge, or discard this patch.
apps/files_sharing/lib/Helper.php 1 patch
Indentation   +237 added lines, -237 removed lines patch added patch discarded remove patch
@@ -36,242 +36,242 @@
 block discarded – undo
36 36
 
37 37
 class Helper {
38 38
 
39
-	public static function registerHooks() {
40
-		\OCP\Util::connectHook('OC_Filesystem', 'post_rename', '\OCA\Files_Sharing\Updater', 'renameHook');
41
-		\OCP\Util::connectHook('OC_Filesystem', 'post_delete', '\OCA\Files_Sharing\Hooks', 'unshareChildren');
42
-
43
-		\OCP\Util::connectHook('OC_User', 'post_deleteUser', '\OCA\Files_Sharing\Hooks', 'deleteUser');
44
-	}
45
-
46
-	/**
47
-	 * Sets up the filesystem and user for public sharing
48
-	 * @param string $token string share token
49
-	 * @param string $relativePath optional path relative to the share
50
-	 * @param string $password optional password
51
-	 * @return array
52
-	 */
53
-	public static function setupFromToken($token, $relativePath = null, $password = null) {
54
-		\OC_User::setIncognitoMode(true);
55
-
56
-		$shareManager = \OC::$server->getShareManager();
57
-
58
-		try {
59
-			$share = $shareManager->getShareByToken($token);
60
-		} catch (ShareNotFound $e) {
61
-			\OC_Response::setStatus(404);
62
-			\OCP\Util::writeLog('core-preview', 'Passed token parameter is not valid', \OCP\Util::DEBUG);
63
-			exit;
64
-		}
65
-
66
-		\OCP\JSON::checkUserExists($share->getShareOwner());
67
-		\OC_Util::tearDownFS();
68
-		\OC_Util::setupFS($share->getShareOwner());
69
-
70
-
71
-		try {
72
-			$path = Filesystem::getPath($share->getNodeId());
73
-		} catch (NotFoundException $e) {
74
-			\OCP\Util::writeLog('share', 'could not resolve linkItem', \OCP\Util::DEBUG);
75
-			\OC_Response::setStatus(404);
76
-			\OCP\JSON::error(array('success' => false));
77
-			exit();
78
-		}
79
-
80
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK && $share->getPassword() !== null) {
81
-			if (!self::authenticate($share, $password)) {
82
-				\OC_Response::setStatus(403);
83
-				\OCP\JSON::error(array('success' => false));
84
-				exit();
85
-			}
86
-		}
87
-
88
-		$basePath = $path;
89
-
90
-		if ($relativePath !== null && Filesystem::isReadable($basePath . $relativePath)) {
91
-			$path .= Filesystem::normalizePath($relativePath);
92
-		}
93
-
94
-		return array(
95
-			'share' => $share,
96
-			'basePath' => $basePath,
97
-			'realPath' => $path
98
-		);
99
-	}
100
-
101
-	/**
102
-	 * Authenticate link item with the given password
103
-	 * or with the session if no password was given.
104
-	 * @param \OCP\Share\IShare $share
105
-	 * @param string $password optional password
106
-	 *
107
-	 * @return boolean true if authorized, false otherwise
108
-	 */
109
-	public static function authenticate($share, $password = null) {
110
-		$shareManager = \OC::$server->getShareManager();
111
-
112
-		if ($password !== null) {
113
-			if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
114
-				if ($shareManager->checkPassword($share, $password)) {
115
-					\OC::$server->getSession()->set('public_link_authenticated', (string)$share->getId());
116
-					return true;
117
-				}
118
-			}
119
-		} else {
120
-			// not authenticated ?
121
-			if (\OC::$server->getSession()->exists('public_link_authenticated')
122
-				&& \OC::$server->getSession()->get('public_link_authenticated') !== (string)$share->getId()) {
123
-				return true;
124
-			}
125
-		}
126
-		return false;
127
-	}
128
-
129
-	public static function getSharesFromItem($target) {
130
-		$result = array();
131
-		$owner = Filesystem::getOwner($target);
132
-		Filesystem::initMountPoints($owner);
133
-		$info = Filesystem::getFileInfo($target);
134
-		$ownerView = new View('/'.$owner.'/files');
135
-		if ( $owner != User::getUser() ) {
136
-			$path = $ownerView->getPath($info['fileid']);
137
-		} else {
138
-			$path = $target;
139
-		}
140
-
141
-
142
-		$ids = array();
143
-		while ($path !== dirname($path)) {
144
-			$info = $ownerView->getFileInfo($path);
145
-			if ($info instanceof \OC\Files\FileInfo) {
146
-				$ids[] = $info['fileid'];
147
-			} else {
148
-				\OCP\Util::writeLog('sharing', 'No fileinfo available for: ' . $path, \OCP\Util::WARN);
149
-			}
150
-			$path = dirname($path);
151
-		}
152
-
153
-		if (!empty($ids)) {
154
-
155
-			$idList = array_chunk($ids, 99, true);
156
-
157
-			foreach ($idList as $subList) {
158
-				$statement = "SELECT `share_with`, `share_type`, `file_target` FROM `*PREFIX*share` WHERE `file_source` IN (" . implode(',', $subList) . ") AND `share_type` IN (0, 1, 2)";
159
-				$query = \OCP\DB::prepare($statement);
160
-				$r = $query->execute();
161
-				$result = array_merge($result, $r->fetchAll());
162
-			}
163
-		}
164
-
165
-		return $result;
166
-	}
167
-
168
-	/**
169
-	 * get the UID of the owner of the file and the path to the file relative to
170
-	 * owners files folder
171
-	 *
172
-	 * @param $filename
173
-	 * @return array
174
-	 * @throws \OC\User\NoUserException
175
-	 */
176
-	public static function getUidAndFilename($filename) {
177
-		$uid = Filesystem::getOwner($filename);
178
-		$userManager = \OC::$server->getUserManager();
179
-		// if the user with the UID doesn't exists, e.g. because the UID points
180
-		// to a remote user with a federated cloud ID we use the current logged-in
181
-		// user. We need a valid local user to create the share
182
-		if (!$userManager->userExists($uid)) {
183
-			$uid = User::getUser();
184
-		}
185
-		Filesystem::initMountPoints($uid);
186
-		if ( $uid != User::getUser() ) {
187
-			$info = Filesystem::getFileInfo($filename);
188
-			$ownerView = new View('/'.$uid.'/files');
189
-			try {
190
-				$filename = $ownerView->getPath($info['fileid']);
191
-			} catch (NotFoundException $e) {
192
-				$filename = null;
193
-			}
194
-		}
195
-		return [$uid, $filename];
196
-	}
197
-
198
-	/**
199
-	 * Format a path to be relative to the /user/files/ directory
200
-	 * @param string $path the absolute path
201
-	 * @return string e.g. turns '/admin/files/test.txt' into 'test.txt'
202
-	 */
203
-	public static function stripUserFilesPath($path) {
204
-		$trimmed = ltrim($path, '/');
205
-		$split = explode('/', $trimmed);
206
-
207
-		// it is not a file relative to data/user/files
208
-		if (count($split) < 3 || $split[1] !== 'files') {
209
-			return false;
210
-		}
211
-
212
-		$sliced = array_slice($split, 2);
213
-		$relPath = implode('/', $sliced);
214
-
215
-		return $relPath;
216
-	}
217
-
218
-	/**
219
-	 * check if file name already exists and generate unique target
220
-	 *
221
-	 * @param string $path
222
-	 * @param array $excludeList
223
-	 * @param View $view
224
-	 * @return string $path
225
-	 */
226
-	public static function generateUniqueTarget($path, $excludeList, $view) {
227
-		$pathinfo = pathinfo($path);
228
-		$ext = (isset($pathinfo['extension'])) ? '.'.$pathinfo['extension'] : '';
229
-		$name = $pathinfo['filename'];
230
-		$dir = $pathinfo['dirname'];
231
-		$i = 2;
232
-		while ($view->file_exists($path) || in_array($path, $excludeList)) {
233
-			$path = Filesystem::normalizePath($dir . '/' . $name . ' ('.$i.')' . $ext);
234
-			$i++;
235
-		}
236
-
237
-		return $path;
238
-	}
239
-
240
-	/**
241
-	 * get default share folder
242
-	 *
243
-	 * @param \OC\Files\View
244
-	 * @return string
245
-	 */
246
-	public static function getShareFolder($view = null) {
247
-		if ($view === null) {
248
-			$view = Filesystem::getView();
249
-		}
250
-		$shareFolder = \OC::$server->getConfig()->getSystemValue('share_folder', '/');
251
-		$shareFolder = Filesystem::normalizePath($shareFolder);
252
-
253
-		if (!$view->file_exists($shareFolder)) {
254
-			$dir = '';
255
-			$subdirs = explode('/', $shareFolder);
256
-			foreach ($subdirs as $subdir) {
257
-				$dir = $dir . '/' . $subdir;
258
-				if (!$view->is_dir($dir)) {
259
-					$view->mkdir($dir);
260
-				}
261
-			}
262
-		}
263
-
264
-		return $shareFolder;
265
-
266
-	}
267
-
268
-	/**
269
-	 * set default share folder
270
-	 *
271
-	 * @param string $shareFolder
272
-	 */
273
-	public static function setShareFolder($shareFolder) {
274
-		\OC::$server->getConfig()->setSystemValue('share_folder', $shareFolder);
275
-	}
39
+    public static function registerHooks() {
40
+        \OCP\Util::connectHook('OC_Filesystem', 'post_rename', '\OCA\Files_Sharing\Updater', 'renameHook');
41
+        \OCP\Util::connectHook('OC_Filesystem', 'post_delete', '\OCA\Files_Sharing\Hooks', 'unshareChildren');
42
+
43
+        \OCP\Util::connectHook('OC_User', 'post_deleteUser', '\OCA\Files_Sharing\Hooks', 'deleteUser');
44
+    }
45
+
46
+    /**
47
+     * Sets up the filesystem and user for public sharing
48
+     * @param string $token string share token
49
+     * @param string $relativePath optional path relative to the share
50
+     * @param string $password optional password
51
+     * @return array
52
+     */
53
+    public static function setupFromToken($token, $relativePath = null, $password = null) {
54
+        \OC_User::setIncognitoMode(true);
55
+
56
+        $shareManager = \OC::$server->getShareManager();
57
+
58
+        try {
59
+            $share = $shareManager->getShareByToken($token);
60
+        } catch (ShareNotFound $e) {
61
+            \OC_Response::setStatus(404);
62
+            \OCP\Util::writeLog('core-preview', 'Passed token parameter is not valid', \OCP\Util::DEBUG);
63
+            exit;
64
+        }
65
+
66
+        \OCP\JSON::checkUserExists($share->getShareOwner());
67
+        \OC_Util::tearDownFS();
68
+        \OC_Util::setupFS($share->getShareOwner());
69
+
70
+
71
+        try {
72
+            $path = Filesystem::getPath($share->getNodeId());
73
+        } catch (NotFoundException $e) {
74
+            \OCP\Util::writeLog('share', 'could not resolve linkItem', \OCP\Util::DEBUG);
75
+            \OC_Response::setStatus(404);
76
+            \OCP\JSON::error(array('success' => false));
77
+            exit();
78
+        }
79
+
80
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK && $share->getPassword() !== null) {
81
+            if (!self::authenticate($share, $password)) {
82
+                \OC_Response::setStatus(403);
83
+                \OCP\JSON::error(array('success' => false));
84
+                exit();
85
+            }
86
+        }
87
+
88
+        $basePath = $path;
89
+
90
+        if ($relativePath !== null && Filesystem::isReadable($basePath . $relativePath)) {
91
+            $path .= Filesystem::normalizePath($relativePath);
92
+        }
93
+
94
+        return array(
95
+            'share' => $share,
96
+            'basePath' => $basePath,
97
+            'realPath' => $path
98
+        );
99
+    }
100
+
101
+    /**
102
+     * Authenticate link item with the given password
103
+     * or with the session if no password was given.
104
+     * @param \OCP\Share\IShare $share
105
+     * @param string $password optional password
106
+     *
107
+     * @return boolean true if authorized, false otherwise
108
+     */
109
+    public static function authenticate($share, $password = null) {
110
+        $shareManager = \OC::$server->getShareManager();
111
+
112
+        if ($password !== null) {
113
+            if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
114
+                if ($shareManager->checkPassword($share, $password)) {
115
+                    \OC::$server->getSession()->set('public_link_authenticated', (string)$share->getId());
116
+                    return true;
117
+                }
118
+            }
119
+        } else {
120
+            // not authenticated ?
121
+            if (\OC::$server->getSession()->exists('public_link_authenticated')
122
+                && \OC::$server->getSession()->get('public_link_authenticated') !== (string)$share->getId()) {
123
+                return true;
124
+            }
125
+        }
126
+        return false;
127
+    }
128
+
129
+    public static function getSharesFromItem($target) {
130
+        $result = array();
131
+        $owner = Filesystem::getOwner($target);
132
+        Filesystem::initMountPoints($owner);
133
+        $info = Filesystem::getFileInfo($target);
134
+        $ownerView = new View('/'.$owner.'/files');
135
+        if ( $owner != User::getUser() ) {
136
+            $path = $ownerView->getPath($info['fileid']);
137
+        } else {
138
+            $path = $target;
139
+        }
140
+
141
+
142
+        $ids = array();
143
+        while ($path !== dirname($path)) {
144
+            $info = $ownerView->getFileInfo($path);
145
+            if ($info instanceof \OC\Files\FileInfo) {
146
+                $ids[] = $info['fileid'];
147
+            } else {
148
+                \OCP\Util::writeLog('sharing', 'No fileinfo available for: ' . $path, \OCP\Util::WARN);
149
+            }
150
+            $path = dirname($path);
151
+        }
152
+
153
+        if (!empty($ids)) {
154
+
155
+            $idList = array_chunk($ids, 99, true);
156
+
157
+            foreach ($idList as $subList) {
158
+                $statement = "SELECT `share_with`, `share_type`, `file_target` FROM `*PREFIX*share` WHERE `file_source` IN (" . implode(',', $subList) . ") AND `share_type` IN (0, 1, 2)";
159
+                $query = \OCP\DB::prepare($statement);
160
+                $r = $query->execute();
161
+                $result = array_merge($result, $r->fetchAll());
162
+            }
163
+        }
164
+
165
+        return $result;
166
+    }
167
+
168
+    /**
169
+     * get the UID of the owner of the file and the path to the file relative to
170
+     * owners files folder
171
+     *
172
+     * @param $filename
173
+     * @return array
174
+     * @throws \OC\User\NoUserException
175
+     */
176
+    public static function getUidAndFilename($filename) {
177
+        $uid = Filesystem::getOwner($filename);
178
+        $userManager = \OC::$server->getUserManager();
179
+        // if the user with the UID doesn't exists, e.g. because the UID points
180
+        // to a remote user with a federated cloud ID we use the current logged-in
181
+        // user. We need a valid local user to create the share
182
+        if (!$userManager->userExists($uid)) {
183
+            $uid = User::getUser();
184
+        }
185
+        Filesystem::initMountPoints($uid);
186
+        if ( $uid != User::getUser() ) {
187
+            $info = Filesystem::getFileInfo($filename);
188
+            $ownerView = new View('/'.$uid.'/files');
189
+            try {
190
+                $filename = $ownerView->getPath($info['fileid']);
191
+            } catch (NotFoundException $e) {
192
+                $filename = null;
193
+            }
194
+        }
195
+        return [$uid, $filename];
196
+    }
197
+
198
+    /**
199
+     * Format a path to be relative to the /user/files/ directory
200
+     * @param string $path the absolute path
201
+     * @return string e.g. turns '/admin/files/test.txt' into 'test.txt'
202
+     */
203
+    public static function stripUserFilesPath($path) {
204
+        $trimmed = ltrim($path, '/');
205
+        $split = explode('/', $trimmed);
206
+
207
+        // it is not a file relative to data/user/files
208
+        if (count($split) < 3 || $split[1] !== 'files') {
209
+            return false;
210
+        }
211
+
212
+        $sliced = array_slice($split, 2);
213
+        $relPath = implode('/', $sliced);
214
+
215
+        return $relPath;
216
+    }
217
+
218
+    /**
219
+     * check if file name already exists and generate unique target
220
+     *
221
+     * @param string $path
222
+     * @param array $excludeList
223
+     * @param View $view
224
+     * @return string $path
225
+     */
226
+    public static function generateUniqueTarget($path, $excludeList, $view) {
227
+        $pathinfo = pathinfo($path);
228
+        $ext = (isset($pathinfo['extension'])) ? '.'.$pathinfo['extension'] : '';
229
+        $name = $pathinfo['filename'];
230
+        $dir = $pathinfo['dirname'];
231
+        $i = 2;
232
+        while ($view->file_exists($path) || in_array($path, $excludeList)) {
233
+            $path = Filesystem::normalizePath($dir . '/' . $name . ' ('.$i.')' . $ext);
234
+            $i++;
235
+        }
236
+
237
+        return $path;
238
+    }
239
+
240
+    /**
241
+     * get default share folder
242
+     *
243
+     * @param \OC\Files\View
244
+     * @return string
245
+     */
246
+    public static function getShareFolder($view = null) {
247
+        if ($view === null) {
248
+            $view = Filesystem::getView();
249
+        }
250
+        $shareFolder = \OC::$server->getConfig()->getSystemValue('share_folder', '/');
251
+        $shareFolder = Filesystem::normalizePath($shareFolder);
252
+
253
+        if (!$view->file_exists($shareFolder)) {
254
+            $dir = '';
255
+            $subdirs = explode('/', $shareFolder);
256
+            foreach ($subdirs as $subdir) {
257
+                $dir = $dir . '/' . $subdir;
258
+                if (!$view->is_dir($dir)) {
259
+                    $view->mkdir($dir);
260
+                }
261
+            }
262
+        }
263
+
264
+        return $shareFolder;
265
+
266
+    }
267
+
268
+    /**
269
+     * set default share folder
270
+     *
271
+     * @param string $shareFolder
272
+     */
273
+    public static function setShareFolder($shareFolder) {
274
+        \OC::$server->getConfig()->setSystemValue('share_folder', $shareFolder);
275
+    }
276 276
 
277 277
 }
Please login to merge, or discard this patch.
apps/files_sharing/lib/Capabilities.php 1 patch
Indentation   +48 added lines, -48 removed lines patch added patch discarded remove patch
@@ -31,63 +31,63 @@
 block discarded – undo
31 31
  */
32 32
 class Capabilities implements ICapability {
33 33
 
34
-	/** @var IConfig */
35
-	private $config;
34
+    /** @var IConfig */
35
+    private $config;
36 36
 
37
-	public function __construct(IConfig $config) {
38
-		$this->config = $config;
39
-	}
37
+    public function __construct(IConfig $config) {
38
+        $this->config = $config;
39
+    }
40 40
 
41
-	/**
42
-	 * Return this classes capabilities
43
-	 *
44
-	 * @return array
45
-	 */
46
-	public function getCapabilities() {
47
-		$res = [];
41
+    /**
42
+     * Return this classes capabilities
43
+     *
44
+     * @return array
45
+     */
46
+    public function getCapabilities() {
47
+        $res = [];
48 48
 
49
-		if ($this->config->getAppValue('core', 'shareapi_enabled', 'yes') !== 'yes') {
50
-			$res['api_enabled'] = false;
51
-			$res['public'] = ['enabled' => false];
52
-			$res['user'] = ['send_mail' => false];
53
-			$res['resharing'] = false;
54
-		} else {
55
-			$res['api_enabled'] = true;
49
+        if ($this->config->getAppValue('core', 'shareapi_enabled', 'yes') !== 'yes') {
50
+            $res['api_enabled'] = false;
51
+            $res['public'] = ['enabled' => false];
52
+            $res['user'] = ['send_mail' => false];
53
+            $res['resharing'] = false;
54
+        } else {
55
+            $res['api_enabled'] = true;
56 56
 
57
-			$public = [];
58
-			$public['enabled'] = $this->config->getAppValue('core', 'shareapi_allow_links', 'yes') === 'yes';
59
-			if ($public['enabled']) {
60
-				$public['password'] = [];
61
-				$public['password']['enforced'] = ($this->config->getAppValue('core', 'shareapi_enforce_links_password', 'no') === 'yes');
57
+            $public = [];
58
+            $public['enabled'] = $this->config->getAppValue('core', 'shareapi_allow_links', 'yes') === 'yes';
59
+            if ($public['enabled']) {
60
+                $public['password'] = [];
61
+                $public['password']['enforced'] = ($this->config->getAppValue('core', 'shareapi_enforce_links_password', 'no') === 'yes');
62 62
 
63
-				$public['expire_date'] = [];
64
-				$public['expire_date']['enabled'] = $this->config->getAppValue('core', 'shareapi_default_expire_date', 'no') === 'yes';
65
-				if ($public['expire_date']['enabled']) {
66
-					$public['expire_date']['days'] = $this->config->getAppValue('core', 'shareapi_expire_after_n_days', '7');
67
-					$public['expire_date']['enforced'] = $this->config->getAppValue('core', 'shareapi_enforce_expire_date', 'no') === 'yes';
68
-				}
63
+                $public['expire_date'] = [];
64
+                $public['expire_date']['enabled'] = $this->config->getAppValue('core', 'shareapi_default_expire_date', 'no') === 'yes';
65
+                if ($public['expire_date']['enabled']) {
66
+                    $public['expire_date']['days'] = $this->config->getAppValue('core', 'shareapi_expire_after_n_days', '7');
67
+                    $public['expire_date']['enforced'] = $this->config->getAppValue('core', 'shareapi_enforce_expire_date', 'no') === 'yes';
68
+                }
69 69
 
70
-				$public['send_mail'] = $this->config->getAppValue('core', 'shareapi_allow_public_notification', 'no') === 'yes';
71
-				$public['upload'] = $this->config->getAppValue('core', 'shareapi_allow_public_upload', 'yes') === 'yes';
72
-				$public['upload_files_drop'] = $public['upload'];
73
-			}
74
-			$res["public"] = $public;
70
+                $public['send_mail'] = $this->config->getAppValue('core', 'shareapi_allow_public_notification', 'no') === 'yes';
71
+                $public['upload'] = $this->config->getAppValue('core', 'shareapi_allow_public_upload', 'yes') === 'yes';
72
+                $public['upload_files_drop'] = $public['upload'];
73
+            }
74
+            $res["public"] = $public;
75 75
 
76
-			$res['resharing'] = $this->config->getAppValue('core', 'shareapi_allow_resharing', 'yes') === 'yes';
76
+            $res['resharing'] = $this->config->getAppValue('core', 'shareapi_allow_resharing', 'yes') === 'yes';
77 77
 
78
-			$res['user']['send_mail'] = false;
78
+            $res['user']['send_mail'] = false;
79 79
 
80
-			$res['group_sharing'] = $this->config->getAppValue('core', 'shareapi_allow_group_sharing', 'yes') === 'yes';
81
-		}
80
+            $res['group_sharing'] = $this->config->getAppValue('core', 'shareapi_allow_group_sharing', 'yes') === 'yes';
81
+        }
82 82
 
83
-		//Federated sharing
84
-		$res['federation'] = [
85
-			'outgoing'  => $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes') === 'yes',
86
-			'incoming' => $this->config->getAppValue('files_sharing', 'incoming_server2server_share_enabled', 'yes') === 'yes'
87
-		];
83
+        //Federated sharing
84
+        $res['federation'] = [
85
+            'outgoing'  => $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes') === 'yes',
86
+            'incoming' => $this->config->getAppValue('files_sharing', 'incoming_server2server_share_enabled', 'yes') === 'yes'
87
+        ];
88 88
 
89
-		return [
90
-			'files_sharing' => $res,
91
-		];
92
-	}
89
+        return [
90
+            'files_sharing' => $res,
91
+        ];
92
+    }
93 93
 }
Please login to merge, or discard this patch.
apps/files_sharing/lib/Hooks.php 1 patch
Indentation   +28 added lines, -28 removed lines patch added patch discarded remove patch
@@ -31,35 +31,35 @@
 block discarded – undo
31 31
 
32 32
 class Hooks {
33 33
 
34
-	public static function deleteUser($params) {
35
-		$discoveryManager = new DiscoveryManager(
36
-			\OC::$server->getMemCacheFactory(),
37
-			\OC::$server->getHTTPClientService()
38
-		);
39
-		$manager = new External\Manager(
40
-			\OC::$server->getDatabaseConnection(),
41
-			\OC\Files\Filesystem::getMountManager(),
42
-			\OC\Files\Filesystem::getLoader(),
43
-			\OC::$server->getHTTPClientService(),
44
-			\OC::$server->getNotificationManager(),
45
-			$discoveryManager,
46
-			$params['uid']);
34
+    public static function deleteUser($params) {
35
+        $discoveryManager = new DiscoveryManager(
36
+            \OC::$server->getMemCacheFactory(),
37
+            \OC::$server->getHTTPClientService()
38
+        );
39
+        $manager = new External\Manager(
40
+            \OC::$server->getDatabaseConnection(),
41
+            \OC\Files\Filesystem::getMountManager(),
42
+            \OC\Files\Filesystem::getLoader(),
43
+            \OC::$server->getHTTPClientService(),
44
+            \OC::$server->getNotificationManager(),
45
+            $discoveryManager,
46
+            $params['uid']);
47 47
 
48
-		$manager->removeUserShares($params['uid']);
49
-	}
48
+        $manager->removeUserShares($params['uid']);
49
+    }
50 50
 
51
-	public static function unshareChildren($params) {
52
-		$path = Filesystem::getView()->getAbsolutePath($params['path']);
53
-		$view = new \OC\Files\View('/');
51
+    public static function unshareChildren($params) {
52
+        $path = Filesystem::getView()->getAbsolutePath($params['path']);
53
+        $view = new \OC\Files\View('/');
54 54
 
55
-		// find share mount points within $path and unmount them
56
-		$mountManager = \OC\Files\Filesystem::getMountManager();
57
-		$mountedShares = $mountManager->findIn($path);
58
-		foreach ($mountedShares as $mount) {
59
-			if ($mount->getStorage()->instanceOfStorage('OCA\Files_Sharing\ISharedStorage')) {
60
-				$mountPoint = $mount->getMountPoint();
61
-				$view->unlink($mountPoint);
62
-			}
63
-		}
64
-	}
55
+        // find share mount points within $path and unmount them
56
+        $mountManager = \OC\Files\Filesystem::getMountManager();
57
+        $mountedShares = $mountManager->findIn($path);
58
+        foreach ($mountedShares as $mount) {
59
+            if ($mount->getStorage()->instanceOfStorage('OCA\Files_Sharing\ISharedStorage')) {
60
+                $mountPoint = $mount->getMountPoint();
61
+                $view->unlink($mountPoint);
62
+            }
63
+        }
64
+    }
65 65
 }
Please login to merge, or discard this patch.
apps/files_sharing/lib/DeleteOrphanedSharesJob.php 1 patch
Indentation   +27 added lines, -27 removed lines patch added patch discarded remove patch
@@ -31,36 +31,36 @@
 block discarded – undo
31 31
  */
32 32
 class DeleteOrphanedSharesJob extends TimedJob {
33 33
 
34
-	/**
35
-	 * Default interval in minutes
36
-	 *
37
-	 * @var int $defaultIntervalMin
38
-	 **/
39
-	protected $defaultIntervalMin = 15;
34
+    /**
35
+     * Default interval in minutes
36
+     *
37
+     * @var int $defaultIntervalMin
38
+     **/
39
+    protected $defaultIntervalMin = 15;
40 40
 
41
-	/**
42
-	 * sets the correct interval for this timed job
43
-	 */
44
-	public function __construct(){
45
-		$this->interval = $this->defaultIntervalMin * 60;
46
-	}
41
+    /**
42
+     * sets the correct interval for this timed job
43
+     */
44
+    public function __construct(){
45
+        $this->interval = $this->defaultIntervalMin * 60;
46
+    }
47 47
 
48
-	/**
49
-	 * Makes the background job do its work
50
-	 *
51
-	 * @param array $argument unused argument
52
-	 */
53
-	public function run($argument) {
54
-		$connection = \OC::$server->getDatabaseConnection();
55
-		$logger = \OC::$server->getLogger();
48
+    /**
49
+     * Makes the background job do its work
50
+     *
51
+     * @param array $argument unused argument
52
+     */
53
+    public function run($argument) {
54
+        $connection = \OC::$server->getDatabaseConnection();
55
+        $logger = \OC::$server->getLogger();
56 56
 
57
-		$sql =
58
-			'DELETE FROM `*PREFIX*share` ' .
59
-			'WHERE `item_type` in (\'file\', \'folder\') ' .
60
-			'AND NOT EXISTS (SELECT `fileid` FROM `*PREFIX*filecache` WHERE `file_source` = `fileid`)';
57
+        $sql =
58
+            'DELETE FROM `*PREFIX*share` ' .
59
+            'WHERE `item_type` in (\'file\', \'folder\') ' .
60
+            'AND NOT EXISTS (SELECT `fileid` FROM `*PREFIX*filecache` WHERE `file_source` = `fileid`)';
61 61
 
62
-		$deletedEntries = $connection->executeUpdate($sql);
63
-		$logger->debug("$deletedEntries orphaned share(s) deleted", ['app' => 'DeleteOrphanedSharesJob']);
64
-	}
62
+        $deletedEntries = $connection->executeUpdate($sql);
63
+        $logger->debug("$deletedEntries orphaned share(s) deleted", ['app' => 'DeleteOrphanedSharesJob']);
64
+    }
65 65
 
66 66
 }
Please login to merge, or discard this patch.
apps/files_sharing/lib/Middleware/OCSShareAPIMiddleware.php 1 patch
Indentation   +35 added lines, -35 removed lines patch added patch discarded remove patch
@@ -10,43 +10,43 @@
 block discarded – undo
10 10
 use OCP\Share\IManager;
11 11
 
12 12
 class OCSShareAPIMiddleware extends Middleware {
13
-	/** @var IManager */
14
-	private $shareManager;
15
-	/** @var IL10N */
16
-	private $l;
13
+    /** @var IManager */
14
+    private $shareManager;
15
+    /** @var IL10N */
16
+    private $l;
17 17
 
18
-	public function __construct(IManager $shareManager,
19
-								IL10N $l) {
20
-		$this->shareManager = $shareManager;
21
-		$this->l = $l;
22
-	}
18
+    public function __construct(IManager $shareManager,
19
+                                IL10N $l) {
20
+        $this->shareManager = $shareManager;
21
+        $this->l = $l;
22
+    }
23 23
 
24
-	/**
25
-	 * @param \OCP\AppFramework\Controller $controller
26
-	 * @param string $methodName
27
-	 *
28
-	 * @throws OCSNotFoundException
29
-	 */
30
-	public function beforeController($controller, $methodName) {
31
-		if ($controller instanceof ShareAPIController) {
32
-			if (!$this->shareManager->shareApiEnabled()) {
33
-				throw new OCSNotFoundException($this->l->t('Share API is disabled'));
34
-			}
35
-		}
36
-	}
24
+    /**
25
+     * @param \OCP\AppFramework\Controller $controller
26
+     * @param string $methodName
27
+     *
28
+     * @throws OCSNotFoundException
29
+     */
30
+    public function beforeController($controller, $methodName) {
31
+        if ($controller instanceof ShareAPIController) {
32
+            if (!$this->shareManager->shareApiEnabled()) {
33
+                throw new OCSNotFoundException($this->l->t('Share API is disabled'));
34
+            }
35
+        }
36
+    }
37 37
 
38
-	/**
39
-	 * @param \OCP\AppFramework\Controller $controller
40
-	 * @param string $methodName
41
-	 * @param Response $response
42
-	 * @return Response
43
-	 */
44
-	public function afterController($controller, $methodName, Response $response) {
45
-		if ($controller instanceof ShareAPIController) {
46
-			/** @var ShareAPIController $controller */
47
-			$controller->cleanup();
48
-		}
38
+    /**
39
+     * @param \OCP\AppFramework\Controller $controller
40
+     * @param string $methodName
41
+     * @param Response $response
42
+     * @return Response
43
+     */
44
+    public function afterController($controller, $methodName, Response $response) {
45
+        if ($controller instanceof ShareAPIController) {
46
+            /** @var ShareAPIController $controller */
47
+            $controller->cleanup();
48
+        }
49 49
 
50
-		return $response;
51
-	}
50
+        return $response;
51
+    }
52 52
 }
Please login to merge, or discard this patch.
apps/files_sharing/lib/Middleware/SharingCheckMiddleware.php 1 patch
Indentation   +126 added lines, -126 removed lines patch added patch discarded remove patch
@@ -45,20 +45,20 @@  discard block
 block discarded – undo
45 45
  */
46 46
 class SharingCheckMiddleware extends Middleware {
47 47
 
48
-	/** @var string */
49
-	protected $appName;
50
-	/** @var IConfig */
51
-	protected $config;
52
-	/** @var IAppManager */
53
-	protected $appManager;
54
-	/** @var IControllerMethodReflector */
55
-	protected $reflector;
56
-	/** @var IManager */
57
-	protected $shareManager;
58
-	/** @var IRequest */
59
-	protected $request;
60
-
61
-	/***
48
+    /** @var string */
49
+    protected $appName;
50
+    /** @var IConfig */
51
+    protected $config;
52
+    /** @var IAppManager */
53
+    protected $appManager;
54
+    /** @var IControllerMethodReflector */
55
+    protected $reflector;
56
+    /** @var IManager */
57
+    protected $shareManager;
58
+    /** @var IRequest */
59
+    protected $request;
60
+
61
+    /***
62 62
 	 * @param string $appName
63 63
 	 * @param IConfig $config
64 64
 	 * @param IAppManager $appManager
@@ -66,117 +66,117 @@  discard block
 block discarded – undo
66 66
 	 * @param IManager $shareManager
67 67
 	 * @param IRequest $request
68 68
 	 */
69
-	public function __construct($appName,
70
-								IConfig $config,
71
-								IAppManager $appManager,
72
-								IControllerMethodReflector $reflector,
73
-								IManager $shareManager,
74
-								IRequest $request
75
-								) {
76
-		$this->appName = $appName;
77
-		$this->config = $config;
78
-		$this->appManager = $appManager;
79
-		$this->reflector = $reflector;
80
-		$this->shareManager = $shareManager;
81
-		$this->request = $request;
82
-	}
83
-
84
-	/**
85
-	 * Check if sharing is enabled before the controllers is executed
86
-	 *
87
-	 * @param \OCP\AppFramework\Controller $controller
88
-	 * @param string $methodName
89
-	 * @throws NotFoundException
90
-	 * @throws S2SException
91
-	 */
92
-	public function beforeController($controller, $methodName) {
93
-		if(!$this->isSharingEnabled()) {
94
-			throw new NotFoundException('Sharing is disabled.');
95
-		}
96
-
97
-		if ($controller instanceof ExternalSharesController &&
98
-			!$this->externalSharesChecks()) {
99
-			throw new S2SException('Federated sharing not allowed');
100
-		} else if ($controller instanceof ShareController) {
101
-			$token = $this->request->getParam('token');
102
-			$share = $this->shareManager->getShareByToken($token);
103
-			if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK
104
-				&& !$this->isLinkSharingEnabled()) {
105
-				throw new NotFoundException('Link sharing is disabled');
106
-			}
107
-		}
108
-	}
109
-
110
-	/**
111
-	 * Return 404 page in case of a not found exception
112
-	 *
113
-	 * @param \OCP\AppFramework\Controller $controller
114
-	 * @param string $methodName
115
-	 * @param \Exception $exception
116
-	 * @return NotFoundResponse
117
-	 * @throws \Exception
118
-	 */
119
-	public function afterException($controller, $methodName, \Exception $exception) {
120
-		if(is_a($exception, '\OCP\Files\NotFoundException')) {
121
-			return new NotFoundResponse();
122
-		}
123
-
124
-		if (is_a($exception, '\OCA\Files_Sharing\Exceptions\S2SException')) {
125
-			return new JSONResponse($exception->getMessage(), 405);
126
-		}
127
-
128
-		throw $exception;
129
-	}
130
-
131
-	/**
132
-	 * Checks for externalshares controller
133
-	 * @return bool
134
-	 */
135
-	private function externalSharesChecks() {
136
-
137
-		if (!$this->reflector->hasAnnotation('NoIncomingFederatedSharingRequired') &&
138
-			$this->config->getAppValue('files_sharing', 'incoming_server2server_share_enabled', 'yes') !== 'yes') {
139
-			return false;
140
-		}
141
-
142
-		if (!$this->reflector->hasAnnotation('NoOutgoingFederatedSharingRequired') &&
143
-		    $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes') !== 'yes') {
144
-			return false;
145
-		}
146
-
147
-		return true;
148
-	}
149
-
150
-	/**
151
-	 * Check whether sharing is enabled
152
-	 * @return bool
153
-	 */
154
-	private function isSharingEnabled() {
155
-		// FIXME: This check is done here since the route is globally defined and not inside the files_sharing app
156
-		// Check whether the sharing application is enabled
157
-		if(!$this->appManager->isEnabledForUser($this->appName)) {
158
-			return false;
159
-		}
160
-
161
-		return true;
162
-	}
163
-
164
-	/**
165
-	 * Check if link sharing is allowed
166
-	 * @return bool
167
-	 */
168
-	private function isLinkSharingEnabled() {
169
-		// Check if the shareAPI is enabled
170
-		if ($this->config->getAppValue('core', 'shareapi_enabled', 'yes') !== 'yes') {
171
-			return false;
172
-		}
173
-
174
-		// Check whether public sharing is enabled
175
-		if($this->config->getAppValue('core', 'shareapi_allow_links', 'yes') !== 'yes') {
176
-			return false;
177
-		}
178
-
179
-		return true;
180
-	}
69
+    public function __construct($appName,
70
+                                IConfig $config,
71
+                                IAppManager $appManager,
72
+                                IControllerMethodReflector $reflector,
73
+                                IManager $shareManager,
74
+                                IRequest $request
75
+                                ) {
76
+        $this->appName = $appName;
77
+        $this->config = $config;
78
+        $this->appManager = $appManager;
79
+        $this->reflector = $reflector;
80
+        $this->shareManager = $shareManager;
81
+        $this->request = $request;
82
+    }
83
+
84
+    /**
85
+     * Check if sharing is enabled before the controllers is executed
86
+     *
87
+     * @param \OCP\AppFramework\Controller $controller
88
+     * @param string $methodName
89
+     * @throws NotFoundException
90
+     * @throws S2SException
91
+     */
92
+    public function beforeController($controller, $methodName) {
93
+        if(!$this->isSharingEnabled()) {
94
+            throw new NotFoundException('Sharing is disabled.');
95
+        }
96
+
97
+        if ($controller instanceof ExternalSharesController &&
98
+            !$this->externalSharesChecks()) {
99
+            throw new S2SException('Federated sharing not allowed');
100
+        } else if ($controller instanceof ShareController) {
101
+            $token = $this->request->getParam('token');
102
+            $share = $this->shareManager->getShareByToken($token);
103
+            if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK
104
+                && !$this->isLinkSharingEnabled()) {
105
+                throw new NotFoundException('Link sharing is disabled');
106
+            }
107
+        }
108
+    }
109
+
110
+    /**
111
+     * Return 404 page in case of a not found exception
112
+     *
113
+     * @param \OCP\AppFramework\Controller $controller
114
+     * @param string $methodName
115
+     * @param \Exception $exception
116
+     * @return NotFoundResponse
117
+     * @throws \Exception
118
+     */
119
+    public function afterException($controller, $methodName, \Exception $exception) {
120
+        if(is_a($exception, '\OCP\Files\NotFoundException')) {
121
+            return new NotFoundResponse();
122
+        }
123
+
124
+        if (is_a($exception, '\OCA\Files_Sharing\Exceptions\S2SException')) {
125
+            return new JSONResponse($exception->getMessage(), 405);
126
+        }
127
+
128
+        throw $exception;
129
+    }
130
+
131
+    /**
132
+     * Checks for externalshares controller
133
+     * @return bool
134
+     */
135
+    private function externalSharesChecks() {
136
+
137
+        if (!$this->reflector->hasAnnotation('NoIncomingFederatedSharingRequired') &&
138
+            $this->config->getAppValue('files_sharing', 'incoming_server2server_share_enabled', 'yes') !== 'yes') {
139
+            return false;
140
+        }
141
+
142
+        if (!$this->reflector->hasAnnotation('NoOutgoingFederatedSharingRequired') &&
143
+            $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes') !== 'yes') {
144
+            return false;
145
+        }
146
+
147
+        return true;
148
+    }
149
+
150
+    /**
151
+     * Check whether sharing is enabled
152
+     * @return bool
153
+     */
154
+    private function isSharingEnabled() {
155
+        // FIXME: This check is done here since the route is globally defined and not inside the files_sharing app
156
+        // Check whether the sharing application is enabled
157
+        if(!$this->appManager->isEnabledForUser($this->appName)) {
158
+            return false;
159
+        }
160
+
161
+        return true;
162
+    }
163
+
164
+    /**
165
+     * Check if link sharing is allowed
166
+     * @return bool
167
+     */
168
+    private function isLinkSharingEnabled() {
169
+        // Check if the shareAPI is enabled
170
+        if ($this->config->getAppValue('core', 'shareapi_enabled', 'yes') !== 'yes') {
171
+            return false;
172
+        }
173
+
174
+        // Check whether public sharing is enabled
175
+        if($this->config->getAppValue('core', 'shareapi_allow_links', 'yes') !== 'yes') {
176
+            return false;
177
+        }
178
+
179
+        return true;
180
+    }
181 181
 
182 182
 }
Please login to merge, or discard this patch.
apps/files_sharing/lib/SharedStorage.php 1 patch
Indentation   +429 added lines, -429 removed lines patch added patch discarded remove patch
@@ -47,433 +47,433 @@
 block discarded – undo
47 47
  */
48 48
 class SharedStorage extends \OC\Files\Storage\Wrapper\Jail implements ISharedStorage {
49 49
 
50
-	/** @var \OCP\Share\IShare */
51
-	private $superShare;
52
-
53
-	/** @var \OCP\Share\IShare[] */
54
-	private $groupedShares;
55
-
56
-	/**
57
-	 * @var \OC\Files\View
58
-	 */
59
-	private $ownerView;
60
-
61
-	private $initialized = false;
62
-
63
-	/**
64
-	 * @var ICacheEntry
65
-	 */
66
-	private $sourceRootInfo;
67
-
68
-	/** @var string */
69
-	private $user;
70
-
71
-	/**
72
-	 * @var \OCP\ILogger
73
-	 */
74
-	private $logger;
75
-
76
-	/** @var  IStorage */
77
-	private $nonMaskedStorage;
78
-
79
-	private $options;
80
-
81
-	public function __construct($arguments) {
82
-		$this->ownerView = $arguments['ownerView'];
83
-		$this->logger = \OC::$server->getLogger();
84
-
85
-		$this->superShare = $arguments['superShare'];
86
-		$this->groupedShares = $arguments['groupedShares'];
87
-
88
-		$this->user = $arguments['user'];
89
-
90
-		parent::__construct([
91
-			'storage' => null,
92
-			'root' => null,
93
-		]);
94
-	}
95
-
96
-	/**
97
-	 * @return ICacheEntry
98
-	 */
99
-	private function getSourceRootInfo() {
100
-		if (is_null($this->sourceRootInfo)) {
101
-			if (is_null($this->superShare->getNodeCacheEntry())) {
102
-				$this->sourceRootInfo = $this->nonMaskedStorage->getCache()->get($this->rootPath);
103
-			} else {
104
-				$this->sourceRootInfo = $this->superShare->getNodeCacheEntry();
105
-			}
106
-		}
107
-		return $this->sourceRootInfo;
108
-	}
109
-
110
-	private function init() {
111
-		if ($this->initialized) {
112
-			return;
113
-		}
114
-		$this->initialized = true;
115
-		try {
116
-			Filesystem::initMountPoints($this->superShare->getShareOwner());
117
-			$sourcePath = $this->ownerView->getPath($this->superShare->getNodeId());
118
-			list($this->nonMaskedStorage, $this->rootPath) = $this->ownerView->resolvePath($sourcePath);
119
-			$this->storage = new PermissionsMask([
120
-				'storage' => $this->nonMaskedStorage,
121
-				'mask' => $this->superShare->getPermissions()
122
-			]);
123
-		} catch (NotFoundException $e) {
124
-			$this->storage = new FailedStorage(['exception' => $e]);
125
-			$this->rootPath = '';
126
-		} catch (\Exception $e) {
127
-			$this->storage = new FailedStorage(['exception' => $e]);
128
-			$this->rootPath = '';
129
-			$this->logger->logException($e);
130
-		}
131
-	}
132
-
133
-	/**
134
-	 * @inheritdoc
135
-	 */
136
-	public function instanceOfStorage($class) {
137
-		if ($class === '\OC\Files\Storage\Common') {
138
-			return true;
139
-		}
140
-		if (in_array($class, ['\OC\Files\Storage\Home', '\OC\Files\ObjectStore\HomeObjectStoreStorage'])) {
141
-			return false;
142
-		}
143
-		return parent::instanceOfStorage($class);
144
-	}
145
-
146
-	/**
147
-	 * @return string
148
-	 */
149
-	public function getShareId() {
150
-		return $this->superShare->getId();
151
-	}
152
-
153
-	private function isValid() {
154
-		return $this->getSourceRootInfo() && ($this->getSourceRootInfo()->getPermissions() & Constants::PERMISSION_SHARE) === Constants::PERMISSION_SHARE;
155
-	}
156
-
157
-	/**
158
-	 * get id of the mount point
159
-	 *
160
-	 * @return string
161
-	 */
162
-	public function getId() {
163
-		return 'shared::' . $this->getMountPoint();
164
-	}
165
-
166
-	/**
167
-	 * Get the permissions granted for a shared file
168
-	 *
169
-	 * @param string $target Shared target file path
170
-	 * @return int CRUDS permissions granted
171
-	 */
172
-	public function getPermissions($target = '') {
173
-		if (!$this->isValid()) {
174
-			return 0;
175
-		}
176
-		$permissions = $this->superShare->getPermissions();
177
-		// part files and the mount point always have delete permissions
178
-		if ($target === '' || pathinfo($target, PATHINFO_EXTENSION) === 'part') {
179
-			$permissions |= \OCP\Constants::PERMISSION_DELETE;
180
-		}
181
-
182
-		if (\OCP\Util::isSharingDisabledForUser()) {
183
-			$permissions &= ~\OCP\Constants::PERMISSION_SHARE;
184
-		}
185
-
186
-		return $permissions;
187
-	}
188
-
189
-	public function isCreatable($path) {
190
-		return ($this->getPermissions($path) & \OCP\Constants::PERMISSION_CREATE);
191
-	}
192
-
193
-	public function isReadable($path) {
194
-		if (!$this->isValid()) {
195
-			return false;
196
-		}
197
-		if (!$this->file_exists($path)) {
198
-			return false;
199
-		}
200
-		/** @var IStorage $storage */
201
-		/** @var string $internalPath */
202
-		list($storage, $internalPath) = $this->resolvePath($path);
203
-		return $storage->isReadable($internalPath);
204
-	}
205
-
206
-	public function isUpdatable($path) {
207
-		return ($this->getPermissions($path) & \OCP\Constants::PERMISSION_UPDATE);
208
-	}
209
-
210
-	public function isDeletable($path) {
211
-		return ($this->getPermissions($path) & \OCP\Constants::PERMISSION_DELETE);
212
-	}
213
-
214
-	public function isSharable($path) {
215
-		if (\OCP\Util::isSharingDisabledForUser() || !\OC\Share\Share::isResharingAllowed()) {
216
-			return false;
217
-		}
218
-		return ($this->getPermissions($path) & \OCP\Constants::PERMISSION_SHARE);
219
-	}
220
-
221
-	public function fopen($path, $mode) {
222
-		if ($source = $this->getSourcePath($path)) {
223
-			switch ($mode) {
224
-				case 'r+':
225
-				case 'rb+':
226
-				case 'w+':
227
-				case 'wb+':
228
-				case 'x+':
229
-				case 'xb+':
230
-				case 'a+':
231
-				case 'ab+':
232
-				case 'w':
233
-				case 'wb':
234
-				case 'x':
235
-				case 'xb':
236
-				case 'a':
237
-				case 'ab':
238
-					$creatable = $this->isCreatable($path);
239
-					$updatable = $this->isUpdatable($path);
240
-					// if neither permissions given, no need to continue
241
-					if (!$creatable && !$updatable) {
242
-						return false;
243
-					}
244
-
245
-					$exists = $this->file_exists($path);
246
-					// if a file exists, updatable permissions are required
247
-					if ($exists && !$updatable) {
248
-						return false;
249
-					}
250
-
251
-					// part file is allowed if !$creatable but the final file is $updatable
252
-					if (pathinfo($path, PATHINFO_EXTENSION) !== 'part') {
253
-						if (!$exists && !$creatable) {
254
-							return false;
255
-						}
256
-					}
257
-			}
258
-			$info = array(
259
-				'target' => $this->getMountPoint() . $path,
260
-				'source' => $source,
261
-				'mode' => $mode,
262
-			);
263
-			\OCP\Util::emitHook('\OC\Files\Storage\Shared', 'fopen', $info);
264
-			return $this->nonMaskedStorage->fopen($this->getSourcePath($path), $mode);
265
-		}
266
-		return false;
267
-	}
268
-
269
-	/**
270
-	 * see http://php.net/manual/en/function.rename.php
271
-	 *
272
-	 * @param string $path1
273
-	 * @param string $path2
274
-	 * @return bool
275
-	 */
276
-	public function rename($path1, $path2) {
277
-		$this->init();
278
-		$isPartFile = pathinfo($path1, PATHINFO_EXTENSION) === 'part';
279
-		$targetExists = $this->file_exists($path2);
280
-		$sameFodler = dirname($path1) === dirname($path2);
281
-
282
-		if ($targetExists || ($sameFodler && !$isPartFile)) {
283
-			if (!$this->isUpdatable('')) {
284
-				return false;
285
-			}
286
-		} else {
287
-			if (!$this->isCreatable('')) {
288
-				return false;
289
-			}
290
-		}
291
-
292
-		return $this->nonMaskedStorage->rename($this->getSourcePath($path1), $this->getSourcePath($path2));
293
-	}
294
-
295
-	/**
296
-	 * return mount point of share, relative to data/user/files
297
-	 *
298
-	 * @return string
299
-	 */
300
-	public function getMountPoint() {
301
-		return $this->superShare->getTarget();
302
-	}
303
-
304
-	/**
305
-	 * @param string $path
306
-	 */
307
-	public function setMountPoint($path) {
308
-		$this->superShare->setTarget($path);
309
-
310
-		foreach ($this->groupedShares as $share) {
311
-			$share->setTarget($path);
312
-		}
313
-	}
314
-
315
-	/**
316
-	 * get the user who shared the file
317
-	 *
318
-	 * @return string
319
-	 */
320
-	public function getSharedFrom() {
321
-		return $this->superShare->getShareOwner();
322
-	}
323
-
324
-	/**
325
-	 * @return \OCP\Share\IShare
326
-	 */
327
-	public function getShare() {
328
-		return $this->superShare;
329
-	}
330
-
331
-	/**
332
-	 * return share type, can be "file" or "folder"
333
-	 *
334
-	 * @return string
335
-	 */
336
-	public function getItemType() {
337
-		return $this->superShare->getNodeType();
338
-	}
339
-
340
-	public function getCache($path = '', $storage = null) {
341
-		if ($this->cache) {
342
-			return $this->cache;
343
-		}
344
-		if (!$storage) {
345
-			$storage = $this;
346
-		}
347
-		$this->cache = new \OCA\Files_Sharing\Cache($storage, $this->getSourceRootInfo(), $this->superShare);
348
-		return $this->cache;
349
-	}
350
-
351
-	public function getScanner($path = '', $storage = null) {
352
-		if (!$storage) {
353
-			$storage = $this;
354
-		}
355
-		return new \OCA\Files_Sharing\Scanner($storage);
356
-	}
357
-
358
-	public function getPropagator($storage = null) {
359
-		if (isset($this->propagator)) {
360
-			return $this->propagator;
361
-		}
362
-
363
-		if (!$storage) {
364
-			$storage = $this;
365
-		}
366
-		$this->propagator = new \OCA\Files_Sharing\SharedPropagator($storage, \OC::$server->getDatabaseConnection());
367
-		return $this->propagator;
368
-	}
369
-
370
-	public function getOwner($path) {
371
-		return $this->superShare->getShareOwner();
372
-	}
373
-
374
-	/**
375
-	 * unshare complete storage, also the grouped shares
376
-	 *
377
-	 * @return bool
378
-	 */
379
-	public function unshareStorage() {
380
-		foreach ($this->groupedShares as $share) {
381
-			\OC::$server->getShareManager()->deleteFromSelf($share, $this->user);
382
-		}
383
-		return true;
384
-	}
385
-
386
-	/**
387
-	 * @param string $path
388
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
389
-	 * @param \OCP\Lock\ILockingProvider $provider
390
-	 * @throws \OCP\Lock\LockedException
391
-	 */
392
-	public function acquireLock($path, $type, ILockingProvider $provider) {
393
-		/** @var \OCP\Files\Storage $targetStorage */
394
-		list($targetStorage, $targetInternalPath) = $this->resolvePath($path);
395
-		$targetStorage->acquireLock($targetInternalPath, $type, $provider);
396
-		// lock the parent folders of the owner when locking the share as recipient
397
-		if ($path === '') {
398
-			$sourcePath = $this->ownerView->getPath($this->superShare->getNodeId());
399
-			$this->ownerView->lockFile(dirname($sourcePath), ILockingProvider::LOCK_SHARED, true);
400
-		}
401
-	}
402
-
403
-	/**
404
-	 * @param string $path
405
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
406
-	 * @param \OCP\Lock\ILockingProvider $provider
407
-	 */
408
-	public function releaseLock($path, $type, ILockingProvider $provider) {
409
-		/** @var \OCP\Files\Storage $targetStorage */
410
-		list($targetStorage, $targetInternalPath) = $this->resolvePath($path);
411
-		$targetStorage->releaseLock($targetInternalPath, $type, $provider);
412
-		// unlock the parent folders of the owner when unlocking the share as recipient
413
-		if ($path === '') {
414
-			$sourcePath = $this->ownerView->getPath($this->superShare->getNodeId());
415
-			$this->ownerView->unlockFile(dirname($sourcePath), ILockingProvider::LOCK_SHARED, true);
416
-		}
417
-	}
418
-
419
-	/**
420
-	 * @param string $path
421
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
422
-	 * @param \OCP\Lock\ILockingProvider $provider
423
-	 */
424
-	public function changeLock($path, $type, ILockingProvider $provider) {
425
-		/** @var \OCP\Files\Storage $targetStorage */
426
-		list($targetStorage, $targetInternalPath) = $this->resolvePath($path);
427
-		$targetStorage->changeLock($targetInternalPath, $type, $provider);
428
-	}
429
-
430
-	/**
431
-	 * @return array [ available, last_checked ]
432
-	 */
433
-	public function getAvailability() {
434
-		// shares do not participate in availability logic
435
-		return [
436
-			'available' => true,
437
-			'last_checked' => 0
438
-		];
439
-	}
440
-
441
-	/**
442
-	 * @param bool $available
443
-	 */
444
-	public function setAvailability($available) {
445
-		// shares do not participate in availability logic
446
-	}
447
-
448
-	public function getSourceStorage() {
449
-		$this->init();
450
-		return $this->nonMaskedStorage;
451
-	}
452
-
453
-	public function getWrapperStorage() {
454
-		$this->init();
455
-		return $this->storage;
456
-	}
457
-
458
-	public function file_get_contents($path) {
459
-		$info = [
460
-			'target' => $this->getMountPoint() . '/' . $path,
461
-			'source' => $this->getSourcePath($path),
462
-		];
463
-		\OCP\Util::emitHook('\OC\Files\Storage\Shared', 'file_get_contents', $info);
464
-		return parent::file_get_contents($path);
465
-	}
466
-
467
-	public function file_put_contents($path, $data) {
468
-		$info = [
469
-			'target' => $this->getMountPoint() . '/' . $path,
470
-			'source' => $this->getSourcePath($path),
471
-		];
472
-		\OCP\Util::emitHook('\OC\Files\Storage\Shared', 'file_put_contents', $info);
473
-		return parent::file_put_contents($path, $data);
474
-	}
475
-
476
-	public function setMountOptions(array $options) {
477
-		$this->mountOptions = $options;
478
-	}
50
+    /** @var \OCP\Share\IShare */
51
+    private $superShare;
52
+
53
+    /** @var \OCP\Share\IShare[] */
54
+    private $groupedShares;
55
+
56
+    /**
57
+     * @var \OC\Files\View
58
+     */
59
+    private $ownerView;
60
+
61
+    private $initialized = false;
62
+
63
+    /**
64
+     * @var ICacheEntry
65
+     */
66
+    private $sourceRootInfo;
67
+
68
+    /** @var string */
69
+    private $user;
70
+
71
+    /**
72
+     * @var \OCP\ILogger
73
+     */
74
+    private $logger;
75
+
76
+    /** @var  IStorage */
77
+    private $nonMaskedStorage;
78
+
79
+    private $options;
80
+
81
+    public function __construct($arguments) {
82
+        $this->ownerView = $arguments['ownerView'];
83
+        $this->logger = \OC::$server->getLogger();
84
+
85
+        $this->superShare = $arguments['superShare'];
86
+        $this->groupedShares = $arguments['groupedShares'];
87
+
88
+        $this->user = $arguments['user'];
89
+
90
+        parent::__construct([
91
+            'storage' => null,
92
+            'root' => null,
93
+        ]);
94
+    }
95
+
96
+    /**
97
+     * @return ICacheEntry
98
+     */
99
+    private function getSourceRootInfo() {
100
+        if (is_null($this->sourceRootInfo)) {
101
+            if (is_null($this->superShare->getNodeCacheEntry())) {
102
+                $this->sourceRootInfo = $this->nonMaskedStorage->getCache()->get($this->rootPath);
103
+            } else {
104
+                $this->sourceRootInfo = $this->superShare->getNodeCacheEntry();
105
+            }
106
+        }
107
+        return $this->sourceRootInfo;
108
+    }
109
+
110
+    private function init() {
111
+        if ($this->initialized) {
112
+            return;
113
+        }
114
+        $this->initialized = true;
115
+        try {
116
+            Filesystem::initMountPoints($this->superShare->getShareOwner());
117
+            $sourcePath = $this->ownerView->getPath($this->superShare->getNodeId());
118
+            list($this->nonMaskedStorage, $this->rootPath) = $this->ownerView->resolvePath($sourcePath);
119
+            $this->storage = new PermissionsMask([
120
+                'storage' => $this->nonMaskedStorage,
121
+                'mask' => $this->superShare->getPermissions()
122
+            ]);
123
+        } catch (NotFoundException $e) {
124
+            $this->storage = new FailedStorage(['exception' => $e]);
125
+            $this->rootPath = '';
126
+        } catch (\Exception $e) {
127
+            $this->storage = new FailedStorage(['exception' => $e]);
128
+            $this->rootPath = '';
129
+            $this->logger->logException($e);
130
+        }
131
+    }
132
+
133
+    /**
134
+     * @inheritdoc
135
+     */
136
+    public function instanceOfStorage($class) {
137
+        if ($class === '\OC\Files\Storage\Common') {
138
+            return true;
139
+        }
140
+        if (in_array($class, ['\OC\Files\Storage\Home', '\OC\Files\ObjectStore\HomeObjectStoreStorage'])) {
141
+            return false;
142
+        }
143
+        return parent::instanceOfStorage($class);
144
+    }
145
+
146
+    /**
147
+     * @return string
148
+     */
149
+    public function getShareId() {
150
+        return $this->superShare->getId();
151
+    }
152
+
153
+    private function isValid() {
154
+        return $this->getSourceRootInfo() && ($this->getSourceRootInfo()->getPermissions() & Constants::PERMISSION_SHARE) === Constants::PERMISSION_SHARE;
155
+    }
156
+
157
+    /**
158
+     * get id of the mount point
159
+     *
160
+     * @return string
161
+     */
162
+    public function getId() {
163
+        return 'shared::' . $this->getMountPoint();
164
+    }
165
+
166
+    /**
167
+     * Get the permissions granted for a shared file
168
+     *
169
+     * @param string $target Shared target file path
170
+     * @return int CRUDS permissions granted
171
+     */
172
+    public function getPermissions($target = '') {
173
+        if (!$this->isValid()) {
174
+            return 0;
175
+        }
176
+        $permissions = $this->superShare->getPermissions();
177
+        // part files and the mount point always have delete permissions
178
+        if ($target === '' || pathinfo($target, PATHINFO_EXTENSION) === 'part') {
179
+            $permissions |= \OCP\Constants::PERMISSION_DELETE;
180
+        }
181
+
182
+        if (\OCP\Util::isSharingDisabledForUser()) {
183
+            $permissions &= ~\OCP\Constants::PERMISSION_SHARE;
184
+        }
185
+
186
+        return $permissions;
187
+    }
188
+
189
+    public function isCreatable($path) {
190
+        return ($this->getPermissions($path) & \OCP\Constants::PERMISSION_CREATE);
191
+    }
192
+
193
+    public function isReadable($path) {
194
+        if (!$this->isValid()) {
195
+            return false;
196
+        }
197
+        if (!$this->file_exists($path)) {
198
+            return false;
199
+        }
200
+        /** @var IStorage $storage */
201
+        /** @var string $internalPath */
202
+        list($storage, $internalPath) = $this->resolvePath($path);
203
+        return $storage->isReadable($internalPath);
204
+    }
205
+
206
+    public function isUpdatable($path) {
207
+        return ($this->getPermissions($path) & \OCP\Constants::PERMISSION_UPDATE);
208
+    }
209
+
210
+    public function isDeletable($path) {
211
+        return ($this->getPermissions($path) & \OCP\Constants::PERMISSION_DELETE);
212
+    }
213
+
214
+    public function isSharable($path) {
215
+        if (\OCP\Util::isSharingDisabledForUser() || !\OC\Share\Share::isResharingAllowed()) {
216
+            return false;
217
+        }
218
+        return ($this->getPermissions($path) & \OCP\Constants::PERMISSION_SHARE);
219
+    }
220
+
221
+    public function fopen($path, $mode) {
222
+        if ($source = $this->getSourcePath($path)) {
223
+            switch ($mode) {
224
+                case 'r+':
225
+                case 'rb+':
226
+                case 'w+':
227
+                case 'wb+':
228
+                case 'x+':
229
+                case 'xb+':
230
+                case 'a+':
231
+                case 'ab+':
232
+                case 'w':
233
+                case 'wb':
234
+                case 'x':
235
+                case 'xb':
236
+                case 'a':
237
+                case 'ab':
238
+                    $creatable = $this->isCreatable($path);
239
+                    $updatable = $this->isUpdatable($path);
240
+                    // if neither permissions given, no need to continue
241
+                    if (!$creatable && !$updatable) {
242
+                        return false;
243
+                    }
244
+
245
+                    $exists = $this->file_exists($path);
246
+                    // if a file exists, updatable permissions are required
247
+                    if ($exists && !$updatable) {
248
+                        return false;
249
+                    }
250
+
251
+                    // part file is allowed if !$creatable but the final file is $updatable
252
+                    if (pathinfo($path, PATHINFO_EXTENSION) !== 'part') {
253
+                        if (!$exists && !$creatable) {
254
+                            return false;
255
+                        }
256
+                    }
257
+            }
258
+            $info = array(
259
+                'target' => $this->getMountPoint() . $path,
260
+                'source' => $source,
261
+                'mode' => $mode,
262
+            );
263
+            \OCP\Util::emitHook('\OC\Files\Storage\Shared', 'fopen', $info);
264
+            return $this->nonMaskedStorage->fopen($this->getSourcePath($path), $mode);
265
+        }
266
+        return false;
267
+    }
268
+
269
+    /**
270
+     * see http://php.net/manual/en/function.rename.php
271
+     *
272
+     * @param string $path1
273
+     * @param string $path2
274
+     * @return bool
275
+     */
276
+    public function rename($path1, $path2) {
277
+        $this->init();
278
+        $isPartFile = pathinfo($path1, PATHINFO_EXTENSION) === 'part';
279
+        $targetExists = $this->file_exists($path2);
280
+        $sameFodler = dirname($path1) === dirname($path2);
281
+
282
+        if ($targetExists || ($sameFodler && !$isPartFile)) {
283
+            if (!$this->isUpdatable('')) {
284
+                return false;
285
+            }
286
+        } else {
287
+            if (!$this->isCreatable('')) {
288
+                return false;
289
+            }
290
+        }
291
+
292
+        return $this->nonMaskedStorage->rename($this->getSourcePath($path1), $this->getSourcePath($path2));
293
+    }
294
+
295
+    /**
296
+     * return mount point of share, relative to data/user/files
297
+     *
298
+     * @return string
299
+     */
300
+    public function getMountPoint() {
301
+        return $this->superShare->getTarget();
302
+    }
303
+
304
+    /**
305
+     * @param string $path
306
+     */
307
+    public function setMountPoint($path) {
308
+        $this->superShare->setTarget($path);
309
+
310
+        foreach ($this->groupedShares as $share) {
311
+            $share->setTarget($path);
312
+        }
313
+    }
314
+
315
+    /**
316
+     * get the user who shared the file
317
+     *
318
+     * @return string
319
+     */
320
+    public function getSharedFrom() {
321
+        return $this->superShare->getShareOwner();
322
+    }
323
+
324
+    /**
325
+     * @return \OCP\Share\IShare
326
+     */
327
+    public function getShare() {
328
+        return $this->superShare;
329
+    }
330
+
331
+    /**
332
+     * return share type, can be "file" or "folder"
333
+     *
334
+     * @return string
335
+     */
336
+    public function getItemType() {
337
+        return $this->superShare->getNodeType();
338
+    }
339
+
340
+    public function getCache($path = '', $storage = null) {
341
+        if ($this->cache) {
342
+            return $this->cache;
343
+        }
344
+        if (!$storage) {
345
+            $storage = $this;
346
+        }
347
+        $this->cache = new \OCA\Files_Sharing\Cache($storage, $this->getSourceRootInfo(), $this->superShare);
348
+        return $this->cache;
349
+    }
350
+
351
+    public function getScanner($path = '', $storage = null) {
352
+        if (!$storage) {
353
+            $storage = $this;
354
+        }
355
+        return new \OCA\Files_Sharing\Scanner($storage);
356
+    }
357
+
358
+    public function getPropagator($storage = null) {
359
+        if (isset($this->propagator)) {
360
+            return $this->propagator;
361
+        }
362
+
363
+        if (!$storage) {
364
+            $storage = $this;
365
+        }
366
+        $this->propagator = new \OCA\Files_Sharing\SharedPropagator($storage, \OC::$server->getDatabaseConnection());
367
+        return $this->propagator;
368
+    }
369
+
370
+    public function getOwner($path) {
371
+        return $this->superShare->getShareOwner();
372
+    }
373
+
374
+    /**
375
+     * unshare complete storage, also the grouped shares
376
+     *
377
+     * @return bool
378
+     */
379
+    public function unshareStorage() {
380
+        foreach ($this->groupedShares as $share) {
381
+            \OC::$server->getShareManager()->deleteFromSelf($share, $this->user);
382
+        }
383
+        return true;
384
+    }
385
+
386
+    /**
387
+     * @param string $path
388
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
389
+     * @param \OCP\Lock\ILockingProvider $provider
390
+     * @throws \OCP\Lock\LockedException
391
+     */
392
+    public function acquireLock($path, $type, ILockingProvider $provider) {
393
+        /** @var \OCP\Files\Storage $targetStorage */
394
+        list($targetStorage, $targetInternalPath) = $this->resolvePath($path);
395
+        $targetStorage->acquireLock($targetInternalPath, $type, $provider);
396
+        // lock the parent folders of the owner when locking the share as recipient
397
+        if ($path === '') {
398
+            $sourcePath = $this->ownerView->getPath($this->superShare->getNodeId());
399
+            $this->ownerView->lockFile(dirname($sourcePath), ILockingProvider::LOCK_SHARED, true);
400
+        }
401
+    }
402
+
403
+    /**
404
+     * @param string $path
405
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
406
+     * @param \OCP\Lock\ILockingProvider $provider
407
+     */
408
+    public function releaseLock($path, $type, ILockingProvider $provider) {
409
+        /** @var \OCP\Files\Storage $targetStorage */
410
+        list($targetStorage, $targetInternalPath) = $this->resolvePath($path);
411
+        $targetStorage->releaseLock($targetInternalPath, $type, $provider);
412
+        // unlock the parent folders of the owner when unlocking the share as recipient
413
+        if ($path === '') {
414
+            $sourcePath = $this->ownerView->getPath($this->superShare->getNodeId());
415
+            $this->ownerView->unlockFile(dirname($sourcePath), ILockingProvider::LOCK_SHARED, true);
416
+        }
417
+    }
418
+
419
+    /**
420
+     * @param string $path
421
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
422
+     * @param \OCP\Lock\ILockingProvider $provider
423
+     */
424
+    public function changeLock($path, $type, ILockingProvider $provider) {
425
+        /** @var \OCP\Files\Storage $targetStorage */
426
+        list($targetStorage, $targetInternalPath) = $this->resolvePath($path);
427
+        $targetStorage->changeLock($targetInternalPath, $type, $provider);
428
+    }
429
+
430
+    /**
431
+     * @return array [ available, last_checked ]
432
+     */
433
+    public function getAvailability() {
434
+        // shares do not participate in availability logic
435
+        return [
436
+            'available' => true,
437
+            'last_checked' => 0
438
+        ];
439
+    }
440
+
441
+    /**
442
+     * @param bool $available
443
+     */
444
+    public function setAvailability($available) {
445
+        // shares do not participate in availability logic
446
+    }
447
+
448
+    public function getSourceStorage() {
449
+        $this->init();
450
+        return $this->nonMaskedStorage;
451
+    }
452
+
453
+    public function getWrapperStorage() {
454
+        $this->init();
455
+        return $this->storage;
456
+    }
457
+
458
+    public function file_get_contents($path) {
459
+        $info = [
460
+            'target' => $this->getMountPoint() . '/' . $path,
461
+            'source' => $this->getSourcePath($path),
462
+        ];
463
+        \OCP\Util::emitHook('\OC\Files\Storage\Shared', 'file_get_contents', $info);
464
+        return parent::file_get_contents($path);
465
+    }
466
+
467
+    public function file_put_contents($path, $data) {
468
+        $info = [
469
+            'target' => $this->getMountPoint() . '/' . $path,
470
+            'source' => $this->getSourcePath($path),
471
+        ];
472
+        \OCP\Util::emitHook('\OC\Files\Storage\Shared', 'file_put_contents', $info);
473
+        return parent::file_put_contents($path, $data);
474
+    }
475
+
476
+    public function setMountOptions(array $options) {
477
+        $this->mountOptions = $options;
478
+    }
479 479
 }
Please login to merge, or discard this patch.
apps/files_sharing/lib/MountProvider.php 1 patch
Indentation   +151 added lines, -151 removed lines patch added patch discarded remove patch
@@ -33,155 +33,155 @@
 block discarded – undo
33 33
 use OCP\Share\IManager;
34 34
 
35 35
 class MountProvider implements IMountProvider {
36
-	/**
37
-	 * @var \OCP\IConfig
38
-	 */
39
-	protected $config;
40
-
41
-	/**
42
-	 * @var IManager
43
-	 */
44
-	protected $shareManager;
45
-
46
-	/**
47
-	 * @var ILogger
48
-	 */
49
-	protected $logger;
50
-
51
-	/**
52
-	 * @param \OCP\IConfig $config
53
-	 * @param IManager $shareManager
54
-	 * @param ILogger $logger
55
-	 */
56
-	public function __construct(IConfig $config, IManager $shareManager, ILogger $logger) {
57
-		$this->config = $config;
58
-		$this->shareManager = $shareManager;
59
-		$this->logger = $logger;
60
-	}
61
-
62
-
63
-	/**
64
-	 * Get all mountpoints applicable for the user and check for shares where we need to update the etags
65
-	 *
66
-	 * @param \OCP\IUser $user
67
-	 * @param \OCP\Files\Storage\IStorageFactory $storageFactory
68
-	 * @return \OCP\Files\Mount\IMountPoint[]
69
-	 */
70
-	public function getMountsForUser(IUser $user, IStorageFactory $storageFactory) {
71
-		$shares = $this->shareManager->getSharedWith($user->getUID(), \OCP\Share::SHARE_TYPE_USER, null, -1);
72
-		$shares = array_merge($shares, $this->shareManager->getSharedWith($user->getUID(), \OCP\Share::SHARE_TYPE_GROUP, null, -1));
73
-		// filter out excluded shares and group shares that includes self
74
-		$shares = array_filter($shares, function (\OCP\Share\IShare $share) use ($user) {
75
-			return $share->getPermissions() > 0 && $share->getShareOwner() !== $user->getUID();
76
-		});
77
-
78
-		$superShares = $this->buildSuperShares($shares, $user);
79
-
80
-		$mounts = [];
81
-		foreach ($superShares as $share) {
82
-			try {
83
-				$mounts[] = new SharedMount(
84
-					'\OCA\Files_Sharing\SharedStorage',
85
-					$mounts,
86
-					[
87
-						'user' => $user->getUID(),
88
-						// parent share
89
-						'superShare' => $share[0],
90
-						// children/component of the superShare
91
-						'groupedShares' => $share[1],
92
-					],
93
-					$storageFactory
94
-				);
95
-			} catch (\Exception $e) {
96
-				$this->logger->logException($e);
97
-				$this->logger->error('Error while trying to create shared mount');
98
-			}
99
-		}
100
-
101
-		// array_filter removes the null values from the array
102
-		return array_filter($mounts);
103
-	}
104
-
105
-	/**
106
-	 * Groups shares by path (nodeId) and target path
107
-	 *
108
-	 * @param \OCP\Share\IShare[] $shares
109
-	 * @return \OCP\Share\IShare[][] array of grouped shares, each element in the
110
-	 * array is a group which itself is an array of shares
111
-	 */
112
-	private function groupShares(array $shares) {
113
-		$tmp = [];
114
-
115
-		foreach ($shares as $share) {
116
-			if (!isset($tmp[$share->getNodeId()])) {
117
-				$tmp[$share->getNodeId()] = [];
118
-			}
119
-			$tmp[$share->getNodeId()][] = $share;
120
-		}
121
-
122
-		$result = [];
123
-		// sort by stime, the super share will be based on the least recent share
124
-		foreach ($tmp as &$tmp2) {
125
-			@usort($tmp2, function($a, $b) {
126
-				if ($a->getShareTime() <= $b->getShareTime()) {
127
-					return -1;
128
-				}
129
-				return 1;
130
-			});
131
-			$result[] = $tmp2;
132
-		}
133
-
134
-		return array_values($result);
135
-	}
136
-
137
-	/**
138
-	 * Build super shares (virtual share) by grouping them by node id and target,
139
-	 * then for each group compute the super share and return it along with the matching
140
-	 * grouped shares. The most permissive permissions are used based on the permissions
141
-	 * of all shares within the group.
142
-	 *
143
-	 * @param \OCP\Share\IShare[] $allShares
144
-	 * @param \OCP\IUser $user user
145
-	 * @return array Tuple of [superShare, groupedShares]
146
-	 */
147
-	private function buildSuperShares(array $allShares, \OCP\IUser $user) {
148
-		$result = [];
149
-
150
-		$groupedShares = $this->groupShares($allShares);
151
-
152
-		/** @var \OCP\Share\IShare[] $shares */
153
-		foreach ($groupedShares as $shares) {
154
-			if (count($shares) === 0) {
155
-				continue;
156
-			}
157
-
158
-			$superShare = $this->shareManager->newShare();
159
-
160
-			// compute super share based on first entry of the group
161
-			$superShare->setId($shares[0]->getId())
162
-				->setShareOwner($shares[0]->getShareOwner())
163
-				->setNodeId($shares[0]->getNodeId())
164
-				->setTarget($shares[0]->getTarget());
165
-
166
-			// use most permissive permissions
167
-			$permissions = 0;
168
-			foreach ($shares as $share) {
169
-				$permissions |= $share->getPermissions();
170
-				if ($share->getTarget() !== $superShare->getTarget()) {
171
-					// adjust target, for database consistency
172
-					$share->setTarget($superShare->getTarget());
173
-					$this->shareManager->moveShare($share, $user->getUID());
174
-				}
175
-				if (!is_null($share->getNodeCacheEntry())) {
176
-					$superShare->setNodeCacheEntry($share->getNodeCacheEntry());
177
-				}
178
-			}
179
-
180
-			$superShare->setPermissions($permissions);
181
-
182
-			$result[] = [$superShare, $shares];
183
-		}
184
-
185
-		return $result;
186
-	}
36
+    /**
37
+     * @var \OCP\IConfig
38
+     */
39
+    protected $config;
40
+
41
+    /**
42
+     * @var IManager
43
+     */
44
+    protected $shareManager;
45
+
46
+    /**
47
+     * @var ILogger
48
+     */
49
+    protected $logger;
50
+
51
+    /**
52
+     * @param \OCP\IConfig $config
53
+     * @param IManager $shareManager
54
+     * @param ILogger $logger
55
+     */
56
+    public function __construct(IConfig $config, IManager $shareManager, ILogger $logger) {
57
+        $this->config = $config;
58
+        $this->shareManager = $shareManager;
59
+        $this->logger = $logger;
60
+    }
61
+
62
+
63
+    /**
64
+     * Get all mountpoints applicable for the user and check for shares where we need to update the etags
65
+     *
66
+     * @param \OCP\IUser $user
67
+     * @param \OCP\Files\Storage\IStorageFactory $storageFactory
68
+     * @return \OCP\Files\Mount\IMountPoint[]
69
+     */
70
+    public function getMountsForUser(IUser $user, IStorageFactory $storageFactory) {
71
+        $shares = $this->shareManager->getSharedWith($user->getUID(), \OCP\Share::SHARE_TYPE_USER, null, -1);
72
+        $shares = array_merge($shares, $this->shareManager->getSharedWith($user->getUID(), \OCP\Share::SHARE_TYPE_GROUP, null, -1));
73
+        // filter out excluded shares and group shares that includes self
74
+        $shares = array_filter($shares, function (\OCP\Share\IShare $share) use ($user) {
75
+            return $share->getPermissions() > 0 && $share->getShareOwner() !== $user->getUID();
76
+        });
77
+
78
+        $superShares = $this->buildSuperShares($shares, $user);
79
+
80
+        $mounts = [];
81
+        foreach ($superShares as $share) {
82
+            try {
83
+                $mounts[] = new SharedMount(
84
+                    '\OCA\Files_Sharing\SharedStorage',
85
+                    $mounts,
86
+                    [
87
+                        'user' => $user->getUID(),
88
+                        // parent share
89
+                        'superShare' => $share[0],
90
+                        // children/component of the superShare
91
+                        'groupedShares' => $share[1],
92
+                    ],
93
+                    $storageFactory
94
+                );
95
+            } catch (\Exception $e) {
96
+                $this->logger->logException($e);
97
+                $this->logger->error('Error while trying to create shared mount');
98
+            }
99
+        }
100
+
101
+        // array_filter removes the null values from the array
102
+        return array_filter($mounts);
103
+    }
104
+
105
+    /**
106
+     * Groups shares by path (nodeId) and target path
107
+     *
108
+     * @param \OCP\Share\IShare[] $shares
109
+     * @return \OCP\Share\IShare[][] array of grouped shares, each element in the
110
+     * array is a group which itself is an array of shares
111
+     */
112
+    private function groupShares(array $shares) {
113
+        $tmp = [];
114
+
115
+        foreach ($shares as $share) {
116
+            if (!isset($tmp[$share->getNodeId()])) {
117
+                $tmp[$share->getNodeId()] = [];
118
+            }
119
+            $tmp[$share->getNodeId()][] = $share;
120
+        }
121
+
122
+        $result = [];
123
+        // sort by stime, the super share will be based on the least recent share
124
+        foreach ($tmp as &$tmp2) {
125
+            @usort($tmp2, function($a, $b) {
126
+                if ($a->getShareTime() <= $b->getShareTime()) {
127
+                    return -1;
128
+                }
129
+                return 1;
130
+            });
131
+            $result[] = $tmp2;
132
+        }
133
+
134
+        return array_values($result);
135
+    }
136
+
137
+    /**
138
+     * Build super shares (virtual share) by grouping them by node id and target,
139
+     * then for each group compute the super share and return it along with the matching
140
+     * grouped shares. The most permissive permissions are used based on the permissions
141
+     * of all shares within the group.
142
+     *
143
+     * @param \OCP\Share\IShare[] $allShares
144
+     * @param \OCP\IUser $user user
145
+     * @return array Tuple of [superShare, groupedShares]
146
+     */
147
+    private function buildSuperShares(array $allShares, \OCP\IUser $user) {
148
+        $result = [];
149
+
150
+        $groupedShares = $this->groupShares($allShares);
151
+
152
+        /** @var \OCP\Share\IShare[] $shares */
153
+        foreach ($groupedShares as $shares) {
154
+            if (count($shares) === 0) {
155
+                continue;
156
+            }
157
+
158
+            $superShare = $this->shareManager->newShare();
159
+
160
+            // compute super share based on first entry of the group
161
+            $superShare->setId($shares[0]->getId())
162
+                ->setShareOwner($shares[0]->getShareOwner())
163
+                ->setNodeId($shares[0]->getNodeId())
164
+                ->setTarget($shares[0]->getTarget());
165
+
166
+            // use most permissive permissions
167
+            $permissions = 0;
168
+            foreach ($shares as $share) {
169
+                $permissions |= $share->getPermissions();
170
+                if ($share->getTarget() !== $superShare->getTarget()) {
171
+                    // adjust target, for database consistency
172
+                    $share->setTarget($superShare->getTarget());
173
+                    $this->shareManager->moveShare($share, $user->getUID());
174
+                }
175
+                if (!is_null($share->getNodeCacheEntry())) {
176
+                    $superShare->setNodeCacheEntry($share->getNodeCacheEntry());
177
+                }
178
+            }
179
+
180
+            $superShare->setPermissions($permissions);
181
+
182
+            $result[] = [$superShare, $shares];
183
+        }
184
+
185
+        return $result;
186
+    }
187 187
 }
Please login to merge, or discard this patch.