ILIAS  release_5-4 Revision v5.4.26-12-gabc799a52e6
FilenameSanitizerImpl.php
Go to the documentation of this file.
1 <?php
2 declare(strict_types=1);
3 
5 
6 use ilFileUtils;
7 
20 {
21 
27  private $whitelist;
28 
29 
33  public function __construct()
34  {
35  $this->whitelist = ilFileUtils::getValidExtensions();
36 
37  // the secure file ending must be valid, therefore add it if it got removed from the white list.
38  if (!in_array(FilenameSanitizer::CLEAN_FILE_SUFFIX, $this->whitelist, true)) {
39  array_push($this->whitelist, FilenameSanitizer::CLEAN_FILE_SUFFIX);
40  }
41  }
42 
43 
47  public function isClean(string $filename) : bool
48  {
49  return in_array($this->extractFileSuffix($filename), $this->whitelist, true);
50  }
51 
52 
56  public function sanitize(string $filename) : string
57  {
58  if ($this->isClean($filename)) {
59  return $filename;
60  }
61 
62  $pathInfo = pathinfo($filename);
63  $basename = $pathInfo['basename'];
64  $parentPath = $pathInfo['dirname'];
65 
66 
67  $filename = str_replace('.', '', $basename);
68  $filename .= "." . FilenameSanitizer::CLEAN_FILE_SUFFIX;
69 
70  // there is no parent
71  if ($parentPath === '') {
72  return $filename;
73  }
74 
75  return "$parentPath/$filename";
76  }
77 
78 
86  private function extractFileSuffix($filename)
87  {
88  return strtolower(pathinfo($filename, PATHINFO_EXTENSION));
89  }
90 }
extractFileSuffix($filename)
Extracts the suffix from the given filename.
const CLEAN_FILE_SUFFIX
This file suffix will be used to sanitize not whitelisted file names.
static getValidExtensions()
Valid extensions.
$filename
Definition: buildRTE.php:89