<?php
/**
* Sanitize upload filenames
* For reference:
* @See http://codex.wordpress.org/Function_Reference/wp_handle_upload
* @See http://php.net/manual/en/function.rename.php
*/
if( !function_exists('vires_artes_sanitize_upload_filenames') ) {
function vires_artes_sanitize_upload_filenames($vals)
{
// Extract the filename and URL Decode it
$name = array_reverse(explode('/', $vals['file']));
$name = urldecode($name[0]);
// Extract the local path to the uploaded file and remove the current filename
$url = str_replace($name, '', urldecode($vals['file']));
// Extract the public URL for the uploaded file and remove the current filename
$wurl = str_replace($name, '', urldecode($vals['url']));
// Sanitize the filename replacing non UTF8 characters
$filetype = wp_check_filetype($name);
$name = str_replace('.'.$filetype['ext'], '', $name);
$name = sanitize_title($name);
$sanitized_file_name = $name . '.' . $filetype['ext'];
// Update the file array with the updated filename in it, precerving the local
// and public url, just updating the filename with the sanitized version.
if(@rename($vals['file'], $url . $sanitized_file_name))
{
return array(
'file' => $url . $sanitized_file_name,
'url' => $wurl . $sanitized_file_name,
'type' => $vals['type']
);
}
// Return the filearray
return $vals;
}
}
add_action('wp_handle_upload', 'vires_artes_sanitize_upload_filenames');
?>