Passed
Push — php82 ( 33963f...175c47 )
by Alexander
19:12 queued 10:01
created

BaseFileHelper::getExtensionByMimeType()   B

Complexity

Conditions 7
Paths 10

Size

Total Lines 25
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 7.116

Importance

Changes 0
Metric Value
cc 7
eloc 15
nc 10
nop 3
dl 0
loc 25
ccs 13
cts 15
cp 0.8667
crap 7.116
rs 8.8333
c 0
b 0
f 0
1
<?php
2
/**
3
 * @link https://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license https://www.yiiframework.com/license/
6
 */
7
8
namespace yii\helpers;
9
10
use Yii;
11
use yii\base\ErrorException;
12
use yii\base\Exception;
13
use yii\base\InvalidArgumentException;
14
use yii\base\InvalidConfigException;
15
16
/**
17
 * BaseFileHelper provides concrete implementation for [[FileHelper]].
18
 *
19
 * Do not use BaseFileHelper. Use [[FileHelper]] instead.
20
 *
21
 * @author Qiang Xue <[email protected]>
22
 * @author Alex Makarov <[email protected]>
23
 * @since 2.0
24
 */
25
class BaseFileHelper
26
{
27
    const PATTERN_NODIR = 1;
28
    const PATTERN_ENDSWITH = 4;
29
    const PATTERN_MUSTBEDIR = 8;
30
    const PATTERN_NEGATIVE = 16;
31
    const PATTERN_CASE_INSENSITIVE = 32;
32
33
    /**
34
     * @var string the path (or alias) of a PHP file containing MIME type information.
35
     */
36
    public static $mimeMagicFile = '@yii/helpers/mimeTypes.php';
37
    /**
38
     * @var string the path (or alias) of a PHP file containing MIME aliases.
39
     * @since 2.0.14
40
     */
41
    public static $mimeAliasesFile = '@yii/helpers/mimeAliases.php';
42
43
    /**
44
     * @var string the path (or alias) of a PHP file containing extensions per MIME type.
45
     * @since 2.0.48
46
     */
47
    public static $mimeExtensionsFile = '@yii/helpers/mimeExtensions.php';
48
49
50
    /**
51
     * Normalizes a file/directory path.
52
     *
53
     * The normalization does the following work:
54
     *
55
     * - Convert all directory separators into `DIRECTORY_SEPARATOR` (e.g. "\a/b\c" becomes "/a/b/c")
56
     * - Remove trailing directory separators (e.g. "/a/b/c/" becomes "/a/b/c")
57
     * - Turn multiple consecutive slashes into a single one (e.g. "/a///b/c" becomes "/a/b/c")
58
     * - Remove ".." and "." based on their meanings (e.g. "/a/./b/../c" becomes "/a/c")
59
     *
60
     * Note: For registered stream wrappers, the consecutive slashes rule
61
     * and ".."/"." translations are skipped.
62
     *
63
     * @param string $path the file/directory path to be normalized
64
     * @param string $ds the directory separator to be used in the normalized result. Defaults to `DIRECTORY_SEPARATOR`.
65
     * @return string the normalized file/directory path
66
     */
67 36
    public static function normalizePath($path, $ds = DIRECTORY_SEPARATOR)
68
    {
69 36
        $path = rtrim(strtr($path, '/\\', $ds . $ds), $ds);
70 36
        if (strpos($ds . $path, "{$ds}.") === false && strpos($path, "{$ds}{$ds}") === false) {
71 35
            return $path;
72
        }
73
        // fix #17235 stream wrappers
74 1
        foreach (stream_get_wrappers() as $protocol) {
75 1
            if (strpos($path, "{$protocol}://") === 0) {
76 1
                return $path;
77
            }
78
        }
79
        // the path may contain ".", ".." or double slashes, need to clean them up
80 1
        if (strpos($path, "{$ds}{$ds}") === 0 && $ds == '\\') {
81 1
            $parts = [$ds];
82
        } else {
83 1
            $parts = [];
84
        }
85 1
        foreach (explode($ds, $path) as $part) {
86 1
            if ($part === '..' && !empty($parts) && end($parts) !== '..') {
87 1
                array_pop($parts);
88 1
            } elseif ($part === '.' || $part === '' && !empty($parts)) {
89 1
                continue;
90
            } else {
91 1
                $parts[] = $part;
92
            }
93
        }
94 1
        $path = implode($ds, $parts);
95 1
        return $path === '' ? '.' : $path;
96
    }
97
98
    /**
99
     * Returns the localized version of a specified file.
100
     *
101
     * The searching is based on the specified language code. In particular,
102
     * a file with the same name will be looked for under the subdirectory
103
     * whose name is the same as the language code. For example, given the file "path/to/view.php"
104
     * and language code "zh-CN", the localized file will be looked for as
105
     * "path/to/zh-CN/view.php". If the file is not found, it will try a fallback with just a language code that is
106
     * "zh" i.e. "path/to/zh/view.php". If it is not found as well the original file will be returned.
107
     *
108
     * If the target and the source language codes are the same, the original file will be returned.
109
     *
110
     * @param string $file the original file
111
     * @param string|null $language the target language that the file should be localized to.
112
     * If not set, the value of [[\yii\base\Application::language]] will be used.
113
     * @param string|null $sourceLanguage the language that the original file is in.
114
     * If not set, the value of [[\yii\base\Application::sourceLanguage]] will be used.
115
     * @return string the matching localized file, or the original file if the localized version is not found.
116
     * If the target and the source language codes are the same, the original file will be returned.
117
     */
118 157
    public static function localize($file, $language = null, $sourceLanguage = null)
119
    {
120 157
        if ($language === null) {
121 156
            $language = Yii::$app->language;
122
        }
123 157
        if ($sourceLanguage === null) {
124 156
            $sourceLanguage = Yii::$app->sourceLanguage;
125
        }
126 157
        if ($language === $sourceLanguage) {
127 157
            return $file;
128
        }
129 1
        $desiredFile = dirname($file) . DIRECTORY_SEPARATOR . $language . DIRECTORY_SEPARATOR . basename($file);
130 1
        if (is_file($desiredFile)) {
131 1
            return $desiredFile;
132
        }
133
134
        $language = substr($language, 0, 2);
135
        if ($language === $sourceLanguage) {
136
            return $file;
137
        }
138
        $desiredFile = dirname($file) . DIRECTORY_SEPARATOR . $language . DIRECTORY_SEPARATOR . basename($file);
139
140
        return is_file($desiredFile) ? $desiredFile : $file;
141
    }
142
143
    /**
144
     * Determines the MIME type of the specified file.
145
     * This method will first try to determine the MIME type based on
146
     * [finfo_open](https://www.php.net/manual/en/function.finfo-open.php). If the `fileinfo` extension is not installed,
147
     * it will fall back to [[getMimeTypeByExtension()]] when `$checkExtension` is true.
148
     * @param string $file the file name.
149
     * @param string|null $magicFile name of the optional magic database file (or alias), usually something like `/path/to/magic.mime`.
150
     * This will be passed as the second parameter to [finfo_open()](https://www.php.net/manual/en/function.finfo-open.php)
151
     * when the `fileinfo` extension is installed. If the MIME type is being determined based via [[getMimeTypeByExtension()]]
152
     * and this is null, it will use the file specified by [[mimeMagicFile]].
153
     * @param bool $checkExtension whether to use the file extension to determine the MIME type in case
154
     * `finfo_open()` cannot determine it.
155
     * @return string|null the MIME type (e.g. `text/plain`). Null is returned if the MIME type cannot be determined.
156
     * @throws InvalidConfigException when the `fileinfo` PHP extension is not installed and `$checkExtension` is `false`.
157
     */
158 32
    public static function getMimeType($file, $magicFile = null, $checkExtension = true)
159
    {
160 32
        if ($magicFile !== null) {
161
            $magicFile = Yii::getAlias($magicFile);
162
        }
163 32
        if (!extension_loaded('fileinfo')) {
164
            if ($checkExtension) {
165
                return static::getMimeTypeByExtension($file, $magicFile);
0 ignored issues
show
Bug introduced by
It seems like $magicFile can also be of type false; however, parameter $magicFile of yii\helpers\BaseFileHelp...etMimeTypeByExtension() does only seem to accept null|string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

165
                return static::getMimeTypeByExtension($file, /** @scrutinizer ignore-type */ $magicFile);
Loading history...
166
            }
167
168
            throw new InvalidConfigException('The fileinfo PHP extension is not installed.');
169
        }
170
171 32
        $info = finfo_open(FILEINFO_MIME_TYPE, $magicFile);
0 ignored issues
show
Bug introduced by
It seems like $magicFile can also be of type false and null; however, parameter $magic_database of finfo_open() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

171
        $info = finfo_open(FILEINFO_MIME_TYPE, /** @scrutinizer ignore-type */ $magicFile);
Loading history...
172
173 32
        if ($info) {
0 ignored issues
show
introduced by
$info is of type resource, thus it always evaluated to false.
Loading history...
174 32
            $result = finfo_file($info, $file);
175 32
            finfo_close($info);
176
177 32
            if ($result !== false) {
178 32
                return $result;
179
            }
180
        }
181
182
        return $checkExtension ? static::getMimeTypeByExtension($file, $magicFile) : null;
183
    }
184
185
    /**
186
     * Determines the MIME type based on the extension name of the specified file.
187
     * This method will use a local map between extension names and MIME types.
188
     * @param string $file the file name.
189
     * @param string|null $magicFile the path (or alias) of the file that contains all available MIME type information.
190
     * If this is not set, the file specified by [[mimeMagicFile]] will be used.
191
     * @return string|null the MIME type. Null is returned if the MIME type cannot be determined.
192
     */
193 11
    public static function getMimeTypeByExtension($file, $magicFile = null)
194
    {
195 11
        $mimeTypes = static::loadMimeTypes($magicFile);
196
197 11
        if (($ext = pathinfo($file, PATHINFO_EXTENSION)) !== '') {
198 11
            $ext = strtolower($ext);
0 ignored issues
show
Bug introduced by
It seems like $ext can also be of type array; however, parameter $string of strtolower() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

198
            $ext = strtolower(/** @scrutinizer ignore-type */ $ext);
Loading history...
199 11
            if (isset($mimeTypes[$ext])) {
200 11
                return $mimeTypes[$ext];
201
            }
202
        }
203
204 1
        return null;
205
    }
206
207
    /**
208
     * Determines the extensions by given MIME type.
209
     * This method will use a local map between extension names and MIME types.
210
     * @param string $mimeType file MIME type.
211
     * @param string|null $magicFile the path (or alias) of the file that contains all available MIME type information.
212
     * If this is not set, the file specified by [[mimeMagicFile]] will be used.
213
     * @return array the extensions corresponding to the specified MIME type
214
     */
215 15
    public static function getExtensionsByMimeType($mimeType, $magicFile = null)
216
    {
217 15
        $aliases = static::loadMimeAliases(static::$mimeAliasesFile);
218 15
        if (isset($aliases[$mimeType])) {
219 2
            $mimeType = $aliases[$mimeType];
220
        }
221
222
        // Note: For backwards compatibility the "MimeTypes" file is used.
223 15
        $mimeTypes = static::loadMimeTypes($magicFile);
224 15
        return array_keys($mimeTypes, mb_strtolower($mimeType, 'UTF-8'), true);
225
    }
226
227
    /**
228
     * Determines the most common extension by given MIME type.
229
     * This method will use a local map between MIME types and extension names.
230
     * @param string $mimeType file MIME type.
231
     * @param bool $preferShort return an extension with a maximum of 3 characters.
232
     * @param string|null $magicFile the path (or alias) of the file that contains all available MIME type information.
233
     * If this is not set, the file specified by [[mimeMagicFile]] will be used.
234
     * @return string|null the extensions corresponding to the specified MIME type
235
     * @since 2.0.48
236
     */
237 4
    public static function getExtensionByMimeType($mimeType, $preferShort = false, $magicFile = null)
238
    {
239 4
        $aliases = static::loadMimeAliases(static::$mimeAliasesFile);
240 4
        if (isset($aliases[$mimeType])) {
241
            $mimeType = $aliases[$mimeType];
242
        }
243
244 4
        $mimeExtensions = static::loadMimeExtensions($magicFile);
245
246 4
        if (!array_key_exists($mimeType, $mimeExtensions)) {
247
            return null;
248
        }
249
250 4
        $extensions = $mimeExtensions[$mimeType];
251 4
        if (is_array($extensions)) {
252 2
            if ($preferShort) {
253 1
                foreach ($extensions as $extension) {
254 1
                    if (mb_strlen($extension, 'UTF-8') <= 3) {
255 1
                        return $extension;
256
                    }
257
                }
258
            }
259 1
            return $extensions[0];
260
        } else {
261 2
            return $extensions;
262
        }
263
    }
264
265
    private static $_mimeTypes = [];
266
267
    /**
268
     * Loads MIME types from the specified file.
269
     * @param string|null $magicFile the path (or alias) of the file that contains all available MIME type information.
270
     * If this is not set, the file specified by [[mimeMagicFile]] will be used.
271
     * @return array the mapping from file extensions to MIME types
272
     */
273 26
    protected static function loadMimeTypes($magicFile)
274
    {
275 26
        if ($magicFile === null) {
276 26
            $magicFile = static::$mimeMagicFile;
277
        }
278 26
        $magicFile = Yii::getAlias($magicFile);
279 26
        if (!isset(self::$_mimeTypes[$magicFile])) {
280 1
            self::$_mimeTypes[$magicFile] = require $magicFile;
281
        }
282
283 26
        return self::$_mimeTypes[$magicFile];
284
    }
285
286
    private static $_mimeAliases = [];
287
288
    /**
289
     * Loads MIME aliases from the specified file.
290
     * @param string|null $aliasesFile the path (or alias) of the file that contains MIME type aliases.
291
     * If this is not set, the file specified by [[mimeAliasesFile]] will be used.
292
     * @return array the mapping from file extensions to MIME types
293
     * @since 2.0.14
294
     */
295 19
    protected static function loadMimeAliases($aliasesFile)
296
    {
297 19
        if ($aliasesFile === null) {
298
            $aliasesFile = static::$mimeAliasesFile;
299
        }
300 19
        $aliasesFile = Yii::getAlias($aliasesFile);
301 19
        if (!isset(self::$_mimeAliases[$aliasesFile])) {
302 1
            self::$_mimeAliases[$aliasesFile] = require $aliasesFile;
303
        }
304
305 19
        return self::$_mimeAliases[$aliasesFile];
306
    }
307
308
    private static $_mimeExtensions = [];
309
310
    /**
311
     * Loads MIME extensions from the specified file.
312
     * @param string|null $extensionsFile the path (or alias) of the file that contains MIME type aliases.
313
     * If this is not set, the file specified by [[mimeAliasesFile]] will be used.
314
     * @return array the mapping from file extensions to MIME types
315
     * @since 2.0.48
316
     */
317 4
    protected static function loadMimeExtensions($extensionsFile)
318
    {
319 4
        if ($extensionsFile === null) {
320 4
            $extensionsFile = static::$mimeExtensionsFile;
321
        }
322 4
        $extensionsFile = Yii::getAlias($extensionsFile);
323 4
        if (!isset(self::$_mimeExtensions[$extensionsFile])) {
324 1
            self::$_mimeExtensions[$extensionsFile] = require $extensionsFile;
325
        }
326
327 4
        return self::$_mimeExtensions[$extensionsFile];
328
    }
329
330
    /**
331
     * Copies a whole directory as another one.
332
     * The files and sub-directories will also be copied over.
333
     * @param string $src the source directory
334
     * @param string $dst the destination directory
335
     * @param array $options options for directory copy. Valid options are:
336
     *
337
     * - dirMode: integer, the permission to be set for newly copied directories. Defaults to 0775.
338
     * - fileMode:  integer, the permission to be set for newly copied files. Defaults to the current environment setting.
339
     * - filter: callback, a PHP callback that is called for each directory or file.
340
     *   The signature of the callback should be: `function ($path)`, where `$path` refers the full path to be filtered.
341
     *   The callback can return one of the following values:
342
     *
343
     *   * true: the directory or file will be copied (the "only" and "except" options will be ignored)
344
     *   * false: the directory or file will NOT be copied (the "only" and "except" options will be ignored)
345
     *   * null: the "only" and "except" options will determine whether the directory or file should be copied
346
     *
347
     * - only: array, list of patterns that the file paths should match if they want to be copied.
348
     *   A path matches a pattern if it contains the pattern string at its end.
349
     *   For example, '.php' matches all file paths ending with '.php'.
350
     *   Note, the '/' characters in a pattern matches both '/' and '\' in the paths.
351
     *   If a file path matches a pattern in both "only" and "except", it will NOT be copied.
352
     * - except: array, list of patterns that the files or directories should match if they want to be excluded from being copied.
353
     *   A path matches a pattern if it contains the pattern string at its end.
354
     *   Patterns ending with '/' apply to directory paths only, and patterns not ending with '/'
355
     *   apply to file paths only. For example, '/a/b' matches all file paths ending with '/a/b';
356
     *   and '.svn/' matches directory paths ending with '.svn'. Note, the '/' characters in a pattern matches
357
     *   both '/' and '\' in the paths.
358
     * - caseSensitive: boolean, whether patterns specified at "only" or "except" should be case sensitive. Defaults to true.
359
     * - recursive: boolean, whether the files under the subdirectories should also be copied. Defaults to true.
360
     * - beforeCopy: callback, a PHP callback that is called before copying each sub-directory or file.
361
     *   If the callback returns false, the copy operation for the sub-directory or file will be cancelled.
362
     *   The signature of the callback should be: `function ($from, $to)`, where `$from` is the sub-directory or
363
     *   file to be copied from, while `$to` is the copy target.
364
     * - afterCopy: callback, a PHP callback that is called after each sub-directory or file is successfully copied.
365
     *   The signature of the callback should be: `function ($from, $to)`, where `$from` is the sub-directory or
366
     *   file copied from, while `$to` is the copy target.
367
     * - copyEmptyDirectories: boolean, whether to copy empty directories. Set this to false to avoid creating directories
368
     *   that do not contain files. This affects directories that do not contain files initially as well as directories that
369
     *   do not contain files at the target destination because files have been filtered via `only` or `except`.
370
     *   Defaults to true. This option is available since version 2.0.12. Before 2.0.12 empty directories are always copied.
371
     * @throws InvalidArgumentException if unable to open directory
372
     */
373 17
    public static function copyDirectory($src, $dst, $options = [])
374
    {
375 17
        $src = static::normalizePath($src);
376 17
        $dst = static::normalizePath($dst);
377
378 17
        if ($src === $dst || strpos($dst, $src . DIRECTORY_SEPARATOR) === 0) {
379 2
            throw new InvalidArgumentException('Trying to copy a directory to itself or a subdirectory.');
380
        }
381 15
        $dstExists = is_dir($dst);
382 15
        if (!$dstExists && (!isset($options['copyEmptyDirectories']) || $options['copyEmptyDirectories'])) {
383 6
            static::createDirectory($dst, isset($options['dirMode']) ? $options['dirMode'] : 0775, true);
384 6
            $dstExists = true;
385
        }
386
387 15
        $handle = opendir($src);
388 15
        if ($handle === false) {
389
            throw new InvalidArgumentException("Unable to open directory: $src");
390
        }
391 15
        if (!isset($options['basePath'])) {
392
            // this should be done only once
393 15
            $options['basePath'] = realpath($src);
394 15
            $options = static::normalizeOptions($options);
395
        }
396 15
        while (($file = readdir($handle)) !== false) {
397 15
            if ($file === '.' || $file === '..') {
398 15
                continue;
399
            }
400 13
            $from = $src . DIRECTORY_SEPARATOR . $file;
401 13
            $to = $dst . DIRECTORY_SEPARATOR . $file;
402 13
            if (static::filterPath($from, $options)) {
403 13
                if (isset($options['beforeCopy']) && !call_user_func($options['beforeCopy'], $from, $to)) {
404 2
                    continue;
405
                }
406 11
                if (is_file($from)) {
407 11
                    if (!$dstExists) {
408
                        // delay creation of destination directory until the first file is copied to avoid creating empty directories
409 5
                        static::createDirectory($dst, isset($options['dirMode']) ? $options['dirMode'] : 0775, true);
410 5
                        $dstExists = true;
411
                    }
412 11
                    copy($from, $to);
413 11
                    if (isset($options['fileMode'])) {
414 11
                        @chmod($to, $options['fileMode']);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for chmod(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

414
                        /** @scrutinizer ignore-unhandled */ @chmod($to, $options['fileMode']);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
415
                    }
416
                } else {
417
                    // recursive copy, defaults to true
418 8
                    if (!isset($options['recursive']) || $options['recursive']) {
419 7
                        static::copyDirectory($from, $to, $options);
420
                    }
421
                }
422 11
                if (isset($options['afterCopy'])) {
423
                    call_user_func($options['afterCopy'], $from, $to);
424
                }
425
            }
426
        }
427 15
        closedir($handle);
428 15
    }
429
430
    /**
431
     * Removes a directory (and all its content) recursively.
432
     *
433
     * @param string $dir the directory to be deleted recursively.
434
     * @param array $options options for directory remove. Valid options are:
435
     *
436
     * - traverseSymlinks: boolean, whether symlinks to the directories should be traversed too.
437
     *   Defaults to `false`, meaning the content of the symlinked directory would not be deleted.
438
     *   Only symlink would be removed in that default case.
439
     *
440
     * @throws ErrorException in case of failure
441
     */
442 223
    public static function removeDirectory($dir, $options = [])
443
    {
444 223
        if (!is_dir($dir)) {
445 108
            return;
446
        }
447 221
        if (!empty($options['traverseSymlinks']) || !is_link($dir)) {
448 221
            if (!($handle = opendir($dir))) {
449
                return;
450
            }
451 221
            while (($file = readdir($handle)) !== false) {
452 221
                if ($file === '.' || $file === '..') {
453 221
                    continue;
454
                }
455 198
                $path = $dir . DIRECTORY_SEPARATOR . $file;
456 198
                if (is_dir($path)) {
457 76
                    static::removeDirectory($path, $options);
458
                } else {
459 176
                    static::unlink($path);
460
                }
461
            }
462 221
            closedir($handle);
463
        }
464 221
        if (is_link($dir)) {
465 2
            static::unlink($dir);
466
        } else {
467 221
            rmdir($dir);
468
        }
469 221
    }
470
471
    /**
472
     * Removes a file or symlink in a cross-platform way
473
     *
474
     * @param string $path
475
     * @return bool
476
     *
477
     * @since 2.0.14
478
     */
479 177
    public static function unlink($path)
480
    {
481 177
        $isWindows = DIRECTORY_SEPARATOR === '\\';
482
483 177
        if (!$isWindows) {
484 177
            return unlink($path);
485
        }
486
487
        if (is_link($path) && is_dir($path)) {
488
            return rmdir($path);
489
        }
490
491
        try {
492
            return unlink($path);
493
        } catch (ErrorException $e) {
494
            // last resort measure for Windows
495
            if (is_dir($path) && count(static::findFiles($path)) !== 0) {
496
                return false;
497
            }
498
            if (function_exists('exec') && file_exists($path)) {
499
                exec('DEL /F/Q ' . escapeshellarg($path));
500
501
                return !file_exists($path);
502
            }
503
504
            return false;
505
        }
506
    }
507
508
    /**
509
     * Returns the files found under the specified directory and subdirectories.
510
     * @param string $dir the directory under which the files will be looked for.
511
     * @param array $options options for file searching. Valid options are:
512
     *
513
     * - `filter`: callback, a PHP callback that is called for each directory or file.
514
     *   The signature of the callback should be: `function ($path)`, where `$path` refers the full path to be filtered.
515
     *   The callback can return one of the following values:
516
     *
517
     *   * `true`: the directory or file will be returned (the `only` and `except` options will be ignored)
518
     *   * `false`: the directory or file will NOT be returned (the `only` and `except` options will be ignored)
519
     *   * `null`: the `only` and `except` options will determine whether the directory or file should be returned
520
     *
521
     * - `except`: array, list of patterns excluding from the results matching file or directory paths.
522
     *   Patterns ending with slash ('/') apply to directory paths only, and patterns not ending with '/'
523
     *   apply to file paths only. For example, '/a/b' matches all file paths ending with '/a/b';
524
     *   and `.svn/` matches directory paths ending with `.svn`.
525
     *   If the pattern does not contain a slash (`/`), it is treated as a shell glob pattern
526
     *   and checked for a match against the pathname relative to `$dir`.
527
     *   Otherwise, the pattern is treated as a shell glob suitable for consumption by `fnmatch(3)`
528
     *   with the `FNM_PATHNAME` flag: wildcards in the pattern will not match a `/` in the pathname.
529
     *   For example, `views/*.php` matches `views/index.php` but not `views/controller/index.php`.
530
     *   A leading slash matches the beginning of the pathname. For example, `/*.php` matches `index.php` but not `views/start/index.php`.
531
     *   An optional prefix `!` which negates the pattern; any matching file excluded by a previous pattern will become included again.
532
     *   If a negated pattern matches, this will override lower precedence patterns sources. Put a backslash (`\`) in front of the first `!`
533
     *   for patterns that begin with a literal `!`, for example, `\!important!.txt`.
534
     *   Note, the '/' characters in a pattern matches both '/' and '\' in the paths.
535
     *   You can find more details about the gitignore pattern format [here](https://git-scm.com/docs/gitignore/en#_pattern_format).
536
     * - `only`: array, list of patterns that the file paths should match if they are to be returned. Directory paths
537
     *   are not checked against them. Same pattern matching rules as in the `except` option are used.
538
     *   If a file path matches a pattern in both `only` and `except`, it will NOT be returned.
539
     * - `caseSensitive`: boolean, whether patterns specified at `only` or `except` should be case sensitive. Defaults to `true`.
540
     * - `recursive`: boolean, whether the files under the subdirectories should also be looked for. Defaults to `true`.
541
     * @return array files found under the directory, in no particular order. Ordering depends on the files system used.
542
     * @throws InvalidArgumentException if the dir is invalid.
543
     */
544 167
    public static function findFiles($dir, $options = [])
545
    {
546 167
        $dir = self::clearDir($dir);
547 167
        $options = self::setBasePath($dir, $options);
548 167
        $list = [];
549 167
        $handle = self::openDir($dir);
550 167
        while (($file = readdir($handle)) !== false) {
551 167
            if ($file === '.' || $file === '..') {
552 167
                continue;
553
            }
554 164
            $path = $dir . DIRECTORY_SEPARATOR . $file;
555 164
            if (static::filterPath($path, $options)) {
556 164
                if (is_file($path)) {
557 162
                    $list[] = $path;
558 25
                } elseif (is_dir($path) && (!isset($options['recursive']) || $options['recursive'])) {
559 24
                    $list = array_merge($list, static::findFiles($path, $options));
560
                }
561
            }
562
        }
563 167
        closedir($handle);
564
565 167
        return $list;
566
    }
567
568
    /**
569
     * Returns the directories found under the specified directory and subdirectories.
570
     * @param string $dir the directory under which the files will be looked for.
571
     * @param array $options options for directory searching. Valid options are:
572
     *
573
     * - `filter`: callback, a PHP callback that is called for each directory or file.
574
     *   The signature of the callback should be: `function (string $path): bool`, where `$path` refers
575
     *   the full path to be filtered. The callback can return one of the following values:
576
     *
577
     *   * `true`: the directory will be returned
578
     *   * `false`: the directory will NOT be returned
579
     *
580
     * - `recursive`: boolean, whether the files under the subdirectories should also be looked for. Defaults to `true`.
581
     *   See [[findFiles()]] for more options.
582
     * @return array directories found under the directory, in no particular order. Ordering depends on the files system used.
583
     * @throws InvalidArgumentException if the dir is invalid.
584
     * @since 2.0.14
585
     */
586 1
    public static function findDirectories($dir, $options = [])
587
    {
588 1
        $dir = self::clearDir($dir);
589 1
        $options = self::setBasePath($dir, $options);
590 1
        $list = [];
591 1
        $handle = self::openDir($dir);
592 1
        while (($file = readdir($handle)) !== false) {
593 1
            if ($file === '.' || $file === '..') {
594 1
                continue;
595
            }
596 1
            $path = $dir . DIRECTORY_SEPARATOR . $file;
597 1
            if (is_dir($path) && static::filterPath($path, $options)) {
598 1
                $list[] = $path;
599 1
                if (!isset($options['recursive']) || $options['recursive']) {
600 1
                    $list = array_merge($list, static::findDirectories($path, $options));
601
                }
602
            }
603
        }
604 1
        closedir($handle);
605
606 1
        return $list;
607
    }
608
609
    /**
610
     * @param string $dir
611
     * @param array $options
612
     * @return array
613
     */
614 168
    private static function setBasePath($dir, $options)
615
    {
616 168
        if (!isset($options['basePath'])) {
617
            // this should be done only once
618 168
            $options['basePath'] = realpath($dir);
619 168
            $options = static::normalizeOptions($options);
620
        }
621
622 168
        return $options;
623
    }
624
625
    /**
626
     * @param string $dir
627
     * @return resource
628
     * @throws InvalidArgumentException if unable to open directory
629
     */
630 168
    private static function openDir($dir)
631
    {
632 168
        $handle = opendir($dir);
633 168
        if ($handle === false) {
634
            throw new InvalidArgumentException("Unable to open directory: $dir");
635
        }
636 168
        return $handle;
637
    }
638
639
    /**
640
     * @param string $dir
641
     * @return string
642
     * @throws InvalidArgumentException if directory not exists
643
     */
644 168
    private static function clearDir($dir)
645
    {
646 168
        if (!is_dir($dir)) {
647
            throw new InvalidArgumentException("The dir argument must be a directory: $dir");
648
        }
649 168
        return rtrim($dir, '\/');
650
    }
651
652
    /**
653
     * Checks if the given file path satisfies the filtering options.
654
     * @param string $path the path of the file or directory to be checked
655
     * @param array $options the filtering options. See [[findFiles()]] for explanations of
656
     * the supported options.
657
     * @return bool whether the file or directory satisfies the filtering options.
658
     */
659 174
    public static function filterPath($path, $options)
660
    {
661 174
        if (isset($options['filter'])) {
662 2
            $result = call_user_func($options['filter'], $path);
663 2
            if (is_bool($result)) {
664 2
                return $result;
665
            }
666
        }
667
668 173
        if (empty($options['except']) && empty($options['only'])) {
669 106
            return true;
670
        }
671
672 76
        $path = str_replace('\\', '/', $path);
673
674
        if (
675 76
            !empty($options['except'])
676 76
            && ($except = self::lastExcludeMatchingFromList($options['basePath'], $path, $options['except'])) !== null
677
        ) {
678 3
            return $except['flags'] & self::PATTERN_NEGATIVE;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $except['flags'] & self::PATTERN_NEGATIVE returns the type integer which is incompatible with the documented return type boolean.
Loading history...
679
        }
680
681 76
        if (!empty($options['only']) && !is_dir($path)) {
682 74
            return self::lastExcludeMatchingFromList($options['basePath'], $path, $options['only']) !== null;
683
        }
684
685 20
        return true;
686
    }
687
688
    /**
689
     * Creates a new directory.
690
     *
691
     * This method is similar to the PHP `mkdir()` function except that
692
     * it uses `chmod()` to set the permission of the created directory
693
     * in order to avoid the impact of the `umask` setting.
694
     *
695
     * @param string $path path of the directory to be created.
696
     * @param int $mode the permission to be set for the created directory.
697
     * @param bool $recursive whether to create parent directories if they do not exist.
698
     * @return bool whether the directory is created successfully
699
     * @throws \yii\base\Exception if the directory could not be created (i.e. php error due to parallel changes)
700
     */
701 276
    public static function createDirectory($path, $mode = 0775, $recursive = true)
702
    {
703 276
        if (is_dir($path)) {
704 165
            return true;
705
        }
706 252
        $parentDir = dirname($path);
707
        // recurse if parent dir does not exist and we are not at the root of the file system.
708 252
        if ($recursive && !is_dir($parentDir) && $parentDir !== $path) {
709 5
            static::createDirectory($parentDir, $mode, true);
710
        }
711
        try {
712 252
            if (!mkdir($path, $mode)) {
713 252
                return false;
714
            }
715
        } catch (\Exception $e) {
716
            if (!is_dir($path)) {// https://github.com/yiisoft/yii2/issues/9288
717
                throw new \yii\base\Exception("Failed to create directory \"$path\": " . $e->getMessage(), $e->getCode(), $e);
718
            }
719
        }
720
        try {
721 252
            return chmod($path, $mode);
722
        } catch (\Exception $e) {
723
            throw new \yii\base\Exception("Failed to change permissions for directory \"$path\": " . $e->getMessage(), $e->getCode(), $e);
724
        }
725
    }
726
727
    /**
728
     * Performs a simple comparison of file or directory names.
729
     *
730
     * Based on match_basename() from dir.c of git 1.8.5.3 sources.
731
     *
732
     * @param string $baseName file or directory name to compare with the pattern
733
     * @param string $pattern the pattern that $baseName will be compared against
734
     * @param int|bool $firstWildcard location of first wildcard character in the $pattern
735
     * @param int $flags pattern flags
736
     * @return bool whether the name matches against pattern
737
     */
738 75
    private static function matchBasename($baseName, $pattern, $firstWildcard, $flags)
739
    {
740 75
        if ($firstWildcard === false) {
741 11
            if ($pattern === $baseName) {
742 11
                return true;
743
            }
744 64
        } elseif ($flags & self::PATTERN_ENDSWITH) {
745
            /* "*literal" matching against "fooliteral" */
746 63
            $n = StringHelper::byteLength($pattern);
747 63
            if (StringHelper::byteSubstr($pattern, 1, $n) === StringHelper::byteSubstr($baseName, -$n, $n)) {
748
                return true;
749
            }
750
        }
751
752 75
        $matchOptions = [];
753 75
        if ($flags & self::PATTERN_CASE_INSENSITIVE) {
754 1
            $matchOptions['caseSensitive'] = false;
755
        }
756
757 75
        return StringHelper::matchWildcard($pattern, $baseName, $matchOptions);
758
    }
759
760
    /**
761
     * Compares a path part against a pattern with optional wildcards.
762
     *
763
     * Based on match_pathname() from dir.c of git 1.8.5.3 sources.
764
     *
765
     * @param string $path full path to compare
766
     * @param string $basePath base of path that will not be compared
767
     * @param string $pattern the pattern that path part will be compared against
768
     * @param int|bool $firstWildcard location of first wildcard character in the $pattern
769
     * @param int $flags pattern flags
770
     * @return bool whether the path part matches against pattern
771
     */
772 57
    private static function matchPathname($path, $basePath, $pattern, $firstWildcard, $flags)
773
    {
774
        // match with FNM_PATHNAME; the pattern has base implicitly in front of it.
775 57
        if (strncmp($pattern, '/', 1) === 0) {
776 54
            $pattern = StringHelper::byteSubstr($pattern, 1, StringHelper::byteLength($pattern));
777 54
            if ($firstWildcard !== false && $firstWildcard !== 0) {
778 54
                $firstWildcard--;
779
            }
780
        }
781
782 57
        $namelen = StringHelper::byteLength($path) - (empty($basePath) ? 0 : StringHelper::byteLength($basePath) + 1);
783 57
        $name = StringHelper::byteSubstr($path, -$namelen, $namelen);
784
785 57
        if ($firstWildcard !== 0) {
786 57
            if ($firstWildcard === false) {
787 56
                $firstWildcard = StringHelper::byteLength($pattern);
788
            }
789
            // if the non-wildcard part is longer than the remaining pathname, surely it cannot match.
790 57
            if ($firstWildcard > $namelen) {
791 3
                return false;
792
            }
793
794 57
            if (strncmp($pattern, $name, $firstWildcard)) {
0 ignored issues
show
Bug introduced by
It seems like $firstWildcard can also be of type true; however, parameter $length of strncmp() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

794
            if (strncmp($pattern, $name, /** @scrutinizer ignore-type */ $firstWildcard)) {
Loading history...
795 57
                return false;
796
            }
797 4
            $pattern = StringHelper::byteSubstr($pattern, $firstWildcard, StringHelper::byteLength($pattern));
0 ignored issues
show
Bug introduced by
It seems like $firstWildcard can also be of type true; however, parameter $start of yii\helpers\BaseStringHelper::byteSubstr() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

797
            $pattern = StringHelper::byteSubstr($pattern, /** @scrutinizer ignore-type */ $firstWildcard, StringHelper::byteLength($pattern));
Loading history...
798 4
            $name = StringHelper::byteSubstr($name, $firstWildcard, $namelen);
799
800
            // If the whole pattern did not have a wildcard, then our prefix match is all we need; we do not need to call fnmatch at all.
801 4
            if (empty($pattern) && empty($name)) {
802 3
                return true;
803
            }
804
        }
805
806
        $matchOptions = [
807 2
            'filePath' => true
808
        ];
809 2
        if ($flags & self::PATTERN_CASE_INSENSITIVE) {
810
            $matchOptions['caseSensitive'] = false;
811
        }
812
813 2
        return StringHelper::matchWildcard($pattern, $name, $matchOptions);
814
    }
815
816
    /**
817
     * Scan the given exclude list in reverse to see whether pathname
818
     * should be ignored.  The first match (i.e. the last on the list), if
819
     * any, determines the fate.  Returns the element which
820
     * matched, or null for undecided.
821
     *
822
     * Based on last_exclude_matching_from_list() from dir.c of git 1.8.5.3 sources.
823
     *
824
     * @param string $basePath
825
     * @param string $path
826
     * @param array $excludes list of patterns to match $path against
827
     * @return array|null null or one of $excludes item as an array with keys: 'pattern', 'flags'
828
     * @throws InvalidArgumentException if any of the exclude patterns is not a string or an array with keys: pattern, flags, firstWildcard.
829
     */
830 76
    private static function lastExcludeMatchingFromList($basePath, $path, $excludes)
831
    {
832 76
        foreach (array_reverse($excludes) as $exclude) {
833 76
            if (is_string($exclude)) {
834
                $exclude = self::parseExcludePattern($exclude, false);
835
            }
836 76
            if (!isset($exclude['pattern']) || !isset($exclude['flags']) || !isset($exclude['firstWildcard'])) {
837
                throw new InvalidArgumentException('If exclude/include pattern is an array it must contain the pattern, flags and firstWildcard keys.');
838
            }
839 76
            if ($exclude['flags'] & self::PATTERN_MUSTBEDIR && !is_dir($path)) {
840
                continue;
841
            }
842
843 76
            if ($exclude['flags'] & self::PATTERN_NODIR) {
844 75
                if (self::matchBasename(basename($path), $exclude['pattern'], $exclude['firstWildcard'], $exclude['flags'])) {
845 73
                    return $exclude;
846
                }
847 74
                continue;
848
            }
849
850 57
            if (self::matchPathname($path, $basePath, $exclude['pattern'], $exclude['firstWildcard'], $exclude['flags'])) {
851 4
                return $exclude;
852
            }
853
        }
854
855 75
        return null;
856
    }
857
858
    /**
859
     * Processes the pattern, stripping special characters like / and ! from the beginning and settings flags instead.
860
     * @param string $pattern
861
     * @param bool $caseSensitive
862
     * @return array with keys: (string) pattern, (int) flags, (int|bool) firstWildcard
863
     * @throws InvalidArgumentException
864
     */
865 82
    private static function parseExcludePattern($pattern, $caseSensitive)
866
    {
867 82
        if (!is_string($pattern)) {
0 ignored issues
show
introduced by
The condition is_string($pattern) is always true.
Loading history...
868
            throw new InvalidArgumentException('Exclude/include pattern must be a string.');
869
        }
870
871
        $result = [
872 82
            'pattern' => $pattern,
873 82
            'flags' => 0,
874
            'firstWildcard' => false,
875
        ];
876
877 82
        if (!$caseSensitive) {
878 1
            $result['flags'] |= self::PATTERN_CASE_INSENSITIVE;
879
        }
880
881 82
        if (empty($pattern)) {
882
            return $result;
883
        }
884
885 82
        if (strncmp($pattern, '!', 1) === 0) {
886 1
            $result['flags'] |= self::PATTERN_NEGATIVE;
887 1
            $pattern = StringHelper::byteSubstr($pattern, 1, StringHelper::byteLength($pattern));
888
        }
889 82
        if (StringHelper::byteLength($pattern) && StringHelper::byteSubstr($pattern, -1, 1) === '/') {
890
            $pattern = StringHelper::byteSubstr($pattern, 0, -1);
891
            $result['flags'] |= self::PATTERN_MUSTBEDIR;
892
        }
893 82
        if (strpos($pattern, '/') === false) {
894 81
            $result['flags'] |= self::PATTERN_NODIR;
895
        }
896 82
        $result['firstWildcard'] = self::firstWildcardInPattern($pattern);
897 82
        if (strncmp($pattern, '*', 1) === 0 && self::firstWildcardInPattern(StringHelper::byteSubstr($pattern, 1, StringHelper::byteLength($pattern))) === false) {
898 69
            $result['flags'] |= self::PATTERN_ENDSWITH;
899
        }
900 82
        $result['pattern'] = $pattern;
901
902 82
        return $result;
903
    }
904
905
    /**
906
     * Searches for the first wildcard character in the pattern.
907
     * @param string $pattern the pattern to search in
908
     * @return int|bool position of first wildcard character or false if not found
909
     */
910 82
    private static function firstWildcardInPattern($pattern)
911
    {
912 82
        $wildcards = ['*', '?', '[', '\\'];
913 82
        $wildcardSearch = function ($r, $c) use ($pattern) {
914 82
            $p = strpos($pattern, $c);
915
916 82
            return $r === false ? $p : ($p === false ? $r : min($r, $p));
917 82
        };
918
919 82
        return array_reduce($wildcards, $wildcardSearch, false);
920
    }
921
922
    /**
923
     * @param array $options raw options
924
     * @return array normalized options
925
     * @since 2.0.12
926
     */
927 179
    protected static function normalizeOptions(array $options)
928
    {
929 179
        if (!array_key_exists('caseSensitive', $options)) {
930 178
            $options['caseSensitive'] = true;
931
        }
932 179
        if (isset($options['except'])) {
933 62
            foreach ($options['except'] as $key => $value) {
934 62
                if (is_string($value)) {
935 62
                    $options['except'][$key] = self::parseExcludePattern($value, $options['caseSensitive']);
936
                }
937
            }
938
        }
939 179
        if (isset($options['only'])) {
940 80
            foreach ($options['only'] as $key => $value) {
941 80
                if (is_string($value)) {
942 80
                    $options['only'][$key] = self::parseExcludePattern($value, $options['caseSensitive']);
943
                }
944
            }
945
        }
946
947 179
        return $options;
948
    }
949
950
    /**
951
     * Changes the Unix user and/or group ownership of a file or directory, and optionally the mode.
952
     * Note: This function will not work on remote files as the file to be examined must be accessible
953
     * via the server's filesystem.
954
     * Note: On Windows, this function fails silently when applied on a regular file.
955
     * @param string $path the path to the file or directory.
956
     * @param string|array|int|null $ownership the user and/or group ownership for the file or directory.
957
     * When $ownership is a string, the format is 'user:group' where both are optional. E.g.
958
     * 'user' or 'user:' will only change the user,
959
     * ':group' will only change the group,
960
     * 'user:group' will change both.
961
     * When $owners is an index array the format is [0 => user, 1 => group], e.g. `[$myUser, $myGroup]`.
962
     * It is also possible to pass an associative array, e.g. ['user' => $myUser, 'group' => $myGroup].
963
     * In case $owners is an integer it will be used as user id.
964
     * If `null`, an empty array or an empty string is passed, the ownership will not be changed.
965
     * @param int|null $mode the permission to be set for the file or directory.
966
     * If `null` is passed, the mode will not be changed.
967
     *
968
     * @since 2.0.43
969
     */
970 90
    public static function changeOwnership($path, $ownership, $mode = null)
971
    {
972 90
        if (!file_exists((string)$path)) {
973 1
            throw new InvalidArgumentException('Unable to change ownership, "' . $path . '" is not a file or directory.');
974
        }
975
976 89
        if (empty($ownership) && $ownership !== 0 && $mode === null) {
977 84
            return;
978
        }
979
980 5
        $user = $group = null;
981 5
        if (!empty($ownership) || $ownership === 0 || $ownership === '0') {
982 4
            if (is_int($ownership)) {
983
                $user = $ownership;
984 4
            } elseif (is_string($ownership)) {
985 1
                $ownerParts = explode(':', $ownership);
986 1
                $user = $ownerParts[0];
987 1
                if (count($ownerParts) > 1) {
988 1
                    $group = $ownerParts[1];
989
                }
990 3
            } elseif (is_array($ownership)) {
0 ignored issues
show
introduced by
The condition is_array($ownership) is always true.
Loading history...
991 2
                $ownershipIsIndexed = ArrayHelper::isIndexed($ownership);
992 2
                $user = ArrayHelper::getValue($ownership, $ownershipIsIndexed ? 0 : 'user');
993 2
                $group = ArrayHelper::getValue($ownership, $ownershipIsIndexed ? 1 : 'group');
994
            } else {
995 1
                throw new InvalidArgumentException('$ownership must be an integer, string, array, or null.');
996
            }
997
        }
998
999 4
        if ($mode !== null) {
1000 1
            if (!is_int($mode)) {
0 ignored issues
show
introduced by
The condition is_int($mode) is always true.
Loading history...
1001 1
                throw new InvalidArgumentException('$mode must be an integer or null.');
1002
            }
1003
            if (!chmod($path, $mode)) {
1004
                throw new Exception('Unable to change mode of "' . $path . '" to "0' . decoct($mode) . '".');
1005
            }
1006
        }
1007 3
        if ($user !== null && $user !== '') {
1008 2
            if (is_numeric($user)) {
1009
                $user = (int) $user;
1010 2
            } elseif (!is_string($user)) {
1011 1
                throw new InvalidArgumentException('The user part of $ownership must be an integer, string, or null.');
1012
            }
1013 1
            if (!chown($path, $user)) {
1014
                throw new Exception('Unable to change user ownership of "' . $path . '" to "' . $user . '".');
1015
            }
1016
        }
1017 1
        if ($group !== null && $group !== '') {
1018 1
            if (is_numeric($group)) {
1019
                $group = (int) $group;
1020 1
            } elseif (!is_string($group)) {
1021 1
                throw new InvalidArgumentException('The group part of $ownership must be an integer, string or null.');
1022
            }
1023
            if (!chgrp($path, $group)) {
1024
                throw new Exception('Unable to change group ownership of "' . $path . '" to "' . $group . '".');
1025
            }
1026
        }
1027
    }
1028
}
1029