function media_sideload_image_1($file, $post_id, $desc = null, $return = 'html') { if (!empty($file)) { // Set variables for storage, fix file filename for query strings. preg_match('/[^\\?]+\\.(jpe?g|jpe|gif|png)\\b/i', $file, $matches); $file_array = array(); $file_array['name'] = basename($matches[0]); // Download file to temp location. $file_array['tmp_name'] = download_url($file); // If error storing temporarily, return the error. if (is_wp_error($file_array['tmp_name'])) { return $file_array['tmp_name']; } // Do the validation and storage stuff. $id = media_handle_sideload($file_array, $post_id, $desc); // If error storing permanently, unlink. if (is_wp_error($id)) { @unlink($file_array['tmp_name']); return $id; } /*$fullsize_path = get_attached_file( $id ); // Full path if (function_exists('ewww_image_optimizer')) { ewww_image_optimizer($fullsize_path, $gallery_type = 4, $converted = false, $new = true, $fullsize = true); }*/ $src = wp_get_attachment_url($id); } if (!empty($src)) { //update_post_meta($post_id, 'image_value', $src); set_post_thumbnail($post_id, $id); //update_post_meta($post_id, 'Thumbnail', $src); return get_post_meta($post_id, 'image_value', true); } else { return new WP_Error('image_sideload_failed'); } }
function fabim_upload_action() { $image = $_POST['image']; //Get the base-64 string from data $filteredData = substr($_POST['image'], strpos($_POST['image'], ",") + 1); //Decode the string $unencodedData = base64_decode($filteredData); $originalName = basename(parse_url('image_marker.png', PHP_URL_PATH)); $tempName = tempnam('/tmp', 'php_files'); $tempName = realpath($tempName); file_put_contents($tempName, $unencodedData); $data = array(); $data['name'] = $originalName; $data['type'] = 'image/png'; $data['tmp_name'] = $tempName; $data['error'] = 0; $data['size'] = strlen($unencodedData); $_FILES['image'] = array('name' => $originalName, 'type' => 'image/jpeg', 'tmp_name' => $tempName, 'error' => 0, 'size' => strlen($unencodedData)); $movefile = media_handle_sideload($_FILES['image'], 0); if ($movefile && !isset($movefile['error'])) { die('Done'); } else { _e('Failed to recreating image, please try again', 'fabric-marker'); } }
public static function image($post_id) { $images = array(); $xml = simplexml_load_file('https://unsplash.com/rss'); foreach ($xml->channel->item as $item) { foreach ($item->image->url as $url) { $images[] = (string) $url; } } shuffle($images); $url = $images[0]; $tmp = download_url($url); $file_array = array('name' => 'new test image', 'tmp_name' => $tmp); // Check for download errors if (is_wp_error($tmp)) { @unlink($file_array['tmp_name']); } $image_id = media_handle_sideload($file_array, $post_id); // Check for handle sideload errors. if (is_wp_error($image_id)) { @unlink($file_array['tmp_name']); } if (is_wp_error($image_id)) { return $image_id; } }
/** * Cron - Thumbnail extraction */ function wp_rp_upload_attachment($url, $post_id) { /* Parts copied from wp-admin/includes/media.php:media_sideload_image */ include_once ABSPATH . 'wp-admin/includes/file.php'; include_once ABSPATH . 'wp-admin/includes/media.php'; include_once ABSPATH . 'wp-admin/includes/image.php'; $tmp = download_url($url); preg_match('/[^\\?]+\\.(jpe?g|jpe|gif|png)\\b/i', $url, $matches); $file_array['name'] = sanitize_file_name(urldecode(basename($matches[0]))); $file_array['tmp_name'] = $tmp; if (is_wp_error($tmp)) { @unlink($file_array['tmp_name']); return false; } $post_data = array('guid' => $url, 'post_title' => 'rp_' . $file_array['name']); $attachment_id = media_handle_sideload($file_array, $post_id, null, $post_data); if (is_wp_error($attachment_id)) { @unlink($file_array['tmp_name']); return false; } $attach_data = wp_get_attachment_metadata($attachment_id); $platform_options = wp_rp_get_platform_options(); $min_width = $platform_options['custom_size_thumbnail_enabled'] ? WP_RP_CUSTOM_THUMBNAILS_WIDTH : WP_RP_THUMBNAILS_WIDTH; $min_height = $platform_options['custom_size_thumbnail_enabled'] ? WP_RP_CUSTOM_THUMBNAILS_HEIGHT : WP_RP_THUMBNAILS_HEIGHT; if (!$attach_data || $attach_data['width'] < $min_width || $attach_data['height'] < $min_height) { wp_delete_attachment($attachment_id); return false; } return $attachment_id; }
/** * Similar to `media_sideload_image` except that it simply returns the attachment's ID on success * * @param (string) $file the url of the image to download and attach to the post * @param (integer) $post_id the post ID to attach the image to * @param (string) $desc an optional description for the image * * @since 0.5.2 */ function largo_media_sideload_image($file, $post_id, $desc = null) { if (!empty($file)) { include_once ABSPATH . 'wp-admin/includes/image.php'; include_once ABSPATH . 'wp-admin/includes/file.php'; include_once ABSPATH . 'wp-admin/includes/media.php'; // Set variables for storage, fix file filename for query strings. preg_match('/[^\\?]+\\.(jpe?g|jpe|gif|png)\\b/i', $file, $matches); $file_array = array(); $file_array['name'] = basename($matches[0]); // Download file to temp location. $file_array['tmp_name'] = download_url($file); // If error storing temporarily, return the error. if (is_wp_error($file_array['tmp_name'])) { return $file_array['tmp_name']; } // Do the validation and storage stuff. $id = media_handle_sideload($file_array, $post_id, $desc); // If error storing permanently, unlink. if (is_wp_error($id)) { @unlink($file_array['tmp_name']); } return $id; } }
function setFeaturedImage($post_id, $url, $featuredImageTitle) { // Download file to temp location and setup a fake $_FILE handler // with a new name based on the post_id $tmp_name = download_url($url); // echo $tmp_name; $file_array['name'] = $post_id . '-thumb.jpg'; // new filename based on slug $file_array['tmp_name'] = $tmp_name; // If error storing temporarily, unlink if (is_wp_error($tmp_name)) { @unlink($file_array['tmp_name']); $file_array['tmp_name'] = ''; } // do validation and storage . Make a description based on the Post_ID $attachment_id = media_handle_sideload($file_array, $post_id, 'Thumbnail for ' . $post_id); // If error storing permanently, unlink if (is_wp_error($attachment_id)) { $error_string = $attachment_id->get_error_message(); @unlink($file_array['tmp_name']); return; } // Set as the post attachment $post_result = add_post_meta($post_id, '_thumbnail_id', $attachment_id, true); // echo $post_result); }
private function create_file($name, $vararray) { $string = $this->generate_csv_string($vararray); $upload_dir = wp_upload_dir(); $file = $upload_dir['path'] . "/" . $name . ".csv"; file_put_contents($file, $string); $url = $upload_dir['url'] . "/" . $name . ".csv"; $tmp = download_url($url); $post_id = $this->options[$this->page_id_field]; $file_array = array(); // Set variables for storage // fix file filename for query strings preg_match('/[^\\?]+\\.(jpg|jpe|jpeg|gif|png|csv)/i', $url, $matches); $file_array['name'] = basename($matches[0]); $file_array['tmp_name'] = $tmp; // If error storing temporarily, unlink if (is_wp_error($tmp)) { print_r($tmp); @unlink($file_array['tmp_name']); $file_array['tmp_name'] = ''; } // do the validation and storage stuff $id = media_handle_sideload($file_array, $post_id, $desc); // If error storing permanently, unlink if (is_wp_error($id)) { print_r($id); @unlink($file_array['tmp_name']); return $id; } $src = wp_get_attachment_url($id); echo $src; }
public function load_thumbnail($post_id, $url, $desc = null) { if (!empty($url)) { // Download file to temp location $tmp = download_url($url); // Set variables for storage // fix file filename for query strings preg_match('/[^\\?]+\\.(jpg|JPG|jpe|JPE|jpeg|JPEG|gif|GIF|png|PNG)/', $url, $matches); if (isset($matches[0])) { $file_array['name'] = basename($matches[0]); } $file_array['tmp_name'] = $tmp; // If error storing temporarily, unlink if (is_wp_error($tmp)) { @unlink($file_array['tmp_name']); $file_array['tmp_name'] = ''; } // do the validation and storage stuff $id = media_handle_sideload($file_array, $post_id, $desc); if (!is_wp_error($id)) { return $id; } // If error storing permanently, unlink @unlink($file_array['tmp_name']); } return false; }
/** * Add track details when a post is saved. * * @param int $post_id The post ID. * @param post $post The post object. * @param bool $update Whether this is an existing post being updated or not. */ function soundpress_add_track_details_to_post($post_id, $post, $update) { $trackurl = get_post_meta($post_id, 'soundpress_soundcloud_url', true); if (wp_is_post_revision($post_id)) { return; } if ($trackurl) { $track_details = soundcloud_remote_get($trackurl); if (is_object($track_details)) { // Check for thumbnail. If not present, get the board Image if (!has_post_thumbnail($post_id)) { $thumbnailurl = $track_details->artwork_url; if (empty($thumbnailurl)) { $thumbnailurl = $track_details->user->avatar_url; } $tmp = download_url($thumbnailurl); if (is_wp_error($tmp)) { } $desc = get_the_title($post_id); $file_array = array(); // Set variables for storage // fix file filename for query strings preg_match('/[^\\?]+\\.(jpg|jpe|jpeg|gif|png)/i', $thumbnailurl, $matches); $file_array['name'] = basename($matches[0]); $file_array['tmp_name'] = $tmp; // If error storing temporarily, unlink if (is_wp_error($tmp)) { @unlink($file_array['tmp_name']); $file_array['tmp_name'] = ''; } // do the validation and storage stuff $id = media_handle_sideload($file_array, $post_id, $desc); // If error storing permanently, unlink if (is_wp_error($id)) { @unlink($file_array['tmp_name']); return $id; } set_post_thumbnail($post_id, $id); } // Check for Description if ("" == get_the_content()) { $postcontentarray = array('ID' => $post_id, 'post_content' => $track_details->description); // Update the post into the database wp_update_post($postcontentarray); } // Get The Duration $durationseconds = $track_details->duration / 1000; update_post_meta($post_id, 'podcast_duration', esc_attr($durationseconds)); if (TRUE == $track_details->downloadable) { $download_url = esc_attr($track_details->download_url); update_post_meta($post_id, 'podcast_download_url', $download_url); } } } }
function insert_attachment($image, $post_id, $setthumb = 'false') { require_once ABSPATH . "wp-admin" . '/includes/image.php'; require_once ABSPATH . "wp-admin" . '/includes/file.php'; require_once ABSPATH . "wp-admin" . '/includes/media.php'; // use image exif/iptc data for title and caption defaults if possible $array = array('name' => basename($image), 'type' => 'image/jpeg', 'tmp_name' => $image, 'error' => 0, 'size' => filesize($image)); $imageId = media_handle_sideload($array, $post_id); if ($setthumb) { update_post_meta($post_id, '_thumbnail_id', $imageId); } return $imageId; }
public function after_save() { if (is_array($this->file_upload)) { //do the upload require_once ABSPATH . 'wp-admin/includes/image.php'; require_once ABSPATH . 'wp-admin/includes/file.php'; require_once ABSPATH . 'wp-admin/includes/media.php'; $media_id = media_handle_sideload($this->file_upload['file'], $this->id, $this->content, array('post_status' => 'inherit')); if (is_wp_error($media_id)) { //todo log //return $media_id; } else { //all good, store the value now update_post_meta($this->id, '_file', $media_id); } } }
function loadImg($url) { // во фронтэнде нужны эти файлы require_once ABSPATH . "wp-admin" . '/includes/image.php'; require_once ABSPATH . "wp-admin" . '/includes/file.php'; require_once ABSPATH . "wp-admin" . '/includes/media.php'; $file_array = array(); $tmp = download_url($url); // корректируем умя файла в строках запроса. $nameR = end(explode('.', end(explode('/', $url)))); $file_array['name'] = rand(100000, 999999) . '.' . $nameR; $file_array['tmp_name'] = $tmp; $id = media_handle_sideload($file_array, 0); // удалим временный файл @unlink($file_array['tmp_name']); return $id; }
/** * Get a fresh icon image from grabicon.com and cache it. */ public function sideload_icon() { require_once ABSPATH . 'wp-admin/includes/file.php'; require_once ABSPATH . 'wp-admin/includes/media.php'; require_once ABSPATH . 'wp-admin/includes/image.php'; $grab_base_url = 'http://grabicon.com/icon'; $home_url_parts = parse_url(home_url()); $grab_url = add_query_arg(array('size' => $this->size, 'domain' => $home_url_parts['host'], 'origin' => $home_url_parts['host'], 'reset' => 'true', 'key' => self::$api_key), $grab_base_url); $file_info = array('name' => 'prompt-site-icon-' . $this->size . '.png', 'tmp_name' => download_url($grab_url, 5)); if (is_wp_error($file_info['tmp_name'])) { return; } $id = media_handle_sideload($file_info, 0); if (!is_wp_error($id)) { $this->attachment_id = $id; } }
/** * An enhanced version of WP's media_sideload_image function. * * If media_sideload_image fails, the file is downloaded manually * as an image, inserted as an attachment, and attached to the post. * * @since 3.5.1 */ function wprss_media_sideload_image($file, $post_id, $desc = null) { try { if (!empty($file)) { // Download file to temp location $tmp = download_url($file); // Set variables for storage // fix file filename for query strings preg_match('/[^\\?]+\\.(jpe?g|jpe|gif|png)\\b/i', $file, $matches); if (count($matches) > 0) { $file_array['name'] = basename($matches[0]); } else { preg_match('/[\\/\\?\\=\\&]([^\\/\\?\\=\\&]*)[\\?]*$/i', $file, $matches2); if (count($matches2) > 1) { $file_array['name'] = $matches2[1] . '.png'; } else { @unlink($tmp); return "<img src='{$file}' alt='' />"; } } $file_array['tmp_name'] = $tmp; // If error storing temporarily, unlink if (is_wp_error($tmp)) { @unlink($file_array['tmp_name']); $file_array['tmp_name'] = ''; } // do the validation and storage stuff $id = media_handle_sideload($file_array, $post_id, $desc); // If error storing permanently, unlink if (is_wp_error($id)) { @unlink($file_array['tmp_name']); return "<img src='{$file}' alt='' />"; } $src = wp_get_attachment_url($id); } // Finally check to make sure the file has been saved, then return the html if (!empty($src)) { $alt = isset($desc) ? esc_attr($desc) : ''; $html = "<img src='{$src}' alt='{$alt}' />"; return $html; } } catch (Exception $e) { return "<img src='{$file}' alt='' />"; } }
public function upload($url) { $tmp = download_url($url); $file_array = ['name' => basename($url), 'tmp_name' => $tmp]; // Check for download errors if (is_wp_error($tmp)) { @unlink($file_array['tmp_name']); return false; } $id = media_handle_sideload($file_array, 0); // Check for handle sideload errors. if (is_wp_error($id)) { @unlink($file_array['tmp_name']); return false; } $attachment_url = wp_get_attachment_url($id); return $attachment_url; // Do whatever you have to here }
function flickr_image_attach($flickrurl, $post_id) { preg_match('/http\\:\\/\\/www\\.flickr\\.com\\/photos\\/(.*?)\\/([0-9]+)\\//si', $flickrurl, $m); if ($m) { $flickruser = $m[1]; $photo_id = $m[2]; } else { return; } //$flickruser = getFlickrUser($photo_id); $file = getFlickrURL($photo_id); if (!empty($file)) { // Download file to temp location $tmp = download_url($file); // Set variables for storage // fix file filename for query strings preg_match('/[^\\?]+\\.(jpe?g|jpe|gif|png)\\b/i', $file, $matches); $file_array['name'] = basename($matches[0]); $file_array['tmp_name'] = $tmp; // If error storing temporarily, unlink if (is_wp_error($tmp)) { @unlink($file_array['tmp_name']); $file_array['tmp_name'] = ''; } // do the validation and storage stuff $id = media_handle_sideload($file_array, $post_id, $desc = null); // If error storing permanently, unlink if (is_wp_error($id)) { @unlink($file_array['tmp_name']); return $id; } $src = wp_get_attachment_url($id); } if (!empty($src)) { update_post_meta($post_id, 'image_url_value', $flickrurl); update_post_meta($post_id, 'image_author_t_value', $flickruser); update_post_meta($post_id, 'image_value', $src); set_post_thumbnail($post_id, $id); return update_post_meta($post_id, 'Thumbnail', $src); } else { return false; } }
public function attachFileToPost($file, $post_id, $desc = null) { if (empty($file)) { return null; } // Set variables for storage // fix file filename for query strings $file_array['name'] = basename($file); $file_array['tmp_name'] = $file; // do the validation and storage stuff $id = media_handle_sideload($file_array, $post_id, $desc); // If error storing permanently, show if (is_wp_error($id)) { echo '<hr /><hr /><hr /><hr /><pre>'; var_dump($id); exit; } return $id; }
private function sideload_attachment($attachment, $_to_post_id, $date) { if ('image' === $attachment->type) { $response = wp_remote_head($attachment->url); if (200 == wp_remote_retrieve_response_code($response)) { $_mimes = array_flip(wp_get_mime_types()); $_content_type = wp_remote_retrieve_header($response, 'content-type'); if (isset($_mimes[$_content_type])) { $_ext = strtok($_mimes[$_content_type], '|'); $_temp_file = download_url($attachment->url); // TODO check for WP_Error $_new_file = str_replace('.tmp', '.' . $_ext, $_temp_file); rename($_temp_file, $_new_file); $file_array = array(); $file_array['name'] = basename($_new_file); $file_array['tmp_name'] = $_new_file; $attachment_id = media_handle_sideload($file_array, $_to_post_id, '', array('post_date' => $date, 'post_date_gmt' => $date)); } } } }
/** * Downloads an external image and optionally attaches it to a post. * * Contains most of core's media_sideload_image() but returns an attachment ID instead of HTML. * * Note: this function does not validate the domain that the image is coming from. Please make sure * to validate this before downloading the image. Should only pull down images from trusted sources. * * Note: This function does not support GET params because these will not work on WPCOM production servers see r157060 * * @param string $image_url URL of the image. * @param int $post_ID ID of the post it should be attached to. * @return $thumbnail_id id of the thumbnail attachment post id */ function wpcom_vip_download_image($image_url, $post_id = 0, $description = '') { if (isset($_SERVER['REQUEST_METHOD']) && strtoupper($_SERVER['REQUEST_METHOD']) == 'GET') { return new WP_Error('invalid-request-method', 'Media sideloading is not supported via GET. Use POST.'); } if (!is_admin()) { return new WP_Error('not-in-admin', 'Media sideloading can only be done in when `true === is_admin()`.'); } if ($post_id < 0) { return new WP_Error('invalid-post-id', 'Please specify a valid post ID.'); } if (!filter_var($image_url, FILTER_VALIDATE_URL)) { return new WP_Error('not-a-url', 'Please specify a valid URL.'); } $image_url_path = parse_url($image_url, PHP_URL_PATH); $image_path_info = pathinfo($image_url_path); if (!in_array(strtolower($image_path_info['extension']), array('jpg', 'jpe', 'jpeg', 'gif', 'png'))) { return new WP_Error('not-an-image', 'Specified URL does not have a valid image extension.'); } // Download file to temp location; short timeout, because we don't have all day. $downloaded_url = download_url($image_url, 30); // We couldn't download and store to a temporary location, so bail. if (is_wp_error($downloaded_url)) { return $downloaded_url; } $file_array['name'] = $image_path_info['basename']; $file_array['tmp_name'] = $downloaded_url; if (empty($description)) { $description = $image_path_info['filename']; } // Now, let's sideload it. $attachment_id = media_handle_sideload($file_array, $post_id, $description); // If error storing permanently, unlink and return the error if (is_wp_error($attachment_id)) { @unlink($file_array['tmp_name']); // unlink can throw errors if the file isn't there return $attachment_id; } return $attachment_id; }
/** * Download an image from the specified URL and attach it to a post. * * @since 1.0 * * @param string $post The serialize of post */ function kt_download_media($id, $post_title, $guid) { global $posts_id; $new_id = kt_get_post_id($id, 'attachment', 'kt_demo_attachment'); if (!$new_id) { require_once ABSPATH . 'wp-admin/includes/media.php'; require_once ABSPATH . 'wp-admin/includes/file.php'; require_once ABSPATH . 'wp-admin/includes/image.php'; require_once ABSPATH . 'wp-includes/pluggable.php'; // Set variables for storage, fix file filename for query strings. preg_match('/[^\\?]+\\.(jpe?g|jpe|gif|png)\\b/i', $guid, $matches); $file_array = array(); $file_array['name'] = basename($matches[0]); // Download file to temp location. $file_array['tmp_name'] = download_url($guid); // If error storing temporarily, return the error. if (is_wp_error($file_array['tmp_name'])) { @unlink($file_array['tmp_name']); echo 'is_wp_error $file_array: ' . $guid; print_r($file_array['tmp_name']); return $file_array['tmp_name']; } // Do the validation and storage stuff. $new_id = media_handle_sideload($file_array, '', $post_title); //$id of attachement or wp_error // If error storing permanently, unlink. if (is_wp_error($new_id)) { @unlink($file_array['tmp_name']); echo 'is_wp_error $id: ' . $new_id->get_error_messages() . ' ' . $guid; return $new_id; } if (isset($posts_id['attachment']['kt_demo_attachment'])) { $posts_id['attachment']['kt_demo_attachment'][$id] = $new_id; } update_post_meta($new_id, 'kt_demo_attachment', $id); return $new_id; } return $new_id; }
function download_import_file($file) { $url = "http://quanticalabs.com/wptest/medicenter/files/2013/04/" . $file["name"] . "." . $file["extension"]; $attachment = get_page_by_title($file["name"], "OBJECT", "attachment"); if ($attachment != null) { $id = $attachment->ID; } else { $tmp = download_url($url); $file_array = array('name' => basename($url), 'tmp_name' => $tmp); // Check for download errors if (is_wp_error($tmp)) { @unlink($file_array['tmp_name']); return $tmp; } $id = media_handle_sideload($file_array, 0); // Check for handle sideload errors. if (is_wp_error($id)) { @unlink($file_array['tmp_name']); return $id; } } return get_attached_file($id); }
function compare_import_image($image_url, $product_id) { if (!empty($image_url)) { $basename = basename($image_url); $image_id = compare_if_image_exists($basename); if (!$image_id) { $tmp = download_url((string) $image_url); compare_display_import_info(__('Downloading image: ', 'compare') . $basename); $file_array = array(); preg_match('/[^\\?]+\\.(jpg|jpe|jpeg|gif|png)/i', $image_url, $matches); $file_array['name'] = basename($matches[0]); $file_array['tmp_name'] = $tmp; // If error storing temporarily, unlink if (is_wp_error($tmp)) { @unlink($file_array['tmp_name']); compare_display_import_info($tmp->get_error_message()); $file_array['tmp_name'] = ''; $image_id = ''; } // do the validation and storage stuff $id = media_handle_sideload($file_array, 0); // If error storing permanently, unlink if (is_wp_error($id)) { compare_display_import_info($id->get_error_message()); @unlink($file_array['tmp_name']); $image_id = ''; } $image_id = $id; } else { compare_display_import_info(__('Image ', 'compare') . $basename . __(' exists, skipping import and using existing one.', 'compare')); } if (!empty($image_id)) { set_post_thumbnail($product_id, $image_id); } } }
public function integrateMediaToWordpress($temporyFile, $fileExtension) { $file_array = []; // Extract folder & filename $tabUrl = explode('/', $temporyFile); $filename = $tabUrl[count($tabUrl) - 1]; $file_array['name'] = $filename . $fileExtension; $file_array['tmp_name'] = $temporyFile . $fileExtension; // Do the validation and storage stuff. $id = media_handle_sideload($file_array, 0); $data = 'ERROR DOWNLOAD FOR ' . print_r($id, true) . ' | url: ' . $temporyFile . print_r($file_array, true); // @todo throw if (gettype($id) != 'integer') { throw new fileDownloadException($data, 1); } $src = wp_get_attachment_url($id); // @todo throw if (gettype($src) != 'string') { throw new fileDownloadException('ERROR DOWNLOAD FOR ' . $src . ' | url: ' . $temporyFile, 1); return $src; } else { return $src; } }
private function update_featured_image($url, $post_id) { if (trim((string) $url) != '' && !has_post_thumbnail($post_id)) { $tmp = download_url((string) $url); $file_array = array(); // Set variables for storage // fix file filename for query strings preg_match('/[^\\?]+\\.(jpg|jpe|jpeg|gif|png)/i', (string) $url, $matches); $file_array['name'] = basename($matches[0]); $file_array['tmp_name'] = $tmp; // If error storing temporarily, unlink if (is_wp_error($tmp)) { @unlink($file_array['tmp_name']); $file_array['tmp_name'] = ''; } // do the validation and storage stuff $attachment_id = media_handle_sideload($file_array, $post_id); if (is_wp_error($attachment_id)) { array_push($error_messages, "We were unable to add the image specified to the unit."); } else { set_post_thumbnail($post_id, $attachment_id); } } }
private function handle_upload() { if (current_user_can('upload_files')) { if (!wp_verify_nonce($_POST['lh_add_media_from_url-nonce'], "lh_add_media_from_url-file_url")) { return new WP_Error('lh_add_media_from_url', 'Could not verify request nonce'); } $upload_url = esc_url(sanitize_text_field($_POST['lh_add_media_from_url-file_url'])); // build up array like PHP file upload $file = array(); $file['name'] = basename($this->reconstruct_url($upload_url)); $file['tmp_name'] = download_url($upload_url); if (is_wp_error($file['tmp_name'])) { @unlink($file['tmp_name']); return new WP_Error('lh_add_media_from_url', 'Could not download file from remote source'); } if (!is_wp_error($file['tmp_name'])) { $attachmentId = media_handle_sideload($file); // create the thumbnails $attach_data = wp_generate_attachment_metadata($attachmentId, get_attached_file($attachmentId)); wp_update_attachment_metadata($attachmentId, $attach_data); return $attachmentId; } } }
function insta_import_image($image_url, $post_id) { // Set variables for storage, fix file filename for query strings. preg_match('/[^\\?]+\\.(jpe?g|jpe|gif|png)\\b/i', $image_url, $matches); if (!$matches) { return new WP_Error('image_sideload_failed', __('Invalid image URL')); } $file_array = array(); $file_array['name'] = basename($matches[0]); // Download file to temp location. $file_array['tmp_name'] = download_url($image_url); // If error storing temporarily, return the error. if (is_wp_error($file_array['tmp_name'])) { return $file_array['tmp_name']; } // Do the validation and storage stuff. $id = media_handle_sideload($file_array, $post_id); // If error storing permanently, unlink. if (is_wp_error($id)) { @unlink($file_array['tmp_name']); return $id; } return set_post_thumbnail($post_id, $id); }
/** * Extract url and load into WP using media_handle_sideload() * Will return an empty string if something went wrong. * * @param string $url * * @see media_handle_sideload * * @return string $src * @throws \Exception */ 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; }
/** * Download an image from the specified URL and attach it to a post. * * @since 2.6.0 * * @param string $file The URL of the image to download * @param int $post_id The post ID the media is to be associated with * @param string $desc Optional. Description of the image * @return string|WP_Error Populated HTML img tag on success */ function media_sideload_image($file, $post_id, $desc = null) { if (!empty($file)) { // Set variables for storage, fix file filename for query strings. preg_match('/[^\\?]+\\.(jpe?g|jpe|gif|png)\\b/i', $file, $matches); $file_array = array(); $file_array['name'] = basename($matches[0]); // Download file to temp location. $file_array['tmp_name'] = download_url($file); // If error storing temporarily, return the error. if (is_wp_error($file_array['tmp_name'])) { return $file_array['tmp_name']; } // Do the validation and storage stuff. $id = media_handle_sideload($file_array, $post_id, $desc); // If error storing permanently, unlink. if (is_wp_error($id)) { @unlink($file_array['tmp_name']); return $id; } $src = wp_get_attachment_url($id); } // Finally check to make sure the file has been saved, then return the HTML. if (!empty($src)) { $alt = isset($desc) ? esc_attr($desc) : ''; $html = "<img src='{$src}' alt='{$alt}' />"; return $html; } }
/** * Handle uploading of the files * * @since 0.4 * * @uses media_handle_sideload * * @param int $post_id Parent post id * @return array Combined result of media ids and errors if any */ function _upload_files($post_id = 0) { $media_ids = $errors = array(); // Bail if there are no files if (empty($_FILES)) { return false; } // File field name could be user defined, so we just get the first file $files = current($_FILES); // There can be multiple files // So we need to iterate over each of the files to process for ($i = 0; $i < count($files['name']); $i++) { $fields = array('name', 'type', 'tmp_name', 'error', 'size'); foreach ($fields as $field) { $k[$field] = $files[$field][$i]; } $k['name'] = sanitize_file_name($k['name']); // Skip to the next file if upload went wrong if ($k['tmp_name'] == "") { continue; } $typecheck = wp_check_filetype_and_ext($k['tmp_name'], $k['name'], false); // Add an error message if MIME-type is not allowed if (!in_array($typecheck['type'], (array) $this->allowed_mime_types)) { $errors['fu-disallowed-mime-type'][] = array('name' => $k['name'], 'mime' => $k['type']); continue; } // Setup some default values // However, you can make additional changes on 'fu_after_upload' action $caption = ''; // Try to set post caption if the field is set on request // Fallback to post_content if the field is not set if (isset($_POST['caption'])) { $caption = sanitize_text_field($_POST['caption']); } elseif (isset($_POST['post_content'])) { $caption = sanitize_text_field($_POST['post_content']); } // TODO: remove or refactor $filename = !empty($this->settings['default_file_name']) ? $this->settings['default_file_name'] : pathinfo($k['name'], PATHINFO_FILENAME); $post_overrides = array('post_status' => $this->_is_public() ? 'publish' : 'private', 'post_title' => isset($_POST['post_title']) && !empty($_POST['post_title']) ? sanitize_text_field($_POST['post_title']) : sanitize_text_field($filename), 'post_content' => empty($caption) ? __('Unnamed', 'frontend-uploader') : $caption, 'post_excerpt' => empty($caption) ? __('Unnamed', 'frontend-uploader') : $caption); // Trying to upload the file $upload_id = media_handle_sideload($k, (int) $post_id, $post_overrides['post_title'], $post_overrides); if (!is_wp_error($upload_id)) { $media_ids[] = $upload_id; } else { $errors['fu-error-media'][] = $k['name']; } } /** * $success determines the rest of upload flow * Setting this to true if no errors were produced even if there's was no files to upload */ $success = empty($errors) ? true : false; if ($success) { foreach ($media_ids as $media_id) { $this->_save_post_meta_fields($media_id); } } // Allow additional setup // Pass array of attachment ids do_action('fu_after_upload', $media_ids, $success, $post_id); return array('success' => $success, 'media_ids' => $media_ids, 'errors' => $errors); }
/** * Attach a given image to a chart post * * @param int the WP post ID of the post being saved * @param string a base64 encoded string of the image we want to attach */ public function attach_image() { if (!is_numeric($_POST['post_ID'])) { return; } $post_id = absint($_POST['post_ID']); if (!current_user_can('edit_post', $post_id)) { return false; } if (!($post = get_post($post_id))) { return false; } if ('' == $_POST[m_chart()->slug]['img']) { return false; } // Decode the image so we can save it $decoded_img = base64_decode(str_replace('data:image/png;base64,', '', $_POST[m_chart()->slug]['img'])); if ('' == $decoded_img) { return false; } // Check for an existing attached image $attachments = get_posts(array('post_type' => 'attachment', 'posts_per_page' => 1, 'post_parent' => $post->ID, 'meta_key' => m_chart()->slug . '-image')); // If an existing image was found delete it foreach ($attachments as $attachment) { wp_delete_attachment($attachment->ID, true); } // Upload image to WP $file = wp_upload_bits(sanitize_title($post->post_title . '-' . $post->ID) . '.png', null, $decoded_img); // START acting like media_sideload_image preg_match('/[^\\?]+\\.(jpe?g|jpe|gif|png)\\b/i', $file['file'], $matches); $file_array['name'] = basename($matches[0]); $file_array['tmp_name'] = $file['file']; if (is_wp_error($file)) { @unlink($file_array['tmp_name']); $file_array['tmp_name'] = ''; } $img_id = media_handle_sideload($file_array, $post->ID, $post->post_title); if (is_wp_error($img_id)) { @unlink($file_array['tmp_name']); return $img_id; } // STOP acting like media_sideload_image // Set some meta on the attachment so we know it came from m-chart add_post_meta($img_id, m_chart()->slug . '-image', $post->ID); // Set the attachment as the chart's thumbnail update_post_meta($post->ID, '_thumbnail_id', $img_id); }