Archive for ‘Drupal’

November 10, 2010

While uploading rename file by replacing special character


I have faced some problem to download files which name has special character (like #).  So I have come up a solution by modifying drupal’s core file, includes>file.inc

on file.inc there is a code block like the following,

// Begin building file object.    
$file = new stdClass();   
$file->filename = file_munge_filename(trim(basename($_FILES['files']['name'][$source]), '.'), $extensions);    
$file->filepath = $_FILES['files']['tmp_name'][$source];    
$file->filemime = file_get_mimetype($file->filename);

I have replaced the code with the following code block,

// Begin building file object.     
$file = new stdClass();	 
$file->filename = trim(basename($_FILES["files"]["name"][$source]), '.');	 
$fn = trim(basename($_FILES["files"]["name"][$source]), '.');	 
// split filename based around the . and 3 or 4 letter ext 	 
preg_match("/(^[A-Za-z0-9.].*)(\.[a-z]{3}|\.[a-z]{4})$/", $fn, $matches);	
// replace anything in name ($matches [1]) that is not letter, number or underscore	 
$fn = preg_replace("/[^A-Za-z0-9_]/","_", trim($matches[1]));	 
// remove the dot from .ext suffix	 
$ext = trim($matches[2], '.');	 
//shorten filename to be 54 chars with ext (50+4)	 
$stem = substr($fn, 0, 50);	 
$file->filename = $stem . "." . $ext;     
// Create temporary name/path for newly uploaded files.     
//$file->filepath = tempnam(file_directory_temp(), 'tmp_');    
$file->filepath = $_FILES['files']['tmp_name'][$source];    
$file->filemime = file_get_mimetype($file->filename);


November 10, 2010

Upload file with any extension in drupal


Drupal has a default extension list and files with those extension only allowed to upload. From administrator UI (administratot>file upload) we can add other extension. But if we want to modify the default list we can do that by modifying includes>file.inc

on file.inc there is a code block like the following,

$extensions = ”;    foreach ($user->roles as $rid => $name) {      $extensions .= ‘ ‘. variable_get(“upload_extensions_$rid”,      variable_get(‘upload_extensions_default’, ‘jpg jpeg gif png txt html doc xls pdf ppt pps odt ods odp’));    }

So we can add our desire extension.

There is also a validation function to check the files with allowed extension. We can disregard the validation.

function file_validate_extensions($file, $extensions) {

global $user;
$errors = array();
// Bypass validation for uid  = 1.

if ($user->uid != 1) {

$regex = ‘/\.(‘. ereg_replace(‘ +’, ‘|’, preg_quote($extensions)) .’)$/i’;

if (!preg_match($regex, $file->filename)) {

$errors[] = t(‘Only files with the following extensions are allowed: %files-allowed.’, array(‘%files-allowed’ => $extensions));

}

}

return $errors;

}