Last active
May 19, 2016 12:56
-
-
Save viruthagiri/99a97212c3d23b4667d30e756436b7ec to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function fetch_remote_file($url) | |
{ | |
// extract the file name and extension from the url | |
require_once(ABSPATH . 'wp-includes/pluggable.php'); | |
$file_name = basename($url); | |
if (strpos($file_name, '?') !== false) { | |
list($file_name) = explode('?', $file_name); | |
} | |
$dummy = false; | |
$add_to_cache = false; | |
$key = null; | |
if (strpos($url, '/dummy/') !== false) { | |
$dummy = true; | |
$key = "dummy_".str_replace('.', '_', $file_name); | |
$value = get_transient($key); | |
if ($value) { | |
return $value; | |
} else { | |
$add_to_cache = true; | |
} | |
} | |
// get placeholder file in the upload dir with a unique, sanitized filename | |
$post_upload_date = isset($post['upload_date']) ? $post['upload_date'] : ''; | |
$upload = wp_upload_bits($file_name, 0, '', $post_upload_date); | |
if ($upload['error']) | |
return new WP_Error('upload_dir_error', $upload['error']); | |
// fetch the remote url and write it to the placeholder file | |
$headers = wp_remote_get($url, array('stream' => true,'filename' => $upload['file'])); | |
$log_message = ''; | |
$filesize = filesize($upload['file']); | |
// request failed | |
if (!$headers) { | |
$log_message = __('Remote server did not respond', 'geodirectory'); | |
} | |
// make sure the fetch was successful | |
elseif ($headers['response']['code'] != '200') { | |
$log_message = sprintf(__('Remote server returned error response %1$d %2$s', 'geodirectory'), esc_html($headers['response']), get_status_header_desc($headers['response'])); | |
} | |
elseif (isset($headers['headers']['content-length']) && $filesize != $headers['headers']['content-length']) { | |
$log_message = __('Remote file is incorrect size', 'geodirectory'); | |
} | |
elseif (0 == $filesize) { | |
$log_message = __('Zero size file downloaded', 'geodirectory'); | |
} | |
if($log_message){ | |
$del = unlink($upload['file']); | |
if(!$del){geodir_error_log(__('GeoDirectory: fetch_remote_file() failed to delete temp file.', 'geodirectory'));} | |
return new WP_Error('import_file_error',$log_message ); | |
} | |
if ($dummy && $add_to_cache && is_array($upload)) { | |
//setting the cache using the WP Transient API | |
set_transient($key, $upload, 60 * 10); //10 minutes cache | |
} | |
return $upload; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment