/** * Sanitize a file name. * * Transliterates the file name and removes all problematic characters. * * @param string $filename * A file name. * @param string $langcode * Optional ISO 639 language code used to import language specific * replacements. Defaults to the current display language. * * @return string * Cleaned file name. */ function transliteration_clean_filename($filename, $langcode = NULL) { // Trim any leading/trailing dots. $filename = trim($filename, '.'); // Transliterate to ASCII. $filename = transliteration_process($filename, '', $langcode); // Replace whitespace. $filename = str_replace(' ', '_', $filename); // Remove any remaining non-safe characters. $filename = preg_replace('/[^0-9A-Za-z_-]/', '', $filename); return $filename; }
function replace_forbidden($str) { static $forbidden_chars; if (!is_array($forbidden_chars)) { global $CONFIG, $mb_utf8_regex; if (function_exists('html_entity_decode')) { $chars = html_entity_decode($CONFIG['forbiden_fname_char'], ENT_QUOTES, 'UTF-8'); } else { $chars = str_replace(array('&', '"', '<', '>', ' ', '''), array('&', '"', '<', '>', ' ', "'"), $CONFIG['forbiden_fname_char']); } preg_match_all("#{$mb_utf8_regex}" . '|[\\x00-\\x7F]#', $chars, $forbidden_chars); } /** * $str may also come from $_POST, in this case, all &, ", etc will get replaced with entities. * Replace them back to normal chars so that the str_replace below can work. */ $str = str_replace(array('&', '"', '<', '>'), array('&', '"', '<', '>'), $str); $return = str_replace($forbidden_chars[0], '_', $str); $condition = array('transliteration' => true, 'special_chars' => true); $condition = CPGPluginAPI::filter('replace_forbidden_conditions', $condition); /** * Transliteration */ if ($condition['transliteration']) { require_once 'include/transliteration.inc.php'; $return = transliteration_process($return, '_'); } /** * Replace special chars */ if ($condition['special_chars']) { $return = str_replace('%', '', rawurlencode($return)); } /** * Fix the obscure, misdocumented "feature" in Apache that causes the server * to process the last "valid" extension in the filename (rar exploit): replace all * dots in the filename except the last one with an underscore. */ // This could be concatenated into a more efficient string later, keeping it in three // lines for better readability for now. $extension = ltrim(substr($return, strrpos($return, '.')), '.'); $filenameWithoutExtension = str_replace('.' . $extension, '', $return); $return = str_replace('.', '_', $filenameWithoutExtension) . '.' . $extension; return $return; }