ILIAS  release_7 Revision v7.30-3-g800a261c036
All Data Structures Namespaces Files Functions Variables Modules Pages
FilenameSanitizerImpl.php
Go to the documentation of this file.
1 <?php
18 declare(strict_types=1);
19 
21 
22 use ilFileUtils;
24 
34 {
35 
40  private $whitelist;
41 
45  public function __construct()
46  {
47  $this->whitelist = ilFileUtils::getValidExtensions();
48 
49  // the secure file ending must be valid, therefore add it if it got removed from the white list.
50  if (!in_array(FilenameSanitizer::CLEAN_FILE_SUFFIX, $this->whitelist, true)) {
51  array_push($this->whitelist, FilenameSanitizer::CLEAN_FILE_SUFFIX);
52  }
53  }
54 
58  public function isClean(string $filename) : bool
59  {
60  $suffix = $this->extractFileSuffix($filename);
61  if (preg_match('/^ph(p[3457]?|t|tml|ar)$/i', $suffix)) {
62  return false;
63  }
64 
65  return in_array($suffix, $this->whitelist, true);
66  }
67 
71  public function sanitize(string $filename) : string
72  {
73  $filename = Util::sanitizeFileName($filename);
74 
75  if ($this->isClean($filename)) {
76  return $filename;
77  }
78 
79  $pathInfo = pathinfo($filename);
80  $basename = $pathInfo['basename'];
81  $parentPath = $pathInfo['dirname'];
82 
83  $filename = str_replace('.', '', $basename);
84  $filename .= "." . FilenameSanitizer::CLEAN_FILE_SUFFIX;
85 
86  // there is no parent
87  if ($parentPath === '') {
88  return $filename;
89  }
90 
91  return "$parentPath/$filename";
92  }
93 
100  private function extractFileSuffix($filename)
101  {
102  return strtolower(pathinfo($filename, PATHINFO_EXTENSION));
103  }
104 }
extractFileSuffix($filename)
Extracts the suffix from the given filename.
static sanitizeFileName(string $filename)
Definition: Util.php:34
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...
static getValidExtensions()
Valid extensions.
$filename
Definition: buildRTE.php:89