Completed
Push — master ( 89abc8...a320a7 )
by Siad
16:11
created

FileSystem::getBooleanAttributes()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
ccs 0
cts 2
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
4
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
5
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
6
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
7
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
8
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
10
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
11
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
12
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
13
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
14
 *
15
 * This software consists of voluntary contributions made by many individuals
16
 * and is licensed under the LGPL. For more information please see
17
 * <http://phing.info>.
18
 */
19
20
/**
21
 * This is an abstract class for platform specific filesystem implementations
22
 * you have to implement each method in the platform specific filesystem implementation
23
 * classes Your local filesytem implementation must extend this class.
24
 * You should also use this class as a template to write your local implementation
25
 * Some native PHP filesystem specific methods are abstracted here as well. Anyway
26
 * you _must_ always use this methods via a PhingFile object (that by nature uses the
27
 * *FileSystem drivers to access the real filesystem via this class using natives.
28
 *
29
 * FIXME:
30
 *  - Error handling reduced to min fallthrough runtime exceptions
31
 *    more precise errorhandling is done by the PhingFile class
32
 *
33
 * @author Charlie Killian <[email protected]>
34
 * @author Hans Lellelid <[email protected]>
35
 *
36
 * @package phing.system.io
37
 */
38
abstract class FileSystem
39
{
40
41
    /**
42
     * @var int
43
     */
44
    public const BA_EXISTS = 0x01;
45
46
    /**
47
     * @var int
48
     */
49
    public const BA_REGULAR = 0x02;
50
51
    /**
52
     * @var int
53
     */
54
    public const BA_DIRECTORY = 0x04;
55
56
    /**
57
     * @var int
58
     */
59
    public const BA_HIDDEN = 0x08;
60
61
    /**
62
     * Instance for getFileSystem() method.
63
     *
64
     * @var FileSystem
65
     */
66
    private static $fs;
67
68
    /**
69
     * @var PhingFile[]
70
     */
71
    private static $filesToDelete = [];
72
73
    /**
74
     * Static method to return the FileSystem singelton representing
75
     * this platform's local filesystem driver.
76
     *
77
     * @return FileSystem
78
     * @throws IOException
79
     */
80 799
    public static function getFileSystem()
81
    {
82 799
        if (self::$fs === null) {
83 6
            switch (Phing::getProperty('host.fstype')) {
84 6
                case 'UNIX':
85 4
                    self::$fs = new UnixFileSystem();
86 4
                    break;
87 2
                case 'WINDOWS':
88 1
                    self::$fs = new WindowsFileSystem();
89 1
                    break;
90
                default:
91 1
                    throw new IOException("Host uses unsupported filesystem, unable to proceed");
92
            }
93
        }
94
95 798
        return self::$fs;
96
    }
97
98
    /* -- Normalization and construction -- */
99
100
    /**
101
     * Return the local filesystem's name-separator character.
102
     */
103
    abstract public function getSeparator();
104
105
    /**
106
     * Return the local filesystem's path-separator character.
107
     */
108
    abstract public function getPathSeparator();
109
110
    /**
111
     * Convert the given pathname string to normal form.  If the string is
112
     * already in normal form then it is simply returned.
113
     *
114
     * @param string $strPath
115
     */
116
    abstract public function normalize($strPath);
117
118
    /**
119
     * Compute the length of this pathname string's prefix.  The pathname
120
     * string must be in normal form.
121
     *
122
     * @param string $pathname
123
     */
124
    abstract public function prefixLength($pathname);
125
126
    /**
127
     * Resolve the child pathname string against the parent.
128
     * Both strings must be in normal form, and the result
129
     * will be a string in normal form.
130
     *
131
     * @param string $parent
132
     * @param string $child
133
     */
134
    abstract public function resolve($parent, $child);
135
136
    /**
137
     * Resolve the given abstract pathname into absolute form.  Invoked by the
138
     * getAbsolutePath and getCanonicalPath methods in the PhingFile class.
139
     *
140
     * @param PhingFile $f
141
     */
142
    abstract public function resolveFile(PhingFile $f);
143
144
    /**
145
     * Return the parent pathname string to be used when the parent-directory
146
     * argument in one of the two-argument PhingFile constructors is the empty
147
     * pathname.
148
     */
149
    abstract public function getDefaultParent();
150
151
    /**
152
     * Post-process the given URI path string if necessary.  This is used on
153
     * win32, e.g., to transform "/c:/foo" into "c:/foo".  The path string
154
     * still has slash separators; code in the PhingFile class will translate them
155
     * after this method returns.
156
     *
157
     * @param string $path
158
     */
159
    abstract public function fromURIPath($path);
160
161
    /* -- Path operations -- */
162
163
    /**
164
     * Tell whether or not the given abstract pathname is absolute.
165
     *
166
     * @param PhingFile $f
167
     */
168
    abstract public function isAbsolute(PhingFile $f);
169
170
    /**
171
     * canonicalize filename by checking on disk
172
     *
173
     * @param  string $strPath
174
     * @return mixed  Canonical path or false if the file doesn't exist.
175
     */
176 779
    public function canonicalize($strPath)
177
    {
178 779
        return @realpath($strPath);
179
    }
180
181
    /* -- Attribute accessors -- */
182
183
    /**
184
     * Check whether the file or directory denoted by the given abstract
185
     * pathname may be accessed by this process.  If the second argument is
186
     * false, then a check for read access is made; if the second
187
     * argument is true, then a check for write (not read-write)
188
     * access is made.  Return false if access is denied or an I/O error
189
     * occurs.
190
     *
191
     * @param  PhingFile $f
192
     * @param  boolean $write
193
     * @return bool
194
     */
195 785
    public function checkAccess(PhingFile $f, $write = false)
196
    {
197
        // we clear stat cache, its expensive to look up from scratch,
198
        // but we need to be sure
199 785
        @clearstatcache();
1 ignored issue
show
Bug introduced by
Are you sure the usage of clearstatcache() is correct as it seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
Security Best Practice introduced by
It seems like you do not handle an error condition for clearstatcache(). 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

199
        /** @scrutinizer ignore-unhandled */ @clearstatcache();

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...
200
201
202
        // Shouldn't this be $f->GetAbsolutePath() ?
203
        // And why doesn't GetAbsolutePath() work?
204
205 785
        $strPath = (string) $f->getPath();
206
207
        // FIXME
208
        // if file object does denote a file that yet not existst
209
        // path rights are checked
210 785
        if (!@file_exists($strPath) && !is_dir($strPath)) {
211 175
            $strPath = $f->getParent();
212 175
            if ($strPath === null || !is_dir($strPath)) {
213 44
                $strPath = Phing::getProperty("user.dir");
214
            }
215
            //$strPath = dirname($strPath);
216
        }
217
218 785
        if (!$write) {
219 785
            return (bool) @is_readable($strPath);
220
        }
221
222 138
        return (bool) @is_writable($strPath);
223
    }
224
225
    /**
226
     * Whether file can be deleted.
227
     *
228
     * @param  PhingFile $f
229
     * @return boolean
230
     */
231
    public function canDelete(PhingFile $f)
232
    {
233
        clearstatcache();
234
        $dir = dirname($f->getAbsolutePath());
235
236
        return @is_writable($dir);
237
    }
238
239
    /**
240
     * Return the time at which the file or directory denoted by the given
241
     * abstract pathname was last modified, or zero if it does not exist or
242
     * some other I/O error occurs.
243
     *
244
     * @param  PhingFile $f
245
     * @return int
246
     * @throws IOException
247
     */
248 41
    public function getLastModifiedTime(PhingFile $f)
249
    {
250 41
        if (!$f->exists()) {
251 7
            return 0;
252
        }
253
254 41
        @clearstatcache();
1 ignored issue
show
Bug introduced by
Are you sure the usage of clearstatcache() is correct as it seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
Security Best Practice introduced by
It seems like you do not handle an error condition for clearstatcache(). 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

254
        /** @scrutinizer ignore-unhandled */ @clearstatcache();

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...
255 41
        error_clear_last();
256 41
        $strPath = (string) $f->getPath();
257
258 41
        if (@is_link($strPath)) {
259 2
            $stats = @lstat($strPath);
260
261 2
            if (!isset($stats['mtime'])) {
262
                $mtime = false;
263
            } else {
264 2
                $mtime = $stats['mtime'];
265
            }
266
        } else {
267 41
            $mtime = @filemtime($strPath);
268
        }
269
270 41
        if (false === $mtime) {
271
            $lastError = error_get_last();
272
            $errormsg = $lastError['message'];
273
            $msg = "FileSystem::getLastModifiedTime() FAILED. Can not get modified time of $strPath. $errormsg";
274
            throw new IOException($msg);
275
        }
276
277 41
        return (int) $mtime;
278
    }
279
280
    /**
281
     * Return the length in bytes of the file denoted by the given abstract
282
     * pathname, or zero if it does not exist, is a directory, or some other
283
     * I/O error occurs.
284
     *
285
     * @param  PhingFile $f
286
     * @throws IOException
287
     * @return int
288
     */
289 14
    public function getLength(PhingFile $f)
290
    {
291 14
        error_clear_last();
292 14
        $strPath = (string) $f->getAbsolutePath();
293 14
        $fs = filesize((string) $strPath);
294 14
        if ($fs !== false) {
295 14
            return $fs;
296
        }
297
298
        $lastError = error_get_last();
299
        $errormsg = $lastError['message'];
300
        $msg = "FileSystem::Read() FAILED. Cannot get filesize of $strPath. $errormsg";
301
        throw new IOException($msg);
302
    }
303
304
    /* -- File operations -- */
305
306
    /**
307
     * Create a new empty file with the given pathname.  Return
308
     * true if the file was created and false if a
309
     * file or directory with the given pathname already exists.  Throw an
310
     * IOException if an I/O error occurs.
311
     *
312
     * @param  string $strPathname Path of the file to be created.
313
     * @throws IOException
314
     * @return boolean
315
     */
316 61
    public function createNewFile($strPathname)
317
    {
318 61
        if (@file_exists($strPathname)) {
319
            return false;
320
        }
321
322
        // Create new file
323 61
        $fp = @fopen($strPathname, "w");
324 61
        if ($fp === false) {
325 1
            $error = error_get_last();
326 1
            throw new IOException("The file \"$strPathname\" could not be created: " . $error['message']);
327
        }
328 60
        @fclose($fp);
1 ignored issue
show
Security Best Practice introduced by
It seems like you do not handle an error condition for fclose(). 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

328
        /** @scrutinizer ignore-unhandled */ @fclose($fp);

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...
329
330 60
        return true;
331
    }
332
333
    /**
334
     * Delete the file or directory denoted by the given abstract pathname,
335
     * returning true if and only if the operation succeeds.
336
     *
337
     * @param  PhingFile $f
338
     * @param  boolean $recursive
339
     * @throws IOException
340
     */
341 144
    public function delete(PhingFile $f, $recursive = false)
342
    {
343 144
        if ($f->isDirectory()) {
344 118
            $this->rmdir($f->getPath(), $recursive);
345
        } else {
346 119
            $this->unlink($f->getPath());
347
        }
348 144
    }
349
350
    /**
351
     * Arrange for the file or directory denoted by the given abstract
352
     * pathname to be deleted when Phing::shutdown is called, returning
353
     * true if and only if the operation succeeds.
354
     *
355
     * @param  PhingFile $f
356
     * @throws IOException
357
     */
358
    public function deleteOnExit(PhingFile $f)
359
    {
360
        self::$filesToDelete[] = $f;
361
    }
362
363 1
    public static function deleteFilesOnExit()
364
    {
365 1
        foreach (self::$filesToDelete as $file) {
366
            $file->delete();
367
        }
368 1
    }
369
370
    /**
371
     * Create a new directory denoted by the given abstract pathname,
372
     * returning true if and only if the operation succeeds.
373
     *
374
     * NOTE: umask() is reset to 0 while executing mkdir(), and restored afterwards
375
     *
376
     * @param  PhingFile $f
377
     * @param  int $mode
378
     * @return boolean
379
     */
380 118
    public function createDirectory(&$f, $mode = 0755)
381
    {
382 118
        $old_umask = umask(0);
383 118
        $return = @mkdir($f->getAbsolutePath(), $mode);
384 118
        umask($old_umask);
385
386 118
        return $return;
387
    }
388
389
    /**
390
     * Rename the file or directory denoted by the first abstract pathname to
391
     * the second abstract pathname, returning true if and only if
392
     * the operation succeeds.
393
     *
394
     * @param  PhingFile $f1 abstract source file
395
     * @param  PhingFile $f2 abstract destination file
396
     * @return void
397
     * @throws IOException if rename cannot be performed
398
     */
399 1
    public function rename(PhingFile $f1, PhingFile $f2)
400
    {
401 1
        error_clear_last();
402
        // get the canonical paths of the file to rename
403 1
        $src = $f1->getAbsolutePath();
404 1
        $dest = $f2->getAbsolutePath();
405 1
        if (false === @rename($src, $dest)) {
406
            $lastError = error_get_last();
407
            $errormsg = $lastError['message'];
408
            $msg = "Rename FAILED. Cannot rename $src to $dest. $errormsg";
409
            throw new IOException($msg);
410
        }
411 1
    }
412
413
    /**
414
     * Set the last-modified time of the file or directory denoted by the
415
     * given abstract pathname returning true if and only if the
416
     * operation succeeds.
417
     *
418
     * @param  PhingFile $f
419
     * @param  int $time
420
     * @return void
421
     * @throws IOException
422
     */
423 65
    public function setLastModifiedTime(PhingFile $f, $time)
424
    {
425 65
        error_clear_last();
426 65
        $path = $f->getPath();
427 65
        $success = @touch($path, $time);
428 65
        if (!$success) {
429
            $lastError = error_get_last();
430
            $errormsg = $lastError['message'];
431
            throw new IOException("Could not touch '" . $path . "' due to: $errormsg");
432
        }
433 65
    }
434
435
    /* -- Basic infrastructure -- */
436
437
    /**
438
     * Compare two abstract pathnames lexicographically.
439
     *
440
     * @param  PhingFile $f1
441
     * @param  PhingFile $f2
442
     * @throws IOException
443
     * @return int
444
     */
445
    public function compare(PhingFile $f1, PhingFile $f2)
446
    {
447
        throw new IOException("compare() not implemented by local fs driver");
448
    }
449
450
    /**
451
     * Copy a file.
452
     *
453
     * @param PhingFile $src Source path and name file to copy.
454
     * @param PhingFile $dest Destination path and name of new file.
455
     *
456
     * @return void
457
     *
458
     * @throws IOException if file cannot be copied.
459
     */
460 10
    public function copy(PhingFile $src, PhingFile $dest)
461
    {
462
        // Recursively copy a directory
463 10
        if ($src->isDirectory()) {
464
            $this->copyr($src->getAbsolutePath(), $dest->getAbsolutePath());
465
        }
466
467 10
        $srcPath = $src->getAbsolutePath();
468 10
        $destPath = $dest->getAbsolutePath();
469
470 10
        error_clear_last();
471 10
        if (false === @copy($srcPath, $destPath)) { // Copy FAILED. Log and return err.
472
            // Add error from php to end of log message. $errormsg.
473
            $lastError = error_get_last();
474
            $errormsg = $lastError['message'];
475
            $msg = "FileSystem::copy() FAILED. Cannot copy $srcPath to $destPath. $errormsg";
476
            throw new IOException($msg);
477
        }
478
479 10
        $dest->setMode($src->getMode());
480 10
    }
481
482
    /**
483
     * Copy a file, or recursively copy a folder and its contents
484
     *
485
     * @author  Aidan Lister <[email protected]>
486
     * @version 1.0.1
487
     * @link    http://aidanlister.com/repos/v/function.copyr.php
488
     *
489
     * @param string $source Source path
490
     * @param string $dest Destination path
491
     *
492
     * @return bool   Returns TRUE on success, FALSE on failure
493
     */
494
    public function copyr($source, $dest)
495
    {
496
        // Check for symlinks
497
        if (is_link($source)) {
498
            return symlink(readlink($source), $dest);
499
        }
500
501
        // Simple copy for a file
502
        if (is_file($source)) {
503
            return copy($source, $dest);
504
        }
505
506
        // Make destination directory
507
        if (!is_dir($dest) && !mkdir($dest) && !is_dir($dest)) {
508
            return false;
509
        }
510
511
        // Loop through the folder
512
        $dir = dir($source);
513
        while (false !== $entry = $dir->read()) {
514
            // Skip pointers
515
            if ($entry == '.' || $entry == '..') {
516
                continue;
517
            }
518
519
            // Deep copy directories
520
            $this->copyr("$source/$entry", "$dest/$entry");
521
        }
522
523
        // Clean up
524
        $dir->close();
525
526
        return true;
527
    }
528
529
    /**
530
     * Change the ownership on a file or directory.
531
     *
532
     * @param string $pathname Path and name of file or directory.
533
     * @param string $user The user name or number of the file or directory. See http://us.php.net/chown
534
     *
535
     * @return void
536
     *
537
     * @throws IOException if operation failed.
538
     */
539
    public function chown($pathname, $user)
540
    {
541
        error_clear_last();
542
        if (false === @chown($pathname, $user)) { // FAILED.
543
            $lastError = error_get_last();
544
            $errormsg = $lastError['message'];
545
            $msg = "FileSystem::chown() FAILED. Cannot chown $pathname. User $user." . (isset($errormsg) ? ' ' . $errormsg : "");
546
            throw new IOException($msg);
547
        }
548
    }
549
550
    /**
551
     * Change the group on a file or directory.
552
     *
553
     * @param string $pathname Path and name of file or directory.
554
     * @param string $group The group of the file or directory. See http://us.php.net/chgrp
555
     *
556
     * @return void
557
     * @throws IOException if operation failed.
558
     */
559
    public function chgrp($pathname, $group)
560
    {
561
        error_clear_last();
562
        if (false === @chgrp($pathname, $group)) { // FAILED.
563
            $lastError = error_get_last();
564
            $errormsg = $lastError['message'];
565
            $msg = "FileSystem::chgrp() FAILED. Cannot chown $pathname. Group $group." . (isset($errormsg) ? ' ' . $errormsg : "");
566
            throw new IOException($msg);
567
        }
568
    }
569
570
    /**
571
     * Change the permissions on a file or directory.
572
     *
573
     * @param string $pathname Path and name of file or directory.
574
     * @param int $mode The mode (permissions) of the file or
575
     *                         directory. If using octal add leading 0. eg. 0777.
576
     *                         Mode is affected by the umask system setting.
577
     *
578
     * @return void
579
     * @throws IOException if operation failed.
580
     */
581 41
    public function chmod($pathname, $mode)
582
    {
583 41
        error_clear_last();
584 41
        $str_mode = decoct($mode); // Show octal in messages.
585 41
        if (false === @chmod($pathname, $mode)) { // FAILED.
586
            $lastError = error_get_last();
587
            $errormsg = $lastError['message'];
588
            $msg = "FileSystem::chmod() FAILED. Cannot chmod $pathname. Mode $str_mode." . (isset($errormsg) ? ' ' . $errormsg : "");
589
            throw new IOException($msg);
590
        }
591 41
    }
592
593
    /**
594
     * Locks a file and throws an Exception if this is not possible.
595
     *
596
     * @param  PhingFile $f
597
     * @return void
598
     * @throws IOException
599
     */
600
    public function lock(PhingFile $f)
601
    {
602
        $filename = $f->getPath();
603
        $fp = @fopen($filename, "w");
604
        $result = @flock($fp, LOCK_EX);
0 ignored issues
show
Bug introduced by
It seems like $fp can also be of type false; however, parameter $handle of flock() does only seem to accept resource, 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

604
        $result = @flock(/** @scrutinizer ignore-type */ $fp, LOCK_EX);
Loading history...
605
        @fclose($fp);
1 ignored issue
show
Security Best Practice introduced by
It seems like you do not handle an error condition for fclose(). 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

605
        /** @scrutinizer ignore-unhandled */ @fclose($fp);

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...
Bug introduced by
It seems like $fp can also be of type false; however, parameter $handle of fclose() does only seem to accept resource, 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

605
        @fclose(/** @scrutinizer ignore-type */ $fp);
Loading history...
606
        if (!$result) {
607
            throw new IOException("Could not lock file '$filename'");
608
        }
609
    }
610
611
    /**
612
     * Unlocks a file and throws an IO Error if this is not possible.
613
     *
614
     * @param  PhingFile $f
615
     * @throws IOException
616
     * @return void
617
     */
618
    public function unlock(PhingFile $f)
619
    {
620
        $filename = $f->getPath();
621
        $fp = @fopen($filename, "w");
622
        $result = @flock($fp, LOCK_UN);
0 ignored issues
show
Bug introduced by
It seems like $fp can also be of type false; however, parameter $handle of flock() does only seem to accept resource, 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

622
        $result = @flock(/** @scrutinizer ignore-type */ $fp, LOCK_UN);
Loading history...
623
        fclose($fp);
0 ignored issues
show
Bug introduced by
It seems like $fp can also be of type false; however, parameter $handle of fclose() does only seem to accept resource, 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

623
        fclose(/** @scrutinizer ignore-type */ $fp);
Loading history...
624
        if (!$result) {
625
            throw new IOException("Could not unlock file '$filename'");
626
        }
627
    }
628
629
    /**
630
     * Delete a file.
631
     *
632
     * @param string $file Path and/or name of file to delete.
633
     *
634
     * @return void
635
     * @throws IOException - if an error is encountered.
636
     */
637 122
    public function unlink($file)
638
    {
639 122
        error_clear_last();
640 122
        if (false === @unlink($file)) {
641
            $lastError = error_get_last();
642
            $errormsg = $lastError['message'];
643
            $msg = "FileSystem::unlink() FAILED. Cannot unlink '$file'. $errormsg";
644
            throw new IOException($msg);
645
        }
646 122
    }
647
648
    /**
649
     * Symbolically link a file to another name.
650
     *
651
     * Currently symlink is not implemented on Windows. Don't use if the application is to be portable.
652
     *
653
     * @param  string $target Path and/or name of file to link.
654
     * @param  string $link Path and/or name of link to be created.
655
     * @throws IOException
656
     * @return void
657
     */
658 15
    public function symlink($target, $link)
659
    {
660
661 15
        error_clear_last();
662
        // If Windows OS then symlink() will report it is not supported in
663
        // the build. Use this error instead of checking for Windows as the OS.
664
665 15
        if (false === @symlink($target, $link)) {
666
            $lastError = error_get_last();
667
            $errormsg = $lastError['message'];
668
            // Add error from php to end of log message.
669
            $msg = "FileSystem::Symlink() FAILED. Cannot symlink '$target' to '$link'. $errormsg";
670
            throw new IOException($msg);
671
        }
672 15
    }
673
674
    /**
675
     * Set the modification and access time on a file to the present time.
676
     *
677
     * @param  string $file Path and/or name of file to touch.
678
     * @param  int $time
679
     * @throws Exception
680
     * @return void
681
     */
682
    public function touch($file, $time = null)
683
    {
684
        error_clear_last();
685
        if (null === $time) {
686
            $error = @touch($file);
687
        } else {
688
            $error = @touch($file, $time);
689
        }
690
691
        if (false === $error) { // FAILED.
692
            $lastError = error_get_last();
693
            $errormsg = $lastError['message'];
694
            // Add error from php to end of log message.
695
            $msg = "FileSystem::touch() FAILED. Cannot touch '$file'. $errormsg";
696
            throw new Exception($msg);
697
        }
698
    }
699
700
    /**
701
     * Delete an empty directory OR a directory and all of its contents.
702
     *
703
     * @param string $dir Path and/or name of directory to delete.
704
     * @param bool $children False: don't delete directory contents.
705
     *                         True: delete directory contents.
706
     *
707
     * @throws Exception
708
     *
709
     * @return void
710
     */
711 118
    public function rmdir($dir, $children = false)
712
    {
713 118
        error_clear_last();
714
715
        // If children=FALSE only delete dir if empty.
716 118
        if (false === $children) {
717 117
            if (false === @rmdir($dir)) { // FAILED.
718
                $lastError = error_get_last();
719
                $errormsg = $lastError['message'];
720
                // Add error from php to end of log message.
721
                $msg = "FileSystem::rmdir() FAILED. Cannot rmdir $dir. $errormsg";
722
                throw new Exception($msg);
723
            }
724
        } else { // delete contents and dir.
725 2
            $handle = @opendir($dir);
726 2
            $lastError = error_get_last();
727 2
            $errormsg = $lastError['message'];
728
729 2
            if (false === $handle) { // Error.
730
                $msg = "FileSystem::rmdir() FAILED. Cannot opendir() $dir. $errormsg";
731
                throw new Exception($msg);
732
            }
733
            // Read from handle.
734
            // Don't error on readdir().
735 2
            while (false !== ($entry = @readdir($handle))) {
736 2
                if ($entry != '.' && $entry != '..') {
737
                    // Only add / if it isn't already the last char.
738
                    // This ONLY serves the purpose of making the Logger
739
                    // output look nice:)
740
741
                    if (strpos(strrev($dir), DIRECTORY_SEPARATOR) === 0) { // there is a /
742
                        $next_entry = $dir . $entry;
743
                    } else { // no /
744
                        $next_entry = $dir . DIRECTORY_SEPARATOR . $entry;
745
                    }
746
747
                    // NOTE: As of php 4.1.1 is_dir doesn't return FALSE it
748
                    // returns 0. So use == not ===.
749
750
                    // Don't error on is_dir()
751
                    if (false == @is_dir($next_entry)) { // Is file.
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
752
                        try {
753
                            $this->unlink($next_entry); // Delete.
754
                        } catch (Exception $e) {
755
                            $msg = "FileSystem::Rmdir() FAILED. Cannot FileSystem::Unlink() $next_entry. " . $e->getMessage();
756
                            throw new Exception($msg);
757
                        }
758
                    } else { // Is directory.
759
                        try {
760
                            $this->rmdir($next_entry, true); // Delete
761
                        } catch (Exception $e) {
762
                            $msg = "FileSystem::rmdir() FAILED. Cannot FileSystem::rmdir() $next_entry. " . $e->getMessage();
763
                            throw new Exception($msg);
764
                        }
765
                    }
766
                }
767
            }
768
769
            // Don't error on closedir()
770 2
            @closedir($handle);
1 ignored issue
show
Bug introduced by
Are you sure the usage of closedir($handle) is correct as it seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
Security Best Practice introduced by
It seems like you do not handle an error condition for closedir(). 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

770
            /** @scrutinizer ignore-unhandled */ @closedir($handle);

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...
771
772 2
            error_clear_last();
773 2
            if (false === @rmdir($dir)) { // FAILED.
774
                // Add error from php to end of log message.
775
                $lastError = error_get_last();
776
                $errormsg = $lastError['message'];
777
                $msg = "FileSystem::rmdir() FAILED. Cannot rmdir $dir. $errormsg";
778
                throw new Exception($msg);
779
            }
780
        }
781 118
    }
782
783
    /**
784
     * Set the umask for file and directory creation.
785
     *
786
     * @param    Int $mode
787
     * @throws   Exception
788
     * @internal param Int $mode . Permissions usually in ocatal. Use leading 0 for
789
     *                    octal. Number between 0 and 0777.
790
     *
791
     * @return void
792
     */
793
    public function umask($mode)
794
    {
795
        error_clear_last();
796
        // CONSIDERME:
797
        // Throw a warning if mode is 0. PHP converts illegal octal numbers to
798
        // 0 so 0 might not be what the user intended.
799
800
        $str_mode = decoct($mode); // Show octal in messages.
0 ignored issues
show
Unused Code introduced by
The assignment to $str_mode is dead and can be removed.
Loading history...
801
802
        if (false === @umask($mode)) { // FAILED.
803
            $lastError = error_get_last();
804
            $errormsg = $lastError['message'];
805
            // Add error from php to end of log message.
806
            $msg = "FileSystem::Umask() FAILED. Value $mode. $errormsg";
807
            throw new Exception($msg);
808
        }
809
    }
810
811
    /**
812
     * Compare the modified time of two files.
813
     *
814
     * @param string $file1 Path and name of file1.
815
     * @param string $file2 Path and name of file2.
816
     *
817
     * @return int  1 if file1 is newer.
818
     *              -1 if file2 is newer.
819
     *              0 if files have the same time.
820
     *              Err object on failure.
821
     *
822
     * @throws Exception - if cannot get modified time of either file.
823
     */
824
    public function compareMTimes($file1, $file2)
825
    {
826
        $mtime1 = filemtime($file1);
827
        $mtime2 = filemtime($file2);
828
829
        if ($mtime1 === false) { // FAILED. Log and return err.
830
            // Add error from php to end of log message.
831
            $msg = "FileSystem::compareMTimes() FAILED. Cannot can not get modified time of $file1.";
832
            throw new Exception($msg);
833
        }
834
835
        if ($mtime2 === false) { // FAILED. Log and return err.
836
            // Add error from php to end of log message.
837
            $msg = "FileSystem::compareMTimes() FAILED. Cannot can not get modified time of $file2.";
838
            throw new Exception($msg);
839
        }
840
841
        // Worked. Log and return compare.
842
        // Compare mtimes.
843
        if ($mtime1 == $mtime2) {
844
            return 0;
845
        }
846
847
        return ($mtime1 < $mtime2) ? -1 : 1; // end compare
848
    }
849
850
    /**
851
     * returns the contents of a directory in an array
852
     *
853
     * @param  PhingFile $f
854
     * @return string[]
855
     */
856 175
    public function listContents(PhingFile $f)
857
    {
858 175
        return array_keys(
859 175
            iterator_to_array(
860 175
                new FilesystemIterator(
861 175
                    $f->getAbsolutePath(),
862 175
                    FilesystemIterator::KEY_AS_FILENAME
863
                )
864
            )
865
        );
866
    }
867
868
    /**
869
     * PHP implementation of the 'which' command.
870
     *
871
     * Used to retrieve/determine the full path for a command.
872
     *
873
     * @param string $executable Executable file to search for
874
     * @param mixed $fallback Default to fallback to.
875
     *
876
     * @return string Full path for the specified executable/command.
877
     */
878 30
    public function which($executable, $fallback = false)
879
    {
880 30
        if (is_string($executable)) {
0 ignored issues
show
introduced by
The condition is_string($executable) is always true.
Loading history...
881 29
            if (trim($executable) === '') {
882
                return $fallback;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $fallback could also return false which is incompatible with the documented return type string. Did you maybe forget to handle an error condition?

If the returned type also contains false, it is an indicator that maybe an error condition leading to the specific return statement remains unhandled.

Loading history...
883
            }
884
        } else {
885 1
            return $fallback;
886
        }
887 29
        if (basename($executable) === $executable) {
888 29
            $path = getenv("PATH");
889
        } else {
890
            $path = dirname($executable);
891
        }
892 29
        $dirSeparator = $this->getSeparator();
893 29
        $pathSeparator = $this->getPathSeparator();
894 29
        $elements = explode($pathSeparator, $path);
895 29
        $amount = count($elements);
896 29
        $fstype = Phing::getProperty('host.fstype');
897 29
        switch ($fstype) {
898 29
            case 'UNIX':
899 29
                for ($count = 0; $count < $amount; ++$count) {
900 29
                    $file = $elements[$count] . $dirSeparator . $executable;
901 29
                    if (file_exists($file) && is_executable($file)) {
902 27
                        return $file;
903
                    }
904
                }
905 4
                break;
906
            case 'WINDOWS':
907
                $exts = getenv('PATHEXT');
908
                if ($exts === false) {
909
                    $exts = ['.exe', '.bat', '.cmd', '.com'];
910
                } else {
911
                    $exts = explode($pathSeparator, $exts);
912
                }
913
                for ($count = 0; $count < $amount; $count++) {
914
                    foreach ($exts as $ext) {
915
                        $file = $elements[$count] . $dirSeparator . $executable . $ext;
916
                        // Not all of the extensions above need to be set executable on Windows for them to be executed.
917
                        // I'm sure there's a joke here somewhere.
918
                        if (file_exists($file)) {
919
                            return $file;
920
                        }
921
                    }
922
                }
923
                break;
924
        }
925 4
        if (file_exists($executable) && is_executable($executable)) {
926
            return $executable;
927
        }
928 4
        return $fallback;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $fallback could also return false which is incompatible with the documented return type string. Did you maybe forget to handle an error condition?

If the returned type also contains false, it is an indicator that maybe an error condition leading to the specific return statement remains unhandled.

Loading history...
929
    }
930
}
931