Passed
Push — master ( df99d8...7685d1 )
by Roeland
11:08
created
apps/files/lib/Helper.php 2 patches
Indentation   +209 added lines, -209 removed lines patch added patch discarded remove patch
@@ -41,232 +41,232 @@
 block discarded – undo
41 41
  * Helper class for manipulating file information
42 42
  */
43 43
 class Helper {
44
-	/**
45
-	 * @param string $dir
46
-	 * @return array
47
-	 * @throws \OCP\Files\NotFoundException
48
-	 */
49
-	public static function buildFileStorageStatistics($dir) {
50
-		// information about storage capacities
51
-		$storageInfo = \OC_Helper::getStorageInfo($dir);
52
-		$l = \OC::$server->getL10N('files');
53
-		$maxUploadFileSize = \OCP\Util::maxUploadFilesize($dir, $storageInfo['free']);
54
-		$maxHumanFileSize = \OCP\Util::humanFileSize($maxUploadFileSize);
55
-		$maxHumanFileSize = $l->t('Upload (max. %s)', [$maxHumanFileSize]);
44
+    /**
45
+     * @param string $dir
46
+     * @return array
47
+     * @throws \OCP\Files\NotFoundException
48
+     */
49
+    public static function buildFileStorageStatistics($dir) {
50
+        // information about storage capacities
51
+        $storageInfo = \OC_Helper::getStorageInfo($dir);
52
+        $l = \OC::$server->getL10N('files');
53
+        $maxUploadFileSize = \OCP\Util::maxUploadFilesize($dir, $storageInfo['free']);
54
+        $maxHumanFileSize = \OCP\Util::humanFileSize($maxUploadFileSize);
55
+        $maxHumanFileSize = $l->t('Upload (max. %s)', [$maxHumanFileSize]);
56 56
 
57
-		return [
58
-			'uploadMaxFilesize' => $maxUploadFileSize,
59
-			'maxHumanFilesize'  => $maxHumanFileSize,
60
-			'freeSpace' => $storageInfo['free'],
61
-			'quota' => $storageInfo['quota'],
62
-			'used' => $storageInfo['used'],
63
-			'usedSpacePercent'  => (int)$storageInfo['relative'],
64
-			'owner' => $storageInfo['owner'],
65
-			'ownerDisplayName' => $storageInfo['ownerDisplayName'],
66
-			'mountType' => $storageInfo['mountType'],
67
-		];
68
-	}
57
+        return [
58
+            'uploadMaxFilesize' => $maxUploadFileSize,
59
+            'maxHumanFilesize'  => $maxHumanFileSize,
60
+            'freeSpace' => $storageInfo['free'],
61
+            'quota' => $storageInfo['quota'],
62
+            'used' => $storageInfo['used'],
63
+            'usedSpacePercent'  => (int)$storageInfo['relative'],
64
+            'owner' => $storageInfo['owner'],
65
+            'ownerDisplayName' => $storageInfo['ownerDisplayName'],
66
+            'mountType' => $storageInfo['mountType'],
67
+        ];
68
+    }
69 69
 
70
-	/**
71
-	 * Determine icon for a given file
72
-	 *
73
-	 * @param \OCP\Files\FileInfo $file file info
74
-	 * @return string icon URL
75
-	 */
76
-	public static function determineIcon($file) {
77
-		if ($file['type'] === 'dir') {
78
-			$icon = \OC::$server->getMimeTypeDetector()->mimeTypeIcon('dir');
79
-			// TODO: move this part to the client side, using mountType
80
-			if ($file->isShared()) {
81
-				$icon = \OC::$server->getMimeTypeDetector()->mimeTypeIcon('dir-shared');
82
-			} elseif ($file->isMounted()) {
83
-				$icon = \OC::$server->getMimeTypeDetector()->mimeTypeIcon('dir-external');
84
-			}
85
-		} else {
86
-			$icon = \OC::$server->getMimeTypeDetector()->mimeTypeIcon($file->getMimetype());
87
-		}
70
+    /**
71
+     * Determine icon for a given file
72
+     *
73
+     * @param \OCP\Files\FileInfo $file file info
74
+     * @return string icon URL
75
+     */
76
+    public static function determineIcon($file) {
77
+        if ($file['type'] === 'dir') {
78
+            $icon = \OC::$server->getMimeTypeDetector()->mimeTypeIcon('dir');
79
+            // TODO: move this part to the client side, using mountType
80
+            if ($file->isShared()) {
81
+                $icon = \OC::$server->getMimeTypeDetector()->mimeTypeIcon('dir-shared');
82
+            } elseif ($file->isMounted()) {
83
+                $icon = \OC::$server->getMimeTypeDetector()->mimeTypeIcon('dir-external');
84
+            }
85
+        } else {
86
+            $icon = \OC::$server->getMimeTypeDetector()->mimeTypeIcon($file->getMimetype());
87
+        }
88 88
 
89
-		return substr($icon, 0, -3) . 'svg';
90
-	}
89
+        return substr($icon, 0, -3) . 'svg';
90
+    }
91 91
 
92
-	/**
93
-	 * Comparator function to sort files alphabetically and have
94
-	 * the directories appear first
95
-	 *
96
-	 * @param \OCP\Files\FileInfo $a file
97
-	 * @param \OCP\Files\FileInfo $b file
98
-	 * @return int -1 if $a must come before $b, 1 otherwise
99
-	 */
100
-	public static function compareFileNames(FileInfo $a, FileInfo $b) {
101
-		$aType = $a->getType();
102
-		$bType = $b->getType();
103
-		if ($aType === 'dir' and $bType !== 'dir') {
104
-			return -1;
105
-		} elseif ($aType !== 'dir' and $bType === 'dir') {
106
-			return 1;
107
-		} else {
108
-			return \OCP\Util::naturalSortCompare($a->getName(), $b->getName());
109
-		}
110
-	}
92
+    /**
93
+     * Comparator function to sort files alphabetically and have
94
+     * the directories appear first
95
+     *
96
+     * @param \OCP\Files\FileInfo $a file
97
+     * @param \OCP\Files\FileInfo $b file
98
+     * @return int -1 if $a must come before $b, 1 otherwise
99
+     */
100
+    public static function compareFileNames(FileInfo $a, FileInfo $b) {
101
+        $aType = $a->getType();
102
+        $bType = $b->getType();
103
+        if ($aType === 'dir' and $bType !== 'dir') {
104
+            return -1;
105
+        } elseif ($aType !== 'dir' and $bType === 'dir') {
106
+            return 1;
107
+        } else {
108
+            return \OCP\Util::naturalSortCompare($a->getName(), $b->getName());
109
+        }
110
+    }
111 111
 
112
-	/**
113
-	 * Comparator function to sort files by date
114
-	 *
115
-	 * @param \OCP\Files\FileInfo $a file
116
-	 * @param \OCP\Files\FileInfo $b file
117
-	 * @return int -1 if $a must come before $b, 1 otherwise
118
-	 */
119
-	public static function compareTimestamp(FileInfo $a, FileInfo $b) {
120
-		$aTime = $a->getMTime();
121
-		$bTime = $b->getMTime();
122
-		return ($aTime < $bTime) ? -1 : 1;
123
-	}
112
+    /**
113
+     * Comparator function to sort files by date
114
+     *
115
+     * @param \OCP\Files\FileInfo $a file
116
+     * @param \OCP\Files\FileInfo $b file
117
+     * @return int -1 if $a must come before $b, 1 otherwise
118
+     */
119
+    public static function compareTimestamp(FileInfo $a, FileInfo $b) {
120
+        $aTime = $a->getMTime();
121
+        $bTime = $b->getMTime();
122
+        return ($aTime < $bTime) ? -1 : 1;
123
+    }
124 124
 
125
-	/**
126
-	 * Comparator function to sort files by size
127
-	 *
128
-	 * @param \OCP\Files\FileInfo $a file
129
-	 * @param \OCP\Files\FileInfo $b file
130
-	 * @return int -1 if $a must come before $b, 1 otherwise
131
-	 */
132
-	public static function compareSize(FileInfo $a, FileInfo $b) {
133
-		$aSize = $a->getSize();
134
-		$bSize = $b->getSize();
135
-		return ($aSize < $bSize) ? -1 : 1;
136
-	}
125
+    /**
126
+     * Comparator function to sort files by size
127
+     *
128
+     * @param \OCP\Files\FileInfo $a file
129
+     * @param \OCP\Files\FileInfo $b file
130
+     * @return int -1 if $a must come before $b, 1 otherwise
131
+     */
132
+    public static function compareSize(FileInfo $a, FileInfo $b) {
133
+        $aSize = $a->getSize();
134
+        $bSize = $b->getSize();
135
+        return ($aSize < $bSize) ? -1 : 1;
136
+    }
137 137
 
138
-	/**
139
-	 * Formats the file info to be returned as JSON to the client.
140
-	 *
141
-	 * @param \OCP\Files\FileInfo $i
142
-	 * @return array formatted file info
143
-	 */
144
-	public static function formatFileInfo(FileInfo $i) {
145
-		$entry = [];
138
+    /**
139
+     * Formats the file info to be returned as JSON to the client.
140
+     *
141
+     * @param \OCP\Files\FileInfo $i
142
+     * @return array formatted file info
143
+     */
144
+    public static function formatFileInfo(FileInfo $i) {
145
+        $entry = [];
146 146
 
147
-		$entry['id'] = $i['fileid'];
148
-		$entry['parentId'] = $i['parent'];
149
-		$entry['mtime'] = $i['mtime'] * 1000;
150
-		// only pick out the needed attributes
151
-		$entry['name'] = $i->getName();
152
-		$entry['permissions'] = $i['permissions'];
153
-		$entry['mimetype'] = $i['mimetype'];
154
-		$entry['size'] = $i['size'];
155
-		$entry['type'] = $i['type'];
156
-		$entry['etag'] = $i['etag'];
157
-		if (isset($i['tags'])) {
158
-			$entry['tags'] = $i['tags'];
159
-		}
160
-		if (isset($i['displayname_owner'])) {
161
-			$entry['shareOwner'] = $i['displayname_owner'];
162
-		}
163
-		if (isset($i['is_share_mount_point'])) {
164
-			$entry['isShareMountPoint'] = $i['is_share_mount_point'];
165
-		}
166
-		$mountType = null;
167
-		$mount = $i->getMountPoint();
168
-		$mountType = $mount->getMountType();
169
-		if ($mountType !== '') {
170
-			if ($i->getInternalPath() === '') {
171
-				$mountType .= '-root';
172
-			}
173
-			$entry['mountType'] = $mountType;
174
-		}
175
-		if (isset($i['extraData'])) {
176
-			$entry['extraData'] = $i['extraData'];
177
-		}
178
-		return $entry;
179
-	}
147
+        $entry['id'] = $i['fileid'];
148
+        $entry['parentId'] = $i['parent'];
149
+        $entry['mtime'] = $i['mtime'] * 1000;
150
+        // only pick out the needed attributes
151
+        $entry['name'] = $i->getName();
152
+        $entry['permissions'] = $i['permissions'];
153
+        $entry['mimetype'] = $i['mimetype'];
154
+        $entry['size'] = $i['size'];
155
+        $entry['type'] = $i['type'];
156
+        $entry['etag'] = $i['etag'];
157
+        if (isset($i['tags'])) {
158
+            $entry['tags'] = $i['tags'];
159
+        }
160
+        if (isset($i['displayname_owner'])) {
161
+            $entry['shareOwner'] = $i['displayname_owner'];
162
+        }
163
+        if (isset($i['is_share_mount_point'])) {
164
+            $entry['isShareMountPoint'] = $i['is_share_mount_point'];
165
+        }
166
+        $mountType = null;
167
+        $mount = $i->getMountPoint();
168
+        $mountType = $mount->getMountType();
169
+        if ($mountType !== '') {
170
+            if ($i->getInternalPath() === '') {
171
+                $mountType .= '-root';
172
+            }
173
+            $entry['mountType'] = $mountType;
174
+        }
175
+        if (isset($i['extraData'])) {
176
+            $entry['extraData'] = $i['extraData'];
177
+        }
178
+        return $entry;
179
+    }
180 180
 
181
-	/**
182
-	 * Format file info for JSON
183
-	 * @param \OCP\Files\FileInfo[] $fileInfos file infos
184
-	 * @return array
185
-	 */
186
-	public static function formatFileInfos($fileInfos) {
187
-		$files = [];
188
-		foreach ($fileInfos as $i) {
189
-			$files[] = self::formatFileInfo($i);
190
-		}
181
+    /**
182
+     * Format file info for JSON
183
+     * @param \OCP\Files\FileInfo[] $fileInfos file infos
184
+     * @return array
185
+     */
186
+    public static function formatFileInfos($fileInfos) {
187
+        $files = [];
188
+        foreach ($fileInfos as $i) {
189
+            $files[] = self::formatFileInfo($i);
190
+        }
191 191
 
192
-		return $files;
193
-	}
192
+        return $files;
193
+    }
194 194
 
195
-	/**
196
-	 * Retrieves the contents of the given directory and
197
-	 * returns it as a sorted array of FileInfo.
198
-	 *
199
-	 * @param string $dir path to the directory
200
-	 * @param string $sortAttribute attribute to sort on
201
-	 * @param bool $sortDescending true for descending sort, false otherwise
202
-	 * @param string $mimetypeFilter limit returned content to this mimetype or mimepart
203
-	 * @return \OCP\Files\FileInfo[] files
204
-	 */
205
-	public static function getFiles($dir, $sortAttribute = 'name', $sortDescending = false, $mimetypeFilter = '') {
206
-		$content = \OC\Files\Filesystem::getDirectoryContent($dir, $mimetypeFilter);
195
+    /**
196
+     * Retrieves the contents of the given directory and
197
+     * returns it as a sorted array of FileInfo.
198
+     *
199
+     * @param string $dir path to the directory
200
+     * @param string $sortAttribute attribute to sort on
201
+     * @param bool $sortDescending true for descending sort, false otherwise
202
+     * @param string $mimetypeFilter limit returned content to this mimetype or mimepart
203
+     * @return \OCP\Files\FileInfo[] files
204
+     */
205
+    public static function getFiles($dir, $sortAttribute = 'name', $sortDescending = false, $mimetypeFilter = '') {
206
+        $content = \OC\Files\Filesystem::getDirectoryContent($dir, $mimetypeFilter);
207 207
 
208
-		return self::sortFiles($content, $sortAttribute, $sortDescending);
209
-	}
208
+        return self::sortFiles($content, $sortAttribute, $sortDescending);
209
+    }
210 210
 
211
-	/**
212
-	 * Populate the result set with file tags
213
-	 *
214
-	 * @param array $fileList
215
-	 * @param string $fileIdentifier identifier attribute name for values in $fileList
216
-	 * @param ITagManager $tagManager
217
-	 * @return array file list populated with tags
218
-	 */
219
-	public static function populateTags(array $fileList, $fileIdentifier = 'fileid', ITagManager $tagManager) {
220
-		$ids = [];
221
-		foreach ($fileList as $fileData) {
222
-			$ids[] = $fileData[$fileIdentifier];
223
-		}
224
-		$tagger = $tagManager->load('files');
225
-		$tags = $tagger->getTagsForObjects($ids);
211
+    /**
212
+     * Populate the result set with file tags
213
+     *
214
+     * @param array $fileList
215
+     * @param string $fileIdentifier identifier attribute name for values in $fileList
216
+     * @param ITagManager $tagManager
217
+     * @return array file list populated with tags
218
+     */
219
+    public static function populateTags(array $fileList, $fileIdentifier = 'fileid', ITagManager $tagManager) {
220
+        $ids = [];
221
+        foreach ($fileList as $fileData) {
222
+            $ids[] = $fileData[$fileIdentifier];
223
+        }
224
+        $tagger = $tagManager->load('files');
225
+        $tags = $tagger->getTagsForObjects($ids);
226 226
 
227
-		if (!is_array($tags)) {
228
-			throw new \UnexpectedValueException('$tags must be an array');
229
-		}
227
+        if (!is_array($tags)) {
228
+            throw new \UnexpectedValueException('$tags must be an array');
229
+        }
230 230
 
231
-		// Set empty tag array
232
-		foreach ($fileList as $key => $fileData) {
233
-			$fileList[$key]['tags'] = [];
234
-		}
231
+        // Set empty tag array
232
+        foreach ($fileList as $key => $fileData) {
233
+            $fileList[$key]['tags'] = [];
234
+        }
235 235
 
236
-		if (!empty($tags)) {
237
-			foreach ($tags as $fileId => $fileTags) {
238
-				foreach ($fileList as $key => $fileData) {
239
-					if ($fileId !== $fileData[$fileIdentifier]) {
240
-						continue;
241
-					}
236
+        if (!empty($tags)) {
237
+            foreach ($tags as $fileId => $fileTags) {
238
+                foreach ($fileList as $key => $fileData) {
239
+                    if ($fileId !== $fileData[$fileIdentifier]) {
240
+                        continue;
241
+                    }
242 242
 
243
-					$fileList[$key]['tags'] = $fileTags;
244
-				}
245
-			}
246
-		}
243
+                    $fileList[$key]['tags'] = $fileTags;
244
+                }
245
+            }
246
+        }
247 247
 
248
-		return $fileList;
249
-	}
248
+        return $fileList;
249
+    }
250 250
 
251
-	/**
252
-	 * Sort the given file info array
253
-	 *
254
-	 * @param \OCP\Files\FileInfo[] $files files to sort
255
-	 * @param string $sortAttribute attribute to sort on
256
-	 * @param bool $sortDescending true for descending sort, false otherwise
257
-	 * @return \OCP\Files\FileInfo[] sorted files
258
-	 */
259
-	public static function sortFiles($files, $sortAttribute = 'name', $sortDescending = false) {
260
-		$sortFunc = 'compareFileNames';
261
-		if ($sortAttribute === 'mtime') {
262
-			$sortFunc = 'compareTimestamp';
263
-		} elseif ($sortAttribute === 'size') {
264
-			$sortFunc = 'compareSize';
265
-		}
266
-		usort($files, [Helper::class, $sortFunc]);
267
-		if ($sortDescending) {
268
-			$files = array_reverse($files);
269
-		}
270
-		return $files;
271
-	}
251
+    /**
252
+     * Sort the given file info array
253
+     *
254
+     * @param \OCP\Files\FileInfo[] $files files to sort
255
+     * @param string $sortAttribute attribute to sort on
256
+     * @param bool $sortDescending true for descending sort, false otherwise
257
+     * @return \OCP\Files\FileInfo[] sorted files
258
+     */
259
+    public static function sortFiles($files, $sortAttribute = 'name', $sortDescending = false) {
260
+        $sortFunc = 'compareFileNames';
261
+        if ($sortAttribute === 'mtime') {
262
+            $sortFunc = 'compareTimestamp';
263
+        } elseif ($sortAttribute === 'size') {
264
+            $sortFunc = 'compareSize';
265
+        }
266
+        usort($files, [Helper::class, $sortFunc]);
267
+        if ($sortDescending) {
268
+            $files = array_reverse($files);
269
+        }
270
+        return $files;
271
+    }
272 272
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -60,7 +60,7 @@  discard block
 block discarded – undo
60 60
 			'freeSpace' => $storageInfo['free'],
61 61
 			'quota' => $storageInfo['quota'],
62 62
 			'used' => $storageInfo['used'],
63
-			'usedSpacePercent'  => (int)$storageInfo['relative'],
63
+			'usedSpacePercent'  => (int) $storageInfo['relative'],
64 64
 			'owner' => $storageInfo['owner'],
65 65
 			'ownerDisplayName' => $storageInfo['ownerDisplayName'],
66 66
 			'mountType' => $storageInfo['mountType'],
@@ -86,7 +86,7 @@  discard block
 block discarded – undo
86 86
 			$icon = \OC::$server->getMimeTypeDetector()->mimeTypeIcon($file->getMimetype());
87 87
 		}
