Passed
Push — master ( d98bd1...667552 )
by Roeland
12:35 queued 11s
created
lib/public/Files/Config/IMountProviderCollection.php 1 patch
Indentation   +51 added lines, -51 removed lines patch added patch discarded remove patch
@@ -30,61 +30,61 @@
 block discarded – undo
30 30
  * @since 8.0.0
31 31
  */
32 32
 interface IMountProviderCollection {
33
-	/**
34
-	 * Get all configured mount points for the user
35
-	 *
36
-	 * @param \OCP\IUser $user
37
-	 * @return \OCP\Files\Mount\IMountPoint[]
38
-	 * @since 8.0.0
39
-	 */
40
-	public function getMountsForUser(IUser $user);
33
+    /**
34
+     * Get all configured mount points for the user
35
+     *
36
+     * @param \OCP\IUser $user
37
+     * @return \OCP\Files\Mount\IMountPoint[]
38
+     * @since 8.0.0
39
+     */
40
+    public function getMountsForUser(IUser $user);
41 41
 
42
-	/**
43
-	 * Get the configured home mount for this user
44
-	 *
45
-	 * @param \OCP\IUser $user
46
-	 * @return \OCP\Files\Mount\IMountPoint
47
-	 * @since 9.1.0
48
-	 */
49
-	public function getHomeMountForUser(IUser $user);
42
+    /**
43
+     * Get the configured home mount for this user
44
+     *
45
+     * @param \OCP\IUser $user
46
+     * @return \OCP\Files\Mount\IMountPoint
47
+     * @since 9.1.0
48
+     */
49
+    public function getHomeMountForUser(IUser $user);
50 50
 
51
-	/**
52
-	 * Add a provider for mount points
53
-	 *
54
-	 * @param \OCP\Files\Config\IMountProvider $provider
55
-	 * @since 8.0.0
56
-	 */
57
-	public function registerProvider(IMountProvider $provider);
51
+    /**
52
+     * Add a provider for mount points
53
+     *
54
+     * @param \OCP\Files\Config\IMountProvider $provider
55
+     * @since 8.0.0
56
+     */
57
+    public function registerProvider(IMountProvider $provider);
58 58
 
59
-	/**
60
-	 * Add a filter for mounts
61
-	 *
62
-	 * @param callable $filter (IMountPoint $mountPoint, IUser $user) => boolean
63
-	 * @since 14.0.0
64
-	 */
65
-	public function registerMountFilter(callable $filter);
59
+    /**
60
+     * Add a filter for mounts
61
+     *
62
+     * @param callable $filter (IMountPoint $mountPoint, IUser $user) => boolean
63
+     * @since 14.0.0
64
+     */
65
+    public function registerMountFilter(callable $filter);
66 66
 
67
-	/**
68
-	 * Add a provider for home mount points
69
-	 *
70
-	 * @param \OCP\Files\Config\IHomeMountProvider $provider
71
-	 * @since 9.1.0
72
-	 */
73
-	public function registerHomeProvider(IHomeMountProvider $provider);
67
+    /**
68
+     * Add a provider for home mount points
69
+     *
70
+     * @param \OCP\Files\Config\IHomeMountProvider $provider
71
+     * @since 9.1.0
72
+     */
73
+    public function registerHomeProvider(IHomeMountProvider $provider);
74 74
 
75
-	/**
76
-	 * Get the mount cache which can be used to search for mounts without setting up the filesystem
77
-	 *
78
-	 * @return IUserMountCache
79
-	 * @since 9.0.0
80
-	 */
81
-	public function getMountCache();
75
+    /**
76
+     * Get the mount cache which can be used to search for mounts without setting up the filesystem
77
+     *
78
+     * @return IUserMountCache
79
+     * @since 9.0.0
80
+     */
81
+    public function getMountCache();
82 82
 
83
-	/**
84
-	 * Get all root mountpoints
85
-	 *
86
-	 * @return \OCP\Files\Mount\IMountPoint[]
87
-	 * @since 20.0.0
88
-	 */
89
-	public function getRootMounts(): array;
83
+    /**
84
+     * Get all root mountpoints
85
+     *
86
+     * @return \OCP\Files\Mount\IMountPoint[]
87
+     * @since 20.0.0
88
+     */
89
+    public function getRootMounts(): array;
90 90
 }
Please login to merge, or discard this patch.
lib/public/Files/Config/IRootMountProvider.php 1 patch
Indentation   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -31,11 +31,11 @@
 block discarded – undo
31 31
  * @since 20.0.0
32 32
  */
33 33
 interface IRootMountProvider {
34
-	/**
35
-	 * Get all root mountpoints of this provider
36
-	 *
37
-	 * @return \OCP\Files\Mount\IMountPoint[]
38
-	 * @since 20.0.0
39
-	 */
40
-	public function getRootMounts(IStorageFactory $loader): array;
34
+    /**
35
+     * Get all root mountpoints of this provider
36
+     *
37
+     * @return \OCP\Files\Mount\IMountPoint[]
38
+     * @since 20.0.0
39
+     */
40
+    public function getRootMounts(IStorageFactory $loader): array;
41 41
 }
Please login to merge, or discard this patch.
lib/private/Files/Config/MountProviderCollection.php 2 patches
Indentation   +185 added lines, -185 removed lines patch added patch discarded remove patch
@@ -38,189 +38,189 @@
 block discarded – undo
38 38
 use OCP\IUser;
39 39
 
40 40
 class MountProviderCollection implements IMountProviderCollection, Emitter {
41
-	use EmitterTrait;
42
-
43
-	/**
44
-	 * @var \OCP\Files\Config\IHomeMountProvider[]
45
-	 */
46
-	private $homeProviders = [];
47
-
48
-	/**
49
-	 * @var \OCP\Files\Config\IMountProvider[]
50
-	 */
51
-	private $providers = [];
52
-
53
-	/** @var \OCP\Files\Config\IRootMountProvider[] */
54
-	private $rootProviders = [];
55
-
56
-	/**
57
-	 * @var \OCP\Files\Storage\IStorageFactory
58
-	 */
59
-	private $loader;
60
-
61
-	/**
62
-	 * @var \OCP\Files\Config\IUserMountCache
63
-	 */
64
-	private $mountCache;
65
-
66
-	/** @var callable[] */
67
-	private $mountFilters = [];
68
-
69
-	/**
70
-	 * @param \OCP\Files\Storage\IStorageFactory $loader
71
-	 * @param IUserMountCache $mountCache
72
-	 */
73
-	public function __construct(IStorageFactory $loader, IUserMountCache $mountCache) {
74
-		$this->loader = $loader;
75
-		$this->mountCache = $mountCache;
76
-	}
77
-
78
-	/**
79
-	 * Get all configured mount points for the user
80
-	 *
81
-	 * @param \OCP\IUser $user
82
-	 * @return \OCP\Files\Mount\IMountPoint[]
83
-	 */
84
-	public function getMountsForUser(IUser $user) {
85
-		$loader = $this->loader;
86
-		$mounts = array_map(function (IMountProvider $provider) use ($user, $loader) {
87
-			return $provider->getMountsForUser($user, $loader);
88
-		}, $this->providers);
89
-		$mounts = array_filter($mounts, function ($result) {
90
-			return is_array($result);
91
-		});
92
-		$mounts = array_reduce($mounts, function (array $mounts, array $providerMounts) {
93
-			return array_merge($mounts, $providerMounts);
94
-		}, []);
95
-		return $this->filterMounts($user, $mounts);
96
-	}
97
-
98
-	public function addMountForUser(IUser $user, IMountManager $mountManager) {
99
-		// shared mount provider gets to go last since it needs to know existing files
100
-		// to check for name collisions
101
-		$firstMounts = [];
102
-		$firstProviders = array_filter($this->providers, function (IMountProvider $provider) {
103
-			return (get_class($provider) !== 'OCA\Files_Sharing\MountProvider');
104
-		});
105
-		$lastProviders = array_filter($this->providers, function (IMountProvider $provider) {
106
-			return (get_class($provider) === 'OCA\Files_Sharing\MountProvider');
107
-		});
108
-		foreach ($firstProviders as $provider) {
109
-			$mounts = $provider->getMountsForUser($user, $this->loader);
110
-			if (is_array($mounts)) {
111
-				$firstMounts = array_merge($firstMounts, $mounts);
112
-			}
113
-		}
114
-		$firstMounts = $this->filterMounts($user, $firstMounts);
115
-		array_walk($firstMounts, [$mountManager, 'addMount']);
116
-
117
-		$lateMounts = [];
118
-		foreach ($lastProviders as $provider) {
119
-			$mounts = $provider->getMountsForUser($user, $this->loader);
120
-			if (is_array($mounts)) {
121
-				$lateMounts = array_merge($lateMounts, $mounts);
122
-			}
123
-		}
124
-
125
-		$lateMounts = $this->filterMounts($user, $lateMounts);
126
-		array_walk($lateMounts, [$mountManager, 'addMount']);
127
-
128
-		return array_merge($lateMounts, $firstMounts);
129
-	}
130
-
131
-	/**
132
-	 * Get the configured home mount for this user
133
-	 *
134
-	 * @param \OCP\IUser $user
135
-	 * @return \OCP\Files\Mount\IMountPoint
136
-	 * @since 9.1.0
137
-	 */
138
-	public function getHomeMountForUser(IUser $user) {
139
-		/** @var \OCP\Files\Config\IHomeMountProvider[] $providers */
140
-		$providers = array_reverse($this->homeProviders); // call the latest registered provider first to give apps an opportunity to overwrite builtin
141
-		foreach ($providers as $homeProvider) {
142
-			if ($mount = $homeProvider->getHomeMountForUser($user, $this->loader)) {
143
-				$mount->setMountPoint('/' . $user->getUID()); //make sure the mountpoint is what we expect
144
-				return $mount;
145
-			}
146
-		}
147
-		throw new \Exception('No home storage configured for user ' . $user);
148
-	}
149
-
150
-	/**
151
-	 * Add a provider for mount points
152
-	 *
153
-	 * @param \OCP\Files\Config\IMountProvider $provider
154
-	 */
155
-	public function registerProvider(IMountProvider $provider) {
156
-		$this->providers[] = $provider;
157
-
158
-		$this->emit('\OC\Files\Config', 'registerMountProvider', [$provider]);
159
-	}
160
-
161
-	public function registerMountFilter(callable $filter) {
162
-		$this->mountFilters[] = $filter;
163
-	}
164
-
165
-	private function filterMounts(IUser $user, array $mountPoints) {
166
-		return array_filter($mountPoints, function (IMountPoint $mountPoint) use ($user) {
167
-			foreach ($this->mountFilters as $filter) {
168
-				if ($filter($mountPoint, $user) === false) {
169
-					return false;
170
-				}
171
-			}
172
-			return true;
173
-		});
174
-	}
175
-
176
-	/**
177
-	 * Add a provider for home mount points
178
-	 *
179
-	 * @param \OCP\Files\Config\IHomeMountProvider $provider
180
-	 * @since 9.1.0
181
-	 */
182
-	public function registerHomeProvider(IHomeMountProvider $provider) {
183
-		$this->homeProviders[] = $provider;
184
-		$this->emit('\OC\Files\Config', 'registerHomeMountProvider', [$provider]);
185
-	}
186
-
187
-	/**
188
-	 * Cache mounts for user
189
-	 *
190
-	 * @param IUser $user
191
-	 * @param IMountPoint[] $mountPoints
192
-	 */
193
-	public function registerMounts(IUser $user, array $mountPoints) {
194
-		$this->mountCache->registerMounts($user, $mountPoints);
195
-	}
196
-
197
-	/**
198
-	 * Get the mount cache which can be used to search for mounts without setting up the filesystem
199
-	 *
200
-	 * @return IUserMountCache
201
-	 */
202
-	public function getMountCache() {
203
-		return $this->mountCache;
204
-	}
205
-
206
-	public function registerRootProvider(IRootMountProvider $provider) {
207
-		$this->rootProviders[] = $provider;
208
-	}
209
-
210
-	/**
211
-	 * Get all root mountpoints
212
-	 *
213
-	 * @return \OCP\Files\Mount\IMountPoint[]
214
-	 * @since 20.0.0
215
-	 */
216
-	public function getRootMounts(): array {
217
-		$loader = $this->loader;
218
-		$mounts = array_map(function (IRootMountProvider $provider) use ($loader) {
219
-			return $provider->getRootMounts($loader);
220
-		}, $this->rootProviders);
221
-		$mounts = array_reduce($mounts, function (array $mounts, array $providerMounts) {
222
-			return array_merge($mounts, $providerMounts);
223
-		}, []);
224
-		return $mounts;
225
-	}
41
+    use EmitterTrait;
42
+
43
+    /**
44
+     * @var \OCP\Files\Config\IHomeMountProvider[]
45
+     */
46
+    private $homeProviders = [];
47
+
48
+    /**
49
+     * @var \OCP\Files\Config\IMountProvider[]
50
+     */
51
+    private $providers = [];
52
+
53
+    /** @var \OCP\Files\Config\IRootMountProvider[] */
54
+    private $rootProviders = [];
55
+
56
+    /**
57
+     * @var \OCP\Files\Storage\IStorageFactory
58
+     */
59
+    private $loader;
60
+
61
+    /**
62
+     * @var \OCP\Files\Config\IUserMountCache
63
+     */
64
+    private $mountCache;
65
+
66
+    /** @var callable[] */
67
+    private $mountFilters = [];
68
+
69
+    /**
70
+     * @param \OCP\Files\Storage\IStorageFactory $loader
71
+     * @param IUserMountCache $mountCache
72
+     */
73
+    public function __construct(IStorageFactory $loader, IUserMountCache $mountCache) {
74
+        $this->loader = $loader;
75
+        $this->mountCache = $mountCache;
76
+    }
77
+
78
+    /**
79
+     * Get all configured mount points for the user
80
+     *
81
+     * @param \OCP\IUser $user
82
+     * @return \OCP\Files\Mount\IMountPoint[]
83
+     */
84
+    public function getMountsForUser(IUser $user) {
85
+        $loader = $this->loader;
86
+        $mounts = array_map(function (IMountProvider $provider) use ($user, $loader) {
87
+            return $provider->getMountsForUser($user, $loader);
88
+        }, $this->providers);
89
+        $mounts = array_filter($mounts, function ($result) {
90
+            return is_array($result);
91
+        });
92
+        $mounts = array_reduce($mounts, function (array $mounts, array $providerMounts) {
93
+            return array_merge($mounts, $providerMounts);
94
+        }, []);
95
+        return $this->filterMounts($user, $mounts);
96
+    }
97
+
98
+    public function addMountForUser(IUser $user, IMountManager $mountManager) {
99
+        // shared mount provider gets to go last since it needs to know existing files
100
+        // to check for name collisions
101
+        $firstMounts = [];
102
+        $firstProviders = array_filter($this->providers, function (IMountProvider $provider) {
103
+            return (get_class($provider) !== 'OCA\Files_Sharing\MountProvider');
104
+        });
105
+        $lastProviders = array_filter($this->providers, function (IMountProvider $provider) {
106
+            return (get_class($provider) === 'OCA\Files_Sharing\MountProvider');
107
+        });
108
+        foreach ($firstProviders as $provider) {
109
+            $mounts = $provider->getMountsForUser($user, $this->loader);
110
+            if (is_array($mounts)) {
111
+                $firstMounts = array_merge($firstMounts, $mounts);
112
+            }
113
+        }
114
+        $firstMounts = $this->filterMounts($user, $firstMounts);
115
+        array_walk($firstMounts, [$mountManager, 'addMount']);
116
+
117
+        $lateMounts = [];
118
+        foreach ($lastProviders as $provider) {
119
+            $mounts = $provider->getMountsForUser($user, $this->loader);
120
+            if (is_array($mounts)) {
121
+                $lateMounts = array_merge($lateMounts, $mounts);
122
+            }
123
+        }
124
+
125
+        $lateMounts = $this->filterMounts($user, $lateMounts);
126
+        array_walk($lateMounts, [$mountManager, 'addMount']);
127
+
128
+        return array_merge($lateMounts, $firstMounts);
129
+    }
130
+
131
+    /**
132
+     * Get the configured home mount for this user
133
+     *
134
+     * @param \OCP\IUser $user
135
+     * @return \OCP\Files\Mount\IMountPoint
136
+     * @since 9.1.0
137
+     */
138
+    public function getHomeMountForUser(IUser $user) {
139
+        /** @var \OCP\Files\Config\IHomeMountProvider[] $providers */
140
+        $providers = array_reverse($this->homeProviders); // call the latest registered provider first to give apps an opportunity to overwrite builtin
141
+        foreach ($providers as $homeProvider) {
142
+            if ($mount = $homeProvider->getHomeMountForUser($user, $this->loader)) {
143
+                $mount->setMountPoint('/' . $user->getUID()); //make sure the mountpoint is what we expect
144
+                return $mount;
145
+            }
146
+        }
147
+        throw new \Exception('No home storage configured for user ' . $user);
148
+    }
149
+
150
+    /**
151
+     * Add a provider for mount points
152
+     *
153
+     * @param \OCP\Files\Config\IMountProvider $provider
154
+     */
155
+    public function registerProvider(IMountProvider $provider) {
156
+        $this->providers[] = $provider;
157
+
158
+        $this->emit('\OC\Files\Config', 'registerMountProvider', [$provider]);
159
+    }
160
+
161
+    public function registerMountFilter(callable $filter) {
162
+        $this->mountFilters[] = $filter;
163
+    }
164
+
165
+    private function filterMounts(IUser $user, array $mountPoints) {
166
+        return array_filter($mountPoints, function (IMountPoint $mountPoint) use ($user) {
167
+            foreach ($this->mountFilters as $filter) {
168
+                if ($filter($mountPoint, $user) === false) {
169
+                    return false;
170
+                }
171
+            }
172
+            return true;
173
+        });
174
+    }
175
+
176
+    /**
177
+     * Add a provider for home mount points
178
+     *
179
+     * @param \OCP\Files\Config\IHomeMountProvider $provider
180
+     * @since 9.1.0
181
+     */
182
+    public function registerHomeProvider(IHomeMountProvider $provider) {
183
+        $this->homeProviders[] = $provider;
184
+        $this->emit('\OC\Files\Config', 'registerHomeMountProvider', [$provider]);
185
+    }
186
+
187
+    /**
188
+     * Cache mounts for user
189
+     *
190
+     * @param IUser $user
191
+     * @param IMountPoint[] $mountPoints
192
+     */
193
+    public function registerMounts(IUser $user, array $mountPoints) {
194
+        $this->mountCache->registerMounts($user, $mountPoints);
195
+    }
196
+
197
+    /**
198
+     * Get the mount cache which can be used to search for mounts without setting up the filesystem
199
+     *
200
+     * @return IUserMountCache
201
+     */
202
+    public function getMountCache() {
203
+        return $this->mountCache;
204
+    }
205
+
206
+    public function registerRootProvider(IRootMountProvider $provider) {
207
+        $this->rootProviders[] = $provider;
208
+    }
209
+
210
+    /**
211
+     * Get all root mountpoints
212
+     *
213
+     * @return \OCP\Files\Mount\IMountPoint[]
214
+     * @since 20.0.0
215
+     */
216
+    public function getRootMounts(): array {
217
+        $loader = $this->loader;
218
+        $mounts = array_map(function (IRootMountProvider $provider) use ($loader) {
219
+            return $provider->getRootMounts($loader);
220
+        }, $this->rootProviders);
221
+        $mounts = array_reduce($mounts, function (array $mounts, array $providerMounts) {
222
+            return array_merge($mounts, $providerMounts);
223
+        }, []);
224
+        return $mounts;
225
+    }
226 226
 }
