Passed
Push — master ( 23e8ae...e8872f )
by Robin
16:16 queued 12s
created
lib/private/Files/Config/CachedMountFileInfo.php 1 patch
Indentation   +24 added lines, -24 removed lines patch added patch discarded remove patch
@@ -27,31 +27,31 @@
 block discarded – undo
27 27
 use OCP\IUser;
28 28
 
29 29
 class CachedMountFileInfo extends CachedMountInfo implements ICachedMountFileInfo {
30
-	private string $internalPath;
30
+    private string $internalPath;
31 31
 
32
-	public function __construct(
33
-		IUser $user,
34
-		int $storageId,
35
-		int $rootId,
36
-		string $mountPoint,
37
-		?int $mountId,
38
-		string $mountProvider,
39
-		string $rootInternalPath,
40
-		string $internalPath
41
-	) {
42
-		parent::__construct($user, $storageId, $rootId, $mountPoint, $mountProvider, $mountId, $rootInternalPath);
43
-		$this->internalPath = $internalPath;
44
-	}
32
+    public function __construct(
33
+        IUser $user,
34
+        int $storageId,
35
+        int $rootId,
36
+        string $mountPoint,
37
+        ?int $mountId,
38
+        string $mountProvider,
39
+        string $rootInternalPath,
40
+        string $internalPath
41
+    ) {
42
+        parent::__construct($user, $storageId, $rootId, $mountPoint, $mountProvider, $mountId, $rootInternalPath);
43
+        $this->internalPath = $internalPath;
44
+    }
45 45
 
46
-	public function getInternalPath(): string {
47
-		if ($this->getRootInternalPath()) {
48
-			return substr($this->internalPath, strlen($this->getRootInternalPath()) + 1);
49
-		} else {
50
-			return $this->internalPath;
51
-		}
52
-	}
46
+    public function getInternalPath(): string {
47
+        if ($this->getRootInternalPath()) {
48
+            return substr($this->internalPath, strlen($this->getRootInternalPath()) + 1);
49
+        } else {
50
+            return $this->internalPath;
51
+        }
52
+    }
53 53
 
54
-	public function getPath(): string {
55
-		return $this->getMountPoint() . $this->getInternalPath();
56
-	}
54
+    public function getPath(): string {
55
+        return $this->getMountPoint() . $this->getInternalPath();
56
+    }
57 57
 }
Please login to merge, or discard this patch.
lib/private/Files/Config/MountProviderCollection.php 1 patch
Indentation   +181 added lines, -181 removed lines patch added patch discarded remove patch
@@ -37,185 +37,185 @@
 block discarded – undo
37 37
 use OCP\IUser;
38 38
 
39 39
 class MountProviderCollection implements IMountProviderCollection, Emitter {
40
-	use EmitterTrait;
41
-
42
-	/**
43
-	 * @var \OCP\Files\Config\IHomeMountProvider[]
44
-	 */
45
-	private $homeProviders = [];
46
-
47
-	/**
48
-	 * @var \OCP\Files\Config\IMountProvider[]
49
-	 */
50
-	private $providers = [];
51
-
52
-	/** @var \OCP\Files\Config\IRootMountProvider[] */
53
-	private $rootProviders = [];
54
-
55
-	/**
56
-	 * @var \OCP\Files\Storage\IStorageFactory
57
-	 */
58
-	private $loader;
59
-
60
-	/**
61
-	 * @var \OCP\Files\Config\IUserMountCache
62
-	 */
63
-	private $mountCache;
64
-
65
-	/** @var callable[] */
66
-	private $mountFilters = [];
67
-
68
-	/**
69
-	 * @param \OCP\Files\Storage\IStorageFactory $loader
70
-	 * @param IUserMountCache $mountCache
71
-	 */
72
-	public function __construct(IStorageFactory $loader, IUserMountCache $mountCache) {
73
-		$this->loader = $loader;
74
-		$this->mountCache = $mountCache;
75
-	}
76
-
77
-	/**
78
-	 * Get all configured mount points for the user
79
-	 *
80
-	 * @param \OCP\IUser $user
81
-	 * @return \OCP\Files\Mount\IMountPoint[]
82
-	 */
83
-	public function getMountsForUser(IUser $user) {
84
-		$loader = $this->loader;
85
-		$mounts = array_map(function (IMountProvider $provider) use ($user, $loader) {
86
-			return $provider->getMountsForUser($user, $loader);
87
-		}, $this->providers);
88
-		$mounts = array_filter($mounts, function ($result) {
89
-			return is_array($result);
90
-		});
91
-		$mounts = array_reduce($mounts, function (array $mounts, array $providerMounts) {
92
-			return array_merge($mounts, $providerMounts);
93
-		}, []);
94
-		return $this->filterMounts($user, $mounts);
95
-	}
96
-
97
-	public function addMountForUser(IUser $user, IMountManager $mountManager) {
98
-		// shared mount provider gets to go last since it needs to know existing files
99
-		// to check for name collisions
100
-		$firstMounts = [];
101
-		$firstProviders = array_filter($this->providers, function (IMountProvider $provider) {
102
-			return (get_class($provider) !== 'OCA\Files_Sharing\MountProvider');
103
-		});
104
-		$lastProviders = array_filter($this->providers, function (IMountProvider $provider) {
105
-			return (get_class($provider) === 'OCA\Files_Sharing\MountProvider');
106
-		});
107
-		foreach ($firstProviders as $provider) {
108
-			$mounts = $provider->getMountsForUser($user, $this->loader);
109
-			if (is_array($mounts)) {
110
-				$firstMounts = array_merge($firstMounts, $mounts);
111
-			}
112
-		}
113
-		$firstMounts = $this->filterMounts($user, $firstMounts);
114
-		array_walk($firstMounts, [$mountManager, 'addMount']);
115
-
116
-		$lateMounts = [];
117
-		foreach ($lastProviders as $provider) {
118
-			$mounts = $provider->getMountsForUser($user, $this->loader);
119
-			if (is_array($mounts)) {
120
-				$lateMounts = array_merge($lateMounts, $mounts);
121
-			}
122
-		}
123
-
124
-		$lateMounts = $this->filterMounts($user, $lateMounts);
125
-		array_walk($lateMounts, [$mountManager, 'addMount']);
126
-
127
-		return array_merge($lateMounts, $firstMounts);
128
-	}
129
-
130
-	/**
131
-	 * Get the configured home mount for this user
132
-	 *
133
-	 * @param \OCP\IUser $user
134
-	 * @return \OCP\Files\Mount\IMountPoint
135
-	 * @since 9.1.0
136
-	 */
137
-	public function getHomeMountForUser(IUser $user) {
138
-		/** @var \OCP\Files\Config\IHomeMountProvider[] $providers */
139
-		$providers = array_reverse($this->homeProviders); // call the latest registered provider first to give apps an opportunity to overwrite builtin
140
-		foreach ($providers as $homeProvider) {
141
-			if ($mount = $homeProvider->getHomeMountForUser($user, $this->loader)) {
142
-				$mount->setMountPoint('/' . $user->getUID()); //make sure the mountpoint is what we expect
143
-				return $mount;
144
-			}
145
-		}
146
-		throw new \Exception('No home storage configured for user ' . $user);
147
-	}
148
-
149
-	/**
150
-	 * Add a provider for mount points
151
-	 *
152
-	 * @param \OCP\Files\Config\IMountProvider $provider
153
-	 */
154
-	public function registerProvider(IMountProvider $provider) {
155
-		$this->providers[] = $provider;
156
-
157
-		$this->emit('\OC\Files\Config', 'registerMountProvider', [$provider]);
158
-	}
159
-
160
-	public function registerMountFilter(callable $filter) {
161
-		$this->mountFilters[] = $filter;
162
-	}
163
-
164
-	private function filterMounts(IUser $user, array $mountPoints) {
165
-		return array_filter($mountPoints, function (IMountPoint $mountPoint) use ($user) {
166
-			foreach ($this->mountFilters as $filter) {
167
-				if ($filter($mountPoint, $user) === false) {
168
-					return false;
169
-				}
170
-			}
171
-			return true;
172
-		});
173
-	}
174
-
175
-	/**
176
-	 * Add a provider for home mount points
177
-	 *
178
-	 * @param \OCP\Files\Config\IHomeMountProvider $provider
179
-	 * @since 9.1.0
180
-	 */
181
-	public function registerHomeProvider(IHomeMountProvider $provider) {
182
-		$this->homeProviders[] = $provider;
183
-		$this->emit('\OC\Files\Config', 'registerHomeMountProvider', [$provider]);
184
-	}
185
-
186
-	/**
187
-	 * Get the mount cache which can be used to search for mounts without setting up the filesystem
188
-	 *
189
-	 * @return IUserMountCache
190
-	 */
191
-	public function getMountCache() {
192
-		return $this->mountCache;
193
-	}
194
-
195
-	public function registerRootProvider(IRootMountProvider $provider) {
196
-		$this->rootProviders[] = $provider;
197
-	}
198
-
199
-	/**
200
-	 * Get all root mountpoints
201
-	 *
202
-	 * @return \OCP\Files\Mount\IMountPoint[]
203
-	 * @since 20.0.0
204
-	 */
205
-	public function getRootMounts(): array {
206
-		$loader = $this->loader;
207
-		$mounts = array_map(function (IRootMountProvider $provider) use ($loader) {
208
-			return $provider->getRootMounts($loader);
209
-		}, $this->rootProviders);
210
-		$mounts = array_reduce($mounts, function (array $mounts, array $providerMounts) {
211
-			return array_merge($mounts, $providerMounts);
212
-		}, []);
213
-		return $mounts;
214
-	}
215
-
216
-	public function clearProviders() {
217
-		$this->providers = [];
218
-		$this->homeProviders = [];
219
-		$this->rootProviders = [];
220
-	}
40
+    use EmitterTrait;
41
+
42
+    /**
43
+     * @var \OCP\Files\Config\IHomeMountProvider[]
44
+     */
45
+    private $homeProviders = [];
46
+
47
+    /**
48
+     * @var \OCP\Files\Config\IMountProvider[]
49
+     */
50
+    private $providers = [];
51
+
52
+    /** @var \OCP\Files\Config\IRootMountProvider[] */
53
+    private $rootProviders = [];
54
+
55
+    /**
56
+     * @var \OCP\Files\Storage\IStorageFactory
57
+     */
58
+    private $loader;
59
+
60
+    /**
61
+     * @var \OCP\Files\Config\IUserMountCache
62
+     */
63
+    private $mountCache;
64
+
65
+    /** @var callable[] */
66
+    private $mountFilters = [];
67
+
68
+    /**
69
+     * @param \OCP\Files\Storage\IStorageFactory $loader
70
+     * @param IUserMountCache $mountCache
71
+     */
72
+    public function __construct(IStorageFactory $loader, IUserMountCache $mountCache) {
73
+        $this->loader = $loader;
74
+        $this->mountCache = $mountCache;
75
+    }
76
+
77
+    /**
78
+     * Get all configured mount points for the user
79
+     *
80
+     * @param \OCP\IUser $user
81
+     * @return \OCP\Files\Mount\IMountPoint[]
82
+     */
83
+    public function getMountsForUser(IUser $user) {
84
+        $loader = $this->loader;
85
+        $mounts = array_map(function (IMountProvider $provider) use ($user, $loader) {
86
+            return $provider->getMountsForUser($user, $loader);
87
+        }, $this->providers);
88
+        $mounts = array_filter($mounts, function ($result) {
89
+            return is_array($result);
90
+        });
91
+        $mounts = array_reduce($mounts, function (array $mounts, array $providerMounts) {
92
+            return array_merge($mounts, $providerMounts);
93
+        }, []);
94
+        return $this->filterMounts($user, $mounts);
95
+    }
96
+
97
+    public function addMountForUser(IUser $user, IMountManager $mountManager) {
98
+        // shared mount provider gets to go last since it needs to know existing files
99
+        // to check for name collisions
100
+        $firstMounts = [];
101
+        $firstProviders = array_filter($this->providers, function (IMountProvider $provider) {
102
+            return (get_class($provider) !== 'OCA\Files_Sharing\MountProvider');
103
+        });
104
+        $lastProviders = array_filter($this->providers, function (IMountProvider $provider) {
105
+            return (get_class($provider) === 'OCA\Files_Sharing\MountProvider');
106
+        });
107
+        foreach ($firstProviders as $provider) {
108
+            $mounts = $provider->getMountsForUser($user, $this->loader);
109
+            if (is_array($mounts)) {
110
+                $firstMounts = array_merge($firstMounts, $mounts);
111
+            }
112
+        }
113
+        $firstMounts = $this->filterMounts($user, $firstMounts);
114
+        array_walk($firstMounts, [$mountManager, 'addMount']);
115
+
116
+        $lateMounts = [];
117
+        foreach ($lastProviders as $provider) {
118
+            $mounts = $provider->getMountsForUser($user, $this->loader);
119
+            if (is_array($mounts)) {
120
+                $lateMounts = array_merge($lateMounts, $mounts);
121
+            }
122
+        }
123
+
124
+        $lateMounts = $this->filterMounts($user, $lateMounts);
125
+        array_walk($lateMounts, [$mountManager, 'addMount']);
126
+
127
+        return array_merge($lateMounts, $firstMounts);
128
+    }
129
+
130
+    /**
131
+     * Get the configured home mount for this user
132
+     *
133
+     * @param \OCP\IUser $user
134
+     * @return \OCP\Files\Mount\IMountPoint
135
+     * @since 9.1.0
136
+     */
137
+    public function getHomeMountForUser(IUser $user) {
138
+        /** @var \OCP\Files\Config\IHomeMountProvider[] $providers */
139
+        $providers = array_reverse($this->homeProviders); // call the latest registered provider first to give apps an opportunity to overwrite builtin
140
+        foreach ($providers as $homeProvider) {
141
+            if ($mount = $homeProvider->getHomeMountForUser($user, $this->loader)) {
142
+                $mount->setMountPoint('/' . $user->getUID()); //make sure the mountpoint is what we expect
143
+                return $mount;
144
+            }
145
+        }
146
+        throw new \Exception('No home storage configured for user ' . $user);
147
+    }
148
+
149
+    /**
150
+     * Add a provider for mount points
151
+     *
152
+     * @param \OCP\Files\Config\IMountProvider $provider
153
+     */
154
+    public function registerProvider(IMountProvider $provider) {
155
+        $this->providers[] = $provider;
156
+
157
+        $this->emit('\OC\Files\Config', 'registerMountProvider', [$provider]);
158
+    }
159
+
160
+    public function registerMountFilter(callable $filter) {
161
+        $this->mountFilters[] = $filter;
162
+    }
163
+
164
+    private function filterMounts(IUser $user, array $mountPoints) {
165
+        return array_filter($mountPoints, function (IMountPoint $mountPoint) use ($user) {
166
+            foreach ($this->mountFilters as $filter) {
167
+                if ($filter($mountPoint, $user) === false) {
168
+                    return false;
169
+                }
170
+            }
171
+            return true;
172
+        });
173
+    }
174
+
175
+    /**
176
+     * Add a provider for home mount points
177
+     *
178
+     * @param \OCP\Files\Config\IHomeMountProvider $provider
179
+     * @since 9.1.0
180
+     */
181
+    public function registerHomeProvider(IHomeMountProvider $provider) {
182
+        $this->homeProviders[] = $provider;
183
+        $this->emit('\OC\Files\Config', 'registerHomeMountProvider', [$provider]);
184
+    }
185
+
186
+    /**
187
+     * Get the mount cache which can be used to search for mounts without setting up the filesystem
188
+     *
189
+     * @return IUserMountCache
190
+     */
191
+    public function getMountCache() {
192
+        return $this->mountCache;
193
+    }
194
+
195
+    public function registerRootProvider(IRootMountProvider $provider) {
196
+        $this->rootProviders[] = $provider;
197
+    }
198
+
199
+    /**
200
+     * Get all root mountpoints
201
+     *
202
+     * @return \OCP\Files\Mount\IMountPoint[]
203
+     * @since 20.0.0
204
+     */
205
+    public function getRootMounts(): array {
206
+        $loader = $this->loader;
207
+        $mounts = array_map(function (IRootMountProvider $provider) use ($loader) {
208
+            return $provider->getRootMounts($loader);
209
+        }, $this->rootProviders);
210
+        $mounts = array_reduce($mounts, function (array $mounts, array $providerMounts) {
211
+            return array_merge($mounts, $providerMounts);
212
+        }, []);
213
+        return $mounts;
214
+    }
215
+
216
+    public function clearProviders() {
217
+        $this->providers = [];
218
+        $this->homeProviders = [];
219
+        $this->rootProviders = [];
220
+    }
221 221
 }
Please login to merge, or discard this patch.
lib/private/Files/Config/CachedMountInfo.php 1 patch
Indentation   +95 added lines, -95 removed lines patch added patch discarded remove patch
@@ -28,108 +28,108 @@
 block discarded – undo
28 28
 use OCP\IUser;
29 29
 
30 30
 class CachedMountInfo implements ICachedMountInfo {
31
-	protected IUser $user;
32
-	protected int $storageId;
33
-	protected int $rootId;
34
-	protected string $mountPoint;
35
-	protected ?int $mountId;
36
-	protected string $rootInternalPath;
37
-	protected string $mountProvider;
31
+    protected IUser $user;
32
+    protected int $storageId;
33
+    protected int $rootId;
34
+    protected string $mountPoint;
35
+    protected ?int $mountId;
36
+    protected string $rootInternalPath;
37
+    protected string $mountProvider;
38 38
 
39
-	/**
40
-	 * CachedMountInfo constructor.
41
-	 *
42
-	 * @param IUser $user
43
-	 * @param int $storageId
44
-	 * @param int $rootId
45
-	 * @param string $mountPoint
46
-	 * @param int|null $mountId
47
-	 * @param string $rootInternalPath
48
-	 */
49
-	public function __construct(
50
-		IUser $user,
51
-		int $storageId,
52
-		int $rootId,
53
-		string $mountPoint,
54
-		string $mountProvider,
55
-		int $mountId = null,
56
-		string $rootInternalPath = ''
57
-	) {
58
-		$this->user = $user;
59
-		$this->storageId = $storageId;
60
-		$this->rootId = $rootId;
61
-		$this->mountPoint = $mountPoint;
62
-		$this->mountId = $mountId;
63
-		$this->rootInternalPath = $rootInternalPath;
64
-		if (strlen($mountProvider) > 128) {
65
-			throw new \Exception("Mount provider $mountProvider name exceeds the limit of 128 characters");
66
-		}
67
-		$this->mountProvider = $mountProvider;
68
-	}
39
+    /**
40
+     * CachedMountInfo constructor.
41
+     *
42
+     * @param IUser $user
43
+     * @param int $storageId
44
+     * @param int $rootId
45
+     * @param string $mountPoint
46
+     * @param int|null $mountId
47
+     * @param string $rootInternalPath
48
+     */
49
+    public function __construct(
50
+        IUser $user,
51
+        int $storageId,
52
+        int $rootId,
53
+        string $mountPoint,
54
+        string $mountProvider,
55
+        int $mountId = null,
56
+        string $rootInternalPath = ''
57
+    ) {
58
+        $this->user = $user;
59
+        $this->storageId = $storageId;
60
+        $this->rootId = $rootId;
61
+        $this->mountPoint = $mountPoint;
62
+        $this->mountId = $mountId;
63
+        $this->rootInternalPath = $rootInternalPath;
64
+        if (strlen($mountProvider) > 128) {
65
+            throw new \Exception("Mount provider $mountProvider name exceeds the limit of 128 characters");
66
+        }
67
+        $this->mountProvider = $mountProvider;
68
+    }
69 69
 
70
-	/**
71
-	 * @return IUser
72
-	 */
73
-	public function getUser(): IUser {
74
-		return $this->user;
75
-	}
70
+    /**
71
+     * @return IUser
72
+     */
73
+    public function getUser(): IUser {
74
+        return $this->user;
75
+    }
76 76
 
77
-	/**
78
-	 * @return int the numeric storage id of the mount
79
-	 */
80
-	public function getStorageId(): int {
81
-		return $this->storageId;
82
-	}
77
+    /**
78
+     * @return int the numeric storage id of the mount
79
+     */
80
+    public function getStorageId(): int {
81
+        return $this->storageId;
82
+    }
83 83
 
84
-	/**
85
-	 * @return int the fileid of the root of the mount
86
-	 */
87
-	public function getRootId(): int {
88
-		return $this->rootId;
89
-	}
84
+    /**
85
+     * @return int the fileid of the root of the mount
86
+     */
87
+    public function getRootId(): int {
88
+        return $this->rootId;
89
+    }
90 90
 
91
-	/**
92
-	 * @return Node|null the root node of the mount
93
-	 */
94
-	public function getMountPointNode(): ?Node {
95
-		// TODO injection etc
96
-		Filesystem::initMountPoints($this->getUser()->getUID());
97
-		$userNode = \OC::$server->getUserFolder($this->getUser()->getUID());
98
-		$nodes = $userNode->getParent()->getById($this->getRootId());
99
-		if (count($nodes) > 0) {
100
-			return $nodes[0];
101
-		} else {
102
-			return null;
103
-		}
104
-	}
91
+    /**
92
+     * @return Node|null the root node of the mount
93
+     */
94
+    public function getMountPointNode(): ?Node {
95
+        // TODO injection etc
96
+        Filesystem::initMountPoints($this->getUser()->getUID());
97
+        $userNode = \OC::$server->getUserFolder($this->getUser()->getUID());
98
+        $nodes = $userNode->getParent()->getById($this->getRootId());
99
+        if (count($nodes) > 0) {
100
+            return $nodes[0];
101
+        } else {
102
+            return null;
103
+        }
104
+    }
105 105
 
106
-	/**
107
-	 * @return string the mount point of the mount for the user
108
-	 */
109
-	public function getMountPoint(): string {
110
-		return $this->mountPoint;
111
-	}
106
+    /**
107
+     * @return string the mount point of the mount for the user
108
+     */
109
+    public function getMountPoint(): string {
110
+        return $this->mountPoint;
111
+    }
112 112
 
113
-	/**
114
-	 * Get the id of the configured mount
115
-	 *
116
-	 * @return int|null mount id or null if not applicable
117
-	 * @since 9.1.0
118
-	 */
119
-	public function getMountId(): ?int {
120
-		return $this->mountId;
121
-	}
113
+    /**
114
+     * Get the id of the configured mount
115
+     *
116
+     * @return int|null mount id or null if not applicable
117
+     * @since 9.1.0
118
+     */
119
+    public function getMountId(): ?int {
120
+        return $this->mountId;
121
+    }
122 122
 
123
-	/**
124
-	 * Get the internal path (within the storage) of the root of the mount
125
-	 *
126
-	 * @return string
127
-	 */
128
-	public function getRootInternalPath(): string {
129
-		return $this->rootInternalPath;
130
-	}
123
+    /**
124
+     * Get the internal path (within the storage) of the root of the mount
125
+     *
126
+     * @return string
127
+     */
128
+    public function getRootInternalPath(): string {
129
+        return $this->rootInternalPath;
130
+    }
131 131
 
132
-	public function getMountProvider(): string {
133
-		return $this->mountProvider;
134
-	}
132
+    public function getMountProvider(): string {
133
+        return $this->mountProvider;
134
+    }
135 135
 }