88 88
 
89
-		return substr($icon, 0, -3) . 'svg';
89
+		return substr($icon, 0, -3).'svg';
90 90
 	}
91 91
 
92 92
 	/**
Please login to merge, or discard this patch.
lib/private/legacy/OC_Helper.php 1 patch
Indentation   +550 added lines, -550 removed lines patch added patch discarded remove patch
@@ -50,554 +50,554 @@
 block discarded – undo
50 50
  * Collection of useful functions
51 51
  */
52 52
 class OC_Helper {
53
-	private static $templateManager;
54
-
55
-	/**
56
-	 * Make a human file size
57
-	 * @param int $bytes file size in bytes
58
-	 * @return string a human readable file size
59
-	 *
60
-	 * Makes 2048 to 2 kB.
61
-	 */
62
-	public static function humanFileSize($bytes) {
63
-		if ($bytes < 0) {
64
-			return "?";
65
-		}
66
-		if ($bytes < 1024) {
67
-			return "$bytes B";
68
-		}
69
-		$bytes = round($bytes / 1024, 0);
70
-		if ($bytes < 1024) {
71
-			return "$bytes KB";
72
-		}
73
-		$bytes = round($bytes / 1024, 1);
74
-		if ($bytes < 1024) {
75
-			return "$bytes MB";
76
-		}
77
-		$bytes = round($bytes / 1024, 1);
78
-		if ($bytes < 1024) {
79
-			return "$bytes GB";
80
-		}
81
-		$bytes = round($bytes / 1024, 1);
82
-		if ($bytes < 1024) {
83
-			return "$bytes TB";
84
-		}
85
-
86
-		$bytes = round($bytes / 1024, 1);
87
-		return "$bytes PB";
88
-	}
89
-
90
-	/**
91
-	 * Make a computer file size
92
-	 * @param string $str file size in human readable format
93
-	 * @return float|bool a file size in bytes
94
-	 *
95
-	 * Makes 2kB to 2048.
96
-	 *
97
-	 * Inspired by: http://www.php.net/manual/en/function.filesize.php#92418
98
-	 */
99
-	public static function computerFileSize($str) {
100
-		$str = strtolower($str);
101
-		if (is_numeric($str)) {
102
-			return (float)$str;
103
-		}
104
-
105
-		$bytes_array = [
106
-			'b' => 1,
107
-			'k' => 1024,
108
-			'kb' => 1024,
109
-			'mb' => 1024 * 1024,
110
-			'm' => 1024 * 1024,
111
-			'gb' => 1024 * 1024 * 1024,
112
-			'g' => 1024 * 1024 * 1024,
113
-			'tb' => 1024 * 1024 * 1024 * 1024,
114
-			't' => 1024 * 1024 * 1024 * 1024,
115
-			'pb' => 1024 * 1024 * 1024 * 1024 * 1024,
116
-			'p' => 1024 * 1024 * 1024 * 1024 * 1024,
117
-		];
118
-
119
-		$bytes = (float)$str;
120
-
121
-		if (preg_match('#([kmgtp]?b?)$#si', $str, $matches) && !empty($bytes_array[$matches[1]])) {
122
-			$bytes *= $bytes_array[$matches[1]];
123
-		} else {
124
-			return false;
125
-		}
126
-
127
-		$bytes = round($bytes);
128
-
129
-		return $bytes;
130
-	}
131
-
132
-	/**
133
-	 * Recursive copying of folders
134
-	 * @param string $src source folder
135
-	 * @param string $dest target folder
136
-	 *
137
-	 */
138
-	public static function copyr($src, $dest) {
139
-		if (is_dir($src)) {
140
-			if (!is_dir($dest)) {
141
-				mkdir($dest);
142
-			}
143
-			$files = scandir($src);
144
-			foreach ($files as $file) {
145
-				if ($file != "." && $file != "..") {
146
-					self::copyr("$src/$file", "$dest/$file");
147
-				}
148
-			}
149
-		} elseif (file_exists($src) && !\OC\Files\Filesystem::isFileBlacklisted($src)) {
150
-			copy($src, $dest);
151
-		}
152
-	}
153
-
154
-	/**
155
-	 * Recursive deletion of folders
156
-	 * @param string $dir path to the folder
157
-	 * @param bool $deleteSelf if set to false only the content of the folder will be deleted
158
-	 * @return bool
159
-	 */
160
-	public static function rmdirr($dir, $deleteSelf = true) {
161
-		if (is_dir($dir)) {
162
-			$files = new RecursiveIteratorIterator(
163
-				new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS),
164
-				RecursiveIteratorIterator::CHILD_FIRST
165
-			);
166
-
167
-			foreach ($files as $fileInfo) {
168
-				/** @var SplFileInfo $fileInfo */
169
-				if ($fileInfo->isLink()) {
170
-					unlink($fileInfo->getPathname());
171
-				} elseif ($fileInfo->isDir()) {
172
-					rmdir($fileInfo->getRealPath());
173
-				} else {
174
-					unlink($fileInfo->getRealPath());
175
-				}
176
-			}
177
-			if ($deleteSelf) {
178
-				rmdir($dir);
179
-			}
180
-		} elseif (file_exists($dir)) {
181
-			if ($deleteSelf) {
182
-				unlink($dir);
183
-			}
184
-		}
185
-		if (!$deleteSelf) {
186
-			return true;
187
-		}
188
-
189
-		return !file_exists($dir);
190
-	}
191
-
192
-	/**
193
-	 * @deprecated 18.0.0
194
-	 * @return \OC\Files\Type\TemplateManager
195
-	 */
196
-	public static function getFileTemplateManager() {
197
-		if (!self::$templateManager) {
198
-			self::$templateManager = new \OC\Files\Type\TemplateManager();
199
-		}
200
-		return self::$templateManager;
201
-	}
202
-
203
-	/**
204
-	 * detect if a given program is found in the search PATH
205
-	 *
206
-	 * @param string $name
207
-	 * @param bool $path
208
-	 * @internal param string $program name
209
-	 * @internal param string $optional search path, defaults to $PATH
210
-	 * @return bool    true if executable program found in path
211
-	 */
212
-	public static function canExecute($name, $path = false) {
213
-		// path defaults to PATH from environment if not set
214
-		if ($path === false) {
215
-			$path = getenv("PATH");
216
-		}
217
-		// we look for an executable file of that name
218
-		$exts = [""];
219
-		$check_fn = "is_executable";
220
-		// Default check will be done with $path directories :
221
-		$dirs = explode(PATH_SEPARATOR, $path);
222
-		// WARNING : We have to check if open_basedir is enabled :
223
-		$obd = OC::$server->get(IniGetWrapper::class)->getString('open_basedir');
224
-		if ($obd != "none") {
225
-			$obd_values = explode(PATH_SEPARATOR, $obd);
226
-			if (count($obd_values) > 0 and $obd_values[0]) {
227
-				// open_basedir is in effect !
228
-				// We need to check if the program is in one of these dirs :
229
-				$dirs = $obd_values;
230
-			}
231
-		}
232
-		foreach ($dirs as $dir) {
233
-			foreach ($exts as $ext) {
234
-				if ($check_fn("$dir/$name" . $ext)) {
235
-					return true;
236
-				}
237
-			}
238
-		}
239
-		return false;
240
-	}
241
-
242
-	/**
243
-	 * copy the contents of one stream to another
244
-	 *
245
-	 * @param resource $source
246
-	 * @param resource $target
247
-	 * @return array the number of bytes copied and result
248
-	 */
249
-	public static function streamCopy($source, $target) {
250
-		if (!$source or !$target) {
251
-			return [0, false];
252
-		}
253
-		$bufSize = 8192;
254
-		$result = true;
255
-		$count = 0;
256
-		while (!feof($source)) {
257
-			$buf = fread($source, $bufSize);
258
-			$bytesWritten = fwrite($target, $buf);
259
-			if ($bytesWritten !== false) {
260
-				$count += $bytesWritten;
261
-			}
262
-			// note: strlen is expensive so only use it when necessary,
263
-			// on the last block
264
-			if ($bytesWritten === false
265
-				|| ($bytesWritten < $bufSize && $bytesWritten < strlen($buf))
266
-			) {
267
-				// write error, could be disk full ?
268
-				$result = false;
269
-				break;
270
-			}
271
-		}
272
-		return [$count, $result];
273
-	}
274
-
275
-	/**
276
-	 * Adds a suffix to the name in case the file exists
277
-	 *
278
-	 * @param string $path
279
-	 * @param string $filename
280
-	 * @return string
281
-	 */
282
-	public static function buildNotExistingFileName($path, $filename) {
283
-		$view = \OC\Files\Filesystem::getView();
284
-		return self::buildNotExistingFileNameForView($path, $filename, $view);
285
-	}
286
-
287
-	/**
288
-	 * Adds a suffix to the name in case the file exists
289
-	 *
290
-	 * @param string $path
291
-	 * @param string $filename
292
-	 * @return string
293
-	 */
294
-	public static function buildNotExistingFileNameForView($path, $filename, \OC\Files\View $view) {
295
-		if ($path === '/') {
296
-			$path = '';
297
-		}
298
-		if ($pos = strrpos($filename, '.')) {
299
-			$name = substr($filename, 0, $pos);
300
-			$ext = substr($filename, $pos);
301
-		} else {
302
-			$name = $filename;
303
-			$ext = '';
304
-		}
305
-
306
-		$newpath = $path . '/' . $filename;
307
-		if ($view->file_exists($newpath)) {
308
-			if (preg_match_all('/\((\d+)\)/', $name, $matches, PREG_OFFSET_CAPTURE)) {
309
-				//Replace the last "(number)" with "(number+1)"
310
-				$last_match = count($matches[0]) - 1;
311
-				$counter = $matches[1][$last_match][0] + 1;
312
-				$offset = $matches[0][$last_match][1];
313
-				$match_length = strlen($matches[0][$last_match][0]);
314
-			} else {
315
-				$counter = 2;
316
-				$match_length = 0;
317
-				$offset = false;
318
-			}
319
-			do {
320
-				if ($offset) {
321
-					//Replace the last "(number)" with "(number+1)"
322
-					$newname = substr_replace($name, '(' . $counter . ')', $offset, $match_length);
323
-				} else {
324
-					$newname = $name . ' (' . $counter . ')';
325
-				}
326
-				$newpath = $path . '/' . $newname . $ext;
327
-				$counter++;
328
-			} while ($view->file_exists($newpath));
329
-		}
330
-
331
-		return $newpath;
332
-	}
333
-
334
-	/**
335
-	 * Returns an array with all keys from input lowercased or uppercased. Numbered indices are left as is.
336
-	 *
337
-	 * @param array $input The array to work on
338
-	 * @param int $case Either MB_CASE_UPPER or MB_CASE_LOWER (default)
339
-	 * @param string $encoding The encoding parameter is the character encoding. Defaults to UTF-8
340
-	 * @return array
341
-	 *
342
-	 * Returns an array with all keys from input lowercased or uppercased. Numbered indices are left as is.
343
-	 * based on http://www.php.net/manual/en/function.array-change-key-case.php#107715
344
-	 *
345
-	 */
346
-	public static function mb_array_change_key_case($input, $case = MB_CASE_LOWER, $encoding = 'UTF-8') {
347
-		$case = ($case != MB_CASE_UPPER) ? MB_CASE_LOWER : MB_CASE_UPPER;
348
-		$ret = [];
349
-		foreach ($input as $k => $v) {
350
-			$ret[mb_convert_case($k, $case, $encoding)] = $v;
351
-		}
352
-		return $ret;
353
-	}
354
-
355
-	/**
356
-	 * performs a search in a nested array
357
-	 * @param array $haystack the array to be searched
358
-	 * @param string $needle the search string
359
-	 * @param mixed $index optional, only search this key name
360
-	 * @return mixed the key of the matching field, otherwise false
361
-	 *
362
-	 * performs a search in a nested array
363
-	 *
364
-	 * taken from http://www.php.net/manual/en/function.array-search.php#97645
365
-	 */
366
-	public static function recursiveArraySearch($haystack, $needle, $index = null) {
367
-		$aIt = new RecursiveArrayIterator($haystack);
368
-		$it = new RecursiveIteratorIterator($aIt);
369
-
370
-		while ($it->valid()) {
371
-			if (((isset($index) and ($it->key() == $index)) or !isset($index)) and ($it->current() == $needle)) {
372
-				return $aIt->key();
373
-			}
374
-
375
-			$it->next();
376
-		}
377
-
378
-		return false;
379
-	}
380
-
381
-	/**
382
-	 * calculates the maximum upload size respecting system settings, free space and user quota
383
-	 *
384
-	 * @param string $dir the current folder where the user currently operates
385
-	 * @param int $freeSpace the number of bytes free on the storage holding $dir, if not set this will be received from the storage directly
386
-	 * @return int number of bytes representing
387
-	 */
388
-	public static function maxUploadFilesize($dir, $freeSpace = null) {
389
-		if (is_null($freeSpace) || $freeSpace < 0) {
390
-			$freeSpace = self::freeSpace($dir);
391
-		}
392
-		return min($freeSpace, self::uploadLimit());
393
-	}
394
-
395
-	/**
396
-	 * Calculate free space left within user quota
397
-	 *
398
-	 * @param string $dir the current folder where the user currently operates
399
-	 * @return int number of bytes representing
400
-	 */
401
-	public static function freeSpace($dir) {
402
-		$freeSpace = \OC\Files\Filesystem::free_space($dir);
403
-		if ($freeSpace < \OCP\Files\FileInfo::SPACE_UNLIMITED) {
404
-			$freeSpace = max($freeSpace, 0);
405
-			return $freeSpace;
406
-		} else {
407
-			return (INF > 0)? INF: PHP_INT_MAX; // work around https://bugs.php.net/bug.php?id=69188
408
-		}
409
-	}
410
-
411
-	/**
412
-	 * Calculate PHP upload limit
413
-	 *
414
-	 * @return int PHP upload file size limit
415
-	 */
416
-	public static function uploadLimit() {
417
-		$ini = \OC::$server->get(IniGetWrapper::class);
418
-		$upload_max_filesize = OCP\Util::computerFileSize($ini->get('upload_max_filesize'));
419
-		$post_max_size = OCP\Util::computerFileSize($ini->get('post_max_size'));
420
-		if ((int)$upload_max_filesize === 0 and (int)$post_max_size === 0) {
421
-			return INF;
422
-		} elseif ((int)$upload_max_filesize === 0 or (int)$post_max_size === 0) {
423
-			return max($upload_max_filesize, $post_max_size); //only the non 0 value counts
424
-		} else {
425
-			return min($upload_max_filesize, $post_max_size);
426
-		}
427
-	}
428
-
429
-	/**
430
-	 * Checks if a function is available
431
-	 *
432
-	 * @param string $function_name
433
-	 * @return bool
434
-	 */
435
-	public static function is_function_enabled($function_name) {
436
-		if (!function_exists($function_name)) {
437
-			return false;
438
-		}
439
-		$ini = \OC::$server->get(IniGetWrapper::class);
440
-		$disabled = explode(',', $ini->get('disable_functions') ?: '');
441
-		$disabled = array_map('trim', $disabled);
442
-		if (in_array($function_name, $disabled)) {
443
-			return false;
444
-		}
445
-		$disabled = explode(',', $ini->get('suhosin.executor.func.blacklist') ?: '');
446
-		$disabled = array_map('trim', $disabled);
447
-		if (in_array($function_name, $disabled)) {
448
-			return false;
449
-		}
450
-		return true;
451
-	}
452
-
453
-	/**
454
-	 * Try to find a program
455
-	 *
456
-	 * @param string $program
457
-	 * @return null|string
458
-	 */
459
-	public static function findBinaryPath($program) {
460
-		$memcache = \OC::$server->getMemCacheFactory()->createDistributed('findBinaryPath');
461
-		if ($memcache->hasKey($program)) {
462
-			return $memcache->get($program);
463
-		}
464
-		$result = null;
465
-		if (self::is_function_enabled('exec')) {
466
-			$exeSniffer = new ExecutableFinder();
467
-			// Returns null if nothing is found
468
-			$result = $exeSniffer->find($program, null, ['/usr/local/sbin', '/usr/local/bin', '/usr/sbin', '/usr/bin', '/sbin', '/bin', '/opt/bin']);
469
-		}
470
-		// store the value for 5 minutes
471
-		$memcache->set($program, $result, 300);
472
-		return $result;
473
-	}
474
-
475
-	/**
476
-	 * Calculate the disc space for the given path
477
-	 *
478
-	 * @param string $path
479
-	 * @param \OCP\Files\FileInfo $rootInfo (optional)
480
-	 * @return array
481
-	 * @throws \OCP\Files\NotFoundException
482
-	 */
483
-	public static function getStorageInfo($path, $rootInfo = null) {
484
-		// return storage info without adding mount points
485
-		$includeExtStorage = \OC::$server->getSystemConfig()->getValue('quota_include_external_storage', false);
486
-
487
-		if (!$rootInfo) {
488
-			$rootInfo = \OC\Files\Filesystem::getFileInfo($path, $includeExtStorage ? 'ext' : false);
489
-		}
490
-		if (!$rootInfo instanceof \OCP\Files\FileInfo) {
491
-			throw new \OCP\Files\NotFoundException();
492
-		}
493
-		$used = $rootInfo->getSize();
494
-		if ($used < 0) {
495
-			$used = 0;
496
-		}
497
-		$quota = \OCP\Files\FileInfo::SPACE_UNLIMITED;
498
-		$mount = $rootInfo->getMountPoint();
499
-		$storage = $mount->getStorage();
500
-		$sourceStorage = $storage;
501
-		if ($storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage')) {
502
-			$includeExtStorage = false;
503
-			$sourceStorage = $storage->getSourceStorage();
504
-		}
505
-		if ($includeExtStorage) {
506
-			if ($storage->instanceOfStorage('\OC\Files\Storage\Home')
507
-				|| $storage->instanceOfStorage('\OC\Files\ObjectStore\HomeObjectStoreStorage')
508
-			) {
509
-				/** @var \OC\Files\Storage\Home $storage */
510
-				$user = $storage->getUser();
511
-			} else {
512
-				$user = \OC::$server->getUserSession()->getUser();
513
-			}
514
-			$quota = OC_Util::getUserQuota($user);
515
-			if ($quota !== \OCP\Files\FileInfo::SPACE_UNLIMITED) {
516
-				// always get free space / total space from root + mount points
517
-				return self::getGlobalStorageInfo($quota);
518
-			}
519
-		}
520
-
521
-		// TODO: need a better way to get total space from storage
522
-		if ($sourceStorage->instanceOfStorage('\OC\Files\Storage\Wrapper\Quota')) {
523
-			/** @var \OC\Files\Storage\Wrapper\Quota $storage */
524
-			$quota = $sourceStorage->getQuota();
525
-		}
526
-		$free = $sourceStorage->free_space($rootInfo->getInternalPath());
527
-		if ($free >= 0) {
528
-			$total = $free + $used;
529
-		} else {
530
-			$total = $free; //either unknown or unlimited
531
-		}
532
-		if ($total > 0) {
533
-			if ($quota > 0 && $total > $quota) {
534
-				$total = $quota;
535
-			}
536
-			// prevent division by zero or error codes (negative values)
537
-			$relative = round(($used / $total) * 10000) / 100;
538
-		} else {
539
-			$relative = 0;
540
-		}
541
-
542
-		$ownerId = $storage->getOwner($path);
543
-		$ownerDisplayName = '';
544
-		$owner = \OC::$server->getUserManager()->get($ownerId);
545
-		if ($owner) {
546
-			$ownerDisplayName = $owner->getDisplayName();
547
-		}
548
-
549
-		return [
550
-			'free' => $free,
551
-			'used' => $used,
552
-			'quota' => $quota,
553
-			'total' => $total,
554
-			'relative' => $relative,
555
-			'owner' => $ownerId,
556
-			'ownerDisplayName' => $ownerDisplayName,
557
-			'mountType' => $mount->getMountType()
558
-		];
559
-	}
560
-
561
-	/**
562
-	 * Get storage info including all mount points and quota
563
-	 *
564
-	 * @param int $quota
565
-	 * @return array
566
-	 */
567
-	private static function getGlobalStorageInfo($quota) {
568
-		$rootInfo = \OC\Files\Filesystem::getFileInfo('', 'ext');
569
-		$used = $rootInfo['size'];
570
-		if ($used < 0) {
571
-			$used = 0;
572
-		}
573
-
574
-		$total = $quota;
575
-		$free = $quota - $used;
576
-
577
-		if ($total > 0) {
578
-			if ($quota > 0 && $total > $quota) {
579
-				$total = $quota;
580
-			}
581
-			// prevent division by zero or error codes (negative values)
582
-			$relative = round(($used / $total) * 10000) / 100;
583
-		} else {
584
-			$relative = 0;
585
-		}
586
-
587
-		return [
588
-			'free' => $free,
589
-			'used' => $used,
590
-			'total' => $total,
591
-			'relative' => $relative,
592
-			'quota' => $quota
593
-		];
594
-	}
595
-
596
-	/**
597
-	 * Returns whether the config file is set manually to read-only
598
-	 * @return bool
599
-	 */
600
-	public static function isReadOnlyConfigEnabled() {
601
-		return \OC::$server->getConfig()->getSystemValue('config_is_read_only', false);
602
-	}
53
+    private static $templateManager;
54
+
55
+    /**
56
+     * Make a human file size
57
+     * @param int $bytes file size in bytes
58
+     * @return string a human readable file size
59
+     *
60
+     * Makes 2048 to 2 kB.
61
+     */
62
+    public static function humanFileSize($bytes) {
63
+        if ($bytes < 0) {
64
+            return "?";
65
+        }
66
+        if ($bytes < 1024) {
67
+            return "$bytes B";
68
+        }
69
+        $bytes = round($bytes / 1024, 0);
70
+        if ($bytes < 1024) {
71
+            return "$bytes KB";
72
+        }
73
+        $bytes = round($bytes / 1024, 1);
74
+        if ($bytes < 1024) {
75
+            return "$bytes MB";
76
+        }
77
+        $bytes = round($bytes / 1024, 1);
78
+        if ($bytes < 1024) {
79
+            return "$bytes GB";
80
+        }
81
+        $bytes = round($bytes / 1024, 1);
82
+        if ($bytes < 1024) {
83
+            return "$bytes TB";
84
+        }
85
+
86
+        $bytes = round($bytes / 1024, 1);
87
+        return "$bytes PB";
88
+    }
89
+
90
+    /**
91
+     * Make a computer file size
92
+     * @param string $str file size in human readable format
93
+     * @return float|bool a file size in bytes
94
+     *
95
+     * Makes 2kB to 2048.
96
+     *
97
+     * Inspired by: http://www.php.net/manual/en/function.filesize.php#92418
98
+     */
99
+    public static function computerFileSize($str) {
100
+        $str = strtolower($str);
101
+        if (is_numeric($str)) {
102
+            return (float)$str;
103
+        }
104
+
105
+        $bytes_array = [
106
+            'b' => 1,
107
+            'k' => 1024,
108
+            'kb' => 1024,
109
+            'mb' => 1024 * 1024,
110
+            'm' => 1024 * 1024,
111
+            'gb' => 1024 * 1024 * 1024,
112
+            'g' => 1024 * 1024 * 1024,
113
+            'tb' => 1024 * 1024 * 1024 * 1024,
114
+            't' => 1024 * 1024 * 1024 * 1024,
115
+            'pb' => 1024 * 1024 * 1024 * 1024 * 1024,
116
+            'p' => 1024 * 1024 * 1024 * 1024 * 1024,
117
+        ];
118
+
119
+        $bytes = (float)$str;
120
+
121
+        if (preg_match('#([kmgtp]?b?)$#si', $str, $matches) && !empty($bytes_array[$matches[1]])) {
122
+            $bytes *= $bytes_array[$matches[1]];
123
+        } else {
124
+            return false;
125
+        }
126
+
127
+        $bytes = round($bytes);
128
+
129
+        return $bytes;
130
+    }
131
+
132
+    /**
133
+     * Recursive copying of folders
134
+     * @param string $src source folder
135
+     * @param string $dest target folder
136
+     *
137
+     */
138
+    public static function copyr($src, $dest) {
139
+        if (is_dir($src)) {
140
+            if (!is_dir($dest)) {
141
+                mkdir($dest);
142
+            }
143
+            $files = scandir($src);
144
+            foreach ($files as $file) {
145
+                if ($file != "." && $file != "..") {
146
+                    self::copyr("$src/$file", "$dest/$file");
147
+                }
148
+            }
149
+        } elseif (file_exists($src) && !\OC\Files\Filesystem::isFileBlacklisted($src)) {
150
+            copy($src, $dest);
151
+        }
152
+    }
153
+
154
+    /**
155
+     * Recursive deletion of folders
156
+     * @param string $dir path to the folder
157
+     * @param bool $deleteSelf if set to false only the content of the folder will be deleted
158
+     * @return bool
159
+     */
160
+    public static function rmdirr($dir, $deleteSelf = true) {
161
+        if (is_dir($dir)) {
162
+            $files = new RecursiveIteratorIterator(
163
+                new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS),
164
+                RecursiveIteratorIterator::CHILD_FIRST
165
+            );
166
+
167
+            foreach ($files as $fileInfo) {
168
+                /** @var SplFileInfo $fileInfo */
169
+                if ($fileInfo->isLink()) {
170
+                    unlink($fileInfo->getPathname());
171
+                } elseif ($fileInfo->isDir()) {
172
+                    rmdir($fileInfo->getRealPath());
173
+                } else {
174
+                    unlink($fileInfo->getRealPath());
175
+                }
176
+            }
177
+            if ($deleteSelf) {
178
+                rmdir($dir);
179
+            }
180
+        } elseif (file_exists($dir)) {
181
+            if ($deleteSelf) {
182
+                unlink($dir);
183
+            }
184
+        }
185
+        if (!$deleteSelf) {
186
+            return true;
187
+        }
188
+
189
+        return !file_exists($dir);
190
+    }
191
+
192
+    /**
193
+     * @deprecated 18.0.0
194
+     * @return \OC\Files\Type\TemplateManager
195
+     */
196
+    public static function getFileTemplateManager() {
197
+        if (!self::$templateManager) {
198
+            self::$templateManager = new \OC\Files\Type\TemplateManager();
199
+        }
200
+        return self::$templateManager;
201
+    }
202
+
203
+    /**
204
+     * detect if a given program is found in the search PATH
205
+     *
206
+     * @param string $name
207
+     * @param bool $path
208
+     * @internal param string $program name
209
+     * @internal param string $optional search path, defaults to $PATH
210
+     * @return bool    true if executable program found in path
211
+     */
212
+    public static function canExecute($name, $path = false) {
213
+        // path defaults to PATH from environment if not set
214
+        if ($path === false) {
215
+            $path = getenv("PATH");
216
+        }
217
+        // we look for an executable file of that name
218
+        $exts = [""];
219
+        $check_fn = "is_executable";
220
+        // Default check will be done with $path directories :
221
+        $dirs = explode(PATH_SEPARATOR, $path);
222
+        // WARNING : We have to check if open_basedir is enabled :
223
+        $obd = OC::$server->get(IniGetWrapper::class)->getString('open_basedir');
224
+        if ($obd != "none") {
225
+            $obd_values = explode(PATH_SEPARATOR, $obd);
226
+            if (count($obd_values) > 0 and $obd_values[0]) {
227
+                // open_basedir is in effect !
228
+                // We need to check if the program is in one of these dirs :
229
+                $dirs = $obd_values;
230
+            }
231
+        }
232
+        foreach ($dirs as $dir) {
233
+            foreach ($exts as $ext) {
234
+                if ($check_fn("$dir/$name" . $ext)) {
235
+                    return true;
236
+                }
237
+            }
238
+        }
239
+        return false;
240
+    }
241
+
242
+    /**
243
+     * copy the contents of one stream to another
244
+     *
245
+     * @param resource $source
246
+     * @param resource $target
247
+     * @return array the number of bytes copied and result
248
+     */
249
+    public static function streamCopy($source, $target) {
250
+        if (!$source or !$target) {
251
+            return [0, false];
252
+        }
253
+        $bufSize = 8192;
254
+        $result = true;
255
+        $count = 0;
256
+        while (!feof($source)) {
257
+            $buf = fread($source, $bufSize);
258
+            $bytesWritten = fwrite($target, $buf);
259
+            if ($bytesWritten !== false) {
260
+                $count += $bytesWritten;
261
+            }
262
+            // note: strlen is expensive so only use it when necessary,
263
+            // on the last block
264
+            if ($bytesWritten === false
265
+                || ($bytesWritten < $bufSize && $bytesWritten < strlen($buf))
266
+            ) {
267
+                // write error, could be disk full ?
268
+                $result = false;
269
+                break;
270
+            }
271
+        }
272
+        return [$count, $result];
273
+    }
274
+
275
+    /**
276
+     * Adds a suffix to the name in case the file exists
277
+     *
278
+     * @param string $path
279
+     * @param string $filename
280
+     * @return string
281
+     */
282
+    public static function buildNotExistingFileName($path, $filename) {
283
+        $view = \OC\Files\Filesystem::getView();
284
+        return self::buildNotExistingFileNameForView($path, $filename, $view);
285
+    }
286
+
287
+    /**
288
+     * Adds a suffix to the name in case the file exists
289
+     *
290
+     * @param string $path
291
+     * @param string $filename
292
+     * @return string
293
+     */
294
+    public static function buildNotExistingFileNameForView($path, $filename, \OC\Files\View $view) {
295
+        if ($path === '/') {
296
+            $path = '';
297
+        }
298
+        if ($pos = strrpos($filename, '.')) {
299
+            $name = substr($filename, 0, $pos);
300
+            $ext = substr($filename, $pos);
301
+        } else {
302
+            $name = $filename;
303
+            $ext = '';
304
+        }
305
+
306
+        $newpath = $path . '/' . $filename;
307
+        if ($view->file_exists($newpath)) {
308
+            if (preg_match_all('/\((\d+)\)/', $name, $matches, PREG_OFFSET_CAPTURE)) {
309
+                //Replace the last "(number)" with "(number+1)"
310
+                $last_match = count($matches[0]) - 1;
311
+                $counter = $matches[1][$last_match][0] + 1;
312
+                $offset = $matches[0][$last_match][1];
313
+                $match_length = strlen($matches[0][$last_match][0]);
314
+            } else {
315
+                $counter = 2;
316
+                $match_length = 0;
317
+                $offset = false;
318
+            }
319
+            do {
320
+                if ($offset) {
321
+                    //Replace the last "(number)" with "(number+1)"
322
+                    $newname = substr_replace($name, '(' . $counter . ')', $offset, $match_length);
323
+                } else {
324
+                    $newname = $name . ' (' . $counter . ')';
325
+                }
326
+                $newpath = $path . '/' . $newname . $ext;
327
+                $counter++;
328
+            } while ($view->file_exists($newpath));
329
+        }
330
+
331
+        return $newpath;
332
+    }
333
+
334
+    /**
335
+     * Returns an array with all keys from input lowercased or uppercased. Numbered indices are left as is.
336
+     *
337
+     * @param array $input The array to work on
338
+     * @param int $case Either MB_CASE_UPPER or MB_CASE_LOWER (default)
339
+     * @param string $encoding The encoding parameter is the character encoding. Defaults to UTF-8
340
+     * @return array
341
+     *
342
+     * Returns an array with all keys from input lowercased or uppercased. Numbered indices are left as is.
343
+     * based on http://www.php.net/manual/en/function.array-change-key-case.php#107715
344
+     *
345
+     */
346
+    public static function mb_array_change_key_case($input, $case = MB_CASE_LOWER, $encoding = 'UTF-8') {
347
+        $case = ($case != MB_CASE_UPPER) ? MB_CASE_LOWER : MB_CASE_UPPER;
348
+        $ret = [];
349
+        foreach ($input as $k => $v) {
350
+            $ret[mb_convert_case($k, $case, $encoding)] = $v;
351
+        }
352
+        return $ret;
353
+    }
354
+
355
+    /**
356
+     * performs a search in a nested array
357
+     * @param array $haystack the array to be searched
358
+     * @param string $needle the search string
359
+     * @param mixed $index optional, only search this key name
360
+     * @return mixed the key of the matching field, otherwise false
361
+     *
362
+     * performs a search in a nested array
363
+     *
364
+     * taken from http://www.php.net/manual/en/function.array-search.php#97645
365
+     */
366
+    public static function recursiveArraySearch($haystack, $needle, $index = null) {
367
+        $aIt = new RecursiveArrayIterator($haystack);
368
+        $it = new RecursiveIteratorIterator($aIt);
369
+
370
+        while ($it->valid()) {
371
+            if (((isset($index) and ($it->key() == $index)) or !isset($index)) and ($it->current() == $needle)) {
372
+                return $aIt->key();
373
+            }
374
+
375
+            $it->next();
376
+        }
377
+
378
+        return false;
379
+    }
380
+
381
+    /**
382
+     * calculates the maximum upload size respecting system settings, free space and user quota
383
+     *
384
+     * @param string $dir the current folder where the user currently operates
385
+     * @param int $freeSpace the number of bytes free on the storage holding $dir, if not set this will be received from the storage directly
386
+     * @return int number of bytes representing
387
+     */
388
+    public static function maxUploadFilesize($dir, $freeSpace = null) {
389
+        if (is_null($freeSpace) || $freeSpace < 0) {
390
+            $freeSpace = self::freeSpace($dir);
391
+        }
392
+        return min($freeSpace, self::uploadLimit());
393
+    }
394
+
395
+    /**
396
+     * Calculate free space left within user quota
397
+     *
398
+     * @param string $dir the current folder where the user currently operates
399
+     * @return int number of bytes representing
400
+     */
401
+    public static function freeSpace($dir) {
402
+        $freeSpace = \OC\Files\Filesystem::free_space($dir);
403
+        if ($freeSpace < \OCP\Files\FileInfo::SPACE_UNLIMITED) {
404
+            $freeSpace = max($freeSpace, 0);
405
+            return $freeSpace;
406
+        } else {
407
+            return (INF > 0)? INF: PHP_INT_MAX; // work around https://bugs.php.net/bug.php?id=69188
408
+        }
409
+    }
410
+
411
+    /**
412
+     * Calculate PHP upload limit
413
+     *
414
+     * @return int PHP upload file size limit
415
+     */
416
+    public static function uploadLimit() {
417
+        $ini = \OC::$server->get(IniGetWrapper::class);
418
+        $upload_max_filesize = OCP\Util::computerFileSize($ini->get('upload_max_filesize'));
419
+        $post_max_size = OCP\Util::computerFileSize($ini->get('post_max_size'));
420
+        if ((int)$upload_max_filesize === 0 and (int)$post_max_size === 0) {
421
+            return INF;
422
+        } elseif ((int)$upload_max_filesize === 0 or (int)$post_max_size === 0) {
423
+            return max($upload_max_filesize, $post_max_size); //only the non 0 value counts
424
+        } else {
425
+            return min($upload_max_filesize, $post_max_size);
426
+        }
427
+    }
428
+
429
+    /**
430
+     * Checks if a function is available
431
+     *
432
+     * @param string $function_name
433
+     * @return bool
434
+     */
435
+    public static function is_function_enabled($function_name) {
436
+        if (!function_exists($function_name)) {
437
+            return false;
438
+        }
439
+        $ini = \OC::$server->get(IniGetWrapper::class);
440
+        $disabled = explode(',', $ini->get('disable_functions') ?: '');
441
+        $disabled = array_map('trim', $disabled);
442
+        if (in_array($function_name, $disabled)) {
443
+            return false;
444
+        }
445
+        $disabled = explode(',', $ini->get('suhosin.executor.func.blacklist') ?: '');
446
+        $disabled = array_map('trim', $disabled);
447
+        if (in_array($function_name, $disabled)) {
448
+            return false;
449
+        }
450
+        return true;
451
+    }
452
+
453
+    /**
454
+     * Try to find a program
455
+     *
456
+     * @param string $program
457
+     * @return null|string
458
+     */
459
+    public static function findBinaryPath($program) {
460
+        $memcache = \OC::$server->getMemCacheFactory()->createDistributed('findBinaryPath');
461
+        if ($memcache->hasKey($program)) {
462
+            return $memcache->get($program);
463
+        }
464
+        $result = null;
465
+        if (self::is_function_enabled('exec')) {
466
+            $exeSniffer = new ExecutableFinder();
467
+            // Returns null if nothing is found
468
+            $result = $exeSniffer->find($program, null, ['/usr/local/sbin', '/usr/local/bin', '/usr/sbin', '/usr/bin', '/sbin', '/bin', '/opt/bin']);
469
+        }
470
+        // store the value for 5 minutes
471
+        $memcache->set($program, $result, 300);
472
+        return $result;
473
+    }
474
+
475
+    /**
476
+     * Calculate the disc space for the given path
477
+     *
478
+     * @param string $path
479
+     * @param \OCP\Files\FileInfo $rootInfo (optional)
480
+     * @return array
481
+     * @throws \OCP\Files\NotFoundException
482
+     */
483
+    public static function getStorageInfo($path, $rootInfo = null) {
484
+        // return storage info without adding mount points
485
+        $includeExtStorage = \OC::$server->getSystemConfig()->getValue('quota_include_external_storage', false);
486
+
487
+        if (!$rootInfo) {
488
+            $rootInfo = \OC\Files\Filesystem::getFileInfo($path, $includeExtStorage ? 'ext' : false);
489
+        }
490
+        if (!$rootInfo instanceof \OCP\Files\FileInfo) {
491
+            throw new \OCP\Files\NotFoundException();
492
+        }
493
+        $used = $rootInfo->getSize();
494
+        if ($used < 0) {
495
+            $used = 0;
496
+        }
497
+        $quota = \OCP\Files\FileInfo::SPACE_UNLIMITED;
498
+        $mount = $rootInfo->getMountPoint();
499
+        $storage = $mount->getStorage();
500
+        $sourceStorage = $storage;
501
+        if ($storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage')) {
502
+            $includeExtStorage = false;
503
+            $sourceStorage = $storage->getSourceStorage();
504
+        }
505
+        if ($includeExtStorage) {
506
+            if ($storage->instanceOfStorage('\OC\Files\Storage\Home')
507
+                || $storage->instanceOfStorage('\OC\Files\ObjectStore\HomeObjectStoreStorage')
508
+            ) {
509
+                /** @var \OC\Files\Storage\Home $storage */
510
+                $user = $storage->getUser();
511
+            } else {
512
+                $user = \OC::$server->getUserSession()->getUser();
513
+            }
514
+            $quota = OC_Util::getUserQuota($user);
515
+            if ($quota !== \OCP\Files\FileInfo::SPACE_UNLIMITED) {
516
+                // always get free space / total space from root + mount points
517
+                return self::getGlobalStorageInfo($quota);
518
+            }
519
+        }
520
+
521
+        // TODO: need a better way to get total space from storage
522
+        if ($sourceStorage->instanceOfStorage('\OC\Files\Storage\Wrapper\Quota')) {
523
+            /** @var \OC\Files\Storage\Wrapper\Quota $storage */
524
+            $quota = $sourceStorage->getQuota();
525
+        }
526
+        $free = $sourceStorage->free_space($rootInfo->getInternalPath());
527
+        if ($free >= 0) {
528
+            $total = $free + $used;
529
+        } else {
530
+            $total = $free; //either unknown or unlimited
531
+        }
532
+        if ($total > 0) {
533
+            if ($quota > 0 && $total > $quota) {
534
+                $total = $quota;
535
+            }
536
+            // prevent division by zero or error codes (negative values)
537
+            $relative = round(($used / $total) * 10000) / 100;
538
+        } else {
539
+            $relative = 0;
540
+        }
541
+
542
+        $ownerId = $storage->getOwner($path);
543
+        $ownerDisplayName = '';
544
+        $owner = \OC::$server->getUserManager()->get($ownerId);
545
+        if ($owner) {
546
+            $ownerDisplayName = $owner->getDisplayName();
547
+        }
548
+
549
+        return [
550
+            'free' => $free,
551
+            'used' => $used,
552
+            'quota' => $quota,
553
+            'total' => $total,
554
+            'relative' => $relative,
555
+            'owner' => $ownerId,
556
+            'ownerDisplayName' => $ownerDisplayName,
557
+            'mountType' => $mount->getMountType()
558
+        ];
559
+    }
560
+
561
+    /**
562
+     * Get storage info including all mount points and quota
563
+     *
564
+     * @param int $quota
565
+     * @return array
566
+     */
567
+    private static function getGlobalStorageInfo($quota) {
568
+        $rootInfo = \OC\Files\Filesystem::getFileInfo('', 'ext');
569
+        $used = $rootInfo['size'];
570
+        if ($used < 0) {
571
+            $used = 0;
572
+        }
573
+
574
+        $total = $quota;
575
+        $free = $quota - $used;
576
+
577
+        if ($total > 0) {
578
+            if ($quota > 0 && $total > $quota) {
579
+                $total = $quota;
580
+            }
581
+            // prevent division by zero or error codes (negative values)
582
+            $relative = round(($used / $total) * 10000) / 100;
583
+        } else {
584
+            $relative = 0;
585
+        }
586
+
587
+        return [
588
+            'free' => $free,
589
+            'used' => $used,
590
+            'total' => $total,
591
+            'relative' => $relative,
592
+            'quota' => $quota
593
+        ];
594
+    }
595
+
596
+    /**
597
+     * Returns whether the config file is set manually to read-only
598
+     * @return bool
599
+     */
600
+    public static function isReadOnlyConfigEnabled() {
601
+        return \OC::$server->getConfig()->getSystemValue('config_is_read_only', false);
602
+    }
603 603
 }
Please login to merge, or discard this patch.