/** * media_sideload_image, but returns ID * @param string $image_url [description] * @param boolean $post_id [description] * @return [type] [description] */ function custom_media_sideload_image($image_url = '', $post_id = false) { require_once ABSPATH . 'wp-admin/includes/file.php'; $tmp = download_url($image_url); // Set variables for storage // fix file filename for query strings preg_match('/[^\\?]+\\.(jpe?g|jpe|gif|png)\\b/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']); $file_array['tmp_name'] = ''; } $time = current_time('mysql'); $file = wp_handle_sideload($file_array, array('test_form' => false), $time); if (isset($file['error'])) { return new WP_Error('upload_error', $file['error']); } $url = $file['url']; $type = $file['type']; $file = $file['file']; $title = preg_replace('/\\.[^.]+$/', '', basename($file)); $parent = (int) absint($post_id) > 0 ? absint($post_id) : 0; $attachment = array('post_mime_type' => $type, 'guid' => $url, 'post_parent' => $parent, 'post_title' => $title, 'post_content' => ''); $id = wp_insert_attachment($attachment, $file, $parent); if (!is_wp_error($id)) { require_once ABSPATH . 'wp-admin/includes/image.php'; $data = wp_generate_attachment_metadata($id, $file); wp_update_attachment_metadata($id, $data); } return $id; }
/** * Process downloaded image * * @param string $tmp_file * @param int|bool $media_author * @param string $media_date * * @return bool */ private function _process_downloaded_image($tmp_file, $media_author, $media_date) { if ('image/jpeg' !== ($mime = mime_content_type($tmp_file))) { WP_CLI::warning('Invalid image type.'); return false; } $info = pathinfo($tmp_file); $name = isset($info['filename']) ? $info['filename'] : 'unsplash'; $file_array = array('name' => $name . '.jpeg', 'type' => $mime, 'tmp_name' => $tmp_file, 'error' => 0, 'size' => filesize($tmp_file)); if ('random' === $media_date) { $timestamp = current_time('timestamp') - mt_rand(0, 315576000); // In last 10 years $media_date = gmdate('Y-m-d H:i:s', $timestamp); } $file = wp_handle_sideload($file_array, array('test_form' => false), $media_date); if (isset($file['error'])) { WP_CLI::warning('Error uploading file.'); return false; } $attachment = array('post_mime_type' => $file['type'], 'guid' => $file['url'], 'post_title' => $name, 'post_author' => $media_author, 'post_date' => $media_date); // Save the attachment metadata $id = wp_insert_attachment($attachment, $file['file']); if (is_wp_error($id)) { WP_CLI::warning('Error creating attachment.'); return false; } wp_update_attachment_metadata($id, wp_generate_attachment_metadata($id, $file['file'])); }
function upload_base64($encode, $filename, $coord, $e) { $upload_dir = wp_upload_dir(); $upload_path = str_replace('/', DIRECTORY_SEPARATOR, $upload_dir['path']) . DIRECTORY_SEPARATOR; $decoded = base64_decode($encode); $hashed_filename = md5($filename . microtime()) . '_' . $filename; header('Content-Type: image/png'); //header png data sistem $img = imagecreatefromstring($decoded); //imagen string list($w, $h) = getimagesizefromstring($decoded); //obtenemos el tamaño real de la imagen $w_m = 800; // estandar $h_m = 600; // estandar $wm = $h * ($w_m / $h_m); //calculo para obtener el width general $hm = $w * ($h_m / $w_m); // calculo para obtener el height general $i = imagecreatetruecolor($w_m, $h_m); // aplicamos el rectangulo 800x600 imagealphablending($i, FALSE); // obtenemos las transparencias imagesavealpha($i, TRUE); // se guarda las transparencias imagecopyresampled($i, $img, 0, 0, $coord->x, $coord->y - 27, $wm, $hm, $wm, $hm); // corta la imagen imagepng($i, $upload_path . $hashed_filename); imagedestroy($img); // file_put_contents($upload_path . $hashed_filename, $decoded ); if (!function_exists('wp_handle_sideload')) { require_once ABSPATH . 'wp-admin/includes/file.php'; } if (!function_exists('wp_get_current_user')) { require_once ABSPATH . 'wp-includes/pluggable.php'; } if (!function_exists("wp_generate_attachment_metadata")) { require_once ABSPATH . 'wp-admin/includes/image.php'; } if (!function_exists("wp_get_image_editor")) { require_once ABSPATH . 'wp-includes/media.php'; } $file = array(); $file['error'] = ''; $file['tmp_name'] = $upload_path . $hashed_filename; $file['name'] = $hashed_filename; $file['type'] = 'image/png'; $file['size'] = filesize($upload_path . $hashed_filename); $file_ = wp_handle_sideload($file, array('test_form' => false)); $attachment = array('post_mime_type' => $file_['type'], 'post_title' => basename($filename), 'post_content' => '', 'post_status' => 'inherit'); $attach_id = wp_insert_attachment($attachment, $file_['file']); $attach_data = wp_generate_attachment_metadata($attach_id, $file_['file']); wp_update_attachment_metadata($attach_id, $attach_data); // $edit = wp_get_image_editor( $upload_path . $hashed_filename); // print_r($edit); return $attach_id; }
/** * Downloads an image from the specified URL. * * Mostly based from media_sideload_image() * and media_handle_sideload(). * * @todo See if commented code is needed for each type and remove. * * @access protected * * @return string $url URL of the downloaded image. */ protected function sideload_image() { // Load file used for image retrieving require_once ABSPATH . 'wp-admin/includes/file.php'; $file = $this->current_map_remote_image_url; // Set variables for storage, fix file filename for query strings preg_match('/[^\\?]+\\.(jpe?g|jpe|gif|png)\\b/i', $file, $matches); if (!$matches) { // Invalid image URL //return; } $file_array = array(); //$file_array['name'] = basename( $matches[0] ); $file_array['name'] = basename($this->current_map_type . $this->current_map_image_extension); // Download file to temp location $file_array['tmp_name'] = download_url($file); // Check there is an error storing temporarily file if (is_wp_error($file_array['tmp_name'])) { return; } // Set values that override default settings $overrides = array('test_form' => false, 'unique_filename_callback' => array($this, 'filename_callback')); // Register filter that modifies uploads directory add_filter('upload_dir', array($this, 'change_upload_dir')); $local = wp_handle_sideload($file_array, $overrides, $this->time); // Deregister filter that modifies uploads directory remove_filter('upload_dir', array($this, 'change_upload_dir')); // Check if URL is set if (isset($local['error']) || !isset($local['url'])) { return; } else { return $local['url']; } }
/** * Handle an upload via raw POST data * * @param array $_files Data from $_FILES. Unused. * @param array $_headers HTTP headers from the request * @return array|WP_Error Data from {@see wp_handle_sideload()} */ protected function upload_from_data($_files, $_headers) { $data = $this->server->get_raw_data(); if (empty($data)) { json_error(BigAppErr::$post['code'], BigAppErr::$post['msg'], ""); } if (empty($_headers['CONTENT_TYPE'])) { json_error(BigAppErr::$post['code'], BigAppErr::$post['msg'], ""); } if (empty($_headers['CONTENT_DISPOSITION'])) { json_error(BigAppErr::$post['code'], BigAppErr::$post['msg'], ""); } // Get the filename $disposition_parts = explode(';', $_headers['CONTENT_DISPOSITION']); $filename = null; foreach ($disposition_parts as $part) { $part = trim($part); if (strpos($part, 'filename') !== 0) { continue; } $filenameparts = explode('=', $part); $filename = trim($filenameparts[1]); } if (empty($filename)) { json_error(BigAppErr::$post['code'], BigAppErr::$post['msg'], ""); } if (!empty($_headers['CONTENT_MD5'])) { $expected = trim($_headers['CONTENT_MD5']); $actual = md5($data); if ($expected !== $actual) { json_error(BigAppErr::$post['code'], BigAppErr::$post['msg'], ""); } } // Get the content-type $type = $_headers['CONTENT_TYPE']; // Save the file $tmpfname = wp_tempnam($filename); $fp = fopen($tmpfname, 'w+'); if (!$fp) { json_error(BigAppErr::$post['code'], BigAppErr::$post['msg'], ""); } fwrite($fp, $data); fclose($fp); // Now, sideload it in $file_data = array('error' => null, 'tmp_name' => $tmpfname, 'name' => $filename, 'type' => $type); $overrides = array('test_form' => false); $sideloaded = wp_handle_sideload($file_data, $overrides); if (isset($sideloaded['error'])) { @unlink($tmpfname); json_error(BigAppErr::$post['code'], BigAppErr::$post['msg'], ""); } return $sideloaded; }
/** * {@internal Missing Short Description}} * * @since unknown * * @param unknown_type $file_array * @param unknown_type $post_id * @param unknown_type $desc * @param unknown_type $post_data * @return unknown */ function media_handle_sideload($file_array, $post_id, $desc = null, $post_data = array()) { $overrides = array('test_form' => false); $file = wp_handle_sideload($file_array, $overrides); if (isset($file['error'])) { return new WP_Error('upload_error', $file['error']); } $url = $file['url']; $type = $file['type']; $file = $file['file']; $title = preg_replace('/\\.[^.]+$/', '', basename($file)); $content = ''; // use image exif/iptc data for title and caption defaults if possible if ($image_meta = @wp_read_image_metadata($file)) { if (trim($image_meta['title'])) { $title = $image_meta['title']; } if (trim($image_meta['caption'])) { $content = $image_meta['caption']; } } $title = @$desc; // Construct the attachment array $attachment = array_merge(array('post_mime_type' => $type, 'guid' => $url, 'post_parent' => $post_id, 'post_title' => $title, 'post_content' => $content), $post_data); // Save the data $id = wp_insert_attachment($attachment, $file, $post_id); if (!is_wp_error($id)) { wp_update_attachment_metadata($id, wp_generate_attachment_metadata($id, $file)); return $url; } return $id; }
function fusion_import_to_media_library($url, $theme_option = '') { // gives us access to the download_url() and wp_handle_sideload() functions require_once ABSPATH . 'wp-admin/includes/file.php'; $timeout_seconds = 30; // download file to temp dir $temp_file = download_url($url, $timeout_seconds); if (!is_wp_error($temp_file)) { // array based on $_FILE as seen in PHP file uploads $file = array('name' => basename($url), 'type' => 'image/png', 'tmp_name' => $temp_file, 'error' => 0, 'size' => filesize($temp_file)); $overrides = array('test_form' => false, 'test_size' => true, 'test_upload' => true); // move the temporary file into the uploads directory $results = wp_handle_sideload($file, $overrides); if (!empty($results['error'])) { return false; } else { $attachment = array('guid' => $results['url'], 'post_mime_type' => $results['type'], 'post_title' => preg_replace('/\\.[^.]+$/', '', basename($results['file'])), 'post_content' => '', 'post_status' => 'inherit'); // Insert the attachment. $attach_id = wp_insert_attachment($attachment, $results['file']); // Make sure that this file is included, as wp_generate_attachment_metadata() depends on it. require_once ABSPATH . 'wp-admin/includes/image.php'; // Generate the metadata for the attachment, and update the database record. $attach_data = wp_generate_attachment_metadata($attach_id, $results['file']); wp_update_attachment_metadata($attach_id, $attach_data); if ($theme_option) { Avada()->settings->set($theme_option, $results['url']); } return $attach_id; } } else { return false; } }
function get_yacht_image($file) { 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. require_once ABSPATH . 'wp-admin/includes/file.php'; write_log('Start Downloading: ' . $file . '...'); $file_array['tmp_name'] = download_url($file, 600); write_log('Completed Downloading: ' . $file . '...' . memory_get_usage()); // If error storing temporarily, return the error. if (is_wp_error($file_array['tmp_name'])) { return $file_array['tmp_name']; } $overrides = array('test_form' => false); $time = current_time('mysql'); $file = wp_handle_sideload($file_array, $overrides, $time); if (isset($file['error'])) { return new WP_Error('upload_error', $file['error']); } $image = wp_get_image_editor($file['file']); // Return an implementation that extends WP_Image_Editor if (!is_wp_error($image)) { $image->resize(640, 465, true); $tmp = explode('/', $file['file']); $file_name = end($tmp); $resized_path = str_replace($file_name, '640x465_' . $file_name, $file['file']); $resized = $image->save($resized_path); if (!is_wp_error($resized)) { return str_replace($file_name, '640x465_' . $file_name, $file['url']); } else { return new WP_Error('image_resize_error', $resized); } } else { return new WP_Error('image_editor_load_error', $image); } } }
/** * Handle an upload via raw POST data * * @param array $data Supplied file data * @param array $headers HTTP headers from the request * @return array|WP_Error Data from {@see wp_handle_sideload()} */ protected function upload_from_data($data, $headers) { if (empty($data)) { return new WP_Error('rest_upload_no_data', __('No data supplied'), array('status' => 400)); } if (empty($headers['content_type'])) { return new WP_Error('rest_upload_no_content_type', __('No Content-Type supplied'), array('status' => 400)); } if (empty($headers['content_disposition'])) { return new WP_Error('rest_upload_no_content_disposition', __('No Content-Disposition supplied'), array('status' => 400)); } // Get the filename $filename = null; foreach ($headers['content_disposition'] as $part) { $part = trim($part); if (strpos($part, 'filename') !== 0) { continue; } $filenameparts = explode('=', $part); $filename = trim($filenameparts[1]); } if (empty($filename)) { return new WP_Error('rest_upload_invalid_disposition', __('Invalid Content-Disposition supplied. Content-Disposition needs to be formatted as "filename=image.png" or similar.'), array('status' => 400)); } if (!empty($headers['content_md5'])) { $content_md5 = array_shift($headers['content_md5']); $expected = trim($content_md5); $actual = md5($data); if ($expected !== $actual) { return new WP_Error('rest_upload_hash_mismatch', __('Content hash did not match expected'), array('status' => 412)); } } // Get the content-type $type = array_shift($headers['content_type']); /** Include admin functions to get access to wp_tempnam() and wp_handle_sideload() */ require_once ABSPATH . 'wp-admin/includes/admin.php'; // Save the file $tmpfname = wp_tempnam($filename); $fp = fopen($tmpfname, 'w+'); if (!$fp) { return new WP_Error('rest_upload_file_error', __('Could not open file handle'), array('status' => 500)); } fwrite($fp, $data); fclose($fp); // Now, sideload it in $file_data = array('error' => null, 'tmp_name' => $tmpfname, 'name' => $filename, 'type' => $type); $overrides = array('test_form' => false); $sideloaded = wp_handle_sideload($file_data, $overrides); if (isset($sideloaded['error'])) { // @codingStandardsIgnoreStart @unlink($tmpfname); // @codingStandardsIgnoreEnd return new WP_Error('rest_upload_sideload_error', $sideloaded['error'], array('status' => 500)); } return $sideloaded; }
function image_handle_upload($url, $post_id, $post_data = array(), $overrides = array('test_form' => false)) { $time = current_time('mysql'); if ($post = get_post($post_id)) { if (substr($post->post_date, 0, 4) > 0) { $time = $post->post_date; } } if (isset($post_id) && $post_id > 0) { $currentImages = array(); $currentImages = $this->getProductImages($post_id); $img = basename($url); foreach ($currentImages as $imageRec) { if (basename($imageRec->guid) == $img) { //img already exists, assume this is update and delete the other one first wp_delete_attachment($imageRec->ID, 1); } } } $file = $this->isGood($this->filesUploaded[$url]) ? $this->filesUploaded[$url] : wp_handle_sideload($this->getFile($url), array('test_form' => false, 'test_upload' => false), $time); $this->filesUploaded[$url] = array_merge($this->filesUploaded[$url], $file); $name = $this->filesUploaded[$url]['name']; if (isset($file['error'])) { return new WP_Error('upload_error', $file['error']); } $name_parts = pathinfo($name); $name = trim(substr($name, 0, -(1 + strlen($name_parts['extension'])))); $url = $file['url']; $type = $file['type']; $file = $file['file']; $title = $name; $content = ''; // use image exif/iptc data for title and caption defaults if possible if ($image_meta = @wp_read_image_metadata($file)) { if (trim($image_meta['title']) && !is_numeric(sanitize_title($image_meta['title']))) { $title = $image_meta['title']; } if (trim($image_meta['caption'])) { $content = $image_meta['caption']; } } // Construct the attachment array $attachment = array_merge(array('post_mime_type' => $type, 'guid' => $url, 'post_parent' => $post_id, 'post_title' => $title, 'post_content' => $content), $post_data); // Save the data $id = wp_insert_attachment($attachment, $file, $post_id); if (!is_wp_error($id)) { wp_update_attachment_metadata($id, wp_generate_attachment_metadata($id, $file)); } return $id; }
/** * Fetches the map of the talent's location from Google Maps * and sets it as the post thumbnail. * * It also replaces all intermediate image sizes with * the file from Google Maps, as they are from better quality * and way smaller than the generated ones. * * @param int $post_id The ID of the current post. */ public function add_map_on_save_post($post_id) { // If this is just a revision or the post already has a thumbnail, don't proceed if (wp_is_post_revision($post_id) || has_post_thumbnail($post_id)) { return; } if (!in_array(get_post_type($post_id), array_keys($this->types))) { return; } // Get the talent's location data $location = Helper::get_talent_meta(get_post($post_id), 'location'); if (empty($location['name'])) { return; } $map_retina = sprintf('https://maps.googleapis.com/maps/api/staticmap?center=%s&scale=2&zoom=6&size=600x320&maptype=roadmap', urlencode($location['name'])); $tmp_retina = download_url($map_retina); $slug = get_post($post_id)->post_name; if ('' === $slug) { $slug = sanitize_title(get_the_title($post_id)); } // Set variables for storage $file_array = array('name' => $slug . '-map.png', 'tmp_name' => $tmp_retina); // If error storing temporarily, unlink if (is_wp_error($tmp_retina)) { return; } // do the validation and storage stuff $attachment_id = media_handle_sideload($file_array, $post_id, $location['name']); // If error storing permanently, unlink if (is_wp_error($attachment_id)) { unlink($file_array['tmp_name']); return; } // Set map as post thumbnail set_post_thumbnail($post_id, $attachment_id); // Add Normal image as image size of the attachment $metadata = wp_get_attachment_metadata($attachment_id); $attachment_path = get_attached_file($attachment_id); $attachment_file = basename($attachment_path); foreach ($this->get_image_sizes() as $size => $values) { $map = sprintf('https://maps.googleapis.com/maps/api/staticmap?center=%s&scale=1&zoom=6&size=%s&maptype=roadmap', urlencode($location['name']), $values['width'] . 'x' . $values['height']); $tmp = download_url($map); // Set variables for storage $file_array = array('name' => $metadata['sizes'][$size]['file'], 'tmp_name' => $tmp); // If error storing temporarily, unlink if (is_wp_error($tmp)) { unlink($file_array['tmp_name']); continue; } unlink(str_replace($attachment_file, $metadata['sizes'][$size]['file'], $attachment_path)); $post = get_post($post_id); $time = $post->post_date; $file = wp_handle_sideload($file_array, array('test_form' => false), $time); if (isset($file['error'])) { unlink($file_array['tmp_name']); } } }
function uncode_add_default_image_with_activation() { $default_back_media = get_page_by_title('uncode-default-back', OBJECT, 'attachment'); if (!isset($default_back_media)) { // gives us access to the download_url() and wp_handle_sideload() functions require_once ABSPATH . 'wp-admin/includes/file.php'; // URL to the WordPress logo $url = 'http://static.undsgn.com/uncode/dummy_placeholders/uncode-default-back.jpeg'; $timeout_seconds = 5; // download file to temp dir $temp_file = download_url($url, $timeout_seconds); if (!is_wp_error($temp_file)) { // array based on $_FILE as seen in PHP file uploads $file = array('name' => basename($url), 'type' => 'image/jpeg', 'tmp_name' => $temp_file, 'error' => 0, 'size' => filesize($temp_file)); $overrides = array('test_form' => false, 'test_size' => true, 'test_upload' => true); // move the temporary file into the uploads directory $results = wp_handle_sideload($file, $overrides); if (!empty($results['error'])) { // insert any error handling here } else { $filename = $results['file']; // full path to the file $local_url = $results['url']; // URL to the file in the uploads dir $type = $results['type']; // MIME type of the file // Check the type of file. We'll use this as the 'post_mime_type'. $filetype = wp_check_filetype(basename($filename), null); // Get the path to the upload directory. $wp_upload_dir = wp_upload_dir(); // Prepare an array of post data for the attachment. $attachment = array('guid' => $wp_upload_dir['url'] . '/' . basename($filename), 'post_mime_type' => $type, 'post_title' => preg_replace('/\\.[^.]+$/', '', basename($filename)), 'post_content' => '', 'post_status' => 'inherit'); // Insert the attachment. $attach_id = wp_insert_attachment($attachment, $filename); // Make sure that this file is included, as wp_generate_attachment_metadata() depends on it. require_once ABSPATH . 'wp-admin/includes/image.php'; // Generate the metadata for the attachment, and update the database record. $attach_data = wp_generate_attachment_metadata($attach_id, $filename); wp_update_attachment_metadata($attach_id, $attach_data); update_option('uncode_default_header_image', $attach_id); } } } }
/** * Handles the CSV source upload/sideload * * @since 3.0.0 * @param string $type * @param string $source * @return string File path in local filesystem or false on failure */ protected function handle_upload($type, $source = 'upload') { $file_path = false; switch ($source) { // handle uploaded files case 'upload': $results = wp_import_handle_upload(); if (isset($results['error'])) { $this->handle_upload_error($results['error']); return false; } $file_path = $results['file']; break; // handle URL or path input // handle URL or path input case 'url': // if this is an URL, try to sideload the file if (filter_var($_POST['url'], FILTER_VALIDATE_URL)) { require_once ABSPATH . 'wp-admin/includes/file.php'; // download the URL to a temp file $temp_file = download_url($_POST['url'], 5); if (is_wp_error($temp_file)) { $this->handle_upload_error($temp_file); return false; } // array based on $_FILE as seen in PHP file uploads $input = array('name' => basename($_POST['url']), 'type' => 'image/png', 'tmp_name' => $temp_file, 'error' => 0, 'size' => filesize($temp_file)); // move the temporary file into the uploads directory $results = wp_handle_sideload($input, array('test_form' => false)); if (!empty($results['error'])) { $this->handle_upload_error($results['error']); return false; } $file_path = $results['file']; } else { if (!is_readable($_POST['url'])) { $error = sprintf(__('Could not find the file %s ', 'woocommerce-csv-import-suite'), esc_html($_POST['url'])); $this->handle_upload_error($error); return false; } $file_path = esc_attr($_POST['url']); } break; // handle copy-pasted data // handle copy-pasted data case 'copypaste': $data = stripslashes($_POST['copypaste']); $results = wp_upload_bits($type . '-' . date('Ymd-His') . '.csv', null, $data); if (!empty($results['error'])) { $this->handle_upload_error($results['error']); return false; } $file_path = $results['file']; break; } return $file_path; }
/** * Used to clean and sanitize the settings fields * * @since 1.0 */ function rocket_settings_callback($inputs) { if (isset($_GET['action']) && 'purge_cache' == $_GET['action']) { return $inputs; } /* * Option : Minification CSS & JS */ $inputs['minify_css'] = !empty($inputs['minify_css']) ? 1 : 0; $inputs['minify_js'] = !empty($inputs['minify_js']) ? 1 : 0; /* * Option : Purge delay */ $inputs['purge_cron_interval'] = isset($inputs['purge_cron_interval']) ? (int) $inputs['purge_cron_interval'] : get_rocket_option('purge_cron_interval'); $inputs['purge_cron_unit'] = isset($inputs['purge_cron_unit']) ? $inputs['purge_cron_unit'] : get_rocket_option('purge_cron_unit'); /* * Option : Prefetch DNS requests */ if (!empty($inputs['dns_prefetch'])) { if (!is_array($inputs['dns_prefetch'])) { $inputs['dns_prefetch'] = explode("\n", $inputs['dns_prefetch']); } $inputs['dns_prefetch'] = array_map('trim', $inputs['dns_prefetch']); $inputs['dns_prefetch'] = array_map('esc_url', $inputs['dns_prefetch']); $inputs['dns_prefetch'] = (array) array_filter($inputs['dns_prefetch']); $inputs['dns_prefetch'] = array_unique($inputs['dns_prefetch']); } else { $inputs['dns_prefetch'] = array(); } /* * Option : Empty the cache of the following pages when updating an article */ if (!empty($inputs['cache_purge_pages'])) { if (!is_array($inputs['cache_purge_pages'])) { $inputs['cache_purge_pages'] = explode("\n", $inputs['cache_purge_pages']); } $inputs['cache_purge_pages'] = array_map('trim', $inputs['cache_purge_pages']); $inputs['cache_purge_pages'] = array_map('esc_url', $inputs['cache_purge_pages']); $inputs['cache_purge_pages'] = array_map('rocket_clean_exclude_file', $inputs['cache_purge_pages']); $inputs['cache_purge_pages'] = (array) array_filter($inputs['cache_purge_pages']); $inputs['cache_purge_pages'] = array_unique($inputs['cache_purge_pages']); } else { $inputs['cache_purge_pages'] = array(); } /* * Option : Never cache the following pages */ if (!empty($inputs['cache_reject_uri'])) { if (!is_array($inputs['cache_reject_uri'])) { $inputs['cache_reject_uri'] = explode("\n", $inputs['cache_reject_uri']); } $inputs['cache_reject_uri'] = array_map('trim', $inputs['cache_reject_uri']); $inputs['cache_reject_uri'] = array_map('esc_url', $inputs['cache_reject_uri']); $inputs['cache_reject_uri'] = array_map('rocket_clean_exclude_file', $inputs['cache_reject_uri']); $inputs['cache_reject_uri'] = (array) array_filter($inputs['cache_reject_uri']); $inputs['cache_reject_uri'] = array_unique($inputs['cache_reject_uri']); } else { $inputs['cache_reject_uri'] = array(); } /* * Option : Don't cache pages that use the following cookies */ if (!empty($inputs['cache_reject_cookies'])) { if (!is_array($inputs['cache_reject_cookies'])) { $inputs['cache_reject_cookies'] = explode("\n", $inputs['cache_reject_cookies']); } $inputs['cache_reject_cookies'] = array_map('trim', $inputs['cache_reject_cookies']); $inputs['cache_reject_cookies'] = array_map('rocket_sanitize_cookie', $inputs['cache_reject_cookies']); $inputs['cache_reject_cookies'] = (array) array_filter($inputs['cache_reject_cookies']); $inputs['cache_reject_cookies'] = array_unique($inputs['cache_reject_cookies']); } else { $inputs['cache_reject_cookies'] = array(); } /* * Option : Cache pages that use the following query strings (GET parameters) */ if (!empty($inputs['cache_query_strings'])) { if (!is_array($inputs['cache_query_strings'])) { $inputs['cache_query_strings'] = explode("\n", $inputs['cache_query_strings']); } $inputs['cache_query_strings'] = array_map('trim', $inputs['cache_query_strings']); $inputs['cache_query_strings'] = array_map('sanitize_key', $inputs['cache_query_strings']); $inputs['cache_query_strings'] = (array) array_filter($inputs['cache_query_strings']); $inputs['cache_query_strings'] = array_unique($inputs['cache_query_strings']); } else { $inputs['cache_query_strings'] = array(); } /* * Option : Never send cache pages for these user agents */ if (!empty($inputs['cache_reject_ua'])) { if (!is_array($inputs['cache_reject_ua'])) { $inputs['cache_reject_ua'] = explode("\n", $inputs['cache_reject_ua']); } $inputs['cache_reject_ua'] = array_map('trim', $inputs['cache_reject_ua']); $inputs['cache_reject_ua'] = array_map('rocket_sanitize_ua', $inputs['cache_reject_ua']); $inputs['cache_reject_ua'] = (array) array_filter($inputs['cache_reject_ua']); $inputs['cache_reject_ua'] = array_unique($inputs['cache_reject_ua']); } else { $inputs['cache_reject_ua'] = array(); } /* * Option : CSS files to exclude of the minification */ if (!empty($inputs['exclude_css'])) { if (!is_array($inputs['exclude_css'])) { $inputs['exclude_css'] = explode("\n", $inputs['exclude_css']); } $inputs['exclude_css'] = array_map('trim', $inputs['exclude_css']); $inputs['exclude_css'] = array_map('rocket_clean_exclude_file', $inputs['exclude_css']); $inputs['exclude_css'] = array_map('rocket_sanitize_css', $inputs['exclude_css']); $inputs['exclude_css'] = (array) array_filter($inputs['exclude_css']); $inputs['exclude_css'] = array_unique($inputs['exclude_css']); } else { $inputs['exclude_css'] = array(); } /* * Option : JS files to exclude of the minification */ if (!empty($inputs['exclude_js'])) { if (!is_array($inputs['exclude_js'])) { $inputs['exclude_js'] = explode("\n", $inputs['exclude_js']); } $inputs['exclude_js'] = array_map('trim', $inputs['exclude_js']); $inputs['exclude_js'] = array_map('rocket_clean_exclude_file', $inputs['exclude_js']); $inputs['exclude_js'] = array_map('rocket_sanitize_js', $inputs['exclude_js']); $inputs['exclude_js'] = (array) array_filter($inputs['exclude_js']); $inputs['exclude_js'] = array_unique($inputs['exclude_js']); } else { $inputs['exclude_js'] = array(); } /* * Option : JS files with deferred loading */ if (!empty($inputs['deferred_js_files'])) { $inputs['deferred_js_files'] = array_unique($inputs['deferred_js_files']); $inputs['deferred_js_files'] = array_map('rocket_sanitize_js', $inputs['deferred_js_files']); $inputs['deferred_js_files'] = array_filter($inputs['deferred_js_files']); } else { $inputs['deferred_js_files'] = array(); } if (!$inputs['deferred_js_files']) { $inputs['deferred_js_wait'] = array(); } else { for ($i = 0; $i <= max(array_keys($inputs['deferred_js_files'])); $i++) { if (!isset($inputs['deferred_js_files'][$i])) { unset($inputs['deferred_js_wait'][$i]); } else { $inputs['deferred_js_wait'][$i] = isset($inputs['deferred_js_wait'][$i]) ? '1' : '0'; } } $inputs['deferred_js_files'] = array_values($inputs['deferred_js_files']); ksort($inputs['deferred_js_wait']); $inputs['deferred_js_wait'] = array_values($inputs['deferred_js_wait']); } /* * Option : JS files of the minification to insert in footer */ if (!empty($inputs['minify_js_in_footer'])) { foreach ($inputs['minify_js_in_footer'] as $k => $url) { if (in_array($url, $inputs['deferred_js_files'])) { unset($inputs['minify_js_in_footer'][$k]); } } $inputs['minify_js_in_footer'] = array_filter(array_map('rocket_sanitize_js', array_unique($inputs['minify_js_in_footer']))); } else { $inputs['minify_js_in_footer'] = array(); } /* * Option : WL */ $inputs['wl_plugin_name'] = isset($inputs['wl_plugin_name']) ? wp_strip_all_tags($inputs['wl_plugin_name']) : get_rocket_option('wl_plugin_name'); $inputs['wl_plugin_URI'] = isset($inputs['wl_plugin_URI']) ? esc_url($inputs['wl_plugin_URI']) : get_rocket_option('wl_plugin_URI'); $inputs['wl_author'] = isset($inputs['wl_author']) ? wp_strip_all_tags($inputs['wl_author']) : get_rocket_option('wl_author'); $inputs['wl_author_URI'] = isset($inputs['wl_author_URI']) ? esc_url($inputs['wl_author_URI']) : get_rocket_option('wl_author_URI'); $inputs['wl_description'] = isset($inputs['wl_description']) ? (array) $inputs['wl_description'] : get_rocket_option('wl_description'); $inputs['wl_plugin_slug'] = sanitize_key($inputs['wl_plugin_name']); /* * Option : CDN */ $inputs['cdn_cnames'] = isset($inputs['cdn_cnames']) ? array_unique(array_filter($inputs['cdn_cnames'])) : array(); if (!$inputs['cdn_cnames']) { $inputs['cdn_zone'] = array(); } else { for ($i = 0; $i <= max(array_keys($inputs['cdn_cnames'])); $i++) { if (!isset($inputs['cdn_cnames'][$i])) { unset($inputs['cdn_zone'][$i]); } else { $inputs['cdn_zone'][$i] = isset($inputs['cdn_zone'][$i]) ? $inputs['cdn_zone'][$i] : 'all'; } } $inputs['cdn_cnames'] = array_values($inputs['cdn_cnames']); ksort($inputs['cdn_zone']); $inputs['cdn_zone'] = array_values($inputs['cdn_zone']); } /* * Option : Files to exclude of the CDN process */ if (!empty($inputs['cdn_reject_files'])) { if (!is_array($inputs['cdn_reject_files'])) { $inputs['cdn_reject_files'] = explode("\n", $inputs['cdn_reject_files']); } $inputs['cdn_reject_files'] = array_map('trim', $inputs['cdn_reject_files']); $inputs['cdn_reject_files'] = array_map('rocket_clean_exclude_file', $inputs['cdn_reject_files']); $inputs['cdn_reject_files'] = (array) array_filter($inputs['cdn_reject_files']); $inputs['cdn_reject_files'] = array_unique($inputs['cdn_reject_files']); } else { $inputs['cdn_reject_files'] = array(); } /* * Option: Support */ $fake_options = array('support_summary', 'support_description', 'support_documentation_validation'); foreach ($fake_options as $option) { if (isset($inputs[$option])) { unset($inputs[$option]); } } if (isset($_FILES['import']) && preg_match('/wp-rocket-settings-20\\d{2}-\\d{2}-\\d{2}-[a-f0-9]{13}\\.txt/', $_FILES['import']['name']) && 'text/plain' == $_FILES['import']['type']) { $file_name = $_FILES['import']['name']; $_POST_action = $_POST['action']; $_POST['action'] = 'wp_handle_sideload'; $file = wp_handle_sideload($_FILES['import'], array('mimes' => array('txt' => 'text/plain'))); $_POST['action'] = $_POST_action; $gz = 'gz' . strrev('etalfni'); $settings = @file_get_contents($file['file']); $settings = $gz($settings); $settings = unserialize($settings); file_put_contents($file['file'], ''); @unlink($file['file']); if (is_array($settings)) { $settings['consumer_key'] = $inputs['consumer_key']; $settings['consumer_email'] = $inputs['consumer_email']; $settings['secret_key'] = $inputs['secret_key']; $settings['secret_cache_key'] = $inputs['secret_cache_key']; $settings['minify_css_key'] = $inputs['minify_css_key']; $settings['minify_js_key'] = $inputs['minify_js_key']; $settings['version'] = $inputs['version']; $inputs = $settings; add_settings_error('general', 'settings_updated', __('Settings imported and saved.', 'rocket'), 'updated'); } } if (!rocket_valid_key()) { $checked = rocket_check_key('live'); } else { $checked = rocket_check_key('transient_1'); } if (is_array($checked)) { $inputs['consumer_key'] = $checked['consumer_key']; $inputs['consumer_email'] = $checked['consumer_email']; $inputs['secret_key'] = $checked['secret_key']; } if (rocket_valid_key() && !empty($inputs['secret_key']) && !isset($inputs['ignore'])) { unset($inputs['ignore']); add_settings_error('general', 'settings_updated', __('Settings saved.', 'rocket'), 'updated'); } return $inputs; }
function badge_designer() { /* Get data about the current user... */ global $current_user; get_currentuserinfo(); /* Has a badge been created? */ if ($_POST['targetImage'] != '') { /* Create a directory to hold temporary image files... */ if (!is_dir(dirname(__FILE__) . '/temp_images')) { mkdir(dirname(__FILE__) . '/temp_images/'); chmod(dirname(__FILE__) . '/temp_images/', 0777); } /* Save a temp version of the badge based on the base64 supplied... */ define('UPLOAD_DIR', dirname(__FILE__) . '/temp_images/'); $img = $_POST['targetImage']; $img = str_replace('data:image/png;base64,', '', $img); $img = str_replace(' ', '+', $img); $data = base64_decode($img); $file = UPLOAD_DIR . uniqid() . '.png'; $success = file_put_contents($file, $data); //echo '<hr/>Temp image created: ';print_r($success); /* Create a $_FILES based array... */ $file_array['tmp_name'] = $file; $file_array['name'] = 'badge.png'; //echo '<hr/>Files array created: ';print_r($file_array); /* Include required files... */ require_once ABSPATH . 'wp-admin/includes/file.php'; require_once ABSPATH . 'wp-admin/includes/media.php'; require_once ABSPATH . 'wp-admin/includes/image.php'; /* Move the file to the uploads directory... */ $uploadedfile = $file_array; $upload_overrides = array('test_form' => false); $movefile = wp_handle_sideload($uploadedfile, $upload_overrides); /* If the move was successful... */ if ($movefile) { /* Remove the temp image file... */ @unlink($file_array['tmp_name']); /* Generate image metadata... */ $wp_filetype = wp_check_filetype(basename($movefile['file']), null); $wp_upload_dir = wp_upload_dir(); $attachment = array('guid' => $wp_upload_dir['url'] . '/' . basename($movefile['file']), 'post_mime_type' => $wp_filetype['type'], 'post_title' => preg_replace('/\\.[^.]+$/', '', basename($movefile['file'])), 'post_content' => '', 'post_status' => 'inherit'); /* Add the image into the media library... */ $attach_id = wp_insert_attachment($attachment, $movefile['file']); $attach_data = wp_generate_attachment_metadata($attach_id, $movefile['file']); $attach_data['go_category'] = 'badge'; wp_update_attachment_metadata($attach_id, $attach_data); //echo "<hr/>File is valid, and was successfully uploaded.\n";print_r( $movefile); /* Redirect to media library */ echo '<script>window.location.replace("' . get_site_url() . '/wp-admin/post.php?post=' . $attach_id . '&action=edit");</script>'; } else { /* something went wrong... */ echo "An error occured - possible file upload attack!\n"; } } else { ?> <div class="wrap"> <iframe name="if" id="if" style="margin-top:5px;" src="https://www.openbadges.me/designer.html?origin=<?php echo get_site_url(); ?> &email=<?php echo $current_user->user_email; ?> " height="670" width="100%"> </iframe> <script> window.onmessage = function(e){ if(e.origin=='https://www.openbadges.me'){ if(e.data!='cancelled'){ document.getElementById('targetImage').value = e.data; document.getElementById('imageForm').submit(); } } }; </script> <form id="imageForm" method="POST" action="" enctype="multipart/form-data"> <input type="hidden" name="targetImage" id="targetImage"/> </form> </div> <a href="javascript:;" onclick="go_display_help_video('http://maclab.guhsd.net/go/video/badgeDesigner/badgeDesigner.mp4');">Help</a> <?php } }
/** * Move image to WP Media Library * * @param string $path Path to image * @param string $name Filename for moved image * @param string $title Title of image in Media Library * @return int ID of image */ function image_gen__move_to_wp($path, $name, $title) { $file_array = array(); $file_array['tmp_name'] = $path; $file_array['name'] = $name; $image = wp_handle_sideload($file_array, array('test_form' => false)); $id = wp_insert_attachment(array('post_title' => $title, 'guid' => $image['url'], 'post_mime_type' => $image['type']), $image['file']); wp_update_attachment_metadata($id, wp_generate_attachment_metadata($id, $image['file'])); return $id; }
/** * Handle an upload via raw POST data * * @param array $_files Data from $_FILES. Unused. * @param array $_headers HTTP headers from the request * @return array|WP_Error Data from {@see wp_handle_sideload()} */ protected function upload_from_data($_files, $_headers) { $data = $this->server->get_raw_data(); if (empty($data)) { return new WP_Error('json_upload_no_data', __('No data supplied'), array('status' => 400)); } if (empty($_headers['CONTENT_TYPE'])) { return new WP_Error('json_upload_no_type', __('No Content-Type supplied'), array('status' => 400)); } if (empty($_headers['CONTENT_DISPOSITION'])) { return new WP_Error('json_upload_no_disposition', __('No Content-Disposition supplied'), array('status' => 400)); } // Get the filename $disposition_parts = explode(';', $_headers['CONTENT_DISPOSITION']); $filename = null; foreach ($disposition_parts as $part) { $part = trim($part); if (strpos($part, 'filename') !== 0) { continue; } $filenameparts = explode('=', $part); $filename = trim($filenameparts[1]); } if (empty($filename)) { return new WP_Error('json_upload_invalid_disposition', __('Invalid Content-Disposition supplied'), array('status' => 400)); } if (!empty($_headers['CONTENT_MD5'])) { $expected = trim($_headers['CONTENT_MD5']); $actual = md5($data); if ($expected !== $actual) { return new WP_Error('json_upload_hash_mismatch', __('Content hash did not match expected'), array('status' => 412)); } } // Get the content-type $type = $_headers['CONTENT_TYPE']; // Save the file $tmpfname = wp_tempnam($filename); $fp = fopen($tmpfname, 'w+'); if (!$fp) { return new WP_Error('json_upload_file_error', __('Could not open file handle'), array('status' => 500)); } fwrite($fp, $data); fclose($fp); // Now, sideload it in $file_data = array('error' => null, 'tmp_name' => $tmpfname, 'name' => $filename, 'type' => $type); $overrides = array('test_form' => false); $sideloaded = wp_handle_sideload($file_data, $overrides); if (isset($sideloaded['error'])) { @unlink($tmpfname); return new WP_Error('json_upload_sideload_error', $sideloaded['error'], array('status' => 500)); } return $sideloaded; }
/** * Convert base64 encoded image into a file and move it to proper WP uploads directory. **/ public static function decode_image_to_uploads($base64_string) { /* Make sure user has permissions to edit in the Visual Editor */ if (!HeadwayCapabilities::can_user_visually_edit()) { return; } /* Create a temporary file and decode the base64 encoded image into it */ $temporary_file = wp_tempnam(); file_put_contents($temporary_file, base64_decode($base64_string)); /* Use wp_check_filetype_and_ext() to figure out the real mimetype of the image. Provide a bogus extension and then we'll use the 'proper_filename' later. */ $filename = 'headway-imported-image.jpg'; $file_information = wp_check_filetype_and_ext($temporary_file, $filename); /* Construct $file array which is similar to a PHP $_FILES array. This array must be a variable since wp_handle_sideload() requires a variable reference argument. */ if (headway_get('proper_filename', $file_information)) { $filename = $file_information['proper_filename']; } $file = array('name' => $filename, 'tmp_name' => $temporary_file); /* Let WordPress move the image and spit out the file path, URL, etc. Set test_form to false that way it doesn't verify $_POST['action'] */ $upload = wp_handle_sideload($file, array('test_form' => false)); /* If there's an error, be sure to unlink/delete the temporary file in case wp_handle_sideload() doesn't. */ if (isset($upload['error'])) { @unlink($temporary_file); } return $upload; }
/** * Process an MLA_List_Table custom bulk action * * Creates new items from the "Bulk Translate" list. * * @since 2.13 * * @param array $item_content NULL, to indicate no handler. * @param string $bulk_action the requested action. * @param integer $post_id the affected attachment. * * @return object updated $item_content. NULL if no handler, otherwise * ( 'message' => error or status message(s), 'body' => '' ) */ public static function mla_list_table_custom_bulk_action($item_content, $bulk_action, $post_id) { if (self::MLA_GFI_ACTION != $bulk_action) { return $item_content; } /* translators: 1: post ID */ $item_prefix = sprintf(__('Item %1$d', 'media-library-assistant'), $post_id) . ', '; /* * If there is a real thumbnail image, no generation is required or allowed */ $thumbnail = wp_get_attachment_image($post_id); if (!empty($thumbnail)) { return array('message' => $item_prefix . __('has native thumbnail.', 'media-library-assistant')); } /* * Look for the "Featured Image" as an alternate thumbnail for PDFs, etc. */ $thumbnail = get_post_thumbnail_id($post_id); if (!empty($thumbnail)) { switch (self::$bulk_action_options['existing_thumbnails']) { case 'ignore': break; case 'trash': delete_post_thumbnail($post_id); wp_delete_post(absint($thumbnail), false); break; case 'delete': delete_post_thumbnail($post_id); wp_delete_post(absint($thumbnail), true); break; case 'keep': default: return array('message' => $item_prefix . __('Featured Image retained.', 'media-library-assistant')); } } /* * Validate the file existance and type */ $file = get_attached_file($post_id); if (empty($file)) { /* translators: 1: ERROR tag 2: Item post ID */ return array('message' => sprintf(__('%1$s: %2$sno attached file.', 'media-library-assistant'), __('ERROR', 'media-library-assistant'), $item_prefix)); } if (!in_array(strtolower(pathinfo($file, PATHINFO_EXTENSION)), array('ai', 'eps', 'pdf', 'ps'))) { return array('message' => $item_prefix . __('unsupported file type.', 'media-library-assistant')); } /* * Generate a thumbnail */ require_once MLA_PLUGIN_PATH . 'includes/class-mla-image-processor.php'; $results = MLAImageProcessor::mla_handle_thumbnail_sideload($file, self::$bulk_action_options); if (!empty($results['error'])) { /* translators: 1: ERROR tag 2: Item post ID */ return array('message' => sprintf(__('%1$s: %2$sthumbnail generation failed', 'media-library-assistant'), __('ERROR', 'media-library-assistant'), $item_prefix) . ' - ' . $results['error']); } /* * Adjust the file name for the new item */ $pathinfo = pathinfo($results['name']); if (isset(self::$bulk_action_options['suffix'])) { $pathinfo['filename'] = sanitize_file_name($pathinfo['filename'] . strtolower(self::$bulk_action_options['suffix'])); } $pathinfo['extension'] = 'image/jpeg' == $results['type'] ? 'jpg' : 'png'; $results['name'] = $pathinfo['filename'] . '.' . $pathinfo['extension']; $overrides = array('test_form' => false, 'test_size' => true, 'test_upload' => true); // move the temporary file into the uploads directory $results = wp_handle_sideload($results, $overrides); $item_data = get_post($post_id, ARRAY_A); unset($item_data['ID']); unset($item_data['post_author']); unset($item_data['post_date']); unset($item_data['post_date_gmt']); if (isset(self::$bulk_action_options['suffix'])) { $item_data['post_title'] .= self::$bulk_action_options['suffix']; } unset($item_data['post_name']); unset($item_data['post_modified']); unset($item_data['post_modified_gmt']); $item_parent = $item_data['post_parent']; unset($item_data['post_parent']); $item_data['guid'] = $results['url']; $item_data['post_mime_type'] = $results['type']; unset($item_data['comment_count']); unset($item_data['ancestors']); unset($item_data['post_category']); unset($item_data['tags_input']); // Insert the attachment. $item_id = wp_insert_attachment($item_data, $results['file'], $item_parent); if (empty($item_id)) { /* translators: 1: ERROR tag 2: Item post ID */ return array('message' => sprintf(__('%1$s: %2$swp_insert_attachment failed.', 'media-library-assistant'), __('ERROR', 'media-library-assistant'), $item_prefix)); } // Make sure that this file is included, as wp_generate_attachment_metadata() depends on it. require_once ABSPATH . 'wp-admin/includes/image.php'; // Generate the metadata for the attachment, and update the database record. $item_data = wp_generate_attachment_metadata($item_id, $results['file']); wp_update_attachment_metadata($item_id, $item_data); // Assign the new item as the source item's Featured Image delete_post_thumbnail($post_id); set_post_thumbnail($post_id, $item_id); MLA_Thumbnail::$bulk_action_includes[] = $item_id; /* translators: 1: Item post ID, 2: new thumbnail item ID */ $item_content = array('message' => sprintf(__('%1$sthumbnail generated as new item %2$s.', 'media-library-assistant'), $item_prefix, $item_id)); return $item_content; }
/** * @since 2.1.6 */ function wpbdp_media_upload($file_, $use_media_library = true, $check_image = false, $constraints = array(), &$error_msg = null, $sideload = false) { require_once ABSPATH . 'wp-admin/includes/file.php'; require_once ABSPATH . 'wp-admin/includes/image.php'; $sideload = is_string($file_) && file_exists($file_) ? true : false; if ($sideload) { $mime_type = ''; if ($finfo = finfo_open(FILEINFO_MIME)) { $mime_type = explode(';', finfo_file($finfo, $file_)); $mime_type = trim($mime_type[0]); finfo_close($finfo); } $file = array('name' => basename($file_), 'tmp_name' => $file_, 'type' => $mime_type, 'error' => 0, 'size' => filesize($file_)); } else { $file = $file_; } $constraints = array_merge(array('image' => false, 'min-size' => 0, 'max-size' => 0, 'min-width' => 0, 'min-height' => 0, 'max-width' => 0, 'max-height' => 0, 'mimetypes' => null), $constraints); foreach (array('min-size', 'max-size', 'min-width', 'min-height', 'max-width', 'max-height') as $k) { $constraints[$k] = absint($constraints[$k]); } if ($file['error'] == 0) { if ($constraints['max-size'] > 0 && $file['size'] > $constraints['max-size']) { $error_msg = sprintf(_x('File size (%s) exceeds maximum file size of %s', 'utils', 'WPBDM'), size_format($file['size'], 2), size_format($constraints['max-size'], 2)); return false; } if ($constraints['min-size'] > 0 && $file['size'] < $constraints['min-size']) { $error_msg = sprintf(_x('File size (%s) is inferior to the required minimum file size of %s', 'utils', 'WPBDM'), size_format($file['size'], 2), size_format($constraints['min-size'], 2)); return false; } if (is_array($constraints['mimetypes'])) { if (!in_array(strtolower($file['type']), $constraints['mimetypes'])) { $error_msg = sprintf(_x('File type "%s" is not allowed', 'utils', 'WPBDM'), $file['type']); return false; } } // We do not accept TIFF format. Compatibility issues. if (in_array(strtolower($file['type']), array('image/tiff'))) { $error_msg = sprintf(_x('File type "%s" is not allowed', 'utils', 'WPBDM'), $file['type']); return false; } $upload = $sideload ? wp_handle_sideload($file, array('test_form' => FALSE)) : wp_handle_upload($file, array('test_form' => FALSE)); if (!$upload || !is_array($upload) || isset($upload['error'])) { $error_msg = isset($upload['error']) ? $upload['error'] : _x('Unkown error while uploading file.', 'utils', 'WPBDM'); return false; } if (!$use_media_library) { return $upload; } if ($attachment_id = wp_insert_attachment(array('post_mime_type' => $upload['type'], 'post_title' => preg_replace('/\\.[^.]+$/', '', basename($upload['file'])), 'post_content' => '', 'post_status' => 'inherit'), $upload['file'])) { $attach_metadata = wp_generate_attachment_metadata($attachment_id, $upload['file']); wp_update_attachment_metadata($attachment_id, $attach_metadata); if ($check_image && !wp_attachment_is_image($attachment_id)) { wp_delete_attachment($attachment_id, true); $error_msg = _x('Uploaded file is not an image', 'utils', 'WPBDM'); return false; } if (wp_attachment_is_image($attachment_id)) { $meta = wp_get_attachment_metadata($attachment_id); $failed = false; if (!$failed && $meta && $constraints['min-width'] > 0 && $meta['width'] < $constraints['min-width']) { $error_msg = sprintf(_x('Image width (%s px) is inferior to minimum required width of %s px.', 'utils', 'WPBDM'), $meta['width'], $constraints['min-width']); } if (!$failed && $meta && $constraints['min-height'] > 0 && $meta['height'] < $constraints['min-height']) { $error_msg = sprintf(_x('Image height (%s px) is inferior to minimum required height of %s px.', 'utils', 'WPBDM'), $meta['height'], $constraints['min-height']); } if (!$failed && $meta && $constraints['max-width'] > 0 && $meta['width'] > $constraints['max-width']) { $error_msg = sprintf(_x('Image width (%s px) is greater than maximum allowed width of %s px.', 'utils', 'WPBDM'), $meta['width'], $constraints['max-width']); } if (!$failed && $meta && $constraints['max-height'] > 0 && $meta['height'] > $constraints['max-height']) { $error_msg = sprintf(_x('Image height (%s px) is greater than maximum required height of %s px.', 'utils', 'WPBDM'), $meta['height'], $constraints['max-height']); } if ($failed) { wp_delete_attachment($attachment_id, true); return false; } } return $attachment_id; } } else { $error_msg = _x('Error while uploading file', 'utils', 'WPBDM'); } return false; }
} } else { //*// // Insert post first $post_id = wp_insert_post($post); wp_set_object_terms($post_id, $tmp_block, 'section'); // Add post meta add_post_meta($post_id, 'ul_header', $tmp_ul_header != '' ? $tmp_ul_header : ''); add_post_meta($post_id, 'ul_location', $tmp_ul_location != '' ? $tmp_ul_location : ''); add_post_meta($post_id, 'ul_link', $tmp_ul_link != '' ? $tmp_ul_link : ''); if ($src != $tmp_ul_link) { $temp_file = download_url($src, $to_seconds); if (!is_wp_error($temp_file)) { $file = array('name' => basename($src), 'type' => 'image/' . pathinfo($src, PATHINFO_EXTENSION), 'tmp_name' => $temp_file, 'error' => 0, 'size' => filesize($temp_file)); // upload image $upload = wp_handle_sideload($file, $overrides); $attachment = array('guid' => $wp_upload_dir['url'] . '/' . basename($upload['file']), 'post_mime_type' => $upload['type'], 'post_title' => preg_replace('/\\.[^.]+$/', '', basename($upload['file'])), 'post_content' => '', 'post_status' => 'inherit'); // Insert attachment $attached_id = wp_insert_attachment($attachment, $upload['file'], $post_id); // generating metadata and update attachment metadata $attach_data = wp_generate_attachment_metadata($attached_id, $upload['file']); wp_update_attachment_metadata($attached_id, $attach_data); // set post thumbnail or featured image if (set_post_thumbnail($post_id, $attached_id)) { echo 'added attachment for #' . $post_id . '<br><br>'; } else { echo '<strong style="color:red">error</strong> attachment for #' . $post_id . '<br><br>'; } } // End of If }
function cfp_upload_image($post_id, $post_image, $post_image_name = null) { $upload_dir = wp_upload_dir(); $upload_path = str_replace('/', DIRECTORY_SEPARATOR, $upload_dir['path']) . DIRECTORY_SEPARATOR; $decoded_img = base64_decode($post_image); if (!$post_image_name) { $filename = 'image.png'; } else { $filename = $post_image_name; } $hashed_filename = md5($filename . microtime()) . '_' . $filename; $image_upload = file_put_contents($upload_path . $hashed_filename, $decoded_img); if (!function_exists('wp_handle_sideload')) { require_once ABSPATH . 'wp-admin/includes/file.php'; } if (!function_exists('wp_get_current_user')) { require_once ABSPATH . 'wp-includes/pluggable.php'; } $file = array(); $file['error'] = ''; $file['tmp_name'] = $upload_path . $hashed_filename; $file['name'] = $hashed_filename; $file['type'] = 'image/jpg'; $file['size'] = filesize($upload_path . $hashed_filename); $file_return = wp_handle_sideload($file, array('test_form' => false)); $file_url = $file_return["file"]; $filetype = wp_check_filetype(basename($file_url), null); $attachment = array('guid' => $upload_dir['url'] . '/' . basename($file_url), 'post_mime_type' => $filetype['type'], 'post_title' => preg_replace('/\\.[^.]+$/', '', basename($file_url)), 'post_content' => '', 'post_status' => 'inherit'); $attach_id = wp_insert_attachment($attachment, $file_url, $post_id); require_once ABSPATH . 'wp-admin/includes/image.php'; $attach_data = wp_generate_attachment_metadata($attach_id, $file_url); wp_update_attachment_metadata($attach_id, $attach_data); update_post_meta($post_id, '_thumbnail_id', $attach_id); }
/** * Handles an upload via raw POST data. * * @since 4.7.0 * @access protected * * @param array $data Supplied file data. * @param array $headers HTTP headers from the request. * @return array|WP_Error Data from wp_handle_sideload(). */ protected function upload_from_data($data, $headers) { if (empty($data)) { return new WP_Error('rest_upload_no_data', __('No data supplied.'), array('status' => 400)); } if (empty($headers['content_type'])) { return new WP_Error('rest_upload_no_content_type', __('No Content-Type supplied.'), array('status' => 400)); } if (empty($headers['content_disposition'])) { return new WP_Error('rest_upload_no_content_disposition', __('No Content-Disposition supplied.'), array('status' => 400)); } $filename = self::get_filename_from_disposition($headers['content_disposition']); if (empty($filename)) { return new WP_Error('rest_upload_invalid_disposition', __('Invalid Content-Disposition supplied. Content-Disposition needs to be formatted as `attachment; filename="image.png"` or similar.'), array('status' => 400)); } if (!empty($headers['content_md5'])) { $content_md5 = array_shift($headers['content_md5']); $expected = trim($content_md5); $actual = md5($data); if ($expected !== $actual) { return new WP_Error('rest_upload_hash_mismatch', __('Content hash did not match expected.'), array('status' => 412)); } } // Get the content-type. $type = array_shift($headers['content_type']); /** Include admin functions to get access to wp_tempnam() and wp_handle_sideload() */ require_once ABSPATH . 'wp-admin/includes/admin.php'; // Save the file. $tmpfname = wp_tempnam($filename); $fp = fopen($tmpfname, 'w+'); if (!$fp) { return new WP_Error('rest_upload_file_error', __('Could not open file handle.'), array('status' => 500)); } fwrite($fp, $data); fclose($fp); // Now, sideload it in. $file_data = array('error' => null, 'tmp_name' => $tmpfname, 'name' => $filename, 'type' => $type); $overrides = array('test_form' => false); $sideloaded = wp_handle_sideload($file_data, $overrides); if (isset($sideloaded['error'])) { @unlink($tmpfname); return new WP_Error('rest_upload_sideload_error', $sideloaded['error'], array('status' => 500)); } return $sideloaded; }
public function importImage($data) { if ($this->registry->exists('image', $data['id'])) { return false; } $download = download_url($data['url'], 30); if (is_wp_error($download)) { return $download; } $file = array('name' => basename($data['url']), 'tmp_name' => $download); $results = wp_handle_sideload($file, array('test_form' => false)); if (!empty($results['error'])) { return new WP_Error('__x__', 'Failed to sideload image: ' + $data['url']); } $name = explode('.', basename($results['file'])); $newPost = wp_insert_attachment(array('post_title' => sanitize_file_name($name[0]), 'post_content' => '', 'post_type' => 'attachment', 'post_mime_type' => $results['type'], 'guid' => $results['url']), $results['file']); if (is_wp_error($newPost)) { return $newPost; } wp_update_attachment_metadata($newPost, wp_generate_attachment_metadata($newPost, $results['file'])); $results['post_id'] = (int) $newPost; $this->registry->set('image', $data['id'], $results); $this->message = sprintf(__('Downloading images...', '__x__'), basename($results['url'])); return true; }
/** * This handles a sideloaded file in the same way as an uploaded file is handled by {@link media_handle_upload()} * * @since 2.6.0 * * @param array $file_array Array similar to a {@link $_FILES} upload array * @param int $post_id The post ID the media is associated with * @param string $desc Description of the sideloaded file * @param array $post_data allows you to overwrite some of the attachment * @return int|object The ID of the attachment or a WP_Error on failure */ function media_handle_sideload($file_array, $post_id, $desc = null, $post_data = array()) { $overrides = array('test_form' => false); $time = current_time('mysql'); if ($post = get_post($post_id)) { if (substr($post->post_date, 0, 4) > 0) { $time = $post->post_date; } } $file = wp_handle_sideload($file_array, $overrides, $time); if (isset($file['error'])) { return new WP_Error('upload_error', $file['error']); } $url = $file['url']; $type = $file['type']; $file = $file['file']; $title = preg_replace('/\\.[^.]+$/', '', basename($file)); $content = ''; // Use image exif/iptc data for title and caption defaults if possible. if ($image_meta = @wp_read_image_metadata($file)) { if (trim($image_meta['title']) && !is_numeric(sanitize_title($image_meta['title']))) { $title = $image_meta['title']; } if (trim($image_meta['caption'])) { $content = $image_meta['caption']; } } if (isset($desc)) { $title = $desc; } // Construct the attachment array. $attachment = array_merge(array('post_mime_type' => $type, 'guid' => $url, 'post_parent' => $post_id, 'post_title' => $title, 'post_content' => $content), $post_data); // This should never be set as it would then overwrite an existing attachment. if (isset($attachment['ID'])) { unset($attachment['ID']); } // Save the attachment metadata $id = wp_insert_attachment($attachment, $file, $post_id); if (!is_wp_error($id)) { wp_update_attachment_metadata($id, wp_generate_attachment_metadata($id, $file)); } return $id; }
/** * Downloads an externally hosted thumbnail image to the local server * * @since 0.1 * * @todo - revisit this whole function, a lot depends on $vid['id'] being set, while it might very well not be * * @todo - also: why not check whether the url is already local (not just an attachment) before doing anything else ? * * @param string $url The remote URL of the image. * @param string $ext Extension to use for the image, optional. * * @return bool|string $img[0] The link to the now locally hosted image. */ protected function make_image_local($url, $ext = '') { $vid = $this->vid; // Remove query parameters from the URL $url = strtok($url, '?'); if (isset($vid['post_id'])) { $att = get_posts(array('numberposts' => 1, 'post_type' => 'attachment', 'meta_key' => 'wpseo_video_id', 'meta_value' => isset($vid['id']) ? $vid['id'] : '', 'post_parent' => $vid['post_id'], 'fields' => 'ids')); if (is_array($att) && count($att) > 0) { $img = wp_get_attachment_image_src($att[0], 'full'); if ($img) { if (strpos($img[0], 'http') !== 0) { return get_site_url(null, $img[0]); } else { return $img[0]; } } } } // Disable wp smush.it to speed up the process // @todo - should this filter maybe be added back at the end ? If so we need to test whether it existed and // only add it back if it did remove_filter('wp_generate_attachment_metadata', 'wp_smushit_resize_from_meta_data'); $tmp = download_url($url); if (is_wp_error($tmp)) { @unlink($tmp); return false; } else { if (preg_match('`[^\\?]+\\.(' . WPSEO_Video_Sitemap::$image_ext_pattern . ')$`i', $url, $matches)) { $ext = $matches[1]; } if ((!isset($vid['title']) || empty($vid['title'])) && isset($vid['post_id'])) { $vid['title'] = get_the_title($vid['post_id']); } else { $vid['title'] = strtolower($vid['id']); } $title = sanitize_title(strtolower($vid['title'])); $file_array = array('name' => sanitize_file_name(preg_replace('`[^a-z0-9\\s_-]`i', '', $title)) . '.' . $ext, 'tmp_name' => $tmp); if (isset($vid['post_id']) && !defined('WPSEO_VIDEO_NO_ATTACHMENTS')) { $ret = media_handle_sideload($file_array, $vid['post_id'], 'Video thumbnail for ' . $vid['type'] . ' video ' . $vid['title']); if (is_wp_error($ret)) { @unlink($tmp); return false; } if (isset($vid['id'])) { update_post_meta($ret, 'wpseo_video_id', $vid['id']); } $img = wp_get_attachment_image_src($ret, 'full'); if ($img) { // Try and prevent relative paths to images if (strpos($img[0], 'http') !== 0) { $img = get_site_url(null, $img[0]); } else { $img = $img[0]; } return $img; } } else { $file = wp_handle_sideload($file_array, array('test_form' => false)); if (!isset($file['error'])) { return $file['url']; } else { @unlink($file); } } return false; } }