Please login to merge, or discard this patch.
lib/private/Files/Mount/Manager.php 2 patches
Indentation   +166 added lines, -166 removed lines patch added patch discarded remove patch
@@ -38,170 +38,170 @@
 block discarded – undo
38 38
 use OCP\Files\NotFoundException;
39 39
 
40 40
 class Manager implements IMountManager {
41
-	/** @var MountPoint[] */
42
-	private array $mounts = [];
43
-	/** @var CappedMemoryCache<IMountPoint> */
44
-	private CappedMemoryCache $pathCache;
45
-	/** @var CappedMemoryCache<IMountPoint[]> */
46
-	private CappedMemoryCache $inPathCache;
47
-	private SetupManager $setupManager;
48
-
49
-	public function __construct(SetupManagerFactory $setupManagerFactory) {
50
-		$this->pathCache = new CappedMemoryCache();
51
-		$this->inPathCache = new CappedMemoryCache();
52
-		$this->setupManager = $setupManagerFactory->create($this);
53
-	}
54
-
55
-	/**
56
-	 * @param IMountPoint $mount
57
-	 */
58
-	public function addMount(IMountPoint $mount) {
59
-		$this->mounts[$mount->getMountPoint()] = $mount;
60
-		$this->pathCache->clear();
61
-		$this->inPathCache->clear();
62
-	}
63
-
64
-	/**
65
-	 * @param string $mountPoint
66
-	 */
67
-	public function removeMount(string $mountPoint) {
68
-		$mountPoint = Filesystem::normalizePath($mountPoint);
69
-		if (\strlen($mountPoint) > 1) {
70
-			$mountPoint .= '/';
71
-		}
72
-		unset($this->mounts[$mountPoint]);
73
-		$this->pathCache->clear();
74
-		$this->inPathCache->clear();
75
-	}
76
-
77
-	/**
78
-	 * @param string $mountPoint
79
-	 * @param string $target
80
-	 */
81
-	public function moveMount(string $mountPoint, string $target) {
82
-		$this->mounts[$target] = $this->mounts[$mountPoint];
83
-		unset($this->mounts[$mountPoint]);
84
-		$this->pathCache->clear();
85
-		$this->inPathCache->clear();
86
-	}
87
-
88
-	/**
89
-	 * Find the mount for $path
90
-	 *
91
-	 * @param string $path
92
-	 * @return IMountPoint
93
-	 */
94
-	public function find(string $path): IMountPoint {
95
-		$this->setupManager->setupForPath($path);
96
-		$path = Filesystem::normalizePath($path);
97
-
98
-		if (isset($this->pathCache[$path])) {
99
-			return $this->pathCache[$path];
100
-		}
101
-
102
-		$current = $path;
103
-		while (true) {
104
-			$mountPoint = $current . '/';
105
-			if (isset($this->mounts[$mountPoint])) {
106
-				$this->pathCache[$path] = $this->mounts[$mountPoint];
107
-				return $this->mounts[$mountPoint];
108
-			} elseif ($current === '') {
109
-				break;
110
-			}
111
-
112
-			$current = dirname($current);
113
-			if ($current === '.' || $current === '/') {
114
-				$current = '';
115
-			}
116
-		}
117
-
118
-		throw new NotFoundException("No mount for path " . $path . " existing mounts: " . implode(",", array_keys($this->mounts)));
119
-	}
120
-
121
-	/**
122
-	 * Find all mounts in $path
123
-	 *
124
-	 * @param string $path
125
-	 * @return IMountPoint[]
126
-	 */
127
-	public function findIn(string $path): array {
128
-		$this->setupManager->setupForPath($path);
129
-		$path = $this->formatPath($path);
130
-
131
-		if (isset($this->inPathCache[$path])) {
132
-			return $this->inPathCache[$path];
133
-		}
134
-
135
-		$result = [];
136
-		$pathLength = \strlen($path);
137
-		$mountPoints = array_keys($this->mounts);
138
-		foreach ($mountPoints as $mountPoint) {
139
-			if (substr($mountPoint, 0, $pathLength) === $path && \strlen($mountPoint) > $pathLength) {
140
-				$result[] = $this->mounts[$mountPoint];
141
-			}
142
-		}
143
-
144
-		$this->inPathCache[$path] = $result;
145
-		return $result;
146
-	}
147
-
148
-	public function clear() {
149
-		$this->mounts = [];
150
-		$this->pathCache->clear();
151
-		$this->inPathCache->clear();
152
-	}
153
-
154
-	/**
155
-	 * Find mounts by storage id
156
-	 *
157
-	 * @param string $id
158
-	 * @return IMountPoint[]
159
-	 */
160
-	public function findByStorageId(string $id): array {
161
-		\OC_Util::setupFS();
162
-		if (\strlen($id) > 64) {
163
-			$id = md5($id);
164
-		}
165
-		$result = [];
166
-		foreach ($this->mounts as $mount) {
167
-			if ($mount->getStorageId() === $id) {
168
-				$result[] = $mount;
169
-			}
170
-		}
171
-		return $result;
172
-	}
173
-
174
-	/**
175
-	 * @return IMountPoint[]
176
-	 */
177
-	public function getAll(): array {
178
-		return $this->mounts;
179
-	}
180
-
181
-	/**
182
-	 * Find mounts by numeric storage id
183
-	 *
184
-	 * @param int $id
185
-	 * @return IMountPoint[]
186
-	 */
187
-	public function findByNumericId(int $id): array {
188
-		$storageId = \OC\Files\Cache\Storage::getStorageId($id);
189
-		return $this->findByStorageId($storageId);
190
-	}
191
-
192
-	/**
193
-	 * @param string $path
194
-	 * @return string
195
-	 */
196
-	private function formatPath(string $path): string {
197
-		$path = Filesystem::normalizePath($path);
198
-		if (\strlen($path) > 1) {
199
-			$path .= '/';
200
-		}
201
-		return $path;
202
-	}
203
-
204
-	public function getSetupManager(): SetupManager {
205
-		return $this->setupManager;
206
-	}
41
+    /** @var MountPoint[] */
42
+    private array $mounts = [];
43
+    /** @var CappedMemoryCache<IMountPoint> */
44
+    private CappedMemoryCache $pathCache;
45
+    /** @var CappedMemoryCache<IMountPoint[]> */
46
+    private CappedMemoryCache $inPathCache;
47
+    private SetupManager $setupManager;
48
+
49
+    public function __construct(SetupManagerFactory $setupManagerFactory) {
50
+        $this->pathCache = new CappedMemoryCache();
51
+        $this->inPathCache = new CappedMemoryCache();
52
+        $this->setupManager = $setupManagerFactory->create($this);
53
+    }
54
+
55
+    /**
56
+     * @param IMountPoint $mount
57
+     */
58
+    public function addMount(IMountPoint $mount) {
59
+        $this->mounts[$mount->getMountPoint()] = $mount;
60
+        $this->pathCache->clear();
61
+        $this->inPathCache->clear();
62
+    }
63
+
64
+    /**
65
+     * @param string $mountPoint
66
+     */
67
+    public function removeMount(string $mountPoint) {
68
+        $mountPoint = Filesystem::normalizePath($mountPoint);
69
+        if (\strlen($mountPoint) > 1) {
70
+            $mountPoint .= '/';
71
+        }
72
+        unset($this->mounts[$mountPoint]);
73
+        $this->pathCache->clear();
74
+        $this->inPathCache->clear();
75
+    }
76
+
77
+    /**
78
+     * @param string $mountPoint
79
+     * @param string $target
80
+     */
81
+    public function moveMount(string $mountPoint, string $target) {
82
+        $this->mounts[$target] = $this->mounts[$mountPoint];
83
+        unset($this->mounts[$mountPoint]);
84
+        $this->pathCache->clear();
85
+        $this->inPathCache->clear();
86
+    }
87
+
88
+    /**
89
+     * Find the mount for $path
90
+     *
91
+     * @param string $path
92
+     * @return IMountPoint
93
+     */
94
+    public function find(string $path): IMountPoint {
95
+        $this->setupManager->setupForPath($path);
96
+        $path = Filesystem::normalizePath($path);
97
+
98
+        if (isset($this->pathCache[$path])) {
99
+            return $this->pathCache[$path];
100
+        }
101
+
102
+        $current = $path;
103
+        while (true) {
104
+            $mountPoint = $current . '/';
105
+            if (isset($this->mounts[$mountPoint])) {
106
+                $this->pathCache[$path] = $this->mounts[$mountPoint];
107
+                return $this->mounts[$mountPoint];
108
+            } elseif ($current === '') {
109
+                break;
110
+            }
111
+
112
+            $current = dirname($current);
113
+            if ($current === '.' || $current === '/') {
114
+                $current = '';
115
+            }
116
+        }
117
+
118
+        throw new NotFoundException("No mount for path " . $path . " existing mounts: " . implode(",", array_keys($this->mounts)));
119
+    }
120
+
121
+    /**
122
+     * Find all mounts in $path
123
+     *
124
+     * @param string $path
125
+     * @return IMountPoint[]
126
+     */
127
+    public function findIn(string $path): array {
128
+        $this->setupManager->setupForPath($path);
129
+        $path = $this->formatPath($path);
130
+
131
+        if (isset($this->inPathCache[$path])) {
132
+            return $this->inPathCache[$path];
133
+        }
134
+
135
+        $result = [];
136
+        $pathLength = \strlen($path);
137
+        $mountPoints = array_keys($this->mounts);
138
+        foreach ($mountPoints as $mountPoint) {
139
+            if (substr($mountPoint, 0, $pathLength) === $path && \strlen($mountPoint) > $pathLength) {
140
+                $result[] = $this->mounts[$mountPoint];
141
+            }
142
+        }
143
+
144
+        $this->inPathCache[$path] = $result;
145
+        return $result;
146
+    }
147
+
148
+    public function clear() {
149
+        $this->mounts = [];
150
+        $this->pathCache->clear();
151
+        $this->inPathCache->clear();
152
+    }
153
+
154
+    /**
155
+     * Find mounts by storage id
156
+     *
157
+     * @param string $id
158
+     * @return IMountPoint[]
159
+     */
160
+    public function findByStorageId(string $id): array {
161
+        \OC_Util::setupFS();
162
+        if (\strlen($id) > 64) {
163
+            $id = md5($id);
164
+        }
165
+        $result = [];
166
+        foreach ($this->mounts as $mount) {
167
+            if ($mount->getStorageId() === $id) {
168
+                $result[] = $mount;
169
+            }
170
+        }
171
+        return $result;
172
+    }
173
+
174
+    /**
175
+     * @return IMountPoint[]
176
+     */
177
+    public function getAll(): array {
178
+        return $this->mounts;
179
+    }
180
+
181
+    /**
182
+     * Find mounts by numeric storage id
183
+     *
184
+     * @param int $id
185
+     * @return IMountPoint[]
186
+     */
187
+    public function findByNumericId(int $id): array {
188
+        $storageId = \OC\Files\Cache\Storage::getStorageId($id);
189
+        return $this->findByStorageId($storageId);
190
+    }
191
+
192
+    /**
193
+     * @param string $path
194
+     * @return string
195
+     */
196
+    private function formatPath(string $path): string {
197
+        $path = Filesystem::normalizePath($path);
198
+        if (\strlen($path) > 1) {
199
+            $path .= '/';
200
+        }
201
+        return $path;
202
+    }
203
+
204
+    public function getSetupManager(): SetupManager {
205
+        return $this->setupManager;
206
+    }
207 207
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -101,7 +101,7 @@  discard block
 block discarded – undo
101 101
 
102 102
 		$current = $path;
103 103
 		while (true) {
104
-			$mountPoint = $current . '/';
104
+			$mountPoint = $current.'/';
105 105
 			if (isset($this->mounts[$mountPoint])) {
106 106
 				$this->pathCache[$path] = $this->mounts[$mountPoint];
107 107
 				return $this->mounts[$mountPoint];
@@ -115,7 +115,7 @@  discard block
 block discarded – undo
115 115
 			}
116 116
 		}
117 117
 
118
-		throw new NotFoundException("No mount for path " . $path . " existing mounts: " . implode(",", array_keys($this->mounts)));
118
+		throw new NotFoundException("No mount for path ".$path." existing mounts: ".implode(",", array_keys($this->mounts)));
119 119
 	}
120 120
 
