ILIAS  release_5-3 Revision v5.3.23-19-g915713cf615
FilenameSanitizerImpl.php
Go to the documentation of this file.
1 <?php
2 
4 
5 use ilException;
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($filename)
48  {
50  return in_array($this->extractFileSuffix($filename), $this->whitelist, true);
51  }
52 
53 
57  public function sanitize($filename)
58  {
60  if ($this->isClean($filename)) {
61  return $filename;
62  }
63 
64  $pathInfo = pathinfo($filename);
65  $basename = $pathInfo['basename'];
66  $parentPath = $pathInfo['dirname'];
67 
68 
69  $filename = str_replace('.', '', $basename);
71 
72  // there is no parent
73  if ($parentPath === '') {
74  return $filename;
75  }
76 
77  return "$parentPath/$filename";
78  }
79 
80 
88  private function extractFileSuffix($filename)
89  {
90  return strtolower(pathinfo($filename, PATHINFO_EXTENSION));
91  }
92 
93 
101  private function validateFilename($filename)
102  {
103  if ($filename === null) {
104  throw new ilException("Filename must not be null to get sanitized!");
105  }
106  }
107 }
extractFileSuffix($filename)
Extracts the suffix from the given filename.
validateFilename($filename)
Validates that the filename is valid for further sanitizing.
const CLEAN_FILE_SUFFIX
This file suffix will be used to sanitize not whitelisted file names.
static getValidExtensions()
Valid extensions.