ILIAS  release_8 Revision v8.19
All Data Structures Namespaces Files Functions Variables Modules Pages
FilenameSanitizerImpl.php
Go to the documentation of this file.
1 <?php
2 
19 declare(strict_types=1);
20 
22 
23 use ilFileUtils;
25 
38 {
44  private array $whitelist;
45 
46 
50  public function __construct(array $whitelist)
51  {
52  $this->whitelist = $whitelist;
53 
54  // the secure file ending must be valid, therefore add it if it got removed from the white list.
55  if (!in_array(FilenameSanitizer::CLEAN_FILE_SUFFIX, $this->whitelist, true)) {
56  $this->whitelist[] = FilenameSanitizer::CLEAN_FILE_SUFFIX;
57  }
58  }
59 
60 
61  public function isClean(string $filename): bool
62  {
63  $suffix = $this->extractFileSuffix($filename);
64  if (preg_match('/^ph(p[3457]?|t|tml|ar)$/i', $suffix)) {
65  return false;
66  }
67 
68  return in_array($suffix, $this->whitelist, true);
69  }
70 
71 
75  public function sanitize(string $filename): string
76  {
77  $filename = Util::sanitizeFileName($filename);
78 
79  if ($this->isClean($filename)) {
80  return $filename;
81  }
82 
83  $pathInfo = pathinfo($filename);
84  $basename = $pathInfo['basename'];
85  $parentPath = $pathInfo['dirname'] === '.' ? '' : $pathInfo['dirname'];
86 
87 
88  $filename = str_replace('.', '', $basename);
89  $filename .= "." . FilenameSanitizer::CLEAN_FILE_SUFFIX;
90 
91  // there is no parent
92  if ($parentPath === '') {
93  return $filename;
94  }
95 
96  return "$parentPath/$filename";
97  }
98 
99 
107  private function extractFileSuffix(string $filename): string
108  {
109  return strtolower(pathinfo($filename, PATHINFO_EXTENSION));
110  }
111 }
__construct(array $whitelist)
FilenameSanitizerImpl constructor.
static sanitizeFileName(string $filename)
Definition: Util.php:36
isClean(string $filename)
Checks if the filename is prefixed with a valid whitelisted ending.
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
extractFileSuffix(string $filename)
Extracts the suffix from the given filename.