121 121
 	/**
Please login to merge, or discard this patch.
lib/private/Files/SetupManager.php 2 patches
Indentation   +227 added lines, -227 removed lines patch added patch discarded remove patch
@@ -51,233 +51,233 @@
 block discarded – undo
51 51
 use OCP\Lockdown\ILockdownManager;
52 52
 
53 53
 class SetupManager {
54
-	private bool $rootSetup = false;
55
-	private IEventLogger $eventLogger;
56
-	private MountProviderCollection $mountProviderCollection;
57
-	private IMountManager $mountManager;
58
-	private IUserManager $userManager;
59
-	private array $setupUsers = [];
60
-	private IEventDispatcher $eventDispatcher;
61
-	private IUserMountCache $userMountCache;
62
-	private ILockdownManager $lockdownManager;
63
-	private bool $listeningForProviders;
64
-
65
-	public function __construct(
66
-		IEventLogger $eventLogger,
67
-		MountProviderCollection $mountProviderCollection,
68
-		IMountManager $mountManager,
69
-		IUserManager $userManager,
70
-		IEventDispatcher $eventDispatcher,
71
-		IUserMountCache $userMountCache,
72
-		ILockdownManager $lockdownManager
73
-	) {
74
-		$this->eventLogger = $eventLogger;
75
-		$this->mountProviderCollection = $mountProviderCollection;
76
-		$this->mountManager = $mountManager;
77
-		$this->userManager = $userManager;
78
-		$this->eventDispatcher = $eventDispatcher;
79
-		$this->userMountCache = $userMountCache;
80
-		$this->lockdownManager = $lockdownManager;
81
-		$this->listeningForProviders = false;
82
-	}
83
-
84
-	private function setupBuiltinWrappers() {
85
-		Filesystem::addStorageWrapper('mount_options', function ($mountPoint, IStorage $storage, IMountPoint $mount) {
86
-			if ($storage->instanceOfStorage(Common::class)) {
87
-				$storage->setMountOptions($mount->getOptions());
88
-			}
89
-			return $storage;
90
-		});
91
-
92
-		Filesystem::addStorageWrapper('enable_sharing', function ($mountPoint, IStorage $storage, IMountPoint $mount) {
93
-			if (!$mount->getOption('enable_sharing', true)) {
94
-				return new PermissionsMask([
95
-					'storage' => $storage,
96
-					'mask' => Constants::PERMISSION_ALL - Constants::PERMISSION_SHARE,
97
-				]);
98
-			}
99
-			return $storage;
100
-		});
101
-
102
-		// install storage availability wrapper, before most other wrappers
103
-		Filesystem::addStorageWrapper('oc_availability', function ($mountPoint, IStorage $storage) {
104
-			if (!$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) {
105
-				return new Availability(['storage' => $storage]);
106
-			}
107
-			return $storage;
108
-		});
109
-
110
-		Filesystem::addStorageWrapper('oc_encoding', function ($mountPoint, IStorage $storage, IMountPoint $mount) {
111
-			if ($mount->getOption('encoding_compatibility', false) && !$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) {
112
-				return new Encoding(['storage' => $storage]);
113
-			}
114
-			return $storage;
115
-		});
116
-
117
-		Filesystem::addStorageWrapper('oc_quota', function ($mountPoint, $storage) {
118
-			// set up quota for home storages, even for other users
119
-			// which can happen when using sharing
120
-
121
-			/**
122
-			 * @var Storage $storage
123
-			 */
124
-			if ($storage->instanceOfStorage(HomeObjectStoreStorage::class) || $storage->instanceOfStorage(Home::class)) {
125
-				if (is_object($storage->getUser())) {
126
-					$quota = OC_Util::getUserQuota($storage->getUser());
127
-					if ($quota !== \OCP\Files\FileInfo::SPACE_UNLIMITED) {
128
-						return new Quota(['storage' => $storage, 'quota' => $quota, 'root' => 'files']);
129
-					}
130
-				}
131
-			}
132
-
133
-			return $storage;
134
-		});
135
-
136
-		Filesystem::addStorageWrapper('readonly', function ($mountPoint, IStorage $storage, IMountPoint $mount) {
137
-			/*
54
+    private bool $rootSetup = false;
55
+    private IEventLogger $eventLogger;
56
+    private MountProviderCollection $mountProviderCollection;
57
+    private IMountManager $mountManager;
58
+    private IUserManager $userManager;
59
+    private array $setupUsers = [];
60
+    private IEventDispatcher $eventDispatcher;
61
+    private IUserMountCache $userMountCache;
62
+    private ILockdownManager $lockdownManager;
63
+    private bool $listeningForProviders;
64
+
65
+    public function __construct(
66
+        IEventLogger $eventLogger,
67
+        MountProviderCollection $mountProviderCollection,
68
+        IMountManager $mountManager,
69
+        IUserManager $userManager,
70
+        IEventDispatcher $eventDispatcher,
71
+        IUserMountCache $userMountCache,
72
+        ILockdownManager $lockdownManager
73
+    ) {
74
+        $this->eventLogger = $eventLogger;
75
+        $this->mountProviderCollection = $mountProviderCollection;
76
+        $this->mountManager = $mountManager;
77
+        $this->userManager = $userManager;
78
+        $this->eventDispatcher = $eventDispatcher;
79
+        $this->userMountCache = $userMountCache;
80
+        $this->lockdownManager = $lockdownManager;
81
+        $this->listeningForProviders = false;
82
+    }
83
+
84
+    private function setupBuiltinWrappers() {
85
+        Filesystem::addStorageWrapper('mount_options', function ($mountPoint, IStorage $storage, IMountPoint $mount) {
86
+            if ($storage->instanceOfStorage(Common::class)) {
87
+                $storage->setMountOptions($mount->getOptions());
88
+            }
89
+            return $storage;
90
+        });
91
+
92
+        Filesystem::addStorageWrapper('enable_sharing', function ($mountPoint, IStorage $storage, IMountPoint $mount) {
93
+            if (!$mount->getOption('enable_sharing', true)) {
94
+                return new PermissionsMask([
95
+                    'storage' => $storage,
96
+                    'mask' => Constants::PERMISSION_ALL - Constants::PERMISSION_SHARE,
97
+                ]);
98
+            }
99
+            return $storage;
100
+        });
101
+
102
+        // install storage availability wrapper, before most other wrappers
103
+        Filesystem::addStorageWrapper('oc_availability', function ($mountPoint, IStorage $storage) {
104
+            if (!$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) {
105
+                return new Availability(['storage' => $storage]);
106
+            }
107
+            return $storage;
108
+        });
109
+
110
+        Filesystem::addStorageWrapper('oc_encoding', function ($mountPoint, IStorage $storage, IMountPoint $mount) {
111
+            if ($mount->getOption('encoding_compatibility', false) && !$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) {
112
+                return new Encoding(['storage' => $storage]);
113
+            }
114
+            return $storage;
115
+        });
116
+
117
+        Filesystem::addStorageWrapper('oc_quota', function ($mountPoint, $storage) {
118
+            // set up quota for home storages, even for other users
119
+            // which can happen when using sharing
120
+
121
+            /**
122
+             * @var Storage $storage
123
+             */
124
+            if ($storage->instanceOfStorage(HomeObjectStoreStorage::class) || $storage->instanceOfStorage(Home::class)) {
125
+                if (is_object($storage->getUser())) {
126
+                    $quota = OC_Util::getUserQuota($storage->getUser());
127
+                    if ($quota !== \OCP\Files\FileInfo::SPACE_UNLIMITED) {
128
+                        return new Quota(['storage' => $storage, 'quota' => $quota, 'root' => 'files']);
129
+                    }
130
+                }
131
+            }
132
+
133
+            return $storage;
134
+        });
135
+
136
+        Filesystem::addStorageWrapper('readonly', function ($mountPoint, IStorage $storage, IMountPoint $mount) {
137
+            /*
138 138
 			 * Do not allow any operations that modify the storage
139 139
 			 */
140
-			if ($mount->getOption('readonly', false)) {
141
-				return new PermissionsMask([
142
-					'storage' => $storage,
143
-					'mask' => Constants::PERMISSION_ALL & ~(
144
-							Constants::PERMISSION_UPDATE |
145
-							Constants::PERMISSION_CREATE |
146
-							Constants::PERMISSION_DELETE
147
-						),
148
-				]);
149
-			}
150
-			return $storage;
151
-		});
152
-	}
153
-
154
-	/**
155
-	 * Setup the full filesystem for the specified user
156
-	 */
157
-	public function setupForUser(IUser $user): void {
158
-		$this->setupRoot();
159
-
160
-		if (in_array($user->getUID(), $this->setupUsers, true)) {
161
-			return;
162
-		}
163
-		$this->setupUsers[] = $user->getUID();
164
-
165
-		$this->eventLogger->start('setup_fs', 'Setup filesystem');
166
-
167
-		$prevLogging = Filesystem::logWarningWhenAddingStorageWrapper(false);
168
-
169
-		OC_Hook::emit('OC_Filesystem', 'preSetup', ['user' => $user->getUID()]);
170
-
171
-		Filesystem::logWarningWhenAddingStorageWrapper($prevLogging);
172
-
173
-		$userDir = '/' . $user->getUID() . '/files';
174
-
175
-		Filesystem::init($user, $userDir);
176
-
177
-		if ($this->lockdownManager->canAccessFilesystem()) {
178
-			// home mounts are handled separate since we need to ensure this is mounted before we call the other mount providers
179
-			$homeMount = $this->mountProviderCollection->getHomeMountForUser($user);
180
-			$this->mountManager->addMount($homeMount);
181
-
182
-			if ($homeMount->getStorageRootId() === -1) {
183
-				$homeMount->getStorage()->mkdir('');
184
-				$homeMount->getStorage()->getScanner()->scan('');
185
-			}
186
-
187
-			// Chance to mount for other storages
188
-			$mounts = $this->mountProviderCollection->addMountForUser($user, $this->mountManager);
189
-			$mounts[] = $homeMount;
190
-			$this->userMountCache->registerMounts($user, $mounts);
191
-
192
-			$this->listenForNewMountProviders();
193
-		} else {
194
-			$this->mountManager->addMount(new MountPoint(
195
-				new NullStorage([]),
196
-				'/' . $user->getUID()
197
-			));
198
-			$this->mountManager->addMount(new MountPoint(
199
-				new NullStorage([]),
200
-				'/' . $user->getUID() . '/files'
201
-			));
202
-		}
203
-		\OC_Hook::emit('OC_Filesystem', 'post_initMountPoints', ['user' => $user->getUID()]);
204
-
205
-		OC_Hook::emit('OC_Filesystem', 'setup', ['user' => $user->getUID(), 'user_dir' => $userDir]);
206
-
207
-		$this->eventLogger->end('setup_fs');
208
-	}
209
-
210
-	/**
211
-	 * Set up the root filesystem
212
-	 */
213
-	public function setupRoot(): void {
214
-		//setting up the filesystem twice can only lead to trouble
215
-		if ($this->rootSetup) {
216
-			return;
217
-		}
218
-		$this->rootSetup = true;
219
-
220
-		$this->eventLogger->start('setup_root_fs', 'Setup root filesystem');
221
-
222
-		// load all filesystem apps before, so no setup-hook gets lost
223
-		OC_App::loadApps(['filesystem']);
224
-		$prevLogging = Filesystem::logWarningWhenAddingStorageWrapper(false);
225
-
226
-		$this->setupBuiltinWrappers();
227
-
228
-		Filesystem::logWarningWhenAddingStorageWrapper($prevLogging);
229
-
230
-		$rootMounts = $this->mountProviderCollection->getRootMounts();
231
-		foreach ($rootMounts as $rootMountProvider) {
232
-			$this->mountManager->addMount($rootMountProvider);
233
-		}
234
-
235
-		$this->eventLogger->end('setup_root_fs');
236
-	}
237
-
238
-	/**
239
-	 * Set up the filesystem for the specified path
240
-	 */
241
-	public function setupForPath(string $path): void {
242
-		if (substr_count($path, '/') < 2 || strpos($path, '/appdata_' . \OC_Util::getInstanceId()) === 0 || strpos($path, '/files_external/') === 0) {
243
-			$this->setupRoot();
244
-			return;
245
-		} else {
246
-			[, $userId] = explode('/', $path);
247
-		}
248
-
249
-		$user = $this->userManager->get($userId);
250
-
251
-		if (!$user) {
252
-			$this->setupRoot();
253
-			return;
254
-		}
255
-
256
-		$this->setupForUser($user);
257
-	}
258
-
259
-	public function tearDown() {
260
-		$this->setupUsers = [];
261
-		$this->rootSetup = false;
262
-		$this->mountManager->clear();
263
-		$this->eventDispatcher->dispatchTyped(new FilesystemTornDownEvent());
264
-	}
265
-
266
-	/**
267
-	 * Get mounts from mount providers that are registered after setup
268
-	 */
269
-	private function listenForNewMountProviders() {
270
-		if (!$this->listeningForProviders) {
271
-			$this->listeningForProviders = true;
272
-			$this->mountProviderCollection->listen('\OC\Files\Config', 'registerMountProvider', function (IMountProvider $provider) {
273
-				foreach ($this->setupUsers as $userId) {
274
-					$user = $this->userManager->get($userId);
275
-					if ($user) {
276
-						$mounts = $provider->getMountsForUser($user, Filesystem::getLoader());
277
-						array_walk($mounts, [$this->mountManager, 'addMount']);
278
-					}
279
-				}
280
-			});
281
-		}
282
-	}
140
+            if ($mount->getOption('readonly', false)) {
141
+                return new PermissionsMask([
142
+                    'storage' => $storage,
143
+                    'mask' => Constants::PERMISSION_ALL & ~(
144
+                            Constants::PERMISSION_UPDATE |
145
+                            Constants::PERMISSION_CREATE |
146
+                            Constants::PERMISSION_DELETE
147
+                        ),
148
+                ]);
149
+            }
150
+            return $storage;
151
+        });
152
+    }
153
+
154
+    /**
155
+     * Setup the full filesystem for the specified user
156
+     */
157
+    public function setupForUser(IUser $user): void {
158
+        $this->setupRoot();
159
+
160
+        if (in_array($user->getUID(), $this->setupUsers, true)) {
161
+            return;
162
+        }
163
+        $this->setupUsers[] = $user->getUID();
164
+
165
+        $this->eventLogger->start('setup_fs', 'Setup filesystem');
166
+
167
+        $prevLogging = Filesystem::logWarningWhenAddingStorageWrapper(false);
168
+
169
+        OC_Hook::emit('OC_Filesystem', 'preSetup', ['user' => $user->getUID()]);
170
+
171
+        Filesystem::logWarningWhenAddingStorageWrapper($prevLogging);
172
+
173
+        $userDir = '/' . $user->getUID() . '/files';
174
+
175
+        Filesystem::init($user, $userDir);
176
+
177
+        if ($this->lockdownManager->canAccessFilesystem()) {
178
+            // home mounts are handled separate since we need to ensure this is mounted before we call the other mount providers
179
+            $homeMount = $this->mountProviderCollection->getHomeMountForUser($user);
180
+            $this->mountManager->addMount($homeMount);
181
+
182
+            if ($homeMount->getStorageRootId() === -1) {
183
+                $homeMount->getStorage()->mkdir('');
184
+                $homeMount->getStorage()->getScanner()->scan('');
185
+            }
186
+
187
+            // Chance to mount for other storages
188
+            $mounts = $this->mountProviderCollection->addMountForUser($user, $this->mountManager);
189
+            $mounts[] = $homeMount;
190
+            $this->userMountCache->registerMounts($user, $mounts);
191
+
192
+            $this->listenForNewMountProviders();
193
+        } else {
194
+            $this->mountManager->addMount(new MountPoint(
195
+                new NullStorage([]),
196
+                '/' . $user->getUID()
197
+            ));
198
+            $this->mountManager->addMount(new MountPoint(
199
+                new NullStorage([]),
200
+                '/' . $user->getUID() . '/files'
201
+            ));
202
+        }
203
+        \OC_Hook::emit('OC_Filesystem', 'post_initMountPoints', ['user' => $user->getUID()]);
204
+
205
+        OC_Hook::emit('OC_Filesystem', 'setup', ['user' => $user->getUID(), 'user_dir' => $userDir]);
206
+
207
+        $this->eventLogger->end('setup_fs');
208
+    }
209
+
210
+    /**
211
+     * Set up the root filesystem
212
+     */
213
+    public function setupRoot(): void {
214
+        //setting up the filesystem twice can only lead to trouble
215
+        if ($this->rootSetup) {
216
+            return;
217
+        }
218
+        $this->rootSetup = true;
219
+
220
+        $this->eventLogger->start('setup_root_fs', 'Setup root filesystem');
221
+
222
+        // load all filesystem apps before, so no setup-hook gets lost
223
+        OC_App::loadApps(['filesystem']);
224
+        $prevLogging = Filesystem::logWarningWhenAddingStorageWrapper(false);
225
+
226
+        $this->setupBuiltinWrappers();
227
+
228
+        Filesystem::logWarningWhenAddingStorageWrapper($prevLogging);
229
+
230
+        $rootMounts = $this->mountProviderCollection->getRootMounts();
231
+        foreach ($rootMounts as $rootMountProvider) {
232
+            $this->mountManager->addMount($rootMountProvider);
233
+        }
234
+
235
+        $this->eventLogger->end('setup_root_fs');
236
+    }
237
+
238
+    /**
239
+     * Set up the filesystem for the specified path
240
+     */
241
+    public function setupForPath(string $path): void {
242
+        if (substr_count($path, '/') < 2 || strpos($path, '/appdata_' . \OC_Util::getInstanceId()) === 0 || strpos($path, '/files_external/') === 0) {
243
+            $this->setupRoot();
244
+            return;
245
+        } else {
246
+            [, $userId] = explode('/', $path);
247
+        }
248
+
249
+        $user = $this->userManager->get($userId);
250
+
251
+        if (!$user) {
252
+            $this->setupRoot();
253
+            return;
254
+        }
255
+
256
+        $this->setupForUser($user);
257
+    }
258
+
259
+    public function tearDown() {
260
+        $this->setupUsers = [];
261
+        $this->rootSetup = false;
262
+        $this->mountManager->clear();
263
+        $this->eventDispatcher->dispatchTyped(new FilesystemTornDownEvent());
264
+    }
265
+
266
+    /**
267
+     * Get mounts from mount providers that are registered after setup
268
+     */
269
+    private function listenForNewMountProviders() {
270
+        if (!$this->listeningForProviders) {
271
+            $this->listeningForProviders = true;
272
+            $this->mountProviderCollection->listen('\OC\Files\Config', 'registerMountProvider', function (IMountProvider $provider) {
273
+                foreach ($this->setupUsers as $userId) {
274
+                    $user = $this->userManager->get($userId);
275
+                    if ($user) {
276
+                        $mounts = $provider->getMountsForUser($user, Filesystem::getLoader());
277
+                        array_walk($mounts, [$this->mountManager, 'addMount']);
278
+                    }
279
+                }
280
+            });
281
+        }
282
+    }
283 283
 }
Please login to merge, or discard this patch.
Spacing   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -82,14 +82,14 @@  discard block
 block discarded – undo
82 82
 	}
83 83
 
