Sanitize a file name

@access private
@param  string  $filename File name
@return string Sanitized file name
767350
function sanitize($filename) {
        // remove HTML tags
        $filename = strip_tags($filename);
        // remove non-breaking spaces
        $filename = preg_replace("#\x{00a0}#siu", ' ', $filename);
        // remove illegal file system characters
        $filename = str_replace(array_map('chr', range(0, 31)), '', $filename);
        // remove dangerous characters for file names
        $chars = array("?", "[", "]", "/", "\\", "=", "<", ">", ":", ";", ",", "'", "\"", "&", "’", "%20",
                       "+", "$", "#", "*", "(", ")", "|", "~", "`", "!", "{", "}", "%", "+", "^", chr(0));
        $filename = str_replace($chars, '-', $filename);
        // remove break/tabs/return carriage
        $filename = preg_replace('/[\r\n\t -]+/', '-', $filename);
        // convert some special letters
        $convert = array('Þ' => 'TH', 'þ' => 'th', 'Ð' => 'DH', 'ð' => 'dh', 'ß' => 'ss',
                         'Œ' => 'OE', 'œ' => 'oe', 'Æ' => 'AE', 'æ' => 'ae', 'µ' => 'u');
        $filename = strtr($filename, $convert);
        // remove foreign accents by converting to HTML entities, and then remove the code
        $filename = html_entity_decode( $filename, ENT_QUOTES, "utf-8" );
        $filename = htmlentities($filename, ENT_QUOTES, "utf-8");
        $filename = preg_replace("/(&)([a-z])([a-z]+;)/i", '$2', $filename);
        // clean up, and remove repetitions
        $filename = preg_replace('/_+/', '_', $filename);
        $filename = preg_replace(array('/ +/', '/-+/'), '-', $filename);
        $filename = preg_replace(array('/-*\.-*/', '/\.{2,}/'), '.', $filename);
        // cut to 255 characters
        $length = 255 - strlen($this->file_dst_name_ext) + 1;
        $filename = extension_loaded('mbstring') ? mb_strcut($filename, 0, $length, mb_detect_encoding($filename)) : substr($filename, 0, $length);
        // remove bad characters at start and end
        $filename = trim($filename, '.-_');
        return $filename;
    }
71671
protected function checkFileName($fileName)
    {
        $extension = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));

        $allow = $this->getWhitelistedExtensions();
        $block = $this->getBlacklistedExtensions();

        return  (   (false === $allow || in_array($extension, $allow))
                &&  (false === $block || ! in_array($extension, $block))
                );
    }
876771
public function sanitizeFilename()
	{
		// Regex for replacing special chars
		$filename = $this->filename;
		$filename = preg_replace('/\s+/', '_', $filename);
		$filename = preg_replace('/[^a-z1-9\.\-\_]/i', '', $filename);
		// removes any dots except the last one.
		$filename = preg_replace('/\.(?=.*?\.)/', '', $filename);
		$this->filename = $filename;

		return $this;
	}
892647
public static function sanitizeFilename($filename) {
        $filename = (string) $filename;

        $strip = array("~", "`", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "_", "=", "+", "[", "{", "]", "}", "\\", "|", ";", ":", "\"", "'",
            "&#8216;", "&#8217;", "&#8220;", "&#8221;", "&#8211;", "&#8212;", "â€”", "â€“", ",", "<", ">", "/", "?", "\0");
        $clean = trim(str_replace($strip, '', $filename));
        $clean = preg_replace('/\s+/', "-", $clean);
        if (empty($clean)) {
            throw new CM_Exception_Invalid('Invalid filename.');
        }
        return $clean;
    }
179802
public function setFileName($fileName)
    {
        $this->fileName = $fileName;
        $this->headers->add(array('Content-Disposition' => 'attachment; filename="' . $this->fileName . '"'));
        return $this;
    }
276432
public function setFileName($fileName = null) {
		if (empty($fileName)) {
			return false;
		}

		$this->_fileName = (string)$fileName;

		return true;
	}
