Completed
Pull Request — master (#9293)
by Blizzz
16:29
created
lib/private/Setup/MySQL.php 3 patches
Indentation   +139 added lines, -139 removed lines patch added patch discarded remove patch
@@ -34,143 +34,143 @@
 block discarded – undo
34 34
 use OCP\ILogger;
35 35
 
36 36
 class MySQL extends AbstractDatabase {
37
-	public $dbprettyname = 'MySQL/MariaDB';
38
-
39
-	public function setupDatabase($username) {
40
-		//check if the database user has admin right
41
-		$connection = $this->connect(['dbname' => null]);
42
-
43
-		// detect mb4
44
-		$tools = new MySqlTools();
45
-		if ($tools->supports4ByteCharset($connection)) {
46
-			$this->config->setValue('mysql.utf8mb4', true);
47
-			$connection = $this->connect(['dbname' => null]);
48
-		}
49
-
50
-		$this->createSpecificUser($username, $connection);
51
-
52
-		//create the database
53
-		$this->createDatabase($connection);
54
-
55
-		//fill the database if needed
56
-		$query='select count(*) from information_schema.tables where table_schema=? AND table_name = ?';
57
-		$connection->executeQuery($query, [$this->dbName, $this->tablePrefix.'users']);
58
-	}
59
-
60
-	/**
61
-	 * @param \OC\DB\Connection $connection
62
-	 */
63
-	private function createDatabase($connection) {
64
-		try{
65
-			$name = $this->dbName;
66
-			$user = $this->dbUser;
67
-			//we can't use OC_DB functions here because we need to connect as the administrative user.
68
-			$characterSet = $this->config->getValue('mysql.utf8mb4', false) ? 'utf8mb4' : 'utf8';
69
-			$query = "CREATE DATABASE IF NOT EXISTS `$name` CHARACTER SET $characterSet COLLATE ${characterSet}_bin;";
70
-			$connection->executeUpdate($query);
71
-		} catch (\Exception $ex) {
72
-			$this->logger->logException($ex, [
73
-				'message' => 'Database creation failed.',
74
-				'level' => ILogger::ERROR,
75
-				'app' => 'mysql.setup',
76
-			]);
77
-			return;
78
-		}
79
-
80
-		try {
81
-			//this query will fail if there aren't the right permissions, ignore the error
82
-			$query="GRANT ALL PRIVILEGES ON `$name` . * TO '$user'";
83
-			$connection->executeUpdate($query);
84
-		} catch (\Exception $ex) {
85
-			$this->logger->logException($ex, [
86
-				'message' => 'Could not automatically grant privileges, this can be ignored if database user already had privileges.',
87
-				'level' => ILogger::DEBUG,
88
-				'app' => 'mysql.setup',
89
-			]);
90
-		}
91
-	}
92
-
93
-	/**
94
-	 * @param IDBConnection $connection
95
-	 * @throws \OC\DatabaseSetupException
96
-	 */
97
-	private function createDBUser($connection) {
98
-		try{
99
-			$name = $this->dbUser;
100
-			$password = $this->dbPassword;
101
-			// we need to create 2 accounts, one for global use and one for local user. if we don't specify the local one,
102
-			// the anonymous user would take precedence when there is one.
103
-			$query = "CREATE USER '$name'@'localhost' IDENTIFIED BY '$password'";
104
-			$connection->executeUpdate($query);
105
-			$query = "CREATE USER '$name'@'%' IDENTIFIED BY '$password'";
106
-			$connection->executeUpdate($query);
107
-		}
108
-		catch (\Exception $ex){
109
-			$this->logger->logException($ex, [
110
-				'message' => 'Database user creation failed.',
111
-				'level' => ILogger::ERROR,
112
-				'app' => 'mysql.setup',
113
-			]);
114
-		}
115
-	}
116
-
117
-	/**
118
-	 * @param $username
119
-	 * @param IDBConnection $connection
120
-	 * @return array
121
-	 */
122
-	private function createSpecificUser($username, $connection) {
123
-		try {
124
-			//user already specified in config
125
-			$oldUser = $this->config->getValue('dbuser', false);
126
-
127
-			//we don't have a dbuser specified in config
128
-			if ($this->dbUser !== $oldUser) {
129
-				//add prefix to the admin username to prevent collisions
130
-				$adminUser = substr('oc_' . $username, 0, 16);
131
-
132
-				$i = 1;
133
-				while (true) {
134
-					//this should be enough to check for admin rights in mysql
135
-					$query = 'SELECT user FROM mysql.user WHERE user=?';
136
-					$result = $connection->executeQuery($query, [$adminUser]);
137
-
138
-					//current dbuser has admin rights
139
-					if ($result) {
140
-						$data = $result->fetchAll();
141
-						//new dbuser does not exist
142
-						if (count($data) === 0) {
143
-							//use the admin login data for the new database user
144
-							$this->dbUser = $adminUser;
145
-
146
-							//create a random password so we don't need to store the admin password in the config file
147
-							$this->dbPassword =  $this->random->generate(30);
148
-
149
-							$this->createDBUser($connection);
150
-
151
-							break;
152
-						} else {
153
-							//repeat with different username
154
-							$length = strlen((string)$i);
155
-							$adminUser = substr('oc_' . $username, 0, 16 - $length) . $i;
156
-							$i++;
157
-						}
158
-					} else {
159
-						break;
160
-					}
161
-				}
162
-			}
163
-		} catch (\Exception $ex) {
164
-			$this->logger->logException($ex, [
165
-				'message' => 'Can not create a new MySQL user, will continue with the provided user.',
166
-				'level' => ILogger::INFO,
167
-				'app' => 'mysql.setup',
168
-			]);
169
-		}
170
-
171
-		$this->config->setValues([
172
-			'dbuser' => $this->dbUser,
173
-			'dbpassword' => $this->dbPassword,
174
-		]);
175
-	}
37
+    public $dbprettyname = 'MySQL/MariaDB';
38
+
39
+    public function setupDatabase($username) {
40
+        //check if the database user has admin right
41
+        $connection = $this->connect(['dbname' => null]);
42
+
43
+        // detect mb4
44
+        $tools = new MySqlTools();
45
+        if ($tools->supports4ByteCharset($connection)) {
46
+            $this->config->setValue('mysql.utf8mb4', true);
47
+            $connection = $this->connect(['dbname' => null]);
48
+        }
49
+
50
+        $this->createSpecificUser($username, $connection);
51
+
52
+        //create the database
53
+        $this->createDatabase($connection);
54
+
55
+        //fill the database if needed
56
+        $query='select count(*) from information_schema.tables where table_schema=? AND table_name = ?';
57
+        $connection->executeQuery($query, [$this->dbName, $this->tablePrefix.'users']);
58
+    }
59
+
60
+    /**
61
+     * @param \OC\DB\Connection $connection
62
+     */
63
+    private function createDatabase($connection) {
64
+        try{
65
+            $name = $this->dbName;
66
+            $user = $this->dbUser;
67
+            //we can't use OC_DB functions here because we need to connect as the administrative user.
68
+            $characterSet = $this->config->getValue('mysql.utf8mb4', false) ? 'utf8mb4' : 'utf8';
69
+            $query = "CREATE DATABASE IF NOT EXISTS `$name` CHARACTER SET $characterSet COLLATE ${characterSet}_bin;";
70
+            $connection->executeUpdate($query);
71
+        } catch (\Exception $ex) {
72
+            $this->logger->logException($ex, [
73
+                'message' => 'Database creation failed.',
74
+                'level' => ILogger::ERROR,
75
+                'app' => 'mysql.setup',
76
+            ]);
77
+            return;
78
+        }
79
+
80
+        try {
81
+            //this query will fail if there aren't the right permissions, ignore the error
82
+            $query="GRANT ALL PRIVILEGES ON `$name` . * TO '$user'";
83
+            $connection->executeUpdate($query);
84
+        } catch (\Exception $ex) {
85
+            $this->logger->logException($ex, [
86
+                'message' => 'Could not automatically grant privileges, this can be ignored if database user already had privileges.',
87
+                'level' => ILogger::DEBUG,
88
+                'app' => 'mysql.setup',
89
+            ]);
90
+        }
91
+    }
92
+
93
+    /**
94
+     * @param IDBConnection $connection
95
+     * @throws \OC\DatabaseSetupException
96
+     */
97
+    private function createDBUser($connection) {
98
+        try{
99
+            $name = $this->dbUser;
100
+            $password = $this->dbPassword;
101
+            // we need to create 2 accounts, one for global use and one for local user. if we don't specify the local one,
102
+            // the anonymous user would take precedence when there is one.
103
+            $query = "CREATE USER '$name'@'localhost' IDENTIFIED BY '$password'";
104
+            $connection->executeUpdate($query);
105
+            $query = "CREATE USER '$name'@'%' IDENTIFIED BY '$password'";
106
+            $connection->executeUpdate($query);
107
+        }
108
+        catch (\Exception $ex){
109
+            $this->logger->logException($ex, [
110
+                'message' => 'Database user creation failed.',
111
+                'level' => ILogger::ERROR,
112
+                'app' => 'mysql.setup',
113
+            ]);
114
+        }
115
+    }
116
+
117
+    /**
118
+     * @param $username
119
+     * @param IDBConnection $connection
120
+     * @return array
121
+     */
122
+    private function createSpecificUser($username, $connection) {
123
+        try {
124
+            //user already specified in config
125
+            $oldUser = $this->config->getValue('dbuser', false);
126
+
127
+            //we don't have a dbuser specified in config
128
+            if ($this->dbUser !== $oldUser) {
129
+                //add prefix to the admin username to prevent collisions
130
+                $adminUser = substr('oc_' . $username, 0, 16);
131
+
132
+                $i = 1;
133
+                while (true) {
134
+                    //this should be enough to check for admin rights in mysql
135
+                    $query = 'SELECT user FROM mysql.user WHERE user=?';
136
+                    $result = $connection->executeQuery($query, [$adminUser]);
137
+
138
+                    //current dbuser has admin rights
139
+                    if ($result) {
140
+                        $data = $result->fetchAll();
141
+                        //new dbuser does not exist
142
+                        if (count($data) === 0) {
143
+                            //use the admin login data for the new database user
144
+                            $this->dbUser = $adminUser;
145
+
146
+                            //create a random password so we don't need to store the admin password in the config file
147
+                            $this->dbPassword =  $this->random->generate(30);
148
+
149
+                            $this->createDBUser($connection);
150
+
151
+                            break;
152
+                        } else {
153
+                            //repeat with different username
154
+                            $length = strlen((string)$i);
155
+                            $adminUser = substr('oc_' . $username, 0, 16 - $length) . $i;
156
+                            $i++;
157
+                        }
158
+                    } else {
159
+                        break;
160
+                    }
161
+                }
162
+            }
163
+        } catch (\Exception $ex) {
164
+            $this->logger->logException($ex, [
165
+                'message' => 'Can not create a new MySQL user, will continue with the provided user.',
166
+                'level' => ILogger::INFO,
167
+                'app' => 'mysql.setup',
168
+            ]);
169
+        }
170
+
171
+        $this->config->setValues([
172
+            'dbuser' => $this->dbUser,
173
+            'dbpassword' => $this->dbPassword,
174
+        ]);
175
+    }
176 176
 }
Please login to merge, or discard this patch.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -53,7 +53,7 @@  discard block
 block discarded – undo
53 53
 		$this->createDatabase($connection);
54 54
 
55 55
 		//fill the database if needed
56
-		$query='select count(*) from information_schema.tables where table_schema=? AND table_name = ?';
56
+		$query = 'select count(*) from information_schema.tables where table_schema=? AND table_name = ?';
57 57
 		$connection->executeQuery($query, [$this->dbName, $this->tablePrefix.'users']);
58 58
 	}
59 59
 
@@ -61,7 +61,7 @@  discard block
 block discarded – undo
61 61
 	 * @param \OC\DB\Connection $connection
62 62
 	 */
63 63
 	private function createDatabase($connection) {
64
-		try{
64
+		try {
65 65
 			$name = $this->dbName;
66 66
 			$user = $this->dbUser;
67 67
 			//we can't use OC_DB functions here because we need to connect as the administrative user.
@@ -79,7 +79,7 @@  discard block
 block discarded – undo
79 79
 
80 80
 		try {
81 81
 			//this query will fail if there aren't the right permissions, ignore the error
82
-			$query="GRANT ALL PRIVILEGES ON `$name` . * TO '$user'";
82
+			$query = "GRANT ALL PRIVILEGES ON `$name` . * TO '$user'";
83 83
 			$connection->executeUpdate($query);
84 84
 		} catch (\Exception $ex) {
85 85
 			$this->logger->logException($ex, [
@@ -95,7 +95,7 @@  discard block
 block discarded – undo
95 95
 	 * @throws \OC\DatabaseSetupException
96 96
 	 */
97 97
 	private function createDBUser($connection) {
98
-		try{
98
+		try {
99 99
 			$name = $this->dbUser;
100 100
 			$password = $this->dbPassword;
101 101
 			// we need to create 2 accounts, one for global use and one for local user. if we don't specify the local one,
@@ -105,7 +105,7 @@  discard block
 block discarded – undo
105 105
 			$query = "CREATE USER '$name'@'%' IDENTIFIED BY '$password'";
106 106
 			$connection->executeUpdate($query);
107 107
 		}
108
-		catch (\Exception $ex){
108
+		catch (\Exception $ex) {
109 109
 			$this->logger->logException($ex, [
110 110
 				'message' => 'Database user creation failed.',
111 111
 				'level' => ILogger::ERROR,
@@ -127,7 +127,7 @@  discard block
 block discarded – undo
127 127
 			//we don't have a dbuser specified in config
128 128
 			if ($this->dbUser !== $oldUser) {
129 129
 				//add prefix to the admin username to prevent collisions
130
-				$adminUser = substr('oc_' . $username, 0, 16);
130
+				$adminUser = substr('oc_'.$username, 0, 16);
131 131
 
132 132
 				$i = 1;
133 133
 				while (true) {
@@ -144,15 +144,15 @@  discard block
 block discarded – undo
144 144
 							$this->dbUser = $adminUser;
145 145
 
146 146
 							//create a random password so we don't need to store the admin password in the config file
147
-							$this->dbPassword =  $this->random->generate(30);
147
+							$this->dbPassword = $this->random->generate(30);
148 148
 
149 149
 							$this->createDBUser($connection);
150 150
 
151 151
 							break;
152 152
 						} else {
153 153
 							//repeat with different username
154
-							$length = strlen((string)$i);
155
-							$adminUser = substr('oc_' . $username, 0, 16 - $length) . $i;
154
+							$length = strlen((string) $i);
155
+							$adminUser = substr('oc_'.$username, 0, 16 - $length).$i;
156 156
 							$i++;
157 157
 						}
158 158
 					} else {
Please login to merge, or discard this patch.
Braces   +1 added lines, -2 removed lines patch added patch discarded remove patch
@@ -104,8 +104,7 @@
 block discarded – undo
104 104
 			$connection->executeUpdate($query);
105 105
 			$query = "CREATE USER '$name'@'%' IDENTIFIED BY '$password'";
106 106
 			$connection->executeUpdate($query);
107
-		}
108
-		catch (\Exception $ex){
107
+		} catch (\Exception $ex){
109 108
 			$this->logger->logException($ex, [
110 109
 				'message' => 'Database user creation failed.',
111 110
 				'level' => ILogger::ERROR,
Please login to merge, or discard this patch.
lib/private/Preview/Bitmap.php 1 patch
Indentation   +81 added lines, -81 removed lines patch added patch discarded remove patch
@@ -35,86 +35,86 @@
 block discarded – undo
35 35
  */
36 36
 abstract class Bitmap extends Provider {
37 37
 
38
-	/**
39
-	 * {@inheritDoc}
40
-	 */
41
-	public function getThumbnail($path, $maxX, $maxY, $scalingup, $fileview) {
42
-
43
-		$tmpPath = $fileview->toTmpFile($path);
44
-		if (!$tmpPath) {
45
-			return false;
46
-		}
47
-
48
-		// Creates \Imagick object from bitmap or vector file
49
-		try {
50
-			$bp = $this->getResizedPreview($tmpPath, $maxX, $maxY);
51
-		} catch (\Exception $e) {
52
-			\OC::$server->getLogger()->logException($e, [
53
-				'message' => 'Imagick says:',
54
-				'level' => ILogger::ERROR,
55
-				'app' => 'core',
56
-			]);
57
-			return false;
58
-		}
59
-
60
-		unlink($tmpPath);
61
-
62
-		//new bitmap image object
63
-		$image = new \OC_Image();
64
-		$image->loadFromData($bp);
65
-		//check if image object is valid
66
-		return $image->valid() ? $image : false;
67
-	}
68
-
69
-	/**
70
-	 * Returns a preview of maxX times maxY dimensions in PNG format
71
-	 *
72
-	 *    * The default resolution is already 72dpi, no need to change it for a bitmap output
73
-	 *    * It's possible to have proper colour conversion using profileimage().
74
-	 *    ICC profiles are here: http://www.color.org/srgbprofiles.xalter
75
-	 *    * It's possible to Gamma-correct an image via gammaImage()
76
-	 *
77
-	 * @param string $tmpPath the location of the file to convert
78
-	 * @param int $maxX
79
-	 * @param int $maxY
80
-	 *
81
-	 * @return \Imagick
82
-	 */
83
-	private function getResizedPreview($tmpPath, $maxX, $maxY) {
84
-		$bp = new Imagick();
85
-
86
-		// Layer 0 contains either the bitmap or a flat representation of all vector layers
87
-		$bp->readImage($tmpPath . '[0]');
88
-
89
-		$bp = $this->resize($bp, $maxX, $maxY);
90
-
91
-		$bp->setImageFormat('png');
92
-
93
-		return $bp;
94
-	}
95
-
96
-	/**
97
-	 * Returns a resized \Imagick object
98
-	 *
99
-	 * If you want to know more on the various methods available to resize an
100
-	 * image, check out this link : @link https://stackoverflow.com/questions/8517304/what-the-difference-of-sample-resample-scale-resize-adaptive-resize-thumbnail-im
101
-	 *
102
-	 * @param \Imagick $bp
103
-	 * @param int $maxX
104
-	 * @param int $maxY
105
-	 *
106
-	 * @return \Imagick
107
-	 */
108
-	private function resize($bp, $maxX, $maxY) {
109
-		list($previewWidth, $previewHeight) = array_values($bp->getImageGeometry());
110
-
111
-		// We only need to resize a preview which doesn't fit in the maximum dimensions
112
-		if ($previewWidth > $maxX || $previewHeight > $maxY) {
113
-			// TODO: LANCZOS is the default filter, CATROM could bring similar results faster
114
-			$bp->resizeImage($maxX, $maxY, imagick::FILTER_LANCZOS, 1, true);
115
-		}
116
-
117
-		return $bp;
118
-	}
38
+    /**
39
+     * {@inheritDoc}
40
+     */
41
+    public function getThumbnail($path, $maxX, $maxY, $scalingup, $fileview) {
42
+
43
+        $tmpPath = $fileview->toTmpFile($path);
44
+        if (!$tmpPath) {
45
+            return false;
46
+        }
47
+
48
+        // Creates \Imagick object from bitmap or vector file
49
+        try {
50
+            $bp = $this->getResizedPreview($tmpPath, $maxX, $maxY);
51
+        } catch (\Exception $e) {
52
+            \OC::$server->getLogger()->logException($e, [
53
+                'message' => 'Imagick says:',
54
+                'level' => ILogger::ERROR,
55
+                'app' => 'core',
56
+            ]);
57
+            return false;
58
+        }
59
+
60
+        unlink($tmpPath);
61
+
62
+        //new bitmap image object
63
+        $image = new \OC_Image();
64
+        $image->loadFromData($bp);
65
+        //check if image object is valid
66
+        return $image->valid() ? $image : false;
67
+    }
68
+
69
+    /**
70
+     * Returns a preview of maxX times maxY dimensions in PNG format
71
+     *
72
+     *    * The default resolution is already 72dpi, no need to change it for a bitmap output
73
+     *    * It's possible to have proper colour conversion using profileimage().
74
+     *    ICC profiles are here: http://www.color.org/srgbprofiles.xalter
75
+     *    * It's possible to Gamma-correct an image via gammaImage()
76
+     *
77
+     * @param string $tmpPath the location of the file to convert
78
+     * @param int $maxX
79
+     * @param int $maxY
80
+     *
81
+     * @return \Imagick
82
+     */
83
+    private function getResizedPreview($tmpPath, $maxX, $maxY) {
84
+        $bp = new Imagick();
85
+
86
+        // Layer 0 contains either the bitmap or a flat representation of all vector layers
87
+        $bp->readImage($tmpPath . '[0]');
88
+
89
+        $bp = $this->resize($bp, $maxX, $maxY);
90
+
91
+        $bp->setImageFormat('png');
92
+
93
+        return $bp;
94
+    }
95
+
96
+    /**
97
+     * Returns a resized \Imagick object
98
+     *
99
+     * If you want to know more on the various methods available to resize an
100
+     * image, check out this link : @link https://stackoverflow.com/questions/8517304/what-the-difference-of-sample-resample-scale-resize-adaptive-resize-thumbnail-im
101
+     *
102
+     * @param \Imagick $bp
103
+     * @param int $maxX
104
+     * @param int $maxY
105
+     *
106
+     * @return \Imagick
107
+     */
108
+    private function resize($bp, $maxX, $maxY) {
109
+        list($previewWidth, $previewHeight) = array_values($bp->getImageGeometry());
110
+
111
+        // We only need to resize a preview which doesn't fit in the maximum dimensions
112
+        if ($previewWidth > $maxX || $previewHeight > $maxY) {
113
+            // TODO: LANCZOS is the default filter, CATROM could bring similar results faster
114
+            $bp->resizeImage($maxX, $maxY, imagick::FILTER_LANCZOS, 1, true);
115
+        }
116
+
117
+        return $bp;
118
+    }
119 119
 
120 120
 }
Please login to merge, or discard this patch.
lib/private/Preview/SVG.php 1 patch
Indentation   +40 added lines, -40 removed lines patch added patch discarded remove patch
@@ -27,50 +27,50 @@
 block discarded – undo
27 27
 use OCP\ILogger;
28 28
 
29 29
 class SVG extends Provider {
30
-	/**
31
-	 * {@inheritDoc}
32
-	 */
33
-	public function getMimeType() {
34
-		return '/image\/svg\+xml/';
35
-	}
30
+    /**
31
+     * {@inheritDoc}
32
+     */
33
+    public function getMimeType() {
34
+        return '/image\/svg\+xml/';
35
+    }
36 36
 
37
-	/**
38
-	 * {@inheritDoc}
39
-	 */
40
-	public function getThumbnail($path, $maxX, $maxY, $scalingup, $fileview) {
41
-		try {
42
-			$svg = new \Imagick();
43
-			$svg->setBackgroundColor(new \ImagickPixel('transparent'));
37
+    /**
38
+     * {@inheritDoc}
39
+     */
40
+    public function getThumbnail($path, $maxX, $maxY, $scalingup, $fileview) {
41
+        try {
42
+            $svg = new \Imagick();
43
+            $svg->setBackgroundColor(new \ImagickPixel('transparent'));
44 44
 
45
-			$content = stream_get_contents($fileview->fopen($path, 'r'));
46
-			if (substr($content, 0, 5) !== '<?xml') {
47
-				$content = '<?xml version="1.0" encoding="UTF-8" standalone="no"?>' . $content;
48
-			}
45
+            $content = stream_get_contents($fileview->fopen($path, 'r'));
46
+            if (substr($content, 0, 5) !== '<?xml') {
47
+                $content = '<?xml version="1.0" encoding="UTF-8" standalone="no"?>' . $content;
48
+            }
49 49
 
50
-			// Do not parse SVG files with references
51
-			if (stripos($content, 'xlink:href') !== false) {
52
-				return false;
53
-			}
50
+            // Do not parse SVG files with references
51
+            if (stripos($content, 'xlink:href') !== false) {
52
+                return false;
53
+            }
54 54
 
55
-			$svg->readImageBlob($content);
56
-			$svg->setImageFormat('png32');
57
-		} catch (\Exception $e) {
58
-			\OC::$server->getLogger()->logException($e, [
59
-				'level' => ILogger::ERROR,
60
-				'app' => 'core',
61
-			]);
62
-			return false;
63
-		}
55
+            $svg->readImageBlob($content);
56
+            $svg->setImageFormat('png32');
57
+        } catch (\Exception $e) {
58
+            \OC::$server->getLogger()->logException($e, [
59
+                'level' => ILogger::ERROR,
60
+                'app' => 'core',
61
+            ]);
62
+            return false;
63
+        }
64 64
 
65
-		//new image object
66
-		$image = new \OC_Image();
67
-		$image->loadFromData($svg);
68
-		//check if image object is valid
69
-		if ($image->valid()) {
70
-			$image->scaleDownToFit($maxX, $maxY);
65
+        //new image object
66
+        $image = new \OC_Image();
67
+        $image->loadFromData($svg);
68
+        //check if image object is valid
69
+        if ($image->valid()) {
70
+            $image->scaleDownToFit($maxX, $maxY);
71 71
 
72
-			return $image;
73
-		}
74
-		return false;
75
-	}
72
+            return $image;
73
+        }
74
+        return false;
75
+    }
76 76
 }
Please login to merge, or discard this patch.
lib/private/Preview/Office.php 1 patch
Indentation   +60 added lines, -60 removed lines patch added patch discarded remove patch
@@ -28,83 +28,83 @@
 block discarded – undo
28 28
 use OCP\ILogger;
29 29
 
30 30
 abstract class Office extends Provider {
31
-	private $cmd;
31
+    private $cmd;
32 32
 
33
-	/**
34
-	 * {@inheritDoc}
35
-	 */
36
-	public function getThumbnail($path, $maxX, $maxY, $scalingup, $fileview) {
37
-		$this->initCmd();
38
-		if (is_null($this->cmd)) {
39
-			return false;
40
-		}
33
+    /**
34
+     * {@inheritDoc}
35
+     */
36
+    public function getThumbnail($path, $maxX, $maxY, $scalingup, $fileview) {
37
+        $this->initCmd();
38
+        if (is_null($this->cmd)) {
39
+            return false;
40
+        }
41 41
 
42
-		$absPath = $fileview->toTmpFile($path);
42
+        $absPath = $fileview->toTmpFile($path);
43 43
 
44
-		$tmpDir = \OC::$server->getTempManager()->getTempBaseDir();
44
+        $tmpDir = \OC::$server->getTempManager()->getTempBaseDir();
45 45
 
46
-		$defaultParameters = ' -env:UserInstallation=file://' . escapeshellarg($tmpDir . '/owncloud-' . \OC_Util::getInstanceId() . '/') . ' --headless --nologo --nofirststartwizard --invisible --norestore --convert-to pdf --outdir ';
47
-		$clParameters = \OC::$server->getConfig()->getSystemValue('preview_office_cl_parameters', $defaultParameters);
46
+        $defaultParameters = ' -env:UserInstallation=file://' . escapeshellarg($tmpDir . '/owncloud-' . \OC_Util::getInstanceId() . '/') . ' --headless --nologo --nofirststartwizard --invisible --norestore --convert-to pdf --outdir ';
47
+        $clParameters = \OC::$server->getConfig()->getSystemValue('preview_office_cl_parameters', $defaultParameters);
48 48
 
49
-		$exec = $this->cmd . $clParameters . escapeshellarg($tmpDir) . ' ' . escapeshellarg($absPath);
49
+        $exec = $this->cmd . $clParameters . escapeshellarg($tmpDir) . ' ' . escapeshellarg($absPath);
50 50
 
51
-		shell_exec($exec);
51
+        shell_exec($exec);
52 52
 
53
-		//create imagick object from pdf
54
-		$pdfPreview = null;
55
-		try {
56
-			list($dirname, , , $filename) = array_values(pathinfo($absPath));
57
-			$pdfPreview = $dirname . '/' . $filename . '.pdf';
53
+        //create imagick object from pdf
54
+        $pdfPreview = null;
55
+        try {
56
+            list($dirname, , , $filename) = array_values(pathinfo($absPath));
57
+            $pdfPreview = $dirname . '/' . $filename . '.pdf';
58 58
 
59
-			$pdf = new \imagick($pdfPreview . '[0]');
60
-			$pdf->setImageFormat('jpg');
61
-		} catch (\Exception $e) {
62
-			unlink($absPath);
63
-			unlink($pdfPreview);
64
-			\OC::$server->getLogger()->logException($e, [
65
-				'level' => ILogger::ERROR,
66
-				'app' => 'core',
67
-			]);
68
-			return false;
69
-		}
59
+            $pdf = new \imagick($pdfPreview . '[0]');
60
+            $pdf->setImageFormat('jpg');
61
+        } catch (\Exception $e) {
62
+            unlink($absPath);
63
+            unlink($pdfPreview);
64
+            \OC::$server->getLogger()->logException($e, [
65
+                'level' => ILogger::ERROR,
66
+                'app' => 'core',
67
+            ]);
68
+            return false;
69
+        }
70 70
 
71
-		$image = new \OC_Image();
72
-		$image->loadFromData($pdf);
71
+        $image = new \OC_Image();
72
+        $image->loadFromData($pdf);
73 73
 
74
-		unlink($absPath);
75
-		unlink($pdfPreview);
74
+        unlink($absPath);
75
+        unlink($pdfPreview);
76 76
 
77
-		if ($image->valid()) {
78
-			$image->scaleDownToFit($maxX, $maxY);
77
+        if ($image->valid()) {
78
+            $image->scaleDownToFit($maxX, $maxY);
79 79
 
80
-			return $image;
81
-		}
82
-		return false;
80
+            return $image;
81
+        }
82
+        return false;
83 83
 
84
-	}
84
+    }
85 85
 
86
-	private function initCmd() {
87
-		$cmd = '';
86
+    private function initCmd() {
87
+        $cmd = '';
88 88
 
89
-		$libreOfficePath = \OC::$server->getConfig()->getSystemValue('preview_libreoffice_path', null);
90
-		if (is_string($libreOfficePath)) {
91
-			$cmd = $libreOfficePath;
92
-		}
89
+        $libreOfficePath = \OC::$server->getConfig()->getSystemValue('preview_libreoffice_path', null);
90
+        if (is_string($libreOfficePath)) {
91
+            $cmd = $libreOfficePath;
92
+        }
93 93
 
94
-		$whichLibreOffice = shell_exec('command -v libreoffice');
95
-		if ($cmd === '' && !empty($whichLibreOffice)) {
96
-			$cmd = 'libreoffice';
97
-		}
94
+        $whichLibreOffice = shell_exec('command -v libreoffice');
95
+        if ($cmd === '' && !empty($whichLibreOffice)) {
96
+            $cmd = 'libreoffice';
97
+        }
98 98
 
99
-		$whichOpenOffice = shell_exec('command -v openoffice');
100
-		if ($cmd === '' && !empty($whichOpenOffice)) {
101
-			$cmd = 'openoffice';
102
-		}
99
+        $whichOpenOffice = shell_exec('command -v openoffice');
100
+        if ($cmd === '' && !empty($whichOpenOffice)) {
101
+            $cmd = 'openoffice';
102
+        }
103 103
 
104
-		if ($cmd === '') {
105
-			$cmd = null;
106
-		}
104
+        if ($cmd === '') {
105
+            $cmd = null;
106
+        }
107 107
 
108
-		$this->cmd = $cmd;
109
-	}
108
+        $this->cmd = $cmd;
109
+    }
110 110
 }
Please login to merge, or discard this patch.
lib/private/legacy/app.php 2 patches
Indentation   +1034 added lines, -1034 removed lines patch added patch discarded remove patch
@@ -64,1038 +64,1038 @@
 block discarded – undo
64 64
  * upgrading and removing apps.
65 65
  */
66 66
 class OC_App {
67
-	static private $adminForms = [];
68
-	static private $personalForms = [];
69
-	static private $appTypes = [];
70
-	static private $loadedApps = [];
71
-	static private $altLogin = [];
72
-	static private $alreadyRegistered = [];
73
-	const officialApp = 200;
74
-
75
-	/**
76
-	 * clean the appId
77
-	 *
78
-	 * @param string $app AppId that needs to be cleaned
79
-	 * @return string
80
-	 */
81
-	public static function cleanAppId(string $app): string {
82
-		return str_replace(array('\0', '/', '\\', '..'), '', $app);
83
-	}
84
-
85
-	/**
86
-	 * Check if an app is loaded
87
-	 *
88
-	 * @param string $app
89
-	 * @return bool
90
-	 */
91
-	public static function isAppLoaded(string $app): bool {
92
-		return in_array($app, self::$loadedApps, true);
93
-	}
94
-
95
-	/**
96
-	 * loads all apps
97
-	 *
98
-	 * @param string[] $types
99
-	 * @return bool
100
-	 *
101
-	 * This function walks through the ownCloud directory and loads all apps
102
-	 * it can find. A directory contains an app if the file /appinfo/info.xml
103
-	 * exists.
104
-	 *
105
-	 * if $types is set to non-empty array, only apps of those types will be loaded
106
-	 */
107
-	public static function loadApps(array $types = []): bool {
108
-		if (\OC::$server->getSystemConfig()->getValue('maintenance', false)) {
109
-			return false;
110
-		}
111
-		// Load the enabled apps here
112
-		$apps = self::getEnabledApps();
113
-
114
-		// Add each apps' folder as allowed class path
115
-		foreach($apps as $app) {
116
-			$path = self::getAppPath($app);
117
-			if($path !== false) {
118
-				self::registerAutoloading($app, $path);
119
-			}
120
-		}
121
-
122
-		// prevent app.php from printing output
123
-		ob_start();
124
-		foreach ($apps as $app) {
125
-			if (($types === [] or self::isType($app, $types)) && !in_array($app, self::$loadedApps)) {
126
-				self::loadApp($app);
127
-			}
128
-		}
129
-		ob_end_clean();
130
-
131
-		return true;
132
-	}
133
-
134
-	/**
135
-	 * load a single app
136
-	 *
137
-	 * @param string $app
138
-	 * @throws Exception
139
-	 */
140
-	public static function loadApp(string $app) {
141
-		self::$loadedApps[] = $app;
142
-		$appPath = self::getAppPath($app);
143
-		if($appPath === false) {
144
-			return;
145
-		}
146
-
147
-		// in case someone calls loadApp() directly
148
-		self::registerAutoloading($app, $appPath);
149
-
150
-		if (is_file($appPath . '/appinfo/app.php')) {
151
-			\OC::$server->getEventLogger()->start('load_app_' . $app, 'Load app: ' . $app);
152
-			try {
153
-				self::requireAppFile($app);
154
-			} catch (Error $ex) {
155
-				\OC::$server->getLogger()->logException($ex);
156
-				if (!\OC::$server->getAppManager()->isShipped($app)) {
157
-					// Only disable apps which are not shipped
158
-					\OC::$server->getAppManager()->disableApp($app);
159
-				}
160
-			}
161
-			\OC::$server->getEventLogger()->end('load_app_' . $app);
162
-		}
163
-
164
-		$info = self::getAppInfo($app);
165
-		if (!empty($info['activity']['filters'])) {
166
-			foreach ($info['activity']['filters'] as $filter) {
167
-				\OC::$server->getActivityManager()->registerFilter($filter);
168
-			}
169
-		}
170
-		if (!empty($info['activity']['settings'])) {
171
-			foreach ($info['activity']['settings'] as $setting) {
172
-				\OC::$server->getActivityManager()->registerSetting($setting);
173
-			}
174
-		}
175
-		if (!empty($info['activity']['providers'])) {
176
-			foreach ($info['activity']['providers'] as $provider) {
177
-				\OC::$server->getActivityManager()->registerProvider($provider);
178
-			}
179
-		}
180
-
181
-		if (!empty($info['settings']['admin'])) {
182
-			foreach ($info['settings']['admin'] as $setting) {
183
-				\OC::$server->getSettingsManager()->registerSetting('admin', $setting);
184
-			}
185
-		}
186
-		if (!empty($info['settings']['admin-section'])) {
187
-			foreach ($info['settings']['admin-section'] as $section) {
188
-				\OC::$server->getSettingsManager()->registerSection('admin', $section);
189
-			}
190
-		}
191
-		if (!empty($info['settings']['personal'])) {
192
-			foreach ($info['settings']['personal'] as $setting) {
193
-				\OC::$server->getSettingsManager()->registerSetting('personal', $setting);
194
-			}
195
-		}
196
-		if (!empty($info['settings']['personal-section'])) {
197
-			foreach ($info['settings']['personal-section'] as $section) {
198
-				\OC::$server->getSettingsManager()->registerSection('personal', $section);
199
-			}
200
-		}
201
-
202
-		if (!empty($info['collaboration']['plugins'])) {
203
-			// deal with one or many plugin entries
204
-			$plugins = isset($info['collaboration']['plugins']['plugin']['@value']) ?
205
-				[$info['collaboration']['plugins']['plugin']] : $info['collaboration']['plugins']['plugin'];
206
-			foreach ($plugins as $plugin) {
207
-				if($plugin['@attributes']['type'] === 'collaborator-search') {
208
-					$pluginInfo = [
209
-						'shareType' => $plugin['@attributes']['share-type'],
210
-						'class' => $plugin['@value'],
211
-					];
212
-					\OC::$server->getCollaboratorSearch()->registerPlugin($pluginInfo);
213
-				} else if ($plugin['@attributes']['type'] === 'autocomplete-sort') {
214
-					\OC::$server->getAutoCompleteManager()->registerSorter($plugin['@value']);
215
-				}
216
-			}
217
-		}
218
-	}
219
-
220
-	/**
221
-	 * @internal
222
-	 * @param string $app
223
-	 * @param string $path
224
-	 */
225
-	public static function registerAutoloading(string $app, string $path) {
226
-		$key = $app . '-' . $path;
227
-		if(isset(self::$alreadyRegistered[$key])) {
228
-			return;
229
-		}
230
-
231
-		self::$alreadyRegistered[$key] = true;
232
-
233
-		// Register on PSR-4 composer autoloader
234
-		$appNamespace = \OC\AppFramework\App::buildAppNamespace($app);
235
-		\OC::$server->registerNamespace($app, $appNamespace);
236
-
237
-		if (file_exists($path . '/composer/autoload.php')) {
238
-			require_once $path . '/composer/autoload.php';
239
-		} else {
240
-			\OC::$composerAutoloader->addPsr4($appNamespace . '\\', $path . '/lib/', true);
241
-			// Register on legacy autoloader
242
-			\OC::$loader->addValidRoot($path);
243
-		}
244
-
245
-		// Register Test namespace only when testing
246
-		if (defined('PHPUNIT_RUN') || defined('CLI_TEST_RUN')) {
247
-			\OC::$composerAutoloader->addPsr4($appNamespace . '\\Tests\\', $path . '/tests/', true);
248
-		}
249
-	}
250
-
251
-	/**
252
-	 * Load app.php from the given app
253
-	 *
254
-	 * @param string $app app name
255
-	 * @throws Error
256
-	 */
257
-	private static function requireAppFile(string $app) {
258
-		// encapsulated here to avoid variable scope conflicts
259
-		require_once $app . '/appinfo/app.php';
260
-	}
261
-
262
-	/**
263
-	 * check if an app is of a specific type
264
-	 *
265
-	 * @param string $app
266
-	 * @param array $types
267
-	 * @return bool
268
-	 */
269
-	public static function isType(string $app, array $types): bool {
270
-		$appTypes = self::getAppTypes($app);
271
-		foreach ($types as $type) {
272
-			if (array_search($type, $appTypes) !== false) {
273
-				return true;
274
-			}
275
-		}
276
-		return false;
277
-	}
278
-
279
-	/**
280
-	 * get the types of an app
281
-	 *
282
-	 * @param string $app
283
-	 * @return array
284
-	 */
285
-	private static function getAppTypes(string $app): array {
286
-		//load the cache
287
-		if (count(self::$appTypes) == 0) {
288
-			self::$appTypes = \OC::$server->getAppConfig()->getValues(false, 'types');
289
-		}
290
-
291
-		if (isset(self::$appTypes[$app])) {
292
-			return explode(',', self::$appTypes[$app]);
293
-		}
294
-
295
-		return [];
296
-	}
297
-
298
-	/**
299
-	 * read app types from info.xml and cache them in the database
300
-	 */
301
-	public static function setAppTypes(string $app) {
302
-		$appManager = \OC::$server->getAppManager();
303
-		$appData = $appManager->getAppInfo($app);
304
-		if(!is_array($appData)) {
305
-			return;
306
-		}
307
-
308
-		if (isset($appData['types'])) {
309
-			$appTypes = implode(',', $appData['types']);
310
-		} else {
311
-			$appTypes = '';
312
-			$appData['types'] = [];
313
-		}
314
-
315
-		$config = \OC::$server->getConfig();
316
-		$config->setAppValue($app, 'types', $appTypes);
317
-
318
-		if ($appManager->hasProtectedAppType($appData['types'])) {
319
-			$enabled = $config->getAppValue($app, 'enabled', 'yes');
320
-			if ($enabled !== 'yes' && $enabled !== 'no') {
321
-				$config->setAppValue($app, 'enabled', 'yes');
322
-			}
323
-		}
324
-	}
325
-
326
-	/**
327
-	 * Returns apps enabled for the current user.
328
-	 *
329
-	 * @param bool $forceRefresh whether to refresh the cache
330
-	 * @param bool $all whether to return apps for all users, not only the
331
-	 * currently logged in one
332
-	 * @return string[]
333
-	 */
334
-	public static function getEnabledApps(bool $forceRefresh = false, bool $all = false): array {
335
-		if (!\OC::$server->getSystemConfig()->getValue('installed', false)) {
336
-			return [];
337
-		}
338
-		// in incognito mode or when logged out, $user will be false,
339
-		// which is also the case during an upgrade
340
-		$appManager = \OC::$server->getAppManager();
341
-		if ($all) {
342
-			$user = null;
343
-		} else {
344
-			$user = \OC::$server->getUserSession()->getUser();
345
-		}
346
-
347
-		if (is_null($user)) {
348
-			$apps = $appManager->getInstalledApps();
349
-		} else {
350
-			$apps = $appManager->getEnabledAppsForUser($user);
351
-		}
352
-		$apps = array_filter($apps, function ($app) {
353
-			return $app !== 'files';//we add this manually
354
-		});
355
-		sort($apps);
356
-		array_unshift($apps, 'files');
357
-		return $apps;
358
-	}
359
-
360
-	/**
361
-	 * checks whether or not an app is enabled
362
-	 *
363
-	 * @param string $app app
364
-	 * @return bool
365
-	 * @deprecated 13.0.0 use \OC::$server->getAppManager()->isEnabledForUser($appId)
366
-	 *
367
-	 * This function checks whether or not an app is enabled.
368
-	 */
369
-	public static function isEnabled(string $app): bool {
370
-		return \OC::$server->getAppManager()->isEnabledForUser($app);
371
-	}
372
-
373
-	/**
374
-	 * enables an app
375
-	 *
376
-	 * @param string $appId
377
-	 * @param array $groups (optional) when set, only these groups will have access to the app
378
-	 * @throws \Exception
379
-	 * @return void
380
-	 *
381
-	 * This function set an app as enabled in appconfig.
382
-	 */
383
-	public function enable(string $appId,
384
-						   array $groups = []) {
385
-
386
-		// Check if app is already downloaded
387
-		/** @var Installer $installer */
388
-		$installer = \OC::$server->query(Installer::class);
389
-		$isDownloaded = $installer->isDownloaded($appId);
390
-
391
-		if(!$isDownloaded) {
392
-			$installer->downloadApp($appId);
393
-		}
394
-
395
-		$installer->installApp($appId);
396
-
397
-		$appManager = \OC::$server->getAppManager();
398
-		if ($groups !== []) {
399
-			$groupManager = \OC::$server->getGroupManager();
400
-			$groupsList = [];
401
-			foreach ($groups as $group) {
402
-				$groupItem = $groupManager->get($group);
403
-				if ($groupItem instanceof \OCP\IGroup) {
404
-					$groupsList[] = $groupManager->get($group);
405
-				}
406
-			}
407
-			$appManager->enableAppForGroups($appId, $groupsList);
408
-		} else {
409
-			$appManager->enableApp($appId);
410
-		}
411
-	}
412
-
413
-	/**
414
-	 * Get the path where to install apps
415
-	 *
416
-	 * @return string|false
417
-	 */
418
-	public static function getInstallPath() {
419
-		if (\OC::$server->getSystemConfig()->getValue('appstoreenabled', true) == false) {
420
-			return false;
421
-		}
422
-
423
-		foreach (OC::$APPSROOTS as $dir) {
424
-			if (isset($dir['writable']) && $dir['writable'] === true) {
425
-				return $dir['path'];
426
-			}
427
-		}
428
-
429
-		\OCP\Util::writeLog('core', 'No application directories are marked as writable.', ILogger::ERROR);
430
-		return null;
431
-	}
432
-
433
-
434
-	/**
435
-	 * search for an app in all app-directories
436
-	 *
437
-	 * @param string $appId
438
-	 * @return false|string
439
-	 */
440
-	public static function findAppInDirectories(string $appId) {
441
-		$sanitizedAppId = self::cleanAppId($appId);
442
-		if($sanitizedAppId !== $appId) {
443
-			return false;
444
-		}
445
-		static $app_dir = [];
446
-
447
-		if (isset($app_dir[$appId])) {
448
-			return $app_dir[$appId];
449
-		}
450
-
451
-		$possibleApps = [];
452
-		foreach (OC::$APPSROOTS as $dir) {
453
-			if (file_exists($dir['path'] . '/' . $appId)) {
454
-				$possibleApps[] = $dir;
455
-			}
456
-		}
457
-
458
-		if (empty($possibleApps)) {
459
-			return false;
460
-		} elseif (count($possibleApps) === 1) {
461
-			$dir = array_shift($possibleApps);
462
-			$app_dir[$appId] = $dir;
463
-			return $dir;
464
-		} else {
465
-			$versionToLoad = [];
466
-			foreach ($possibleApps as $possibleApp) {
467
-				$version = self::getAppVersionByPath($possibleApp['path']);
468
-				if (empty($versionToLoad) || version_compare($version, $versionToLoad['version'], '>')) {
469
-					$versionToLoad = array(
470
-						'dir' => $possibleApp,
471
-						'version' => $version,
472
-					);
473
-				}
474
-			}
475
-			$app_dir[$appId] = $versionToLoad['dir'];
476
-			return $versionToLoad['dir'];
477
-			//TODO - write test
478
-		}
479
-	}
480
-
481
-	/**
482
-	 * Get the directory for the given app.
483
-	 * If the app is defined in multiple directories, the first one is taken. (false if not found)
484
-	 *
485
-	 * @param string $appId
486
-	 * @return string|false
487
-	 */
488
-	public static function getAppPath(string $appId) {
489
-		if ($appId === null || trim($appId) === '') {
490
-			return false;
491
-		}
492
-
493
-		if (($dir = self::findAppInDirectories($appId)) != false) {
494
-			return $dir['path'] . '/' . $appId;
495
-		}
496
-		return false;
497
-	}
498
-
499
-	/**
500
-	 * Get the path for the given app on the access
501
-	 * If the app is defined in multiple directories, the first one is taken. (false if not found)
502
-	 *
503
-	 * @param string $appId
504
-	 * @return string|false
505
-	 */
506
-	public static function getAppWebPath(string $appId) {
507
-		if (($dir = self::findAppInDirectories($appId)) != false) {
508
-			return OC::$WEBROOT . $dir['url'] . '/' . $appId;
509
-		}
510
-		return false;
511
-	}
512
-
513
-	/**
514
-	 * get the last version of the app from appinfo/info.xml
515
-	 *
516
-	 * @param string $appId
517
-	 * @param bool $useCache
518
-	 * @return string
519
-	 * @deprecated 14.0.0 use \OC::$server->getAppManager()->getAppVersion()
520
-	 */
521
-	public static function getAppVersion(string $appId, bool $useCache = true): string {
522
-		return \OC::$server->getAppManager()->getAppVersion($appId, $useCache);
523
-	}
524
-
525
-	/**
526
-	 * get app's version based on it's path
527
-	 *
528
-	 * @param string $path
529
-	 * @return string
530
-	 */
531
-	public static function getAppVersionByPath(string $path): string {
532
-		$infoFile = $path . '/appinfo/info.xml';
533
-		$appData = \OC::$server->getAppManager()->getAppInfo($infoFile, true);
534
-		return isset($appData['version']) ? $appData['version'] : '';
535
-	}
536
-
537
-
538
-	/**
539
-	 * Read all app metadata from the info.xml file
540
-	 *
541
-	 * @param string $appId id of the app or the path of the info.xml file
542
-	 * @param bool $path
543
-	 * @param string $lang
544
-	 * @return array|null
545
-	 * @note all data is read from info.xml, not just pre-defined fields
546
-	 * @deprecated 14.0.0 use \OC::$server->getAppManager()->getAppInfo()
547
-	 */
548
-	public static function getAppInfo(string $appId, bool $path = false, string $lang = null) {
549
-		return \OC::$server->getAppManager()->getAppInfo($appId, $path, $lang);
550
-	}
551
-
552
-	/**
553
-	 * Returns the navigation
554
-	 *
555
-	 * @return array
556
-	 * @deprecated 14.0.0 use \OC::$server->getNavigationManager()->getAll()
557
-	 *
558
-	 * This function returns an array containing all entries added. The
559
-	 * entries are sorted by the key 'order' ascending. Additional to the keys
560
-	 * given for each app the following keys exist:
561
-	 *   - active: boolean, signals if the user is on this navigation entry
562
-	 */
563
-	public static function getNavigation(): array {
564
-		return OC::$server->getNavigationManager()->getAll();
565
-	}
566
-
567
-	/**
568
-	 * Returns the Settings Navigation
569
-	 *
570
-	 * @return string[]
571
-	 * @deprecated 14.0.0 use \OC::$server->getNavigationManager()->getAll('settings')
572
-	 *
573
-	 * This function returns an array containing all settings pages added. The
574
-	 * entries are sorted by the key 'order' ascending.
575
-	 */
576
-	public static function getSettingsNavigation(): array {
577
-		return OC::$server->getNavigationManager()->getAll('settings');
578
-	}
579
-
580
-	/**
581
-	 * get the id of loaded app
582
-	 *
583
-	 * @return string
584
-	 */
585
-	public static function getCurrentApp(): string {
586
-		$request = \OC::$server->getRequest();
587
-		$script = substr($request->getScriptName(), strlen(OC::$WEBROOT) + 1);
588
-		$topFolder = substr($script, 0, strpos($script, '/') ?: 0);
589
-		if (empty($topFolder)) {
590
-			$path_info = $request->getPathInfo();
591
-			if ($path_info) {
592
-				$topFolder = substr($path_info, 1, strpos($path_info, '/', 1) - 1);
593
-			}
594
-		}
595
-		if ($topFolder == 'apps') {
596
-			$length = strlen($topFolder);
597
-			return substr($script, $length + 1, strpos($script, '/', $length + 1) - $length - 1) ?: '';
598
-		} else {
599
-			return $topFolder;
600
-		}
601
-	}
602
-
603
-	/**
604
-	 * @param string $type
605
-	 * @return array
606
-	 */
607
-	public static function getForms(string $type): array {
608
-		$forms = [];
609
-		switch ($type) {
610
-			case 'admin':
611
-				$source = self::$adminForms;
612
-				break;
613
-			case 'personal':
614
-				$source = self::$personalForms;
615
-				break;
616
-			default:
617
-				return [];
618
-		}
619
-		foreach ($source as $form) {
620
-			$forms[] = include $form;
621
-		}
622
-		return $forms;
623
-	}
624
-
625
-	/**
626
-	 * register an admin form to be shown
627
-	 *
628
-	 * @param string $app
629
-	 * @param string $page
630
-	 */
631
-	public static function registerAdmin(string $app, string $page) {
632
-		self::$adminForms[] = $app . '/' . $page . '.php';
633
-	}
634
-
635
-	/**
636
-	 * register a personal form to be shown
637
-	 * @param string $app
638
-	 * @param string $page
639
-	 */
640
-	public static function registerPersonal(string $app, string $page) {
641
-		self::$personalForms[] = $app . '/' . $page . '.php';
642
-	}
643
-
644
-	/**
645
-	 * @param array $entry
646
-	 */
647
-	public static function registerLogIn(array $entry) {
648
-		self::$altLogin[] = $entry;
649
-	}
650
-
651
-	/**
652
-	 * @return array
653
-	 */
654
-	public static function getAlternativeLogIns(): array {
655
-		return self::$altLogin;
656
-	}
657
-
658
-	/**
659
-	 * get a list of all apps in the apps folder
660
-	 *
661
-	 * @return array an array of app names (string IDs)
662
-	 * @todo: change the name of this method to getInstalledApps, which is more accurate
663
-	 */
664
-	public static function getAllApps(): array {
665
-
666
-		$apps = [];
667
-
668
-		foreach (OC::$APPSROOTS as $apps_dir) {
669
-			if (!is_readable($apps_dir['path'])) {
670
-				\OCP\Util::writeLog('core', 'unable to read app folder : ' . $apps_dir['path'], ILogger::WARN);
671
-				continue;
672
-			}
673
-			$dh = opendir($apps_dir['path']);
674
-
675
-			if (is_resource($dh)) {
676
-				while (($file = readdir($dh)) !== false) {
677
-
678
-					if ($file[0] != '.' and is_dir($apps_dir['path'] . '/' . $file) and is_file($apps_dir['path'] . '/' . $file . '/appinfo/info.xml')) {
679
-
680
-						$apps[] = $file;
681
-					}
682
-				}
683
-			}
684
-		}
685
-
686
-		$apps = array_unique($apps);
687
-
688
-		return $apps;
689
-	}
690
-
691
-	/**
692
-	 * List all apps, this is used in apps.php
693
-	 *
694
-	 * @return array
695
-	 */
696
-	public function listAllApps(): array {
697
-		$installedApps = OC_App::getAllApps();
698
-
699
-		$appManager = \OC::$server->getAppManager();
700
-		//we don't want to show configuration for these
701
-		$blacklist = $appManager->getAlwaysEnabledApps();
702
-		$appList = [];
703
-		$langCode = \OC::$server->getL10N('core')->getLanguageCode();
704
-		$urlGenerator = \OC::$server->getURLGenerator();
705
-
706
-		foreach ($installedApps as $app) {
707
-			if (array_search($app, $blacklist) === false) {
708
-
709
-				$info = OC_App::getAppInfo($app, false, $langCode);
710
-				if (!is_array($info)) {
711
-					\OCP\Util::writeLog('core', 'Could not read app info file for app "' . $app . '"', ILogger::ERROR);
712
-					continue;
713
-				}
714
-
715
-				if (!isset($info['name'])) {
716
-					\OCP\Util::writeLog('core', 'App id "' . $app . '" has no name in appinfo', ILogger::ERROR);
717
-					continue;
718
-				}
719
-
720
-				$enabled = \OC::$server->getConfig()->getAppValue($app, 'enabled', 'no');
721
-				$info['groups'] = null;
722
-				if ($enabled === 'yes') {
723
-					$active = true;
724
-				} else if ($enabled === 'no') {
725
-					$active = false;
726
-				} else {
727
-					$active = true;
728
-					$info['groups'] = $enabled;
729
-				}
730
-
731
-				$info['active'] = $active;
732
-
733
-				if ($appManager->isShipped($app)) {
734
-					$info['internal'] = true;
735
-					$info['level'] = self::officialApp;
736
-					$info['removable'] = false;
737
-				} else {
738
-					$info['internal'] = false;
739
-					$info['removable'] = true;
740
-				}
741
-
742
-				$appPath = self::getAppPath($app);
743
-				if($appPath !== false) {
744
-					$appIcon = $appPath . '/img/' . $app . '.svg';
745
-					if (file_exists($appIcon)) {
746
-						$info['preview'] = $urlGenerator->imagePath($app, $app . '.svg');
747
-						$info['previewAsIcon'] = true;
748
-					} else {
749
-						$appIcon = $appPath . '/img/app.svg';
750
-						if (file_exists($appIcon)) {
751
-							$info['preview'] = $urlGenerator->imagePath($app, 'app.svg');
752
-							$info['previewAsIcon'] = true;
753
-						}
754
-					}
755
-				}
756
-				// fix documentation
757
-				if (isset($info['documentation']) && is_array($info['documentation'])) {
758
-					foreach ($info['documentation'] as $key => $url) {
759
-						// If it is not an absolute URL we assume it is a key
760
-						// i.e. admin-ldap will get converted to go.php?to=admin-ldap
761
-						if (stripos($url, 'https://') !== 0 && stripos($url, 'http://') !== 0) {
762
-							$url = $urlGenerator->linkToDocs($url);
763
-						}
764
-
765
-						$info['documentation'][$key] = $url;
766
-					}
767
-				}
768
-
769
-				$info['version'] = OC_App::getAppVersion($app);
770
-				$appList[] = $info;
771
-			}
772
-		}
773
-
774
-		return $appList;
775
-	}
776
-
777
-	public static function shouldUpgrade(string $app): bool {
778
-		$versions = self::getAppVersions();
779
-		$currentVersion = OC_App::getAppVersion($app);
780
-		if ($currentVersion && isset($versions[$app])) {
781
-			$installedVersion = $versions[$app];
782
-			if (!version_compare($currentVersion, $installedVersion, '=')) {
783
-				return true;
784
-			}
785
-		}
786
-		return false;
787
-	}
788
-
789
-	/**
790
-	 * Adjust the number of version parts of $version1 to match
791
-	 * the number of version parts of $version2.
792
-	 *
793
-	 * @param string $version1 version to adjust
794
-	 * @param string $version2 version to take the number of parts from
795
-	 * @return string shortened $version1
796
-	 */
797
-	private static function adjustVersionParts(string $version1, string $version2): string {
798
-		$version1 = explode('.', $version1);
799
-		$version2 = explode('.', $version2);
800
-		// reduce $version1 to match the number of parts in $version2
801
-		while (count($version1) > count($version2)) {
802
-			array_pop($version1);
803
-		}
804
-		// if $version1 does not have enough parts, add some
805
-		while (count($version1) < count($version2)) {
806
-			$version1[] = '0';
807
-		}
808
-		return implode('.', $version1);
809
-	}
810
-
811
-	/**
812
-	 * Check whether the current ownCloud version matches the given
813
-	 * application's version requirements.
814
-	 *
815
-	 * The comparison is made based on the number of parts that the
816
-	 * app info version has. For example for ownCloud 6.0.3 if the
817
-	 * app info version is expecting version 6.0, the comparison is
818
-	 * made on the first two parts of the ownCloud version.
819
-	 * This means that it's possible to specify "requiremin" => 6
820
-	 * and "requiremax" => 6 and it will still match ownCloud 6.0.3.
821
-	 *
822
-	 * @param string $ocVersion ownCloud version to check against
823
-	 * @param array $appInfo app info (from xml)
824
-	 *
825
-	 * @return boolean true if compatible, otherwise false
826
-	 */
827
-	public static function isAppCompatible(string $ocVersion, array $appInfo): bool {
828
-		$requireMin = '';
829
-		$requireMax = '';
830
-		if (isset($appInfo['dependencies']['nextcloud']['@attributes']['min-version'])) {
831
-			$requireMin = $appInfo['dependencies']['nextcloud']['@attributes']['min-version'];
832
-		} elseif (isset($appInfo['dependencies']['owncloud']['@attributes']['min-version'])) {
833
-			$requireMin = $appInfo['dependencies']['owncloud']['@attributes']['min-version'];
834
-		} else if (isset($appInfo['requiremin'])) {
835
-			$requireMin = $appInfo['requiremin'];
836
-		} else if (isset($appInfo['require'])) {
837
-			$requireMin = $appInfo['require'];
838
-		}
839
-
840
-		if (isset($appInfo['dependencies']['nextcloud']['@attributes']['max-version'])) {
841
-			$requireMax = $appInfo['dependencies']['nextcloud']['@attributes']['max-version'];
842
-		} elseif (isset($appInfo['dependencies']['owncloud']['@attributes']['max-version'])) {
843
-			$requireMax = $appInfo['dependencies']['owncloud']['@attributes']['max-version'];
844
-		} else if (isset($appInfo['requiremax'])) {
845
-			$requireMax = $appInfo['requiremax'];
846
-		}
847
-
848
-		if (!empty($requireMin)
849
-			&& version_compare(self::adjustVersionParts($ocVersion, $requireMin), $requireMin, '<')
850
-		) {
851
-
852
-			return false;
853
-		}
854
-
855
-		if (!empty($requireMax)
856
-			&& version_compare(self::adjustVersionParts($ocVersion, $requireMax), $requireMax, '>')
857
-		) {
858
-			return false;
859
-		}
860
-
861
-		return true;
862
-	}
863
-
864
-	/**
865
-	 * get the installed version of all apps
866
-	 */
867
-	public static function getAppVersions() {
868
-		static $versions;
869
-
870
-		if(!$versions) {
871
-			$appConfig = \OC::$server->getAppConfig();
872
-			$versions = $appConfig->getValues(false, 'installed_version');
873
-		}
874
-		return $versions;
875
-	}
876
-
877
-	/**
878
-	 * update the database for the app and call the update script
879
-	 *
880
-	 * @param string $appId
881
-	 * @return bool
882
-	 */
883
-	public static function updateApp(string $appId): bool {
884
-		$appPath = self::getAppPath($appId);
885
-		if($appPath === false) {
886
-			return false;
887
-		}
888
-		self::registerAutoloading($appId, $appPath);
889
-
890
-		$appData = self::getAppInfo($appId);
891
-		self::executeRepairSteps($appId, $appData['repair-steps']['pre-migration']);
892
-
893
-		if (file_exists($appPath . '/appinfo/database.xml')) {
894
-			OC_DB::updateDbFromStructure($appPath . '/appinfo/database.xml');
895
-		} else {
896
-			$ms = new MigrationService($appId, \OC::$server->getDatabaseConnection());
897
-			$ms->migrate();
898
-		}
899
-
900
-		self::executeRepairSteps($appId, $appData['repair-steps']['post-migration']);
901
-		self::setupLiveMigrations($appId, $appData['repair-steps']['live-migration']);
902
-		// update appversion in app manager
903
-		\OC::$server->getAppManager()->getAppVersion($appId, false);
904
-
905
-		// run upgrade code
906
-		if (file_exists($appPath . '/appinfo/update.php')) {
907
-			self::loadApp($appId);
908
-			include $appPath . '/appinfo/update.php';
909
-		}
910
-		self::setupBackgroundJobs($appData['background-jobs']);
911
-
912
-		//set remote/public handlers
913
-		if (array_key_exists('ocsid', $appData)) {
914
-			\OC::$server->getConfig()->setAppValue($appId, 'ocsid', $appData['ocsid']);
915
-		} elseif(\OC::$server->getConfig()->getAppValue($appId, 'ocsid', null) !== null) {
916
-			\OC::$server->getConfig()->deleteAppValue($appId, 'ocsid');
917
-		}
918
-		foreach ($appData['remote'] as $name => $path) {
919
-			\OC::$server->getConfig()->setAppValue('core', 'remote_' . $name, $appId . '/' . $path);
920
-		}
921
-		foreach ($appData['public'] as $name => $path) {
922
-			\OC::$server->getConfig()->setAppValue('core', 'public_' . $name, $appId . '/' . $path);
923
-		}
924
-
925
-		self::setAppTypes($appId);
926
-
927
-		$version = \OC_App::getAppVersion($appId);
928
-		\OC::$server->getConfig()->setAppValue($appId, 'installed_version', $version);
929
-
930
-		\OC::$server->getEventDispatcher()->dispatch(ManagerEvent::EVENT_APP_UPDATE, new ManagerEvent(
931
-			ManagerEvent::EVENT_APP_UPDATE, $appId
932
-		));
933
-
934
-		return true;
935
-	}
936
-
937
-	/**
938
-	 * @param string $appId
939
-	 * @param string[] $steps
940
-	 * @throws \OC\NeedsUpdateException
941
-	 */
942
-	public static function executeRepairSteps(string $appId, array $steps) {
943
-		if (empty($steps)) {
944
-			return;
945
-		}
946
-		// load the app
947
-		self::loadApp($appId);
948
-
949
-		$dispatcher = OC::$server->getEventDispatcher();
950
-
951
-		// load the steps
952
-		$r = new Repair([], $dispatcher);
953
-		foreach ($steps as $step) {
954
-			try {
955
-				$r->addStep($step);
956
-			} catch (Exception $ex) {
957
-				$r->emit('\OC\Repair', 'error', [$ex->getMessage()]);
958
-				\OC::$server->getLogger()->logException($ex);
959
-			}
960
-		}
961
-		// run the steps
962
-		$r->run();
963
-	}
964
-
965
-	public static function setupBackgroundJobs(array $jobs) {
966
-		$queue = \OC::$server->getJobList();
967
-		foreach ($jobs as $job) {
968
-			$queue->add($job);
969
-		}
970
-	}
971
-
972
-	/**
973
-	 * @param string $appId
974
-	 * @param string[] $steps
975
-	 */
976
-	private static function setupLiveMigrations(string $appId, array $steps) {
977
-		$queue = \OC::$server->getJobList();
978
-		foreach ($steps as $step) {
979
-			$queue->add('OC\Migration\BackgroundRepair', [
980
-				'app' => $appId,
981
-				'step' => $step]);
982
-		}
983
-	}
984
-
985
-	/**
986
-	 * @param string $appId
987
-	 * @return \OC\Files\View|false
988
-	 */
989
-	public static function getStorage(string $appId) {
990
-		if (\OC::$server->getAppManager()->isEnabledForUser($appId)) { //sanity check
991
-			if (\OC::$server->getUserSession()->isLoggedIn()) {
992
-				$view = new \OC\Files\View('/' . OC_User::getUser());
993
-				if (!$view->file_exists($appId)) {
994
-					$view->mkdir($appId);
995
-				}
996
-				return new \OC\Files\View('/' . OC_User::getUser() . '/' . $appId);
997
-			} else {
998
-				\OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ', user not logged in', ILogger::ERROR);
999
-				return false;
1000
-			}
1001
-		} else {
1002
-			\OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ' not enabled', ILogger::ERROR);
1003
-			return false;
1004
-		}
1005
-	}
1006
-
1007
-	protected static function findBestL10NOption(array $options, string $lang): string {
1008
-		// only a single option
1009
-		if (isset($options['@value'])) {
1010
-			return $options['@value'];
1011
-		}
1012
-
1013
-		$fallback = $similarLangFallback = $englishFallback = false;
1014
-
1015
-		$lang = strtolower($lang);
1016
-		$similarLang = $lang;
1017
-		if (strpos($similarLang, '_')) {
1018
-			// For "de_DE" we want to find "de" and the other way around
1019
-			$similarLang = substr($lang, 0, strpos($lang, '_'));
1020
-		}
1021
-
1022
-		foreach ($options as $option) {
1023
-			if (is_array($option)) {
1024
-				if ($fallback === false) {
1025
-					$fallback = $option['@value'];
1026
-				}
1027
-
1028
-				if (!isset($option['@attributes']['lang'])) {
1029
-					continue;
1030
-				}
1031
-
1032
-				$attributeLang = strtolower($option['@attributes']['lang']);
1033
-				if ($attributeLang === $lang) {
1034
-					return $option['@value'];
1035
-				}
1036
-
1037
-				if ($attributeLang === $similarLang) {
1038
-					$similarLangFallback = $option['@value'];
1039
-				} else if (strpos($attributeLang, $similarLang . '_') === 0) {
1040
-					if ($similarLangFallback === false) {
1041
-						$similarLangFallback =  $option['@value'];
1042
-					}
1043
-				}
1044
-			} else {
1045
-				$englishFallback = $option;
1046
-			}
1047
-		}
1048
-
1049
-		if ($similarLangFallback !== false) {
1050
-			return $similarLangFallback;
1051
-		} else if ($englishFallback !== false) {
1052
-			return $englishFallback;
1053
-		}
1054
-		return (string) $fallback;
1055
-	}
1056
-
1057
-	/**
1058
-	 * parses the app data array and enhanced the 'description' value
1059
-	 *
1060
-	 * @param array $data the app data
1061
-	 * @param string $lang
1062
-	 * @return array improved app data
1063
-	 */
1064
-	public static function parseAppInfo(array $data, $lang = null): array {
1065
-
1066
-		if ($lang && isset($data['name']) && is_array($data['name'])) {
1067
-			$data['name'] = self::findBestL10NOption($data['name'], $lang);
1068
-		}
1069
-		if ($lang && isset($data['summary']) && is_array($data['summary'])) {
1070
-			$data['summary'] = self::findBestL10NOption($data['summary'], $lang);
1071
-		}
1072
-		if ($lang && isset($data['description']) && is_array($data['description'])) {
1073
-			$data['description'] = trim(self::findBestL10NOption($data['description'], $lang));
1074
-		} else if (isset($data['description']) && is_string($data['description'])) {
1075
-			$data['description'] = trim($data['description']);
1076
-		} else  {
1077
-			$data['description'] = '';
1078
-		}
1079
-
1080
-		return $data;
1081
-	}
1082
-
1083
-	/**
1084
-	 * @param \OCP\IConfig $config
1085
-	 * @param \OCP\IL10N $l
1086
-	 * @param array $info
1087
-	 * @throws \Exception
1088
-	 */
1089
-	public static function checkAppDependencies(\OCP\IConfig $config, \OCP\IL10N $l, array $info) {
1090
-		$dependencyAnalyzer = new DependencyAnalyzer(new Platform($config), $l);
1091
-		$missing = $dependencyAnalyzer->analyze($info);
1092
-		if (!empty($missing)) {
1093
-			$missingMsg = implode(PHP_EOL, $missing);
1094
-			throw new \Exception(
1095
-				$l->t('App "%s" cannot be installed because the following dependencies are not fulfilled: %s',
1096
-					[$info['name'], $missingMsg]
1097
-				)
1098
-			);
1099
-		}
1100
-	}
67
+    static private $adminForms = [];
68
+    static private $personalForms = [];
69
+    static private $appTypes = [];
70
+    static private $loadedApps = [];
71
+    static private $altLogin = [];
72
+    static private $alreadyRegistered = [];
73
+    const officialApp = 200;
74
+
75
+    /**
76
+     * clean the appId
77
+     *
78
+     * @param string $app AppId that needs to be cleaned
79
+     * @return string
80
+     */
81
+    public static function cleanAppId(string $app): string {
82
+        return str_replace(array('\0', '/', '\\', '..'), '', $app);
83
+    }
84
+
85
+    /**
86
+     * Check if an app is loaded
87
+     *
88
+     * @param string $app
89
+     * @return bool
90
+     */
91
+    public static function isAppLoaded(string $app): bool {
92
+        return in_array($app, self::$loadedApps, true);
93
+    }
94
+
95
+    /**
96
+     * loads all apps
97
+     *
98
+     * @param string[] $types
99
+     * @return bool
100
+     *
101
+     * This function walks through the ownCloud directory and loads all apps
102
+     * it can find. A directory contains an app if the file /appinfo/info.xml
103
+     * exists.
104
+     *
105
+     * if $types is set to non-empty array, only apps of those types will be loaded
106
+     */
107
+    public static function loadApps(array $types = []): bool {
108
+        if (\OC::$server->getSystemConfig()->getValue('maintenance', false)) {
109
+            return false;
110
+        }
111
+        // Load the enabled apps here
112
+        $apps = self::getEnabledApps();
113
+
114
+        // Add each apps' folder as allowed class path
115
+        foreach($apps as $app) {
116
+            $path = self::getAppPath($app);
117
+            if($path !== false) {
118
+                self::registerAutoloading($app, $path);
119
+            }
120
+        }
121
+
122
+        // prevent app.php from printing output
123
+        ob_start();
124
+        foreach ($apps as $app) {
125
+            if (($types === [] or self::isType($app, $types)) && !in_array($app, self::$loadedApps)) {
126
+                self::loadApp($app);
127
+            }
128
+        }
129
+        ob_end_clean();
130
+
131
+        return true;
132
+    }
133
+
134
+    /**
135
+     * load a single app
136
+     *
137
+     * @param string $app
138
+     * @throws Exception
139
+     */
140
+    public static function loadApp(string $app) {
141
+        self::$loadedApps[] = $app;
142
+        $appPath = self::getAppPath($app);
143
+        if($appPath === false) {
144
+            return;
145
+        }
146
+
147
+        // in case someone calls loadApp() directly
148
+        self::registerAutoloading($app, $appPath);
149
+
150
+        if (is_file($appPath . '/appinfo/app.php')) {
151
+            \OC::$server->getEventLogger()->start('load_app_' . $app, 'Load app: ' . $app);
152
+            try {
153
+                self::requireAppFile($app);
154
+            } catch (Error $ex) {
155
+                \OC::$server->getLogger()->logException($ex);
156
+                if (!\OC::$server->getAppManager()->isShipped($app)) {
157
+                    // Only disable apps which are not shipped
158
+                    \OC::$server->getAppManager()->disableApp($app);
159
+                }
160
+            }
161
+            \OC::$server->getEventLogger()->end('load_app_' . $app);
162
+        }
163
+
164
+        $info = self::getAppInfo($app);
165
+        if (!empty($info['activity']['filters'])) {
166
+            foreach ($info['activity']['filters'] as $filter) {
167
+                \OC::$server->getActivityManager()->registerFilter($filter);
168
+            }
169
+        }
170
+        if (!empty($info['activity']['settings'])) {
171
+            foreach ($info['activity']['settings'] as $setting) {
172
+                \OC::$server->getActivityManager()->registerSetting($setting);
173
+            }
174
+        }
175
+        if (!empty($info['activity']['providers'])) {
176
+            foreach ($info['activity']['providers'] as $provider) {
177
+                \OC::$server->getActivityManager()->registerProvider($provider);
178
+            }
179
+        }
180
+
181
+        if (!empty($info['settings']['admin'])) {
182
+            foreach ($info['settings']['admin'] as $setting) {
183
+                \OC::$server->getSettingsManager()->registerSetting('admin', $setting);
184
+            }
185
+        }
186
+        if (!empty($info['settings']['admin-section'])) {
187
+            foreach ($info['settings']['admin-section'] as $section) {
188
+                \OC::$server->getSettingsManager()->registerSection('admin', $section);
189
+            }
190
+        }
191
+        if (!empty($info['settings']['personal'])) {
192
+            foreach ($info['settings']['personal'] as $setting) {
193
+                \OC::$server->getSettingsManager()->registerSetting('personal', $setting);
194
+            }
195
+        }
196
+        if (!empty($info['settings']['personal-section'])) {
197
+            foreach ($info['settings']['personal-section'] as $section) {
198
+                \OC::$server->getSettingsManager()->registerSection('personal', $section);
199
+            }
200
+        }
201
+
202
+        if (!empty($info['collaboration']['plugins'])) {
203
+            // deal with one or many plugin entries
204
+            $plugins = isset($info['collaboration']['plugins']['plugin']['@value']) ?
205
+                [$info['collaboration']['plugins']['plugin']] : $info['collaboration']['plugins']['plugin'];
206
+            foreach ($plugins as $plugin) {
207
+                if($plugin['@attributes']['type'] === 'collaborator-search') {
208
+                    $pluginInfo = [
209
+                        'shareType' => $plugin['@attributes']['share-type'],
210
+                        'class' => $plugin['@value'],
211
+                    ];
212
+                    \OC::$server->getCollaboratorSearch()->registerPlugin($pluginInfo);
213
+                } else if ($plugin['@attributes']['type'] === 'autocomplete-sort') {
214
+                    \OC::$server->getAutoCompleteManager()->registerSorter($plugin['@value']);
215
+                }
216
+            }
217
+        }
218
+    }
219
+
220
+    /**
221
+     * @internal
222
+     * @param string $app
223
+     * @param string $path
224
+     */
225
+    public static function registerAutoloading(string $app, string $path) {
226
+        $key = $app . '-' . $path;
227
+        if(isset(self::$alreadyRegistered[$key])) {
228
+            return;
229
+        }
230
+
231
+        self::$alreadyRegistered[$key] = true;
232
+
233
+        // Register on PSR-4 composer autoloader
234
+        $appNamespace = \OC\AppFramework\App::buildAppNamespace($app);
235
+        \OC::$server->registerNamespace($app, $appNamespace);
236
+
237
+        if (file_exists($path . '/composer/autoload.php')) {
238
+            require_once $path . '/composer/autoload.php';
239
+        } else {
240
+            \OC::$composerAutoloader->addPsr4($appNamespace . '\\', $path . '/lib/', true);
241
+            // Register on legacy autoloader
242
+            \OC::$loader->addValidRoot($path);
243
+        }
244
+
245
+        // Register Test namespace only when testing
246
+        if (defined('PHPUNIT_RUN') || defined('CLI_TEST_RUN')) {
247
+            \OC::$composerAutoloader->addPsr4($appNamespace . '\\Tests\\', $path . '/tests/', true);
248
+        }
249
+    }
250
+
251
+    /**
252
+     * Load app.php from the given app
253
+     *
254
+     * @param string $app app name
255
+     * @throws Error
256
+     */
257
+    private static function requireAppFile(string $app) {
258
+        // encapsulated here to avoid variable scope conflicts
259
+        require_once $app . '/appinfo/app.php';
260
+    }
261
+
262
+    /**
263
+     * check if an app is of a specific type
264
+     *
265
+     * @param string $app
266
+     * @param array $types
267
+     * @return bool
268
+     */
269
+    public static function isType(string $app, array $types): bool {
270
+        $appTypes = self::getAppTypes($app);
271
+        foreach ($types as $type) {
272
+            if (array_search($type, $appTypes) !== false) {
273
+                return true;
274
+            }
275
+        }
276
+        return false;
277
+    }
278
+
279
+    /**
280
+     * get the types of an app
281
+     *
282
+     * @param string $app
283
+     * @return array
284
+     */
285
+    private static function getAppTypes(string $app): array {
286
+        //load the cache
287
+        if (count(self::$appTypes) == 0) {
288
+            self::$appTypes = \OC::$server->getAppConfig()->getValues(false, 'types');
289
+        }
290
+
291
+        if (isset(self::$appTypes[$app])) {
292
+            return explode(',', self::$appTypes[$app]);
293
+        }
294
+
295
+        return [];
296
+    }
297
+
298
+    /**
299
+     * read app types from info.xml and cache them in the database
300
+     */
301
+    public static function setAppTypes(string $app) {
302
+        $appManager = \OC::$server->getAppManager();
303
+        $appData = $appManager->getAppInfo($app);
304
+        if(!is_array($appData)) {
305
+            return;
306
+        }
307
+
308
+        if (isset($appData['types'])) {
309
+            $appTypes = implode(',', $appData['types']);
310
+        } else {
311
+            $appTypes = '';
312
+            $appData['types'] = [];
313
+        }
314
+
315
+        $config = \OC::$server->getConfig();
316
+        $config->setAppValue($app, 'types', $appTypes);
317
+
318
+        if ($appManager->hasProtectedAppType($appData['types'])) {
319
+            $enabled = $config->getAppValue($app, 'enabled', 'yes');
320
+            if ($enabled !== 'yes' && $enabled !== 'no') {
321
+                $config->setAppValue($app, 'enabled', 'yes');
322
+            }
323
+        }
324
+    }
325
+
326
+    /**
327
+     * Returns apps enabled for the current user.
328
+     *
329
+     * @param bool $forceRefresh whether to refresh the cache
330
+     * @param bool $all whether to return apps for all users, not only the
331
+     * currently logged in one
332
+     * @return string[]
333
+     */
334
+    public static function getEnabledApps(bool $forceRefresh = false, bool $all = false): array {
335
+        if (!\OC::$server->getSystemConfig()->getValue('installed', false)) {
336
+            return [];
337
+        }
338
+        // in incognito mode or when logged out, $user will be false,
339
+        // which is also the case during an upgrade
340
+        $appManager = \OC::$server->getAppManager();
341
+        if ($all) {
342
+            $user = null;
343
+        } else {
344
+            $user = \OC::$server->getUserSession()->getUser();
345
+        }
346
+
347
+        if (is_null($user)) {
348
+            $apps = $appManager->getInstalledApps();
349
+        } else {
350
+            $apps = $appManager->getEnabledAppsForUser($user);
351
+        }
352
+        $apps = array_filter($apps, function ($app) {
353
+            return $app !== 'files';//we add this manually
354
+        });
355
+        sort($apps);
356
+        array_unshift($apps, 'files');
357
+        return $apps;
358
+    }
359
+
360
+    /**
361
+     * checks whether or not an app is enabled
362
+     *
363
+     * @param string $app app
364
+     * @return bool
365
+     * @deprecated 13.0.0 use \OC::$server->getAppManager()->isEnabledForUser($appId)
366
+     *
367
+     * This function checks whether or not an app is enabled.
368
+     */
369
+    public static function isEnabled(string $app): bool {
370
+        return \OC::$server->getAppManager()->isEnabledForUser($app);
371
+    }
372
+
373
+    /**
374
+     * enables an app
375
+     *
376
+     * @param string $appId
377
+     * @param array $groups (optional) when set, only these groups will have access to the app
378
+     * @throws \Exception
379
+     * @return void
380
+     *
381
+     * This function set an app as enabled in appconfig.
382
+     */
383
+    public function enable(string $appId,
384
+                            array $groups = []) {
385
+
386
+        // Check if app is already downloaded
387
+        /** @var Installer $installer */
388
+        $installer = \OC::$server->query(Installer::class);
389
+        $isDownloaded = $installer->isDownloaded($appId);
390
+
391
+        if(!$isDownloaded) {
392
+            $installer->downloadApp($appId);
393
+        }
394
+
395
+        $installer->installApp($appId);
396
+
397
+        $appManager = \OC::$server->getAppManager();
398
+        if ($groups !== []) {
399
+            $groupManager = \OC::$server->getGroupManager();
400
+            $groupsList = [];
401
+            foreach ($groups as $group) {
402
+                $groupItem = $groupManager->get($group);
403
+                if ($groupItem instanceof \OCP\IGroup) {
404
+                    $groupsList[] = $groupManager->get($group);
405
+                }
406
+            }
407
+            $appManager->enableAppForGroups($appId, $groupsList);
408
+        } else {
409
+            $appManager->enableApp($appId);
410
+        }
411
+    }
412
+
413
+    /**
414
+     * Get the path where to install apps
415
+     *
416
+     * @return string|false
417
+     */
418
+    public static function getInstallPath() {
419
+        if (\OC::$server->getSystemConfig()->getValue('appstoreenabled', true) == false) {
420
+            return false;
421
+        }
422
+
423
+        foreach (OC::$APPSROOTS as $dir) {
424
+            if (isset($dir['writable']) && $dir['writable'] === true) {
425
+                return $dir['path'];
426
+            }
427
+        }
428
+
429
+        \OCP\Util::writeLog('core', 'No application directories are marked as writable.', ILogger::ERROR);
430
+        return null;
431
+    }
432
+
433
+
434
+    /**
435
+     * search for an app in all app-directories
436
+     *
437
+     * @param string $appId
438
+     * @return false|string
439
+     */
440
+    public static function findAppInDirectories(string $appId) {
441
+        $sanitizedAppId = self::cleanAppId($appId);
442
+        if($sanitizedAppId !== $appId) {
443
+            return false;
444
+        }
445
+        static $app_dir = [];
446
+
447
+        if (isset($app_dir[$appId])) {
448
+            return $app_dir[$appId];
449
+        }
450
+
451
+        $possibleApps = [];
452
+        foreach (OC::$APPSROOTS as $dir) {
453
+            if (file_exists($dir['path'] . '/' . $appId)) {
454
+                $possibleApps[] = $dir;
455
+            }
456
+        }
457
+
458
+        if (empty($possibleApps)) {
459
+            return false;
460
+        } elseif (count($possibleApps) === 1) {
461
+            $dir = array_shift($possibleApps);
462
+            $app_dir[$appId] = $dir;
463
+            return $dir;
464
+        } else {
465
+            $versionToLoad = [];
466
+            foreach ($possibleApps as $possibleApp) {
467
+                $version = self::getAppVersionByPath($possibleApp['path']);
468
+                if (empty($versionToLoad) || version_compare($version, $versionToLoad['version'], '>')) {
469
+                    $versionToLoad = array(
470
+                        'dir' => $possibleApp,
471
+                        'version' => $version,
472
+                    );
473
+                }
474
+            }
475
+            $app_dir[$appId] = $versionToLoad['dir'];
476
+            return $versionToLoad['dir'];
477
+            //TODO - write test
478
+        }
479
+    }
480
+
481
+    /**
482
+     * Get the directory for the given app.
483
+     * If the app is defined in multiple directories, the first one is taken. (false if not found)
484
+     *
485
+     * @param string $appId
486
+     * @return string|false
487
+     */
488
+    public static function getAppPath(string $appId) {
489
+        if ($appId === null || trim($appId) === '') {
490
+            return false;
491
+        }
492
+
493
+        if (($dir = self::findAppInDirectories($appId)) != false) {
494
+            return $dir['path'] . '/' . $appId;
495
+        }
496
+        return false;
497
+    }
498
+
499
+    /**
500
+     * Get the path for the given app on the access
501
+     * If the app is defined in multiple directories, the first one is taken. (false if not found)
502
+     *
503
+     * @param string $appId
504
+     * @return string|false
505
+     */
506
+    public static function getAppWebPath(string $appId) {
507
+        if (($dir = self::findAppInDirectories($appId)) != false) {
508
+            return OC::$WEBROOT . $dir['url'] . '/' . $appId;
509
+        }
510
+        return false;
511
+    }
512
+
513
+    /**
514
+     * get the last version of the app from appinfo/info.xml
515
+     *
516
+     * @param string $appId
517
+     * @param bool $useCache
518
+     * @return string
519
+     * @deprecated 14.0.0 use \OC::$server->getAppManager()->getAppVersion()
520
+     */
521
+    public static function getAppVersion(string $appId, bool $useCache = true): string {
522
+        return \OC::$server->getAppManager()->getAppVersion($appId, $useCache);
523
+    }
524
+
525
+    /**
526
+     * get app's version based on it's path
527
+     *
528
+     * @param string $path
529
+     * @return string
530
+     */
531
+    public static function getAppVersionByPath(string $path): string {
532
+        $infoFile = $path . '/appinfo/info.xml';
533
+        $appData = \OC::$server->getAppManager()->getAppInfo($infoFile, true);
534
+        return isset($appData['version']) ? $appData['version'] : '';
535
+    }
536
+
537
+
538
+    /**
539
+     * Read all app metadata from the info.xml file
540
+     *
541
+     * @param string $appId id of the app or the path of the info.xml file
542
+     * @param bool $path
543
+     * @param string $lang
544
+     * @return array|null
545
+     * @note all data is read from info.xml, not just pre-defined fields
546
+     * @deprecated 14.0.0 use \OC::$server->getAppManager()->getAppInfo()
547
+     */
548
+    public static function getAppInfo(string $appId, bool $path = false, string $lang = null) {
549
+        return \OC::$server->getAppManager()->getAppInfo($appId, $path, $lang);
550
+    }
551
+
552
+    /**
553
+     * Returns the navigation
554
+     *
555
+     * @return array
556
+     * @deprecated 14.0.0 use \OC::$server->getNavigationManager()->getAll()
557
+     *
558
+     * This function returns an array containing all entries added. The
559
+     * entries are sorted by the key 'order' ascending. Additional to the keys
560
+     * given for each app the following keys exist:
561
+     *   - active: boolean, signals if the user is on this navigation entry
562
+     */
563
+    public static function getNavigation(): array {
564
+        return OC::$server->getNavigationManager()->getAll();
565
+    }
566
+
567
+    /**
568
+     * Returns the Settings Navigation
569
+     *
570
+     * @return string[]
571
+     * @deprecated 14.0.0 use \OC::$server->getNavigationManager()->getAll('settings')
572
+     *
573
+     * This function returns an array containing all settings pages added. The
574
+     * entries are sorted by the key 'order' ascending.
575
+     */
576
+    public static function getSettingsNavigation(): array {
577
+        return OC::$server->getNavigationManager()->getAll('settings');
578
+    }
579
+
580
+    /**
581
+     * get the id of loaded app
582
+     *
583
+     * @return string
584
+     */
585
+    public static function getCurrentApp(): string {
586
+        $request = \OC::$server->getRequest();
587
+        $script = substr($request->getScriptName(), strlen(OC::$WEBROOT) + 1);
588
+        $topFolder = substr($script, 0, strpos($script, '/') ?: 0);
589
+        if (empty($topFolder)) {
590
+            $path_info = $request->getPathInfo();
591
+            if ($path_info) {
592
+                $topFolder = substr($path_info, 1, strpos($path_info, '/', 1) - 1);
593
+            }
594
+        }
595
+        if ($topFolder == 'apps') {
596
+            $length = strlen($topFolder);
597
+            return substr($script, $length + 1, strpos($script, '/', $length + 1) - $length - 1) ?: '';
598
+        } else {
599
+            return $topFolder;
600
+        }
601
+    }
602
+
603
+    /**
604
+     * @param string $type
605
+     * @return array
606
+     */
607
+    public static function getForms(string $type): array {
608
+        $forms = [];
609
+        switch ($type) {
610
+            case 'admin':
611
+                $source = self::$adminForms;
612
+                break;
613
+            case 'personal':
614
+                $source = self::$personalForms;
615
+                break;
616
+            default:
617
+                return [];
618
+        }
619
+        foreach ($source as $form) {
620
+            $forms[] = include $form;
621
+        }
622
+        return $forms;
623
+    }
624
+
625
+    /**
626
+     * register an admin form to be shown
627
+     *
628
+     * @param string $app
629
+     * @param string $page
630
+     */
631
+    public static function registerAdmin(string $app, string $page) {
632
+        self::$adminForms[] = $app . '/' . $page . '.php';
633
+    }
634
+
635
+    /**
636
+     * register a personal form to be shown
637
+     * @param string $app
638
+     * @param string $page
639
+     */
640
+    public static function registerPersonal(string $app, string $page) {
641
+        self::$personalForms[] = $app . '/' . $page . '.php';
642
+    }
643
+
644
+    /**
645
+     * @param array $entry
646
+     */
647
+    public static function registerLogIn(array $entry) {
648
+        self::$altLogin[] = $entry;
649
+    }
650
+
651
+    /**
652
+     * @return array
653
+     */
654
+    public static function getAlternativeLogIns(): array {
655
+        return self::$altLogin;
656
+    }
657
+
658
+    /**
659
+     * get a list of all apps in the apps folder
660
+     *
661
+     * @return array an array of app names (string IDs)
662
+     * @todo: change the name of this method to getInstalledApps, which is more accurate
663
+     */
664
+    public static function getAllApps(): array {
665
+
666
+        $apps = [];
667
+
668
+        foreach (OC::$APPSROOTS as $apps_dir) {
669
+            if (!is_readable($apps_dir['path'])) {
670
+                \OCP\Util::writeLog('core', 'unable to read app folder : ' . $apps_dir['path'], ILogger::WARN);
671
+                continue;
672
+            }
673
+            $dh = opendir($apps_dir['path']);
674
+
675
+            if (is_resource($dh)) {
676
+                while (($file = readdir($dh)) !== false) {
677
+
678
+                    if ($file[0] != '.' and is_dir($apps_dir['path'] . '/' . $file) and is_file($apps_dir['path'] . '/' . $file . '/appinfo/info.xml')) {
679
+
680
+                        $apps[] = $file;
681
+                    }
682
+                }
683
+            }
684
+        }
685
+
686
+        $apps = array_unique($apps);
687
+
688
+        return $apps;
689
+    }
690
+
691
+    /**
692
+     * List all apps, this is used in apps.php
693
+     *
694
+     * @return array
695
+     */
696
+    public function listAllApps(): array {
697
+        $installedApps = OC_App::getAllApps();
698
+
699
+        $appManager = \OC::$server->getAppManager();
700
+        //we don't want to show configuration for these
701
+        $blacklist = $appManager->getAlwaysEnabledApps();
702
+        $appList = [];
703
+        $langCode = \OC::$server->getL10N('core')->getLanguageCode();
704
+        $urlGenerator = \OC::$server->getURLGenerator();
705
+
706
+        foreach ($installedApps as $app) {
707
+            if (array_search($app, $blacklist) === false) {
708
+
709
+                $info = OC_App::getAppInfo($app, false, $langCode);
710
+                if (!is_array($info)) {
711
+                    \OCP\Util::writeLog('core', 'Could not read app info file for app "' . $app . '"', ILogger::ERROR);
712
+                    continue;
713
+                }
714
+
715
+                if (!isset($info['name'])) {
716
+                    \OCP\Util::writeLog('core', 'App id "' . $app . '" has no name in appinfo', ILogger::ERROR);
717
+                    continue;
718
+                }
719
+
720
+                $enabled = \OC::$server->getConfig()->getAppValue($app, 'enabled', 'no');
721
+                $info['groups'] = null;
722
+                if ($enabled === 'yes') {
723
+                    $active = true;
724
+                } else if ($enabled === 'no') {
725
+                    $active = false;
726
+                } else {
727
+                    $active = true;
728
+                    $info['groups'] = $enabled;
729
+                }
730
+
731
+                $info['active'] = $active;
732
+
733
+                if ($appManager->isShipped($app)) {
734
+                    $info['internal'] = true;
735
+                    $info['level'] = self::officialApp;
736
+                    $info['removable'] = false;
737
+                } else {
738
+                    $info['internal'] = false;
739
+                    $info['removable'] = true;
740
+                }
741
+
742
+                $appPath = self::getAppPath($app);
743
+                if($appPath !== false) {
744
+                    $appIcon = $appPath . '/img/' . $app . '.svg';
745
+                    if (file_exists($appIcon)) {
746
+                        $info['preview'] = $urlGenerator->imagePath($app, $app . '.svg');
747
+                        $info['previewAsIcon'] = true;
748
+                    } else {
749
+                        $appIcon = $appPath . '/img/app.svg';
750
+                        if (file_exists($appIcon)) {
751
+                            $info['preview'] = $urlGenerator->imagePath($app, 'app.svg');
752
+                            $info['previewAsIcon'] = true;
753
+                        }
754
+                    }
755
+                }
756
+                // fix documentation
757
+                if (isset($info['documentation']) && is_array($info['documentation'])) {
758
+                    foreach ($info['documentation'] as $key => $url) {
759
+                        // If it is not an absolute URL we assume it is a key
760
+                        // i.e. admin-ldap will get converted to go.php?to=admin-ldap
761
+                        if (stripos($url, 'https://') !== 0 && stripos($url, 'http://') !== 0) {
762
+                            $url = $urlGenerator->linkToDocs($url);
763
+                        }
764
+
765
+                        $info['documentation'][$key] = $url;
766
+                    }
767
+                }
768
+
769
+                $info['version'] = OC_App::getAppVersion($app);
770
+                $appList[] = $info;
771
+            }
772
+        }
773
+
774
+        return $appList;
775
+    }
776
+
777
+    public static function shouldUpgrade(string $app): bool {
778
+        $versions = self::getAppVersions();
779
+        $currentVersion = OC_App::getAppVersion($app);
780
+        if ($currentVersion && isset($versions[$app])) {
781
+            $installedVersion = $versions[$app];
782
+            if (!version_compare($currentVersion, $installedVersion, '=')) {
783
+                return true;
784
+            }
785
+        }
786
+        return false;
787
+    }
788
+
789
+    /**
790
+     * Adjust the number of version parts of $version1 to match
791
+     * the number of version parts of $version2.
792
+     *
793
+     * @param string $version1 version to adjust
794
+     * @param string $version2 version to take the number of parts from
795
+     * @return string shortened $version1
796
+     */
797
+    private static function adjustVersionParts(string $version1, string $version2): string {
798
+        $version1 = explode('.', $version1);
799
+        $version2 = explode('.', $version2);
800
+        // reduce $version1 to match the number of parts in $version2
801
+        while (count($version1) > count($version2)) {
802
+            array_pop($version1);
803
+        }
804
+        // if $version1 does not have enough parts, add some
805
+        while (count($version1) < count($version2)) {
806
+            $version1[] = '0';
807
+        }
808
+        return implode('.', $version1);
809
+    }
810
+
811
+    /**
812
+     * Check whether the current ownCloud version matches the given
813
+     * application's version requirements.
814
+     *
815
+     * The comparison is made based on the number of parts that the
816
+     * app info version has. For example for ownCloud 6.0.3 if the
817
+     * app info version is expecting version 6.0, the comparison is
818
+     * made on the first two parts of the ownCloud version.
819
+     * This means that it's possible to specify "requiremin" => 6
820
+     * and "requiremax" => 6 and it will still match ownCloud 6.0.3.
821
+     *
822
+     * @param string $ocVersion ownCloud version to check against
823
+     * @param array $appInfo app info (from xml)
824
+     *
825
+     * @return boolean true if compatible, otherwise false
826
+     */
827
+    public static function isAppCompatible(string $ocVersion, array $appInfo): bool {
828
+        $requireMin = '';
829
+        $requireMax = '';
830
+        if (isset($appInfo['dependencies']['nextcloud']['@attributes']['min-version'])) {
831
+            $requireMin = $appInfo['dependencies']['nextcloud']['@attributes']['min-version'];
832
+        } elseif (isset($appInfo['dependencies']['owncloud']['@attributes']['min-version'])) {
833
+            $requireMin = $appInfo['dependencies']['owncloud']['@attributes']['min-version'];
834
+        } else if (isset($appInfo['requiremin'])) {
835
+            $requireMin = $appInfo['requiremin'];
836
+        } else if (isset($appInfo['require'])) {
837
+            $requireMin = $appInfo['require'];
838
+        }
839
+
840
+        if (isset($appInfo['dependencies']['nextcloud']['@attributes']['max-version'])) {
841
+            $requireMax = $appInfo['dependencies']['nextcloud']['@attributes']['max-version'];
842
+        } elseif (isset($appInfo['dependencies']['owncloud']['@attributes']['max-version'])) {
843
+            $requireMax = $appInfo['dependencies']['owncloud']['@attributes']['max-version'];
844
+        } else if (isset($appInfo['requiremax'])) {
845
+            $requireMax = $appInfo['requiremax'];
846
+        }
847
+
848
+        if (!empty($requireMin)
849
+            && version_compare(self::adjustVersionParts($ocVersion, $requireMin), $requireMin, '<')
850
+        ) {
851
+
852
+            return false;
853
+        }
854
+
855
+        if (!empty($requireMax)
856
+            && version_compare(self::adjustVersionParts($ocVersion, $requireMax), $requireMax, '>')
857
+        ) {
858
+            return false;
859
+        }
860
+
861
+        return true;
862
+    }
863
+
864
+    /**
865
+     * get the installed version of all apps
866
+     */
867
+    public static function getAppVersions() {
868
+        static $versions;
869
+
870
+        if(!$versions) {
871
+            $appConfig = \OC::$server->getAppConfig();
872
+            $versions = $appConfig->getValues(false, 'installed_version');
873
+        }
874
+        return $versions;
875
+    }
876
+
877
+    /**
878
+     * update the database for the app and call the update script
879
+     *
880
+     * @param string $appId
881
+     * @return bool
882
+     */
883
+    public static function updateApp(string $appId): bool {
884
+        $appPath = self::getAppPath($appId);
885
+        if($appPath === false) {
886
+            return false;
887
+        }
888
+        self::registerAutoloading($appId, $appPath);
889
+
890
+        $appData = self::getAppInfo($appId);
891
+        self::executeRepairSteps($appId, $appData['repair-steps']['pre-migration']);
892
+
893
+        if (file_exists($appPath . '/appinfo/database.xml')) {
894
+            OC_DB::updateDbFromStructure($appPath . '/appinfo/database.xml');
895
+        } else {
896
+            $ms = new MigrationService($appId, \OC::$server->getDatabaseConnection());
897
+            $ms->migrate();
898
+        }
899
+
900
+        self::executeRepairSteps($appId, $appData['repair-steps']['post-migration']);
901
+        self::setupLiveMigrations($appId, $appData['repair-steps']['live-migration']);
902
+        // update appversion in app manager
903
+        \OC::$server->getAppManager()->getAppVersion($appId, false);
904
+
905
+        // run upgrade code
906
+        if (file_exists($appPath . '/appinfo/update.php')) {
907
+            self::loadApp($appId);
908
+            include $appPath . '/appinfo/update.php';
909
+        }
910
+        self::setupBackgroundJobs($appData['background-jobs']);
911
+
912
+        //set remote/public handlers
913
+        if (array_key_exists('ocsid', $appData)) {
914
+            \OC::$server->getConfig()->setAppValue($appId, 'ocsid', $appData['ocsid']);
915
+        } elseif(\OC::$server->getConfig()->getAppValue($appId, 'ocsid', null) !== null) {
916
+            \OC::$server->getConfig()->deleteAppValue($appId, 'ocsid');
917
+        }
918
+        foreach ($appData['remote'] as $name => $path) {
919
+            \OC::$server->getConfig()->setAppValue('core', 'remote_' . $name, $appId . '/' . $path);
920
+        }
921
+        foreach ($appData['public'] as $name => $path) {
922
+            \OC::$server->getConfig()->setAppValue('core', 'public_' . $name, $appId . '/' . $path);
923
+        }
924
+
925
+        self::setAppTypes($appId);
926
+
927
+        $version = \OC_App::getAppVersion($appId);
928
+        \OC::$server->getConfig()->setAppValue($appId, 'installed_version', $version);
929
+
930
+        \OC::$server->getEventDispatcher()->dispatch(ManagerEvent::EVENT_APP_UPDATE, new ManagerEvent(
931
+            ManagerEvent::EVENT_APP_UPDATE, $appId
932
+        ));
933
+
934
+        return true;
935
+    }
936
+
937
+    /**
938
+     * @param string $appId
939
+     * @param string[] $steps
940
+     * @throws \OC\NeedsUpdateException
941
+     */
942
+    public static function executeRepairSteps(string $appId, array $steps) {
943
+        if (empty($steps)) {
944
+            return;
945
+        }
946
+        // load the app
947
+        self::loadApp($appId);
948
+
949
+        $dispatcher = OC::$server->getEventDispatcher();
950
+
951
+        // load the steps
952
+        $r = new Repair([], $dispatcher);
953
+        foreach ($steps as $step) {
954
+            try {
955
+                $r->addStep($step);
956
+            } catch (Exception $ex) {
957
+                $r->emit('\OC\Repair', 'error', [$ex->getMessage()]);
958
+                \OC::$server->getLogger()->logException($ex);
959
+            }
960
+        }
961
+        // run the steps
962
+        $r->run();
963
+    }
964
+
965
+    public static function setupBackgroundJobs(array $jobs) {
966
+        $queue = \OC::$server->getJobList();
967
+        foreach ($jobs as $job) {
968
+            $queue->add($job);
969
+        }
970
+    }
971
+
972
+    /**
973
+     * @param string $appId
974
+     * @param string[] $steps
975
+     */
976
+    private static function setupLiveMigrations(string $appId, array $steps) {
977
+        $queue = \OC::$server->getJobList();
978
+        foreach ($steps as $step) {
979
+            $queue->add('OC\Migration\BackgroundRepair', [
980
+                'app' => $appId,
981
+                'step' => $step]);
982
+        }
983
+    }
984
+
985
+    /**
986
+     * @param string $appId
987
+     * @return \OC\Files\View|false
988
+     */
989
+    public static function getStorage(string $appId) {
990
+        if (\OC::$server->getAppManager()->isEnabledForUser($appId)) { //sanity check
991
+            if (\OC::$server->getUserSession()->isLoggedIn()) {
992
+                $view = new \OC\Files\View('/' . OC_User::getUser());
993
+                if (!$view->file_exists($appId)) {
994
+                    $view->mkdir($appId);
995
+                }
996
+                return new \OC\Files\View('/' . OC_User::getUser() . '/' . $appId);
997
+            } else {
998
+                \OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ', user not logged in', ILogger::ERROR);
999
+                return false;
1000
+            }
1001
+        } else {
1002
+            \OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ' not enabled', ILogger::ERROR);
1003
+            return false;
1004
+        }
1005
+    }
1006
+
1007
+    protected static function findBestL10NOption(array $options, string $lang): string {
1008
+        // only a single option
1009
+        if (isset($options['@value'])) {
1010
+            return $options['@value'];
1011
+        }
1012
+
1013
+        $fallback = $similarLangFallback = $englishFallback = false;
1014
+
1015
+        $lang = strtolower($lang);
1016
+        $similarLang = $lang;
1017
+        if (strpos($similarLang, '_')) {
1018
+            // For "de_DE" we want to find "de" and the other way around
1019
+            $similarLang = substr($lang, 0, strpos($lang, '_'));
1020
+        }
1021
+
1022
+        foreach ($options as $option) {
1023
+            if (is_array($option)) {
1024
+                if ($fallback === false) {
1025
+                    $fallback = $option['@value'];
1026
+                }
1027
+
1028
+                if (!isset($option['@attributes']['lang'])) {
1029
+                    continue;
1030
+                }
1031
+
1032
+                $attributeLang = strtolower($option['@attributes']['lang']);
1033
+                if ($attributeLang === $lang) {
1034
+                    return $option['@value'];
1035
+                }
1036
+
1037
+                if ($attributeLang === $similarLang) {
1038
+                    $similarLangFallback = $option['@value'];
1039
+                } else if (strpos($attributeLang, $similarLang . '_') === 0) {
1040
+                    if ($similarLangFallback === false) {
1041
+                        $similarLangFallback =  $option['@value'];
1042
+                    }
1043
+                }
1044
+            } else {
1045
+                $englishFallback = $option;
1046
+            }
1047
+        }
1048
+
1049
+        if ($similarLangFallback !== false) {
1050
+            return $similarLangFallback;
1051
+        } else if ($englishFallback !== false) {
1052
+            return $englishFallback;
1053
+        }
1054
+        return (string) $fallback;
1055
+    }
1056
+
1057
+    /**
1058
+     * parses the app data array and enhanced the 'description' value
1059
+     *
1060
+     * @param array $data the app data
1061
+     * @param string $lang
1062
+     * @return array improved app data
1063
+     */
1064
+    public static function parseAppInfo(array $data, $lang = null): array {
1065
+
1066
+        if ($lang && isset($data['name']) && is_array($data['name'])) {
1067
+            $data['name'] = self::findBestL10NOption($data['name'], $lang);
1068
+        }
1069
+        if ($lang && isset($data['summary']) && is_array($data['summary'])) {
1070
+            $data['summary'] = self::findBestL10NOption($data['summary'], $lang);
1071
+        }
1072
+        if ($lang && isset($data['description']) && is_array($data['description'])) {
1073
+            $data['description'] = trim(self::findBestL10NOption($data['description'], $lang));
1074
+        } else if (isset($data['description']) && is_string($data['description'])) {
1075
+            $data['description'] = trim($data['description']);
1076
+        } else  {
1077
+            $data['description'] = '';
1078
+        }
1079
+
1080
+        return $data;
1081
+    }
1082
+
1083
+    /**
1084
+     * @param \OCP\IConfig $config
1085
+     * @param \OCP\IL10N $l
1086
+     * @param array $info
1087
+     * @throws \Exception
1088
+     */
1089
+    public static function checkAppDependencies(\OCP\IConfig $config, \OCP\IL10N $l, array $info) {
1090
+        $dependencyAnalyzer = new DependencyAnalyzer(new Platform($config), $l);
1091
+        $missing = $dependencyAnalyzer->analyze($info);
1092
+        if (!empty($missing)) {
1093
+            $missingMsg = implode(PHP_EOL, $missing);
1094
+            throw new \Exception(
1095
+                $l->t('App "%s" cannot be installed because the following dependencies are not fulfilled: %s',
1096
+                    [$info['name'], $missingMsg]
1097
+                )
1098
+            );
1099
+        }
1100
+    }
1101 1101
 }
Please login to merge, or discard this patch.
Spacing   +49 added lines, -49 removed lines patch added patch discarded remove patch
@@ -112,9 +112,9 @@  discard block
 block discarded – undo
112 112
 		$apps = self::getEnabledApps();
113 113
 
114 114
 		// Add each apps' folder as allowed class path
115
-		foreach($apps as $app) {
115
+		foreach ($apps as $app) {
116 116
 			$path = self::getAppPath($app);
117
-			if($path !== false) {
117
+			if ($path !== false) {
118 118
 				self::registerAutoloading($app, $path);
119 119
 			}
120 120
 		}
@@ -140,15 +140,15 @@  discard block
 block discarded – undo
140 140
 	public static function loadApp(string $app) {
141 141
 		self::$loadedApps[] = $app;
142 142
 		$appPath = self::getAppPath($app);
143
-		if($appPath === false) {
143
+		if ($appPath === false) {
144 144
 			return;
145 145
 		}
146 146
 
147 147
 		// in case someone calls loadApp() directly
148 148
 		self::registerAutoloading($app, $appPath);
149 149
 
150
-		if (is_file($appPath . '/appinfo/app.php')) {
151
-			\OC::$server->getEventLogger()->start('load_app_' . $app, 'Load app: ' . $app);
150
+		if (is_file($appPath.'/appinfo/app.php')) {
151
+			\OC::$server->getEventLogger()->start('load_app_'.$app, 'Load app: '.$app);
152 152
 			try {
153 153
 				self::requireAppFile($app);
154 154
 			} catch (Error $ex) {
@@ -158,7 +158,7 @@  discard block
 block discarded – undo
158 158
 					\OC::$server->getAppManager()->disableApp($app);
159 159
 				}
160 160
 			}
161
-			\OC::$server->getEventLogger()->end('load_app_' . $app);
161
+			\OC::$server->getEventLogger()->end('load_app_'.$app);
162 162
 		}
163 163
 
164 164
 		$info = self::getAppInfo($app);
@@ -204,7 +204,7 @@  discard block
 block discarded – undo
204 204
 			$plugins = isset($info['collaboration']['plugins']['plugin']['@value']) ?
205 205
 				[$info['collaboration']['plugins']['plugin']] : $info['collaboration']['plugins']['plugin'];
206 206
 			foreach ($plugins as $plugin) {
207
-				if($plugin['@attributes']['type'] === 'collaborator-search') {
207
+				if ($plugin['@attributes']['type'] === 'collaborator-search') {
208 208
 					$pluginInfo = [
209 209
 						'shareType' => $plugin['@attributes']['share-type'],
210 210
 						'class' => $plugin['@value'],
@@ -223,8 +223,8 @@  discard block
 block discarded – undo
223 223
 	 * @param string $path
224 224
 	 */
225 225
 	public static function registerAutoloading(string $app, string $path) {
226
-		$key = $app . '-' . $path;
227
-		if(isset(self::$alreadyRegistered[$key])) {
226
+		$key = $app.'-'.$path;
227
+		if (isset(self::$alreadyRegistered[$key])) {
228 228
 			return;
229 229
 		}
230 230
 
@@ -234,17 +234,17 @@  discard block
 block discarded – undo
234 234
 		$appNamespace = \OC\AppFramework\App::buildAppNamespace($app);
235 235
 		\OC::$server->registerNamespace($app, $appNamespace);
236 236
 
237
-		if (file_exists($path . '/composer/autoload.php')) {
238
-			require_once $path . '/composer/autoload.php';
237
+		if (file_exists($path.'/composer/autoload.php')) {
238
+			require_once $path.'/composer/autoload.php';
239 239
 		} else {
240
-			\OC::$composerAutoloader->addPsr4($appNamespace . '\\', $path . '/lib/', true);
240
+			\OC::$composerAutoloader->addPsr4($appNamespace.'\\', $path.'/lib/', true);
241 241
 			// Register on legacy autoloader
242 242
 			\OC::$loader->addValidRoot($path);
243 243
 		}
244 244
 
245 245
 		// Register Test namespace only when testing
246 246
 		if (defined('PHPUNIT_RUN') || defined('CLI_TEST_RUN')) {
247
-			\OC::$composerAutoloader->addPsr4($appNamespace . '\\Tests\\', $path . '/tests/', true);
247
+			\OC::$composerAutoloader->addPsr4($appNamespace.'\\Tests\\', $path.'/tests/', true);
248 248
 		}
249 249
 	}
250 250
 
@@ -256,7 +256,7 @@  discard block
 block discarded – undo
256 256
 	 */
257 257
 	private static function requireAppFile(string $app) {
258 258
 		// encapsulated here to avoid variable scope conflicts
259
-		require_once $app . '/appinfo/app.php';
259
+		require_once $app.'/appinfo/app.php';
260 260
 	}
261 261
 
262 262
 	/**
@@ -301,7 +301,7 @@  discard block
 block discarded – undo
301 301
 	public static function setAppTypes(string $app) {
302 302
 		$appManager = \OC::$server->getAppManager();
303 303
 		$appData = $appManager->getAppInfo($app);
304
-		if(!is_array($appData)) {
304
+		if (!is_array($appData)) {
305 305
 			return;
306 306
 		}
307 307
 
@@ -349,8 +349,8 @@  discard block
 block discarded – undo
349 349
 		} else {
350 350
 			$apps = $appManager->getEnabledAppsForUser($user);
351 351
 		}
352
-		$apps = array_filter($apps, function ($app) {
353
-			return $app !== 'files';//we add this manually
352
+		$apps = array_filter($apps, function($app) {
353
+			return $app !== 'files'; //we add this manually
354 354
 		});
355 355
 		sort($apps);
356 356
 		array_unshift($apps, 'files');
@@ -388,7 +388,7 @@  discard block
 block discarded – undo
388 388
 		$installer = \OC::$server->query(Installer::class);
389 389
 		$isDownloaded = $installer->isDownloaded($appId);
390 390
 
391
-		if(!$isDownloaded) {
391
+		if (!$isDownloaded) {
392 392
 			$installer->downloadApp($appId);
393 393
 		}
394 394
 
@@ -439,7 +439,7 @@  discard block
 block discarded – undo
439 439
 	 */
440 440
 	public static function findAppInDirectories(string $appId) {
441 441
 		$sanitizedAppId = self::cleanAppId($appId);
442
-		if($sanitizedAppId !== $appId) {
442
+		if ($sanitizedAppId !== $appId) {
443 443
 			return false;
444 444
 		}
445 445
 		static $app_dir = [];
@@ -450,7 +450,7 @@  discard block
 block discarded – undo
450 450
 
451 451
 		$possibleApps = [];
452 452
 		foreach (OC::$APPSROOTS as $dir) {
453
-			if (file_exists($dir['path'] . '/' . $appId)) {
453
+			if (file_exists($dir['path'].'/'.$appId)) {
454 454
 				$possibleApps[] = $dir;
455 455
 			}
456 456
 		}
@@ -491,7 +491,7 @@  discard block
 block discarded – undo
491 491
 		}
492 492
 
493 493
 		if (($dir = self::findAppInDirectories($appId)) != false) {
494
-			return $dir['path'] . '/' . $appId;
494
+			return $dir['path'].'/'.$appId;
495 495
 		}
496 496
 		return false;
497 497
 	}
@@ -505,7 +505,7 @@  discard block
 block discarded – undo
505 505
 	 */
506 506
 	public static function getAppWebPath(string $appId) {
507 507
 		if (($dir = self::findAppInDirectories($appId)) != false) {
508
-			return OC::$WEBROOT . $dir['url'] . '/' . $appId;
508
+			return OC::$WEBROOT.$dir['url'].'/'.$appId;
509 509
 		}
510 510
 		return false;
511 511
 	}
@@ -529,7 +529,7 @@  discard block
 block discarded – undo
529 529
 	 * @return string
530 530
 	 */
531 531
 	public static function getAppVersionByPath(string $path): string {
532
-		$infoFile = $path . '/appinfo/info.xml';
532
+		$infoFile = $path.'/appinfo/info.xml';
533 533
 		$appData = \OC::$server->getAppManager()->getAppInfo($infoFile, true);
534 534
 		return isset($appData['version']) ? $appData['version'] : '';
535 535
 	}
@@ -629,7 +629,7 @@  discard block
 block discarded – undo
629 629
 	 * @param string $page
630 630
 	 */
631 631
 	public static function registerAdmin(string $app, string $page) {
632
-		self::$adminForms[] = $app . '/' . $page . '.php';
632
+		self::$adminForms[] = $app.'/'.$page.'.php';
633 633
 	}
634 634
 
635 635
 	/**
@@ -638,7 +638,7 @@  discard block
 block discarded – undo
638 638
 	 * @param string $page
639 639
 	 */
640 640
 	public static function registerPersonal(string $app, string $page) {
641
-		self::$personalForms[] = $app . '/' . $page . '.php';
641
+		self::$personalForms[] = $app.'/'.$page.'.php';
642 642
 	}
643 643
 
644 644
 	/**
@@ -667,7 +667,7 @@  discard block
 block discarded – undo
667 667
 
668 668
 		foreach (OC::$APPSROOTS as $apps_dir) {
669 669
 			if (!is_readable($apps_dir['path'])) {
670
-				\OCP\Util::writeLog('core', 'unable to read app folder : ' . $apps_dir['path'], ILogger::WARN);
670
+				\OCP\Util::writeLog('core', 'unable to read app folder : '.$apps_dir['path'], ILogger::WARN);
671 671
 				continue;
672 672
 			}
673 673
 			$dh = opendir($apps_dir['path']);
@@ -675,7 +675,7 @@  discard block
 block discarded – undo
675 675
 			if (is_resource($dh)) {
676 676
 				while (($file = readdir($dh)) !== false) {
677 677
 
678
-					if ($file[0] != '.' and is_dir($apps_dir['path'] . '/' . $file) and is_file($apps_dir['path'] . '/' . $file . '/appinfo/info.xml')) {
678
+					if ($file[0] != '.' and is_dir($apps_dir['path'].'/'.$file) and is_file($apps_dir['path'].'/'.$file.'/appinfo/info.xml')) {
679 679
 
680 680
 						$apps[] = $file;
681 681
 					}
@@ -708,12 +708,12 @@  discard block
 block discarded – undo
708 708
 
709 709
 				$info = OC_App::getAppInfo($app, false, $langCode);
710 710
 				if (!is_array($info)) {
711
-					\OCP\Util::writeLog('core', 'Could not read app info file for app "' . $app . '"', ILogger::ERROR);
711
+					\OCP\Util::writeLog('core', 'Could not read app info file for app "'.$app.'"', ILogger::ERROR);
712 712
 					continue;
713 713
 				}
714 714
 
715 715
 				if (!isset($info['name'])) {
716
-					\OCP\Util::writeLog('core', 'App id "' . $app . '" has no name in appinfo', ILogger::ERROR);
716
+					\OCP\Util::writeLog('core', 'App id "'.$app.'" has no name in appinfo', ILogger::ERROR);
717 717
 					continue;
718 718
 				}
719 719
 
@@ -740,13 +740,13 @@  discard block
 block discarded – undo
740 740
 				}
741 741
 
742 742
 				$appPath = self::getAppPath($app);
743
-				if($appPath !== false) {
744
-					$appIcon = $appPath . '/img/' . $app . '.svg';
743
+				if ($appPath !== false) {
744
+					$appIcon = $appPath.'/img/'.$app.'.svg';
745 745
 					if (file_exists($appIcon)) {
746
-						$info['preview'] = $urlGenerator->imagePath($app, $app . '.svg');
746
+						$info['preview'] = $urlGenerator->imagePath($app, $app.'.svg');
747 747
 						$info['previewAsIcon'] = true;
748 748
 					} else {
749
-						$appIcon = $appPath . '/img/app.svg';
749
+						$appIcon = $appPath.'/img/app.svg';
750 750
 						if (file_exists($appIcon)) {
751 751
 							$info['preview'] = $urlGenerator->imagePath($app, 'app.svg');
752 752
 							$info['previewAsIcon'] = true;
@@ -867,7 +867,7 @@  discard block
 block discarded – undo
867 867
 	public static function getAppVersions() {
868 868
 		static $versions;
869 869
 
870
-		if(!$versions) {
870
+		if (!$versions) {
871 871
 			$appConfig = \OC::$server->getAppConfig();
872 872
 			$versions = $appConfig->getValues(false, 'installed_version');
873 873
 		}
@@ -882,7 +882,7 @@  discard block
 block discarded – undo
882 882
 	 */
883 883
 	public static function updateApp(string $appId): bool {
884 884
 		$appPath = self::getAppPath($appId);
885
-		if($appPath === false) {
885
+		if ($appPath === false) {
886 886
 			return false;
887 887
 		}
888 888
 		self::registerAutoloading($appId, $appPath);
@@ -890,8 +890,8 @@  discard block
 block discarded – undo
890 890
 		$appData = self::getAppInfo($appId);
891 891
 		self::executeRepairSteps($appId, $appData['repair-steps']['pre-migration']);
892 892
 
893
-		if (file_exists($appPath . '/appinfo/database.xml')) {
894
-			OC_DB::updateDbFromStructure($appPath . '/appinfo/database.xml');
893
+		if (file_exists($appPath.'/appinfo/database.xml')) {
894
+			OC_DB::updateDbFromStructure($appPath.'/appinfo/database.xml');
895 895
 		} else {
896 896
 			$ms = new MigrationService($appId, \OC::$server->getDatabaseConnection());
897 897
 			$ms->migrate();
@@ -903,23 +903,23 @@  discard block
 block discarded – undo
903 903
 		\OC::$server->getAppManager()->getAppVersion($appId, false);
904 904
 
905 905
 		// run upgrade code
906
-		if (file_exists($appPath . '/appinfo/update.php')) {
906
+		if (file_exists($appPath.'/appinfo/update.php')) {
907 907
 			self::loadApp($appId);
908
-			include $appPath . '/appinfo/update.php';
908
+			include $appPath.'/appinfo/update.php';
909 909
 		}
910 910
 		self::setupBackgroundJobs($appData['background-jobs']);
911 911
 
912 912
 		//set remote/public handlers
913 913
 		if (array_key_exists('ocsid', $appData)) {
914 914
 			\OC::$server->getConfig()->setAppValue($appId, 'ocsid', $appData['ocsid']);
915
-		} elseif(\OC::$server->getConfig()->getAppValue($appId, 'ocsid', null) !== null) {
915
+		} elseif (\OC::$server->getConfig()->getAppValue($appId, 'ocsid', null) !== null) {
916 916
 			\OC::$server->getConfig()->deleteAppValue($appId, 'ocsid');
917 917
 		}
918 918
 		foreach ($appData['remote'] as $name => $path) {
919
-			\OC::$server->getConfig()->setAppValue('core', 'remote_' . $name, $appId . '/' . $path);
919
+			\OC::$server->getConfig()->setAppValue('core', 'remote_'.$name, $appId.'/'.$path);
920 920
 		}
921 921
 		foreach ($appData['public'] as $name => $path) {
922
-			\OC::$server->getConfig()->setAppValue('core', 'public_' . $name, $appId . '/' . $path);
922
+			\OC::$server->getConfig()->setAppValue('core', 'public_'.$name, $appId.'/'.$path);
923 923
 		}
924 924
 
925 925
 		self::setAppTypes($appId);
@@ -989,17 +989,17 @@  discard block
 block discarded – undo
989 989
 	public static function getStorage(string $appId) {
990 990
 		if (\OC::$server->getAppManager()->isEnabledForUser($appId)) { //sanity check
991 991
 			if (\OC::$server->getUserSession()->isLoggedIn()) {
992
-				$view = new \OC\Files\View('/' . OC_User::getUser());
992
+				$view = new \OC\Files\View('/'.OC_User::getUser());
993 993
 				if (!$view->file_exists($appId)) {
994 994
 					$view->mkdir($appId);
995 995
 				}
996
-				return new \OC\Files\View('/' . OC_User::getUser() . '/' . $appId);
996
+				return new \OC\Files\View('/'.OC_User::getUser().'/'.$appId);
997 997
 			} else {
998
-				\OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ', user not logged in', ILogger::ERROR);
998
+				\OCP\Util::writeLog('core', 'Can\'t get app storage, app '.$appId.', user not logged in', ILogger::ERROR);
999 999
 				return false;
1000 1000
 			}
1001 1001
 		} else {
1002
-			\OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ' not enabled', ILogger::ERROR);
1002
+			\OCP\Util::writeLog('core', 'Can\'t get app storage, app '.$appId.' not enabled', ILogger::ERROR);
1003 1003
 			return false;
1004 1004
 		}
1005 1005
 	}
@@ -1036,9 +1036,9 @@  discard block
 block discarded – undo
1036 1036
 
1037 1037
 				if ($attributeLang === $similarLang) {
1038 1038
 					$similarLangFallback = $option['@value'];
1039
-				} else if (strpos($attributeLang, $similarLang . '_') === 0) {
1039
+				} else if (strpos($attributeLang, $similarLang.'_') === 0) {
1040 1040
 					if ($similarLangFallback === false) {
1041
-						$similarLangFallback =  $option['@value'];
1041
+						$similarLangFallback = $option['@value'];
1042 1042
 					}
1043 1043
 				}
1044 1044
 			} else {
@@ -1073,7 +1073,7 @@  discard block
 block discarded – undo
1073 1073
 			$data['description'] = trim(self::findBestL10NOption($data['description'], $lang));
1074 1074
 		} else if (isset($data['description']) && is_string($data['description'])) {
1075 1075
 			$data['description'] = trim($data['description']);
1076
-		} else  {
1076
+		} else {
1077 1077
 			$data['description'] = '';
1078 1078
 		}
1079 1079
 
Please login to merge, or discard this patch.
lib/private/legacy/user.php 2 patches
Indentation   +346 added lines, -346 removed lines patch added patch discarded remove patch
@@ -60,350 +60,350 @@
 block discarded – undo
60 60
  */
61 61
 class OC_User {
62 62
 
63
-	private static $_usedBackends = array();
64
-
65
-	private static $_setupedBackends = array();
66
-
67
-	// bool, stores if a user want to access a resource anonymously, e.g if they open a public link
68
-	private static $incognitoMode = false;
69
-
70
-	/**
71
-	 * Adds the backend to the list of used backends
72
-	 *
73
-	 * @param string|\OCP\UserInterface $backend default: database The backend to use for user management
74
-	 * @return bool
75
-	 *
76
-	 * Set the User Authentication Module
77
-	 * @suppress PhanDeprecatedFunction
78
-	 */
79
-	public static function useBackend($backend = 'database') {
80
-		if ($backend instanceof \OCP\UserInterface) {
81
-			self::$_usedBackends[get_class($backend)] = $backend;
82
-			\OC::$server->getUserManager()->registerBackend($backend);
83
-		} else {
84
-			// You'll never know what happens
85
-			if (null === $backend OR !is_string($backend)) {
86
-				$backend = 'database';
87
-			}
88
-
89
-			// Load backend
90
-			switch ($backend) {
91
-				case 'database':
92
-				case 'mysql':
93
-				case 'sqlite':
94
-					\OCP\Util::writeLog('core', 'Adding user backend ' . $backend . '.', ILogger::DEBUG);
95
-					self::$_usedBackends[$backend] = new \OC\User\Database();
96
-					\OC::$server->getUserManager()->registerBackend(self::$_usedBackends[$backend]);
97
-					break;
98
-				case 'dummy':
99
-					self::$_usedBackends[$backend] = new \Test\Util\User\Dummy();
100
-					\OC::$server->getUserManager()->registerBackend(self::$_usedBackends[$backend]);
101
-					break;
102
-				default:
103
-					\OCP\Util::writeLog('core', 'Adding default user backend ' . $backend . '.', ILogger::DEBUG);
104
-					$className = 'OC_USER_' . strtoupper($backend);
105
-					self::$_usedBackends[$backend] = new $className();
106
-					\OC::$server->getUserManager()->registerBackend(self::$_usedBackends[$backend]);
107
-					break;
108
-			}
109
-		}
110
-		return true;
111
-	}
112
-
113
-	/**
114
-	 * remove all used backends
115
-	 */
116
-	public static function clearBackends() {
117
-		self::$_usedBackends = array();
118
-		\OC::$server->getUserManager()->clearBackends();
119
-	}
120
-
121
-	/**
122
-	 * setup the configured backends in config.php
123
-	 * @suppress PhanDeprecatedFunction
124
-	 */
125
-	public static function setupBackends() {
126
-		OC_App::loadApps(['prelogin']);
127
-		$backends = \OC::$server->getSystemConfig()->getValue('user_backends', []);
128
-		if (isset($backends['default']) && !$backends['default']) {
129
-			// clear default backends
130
-			self::clearBackends();
131
-		}
132
-		foreach ($backends as $i => $config) {
133
-			if (!is_array($config)) {
134
-				continue;
135
-			}
136
-			$class = $config['class'];
137
-			$arguments = $config['arguments'];
138
-			if (class_exists($class)) {
139
-				if (array_search($i, self::$_setupedBackends) === false) {
140
-					// make a reflection object
141
-					$reflectionObj = new ReflectionClass($class);
142
-
143
-					// use Reflection to create a new instance, using the $args
144
-					$backend = $reflectionObj->newInstanceArgs($arguments);
145
-					self::useBackend($backend);
146
-					self::$_setupedBackends[] = $i;
147
-				} else {
148
-					\OCP\Util::writeLog('core', 'User backend ' . $class . ' already initialized.', ILogger::DEBUG);
149
-				}
150
-			} else {
151
-				\OCP\Util::writeLog('core', 'User backend ' . $class . ' not found.', ILogger::ERROR);
152
-			}
153
-		}
154
-	}
155
-
156
-	/**
157
-	 * Try to login a user, assuming authentication
158
-	 * has already happened (e.g. via Single Sign On).
159
-	 *
160
-	 * Log in a user and regenerate a new session.
161
-	 *
162
-	 * @param \OCP\Authentication\IApacheBackend $backend
163
-	 * @return bool
164
-	 */
165
-	public static function loginWithApache(\OCP\Authentication\IApacheBackend $backend) {
166
-
167
-		$uid = $backend->getCurrentUserId();
168
-		$run = true;
169
-		OC_Hook::emit("OC_User", "pre_login", array("run" => &$run, "uid" => $uid));
170
-
171
-		if ($uid) {
172
-			if (self::getUser() !== $uid) {
173
-				self::setUserId($uid);
174
-				$userSession = \OC::$server->getUserSession();
175
-				$userSession->setLoginName($uid);
176
-				$request = OC::$server->getRequest();
177
-				$userSession->createSessionToken($request, $uid, $uid);
178
-				// setup the filesystem
179
-				OC_Util::setupFS($uid);
180
-				// first call the post_login hooks, the login-process needs to be
181
-				// completed before we can safely create the users folder.
182
-				// For example encryption needs to initialize the users keys first
183
-				// before we can create the user folder with the skeleton files
184
-				OC_Hook::emit("OC_User", "post_login", array("uid" => $uid, 'password' => ''));
185
-				//trigger creation of user home and /files folder
186
-				\OC::$server->getUserFolder($uid);
187
-			}
188
-			return true;
189
-		}
190
-		return false;
191
-	}
192
-
193
-	/**
194
-	 * Verify with Apache whether user is authenticated.
195
-	 *
196
-	 * @return boolean|null
197
-	 *          true: authenticated
198
-	 *          false: not authenticated
199
-	 *          null: not handled / no backend available
200
-	 */
201
-	public static function handleApacheAuth() {
202
-		$backend = self::findFirstActiveUsedBackend();
203
-		if ($backend) {
204
-			OC_App::loadApps();
205
-
206
-			//setup extra user backends
207
-			self::setupBackends();
208
-			\OC::$server->getUserSession()->unsetMagicInCookie();
209
-
210
-			return self::loginWithApache($backend);
211
-		}
212
-
213
-		return null;
214
-	}
215
-
216
-
217
-	/**
218
-	 * Sets user id for session and triggers emit
219
-	 *
220
-	 * @param string $uid
221
-	 */
222
-	public static function setUserId($uid) {
223
-		$userSession = \OC::$server->getUserSession();
224
-		$userManager = \OC::$server->getUserManager();
225
-		if ($user = $userManager->get($uid)) {
226
-			$userSession->setUser($user);
227
-		} else {
228
-			\OC::$server->getSession()->set('user_id', $uid);
229
-		}
230
-	}
231
-
232
-	/**
233
-	 * Check if the user is logged in, considers also the HTTP basic credentials
234
-	 *
235
-	 * @deprecated use \OC::$server->getUserSession()->isLoggedIn()
236
-	 * @return bool
237
-	 */
238
-	public static function isLoggedIn() {
239
-		return \OC::$server->getUserSession()->isLoggedIn();
240
-	}
241
-
242
-	/**
243
-	 * set incognito mode, e.g. if a user wants to open a public link
244
-	 *
245
-	 * @param bool $status
246
-	 */
247
-	public static function setIncognitoMode($status) {
248
-		self::$incognitoMode = $status;
249
-	}
250
-
251
-	/**
252
-	 * get incognito mode status
253
-	 *
254
-	 * @return bool
255
-	 */
256
-	public static function isIncognitoMode() {
257
-		return self::$incognitoMode;
258
-	}
259
-
260
-	/**
261
-	 * Returns the current logout URL valid for the currently logged-in user
262
-	 *
263
-	 * @param \OCP\IURLGenerator $urlGenerator
264
-	 * @return string
265
-	 */
266
-	public static function getLogoutUrl(\OCP\IURLGenerator $urlGenerator) {
267
-		$backend = self::findFirstActiveUsedBackend();
268
-		if ($backend) {
269
-			return $backend->getLogoutUrl();
270
-		}
271
-
272
-		$logoutUrl = $urlGenerator->linkToRouteAbsolute(
273
-			'core.login.logout',
274
-			[
275
-				'requesttoken' => \OCP\Util::callRegister(),
276
-			]
277
-		);
278
-
279
-		return $logoutUrl;
280
-	}
281
-
282
-	/**
283
-	 * Check if the user is an admin user
284
-	 *
285
-	 * @param string $uid uid of the admin
286
-	 * @return bool
287
-	 */
288
-	public static function isAdminUser($uid) {
289
-		$group = \OC::$server->getGroupManager()->get('admin');
290
-		$user = \OC::$server->getUserManager()->get($uid);
291
-		if ($group && $user && $group->inGroup($user) && self::$incognitoMode === false) {
292
-			return true;
293
-		}
294
-		return false;
295
-	}
296
-
297
-
298
-	/**
299
-	 * get the user id of the user currently logged in.
300
-	 *
301
-	 * @return string|bool uid or false
302
-	 */
303
-	public static function getUser() {
304
-		$uid = \OC::$server->getSession() ? \OC::$server->getSession()->get('user_id') : null;
305
-		if (!is_null($uid) && self::$incognitoMode === false) {
306
-			return $uid;
307
-		} else {
308
-			return false;
309
-		}
310
-	}
311
-
312
-	/**
313
-	 * get the display name of the user currently logged in.
314
-	 *
315
-	 * @param string $uid
316
-	 * @return string|bool uid or false
317
-	 * @deprecated 8.1.0 fetch \OCP\IUser (has getDisplayName()) by using method
318
-	 *                   get() of \OCP\IUserManager - \OC::$server->getUserManager()
319
-	 */
320
-	public static function getDisplayName($uid = null) {
321
-		if ($uid) {
322
-			$user = \OC::$server->getUserManager()->get($uid);
323
-			if ($user) {
324
-				return $user->getDisplayName();
325
-			} else {
326
-				return $uid;
327
-			}
328
-		} else {
329
-			$user = \OC::$server->getUserSession()->getUser();
330
-			if ($user) {
331
-				return $user->getDisplayName();
332
-			} else {
333
-				return false;
334
-			}
335
-		}
336
-	}
337
-
338
-	/**
339
-	 * Set password
340
-	 *
341
-	 * @param string $uid The username
342
-	 * @param string $password The new password
343
-	 * @param string $recoveryPassword for the encryption app to reset encryption keys
344
-	 * @return bool
345
-	 *
346
-	 * Change the password of a user
347
-	 */
348
-	public static function setPassword($uid, $password, $recoveryPassword = null) {
349
-		$user = \OC::$server->getUserManager()->get($uid);
350
-		if ($user) {
351
-			return $user->setPassword($password, $recoveryPassword);
352
-		} else {
353
-			return false;
354
-		}
355
-	}
356
-
357
-	/**
358
-	 * @param string $uid The username
359
-	 * @return string
360
-	 *
361
-	 * returns the path to the users home directory
362
-	 * @deprecated Use \OC::$server->getUserManager->getHome()
363
-	 */
364
-	public static function getHome($uid) {
365
-		$user = \OC::$server->getUserManager()->get($uid);
366
-		if ($user) {
367
-			return $user->getHome();
368
-		} else {
369
-			return \OC::$server->getSystemConfig()->getValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $uid;
370
-		}
371
-	}
372
-
373
-	/**
374
-	 * Get a list of all users display name
375
-	 *
376
-	 * @param string $search
377
-	 * @param int $limit
378
-	 * @param int $offset
379
-	 * @return array associative array with all display names (value) and corresponding uids (key)
380
-	 *
381
-	 * Get a list of all display names and user ids.
382
-	 * @deprecated Use \OC::$server->getUserManager->searchDisplayName($search, $limit, $offset) instead.
383
-	 */
384
-	public static function getDisplayNames($search = '', $limit = null, $offset = null) {
385
-		$displayNames = array();
386
-		$users = \OC::$server->getUserManager()->searchDisplayName($search, $limit, $offset);
387
-		foreach ($users as $user) {
388
-			$displayNames[$user->getUID()] = $user->getDisplayName();
389
-		}
390
-		return $displayNames;
391
-	}
392
-
393
-	/**
394
-	 * Returns the first active backend from self::$_usedBackends.
395
-	 *
396
-	 * @return OCP\Authentication\IApacheBackend|null if no backend active, otherwise OCP\Authentication\IApacheBackend
397
-	 */
398
-	private static function findFirstActiveUsedBackend() {
399
-		foreach (self::$_usedBackends as $backend) {
400
-			if ($backend instanceof OCP\Authentication\IApacheBackend) {
401
-				if ($backend->isSessionActive()) {
402
-					return $backend;
403
-				}
404
-			}
405
-		}
406
-
407
-		return null;
408
-	}
63
+    private static $_usedBackends = array();
64
+
65
+    private static $_setupedBackends = array();
66
+
67
+    // bool, stores if a user want to access a resource anonymously, e.g if they open a public link
68
+    private static $incognitoMode = false;
69
+
70
+    /**
71
+     * Adds the backend to the list of used backends
72
+     *
73
+     * @param string|\OCP\UserInterface $backend default: database The backend to use for user management
74
+     * @return bool
75
+     *
76
+     * Set the User Authentication Module
77
+     * @suppress PhanDeprecatedFunction
78
+     */
79
+    public static function useBackend($backend = 'database') {
80
+        if ($backend instanceof \OCP\UserInterface) {
81
+            self::$_usedBackends[get_class($backend)] = $backend;
82
+            \OC::$server->getUserManager()->registerBackend($backend);
83
+        } else {
84
+            // You'll never know what happens
85
+            if (null === $backend OR !is_string($backend)) {
86
+                $backend = 'database';
87
+            }
88
+
89
+            // Load backend
90
+            switch ($backend) {
91
+                case 'database':
92
+                case 'mysql':
93
+                case 'sqlite':
94
+                    \OCP\Util::writeLog('core', 'Adding user backend ' . $backend . '.', ILogger::DEBUG);
95
+                    self::$_usedBackends[$backend] = new \OC\User\Database();
96
+                    \OC::$server->getUserManager()->registerBackend(self::$_usedBackends[$backend]);
97
+                    break;
98
+                case 'dummy':
99
+                    self::$_usedBackends[$backend] = new \Test\Util\User\Dummy();
100
+                    \OC::$server->getUserManager()->registerBackend(self::$_usedBackends[$backend]);
101
+                    break;
102
+                default:
103
+                    \OCP\Util::writeLog('core', 'Adding default user backend ' . $backend . '.', ILogger::DEBUG);
104
+                    $className = 'OC_USER_' . strtoupper($backend);
105
+                    self::$_usedBackends[$backend] = new $className();
106
+                    \OC::$server->getUserManager()->registerBackend(self::$_usedBackends[$backend]);
107
+                    break;
108
+            }
109
+        }
110
+        return true;
111
+    }
112
+
113
+    /**
114
+     * remove all used backends
115
+     */
116
+    public static function clearBackends() {
117
+        self::$_usedBackends = array();
118
+        \OC::$server->getUserManager()->clearBackends();
119
+    }
120
+
121
+    /**
122
+     * setup the configured backends in config.php
123
+     * @suppress PhanDeprecatedFunction
124
+     */
125
+    public static function setupBackends() {
126
+        OC_App::loadApps(['prelogin']);
127
+        $backends = \OC::$server->getSystemConfig()->getValue('user_backends', []);
128
+        if (isset($backends['default']) && !$backends['default']) {
129
+            // clear default backends
130
+            self::clearBackends();
131
+        }
132
+        foreach ($backends as $i => $config) {
133
+            if (!is_array($config)) {
134
+                continue;
135
+            }
136
+            $class = $config['class'];
137
+            $arguments = $config['arguments'];
138
+            if (class_exists($class)) {
139
+                if (array_search($i, self::$_setupedBackends) === false) {
140
+                    // make a reflection object
141
+                    $reflectionObj = new ReflectionClass($class);
142
+
143
+                    // use Reflection to create a new instance, using the $args
144
+                    $backend = $reflectionObj->newInstanceArgs($arguments);
145
+                    self::useBackend($backend);
146
+                    self::$_setupedBackends[] = $i;
147
+                } else {
148
+                    \OCP\Util::writeLog('core', 'User backend ' . $class . ' already initialized.', ILogger::DEBUG);
149
+                }
150
+            } else {
151
+                \OCP\Util::writeLog('core', 'User backend ' . $class . ' not found.', ILogger::ERROR);
152
+            }
153
+        }
154
+    }
155
+
156
+    /**
157
+     * Try to login a user, assuming authentication
158
+     * has already happened (e.g. via Single Sign On).
159
+     *
160
+     * Log in a user and regenerate a new session.
161
+     *
162
+     * @param \OCP\Authentication\IApacheBackend $backend
163
+     * @return bool
164
+     */
165
+    public static function loginWithApache(\OCP\Authentication\IApacheBackend $backend) {
166
+
167
+        $uid = $backend->getCurrentUserId();
168
+        $run = true;
169
+        OC_Hook::emit("OC_User", "pre_login", array("run" => &$run, "uid" => $uid));
170
+
171
+        if ($uid) {
172
+            if (self::getUser() !== $uid) {
173
+                self::setUserId($uid);
174
+                $userSession = \OC::$server->getUserSession();
175
+                $userSession->setLoginName($uid);
176
+                $request = OC::$server->getRequest();
177
+                $userSession->createSessionToken($request, $uid, $uid);
178
+                // setup the filesystem
179
+                OC_Util::setupFS($uid);
180
+                // first call the post_login hooks, the login-process needs to be
181
+                // completed before we can safely create the users folder.
182
+                // For example encryption needs to initialize the users keys first
183
+                // before we can create the user folder with the skeleton files
184
+                OC_Hook::emit("OC_User", "post_login", array("uid" => $uid, 'password' => ''));
185
+                //trigger creation of user home and /files folder
186
+                \OC::$server->getUserFolder($uid);
187
+            }
188
+            return true;
189
+        }
190
+        return false;
191
+    }
192
+
193
+    /**
194
+     * Verify with Apache whether user is authenticated.
195
+     *
196
+     * @return boolean|null
197
+     *          true: authenticated
198
+     *          false: not authenticated
199
+     *          null: not handled / no backend available
200
+     */
201
+    public static function handleApacheAuth() {
202
+        $backend = self::findFirstActiveUsedBackend();
203
+        if ($backend) {
204
+            OC_App::loadApps();
205
+
206
+            //setup extra user backends
207
+            self::setupBackends();
208
+            \OC::$server->getUserSession()->unsetMagicInCookie();
209
+
210
+            return self::loginWithApache($backend);
211
+        }
212
+
213
+        return null;
214
+    }
215
+
216
+
217
+    /**
218
+     * Sets user id for session and triggers emit
219
+     *
220
+     * @param string $uid
221
+     */
222
+    public static function setUserId($uid) {
223
+        $userSession = \OC::$server->getUserSession();
224
+        $userManager = \OC::$server->getUserManager();
225
+        if ($user = $userManager->get($uid)) {
226
+            $userSession->setUser($user);
227
+        } else {
228
+            \OC::$server->getSession()->set('user_id', $uid);
229
+        }
230
+    }
231
+
232
+    /**
233
+     * Check if the user is logged in, considers also the HTTP basic credentials
234
+     *
235
+     * @deprecated use \OC::$server->getUserSession()->isLoggedIn()
236
+     * @return bool
237
+     */
238
+    public static function isLoggedIn() {
239
+        return \OC::$server->getUserSession()->isLoggedIn();
240
+    }
241
+
242
+    /**
243
+     * set incognito mode, e.g. if a user wants to open a public link
244
+     *
245
+     * @param bool $status
246
+     */
247
+    public static function setIncognitoMode($status) {
248
+        self::$incognitoMode = $status;
249
+    }
250
+
251
+    /**
252
+     * get incognito mode status
253
+     *
254
+     * @return bool
255
+     */
256
+    public static function isIncognitoMode() {
257
+        return self::$incognitoMode;
258
+    }
259
+
260
+    /**
261
+     * Returns the current logout URL valid for the currently logged-in user
262
+     *
263
+     * @param \OCP\IURLGenerator $urlGenerator
264
+     * @return string
265
+     */
266
+    public static function getLogoutUrl(\OCP\IURLGenerator $urlGenerator) {
267
+        $backend = self::findFirstActiveUsedBackend();
268
+        if ($backend) {
269
+            return $backend->getLogoutUrl();
270
+        }
271
+
272
+        $logoutUrl = $urlGenerator->linkToRouteAbsolute(
273
+            'core.login.logout',
274
+            [
275
+                'requesttoken' => \OCP\Util::callRegister(),
276
+            ]
277
+        );
278
+
279
+        return $logoutUrl;
280
+    }
281
+
282
+    /**
283
+     * Check if the user is an admin user
284
+     *
285
+     * @param string $uid uid of the admin
286
+     * @return bool
287
+     */
288
+    public static function isAdminUser($uid) {
289
+        $group = \OC::$server->getGroupManager()->get('admin');
290
+        $user = \OC::$server->getUserManager()->get($uid);
291
+        if ($group && $user && $group->inGroup($user) && self::$incognitoMode === false) {
292
+            return true;
293
+        }
294
+        return false;
295
+    }
296
+
297
+
298
+    /**
299
+     * get the user id of the user currently logged in.
300
+     *
301
+     * @return string|bool uid or false
302
+     */
303
+    public static function getUser() {
304
+        $uid = \OC::$server->getSession() ? \OC::$server->getSession()->get('user_id') : null;
305
+        if (!is_null($uid) && self::$incognitoMode === false) {
306
+            return $uid;
307
+        } else {
308
+            return false;
309
+        }
310
+    }
311
+
312
+    /**
313
+     * get the display name of the user currently logged in.
314
+     *
315
+     * @param string $uid
316
+     * @return string|bool uid or false
317
+     * @deprecated 8.1.0 fetch \OCP\IUser (has getDisplayName()) by using method
318
+     *                   get() of \OCP\IUserManager - \OC::$server->getUserManager()
319
+     */
320
+    public static function getDisplayName($uid = null) {
321
+        if ($uid) {
322
+            $user = \OC::$server->getUserManager()->get($uid);
323
+            if ($user) {
324
+                return $user->getDisplayName();
325
+            } else {
326
+                return $uid;
327
+            }
328
+        } else {
329
+            $user = \OC::$server->getUserSession()->getUser();
330
+            if ($user) {
331
+                return $user->getDisplayName();
332
+            } else {
333
+                return false;
334
+            }
335
+        }
336
+    }
337
+
338
+    /**
339
+     * Set password
340
+     *
341
+     * @param string $uid The username
342
+     * @param string $password The new password
343
+     * @param string $recoveryPassword for the encryption app to reset encryption keys
344
+     * @return bool
345
+     *
346
+     * Change the password of a user
347
+     */
348
+    public static function setPassword($uid, $password, $recoveryPassword = null) {
349
+        $user = \OC::$server->getUserManager()->get($uid);
350
+        if ($user) {
351
+            return $user->setPassword($password, $recoveryPassword);
352
+        } else {
353
+            return false;
354
+        }
355
+    }
356
+
357
+    /**
358
+     * @param string $uid The username
359
+     * @return string
360
+     *
361
+     * returns the path to the users home directory
362
+     * @deprecated Use \OC::$server->getUserManager->getHome()
363
+     */
364
+    public static function getHome($uid) {
365
+        $user = \OC::$server->getUserManager()->get($uid);
366
+        if ($user) {
367
+            return $user->getHome();
368
+        } else {
369
+            return \OC::$server->getSystemConfig()->getValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $uid;
370
+        }
371
+    }
372
+
373
+    /**
374
+     * Get a list of all users display name
375
+     *
376
+     * @param string $search
377
+     * @param int $limit
378
+     * @param int $offset
379
+     * @return array associative array with all display names (value) and corresponding uids (key)
380
+     *
381
+     * Get a list of all display names and user ids.
382
+     * @deprecated Use \OC::$server->getUserManager->searchDisplayName($search, $limit, $offset) instead.
383
+     */
384
+    public static function getDisplayNames($search = '', $limit = null, $offset = null) {
385
+        $displayNames = array();
386
+        $users = \OC::$server->getUserManager()->searchDisplayName($search, $limit, $offset);
387
+        foreach ($users as $user) {
388
+            $displayNames[$user->getUID()] = $user->getDisplayName();
389
+        }
390
+        return $displayNames;
391
+    }
392
+
393
+    /**
394
+     * Returns the first active backend from self::$_usedBackends.
395
+     *
396
+     * @return OCP\Authentication\IApacheBackend|null if no backend active, otherwise OCP\Authentication\IApacheBackend
397
+     */
398
+    private static function findFirstActiveUsedBackend() {
399
+        foreach (self::$_usedBackends as $backend) {
400
+            if ($backend instanceof OCP\Authentication\IApacheBackend) {
401
+                if ($backend->isSessionActive()) {
402
+                    return $backend;
403
+                }
404
+            }
405
+        }
406
+
407
+        return null;
408
+    }
409 409
 }
Please login to merge, or discard this patch.
Spacing   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -91,7 +91,7 @@  discard block
 block discarded – undo
91 91
 				case 'database':
92 92
 				case 'mysql':
93 93
 				case 'sqlite':
94
-					\OCP\Util::writeLog('core', 'Adding user backend ' . $backend . '.', ILogger::DEBUG);
94
+					\OCP\Util::writeLog('core', 'Adding user backend '.$backend.'.', ILogger::DEBUG);
95 95
 					self::$_usedBackends[$backend] = new \OC\User\Database();
96 96
 					\OC::$server->getUserManager()->registerBackend(self::$_usedBackends[$backend]);
97 97
 					break;
@@ -100,8 +100,8 @@  discard block
 block discarded – undo
100 100
 					\OC::$server->getUserManager()->registerBackend(self::$_usedBackends[$backend]);
101 101
 					break;
102 102
 				default:
103
-					\OCP\Util::writeLog('core', 'Adding default user backend ' . $backend . '.', ILogger::DEBUG);
104
-					$className = 'OC_USER_' . strtoupper($backend);
103
+					\OCP\Util::writeLog('core', 'Adding default user backend '.$backend.'.', ILogger::DEBUG);
104
+					$className = 'OC_USER_'.strtoupper($backend);
105 105
 					self::$_usedBackends[$backend] = new $className();
106 106
 					\OC::$server->getUserManager()->registerBackend(self::$_usedBackends[$backend]);
107 107
 					break;
@@ -145,10 +145,10 @@  discard block
 block discarded – undo
145 145
 					self::useBackend($backend);
146 146
 					self::$_setupedBackends[] = $i;
147 147
 				} else {
148
-					\OCP\Util::writeLog('core', 'User backend ' . $class . ' already initialized.', ILogger::DEBUG);
148
+					\OCP\Util::writeLog('core', 'User backend '.$class.' already initialized.', ILogger::DEBUG);
149 149
 				}
150 150
 			} else {
151
-				\OCP\Util::writeLog('core', 'User backend ' . $class . ' not found.', ILogger::ERROR);
151
+				\OCP\Util::writeLog('core', 'User backend '.$class.' not found.', ILogger::ERROR);
152 152
 			}
153 153
 		}
154 154
 	}
@@ -366,7 +366,7 @@  discard block
 block discarded – undo
366 366
 		if ($user) {
367 367
 			return $user->getHome();
368 368
 		} else {
369
-			return \OC::$server->getSystemConfig()->getValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $uid;
369
+			return \OC::$server->getSystemConfig()->getValue('datadirectory', OC::$SERVERROOT.'/data').'/'.$uid;
370 370
 		}
371 371
 	}
372 372
 
Please login to merge, or discard this patch.
lib/private/legacy/db.php 1 patch
Indentation   +193 added lines, -193 removed lines patch added patch discarded remove patch
@@ -36,209 +36,209 @@
 block discarded – undo
36 36
  */
37 37
 class OC_DB {
38 38
 
39
-	/**
40
-	 * get MDB2 schema manager
41
-	 *
42
-	 * @return \OC\DB\MDB2SchemaManager
43
-	 */
44
-	private static function getMDB2SchemaManager() {
45
-		return new \OC\DB\MDB2SchemaManager(\OC::$server->getDatabaseConnection());
46
-	}
39
+    /**
40
+     * get MDB2 schema manager
41
+     *
42
+     * @return \OC\DB\MDB2SchemaManager
43
+     */
44
+    private static function getMDB2SchemaManager() {
45
+        return new \OC\DB\MDB2SchemaManager(\OC::$server->getDatabaseConnection());
46
+    }
47 47
 
48
-	/**
49
-	 * Prepare a SQL query
50
-	 * @param string $query Query string
51
-	 * @param int|null $limit
52
-	 * @param int|null $offset
53
-	 * @param bool|null $isManipulation
54
-	 * @throws \OC\DatabaseException
55
-	 * @return OC_DB_StatementWrapper prepared SQL query
56
-	 *
57
-	 * SQL query via Doctrine prepare(), needs to be execute()'d!
58
-	 */
59
-	static public function prepare( $query , $limit = null, $offset = null, $isManipulation = null) {
60
-		$connection = \OC::$server->getDatabaseConnection();
48
+    /**
49
+     * Prepare a SQL query
50
+     * @param string $query Query string
51
+     * @param int|null $limit
52
+     * @param int|null $offset
53
+     * @param bool|null $isManipulation
54
+     * @throws \OC\DatabaseException
55
+     * @return OC_DB_StatementWrapper prepared SQL query
56
+     *
57
+     * SQL query via Doctrine prepare(), needs to be execute()'d!
58
+     */
59
+    static public function prepare( $query , $limit = null, $offset = null, $isManipulation = null) {
60
+        $connection = \OC::$server->getDatabaseConnection();
61 61
 
62
-		if ($isManipulation === null) {
63
-			//try to guess, so we return the number of rows on manipulations
64
-			$isManipulation = self::isManipulation($query);
65
-		}
62
+        if ($isManipulation === null) {
63
+            //try to guess, so we return the number of rows on manipulations
64
+            $isManipulation = self::isManipulation($query);
65
+        }
66 66
 
67
-		// return the result
68
-		try {
69
-			$result =$connection->prepare($query, $limit, $offset);
70
-		} catch (\Doctrine\DBAL\DBALException $e) {
71
-			throw new \OC\DatabaseException($e->getMessage());
72
-		}
73
-		// differentiate between query and manipulation
74
-		$result = new OC_DB_StatementWrapper($result, $isManipulation);
75
-		return $result;
76
-	}
67
+        // return the result
68
+        try {
69
+            $result =$connection->prepare($query, $limit, $offset);
70
+        } catch (\Doctrine\DBAL\DBALException $e) {
71
+            throw new \OC\DatabaseException($e->getMessage());
72
+        }
73
+        // differentiate between query and manipulation
74
+        $result = new OC_DB_StatementWrapper($result, $isManipulation);
75
+        return $result;
76
+    }
77 77
 
78
-	/**
79
-	 * tries to guess the type of statement based on the first 10 characters
80
-	 * the current check allows some whitespace but does not work with IF EXISTS or other more complex statements
81
-	 *
82
-	 * @param string $sql
83
-	 * @return bool
84
-	 */
85
-	static public function isManipulation( $sql ) {
86
-		$selectOccurrence = stripos($sql, 'SELECT');
87
-		if ($selectOccurrence !== false && $selectOccurrence < 10) {
88
-			return false;
89
-		}
90
-		$insertOccurrence = stripos($sql, 'INSERT');
91
-		if ($insertOccurrence !== false && $insertOccurrence < 10) {
92
-			return true;
93
-		}
94
-		$updateOccurrence = stripos($sql, 'UPDATE');
95
-		if ($updateOccurrence !== false && $updateOccurrence < 10) {
96
-			return true;
97
-		}
98
-		$deleteOccurrence = stripos($sql, 'DELETE');
99
-		if ($deleteOccurrence !== false && $deleteOccurrence < 10) {
100
-			return true;
101
-		}
102
-		return false;
103
-	}
78
+    /**
79
+     * tries to guess the type of statement based on the first 10 characters
80
+     * the current check allows some whitespace but does not work with IF EXISTS or other more complex statements
81
+     *
82
+     * @param string $sql
83
+     * @return bool
84
+     */
85
+    static public function isManipulation( $sql ) {
86
+        $selectOccurrence = stripos($sql, 'SELECT');
87
+        if ($selectOccurrence !== false && $selectOccurrence < 10) {
88
+            return false;
89
+        }
90
+        $insertOccurrence = stripos($sql, 'INSERT');
91
+        if ($insertOccurrence !== false && $insertOccurrence < 10) {
92
+            return true;
93
+        }
94
+        $updateOccurrence = stripos($sql, 'UPDATE');
95
+        if ($updateOccurrence !== false && $updateOccurrence < 10) {
96
+            return true;
97
+        }
98
+        $deleteOccurrence = stripos($sql, 'DELETE');
99
+        if ($deleteOccurrence !== false && $deleteOccurrence < 10) {
100
+            return true;
101
+        }
102
+        return false;
103
+    }
104 104
 
105
-	/**
106
-	 * execute a prepared statement, on error write log and throw exception
107
-	 * @param mixed $stmt OC_DB_StatementWrapper,
108
-	 *					  an array with 'sql' and optionally 'limit' and 'offset' keys
109
-	 *					.. or a simple sql query string
110
-	 * @param array $parameters
111
-	 * @return OC_DB_StatementWrapper
112
-	 * @throws \OC\DatabaseException
113
-	 */
114
-	static public function executeAudited( $stmt, array $parameters = []) {
115
-		if (is_string($stmt)) {
116
-			// convert to an array with 'sql'
117
-			if (stripos($stmt, 'LIMIT') !== false) { //OFFSET requires LIMIT, so we only need to check for LIMIT
118
-				// TODO try to convert LIMIT OFFSET notation to parameters
119
-				$message = 'LIMIT and OFFSET are forbidden for portability reasons,'
120
-						 . ' pass an array with \'limit\' and \'offset\' instead';
121
-				throw new \OC\DatabaseException($message);
122
-			}
123
-			$stmt = array('sql' => $stmt, 'limit' => null, 'offset' => null);
124
-		}
125
-		if (is_array($stmt)) {
126
-			// convert to prepared statement
127
-			if ( ! array_key_exists('sql', $stmt) ) {
128
-				$message = 'statement array must at least contain key \'sql\'';
129
-				throw new \OC\DatabaseException($message);
130
-			}
131
-			if ( ! array_key_exists('limit', $stmt) ) {
132
-				$stmt['limit'] = null;
133
-			}
134
-			if ( ! array_key_exists('limit', $stmt) ) {
135
-				$stmt['offset'] = null;
136
-			}
137
-			$stmt = self::prepare($stmt['sql'], $stmt['limit'], $stmt['offset']);
138
-		}
139
-		self::raiseExceptionOnError($stmt, 'Could not prepare statement');
140
-		if ($stmt instanceof OC_DB_StatementWrapper) {
141
-			$result = $stmt->execute($parameters);
142
-			self::raiseExceptionOnError($result, 'Could not execute statement');
143
-		} else {
144
-			if (is_object($stmt)) {
145
-				$message = 'Expected a prepared statement or array got ' . get_class($stmt);
146
-			} else {
147
-				$message = 'Expected a prepared statement or array got ' . gettype($stmt);
148
-			}
149
-			throw new \OC\DatabaseException($message);
150
-		}
151
-		return $result;
152
-	}
105
+    /**
106
+     * execute a prepared statement, on error write log and throw exception
107
+     * @param mixed $stmt OC_DB_StatementWrapper,
108
+     *					  an array with 'sql' and optionally 'limit' and 'offset' keys
109
+     *					.. or a simple sql query string
110
+     * @param array $parameters
111
+     * @return OC_DB_StatementWrapper
112
+     * @throws \OC\DatabaseException
113
+     */
114
+    static public function executeAudited( $stmt, array $parameters = []) {
115
+        if (is_string($stmt)) {
116
+            // convert to an array with 'sql'
117
+            if (stripos($stmt, 'LIMIT') !== false) { //OFFSET requires LIMIT, so we only need to check for LIMIT
118
+                // TODO try to convert LIMIT OFFSET notation to parameters
119
+                $message = 'LIMIT and OFFSET are forbidden for portability reasons,'
120
+                            . ' pass an array with \'limit\' and \'offset\' instead';
121
+                throw new \OC\DatabaseException($message);
122
+            }
123
+            $stmt = array('sql' => $stmt, 'limit' => null, 'offset' => null);
124
+        }
125
+        if (is_array($stmt)) {
126
+            // convert to prepared statement
127
+            if ( ! array_key_exists('sql', $stmt) ) {
128
+                $message = 'statement array must at least contain key \'sql\'';
129
+                throw new \OC\DatabaseException($message);
130
+            }
131
+            if ( ! array_key_exists('limit', $stmt) ) {
132
+                $stmt['limit'] = null;
133
+            }
134
+            if ( ! array_key_exists('limit', $stmt) ) {
135
+                $stmt['offset'] = null;
136
+            }
137
+            $stmt = self::prepare($stmt['sql'], $stmt['limit'], $stmt['offset']);
138
+        }
139
+        self::raiseExceptionOnError($stmt, 'Could not prepare statement');
140
+        if ($stmt instanceof OC_DB_StatementWrapper) {
141
+            $result = $stmt->execute($parameters);
142
+            self::raiseExceptionOnError($result, 'Could not execute statement');
143
+        } else {
144
+            if (is_object($stmt)) {
145
+                $message = 'Expected a prepared statement or array got ' . get_class($stmt);
146
+            } else {
147
+                $message = 'Expected a prepared statement or array got ' . gettype($stmt);
148
+            }
149
+            throw new \OC\DatabaseException($message);
150
+        }
151
+        return $result;
152
+    }
153 153
 
154
-	/**
155
-	 * saves database schema to xml file
156
-	 * @param string $file name of file
157
-	 * @return bool
158
-	 *
159
-	 * TODO: write more documentation
160
-	 */
161
-	public static function getDbStructure($file) {
162
-		$schemaManager = self::getMDB2SchemaManager();
163
-		return $schemaManager->getDbStructure($file);
164
-	}
154
+    /**
155
+     * saves database schema to xml file
156
+     * @param string $file name of file
157
+     * @return bool
158
+     *
159
+     * TODO: write more documentation
160
+     */
161
+    public static function getDbStructure($file) {
162
+        $schemaManager = self::getMDB2SchemaManager();
163
+        return $schemaManager->getDbStructure($file);
164
+    }
165 165
 
166
-	/**
167
-	 * Creates tables from XML file
168
-	 * @param string $file file to read structure from
169
-	 * @return bool
170
-	 *
171
-	 * TODO: write more documentation
172
-	 */
173
-	public static function createDbFromStructure( $file ) {
174
-		$schemaManager = self::getMDB2SchemaManager();
175
-		return $schemaManager->createDbFromStructure($file);
176
-	}
166
+    /**
167
+     * Creates tables from XML file
168
+     * @param string $file file to read structure from
169
+     * @return bool
170
+     *
171
+     * TODO: write more documentation
172
+     */
173
+    public static function createDbFromStructure( $file ) {
174
+        $schemaManager = self::getMDB2SchemaManager();
175
+        return $schemaManager->createDbFromStructure($file);
176
+    }
177 177
 
178
-	/**
179
-	 * update the database schema
180
-	 * @param string $file file to read structure from
181
-	 * @throws Exception
182
-	 * @return string|boolean
183
-	 * @suppress PhanDeprecatedFunction
184
-	 */
185
-	public static function updateDbFromStructure($file) {
186
-		$schemaManager = self::getMDB2SchemaManager();
187
-		try {
188
-			$result = $schemaManager->updateDbFromStructure($file);
189
-		} catch (Exception $e) {
190
-			\OCP\Util::writeLog('core', 'Failed to update database structure ('.$e.')', ILogger::FATAL);
191
-			throw $e;
192
-		}
193
-		return $result;
194
-	}
178
+    /**
179
+     * update the database schema
180
+     * @param string $file file to read structure from
181
+     * @throws Exception
182
+     * @return string|boolean
183
+     * @suppress PhanDeprecatedFunction
184
+     */
185
+    public static function updateDbFromStructure($file) {
186
+        $schemaManager = self::getMDB2SchemaManager();
187
+        try {
188
+            $result = $schemaManager->updateDbFromStructure($file);
189
+        } catch (Exception $e) {
190
+            \OCP\Util::writeLog('core', 'Failed to update database structure ('.$e.')', ILogger::FATAL);
191
+            throw $e;
192
+        }
193
+        return $result;
194
+    }
195 195
 
196
-	/**
197
-	 * remove all tables defined in a database structure xml file
198
-	 * @param string $file the xml file describing the tables
199
-	 */
200
-	public static function removeDBStructure($file) {
201
-		$schemaManager = self::getMDB2SchemaManager();
202
-		$schemaManager->removeDBStructure($file);
203
-	}
196
+    /**
197
+     * remove all tables defined in a database structure xml file
198
+     * @param string $file the xml file describing the tables
199
+     */
200
+    public static function removeDBStructure($file) {
201
+        $schemaManager = self::getMDB2SchemaManager();
202
+        $schemaManager->removeDBStructure($file);
203
+    }
204 204
 
205
-	/**
206
-	 * check if a result is an error and throws an exception, works with \Doctrine\DBAL\DBALException
207
-	 * @param mixed $result
208
-	 * @param string $message
209
-	 * @return void
210
-	 * @throws \OC\DatabaseException
211
-	 */
212
-	public static function raiseExceptionOnError($result, $message = null) {
213
-		if($result === false) {
214
-			if ($message === null) {
215
-				$message = self::getErrorMessage();
216
-			} else {
217
-				$message .= ', Root cause:' . self::getErrorMessage();
218
-			}
219
-			throw new \OC\DatabaseException($message);
220
-		}
221
-	}
205
+    /**
206
+     * check if a result is an error and throws an exception, works with \Doctrine\DBAL\DBALException
207
+     * @param mixed $result
208
+     * @param string $message
209
+     * @return void
210
+     * @throws \OC\DatabaseException
211
+     */
212
+    public static function raiseExceptionOnError($result, $message = null) {
213
+        if($result === false) {
214
+            if ($message === null) {
215
+                $message = self::getErrorMessage();
216
+            } else {
217
+                $message .= ', Root cause:' . self::getErrorMessage();
218
+            }
219
+            throw new \OC\DatabaseException($message);
220
+        }
221
+    }
222 222
 
223
-	/**
224
-	 * returns the error code and message as a string for logging
225
-	 * works with DoctrineException
226
-	 * @return string
227
-	 */
228
-	public static function getErrorMessage() {
229
-		$connection = \OC::$server->getDatabaseConnection();
230
-		return $connection->getError();
231
-	}
223
+    /**
224
+     * returns the error code and message as a string for logging
225
+     * works with DoctrineException
226
+     * @return string
227
+     */
228
+    public static function getErrorMessage() {
229
+        $connection = \OC::$server->getDatabaseConnection();
230
+        return $connection->getError();
231
+    }
232 232
 
233
-	/**
234
-	 * Checks if a table exists in the database - the database prefix will be prepended
235
-	 *
236
-	 * @param string $table
237
-	 * @return bool
238
-	 * @throws \OC\DatabaseException
239
-	 */
240
-	public static function tableExists($table) {
241
-		$connection = \OC::$server->getDatabaseConnection();
242
-		return $connection->tableExists($table);
243
-	}
233
+    /**
234
+     * Checks if a table exists in the database - the database prefix will be prepended
235
+     *
236
+     * @param string $table
237
+     * @return bool
238
+     * @throws \OC\DatabaseException
239
+     */
240
+    public static function tableExists($table) {
241
+        $connection = \OC::$server->getDatabaseConnection();
242
+        return $connection->tableExists($table);
243
+    }
244 244
 }
Please login to merge, or discard this patch.
lib/private/legacy/files.php 2 patches
Indentation   +430 added lines, -430 removed lines patch added patch discarded remove patch
@@ -49,438 +49,438 @@
 block discarded – undo
49 49
  *
50 50
  */
51 51
 class OC_Files {
52
-	const FILE = 1;
53
-	const ZIP_FILES = 2;
54
-	const ZIP_DIR = 3;
55
-
56
-	const UPLOAD_MIN_LIMIT_BYTES = 1048576; // 1 MiB
57
-
58
-
59
-	private static $multipartBoundary = '';
60
-
61
-	/**
62
-	 * @return string
63
-	 */
64
-	private static function getBoundary() {
65
-		if (empty(self::$multipartBoundary)) {
66
-			self::$multipartBoundary = md5(mt_rand());
67
-		}
68
-		return self::$multipartBoundary;
69
-	}
70
-
71
-	/**
72
-	 * @param string $filename
73
-	 * @param string $name
74
-	 * @param array $rangeArray ('from'=>int,'to'=>int), ...
75
-	 */
76
-	private static function sendHeaders($filename, $name, array $rangeArray) {
77
-		OC_Response::setContentDispositionHeader($name, 'attachment');
78
-		header('Content-Transfer-Encoding: binary', true);
79
-		header('Pragma: public');// enable caching in IE
80
-		header('Expires: 0');
81
-		header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
82
-		$fileSize = \OC\Files\Filesystem::filesize($filename);
83
-		$type = \OC::$server->getMimeTypeDetector()->getSecureMimeType(\OC\Files\Filesystem::getMimeType($filename));
84
-		if ($fileSize > -1) {
85
-			if (!empty($rangeArray)) {
86
-			    header('HTTP/1.1 206 Partial Content', true);
87
-			    header('Accept-Ranges: bytes', true);
88
-			    if (count($rangeArray) > 1) {
89
-				$type = 'multipart/byteranges; boundary='.self::getBoundary();
90
-				// no Content-Length header here
91
-			    }
92
-			    else {
93
-				header(sprintf('Content-Range: bytes %d-%d/%d', $rangeArray[0]['from'], $rangeArray[0]['to'], $fileSize), true);
94
-				OC_Response::setContentLengthHeader($rangeArray[0]['to'] - $rangeArray[0]['from'] + 1);
95
-			    }
96
-			}
97
-			else {
98
-			    OC_Response::setContentLengthHeader($fileSize);
99
-			}
100
-		}
101
-		header('Content-Type: '.$type, true);
102
-	}
103
-
104
-	/**
105
-	 * return the content of a file or return a zip file containing multiple files
106
-	 *
107
-	 * @param string $dir
108
-	 * @param string $files ; separated list of files to download
109
-	 * @param array $params ; 'head' boolean to only send header of the request ; 'range' http range header
110
-	 */
111
-	public static function get($dir, $files, $params = null) {
112
-
113
-		$view = \OC\Files\Filesystem::getView();
114
-		$getType = self::FILE;
115
-		$filename = $dir;
116
-		try {
117
-
118
-			if (is_array($files) && count($files) === 1) {
119
-				$files = $files[0];
120
-			}
121
-
122
-			if (!is_array($files)) {
123
-				$filename = $dir . '/' . $files;
124
-				if (!$view->is_dir($filename)) {
125
-					self::getSingleFile($view, $dir, $files, is_null($params) ? array() : $params);
126
-					return;
127
-				}
128
-			}
129
-
130
-			$name = 'download';
131
-			if (is_array($files)) {
132
-				$getType = self::ZIP_FILES;
133
-				$basename = basename($dir);
134
-				if ($basename) {
135
-					$name = $basename;
136
-				}
137
-
138
-				$filename = $dir . '/' . $name;
139
-			} else {
140
-				$filename = $dir . '/' . $files;
141
-				$getType = self::ZIP_DIR;
142
-				// downloading root ?
143
-				if ($files !== '') {
144
-					$name = $files;
145
-				}
146
-			}
147
-
148
-			self::lockFiles($view, $dir, $files);
149
-
150
-			/* Calculate filesize and number of files */
151
-			if ($getType === self::ZIP_FILES) {
152
-				$fileInfos = array();
153
-				$fileSize = 0;
154
-				foreach ($files as $file) {
155
-					$fileInfo = \OC\Files\Filesystem::getFileInfo($dir . '/' . $file);
156
-					$fileSize += $fileInfo->getSize();
157
-					$fileInfos[] = $fileInfo;
158
-				}
159
-				$numberOfFiles = self::getNumberOfFiles($fileInfos);
160
-			} elseif ($getType === self::ZIP_DIR) {
161
-				$fileInfo = \OC\Files\Filesystem::getFileInfo($dir . '/' . $files);
162
-				$fileSize = $fileInfo->getSize();
163
-				$numberOfFiles = self::getNumberOfFiles(array($fileInfo));
164
-			}
165
-
166
-			$streamer = new Streamer(\OC::$server->getRequest(), $fileSize, $numberOfFiles);
167
-			OC_Util::obEnd();
168
-
169
-			$streamer->sendHeaders($name);
170
-			$executionTime = (int)OC::$server->getIniWrapper()->getNumeric('max_execution_time');
171
-			if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
172
-				@set_time_limit(0);
173
-			}
174
-			ignore_user_abort(true);
175
-
176
-			if ($getType === self::ZIP_FILES) {
177
-				foreach ($files as $file) {
178
-					$file = $dir . '/' . $file;
179
-					if (\OC\Files\Filesystem::is_file($file)) {
180
-						$fileSize = \OC\Files\Filesystem::filesize($file);
181
-						$fileTime = \OC\Files\Filesystem::filemtime($file);
182
-						$fh = \OC\Files\Filesystem::fopen($file, 'r');
183
-						$streamer->addFileFromStream($fh, basename($file), $fileSize, $fileTime);
184
-						fclose($fh);
185
-					} elseif (\OC\Files\Filesystem::is_dir($file)) {
186
-						$streamer->addDirRecursive($file);
187
-					}
188
-				}
189
-			} elseif ($getType === self::ZIP_DIR) {
190
-				$file = $dir . '/' . $files;
191
-				$streamer->addDirRecursive($file);
192
-			}
193
-			$streamer->finalize();
194
-			set_time_limit($executionTime);
195
-			self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
196
-		} catch (\OCP\Lock\LockedException $ex) {
197
-			self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
198
-			OC::$server->getLogger()->logException($ex);
199
-			$l = \OC::$server->getL10N('core');
200
-			$hint = method_exists($ex, 'getHint') ? $ex->getHint() : '';
201
-			\OC_Template::printErrorPage($l->t('File is currently busy, please try again later'), $hint);
202
-		} catch (\OCP\Files\ForbiddenException $ex) {
203
-			self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
204
-			OC::$server->getLogger()->logException($ex);
205
-			$l = \OC::$server->getL10N('core');
206
-			\OC_Template::printErrorPage($l->t('Can\'t read file'), $ex->getMessage());
207
-		} catch (\Exception $ex) {
208
-			self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
209
-			OC::$server->getLogger()->logException($ex);
210
-			$l = \OC::$server->getL10N('core');
211
-			$hint = method_exists($ex, 'getHint') ? $ex->getHint() : '';
212
-			\OC_Template::printErrorPage($l->t('Can\'t read file'), $hint);
213
-		}
214
-	}
215
-
216
-	/**
217
-	 * @param string $rangeHeaderPos
218
-	 * @param int $fileSize
219
-	 * @return array $rangeArray ('from'=>int,'to'=>int), ...
220
-	 */
221
-	private static function parseHttpRangeHeader($rangeHeaderPos, $fileSize) {
222
-		$rArray=explode(',', $rangeHeaderPos);
223
-		$minOffset = 0;
224
-		$ind = 0;
225
-
226
-		$rangeArray = array();
227
-
228
-		foreach ($rArray as $value) {
229
-			$ranges = explode('-', $value);
230
-			if (is_numeric($ranges[0])) {
231
-				if ($ranges[0] < $minOffset) { // case: bytes=500-700,601-999
232
-					$ranges[0] = $minOffset;
233
-				}
234
-				if ($ind > 0 && $rangeArray[$ind-1]['to']+1 == $ranges[0]) { // case: bytes=500-600,601-999
235
-					$ind--;
236
-					$ranges[0] = $rangeArray[$ind]['from'];
237
-				}
238
-			}
239
-
240
-			if (is_numeric($ranges[0]) && is_numeric($ranges[1]) && $ranges[0] < $fileSize && $ranges[0] <= $ranges[1]) {
241
-				// case: x-x
242
-				if ($ranges[1] >= $fileSize) {
243
-					$ranges[1] = $fileSize-1;
244
-				}
245
-				$rangeArray[$ind++] = array( 'from' => $ranges[0], 'to' => $ranges[1], 'size' => $fileSize );
246
-				$minOffset = $ranges[1] + 1;
247
-				if ($minOffset >= $fileSize) {
248
-					break;
249
-				}
250
-			}
251
-			elseif (is_numeric($ranges[0]) && $ranges[0] < $fileSize) {
252
-				// case: x-
253
-				$rangeArray[$ind++] = array( 'from' => $ranges[0], 'to' => $fileSize-1, 'size' => $fileSize );
254
-				break;
255
-			}
256
-			elseif (is_numeric($ranges[1])) {
257
-				// case: -x
258
-				if ($ranges[1] > $fileSize) {
259
-					$ranges[1] = $fileSize;
260
-				}
261
-				$rangeArray[$ind++] = array( 'from' => $fileSize-$ranges[1], 'to' => $fileSize-1, 'size' => $fileSize );
262
-				break;
263
-			}
264
-		}
265
-		return $rangeArray;
266
-	}
267
-
268
-	/**
269
-	 * @param View $view
270
-	 * @param string $name
271
-	 * @param string $dir
272
-	 * @param array $params ; 'head' boolean to only send header of the request ; 'range' http range header
273
-	 */
274
-	private static function getSingleFile($view, $dir, $name, $params) {
275
-		$filename = $dir . '/' . $name;
276
-		OC_Util::obEnd();
277
-		$view->lockFile($filename, ILockingProvider::LOCK_SHARED);
52
+    const FILE = 1;
53
+    const ZIP_FILES = 2;
54
+    const ZIP_DIR = 3;
55
+
56
+    const UPLOAD_MIN_LIMIT_BYTES = 1048576; // 1 MiB
57
+
58
+
59
+    private static $multipartBoundary = '';
60
+
61
+    /**
62
+     * @return string
63
+     */
64
+    private static function getBoundary() {
65
+        if (empty(self::$multipartBoundary)) {
66
+            self::$multipartBoundary = md5(mt_rand());
67
+        }
68
+        return self::$multipartBoundary;
69
+    }
70
+
71
+    /**
72
+     * @param string $filename
73
+     * @param string $name
74
+     * @param array $rangeArray ('from'=>int,'to'=>int), ...
75
+     */
76
+    private static function sendHeaders($filename, $name, array $rangeArray) {
77
+        OC_Response::setContentDispositionHeader($name, 'attachment');
78
+        header('Content-Transfer-Encoding: binary', true);
79
+        header('Pragma: public');// enable caching in IE
80
+        header('Expires: 0');
81
+        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
82
+        $fileSize = \OC\Files\Filesystem::filesize($filename);
83
+        $type = \OC::$server->getMimeTypeDetector()->getSecureMimeType(\OC\Files\Filesystem::getMimeType($filename));
84
+        if ($fileSize > -1) {
85
+            if (!empty($rangeArray)) {
86
+                header('HTTP/1.1 206 Partial Content', true);
87
+                header('Accept-Ranges: bytes', true);
88
+                if (count($rangeArray) > 1) {
89
+                $type = 'multipart/byteranges; boundary='.self::getBoundary();
90
+                // no Content-Length header here
91
+                }
92
+                else {
93
+                header(sprintf('Content-Range: bytes %d-%d/%d', $rangeArray[0]['from'], $rangeArray[0]['to'], $fileSize), true);
94
+                OC_Response::setContentLengthHeader($rangeArray[0]['to'] - $rangeArray[0]['from'] + 1);
95
+                }
96
+            }
97
+            else {
98
+                OC_Response::setContentLengthHeader($fileSize);
99
+            }
100
+        }
101
+        header('Content-Type: '.$type, true);
102
+    }
103
+
104
+    /**
105
+     * return the content of a file or return a zip file containing multiple files
106
+     *
107
+     * @param string $dir
108
+     * @param string $files ; separated list of files to download
109
+     * @param array $params ; 'head' boolean to only send header of the request ; 'range' http range header
110
+     */
111
+    public static function get($dir, $files, $params = null) {
112
+
113
+        $view = \OC\Files\Filesystem::getView();
114
+        $getType = self::FILE;
115
+        $filename = $dir;
116
+        try {
117
+
118
+            if (is_array($files) && count($files) === 1) {
119
+                $files = $files[0];
120
+            }
121
+
122
+            if (!is_array($files)) {
123
+                $filename = $dir . '/' . $files;
124
+                if (!$view->is_dir($filename)) {
125
+                    self::getSingleFile($view, $dir, $files, is_null($params) ? array() : $params);
126
+                    return;
127
+                }
128
+            }
129
+
130
+            $name = 'download';
131
+            if (is_array($files)) {
132
+                $getType = self::ZIP_FILES;
133
+                $basename = basename($dir);
134
+                if ($basename) {
135
+                    $name = $basename;
136
+                }
137
+
138
+                $filename = $dir . '/' . $name;
139
+            } else {
140
+                $filename = $dir . '/' . $files;
141
+                $getType = self::ZIP_DIR;
142
+                // downloading root ?
143
+                if ($files !== '') {
144
+                    $name = $files;
145
+                }
146
+            }
147
+
148
+            self::lockFiles($view, $dir, $files);
149
+
150
+            /* Calculate filesize and number of files */
151
+            if ($getType === self::ZIP_FILES) {
152
+                $fileInfos = array();
153
+                $fileSize = 0;
154
+                foreach ($files as $file) {
155
+                    $fileInfo = \OC\Files\Filesystem::getFileInfo($dir . '/' . $file);
156
+                    $fileSize += $fileInfo->getSize();
157
+                    $fileInfos[] = $fileInfo;
158
+                }
159
+                $numberOfFiles = self::getNumberOfFiles($fileInfos);
160
+            } elseif ($getType === self::ZIP_DIR) {
161
+                $fileInfo = \OC\Files\Filesystem::getFileInfo($dir . '/' . $files);
162
+                $fileSize = $fileInfo->getSize();
163
+                $numberOfFiles = self::getNumberOfFiles(array($fileInfo));
164
+            }
165
+
166
+            $streamer = new Streamer(\OC::$server->getRequest(), $fileSize, $numberOfFiles);
167
+            OC_Util::obEnd();
168
+
169
+            $streamer->sendHeaders($name);
170
+            $executionTime = (int)OC::$server->getIniWrapper()->getNumeric('max_execution_time');
171
+            if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
172
+                @set_time_limit(0);
173
+            }
174
+            ignore_user_abort(true);
175
+
176
+            if ($getType === self::ZIP_FILES) {
177
+                foreach ($files as $file) {
178
+                    $file = $dir . '/' . $file;
179
+                    if (\OC\Files\Filesystem::is_file($file)) {
180
+                        $fileSize = \OC\Files\Filesystem::filesize($file);
181
+                        $fileTime = \OC\Files\Filesystem::filemtime($file);
182
+                        $fh = \OC\Files\Filesystem::fopen($file, 'r');
183
+                        $streamer->addFileFromStream($fh, basename($file), $fileSize, $fileTime);
184
+                        fclose($fh);
185
+                    } elseif (\OC\Files\Filesystem::is_dir($file)) {
186
+                        $streamer->addDirRecursive($file);
187
+                    }
188
+                }
189
+            } elseif ($getType === self::ZIP_DIR) {
190
+                $file = $dir . '/' . $files;
191
+                $streamer->addDirRecursive($file);
192
+            }
193
+            $streamer->finalize();
194
+            set_time_limit($executionTime);
195
+            self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
196
+        } catch (\OCP\Lock\LockedException $ex) {
197
+            self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
198
+            OC::$server->getLogger()->logException($ex);
199
+            $l = \OC::$server->getL10N('core');
200
+            $hint = method_exists($ex, 'getHint') ? $ex->getHint() : '';
201
+            \OC_Template::printErrorPage($l->t('File is currently busy, please try again later'), $hint);
202
+        } catch (\OCP\Files\ForbiddenException $ex) {
203
+            self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
204
+            OC::$server->getLogger()->logException($ex);
205
+            $l = \OC::$server->getL10N('core');
206
+            \OC_Template::printErrorPage($l->t('Can\'t read file'), $ex->getMessage());
207
+        } catch (\Exception $ex) {
208
+            self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
209
+            OC::$server->getLogger()->logException($ex);
210
+            $l = \OC::$server->getL10N('core');
211
+            $hint = method_exists($ex, 'getHint') ? $ex->getHint() : '';
212
+            \OC_Template::printErrorPage($l->t('Can\'t read file'), $hint);
213
+        }
214
+    }
215
+
216
+    /**
217
+     * @param string $rangeHeaderPos
218
+     * @param int $fileSize
219
+     * @return array $rangeArray ('from'=>int,'to'=>int), ...
220
+     */
221
+    private static function parseHttpRangeHeader($rangeHeaderPos, $fileSize) {
222
+        $rArray=explode(',', $rangeHeaderPos);
223
+        $minOffset = 0;
224
+        $ind = 0;
225
+
226
+        $rangeArray = array();
227
+
228
+        foreach ($rArray as $value) {
229
+            $ranges = explode('-', $value);
230
+            if (is_numeric($ranges[0])) {
231
+                if ($ranges[0] < $minOffset) { // case: bytes=500-700,601-999
232
+                    $ranges[0] = $minOffset;
233
+                }
234
+                if ($ind > 0 && $rangeArray[$ind-1]['to']+1 == $ranges[0]) { // case: bytes=500-600,601-999
235
+                    $ind--;
236
+                    $ranges[0] = $rangeArray[$ind]['from'];
237
+                }
238
+            }
239
+
240
+            if (is_numeric($ranges[0]) && is_numeric($ranges[1]) && $ranges[0] < $fileSize && $ranges[0] <= $ranges[1]) {
241
+                // case: x-x
242
+                if ($ranges[1] >= $fileSize) {
243
+                    $ranges[1] = $fileSize-1;
244
+                }
245
+                $rangeArray[$ind++] = array( 'from' => $ranges[0], 'to' => $ranges[1], 'size' => $fileSize );
246
+                $minOffset = $ranges[1] + 1;
247
+                if ($minOffset >= $fileSize) {
248
+                    break;
249
+                }
250
+            }
251
+            elseif (is_numeric($ranges[0]) && $ranges[0] < $fileSize) {
252
+                // case: x-
253
+                $rangeArray[$ind++] = array( 'from' => $ranges[0], 'to' => $fileSize-1, 'size' => $fileSize );
254
+                break;
255
+            }
256
+            elseif (is_numeric($ranges[1])) {
257
+                // case: -x
258
+                if ($ranges[1] > $fileSize) {
259
+                    $ranges[1] = $fileSize;
260
+                }
261
+                $rangeArray[$ind++] = array( 'from' => $fileSize-$ranges[1], 'to' => $fileSize-1, 'size' => $fileSize );
262
+                break;
263
+            }
264
+        }
265
+        return $rangeArray;
266
+    }
267
+
268
+    /**
269
+     * @param View $view
270
+     * @param string $name
271
+     * @param string $dir
272
+     * @param array $params ; 'head' boolean to only send header of the request ; 'range' http range header
273
+     */
274
+    private static function getSingleFile($view, $dir, $name, $params) {
275
+        $filename = $dir . '/' . $name;
276
+        OC_Util::obEnd();
277
+        $view->lockFile($filename, ILockingProvider::LOCK_SHARED);
278 278
 		
279
-		$rangeArray = array();
279
+        $rangeArray = array();
280 280
 
281
-		if (isset($params['range']) && substr($params['range'], 0, 6) === 'bytes=') {
282
-			$rangeArray = self::parseHttpRangeHeader(substr($params['range'], 6), 
283
-								 \OC\Files\Filesystem::filesize($filename));
284
-		}
281
+        if (isset($params['range']) && substr($params['range'], 0, 6) === 'bytes=') {
282
+            $rangeArray = self::parseHttpRangeHeader(substr($params['range'], 6), 
283
+                                    \OC\Files\Filesystem::filesize($filename));
284
+        }
285 285
 		
286
-		if (\OC\Files\Filesystem::isReadable($filename)) {
287
-			self::sendHeaders($filename, $name, $rangeArray);
288
-		} elseif (!\OC\Files\Filesystem::file_exists($filename)) {
289
-			header("HTTP/1.1 404 Not Found");
290
-			$tmpl = new OC_Template('', '404', 'guest');
291
-			$tmpl->printPage();
292
-			exit();
293
-		} else {
294
-			header("HTTP/1.1 403 Forbidden");
295
-			die('403 Forbidden');
296
-		}
297
-		if (isset($params['head']) && $params['head']) {
298
-			return;
299
-		}
300
-		if (!empty($rangeArray)) {
301
-			try {
302
-			    if (count($rangeArray) == 1) {
303
-				$view->readfilePart($filename, $rangeArray[0]['from'], $rangeArray[0]['to']);
304
-			    }
305
-			    else {
306
-				// check if file is seekable (if not throw UnseekableException)
307
-				// we have to check it before body contents
308
-				$view->readfilePart($filename, $rangeArray[0]['size'], $rangeArray[0]['size']);
309
-
310
-				$type = \OC::$server->getMimeTypeDetector()->getSecureMimeType(\OC\Files\Filesystem::getMimeType($filename));
311
-
312
-				foreach ($rangeArray as $range) {
313
-				    echo "\r\n--".self::getBoundary()."\r\n".
314
-				         "Content-type: ".$type."\r\n".
315
-				         "Content-range: bytes ".$range['from']."-".$range['to']."/".$range['size']."\r\n\r\n";
316
-				    $view->readfilePart($filename, $range['from'], $range['to']);
317
-				}
318
-				echo "\r\n--".self::getBoundary()."--\r\n";
319
-			    }
320
-			} catch (\OCP\Files\UnseekableException $ex) {
321
-			    // file is unseekable
322
-			    header_remove('Accept-Ranges');
323
-			    header_remove('Content-Range');
324
-			    header("HTTP/1.1 200 OK");
325
-			    self::sendHeaders($filename, $name, array());
326
-			    $view->readfile($filename);
327
-			}
328
-		}
329
-		else {
330
-		    $view->readfile($filename);
331
-		}
332
-	}
333
-
334
-	/**
335
-	 * Returns the total (recursive) number of files and folders in the given
336
-	 * FileInfos.
337
-	 *
338
-	 * @param \OCP\Files\FileInfo[] $fileInfos the FileInfos to count
339
-	 * @return int the total number of files and folders
340
-	 */
341
-	private static function getNumberOfFiles($fileInfos) {
342
-		$numberOfFiles = 0;
343
-
344
-		$view = new View();
345
-
346
-		while ($fileInfo = array_pop($fileInfos)) {
347
-			$numberOfFiles++;
348
-
349
-			if ($fileInfo->getType() === \OCP\Files\FileInfo::TYPE_FOLDER) {
350
-				$fileInfos = array_merge($fileInfos, $view->getDirectoryContent($fileInfo->getPath()));
351
-			}
352
-		}
353
-
354
-		return $numberOfFiles;
355
-	}
356
-
357
-	/**
358
-	 * @param View $view
359
-	 * @param string $dir
360
-	 * @param string[]|string $files
361
-	 */
362
-	public static function lockFiles($view, $dir, $files) {
363
-		if (!is_array($files)) {
364
-			$file = $dir . '/' . $files;
365
-			$files = [$file];
366
-		}
367
-		foreach ($files as $file) {
368
-			$file = $dir . '/' . $file;
369
-			$view->lockFile($file, ILockingProvider::LOCK_SHARED);
370
-			if ($view->is_dir($file)) {
371
-				$contents = $view->getDirectoryContent($file);
372
-				$contents = array_map(function($fileInfo) use ($file) {
373
-					/** @var \OCP\Files\FileInfo $fileInfo */
374
-					return $file . '/' . $fileInfo->getName();
375
-				}, $contents);
376
-				self::lockFiles($view, $dir, $contents);
377
-			}
378
-		}
379
-	}
380
-
381
-	/**
382
-	 * set the maximum upload size limit for apache hosts using .htaccess
383
-	 *
384
-	 * @param int $size file size in bytes
385
-	 * @param array $files override '.htaccess' and '.user.ini' locations
386
-	 * @return bool|int false on failure, size on success
387
-	 */
388
-	public static function setUploadLimit($size, $files = []) {
389
-		//don't allow user to break his config
390
-		$size = (int)$size;
391
-		if ($size < self::UPLOAD_MIN_LIMIT_BYTES) {
392
-			return false;
393
-		}
394
-		$size = OC_Helper::phpFileSize($size);
395
-
396
-		$phpValueKeys = array(
397
-			'upload_max_filesize',
398
-			'post_max_size'
399
-		);
400
-
401
-		// default locations if not overridden by $files
402
-		$files = array_merge([
403
-			'.htaccess' => OC::$SERVERROOT . '/.htaccess',
404
-			'.user.ini' => OC::$SERVERROOT . '/.user.ini'
405
-		], $files);
406
-
407
-		$updateFiles = [
408
-			$files['.htaccess'] => [
409
-				'pattern' => '/php_value %1$s (\S)*/',
410
-				'setting' => 'php_value %1$s %2$s'
411
-			],
412
-			$files['.user.ini'] => [
413
-				'pattern' => '/%1$s=(\S)*/',
414
-				'setting' => '%1$s=%2$s'
415
-			]
416
-		];
417
-
418
-		$success = true;
419
-
420
-		foreach ($updateFiles as $filename => $patternMap) {
421
-			// suppress warnings from fopen()
422
-			$handle = @fopen($filename, 'r+');
423
-			if (!$handle) {
424
-				\OCP\Util::writeLog('files',
425
-					'Can\'t write upload limit to ' . $filename . '. Please check the file permissions',
426
-					ILogger::WARN);
427
-				$success = false;
428
-				continue; // try to update as many files as possible
429
-			}
430
-
431
-			$content = '';
432
-			while (!feof($handle)) {
433
-				$content .= fread($handle, 1000);
434
-			}
435
-
436
-			foreach ($phpValueKeys as $key) {
437
-				$pattern = vsprintf($patternMap['pattern'], [$key]);
438
-				$setting = vsprintf($patternMap['setting'], [$key, $size]);
439
-				$hasReplaced = 0;
440
-				$newContent = preg_replace($pattern, $setting, $content, 2, $hasReplaced);
441
-				if ($newContent !== null) {
442
-					$content = $newContent;
443
-				}
444
-				if ($hasReplaced === 0) {
445
-					$content .= "\n" . $setting;
446
-				}
447
-			}
448
-
449
-			// write file back
450
-			ftruncate($handle, 0);
451
-			rewind($handle);
452
-			fwrite($handle, $content);
453
-
454
-			fclose($handle);
455
-		}
456
-
457
-		if ($success) {
458
-			return OC_Helper::computerFileSize($size);
459
-		}
460
-		return false;
461
-	}
462
-
463
-	/**
464
-	 * @param string $dir
465
-	 * @param $files
466
-	 * @param integer $getType
467
-	 * @param View $view
468
-	 * @param string $filename
469
-	 */
470
-	private static function unlockAllTheFiles($dir, $files, $getType, $view, $filename) {
471
-		if ($getType === self::FILE) {
472
-			$view->unlockFile($filename, ILockingProvider::LOCK_SHARED);
473
-		}
474
-		if ($getType === self::ZIP_FILES) {
475
-			foreach ($files as $file) {
476
-				$file = $dir . '/' . $file;
477
-				$view->unlockFile($file, ILockingProvider::LOCK_SHARED);
478
-			}
479
-		}
480
-		if ($getType === self::ZIP_DIR) {
481
-			$file = $dir . '/' . $files;
482
-			$view->unlockFile($file, ILockingProvider::LOCK_SHARED);
483
-		}
484
-	}
286
+        if (\OC\Files\Filesystem::isReadable($filename)) {
287
+            self::sendHeaders($filename, $name, $rangeArray);
288
+        } elseif (!\OC\Files\Filesystem::file_exists($filename)) {
289
+            header("HTTP/1.1 404 Not Found");
290
+            $tmpl = new OC_Template('', '404', 'guest');
291
+            $tmpl->printPage();
292
+            exit();
293
+        } else {
294
+            header("HTTP/1.1 403 Forbidden");
295
+            die('403 Forbidden');
296
+        }
297
+        if (isset($params['head']) && $params['head']) {
298
+            return;
299
+        }
300
+        if (!empty($rangeArray)) {
301
+            try {
302
+                if (count($rangeArray) == 1) {
303
+                $view->readfilePart($filename, $rangeArray[0]['from'], $rangeArray[0]['to']);
304
+                }
305
+                else {
306
+                // check if file is seekable (if not throw UnseekableException)
307
+                // we have to check it before body contents
308
+                $view->readfilePart($filename, $rangeArray[0]['size'], $rangeArray[0]['size']);
309
+
310
+                $type = \OC::$server->getMimeTypeDetector()->getSecureMimeType(\OC\Files\Filesystem::getMimeType($filename));
311
+
312
+                foreach ($rangeArray as $range) {
313
+                    echo "\r\n--".self::getBoundary()."\r\n".
314
+                            "Content-type: ".$type."\r\n".
315
+                            "Content-range: bytes ".$range['from']."-".$range['to']."/".$range['size']."\r\n\r\n";
316
+                    $view->readfilePart($filename, $range['from'], $range['to']);
317
+                }
318
+                echo "\r\n--".self::getBoundary()."--\r\n";
319
+                }
320
+            } catch (\OCP\Files\UnseekableException $ex) {
321
+                // file is unseekable
322
+                header_remove('Accept-Ranges');
323
+                header_remove('Content-Range');
324
+                header("HTTP/1.1 200 OK");
325
+                self::sendHeaders($filename, $name, array());
326
+                $view->readfile($filename);
327
+            }
328
+        }
329
+        else {
330
+            $view->readfile($filename);
331
+        }
332
+    }
333
+
334
+    /**
335
+     * Returns the total (recursive) number of files and folders in the given
336
+     * FileInfos.
337
+     *
338
+     * @param \OCP\Files\FileInfo[] $fileInfos the FileInfos to count
339
+     * @return int the total number of files and folders
340
+     */
341
+    private static function getNumberOfFiles($fileInfos) {
342
+        $numberOfFiles = 0;
343
+
344
+        $view = new View();
345
+
346
+        while ($fileInfo = array_pop($fileInfos)) {
347
+            $numberOfFiles++;
348
+
349
+            if ($fileInfo->getType() === \OCP\Files\FileInfo::TYPE_FOLDER) {
350
+                $fileInfos = array_merge($fileInfos, $view->getDirectoryContent($fileInfo->getPath()));
351
+            }
352
+        }
353
+
354
+        return $numberOfFiles;
355
+    }
356
+
357
+    /**
358
+     * @param View $view
359
+     * @param string $dir
360
+     * @param string[]|string $files
361
+     */
362
+    public static function lockFiles($view, $dir, $files) {
363
+        if (!is_array($files)) {
364
+            $file = $dir . '/' . $files;
365
+            $files = [$file];
366
+        }
367
+        foreach ($files as $file) {
368
+            $file = $dir . '/' . $file;
369
+            $view->lockFile($file, ILockingProvider::LOCK_SHARED);
370
+            if ($view->is_dir($file)) {
371
+                $contents = $view->getDirectoryContent($file);
372
+                $contents = array_map(function($fileInfo) use ($file) {
373
+                    /** @var \OCP\Files\FileInfo $fileInfo */
374
+                    return $file . '/' . $fileInfo->getName();
375
+                }, $contents);
376
+                self::lockFiles($view, $dir, $contents);
377
+            }
378
+        }
379
+    }
380
+
381
+    /**
382
+     * set the maximum upload size limit for apache hosts using .htaccess
383
+     *
384
+     * @param int $size file size in bytes
385
+     * @param array $files override '.htaccess' and '.user.ini' locations
386
+     * @return bool|int false on failure, size on success
387
+     */
388
+    public static function setUploadLimit($size, $files = []) {
389
+        //don't allow user to break his config
390
+        $size = (int)$size;
391
+        if ($size < self::UPLOAD_MIN_LIMIT_BYTES) {
392
+            return false;
393
+        }
394
+        $size = OC_Helper::phpFileSize($size);
395
+
396
+        $phpValueKeys = array(
397
+            'upload_max_filesize',
398
+            'post_max_size'
399
+        );
400
+
401
+        // default locations if not overridden by $files
402
+        $files = array_merge([
403
+            '.htaccess' => OC::$SERVERROOT . '/.htaccess',
404
+            '.user.ini' => OC::$SERVERROOT . '/.user.ini'
405
+        ], $files);
406
+
407
+        $updateFiles = [
408
+            $files['.htaccess'] => [
409
+                'pattern' => '/php_value %1$s (\S)*/',
410
+                'setting' => 'php_value %1$s %2$s'
411
+            ],
412
+            $files['.user.ini'] => [
413
+                'pattern' => '/%1$s=(\S)*/',
414
+                'setting' => '%1$s=%2$s'
415
+            ]
416
+        ];
417
+
418
+        $success = true;
419
+
420
+        foreach ($updateFiles as $filename => $patternMap) {
421
+            // suppress warnings from fopen()
422
+            $handle = @fopen($filename, 'r+');
423
+            if (!$handle) {
424
+                \OCP\Util::writeLog('files',
425
+                    'Can\'t write upload limit to ' . $filename . '. Please check the file permissions',
426
+                    ILogger::WARN);
427
+                $success = false;
428
+                continue; // try to update as many files as possible
429
+            }
430
+
431
+            $content = '';
432
+            while (!feof($handle)) {
433
+                $content .= fread($handle, 1000);
434
+            }
435
+
436
+            foreach ($phpValueKeys as $key) {
437
+                $pattern = vsprintf($patternMap['pattern'], [$key]);
438
+                $setting = vsprintf($patternMap['setting'], [$key, $size]);
439
+                $hasReplaced = 0;
440
+                $newContent = preg_replace($pattern, $setting, $content, 2, $hasReplaced);
441
+                if ($newContent !== null) {
442
+                    $content = $newContent;
443
+                }
444
+                if ($hasReplaced === 0) {
445
+                    $content .= "\n" . $setting;
446
+                }
447
+            }
448
+
449
+            // write file back
450
+            ftruncate($handle, 0);
451
+            rewind($handle);
452
+            fwrite($handle, $content);
453
+
454
+            fclose($handle);
455
+        }
456
+
457
+        if ($success) {
458
+            return OC_Helper::computerFileSize($size);
459
+        }
460
+        return false;
461
+    }
462
+
463
+    /**
464
+     * @param string $dir
465
+     * @param $files
466
+     * @param integer $getType
467
+     * @param View $view
468
+     * @param string $filename
469
+     */
470
+    private static function unlockAllTheFiles($dir, $files, $getType, $view, $filename) {
471
+        if ($getType === self::FILE) {
472
+            $view->unlockFile($filename, ILockingProvider::LOCK_SHARED);
473
+        }
474
+        if ($getType === self::ZIP_FILES) {
475
+            foreach ($files as $file) {
476
+                $file = $dir . '/' . $file;
477
+                $view->unlockFile($file, ILockingProvider::LOCK_SHARED);
478
+            }
479
+        }
480
+        if ($getType === self::ZIP_DIR) {
481
+            $file = $dir . '/' . $files;
482
+            $view->unlockFile($file, ILockingProvider::LOCK_SHARED);
483
+        }
484
+    }
485 485
 
486 486
 }
Please login to merge, or discard this patch.
Spacing   +26 added lines, -26 removed lines patch added patch discarded remove patch
@@ -76,7 +76,7 @@  discard block
 block discarded – undo
76 76
 	private static function sendHeaders($filename, $name, array $rangeArray) {
77 77
 		OC_Response::setContentDispositionHeader($name, 'attachment');
78 78
 		header('Content-Transfer-Encoding: binary', true);
79
-		header('Pragma: public');// enable caching in IE
79
+		header('Pragma: public'); // enable caching in IE
80 80
 		header('Expires: 0');
81 81
 		header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
82 82
 		$fileSize = \OC\Files\Filesystem::filesize($filename);
@@ -120,7 +120,7 @@  discard block
 block discarded – undo
120 120
 			}
121 121
 
122 122
 			if (!is_array($files)) {
123
-				$filename = $dir . '/' . $files;
123
+				$filename = $dir.'/'.$files;
124 124
 				if (!$view->is_dir($filename)) {
125 125
 					self::getSingleFile($view, $dir, $files, is_null($params) ? array() : $params);
126 126
 					return;
@@ -135,9 +135,9 @@  discard block
 block discarded – undo
135 135
 					$name = $basename;
136 136
 				}
137 137
 
138
-				$filename = $dir . '/' . $name;
138
+				$filename = $dir.'/'.$name;
139 139
 			} else {
140
-				$filename = $dir . '/' . $files;
140
+				$filename = $dir.'/'.$files;
141 141
 				$getType = self::ZIP_DIR;
142 142
 				// downloading root ?
143 143
 				if ($files !== '') {
@@ -152,13 +152,13 @@  discard block
 block discarded – undo
152 152
 				$fileInfos = array();
153 153
 				$fileSize = 0;
154 154
 				foreach ($files as $file) {
155
-					$fileInfo = \OC\Files\Filesystem::getFileInfo($dir . '/' . $file);
155
+					$fileInfo = \OC\Files\Filesystem::getFileInfo($dir.'/'.$file);
156 156
 					$fileSize += $fileInfo->getSize();
157 157
 					$fileInfos[] = $fileInfo;
158 158
 				}
159 159
 				$numberOfFiles = self::getNumberOfFiles($fileInfos);
160 160
 			} elseif ($getType === self::ZIP_DIR) {
161
-				$fileInfo = \OC\Files\Filesystem::getFileInfo($dir . '/' . $files);
161
+				$fileInfo = \OC\Files\Filesystem::getFileInfo($dir.'/'.$files);
162 162
 				$fileSize = $fileInfo->getSize();
163 163
 				$numberOfFiles = self::getNumberOfFiles(array($fileInfo));
164 164
 			}
@@ -167,7 +167,7 @@  discard block
 block discarded – undo
167 167
 			OC_Util::obEnd();
168 168
 
169 169
 			$streamer->sendHeaders($name);
170
-			$executionTime = (int)OC::$server->getIniWrapper()->getNumeric('max_execution_time');
170
+			$executionTime = (int) OC::$server->getIniWrapper()->getNumeric('max_execution_time');
171 171
 			if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
172 172
 				@set_time_limit(0);
173 173
 			}
@@ -175,7 +175,7 @@  discard block
 block discarded – undo
175 175
 
176 176
 			if ($getType === self::ZIP_FILES) {
177 177
 				foreach ($files as $file) {
178
-					$file = $dir . '/' . $file;
178
+					$file = $dir.'/'.$file;
179 179
 					if (\OC\Files\Filesystem::is_file($file)) {
180 180
 						$fileSize = \OC\Files\Filesystem::filesize($file);
181 181
 						$fileTime = \OC\Files\Filesystem::filemtime($file);
@@ -187,7 +187,7 @@  discard block
 block discarded – undo
187 187
 					}
188 188
 				}
189 189
 			} elseif ($getType === self::ZIP_DIR) {
190
-				$file = $dir . '/' . $files;
190
+				$file = $dir.'/'.$files;
191 191
 				$streamer->addDirRecursive($file);
192 192
 			}
193 193
 			$streamer->finalize();
@@ -219,7 +219,7 @@  discard block
 block discarded – undo
219 219
 	 * @return array $rangeArray ('from'=>int,'to'=>int), ...
220 220
 	 */
221 221
 	private static function parseHttpRangeHeader($rangeHeaderPos, $fileSize) {
222
-		$rArray=explode(',', $rangeHeaderPos);
222
+		$rArray = explode(',', $rangeHeaderPos);
223 223
 		$minOffset = 0;
224 224
 		$ind = 0;
225 225
 
@@ -231,7 +231,7 @@  discard block
 block discarded – undo
231 231
 				if ($ranges[0] < $minOffset) { // case: bytes=500-700,601-999
232 232
 					$ranges[0] = $minOffset;
233 233
 				}
234
-				if ($ind > 0 && $rangeArray[$ind-1]['to']+1 == $ranges[0]) { // case: bytes=500-600,601-999
234
+				if ($ind > 0 && $rangeArray[$ind - 1]['to'] + 1 == $ranges[0]) { // case: bytes=500-600,601-999
235 235
 					$ind--;
236 236
 					$ranges[0] = $rangeArray[$ind]['from'];
237 237
 				}
@@ -240,9 +240,9 @@  discard block
 block discarded – undo
240 240
 			if (is_numeric($ranges[0]) && is_numeric($ranges[1]) && $ranges[0] < $fileSize && $ranges[0] <= $ranges[1]) {
241 241
 				// case: x-x
242 242
 				if ($ranges[1] >= $fileSize) {
243
-					$ranges[1] = $fileSize-1;
243
+					$ranges[1] = $fileSize - 1;
244 244
 				}
245
-				$rangeArray[$ind++] = array( 'from' => $ranges[0], 'to' => $ranges[1], 'size' => $fileSize );
245
+				$rangeArray[$ind++] = array('from' => $ranges[0], 'to' => $ranges[1], 'size' => $fileSize);
246 246
 				$minOffset = $ranges[1] + 1;
247 247
 				if ($minOffset >= $fileSize) {
248 248
 					break;
@@ -250,7 +250,7 @@  discard block
 block discarded – undo
250 250
 			}
251 251
 			elseif (is_numeric($ranges[0]) && $ranges[0] < $fileSize) {
252 252
 				// case: x-
253
-				$rangeArray[$ind++] = array( 'from' => $ranges[0], 'to' => $fileSize-1, 'size' => $fileSize );
253
+				$rangeArray[$ind++] = array('from' => $ranges[0], 'to' => $fileSize - 1, 'size' => $fileSize);
254 254
 				break;
255 255
 			}
256 256
 			elseif (is_numeric($ranges[1])) {
@@ -258,7 +258,7 @@  discard block
 block discarded – undo
258 258
 				if ($ranges[1] > $fileSize) {
259 259
 					$ranges[1] = $fileSize;
260 260
 				}
261
-				$rangeArray[$ind++] = array( 'from' => $fileSize-$ranges[1], 'to' => $fileSize-1, 'size' => $fileSize );
261
+				$rangeArray[$ind++] = array('from' => $fileSize - $ranges[1], 'to' => $fileSize - 1, 'size' => $fileSize);
262 262
 				break;
263 263
 			}
264 264
 		}
@@ -272,7 +272,7 @@  discard block
 block discarded – undo
272 272
 	 * @param array $params ; 'head' boolean to only send header of the request ; 'range' http range header
273 273
 	 */
274 274
 	private static function getSingleFile($view, $dir, $name, $params) {
275
-		$filename = $dir . '/' . $name;
275
+		$filename = $dir.'/'.$name;
276 276
 		OC_Util::obEnd();
277 277
 		$view->lockFile($filename, ILockingProvider::LOCK_SHARED);
278 278
 		
@@ -361,17 +361,17 @@  discard block
 block discarded – undo
361 361
 	 */
362 362
 	public static function lockFiles($view, $dir, $files) {
363 363
 		if (!is_array($files)) {
364
-			$file = $dir . '/' . $files;
364
+			$file = $dir.'/'.$files;
365 365
 			$files = [$file];
366 366
 		}
367 367
 		foreach ($files as $file) {
368
-			$file = $dir . '/' . $file;
368
+			$file = $dir.'/'.$file;
369 369
 			$view->lockFile($file, ILockingProvider::LOCK_SHARED);
370 370
 			if ($view->is_dir($file)) {
371 371
 				$contents = $view->getDirectoryContent($file);
372 372
 				$contents = array_map(function($fileInfo) use ($file) {
373 373
 					/** @var \OCP\Files\FileInfo $fileInfo */
374
-					return $file . '/' . $fileInfo->getName();
374
+					return $file.'/'.$fileInfo->getName();
375 375
 				}, $contents);
376 376
 				self::lockFiles($view, $dir, $contents);
377 377
 			}
@@ -387,7 +387,7 @@  discard block
 block discarded – undo
387 387
 	 */
388 388
 	public static function setUploadLimit($size, $files = []) {
389 389
 		//don't allow user to break his config
390
-		$size = (int)$size;
390
+		$size = (int) $size;
391 391
 		if ($size < self::UPLOAD_MIN_LIMIT_BYTES) {
392 392
 			return false;
393 393
 		}
@@ -400,8 +400,8 @@  discard block
 block discarded – undo
400 400
 
401 401
 		// default locations if not overridden by $files
402 402
 		$files = array_merge([
403
-			'.htaccess' => OC::$SERVERROOT . '/.htaccess',
404
-			'.user.ini' => OC::$SERVERROOT . '/.user.ini'
403
+			'.htaccess' => OC::$SERVERROOT.'/.htaccess',
404
+			'.user.ini' => OC::$SERVERROOT.'/.user.ini'
405 405
 		], $files);
406 406
 
407 407
 		$updateFiles = [
@@ -422,7 +422,7 @@  discard block
 block discarded – undo
422 422
 			$handle = @fopen($filename, 'r+');
423 423
 			if (!$handle) {
424 424
 				\OCP\Util::writeLog('files',
425
-					'Can\'t write upload limit to ' . $filename . '. Please check the file permissions',
425
+					'Can\'t write upload limit to '.$filename.'. Please check the file permissions',
426 426
 					ILogger::WARN);
427 427
 				$success = false;
428 428
 				continue; // try to update as many files as possible
@@ -442,7 +442,7 @@  discard block
 block discarded – undo
442 442
 					$content = $newContent;
443 443
 				}
444 444
 				if ($hasReplaced === 0) {
445
-					$content .= "\n" . $setting;
445
+					$content .= "\n".$setting;
446 446
 				}
447 447
 			}
448 448
 
@@ -473,12 +473,12 @@  discard block
 block discarded – undo
473 473
 		}
474 474
 		if ($getType === self::ZIP_FILES) {
475 475
 			foreach ($files as $file) {
476
-				$file = $dir . '/' . $file;
476
+				$file = $dir.'/'.$file;
477 477
 				$view->unlockFile($file, ILockingProvider::LOCK_SHARED);
478 478
 			}
479 479
 		}
480 480
 		if ($getType === self::ZIP_DIR) {
481
-			$file = $dir . '/' . $files;
481
+			$file = $dir.'/'.$files;
482 482
 			$view->unlockFile($file, ILockingProvider::LOCK_SHARED);
483 483
 		}
484 484
 	}
Please login to merge, or discard this patch.
lib/private/legacy/util.php 1 patch
Indentation   +1432 added lines, -1432 removed lines patch added patch discarded remove patch
@@ -66,1440 +66,1440 @@
 block discarded – undo
66 66
 use OCP\IUser;
67 67
 
68 68
 class OC_Util {
69
-	public static $scripts = array();
70
-	public static $styles = array();
71
-	public static $headers = array();
72
-	private static $rootMounted = false;
73
-	private static $fsSetup = false;
74
-
75
-	/** @var array Local cache of version.php */
76
-	private static $versionCache = null;
77
-
78
-	protected static function getAppManager() {
79
-		return \OC::$server->getAppManager();
80
-	}
81
-
82
-	private static function initLocalStorageRootFS() {
83
-		// mount local file backend as root
84
-		$configDataDirectory = \OC::$server->getSystemConfig()->getValue("datadirectory", OC::$SERVERROOT . "/data");
85
-		//first set up the local "root" storage
86
-		\OC\Files\Filesystem::initMountManager();
87
-		if (!self::$rootMounted) {
88
-			\OC\Files\Filesystem::mount('\OC\Files\Storage\Local', array('datadir' => $configDataDirectory), '/');
89
-			self::$rootMounted = true;
90
-		}
91
-	}
92
-
93
-	/**
94
-	 * mounting an object storage as the root fs will in essence remove the
95
-	 * necessity of a data folder being present.
96
-	 * TODO make home storage aware of this and use the object storage instead of local disk access
97
-	 *
98
-	 * @param array $config containing 'class' and optional 'arguments'
99
-	 * @suppress PhanDeprecatedFunction
100
-	 */
101
-	private static function initObjectStoreRootFS($config) {
102
-		// check misconfiguration
103
-		if (empty($config['class'])) {
104
-			\OCP\Util::writeLog('files', 'No class given for objectstore', ILogger::ERROR);
105
-		}
106
-		if (!isset($config['arguments'])) {
107
-			$config['arguments'] = array();
108
-		}
109
-
110
-		// instantiate object store implementation
111
-		$name = $config['class'];
112
-		if (strpos($name, 'OCA\\') === 0 && substr_count($name, '\\') >= 2) {
113
-			$segments = explode('\\', $name);
114
-			OC_App::loadApp(strtolower($segments[1]));
115
-		}
116
-		$config['arguments']['objectstore'] = new $config['class']($config['arguments']);
117
-		// mount with plain / root object store implementation
118
-		$config['class'] = '\OC\Files\ObjectStore\ObjectStoreStorage';
119
-
120
-		// mount object storage as root
121
-		\OC\Files\Filesystem::initMountManager();
122
-		if (!self::$rootMounted) {
123
-			\OC\Files\Filesystem::mount($config['class'], $config['arguments'], '/');
124
-			self::$rootMounted = true;
125
-		}
126
-	}
127
-
128
-	/**
129
-	 * mounting an object storage as the root fs will in essence remove the
130
-	 * necessity of a data folder being present.
131
-	 *
132
-	 * @param array $config containing 'class' and optional 'arguments'
133
-	 * @suppress PhanDeprecatedFunction
134
-	 */
135
-	private static function initObjectStoreMultibucketRootFS($config) {
136
-		// check misconfiguration
137
-		if (empty($config['class'])) {
138
-			\OCP\Util::writeLog('files', 'No class given for objectstore', ILogger::ERROR);
139
-		}
140
-		if (!isset($config['arguments'])) {
141
-			$config['arguments'] = array();
142
-		}
143
-
144
-		// instantiate object store implementation
145
-		$name = $config['class'];
146
-		if (strpos($name, 'OCA\\') === 0 && substr_count($name, '\\') >= 2) {
147
-			$segments = explode('\\', $name);
148
-			OC_App::loadApp(strtolower($segments[1]));
149
-		}
150
-
151
-		if (!isset($config['arguments']['bucket'])) {
152
-			$config['arguments']['bucket'] = '';
153
-		}
154
-		// put the root FS always in first bucket for multibucket configuration
155
-		$config['arguments']['bucket'] .= '0';
156
-
157
-		$config['arguments']['objectstore'] = new $config['class']($config['arguments']);
158
-		// mount with plain / root object store implementation
159
-		$config['class'] = '\OC\Files\ObjectStore\ObjectStoreStorage';
160
-
161
-		// mount object storage as root
162
-		\OC\Files\Filesystem::initMountManager();
163
-		if (!self::$rootMounted) {
164
-			\OC\Files\Filesystem::mount($config['class'], $config['arguments'], '/');
165
-			self::$rootMounted = true;
166
-		}
167
-	}
168
-
169
-	/**
170
-	 * Can be set up
171
-	 *
172
-	 * @param string $user
173
-	 * @return boolean
174
-	 * @description configure the initial filesystem based on the configuration
175
-	 * @suppress PhanDeprecatedFunction
176
-	 * @suppress PhanAccessMethodInternal
177
-	 */
178
-	public static function setupFS($user = '') {
179
-		//setting up the filesystem twice can only lead to trouble
180
-		if (self::$fsSetup) {
181
-			return false;
182
-		}
183
-
184
-		\OC::$server->getEventLogger()->start('setup_fs', 'Setup filesystem');
185
-
186
-		// If we are not forced to load a specific user we load the one that is logged in
187
-		if ($user === null) {
188
-			$user = '';
189
-		} else if ($user == "" && \OC::$server->getUserSession()->isLoggedIn()) {
190
-			$user = OC_User::getUser();
191
-		}
192
-
193
-		// load all filesystem apps before, so no setup-hook gets lost
194
-		OC_App::loadApps(array('filesystem'));
195
-
196
-		// the filesystem will finish when $user is not empty,
197
-		// mark fs setup here to avoid doing the setup from loading
198
-		// OC_Filesystem
199
-		if ($user != '') {
200
-			self::$fsSetup = true;
201
-		}
202
-
203
-		\OC\Files\Filesystem::initMountManager();
204
-
205
-		\OC\Files\Filesystem::logWarningWhenAddingStorageWrapper(false);
206
-		\OC\Files\Filesystem::addStorageWrapper('mount_options', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
207
-			if ($storage->instanceOfStorage('\OC\Files\Storage\Common')) {
208
-				/** @var \OC\Files\Storage\Common $storage */
209
-				$storage->setMountOptions($mount->getOptions());
210
-			}
211
-			return $storage;
212
-		});
213
-
214
-		\OC\Files\Filesystem::addStorageWrapper('enable_sharing', function ($mountPoint, \OCP\Files\Storage\IStorage $storage, \OCP\Files\Mount\IMountPoint $mount) {
215
-			if (!$mount->getOption('enable_sharing', true)) {
216
-				return new \OC\Files\Storage\Wrapper\PermissionsMask([
217
-					'storage' => $storage,
218
-					'mask' => \OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_SHARE
219
-				]);
220
-			}
221
-			return $storage;
222
-		});
223
-
224
-		// install storage availability wrapper, before most other wrappers
225
-		\OC\Files\Filesystem::addStorageWrapper('oc_availability', function ($mountPoint, \OCP\Files\Storage\IStorage $storage) {
226
-			if (!$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) {
227
-				return new \OC\Files\Storage\Wrapper\Availability(['storage' => $storage]);
228
-			}
229
-			return $storage;
230
-		});
231
-
232
-		\OC\Files\Filesystem::addStorageWrapper('oc_encoding', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
233
-			if ($mount->getOption('encoding_compatibility', false) && !$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) {
234
-				return new \OC\Files\Storage\Wrapper\Encoding(['storage' => $storage]);
235
-			}
236
-			return $storage;
237
-		});
238
-
239
-		\OC\Files\Filesystem::addStorageWrapper('oc_quota', function ($mountPoint, $storage) {
240
-			// set up quota for home storages, even for other users
241
-			// which can happen when using sharing
242
-
243
-			/**
244
-			 * @var \OC\Files\Storage\Storage $storage
245
-			 */
246
-			if ($storage->instanceOfStorage('\OC\Files\Storage\Home')
247
-				|| $storage->instanceOfStorage('\OC\Files\ObjectStore\HomeObjectStoreStorage')
248
-			) {
249
-				/** @var \OC\Files\Storage\Home $storage */
250
-				if (is_object($storage->getUser())) {
251
-					$user = $storage->getUser()->getUID();
252
-					$quota = OC_Util::getUserQuota($user);
253
-					if ($quota !== \OCP\Files\FileInfo::SPACE_UNLIMITED) {
254
-						return new \OC\Files\Storage\Wrapper\Quota(array('storage' => $storage, 'quota' => $quota, 'root' => 'files'));
255
-					}
256
-				}
257
-			}
258
-
259
-			return $storage;
260
-		});
261
-
262
-		OC_Hook::emit('OC_Filesystem', 'preSetup', array('user' => $user));
263
-		\OC\Files\Filesystem::logWarningWhenAddingStorageWrapper(true);
264
-
265
-		//check if we are using an object storage
266
-		$objectStore = \OC::$server->getSystemConfig()->getValue('objectstore', null);
267
-		$objectStoreMultibucket = \OC::$server->getSystemConfig()->getValue('objectstore_multibucket', null);
268
-
269
-		// use the same order as in ObjectHomeMountProvider
270
-		if (isset($objectStoreMultibucket)) {
271
-			self::initObjectStoreMultibucketRootFS($objectStoreMultibucket);
272
-		} elseif (isset($objectStore)) {
273
-			self::initObjectStoreRootFS($objectStore);
274
-		} else {
275
-			self::initLocalStorageRootFS();
276
-		}
277
-
278
-		if ($user != '' && !\OC::$server->getUserManager()->userExists($user)) {
279
-			\OC::$server->getEventLogger()->end('setup_fs');
280
-			return false;
281
-		}
282
-
283
-		//if we aren't logged in, there is no use to set up the filesystem
284
-		if ($user != "") {
285
-
286
-			$userDir = '/' . $user . '/files';
287
-
288
-			//jail the user into his "home" directory
289
-			\OC\Files\Filesystem::init($user, $userDir);
290
-
291
-			OC_Hook::emit('OC_Filesystem', 'setup', array('user' => $user, 'user_dir' => $userDir));
292
-		}
293
-		\OC::$server->getEventLogger()->end('setup_fs');
294
-		return true;
295
-	}
296
-
297
-	/**
298
-	 * check if a password is required for each public link
299
-	 *
300
-	 * @return boolean
301
-	 * @suppress PhanDeprecatedFunction
302
-	 */
303
-	public static function isPublicLinkPasswordRequired() {
304
-		$enforcePassword = \OC::$server->getConfig()->getAppValue('core', 'shareapi_enforce_links_password', 'no');
305
-		return $enforcePassword === 'yes';
306
-	}
307
-
308
-	/**
309
-	 * check if sharing is disabled for the current user
310
-	 * @param IConfig $config
311
-	 * @param IGroupManager $groupManager
312
-	 * @param IUser|null $user
313
-	 * @return bool
314
-	 */
315
-	public static function isSharingDisabledForUser(IConfig $config, IGroupManager $groupManager, $user) {
316
-		if ($config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') {
317
-			$groupsList = $config->getAppValue('core', 'shareapi_exclude_groups_list', '');
318
-			$excludedGroups = json_decode($groupsList);
319
-			if (is_null($excludedGroups)) {
320
-				$excludedGroups = explode(',', $groupsList);
321
-				$newValue = json_encode($excludedGroups);
322
-				$config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue);
323
-			}
324
-			$usersGroups = $groupManager->getUserGroupIds($user);
325
-			if (!empty($usersGroups)) {
326
-				$remainingGroups = array_diff($usersGroups, $excludedGroups);
327
-				// if the user is only in groups which are disabled for sharing then
328
-				// sharing is also disabled for the user
329
-				if (empty($remainingGroups)) {
330
-					return true;
331
-				}
332
-			}
333
-		}
334
-		return false;
335
-	}
336
-
337
-	/**
338
-	 * check if share API enforces a default expire date
339
-	 *
340
-	 * @return boolean
341
-	 * @suppress PhanDeprecatedFunction
342
-	 */
343
-	public static function isDefaultExpireDateEnforced() {
344
-		$isDefaultExpireDateEnabled = \OC::$server->getConfig()->getAppValue('core', 'shareapi_default_expire_date', 'no');
345
-		$enforceDefaultExpireDate = false;
346
-		if ($isDefaultExpireDateEnabled === 'yes') {
347
-			$value = \OC::$server->getConfig()->getAppValue('core', 'shareapi_enforce_expire_date', 'no');
348
-			$enforceDefaultExpireDate = $value === 'yes';
349
-		}
350
-
351
-		return $enforceDefaultExpireDate;
352
-	}
353
-
354
-	/**
355
-	 * Get the quota of a user
356
-	 *
357
-	 * @param string $userId
358
-	 * @return float Quota bytes
359
-	 */
360
-	public static function getUserQuota($userId) {
361
-		$user = \OC::$server->getUserManager()->get($userId);
362
-		if (is_null($user)) {
363
-			return \OCP\Files\FileInfo::SPACE_UNLIMITED;
364
-		}
365
-		$userQuota = $user->getQuota();
366
-		if($userQuota === 'none') {
367
-			return \OCP\Files\FileInfo::SPACE_UNLIMITED;
368
-		}
369
-		return OC_Helper::computerFileSize($userQuota);
370
-	}
371
-
372
-	/**
373
-	 * copies the skeleton to the users /files
374
-	 *
375
-	 * @param String $userId
376
-	 * @param \OCP\Files\Folder $userDirectory
377
-	 * @throws \RuntimeException
378
-	 * @suppress PhanDeprecatedFunction
379
-	 */
380
-	public static function copySkeleton($userId, \OCP\Files\Folder $userDirectory) {
381
-
382
-		$plainSkeletonDirectory = \OC::$server->getConfig()->getSystemValue('skeletondirectory', \OC::$SERVERROOT . '/core/skeleton');
383
-		$userLang = \OC::$server->getL10NFactory()->findLanguage();
384
-		$skeletonDirectory = str_replace('{lang}', $userLang, $plainSkeletonDirectory);
385
-
386
-		if (!file_exists($skeletonDirectory)) {
387
-			$dialectStart = strpos($userLang, '_');
388
-			if ($dialectStart !== false) {
389
-				$skeletonDirectory = str_replace('{lang}', substr($userLang, 0, $dialectStart), $plainSkeletonDirectory);
390
-			}
391
-			if ($dialectStart === false || !file_exists($skeletonDirectory)) {
392
-				$skeletonDirectory = str_replace('{lang}', 'default', $plainSkeletonDirectory);
393
-			}
394
-			if (!file_exists($skeletonDirectory)) {
395
-				$skeletonDirectory = '';
396
-			}
397
-		}
398
-
399
-		$instanceId = \OC::$server->getConfig()->getSystemValue('instanceid', '');
400
-
401
-		if ($instanceId === null) {
402
-			throw new \RuntimeException('no instance id!');
403
-		}
404
-		$appdata = 'appdata_' . $instanceId;
405
-		if ($userId === $appdata) {
406
-			throw new \RuntimeException('username is reserved name: ' . $appdata);
407
-		}
408
-
409
-		if (!empty($skeletonDirectory)) {
410
-			\OCP\Util::writeLog(
411
-				'files_skeleton',
412
-				'copying skeleton for '.$userId.' from '.$skeletonDirectory.' to '.$userDirectory->getFullPath('/'),
413
-				ILogger::DEBUG
414
-			);
415
-			self::copyr($skeletonDirectory, $userDirectory);
416
-			// update the file cache
417
-			$userDirectory->getStorage()->getScanner()->scan('', \OC\Files\Cache\Scanner::SCAN_RECURSIVE);
418
-		}
419
-	}
420
-
421
-	/**
422
-	 * copies a directory recursively by using streams
423
-	 *
424
-	 * @param string $source
425
-	 * @param \OCP\Files\Folder $target
426
-	 * @return void
427
-	 */
428
-	public static function copyr($source, \OCP\Files\Folder $target) {
429
-		$logger = \OC::$server->getLogger();
430
-
431
-		// Verify if folder exists
432
-		$dir = opendir($source);
433
-		if($dir === false) {
434
-			$logger->error(sprintf('Could not opendir "%s"', $source), ['app' => 'core']);
435
-			return;
436
-		}
437
-
438
-		// Copy the files
439
-		while (false !== ($file = readdir($dir))) {
440
-			if (!\OC\Files\Filesystem::isIgnoredDir($file)) {
441
-				if (is_dir($source . '/' . $file)) {
442
-					$child = $target->newFolder($file);
443
-					self::copyr($source . '/' . $file, $child);
444
-				} else {
445
-					$child = $target->newFile($file);
446
-					$sourceStream = fopen($source . '/' . $file, 'r');
447
-					if($sourceStream === false) {
448
-						$logger->error(sprintf('Could not fopen "%s"', $source . '/' . $file), ['app' => 'core']);
449
-						closedir($dir);
450
-						return;
451
-					}
452
-					stream_copy_to_stream($sourceStream, $child->fopen('w'));
453
-				}
454
-			}
455
-		}
456
-		closedir($dir);
457
-	}
458
-
459
-	/**
460
-	 * @return void
461
-	 * @suppress PhanUndeclaredMethod
462
-	 */
463
-	public static function tearDownFS() {
464
-		\OC\Files\Filesystem::tearDown();
465
-		\OC::$server->getRootFolder()->clearCache();
466
-		self::$fsSetup = false;
467
-		self::$rootMounted = false;
468
-	}
469
-
470
-	/**
471
-	 * get the current installed version of ownCloud
472
-	 *
473
-	 * @return array
474
-	 */
475
-	public static function getVersion() {
476
-		OC_Util::loadVersion();
477
-		return self::$versionCache['OC_Version'];
478
-	}
479
-
480
-	/**
481
-	 * get the current installed version string of ownCloud
482
-	 *
483
-	 * @return string
484
-	 */
485
-	public static function getVersionString() {
486
-		OC_Util::loadVersion();
487
-		return self::$versionCache['OC_VersionString'];
488
-	}
489
-
490
-	/**
491
-	 * @deprecated the value is of no use anymore
492
-	 * @return string
493
-	 */
494
-	public static function getEditionString() {
495
-		return '';
496
-	}
497
-
498
-	/**
499
-	 * @description get the update channel of the current installed of ownCloud.
500
-	 * @return string
501
-	 */
502
-	public static function getChannel() {
503
-		OC_Util::loadVersion();
504
-		return \OC::$server->getConfig()->getSystemValue('updater.release.channel', self::$versionCache['OC_Channel']);
505
-	}
506
-
507
-	/**
508
-	 * @description get the build number of the current installed of ownCloud.
509
-	 * @return string
510
-	 */
511
-	public static function getBuild() {
512
-		OC_Util::loadVersion();
513
-		return self::$versionCache['OC_Build'];
514
-	}
515
-
516
-	/**
517
-	 * @description load the version.php into the session as cache
518
-	 * @suppress PhanUndeclaredVariable
519
-	 */
520
-	private static function loadVersion() {
521
-		if (self::$versionCache !== null) {
522
-			return;
523
-		}
524
-
525
-		$timestamp = filemtime(OC::$SERVERROOT . '/version.php');
526
-		require OC::$SERVERROOT . '/version.php';
527
-		/** @var $timestamp int */
528
-		self::$versionCache['OC_Version_Timestamp'] = $timestamp;
529
-		/** @var $OC_Version string */
530
-		self::$versionCache['OC_Version'] = $OC_Version;
531
-		/** @var $OC_VersionString string */
532
-		self::$versionCache['OC_VersionString'] = $OC_VersionString;
533
-		/** @var $OC_Build string */
534
-		self::$versionCache['OC_Build'] = $OC_Build;
535
-
536
-		/** @var $OC_Channel string */
537
-		self::$versionCache['OC_Channel'] = $OC_Channel;
538
-	}
539
-
540
-	/**
541
-	 * generates a path for JS/CSS files. If no application is provided it will create the path for core.
542
-	 *
543
-	 * @param string $application application to get the files from
544
-	 * @param string $directory directory within this application (css, js, vendor, etc)
545
-	 * @param string $file the file inside of the above folder
546
-	 * @return string the path
547
-	 */
548
-	private static function generatePath($application, $directory, $file) {
549
-		if (is_null($file)) {
550
-			$file = $application;
551
-			$application = "";
552
-		}
553
-		if (!empty($application)) {
554
-			return "$application/$directory/$file";
555
-		} else {
556
-			return "$directory/$file";
557
-		}
558
-	}
559
-
560
-	/**
561
-	 * add a javascript file
562
-	 *
563
-	 * @param string $application application id
564
-	 * @param string|null $file filename
565
-	 * @param bool $prepend prepend the Script to the beginning of the list
566
-	 * @return void
567
-	 */
568
-	public static function addScript($application, $file = null, $prepend = false) {
569
-		$path = OC_Util::generatePath($application, 'js', $file);
570
-
571
-		// core js files need separate handling
572
-		if ($application !== 'core' && $file !== null) {
573
-			self::addTranslations ( $application );
574
-		}
575
-		self::addExternalResource($application, $prepend, $path, "script");
576
-	}
577
-
578
-	/**
579
-	 * add a javascript file from the vendor sub folder
580
-	 *
581
-	 * @param string $application application id
582
-	 * @param string|null $file filename
583
-	 * @param bool $prepend prepend the Script to the beginning of the list
584
-	 * @return void
585
-	 */
586
-	public static function addVendorScript($application, $file = null, $prepend = false) {
587
-		$path = OC_Util::generatePath($application, 'vendor', $file);
588
-		self::addExternalResource($application, $prepend, $path, "script");
589
-	}
590
-
591
-	/**
592
-	 * add a translation JS file
593
-	 *
594
-	 * @param string $application application id
595
-	 * @param string|null $languageCode language code, defaults to the current language
596
-	 * @param bool|null $prepend prepend the Script to the beginning of the list
597
-	 */
598
-	public static function addTranslations($application, $languageCode = null, $prepend = false) {
599
-		if (is_null($languageCode)) {
600
-			$languageCode = \OC::$server->getL10NFactory()->findLanguage($application);
601
-		}
602
-		if (!empty($application)) {
603
-			$path = "$application/l10n/$languageCode";
604
-		} else {
605
-			$path = "l10n/$languageCode";
606
-		}
607
-		self::addExternalResource($application, $prepend, $path, "script");
608
-	}
609
-
610
-	/**
611
-	 * add a css file
612
-	 *
613
-	 * @param string $application application id
614
-	 * @param string|null $file filename
615
-	 * @param bool $prepend prepend the Style to the beginning of the list
616
-	 * @return void
617
-	 */
618
-	public static function addStyle($application, $file = null, $prepend = false) {
619
-		$path = OC_Util::generatePath($application, 'css', $file);
620
-		self::addExternalResource($application, $prepend, $path, "style");
621
-	}
622
-
623
-	/**
624
-	 * add a css file from the vendor sub folder
625
-	 *
626
-	 * @param string $application application id
627
-	 * @param string|null $file filename
628
-	 * @param bool $prepend prepend the Style to the beginning of the list
629
-	 * @return void
630
-	 */
631
-	public static function addVendorStyle($application, $file = null, $prepend = false) {
632
-		$path = OC_Util::generatePath($application, 'vendor', $file);
633
-		self::addExternalResource($application, $prepend, $path, "style");
634
-	}
635
-
636
-	/**
637
-	 * add an external resource css/js file
638
-	 *
639
-	 * @param string $application application id
640
-	 * @param bool $prepend prepend the file to the beginning of the list
641
-	 * @param string $path
642
-	 * @param string $type (script or style)
643
-	 * @return void
644
-	 */
645
-	private static function addExternalResource($application, $prepend, $path, $type = "script") {
646
-
647
-		if ($type === "style") {
648
-			if (!in_array($path, self::$styles)) {
649
-				if ($prepend === true) {
650
-					array_unshift ( self::$styles, $path );
651
-				} else {
652
-					self::$styles[] = $path;
653
-				}
654
-			}
655
-		} elseif ($type === "script") {
656
-			if (!in_array($path, self::$scripts)) {
657
-				if ($prepend === true) {
658
-					array_unshift ( self::$scripts, $path );
659
-				} else {
660
-					self::$scripts [] = $path;
661
-				}
662
-			}
663
-		}
664
-	}
665
-
666
-	/**
667
-	 * Add a custom element to the header
668
-	 * If $text is null then the element will be written as empty element.
669
-	 * So use "" to get a closing tag.
670
-	 * @param string $tag tag name of the element
671
-	 * @param array $attributes array of attributes for the element
672
-	 * @param string $text the text content for the element
673
-	 */
674
-	public static function addHeader($tag, $attributes, $text=null) {
675
-		self::$headers[] = array(
676
-			'tag' => $tag,
677
-			'attributes' => $attributes,
678
-			'text' => $text
679
-		);
680
-	}
681
-
682
-	/**
683
-	 * check if the current server configuration is suitable for ownCloud
684
-	 *
685
-	 * @param \OC\SystemConfig $config
686
-	 * @return array arrays with error messages and hints
687
-	 */
688
-	public static function checkServer(\OC\SystemConfig $config) {
689
-		$l = \OC::$server->getL10N('lib');
690
-		$errors = array();
691
-		$CONFIG_DATADIRECTORY = $config->getValue('datadirectory', OC::$SERVERROOT . '/data');
692
-
693
-		if (!self::needUpgrade($config) && $config->getValue('installed', false)) {
694
-			// this check needs to be done every time
695
-			$errors = self::checkDataDirectoryValidity($CONFIG_DATADIRECTORY);
696
-		}
697
-
698
-		// Assume that if checkServer() succeeded before in this session, then all is fine.
699
-		if (\OC::$server->getSession()->exists('checkServer_succeeded') && \OC::$server->getSession()->get('checkServer_succeeded')) {
700
-			return $errors;
701
-		}
702
-
703
-		$webServerRestart = false;
704
-		$setup = new \OC\Setup(
705
-			$config,
706
-			\OC::$server->getIniWrapper(),
707
-			\OC::$server->getL10N('lib'),
708
-			\OC::$server->query(\OCP\Defaults::class),
709
-			\OC::$server->getLogger(),
710
-			\OC::$server->getSecureRandom(),
711
-			\OC::$server->query(\OC\Installer::class)
712
-		);
713
-
714
-		$urlGenerator = \OC::$server->getURLGenerator();
715
-
716
-		$availableDatabases = $setup->getSupportedDatabases();
717
-		if (empty($availableDatabases)) {
718
-			$errors[] = array(
719
-				'error' => $l->t('No database drivers (sqlite, mysql, or postgresql) installed.'),
720
-				'hint' => '' //TODO: sane hint
721
-			);
722
-			$webServerRestart = true;
723
-		}
724
-
725
-		// Check if config folder is writable.
726
-		if(!OC_Helper::isReadOnlyConfigEnabled()) {
727
-			if (!is_writable(OC::$configDir) or !is_readable(OC::$configDir)) {
728
-				$errors[] = array(
729
-					'error' => $l->t('Cannot write into "config" directory'),
730
-					'hint' => $l->t('This can usually be fixed by giving the webserver write access to the config directory. See %s',
731
-						[$urlGenerator->linkToDocs('admin-dir_permissions')])
732
-				);
733
-			}
734
-		}
735
-
736
-		// Check if there is a writable install folder.
737
-		if ($config->getValue('appstoreenabled', true)) {
738
-			if (OC_App::getInstallPath() === null
739
-				|| !is_writable(OC_App::getInstallPath())
740
-				|| !is_readable(OC_App::getInstallPath())
741
-			) {
742
-				$errors[] = array(
743
-					'error' => $l->t('Cannot write into "apps" directory'),
744
-					'hint' => $l->t('This can usually be fixed by giving the webserver write access to the apps directory'
745
-						. ' or disabling the appstore in the config file. See %s',
746
-						[$urlGenerator->linkToDocs('admin-dir_permissions')])
747
-				);
748
-			}
749
-		}
750
-		// Create root dir.
751
-		if ($config->getValue('installed', false)) {
752
-			if (!is_dir($CONFIG_DATADIRECTORY)) {
753
-				$success = @mkdir($CONFIG_DATADIRECTORY);
754
-				if ($success) {
755
-					$errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
756
-				} else {
757
-					$errors[] = [
758
-						'error' => $l->t('Cannot create "data" directory'),
759
-						'hint' => $l->t('This can usually be fixed by giving the webserver write access to the root directory. See %s',
760
-							[$urlGenerator->linkToDocs('admin-dir_permissions')])
761
-					];
762
-				}
763
-			} else if (!is_writable($CONFIG_DATADIRECTORY) or !is_readable($CONFIG_DATADIRECTORY)) {
764
-				//common hint for all file permissions error messages
765
-				$permissionsHint = $l->t('Permissions can usually be fixed by giving the webserver write access to the root directory. See %s.',
766
-					[$urlGenerator->linkToDocs('admin-dir_permissions')]);
767
-				$errors[] = [
768
-					'error' => 'Your data directory is not writable',
769
-					'hint' => $permissionsHint
770
-				];
771
-			} else {
772
-				$errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
773
-			}
774
-		}
775
-
776
-		if (!OC_Util::isSetLocaleWorking()) {
777
-			$errors[] = array(
778
-				'error' => $l->t('Setting locale to %s failed',
779
-					array('en_US.UTF-8/fr_FR.UTF-8/es_ES.UTF-8/de_DE.UTF-8/ru_RU.UTF-8/'
780
-						. 'pt_BR.UTF-8/it_IT.UTF-8/ja_JP.UTF-8/zh_CN.UTF-8')),
781
-				'hint' => $l->t('Please install one of these locales on your system and restart your webserver.')
782
-			);
783
-		}
784
-
785
-		// Contains the dependencies that should be checked against
786
-		// classes = class_exists
787
-		// functions = function_exists
788
-		// defined = defined
789
-		// ini = ini_get
790
-		// If the dependency is not found the missing module name is shown to the EndUser
791
-		// When adding new checks always verify that they pass on Travis as well
792
-		// for ini settings, see https://github.com/owncloud/administration/blob/master/travis-ci/custom.ini
793
-		$dependencies = array(
794
-			'classes' => array(
795
-				'ZipArchive' => 'zip',
796
-				'DOMDocument' => 'dom',
797
-				'XMLWriter' => 'XMLWriter',
798
-				'XMLReader' => 'XMLReader',
799
-			),
800
-			'functions' => [
801
-				'xml_parser_create' => 'libxml',
802
-				'mb_strcut' => 'mb multibyte',
803
-				'ctype_digit' => 'ctype',
804
-				'json_encode' => 'JSON',
805
-				'gd_info' => 'GD',
806
-				'gzencode' => 'zlib',
807
-				'iconv' => 'iconv',
808
-				'simplexml_load_string' => 'SimpleXML',
809
-				'hash' => 'HASH Message Digest Framework',
810
-				'curl_init' => 'cURL',
811
-				'openssl_verify' => 'OpenSSL',
812
-			],
813
-			'defined' => array(
814
-				'PDO::ATTR_DRIVER_NAME' => 'PDO'
815
-			),
816
-			'ini' => [
817
-				'default_charset' => 'UTF-8',
818
-			],
819
-		);
820
-		$missingDependencies = array();
821
-		$invalidIniSettings = [];
822
-		$moduleHint = $l->t('Please ask your server administrator to install the module.');
823
-
824
-		/**
825
-		 * FIXME: The dependency check does not work properly on HHVM on the moment
826
-		 *        and prevents installation. Once HHVM is more compatible with our
827
-		 *        approach to check for these values we should re-enable those
828
-		 *        checks.
829
-		 */
830
-		$iniWrapper = \OC::$server->getIniWrapper();
831
-		if (!self::runningOnHhvm()) {
832
-			foreach ($dependencies['classes'] as $class => $module) {
833
-				if (!class_exists($class)) {
834
-					$missingDependencies[] = $module;
835
-				}
836
-			}
837
-			foreach ($dependencies['functions'] as $function => $module) {
838
-				if (!function_exists($function)) {
839
-					$missingDependencies[] = $module;
840
-				}
841
-			}
842
-			foreach ($dependencies['defined'] as $defined => $module) {
843
-				if (!defined($defined)) {
844
-					$missingDependencies[] = $module;
845
-				}
846
-			}
847
-			foreach ($dependencies['ini'] as $setting => $expected) {
848
-				if (is_bool($expected)) {
849
-					if ($iniWrapper->getBool($setting) !== $expected) {
850
-						$invalidIniSettings[] = [$setting, $expected];
851
-					}
852
-				}
853
-				if (is_int($expected)) {
854
-					if ($iniWrapper->getNumeric($setting) !== $expected) {
855
-						$invalidIniSettings[] = [$setting, $expected];
856
-					}
857
-				}
858
-				if (is_string($expected)) {
859
-					if (strtolower($iniWrapper->getString($setting)) !== strtolower($expected)) {
860
-						$invalidIniSettings[] = [$setting, $expected];
861
-					}
862
-				}
863
-			}
864
-		}
865
-
866
-		foreach($missingDependencies as $missingDependency) {
867
-			$errors[] = array(
868
-				'error' => $l->t('PHP module %s not installed.', array($missingDependency)),
869
-				'hint' => $moduleHint
870
-			);
871
-			$webServerRestart = true;
872
-		}
873
-		foreach($invalidIniSettings as $setting) {
874
-			if(is_bool($setting[1])) {
875
-				$setting[1] = $setting[1] ? 'on' : 'off';
876
-			}
877
-			$errors[] = [
878
-				'error' => $l->t('PHP setting "%s" is not set to "%s".', [$setting[0], var_export($setting[1], true)]),
879
-				'hint' =>  $l->t('Adjusting this setting in php.ini will make Nextcloud run again')
880
-			];
881
-			$webServerRestart = true;
882
-		}
883
-
884
-		/**
885
-		 * The mbstring.func_overload check can only be performed if the mbstring
886
-		 * module is installed as it will return null if the checking setting is
887
-		 * not available and thus a check on the boolean value fails.
888
-		 *
889
-		 * TODO: Should probably be implemented in the above generic dependency
890
-		 *       check somehow in the long-term.
891
-		 */
892
-		if($iniWrapper->getBool('mbstring.func_overload') !== null &&
893
-			$iniWrapper->getBool('mbstring.func_overload') === true) {
894
-			$errors[] = array(
895
-				'error' => $l->t('mbstring.func_overload is set to "%s" instead of the expected value "0"', [$iniWrapper->getString('mbstring.func_overload')]),
896
-				'hint' => $l->t('To fix this issue set <code>mbstring.func_overload</code> to <code>0</code> in your php.ini')
897
-			);
898
-		}
899
-
900
-		if(function_exists('xml_parser_create') &&
901
-			LIBXML_LOADED_VERSION < 20700 ) {
902
-			$version = LIBXML_LOADED_VERSION;
903
-			$major = floor($version/10000);
904
-			$version -= ($major * 10000);
905
-			$minor = floor($version/100);
906
-			$version -= ($minor * 100);
907
-			$patch = $version;
908
-			$errors[] = array(
909
-				'error' => $l->t('libxml2 2.7.0 is at least required. Currently %s is installed.', [$major . '.' . $minor . '.' . $patch]),
910
-				'hint' => $l->t('To fix this issue update your libxml2 version and restart your web server.')
911
-			);
912
-		}
913
-
914
-		if (!self::isAnnotationsWorking()) {
915
-			$errors[] = array(
916
-				'error' => $l->t('PHP is apparently set up to strip inline doc blocks. This will make several core apps inaccessible.'),
917
-				'hint' => $l->t('This is probably caused by a cache/accelerator such as Zend OPcache or eAccelerator.')
918
-			);
919
-		}
920
-
921
-		if (!\OC::$CLI && $webServerRestart) {
922
-			$errors[] = array(
923
-				'error' => $l->t('PHP modules have been installed, but they are still listed as missing?'),
924
-				'hint' => $l->t('Please ask your server administrator to restart the web server.')
925
-			);
926
-		}
927
-
928
-		$errors = array_merge($errors, self::checkDatabaseVersion());
929
-
930
-		// Cache the result of this function
931
-		\OC::$server->getSession()->set('checkServer_succeeded', count($errors) == 0);
932
-
933
-		return $errors;
934
-	}
935
-
936
-	/**
937
-	 * Check the database version
938
-	 *
939
-	 * @return array errors array
940
-	 */
941
-	public static function checkDatabaseVersion() {
942
-		$l = \OC::$server->getL10N('lib');
943
-		$errors = array();
944
-		$dbType = \OC::$server->getSystemConfig()->getValue('dbtype', 'sqlite');
945
-		if ($dbType === 'pgsql') {
946
-			// check PostgreSQL version
947
-			try {
948
-				$result = \OC_DB::executeAudited('SHOW SERVER_VERSION');
949
-				$data = $result->fetchRow();
950
-				if (isset($data['server_version'])) {
951
-					$version = $data['server_version'];
952
-					if (version_compare($version, '9.0.0', '<')) {
953
-						$errors[] = array(
954
-							'error' => $l->t('PostgreSQL >= 9 required'),
955
-							'hint' => $l->t('Please upgrade your database version')
956
-						);
957
-					}
958
-				}
959
-			} catch (\Doctrine\DBAL\DBALException $e) {
960
-				$logger = \OC::$server->getLogger();
961
-				$logger->warning('Error occurred while checking PostgreSQL version, assuming >= 9');
962
-				$logger->logException($e);
963
-			}
964
-		}
965
-		return $errors;
966
-	}
967
-
968
-	/**
969
-	 * Check for correct file permissions of data directory
970
-	 *
971
-	 * @param string $dataDirectory
972
-	 * @return array arrays with error messages and hints
973
-	 */
974
-	public static function checkDataDirectoryPermissions($dataDirectory) {
975
-		if(\OC::$server->getConfig()->getSystemValue('check_data_directory_permissions', true) === false) {
976
-			return  [];
977
-		}
978
-		$l = \OC::$server->getL10N('lib');
979
-		$errors = [];
980
-		$permissionsModHint = $l->t('Please change the permissions to 0770 so that the directory'
981
-			. ' cannot be listed by other users.');
982
-		$perms = substr(decoct(@fileperms($dataDirectory)), -3);
983
-		if (substr($perms, -1) !== '0') {
984
-			chmod($dataDirectory, 0770);
985
-			clearstatcache();
986
-			$perms = substr(decoct(@fileperms($dataDirectory)), -3);
987
-			if ($perms[2] !== '0') {
988
-				$errors[] = [
989
-					'error' => $l->t('Your data directory is readable by other users'),
990
-					'hint' => $permissionsModHint
991
-				];
992
-			}
993
-		}
994
-		return $errors;
995
-	}
996
-
997
-	/**
998
-	 * Check that the data directory exists and is valid by
999
-	 * checking the existence of the ".ocdata" file.
1000
-	 *
1001
-	 * @param string $dataDirectory data directory path
1002
-	 * @return array errors found
1003
-	 */
1004
-	public static function checkDataDirectoryValidity($dataDirectory) {
1005
-		$l = \OC::$server->getL10N('lib');
1006
-		$errors = [];
1007
-		if ($dataDirectory[0] !== '/') {
1008
-			$errors[] = [
1009
-				'error' => $l->t('Your data directory must be an absolute path'),
1010
-				'hint' => $l->t('Check the value of "datadirectory" in your configuration')
1011
-			];
1012
-		}
1013
-		if (!file_exists($dataDirectory . '/.ocdata')) {
1014
-			$errors[] = [
1015
-				'error' => $l->t('Your data directory is invalid'),
1016
-				'hint' => $l->t('Ensure there is a file called ".ocdata"' .
1017
-					' in the root of the data directory.')
1018
-			];
1019
-		}
1020
-		return $errors;
1021
-	}
1022
-
1023
-	/**
1024
-	 * Check if the user is logged in, redirects to home if not. With
1025
-	 * redirect URL parameter to the request URI.
1026
-	 *
1027
-	 * @return void
1028
-	 */
1029
-	public static function checkLoggedIn() {
1030
-		// Check if we are a user
1031
-		if (!\OC::$server->getUserSession()->isLoggedIn()) {
1032
-			header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute(
1033
-						'core.login.showLoginForm',
1034
-						[
1035
-							'redirect_url' => \OC::$server->getRequest()->getRequestUri(),
1036
-						]
1037
-					)
1038
-			);
1039
-			exit();
1040
-		}
1041
-		// Redirect to 2FA challenge selection if 2FA challenge was not solved yet
1042
-		if (\OC::$server->getTwoFactorAuthManager()->needsSecondFactor(\OC::$server->getUserSession()->getUser())) {
1043
-			header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute('core.TwoFactorChallenge.selectChallenge'));
1044
-			exit();
1045
-		}
1046
-	}
1047
-
1048
-	/**
1049
-	 * Check if the user is a admin, redirects to home if not
1050
-	 *
1051
-	 * @return void
1052
-	 */
1053
-	public static function checkAdminUser() {
1054
-		OC_Util::checkLoggedIn();
1055
-		if (!OC_User::isAdminUser(OC_User::getUser())) {
1056
-			header('Location: ' . \OCP\Util::linkToAbsolute('', 'index.php'));
1057
-			exit();
1058
-		}
1059
-	}
1060
-
1061
-	/**
1062
-	 * Check if the user is a subadmin, redirects to home if not
1063
-	 *
1064
-	 * @return null|boolean $groups where the current user is subadmin
1065
-	 */
1066
-	public static function checkSubAdminUser() {
1067
-		OC_Util::checkLoggedIn();
1068
-		$userObject = \OC::$server->getUserSession()->getUser();
1069
-		$isSubAdmin = false;
1070
-		if($userObject !== null) {
1071
-			$isSubAdmin = \OC::$server->getGroupManager()->getSubAdmin()->isSubAdmin($userObject);
1072
-		}
1073
-
1074
-		if (!$isSubAdmin) {
1075
-			header('Location: ' . \OCP\Util::linkToAbsolute('', 'index.php'));
1076
-			exit();
1077
-		}
1078
-		return true;
1079
-	}
1080
-
1081
-	/**
1082
-	 * Returns the URL of the default page
1083
-	 * based on the system configuration and
1084
-	 * the apps visible for the current user
1085
-	 *
1086
-	 * @return string URL
1087
-	 * @suppress PhanDeprecatedFunction
1088
-	 */
1089
-	public static function getDefaultPageUrl() {
1090
-		$urlGenerator = \OC::$server->getURLGenerator();
1091
-		// Deny the redirect if the URL contains a @
1092
-		// This prevents unvalidated redirects like ?redirect_url=:[email protected]
1093
-		if (isset($_REQUEST['redirect_url']) && strpos($_REQUEST['redirect_url'], '@') === false) {
1094
-			$location = $urlGenerator->getAbsoluteURL(urldecode($_REQUEST['redirect_url']));
1095
-		} else {
1096
-			$defaultPage = \OC::$server->getConfig()->getAppValue('core', 'defaultpage');
1097
-			if ($defaultPage) {
1098
-				$location = $urlGenerator->getAbsoluteURL($defaultPage);
1099
-			} else {
1100
-				$appId = 'files';
1101
-				$config = \OC::$server->getConfig();
1102
-				$defaultApps = explode(',', $config->getSystemValue('defaultapp', 'files'));
1103
-				// find the first app that is enabled for the current user
1104
-				foreach ($defaultApps as $defaultApp) {
1105
-					$defaultApp = OC_App::cleanAppId(strip_tags($defaultApp));
1106
-					if (static::getAppManager()->isEnabledForUser($defaultApp)) {
1107
-						$appId = $defaultApp;
1108
-						break;
1109
-					}
1110
-				}
1111
-
1112
-				if($config->getSystemValue('htaccess.IgnoreFrontController', false) === true || getenv('front_controller_active') === 'true') {
1113
-					$location = $urlGenerator->getAbsoluteURL('/apps/' . $appId . '/');
1114
-				} else {
1115
-					$location = $urlGenerator->getAbsoluteURL('/index.php/apps/' . $appId . '/');
1116
-				}
1117
-			}
1118
-		}
1119
-		return $location;
1120
-	}
1121
-
1122
-	/**
1123
-	 * Redirect to the user default page
1124
-	 *
1125
-	 * @return void
1126
-	 */
1127
-	public static function redirectToDefaultPage() {
1128
-		$location = self::getDefaultPageUrl();
1129
-		header('Location: ' . $location);
1130
-		exit();
1131
-	}
1132
-
1133
-	/**
1134
-	 * get an id unique for this instance
1135
-	 *
1136
-	 * @return string
1137
-	 */
1138
-	public static function getInstanceId() {
1139
-		$id = \OC::$server->getSystemConfig()->getValue('instanceid', null);
1140
-		if (is_null($id)) {
1141
-			// We need to guarantee at least one letter in instanceid so it can be used as the session_name
1142
-			$id = 'oc' . \OC::$server->getSecureRandom()->generate(10, \OCP\Security\ISecureRandom::CHAR_LOWER.\OCP\Security\ISecureRandom::CHAR_DIGITS);
1143
-			\OC::$server->getSystemConfig()->setValue('instanceid', $id);
1144
-		}
1145
-		return $id;
1146
-	}
1147
-
1148
-	/**
1149
-	 * Public function to sanitize HTML
1150
-	 *
1151
-	 * This function is used to sanitize HTML and should be applied on any
1152
-	 * string or array of strings before displaying it on a web page.
1153
-	 *
1154
-	 * @param string|array $value
1155
-	 * @return string|array an array of sanitized strings or a single sanitized string, depends on the input parameter.
1156
-	 */
1157
-	public static function sanitizeHTML($value) {
1158
-		if (is_array($value)) {
1159
-			$value = array_map(function($value) {
1160
-				return self::sanitizeHTML($value);
1161
-			}, $value);
1162
-		} else {
1163
-			// Specify encoding for PHP<5.4
1164
-			$value = htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
1165
-		}
1166
-		return $value;
1167
-	}
1168
-
1169
-	/**
1170
-	 * Public function to encode url parameters
1171
-	 *
1172
-	 * This function is used to encode path to file before output.
1173
-	 * Encoding is done according to RFC 3986 with one exception:
1174
-	 * Character '/' is preserved as is.
1175
-	 *
1176
-	 * @param string $component part of URI to encode
1177
-	 * @return string
1178
-	 */
1179
-	public static function encodePath($component) {
1180
-		$encoded = rawurlencode($component);
1181
-		$encoded = str_replace('%2F', '/', $encoded);
1182
-		return $encoded;
1183
-	}
1184
-
1185
-
1186
-	public function createHtaccessTestFile(\OCP\IConfig $config) {
1187
-		// php dev server does not support htaccess
1188
-		if (php_sapi_name() === 'cli-server') {
1189
-			return false;
1190
-		}
1191
-
1192
-		// testdata
1193
-		$fileName = '/htaccesstest.txt';
1194
-		$testContent = 'This is used for testing whether htaccess is properly enabled to disallow access from the outside. This file can be safely removed.';
1195
-
1196
-		// creating a test file
1197
-		$testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
1198
-
1199
-		if (file_exists($testFile)) {// already running this test, possible recursive call
1200
-			return false;
1201
-		}
1202
-
1203
-		$fp = @fopen($testFile, 'w');
1204
-		if (!$fp) {
1205
-			throw new OC\HintException('Can\'t create test file to check for working .htaccess file.',
1206
-				'Make sure it is possible for the webserver to write to ' . $testFile);
1207
-		}
1208
-		fwrite($fp, $testContent);
1209
-		fclose($fp);
1210
-
1211
-		return $testContent;
1212
-	}
1213
-
1214
-	/**
1215
-	 * Check if the .htaccess file is working
1216
-	 * @param \OCP\IConfig $config
1217
-	 * @return bool
1218
-	 * @throws Exception
1219
-	 * @throws \OC\HintException If the test file can't get written.
1220
-	 */
1221
-	public function isHtaccessWorking(\OCP\IConfig $config) {
1222
-
1223
-		if (\OC::$CLI || !$config->getSystemValue('check_for_working_htaccess', true)) {
1224
-			return true;
1225
-		}
1226
-
1227
-		$testContent = $this->createHtaccessTestFile($config);
1228
-		if ($testContent === false) {
1229
-			return false;
1230
-		}
1231
-
1232
-		$fileName = '/htaccesstest.txt';
1233
-		$testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
1234
-
1235
-		// accessing the file via http
1236
-		$url = \OC::$server->getURLGenerator()->getAbsoluteURL(OC::$WEBROOT . '/data' . $fileName);
1237
-		try {
1238
-			$content = \OC::$server->getHTTPClientService()->newClient()->get($url)->getBody();
1239
-		} catch (\Exception $e) {
1240
-			$content = false;
1241
-		}
1242
-
1243
-		// cleanup
1244
-		@unlink($testFile);
1245
-
1246
-		/*
69
+    public static $scripts = array();
70
+    public static $styles = array();
71
+    public static $headers = array();
72
+    private static $rootMounted = false;
73
+    private static $fsSetup = false;
74
+
75
+    /** @var array Local cache of version.php */
76
+    private static $versionCache = null;
77
+
78
+    protected static function getAppManager() {
79
+        return \OC::$server->getAppManager();
80
+    }
81
+
82
+    private static function initLocalStorageRootFS() {
83
+        // mount local file backend as root
84
+        $configDataDirectory = \OC::$server->getSystemConfig()->getValue("datadirectory", OC::$SERVERROOT . "/data");
85
+        //first set up the local "root" storage
86
+        \OC\Files\Filesystem::initMountManager();
87
+        if (!self::$rootMounted) {
88
+            \OC\Files\Filesystem::mount('\OC\Files\Storage\Local', array('datadir' => $configDataDirectory), '/');
89
+            self::$rootMounted = true;
90
+        }
91
+    }
92
+
93
+    /**
94
+     * mounting an object storage as the root fs will in essence remove the
95
+     * necessity of a data folder being present.
96
+     * TODO make home storage aware of this and use the object storage instead of local disk access
97
+     *
98
+     * @param array $config containing 'class' and optional 'arguments'
99
+     * @suppress PhanDeprecatedFunction
100
+     */
101
+    private static function initObjectStoreRootFS($config) {
102
+        // check misconfiguration
103
+        if (empty($config['class'])) {
104
+            \OCP\Util::writeLog('files', 'No class given for objectstore', ILogger::ERROR);
105
+        }
106
+        if (!isset($config['arguments'])) {
107
+            $config['arguments'] = array();
108
+        }
109
+
110
+        // instantiate object store implementation
111
+        $name = $config['class'];
112
+        if (strpos($name, 'OCA\\') === 0 && substr_count($name, '\\') >= 2) {
113
+            $segments = explode('\\', $name);
114
+            OC_App::loadApp(strtolower($segments[1]));
115
+        }
116
+        $config['arguments']['objectstore'] = new $config['class']($config['arguments']);
117
+        // mount with plain / root object store implementation
118
+        $config['class'] = '\OC\Files\ObjectStore\ObjectStoreStorage';
119
+
120
+        // mount object storage as root
121
+        \OC\Files\Filesystem::initMountManager();
122
+        if (!self::$rootMounted) {
123
+            \OC\Files\Filesystem::mount($config['class'], $config['arguments'], '/');
124
+            self::$rootMounted = true;
125
+        }
126
+    }
127
+
128
+    /**
129
+     * mounting an object storage as the root fs will in essence remove the
130
+     * necessity of a data folder being present.
131
+     *
132
+     * @param array $config containing 'class' and optional 'arguments'
133
+     * @suppress PhanDeprecatedFunction
134
+     */
135
+    private static function initObjectStoreMultibucketRootFS($config) {
136
+        // check misconfiguration
137
+        if (empty($config['class'])) {
138
+            \OCP\Util::writeLog('files', 'No class given for objectstore', ILogger::ERROR);
139
+        }
140
+        if (!isset($config['arguments'])) {
141
+            $config['arguments'] = array();
142
+        }
143
+
144
+        // instantiate object store implementation
145
+        $name = $config['class'];
146
+        if (strpos($name, 'OCA\\') === 0 && substr_count($name, '\\') >= 2) {
147
+            $segments = explode('\\', $name);
148
+            OC_App::loadApp(strtolower($segments[1]));
149
+        }
150
+
151
+        if (!isset($config['arguments']['bucket'])) {
152
+            $config['arguments']['bucket'] = '';
153
+        }
154
+        // put the root FS always in first bucket for multibucket configuration
155
+        $config['arguments']['bucket'] .= '0';
156
+
157
+        $config['arguments']['objectstore'] = new $config['class']($config['arguments']);
158
+        // mount with plain / root object store implementation
159
+        $config['class'] = '\OC\Files\ObjectStore\ObjectStoreStorage';
160
+
161
+        // mount object storage as root
162
+        \OC\Files\Filesystem::initMountManager();
163
+        if (!self::$rootMounted) {
164
+            \OC\Files\Filesystem::mount($config['class'], $config['arguments'], '/');
165
+            self::$rootMounted = true;
166
+        }
167
+    }
168
+
169
+    /**
170
+     * Can be set up
171
+     *
172
+     * @param string $user
173
+     * @return boolean
174
+     * @description configure the initial filesystem based on the configuration
175
+     * @suppress PhanDeprecatedFunction
176
+     * @suppress PhanAccessMethodInternal
177
+     */
178
+    public static function setupFS($user = '') {
179
+        //setting up the filesystem twice can only lead to trouble
180
+        if (self::$fsSetup) {
181
+            return false;
182
+        }
183
+
184
+        \OC::$server->getEventLogger()->start('setup_fs', 'Setup filesystem');
185
+
186
+        // If we are not forced to load a specific user we load the one that is logged in
187
+        if ($user === null) {
188
+            $user = '';
189
+        } else if ($user == "" && \OC::$server->getUserSession()->isLoggedIn()) {
190
+            $user = OC_User::getUser();
191
+        }
192
+
193
+        // load all filesystem apps before, so no setup-hook gets lost
194
+        OC_App::loadApps(array('filesystem'));
195
+
196
+        // the filesystem will finish when $user is not empty,
197
+        // mark fs setup here to avoid doing the setup from loading
198
+        // OC_Filesystem
199
+        if ($user != '') {
200
+            self::$fsSetup = true;
201
+        }
202
+
203
+        \OC\Files\Filesystem::initMountManager();
204
+
205
+        \OC\Files\Filesystem::logWarningWhenAddingStorageWrapper(false);
206
+        \OC\Files\Filesystem::addStorageWrapper('mount_options', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
207
+            if ($storage->instanceOfStorage('\OC\Files\Storage\Common')) {
208
+                /** @var \OC\Files\Storage\Common $storage */
209
+                $storage->setMountOptions($mount->getOptions());
210
+            }
211
+            return $storage;
212
+        });
213
+
214
+        \OC\Files\Filesystem::addStorageWrapper('enable_sharing', function ($mountPoint, \OCP\Files\Storage\IStorage $storage, \OCP\Files\Mount\IMountPoint $mount) {
215
+            if (!$mount->getOption('enable_sharing', true)) {
216
+                return new \OC\Files\Storage\Wrapper\PermissionsMask([
217
+                    'storage' => $storage,
218
+                    'mask' => \OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_SHARE
219
+                ]);
220
+            }
221
+            return $storage;
222
+        });
223
+
224
+        // install storage availability wrapper, before most other wrappers
225
+        \OC\Files\Filesystem::addStorageWrapper('oc_availability', function ($mountPoint, \OCP\Files\Storage\IStorage $storage) {
226
+            if (!$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) {
227
+                return new \OC\Files\Storage\Wrapper\Availability(['storage' => $storage]);
228
+            }
229
+            return $storage;
230
+        });
231
+
232
+        \OC\Files\Filesystem::addStorageWrapper('oc_encoding', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
233
+            if ($mount->getOption('encoding_compatibility', false) && !$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) {
234
+                return new \OC\Files\Storage\Wrapper\Encoding(['storage' => $storage]);
235
+            }
236
+            return $storage;
237
+        });
238
+
239
+        \OC\Files\Filesystem::addStorageWrapper('oc_quota', function ($mountPoint, $storage) {
240
+            // set up quota for home storages, even for other users
241
+            // which can happen when using sharing
242
+
243
+            /**
244
+             * @var \OC\Files\Storage\Storage $storage
245
+             */
246
+            if ($storage->instanceOfStorage('\OC\Files\Storage\Home')
247
+                || $storage->instanceOfStorage('\OC\Files\ObjectStore\HomeObjectStoreStorage')
248
+            ) {
249
+                /** @var \OC\Files\Storage\Home $storage */
250
+                if (is_object($storage->getUser())) {
251
+                    $user = $storage->getUser()->getUID();
252
+                    $quota = OC_Util::getUserQuota($user);
253
+                    if ($quota !== \OCP\Files\FileInfo::SPACE_UNLIMITED) {
254
+                        return new \OC\Files\Storage\Wrapper\Quota(array('storage' => $storage, 'quota' => $quota, 'root' => 'files'));
255
+                    }
256
+                }
257
+            }
258
+
259
+            return $storage;
260
+        });
261
+
262
+        OC_Hook::emit('OC_Filesystem', 'preSetup', array('user' => $user));
263
+        \OC\Files\Filesystem::logWarningWhenAddingStorageWrapper(true);
264
+
265
+        //check if we are using an object storage
266
+        $objectStore = \OC::$server->getSystemConfig()->getValue('objectstore', null);
267
+        $objectStoreMultibucket = \OC::$server->getSystemConfig()->getValue('objectstore_multibucket', null);
268
+
269
+        // use the same order as in ObjectHomeMountProvider
270
+        if (isset($objectStoreMultibucket)) {
271
+            self::initObjectStoreMultibucketRootFS($objectStoreMultibucket);
272
+        } elseif (isset($objectStore)) {
273
+            self::initObjectStoreRootFS($objectStore);
274
+        } else {
275
+            self::initLocalStorageRootFS();
276
+        }
277
+
278
+        if ($user != '' && !\OC::$server->getUserManager()->userExists($user)) {
279
+            \OC::$server->getEventLogger()->end('setup_fs');
280
+            return false;
281
+        }
282
+
283
+        //if we aren't logged in, there is no use to set up the filesystem
284
+        if ($user != "") {
285
+
286
+            $userDir = '/' . $user . '/files';
287
+
288
+            //jail the user into his "home" directory
289
+            \OC\Files\Filesystem::init($user, $userDir);
290
+
291
+            OC_Hook::emit('OC_Filesystem', 'setup', array('user' => $user, 'user_dir' => $userDir));
292
+        }
293
+        \OC::$server->getEventLogger()->end('setup_fs');
294
+        return true;
295
+    }
296
+
297
+    /**
298
+     * check if a password is required for each public link
299
+     *
300
+     * @return boolean
301
+     * @suppress PhanDeprecatedFunction
302
+     */
303
+    public static function isPublicLinkPasswordRequired() {
304
+        $enforcePassword = \OC::$server->getConfig()->getAppValue('core', 'shareapi_enforce_links_password', 'no');
305
+        return $enforcePassword === 'yes';
306
+    }
307
+
308
+    /**
309
+     * check if sharing is disabled for the current user
310
+     * @param IConfig $config
311
+     * @param IGroupManager $groupManager
312
+     * @param IUser|null $user
313
+     * @return bool
314
+     */
315
+    public static function isSharingDisabledForUser(IConfig $config, IGroupManager $groupManager, $user) {
316
+        if ($config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') {
317
+            $groupsList = $config->getAppValue('core', 'shareapi_exclude_groups_list', '');
318
+            $excludedGroups = json_decode($groupsList);
319
+            if (is_null($excludedGroups)) {
320
+                $excludedGroups = explode(',', $groupsList);
321
+                $newValue = json_encode($excludedGroups);
322
+                $config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue);
323
+            }
324
+            $usersGroups = $groupManager->getUserGroupIds($user);
325
+            if (!empty($usersGroups)) {
326
+                $remainingGroups = array_diff($usersGroups, $excludedGroups);
327
+                // if the user is only in groups which are disabled for sharing then
328
+                // sharing is also disabled for the user
329
+                if (empty($remainingGroups)) {
330
+                    return true;
331
+                }
332
+            }
333
+        }
334
+        return false;
335
+    }
336
+
337
+    /**
338
+     * check if share API enforces a default expire date
339
+     *
340
+     * @return boolean
341
+     * @suppress PhanDeprecatedFunction
342
+     */
343
+    public static function isDefaultExpireDateEnforced() {
344
+        $isDefaultExpireDateEnabled = \OC::$server->getConfig()->getAppValue('core', 'shareapi_default_expire_date', 'no');
345
+        $enforceDefaultExpireDate = false;
346
+        if ($isDefaultExpireDateEnabled === 'yes') {
347
+            $value = \OC::$server->getConfig()->getAppValue('core', 'shareapi_enforce_expire_date', 'no');
348
+            $enforceDefaultExpireDate = $value === 'yes';
349
+        }
350
+
351
+        return $enforceDefaultExpireDate;
352
+    }
353
+
354
+    /**
355
+     * Get the quota of a user
356
+     *
357
+     * @param string $userId
358
+     * @return float Quota bytes
359
+     */
360
+    public static function getUserQuota($userId) {
361
+        $user = \OC::$server->getUserManager()->get($userId);
362
+        if (is_null($user)) {
363
+            return \OCP\Files\FileInfo::SPACE_UNLIMITED;
364
+        }
365
+        $userQuota = $user->getQuota();
366
+        if($userQuota === 'none') {
367
+            return \OCP\Files\FileInfo::SPACE_UNLIMITED;
368
+        }
369
+        return OC_Helper::computerFileSize($userQuota);
370
+    }
371
+
372
+    /**
373
+     * copies the skeleton to the users /files
374
+     *
375
+     * @param String $userId
376
+     * @param \OCP\Files\Folder $userDirectory
377
+     * @throws \RuntimeException
378
+     * @suppress PhanDeprecatedFunction
379
+     */
380
+    public static function copySkeleton($userId, \OCP\Files\Folder $userDirectory) {
381
+
382
+        $plainSkeletonDirectory = \OC::$server->getConfig()->getSystemValue('skeletondirectory', \OC::$SERVERROOT . '/core/skeleton');
383
+        $userLang = \OC::$server->getL10NFactory()->findLanguage();
384
+        $skeletonDirectory = str_replace('{lang}', $userLang, $plainSkeletonDirectory);
385
+
386
+        if (!file_exists($skeletonDirectory)) {
387
+            $dialectStart = strpos($userLang, '_');
388
+            if ($dialectStart !== false) {
389
+                $skeletonDirectory = str_replace('{lang}', substr($userLang, 0, $dialectStart), $plainSkeletonDirectory);
390
+            }
391
+            if ($dialectStart === false || !file_exists($skeletonDirectory)) {
392
+                $skeletonDirectory = str_replace('{lang}', 'default', $plainSkeletonDirectory);
393
+            }
394
+            if (!file_exists($skeletonDirectory)) {
395
+                $skeletonDirectory = '';
396
+            }
397
+        }
398
+
399
+        $instanceId = \OC::$server->getConfig()->getSystemValue('instanceid', '');
400
+
401
+        if ($instanceId === null) {
402
+            throw new \RuntimeException('no instance id!');
403
+        }
404
+        $appdata = 'appdata_' . $instanceId;
405
+        if ($userId === $appdata) {
406
+            throw new \RuntimeException('username is reserved name: ' . $appdata);
407
+        }
408
+
409
+        if (!empty($skeletonDirectory)) {
410
+            \OCP\Util::writeLog(
411
+                'files_skeleton',
412
+                'copying skeleton for '.$userId.' from '.$skeletonDirectory.' to '.$userDirectory->getFullPath('/'),
413
+                ILogger::DEBUG
414
+            );
415
+            self::copyr($skeletonDirectory, $userDirectory);
416
+            // update the file cache
417
+            $userDirectory->getStorage()->getScanner()->scan('', \OC\Files\Cache\Scanner::SCAN_RECURSIVE);
418
+        }
419
+    }
420
+
421
+    /**
422
+     * copies a directory recursively by using streams
423
+     *
424
+     * @param string $source
425
+     * @param \OCP\Files\Folder $target
426
+     * @return void
427
+     */
428
+    public static function copyr($source, \OCP\Files\Folder $target) {
429
+        $logger = \OC::$server->getLogger();
430
+
431
+        // Verify if folder exists
432
+        $dir = opendir($source);
433
+        if($dir === false) {
434
+            $logger->error(sprintf('Could not opendir "%s"', $source), ['app' => 'core']);
435
+            return;
436
+        }
437
+
438
+        // Copy the files
439
+        while (false !== ($file = readdir($dir))) {
440
+            if (!\OC\Files\Filesystem::isIgnoredDir($file)) {
441
+                if (is_dir($source . '/' . $file)) {
442
+                    $child = $target->newFolder($file);
443
+                    self::copyr($source . '/' . $file, $child);
444
+                } else {
445
+                    $child = $target->newFile($file);
446
+                    $sourceStream = fopen($source . '/' . $file, 'r');
447
+                    if($sourceStream === false) {
448
+                        $logger->error(sprintf('Could not fopen "%s"', $source . '/' . $file), ['app' => 'core']);
449
+                        closedir($dir);
450
+                        return;
451
+                    }
452
+                    stream_copy_to_stream($sourceStream, $child->fopen('w'));
453
+                }
454
+            }
455
+        }
456
+        closedir($dir);
457
+    }
458
+
459
+    /**
460
+     * @return void
461
+     * @suppress PhanUndeclaredMethod
462
+     */
463
+    public static function tearDownFS() {
464
+        \OC\Files\Filesystem::tearDown();
465
+        \OC::$server->getRootFolder()->clearCache();
466
+        self::$fsSetup = false;
467
+        self::$rootMounted = false;
468
+    }
469
+
470
+    /**
471
+     * get the current installed version of ownCloud
472
+     *
473
+     * @return array
474
+     */
475
+    public static function getVersion() {
476
+        OC_Util::loadVersion();
477
+        return self::$versionCache['OC_Version'];
478
+    }
479
+
480
+    /**
481
+     * get the current installed version string of ownCloud
482
+     *
483
+     * @return string
484
+     */
485
+    public static function getVersionString() {
486
+        OC_Util::loadVersion();
487
+        return self::$versionCache['OC_VersionString'];
488
+    }
489
+
490
+    /**
491
+     * @deprecated the value is of no use anymore
492
+     * @return string
493
+     */
494
+    public static function getEditionString() {
495
+        return '';
496
+    }
497
+
498
+    /**
499
+     * @description get the update channel of the current installed of ownCloud.
500
+     * @return string
501
+     */
502
+    public static function getChannel() {
503
+        OC_Util::loadVersion();
504
+        return \OC::$server->getConfig()->getSystemValue('updater.release.channel', self::$versionCache['OC_Channel']);
505
+    }
506
+
507
+    /**
508
+     * @description get the build number of the current installed of ownCloud.
509
+     * @return string
510
+     */
511
+    public static function getBuild() {
512
+        OC_Util::loadVersion();
513
+        return self::$versionCache['OC_Build'];
514
+    }
515
+
516
+    /**
517
+     * @description load the version.php into the session as cache
518
+     * @suppress PhanUndeclaredVariable
519
+     */
520
+    private static function loadVersion() {
521
+        if (self::$versionCache !== null) {
522
+            return;
523
+        }
524
+
525
+        $timestamp = filemtime(OC::$SERVERROOT . '/version.php');
526
+        require OC::$SERVERROOT . '/version.php';
527
+        /** @var $timestamp int */
528
+        self::$versionCache['OC_Version_Timestamp'] = $timestamp;
529
+        /** @var $OC_Version string */
530
+        self::$versionCache['OC_Version'] = $OC_Version;
531
+        /** @var $OC_VersionString string */
532
+        self::$versionCache['OC_VersionString'] = $OC_VersionString;
533
+        /** @var $OC_Build string */
534
+        self::$versionCache['OC_Build'] = $OC_Build;
535
+
536
+        /** @var $OC_Channel string */
537
+        self::$versionCache['OC_Channel'] = $OC_Channel;
538
+    }
539
+
540
+    /**
541
+     * generates a path for JS/CSS files. If no application is provided it will create the path for core.
542
+     *
543
+     * @param string $application application to get the files from
544
+     * @param string $directory directory within this application (css, js, vendor, etc)
545
+     * @param string $file the file inside of the above folder
546
+     * @return string the path
547
+     */
548
+    private static function generatePath($application, $directory, $file) {
549
+        if (is_null($file)) {
550
+            $file = $application;
551
+            $application = "";
552
+        }
553
+        if (!empty($application)) {
554
+            return "$application/$directory/$file";
555
+        } else {
556
+            return "$directory/$file";
557
+        }
558
+    }
559
+
560
+    /**
561
+     * add a javascript file
562
+     *
563
+     * @param string $application application id
564
+     * @param string|null $file filename
565
+     * @param bool $prepend prepend the Script to the beginning of the list
566
+     * @return void
567
+     */
568
+    public static function addScript($application, $file = null, $prepend = false) {
569
+        $path = OC_Util::generatePath($application, 'js', $file);
570
+
571
+        // core js files need separate handling
572
+        if ($application !== 'core' && $file !== null) {
573
+            self::addTranslations ( $application );
574
+        }
575
+        self::addExternalResource($application, $prepend, $path, "script");
576
+    }
577
+
578
+    /**
579
+     * add a javascript file from the vendor sub folder
580
+     *
581
+     * @param string $application application id
582
+     * @param string|null $file filename
583
+     * @param bool $prepend prepend the Script to the beginning of the list
584
+     * @return void
585
+     */
586
+    public static function addVendorScript($application, $file = null, $prepend = false) {
587
+        $path = OC_Util::generatePath($application, 'vendor', $file);
588
+        self::addExternalResource($application, $prepend, $path, "script");
589
+    }
590
+
591
+    /**
592
+     * add a translation JS file
593
+     *
594
+     * @param string $application application id
595
+     * @param string|null $languageCode language code, defaults to the current language
596
+     * @param bool|null $prepend prepend the Script to the beginning of the list
597
+     */
598
+    public static function addTranslations($application, $languageCode = null, $prepend = false) {
599
+        if (is_null($languageCode)) {
600
+            $languageCode = \OC::$server->getL10NFactory()->findLanguage($application);
601
+        }
602
+        if (!empty($application)) {
603
+            $path = "$application/l10n/$languageCode";
604
+        } else {
605
+            $path = "l10n/$languageCode";
606
+        }
607
+        self::addExternalResource($application, $prepend, $path, "script");
608
+    }
609
+
610
+    /**
611
+     * add a css file
612
+     *
613
+     * @param string $application application id
614
+     * @param string|null $file filename
615
+     * @param bool $prepend prepend the Style to the beginning of the list
616
+     * @return void
617
+     */
618
+    public static function addStyle($application, $file = null, $prepend = false) {
619
+        $path = OC_Util::generatePath($application, 'css', $file);
620
+        self::addExternalResource($application, $prepend, $path, "style");
621
+    }
622
+
623
+    /**
624
+     * add a css file from the vendor sub folder
625
+     *
626
+     * @param string $application application id
627
+     * @param string|null $file filename
628
+     * @param bool $prepend prepend the Style to the beginning of the list
629
+     * @return void
630
+     */
631
+    public static function addVendorStyle($application, $file = null, $prepend = false) {
632
+        $path = OC_Util::generatePath($application, 'vendor', $file);
633
+        self::addExternalResource($application, $prepend, $path, "style");
634
+    }
635
+
636
+    /**
637
+     * add an external resource css/js file
638
+     *
639
+     * @param string $application application id
640
+     * @param bool $prepend prepend the file to the beginning of the list
641
+     * @param string $path
642
+     * @param string $type (script or style)
643
+     * @return void
644
+     */
645
+    private static function addExternalResource($application, $prepend, $path, $type = "script") {
646
+
647
+        if ($type === "style") {
648
+            if (!in_array($path, self::$styles)) {
649
+                if ($prepend === true) {
650
+                    array_unshift ( self::$styles, $path );
651
+                } else {
652
+                    self::$styles[] = $path;
653
+                }
654
+            }
655
+        } elseif ($type === "script") {
656
+            if (!in_array($path, self::$scripts)) {
657
+                if ($prepend === true) {
658
+                    array_unshift ( self::$scripts, $path );
659
+                } else {
660
+                    self::$scripts [] = $path;
661
+                }
662
+            }
663
+        }
664
+    }
665
+
666
+    /**
667
+     * Add a custom element to the header
668
+     * If $text is null then the element will be written as empty element.
669
+     * So use "" to get a closing tag.
670
+     * @param string $tag tag name of the element
671
+     * @param array $attributes array of attributes for the element
672
+     * @param string $text the text content for the element
673
+     */
674
+    public static function addHeader($tag, $attributes, $text=null) {
675
+        self::$headers[] = array(
676
+            'tag' => $tag,
677
+            'attributes' => $attributes,
678
+            'text' => $text
679
+        );
680
+    }
681
+
682
+    /**
683
+     * check if the current server configuration is suitable for ownCloud
684
+     *
685
+     * @param \OC\SystemConfig $config
686
+     * @return array arrays with error messages and hints
687
+     */
688
+    public static function checkServer(\OC\SystemConfig $config) {
689
+        $l = \OC::$server->getL10N('lib');
690
+        $errors = array();
691
+        $CONFIG_DATADIRECTORY = $config->getValue('datadirectory', OC::$SERVERROOT . '/data');
692
+
693
+        if (!self::needUpgrade($config) && $config->getValue('installed', false)) {
694
+            // this check needs to be done every time
695
+            $errors = self::checkDataDirectoryValidity($CONFIG_DATADIRECTORY);
696
+        }
697
+
698
+        // Assume that if checkServer() succeeded before in this session, then all is fine.
699
+        if (\OC::$server->getSession()->exists('checkServer_succeeded') && \OC::$server->getSession()->get('checkServer_succeeded')) {
700
+            return $errors;
701
+        }
702
+
703
+        $webServerRestart = false;
704
+        $setup = new \OC\Setup(
705
+            $config,
706
+            \OC::$server->getIniWrapper(),
707
+            \OC::$server->getL10N('lib'),
708
+            \OC::$server->query(\OCP\Defaults::class),
709
+            \OC::$server->getLogger(),
710
+            \OC::$server->getSecureRandom(),
711
+            \OC::$server->query(\OC\Installer::class)
712
+        );
713
+
714
+        $urlGenerator = \OC::$server->getURLGenerator();
715
+
716
+        $availableDatabases = $setup->getSupportedDatabases();
717
+        if (empty($availableDatabases)) {
718
+            $errors[] = array(
719
+                'error' => $l->t('No database drivers (sqlite, mysql, or postgresql) installed.'),
720
+                'hint' => '' //TODO: sane hint
721
+            );
722
+            $webServerRestart = true;
723
+        }
724
+
725
+        // Check if config folder is writable.
726
+        if(!OC_Helper::isReadOnlyConfigEnabled()) {
727
+            if (!is_writable(OC::$configDir) or !is_readable(OC::$configDir)) {
728
+                $errors[] = array(
729
+                    'error' => $l->t('Cannot write into "config" directory'),
730
+                    'hint' => $l->t('This can usually be fixed by giving the webserver write access to the config directory. See %s',
731
+                        [$urlGenerator->linkToDocs('admin-dir_permissions')])
732
+                );
733
+            }
734
+        }
735
+
736
+        // Check if there is a writable install folder.
737
+        if ($config->getValue('appstoreenabled', true)) {
738
+            if (OC_App::getInstallPath() === null
739
+                || !is_writable(OC_App::getInstallPath())
740
+                || !is_readable(OC_App::getInstallPath())
741
+            ) {
742
+                $errors[] = array(
743
+                    'error' => $l->t('Cannot write into "apps" directory'),
744
+                    'hint' => $l->t('This can usually be fixed by giving the webserver write access to the apps directory'
745
+                        . ' or disabling the appstore in the config file. See %s',
746
+                        [$urlGenerator->linkToDocs('admin-dir_permissions')])
747
+                );
748
+            }
749
+        }
750
+        // Create root dir.
751
+        if ($config->getValue('installed', false)) {
752
+            if (!is_dir($CONFIG_DATADIRECTORY)) {
753
+                $success = @mkdir($CONFIG_DATADIRECTORY);
754
+                if ($success) {
755
+                    $errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
756
+                } else {
757
+                    $errors[] = [
758
+                        'error' => $l->t('Cannot create "data" directory'),
759
+                        'hint' => $l->t('This can usually be fixed by giving the webserver write access to the root directory. See %s',
760
+                            [$urlGenerator->linkToDocs('admin-dir_permissions')])
761
+                    ];
762
+                }
763
+            } else if (!is_writable($CONFIG_DATADIRECTORY) or !is_readable($CONFIG_DATADIRECTORY)) {
764
+                //common hint for all file permissions error messages
765
+                $permissionsHint = $l->t('Permissions can usually be fixed by giving the webserver write access to the root directory. See %s.',
766
+                    [$urlGenerator->linkToDocs('admin-dir_permissions')]);
767
+                $errors[] = [
768
+                    'error' => 'Your data directory is not writable',
769
+                    'hint' => $permissionsHint
770
+                ];
771
+            } else {
772
+                $errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
773
+            }
774
+        }
775
+
776
+        if (!OC_Util::isSetLocaleWorking()) {
777
+            $errors[] = array(
778
+                'error' => $l->t('Setting locale to %s failed',
779
+                    array('en_US.UTF-8/fr_FR.UTF-8/es_ES.UTF-8/de_DE.UTF-8/ru_RU.UTF-8/'
780
+                        . 'pt_BR.UTF-8/it_IT.UTF-8/ja_JP.UTF-8/zh_CN.UTF-8')),
781
+                'hint' => $l->t('Please install one of these locales on your system and restart your webserver.')
782
+            );
783
+        }
784
+
785
+        // Contains the dependencies that should be checked against
786
+        // classes = class_exists
787
+        // functions = function_exists
788
+        // defined = defined
789
+        // ini = ini_get
790
+        // If the dependency is not found the missing module name is shown to the EndUser
791
+        // When adding new checks always verify that they pass on Travis as well
792
+        // for ini settings, see https://github.com/owncloud/administration/blob/master/travis-ci/custom.ini
793
+        $dependencies = array(
794
+            'classes' => array(
795
+                'ZipArchive' => 'zip',
796
+                'DOMDocument' => 'dom',
797
+                'XMLWriter' => 'XMLWriter',
798
+                'XMLReader' => 'XMLReader',
799
+            ),
800
+            'functions' => [
801
+                'xml_parser_create' => 'libxml',
802
+                'mb_strcut' => 'mb multibyte',
803
+                'ctype_digit' => 'ctype',
804
+                'json_encode' => 'JSON',
805
+                'gd_info' => 'GD',
806
+                'gzencode' => 'zlib',
807
+                'iconv' => 'iconv',
808
+                'simplexml_load_string' => 'SimpleXML',
809
+                'hash' => 'HASH Message Digest Framework',
810
+                'curl_init' => 'cURL',
811
+                'openssl_verify' => 'OpenSSL',
812
+            ],
813
+            'defined' => array(
814
+                'PDO::ATTR_DRIVER_NAME' => 'PDO'
815
+            ),
816
+            'ini' => [
817
+                'default_charset' => 'UTF-8',
818
+            ],
819
+        );
820
+        $missingDependencies = array();
821
+        $invalidIniSettings = [];
822
+        $moduleHint = $l->t('Please ask your server administrator to install the module.');
823
+
824
+        /**
825
+         * FIXME: The dependency check does not work properly on HHVM on the moment
826
+         *        and prevents installation. Once HHVM is more compatible with our
827
+         *        approach to check for these values we should re-enable those
828
+         *        checks.
829
+         */
830
+        $iniWrapper = \OC::$server->getIniWrapper();
831
+        if (!self::runningOnHhvm()) {
832
+            foreach ($dependencies['classes'] as $class => $module) {
833
+                if (!class_exists($class)) {
834
+                    $missingDependencies[] = $module;
835
+                }
836
+            }
837
+            foreach ($dependencies['functions'] as $function => $module) {
838
+                if (!function_exists($function)) {
839
+                    $missingDependencies[] = $module;
840
+                }
841
+            }
842
+            foreach ($dependencies['defined'] as $defined => $module) {
843
+                if (!defined($defined)) {
844
+                    $missingDependencies[] = $module;
845
+                }
846
+            }
847
+            foreach ($dependencies['ini'] as $setting => $expected) {
848
+                if (is_bool($expected)) {
849
+                    if ($iniWrapper->getBool($setting) !== $expected) {
850
+                        $invalidIniSettings[] = [$setting, $expected];
851
+                    }
852
+                }
853
+                if (is_int($expected)) {
854
+                    if ($iniWrapper->getNumeric($setting) !== $expected) {
855
+                        $invalidIniSettings[] = [$setting, $expected];
856
+                    }
857
+                }
858
+                if (is_string($expected)) {
859
+                    if (strtolower($iniWrapper->getString($setting)) !== strtolower($expected)) {
860
+                        $invalidIniSettings[] = [$setting, $expected];
861
+                    }
862
+                }
863
+            }
864
+        }
865
+
866
+        foreach($missingDependencies as $missingDependency) {
867
+            $errors[] = array(
868
+                'error' => $l->t('PHP module %s not installed.', array($missingDependency)),
869
+                'hint' => $moduleHint
870
+            );
871
+            $webServerRestart = true;
872
+        }
873
+        foreach($invalidIniSettings as $setting) {
874
+            if(is_bool($setting[1])) {
875
+                $setting[1] = $setting[1] ? 'on' : 'off';
876
+            }
877
+            $errors[] = [
878
+                'error' => $l->t('PHP setting "%s" is not set to "%s".', [$setting[0], var_export($setting[1], true)]),
879
+                'hint' =>  $l->t('Adjusting this setting in php.ini will make Nextcloud run again')
880
+            ];
881
+            $webServerRestart = true;
882
+        }
883
+
884
+        /**
885
+         * The mbstring.func_overload check can only be performed if the mbstring
886
+         * module is installed as it will return null if the checking setting is
887
+         * not available and thus a check on the boolean value fails.
888
+         *
889
+         * TODO: Should probably be implemented in the above generic dependency
890
+         *       check somehow in the long-term.
891
+         */
892
+        if($iniWrapper->getBool('mbstring.func_overload') !== null &&
893
+            $iniWrapper->getBool('mbstring.func_overload') === true) {
894
+            $errors[] = array(
895
+                'error' => $l->t('mbstring.func_overload is set to "%s" instead of the expected value "0"', [$iniWrapper->getString('mbstring.func_overload')]),
896
+                'hint' => $l->t('To fix this issue set <code>mbstring.func_overload</code> to <code>0</code> in your php.ini')
897
+            );
898
+        }
899
+
900
+        if(function_exists('xml_parser_create') &&
901
+            LIBXML_LOADED_VERSION < 20700 ) {
902
+            $version = LIBXML_LOADED_VERSION;
903
+            $major = floor($version/10000);
904
+            $version -= ($major * 10000);
905
+            $minor = floor($version/100);
906
+            $version -= ($minor * 100);
907
+            $patch = $version;
908
+            $errors[] = array(
909
+                'error' => $l->t('libxml2 2.7.0 is at least required. Currently %s is installed.', [$major . '.' . $minor . '.' . $patch]),
910
+                'hint' => $l->t('To fix this issue update your libxml2 version and restart your web server.')
911
+            );
912
+        }
913
+
914
+        if (!self::isAnnotationsWorking()) {
915
+            $errors[] = array(
916
+                'error' => $l->t('PHP is apparently set up to strip inline doc blocks. This will make several core apps inaccessible.'),
917
+                'hint' => $l->t('This is probably caused by a cache/accelerator such as Zend OPcache or eAccelerator.')
918
+            );
919
+        }
920
+
921
+        if (!\OC::$CLI && $webServerRestart) {
922
+            $errors[] = array(
923
+                'error' => $l->t('PHP modules have been installed, but they are still listed as missing?'),
924
+                'hint' => $l->t('Please ask your server administrator to restart the web server.')
925
+            );
926
+        }
927
+
928
+        $errors = array_merge($errors, self::checkDatabaseVersion());
929
+
930
+        // Cache the result of this function
931
+        \OC::$server->getSession()->set('checkServer_succeeded', count($errors) == 0);
932
+
933
+        return $errors;
934
+    }
935
+
936
+    /**
937
+     * Check the database version
938
+     *
939
+     * @return array errors array
940
+     */
941
+    public static function checkDatabaseVersion() {
942
+        $l = \OC::$server->getL10N('lib');
943
+        $errors = array();
944
+        $dbType = \OC::$server->getSystemConfig()->getValue('dbtype', 'sqlite');
945
+        if ($dbType === 'pgsql') {
946
+            // check PostgreSQL version
947
+            try {
948
+                $result = \OC_DB::executeAudited('SHOW SERVER_VERSION');
949
+                $data = $result->fetchRow();
950
+                if (isset($data['server_version'])) {
951
+                    $version = $data['server_version'];
952
+                    if (version_compare($version, '9.0.0', '<')) {
953
+                        $errors[] = array(
954
+                            'error' => $l->t('PostgreSQL >= 9 required'),
955
+                            'hint' => $l->t('Please upgrade your database version')
956
+                        );
957
+                    }
958
+                }
959
+            } catch (\Doctrine\DBAL\DBALException $e) {
960
+                $logger = \OC::$server->getLogger();
961
+                $logger->warning('Error occurred while checking PostgreSQL version, assuming >= 9');
962
+                $logger->logException($e);
963
+            }
964
+        }
965
+        return $errors;
966
+    }
967
+
968
+    /**
969
+     * Check for correct file permissions of data directory
970
+     *
971
+     * @param string $dataDirectory
972
+     * @return array arrays with error messages and hints
973
+     */
974
+    public static function checkDataDirectoryPermissions($dataDirectory) {
975
+        if(\OC::$server->getConfig()->getSystemValue('check_data_directory_permissions', true) === false) {
976
+            return  [];
977
+        }
978
+        $l = \OC::$server->getL10N('lib');
979
+        $errors = [];
980
+        $permissionsModHint = $l->t('Please change the permissions to 0770 so that the directory'
981
+            . ' cannot be listed by other users.');
982
+        $perms = substr(decoct(@fileperms($dataDirectory)), -3);
983
+        if (substr($perms, -1) !== '0') {
984
+            chmod($dataDirectory, 0770);
985
+            clearstatcache();
986
+            $perms = substr(decoct(@fileperms($dataDirectory)), -3);
987
+            if ($perms[2] !== '0') {
988
+                $errors[] = [
989
+                    'error' => $l->t('Your data directory is readable by other users'),
990
+                    'hint' => $permissionsModHint
991
+                ];
992
+            }
993
+        }
994
+        return $errors;
995
+    }
996
+
997
+    /**
998
+     * Check that the data directory exists and is valid by
999
+     * checking the existence of the ".ocdata" file.
1000
+     *
1001
+     * @param string $dataDirectory data directory path
1002
+     * @return array errors found
1003
+     */
1004
+    public static function checkDataDirectoryValidity($dataDirectory) {
1005
+        $l = \OC::$server->getL10N('lib');
1006
+        $errors = [];
1007
+        if ($dataDirectory[0] !== '/') {
1008
+            $errors[] = [
1009
+                'error' => $l->t('Your data directory must be an absolute path'),
1010
+                'hint' => $l->t('Check the value of "datadirectory" in your configuration')
1011
+            ];
1012
+        }
1013
+        if (!file_exists($dataDirectory . '/.ocdata')) {
1014
+            $errors[] = [
1015
+                'error' => $l->t('Your data directory is invalid'),
1016
+                'hint' => $l->t('Ensure there is a file called ".ocdata"' .
1017
+                    ' in the root of the data directory.')
1018
+            ];
1019
+        }
1020
+        return $errors;
1021
+    }
1022
+
1023
+    /**
1024
+     * Check if the user is logged in, redirects to home if not. With
1025
+     * redirect URL parameter to the request URI.
1026
+     *
1027
+     * @return void
1028
+     */
1029
+    public static function checkLoggedIn() {
1030
+        // Check if we are a user
1031
+        if (!\OC::$server->getUserSession()->isLoggedIn()) {
1032
+            header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute(
1033
+                        'core.login.showLoginForm',
1034
+                        [
1035
+                            'redirect_url' => \OC::$server->getRequest()->getRequestUri(),
1036
+                        ]
1037
+                    )
1038
+            );
1039
+            exit();
1040
+        }
1041
+        // Redirect to 2FA challenge selection if 2FA challenge was not solved yet
1042
+        if (\OC::$server->getTwoFactorAuthManager()->needsSecondFactor(\OC::$server->getUserSession()->getUser())) {
1043
+            header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute('core.TwoFactorChallenge.selectChallenge'));
1044
+            exit();
1045
+        }
1046
+    }
1047
+
1048
+    /**
1049
+     * Check if the user is a admin, redirects to home if not
1050
+     *
1051
+     * @return void
1052
+     */
1053
+    public static function checkAdminUser() {
1054
+        OC_Util::checkLoggedIn();
1055
+        if (!OC_User::isAdminUser(OC_User::getUser())) {
1056
+            header('Location: ' . \OCP\Util::linkToAbsolute('', 'index.php'));
1057
+            exit();
1058
+        }
1059
+    }
1060
+
1061
+    /**
1062
+     * Check if the user is a subadmin, redirects to home if not
1063
+     *
1064
+     * @return null|boolean $groups where the current user is subadmin
1065
+     */
1066
+    public static function checkSubAdminUser() {
1067
+        OC_Util::checkLoggedIn();
1068
+        $userObject = \OC::$server->getUserSession()->getUser();
1069
+        $isSubAdmin = false;
1070
+        if($userObject !== null) {
1071
+            $isSubAdmin = \OC::$server->getGroupManager()->getSubAdmin()->isSubAdmin($userObject);
1072
+        }
1073
+
1074
+        if (!$isSubAdmin) {
1075
+            header('Location: ' . \OCP\Util::linkToAbsolute('', 'index.php'));
1076
+            exit();
1077
+        }
1078
+        return true;
1079
+    }
1080
+
1081
+    /**
1082
+     * Returns the URL of the default page
1083
+     * based on the system configuration and
1084
+     * the apps visible for the current user
1085
+     *
1086
+     * @return string URL
1087
+     * @suppress PhanDeprecatedFunction
1088
+     */
1089
+    public static function getDefaultPageUrl() {
1090
+        $urlGenerator = \OC::$server->getURLGenerator();
1091
+        // Deny the redirect if the URL contains a @
1092
+        // This prevents unvalidated redirects like ?redirect_url=:[email protected]
1093
+        if (isset($_REQUEST['redirect_url']) && strpos($_REQUEST['redirect_url'], '@') === false) {
1094
+            $location = $urlGenerator->getAbsoluteURL(urldecode($_REQUEST['redirect_url']));
1095
+        } else {
1096
+            $defaultPage = \OC::$server->getConfig()->getAppValue('core', 'defaultpage');
1097
+            if ($defaultPage) {
1098
+                $location = $urlGenerator->getAbsoluteURL($defaultPage);
1099
+            } else {
1100
+                $appId = 'files';
1101
+                $config = \OC::$server->getConfig();
1102
+                $defaultApps = explode(',', $config->getSystemValue('defaultapp', 'files'));
1103
+                // find the first app that is enabled for the current user
1104
+                foreach ($defaultApps as $defaultApp) {
1105
+                    $defaultApp = OC_App::cleanAppId(strip_tags($defaultApp));
1106
+                    if (static::getAppManager()->isEnabledForUser($defaultApp)) {
1107
+                        $appId = $defaultApp;
1108
+                        break;
1109
+                    }
1110
+                }
1111
+
1112
+                if($config->getSystemValue('htaccess.IgnoreFrontController', false) === true || getenv('front_controller_active') === 'true') {
1113
+                    $location = $urlGenerator->getAbsoluteURL('/apps/' . $appId . '/');
1114
+                } else {
1115
+                    $location = $urlGenerator->getAbsoluteURL('/index.php/apps/' . $appId . '/');
1116
+                }
1117
+            }
1118
+        }
1119
+        return $location;
1120
+    }
1121
+
1122
+    /**
1123
+     * Redirect to the user default page
1124
+     *
1125
+     * @return void
1126
+     */
1127
+    public static function redirectToDefaultPage() {
1128
+        $location = self::getDefaultPageUrl();
1129
+        header('Location: ' . $location);
1130
+        exit();
1131
+    }
1132
+
1133
+    /**
1134
+     * get an id unique for this instance
1135
+     *
1136
+     * @return string
1137
+     */
1138
+    public static function getInstanceId() {
1139
+        $id = \OC::$server->getSystemConfig()->getValue('instanceid', null);
1140
+        if (is_null($id)) {
1141
+            // We need to guarantee at least one letter in instanceid so it can be used as the session_name
1142
+            $id = 'oc' . \OC::$server->getSecureRandom()->generate(10, \OCP\Security\ISecureRandom::CHAR_LOWER.\OCP\Security\ISecureRandom::CHAR_DIGITS);
1143
+            \OC::$server->getSystemConfig()->setValue('instanceid', $id);
1144
+        }
1145
+        return $id;
1146
+    }
1147
+
1148
+    /**
1149
+     * Public function to sanitize HTML
1150
+     *
1151
+     * This function is used to sanitize HTML and should be applied on any
1152
+     * string or array of strings before displaying it on a web page.
1153
+     *
1154
+     * @param string|array $value
1155
+     * @return string|array an array of sanitized strings or a single sanitized string, depends on the input parameter.
1156
+     */
1157
+    public static function sanitizeHTML($value) {
1158
+        if (is_array($value)) {
1159
+            $value = array_map(function($value) {
1160
+                return self::sanitizeHTML($value);
1161
+            }, $value);
1162
+        } else {
1163
+            // Specify encoding for PHP<5.4
1164
+            $value = htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
1165
+        }
1166
+        return $value;
1167
+    }
1168
+
1169
+    /**
1170
+     * Public function to encode url parameters
1171
+     *
1172
+     * This function is used to encode path to file before output.
1173
+     * Encoding is done according to RFC 3986 with one exception:
1174
+     * Character '/' is preserved as is.
1175
+     *
1176
+     * @param string $component part of URI to encode
1177
+     * @return string
1178
+     */
1179
+    public static function encodePath($component) {
1180
+        $encoded = rawurlencode($component);
1181
+        $encoded = str_replace('%2F', '/', $encoded);
1182
+        return $encoded;
1183
+    }
1184
+
1185
+
1186
+    public function createHtaccessTestFile(\OCP\IConfig $config) {
1187
+        // php dev server does not support htaccess
1188
+        if (php_sapi_name() === 'cli-server') {
1189
+            return false;
1190
+        }
1191
+
1192
+        // testdata
1193
+        $fileName = '/htaccesstest.txt';
1194
+        $testContent = 'This is used for testing whether htaccess is properly enabled to disallow access from the outside. This file can be safely removed.';
1195
+
1196
+        // creating a test file
1197
+        $testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
1198
+
1199
+        if (file_exists($testFile)) {// already running this test, possible recursive call
1200
+            return false;
1201
+        }
1202
+
1203
+        $fp = @fopen($testFile, 'w');
1204
+        if (!$fp) {
1205
+            throw new OC\HintException('Can\'t create test file to check for working .htaccess file.',
1206
+                'Make sure it is possible for the webserver to write to ' . $testFile);
1207
+        }
1208
+        fwrite($fp, $testContent);
1209
+        fclose($fp);
1210
+
1211
+        return $testContent;
1212
+    }
1213
+
1214
+    /**
1215
+     * Check if the .htaccess file is working
1216
+     * @param \OCP\IConfig $config
1217
+     * @return bool
1218
+     * @throws Exception
1219
+     * @throws \OC\HintException If the test file can't get written.
1220
+     */
1221
+    public function isHtaccessWorking(\OCP\IConfig $config) {
1222
+
1223
+        if (\OC::$CLI || !$config->getSystemValue('check_for_working_htaccess', true)) {
1224
+            return true;
1225
+        }
1226
+
1227
+        $testContent = $this->createHtaccessTestFile($config);
1228
+        if ($testContent === false) {
1229
+            return false;
1230
+        }
1231
+
1232
+        $fileName = '/htaccesstest.txt';
1233
+        $testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
1234
+
1235
+        // accessing the file via http
1236
+        $url = \OC::$server->getURLGenerator()->getAbsoluteURL(OC::$WEBROOT . '/data' . $fileName);
1237
+        try {
1238
+            $content = \OC::$server->getHTTPClientService()->newClient()->get($url)->getBody();
1239
+        } catch (\Exception $e) {
1240
+            $content = false;
1241
+        }
1242
+
1243
+        // cleanup
1244
+        @unlink($testFile);
1245
+
1246
+        /*
1247 1247
 		 * If the content is not equal to test content our .htaccess
1248 1248
 		 * is working as required
1249 1249
 		 */
1250
-		return $content !== $testContent;
1251
-	}
1252
-
1253
-	/**
1254
-	 * Check if the setlocal call does not work. This can happen if the right
1255
-	 * local packages are not available on the server.
1256
-	 *
1257
-	 * @return bool
1258
-	 */
1259
-	public static function isSetLocaleWorking() {
1260
-		\Patchwork\Utf8\Bootup::initLocale();
1261
-		if ('' === basename('§')) {
1262
-			return false;
1263
-		}
1264
-		return true;
1265
-	}
1266
-
1267
-	/**
1268
-	 * Check if it's possible to get the inline annotations
1269
-	 *
1270
-	 * @return bool
1271
-	 */
1272
-	public static function isAnnotationsWorking() {
1273
-		$reflection = new \ReflectionMethod(__METHOD__);
1274
-		$docs = $reflection->getDocComment();
1275
-
1276
-		return (is_string($docs) && strlen($docs) > 50);
1277
-	}
1278
-
1279
-	/**
1280
-	 * Check if the PHP module fileinfo is loaded.
1281
-	 *
1282
-	 * @return bool
1283
-	 */
1284
-	public static function fileInfoLoaded() {
1285
-		return function_exists('finfo_open');
1286
-	}
1287
-
1288
-	/**
1289
-	 * clear all levels of output buffering
1290
-	 *
1291
-	 * @return void
1292
-	 */
1293
-	public static function obEnd() {
1294
-		while (ob_get_level()) {
1295
-			ob_end_clean();
1296
-		}
1297
-	}
1298
-
1299
-	/**
1300
-	 * Checks whether the server is running on Mac OS X
1301
-	 *
1302
-	 * @return bool true if running on Mac OS X, false otherwise
1303
-	 */
1304
-	public static function runningOnMac() {
1305
-		return (strtoupper(substr(PHP_OS, 0, 6)) === 'DARWIN');
1306
-	}
1307
-
1308
-	/**
1309
-	 * Checks whether server is running on HHVM
1310
-	 *
1311
-	 * @return bool True if running on HHVM, false otherwise
1312
-	 */
1313
-	public static function runningOnHhvm() {
1314
-		return defined('HHVM_VERSION');
1315
-	}
1316
-
1317
-	/**
1318
-	 * Handles the case that there may not be a theme, then check if a "default"
1319
-	 * theme exists and take that one
1320
-	 *
1321
-	 * @return string the theme
1322
-	 */
1323
-	public static function getTheme() {
1324
-		$theme = \OC::$server->getSystemConfig()->getValue("theme", '');
1325
-
1326
-		if ($theme === '') {
1327
-			if (is_dir(OC::$SERVERROOT . '/themes/default')) {
1328
-				$theme = 'default';
1329
-			}
1330
-		}
1331
-
1332
-		return $theme;
1333
-	}
1334
-
1335
-	/**
1336
-	 * Clear a single file from the opcode cache
1337
-	 * This is useful for writing to the config file
1338
-	 * in case the opcode cache does not re-validate files
1339
-	 * Returns true if successful, false if unsuccessful:
1340
-	 * caller should fall back on clearing the entire cache
1341
-	 * with clearOpcodeCache() if unsuccessful
1342
-	 *
1343
-	 * @param string $path the path of the file to clear from the cache
1344
-	 * @return bool true if underlying function returns true, otherwise false
1345
-	 */
1346
-	public static function deleteFromOpcodeCache($path) {
1347
-		$ret = false;
1348
-		if ($path) {
1349
-			// APC >= 3.1.1
1350
-			if (function_exists('apc_delete_file')) {
1351
-				$ret = @apc_delete_file($path);
1352
-			}
1353
-			// Zend OpCache >= 7.0.0, PHP >= 5.5.0
1354
-			if (function_exists('opcache_invalidate')) {
1355
-				$ret = opcache_invalidate($path);
1356
-			}
1357
-		}
1358
-		return $ret;
1359
-	}
1360
-
1361
-	/**
1362
-	 * Clear the opcode cache if one exists
1363
-	 * This is necessary for writing to the config file
1364
-	 * in case the opcode cache does not re-validate files
1365
-	 *
1366
-	 * @return void
1367
-	 * @suppress PhanDeprecatedFunction
1368
-	 * @suppress PhanUndeclaredConstant
1369
-	 */
1370
-	public static function clearOpcodeCache() {
1371
-		// APC
1372
-		if (function_exists('apc_clear_cache')) {
1373
-			apc_clear_cache();
1374
-		}
1375
-		// Zend Opcache
1376
-		if (function_exists('accelerator_reset')) {
1377
-			accelerator_reset();
1378
-		}
1379
-		// XCache
1380
-		if (function_exists('xcache_clear_cache')) {
1381
-			if (\OC::$server->getIniWrapper()->getBool('xcache.admin.enable_auth')) {
1382
-				\OCP\Util::writeLog('core', 'XCache opcode cache will not be cleared because "xcache.admin.enable_auth" is enabled.', ILogger::WARN);
1383
-			} else {
1384
-				@xcache_clear_cache(XC_TYPE_PHP, 0);
1385
-			}
1386
-		}
1387
-		// Opcache (PHP >= 5.5)
1388
-		if (function_exists('opcache_reset')) {
1389
-			opcache_reset();
1390
-		}
1391
-	}
1392
-
1393
-	/**
1394
-	 * Normalize a unicode string
1395
-	 *
1396
-	 * @param string $value a not normalized string
1397
-	 * @return bool|string
1398
-	 */
1399
-	public static function normalizeUnicode($value) {
1400
-		if(Normalizer::isNormalized($value)) {
1401
-			return $value;
1402
-		}
1403
-
1404
-		$normalizedValue = Normalizer::normalize($value);
1405
-		if ($normalizedValue === null || $normalizedValue === false) {
1406
-			\OC::$server->getLogger()->warning('normalizing failed for "' . $value . '"', ['app' => 'core']);
1407
-			return $value;
1408
-		}
1409
-
1410
-		return $normalizedValue;
1411
-	}
1412
-
1413
-	/**
1414
-	 * A human readable string is generated based on version and build number
1415
-	 *
1416
-	 * @return string
1417
-	 */
1418
-	public static function getHumanVersion() {
1419
-		$version = OC_Util::getVersionString();
1420
-		$build = OC_Util::getBuild();
1421
-		if (!empty($build) and OC_Util::getChannel() === 'daily') {
1422
-			$version .= ' Build:' . $build;
1423
-		}
1424
-		return $version;
1425
-	}
1426
-
1427
-	/**
1428
-	 * Returns whether the given file name is valid
1429
-	 *
1430
-	 * @param string $file file name to check
1431
-	 * @return bool true if the file name is valid, false otherwise
1432
-	 * @deprecated use \OC\Files\View::verifyPath()
1433
-	 */
1434
-	public static function isValidFileName($file) {
1435
-		$trimmed = trim($file);
1436
-		if ($trimmed === '') {
1437
-			return false;
1438
-		}
1439
-		if (\OC\Files\Filesystem::isIgnoredDir($trimmed)) {
1440
-			return false;
1441
-		}
1442
-
1443
-		// detect part files
1444
-		if (preg_match('/' . \OCP\Files\FileInfo::BLACKLIST_FILES_REGEX . '/', $trimmed) !== 0) {
1445
-			return false;
1446
-		}
1447
-
1448
-		foreach (str_split($trimmed) as $char) {
1449
-			if (strpos(\OCP\Constants::FILENAME_INVALID_CHARS, $char) !== false) {
1450
-				return false;
1451
-			}
1452
-		}
1453
-		return true;
1454
-	}
1455
-
1456
-	/**
1457
-	 * Check whether the instance needs to perform an upgrade,
1458
-	 * either when the core version is higher or any app requires
1459
-	 * an upgrade.
1460
-	 *
1461
-	 * @param \OC\SystemConfig $config
1462
-	 * @return bool whether the core or any app needs an upgrade
1463
-	 * @throws \OC\HintException When the upgrade from the given version is not allowed
1464
-	 */
1465
-	public static function needUpgrade(\OC\SystemConfig $config) {
1466
-		if ($config->getValue('installed', false)) {
1467
-			$installedVersion = $config->getValue('version', '0.0.0');
1468
-			$currentVersion = implode('.', \OCP\Util::getVersion());
1469
-			$versionDiff = version_compare($currentVersion, $installedVersion);
1470
-			if ($versionDiff > 0) {
1471
-				return true;
1472
-			} else if ($config->getValue('debug', false) && $versionDiff < 0) {
1473
-				// downgrade with debug
1474
-				$installedMajor = explode('.', $installedVersion);
1475
-				$installedMajor = $installedMajor[0] . '.' . $installedMajor[1];
1476
-				$currentMajor = explode('.', $currentVersion);
1477
-				$currentMajor = $currentMajor[0] . '.' . $currentMajor[1];
1478
-				if ($installedMajor === $currentMajor) {
1479
-					// Same major, allow downgrade for developers
1480
-					return true;
1481
-				} else {
1482
-					// downgrade attempt, throw exception
1483
-					throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1484
-				}
1485
-			} else if ($versionDiff < 0) {
1486
-				// downgrade attempt, throw exception
1487
-				throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1488
-			}
1489
-
1490
-			// also check for upgrades for apps (independently from the user)
1491
-			$apps = \OC_App::getEnabledApps(false, true);
1492
-			$shouldUpgrade = false;
1493
-			foreach ($apps as $app) {
1494
-				if (\OC_App::shouldUpgrade($app)) {
1495
-					$shouldUpgrade = true;
1496
-					break;
1497
-				}
1498
-			}
1499
-			return $shouldUpgrade;
1500
-		} else {
1501
-			return false;
1502
-		}
1503
-	}
1250
+        return $content !== $testContent;
1251
+    }
1252
+
1253
+    /**
1254
+     * Check if the setlocal call does not work. This can happen if the right
1255
+     * local packages are not available on the server.
1256
+     *
1257
+     * @return bool
1258
+     */
1259
+    public static function isSetLocaleWorking() {
1260
+        \Patchwork\Utf8\Bootup::initLocale();
1261
+        if ('' === basename('§')) {
1262
+            return false;
1263
+        }
1264
+        return true;
1265
+    }
1266
+
1267
+    /**
1268
+     * Check if it's possible to get the inline annotations
1269
+     *
1270
+     * @return bool
1271
+     */
1272
+    public static function isAnnotationsWorking() {
1273
+        $reflection = new \ReflectionMethod(__METHOD__);
1274
+        $docs = $reflection->getDocComment();
1275
+
1276
+        return (is_string($docs) && strlen($docs) > 50);
1277
+    }
1278
+
1279
+    /**
1280
+     * Check if the PHP module fileinfo is loaded.
1281
+     *
1282
+     * @return bool
1283
+     */
1284
+    public static function fileInfoLoaded() {
1285
+        return function_exists('finfo_open');
1286
+    }
1287
+
1288
+    /**
1289
+     * clear all levels of output buffering
1290
+     *
1291
+     * @return void
1292
+     */
1293
+    public static function obEnd() {
1294
+        while (ob_get_level()) {
1295
+            ob_end_clean();
1296
+        }
1297
+    }
1298
+
1299
+    /**
1300
+     * Checks whether the server is running on Mac OS X
1301
+     *
1302
+     * @return bool true if running on Mac OS X, false otherwise
1303
+     */
1304
+    public static function runningOnMac() {
1305
+        return (strtoupper(substr(PHP_OS, 0, 6)) === 'DARWIN');
1306
+    }
1307
+
1308
+    /**
1309
+     * Checks whether server is running on HHVM
1310
+     *
1311
+     * @return bool True if running on HHVM, false otherwise
1312
+     */
1313
+    public static function runningOnHhvm() {
1314
+        return defined('HHVM_VERSION');
1315
+    }
1316
+
1317
+    /**
1318
+     * Handles the case that there may not be a theme, then check if a "default"
1319
+     * theme exists and take that one
1320
+     *
1321
+     * @return string the theme
1322
+     */
1323
+    public static function getTheme() {
1324
+        $theme = \OC::$server->getSystemConfig()->getValue("theme", '');
1325
+
1326
+        if ($theme === '') {
1327
+            if (is_dir(OC::$SERVERROOT . '/themes/default')) {
1328
+                $theme = 'default';
1329
+            }
1330
+        }
1331
+
1332
+        return $theme;
1333
+    }
1334
+
1335
+    /**
1336
+     * Clear a single file from the opcode cache
1337
+     * This is useful for writing to the config file
1338
+     * in case the opcode cache does not re-validate files
1339
+     * Returns true if successful, false if unsuccessful:
1340
+     * caller should fall back on clearing the entire cache
1341
+     * with clearOpcodeCache() if unsuccessful
1342
+     *
1343
+     * @param string $path the path of the file to clear from the cache
1344
+     * @return bool true if underlying function returns true, otherwise false
1345
+     */
1346
+    public static function deleteFromOpcodeCache($path) {
1347
+        $ret = false;
1348
+        if ($path) {
1349
+            // APC >= 3.1.1
1350
+            if (function_exists('apc_delete_file')) {
1351
+                $ret = @apc_delete_file($path);
1352
+            }
1353
+            // Zend OpCache >= 7.0.0, PHP >= 5.5.0
1354
+            if (function_exists('opcache_invalidate')) {
1355
+                $ret = opcache_invalidate($path);
1356
+            }
1357
+        }
1358
+        return $ret;
1359
+    }
1360
+
1361
+    /**
1362
+     * Clear the opcode cache if one exists
1363
+     * This is necessary for writing to the config file
1364
+     * in case the opcode cache does not re-validate files
1365
+     *
1366
+     * @return void
1367
+     * @suppress PhanDeprecatedFunction
1368
+     * @suppress PhanUndeclaredConstant
1369
+     */
1370
+    public static function clearOpcodeCache() {
1371
+        // APC
1372
+        if (function_exists('apc_clear_cache')) {
1373
+            apc_clear_cache();
1374
+        }
1375
+        // Zend Opcache
1376
+        if (function_exists('accelerator_reset')) {
1377
+            accelerator_reset();
1378
+        }
1379
+        // XCache
1380
+        if (function_exists('xcache_clear_cache')) {
1381
+            if (\OC::$server->getIniWrapper()->getBool('xcache.admin.enable_auth')) {
1382
+                \OCP\Util::writeLog('core', 'XCache opcode cache will not be cleared because "xcache.admin.enable_auth" is enabled.', ILogger::WARN);
1383
+            } else {
1384
+                @xcache_clear_cache(XC_TYPE_PHP, 0);
1385
+            }
1386
+        }
1387
+        // Opcache (PHP >= 5.5)
1388
+        if (function_exists('opcache_reset')) {
1389
+            opcache_reset();
1390
+        }
1391
+    }
1392
+
1393
+    /**
1394
+     * Normalize a unicode string
1395
+     *
1396
+     * @param string $value a not normalized string
1397
+     * @return bool|string
1398
+     */
1399
+    public static function normalizeUnicode($value) {
1400
+        if(Normalizer::isNormalized($value)) {
1401
+            return $value;
1402
+        }
1403
+
1404
+        $normalizedValue = Normalizer::normalize($value);
1405
+        if ($normalizedValue === null || $normalizedValue === false) {
1406
+            \OC::$server->getLogger()->warning('normalizing failed for "' . $value . '"', ['app' => 'core']);
1407
+            return $value;
1408
+        }
1409
+
1410
+        return $normalizedValue;
1411
+    }
1412
+
1413
+    /**
1414
+     * A human readable string is generated based on version and build number
1415
+     *
1416
+     * @return string
1417
+     */
1418
+    public static function getHumanVersion() {
1419
+        $version = OC_Util::getVersionString();
1420
+        $build = OC_Util::getBuild();
1421
+        if (!empty($build) and OC_Util::getChannel() === 'daily') {
1422
+            $version .= ' Build:' . $build;
1423
+        }
1424
+        return $version;
1425
+    }
1426
+
1427
+    /**
1428
+     * Returns whether the given file name is valid
1429
+     *
1430
+     * @param string $file file name to check
1431
+     * @return bool true if the file name is valid, false otherwise
1432
+     * @deprecated use \OC\Files\View::verifyPath()
1433
+     */
1434
+    public static function isValidFileName($file) {
1435
+        $trimmed = trim($file);
1436
+        if ($trimmed === '') {
1437
+            return false;
1438
+        }
1439
+        if (\OC\Files\Filesystem::isIgnoredDir($trimmed)) {
1440
+            return false;
1441
+        }
1442
+
1443
+        // detect part files
1444
+        if (preg_match('/' . \OCP\Files\FileInfo::BLACKLIST_FILES_REGEX . '/', $trimmed) !== 0) {
1445
+            return false;
1446
+        }
1447
+
1448
+        foreach (str_split($trimmed) as $char) {
1449
+            if (strpos(\OCP\Constants::FILENAME_INVALID_CHARS, $char) !== false) {
1450
+                return false;
1451
+            }
1452
+        }
1453
+        return true;
1454
+    }
1455
+
1456
+    /**
1457
+     * Check whether the instance needs to perform an upgrade,
1458
+     * either when the core version is higher or any app requires
1459
+     * an upgrade.
1460
+     *
1461
+     * @param \OC\SystemConfig $config
1462
+     * @return bool whether the core or any app needs an upgrade
1463
+     * @throws \OC\HintException When the upgrade from the given version is not allowed
1464
+     */
1465
+    public static function needUpgrade(\OC\SystemConfig $config) {
1466
+        if ($config->getValue('installed', false)) {
1467
+            $installedVersion = $config->getValue('version', '0.0.0');
1468
+            $currentVersion = implode('.', \OCP\Util::getVersion());
1469
+            $versionDiff = version_compare($currentVersion, $installedVersion);
1470
+            if ($versionDiff > 0) {
1471
+                return true;
1472
+            } else if ($config->getValue('debug', false) && $versionDiff < 0) {
1473
+                // downgrade with debug
1474
+                $installedMajor = explode('.', $installedVersion);
1475
+                $installedMajor = $installedMajor[0] . '.' . $installedMajor[1];
1476
+                $currentMajor = explode('.', $currentVersion);
1477
+                $currentMajor = $currentMajor[0] . '.' . $currentMajor[1];
1478
+                if ($installedMajor === $currentMajor) {
1479
+                    // Same major, allow downgrade for developers
1480
+                    return true;
1481
+                } else {
1482
+                    // downgrade attempt, throw exception
1483
+                    throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1484
+                }
1485
+            } else if ($versionDiff < 0) {
1486
+                // downgrade attempt, throw exception
1487
+                throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1488
+            }
1489
+
1490
+            // also check for upgrades for apps (independently from the user)
1491
+            $apps = \OC_App::getEnabledApps(false, true);
1492
+            $shouldUpgrade = false;
1493
+            foreach ($apps as $app) {
1494
+                if (\OC_App::shouldUpgrade($app)) {
1495
+                    $shouldUpgrade = true;
1496
+                    break;
1497
+                }
1498
+            }
1499
+            return $shouldUpgrade;
1500
+        } else {
1501
+            return false;
1502
+        }
1503
+    }
1504 1504
 
1505 1505
 }
Please login to merge, or discard this patch.