84 84
 	private function setupBuiltinWrappers() {
85
-		Filesystem::addStorageWrapper('mount_options', function ($mountPoint, IStorage $storage, IMountPoint $mount) {
85
+		Filesystem::addStorageWrapper('mount_options', function($mountPoint, IStorage $storage, IMountPoint $mount) {
86 86
 			if ($storage->instanceOfStorage(Common::class)) {
87 87
 				$storage->setMountOptions($mount->getOptions());
88 88
 			}
89 89
 			return $storage;
90 90
 		});
91 91
 
92
-		Filesystem::addStorageWrapper('enable_sharing', function ($mountPoint, IStorage $storage, IMountPoint $mount) {
92
+		Filesystem::addStorageWrapper('enable_sharing', function($mountPoint, IStorage $storage, IMountPoint $mount) {
93 93
 			if (!$mount->getOption('enable_sharing', true)) {
94 94
 				return new PermissionsMask([
95 95
 					'storage' => $storage,
@@ -100,21 +100,21 @@  discard block
 block discarded – undo
100 100
 		});
101 101
 
102 102
 		// install storage availability wrapper, before most other wrappers
103
-		Filesystem::addStorageWrapper('oc_availability', function ($mountPoint, IStorage $storage) {
103
+		Filesystem::addStorageWrapper('oc_availability', function($mountPoint, IStorage $storage) {
104 104
 			if (!$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) {
105 105
 				return new Availability(['storage' => $storage]);
106 106
 			}
107 107
 			return $storage;
108 108
 		});
109 109
 
110
-		Filesystem::addStorageWrapper('oc_encoding', function ($mountPoint, IStorage $storage, IMountPoint $mount) {
110
+		Filesystem::addStorageWrapper('oc_encoding', function($mountPoint, IStorage $storage, IMountPoint $mount) {
111 111
 			if ($mount->getOption('encoding_compatibility', false) && !$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) {
112 112
 				return new Encoding(['storage' => $storage]);
113 113
 			}
114 114
 			return $storage;
115 115
 		});
116 116
 
117
-		Filesystem::addStorageWrapper('oc_quota', function ($mountPoint, $storage) {
117
+		Filesystem::addStorageWrapper('oc_quota', function($mountPoint, $storage) {
118 118
 			// set up quota for home storages, even for other users
119 119
 			// which can happen when using sharing
120 120
 
@@ -133,7 +133,7 @@  discard block
 block discarded – undo
133 133
 			return $storage;
134 134
 		});
135 135
 
136
-		Filesystem::addStorageWrapper('readonly', function ($mountPoint, IStorage $storage, IMountPoint $mount) {
136
+		Filesystem::addStorageWrapper('readonly', function($mountPoint, IStorage $storage, IMountPoint $mount) {
137 137
 			/*
138 138
 			 * Do not allow any operations that modify the storage
139 139
 			 */
@@ -170,7 +170,7 @@  discard block
 block discarded – undo
170 170
 
171 171
 		Filesystem::logWarningWhenAddingStorageWrapper($prevLogging);
172 172
 
173
-		$userDir = '/' . $user->getUID() . '/files';
173
+		$userDir = '/'.$user->getUID().'/files';
174 174
 
175 175
 		Filesystem::init($user, $userDir);
176 176
 
@@ -193,11 +193,11 @@  discard block
 block discarded – undo
193 193
 		} else {
194 194
 			$this->mountManager->addMount(new MountPoint(
195 195
 				new NullStorage([]),
196
-				'/' . $user->getUID()
196
+				'/'.$user->getUID()
197 197
 			));
198 198
 			$this->mountManager->addMount(new MountPoint(
199 199
 				new NullStorage([]),
200
-				'/' . $user->getUID() . '/files'
200
+				'/'.$user->getUID().'/files'
201 201
 			));
202 202
 		}
203 203
 		\OC_Hook::emit('OC_Filesystem', 'post_initMountPoints', ['user' => $user->getUID()]);
@@ -239,7 +239,7 @@  discard block
 block discarded – undo
239 239
 	 * Set up the filesystem for the specified path
240 240
 	 */
241 241
 	public function setupForPath(string $path): void {
242
-		if (substr_count($path, '/') < 2 || strpos($path, '/appdata_' . \OC_Util::getInstanceId()) === 0 || strpos($path, '/files_external/') === 0) {
242
+		if (substr_count($path, '/') < 2 || strpos($path, '/appdata_'.\OC_Util::getInstanceId()) === 0 || strpos($path, '/files_external/') === 0) {
243 243
 			$this->setupRoot();
244 244
 			return;
245 245
 		} else {
@@ -269,7 +269,7 @@  discard block
 block discarded – undo
269 269
 	private function listenForNewMountProviders() {
270 270
 		if (!$this->listeningForProviders) {
271 271
 			$this->listeningForProviders = true;
272
-			$this->mountProviderCollection->listen('\OC\Files\Config', 'registerMountProvider', function (IMountProvider $provider) {
272
+			$this->mountProviderCollection->listen('\OC\Files\Config', 'registerMountProvider', function(IMountProvider $provider) {
273 273
 				foreach ($this->setupUsers as $userId) {
274 274
 					$user = $this->userManager->get($userId);
275 275
 					if ($user) {
Please login to merge, or discard this patch.
lib/private/Files/Filesystem.php 2 patches
Indentation   +740 added lines, -740 removed lines patch added patch discarded remove patch
@@ -49,744 +49,744 @@
 block discarded – undo
49 49
 
50 50
 class Filesystem {
51 51
 
52
-	/**
53
-	 * @var Mount\Manager $mounts
54
-	 */
55
-	private static $mounts;
56
-
57
-	public static $loaded = false;
58
-	/**
59
-	 * @var \OC\Files\View $defaultInstance
60
-	 */
61
-	private static $defaultInstance;
62
-
63
-	private static $usersSetup = [];
64
-
65
-	private static $normalizedPathCache = null;
66
-
67
-	private static $listeningForProviders = false;
68
-
69
-	/**
70
-	 * classname which used for hooks handling
71
-	 * used as signalclass in OC_Hooks::emit()
72
-	 */
73
-	public const CLASSNAME = 'OC_Filesystem';
74
-
75
-	/**
76
-	 * signalname emitted before file renaming
77
-	 *
78
-	 * @param string $oldpath
79
-	 * @param string $newpath
80
-	 */
81
-	public const signal_rename = 'rename';
82
-
83
-	/**
84
-	 * signal emitted after file renaming
85
-	 *
86
-	 * @param string $oldpath
87
-	 * @param string $newpath
88
-	 */
89
-	public const signal_post_rename = 'post_rename';
90
-
91
-	/**
92
-	 * signal emitted before file/dir creation
93
-	 *
94
-	 * @param string $path
95
-	 * @param bool $run changing this flag to false in hook handler will cancel event
96
-	 */
97
-	public const signal_create = 'create';
98
-
99
-	/**
100
-	 * signal emitted after file/dir creation
101
-	 *
102
-	 * @param string $path
103
-	 * @param bool $run changing this flag to false in hook handler will cancel event
104
-	 */
105
-	public const signal_post_create = 'post_create';
106
-
107
-	/**
108
-	 * signal emits before file/dir copy
109
-	 *
110
-	 * @param string $oldpath
111
-	 * @param string $newpath
112
-	 * @param bool $run changing this flag to false in hook handler will cancel event
113
-	 */
114
-	public const signal_copy = 'copy';
115
-
116
-	/**
117
-	 * signal emits after file/dir copy
118
-	 *
119
-	 * @param string $oldpath
120
-	 * @param string $newpath
121
-	 */
122
-	public const signal_post_copy = 'post_copy';
123
-
124
-	/**
125
-	 * signal emits before file/dir save
126
-	 *
127
-	 * @param string $path
128
-	 * @param bool $run changing this flag to false in hook handler will cancel event
129
-	 */
130
-	public const signal_write = 'write';
131
-
132
-	/**
133
-	 * signal emits after file/dir save
134
-	 *
135
-	 * @param string $path
136
-	 */
137
-	public const signal_post_write = 'post_write';
138
-
139
-	/**
140
-	 * signal emitted before file/dir update
141
-	 *
142
-	 * @param string $path
143
-	 * @param bool $run changing this flag to false in hook handler will cancel event
144
-	 */
145
-	public const signal_update = 'update';
146
-
147
-	/**
148
-	 * signal emitted after file/dir update
149
-	 *
150
-	 * @param string $path
151
-	 * @param bool $run changing this flag to false in hook handler will cancel event
152
-	 */
153
-	public const signal_post_update = 'post_update';
154
-
155
-	/**
156
-	 * signal emits when reading file/dir
157
-	 *
158
-	 * @param string $path
159
-	 */
160
-	public const signal_read = 'read';
161
-
162
-	/**
163
-	 * signal emits when removing file/dir
164
-	 *
165
-	 * @param string $path
166
-	 */
167
-	public const signal_delete = 'delete';
168
-
169
-	/**
170
-	 * parameters definitions for signals
171
-	 */
172
-	public const signal_param_path = 'path';
173
-	public const signal_param_oldpath = 'oldpath';
174
-	public const signal_param_newpath = 'newpath';
175
-
176
-	/**
177
-	 * run - changing this flag to false in hook handler will cancel event
178
-	 */
179
-	public const signal_param_run = 'run';
180
-
181
-	public const signal_create_mount = 'create_mount';
182
-	public const signal_delete_mount = 'delete_mount';
183
-	public const signal_param_mount_type = 'mounttype';
184
-	public const signal_param_users = 'users';
185
-
186
-	/**
187
-	 * @var \OC\Files\Storage\StorageFactory $loader
188
-	 */
189
-	private static $loader;
190
-
191
-	/** @var bool */
192
-	private static $logWarningWhenAddingStorageWrapper = true;
193
-
194
-	/**
195
-	 * @param bool $shouldLog
196
-	 * @return bool previous value
197
-	 * @internal
198
-	 */
199
-	public static function logWarningWhenAddingStorageWrapper($shouldLog) {
200
-		$previousValue = self::$logWarningWhenAddingStorageWrapper;
201
-		self::$logWarningWhenAddingStorageWrapper = (bool) $shouldLog;
202
-		return $previousValue;
203
-	}
204
-
205
-	/**
206
-	 * @param string $wrapperName
207
-	 * @param callable $wrapper
208
-	 * @param int $priority
209
-	 */
210
-	public static function addStorageWrapper($wrapperName, $wrapper, $priority = 50) {
211
-		if (self::$logWarningWhenAddingStorageWrapper) {
212
-			\OC::$server->getLogger()->warning("Storage wrapper '{wrapper}' was not registered via the 'OC_Filesystem - preSetup' hook which could cause potential problems.", [
213
-				'wrapper' => $wrapperName,
214
-				'app' => 'filesystem',
215
-			]);
216
-		}
217
-
218
-		$mounts = self::getMountManager()->getAll();
219
-		if (!self::getLoader()->addStorageWrapper($wrapperName, $wrapper, $priority, $mounts)) {
220
-			// do not re-wrap if storage with this name already existed
221
-			return;
222
-		}
223
-	}
224
-
225
-	/**
226
-	 * Returns the storage factory
227
-	 *
228
-	 * @return IStorageFactory
229
-	 */
230
-	public static function getLoader() {
231
-		if (!self::$loader) {
232
-			self::$loader = \OC::$server->query(IStorageFactory::class);
233
-		}
234
-		return self::$loader;
235
-	}
236
-
237
-	/**
238
-	 * Returns the mount manager
239
-	 *
240
-	 * @return \OC\Files\Mount\Manager
241
-	 */
242
-	public static function getMountManager($user = '') {
243
-		self::initMountManager();
244
-		return self::$mounts;
245
-	}
246
-
247
-	/**
248
-	 * get the mountpoint of the storage object for a path
249
-	 * ( note: because a storage is not always mounted inside the fakeroot, the
250
-	 * returned mountpoint is relative to the absolute root of the filesystem
251
-	 * and doesn't take the chroot into account )
252
-	 *
253
-	 * @param string $path
254
-	 * @return string
255
-	 */
256
-	public static function getMountPoint($path) {
257
-		if (!self::$mounts) {
258
-			\OC_Util::setupFS();
259
-		}
260
-		$mount = self::$mounts->find($path);
261
-		return $mount->getMountPoint();
262
-	}
263
-
264
-	/**
265
-	 * get a list of all mount points in a directory
266
-	 *
267
-	 * @param string $path
268
-	 * @return string[]
269
-	 */
270
-	public static function getMountPoints($path) {
271
-		if (!self::$mounts) {
272
-			\OC_Util::setupFS();
273
-		}
274
-		$result = [];
275
-		$mounts = self::$mounts->findIn($path);
276
-		foreach ($mounts as $mount) {
277
-			$result[] = $mount->getMountPoint();
278
-		}
279
-		return $result;
280
-	}
281
-
282
-	/**
283
-	 * get the storage mounted at $mountPoint
284
-	 *
285
-	 * @param string $mountPoint
286
-	 * @return \OC\Files\Storage\Storage|null
287
-	 */
288
-	public static function getStorage($mountPoint) {
289
-		$mount = self::getMountManager()->find($mountPoint);
290
-		return $mount->getStorage();
291
-	}
292
-
293
-	/**
294
-	 * @param string $id
295
-	 * @return Mount\MountPoint[]
296
-	 */
297
-	public static function getMountByStorageId($id) {
298
-		return self::getMountManager()->findByStorageId($id);
299
-	}
300
-
301
-	/**
302
-	 * @param int $id
303
-	 * @return Mount\MountPoint[]
304
-	 */
305
-	public static function getMountByNumericId($id) {
306
-		return self::getMountManager()->findByNumericId($id);
307
-	}
308
-
309
-	/**
310
-	 * resolve a path to a storage and internal path
311
-	 *
312
-	 * @param string $path
313
-	 * @return array an array consisting of the storage and the internal path
314
-	 */
315
-	public static function resolvePath($path) {
316
-		$mount = self::getMountManager()->find($path);
317
-		return [$mount->getStorage(), rtrim($mount->getInternalPath($path), '/')];
318
-	}
319
-
320
-	public static function init($user, $root) {
321
-		if (self::$defaultInstance) {
322
-			return false;
323
-		}
324
-		self::getLoader();
325
-		self::$defaultInstance = new View($root);
326
-		/** @var IEventDispatcher $eventDispatcher */
327
-		$eventDispatcher = \OC::$server->get(IEventDispatcher::class);
328
-		$eventDispatcher->addListener(FilesystemTornDownEvent::class, function () {
329
-			self::$defaultInstance = null;
330
-			self::$usersSetup = [];
331
-			self::$loaded = false;
332
-		});
333
-
334
-		if (!self::$mounts) {
335
-			self::$mounts = \OC::$server->getMountManager();
336
-		}
337
-
338
-		//load custom mount config
339
-		self::initMountPoints($user);
340
-
341
-		self::$loaded = true;
342
-
343
-		return true;
344
-	}
345
-
346
-	public static function initMountManager() {
347
-		if (!self::$mounts) {
348
-			self::$mounts = \OC::$server->getMountManager();
349
-		}
350
-	}
351
-
352
-	/**
353
-	 * Initialize system and personal mount points for a user
354
-	 *
355
-	 * @param string|IUser|null $user
356
-	 * @throws \OC\User\NoUserException if the user is not available
357
-	 */
358
-	public static function initMountPoints($user = '') {
359
-		/** @var IUserManager $userManager */
360
-		$userManager = \OC::$server->get(IUserManager::class);
361
-
362
-		$userObject = ($user instanceof IUser) ? $user : $userManager->get($user);
363
-		if ($userObject) {
364
-			/** @var SetupManager $setupManager */
365
-			$setupManager = \OC::$server->get(SetupManager::class);
366
-			$setupManager->setupForUser($userObject);
367
-		} else {
368
-			throw new NoUserException();
369
-		}
370
-	}
371
-
372
-	/**
373
-	 * get the default filesystem view
374
-	 *
375
-	 * @return View
376
-	 */
377
-	public static function getView() {
378
-		return self::$defaultInstance;
379
-	}
380
-
381
-	/**
382
-	 * tear down the filesystem, removing all storage providers
383
-	 */
384
-	public static function tearDown() {
385
-		\OC_Util::tearDownFS();
386
-	}
387
-
388
-	/**
389
-	 * get the relative path of the root data directory for the current user
390
-	 *
391
-	 * @return string
392
-	 *
393
-	 * Returns path like /admin/files
394
-	 */
395
-	public static function getRoot() {
396
-		if (!self::$defaultInstance) {
397
-			return null;
398
-		}
399
-		return self::$defaultInstance->getRoot();
400
-	}
401
-
402
-	/**
403
-	 * mount an \OC\Files\Storage\Storage in our virtual filesystem
404
-	 *
405
-	 * @param \OC\Files\Storage\Storage|string $class
406
-	 * @param array $arguments
407
-	 * @param string $mountpoint
408
-	 */
409
-	public static function mount($class, $arguments, $mountpoint) {
410
-		if (!self::$mounts) {
411
-			\OC_Util::setupFS();
412
-		}
413
-		$mount = new Mount\MountPoint($class, $mountpoint, $arguments, self::getLoader());
414
-		self::$mounts->addMount($mount);
415
-	}
416
-
417
-	/**
418
-	 * return the path to a local version of the file
419
-	 * we need this because we can't know if a file is stored local or not from
420
-	 * outside the filestorage and for some purposes a local file is needed
421
-	 *
422
-	 * @param string $path
423
-	 * @return string
424
-	 */
425
-	public static function getLocalFile($path) {
426
-		return self::$defaultInstance->getLocalFile($path);
427
-	}
428
-
429
-	/**
430
-	 * @param string $path
431
-	 * @return string
432
-	 */
433
-	public static function getLocalFolder($path) {
434
-		return self::$defaultInstance->getLocalFolder($path);
435
-	}
436
-
437
-	/**
438
-	 * return path to file which reflects one visible in browser
439
-	 *
440
-	 * @param string $path
441
-	 * @return string
442
-	 */
443
-	public static function getLocalPath($path) {
444
-		$datadir = \OC_User::getHome(\OC_User::getUser()) . '/files';
445
-		$newpath = $path;
446
-		if (strncmp($newpath, $datadir, strlen($datadir)) == 0) {
447
-			$newpath = substr($path, strlen($datadir));
448
-		}
449
-		return $newpath;
450
-	}
451
-
452
-	/**
453
-	 * check if the requested path is valid
454
-	 *
455
-	 * @param string $path
456
-	 * @return bool
457
-	 */
458
-	public static function isValidPath($path) {
459
-		$path = self::normalizePath($path);
460
-		if (!$path || $path[0] !== '/') {
461
-			$path = '/' . $path;
462
-		}
463
-		if (strpos($path, '/../') !== false || strrchr($path, '/') === '/..') {
464
-			return false;
465
-		}
466
-		return true;
467
-	}
468
-
469
-	/**
470
-	 * checks if a file is blacklisted for storage in the filesystem
471
-	 * Listens to write and rename hooks
472
-	 *
473
-	 * @param array $data from hook
474
-	 */
475
-	public static function isBlacklisted($data) {
476
-		if (isset($data['path'])) {
477
-			$path = $data['path'];
478
-		} elseif (isset($data['newpath'])) {
479
-			$path = $data['newpath'];
480
-		}
481
-		if (isset($path)) {
482
-			if (self::isFileBlacklisted($path)) {
483
-				$data['run'] = false;
484
-			}
485
-		}
486
-	}
487
-
488
-	/**
489
-	 * @param string $filename
490
-	 * @return bool
491
-	 */
492
-	public static function isFileBlacklisted($filename) {
493
-		$filename = self::normalizePath($filename);
494
-
495
-		$blacklist = \OC::$server->getConfig()->getSystemValue('blacklisted_files', ['.htaccess']);
496
-		$filename = strtolower(basename($filename));
497
-		return in_array($filename, $blacklist);
498
-	}
499
-
500
-	/**
501
-	 * check if the directory should be ignored when scanning
502
-	 * NOTE: the special directories . and .. would cause never ending recursion
503
-	 *
504
-	 * @param string $dir
505
-	 * @return boolean
506
-	 */
507
-	public static function isIgnoredDir($dir) {
508
-		if ($dir === '.' || $dir === '..') {
509
-			return true;
510
-		}
511
-		return false;
512
-	}
513
-
514
-	/**
515
-	 * following functions are equivalent to their php builtin equivalents for arguments/return values.
516
-	 */
517
-	public static function mkdir($path) {
518
-		return self::$defaultInstance->mkdir($path);
519
-	}
520
-
521
-	public static function rmdir($path) {
522
-		return self::$defaultInstance->rmdir($path);
523
-	}
524
-
525
-	public static function is_dir($path) {
526
-		return self::$defaultInstance->is_dir($path);
527
-	}
528
-
529
-	public static function is_file($path) {
530
-		return self::$defaultInstance->is_file($path);
531
-	}
532
-
533
-	public static function stat($path) {
534
-		return self::$defaultInstance->stat($path);
535
-	}
536
-
537
-	public static function filetype($path) {
538
-		return self::$defaultInstance->filetype($path);
539
-	}
540
-
541
-	public static function filesize($path) {
542
-		return self::$defaultInstance->filesize($path);
543
-	}
544
-
545
-	public static function readfile($path) {
546
-		return self::$defaultInstance->readfile($path);
547
-	}
548
-
549
-	public static function isCreatable($path) {
550
-		return self::$defaultInstance->isCreatable($path);
551
-	}
552
-
553
-	public static function isReadable($path) {
554
-		return self::$defaultInstance->isReadable($path);
555
-	}
556
-
557
-	public static function isUpdatable($path) {
558
-		return self::$defaultInstance->isUpdatable($path);
559
-	}
560
-
561
-	public static function isDeletable($path) {
562
-		return self::$defaultInstance->isDeletable($path);
563
-	}
564
-
565
-	public static function isSharable($path) {
566
-		return self::$defaultInstance->isSharable($path);
567
-	}
568
-
569
-	public static function file_exists($path) {
570
-		return self::$defaultInstance->file_exists($path);
571
-	}
572
-
573
-	public static function filemtime($path) {
574
-		return self::$defaultInstance->filemtime($path);
575
-	}
576
-
577
-	public static function touch($path, $mtime = null) {
578
-		return self::$defaultInstance->touch($path, $mtime);
579
-	}
580
-
581
-	/**
582
-	 * @return string
583
-	 */
584
-	public static function file_get_contents($path) {
585
-		return self::$defaultInstance->file_get_contents($path);
586
-	}
587
-
588
-	public static function file_put_contents($path, $data) {
589
-		return self::$defaultInstance->file_put_contents($path, $data);
590
-	}
591
-
592
-	public static function unlink($path) {
593
-		return self::$defaultInstance->unlink($path);
594
-	}
595
-
596
-	public static function rename($path1, $path2) {
597
-		return self::$defaultInstance->rename($path1, $path2);
598
-	}
599
-
600
-	public static function copy($path1, $path2) {
601
-		return self::$defaultInstance->copy($path1, $path2);
602
-	}
603
-
604
-	public static function fopen($path, $mode) {
605
-		return self::$defaultInstance->fopen($path, $mode);
606
-	}
607
-
608
-	/**
609
-	 * @return string
610
-	 */
611
-	public static function toTmpFile($path) {
612
-		return self::$defaultInstance->toTmpFile($path);
613
-	}
614
-
615
-	public static function fromTmpFile($tmpFile, $path) {
616
-		return self::$defaultInstance->fromTmpFile($tmpFile, $path);
617
-	}
618
-
619
-	public static function getMimeType($path) {
620
-		return self::$defaultInstance->getMimeType($path);
621
-	}
622
-
623
-	public static function hash($type, $path, $raw = false) {
624
-		return self::$defaultInstance->hash($type, $path, $raw);
625
-	}
626
-
627
-	public static function free_space($path = '/') {
628
-		return self::$defaultInstance->free_space($path);
629
-	}
630
-
631
-	public static function search($query) {
632
-		return self::$defaultInstance->search($query);
633
-	}
634
-
635
-	/**
636
-	 * @param string $query
637
-	 */
638
-	public static function searchByMime($query) {
639
-		return self::$defaultInstance->searchByMime($query);
640
-	}
641
-
642
-	/**
643
-	 * @param string|int $tag name or tag id
644
-	 * @param string $userId owner of the tags
645
-	 * @return FileInfo[] array or file info
646
-	 */
647
-	public static function searchByTag($tag, $userId) {
648
-		return self::$defaultInstance->searchByTag($tag, $userId);
649
-	}
650
-
651
-	/**
652
-	 * check if a file or folder has been updated since $time
653
-	 *
654
-	 * @param string $path
655
-	 * @param int $time
656
-	 * @return bool
657
-	 */
658
-	public static function hasUpdated($path, $time) {
659
-		return self::$defaultInstance->hasUpdated($path, $time);
660
-	}
661
-
662
-	/**
663
-	 * Fix common problems with a file path
664
-	 *
665
-	 * @param string $path
666
-	 * @param bool $stripTrailingSlash whether to strip the trailing slash
667
-	 * @param bool $isAbsolutePath whether the given path is absolute
668
-	 * @param bool $keepUnicode true to disable unicode normalization
669
-	 * @return string
670
-	 */
671
-	public static function normalizePath($path, $stripTrailingSlash = true, $isAbsolutePath = false, $keepUnicode = false) {
672
-		/**
673
-		 * FIXME: This is a workaround for existing classes and files which call
674
-		 *        this function with another type than a valid string. This
675
-		 *        conversion should get removed as soon as all existing
676
-		 *        function calls have been fixed.
677
-		 */
678
-		$path = (string)$path;
679
-
680
-		if ($path === '') {
681
-			return '/';
682
-		}
683
-
684
-		if (is_null(self::$normalizedPathCache)) {
685
-			self::$normalizedPathCache = new CappedMemoryCache(2048);
686
-		}
687
-
688
-		$cacheKey = json_encode([$path, $stripTrailingSlash, $isAbsolutePath, $keepUnicode]);
689
-
690
-		if ($cacheKey && isset(self::$normalizedPathCache[$cacheKey])) {
691
-			return self::$normalizedPathCache[$cacheKey];
692
-		}
693
-
694
-		//normalize unicode if possible
695
-		if (!$keepUnicode) {
696
-			$path = \OC_Util::normalizeUnicode($path);
697
-		}
698
-
699
-		//add leading slash, if it is already there we strip it anyway
700
-		$path = '/' . $path;
701
-
702
-		$patterns = [
703
-			'#\\\\#s',       // no windows style '\\' slashes
704
-			'#/\.(/\.)*/#s', // remove '/./'
705
-			'#\//+#s',       // remove sequence of slashes
706
-			'#/\.$#s',       // remove trailing '/.'
707
-		];
708
-
709
-		do {
710
-			$count = 0;
711
-			$path = preg_replace($patterns, '/', $path, -1, $count);
712
-		} while ($count > 0);
713
-
714
-		//remove trailing slash
715
-		if ($stripTrailingSlash && strlen($path) > 1) {
716
-			$path = rtrim($path, '/');
717
-		}
718
-
719
-		self::$normalizedPathCache[$cacheKey] = $path;
720
-
721
-		return $path;
722
-	}
723
-
724
-	/**
725
-	 * get the filesystem info
726
-	 *
727
-	 * @param string $path
728
-	 * @param boolean $includeMountPoints whether to add mountpoint sizes,
729
-	 * defaults to true
730
-	 * @return \OC\Files\FileInfo|false False if file does not exist
731
-	 */
732
-	public static function getFileInfo($path, $includeMountPoints = true) {
733
-		return self::$defaultInstance->getFileInfo($path, $includeMountPoints);
734
-	}
735
-
736
-	/**
737
-	 * change file metadata
738
-	 *
739
-	 * @param string $path
740
-	 * @param array $data
741
-	 * @return int
742
-	 *
743
-	 * returns the fileid of the updated file
744
-	 */
745
-	public static function putFileInfo($path, $data) {
746
-		return self::$defaultInstance->putFileInfo($path, $data);
747
-	}
748
-
749
-	/**
750
-	 * get the content of a directory
751
-	 *
752
-	 * @param string $directory path under datadirectory
753
-	 * @param string $mimetype_filter limit returned content to this mimetype or mimepart
754
-	 * @return \OC\Files\FileInfo[]
755
-	 */
756
-	public static function getDirectoryContent($directory, $mimetype_filter = '') {
757
-		return self::$defaultInstance->getDirectoryContent($directory, $mimetype_filter);
758
-	}
759
-
760
-	/**
761
-	 * Get the path of a file by id
762
-	 *
763
-	 * Note that the resulting path is not guaranteed to be unique for the id, multiple paths can point to the same file
764
-	 *
765
-	 * @param int $id
766
-	 * @throws NotFoundException
767
-	 * @return string
768
-	 */
769
-	public static function getPath($id) {
770
-		return self::$defaultInstance->getPath($id);
771
-	}
772
-
773
-	/**
774
-	 * Get the owner for a file or folder
775
-	 *
776
-	 * @param string $path
777
-	 * @return string
778
-	 */
779
-	public static function getOwner($path) {
780
-		return self::$defaultInstance->getOwner($path);
781
-	}
782
-
783
-	/**
784
-	 * get the ETag for a file or folder
785
-	 *
786
-	 * @param string $path
787
-	 * @return string
788
-	 */
789
-	public static function getETag($path) {
790
-		return self::$defaultInstance->getETag($path);
791
-	}
52
+    /**
53
+     * @var Mount\Manager $mounts
54
+     */
55
+    private static $mounts;
56
+
57
+    public static $loaded = false;
58
+    /**
59
+     * @var \OC\Files\View $defaultInstance
60
+     */
61
+    private static $defaultInstance;
62
+
63
+    private static $usersSetup = [];
64
+
65
+    private static $normalizedPathCache = null;
66
+
67
+    private static $listeningForProviders = false;
68
+
69
+    /**
70
+     * classname which used for hooks handling
71
+     * used as signalclass in OC_Hooks::emit()
72
+     */
73
+    public const CLASSNAME = 'OC_Filesystem';
74
+
75
+    /**
76
+     * signalname emitted before file renaming
77
+     *
78
+     * @param string $oldpath
79
+     * @param string $newpath
80
+     */
81
+    public const signal_rename = 'rename';
82
+
83
+    /**
84
+     * signal emitted after file renaming
85
+     *
86
+     * @param string $oldpath
87
+     * @param string $newpath
88
+     */
89
+    public const signal_post_rename = 'post_rename';
90
+
91
+    /**
92
+     * signal emitted before file/dir creation
93
+     *
94
+     * @param string $path
95
+     * @param bool $run changing this flag to false in hook handler will cancel event
96
+     */
97
+    public const signal_create = 'create';
98
+
99
+    /**
100
+     * signal emitted after file/dir creation
101
+     *
102
+     * @param string $path
103
+     * @param bool $run changing this flag to false in hook handler will cancel event
104
+     */
105
+    public const signal_post_create = 'post_create';
106
+
107
+    /**
108
+     * signal emits before file/dir copy
109
+     *
110
+     * @param string $oldpath
111
+     * @param string $newpath
112
+     * @param bool $run changing this flag to false in hook handler will cancel event
113
+     */
114
+    public const signal_copy = 'copy';
115
+
116
+    /**
117
+     * signal emits after file/dir copy
118
+     *
119
+     * @param string $oldpath
120
+     * @param string $newpath
121
+     */
122
+    public const signal_post_copy = 'post_copy';
123
+
124
+    /**
125
+     * signal emits before file/dir save
126
+     *
127
+     * @param string $path
128
+     * @param bool $run changing this flag to false in hook handler will cancel event
129
+     */
130
+    public const signal_write = 'write';
131
+
132
+    /**
133
+     * signal emits after file/dir save
134
+     *
135
+     * @param string $path
136
+     */
137
+    public const signal_post_write = 'post_write';
138
+
139
+    /**
140
+     * signal emitted before file/dir update
141
+     *
142
+     * @param string $path
143
+     * @param bool $run changing this flag to false in hook handler will cancel event
144
+     */
145
+    public const signal_update = 'update';
146
+
147
+    /**
148
+     * signal emitted after file/dir update
149
+     *
150
+     * @param string $path
151
+     * @param bool $run changing this flag to false in hook handler will cancel event
152
+     */
153
+    public const signal_post_update = 'post_update';
154
+
155
+    /**
156
+     * signal emits when reading file/dir
157
+     *
158
+     * @param string $path
159
+     */
160
+    public const signal_read = 'read';
161
+
162
+    /**
163
+     * signal emits when removing file/dir
164
+     *
165
+     * @param string $path
166
+     */
167
+    public const signal_delete = 'delete';
168
+
169
+    /**
170
+     * parameters definitions for signals
171
+     */
172
+    public const signal_param_path = 'path';
173
+    public const signal_param_oldpath = 'oldpath';
174
+    public const signal_param_newpath = 'newpath';
175
+
176
+    /**
177
+     * run - changing this flag to false in hook handler will cancel event
178
+     */
179
+    public const signal_param_run = 'run';
180
+
181
+    public const signal_create_mount = 'create_mount';
182
+    public const signal_delete_mount = 'delete_mount';
183
+    public const signal_param_mount_type = 'mounttype';
184
+    public const signal_param_users = 'users';
185
+
186
+    /**
187
+     * @var \OC\Files\Storage\StorageFactory $loader
188
+     */
189
+    private static $loader;
190
+
191
+    /** @var bool */
192
+    private static $logWarningWhenAddingStorageWrapper = true;
193
+
194
+    /**
195
+     * @param bool $shouldLog
196
+     * @return bool previous value
197
+     * @internal
198
+     */
199
+    public static function logWarningWhenAddingStorageWrapper($shouldLog) {
200
+        $previousValue = self::$logWarningWhenAddingStorageWrapper;
201
+        self::$logWarningWhenAddingStorageWrapper = (bool) $shouldLog;
202
+        return $previousValue;
203
+    }
204
+
205
+    /**
206
+     * @param string $wrapperName
207
+     * @param callable $wrapper
208
+     * @param int $priority
209
+     */
210
+    public static function addStorageWrapper($wrapperName, $wrapper, $priority = 50) {
211
+        if (self::$logWarningWhenAddingStorageWrapper) {
212
+            \OC::$server->getLogger()->warning("Storage wrapper '{wrapper}' was not registered via the 'OC_Filesystem - preSetup' hook which could cause potential problems.", [
213
+                'wrapper' => $wrapperName,
214
+                'app' => 'filesystem',
215
+            ]);
216
+        }
217
+
218
+        $mounts = self::getMountManager()->getAll();
219
+        if (!self::getLoader()->addStorageWrapper($wrapperName, $wrapper, $priority, $mounts)) {
220
+            // do not re-wrap if storage with this name already existed
221
+            return;
222
+        }
223
+    }
224
+
225
+    /**
226
+     * Returns the storage factory
227
+     *
228
+     * @return IStorageFactory
229
+     */
230
+    public static function getLoader() {
231
+        if (!self::$loader) {
232
+            self::$loader = \OC::$server->query(IStorageFactory::class);
233
+        }
234
+        return self::$loader;
235
+    }
236
+
237
+    /**
238
+     * Returns the mount manager
239
+     *
240
+     * @return \OC\Files\Mount\Manager
241
+     */
242
+    public static function getMountManager($user = '') {
243
+        self::initMountManager();
244
+        return self::$mounts;
245
+    }
246
+
247
+    /**
248
+     * get the mountpoint of the storage object for a path
249
+     * ( note: because a storage is not always mounted inside the fakeroot, the
250
+     * returned mountpoint is relative to the absolute root of the filesystem
251
+     * and doesn't take the chroot into account )
252
+     *
253
+     * @param string $path
254
+     * @return string
255
+     */
256
+    public static function getMountPoint($path) {
257
+        if (!self::$mounts) {
258
+            \OC_Util::setupFS();
259
+        }
260
+        $mount = self::$mounts->find($path);
261
+        return $mount->getMountPoint();
262
+    }
263
+
264
+    /**
265
+     * get a list of all mount points in a directory
266
+     *
267
+     * @param string $path
268
+     * @return string[]
269
+     */
270
+    public static function getMountPoints($path) {
271
+        if (!self::$mounts) {
272
+            \OC_Util::setupFS();
273
+        }
274
+        $result = [];
275
+        $mounts = self::$mounts->findIn($path);
276
+        foreach ($mounts as $mount) {
277
+            $result[] = $mount->getMountPoint();
278
+        }
279
+        return $result;
280
+    }
281
+
282
+    /**
283
+     * get the storage mounted at $mountPoint
284
+     *
285
+     * @param string $mountPoint
286
+     * @return \OC\Files\Storage\Storage|null
287
+     */
288
+    public static function getStorage($mountPoint) {
289
+        $mount = self::getMountManager()->find($mountPoint);
290
+        return $mount->getStorage();
291
+    }
292
+
293
+    /**
294
+     * @param string $id
295
+     * @return Mount\MountPoint[]
296
+     */
297
+    public static function getMountByStorageId($id) {
298
+        return self::getMountManager()->findByStorageId($id);
299
+    }
300
+
301
+    /**
302
+     * @param int $id
303
+     * @return Mount\MountPoint[]
304
+     */
305
+    public static function getMountByNumericId($id) {
306
+        return self::getMountManager()->findByNumericId($id);
307
+    }
308
+
309
+    /**
310
+     * resolve a path to a storage and internal path
311
+     *
312
+     * @param string $path
313
+     * @return array an array consisting of the storage and the internal path
314
+     */
315
+    public static function resolvePath($path) {
316
+        $mount = self::getMountManager()->find($path);
317
+        return [$mount->getStorage(), rtrim($mount->getInternalPath($path), '/')];
318
+    }
319
+
320
+    public static function init($user, $root) {
321
+        if (self::$defaultInstance) {
322
+            return false;
323
+        }
324
+        self::getLoader();
325
+        self::$defaultInstance = new View($root);
326
+        /** @var IEventDispatcher $eventDispatcher */
327
+        $eventDispatcher = \OC::$server->get(IEventDispatcher::class);
328
+        $eventDispatcher->addListener(FilesystemTornDownEvent::class, function () {
329
+            self::$defaultInstance = null;
330
+            self::$usersSetup = [];
331
+            self::$loaded = false;
332
+        });
333
+
334
+        if (!self::$mounts) {
335
+            self::$mounts = \OC::$server->getMountManager();
336
+        }
337
+
338
+        //load custom mount config
339
+        self::initMountPoints($user);
340
+
341
+        self::$loaded = true;
342
+
343
+        return true;
344
+    }
345
+
346
+    public static function initMountManager() {
347
+        if (!self::$mounts) {
348
+            self::$mounts = \OC::$server->getMountManager();
349
+        }
350
+    }
351
+
352
+    /**
353
+     * Initialize system and personal mount points for a user
354
+     *
355
+     * @param string|IUser|null $user
356
+     * @throws \OC\User\NoUserException if the user is not available
357
+     */
358
+    public static function initMountPoints($user = '') {
359
+        /** @var IUserManager $userManager */
360
+        $userManager = \OC::$server->get(IUserManager::class);
361
+
362
+        $userObject = ($user instanceof IUser) ? $user : $userManager->get($user);
363
+        if ($userObject) {
364
+            /** @var SetupManager $setupManager */
365
+            $setupManager = \OC::$server->get(SetupManager::class);
366
+            $setupManager->setupForUser($userObject);
367
+        } else {
368
+            throw new NoUserException();
369
+        }
370
+    }
371
+
372
+    /**
373
+     * get the default filesystem view
374
+     *
375
+     * @return View
376
+     */
377
+    public static function getView() {
378
+        return self::$defaultInstance;
379
+    }
380
+
381
+    /**
382
+     * tear down the filesystem, removing all storage providers
383
+     */
384
+    public static function tearDown() {
385
+        \OC_Util::tearDownFS();
386
+    }
387
+
388
+    /**
389
+     * get the relative path of the root data directory for the current user
390
+     *
391
+     * @return string
392
+     *
393
+     * Returns path like /admin/files
394
+     */
395
+    public static function getRoot() {
396
+        if (!self::$defaultInstance) {
397
+            return null;
398
+        }
399
+        return self::$defaultInstance->getRoot();
400
+    }
401
+
402
+    /**
403
+     * mount an \OC\Files\Storage\Storage in our virtual filesystem
404
+     *
405
+     * @param \OC\Files\Storage\Storage|string $class
406
+     * @param array $arguments
407
+     * @param string $mountpoint
408
+     */
409
+    public static function mount($class, $arguments, $mountpoint) {
410
+        if (!self::$mounts) {
411
+            \OC_Util::setupFS();
412
+        }
413
+        $mount = new Mount\MountPoint($class, $mountpoint, $arguments, self::getLoader());
414
+        self::$mounts->addMount($mount);
415
+    }
416
+
417
+    /**
418
+     * return the path to a local version of the file
419
+     * we need this because we can't know if a file is stored local or not from
420
+     * outside the filestorage and for some purposes a local file is needed
421
+     *
422
+     * @param string $path
423
+     * @return string
424
+     */
425
+    public static function getLocalFile($path) {
426
+        return self::$defaultInstance->getLocalFile($path);
427
+    }
428
+
429
+    /**
430
+     * @param string $path
431
+     * @return string
432
+     */
433
+    public static function getLocalFolder($path) {
434
+        return self::$defaultInstance->getLocalFolder($path);
435
+    }
436
+
437
+    /**
438
+     * return path to file which reflects one visible in browser
439
+     *
440
+     * @param string $path
441
+     * @return string
442
+     */
443
+    public static function getLocalPath($path) {
444
+        $datadir = \OC_User::getHome(\OC_User::getUser()) . '/files';
445
+        $newpath = $path;
446
+        if (strncmp($newpath, $datadir, strlen($datadir)) == 0) {
447
+            $newpath = substr($path, strlen($datadir));
448
+        }
449
+        return $newpath;
450
+    }
451
+
452
+    /**
453
+     * check if the requested path is valid
454
+     *
455
+     * @param string $path
456
+     * @return bool
457
+     */
458
+    public static function isValidPath($path) {
459
+        $path = self::normalizePath($path);
460
+        if (!$path || $path[0] !== '/') {
461
+            $path = '/' . $path;
462
+        }
463
+        if (strpos($path, '/../') !== false || strrchr($path, '/') === '/..') {
464
+            return false;
465
+        }
466
+        return true;
467
+    }
468
+
469
+    /**
470
+     * checks if a file is blacklisted for storage in the filesystem
471
+     * Listens to write and rename hooks
472
+     *
473
+     * @param array $data from hook
474
+     */
475
+    public static function isBlacklisted($data) {
476
+        if (isset($data['path'])) {
477
+            $path = $data['path'];
478
+        } elseif (isset($data['newpath'])) {
479
+            $path = $data['newpath'];
480
+        }
481
+        if (isset($path)) {
482
+            if (self::isFileBlacklisted($path)) {
483
+                $data['run'] = false;
484
+            }
485
+        }
486
+    }
487
+
488
+    /**
489
+     * @param string $filename
490
+     * @return bool
491
+     */
492
+    public static function isFileBlacklisted($filename) {
493
+        $filename = self::normalizePath($filename);
494
+
495
+        $blacklist = \OC::$server->getConfig()->getSystemValue('blacklisted_files', ['.htaccess']);
496
+        $filename = strtolower(basename($filename));
497
+        return in_array($filename, $blacklist);
498
+    }
499
+
500
+    /**
501
+     * check if the directory should be ignored when scanning
502
+     * NOTE: the special directories . and .. would cause never ending recursion
503
+     *
504
+     * @param string $dir
505
+     * @return boolean
506
+     */
507
+    public static function isIgnoredDir($dir) {
508
+        if ($dir === '.' || $dir === '..') {
509
+            return true;
510
+        }
511
+        return false;
512
+    }
513
+
514
+    /**
515
+     * following functions are equivalent to their php builtin equivalents for arguments/return values.
516
+     */
517
+    public static function mkdir($path) {
518
+        return self::$defaultInstance->mkdir($path);
519
+    }
520
+
521
+    public static function rmdir($path) {
522
+        return self::$defaultInstance->rmdir($path);
523
+    }
524
+
525
+    public static function is_dir($path) {
526
+        return self::$defaultInstance->is_dir($path);
527
+    }
528
+
529
+    public static function is_file($path) {
530
+        return self::$defaultInstance->is_file($path);
531
+    }
532
+
533
+    public static function stat($path) {
534
+        return self::$defaultInstance->stat($path);
535
+    }
536
+
537
+    public static function filetype($path) {
538
+        return self::$defaultInstance->filetype($path);
539
+    }
540
+
541
+    public static function filesize($path) {
542
+        return self::$defaultInstance->filesize($path);
543
+    }
544
+
545
+    public static function readfile($path) {
546
+        return self::$defaultInstance->readfile($path);
547
+    }
548
+
549
+    public static function isCreatable($path) {
550
+        return self::$defaultInstance->isCreatable($path);
551
+    }
552
+
553
+    public static function isReadable($path) {
554
+        return self::$defaultInstance->isReadable($path);
555
+    }
556
+
557
+    public static function isUpdatable($path) {
558
+        return self::$defaultInstance->isUpdatable($path);
559
+    }
560
+
561
+    public static function isDeletable($path) {
562
+        return self::$defaultInstance->isDeletable($path);
563
+    }
564
+
565
+    public static function isSharable($path) {
566
+        return self::$defaultInstance->isSharable($path);
567
+    }
568
+
569
+    public static function file_exists($path) {
570
+        return self::$defaultInstance->file_exists($path);
571
+    }
572
+
573
+    public static function filemtime($path) {
574
+        return self::$defaultInstance->filemtime($path);
575
+    }
576
+
577
+    public static function touch($path, $mtime = null) {
578
+        return self::$defaultInstance->touch($path, $mtime);
579
+    }
580
+
581
+    /**
582
+     * @return string
583
+     */
584
+    public static function file_get_contents($path) {
585
+        return self::$defaultInstance->file_get_contents($path);
586
+    }
587
+
588
+    public static function file_put_contents($path, $data) {
589
+        return self::$defaultInstance->file_put_contents($path, $data);
590
+    }
591
+
592
+    public static function unlink($path) {
593
+        return self::$defaultInstance->unlink($path);
594
+    }
595
+
596
+    public static function rename($path1, $path2) {
597
+        return self::$defaultInstance->rename($path1, $path2);
598
+    }
599
+
600
+    public static function copy($path1, $path2) {
601
+        return self::$defaultInstance->copy($path1, $path2);
602
+    }
603
+
604
+    public static function fopen($path, $mode) {
605
+        return self::$defaultInstance->fopen($path, $mode);
606
+    }
607
+
608
+    /**
609
+     * @return string
610
+     */
611
+    public static function toTmpFile($path) {
612
+        return self::$defaultInstance->toTmpFile($path);
613
+    }
614
+
615
+    public static function fromTmpFile($tmpFile, $path) {
616
+        return self::$defaultInstance->fromTmpFile($tmpFile, $path);
617
+    }
618
+
619
+    public static function getMimeType($path) {
620
+        return self::$defaultInstance->getMimeType($path);
621
+    }
622
+
623
+    public static function hash($type, $path, $raw = false) {
624
+        return self::$defaultInstance->hash($type, $path, $raw);
625
+    }
626
+
627
+    public static function free_space($path = '/') {
628
+        return self::$defaultInstance->free_space($path);
629
+    }
630
+
631
+    public static function search($query) {
632
+        return self::$defaultInstance->search($query);
633
+    }
634
+
635
+    /**
636
+     * @param string $query
637
+     */
638
+    public static function searchByMime($query) {
639
+        return self::$defaultInstance->searchByMime($query);
640
+    }
641
+
642
+    /**
643
+     * @param string|int $tag name or tag id
644
+     * @param string $userId owner of the tags
645
+     * @return FileInfo[] array or file info
646
+     */
647
+    public static function searchByTag($tag, $userId) {
648
+        return self::$defaultInstance->searchByTag($tag, $userId);
649
+    }
650
+
651
+    /**
652
+     * check if a file or folder has been updated since $time
653
+     *
654
+     * @param string $path
655
+     * @param int $time
656
+     * @return bool
657
+     */
658
+    public static function hasUpdated($path, $time) {
659
+        return self::$defaultInstance->hasUpdated($path, $time);
660
+    }
661
+
662
+    /**
663
+     * Fix common problems with a file path
664
+     *
665
+     * @param string $path
666
+     * @param bool $stripTrailingSlash whether to strip the trailing slash
667
+     * @param bool $isAbsolutePath whether the given path is absolute
668
+     * @param bool $keepUnicode true to disable unicode normalization
669
+     * @return string
670
+     */
671
+    public static function normalizePath($path, $stripTrailingSlash = true, $isAbsolutePath = false, $keepUnicode = false) {
672
+        /**
673
+         * FIXME: This is a workaround for existing classes and files which call
674
+         *        this function with another type than a valid string. This
675
+         *        conversion should get removed as soon as all existing
676
+         *        function calls have been fixed.
677
+         */
678
+        $path = (string)$path;
679
+
680
+        if ($path === '') {
681
+            return '/';
682
+        }
683
+
684
+        if (is_null(self::$normalizedPathCache)) {
685
+            self::$normalizedPathCache = new CappedMemoryCache(2048);
686
+        }
687
+
688
+        $cacheKey = json_encode([$path, $stripTrailingSlash, $isAbsolutePath, $keepUnicode]);
689
+
690
+        if ($cacheKey && isset(self::$normalizedPathCache[$cacheKey])) {
691
+            return self::$normalizedPathCache[$cacheKey];
692
+        }
693
+
694
+        //normalize unicode if possible
695
+        if (!$keepUnicode) {
696
+            $path = \OC_Util::normalizeUnicode($path);
697
+        }
698
+
699
+        //add leading slash, if it is already there we strip it anyway
700
+        $path = '/' . $path;
701
+
702
+        $patterns = [
703
+            '#\\\\#s',       // no windows style '\\' slashes
704
+            '#/\.(/\.)*/#s', // remove '/./'
705
+            '#\//+#s',       // remove sequence of slashes
706
+            '#/\.$#s',       // remove trailing '/.'
707
+        ];
708
+
709
+        do {
710
+            $count = 0;
711
+            $path = preg_replace($patterns, '/', $path, -1, $count);
712
+        } while ($count > 0);
713
+
714
+        //remove trailing slash
715
+        if ($stripTrailingSlash && strlen($path) > 1) {
716
+            $path = rtrim($path, '/');
717
+        }
718
+
719
+        self::$normalizedPathCache[$cacheKey] = $path;
720
+
721
+        return $path;
722
+    }
723
+
724
+    /**
725
+     * get the filesystem info
726
+     *
727
+     * @param string $path
728
+     * @param boolean $includeMountPoints whether to add mountpoint sizes,
729
+     * defaults to true
730
+     * @return \OC\Files\FileInfo|false False if file does not exist
731
+     */
732
+    public static function getFileInfo($path, $includeMountPoints = true) {
733
+        return self::$defaultInstance->getFileInfo($path, $includeMountPoints);
734
+    }
735
+
736
+    /**
737
+     * change file metadata
738
+     *
739
+     * @param string $path
740
+     * @param array $data
741
+     * @return int
742
+     *
743
+     * returns the fileid of the updated file
744
+     */
745
+    public static function putFileInfo($path, $data) {
746
+        return self::$defaultInstance->putFileInfo($path, $data);
747
+    }
748
+
749
+    /**
750
+     * get the content of a directory
751
+     *
752
+     * @param string $directory path under datadirectory
753
+     * @param string $mimetype_filter limit returned content to this mimetype or mimepart
754
+     * @return \OC\Files\FileInfo[]
755
+     */
756
+    public static function getDirectoryContent($directory, $mimetype_filter = '') {
757
+        return self::$defaultInstance->getDirectoryContent($directory, $mimetype_filter);
758
+    }
759
+
760
+    /**
761
+     * Get the path of a file by id
762
+     *
763
+     * Note that the resulting path is not guaranteed to be unique for the id, multiple paths can point to the same file
764
+     *
765
+     * @param int $id
766
+     * @throws NotFoundException
767
+     * @return string
768
+     */
769
+    public static function getPath($id) {
770
+        return self::$defaultInstance->getPath($id);
771
+    }
772
+
773
+    /**
774
+     * Get the owner for a file or folder
775
+     *
776
+     * @param string $path
777
+     * @return string
778
+     */
779
+    public static function getOwner($path) {
780
+        return self::$defaultInstance->getOwner($path);
781
+    }
782
+
783
+    /**
784
+     * get the ETag for a file or folder
785
+     *
786
+     * @param string $path
787
+     * @return string
788
+     */
789
+    public static function getETag($path) {
790
+        return self::$defaultInstance->getETag($path);
791
+    }
792 792
 }
Please login to merge, or discard this patch.
Spacing   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -325,7 +325,7 @@  discard block
 block discarded – undo
325 325
 		self::$defaultInstance = new View($root);
326 326
 		/** @var IEventDispatcher $eventDispatcher */
327 327
 		$eventDispatcher = \OC::$server->get(IEventDispatcher::class);
328
-		$eventDispatcher->addListener(FilesystemTornDownEvent::class, function () {
328
+		$eventDispatcher->addListener(FilesystemTornDownEvent::class, function() {
329 329
 			self::$defaultInstance = null;
330 330
 			self::$usersSetup = [];
331 331
 			self::$loaded = false;
@@ -441,7 +441,7 @@  discard block
 block discarded – undo
441 441
 	 * @return string
442 442
 	 */
443 443
 	public static function getLocalPath($path) {
444
-		$datadir = \OC_User::getHome(\OC_User::getUser()) . '/files';
444
+		$datadir = \OC_User::getHome(\OC_User::getUser()).'/files';
445 445
 		$newpath = $path;
446 446
 		if (strncmp($newpath, $datadir, strlen($datadir)) == 0) {
447 447
 			$newpath = substr($path, strlen($datadir));
@@ -458,7 +458,7 @@  discard block
 block discarded – undo
458 458
 	public static function isValidPath($path) {
459 459
 		$path = self::normalizePath($path);
460 460
 		if (!$path || $path[0] !== '/') {
461
-			$path = '/' . $path;
461
+			$path = '/'.$path;
462 462
 		}
463 463
 		if (strpos($path, '/../') !== false || strrchr($path, '/') === '/..') {
464 464
 			return false;
@@ -675,7 +675,7 @@  discard block
 block discarded – undo
675 675
 		 *        conversion should get removed as soon as all existing
676 676
 		 *        function calls have been fixed.
677 677
 		 */
678
-		$path = (string)$path;
678
+		$path = (string) $path;
679 679
 
680 680
 		if ($path === '') {
681 681
 			return '/';
@@ -697,13 +697,13 @@  discard block
 block discarded – undo
697 697
 		}
698 698
 
699 699
 		//add leading slash, if it is already there we strip it anyway
700
-		$path = '/' . $path;
700
+		$path = '/'.$path;
701 701
 
702 702
 		$patterns = [
703
-			'#\\\\#s',       // no windows style '\\' slashes
703
+			'#\\\\#s', // no windows style '\\' slashes
704 704
 			'#/\.(/\.)*/#s', // remove '/./'
705
-			'#\//+#s',       // remove sequence of slashes
706
-			'#/\.$#s',       // remove trailing '/.'
705
+			'#\//+#s', // remove sequence of slashes
706
+			'#/\.$#s', // remove trailing '/.'
707 707
 		];
708 708
 
709 709
 		do {
Please login to merge, or discard this patch.
apps/files_sharing/lib/External/Manager.php 1 patch
Indentation   +720 added lines, -720 removed lines patch added patch discarded remove patch
@@ -57,771 +57,771 @@
 block discarded – undo
57 57
 use Psr\Log\LoggerInterface;
58 58
 
59 59
 class Manager {
60
-	public const STORAGE = '\OCA\Files_Sharing\External\Storage';
61
-
62
-	/** @var string|null */
63
-	private $uid;
64
-
65
-	/** @var IDBConnection */
66
-	private $connection;
67
-
68
-	/** @var \OC\Files\Mount\Manager */
69
-	private $mountManager;
70
-
71
-	/** @var IStorageFactory */
72
-	private $storageLoader;
73
-
74
-	/** @var IClientService */
75
-	private $clientService;
76
-
77
-	/** @var IManager */
78
-	private $notificationManager;
79
-
80
-	/** @var IDiscoveryService */
81
-	private $discoveryService;
82
-
83
-	/** @var ICloudFederationProviderManager */
84
-	private $cloudFederationProviderManager;
85
-
86
-	/** @var ICloudFederationFactory */
87
-	private $cloudFederationFactory;
88
-
89
-	/** @var IGroupManager */
90
-	private $groupManager;
91
-
92
-	/** @var IUserManager */
93
-	private $userManager;
94
-
95
-	/** @var IEventDispatcher */
96
-	private $eventDispatcher;
97
-
98
-	/** @var LoggerInterface */
99
-	private $logger;
100
-
101
-	public function __construct(
102
-		IDBConnection                   $connection,
103
-		\OC\Files\Mount\Manager         $mountManager,
104
-		IStorageFactory                 $storageLoader,
105
-		IClientService                  $clientService,
106
-		IManager                        $notificationManager,
107
-		IDiscoveryService               $discoveryService,
108
-		ICloudFederationProviderManager $cloudFederationProviderManager,
109
-		ICloudFederationFactory         $cloudFederationFactory,
110
-		IGroupManager                   $groupManager,
111
-		IUserManager                    $userManager,
112
-		IUserSession                    $userSession,
113
-		IEventDispatcher                $eventDispatcher,
114
-		LoggerInterface                 $logger
115
-	) {
116
-		$user = $userSession->getUser();
117
-		$this->connection = $connection;
118
-		$this->mountManager = $mountManager;
119
-		$this->storageLoader = $storageLoader;
120
-		$this->clientService = $clientService;
121
-		$this->uid = $user ? $user->getUID() : null;
122
-		$this->notificationManager = $notificationManager;
123
-		$this->discoveryService = $discoveryService;
124
-		$this->cloudFederationProviderManager = $cloudFederationProviderManager;
125
-		$this->cloudFederationFactory = $cloudFederationFactory;
126
-		$this->groupManager = $groupManager;
127
-		$this->userManager = $userManager;
128
-		$this->eventDispatcher = $eventDispatcher;
129
-		$this->logger = $logger;
130
-	}
131
-
132
-	/**
133
-	 * add new server-to-server share
134
-	 *
135
-	 * @param string $remote
136
-	 * @param string $token
137
-	 * @param string $password
138
-	 * @param string $name
139
-	 * @param string $owner
140
-	 * @param int $shareType
141
-	 * @param boolean $accepted
142
-	 * @param string $user
143
-	 * @param string $remoteId
144
-	 * @param int $parent
145
-	 * @return Mount|null
146
-	 * @throws \Doctrine\DBAL\Exception
147
-	 */
148
-	public function addShare($remote, $token, $password, $name, $owner, $shareType, $accepted = false, $user = null, $remoteId = '', $parent = -1) {
149
-		$user = $user ? $user : $this->uid;
150
-		$accepted = $accepted ? IShare::STATUS_ACCEPTED : IShare::STATUS_PENDING;
151
-		$name = Filesystem::normalizePath('/' . $name);
152
-
153
-		if ($accepted !== IShare::STATUS_ACCEPTED) {
154
-			// To avoid conflicts with the mount point generation later,
155
-			// we only use a temporary mount point name here. The real
156
-			// mount point name will be generated when accepting the share,
157
-			// using the original share item name.
158
-			$tmpMountPointName = '{{TemporaryMountPointName#' . $name . '}}';
159
-			$mountPoint = $tmpMountPointName;
160
-			$hash = md5($tmpMountPointName);
161
-			$data = [
162
-				'remote' => $remote,
163
-				'share_token' => $token,
164
-				'password' => $password,
165
-				'name' => $name,
166
-				'owner' => $owner,
167
-				'user' => $user,
168
-				'mountpoint' => $mountPoint,
169
-				'mountpoint_hash' => $hash,
170
-				'accepted' => $accepted,
171
-				'remote_id' => $remoteId,
172
-				'share_type' => $shareType,
173
-			];
174
-
175
-			$i = 1;
176
-			while (!$this->connection->insertIfNotExist('*PREFIX*share_external', $data, ['user', 'mountpoint_hash'])) {
177
-				// The external share already exists for the user
178
-				$data['mountpoint'] = $tmpMountPointName . '-' . $i;
179
-				$data['mountpoint_hash'] = md5($data['mountpoint']);
180
-				$i++;
181
-			}
182
-			return null;
183
-		}
184
-
185
-		$mountPoint = Files::buildNotExistingFileName('/', $name);
186
-		$mountPoint = Filesystem::normalizePath('/' . $mountPoint);
187
-		$hash = md5($mountPoint);
188
-
189
-		$this->writeShareToDb($remote, $token, $password, $name, $owner, $user, $mountPoint, $hash, $accepted, $remoteId, $parent, $shareType);
190
-
191
-		$options = [
192
-			'remote' => $remote,
193
-			'token' => $token,
194
-			'password' => $password,
195
-			'mountpoint' => $mountPoint,
196
-			'owner' => $owner
197
-		];
198
-		return $this->mountShare($options);
199
-	}
200
-
201
-	/**
202
-	 * write remote share to the database
203
-	 *
204
-	 * @param $remote
205
-	 * @param $token
206
-	 * @param $password
207
-	 * @param $name
208
-	 * @param $owner
209
-	 * @param $user
210
-	 * @param $mountPoint
211
-	 * @param $hash
212
-	 * @param $accepted
213
-	 * @param $remoteId
214
-	 * @param $parent
215
-	 * @param $shareType
216
-	 *
217
-	 * @return void
218
-	 * @throws \Doctrine\DBAL\Driver\Exception
219
-	 */
220
-	private function writeShareToDb($remote, $token, $password, $name, $owner, $user, $mountPoint, $hash, $accepted, $remoteId, $parent, $shareType): void {
221
-		$query = $this->connection->prepare('
60
+    public const STORAGE = '\OCA\Files_Sharing\External\Storage';
61
+
62
+    /** @var string|null */
63
+    private $uid;
64
+
65
+    /** @var IDBConnection */
66
+    private $connection;
67
+
68
+    /** @var \OC\Files\Mount\Manager */
69
+    private $mountManager;
70
+
71
+    /** @var IStorageFactory */
72
+    private $storageLoader;
73
+
74
+    /** @var IClientService */
75
+    private $clientService;
76
+
77
+    /** @var IManager */
78
+    private $notificationManager;
79
+
80
+    /** @var IDiscoveryService */
81
+    private $discoveryService;
82
+
83
+    /** @var ICloudFederationProviderManager */
84
+    private $cloudFederationProviderManager;
85
+
86
+    /** @var ICloudFederationFactory */
87
+    private $cloudFederationFactory;
88
+
89
+    /** @var IGroupManager */
90
+    private $groupManager;
91
+
92
+    /** @var IUserManager */
93
+    private $userManager;
94
+
95
+    /** @var IEventDispatcher */
96
+    private $eventDispatcher;
97
+
98
+    /** @var LoggerInterface */
99
+    private $logger;
100
+
101
+    public function __construct(
102
+        IDBConnection                   $connection,
103
+        \OC\Files\Mount\Manager         $mountManager,
104
+        IStorageFactory                 $storageLoader,
105
+        IClientService                  $clientService,
106
+        IManager                        $notificationManager,
107
+        IDiscoveryService               $discoveryService,
108
+        ICloudFederationProviderManager $cloudFederationProviderManager,
109
+        ICloudFederationFactory         $cloudFederationFactory,
110
+        IGroupManager                   $groupManager,
111
+        IUserManager                    $userManager,
112
+        IUserSession                    $userSession,
113
+        IEventDispatcher                $eventDispatcher,
114
+        LoggerInterface                 $logger
115
+    ) {
116
+        $user = $userSession->getUser();
117
+        $this->connection = $connection;
118
+        $this->mountManager = $mountManager;
119
+        $this->storageLoader = $storageLoader;
120
+        $this->clientService = $clientService;
121
+        $this->uid = $user ? $user->getUID() : null;
122
+        $this->notificationManager = $notificationManager;
123
+        $this->discoveryService = $discoveryService;
124
+        $this->cloudFederationProviderManager = $cloudFederationProviderManager;
125
+        $this->cloudFederationFactory = $cloudFederationFactory;
126
+        $this->groupManager = $groupManager;
127
+        $this->userManager = $userManager;
128
+        $this->eventDispatcher = $eventDispatcher;
129
+        $this->logger = $logger;
130
+    }
131
+
132
+    /**
133
+     * add new server-to-server share
134
+     *
135
+     * @param string $remote
136
+     * @param string $token
137
+     * @param string $password
138
+     * @param string $name
139
+     * @param string $owner
140
+     * @param int $shareType
141
+     * @param boolean $accepted
142
+     * @param string $user
143
+     * @param string $remoteId
144
+     * @param int $parent
145
+     * @return Mount|null
146
+     * @throws \Doctrine\DBAL\Exception
147
+     */
148
+    public function addShare($remote, $token, $password, $name, $owner, $shareType, $accepted = false, $user = null, $remoteId = '', $parent = -1) {
149
+        $user = $user ? $user : $this->uid;
150
+        $accepted = $accepted ? IShare::STATUS_ACCEPTED : IShare::STATUS_PENDING;
151
+        $name = Filesystem::normalizePath('/' . $name);
152
+
153
+        if ($accepted !== IShare::STATUS_ACCEPTED) {
154
+            // To avoid conflicts with the mount point generation later,
155
+            // we only use a temporary mount point name here. The real
156
+            // mount point name will be generated when accepting the share,
157
+            // using the original share item name.
158
+            $tmpMountPointName = '{{TemporaryMountPointName#' . $name . '}}';
159
+            $mountPoint = $tmpMountPointName;
160
+            $hash = md5($tmpMountPointName);
161
+            $data = [
162
+                'remote' => $remote,
163
+                'share_token' => $token,
164
+                'password' => $password,
165
+                'name' => $name,
166
+                'owner' => $owner,
167
+                'user' => $user,
168
+                'mountpoint' => $mountPoint,
169
+                'mountpoint_hash' => $hash,
170
+                'accepted' => $accepted,
171
+                'remote_id' => $remoteId,
172
+                'share_type' => $shareType,
173
+            ];
174
+
175
+            $i = 1;
176
+            while (!$this->connection->insertIfNotExist('*PREFIX*share_external', $data, ['user', 'mountpoint_hash'])) {
177
+                // The external share already exists for the user
178
+                $data['mountpoint'] = $tmpMountPointName . '-' . $i;
179
+                $data['mountpoint_hash'] = md5($data['mountpoint']);
180
+                $i++;
181
+            }
182
+            return null;
183
+        }
184
+
185
+        $mountPoint = Files::buildNotExistingFileName('/', $name);
186
+        $mountPoint = Filesystem::normalizePath('/' . $mountPoint);
187
+        $hash = md5($mountPoint);
188
+
189
+        $this->writeShareToDb($remote, $token, $password, $name, $owner, $user, $mountPoint, $hash, $accepted, $remoteId, $parent, $shareType);
190
+
191
+        $options = [
192
+            'remote' => $remote,
193
+            'token' => $token,
194
+            'password' => $password,
195
+            'mountpoint' => $mountPoint,
196
+            'owner' => $owner
197
+        ];
198
+        return $this->mountShare($options);
199
+    }
200
+
201
+    /**
202
+     * write remote share to the database
203
+     *
204
+     * @param $remote
205
+     * @param $token
206
+     * @param $password
207
+     * @param $name
208
+     * @param $owner
209
+     * @param $user
210
+     * @param $mountPoint
211
+     * @param $hash
212
+     * @param $accepted
213
+     * @param $remoteId
214
+     * @param $parent
215
+     * @param $shareType
216
+     *
217
+     * @return void
218
+     * @throws \Doctrine\DBAL\Driver\Exception
219
+     */
220
+    private function writeShareToDb($remote, $token, $password, $name, $owner, $user, $mountPoint, $hash, $accepted, $remoteId, $parent, $shareType): void {
221
+        $query = $this->connection->prepare('
222 222
 				INSERT INTO `*PREFIX*share_external`
223 223
 					(`remote`, `share_token`, `password`, `name`, `owner`, `user`, `mountpoint`, `mountpoint_hash`, `accepted`, `remote_id`, `parent`, `share_type`)
224 224
 				VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
225 225
 			');
226
-		$query->execute([$remote, $token, $password, $name, $owner, $user, $mountPoint, $hash, $accepted, $remoteId, $parent, $shareType]);
227
-	}
228
-
229
-	/**
230
-	 * get share
231
-	 *
232
-	 * @param int $id share id
233
-	 * @return mixed share of false
234
-	 */
235
-	private function fetchShare($id) {
236
-		$getShare = $this->connection->prepare('
226
+        $query->execute([$remote, $token, $password, $name, $owner, $user, $mountPoint, $hash, $accepted, $remoteId, $parent, $shareType]);
227
+    }
228
+
229
+    /**
230
+     * get share
231
+     *
232
+     * @param int $id share id
233
+     * @return mixed share of false
234
+     */
235
+    private function fetchShare($id) {
236
+        $getShare = $this->connection->prepare('
237 237
 			SELECT `id`, `remote`, `remote_id`, `share_token`, `name`, `owner`, `user`, `mountpoint`, `accepted`, `parent`, `share_type`, `password`, `mountpoint_hash`
238 238
 			FROM  `*PREFIX*share_external`
239 239
 			WHERE `id` = ?');
240
-		$result = $getShare->execute([$id]);
241
-		$share = $result->fetch();
242
-		$result->closeCursor();
243
-		return $share;
244
-	}
245
-
246
-	private function fetchUserShare($parentId, $uid) {
247
-		$getShare = $this->connection->prepare('
240
+        $result = $getShare->execute([$id]);
241
+        $share = $result->fetch();
242
+        $result->closeCursor();
243
+        return $share;
244
+    }
245
+
246
+    private function fetchUserShare($parentId, $uid) {
247
+        $getShare = $this->connection->prepare('
248 248
 			SELECT `id`, `remote`, `remote_id`, `share_token`, `name`, `owner`, `user`, `mountpoint`, `accepted`, `parent`, `share_type`, `password`, `mountpoint_hash`
249 249
 			FROM  `*PREFIX*share_external`
250 250
 			WHERE `parent` = ? AND `user` = ?');
251
-		$result = $getShare->execute([$parentId, $uid]);
252
-		$share = $result->fetch();
253
-		$result->closeCursor();
254
-		if ($share !== false) {
255
-			return $share;
256
-		}
257
-		return null;
258
-	}
259
-
260
-	/**
261
-	 * get share
262
-	 *
263
-	 * @param int $id share id
264
-	 * @return mixed share of false
265
-	 */
266
-	public function getShare($id) {
267
-		$share = $this->fetchShare($id);
268
-		$validShare = is_array($share) && isset($share['share_type']) && isset($share['user']);
269
-
270
-		// check if the user is allowed to access it
271
-		if ($validShare && (int)$share['share_type'] === IShare::TYPE_USER && $share['user'] === $this->uid) {
272
-			return $share;
273
-		} elseif ($validShare && (int)$share['share_type'] === IShare::TYPE_GROUP) {
274
-			$parentId = (int)$share['parent'];
275
-			if ($parentId !== -1) {
276
-				// we just retrieved a sub-share, switch to the parent entry for verification
277
-				$groupShare = $this->fetchShare($parentId);
278
-			} else {
279
-				$groupShare = $share;
280
-			}
281
-			$user = $this->userManager->get($this->uid);
282
-			if ($this->groupManager->get($groupShare['user'])->inGroup($user)) {
283
-				return $share;
284
-			}
285
-		}
286
-
287
-		return false;
288
-	}
289
-
290
-	/**
291
-	 * Updates accepted flag in the database
292
-	 *
293
-	 * @param int $id
294
-	 */
295
-	private function updateAccepted(int $shareId, bool $accepted) : void {
296
-		$query = $this->connection->prepare('
251
+        $result = $getShare->execute([$parentId, $uid]);
252
+        $share = $result->fetch();
253
+        $result->closeCursor();
254
+        if ($share !== false) {
255
+            return $share;
256
+        }
257
+        return null;
258
+    }
259
+
260
+    /**
261
+     * get share
262
+     *
263
+     * @param int $id share id
264
+     * @return mixed share of false
265
+     */
266
+    public function getShare($id) {
267
+        $share = $this->fetchShare($id);
268
+        $validShare = is_array($share) && isset($share['share_type']) && isset($share['user']);
269
+
270
+        // check if the user is allowed to access it
271
+        if ($validShare && (int)$share['share_type'] === IShare::TYPE_USER && $share['user'] === $this->uid) {
272
+            return $share;
273
+        } elseif ($validShare && (int)$share['share_type'] === IShare::TYPE_GROUP) {
274
+            $parentId = (int)$share['parent'];
275
+            if ($parentId !== -1) {
276
+                // we just retrieved a sub-share, switch to the parent entry for verification
277
+                $groupShare = $this->fetchShare($parentId);
278
+            } else {
279
+                $groupShare = $share;
280
+            }
281
+            $user = $this->userManager->get($this->uid);
282
+            if ($this->groupManager->get($groupShare['user'])->inGroup($user)) {
283
+                return $share;
284
+            }
285
+        }
286
+
287
+        return false;
288
+    }
289
+
290
+    /**
291
+     * Updates accepted flag in the database
292
+     *
293
+     * @param int $id
294
+     */
295
+    private function updateAccepted(int $shareId, bool $accepted) : void {
296
+        $query = $this->connection->prepare('
297 297
 			UPDATE `*PREFIX*share_external`
298 298
 			SET `accepted` = ?
299 299
 			WHERE `id` = ?');
300
-		$updateResult = $query->execute([$accepted ? 1 : 0, $shareId]);
301
-		$updateResult->closeCursor();
302
-	}
303
-
304
-	/**
305
-	 * accept server-to-server share
306
-	 *
307
-	 * @param int $id
308
-	 * @return bool True if the share could be accepted, false otherwise
309
-	 */
310
-	public function acceptShare($id) {
311
-		$share = $this->getShare($id);
312
-		$result = false;
313
-
314
-		if ($share) {
315
-			\OC_Util::setupFS($this->uid);
316
-			$shareFolder = Helper::getShareFolder(null, $this->uid);
317
-			$mountPoint = Files::buildNotExistingFileName($shareFolder, $share['name']);
318
-			$mountPoint = Filesystem::normalizePath($mountPoint);
319
-			$hash = md5($mountPoint);
320
-			$userShareAccepted = false;
321
-
322
-			if ((int)$share['share_type'] === IShare::TYPE_USER) {
323
-				$acceptShare = $this->connection->prepare('
300
+        $updateResult = $query->execute([$accepted ? 1 : 0, $shareId]);
301
+        $updateResult->closeCursor();
302
+    }
303
+
304
+    /**
305
+     * accept server-to-server share
306
+     *
307
+     * @param int $id
308
+     * @return bool True if the share could be accepted, false otherwise
309
+     */
310
+    public function acceptShare($id) {
311
+        $share = $this->getShare($id);
312
+        $result = false;
313
+
314
+        if ($share) {
315
+            \OC_Util::setupFS($this->uid);
316
+            $shareFolder = Helper::getShareFolder(null, $this->uid);
317
+            $mountPoint = Files::buildNotExistingFileName($shareFolder, $share['name']);
318
+            $mountPoint = Filesystem::normalizePath($mountPoint);
319
+            $hash = md5($mountPoint);
320
+            $userShareAccepted = false;
321
+
322
+            if ((int)$share['share_type'] === IShare::TYPE_USER) {
323
+                $acceptShare = $this->connection->prepare('
324 324
 				UPDATE `*PREFIX*share_external`
325 325
 				SET `accepted` = ?,
326 326
 					`mountpoint` = ?,
327 327
 					`mountpoint_hash` = ?
328 328
 				WHERE `id` = ? AND `user` = ?');
329
-				$userShareAccepted = $acceptShare->execute([1, $mountPoint, $hash, $id, $this->uid]);
330
-			} else {
331
-				$parentId = (int)$share['parent'];
332
-				if ($parentId !== -1) {
333
-					// this is the sub-share
334
-					$subshare = $share;
335
-				} else {
336
-					$subshare = $this->fetchUserShare($id, $this->uid);
337
-				}
338
-
339
-				if ($subshare !== null) {
340
-					try {
341
-						$acceptShare = $this->connection->prepare('
329
+                $userShareAccepted = $acceptShare->execute([1, $mountPoint, $hash, $id, $this->uid]);
330
+            } else {
331
+                $parentId = (int)$share['parent'];
332
+                if ($parentId !== -1) {
333
+                    // this is the sub-share
334
+                    $subshare = $share;
335
+                } else {
336
+                    $subshare = $this->fetchUserShare($id, $this->uid);
337
+                }
338
+
339
+                if ($subshare !== null) {
340
+                    try {
341
+                        $acceptShare = $this->connection->prepare('
342 342
 						UPDATE `*PREFIX*share_external`
343 343
 						SET `accepted` = ?,
344 344
 							`mountpoint` = ?,
345 345
 							`mountpoint_hash` = ?
346 346
 						WHERE `id` = ? AND `user` = ?');
347
-						$acceptShare->execute([1, $mountPoint, $hash, $subshare['id'], $this->uid]);
348
-						$result = true;
349
-					} catch (Exception $e) {
350
-						$this->logger->emergency('Could not update share', ['exception' => $e]);
351
-						$result = false;
352
-					}
353
-				} else {
354
-					try {
355
-						$this->writeShareToDb(
356
-							$share['remote'],
357
-							$share['share_token'],
358
-							$share['password'],
359
-							$share['name'],
360
-							$share['owner'],
361
-							$this->uid,
362
-							$mountPoint, $hash, 1,
363
-							$share['remote_id'],
364
-							$id,
365
-							$share['share_type']);
366
-						$result = true;
367
-					} catch (Exception $e) {
368
-						$this->logger->emergency('Could not create share', ['exception' => $e]);
369
-						$result = false;
370
-					}
371
-				}
372
-			}
373
-			if ($userShareAccepted !== false) {
374
-				$this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'accept');
375
-				$event = new FederatedShareAddedEvent($share['remote']);
376
-				$this->eventDispatcher->dispatchTyped($event);
377
-				$result = true;
378
-			}
379
-		}
380
-
381
-		// Make sure the user has no notification for something that does not exist anymore.
382
-		$this->processNotification($id);
383
-
384
-		return $result;
385
-	}
386
-
387
-	/**
388
-	 * decline server-to-server share
389
-	 *
390
-	 * @param int $id
391
-	 * @return bool True if the share could be declined, false otherwise
392
-	 */
393
-	public function declineShare($id) {
394
-		$share = $this->getShare($id);
395
-		$result = false;
396
-
397
-		if ($share && (int)$share['share_type'] === IShare::TYPE_USER) {
398
-			$removeShare = $this->connection->prepare('
347
+                        $acceptShare->execute([1, $mountPoint, $hash, $subshare['id'], $this->uid]);
348
+                        $result = true;
349
+                    } catch (Exception $e) {
350
+                        $this->logger->emergency('Could not update share', ['exception' => $e]);
351
+                        $result = false;
352
+                    }
353
+                } else {
354
+                    try {
355
+                        $this->writeShareToDb(
356
+                            $share['remote'],
357
+                            $share['share_token'],
358
+                            $share['password'],
359
+                            $share['name'],
360
+                            $share['owner'],
361
+                            $this->uid,
362
+                            $mountPoint, $hash, 1,
363
+                            $share['remote_id'],
364
+                            $id,
365
+                            $share['share_type']);
366
+                        $result = true;
367
+                    } catch (Exception $e) {
368
+                        $this->logger->emergency('Could not create share', ['exception' => $e]);
369
+                        $result = false;
370
+                    }
371
+                }
372
+            }
373
+            if ($userShareAccepted !== false) {
374
+                $this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'accept');
375
+                $event = new FederatedShareAddedEvent($share['remote']);
376
+                $this->eventDispatcher->dispatchTyped($event);
377
+                $result = true;
378
+            }
379
+        }
380
+
381
+        // Make sure the user has no notification for something that does not exist anymore.
382
+        $this->processNotification($id);
383
+
384
+        return $result;
385
+    }
386
+
387
+    /**
388
+     * decline server-to-server share
389
+     *
390
+     * @param int $id
391
+     * @return bool True if the share could be declined, false otherwise
392
+     */
393
+    public function declineShare($id) {
394
+        $share = $this->getShare($id);
395
+        $result = false;
396
+
397
+        if ($share && (int)$share['share_type'] === IShare::TYPE_USER) {
398
+            $removeShare = $this->connection->prepare('
399 399
 				DELETE FROM `*PREFIX*share_external` WHERE `id` = ? AND `user` = ?');
400
-			$removeShare->execute([$id, $this->uid]);
401
-			$this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'decline');
402
-
403
-			$this->processNotification($id);
404
-			$result = true;
405
-		} elseif ($share && (int)$share['share_type'] === IShare::TYPE_GROUP) {
406
-			$parentId = (int)$share['parent'];
407
-			if ($parentId !== -1) {
408
-				// this is the sub-share
409
-				$subshare = $share;
410
-			} else {
411
-				$subshare = $this->fetchUserShare($id, $this->uid);
412
-			}
413
-
414
-			if ($subshare !== null) {
415
-				try {
416
-					$this->updateAccepted((int)$subshare['id'], false);
417
-					$result = true;
418
-				} catch (Exception $e) {
419
-					$this->logger->emergency('Could not update share', ['exception' => $e]);
420
-					$result = false;
421
-				}
422
-			} else {
423
-				try {
424
-					$this->writeShareToDb(
425
-						$share['remote'],
426
-						$share['share_token'],
427
-						$share['password'],
428
-						$share['name'],
429
-						$share['owner'],
430
-						$this->uid,
431
-						$share['mountpoint'],
432
-						$share['mountpoint_hash'],
433
-						0,
434
-						$share['remote_id'],
435
-						$id,
436
-						$share['share_type']);
437
-					$result = true;
438
-				} catch (Exception $e) {
439
-					$this->logger->emergency('Could not create share', ['exception' => $e]);
440
-					$result = false;
441
-				}
442
-			}
443
-			$this->processNotification($id);
444
-		}
445
-
446
-		return $result;
447
-	}
448
-
449
-	/**
450
-	 * @param int $remoteShare
451
-	 */
452
-	public function processNotification($remoteShare) {
453
-		$filter = $this->notificationManager->createNotification();
454
-		$filter->setApp('files_sharing')
455
-			->setUser($this->uid)
456
-			->setObject('remote_share', (int) $remoteShare);
457
-		$this->notificationManager->markProcessed($filter);
458
-	}
459
-
460
-	/**
461
-	 * inform remote server whether server-to-server share was accepted/declined
462
-	 *
463
-	 * @param string $remote
464
-	 * @param string $token
465
-	 * @param string $remoteId Share id on the remote host
466
-	 * @param string $feedback
467
-	 * @return boolean
468
-	 */
469
-	private function sendFeedbackToRemote($remote, $token, $remoteId, $feedback) {
470
-		$result = $this->tryOCMEndPoint($remote, $token, $remoteId, $feedback);
471
-
472
-		if (is_array($result)) {
473
-			return true;
474
-		}
475
-
476
-		$federationEndpoints = $this->discoveryService->discover($remote, 'FEDERATED_SHARING');
477
-		$endpoint = isset($federationEndpoints['share']) ? $federationEndpoints['share'] : '/ocs/v2.php/cloud/shares';
478
-
479
-		$url = rtrim($remote, '/') . $endpoint . '/' . $remoteId . '/' . $feedback . '?format=' . Share::RESPONSE_FORMAT;
480
-		$fields = ['token' => $token];
481
-
482
-		$client = $this->clientService->newClient();
483
-
484
-		try {
485
-			$response = $client->post(
486
-				$url,
487
-				[
488
-					'body' => $fields,
489
-					'connect_timeout' => 10,
490
-				]
491
-			);
492
-		} catch (\Exception $e) {
493
-			return false;
494
-		}
495
-
496
-		$status = json_decode($response->getBody(), true);
497
-
498
-		return ($status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200);
499
-	}
500
-
501
-	/**
502
-	 * try send accept message to ocm end-point
503
-	 *
504
-	 * @param string $remoteDomain
505
-	 * @param string $token
506
-	 * @param string $remoteId id of the share
507
-	 * @param string $feedback
508
-	 * @return array|false
509
-	 */
510
-	protected function tryOCMEndPoint($remoteDomain, $token, $remoteId, $feedback) {
511
-		switch ($feedback) {
512
-			case 'accept':
513
-				$notification = $this->cloudFederationFactory->getCloudFederationNotification();
514
-				$notification->setMessage(
515
-					'SHARE_ACCEPTED',
516
-					'file',
517
-					$remoteId,
518
-					[
519
-						'sharedSecret' => $token,
520
-						'message' => 'Recipient accept the share'
521
-					]
522
-
523
-				);
524
-				return $this->cloudFederationProviderManager->sendNotification($remoteDomain, $notification);
525
-			case 'decline':
526
-				$notification = $this->cloudFederationFactory->getCloudFederationNotification();
527
-				$notification->setMessage(
528
-					'SHARE_DECLINED',
529
-					'file',
530
-					$remoteId,
531
-					[
532
-						'sharedSecret' => $token,
533
-						'message' => 'Recipient declined the share'
534
-					]
535
-
536
-				);
537
-				return $this->cloudFederationProviderManager->sendNotification($remoteDomain, $notification);
538
-		}
539
-
540
-		return false;
541
-	}
542
-
543
-
544
-	/**
545
-	 * remove '/user/files' from the path and trailing slashes
546
-	 *
547
-	 * @param string $path
548
-	 * @return string
549
-	 */
550
-	protected function stripPath($path) {
551
-		$prefix = '/' . $this->uid . '/files';
552
-		return rtrim(substr($path, strlen($prefix)), '/');
553
-	}
554
-
555
-	public function getMount($data) {
556
-		$data['manager'] = $this;
557
-		$mountPoint = '/' . $this->uid . '/files' . $data['mountpoint'];
558
-		$data['mountpoint'] = $mountPoint;
559
-		$data['certificateManager'] = \OC::$server->getCertificateManager();
560
-		return new Mount(self::STORAGE, $mountPoint, $data, $this, $this->storageLoader);
561
-	}
562
-
563
-	/**
564
-	 * @param array $data
565
-	 * @return Mount
566
-	 */
567
-	protected function mountShare($data) {
568
-		$mount = $this->getMount($data);
569
-		$this->mountManager->addMount($mount);
570
-		return $mount;
571
-	}
572
-
573
-	/**
574
-	 * @return \OC\Files\Mount\Manager
575
-	 */
576
-	public function getMountManager() {
577
-		return $this->mountManager;
578
-	}
579
-
580
-	/**
581
-	 * @param string $source
582
-	 * @param string $target
583
-	 * @return bool
584
-	 */
585
-	public function setMountPoint($source, $target) {
586
-		$source = $this->stripPath($source);
587
-		$target = $this->stripPath($target);
588
-		$sourceHash = md5($source);
589
-		$targetHash = md5($target);
590
-
591
-		$query = $this->connection->prepare('
400
+            $removeShare->execute([$id, $this->uid]);
401
+            $this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'decline');
402
+
403
+            $this->processNotification($id);
404
+            $result = true;
405
+        } elseif ($share && (int)$share['share_type'] === IShare::TYPE_GROUP) {
406
+            $parentId = (int)$share['parent'];
407
+            if ($parentId !== -1) {
408
+                // this is the sub-share
409
+                $subshare = $share;
410
+            } else {
411
+                $subshare = $this->fetchUserShare($id, $this->uid);
412
+            }
413
+
414
+            if ($subshare !== null) {
415
+                try {
416
+                    $this->updateAccepted((int)$subshare['id'], false);
417
+                    $result = true;
418
+                } catch (Exception $e) {
419
+                    $this->logger->emergency('Could not update share', ['exception' => $e]);
420
+                    $result = false;
421
+                }
422
+            } else {
423
+                try {
424
+                    $this->writeShareToDb(
425
+                        $share['remote'],
426
+                        $share['share_token'],
427
+                        $share['password'],
428
+                        $share['name'],
429
+                        $share['owner'],
430
+                        $this->uid,
431
+                        $share['mountpoint'],
432
+                        $share['mountpoint_hash'],
433
+                        0,
434
+                        $share['remote_id'],
435
+                        $id,
436
+                        $share['share_type']);
437
+                    $result = true;
438
+                } catch (Exception $e) {
439
+                    $this->logger->emergency('Could not create share', ['exception' => $e]);
440
+                    $result = false;
441
+                }
442
+            }
443
+            $this->processNotification($id);
444
+        }
445
+
446
+        return $result;
447
+    }
448
+
449
+    /**
450
+     * @param int $remoteShare
451
+     */
452
+    public function processNotification($remoteShare) {
453
+        $filter = $this->notificationManager->createNotification();
454
+        $filter->setApp('files_sharing')
455
+            ->setUser($this->uid)
456
+            ->setObject('remote_share', (int) $remoteShare);
457
+        $this->notificationManager->markProcessed($filter);
458
+    }
459
+
460
+    /**
461
+     * inform remote server whether server-to-server share was accepted/declined
462
+     *
463
+     * @param string $remote
464
+     * @param string $token
465
+     * @param string $remoteId Share id on the remote host
466
+     * @param string $feedback
467
+     * @return boolean
468
+     */
469
+    private function sendFeedbackToRemote($remote, $token, $remoteId, $feedback) {
470
+        $result = $this->tryOCMEndPoint($remote, $token, $remoteId, $feedback);
471
+
472
+        if (is_array($result)) {
473
+            return true;
474
+        }
475
+
476
+        $federationEndpoints = $this->discoveryService->discover($remote, 'FEDERATED_SHARING');
477
+        $endpoint = isset($federationEndpoints['share']) ? $federationEndpoints['share'] : '/ocs/v2.php/cloud/shares';
478
+
479
+        $url = rtrim($remote, '/') . $endpoint . '/' . $remoteId . '/' . $feedback . '?format=' . Share::RESPONSE_FORMAT;
480
+        $fields = ['token' => $token];
481
+
482
+        $client = $this->clientService->newClient();
483
+
484
+        try {
485
+            $response = $client->post(
486
+                $url,
487
+                [
488
+                    'body' => $fields,
489
+                    'connect_timeout' => 10,
490
+                ]
491
+            );
492
+        } catch (\Exception $e) {
493
+            return false;
494
+        }
495
+
496
+        $status = json_decode($response->getBody(), true);
497
+
498
+        return ($status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200);
499
+    }
500
+
501
+    /**
502
+     * try send accept message to ocm end-point
503
+     *
504
+     * @param string $remoteDomain
505
+     * @param string $token
506
+     * @param string $remoteId id of the share
507
+     * @param string $feedback
508
+     * @return array|false
509
+     */
510
+    protected function tryOCMEndPoint($remoteDomain, $token, $remoteId, $feedback) {
511
+        switch ($feedback) {
512
+            case 'accept':
513
+                $notification = $this->cloudFederationFactory->getCloudFederationNotification();
514
+                $notification->setMessage(
515
+                    'SHARE_ACCEPTED',
516
+                    'file',
517
+                    $remoteId,
518
+                    [
519
+                        'sharedSecret' => $token,
520
+                        'message' => 'Recipient accept the share'
521
+                    ]
522
+
523
+                );
524
+                return $this->cloudFederationProviderManager->sendNotification($remoteDomain, $notification);
525
+            case 'decline':
526
+                $notification = $this->cloudFederationFactory->getCloudFederationNotification();
527
+                $notification->setMessage(
528
+                    'SHARE_DECLINED',
529
+                    'file',
530
+                    $remoteId,
531
+                    [
532
+                        'sharedSecret' => $token,
533
+                        'message' => 'Recipient declined the share'
534
+                    ]
535
+
536
+                );
537
+                return $this->cloudFederationProviderManager->sendNotification($remoteDomain, $notification);
538
+        }
539
+
540
+        return false;
541
+    }
542
+
543
+
544
+    /**
545
+     * remove '/user/files' from the path and trailing slashes
546
+     *
547
+     * @param string $path
548
+     * @return string
549
+     */
550
+    protected function stripPath($path) {
551
+        $prefix = '/' . $this->uid . '/files';
552
+        return rtrim(substr($path, strlen($prefix)), '/');
553
+    }
554
+
555
+    public function getMount($data) {
556
+        $data['manager'] = $this;
557
+        $mountPoint = '/' . $this->uid . '/files' . $data['mountpoint'];
558
+        $data['mountpoint'] = $mountPoint;
559
+        $data['certificateManager'] = \OC::$server->getCertificateManager();
560
+        return new Mount(self::STORAGE, $mountPoint, $data, $this, $this->storageLoader);
561
+    }
562
+
563
+    /**
564
+     * @param array $data
565
+     * @return Mount
566
+     */
567
+    protected function mountShare($data) {
568
+        $mount = $this->getMount($data);
569
+        $this->mountManager->addMount($mount);
570
+        return $mount;
571
+    }
572
+
573
+    /**
574
+     * @return \OC\Files\Mount\Manager
575
+     */
576
+    public function getMountManager() {
577
+        return $this->mountManager;
578
+    }
579
+
580
+    /**
581
+     * @param string $source
582
+     * @param string $target
583
+     * @return bool
584
+     */
585
+    public function setMountPoint($source, $target) {
586
+        $source = $this->stripPath($source);
587
+        $target = $this->stripPath($target);
588
+        $sourceHash = md5($source);
589
+        $targetHash = md5($target);
590
+
591
+        $query = $this->connection->prepare('
592 592
 			UPDATE `*PREFIX*share_external`
593 593
 			SET `mountpoint` = ?, `mountpoint_hash` = ?
594 594
 			WHERE `mountpoint_hash` = ?
595 595
 			AND `user` = ?
596 596
 		');
597
-		$result = (bool)$query->execute([$target, $targetHash, $sourceHash, $this->uid]);
597
+        $result = (bool)$query->execute([$target, $targetHash, $sourceHash, $this->uid]);
598 598
 
599
-		return $result;
600
-	}
599
+        return $result;
600
+    }
601 601
 
602
-	public function removeShare($mountPoint): bool {
603
-		try {
604
-			$mountPointObj = $this->mountManager->find($mountPoint);
605
-		} catch (NotFoundException $e) {
606
-			$this->logger->error('Mount point to remove share not found', ['mountPoint' => $mountPoint]);
607
-			return false;
608
-		}
609
-		$id = $mountPointObj->getStorage()->getCache()->getId('');
602
+    public function removeShare($mountPoint): bool {
603
+        try {
604
+            $mountPointObj = $this->mountManager->find($mountPoint);
605
+        } catch (NotFoundException $e) {
606
+            $this->logger->error('Mount point to remove share not found', ['mountPoint' => $mountPoint]);
607
+            return false;
608
+        }
609
+        $id = $mountPointObj->getStorage()->getCache()->getId('');
610 610
 
611
-		$mountPoint = $this->stripPath($mountPoint);
612
-		$hash = md5($mountPoint);
611
+        $mountPoint = $this->stripPath($mountPoint);
612
+        $hash = md5($mountPoint);
613 613
 
614
-		try {
615
-			$getShare = $this->connection->prepare('
614
+        try {
615
+            $getShare = $this->connection->prepare('
616 616
 				SELECT `remote`, `share_token`, `remote_id`, `share_type`, `id`
617 617
 				FROM  `*PREFIX*share_external`
618 618
 				WHERE `mountpoint_hash` = ? AND `user` = ?');
619
-			$result = $getShare->execute([$hash, $this->uid]);
620
-			$share = $result->fetch();
621
-			$result->closeCursor();
622
-			if ($share !== false && (int)$share['share_type'] === IShare::TYPE_USER) {
623
-				try {
624
-					$this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'decline');
625
-				} catch (\Throwable $e) {
626
-					// if we fail to notify the remote (probably cause the remote is down)
627
-					// we still want the share to be gone to prevent undeletable remotes
628
-				}
629
-
630
-				$query = $this->connection->prepare('
619
+            $result = $getShare->execute([$hash, $this->uid]);
620
+            $share = $result->fetch();
621
+            $result->closeCursor();
622
+            if ($share !== false && (int)$share['share_type'] === IShare::TYPE_USER) {
623
+                try {
624
+                    $this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'decline');
625
+                } catch (\Throwable $e) {
626
+                    // if we fail to notify the remote (probably cause the remote is down)
627
+                    // we still want the share to be gone to prevent undeletable remotes
628
+                }
629
+
630
+                $query = $this->connection->prepare('
631 631
 					DELETE FROM `*PREFIX*share_external`
632 632
 					WHERE `id` = ?
633 633
 				');
634
-				$deleteResult = $query->execute([(int)$share['id']]);
635
-				$deleteResult->closeCursor();
636
-			} elseif ($share !== false && (int)$share['share_type'] === IShare::TYPE_GROUP) {
637
-				$this->updateAccepted((int)$share['id'], false);
638
-			}
639
-
640
-			$this->removeReShares($id);
641
-		} catch (\Doctrine\DBAL\Exception $ex) {
642
-			$this->logger->emergency('Could not update share', ['exception' => $ex]);
643
-			return false;
644
-		}
645
-
646
-		return true;
647
-	}
648
-
649
-	/**
650
-	 * remove re-shares from share table and mapping in the federated_reshares table
651
-	 *
652
-	 * @param $mountPointId
653
-	 */
654
-	protected function removeReShares($mountPointId) {
655
-		$selectQuery = $this->connection->getQueryBuilder();
656
-		$query = $this->connection->getQueryBuilder();
657
-		$selectQuery->select('id')->from('share')
658
-			->where($selectQuery->expr()->eq('file_source', $query->createNamedParameter($mountPointId)));
659
-		$select = $selectQuery->getSQL();
660
-
661
-
662
-		$query->delete('federated_reshares')
663
-			->where($query->expr()->in('share_id', $query->createFunction('(' . $select . ')')));
664
-		$query->execute();
665
-
666
-		$deleteReShares = $this->connection->getQueryBuilder();
667
-		$deleteReShares->delete('share')
668
-			->where($deleteReShares->expr()->eq('file_source', $deleteReShares->createNamedParameter($mountPointId)));
669
-		$deleteReShares->execute();
670
-	}
671
-
672
-	/**
673
-	 * remove all shares for user $uid if the user was deleted
674
-	 *
675
-	 * @param string $uid
676
-	 */
677
-	public function removeUserShares($uid): bool {
678
-		try {
679
-			// TODO: use query builder
680
-			$getShare = $this->connection->prepare('
634
+                $deleteResult = $query->execute([(int)$share['id']]);
635
+                $deleteResult->closeCursor();
636
+            } elseif ($share !== false && (int)$share['share_type'] === IShare::TYPE_GROUP) {
637
+                $this->updateAccepted((int)$share['id'], false);
638
+            }
639
+
640
+            $this->removeReShares($id);
641
+        } catch (\Doctrine\DBAL\Exception $ex) {
642
+            $this->logger->emergency('Could not update share', ['exception' => $ex]);
643
+            return false;
644
+        }
645
+
646
+        return true;
647
+    }
648
+
649
+    /**
650
+     * remove re-shares from share table and mapping in the federated_reshares table
651
+     *
652
+     * @param $mountPointId
653
+     */
654
+    protected function removeReShares($mountPointId) {
655
+        $selectQuery = $this->connection->getQueryBuilder();
656
+        $query = $this->connection->getQueryBuilder();
657
+        $selectQuery->select('id')->from('share')
658
+            ->where($selectQuery->expr()->eq('file_source', $query->createNamedParameter($mountPointId)));
659
+        $select = $selectQuery->getSQL();
660
+
661
+
662
+        $query->delete('federated_reshares')
663
+            ->where($query->expr()->in('share_id', $query->createFunction('(' . $select . ')')));
664
+        $query->execute();
665
+
666
+        $deleteReShares = $this->connection->getQueryBuilder();
667
+        $deleteReShares->delete('share')
668
+            ->where($deleteReShares->expr()->eq('file_source', $deleteReShares->createNamedParameter($mountPointId)));
669
+        $deleteReShares->execute();
670
+    }
671
+
672
+    /**
673
+     * remove all shares for user $uid if the user was deleted
674
+     *
675
+     * @param string $uid
676
+     */
677
+    public function removeUserShares($uid): bool {
678
+        try {
679
+            // TODO: use query builder
680
+            $getShare = $this->connection->prepare('
681 681
 				SELECT `id`, `remote`, `share_type`, `share_token`, `remote_id`
682 682
 				FROM  `*PREFIX*share_external`
683 683
 				WHERE `user` = ?
684 684
 				AND `share_type` = ?');
685
-			$result = $getShare->execute([$uid, IShare::TYPE_USER]);
686
-			$shares = $result->fetchAll();
687
-			$result->closeCursor();
688
-
689
-			foreach ($shares as $share) {
690
-				$this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'decline');
691
-			}
692
-
693
-			$qb = $this->connection->getQueryBuilder();
694
-			$qb->delete('share_external')
695
-				// user field can specify a user or a group
696
-				->where($qb->expr()->eq('user', $qb->createNamedParameter($uid)))
697
-				->andWhere(
698
-					$qb->expr()->orX(
699
-						// delete direct shares
700
-						$qb->expr()->eq('share_type', $qb->expr()->literal(IShare::TYPE_USER)),
701
-						// delete sub-shares of group shares for that user
702
-						$qb->expr()->andX(
703
-							$qb->expr()->eq('share_type', $qb->expr()->literal(IShare::TYPE_GROUP)),
704
-							$qb->expr()->neq('parent', $qb->expr()->literal(-1)),
705
-						)
706
-					)
707
-				);
708
-			$qb->execute();
709
-		} catch (\Doctrine\DBAL\Exception $ex) {
710
-			$this->logger->emergency('Could not delete user shares', ['exception' => $ex]);
711
-			return false;
712
-		}
713
-
714
-		return true;
715
-	}
716
-
717
-	public function removeGroupShares($gid): bool {
718
-		try {
719
-			$getShare = $this->connection->prepare('
685
+            $result = $getShare->execute([$uid, IShare::TYPE_USER]);
686
+            $shares = $result->fetchAll();
687
+            $result->closeCursor();
688
+
689
+            foreach ($shares as $share) {
690
+                $this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'decline');
691
+            }
692
+
693
+            $qb = $this->connection->getQueryBuilder();
694
+            $qb->delete('share_external')
695
+                // user field can specify a user or a group
696
+                ->where($qb->expr()->eq('user', $qb->createNamedParameter($uid)))
697
+                ->andWhere(
698
+                    $qb->expr()->orX(
699
+                        // delete direct shares
700
+                        $qb->expr()->eq('share_type', $qb->expr()->literal(IShare::TYPE_USER)),
701
+                        // delete sub-shares of group shares for that user
702
+                        $qb->expr()->andX(
703
+                            $qb->expr()->eq('share_type', $qb->expr()->literal(IShare::TYPE_GROUP)),
704
+                            $qb->expr()->neq('parent', $qb->expr()->literal(-1)),
705
+                        )
706
+                    )
707
+                );
708
+            $qb->execute();
709
+        } catch (\Doctrine\DBAL\Exception $ex) {
710
+            $this->logger->emergency('Could not delete user shares', ['exception' => $ex]);
711
+            return false;
712
+        }
713
+
714
+        return true;
715
+    }
716
+
717
+    public function removeGroupShares($gid): bool {
718
+        try {
719
+            $getShare = $this->connection->prepare('
720 720
 				SELECT `id`, `remote`, `share_type`, `share_token`, `remote_id`
721 721
 				FROM  `*PREFIX*share_external`
722 722
 				WHERE `user` = ?
723 723
 				AND `share_type` = ?');
724
-			$result = $getShare->execute([$gid, IShare::TYPE_GROUP]);
725
-			$shares = $result->fetchAll();
726
-			$result->closeCursor();
727
-
728
-			$deletedGroupShares = [];
729
-			$qb = $this->connection->getQueryBuilder();
730
-			// delete group share entry and matching sub-entries
731
-			$qb->delete('share_external')
732
-			   ->where(
733
-				   $qb->expr()->orX(
734
-					   $qb->expr()->eq('id', $qb->createParameter('share_id')),
735
-					   $qb->expr()->eq('parent', $qb->createParameter('share_parent_id'))
736
-				   )
737
-			   );
738
-
739
-			foreach ($shares as $share) {
740
-				$qb->setParameter('share_id', $share['id']);
741
-				$qb->setParameter('share_parent_id', $share['id']);
742
-				$qb->execute();
743
-			}
744
-		} catch (\Doctrine\DBAL\Exception $ex) {
745
-			$this->logger->emergency('Could not delete user shares', ['exception' => $ex]);
746
-			return false;
747
-		}
748
-
749
-		return true;
750
-	}
751
-
752
-	/**
753
-	 * return a list of shares which are not yet accepted by the user
754
-	 *
755
-	 * @return array list of open server-to-server shares
756
-	 */
757
-	public function getOpenShares() {
758
-		return $this->getShares(false);
759
-	}
760
-
761
-	/**
762
-	 * return a list of shares which are accepted by the user
763
-	 *
764
-	 * @return array list of accepted server-to-server shares
765
-	 */
766
-	public function getAcceptedShares() {
767
-		return $this->getShares(true);
768
-	}
769
-
770
-	/**
771
-	 * return a list of shares for the user
772
-	 *
773
-	 * @param bool|null $accepted True for accepted only,
774
-	 *                            false for not accepted,
775
-	 *                            null for all shares of the user
776
-	 * @return array list of open server-to-server shares
777
-	 */
778
-	private function getShares($accepted) {
779
-		$user = $this->userManager->get($this->uid);
780
-		$groups = $this->groupManager->getUserGroups($user);
781
-		$userGroups = [];
782
-		foreach ($groups as $group) {
783
-			$userGroups[] = $group->getGID();
784
-		}
785
-
786
-		$qb = $this->connection->getQueryBuilder();
787
-		$qb->select('id', 'share_type', 'parent', 'remote', 'remote_id', 'share_token', 'name', 'owner', 'user', 'mountpoint', 'accepted')
788
-			->from('share_external')
789
-			->where(
790
-				$qb->expr()->orX(
791
-					$qb->expr()->eq('user', $qb->createNamedParameter($this->uid)),
792
-					$qb->expr()->in(
793
-						'user',
794
-						$qb->createNamedParameter($userGroups, IQueryBuilder::PARAM_STR_ARRAY)
795
-					)
796
-				)
797
-			)
798
-			->orderBy('id', 'ASC');
799
-
800
-		try {
801
-			$result = $qb->execute();
802
-			$shares = $result->fetchAll();
803
-			$result->closeCursor();
804
-
805
-			// remove parent group share entry if we have a specific user share entry for the user
806
-			$toRemove = [];
807
-			foreach ($shares as $share) {
808
-				if ((int)$share['share_type'] === IShare::TYPE_GROUP && (int)$share['parent'] > 0) {
809
-					$toRemove[] = $share['parent'];
810
-				}
811
-			}
812
-			$shares = array_filter($shares, function ($share) use ($toRemove) {
813
-				return !in_array($share['id'], $toRemove, true);
814
-			});
815
-
816
-			if (!is_null($accepted)) {
817
-				$shares = array_filter($shares, function ($share) use ($accepted) {
818
-					return (bool)$share['accepted'] === $accepted;
819
-				});
820
-			}
821
-			return array_values($shares);
822
-		} catch (\Doctrine\DBAL\Exception $e) {
823
-			$this->logger->emergency('Error when retrieving shares', ['exception' => $e]);
824
-			return [];
825
-		}
826
-	}
724
+            $result = $getShare->execute([$gid, IShare::TYPE_GROUP]);
725
+            $shares = $result->fetchAll();
726
+            $result->closeCursor();
727
+
728
+            $deletedGroupShares = [];
729
+            $qb = $this->connection->getQueryBuilder();
730
+            // delete group share entry and matching sub-entries
731
+            $qb->delete('share_external')
732
+                ->where(
733
+                    $qb->expr()->orX(
734
+                        $qb->expr()->eq('id', $qb->createParameter('share_id')),
735
+                        $qb->expr()->eq('parent', $qb->createParameter('share_parent_id'))
736
+                    )
737
+                );
738
+
739
+            foreach ($shares as $share) {
740
+                $qb->setParameter('share_id', $share['id']);
741
+                $qb->setParameter('share_parent_id', $share['id']);
742
+                $qb->execute();
743
+            }
744
+        } catch (\Doctrine\DBAL\Exception $ex) {
745
+            $this->logger->emergency('Could not delete user shares', ['exception' => $ex]);
746
+            return false;
747
+        }
748
+
749
+        return true;
750
+    }
751
+
752
+    /**
753
+     * return a list of shares which are not yet accepted by the user
754
+     *
755
+     * @return array list of open server-to-server shares
756
+     */
757
+    public function getOpenShares() {
758
+        return $this->getShares(false);
759
+    }
760
+
761
+    /**
762
+     * return a list of shares which are accepted by the user
763
+     *
764
+     * @return array list of accepted server-to-server shares
765
+     */
766
+    public function getAcceptedShares() {
767
+        return $this->getShares(true);
768
+    }
769
+
770
+    /**
771
+     * return a list of shares for the user
772
+     *
773
+     * @param bool|null $accepted True for accepted only,
774
+     *                            false for not accepted,
775
+     *                            null for all shares of the user
776
+     * @return array list of open server-to-server shares
777
+     */
778
+    private function getShares($accepted) {
779
+        $user = $this->userManager->get($this->uid);
780
+        $groups = $this->groupManager->getUserGroups($user);
781
+        $userGroups = [];
782
+        foreach ($groups as $group) {
783
+            $userGroups[] = $group->getGID();
784
+        }
785
+
786
+        $qb = $this->connection->getQueryBuilder();
787
+        $qb->select('id', 'share_type', 'parent', 'remote', 'remote_id', 'share_token', 'name', 'owner', 'user', 'mountpoint', 'accepted')
788
+            ->from('share_external')
789
+            ->where(
790
+                $qb->expr()->orX(
791
+                    $qb->expr()->eq('user', $qb->createNamedParameter($this->uid)),
792
+                    $qb->expr()->in(
793
+                        'user',
794
+                        $qb->createNamedParameter($userGroups, IQueryBuilder::PARAM_STR_ARRAY)
795
+                    )
796
+                )
797
+            )
798
+            ->orderBy('id', 'ASC');
799
+
800
+        try {
801
+            $result = $qb->execute();
802
+            $shares = $result->fetchAll();
803
+            $result->closeCursor();
804
+
805
+            // remove parent group share entry if we have a specific user share entry for the user
806
+            $toRemove = [];
807
+            foreach ($shares as $share) {
808
+                if ((int)$share['share_type'] === IShare::TYPE_GROUP && (int)$share['parent'] > 0) {
809
+                    $toRemove[] = $share['parent'];
810
+                }
811
+            }
812
+            $shares = array_filter($shares, function ($share) use ($toRemove) {
813
+                return !in_array($share['id'], $toRemove, true);
814
+            });
815
+
816
+            if (!is_null($accepted)) {
817
+                $shares = array_filter($shares, function ($share) use ($accepted) {
818
+                    return (bool)$share['accepted'] === $accepted;
819
+                });
820
+            }
821
+            return array_values($shares);
822
+        } catch (\Doctrine\DBAL\Exception $e) {
823
+            $this->logger->emergency('Error when retrieving shares', ['exception' => $e]);
824
+            return [];
825
+        }
826
+    }
827 827
 }
Please login to merge, or discard this patch.
apps/files_sharing/lib/Updater.php 2 patches
Indentation   +71 added lines, -71 removed lines patch added patch discarded remove patch
@@ -32,86 +32,86 @@
 block discarded – undo
32 32
 
33 33
 class Updater {
34 34
 
35
-	/**
36
-	 * @param array $params
37
-	 */
38
-	public static function renameHook($params) {
39
-		self::renameChildren($params['oldpath'], $params['newpath']);
40
-		self::moveShareToShare($params['newpath']);
41
-	}
35
+    /**
36
+     * @param array $params
37
+     */
38
+    public static function renameHook($params) {
39
+        self::renameChildren($params['oldpath'], $params['newpath']);
40
+        self::moveShareToShare($params['newpath']);
41
+    }
42 42
 
43
-	/**
44
-	 * Fix for https://github.com/owncloud/core/issues/20769
45
-	 *
46
-	 * The owner is allowed to move their files (if they are shared) into a receiving folder
47
-	 * In this case we need to update the parent of the moved share. Since they are
48
-	 * effectively handing over ownership of the file the rest of the code needs to know
49
-	 * they need to build up the reshare tree.
50
-	 *
51
-	 * @param string $path
52
-	 */
53
-	private static function moveShareToShare($path) {
54
-		$userFolder = \OC::$server->getUserFolder();
43
+    /**
44
+     * Fix for https://github.com/owncloud/core/issues/20769
45
+     *
46
+     * The owner is allowed to move their files (if they are shared) into a receiving folder
47
+     * In this case we need to update the parent of the moved share. Since they are
48
+     * effectively handing over ownership of the file the rest of the code needs to know
49
+     * they need to build up the reshare tree.
50
+     *
51
+     * @param string $path
52
+     */
53
+    private static function moveShareToShare($path) {
54
+        $userFolder = \OC::$server->getUserFolder();
55 55
 
56
-		// If the user folder can't be constructed (e.g. link share) just return.
57
-		if ($userFolder === null) {
58
-			return;
59
-		}
56
+        // If the user folder can't be constructed (e.g. link share) just return.
57
+        if ($userFolder === null) {
58
+            return;
59
+        }
60 60
 
61
-		$src = $userFolder->get($path);
61
+        $src = $userFolder->get($path);
62 62
 
63
-		$shareManager = \OC::$server->getShareManager();
63
+        $shareManager = \OC::$server->getShareManager();
64 64
 
65
-		$shares = $shareManager->getSharesBy($userFolder->getOwner()->getUID(), IShare::TYPE_USER, $src, false, -1);
66
-		$shares = array_merge($shares, $shareManager->getSharesBy($userFolder->getOwner()->getUID(), IShare::TYPE_GROUP, $src, false, -1));
67
-		$shares = array_merge($shares, $shareManager->getSharesBy($userFolder->getOwner()->getUID(), IShare::TYPE_ROOM, $src, false, -1));
65
+        $shares = $shareManager->getSharesBy($userFolder->getOwner()->getUID(), IShare::TYPE_USER, $src, false, -1);
66
+        $shares = array_merge($shares, $shareManager->getSharesBy($userFolder->getOwner()->getUID(), IShare::TYPE_GROUP, $src, false, -1));
67
+        $shares = array_merge($shares, $shareManager->getSharesBy($userFolder->getOwner()->getUID(), IShare::TYPE_ROOM, $src, false, -1));
68 68
 
69
-		// If the path we move is not a share we don't care
70
-		if (empty($shares)) {
71
-			return;
72
-		}
69
+        // If the path we move is not a share we don't care
70
+        if (empty($shares)) {
71
+            return;
72
+        }
73 73
 
74
-		// Check if the destination is inside a share
75
-		$mountManager = \OC::$server->getMountManager();
76
-		$dstMount = $mountManager->find($src->getPath());
77
-		if (!($dstMount instanceof \OCA\Files_Sharing\SharedMount)) {
78
-			return;
79
-		}
74
+        // Check if the destination is inside a share
75
+        $mountManager = \OC::$server->getMountManager();
76
+        $dstMount = $mountManager->find($src->getPath());
77
+        if (!($dstMount instanceof \OCA\Files_Sharing\SharedMount)) {
78
+            return;
79
+        }
80 80
 
81
-		$newOwner = $dstMount->getShare()->getShareOwner();
81
+        $newOwner = $dstMount->getShare()->getShareOwner();
82 82
 
83
-		//Ownership is moved over
84
-		foreach ($shares as $share) {
85
-			/** @var IShare $share */
86
-			if (!($dstMount->getShare()->getPermissions() & Constants::PERMISSION_SHARE)) {
87
-				$shareManager->deleteShare($share);
88
-				continue;
89
-			}
90
-			$share->setShareOwner($newOwner);
91
-			$share->setPermissions($share->getPermissions() & $dstMount->getShare()->getPermissions());
92
-			$shareManager->updateShare($share);
93
-		}
94
-	}
83
+        //Ownership is moved over
84
+        foreach ($shares as $share) {
85
+            /** @var IShare $share */
86
+            if (!($dstMount->getShare()->getPermissions() & Constants::PERMISSION_SHARE)) {
87
+                $shareManager->deleteShare($share);
88
+                continue;
89
+            }
90
+            $share->setShareOwner($newOwner);
91
+            $share->setPermissions($share->getPermissions() & $dstMount->getShare()->getPermissions());
92
+            $shareManager->updateShare($share);
93
+        }
94
+    }
95 95
 
96
-	/**
97
-	 * rename mount point from the children if the parent was renamed
98
-	 *
99
-	 * @param string $oldPath old path relative to data/user/files
100
-	 * @param string $newPath new path relative to data/user/files
101
-	 */
102
-	private static function renameChildren($oldPath, $newPath) {
103
-		$absNewPath = \OC\Files\Filesystem::normalizePath('/' . \OC_User::getUser() . '/files/' . $newPath);
104
-		$absOldPath = \OC\Files\Filesystem::normalizePath('/' . \OC_User::getUser() . '/files/' . $oldPath);
96
+    /**
97
+     * rename mount point from the children if the parent was renamed
98
+     *
99
+     * @param string $oldPath old path relative to data/user/files
100
+     * @param string $newPath new path relative to data/user/files
101
+     */
102
+    private static function renameChildren($oldPath, $newPath) {
103
+        $absNewPath = \OC\Files\Filesystem::normalizePath('/' . \OC_User::getUser() . '/files/' . $newPath);
104
+        $absOldPath = \OC\Files\Filesystem::normalizePath('/' . \OC_User::getUser() . '/files/' . $oldPath);
105 105
 
106
-		$mountManager = \OC\Files\Filesystem::getMountManager();
107
-		$mountedShares = $mountManager->findIn('/' . \OC_User::getUser() . '/files/' . $oldPath);
108
-		foreach ($mountedShares as $mount) {
109
-			/** @var MountPoint $mount */
110
-			if ($mount->getStorage()->instanceOfStorage(ISharedStorage::class)) {
111
-				$mountPoint = $mount->getMountPoint();
112
-				$target = str_replace($absOldPath, $absNewPath, $mountPoint);
113
-				$mount->moveMount($target);
114
-			}
115
-		}
116
-	}
106
+        $mountManager = \OC\Files\Filesystem::getMountManager();
107
+        $mountedShares = $mountManager->findIn('/' . \OC_User::getUser() . '/files/' . $oldPath);
108
+        foreach ($mountedShares as $mount) {
109
+            /** @var MountPoint $mount */
110
+            if ($mount->getStorage()->instanceOfStorage(ISharedStorage::class)) {
111
+                $mountPoint = $mount->getMountPoint();
112
+                $target = str_replace($absOldPath, $absNewPath, $mountPoint);
113
+                $mount->moveMount($target);
114
+            }
115
+        }
116
+    }
117 117
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -100,11 +100,11 @@
 block discarded – undo
100 100
 	 * @param string $newPath new path relative to data/user/files
101 101
 	 */
102 102
 	private static function renameChildren($oldPath, $newPath) {
103
-		$absNewPath = \OC\Files\Filesystem::normalizePath('/' . \OC_User::getUser() . '/files/' . $newPath);
104
-		$absOldPath = \OC\Files\Filesystem::normalizePath('/' . \OC_User::getUser() . '/files/' . $oldPath);
103
+		$absNewPath = \OC\Files\Filesystem::normalizePath('/'.\OC_User::getUser().'/files/'.$newPath);
104
+		$absOldPath = \OC\Files\Filesystem::normalizePath('/'.\OC_User::getUser().'/files/'.$oldPath);
105 105
 
106 106
 		$mountManager = \OC\Files\Filesystem::getMountManager();
107
-		$mountedShares = $mountManager->findIn('/' . \OC_User::getUser() . '/files/' . $oldPath);
107
+		$mountedShares = $mountManager->findIn('/'.\OC_User::getUser().'/files/'.$oldPath);
108 108
 		foreach ($mountedShares as $mount) {
109 109
 			/** @var MountPoint $mount */
110 110
 			if ($mount->getStorage()->instanceOfStorage(ISharedStorage::class)) {
Please login to merge, or discard this patch.