RMCreative → files/src/drupal_file_upload_from_url.phps
<?php
/**
 * Grabs a file from URL and saves it to Drupal files directory.
 * The file will be added to the files table as a permanent file.
 * If file already exists returns file object (incomplete).
 *
 * @param $url
 *   A string URL to grab file from.
 * @return
 *   An object containing the file information, or false if can't upload file
 */
function file_upload_from_url($url) {
    global 
$user;

    
$url_parts parse_url($url);
    
$dest $url_parts['path'];

    
// Build the list of non-munged extensions
    
$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'));
    }

    
// Begin building file object.
    
$file = new stdClass();
    
$file->filename file_munge_filename(trim(basename($url), '.'), $extensions);
    
$file->filemime file_get_mimetype($file->filename);

    
$path file_create_path(md5($dest)).'/'.$file->filename;

    
$file->filepath file_destination($pathFILE_EXISTS_ERROR);
    if(!
$file->filepath){
        
$file->filepath $path;
        return 
$file;
    }

    
//TODO: better way?
    
$response drupal_http_request($url);

    
file_check_directory(dirname($file->filepath), true);

    if(!
file_put_contents($file->filepath$response->data)) return false;

    
$info image_get_info($file->filepath);
    
$file->filesize $info['file_size'];

    
$file->uid $user->uid;
    
$file->status FILE_STATUS_PERMANENT;
    
$file->timestamp time();
    
drupal_write_record('files'$file);

    return 
$file;
}