ILIAS  trunk Revision v11.0_alpha-2638-g80c1d007f79
FilenameSanitizerImpl.php
Go to the documentation of this file.
1 <?php
2 
19 declare(strict_types=1);
20 
22 
24 
32 {
37  public function __construct(
41  private array $whitelist
42  ) {
43  // the secure file ending must be valid, therefore add it if it got removed from the white list.
44  if (!in_array(FilenameSanitizer::CLEAN_FILE_SUFFIX, $this->whitelist, true)) {
45  $this->whitelist[] = FilenameSanitizer::CLEAN_FILE_SUFFIX;
46  }
47  }
48 
49 
50  public function isClean(string $filename): bool
51  {
52  $suffix = $this->extractFileSuffix($filename);
53  if (preg_match('/^ph(p[3457]?|t|tml|ar)$/i', $suffix)) {
54  return false;
55  }
56 
57  return in_array($suffix, $this->whitelist, true);
58  }
59 
63  public function sanitize(string $filename): string
64  {
65  $filename = Util::sanitizeFileName($filename);
66 
67  if ($this->isClean($filename)) {
68  return $filename;
69  }
70 
71  $pathInfo = pathinfo($filename);
72  $basename = $pathInfo['basename'];
73  $parentPath = $pathInfo['dirname'] === '.' ? '' : $pathInfo['dirname'];
74 
75  $filename = str_replace('.', '', $basename);
76  $filename .= "." . FilenameSanitizer::CLEAN_FILE_SUFFIX;
77 
78  // there is no parent
79  if ($parentPath === '') {
80  return $filename;
81  }
82 
83  return "$parentPath/$filename";
84  }
85 
93  private function extractFileSuffix(string $filename): string
94  {
95  return strtolower(pathinfo($filename, PATHINFO_EXTENSION));
96  }
97 }
Standard implementation of the filename sanitizing interface.
static sanitizeFileName(string $filename)
Definition: Util.php:48
This file is part of ILIAS, a powerful learning management system published by ILIAS open source e-Le...
isClean(string $filename)
Checks if the filename is prefixed with a valid whitelisted ending.
The filename sanitizer verifies and fixes file name endings.
const CLEAN_FILE_SUFFIX
This file suffix will be used to sanitize not whitelisted file names.
This file is part of ILIAS, a powerful learning management system published by ILIAS open source e-Le...
$filename
Definition: buildRTE.php:78
__construct(private array $whitelist)
FilenameSanitizerImpl constructor.
extractFileSuffix(string $filename)
Extracts the suffix from the given filename.