• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

PHP wp_handle_sideload函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了PHP中wp_handle_sideload函数的典型用法代码示例。如果您正苦于以下问题:PHP wp_handle_sideload函数的具体用法?PHP wp_handle_sideload怎么用?PHP wp_handle_sideload使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了wp_handle_sideload函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的PHP代码示例。

示例1: custom_media_sideload_image

/**
 * 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;
}
开发者ID:developmentDM2,项目名称:Whohaha,代码行数:39,代码来源:snippets.php


示例2: _process_downloaded_image

 /**
  * 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']));
 }
开发者ID:A5hleyRich,项目名称:wp-cli-unsplash-command,代码行数:37,代码来源:class-wp-cli-unsplash-command.php


示例3: upload_base64

 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;
 }
开发者ID:prosenjit-itobuz,项目名称:Unitee,代码行数:58,代码来源:wc_response.php


示例4: sideload_image

 /**
  * 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'];
     }
 }
开发者ID:dimadin,项目名称:wis-wp-plugin,代码行数:46,代码来源:Sideloader.php


示例5: upload_from_data

 /**
  * 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;
 }
开发者ID:Mushan3420,项目名称:BigApp-PHP7,代码行数:60,代码来源:class-wp-json-media.php


示例6: media_handle_sideload

/**
 * {@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;
}
开发者ID:Alenjandro,项目名称:data-my-share,代码行数:43,代码来源:media.php


示例7: fusion_import_to_media_library

 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;
     }
 }
开发者ID:agiper,项目名称:wordpress,代码行数:33,代码来源:fusion-functions.php


示例8: get_yacht_image

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);
        }
    }
}
开发者ID:shesser,项目名称:selenenw,代码行数:40,代码来源:functions.php


示例9: upload_from_data

 /**
  * 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;
 }
开发者ID:pristupaeugen,项目名称:wordpress_rest_api,代码行数:63,代码来源:class-wp-rest-attachments-controller.php


示例10: image_handle_upload

 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;
 }
开发者ID:pankajsinghjarial,项目名称:SYLC,代码行数:50,代码来源:products.class.php


示例11: add_map_on_save_post

 /**
  * 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']);
         }
     }
 }
开发者ID:Steadroy,项目名称:wptalents,代码行数:68,代码来源:Plugin.php


示例12: uncode_add_default_image_with_activation

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);
            }
        }
    }
}
开发者ID:b0123498765,项目名称:fithealthyandwealthy,代码行数:44,代码来源:admin.php


示例13: handle_upload

 /**
  * 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;
 }
开发者ID:arobbins,项目名称:spellestate,代码行数:65,代码来源:class-wc-csv-import-suite-importer.php


示例14: rocket_settings_callback


//.........这里部分代码省略.........
    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;
}
开发者ID:EliasGoldberg,项目名称:troop-sim,代码行数:101,代码来源:options.php


示例15: badge_designer

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 
    }
}
开发者ID:zetheroth,项目名称:game-on,代码行数:82,代码来源:badge_designer.php


示例16: image_gen__move_to_wp

/**
 * 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;
}
开发者ID:keesiemeijer,项目名称:image-gen,代码行数:18,代码来源:image-gen.php


示例17: upload_from_data

 /**
  * 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 fi 

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
PHP wp_handle_upload函数代码示例发布时间:2022-05-23
下一篇:
PHP wp_guess_url函数代码示例发布时间:2022-05-23
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap