protected function fetchAndSaveUniqueImage($url)
{
if (!filter_var($url, FILTER_VALIDATE_URL)) {
return '';
}
$remote_img_location = $url;
// Cheap cache
static $already_done = array();
if (isset($already_done[$remote_img_location])) {
return $already_done[$remote_img_location];
}
/* Process */
// Basename without query string
$filename = explode('?', basename($url));
$filename = array_shift($filename);
$filename = sanitize_file_name(urldecode($filename));
if (!preg_match('/\\.(jpe?g|gif|png)$/i', $filename)) {
// Unsupported image type
$already_done[$remote_img_location] = '';
return '';
}
$tmp_name = download_url($remote_img_location);
if (is_wp_error($tmp_name)) {
// Download failed
$already_done[$remote_img_location] = '';
return '';
}
if (!\Pressbooks\Image\is_valid_image($tmp_name, $filename)) {
try {
// changing the file name so that extension matches the mime type
$filename = $this->properImageExtension($tmp_name, $filename);
if (!\Pressbooks\Image\is_valid_image($tmp_name, $filename)) {
throw new \Exception('Image is corrupt, and file extension matches the mime type');
}
} catch (\Exception $exc) {
// Garbage, don't import
$already_done[$remote_img_location] = '';
unlink($tmp_name);
return '';
}
}
$pid = media_handle_sideload(array('name' => $filename, 'tmp_name' => $tmp_name), 0);
$src = wp_get_attachment_url($pid);
if (!$src) {
$src = '';
// Change false to empty string
}
$already_done[$remote_img_location] = $src;
@unlink($tmp_name);
return $src;
}