@@ -997,16 +997,22 @@ function file_build_uri($path) {
997
997
* @return
998
998
* The destination filepath, or FALSE if the file already exists
999
999
* and FILE_EXISTS_ERROR is specified.
1000
+ *
1001
+ * @throws RuntimeException
1002
+ * Thrown if the filename contains invalid UTF-8.
1000
1003
*/
1001
1004
function file_destination ($ destination , $ replace ) {
1005
+ $ basename = drupal_basename ($ destination );
1006
+ if (!drupal_validate_utf8 ($ basename )) {
1007
+ throw new RuntimeException (sprintf ("Invalid filename '%s' " , $ basename ));
1008
+ }
1002
1009
if (file_exists ($ destination )) {
1003
1010
switch ($ replace ) {
1004
1011
case FILE_EXISTS_REPLACE :
1005
1012
// Do nothing here, we want to overwrite the existing file.
1006
1013
break ;
1007
1014
1008
1015
case FILE_EXISTS_RENAME :
1009
- $ basename = drupal_basename ($ destination );
1010
1016
$ directory = drupal_dirname ($ destination );
1011
1017
$ destination = file_create_filename ($ basename , $ directory );
1012
1018
break ;
@@ -1222,11 +1228,20 @@ function file_unmunge_filename($filename) {
1222
1228
* @return
1223
1229
* File path consisting of $directory and a unique filename based off
1224
1230
* of $basename.
1231
+ *
1232
+ * @throws RuntimeException
1233
+ * Thrown if the $basename is not valid UTF-8 or another error occurs
1234
+ * stripping control characters.
1225
1235
*/
1226
1236
function file_create_filename ($ basename , $ directory ) {
1237
+ $ original = $ basename ;
1227
1238
// Strip control characters (ASCII value < 32). Though these are allowed in
1228
1239
// some filesystems, not many applications handle them well.
1229
1240
$ basename = preg_replace ('/[\x00-\x1F]/u ' , '_ ' , $ basename );
1241
+ if (preg_last_error () !== PREG_NO_ERROR ) {
1242
+ throw new RuntimeException (sprintf ("Invalid filename '%s' " , $ original ));
1243
+ }
1244
+
1230
1245
if (substr (PHP_OS , 0 , 3 ) == 'WIN ' ) {
1231
1246
// These characters are not allowed in Windows filenames
1232
1247
$ basename = str_replace (array (': ' , '* ' , '? ' , '" ' , '< ' , '> ' , '| ' ), '_ ' , $ basename );
@@ -1567,7 +1582,13 @@ function file_save_upload($form_field_name, $validators = array(), $destination
1567
1582
if (substr ($ destination , -1 ) != '/ ' ) {
1568
1583
$ destination .= '/ ' ;
1569
1584
}
1570
- $ file ->destination = file_destination ($ destination . $ file ->filename , $ replace );
1585
+ try {
1586
+ $ file ->destination = file_destination ($ destination . $ file ->filename , $ replace );
1587
+ }
1588
+ catch (RuntimeException $ e ) {
1589
+ drupal_set_message (t ('The file %source could not be uploaded because the name is invalid. ' , array ('%source ' => $ form_field_name )), 'error ' );
1590
+ return FALSE ;
1591
+ }
1571
1592
// If file_destination() returns FALSE then $replace == FILE_EXISTS_ERROR and
1572
1593
// there's an existing file so we need to bail.
1573
1594
if ($ file ->destination === FALSE ) {
0 commit comments