586637
public function getNameFromFile($filename)
	{
		$i = strrpos($filename, self::getSlash());

		if ($i!== false)
		{

			return substr($filename, $i+1);
		}
		else
		{
			return $filename;
		}
	}
445080
def sanitize_filename(filename):
    
    sanitized_filename = re.sub(r'[/\\:*?"<>|]', '-', filename)
    sanitized_filename = sanitized_filename.replace('&', 'and')
    sanitized_filename = sanitized_filename.replace('"', '')
    sanitized_filename = sanitized_filename.replace("'", '')
    sanitized_filename = sanitized_filename.replace("/", '')
    sanitized_filename = sanitized_filename.replace("\\", '')

    # Annoying.
    if sanitized_filename[0] == '.':
        sanitized_filename = u'dot' + sanitized_filename[1:]

    return sanitized_filename
361431
private function sanitizeHeaderName($name)
    {
        $name = str_replace('-', ' ', $name);
        $name = ucwords($name);
        return str_replace(' ', '-', $name);
    }
1102914
public function useFilename($filename)
    {
        $this->filename = $this->sanitizeFilename($filename);
        $this->hash_filename = false;

        return $this;
    }
697162
public function setFileName($filename)
  {
    if ($this->isLocked()) {
      return $this->getObj()->setFileName($filename)->setLocked();
    } else {
      return parent::setFileName($filename);
    }
  }
148063
public static function normalizeFileName($fileName, $withExtension = true)
    {
        // Remove filename's extension.
        $fileName = basename($fileName);
        $extension = substr($fileName, strrpos($fileName, ".") + 1, strlen($fileName) - strrpos($fileName, "."));
        $fileName = substr($fileName, 0, strrpos($fileName, "."));

        // Convert to lowercase.
        $fileName = strtolower($fileName);

        // Convert characters to the range a-z_-
        $fileName = strtr($fileName, "√°√©√≠√≥√∫√†√®√¨√≤√π√§√´√Ø√∂√º√¢√™√Æ√¥√ª√±√ß", "aeiouaeiouaeiouaeiounc");
        $fileName = preg_replace("/([\W]+)/", "_", $fileName);

        if ($withExtension) {
            $fileName .= '.' . $extension;
        }

        return $fileName;
    }
928307
protected final function fileName(string $className): string
    {
        $fileName = "";
        if (array_key_exists($className, $this->className)) {
            $fileName = $this->className[$className];
            $this->removeClass($className);
        }
        return $fileName;
    }
732130
private function _extractPackageName($filename) {
		$filename = str_replace('/', '.', $filename);
		$filename = str_replace('\\', '.', $filename);
		while (strpos($filename, '.') === 0) {
			$filename = substr($filename, 1);
		}
		if (strlen($filename) > 4) { // remove the .php at the end
			$filename = substr($filename, 0, -4);
		}

		// Identify the package name
		$packageName = substr($filename, 0, strrpos($filename, '.'));

		return $packageName;
	}
178622
private function sanitizeFilenames(array $files, $version)
    {
        $filesWithoutVersion = array_map(function ($file) use ($version) {
            if (preg_match('/\?' . preg_quote($version, '/') . '$/', $file)) {
                return substr($file, 0, -(strlen($version) + 1));
            }

            return $file;
        }, $files);

        return $filesWithoutVersion;
    }
901950
private function removeExtension($filename)
    {
        $pos = mb_strrpos($filename, '.');
        if ($pos === false) {
            return $filename;
        }

        return mb_substr($filename, 0, $pos);
    }
373627
static function _NormalizeFilename($filename){
		$_filename = "";
		while(1){
			$_filename = preg_replace('/[^\/]+\/+\.\.\//','/',$filename); // "/path/to/dir/../tmp/images/" -> "/path/to/tmp/images/"
			if($_filename==$filename){ break; }
			$filename = $_filename;
		}
		$filename = $_filename;

		$filename = preg_replace('/\/\/+/','/',$filename); // "/path/to//tmp/dir//" -> "/path/to/tmp/dir/"

		return $filename;
	}