Please login to merge, or discard this patch.
Spacing   +10 added lines, -10 removed lines patch added patch discarded remove patch
@@ -83,13 +83,13 @@  discard block
 block discarded – undo
83 83
 	 */
84 84
 	public function getMountsForUser(IUser $user) {
85 85
 		$loader = $this->loader;
86
-		$mounts = array_map(function (IMountProvider $provider) use ($user, $loader) {
86
+		$mounts = array_map(function(IMountProvider $provider) use ($user, $loader) {
87 87
 			return $provider->getMountsForUser($user, $loader);
88 88
 		}, $this->providers);
89
-		$mounts = array_filter($mounts, function ($result) {
89
+		$mounts = array_filter($mounts, function($result) {
90 90
 			return is_array($result);
91 91
 		});
92
-		$mounts = array_reduce($mounts, function (array $mounts, array $providerMounts) {
92
+		$mounts = array_reduce($mounts, function(array $mounts, array $providerMounts) {
93 93
 			return array_merge($mounts, $providerMounts);
94 94
 		}, []);
95 95
 		return $this->filterMounts($user, $mounts);
@@ -99,10 +99,10 @@  discard block
 block discarded – undo
99 99
 		// shared mount provider gets to go last since it needs to know existing files
100 100
 		// to check for name collisions
101 101
 		$firstMounts = [];
102
-		$firstProviders = array_filter($this->providers, function (IMountProvider $provider) {
102
+		$firstProviders = array_filter($this->providers, function(IMountProvider $provider) {
103 103
 			return (get_class($provider) !== 'OCA\Files_Sharing\MountProvider');
104 104
 		});
105
-		$lastProviders = array_filter($this->providers, function (IMountProvider $provider) {
105
+		$lastProviders = array_filter($this->providers, function(IMountProvider $provider) {
106 106
 			return (get_class($provider) === 'OCA\Files_Sharing\MountProvider');
107 107
 		});
108 108
 		foreach ($firstProviders as $provider) {
@@ -140,11 +140,11 @@  discard block
 block discarded – undo
140 140
 		$providers = array_reverse($this->homeProviders); // call the latest registered provider first to give apps an opportunity to overwrite builtin
141 141
 		foreach ($providers as $homeProvider) {
142 142
 			if ($mount = $homeProvider->getHomeMountForUser($user, $this->loader)) {
143
-				$mount->setMountPoint('/' . $user->getUID()); //make sure the mountpoint is what we expect
143
+				$mount->setMountPoint('/'.$user->getUID()); //make sure the mountpoint is what we expect
144 144
 				return $mount;
145 145
 			}
146 146
 		}
147
-		throw new \Exception('No home storage configured for user ' . $user);
147
+		throw new \Exception('No home storage configured for user '.$user);
148 148
 	}
149 149
 
150 150
 	/**
@@ -163,7 +163,7 @@  discard block
 block discarded – undo
163 163
 	}
164 164
 
165 165
 	private function filterMounts(IUser $user, array $mountPoints) {
166
-		return array_filter($mountPoints, function (IMountPoint $mountPoint) use ($user) {
166
+		return array_filter($mountPoints, function(IMountPoint $mountPoint) use ($user) {
167 167
 			foreach ($this->mountFilters as $filter) {
168 168
 				if ($filter($mountPoint, $user) === false) {
169 169
 					return false;
@@ -215,10 +215,10 @@  discard block
 block discarded – undo
215 215
 	 */
216 216
 	public function getRootMounts(): array {
217 217
 		$loader = $this->loader;
218
-		$mounts = array_map(function (IRootMountProvider $provider) use ($loader) {
218
+		$mounts = array_map(function(IRootMountProvider $provider) use ($loader) {
219 219
 			return $provider->getRootMounts($loader);
220 220
 		}, $this->rootProviders);
221
-		$mounts = array_reduce($mounts, function (array $mounts, array $providerMounts) {
221
+		$mounts = array_reduce($mounts, function(array $mounts, array $providerMounts) {
222 222
 			return array_merge($mounts, $providerMounts);
223 223
 		}, []);
224 224
 		return $mounts;
Please login to merge, or discard this patch.
lib/private/legacy/OC_Util.php 1 patch
Indentation   +1404 added lines, -1404 removed lines patch added patch discarded remove patch
@@ -71,1413 +71,1413 @@
 block discarded – undo
71 71
 use OCP\IUserSession;
72 72
 
73 73
 class OC_Util {
74
-	public static $scripts = [];
75
-	public static $styles = [];
76
-	public static $headers = [];
77
-	private static $rootMounted = false;
78
-	private static $fsSetup = false;
79
-
80
-	/** @var array Local cache of version.php */
81
-	private static $versionCache = null;
82
-
83
-	protected static function getAppManager() {
84
-		return \OC::$server->getAppManager();
85
-	}
86
-
87
-	private static function initLocalStorageRootFS() {
88
-		// mount local file backend as root
89
-		$configDataDirectory = \OC::$server->getSystemConfig()->getValue("datadirectory", OC::$SERVERROOT . "/data");
90
-		//first set up the local "root" storage
91
-		\OC\Files\Filesystem::initMountManager();
92
-		if (!self::$rootMounted) {
93
-			\OC\Files\Filesystem::mount(LocalRootStorage::class, ['datadir' => $configDataDirectory], '/');
94
-			self::$rootMounted = true;
95
-		}
96
-	}
97
-
98
-	/**
99
-	 * mounting an object storage as the root fs will in essence remove the
100
-	 * necessity of a data folder being present.
101
-	 * TODO make home storage aware of this and use the object storage instead of local disk access
102
-	 *
103
-	 * @param array $config containing 'class' and optional 'arguments'
104
-	 * @suppress PhanDeprecatedFunction
105
-	 */
106
-	private static function initObjectStoreRootFS($config) {
107
-		// check misconfiguration
108
-		if (empty($config['class'])) {
109
-			\OCP\Util::writeLog('files', 'No class given for objectstore', ILogger::ERROR);
110
-		}
111
-		if (!isset($config['arguments'])) {
112
-			$config['arguments'] = [];
113
-		}
114
-
115
-		// instantiate object store implementation
116
-		$name = $config['class'];
117
-		if (strpos($name, 'OCA\\') === 0 && substr_count($name, '\\') >= 2) {
118
-			$segments = explode('\\', $name);
119
-			OC_App::loadApp(strtolower($segments[1]));
120
-		}
121
-		$config['arguments']['objectstore'] = new $config['class']($config['arguments']);
122
-		// mount with plain / root object store implementation
123
-		$config['class'] = '\OC\Files\ObjectStore\ObjectStoreStorage';
124
-
125
-		// mount object storage as root
126
-		\OC\Files\Filesystem::initMountManager();
127
-		if (!self::$rootMounted) {
128
-			\OC\Files\Filesystem::mount($config['class'], $config['arguments'], '/');
129
-			self::$rootMounted = true;
130
-		}
131
-	}
132
-
133
-	/**
134
-	 * mounting an object storage as the root fs will in essence remove the
135
-	 * necessity of a data folder being present.
136
-	 *
137
-	 * @param array $config containing 'class' and optional 'arguments'
138
-	 * @suppress PhanDeprecatedFunction
139
-	 */
140
-	private static function initObjectStoreMultibucketRootFS($config) {
141
-		// check misconfiguration
142
-		if (empty($config['class'])) {
143
-			\OCP\Util::writeLog('files', 'No class given for objectstore', ILogger::ERROR);
144
-		}
145
-		if (!isset($config['arguments'])) {
146
-			$config['arguments'] = [];
147
-		}
148
-
149
-		// instantiate object store implementation
150
-		$name = $config['class'];
151
-		if (strpos($name, 'OCA\\') === 0 && substr_count($name, '\\') >= 2) {
152
-			$segments = explode('\\', $name);
153
-			OC_App::loadApp(strtolower($segments[1]));
154
-		}
155
-
156
-		if (!isset($config['arguments']['bucket'])) {
157
-			$config['arguments']['bucket'] = '';
158
-		}
159
-		// put the root FS always in first bucket for multibucket configuration
160
-		$config['arguments']['bucket'] .= '0';
161
-
162
-		$config['arguments']['objectstore'] = new $config['class']($config['arguments']);
163
-		// mount with plain / root object store implementation
164
-		$config['class'] = '\OC\Files\ObjectStore\ObjectStoreStorage';
165
-
166
-		// mount object storage as root
167
-		\OC\Files\Filesystem::initMountManager();
168
-		if (!self::$rootMounted) {
169
-			\OC\Files\Filesystem::mount($config['class'], $config['arguments'], '/');
170
-			self::$rootMounted = true;
171
-		}
172
-	}
173
-
174
-	/**
175
-	 * Can be set up
176
-	 *
177
-	 * @param string $user
178
-	 * @return boolean
179
-	 * @description configure the initial filesystem based on the configuration
180
-	 * @suppress PhanDeprecatedFunction
181
-	 * @suppress PhanAccessMethodInternal
182
-	 */
183
-	public static function setupFS($user = '') {
184
-		//setting up the filesystem twice can only lead to trouble
185
-		if (self::$fsSetup) {
186
-			return false;
187
-		}
188
-
189
-		\OC::$server->getEventLogger()->start('setup_fs', 'Setup filesystem');
190
-
191
-		// If we are not forced to load a specific user we load the one that is logged in
192
-		if ($user === null) {
193
-			$user = '';
194
-		} elseif ($user == "" && \OC::$server->getUserSession()->isLoggedIn()) {
195
-			$user = OC_User::getUser();
196
-		}
197
-
198
-		// load all filesystem apps before, so no setup-hook gets lost
199
-		OC_App::loadApps(['filesystem']);
200
-
201
-		// the filesystem will finish when $user is not empty,
202
-		// mark fs setup here to avoid doing the setup from loading
203
-		// OC_Filesystem
204
-		if ($user != '') {
205
-			self::$fsSetup = true;
206
-		}
207
-
208
-		\OC\Files\Filesystem::initMountManager();
209
-
210
-		$prevLogging = \OC\Files\Filesystem::logWarningWhenAddingStorageWrapper(false);
211
-		\OC\Files\Filesystem::addStorageWrapper('mount_options', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
212
-			if ($storage->instanceOfStorage('\OC\Files\Storage\Common')) {
213
-				/** @var \OC\Files\Storage\Common $storage */
214
-				$storage->setMountOptions($mount->getOptions());
215
-			}
216
-			return $storage;
217
-		});
218
-
219
-		\OC\Files\Filesystem::addStorageWrapper('enable_sharing', function ($mountPoint, \OCP\Files\Storage\IStorage $storage, \OCP\Files\Mount\IMountPoint $mount) {
220
-			if (!$mount->getOption('enable_sharing', true)) {
221
-				return new \OC\Files\Storage\Wrapper\PermissionsMask([
222
-					'storage' => $storage,
223
-					'mask' => \OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_SHARE
224
-				]);
225
-			}
226
-			return $storage;
227
-		});
228
-
229
-		// install storage availability wrapper, before most other wrappers
230
-		\OC\Files\Filesystem::addStorageWrapper('oc_availability', function ($mountPoint, \OCP\Files\Storage\IStorage $storage) {
231
-			if (!$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) {
232
-				return new \OC\Files\Storage\Wrapper\Availability(['storage' => $storage]);
233
-			}
234
-			return $storage;
235
-		});
236
-
237
-		\OC\Files\Filesystem::addStorageWrapper('oc_encoding', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
238
-			if ($mount->getOption('encoding_compatibility', false) && !$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) {
239
-				return new \OC\Files\Storage\Wrapper\Encoding(['storage' => $storage]);
240
-			}
241
-			return $storage;
242
-		});
243
-
244
-		\OC\Files\Filesystem::addStorageWrapper('oc_quota', function ($mountPoint, $storage) {
245
-			// set up quota for home storages, even for other users
246
-			// which can happen when using sharing
247
-
248
-			/**
249
-			 * @var \OC\Files\Storage\Storage $storage
250
-			 */
251
-			if ($storage->instanceOfStorage('\OC\Files\Storage\Home')
252
-				|| $storage->instanceOfStorage('\OC\Files\ObjectStore\HomeObjectStoreStorage')
253
-			) {
254
-				/** @var \OC\Files\Storage\Home $storage */
255
-				if (is_object($storage->getUser())) {
256
-					$quota = OC_Util::getUserQuota($storage->getUser());
257
-					if ($quota !== \OCP\Files\FileInfo::SPACE_UNLIMITED) {
258
-						return new \OC\Files\Storage\Wrapper\Quota(['storage' => $storage, 'quota' => $quota, 'root' => 'files']);
259
-					}
260
-				}
261
-			}
262
-
263
-			return $storage;
264
-		});
265
-
266
-		\OC\Files\Filesystem::addStorageWrapper('readonly', function ($mountPoint, \OCP\Files\Storage\IStorage $storage, \OCP\Files\Mount\IMountPoint $mount) {
267
-			/*
74
+    public static $scripts = [];
75
+    public static $styles = [];
76
+    public static $headers = [];
77
+    private static $rootMounted = false;
78
+    private static $fsSetup = false;
79
+
80
+    /** @var array Local cache of version.php */
81
+    private static $versionCache = null;
82
+
83
+    protected static function getAppManager() {
84
+        return \OC::$server->getAppManager();
85
+    }
86
+
87
+    private static function initLocalStorageRootFS() {
88
+        // mount local file backend as root
89
+        $configDataDirectory = \OC::$server->getSystemConfig()->getValue("datadirectory", OC::$SERVERROOT . "/data");
90
+        //first set up the local "root" storage
91
+        \OC\Files\Filesystem::initMountManager();
92
+        if (!self::$rootMounted) {
93
+            \OC\Files\Filesystem::mount(LocalRootStorage::class, ['datadir' => $configDataDirectory], '/');
94
+            self::$rootMounted = true;
95
+        }
96
+    }
97
+
98
+    /**
99
+     * mounting an object storage as the root fs will in essence remove the
100
+     * necessity of a data folder being present.
101
+     * TODO make home storage aware of this and use the object storage instead of local disk access
102
+     *
103
+     * @param array $config containing 'class' and optional 'arguments'
104
+     * @suppress PhanDeprecatedFunction
105
+     */
106
+    private static function initObjectStoreRootFS($config) {
107
+        // check misconfiguration
108
+        if (empty($config['class'])) {
109
+            \OCP\Util::writeLog('files', 'No class given for objectstore', ILogger::ERROR);
110
+        }
111
+        if (!isset($config['arguments'])) {
112
+            $config['arguments'] = [];
113
+        }
114
+
115
+        // instantiate object store implementation
116
+        $name = $config['class'];
117
+        if (strpos($name, 'OCA\\') === 0 && substr_count($name, '\\') >= 2) {
118
+            $segments = explode('\\', $name);
119
+            OC_App::loadApp(strtolower($segments[1]));
120
+        }
121
+        $config['arguments']['objectstore'] = new $config['class']($config['arguments']);
122
+        // mount with plain / root object store implementation
123
+        $config['class'] = '\OC\Files\ObjectStore\ObjectStoreStorage';
124
+
125
+        // mount object storage as root
126
+        \OC\Files\Filesystem::initMountManager();
127
+        if (!self::$rootMounted) {
128
+            \OC\Files\Filesystem::mount($config['class'], $config['arguments'], '/');
129
+            self::$rootMounted = true;
130
+        }
131
+    }
132
+
133
+    /**
134
+     * mounting an object storage as the root fs will in essence remove the
135
+     * necessity of a data folder being present.
136
+     *
137
+     * @param array $config containing 'class' and optional 'arguments'
138
+     * @suppress PhanDeprecatedFunction
139
+     */
140
+    private static function initObjectStoreMultibucketRootFS($config) {
141
+        // check misconfiguration
142
+        if (empty($config['class'])) {
143
+            \OCP\Util::writeLog('files', 'No class given for objectstore', ILogger::ERROR);
144
+        }
145
+        if (!isset($config['arguments'])) {
146
+            $config['arguments'] = [];
147
+        }
148
+
149
+        // instantiate object store implementation
150
+        $name = $config['class'];
151
+        if (strpos($name, 'OCA\\') === 0 && substr_count($name, '\\') >= 2) {
152
+            $segments = explode('\\', $name);
153
+            OC_App::loadApp(strtolower($segments[1]));
154
+        }
155
+
156
+        if (!isset($config['arguments']['bucket'])) {
157
+            $config['arguments']['bucket'] = '';
158
+        }
159
+        // put the root FS always in first bucket for multibucket configuration
160
+        $config['arguments']['bucket'] .= '0';
161
+
162
+        $config['arguments']['objectstore'] = new $config['class']($config['arguments']);
163
+        // mount with plain / root object store implementation
164
+        $config['class'] = '\OC\Files\ObjectStore\ObjectStoreStorage';
165
+
166
+        // mount object storage as root
167
+        \OC\Files\Filesystem::initMountManager();
168
+        if (!self::$rootMounted) {
169
+            \OC\Files\Filesystem::mount($config['class'], $config['arguments'], '/');
170
+            self::$rootMounted = true;
171
+        }
172
+    }
173
+
174
+    /**
175
+     * Can be set up
176
+     *
177
+     * @param string $user
178
+     * @return boolean
179
+     * @description configure the initial filesystem based on the configuration
180
+     * @suppress PhanDeprecatedFunction
181
+     * @suppress PhanAccessMethodInternal
182
+     */
183
+    public static function setupFS($user = '') {
184
+        //setting up the filesystem twice can only lead to trouble
185
+        if (self::$fsSetup) {
186
+            return false;
187
+        }
188
+
189
+        \OC::$server->getEventLogger()->start('setup_fs', 'Setup filesystem');
190
+
191
+        // If we are not forced to load a specific user we load the one that is logged in
192
+        if ($user === null) {
193
+            $user = '';
194
+        } elseif ($user == "" && \OC::$server->getUserSession()->isLoggedIn()) {
195
+            $user = OC_User::getUser();
196
+        }
197
+
198
+        // load all filesystem apps before, so no setup-hook gets lost
199
+        OC_App::loadApps(['filesystem']);
200
+
201
+        // the filesystem will finish when $user is not empty,
202
+        // mark fs setup here to avoid doing the setup from loading
203
+        // OC_Filesystem
204
+        if ($user != '') {
205
+            self::$fsSetup = true;
206
+        }
207
+
208
+        \OC\Files\Filesystem::initMountManager();
209
+
210
+        $prevLogging = \OC\Files\Filesystem::logWarningWhenAddingStorageWrapper(false);
211
+        \OC\Files\Filesystem::addStorageWrapper('mount_options', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
212
+            if ($storage->instanceOfStorage('\OC\Files\Storage\Common')) {
213
+                /** @var \OC\Files\Storage\Common $storage */
214
+                $storage->setMountOptions($mount->getOptions());
215
+            }
216
+            return $storage;
217
+        });
218
+
219
+        \OC\Files\Filesystem::addStorageWrapper('enable_sharing', function ($mountPoint, \OCP\Files\Storage\IStorage $storage, \OCP\Files\Mount\IMountPoint $mount) {
220
+            if (!$mount->getOption('enable_sharing', true)) {
221
+                return new \OC\Files\Storage\Wrapper\PermissionsMask([
222
+                    'storage' => $storage,
223
+                    'mask' => \OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_SHARE
224
+                ]);
225
+            }
226
+            return $storage;
227
+        });
228
+
229
+        // install storage availability wrapper, before most other wrappers
230
+        \OC\Files\Filesystem::addStorageWrapper('oc_availability', function ($mountPoint, \OCP\Files\Storage\IStorage $storage) {
231
+            if (!$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) {
232
+                return new \OC\Files\Storage\Wrapper\Availability(['storage' => $storage]);
233
+            }
234
+            return $storage;
235
+        });
236
+
237
+        \OC\Files\Filesystem::addStorageWrapper('oc_encoding', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
238
+            if ($mount->getOption('encoding_compatibility', false) && !$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) {
239
+                return new \OC\Files\Storage\Wrapper\Encoding(['storage' => $storage]);
240
+            }
241
+            return $storage;
242
+        });
243
+
244
+        \OC\Files\Filesystem::addStorageWrapper('oc_quota', function ($mountPoint, $storage) {
245
+            // set up quota for home storages, even for other users
246
+            // which can happen when using sharing
247
+
248
+            /**
249
+             * @var \OC\Files\Storage\Storage $storage
250
+             */
251
+            if ($storage->instanceOfStorage('\OC\Files\Storage\Home')
252
+                || $storage->instanceOfStorage('\OC\Files\ObjectStore\HomeObjectStoreStorage')
253
+            ) {
254
+                /** @var \OC\Files\Storage\Home $storage */
255
+                if (is_object($storage->getUser())) {
256
+                    $quota = OC_Util::getUserQuota($storage->getUser());
257
+                    if ($quota !== \OCP\Files\FileInfo::SPACE_UNLIMITED) {
258
+                        return new \OC\Files\Storage\Wrapper\Quota(['storage' => $storage, 'quota' => $quota, 'root' => 'files']);
259
+                    }
260
+                }
261
+            }
262
+
263
+            return $storage;
264
+        });
265
+
266
+        \OC\Files\Filesystem::addStorageWrapper('readonly', function ($mountPoint, \OCP\Files\Storage\IStorage $storage, \OCP\Files\Mount\IMountPoint $mount) {
267
+            /*
268 268
 			 * Do not allow any operations that modify the storage
269 269
 			 */
270
-			if ($mount->getOption('readonly', false)) {
271
-				return new \OC\Files\Storage\Wrapper\PermissionsMask([
272
-					'storage' => $storage,
273
-					'mask' => \OCP\Constants::PERMISSION_ALL & ~(
274
-						\OCP\Constants::PERMISSION_UPDATE |
275
-						\OCP\Constants::PERMISSION_CREATE |
276
-						\OCP\Constants::PERMISSION_DELETE
277
-					),
278
-				]);
279
-			}
280
-			return $storage;
281
-		});
282
-
283
-		OC_Hook::emit('OC_Filesystem', 'preSetup', ['user' => $user]);
284
-
285
-		\OC\Files\Filesystem::logWarningWhenAddingStorageWrapper($prevLogging);
286
-
287
-		//check if we are using an object storage
288
-		$objectStore = \OC::$server->getSystemConfig()->getValue('objectstore', null);
289
-		$objectStoreMultibucket = \OC::$server->getSystemConfig()->getValue('objectstore_multibucket', null);
290
-
291
-		// use the same order as in ObjectHomeMountProvider
292
-		if (isset($objectStoreMultibucket)) {
293
-			self::initObjectStoreMultibucketRootFS($objectStoreMultibucket);
294
-		} elseif (isset($objectStore)) {
295
-			self::initObjectStoreRootFS($objectStore);
296
-		} else {
297
-			self::initLocalStorageRootFS();
298
-		}
299
-
300
-		/** @var \OCP\Files\Config\IMountProviderCollection $mountProviderCollection */
301
-		$mountProviderCollection = \OC::$server->query(\OCP\Files\Config\IMountProviderCollection::class);
302
-		$rootMountProviders = $mountProviderCollection->getRootMounts();
303
-
304
-		/** @var \OC\Files\Mount\Manager $mountManager */
305
-		$mountManager = \OC\Files\Filesystem::getMountManager();
306
-		foreach ($rootMountProviders as $rootMountProvider) {
307
-			$mountManager->addMount($rootMountProvider);
308
-		}
309
-
310
-		if ($user != '' && !\OC::$server->getUserManager()->userExists($user)) {
311
-			\OC::$server->getEventLogger()->end('setup_fs');
312
-			return false;
313
-		}
314
-
315
-		//if we aren't logged in, there is no use to set up the filesystem
316
-		if ($user != "") {
317
-			$userDir = '/' . $user . '/files';
318
-
319
-			//jail the user into his "home" directory
320
-			\OC\Files\Filesystem::init($user, $userDir);
321
-
322
-			OC_Hook::emit('OC_Filesystem', 'setup', ['user' => $user, 'user_dir' => $userDir]);
323
-		}
324
-		\OC::$server->getEventLogger()->end('setup_fs');
325
-		return true;
326
-	}
327
-
328
-	/**
329
-	 * check if a password is required for each public link
330
-	 *
331
-	 * @return boolean
332
-	 * @suppress PhanDeprecatedFunction
333
-	 */
334
-	public static function isPublicLinkPasswordRequired() {
335
-		$enforcePassword = \OC::$server->getConfig()->getAppValue('core', 'shareapi_enforce_links_password', 'no');
336
-		return $enforcePassword === 'yes';
337
-	}
338
-
339
-	/**
340
-	 * check if sharing is disabled for the current user
341
-	 * @param IConfig $config
342
-	 * @param IGroupManager $groupManager
343
-	 * @param IUser|null $user
344
-	 * @return bool
345
-	 */
346
-	public static function isSharingDisabledForUser(IConfig $config, IGroupManager $groupManager, $user) {
347
-		if ($config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') {
348
-			$groupsList = $config->getAppValue('core', 'shareapi_exclude_groups_list', '');
349
-			$excludedGroups = json_decode($groupsList);
350
-			if (is_null($excludedGroups)) {
351
-				$excludedGroups = explode(',', $groupsList);
352
-				$newValue = json_encode($excludedGroups);
353
-				$config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue);
354
-			}
355
-			$usersGroups = $groupManager->getUserGroupIds($user);
356
-			if (!empty($usersGroups)) {
357
-				$remainingGroups = array_diff($usersGroups, $excludedGroups);
358
-				// if the user is only in groups which are disabled for sharing then
359
-				// sharing is also disabled for the user
360
-				if (empty($remainingGroups)) {
361
-					return true;
362
-				}
363
-			}
364
-		}
365
-		return false;
366
-	}
367
-
368
-	/**
369
-	 * check if share API enforces a default expire date
370
-	 *
371
-	 * @return boolean
372
-	 * @suppress PhanDeprecatedFunction
373
-	 */
374
-	public static function isDefaultExpireDateEnforced() {
375
-		$isDefaultExpireDateEnabled = \OC::$server->getConfig()->getAppValue('core', 'shareapi_default_expire_date', 'no');
376
-		$enforceDefaultExpireDate = false;
377
-		if ($isDefaultExpireDateEnabled === 'yes') {
378
-			$value = \OC::$server->getConfig()->getAppValue('core', 'shareapi_enforce_expire_date', 'no');
379
-			$enforceDefaultExpireDate = $value === 'yes';
380
-		}
381
-
382
-		return $enforceDefaultExpireDate;
383
-	}
384
-
385
-	/**
386
-	 * Get the quota of a user
387
-	 *
388
-	 * @param IUser|null $user
389
-	 * @return float Quota bytes
390
-	 */
391
-	public static function getUserQuota(?IUser $user) {
392
-		if (is_null($user)) {
393
-			return \OCP\Files\FileInfo::SPACE_UNLIMITED;
394
-		}
395
-		$userQuota = $user->getQuota();
396
-		if ($userQuota === 'none') {
397
-			return \OCP\Files\FileInfo::SPACE_UNLIMITED;
398
-		}
399
-		return OC_Helper::computerFileSize($userQuota);
400
-	}
401
-
402
-	/**
403
-	 * copies the skeleton to the users /files
404
-	 *
405
-	 * @param string $userId
406
-	 * @param \OCP\Files\Folder $userDirectory
407
-	 * @throws \OCP\Files\NotFoundException
408
-	 * @throws \OCP\Files\NotPermittedException
409
-	 * @suppress PhanDeprecatedFunction
410
-	 */
411
-	public static function copySkeleton($userId, \OCP\Files\Folder $userDirectory) {
412
-		$plainSkeletonDirectory = \OC::$server->getConfig()->getSystemValue('skeletondirectory', \OC::$SERVERROOT . '/core/skeleton');
413
-		$userLang = \OC::$server->getL10NFactory()->findLanguage();
414
-		$skeletonDirectory = str_replace('{lang}', $userLang, $plainSkeletonDirectory);
415
-
416
-		if (!file_exists($skeletonDirectory)) {
417
-			$dialectStart = strpos($userLang, '_');
418
-			if ($dialectStart !== false) {
419
-				$skeletonDirectory = str_replace('{lang}', substr($userLang, 0, $dialectStart), $plainSkeletonDirectory);
420
-			}
421
-			if ($dialectStart === false || !file_exists($skeletonDirectory)) {
422
-				$skeletonDirectory = str_replace('{lang}', 'default', $plainSkeletonDirectory);
423
-			}
424
-			if (!file_exists($skeletonDirectory)) {
425
-				$skeletonDirectory = '';
426
-			}
427
-		}
428
-
429
-		$instanceId = \OC::$server->getConfig()->getSystemValue('instanceid', '');
430
-
431
-		if ($instanceId === null) {
432
-			throw new \RuntimeException('no instance id!');
433
-		}
434
-		$appdata = 'appdata_' . $instanceId;
435
-		if ($userId === $appdata) {
436
-			throw new \RuntimeException('username is reserved name: ' . $appdata);
437
-		}
438
-
439
-		if (!empty($skeletonDirectory)) {
440
-			\OCP\Util::writeLog(
441
-				'files_skeleton',
442
-				'copying skeleton for '.$userId.' from '.$skeletonDirectory.' to '.$userDirectory->getFullPath('/'),
443
-				ILogger::DEBUG
444
-			);
445
-			self::copyr($skeletonDirectory, $userDirectory);
446
-			// update the file cache
447
-			$userDirectory->getStorage()->getScanner()->scan('', \OC\Files\Cache\Scanner::SCAN_RECURSIVE);
448
-		}
449
-	}
450
-
451
-	/**
452
-	 * copies a directory recursively by using streams
453
-	 *
454
-	 * @param string $source
455
-	 * @param \OCP\Files\Folder $target
456
-	 * @return void
457
-	 */
458
-	public static function copyr($source, \OCP\Files\Folder $target) {
459
-		$logger = \OC::$server->getLogger();
460
-
461
-		// Verify if folder exists
462
-		$dir = opendir($source);
463
-		if ($dir === false) {
464
-			$logger->error(sprintf('Could not opendir "%s"', $source), ['app' => 'core']);
465
-			return;
466
-		}
467
-
468
-		// Copy the files
469
-		while (false !== ($file = readdir($dir))) {
470
-			if (!\OC\Files\Filesystem::isIgnoredDir($file)) {
471
-				if (is_dir($source . '/' . $file)) {
472
-					$child = $target->newFolder($file);
473
-					self::copyr($source . '/' . $file, $child);
474
-				} else {
475
-					$child = $target->newFile($file);
476
-					$sourceStream = fopen($source . '/' . $file, 'r');
477
-					if ($sourceStream === false) {
478
-						$logger->error(sprintf('Could not fopen "%s"', $source . '/' . $file), ['app' => 'core']);
479
-						closedir($dir);
480
-						return;
481
-					}
482
-					stream_copy_to_stream($sourceStream, $child->fopen('w'));
483
-				}
484
-			}
485
-		}
486
-		closedir($dir);
487
-	}
488
-
489
-	/**
490
-	 * @return void
491
-	 * @suppress PhanUndeclaredMethod
492
-	 */
493
-	public static function tearDownFS() {
494
-		\OC\Files\Filesystem::tearDown();
495
-		\OC::$server->getRootFolder()->clearCache();
496
-		self::$fsSetup = false;
497
-		self::$rootMounted = false;
498
-	}
499
-
500
-	/**
501
-	 * get the current installed version of ownCloud
502
-	 *
503
-	 * @return array
504
-	 */
505
-	public static function getVersion() {
506
-		OC_Util::loadVersion();
507
-		return self::$versionCache['OC_Version'];
508
-	}
509
-
510
-	/**
511
-	 * get the current installed version string of ownCloud
512
-	 *
513
-	 * @return string
514
-	 */
515
-	public static function getVersionString() {
516
-		OC_Util::loadVersion();
517
-		return self::$versionCache['OC_VersionString'];
518
-	}
519
-
520
-	/**
521
-	 * @deprecated the value is of no use anymore
522
-	 * @return string
523
-	 */
524
-	public static function getEditionString() {
525
-		return '';
526
-	}
527
-
528
-	/**
529
-	 * @description get the update channel of the current installed of ownCloud.
530
-	 * @return string
531
-	 */
532
-	public static function getChannel() {
533
-		OC_Util::loadVersion();
534
-		return \OC::$server->getConfig()->getSystemValue('updater.release.channel', self::$versionCache['OC_Channel']);
535
-	}
536
-
537
-	/**
538
-	 * @description get the build number of the current installed of ownCloud.
539
-	 * @return string
540
-	 */
541
-	public static function getBuild() {
542
-		OC_Util::loadVersion();
543
-		return self::$versionCache['OC_Build'];
544
-	}
545
-
546
-	/**
547
-	 * @description load the version.php into the session as cache
548
-	 * @suppress PhanUndeclaredVariable
549
-	 */
550
-	private static function loadVersion() {
551
-		if (self::$versionCache !== null) {
552
-			return;
553
-		}
554
-
555
-		$timestamp = filemtime(OC::$SERVERROOT . '/version.php');
556
-		require OC::$SERVERROOT . '/version.php';
557
-		/** @var int $timestamp */
558
-		self::$versionCache['OC_Version_Timestamp'] = $timestamp;
559
-		/** @var string $OC_Version */
560
-		self::$versionCache['OC_Version'] = $OC_Version;
561
-		/** @var string $OC_VersionString */
562
-		self::$versionCache['OC_VersionString'] = $OC_VersionString;
563
-		/** @var string $OC_Build */
564
-		self::$versionCache['OC_Build'] = $OC_Build;
565
-
566
-		/** @var string $OC_Channel */
567
-		self::$versionCache['OC_Channel'] = $OC_Channel;
568
-	}
569
-
570
-	/**
571
-	 * generates a path for JS/CSS files. If no application is provided it will create the path for core.
572
-	 *
573
-	 * @param string $application application to get the files from
574
-	 * @param string $directory directory within this application (css, js, vendor, etc)
575
-	 * @param string $file the file inside of the above folder
576
-	 * @return string the path
577
-	 */
578
-	private static function generatePath($application, $directory, $file) {
579
-		if (is_null($file)) {
580
-			$file = $application;
581
-			$application = "";
582
-		}
583
-		if (!empty($application)) {
584
-			return "$application/$directory/$file";
585
-		} else {
586
-			return "$directory/$file";
587
-		}
588
-	}
589
-
590
-	/**
591
-	 * add a javascript file
592
-	 *
593
-	 * @param string $application application id
594
-	 * @param string|null $file filename
595
-	 * @param bool $prepend prepend the Script to the beginning of the list
596
-	 * @return void
597
-	 */
598
-	public static function addScript($application, $file = null, $prepend = false) {
599
-		$path = OC_Util::generatePath($application, 'js', $file);
600
-
601
-		// core js files need separate handling
602
-		if ($application !== 'core' && $file !== null) {
603
-			self::addTranslations($application);
604
-		}
605
-		self::addExternalResource($application, $prepend, $path, "script");
606
-	}
607
-
608
-	/**
609
-	 * add a javascript file from the vendor sub folder
610
-	 *
611
-	 * @param string $application application id
612
-	 * @param string|null $file filename
613
-	 * @param bool $prepend prepend the Script to the beginning of the list
614
-	 * @return void
615
-	 */
616
-	public static function addVendorScript($application, $file = null, $prepend = false) {
617
-		$path = OC_Util::generatePath($application, 'vendor', $file);
618
-		self::addExternalResource($application, $prepend, $path, "script");
619
-	}
620
-
621
-	/**
622
-	 * add a translation JS file
623
-	 *
624
-	 * @param string $application application id
625
-	 * @param string|null $languageCode language code, defaults to the current language
626
-	 * @param bool|null $prepend prepend the Script to the beginning of the list
627
-	 */
628
-	public static function addTranslations($application, $languageCode = null, $prepend = false) {
629
-		if (is_null($languageCode)) {
630
-			$languageCode = \OC::$server->getL10NFactory()->findLanguage($application);
631
-		}
632
-		if (!empty($application)) {
633
-			$path = "$application/l10n/$languageCode";
634
-		} else {
635
-			$path = "l10n/$languageCode";
636
-		}
637
-		self::addExternalResource($application, $prepend, $path, "script");
638
-	}
639
-
640
-	/**
641
-	 * add a css file
642
-	 *
643
-	 * @param string $application application id
644
-	 * @param string|null $file filename
645
-	 * @param bool $prepend prepend the Style to the beginning of the list
646
-	 * @return void
647
-	 */
648
-	public static function addStyle($application, $file = null, $prepend = false) {
649
-		$path = OC_Util::generatePath($application, 'css', $file);
650
-		self::addExternalResource($application, $prepend, $path, "style");
651
-	}
652
-
653
-	/**
654
-	 * add a css file from the vendor sub folder
655
-	 *
656
-	 * @param string $application application id
657
-	 * @param string|null $file filename
658
-	 * @param bool $prepend prepend the Style to the beginning of the list
659
-	 * @return void
660
-	 */
661
-	public static function addVendorStyle($application, $file = null, $prepend = false) {
662
-		$path = OC_Util::generatePath($application, 'vendor', $file);
663
-		self::addExternalResource($application, $prepend, $path, "style");
664
-	}
665
-
666
-	/**
667
-	 * add an external resource css/js file
668
-	 *
669
-	 * @param string $application application id
670
-	 * @param bool $prepend prepend the file to the beginning of the list
671
-	 * @param string $path
672
-	 * @param string $type (script or style)
673
-	 * @return void
674
-	 */
675
-	private static function addExternalResource($application, $prepend, $path, $type = "script") {
676
-		if ($type === "style") {
677
-			if (!in_array($path, self::$styles)) {
678
-				if ($prepend === true) {
679
-					array_unshift(self::$styles, $path);
680
-				} else {
681
-					self::$styles[] = $path;
682
-				}
683
-			}
684
-		} elseif ($type === "script") {
685
-			if (!in_array($path, self::$scripts)) {
686
-				if ($prepend === true) {
687
-					array_unshift(self::$scripts, $path);
688
-				} else {
689
-					self::$scripts [] = $path;
690
-				}
691
-			}
692
-		}
693
-	}
694
-
695
-	/**
696
-	 * Add a custom element to the header
697
-	 * If $text is null then the element will be written as empty element.
698
-	 * So use "" to get a closing tag.
699
-	 * @param string $tag tag name of the element
700
-	 * @param array $attributes array of attributes for the element
701
-	 * @param string $text the text content for the element
702
-	 * @param bool $prepend prepend the header to the beginning of the list
703
-	 */
704
-	public static function addHeader($tag, $attributes, $text = null, $prepend = false) {
705
-		$header = [
706
-			'tag' => $tag,
707
-			'attributes' => $attributes,
708
-			'text' => $text
709
-		];
710
-		if ($prepend === true) {
711
-			array_unshift(self::$headers, $header);
712
-		} else {
713
-			self::$headers[] = $header;
714
-		}
715
-	}
716
-
717
-	/**
718
-	 * check if the current server configuration is suitable for ownCloud
719
-	 *
720
-	 * @param \OC\SystemConfig $config
721
-	 * @return array arrays with error messages and hints
722
-	 */
723
-	public static function checkServer(\OC\SystemConfig $config) {
724
-		$l = \OC::$server->getL10N('lib');
725
-		$errors = [];
726
-		$CONFIG_DATADIRECTORY = $config->getValue('datadirectory', OC::$SERVERROOT . '/data');
727
-
728
-		if (!self::needUpgrade($config) && $config->getValue('installed', false)) {
729
-			// this check needs to be done every time
730
-			$errors = self::checkDataDirectoryValidity($CONFIG_DATADIRECTORY);
731
-		}
732
-
733
-		// Assume that if checkServer() succeeded before in this session, then all is fine.
734
-		if (\OC::$server->getSession()->exists('checkServer_succeeded') && \OC::$server->getSession()->get('checkServer_succeeded')) {
735
-			return $errors;
736
-		}
737
-
738
-		$webServerRestart = false;
739
-		$setup = new \OC\Setup(
740
-			$config,
741
-			\OC::$server->getIniWrapper(),
742
-			\OC::$server->getL10N('lib'),
743
-			\OC::$server->query(\OCP\Defaults::class),
744
-			\OC::$server->getLogger(),
745
-			\OC::$server->getSecureRandom(),
746
-			\OC::$server->query(\OC\Installer::class)
747
-		);
748
-
749
-		$urlGenerator = \OC::$server->getURLGenerator();
750
-
751
-		$availableDatabases = $setup->getSupportedDatabases();
752
-		if (empty($availableDatabases)) {
753
-			$errors[] = [
754
-				'error' => $l->t('No database drivers (sqlite, mysql, or postgresql) installed.'),
755
-				'hint' => '' //TODO: sane hint
756
-			];
757
-			$webServerRestart = true;
758
-		}
759
-
760
-		// Check if config folder is writable.
761
-		if (!OC_Helper::isReadOnlyConfigEnabled()) {
762
-			if (!is_writable(OC::$configDir) or !is_readable(OC::$configDir)) {
763
-				$errors[] = [
764
-					'error' => $l->t('Cannot write into "config" directory'),
765
-					'hint' => $l->t('This can usually be fixed by giving the webserver write access to the config directory. See %s',
766
-						[ $urlGenerator->linkToDocs('admin-dir_permissions') ]) . '. '
767
-						. $l->t('Or, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it. See %s',
768
-						[ $urlGenerator->linkToDocs('admin-config') ])
769
-				];
770
-			}
771
-		}
772
-
773
-		// Check if there is a writable install folder.
774
-		if ($config->getValue('appstoreenabled', true)) {
775
-			if (OC_App::getInstallPath() === null
776
-				|| !is_writable(OC_App::getInstallPath())
777
-				|| !is_readable(OC_App::getInstallPath())
778
-			) {
779
-				$errors[] = [
780
-					'error' => $l->t('Cannot write into "apps" directory'),
781
-					'hint' => $l->t('This can usually be fixed by giving the webserver write access to the apps directory'
782
-						. ' or disabling the appstore in the config file.')
783
-				];
784
-			}
785
-		}
786
-		// Create root dir.
787
-		if ($config->getValue('installed', false)) {
788
-			if (!is_dir($CONFIG_DATADIRECTORY)) {
789
-				$success = @mkdir($CONFIG_DATADIRECTORY);
790
-				if ($success) {
791
-					$errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
792
-				} else {
793
-					$errors[] = [
794
-						'error' => $l->t('Cannot create "data" directory'),
795
-						'hint' => $l->t('This can usually be fixed by giving the webserver write access to the root directory. See %s',
796
-							[$urlGenerator->linkToDocs('admin-dir_permissions')])
797
-					];
798
-				}
799
-			} elseif (!is_writable($CONFIG_DATADIRECTORY) or !is_readable($CONFIG_DATADIRECTORY)) {
800
-				// is_writable doesn't work for NFS mounts, so try to write a file and check if it exists.
801
-				$testFile = sprintf('%s/%s.tmp', $CONFIG_DATADIRECTORY, uniqid('data_dir_writability_test_'));
802
-				$handle = fopen($testFile, 'w');
803
-				if (!$handle || fwrite($handle, 'Test write operation') === false) {
804
-					$permissionsHint = $l->t('Permissions can usually be fixed by giving the webserver write access to the root directory. See %s.',
805
-						[$urlGenerator->linkToDocs('admin-dir_permissions')]);
806
-					$errors[] = [
807
-						'error' => 'Your data directory is not writable',
808
-						'hint' => $permissionsHint
809
-					];
810
-				} else {
811
-					fclose($handle);
812
-					unlink($testFile);
813
-				}
814
-			} else {
815
-				$errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
816
-			}
817
-		}
818
-
819
-		if (!OC_Util::isSetLocaleWorking()) {
820
-			$errors[] = [
821
-				'error' => $l->t('Setting locale to %s failed',
822
-					['en_US.UTF-8/fr_FR.UTF-8/es_ES.UTF-8/de_DE.UTF-8/ru_RU.UTF-8/'
823
-						. 'pt_BR.UTF-8/it_IT.UTF-8/ja_JP.UTF-8/zh_CN.UTF-8']),
824
-				'hint' => $l->t('Please install one of these locales on your system and restart your webserver.')
825
-			];
826
-		}
827
-
828
-		// Contains the dependencies that should be checked against
829
-		// classes = class_exists
830
-		// functions = function_exists
831
-		// defined = defined
832
-		// ini = ini_get
833
-		// If the dependency is not found the missing module name is shown to the EndUser
834
-		// When adding new checks always verify that they pass on Travis as well
835
-		// for ini settings, see https://github.com/owncloud/administration/blob/master/travis-ci/custom.ini
836
-		$dependencies = [
837
-			'classes' => [
838
-				'ZipArchive' => 'zip',
839
-				'DOMDocument' => 'dom',
840
-				'XMLWriter' => 'XMLWriter',
841
-				'XMLReader' => 'XMLReader',
842
-			],
843
-			'functions' => [
844
-				'xml_parser_create' => 'libxml',
845
-				'mb_strcut' => 'mbstring',
846
-				'ctype_digit' => 'ctype',
847
-				'json_encode' => 'JSON',
848
-				'gd_info' => 'GD',
849
-				'gzencode' => 'zlib',
850
-				'iconv' => 'iconv',
851
-				'simplexml_load_string' => 'SimpleXML',
852
-				'hash' => 'HASH Message Digest Framework',
853
-				'curl_init' => 'cURL',
854
-				'openssl_verify' => 'OpenSSL',
855
-			],
856
-			'defined' => [
857
-				'PDO::ATTR_DRIVER_NAME' => 'PDO'
858
-			],
859
-			'ini' => [
860
-				'default_charset' => 'UTF-8',
861
-			],
862
-		];
863
-		$missingDependencies = [];
864
-		$invalidIniSettings = [];
865
-
866
-		$iniWrapper = \OC::$server->getIniWrapper();
867
-		foreach ($dependencies['classes'] as $class => $module) {
868
-			if (!class_exists($class)) {
869
-				$missingDependencies[] = $module;
870
-			}
871
-		}
872
-		foreach ($dependencies['functions'] as $function => $module) {
873
-			if (!function_exists($function)) {
874
-				$missingDependencies[] = $module;
875
-			}
876
-		}
877
-		foreach ($dependencies['defined'] as $defined => $module) {
878
-			if (!defined($defined)) {
879
-				$missingDependencies[] = $module;
880
-			}
881
-		}
882
-		foreach ($dependencies['ini'] as $setting => $expected) {
883
-			if (is_bool($expected)) {
884
-				if ($iniWrapper->getBool($setting) !== $expected) {
885
-					$invalidIniSettings[] = [$setting, $expected];
886
-				}
887
-			}
888
-			if (is_int($expected)) {
889
-				if ($iniWrapper->getNumeric($setting) !== $expected) {
890
-					$invalidIniSettings[] = [$setting, $expected];
891
-				}
892
-			}
893
-			if (is_string($expected)) {
894
-				if (strtolower($iniWrapper->getString($setting)) !== strtolower($expected)) {
895
-					$invalidIniSettings[] = [$setting, $expected];
896
-				}
897
-			}
898
-		}
899
-
900
-		foreach ($missingDependencies as $missingDependency) {
901
-			$errors[] = [
902
-				'error' => $l->t('PHP module %s not installed.', [$missingDependency]),
903
-				'hint' => $l->t('Please ask your server administrator to install the module.'),
904
-			];
905
-			$webServerRestart = true;
906
-		}
907
-		foreach ($invalidIniSettings as $setting) {
908
-			if (is_bool($setting[1])) {
909
-				$setting[1] = $setting[1] ? 'on' : 'off';
910
-			}
911
-			$errors[] = [
912
-				'error' => $l->t('PHP setting "%s" is not set to "%s".', [$setting[0], var_export($setting[1], true)]),
913
-				'hint' =>  $l->t('Adjusting this setting in php.ini will make Nextcloud run again')
914
-			];
915
-			$webServerRestart = true;
916
-		}
917
-
918
-		/**
919
-		 * The mbstring.func_overload check can only be performed if the mbstring
920
-		 * module is installed as it will return null if the checking setting is
921
-		 * not available and thus a check on the boolean value fails.
922
-		 *
923
-		 * TODO: Should probably be implemented in the above generic dependency
924
-		 *       check somehow in the long-term.
925
-		 */
926
-		if ($iniWrapper->getBool('mbstring.func_overload') !== null &&
927
-			$iniWrapper->getBool('mbstring.func_overload') === true) {
928
-			$errors[] = [
929
-				'error' => $l->t('mbstring.func_overload is set to "%s" instead of the expected value "0"', [$iniWrapper->getString('mbstring.func_overload')]),
930
-				'hint' => $l->t('To fix this issue set <code>mbstring.func_overload</code> to <code>0</code> in your php.ini')
931
-			];
932
-		}
933
-
934
-		if (function_exists('xml_parser_create') &&
935
-			LIBXML_LOADED_VERSION < 20700) {
936
-			$version = LIBXML_LOADED_VERSION;
937
-			$major = floor($version/10000);
938
-			$version -= ($major * 10000);
939
-			$minor = floor($version/100);
940
-			$version -= ($minor * 100);
941
-			$patch = $version;
942
-			$errors[] = [
943
-				'error' => $l->t('libxml2 2.7.0 is at least required. Currently %s is installed.', [$major . '.' . $minor . '.' . $patch]),
944
-				'hint' => $l->t('To fix this issue update your libxml2 version and restart your web server.')
945
-			];
946
-		}
947
-
948
-		if (!self::isAnnotationsWorking()) {
949
-			$errors[] = [
950
-				'error' => $l->t('PHP is apparently set up to strip inline doc blocks. This will make several core apps inaccessible.'),
951
-				'hint' => $l->t('This is probably caused by a cache/accelerator such as Zend OPcache or eAccelerator.')
952
-			];
953
-		}
954
-
955
-		if (!\OC::$CLI && $webServerRestart) {
956
-			$errors[] = [
957
-				'error' => $l->t('PHP modules have been installed, but they are still listed as missing?'),
958
-				'hint' => $l->t('Please ask your server administrator to restart the web server.')
959
-			];
960
-		}
961
-
962
-		$errors = array_merge($errors, self::checkDatabaseVersion());
963
-
964
-		// Cache the result of this function
965
-		\OC::$server->getSession()->set('checkServer_succeeded', count($errors) == 0);
966
-
967
-		return $errors;
968
-	}
969
-
970
-	/**
971
-	 * Check the database version
972
-	 *
973
-	 * @return array errors array
974
-	 */
975
-	public static function checkDatabaseVersion() {
976
-		$l = \OC::$server->getL10N('lib');
977
-		$errors = [];
978
-		$dbType = \OC::$server->getSystemConfig()->getValue('dbtype', 'sqlite');
979
-		if ($dbType === 'pgsql') {
980
-			// check PostgreSQL version
981
-			try {
982
-				$result = \OC_DB::executeAudited('SHOW SERVER_VERSION');
983
-				$data = $result->fetchRow();
984
-				if (isset($data['server_version'])) {
985
-					$version = $data['server_version'];
986
-					if (version_compare($version, '9.0.0', '<')) {
987
-						$errors[] = [
988
-							'error' => $l->t('PostgreSQL >= 9 required'),
989
-							'hint' => $l->t('Please upgrade your database version')
990
-						];
991
-					}
992
-				}
993
-			} catch (\Doctrine\DBAL\DBALException $e) {
994
-				$logger = \OC::$server->getLogger();
995
-				$logger->warning('Error occurred while checking PostgreSQL version, assuming >= 9');
996
-				$logger->logException($e);
997
-			}
998
-		}
999
-		return $errors;
1000
-	}
1001
-
1002
-	/**
1003
-	 * Check for correct file permissions of data directory
1004
-	 *
1005
-	 * @param string $dataDirectory
1006
-	 * @return array arrays with error messages and hints
1007
-	 */
1008
-	public static function checkDataDirectoryPermissions($dataDirectory) {
1009
-		if (\OC::$server->getConfig()->getSystemValue('check_data_directory_permissions', true) === false) {
1010
-			return  [];
1011
-		}
1012
-
1013
-		$perms = substr(decoct(@fileperms($dataDirectory)), -3);
1014
-		if (substr($perms, -1) !== '0') {
1015
-			chmod($dataDirectory, 0770);
1016
-			clearstatcache();
1017
-			$perms = substr(decoct(@fileperms($dataDirectory)), -3);
1018
-			if ($perms[2] !== '0') {
1019
-				$l = \OC::$server->getL10N('lib');
1020
-				return [[
1021
-					'error' => $l->t('Your data directory is readable by other users'),
1022
-					'hint' => $l->t('Please change the permissions to 0770 so that the directory cannot be listed by other users.'),
1023
-				]];
1024
-			}
1025
-		}
1026
-		return [];
1027
-	}
1028
-
1029
-	/**
1030
-	 * Check that the data directory exists and is valid by
1031
-	 * checking the existence of the ".ocdata" file.
1032
-	 *
1033
-	 * @param string $dataDirectory data directory path
1034
-	 * @return array errors found
1035
-	 */
1036
-	public static function checkDataDirectoryValidity($dataDirectory) {
1037
-		$l = \OC::$server->getL10N('lib');
1038
-		$errors = [];
1039
-		if ($dataDirectory[0] !== '/') {
1040
-			$errors[] = [
1041
-				'error' => $l->t('Your data directory must be an absolute path'),
1042
-				'hint' => $l->t('Check the value of "datadirectory" in your configuration')
1043
-			];
1044
-		}
1045
-		if (!file_exists($dataDirectory . '/.ocdata')) {
1046
-			$errors[] = [
1047
-				'error' => $l->t('Your data directory is invalid'),
1048
-				'hint' => $l->t('Ensure there is a file called ".ocdata"' .
1049
-					' in the root of the data directory.')
1050
-			];
1051
-		}
1052
-		return $errors;
1053
-	}
1054
-
1055
-	/**
1056
-	 * Check if the user is logged in, redirects to home if not. With
1057
-	 * redirect URL parameter to the request URI.
1058
-	 *
1059
-	 * @return void
1060
-	 */
1061
-	public static function checkLoggedIn() {
1062
-		// Check if we are a user
1063
-		if (!\OC::$server->getUserSession()->isLoggedIn()) {
1064
-			header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute(
1065
-						'core.login.showLoginForm',
1066
-						[
1067
-							'redirect_url' => \OC::$server->getRequest()->getRequestUri(),
1068
-						]
1069
-					)
1070
-			);
1071
-			exit();
1072
-		}
1073
-		// Redirect to 2FA challenge selection if 2FA challenge was not solved yet
1074
-		if (\OC::$server->getTwoFactorAuthManager()->needsSecondFactor(\OC::$server->getUserSession()->getUser())) {
1075
-			header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute('core.TwoFactorChallenge.selectChallenge'));
1076
-			exit();
1077
-		}
1078
-	}
1079
-
1080
-	/**
1081
-	 * Check if the user is a admin, redirects to home if not
1082
-	 *
1083
-	 * @return void
1084
-	 */
1085
-	public static function checkAdminUser() {
1086
-		OC_Util::checkLoggedIn();
1087
-		if (!OC_User::isAdminUser(OC_User::getUser())) {
1088
-			header('Location: ' . \OCP\Util::linkToAbsolute('', 'index.php'));
1089
-			exit();
1090
-		}
1091
-	}
1092
-
1093
-	/**
1094
-	 * Returns the URL of the default page
1095
-	 * based on the system configuration and
1096
-	 * the apps visible for the current user
1097
-	 *
1098
-	 * @return string URL
1099
-	 * @suppress PhanDeprecatedFunction
1100
-	 */
1101
-	public static function getDefaultPageUrl() {
1102
-		/** @var IConfig $config */
1103
-		$config = \OC::$server->get(IConfig::class);
1104
-		$urlGenerator = \OC::$server->getURLGenerator();
1105
-		// Deny the redirect if the URL contains a @
1106
-		// This prevents unvalidated redirects like ?redirect_url=:[email protected]
1107
-		if (isset($_REQUEST['redirect_url']) && strpos($_REQUEST['redirect_url'], '@') === false) {
1108
-			$location = $urlGenerator->getAbsoluteURL(urldecode($_REQUEST['redirect_url']));
1109
-		} else {
1110
-			$defaultPage = \OC::$server->getConfig()->getAppValue('core', 'defaultpage');
1111
-			if ($defaultPage) {
1112
-				$location = $urlGenerator->getAbsoluteURL($defaultPage);
1113
-			} else {
1114
-				$appId = 'files';
1115
-				$defaultApps = explode(',', $config->getSystemValue('defaultapp', 'dashboard,files'));
1116
-
1117
-				/** @var IUserSession $userSession */
1118
-				$userSession = \OC::$server->get(IUserSession::class);
1119
-				$user = $userSession->getUser();
1120
-				if ($user) {
1121
-					$userDefaultApps = explode(',', $config->getUserValue($user->getUID(), 'core', 'defaultapp'));
1122
-					$defaultApps = array_filter(array_merge($userDefaultApps, $defaultApps));
1123
-				}
1124
-
1125
-				// find the first app that is enabled for the current user
1126
-				foreach ($defaultApps as $defaultApp) {
1127
-					$defaultApp = OC_App::cleanAppId(strip_tags($defaultApp));
1128
-					if (static::getAppManager()->isEnabledForUser($defaultApp)) {
1129
-						$appId = $defaultApp;
1130
-						break;
1131
-					}
1132
-				}
1133
-
1134
-				if ($config->getSystemValue('htaccess.IgnoreFrontController', false) === true || getenv('front_controller_active') === 'true') {
1135
-					$location = $urlGenerator->getAbsoluteURL('/apps/' . $appId . '/');
1136
-				} else {
1137
-					$location = $urlGenerator->getAbsoluteURL('/index.php/apps/' . $appId . '/');
1138
-				}
1139
-			}
1140
-		}
1141
-		return $location;
1142
-	}
1143
-
1144
-	/**
1145
-	 * Redirect to the user default page
1146
-	 *
1147
-	 * @return void
1148
-	 */
1149
-	public static function redirectToDefaultPage() {
1150
-		$location = self::getDefaultPageUrl();
1151
-		header('Location: ' . $location);
1152
-		exit();
1153
-	}
1154
-
1155
-	/**
1156
-	 * get an id unique for this instance
1157
-	 *
1158
-	 * @return string
1159
-	 */
1160
-	public static function getInstanceId() {
1161
-		$id = \OC::$server->getSystemConfig()->getValue('instanceid', null);
1162
-		if (is_null($id)) {
1163
-			// We need to guarantee at least one letter in instanceid so it can be used as the session_name
1164
-			$id = 'oc' . \OC::$server->getSecureRandom()->generate(10, \OCP\Security\ISecureRandom::CHAR_LOWER.\OCP\Security\ISecureRandom::CHAR_DIGITS);
1165
-			\OC::$server->getSystemConfig()->setValue('instanceid', $id);
1166
-		}
1167
-		return $id;
1168
-	}
1169
-
1170
-	/**
1171
-	 * Public function to sanitize HTML
1172
-	 *
1173
-	 * This function is used to sanitize HTML and should be applied on any
1174
-	 * string or array of strings before displaying it on a web page.
1175
-	 *
1176
-	 * @param string|array $value
1177
-	 * @return string|array an array of sanitized strings or a single sanitized string, depends on the input parameter.
1178
-	 */
1179
-	public static function sanitizeHTML($value) {
1180
-		if (is_array($value)) {
1181
-			$value = array_map(function ($value) {
1182
-				return self::sanitizeHTML($value);
1183
-			}, $value);
1184
-		} else {
1185
-			// Specify encoding for PHP<5.4
1186
-			$value = htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
1187
-		}
1188
-		return $value;
1189
-	}
1190
-
1191
-	/**
1192
-	 * Public function to encode url parameters
1193
-	 *
1194
-	 * This function is used to encode path to file before output.
1195
-	 * Encoding is done according to RFC 3986 with one exception:
1196
-	 * Character '/' is preserved as is.
1197
-	 *
1198
-	 * @param string $component part of URI to encode
1199
-	 * @return string
1200
-	 */
1201
-	public static function encodePath($component) {
1202
-		$encoded = rawurlencode($component);
1203
-		$encoded = str_replace('%2F', '/', $encoded);
1204
-		return $encoded;
1205
-	}
1206
-
1207
-
1208
-	public function createHtaccessTestFile(\OCP\IConfig $config) {
1209
-		// php dev server does not support htaccess
1210
-		if (php_sapi_name() === 'cli-server') {
1211
-			return false;
1212
-		}
1213
-
1214
-		// testdata
1215
-		$fileName = '/htaccesstest.txt';
1216
-		$testContent = 'This is used for testing whether htaccess is properly enabled to disallow access from the outside. This file can be safely removed.';
1217
-
1218
-		// creating a test file
1219
-		$testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
1220
-
1221
-		if (file_exists($testFile)) {// already running this test, possible recursive call
1222
-			return false;
1223
-		}
1224
-
1225
-		$fp = @fopen($testFile, 'w');
1226
-		if (!$fp) {
1227
-			throw new OC\HintException('Can\'t create test file to check for working .htaccess file.',
1228
-				'Make sure it is possible for the webserver to write to ' . $testFile);
1229
-		}
1230
-		fwrite($fp, $testContent);
1231
-		fclose($fp);
1232
-
1233
-		return $testContent;
1234
-	}
1235
-
1236
-	/**
1237
-	 * Check if the .htaccess file is working
1238
-	 * @param \OCP\IConfig $config
1239
-	 * @return bool
1240
-	 * @throws Exception
1241
-	 * @throws \OC\HintException If the test file can't get written.
1242
-	 */
1243
-	public function isHtaccessWorking(\OCP\IConfig $config) {
1244
-		if (\OC::$CLI || !$config->getSystemValue('check_for_working_htaccess', true)) {
1245
-			return true;
1246
-		}
1247
-
1248
-		$testContent = $this->createHtaccessTestFile($config);
1249
-		if ($testContent === false) {
1250
-			return false;
1251
-		}
1252
-
1253
-		$fileName = '/htaccesstest.txt';
1254
-		$testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
1255
-
1256
-		// accessing the file via http
1257
-		$url = \OC::$server->getURLGenerator()->getAbsoluteURL(OC::$WEBROOT . '/data' . $fileName);
1258
-		try {
1259
-			$content = \OC::$server->getHTTPClientService()->newClient()->get($url)->getBody();
1260
-		} catch (\Exception $e) {
1261
-			$content = false;
1262
-		}
1263
-
1264
-		if (strpos($url, 'https:') === 0) {
1265
-			$url = 'http:' . substr($url, 6);
1266
-		} else {
1267
-			$url = 'https:' . substr($url, 5);
1268
-		}
1269
-
1270
-		try {
1271
-			$fallbackContent = \OC::$server->getHTTPClientService()->newClient()->get($url)->getBody();
1272
-		} catch (\Exception $e) {
1273
-			$fallbackContent = false;
1274
-		}
1275
-
1276
-		// cleanup
1277
-		@unlink($testFile);
1278
-
1279
-		/*
270
+            if ($mount->getOption('readonly', false)) {
271
+                return new \OC\Files\Storage\Wrapper\PermissionsMask([
272
+                    'storage' => $storage,
273
+                    'mask' => \OCP\Constants::PERMISSION_ALL & ~(
274
+                        \OCP\Constants::PERMISSION_UPDATE |
275
+                        \OCP\Constants::PERMISSION_CREATE |
276
+                        \OCP\Constants::PERMISSION_DELETE
277
+                    ),
278
+                ]);
279
+            }
280
+            return $storage;
281
+        });
282
+
283
+        OC_Hook::emit('OC_Filesystem', 'preSetup', ['user' => $user]);
284
+
285
+        \OC\Files\Filesystem::logWarningWhenAddingStorageWrapper($prevLogging);
286
+
287
+        //check if we are using an object storage
288
+        $objectStore = \OC::$server->getSystemConfig()->getValue('objectstore', null);
289
+        $objectStoreMultibucket = \OC::$server->getSystemConfig()->getValue('objectstore_multibucket', null);
290
+
291
+        // use the same order as in ObjectHomeMountProvider
292
+        if (isset($objectStoreMultibucket)) {
293
+            self::initObjectStoreMultibucketRootFS($objectStoreMultibucket);
294
+        } elseif (isset($objectStore)) {
295
+            self::initObjectStoreRootFS($objectStore);
296
+        } else {
297
+            self::initLocalStorageRootFS();
298
+        }
299
+
300
+        /** @var \OCP\Files\Config\IMountProviderCollection $mountProviderCollection */
301
+        $mountProviderCollection = \OC::$server->query(\OCP\Files\Config\IMountProviderCollection::class);
302
+        $rootMountProviders = $mountProviderCollection->getRootMounts();
303
+
304
+        /** @var \OC\Files\Mount\Manager $mountManager */
305
+        $mountManager = \OC\Files\Filesystem::getMountManager();
306
+        foreach ($rootMountProviders as $rootMountProvider) {
307
+            $mountManager->addMount($rootMountProvider);
308
+        }
309
+
310
+        if ($user != '' && !\OC::$server->getUserManager()->userExists($user)) {
311
+            \OC::$server->getEventLogger()->end('setup_fs');
312
+            return false;
313
+        }
314
+
315
+        //if we aren't logged in, there is no use to set up the filesystem
316
+        if ($user != "") {
317
+            $userDir = '/' . $user . '/files';
318
+
319
+            //jail the user into his "home" directory
320
+            \OC\Files\Filesystem::init($user, $userDir);
321
+
322
+            OC_Hook::emit('OC_Filesystem', 'setup', ['user' => $user, 'user_dir' => $userDir]);
323
+        }
324
+        \OC::$server->getEventLogger()->end('setup_fs');
325
+        return true;
326
+    }
327
+
328
+    /**
329
+     * check if a password is required for each public link
330
+     *
331
+     * @return boolean
332
+     * @suppress PhanDeprecatedFunction
333
+     */
334
+    public static function isPublicLinkPasswordRequired() {
335
+        $enforcePassword = \OC::$server->getConfig()->getAppValue('core', 'shareapi_enforce_links_password', 'no');
336
+        return $enforcePassword === 'yes';
337
+    }
338
+
339
+    /**
340
+     * check if sharing is disabled for the current user
341
+     * @param IConfig $config
342
+     * @param IGroupManager $groupManager
343
+     * @param IUser|null $user
344
+     * @return bool
345
+     */
346
+    public static function isSharingDisabledForUser(IConfig $config, IGroupManager $groupManager, $user) {
347
+        if ($config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') {
348
+            $groupsList = $config->getAppValue('core', 'shareapi_exclude_groups_list', '');
349
+            $excludedGroups = json_decode($groupsList);
350
+            if (is_null($excludedGroups)) {
351
+                $excludedGroups = explode(',', $groupsList);
352
+                $newValue = json_encode($excludedGroups);
353
+                $config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue);
354
+            }
355
+            $usersGroups = $groupManager->getUserGroupIds($user);
356
+            if (!empty($usersGroups)) {
357
+                $remainingGroups = array_diff($usersGroups, $excludedGroups);
358
+                // if the user is only in groups which are disabled for sharing then
359
+                // sharing is also disabled for the user
360
+                if (empty($remainingGroups)) {
361
+                    return true;
362
+                }
363
+            }
364
+        }
365
+        return false;
366
+    }
367
+
368
+    /**
369
+     * check if share API enforces a default expire date
370
+     *
371
+     * @return boolean
372
+     * @suppress PhanDeprecatedFunction
373
+     */
374
+    public static function isDefaultExpireDateEnforced() {
375
+        $isDefaultExpireDateEnabled = \OC::$server->getConfig()->getAppValue('core', 'shareapi_default_expire_date', 'no');
376
+        $enforceDefaultExpireDate = false;
377
+        if ($isDefaultExpireDateEnabled === 'yes') {
378
+            $value = \OC::$server->getConfig()->getAppValue('core', 'shareapi_enforce_expire_date', 'no');
379
+            $enforceDefaultExpireDate = $value === 'yes';
380
+        }
381
+
382
+        return $enforceDefaultExpireDate;
383
+    }
384
+
385
+    /**
386
+     * Get the quota of a user
387
+     *
388
+     * @param IUser|null $user
389
+     * @return float Quota bytes
390
+     */
391
+    public static function getUserQuota(?IUser $user) {
392
+        if (is_null($user)) {
393
+            return \OCP\Files\FileInfo::SPACE_UNLIMITED;
394
+        }
395
+        $userQuota = $user->getQuota();
396
+        if ($userQuota === 'none') {
397
+            return \OCP\Files\FileInfo::SPACE_UNLIMITED;
398
+        }
399
+        return OC_Helper::computerFileSize($userQuota);
400
+    }
401
+
402
+    /**
403
+     * copies the skeleton to the users /files
404
+     *
405
+     * @param string $userId
406
+     * @param \OCP\Files\Folder $userDirectory
407
+     * @throws \OCP\Files\NotFoundException
408
+     * @throws \OCP\Files\NotPermittedException
409
+     * @suppress PhanDeprecatedFunction
410
+     */
411
+    public static function copySkeleton($userId, \OCP\Files\Folder $userDirectory) {
412
+        $plainSkeletonDirectory = \OC::$server->getConfig()->getSystemValue('skeletondirectory', \OC::$SERVERROOT . '/core/skeleton');
413
+        $userLang = \OC::$server->getL10NFactory()->findLanguage();
414
+        $skeletonDirectory = str_replace('{lang}', $userLang, $plainSkeletonDirectory);
415
+
416
+        if (!file_exists($skeletonDirectory)) {
417
+            $dialectStart = strpos($userLang, '_');
418
+            if ($dialectStart !== false) {
419
+                $skeletonDirectory = str_replace('{lang}', substr($userLang, 0, $dialectStart), $plainSkeletonDirectory);
420
+            }
421
+            if ($dialectStart === false || !file_exists($skeletonDirectory)) {
422
+                $skeletonDirectory = str_replace('{lang}', 'default', $plainSkeletonDirectory);
423
+            }
424
+            if (!file_exists($skeletonDirectory)) {
425
+                $skeletonDirectory = '';
426
+            }
427
+        }
428
+
429
+        $instanceId = \OC::$server->getConfig()->getSystemValue('instanceid', '');
430
+
431
+        if ($instanceId === null) {
432
+            throw new \RuntimeException('no instance id!');
433
+        }
434
+        $appdata = 'appdata_' . $instanceId;
435
+        if ($userId === $appdata) {
436
+            throw new \RuntimeException('username is reserved name: ' . $appdata);
437
+        }
438
+
439
+        if (!empty($skeletonDirectory)) {
440
+            \OCP\Util::writeLog(
441
+                'files_skeleton',
442
+                'copying skeleton for '.$userId.' from '.$skeletonDirectory.' to '.$userDirectory->getFullPath('/'),
443
+                ILogger::DEBUG
444
+            );
445
+            self::copyr($skeletonDirectory, $userDirectory);
446
+            // update the file cache
447
+            $userDirectory->getStorage()->getScanner()->scan('', \OC\Files\Cache\Scanner::SCAN_RECURSIVE);
448
+        }
449
+    }
450
+
451
+    /**
452
+     * copies a directory recursively by using streams
453
+     *
454
+     * @param string $source
455
+     * @param \OCP\Files\Folder $target
456
+     * @return void
457
+     */
458
+    public static function copyr($source, \OCP\Files\Folder $target) {
459
+        $logger = \OC::$server->getLogger();
460
+
461
+        // Verify if folder exists
462
+        $dir = opendir($source);
463
+        if ($dir === false) {
464
+            $logger->error(sprintf('Could not opendir "%s"', $source), ['app' => 'core']);
465
+            return;
466
+        }
467
+
468
+        // Copy the files
469
+        while (false !== ($file = readdir($dir))) {
470
+            if (!\OC\Files\Filesystem::isIgnoredDir($file)) {
471
+                if (is_dir($source . '/' . $file)) {
472
+                    $child = $target->newFolder($file);
473
+                    self::copyr($source . '/' . $file, $child);
474
+                } else {
475
+                    $child = $target->newFile($file);
476
+                    $sourceStream = fopen($source . '/' . $file, 'r');
477
+                    if ($sourceStream === false) {
478
+                        $logger->error(sprintf('Could not fopen "%s"', $source . '/' . $file), ['app' => 'core']);
479
+                        closedir($dir);
480
+                        return;
481
+                    }
482
+                    stream_copy_to_stream($sourceStream, $child->fopen('w'));
483
+                }
484
+            }
485
+        }
486
+        closedir($dir);
487
+    }
488
+
489
+    /**
490
+     * @return void
491
+     * @suppress PhanUndeclaredMethod
492
+     */
493
+    public static function tearDownFS() {
494
+        \OC\Files\Filesystem::tearDown();
495
+        \OC::$server->getRootFolder()->clearCache();
496
+        self::$fsSetup = false;
497
+        self::$rootMounted = false;
498
+    }
499
+
500
+    /**
501
+     * get the current installed version of ownCloud
502
+     *
503
+     * @return array
504
+     */
505
+    public static function getVersion() {
506
+        OC_Util::loadVersion();
507
+        return self::$versionCache['OC_Version'];
508
+    }
509
+
510
+    /**
511
+     * get the current installed version string of ownCloud
512
+     *
513
+     * @return string
514
+     */
515
+    public static function getVersionString() {
516
+        OC_Util::loadVersion();
517
+        return self::$versionCache['OC_VersionString'];
518
+    }
519
+
520
+    /**
521
+     * @deprecated the value is of no use anymore
522
+     * @return string
523
+     */
524
+    public static function getEditionString() {
525
+        return '';
526
+    }
527
+
528
+    /**
529
+     * @description get the update channel of the current installed of ownCloud.
530
+     * @return string
531
+     */
532
+    public static function getChannel() {
533
+        OC_Util::loadVersion();
534
+        return \OC::$server->getConfig()->getSystemValue('updater.release.channel', self::$versionCache['OC_Channel']);
535
+    }
536
+
537
+    /**
538
+     * @description get the build number of the current installed of ownCloud.
539
+     * @return string
540
+     */
541
+    public static function getBuild() {
542
+        OC_Util::loadVersion();
543
+        return self::$versionCache['OC_Build'];
544
+    }
545
+
546
+    /**
547
+     * @description load the version.php into the session as cache
548
+     * @suppress PhanUndeclaredVariable
549
+     */
550
+    private static function loadVersion() {
551
+        if (self::$versionCache !== null) {
552
+            return;
553
+        }
554
+
555
+        $timestamp = filemtime(OC::$SERVERROOT . '/version.php');
556
+        require OC::$SERVERROOT . '/version.php';
557
+        /** @var int $timestamp */
558
+        self::$versionCache['OC_Version_Timestamp'] = $timestamp;
559
+        /** @var string $OC_Version */
560
+        self::$versionCache['OC_Version'] = $OC_Version;
561
+        /** @var string $OC_VersionString */
562
+        self::$versionCache['OC_VersionString'] = $OC_VersionString;
563
+        /** @var string $OC_Build */
564
+        self::$versionCache['OC_Build'] = $OC_Build;
565
+
566
+        /** @var string $OC_Channel */
567
+        self::$versionCache['OC_Channel'] = $OC_Channel;
568
+    }
569
+
570
+    /**
571
+     * generates a path for JS/CSS files. If no application is provided it will create the path for core.
572
+     *
573
+     * @param string $application application to get the files from
574
+     * @param string $directory directory within this application (css, js, vendor, etc)
575
+     * @param string $file the file inside of the above folder
576
+     * @return string the path
577
+     */
578
+    private static function generatePath($application, $directory, $file) {
579
+        if (is_null($file)) {
580
+            $file = $application;
581
+            $application = "";
582
+        }
583
+        if (!empty($application)) {
584
+            return "$application/$directory/$file";
585
+        } else {
586
+            return "$directory/$file";
587
+        }
588
+    }
589
+
590
+    /**
591
+     * add a javascript file
592
+     *
593
+     * @param string $application application id
594
+     * @param string|null $file filename
595
+     * @param bool $prepend prepend the Script to the beginning of the list
596
+     * @return void
597
+     */
598
+    public static function addScript($application, $file = null, $prepend = false) {
599
+        $path = OC_Util::generatePath($application, 'js', $file);
600
+
601
+        // core js files need separate handling
602
+        if ($application !== 'core' && $file !== null) {
603
+            self::addTranslations($application);
604
+        }
605
+        self::addExternalResource($application, $prepend, $path, "script");
606
+    }
607
+
608
+    /**
609
+     * add a javascript file from the vendor sub folder
610
+     *
611
+     * @param string $application application id
612
+     * @param string|null $file filename
613
+     * @param bool $prepend prepend the Script to the beginning of the list
614
+     * @return void
615
+     */
616
+    public static function addVendorScript($application, $file = null, $prepend = false) {
617
+        $path = OC_Util::generatePath($application, 'vendor', $file);
618
+        self::addExternalResource($application, $prepend, $path, "script");
619
+    }
620
+
621
+    /**
622
+     * add a translation JS file
623
+     *
624
+     * @param string $application application id
625
+     * @param string|null $languageCode language code, defaults to the current language
626
+     * @param bool|null $prepend prepend the Script to the beginning of the list
627
+     */
628
+    public static function addTranslations($application, $languageCode = null, $prepend = false) {
629
+        if (is_null($languageCode)) {
630
+            $languageCode = \OC::$server->getL10NFactory()->findLanguage($application);
631
+        }
632
+        if (!empty($application)) {
633
+            $path = "$application/l10n/$languageCode";
634
+        } else {
635
+            $path = "l10n/$languageCode";
636
+        }
637
+        self::addExternalResource($application, $prepend, $path, "script");
638
+    }
639
+
640
+    /**
641
+     * add a css file
642
+     *
643
+     * @param string $application application id
644
+     * @param string|null $file filename
645
+     * @param bool $prepend prepend the Style to the beginning of the list
646
+     * @return void
647
+     */
648
+    public static function addStyle($application, $file = null, $prepend = false) {
649
+        $path = OC_Util::generatePath($application, 'css', $file);
650
+        self::addExternalResource($application, $prepend, $path, "style");
651
+    }
652
+
653
+    /**
654
+     * add a css file from the vendor sub folder
655
+     *
656
+     * @param string $application application id
657
+     * @param string|null $file filename
658
+     * @param bool $prepend prepend the Style to the beginning of the list
659
+     * @return void
660
+     */
661
+    public static function addVendorStyle($application, $file = null, $prepend = false) {
662
+        $path = OC_Util::generatePath($application, 'vendor', $file);
663
+        self::addExternalResource($application, $prepend, $path, "style");
664
+    }
665
+
666
+    /**
667
+     * add an external resource css/js file
668
+     *
669
+     * @param string $application application id
670
+     * @param bool $prepend prepend the file to the beginning of the list
671
+     * @param string $path
672
+     * @param string $type (script or style)
673
+     * @return void
674
+     */
675
+    private static function addExternalResource($application, $prepend, $path, $type = "script") {
676
+        if ($type === "style") {
677
+            if (!in_array($path, self::$styles)) {
678
+                if ($prepend === true) {
679
+                    array_unshift(self::$styles, $path);
680
+                } else {
681
+                    self::$styles[] = $path;
682
+                }
683
+            }
684
+        } elseif ($type === "script") {
685
+            if (!in_array($path, self::$scripts)) {
686
+                if ($prepend === true) {
687
+                    array_unshift(self::$scripts, $path);
688
+                } else {
689
+                    self::$scripts [] = $path;
690
+                }
691
+            }
692
+        }
693
+    }
694
+
695
+    /**
696
+     * Add a custom element to the header
697
+     * If $text is null then the element will be written as empty element.
698
+     * So use "" to get a closing tag.
699
+     * @param string $tag tag name of the element
700
+     * @param array $attributes array of attributes for the element
701
+     * @param string $text the text content for the element
702
+     * @param bool $prepend prepend the header to the beginning of the list
703
+     */
704
+    public static function addHeader($tag, $attributes, $text = null, $prepend = false) {
705
+        $header = [
706
+            'tag' => $tag,
707
+            'attributes' => $attributes,
708
+            'text' => $text
709
+        ];
710
+        if ($prepend === true) {
711
+            array_unshift(self::$headers, $header);
712
+        } else {
713
+            self::$headers[] = $header;
714
+        }
715
+    }
716
+
717
+    /**
718
+     * check if the current server configuration is suitable for ownCloud
719
+     *
720
+     * @param \OC\SystemConfig $config
721
+     * @return array arrays with error messages and hints
722
+     */
723
+    public static function checkServer(\OC\SystemConfig $config) {
724
+        $l = \OC::$server->getL10N('lib');
725
+        $errors = [];
726
+        $CONFIG_DATADIRECTORY = $config->getValue('datadirectory', OC::$SERVERROOT . '/data');
727
+
728
+        if (!self::needUpgrade($config) && $config->getValue('installed', false)) {
729
+            // this check needs to be done every time
730
+            $errors = self::checkDataDirectoryValidity($CONFIG_DATADIRECTORY);
731
+        }
732
+
733
+        // Assume that if checkServer() succeeded before in this session, then all is fine.
734
+        if (\OC::$server->getSession()->exists('checkServer_succeeded') && \OC::$server->getSession()->get('checkServer_succeeded')) {
735
+            return $errors;
736
+        }
737
+
738
+        $webServerRestart = false;
739
+        $setup = new \OC\Setup(
740
+            $config,
741
+            \OC::$server->getIniWrapper(),
742
+            \OC::$server->getL10N('lib'),
743
+            \OC::$server->query(\OCP\Defaults::class),
744
+            \OC::$server->getLogger(),
745
+            \OC::$server->getSecureRandom(),
746
+            \OC::$server->query(\OC\Installer::class)
747
+        );
748
+
749
+        $urlGenerator = \OC::$server->getURLGenerator();
750
+
751
+        $availableDatabases = $setup->getSupportedDatabases();
752
+        if (empty($availableDatabases)) {
753
+            $errors[] = [
754
+                'error' => $l->t('No database drivers (sqlite, mysql, or postgresql) installed.'),
755
+                'hint' => '' //TODO: sane hint
756
+            ];
757
+            $webServerRestart = true;
758
+        }
759
+
760
+        // Check if config folder is writable.
761
+        if (!OC_Helper::isReadOnlyConfigEnabled()) {
762
+            if (!is_writable(OC::$configDir) or !is_readable(OC::$configDir)) {
763
+                $errors[] = [
764
+                    'error' => $l->t('Cannot write into "config" directory'),
765
+                    'hint' => $l->t('This can usually be fixed by giving the webserver write access to the config directory. See %s',
766
+                        [ $urlGenerator->linkToDocs('admin-dir_permissions') ]) . '. '
767
+                        . $l->t('Or, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it. See %s',
768
+                        [ $urlGenerator->linkToDocs('admin-config') ])
769
+                ];
770
+            }
771
+        }
772
+
773
+        // Check if there is a writable install folder.
774
+        if ($config->getValue('appstoreenabled', true)) {
775
+            if (OC_App::getInstallPath() === null
776
+                || !is_writable(OC_App::getInstallPath())
777
+                || !is_readable(OC_App::getInstallPath())
778
+            ) {
779
+                $errors[] = [
780
+                    'error' => $l->t('Cannot write into "apps" directory'),
781
+                    'hint' => $l->t('This can usually be fixed by giving the webserver write access to the apps directory'
782
+                        . ' or disabling the appstore in the config file.')
783
+                ];
784
+            }
785
+        }
786
+        // Create root dir.
787
+        if ($config->getValue('installed', false)) {
788
+            if (!is_dir($CONFIG_DATADIRECTORY)) {
789
+                $success = @mkdir($CONFIG_DATADIRECTORY);
790
+                if ($success) {
791
+                    $errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
792
+                } else {
793
+                    $errors[] = [
794
+                        'error' => $l->t('Cannot create "data" directory'),
795
+                        'hint' => $l->t('This can usually be fixed by giving the webserver write access to the root directory. See %s',
796
+                            [$urlGenerator->linkToDocs('admin-dir_permissions')])
797
+                    ];
798
+                }
799
+            } elseif (!is_writable($CONFIG_DATADIRECTORY) or !is_readable($CONFIG_DATADIRECTORY)) {
800
+                // is_writable doesn't work for NFS mounts, so try to write a file and check if it exists.
801
+                $testFile = sprintf('%s/%s.tmp', $CONFIG_DATADIRECTORY, uniqid('data_dir_writability_test_'));
802
+                $handle = fopen($testFile, 'w');
803
+                if (!$handle || fwrite($handle, 'Test write operation') === false) {
804
+                    $permissionsHint = $l->t('Permissions can usually be fixed by giving the webserver write access to the root directory. See %s.',
805
+                        [$urlGenerator->linkToDocs('admin-dir_permissions')]);
806
+                    $errors[] = [
807
+                        'error' => 'Your data directory is not writable',
808
+                        'hint' => $permissionsHint
809
+                    ];
810
+                } else {
811
+                    fclose($handle);
812
+                    unlink($testFile);
813
+                }
814
+            } else {
815
+                $errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
816
+            }
817
+        }
818
+
819
+        if (!OC_Util::isSetLocaleWorking()) {
820
+            $errors[] = [
821
+                'error' => $l->t('Setting locale to %s failed',
822
+                    ['en_US.UTF-8/fr_FR.UTF-8/es_ES.UTF-8/de_DE.UTF-8/ru_RU.UTF-8/'
823
+                        . 'pt_BR.UTF-8/it_IT.UTF-8/ja_JP.UTF-8/zh_CN.UTF-8']),
824
+                'hint' => $l->t('Please install one of these locales on your system and restart your webserver.')
825
+            ];
826
+        }
827
+
828
+        // Contains the dependencies that should be checked against
829
+        // classes = class_exists
830
+        // functions = function_exists
831
+        // defined = defined
832
+        // ini = ini_get
833
+        // If the dependency is not found the missing module name is shown to the EndUser
834
+        // When adding new checks always verify that they pass on Travis as well
835
+        // for ini settings, see https://github.com/owncloud/administration/blob/master/travis-ci/custom.ini
836
+        $dependencies = [
837
+            'classes' => [
838
+                'ZipArchive' => 'zip',
839
+                'DOMDocument' => 'dom',
840
+                'XMLWriter' => 'XMLWriter',
841
+                'XMLReader' => 'XMLReader',
842
+            ],
843
+            'functions' => [
844
+                'xml_parser_create' => 'libxml',
845
+                'mb_strcut' => 'mbstring',
846
+                'ctype_digit' => 'ctype',
847
+                'json_encode' => 'JSON',
848
+                'gd_info' => 'GD',
849
+                'gzencode' => 'zlib',
850
+                'iconv' => 'iconv',
851
+                'simplexml_load_string' => 'SimpleXML',
852
+                'hash' => 'HASH Message Digest Framework',
853
+                'curl_init' => 'cURL',
854
+                'openssl_verify' => 'OpenSSL',
855
+            ],
856
+            'defined' => [
857
+                'PDO::ATTR_DRIVER_NAME' => 'PDO'
858
+            ],
859
+            'ini' => [
860
+                'default_charset' => 'UTF-8',
861
+            ],
862
+        ];
863
+        $missingDependencies = [];
864
+        $invalidIniSettings = [];
865
+
866
+        $iniWrapper = \OC::$server->getIniWrapper();
867
+        foreach ($dependencies['classes'] as $class => $module) {
868
+            if (!class_exists($class)) {
869
+                $missingDependencies[] = $module;
870
+            }
871
+        }
872
+        foreach ($dependencies['functions'] as $function => $module) {
873
+            if (!function_exists($function)) {
874
+                $missingDependencies[] = $module;
875
+            }
876
+        }
877
+        foreach ($dependencies['defined'] as $defined => $module) {
878
+            if (!defined($defined)) {
879
+                $missingDependencies[] = $module;
880
+            }
881
+        }
882
+        foreach ($dependencies['ini'] as $setting => $expected) {
883
+            if (is_bool($expected)) {
884
+                if ($iniWrapper->getBool($setting) !== $expected) {
885
+                    $invalidIniSettings[] = [$setting, $expected];
886
+                }
887
+            }
888
+            if (is_int($expected)) {
889
+                if ($iniWrapper->getNumeric($setting) !== $expected) {
890
+                    $invalidIniSettings[] = [$setting, $expected];
891
+                }
892
+            }
893
+            if (is_string($expected)) {
894
+                if (strtolower($iniWrapper->getString($setting)) !== strtolower($expected)) {
895
+                    $invalidIniSettings[] = [$setting, $expected];
896
+                }
897
+            }
898
+        }
899
+
900
+        foreach ($missingDependencies as $missingDependency) {
901
+            $errors[] = [
902
+                'error' => $l->t('PHP module %s not installed.', [$missingDependency]),
903
+                'hint' => $l->t('Please ask your server administrator to install the module.'),
904
+            ];
905
+            $webServerRestart = true;
906
+        }
907
+        foreach ($invalidIniSettings as $setting) {
908
+            if (is_bool($setting[1])) {
909
+                $setting[1] = $setting[1] ? 'on' : 'off';
910
+            }
911
+            $errors[] = [
912
+                'error' => $l->t('PHP setting "%s" is not set to "%s".', [$setting[0], var_export($setting[1], true)]),
913
+                'hint' =>  $l->t('Adjusting this setting in php.ini will make Nextcloud run again')
914
+            ];
915
+            $webServerRestart = true;
916
+        }
917
+
918
+        /**
919
+         * The mbstring.func_overload check can only be performed if the mbstring
920
+         * module is installed as it will return null if the checking setting is
921
+         * not available and thus a check on the boolean value fails.
922
+         *
923
+         * TODO: Should probably be implemented in the above generic dependency
924
+         *       check somehow in the long-term.
925
+         */
926
+        if ($iniWrapper->getBool('mbstring.func_overload') !== null &&
927
+            $iniWrapper->getBool('mbstring.func_overload') === true) {
928
+            $errors[] = [
929
+                'error' => $l->t('mbstring.func_overload is set to "%s" instead of the expected value "0"', [$iniWrapper->getString('mbstring.func_overload')]),
930
+                'hint' => $l->t('To fix this issue set <code>mbstring.func_overload</code> to <code>0</code> in your php.ini')
931
+            ];
932
+        }
933
+
934
+        if (function_exists('xml_parser_create') &&
935
+            LIBXML_LOADED_VERSION < 20700) {
936
+            $version = LIBXML_LOADED_VERSION;
937
+            $major = floor($version/10000);
938
+            $version -= ($major * 10000);
939
+            $minor = floor($version/100);
940
+            $version -= ($minor * 100);
941
+            $patch = $version;
942
+            $errors[] = [
943
+                'error' => $l->t('libxml2 2.7.0 is at least required. Currently %s is installed.', [$major . '.' . $minor . '.' . $patch]),
944
+                'hint' => $l->t('To fix this issue update your libxml2 version and restart your web server.')
945
+            ];
946
+        }
947
+
948
+        if (!self::isAnnotationsWorking()) {
949
+            $errors[] = [
950
+                'error' => $l->t('PHP is apparently set up to strip inline doc blocks. This will make several core apps inaccessible.'),
951
+                'hint' => $l->t('This is probably caused by a cache/accelerator such as Zend OPcache or eAccelerator.')
952
+            ];
953
+        }
954
+
955
+        if (!\OC::$CLI && $webServerRestart) {
956
+            $errors[] = [
957
+                'error' => $l->t('PHP modules have been installed, but they are still listed as missing?'),
958
+                'hint' => $l->t('Please ask your server administrator to restart the web server.')
959
+            ];
960
+        }
961
+
962
+        $errors = array_merge($errors, self::checkDatabaseVersion());
963
+
964
+        // Cache the result of this function
965
+        \OC::$server->getSession()->set('checkServer_succeeded', count($errors) == 0);
966
+
967
+        return $errors;
968
+    }
969
+
970
+    /**
971
+     * Check the database version
972
+     *
973
+     * @return array errors array
974
+     */
975
+    public static function checkDatabaseVersion() {
976
+        $l = \OC::$server->getL10N('lib');
977
+        $errors = [];
978
+        $dbType = \OC::$server->getSystemConfig()->getValue('dbtype', 'sqlite');
979
+        if ($dbType === 'pgsql') {
980
+            // check PostgreSQL version
981
+            try {
982
+                $result = \OC_DB::executeAudited('SHOW SERVER_VERSION');
983
+                $data = $result->fetchRow();
984
+                if (isset($data['server_version'])) {
985
+                    $version = $data['server_version'];
986
+                    if (version_compare($version, '9.0.0', '<')) {
987
+                        $errors[] = [
988
+                            'error' => $l->t('PostgreSQL >= 9 required'),
989
+                            'hint' => $l->t('Please upgrade your database version')
990
+                        ];
991
+                    }
992
+                }
993
+            } catch (\Doctrine\DBAL\DBALException $e) {
994
+                $logger = \OC::$server->getLogger();
995
+                $logger->warning('Error occurred while checking PostgreSQL version, assuming >= 9');
996
+                $logger->logException($e);
997
+            }
998
+        }
999
+        return $errors;
1000
+    }
1001
+
1002
+    /**
1003
+     * Check for correct file permissions of data directory
1004
+     *
1005
+     * @param string $dataDirectory
1006
+     * @return array arrays with error messages and hints
1007
+     */
1008
+    public static function checkDataDirectoryPermissions($dataDirectory) {
1009
+        if (\OC::$server->getConfig()->getSystemValue('check_data_directory_permissions', true) === false) {
1010
+            return  [];
1011
+        }
1012
+
1013
+        $perms = substr(decoct(@fileperms($dataDirectory)), -3);
1014
+        if (substr($perms, -1) !== '0') {
1015
+            chmod($dataDirectory, 0770);
1016
+            clearstatcache();
1017
+            $perms = substr(decoct(@fileperms($dataDirectory)), -3);
1018
+            if ($perms[2] !== '0') {
1019
+                $l = \OC::$server->getL10N('lib');
1020
+                return [[
1021
+                    'error' => $l->t('Your data directory is readable by other users'),
1022
+                    'hint' => $l->t('Please change the permissions to 0770 so that the directory cannot be listed by other users.'),
1023
+                ]];
1024
+            }
1025
+        }
1026
+        return [];
1027
+    }
1028
+
1029
+    /**
1030
+     * Check that the data directory exists and is valid by
1031
+     * checking the existence of the ".ocdata" file.
1032
+     *
1033
+     * @param string $dataDirectory data directory path
1034
+     * @return array errors found
1035
+     */
1036
+    public static function checkDataDirectoryValidity($dataDirectory) {
1037
+        $l = \OC::$server->getL10N('lib');
1038
+        $errors = [];
1039
+        if ($dataDirectory[0] !== '/') {
1040
+            $errors[] = [
1041
+                'error' => $l->t('Your data directory must be an absolute path'),
1042
+                'hint' => $l->t('Check the value of "datadirectory" in your configuration')
1043
+            ];
1044
+        }
1045
+        if (!file_exists($dataDirectory . '/.ocdata')) {
1046
+            $errors[] = [
1047
+                'error' => $l->t('Your data directory is invalid'),
1048
+                'hint' => $l->t('Ensure there is a file called ".ocdata"' .
1049
+                    ' in the root of the data directory.')
1050
+            ];
1051
+        }
1052
+        return $errors;
1053
+    }
1054
+
1055
+    /**
1056
+     * Check if the user is logged in, redirects to home if not. With
1057
+     * redirect URL parameter to the request URI.
1058
+     *
1059
+     * @return void
1060
+     */
1061
+    public static function checkLoggedIn() {
1062
+        // Check if we are a user
1063
+        if (!\OC::$server->getUserSession()->isLoggedIn()) {
1064
+            header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute(
1065
+                        'core.login.showLoginForm',
1066
+                        [
1067
+                            'redirect_url' => \OC::$server->getRequest()->getRequestUri(),
1068
+                        ]
1069
+                    )
1070
+            );
1071
+            exit();
1072
+        }
1073
+        // Redirect to 2FA challenge selection if 2FA challenge was not solved yet
1074
+        if (\OC::$server->getTwoFactorAuthManager()->needsSecondFactor(\OC::$server->getUserSession()->getUser())) {
1075
+            header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute('core.TwoFactorChallenge.selectChallenge'));
1076
+            exit();
1077
+        }
1078
+    }
1079
+
1080
+    /**
1081
+     * Check if the user is a admin, redirects to home if not
1082
+     *
1083
+     * @return void
1084
+     */
1085
+    public static function checkAdminUser() {
1086
+        OC_Util::checkLoggedIn();
1087
+        if (!OC_User::isAdminUser(OC_User::getUser())) {
1088
+            header('Location: ' . \OCP\Util::linkToAbsolute('', 'index.php'));
1089
+            exit();
1090
+        }
1091
+    }
1092
+
1093
+    /**
1094
+     * Returns the URL of the default page
1095
+     * based on the system configuration and
1096
+     * the apps visible for the current user
1097
+     *
1098
+     * @return string URL
1099
+     * @suppress PhanDeprecatedFunction
1100
+     */
1101
+    public static function getDefaultPageUrl() {
1102
+        /** @var IConfig $config */
1103
+        $config = \OC::$server->get(IConfig::class);
1104
+        $urlGenerator = \OC::$server->getURLGenerator();
1105
+        // Deny the redirect if the URL contains a @
1106
+        // This prevents unvalidated redirects like ?redirect_url=:[email protected]
1107
+        if (isset($_REQUEST['redirect_url']) && strpos($_REQUEST['redirect_url'], '@') === false) {
1108
+            $location = $urlGenerator->getAbsoluteURL(urldecode($_REQUEST['redirect_url']));
1109
+        } else {
1110
+            $defaultPage = \OC::$server->getConfig()->getAppValue('core', 'defaultpage');
1111
+            if ($defaultPage) {
1112
+                $location = $urlGenerator->getAbsoluteURL($defaultPage);
1113
+            } else {
1114
+                $appId = 'files';
1115
+                $defaultApps = explode(',', $config->getSystemValue('defaultapp', 'dashboard,files'));
1116
+
1117
+                /** @var IUserSession $userSession */
1118
+                $userSession = \OC::$server->get(IUserSession::class);
1119
+                $user = $userSession->getUser();
1120
+                if ($user) {
1121
+                    $userDefaultApps = explode(',', $config->getUserValue($user->getUID(), 'core', 'defaultapp'));
1122
+                    $defaultApps = array_filter(array_merge($userDefaultApps, $defaultApps));
1123
+                }
1124
+
1125
+                // find the first app that is enabled for the current user
1126
+                foreach ($defaultApps as $defaultApp) {
1127
+                    $defaultApp = OC_App::cleanAppId(strip_tags($defaultApp));
1128
+                    if (static::getAppManager()->isEnabledForUser($defaultApp)) {
1129
+                        $appId = $defaultApp;
1130
+                        break;
1131
+                    }
1132
+                }
1133
+
1134
+                if ($config->getSystemValue('htaccess.IgnoreFrontController', false) === true || getenv('front_controller_active') === 'true') {
1135
+                    $location = $urlGenerator->getAbsoluteURL('/apps/' . $appId . '/');
1136
+                } else {
1137
+                    $location = $urlGenerator->getAbsoluteURL('/index.php/apps/' . $appId . '/');
1138
+                }
1139
+            }
1140
+        }
1141
+        return $location;
1142
+    }
1143
+
1144
+    /**
1145
+     * Redirect to the user default page
1146
+     *
1147
+     * @return void
1148
+     */
1149
+    public static function redirectToDefaultPage() {
1150
+        $location = self::getDefaultPageUrl();
1151
+        header('Location: ' . $location);
1152
+        exit();
1153
+    }
1154
+
1155
+    /**
1156
+     * get an id unique for this instance
1157
+     *
1158
+     * @return string
1159
+     */
1160
+    public static function getInstanceId() {
1161
+        $id = \OC::$server->getSystemConfig()->getValue('instanceid', null);
1162
+        if (is_null($id)) {
1163
+            // We need to guarantee at least one letter in instanceid so it can be used as the session_name
1164
+            $id = 'oc' . \OC::$server->getSecureRandom()->generate(10, \OCP\Security\ISecureRandom::CHAR_LOWER.\OCP\Security\ISecureRandom::CHAR_DIGITS);
1165
+            \OC::$server->getSystemConfig()->setValue('instanceid', $id);
1166
+        }
1167
+        return $id;
1168
+    }
1169
+
1170
+    /**
1171
+     * Public function to sanitize HTML
1172
+     *
1173
+     * This function is used to sanitize HTML and should be applied on any
1174
+     * string or array of strings before displaying it on a web page.
1175
+     *
1176
+     * @param string|array $value
1177
+     * @return string|array an array of sanitized strings or a single sanitized string, depends on the input parameter.
1178
+     */
1179
+    public static function sanitizeHTML($value) {
1180
+        if (is_array($value)) {
1181
+            $value = array_map(function ($value) {
1182
+                return self::sanitizeHTML($value);
1183
+            }, $value);
1184
+        } else {
1185
+            // Specify encoding for PHP<5.4
1186
+            $value = htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
1187
+        }
1188
+        return $value;
1189
+    }
1190
+
1191
+    /**
1192
+     * Public function to encode url parameters
1193
+     *
1194
+     * This function is used to encode path to file before output.
1195
+     * Encoding is done according to RFC 3986 with one exception:
1196
+     * Character '/' is preserved as is.
1197
+     *
1198
+     * @param string $component part of URI to encode
1199
+     * @return string
1200
+     */
1201
+    public static function encodePath($component) {
1202
+        $encoded = rawurlencode($component);
1203
+        $encoded = str_replace('%2F', '/', $encoded);
1204
+        return $encoded;
1205
+    }
1206
+
1207
+
1208
+    public function createHtaccessTestFile(\OCP\IConfig $config) {
1209
+        // php dev server does not support htaccess
1210
+        if (php_sapi_name() === 'cli-server') {
1211
+            return false;
1212
+        }
1213
+
1214
+        // testdata
1215
+        $fileName = '/htaccesstest.txt';
1216
+        $testContent = 'This is used for testing whether htaccess is properly enabled to disallow access from the outside. This file can be safely removed.';
1217
+
1218
+        // creating a test file
1219
+        $testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
1220
+
1221
+        if (file_exists($testFile)) {// already running this test, possible recursive call
1222
+            return false;
1223
+        }
1224
+
1225
+        $fp = @fopen($testFile, 'w');
1226
+        if (!$fp) {
1227
+            throw new OC\HintException('Can\'t create test file to check for working .htaccess file.',
1228
+                'Make sure it is possible for the webserver to write to ' . $testFile);
1229
+        }
1230
+        fwrite($fp, $testContent);
1231
+        fclose($fp);
1232
+
1233
+        return $testContent;
1234
+    }
1235
+
1236
+    /**
1237
+     * Check if the .htaccess file is working
1238
+     * @param \OCP\IConfig $config
1239
+     * @return bool
1240
+     * @throws Exception
1241
+     * @throws \OC\HintException If the test file can't get written.
1242
+     */
1243
+    public function isHtaccessWorking(\OCP\IConfig $config) {
1244
+        if (\OC::$CLI || !$config->getSystemValue('check_for_working_htaccess', true)) {
1245
+            return true;
1246
+        }
1247
+
1248
+        $testContent = $this->createHtaccessTestFile($config);
1249
+        if ($testContent === false) {
1250
+            return false;
1251
+        }
1252
+
1253
+        $fileName = '/htaccesstest.txt';
1254
+        $testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
1255
+
1256
+        // accessing the file via http
1257
+        $url = \OC::$server->getURLGenerator()->getAbsoluteURL(OC::$WEBROOT . '/data' . $fileName);
1258
+        try {
1259
+            $content = \OC::$server->getHTTPClientService()->newClient()->get($url)->getBody();
1260
+        } catch (\Exception $e) {
1261
+            $content = false;
1262
+        }
1263
+
1264
+        if (strpos($url, 'https:') === 0) {
1265
+            $url = 'http:' . substr($url, 6);
1266
+        } else {
1267
+            $url = 'https:' . substr($url, 5);
1268
+        }
1269
+
1270
+        try {
1271
+            $fallbackContent = \OC::$server->getHTTPClientService()->newClient()->get($url)->getBody();
1272
+        } catch (\Exception $e) {
1273
+            $fallbackContent = false;
1274
+        }
1275
+
1276
+        // cleanup
1277
+        @unlink($testFile);
1278
+
1279
+        /*
1280 1280
 		 * If the content is not equal to test content our .htaccess
1281 1281
 		 * is working as required
1282 1282
 		 */
1283
-		return $content !== $testContent && $fallbackContent !== $testContent;
1284
-	}
1285
-
1286
-	/**
1287
-	 * Check if the setlocal call does not work. This can happen if the right
1288
-	 * local packages are not available on the server.
1289
-	 *
1290
-	 * @return bool
1291
-	 */
1292
-	public static function isSetLocaleWorking() {
1293
-		\Patchwork\Utf8\Bootup::initLocale();
1294
-		if ('' === basename('§')) {
1295
-			return false;
1296
-		}
1297
-		return true;
1298
-	}
1299
-
1300
-	/**
1301
-	 * Check if it's possible to get the inline annotations
1302
-	 *
1303
-	 * @return bool
1304
-	 */
1305
-	public static function isAnnotationsWorking() {
1306
-		$reflection = new \ReflectionMethod(__METHOD__);
1307
-		$docs = $reflection->getDocComment();
1308
-
1309
-		return (is_string($docs) && strlen($docs) > 50);
1310
-	}
1311
-
1312
-	/**
1313
-	 * Check if the PHP module fileinfo is loaded.
1314
-	 *
1315
-	 * @return bool
1316
-	 */
1317
-	public static function fileInfoLoaded() {
1318
-		return function_exists('finfo_open');
1319
-	}
1320
-
1321
-	/**
1322
-	 * clear all levels of output buffering
1323
-	 *
1324
-	 * @return void
1325
-	 */
1326
-	public static function obEnd() {
1327
-		while (ob_get_level()) {
1328
-			ob_end_clean();
1329
-		}
1330
-	}
1331
-
1332
-	/**
1333
-	 * Checks whether the server is running on Mac OS X
1334
-	 *
1335
-	 * @return bool true if running on Mac OS X, false otherwise
1336
-	 */
1337
-	public static function runningOnMac() {
1338
-		return (strtoupper(substr(PHP_OS, 0, 6)) === 'DARWIN');
1339
-	}
1340
-
1341
-	/**
1342
-	 * Handles the case that there may not be a theme, then check if a "default"
1343
-	 * theme exists and take that one
1344
-	 *
1345
-	 * @return string the theme
1346
-	 */
1347
-	public static function getTheme() {
1348
-		$theme = \OC::$server->getSystemConfig()->getValue("theme", '');
1349
-
1350
-		if ($theme === '') {
1351
-			if (is_dir(OC::$SERVERROOT . '/themes/default')) {
1352
-				$theme = 'default';
1353
-			}
1354
-		}
1355
-
1356
-		return $theme;
1357
-	}
1358
-
1359
-	/**
1360
-	 * Normalize a unicode string
1361
-	 *
1362
-	 * @param string $value a not normalized string
1363
-	 * @return bool|string
1364
-	 */
1365
-	public static function normalizeUnicode($value) {
1366
-		if (Normalizer::isNormalized($value)) {
1367
-			return $value;
1368
-		}
1369
-
1370
-		$normalizedValue = Normalizer::normalize($value);
1371
-		if ($normalizedValue === null || $normalizedValue === false) {
1372
-			\OC::$server->getLogger()->warning('normalizing failed for "' . $value . '"', ['app' => 'core']);
1373
-			return $value;
1374
-		}
1375
-
1376
-		return $normalizedValue;
1377
-	}
1378
-
1379
-	/**
1380
-	 * A human readable string is generated based on version and build number
1381
-	 *
1382
-	 * @return string
1383
-	 */
1384
-	public static function getHumanVersion() {
1385
-		$version = OC_Util::getVersionString();
1386
-		$build = OC_Util::getBuild();
1387
-		if (!empty($build) and OC_Util::getChannel() === 'daily') {
1388
-			$version .= ' Build:' . $build;
1389
-		}
1390
-		return $version;
1391
-	}
1392
-
1393
-	/**
1394
-	 * Returns whether the given file name is valid
1395
-	 *
1396
-	 * @param string $file file name to check
1397
-	 * @return bool true if the file name is valid, false otherwise
1398
-	 * @deprecated use \OC\Files\View::verifyPath()
1399
-	 */
1400
-	public static function isValidFileName($file) {
1401
-		$trimmed = trim($file);
1402
-		if ($trimmed === '') {
1403
-			return false;
1404
-		}
1405
-		if (\OC\Files\Filesystem::isIgnoredDir($trimmed)) {
1406
-			return false;
1407
-		}
1408
-
1409
-		// detect part files
1410
-		if (preg_match('/' . \OCP\Files\FileInfo::BLACKLIST_FILES_REGEX . '/', $trimmed) !== 0) {
1411
-			return false;
1412
-		}
1413
-
1414
-		foreach (str_split($trimmed) as $char) {
1415
-			if (strpos(\OCP\Constants::FILENAME_INVALID_CHARS, $char) !== false) {
1416
-				return false;
1417
-			}
1418
-		}
1419
-		return true;
1420
-	}
1421
-
1422
-	/**
1423
-	 * Check whether the instance needs to perform an upgrade,
1424
-	 * either when the core version is higher or any app requires
1425
-	 * an upgrade.
1426
-	 *
1427
-	 * @param \OC\SystemConfig $config
1428
-	 * @return bool whether the core or any app needs an upgrade
1429
-	 * @throws \OC\HintException When the upgrade from the given version is not allowed
1430
-	 */
1431
-	public static function needUpgrade(\OC\SystemConfig $config) {
1432
-		if ($config->getValue('installed', false)) {
1433
-			$installedVersion = $config->getValue('version', '0.0.0');
1434
-			$currentVersion = implode('.', \OCP\Util::getVersion());
1435
-			$versionDiff = version_compare($currentVersion, $installedVersion);
1436
-			if ($versionDiff > 0) {
1437
-				return true;
1438
-			} elseif ($config->getValue('debug', false) && $versionDiff < 0) {
1439
-				// downgrade with debug
1440
-				$installedMajor = explode('.', $installedVersion);
1441
-				$installedMajor = $installedMajor[0] . '.' . $installedMajor[1];
1442
-				$currentMajor = explode('.', $currentVersion);
1443
-				$currentMajor = $currentMajor[0] . '.' . $currentMajor[1];
1444
-				if ($installedMajor === $currentMajor) {
1445
-					// Same major, allow downgrade for developers
1446
-					return true;
1447
-				} else {
1448
-					// downgrade attempt, throw exception
1449
-					throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1450
-				}
1451
-			} elseif ($versionDiff < 0) {
1452
-				// downgrade attempt, throw exception
1453
-				throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1454
-			}
1455
-
1456
-			// also check for upgrades for apps (independently from the user)
1457
-			$apps = \OC_App::getEnabledApps(false, true);
1458
-			$shouldUpgrade = false;
1459
-			foreach ($apps as $app) {
1460
-				if (\OC_App::shouldUpgrade($app)) {
1461
-					$shouldUpgrade = true;
1462
-					break;
1463
-				}
1464
-			}
1465
-			return $shouldUpgrade;
1466
-		} else {
1467
-			return false;
1468
-		}
1469
-	}
1470
-
1471
-	/**
1472
-	 * is this Internet explorer ?
1473
-	 *
1474
-	 * @return boolean
1475
-	 */
1476
-	public static function isIe() {
1477
-		if (!isset($_SERVER['HTTP_USER_AGENT'])) {
1478
-			return false;
1479
-		}
1480
-
1481
-		return preg_match(Request::USER_AGENT_IE, $_SERVER['HTTP_USER_AGENT']) === 1;
1482
-	}
1283
+        return $content !== $testContent && $fallbackContent !== $testContent;
1284
+    }
1285
+
1286
+    /**
1287
+     * Check if the setlocal call does not work. This can happen if the right
1288
+     * local packages are not available on the server.
1289
+     *
1290
+     * @return bool
1291
+     */
1292
+    public static function isSetLocaleWorking() {
1293
+        \Patchwork\Utf8\Bootup::initLocale();
1294
+        if ('' === basename('§')) {
1295
+            return false;
1296
+        }
1297
+        return true;
1298
+    }
1299
+
1300
+    /**
1301
+     * Check if it's possible to get the inline annotations
1302
+     *
1303
+     * @return bool
1304
+     */
1305
+    public static function isAnnotationsWorking() {
1306
+        $reflection = new \ReflectionMethod(__METHOD__);
1307
+        $docs = $reflection->getDocComment();
1308
+
1309
+        return (is_string($docs) && strlen($docs) > 50);
1310
+    }
1311
+
1312
+    /**
1313
+     * Check if the PHP module fileinfo is loaded.
1314
+     *
1315
+     * @return bool
1316
+     */
1317
+    public static function fileInfoLoaded() {
1318
+        return function_exists('finfo_open');
1319
+    }
1320
+
1321
+    /**
1322
+     * clear all levels of output buffering
1323
+     *
1324
+     * @return void
1325
+     */
1326
+    public static function obEnd() {
1327
+        while (ob_get_level()) {
1328
+            ob_end_clean();
1329
+        }
1330
+    }
1331
+
1332
+    /**
1333
+     * Checks whether the server is running on Mac OS X
1334
+     *
1335
+     * @return bool true if running on Mac OS X, false otherwise
1336
+     */
1337
+    public static function runningOnMac() {
1338
+        return (strtoupper(substr(PHP_OS, 0, 6)) === 'DARWIN');
1339
+    }
1340
+
1341
+    /**
1342
+     * Handles the case that there may not be a theme, then check if a "default"
1343
+     * theme exists and take that one
1344
+     *
1345
+     * @return string the theme
1346
+     */
1347
+    public static function getTheme() {
1348
+        $theme = \OC::$server->getSystemConfig()->getValue("theme", '');
1349
+
1350
+        if ($theme === '') {
1351
+            if (is_dir(OC::$SERVERROOT . '/themes/default')) {
1352
+                $theme = 'default';
1353
+            }
1354
+        }
1355
+
1356
+        return $theme;
1357
+    }
1358
+
1359
+    /**
1360
+     * Normalize a unicode string
1361
+     *
1362
+     * @param string $value a not normalized string
1363
+     * @return bool|string
1364
+     */
1365
+    public static function normalizeUnicode($value) {
1366
+        if (Normalizer::isNormalized($value)) {
1367
+            return $value;
1368
+        }
1369
+
1370
+        $normalizedValue = Normalizer::normalize($value);
1371
+        if ($normalizedValue === null || $normalizedValue === false) {
1372
+            \OC::$server->getLogger()->warning('normalizing failed for "' . $value . '"', ['app' => 'core']);
1373
+            return $value;
1374
+        }
1375
+
1376
+        return $normalizedValue;
1377
+    }
1378
+
1379
+    /**
1380
+     * A human readable string is generated based on version and build number
1381
+     *
1382
+     * @return string
1383
+     */
1384
+    public static function getHumanVersion() {
1385
+        $version = OC_Util::getVersionString();
1386
+        $build = OC_Util::getBuild();
1387
+        if (!empty($build) and OC_Util::getChannel() === 'daily') {
1388
+            $version .= ' Build:' . $build;
1389
+        }
1390
+        return $version;
1391
+    }
1392
+
1393
+    /**
1394
+     * Returns whether the given file name is valid
1395
+     *
1396
+     * @param string $file file name to check
1397
+     * @return bool true if the file name is valid, false otherwise
1398
+     * @deprecated use \OC\Files\View::verifyPath()
1399
+     */
1400
+    public static function isValidFileName($file) {
1401
+        $trimmed = trim($file);
1402
+        if ($trimmed === '') {
1403
+            return false;
1404
+        }
1405
+        if (\OC\Files\Filesystem::isIgnoredDir($trimmed)) {
1406
+            return false;
1407
+        }
1408
+
1409
+        // detect part files
1410
+        if (preg_match('/' . \OCP\Files\FileInfo::BLACKLIST_FILES_REGEX . '/', $trimmed) !== 0) {
1411
+            return false;
1412
+        }
1413
+
1414
+        foreach (str_split($trimmed) as $char) {
1415
+            if (strpos(\OCP\Constants::FILENAME_INVALID_CHARS, $char) !== false) {
1416
+                return false;
1417
+            }
1418
+        }
1419
+        return true;
1420
+    }
1421
+
1422
+    /**
1423
+     * Check whether the instance needs to perform an upgrade,
1424
+     * either when the core version is higher or any app requires
1425
+     * an upgrade.
1426
+     *
1427
+     * @param \OC\SystemConfig $config
1428
+     * @return bool whether the core or any app needs an upgrade
1429
+     * @throws \OC\HintException When the upgrade from the given version is not allowed
1430
+     */
1431
+    public static function needUpgrade(\OC\SystemConfig $config) {
1432
+        if ($config->getValue('installed', false)) {
1433
+            $installedVersion = $config->getValue('version', '0.0.0');
1434
+            $currentVersion = implode('.', \OCP\Util::getVersion());
1435
+            $versionDiff = version_compare($currentVersion, $installedVersion);
1436
+            if ($versionDiff > 0) {
1437
+                return true;
1438
+            } elseif ($config->getValue('debug', false) && $versionDiff < 0) {
1439
+                // downgrade with debug
1440
+                $installedMajor = explode('.', $installedVersion);
1441
+                $installedMajor = $installedMajor[0] . '.' . $installedMajor[1];
1442
+                $currentMajor = explode('.', $currentVersion);
1443
+                $currentMajor = $currentMajor[0] . '.' . $currentMajor[1];
1444
+                if ($installedMajor === $currentMajor) {
1445
+                    // Same major, allow downgrade for developers
1446
+                    return true;
1447
+                } else {
1448
+                    // downgrade attempt, throw exception
1449
+                    throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1450
+                }
1451
+            } elseif ($versionDiff < 0) {
1452
+                // downgrade attempt, throw exception
1453
+                throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1454
+            }
1455
+
1456
+            // also check for upgrades for apps (independently from the user)
1457
+            $apps = \OC_App::getEnabledApps(false, true);
1458
+            $shouldUpgrade = false;
1459
+            foreach ($apps as $app) {
1460
+                if (\OC_App::shouldUpgrade($app)) {
1461
+                    $shouldUpgrade = true;
1462
+                    break;
1463
+                }
1464
+            }
1465
+            return $shouldUpgrade;
1466
+        } else {
1467
+            return false;
1468
+        }
1469
+    }
1470
+
1471
+    /**
1472
+     * is this Internet explorer ?
1473
+     *
1474
+     * @return boolean
1475
+     */
1476
+    public static function isIe() {
1477
+        if (!isset($_SERVER['HTTP_USER_AGENT'])) {
1478
+            return false;
1479
+        }
1480
+
1481
+        return preg_match(Request::USER_AGENT_IE, $_SERVER['HTTP_USER_AGENT']) === 1;
1482
+    }
1483 1483
 }
Please login to merge, or discard this patch.