/**
  * Upload
  * Ajax callback function
  *
  * @return string Error or (XML-)response
  */
 static function handle_upload()
 {
     check_admin_referer('rwmb-upload-images_' . $_REQUEST['field_id']);
     $post_id = 0;
     if (is_numeric($_REQUEST['post_id'])) {
         $post_id = (int) $_REQUEST['post_id'];
     }
     // You can use WP's wp_handle_upload() function:
     $file = $_FILES['async-upload'];
     $file_attr = wp_handle_upload($file, array('test_form' => true, 'action' => 'plupload_image_upload'));
     $attachment = array('guid' => $file_attr['url'], 'post_mime_type' => $file_attr['type'], 'post_title' => preg_replace('/\\.[^.]+$/', '', basename($file['name'])), 'post_content' => '', 'post_status' => 'inherit');
     // Adds file as attachment to WordPress
     $id = wp_insert_attachment($attachment, $file_attr['file'], $post_id);
     if (!is_wp_error($id)) {
         wp_update_attachment_metadata($id, wp_generate_attachment_metadata($id, $file_attr['file']));
         // Save file ID in meta field
         if (isset($_REQUEST['field_id'])) {
             add_post_meta($post_id, $_REQUEST['field_id'], $id, false);
         }
         $response = new WP_Ajax_Response();
         $response->add(array('what' => 'rwmb_image_response', 'data' => self::img_html($id)));
         $response->send();
     }
     exit;
 }
Example #2
6
 public function do_save($return_val, $params, $metas, $module)
 {
     if (empty($params['attachment_url'])) {
         return false;
     }
     $bits = file_get_contents($params['attachment_url']);
     $filename = $this->faker->uuid() . '.jpg';
     $upload = wp_upload_bits($filename, null, $bits);
     $params['guid'] = $upload['url'];
     $params['post_mime_type'] = 'image/jpeg';
     // Insert the attachment.
     $attach_id = wp_insert_attachment($params, $upload['file'], 0);
     if (!is_numeric($attach_id)) {
         return false;
     }
     if (!function_exists('wp_generate_attachment_metadata')) {
         // 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.
     $metas['_wp_attachment_metadata'] = wp_generate_attachment_metadata($attach_id, $upload['file']);
     foreach ($metas as $key => $value) {
         update_post_meta($attach_id, $key, $value);
     }
     return $attach_id;
 }
 /**
  * @param strin $file_url
  *
  * @return int
  */
 private function upload_file($file_url)
 {
     if (!filter_var($file_url, FILTER_VALIDATE_URL)) {
         return false;
     }
     $contents = @file_get_contents($file_url);
     if ($contents === false) {
         return false;
     }
     $upload = wp_upload_bits(basename($file_url), null, $contents);
     if (isset($upload['error']) && $upload['error']) {
         return false;
     }
     $type = '';
     if (!empty($upload['type'])) {
         $type = $upload['type'];
     } else {
         $mime = wp_check_filetype($upload['file']);
         if ($mime) {
             $type = $mime['type'];
         }
     }
     $attachment = array('post_title' => basename($upload['file']), 'post_content' => '', 'post_type' => 'attachment', 'post_mime_type' => $type, 'guid' => $upload['url']);
     $id = wp_insert_attachment($attachment, $upload['file']);
     wp_update_attachment_metadata($id, wp_generate_attachment_metadata($id, $upload['file']));
     return $id;
 }
function programmatically_create_post()
{
    $url = 'http://widgets.pinterest.com/v3/pidgets/boards/bradleyblose/my-stuff/pins/';
    $json_O = json_decode(file_get_contents($url), true);
    $id = $json_O['data']['pins'][0]['id'];
    $titlelink = 'https://www.pinterest.com/pin/' . $id . '/';
    $title = get_title($titlelink);
    var_dump($title);
    $original = $json_O['data']['pins'][0]['images']['237x']['url'];
    $image_url = preg_replace('/237x/', '736x', $original);
    $description = $json_O['data']['pins'][0]['description'];
    // Initialize the page ID to -1. This indicates no action has been taken.
    $post_id = -1;
    // Setup the author, slug, and title for the post
    $author_id = 1;
    $mytitle = get_page_by_title($title, OBJECT, 'post');
    var_dump($mytitle);
    // If the page doesn't already exist, then create it
    if (NULL == get_page_by_title($title, OBJECT, 'post')) {
        // Set the post ID so that we know the post was created successfully
        $post_id = wp_insert_post(array('comment_status' => 'closed', 'ping_status' => 'closed', 'post_author' => $author_id, 'post_name' => $title, 'post_title' => $title, 'post_content' => $description, 'post_status' => 'publish', 'post_type' => 'post'));
        //upload featured image
        $upload_dir = wp_upload_dir();
        $image_data = file_get_contents($image_url);
        $filename = basename($image_url);
        if (wp_mkdir_p($upload_dir['path'])) {
            $file = $upload_dir['path'] . '/' . $filename;
            $path = $upload_dir['path'] . '/';
        } else {
            $file = $upload_dir['basedir'] . '/' . $filename;
            $path = $upload_dir['basedir'] . '/';
        }
        file_put_contents($file, $image_data);
        //edit featured image to correct specs to fit theme
        $pngfilename = $filename . '.png';
        $targetThumb = $path . '/' . $pngfilename;
        $img = new Imagick($file);
        $img->scaleImage(250, 250, true);
        $img->setImageBackgroundColor('None');
        $w = $img->getImageWidth();
        $h = $img->getImageHeight();
        $img->extentImage(250, 250, ($w - 250) / 2, ($h - 250) / 2);
        $img->writeImage($targetThumb);
        unlink($file);
        //Attach featured image
        $wp_filetype = wp_check_filetype($pngfilename, null);
        $attachment = array('post_mime_type' => $wp_filetype['type'], 'post_title' => sanitize_file_name($pngfilename), 'post_content' => '', 'post_status' => 'inherit');
        $attach_id = wp_insert_attachment($attachment, $targetThumb, $post_id);
        require_once ABSPATH . 'wp-admin/includes/image.php';
        $attach_data = wp_generate_attachment_metadata($attach_id, $targetThumb);
        wp_update_attachment_metadata($attach_id, $attach_data);
        set_post_thumbnail($post_id, $attach_id);
        // Otherwise, we'll stop
    } else {
        // Arbitrarily use -2 to indicate that the page with the title already exists
        $post_id = -2;
    }
    // end if
}
Example #5
0
/**
 * 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;
}
Example #6
0
 function it_regenerate_wp_images()
 {
     return false;
     set_time_limit(0);
     echo "<pre>";
     echo "Regenerating thumbnails...\n";
     $args = array('post_type' => 'attachment', 'numberposts' => -1, 'post_status' => null);
     $attachments = get_posts($args);
     if ($attachments) {
         echo count($attachments) . " images were found.\n";
         foreach ($attachments as $attachment) {
             $full_size_path = get_attached_file($attachment->ID);
             if (false === $full_size_path || !file_exists($full_size_path)) {
                 echo "Image ID " . $attachment->ID . " was not found.\n";
                 continue;
             }
             $meta_data = wp_generate_attachment_metadata($attachment->ID, $full_size_path);
             if (is_wp_error($meta_data)) {
                 echo "Image ID " . $attachment->ID . " raised an error: " . $mata_data->get_error_message() . "\n";
                 continue;
             }
             if (empty($meta_data)) {
                 echo "Image ID " . $attachment->ID . " failed with unknown reason\n";
                 continue;
             }
             wp_update_attachment_metadata($attachment->ID, $meta_data);
         }
         echo "Done.";
     }
     echo "</pre>";
 }
Example #7
0
/**
 * Upload theme default site icon
 *
 * @return void
 */
function dswoddil_site_icon_upload()
{
    $image_name = 'site-icon';
    if (!function_exists('wp_update_attachment_metadata')) {
        require_once ABSPATH . 'wp-admin/includes/image.php';
    }
    if (!dswoddil_get_attachment_by_post_name('dswoddil-' . $image_name)) {
        $site_icon = get_template_directory() . '/img/' . $image_name . '.png';
        // create $file array with the indexes show below
        $file['name'] = $site_icon;
        $file['type'] = 'image/png';
        // get image size
        $file['size'] = filesize($file['name']);
        $file['tmp_name'] = $image_name . '.png';
        $file['error'] = 1;
        $file_content = file_get_contents($site_icon);
        $upload_image = wp_upload_bits($file['tmp_name'], null, $file_content);
        // Check the type of tile. We'll use this as the 'post_mime_type'.
        $filetype = wp_check_filetype(basename($upload_image['file']), null);
        $attachment = array('guid' => $upload_image['file'], 'post_mime_type' => $filetype['type'], 'post_title' => 'dswoddil-' . $image_name, 'post_content' => '', 'post_status' => 'inherit');
        //insert wordpress attachment of uploaded image to get attachmen ID
        $attachment_id = wp_insert_attachment($attachment, $upload_image['file']);
        //generate attachment thumbnail
        wp_update_attachment_metadata($attachment_id, wp_generate_attachment_metadata($attachment_id, $upload_image['file']));
        add_post_meta($attachment_id, '_wp_attachment_context', $image_name);
    }
}
Example #8
0
 public function import($attachment)
 {
     $saved_image = $this->_return_saved_image($attachment);
     if ($saved_image) {
         return $saved_image;
     }
     // Extract the file name and extension from the url
     $filename = basename($attachment['url']);
     if (function_exists('file_get_contents')) {
         $options = ['http' => ['user_agent' => 'Mozilla/5.0 (X11; Ubuntu; Linux i686 on x86_64; rv:49.0) Gecko/20100101 Firefox/49.0']];
         $context = stream_context_create($options);
         $file_content = file_get_contents($attachment['url'], false, $context);
     } else {
         $file_content = wp_remote_retrieve_body(wp_safe_remote_get($attachment['url']));
     }
     if (empty($file_content)) {
         return false;
     }
     $upload = wp_upload_bits($filename, null, $file_content);
     $post = ['post_title' => $filename, 'guid' => $upload['url']];
     $info = wp_check_filetype($upload['file']);
     if ($info) {
         $post['post_mime_type'] = $info['type'];
     } else {
         // For now just return the origin attachment
         return $attachment;
         //return new \WP_Error( 'attachment_processing_error', __( 'Invalid file type', 'elementor' ) );
     }
     $post_id = wp_insert_attachment($post, $upload['file']);
     wp_update_attachment_metadata($post_id, wp_generate_attachment_metadata($post_id, $upload['file']));
     update_post_meta($post_id, '_elementor_source_image_hash', $this->_get_hash_image($attachment['url']));
     $new_attachment = ['id' => $post_id, 'url' => $upload['url']];
     $this->_replace_image_ids[$attachment['id']] = $new_attachment;
     return $new_attachment;
 }
 function file_import()
 {
     if (wp_verify_nonce($_POST['nonce'], "molie_admin_file")) {
         $post = get_post($_POST['course_post']);
         $file_system = get_post_meta($post->ID, "courseFileSystem", true);
         $file_contents = file_get_contents($_POST['url']);
         file_put_contents($file_system[$_POST['folder']]['actual_path'] . "/" . $_POST['filename'], $file_contents);
         $filetype = wp_check_filetype(basename($file_system[$_POST['folder']]['actual_path'] . "/" . $_POST['filename']), null);
         echo $file_system[$_POST['folder']]['actual_path'] . "/" . $_POST['filename'] . "<br />";
         $attachment = array('guid' => $file_system[$_POST['folder']]['actual_path'] . "/" . $_POST['filename'], 'post_mime_type' => $filetype['type'], 'post_title' => preg_replace('/\\.[^.]+$/', '', basename($_POST['filename'])), 'post_content' => '', 'post_status' => 'inherit');
         $attach_id = wp_insert_attachment($attachment, $file_system[$_POST['folder']]['actual_path'] . "/" . $_POST['filename']);
         $data = wp_generate_attachment_metadata($attach_id, $file_system[$_POST['folder']]['actual_path'] . "/" . $_POST['filename']);
         update_post_meta($attach_id, "_wp_attachment_metadata", $data, true);
         update_post_meta($post->ID, "molie_file_" . $_POST['item'], $attach_id);
         update_post_meta($attach_id, "CanvasCourse", get_post_meta($post->ID, "courseID", true));
         update_post_meta($attach_id, "CanvasFileVerifier", $_POST['verifier']);
         update_post_meta($attach_id, "CanvasCourseIDFileID", get_post_meta($post->ID, "courseID", true) . "," . $_POST['item']);
         $file_url = get_post_meta($post->ID, "courseURL", true) . "/courses/" . get_post_meta($post->ID, "courseID", true) . "/files/" . $_POST['item'] . "/download?verifier=" . $_POST['verifier'];
         update_post_meta($attach_id, "CanvasFileURL", $file_url);
         echo __("File Downloaded");
     } else {
         echo "Nonce failed";
     }
     wp_die();
 }
Example #10
0
 static function add_image($image_url)
 {
     if (empty($image_url)) {
         return FALSE;
     }
     // Add Featured Image to Post
     $upload_dir = wp_upload_dir();
     // Set upload folder
     $image_data = file_get_contents($image_url);
     // Get image data
     $filename = basename($image_url);
     // Create image file name
     // Check folder permission and define file location
     if (wp_mkdir_p($upload_dir['path'])) {
         $file = $upload_dir['path'] . '/' . $filename;
     } else {
         $file = $upload_dir['basedir'] . '/' . $filename;
     }
     // Create the image  file on the server
     file_put_contents($file, $image_data);
     // Check image file type
     $wp_filetype = wp_check_filetype($filename, NULL);
     // Set attachment data
     $attachment = array('post_mime_type' => $wp_filetype['type'], 'post_title' => sanitize_file_name($filename), 'post_content' => '', 'post_status' => 'inherit');
     // Create the attachment
     $attach_id = wp_insert_attachment($attachment, $file);
     // Include image.php
     require_once ABSPATH . 'wp-admin/includes/image.php';
     // Define attachment metadata
     $attach_data = wp_generate_attachment_metadata($attach_id, $file);
     // Assign metadata to attachment
     wp_update_attachment_metadata($attach_id, $attach_data);
     return $attach_id;
 }
function process_attachment($post, $url)
{
    // if the URL is absolute, but does not contain address, then upload it assuming base_site_url
    //if ( preg_match( '|^/[\w\W]+$|', $url ) )
    //	$url = rtrim( $this->base_url, '/' ) . $url;
    global $url_remap;
    $upload = fetch_remote_file($url, $post);
    if (is_wp_error($upload)) {
        return $upload;
    }
    if ($info = wp_check_filetype($upload['file'])) {
        $post['post_mime_type'] = $info['type'];
    } else {
        return new WP_Error('attachment_processing_error', __('Invalid file type', 'wordpress-importer'));
    }
    $post['guid'] = $upload['url'];
    // as per wp-admin/includes/upload.php
    $post_id = wp_insert_attachment($post, $upload['file']);
    wp_update_attachment_metadata($post_id, wp_generate_attachment_metadata($post_id, $upload['file']));
    // remap resized image URLs, works by stripping the extension and remapping the URL stub.
    if (preg_match('!^image/!', $info['type'])) {
        $parts = pathinfo($url);
        $name = basename($parts['basename'], ".{$parts['extension']}");
        // PATHINFO_FILENAME in PHP 5.2
        $parts_new = pathinfo($upload['url']);
        $name_new = basename($parts_new['basename'], ".{$parts_new['extension']}");
        $url_remap[$parts['dirname'] . '/' . $name] = $parts_new['dirname'] . '/' . $name_new;
    }
    return $post_id;
}
 public function wpua_avatar_upload($file)
 {
     $filetype = wp_check_filetype($file->name);
     $media_upload = array();
     $media_upload['file'] = array('name' => $file->name, 'type' => $filetype['type'], 'tmp_name' => $file->path, 'error' => 0, 'size' => filesize($file->path));
     $media_file = wp_handle_upload($media_upload['file'], array('test_form' => false, 'test_upload' => false, 'action' => 'custom_action'));
     if ($media_file['file']) {
         $url = $media_file['url'];
         $filepath = $media_file['file'];
         if ($image_meta = @wp_read_image_metadata($filepath)) {
             if (trim($image_meta['title']) && !is_numeric(sanitize_title($image_meta['title']))) {
                 $title = $image_meta['title'];
             }
         }
         $attachment = array('guid' => $url, 'post_mime_type' => $filetype['type'], 'post_title' => $title);
         $attachment_id = wp_insert_attachment($attachment, $filepath);
         if (!is_wp_error($attachment_id)) {
             $this->delete_attachment_by_user($this->user_id);
             wp_update_attachment_metadata($attachment_id, wp_generate_attachment_metadata($attachment_id, $filepath));
             update_post_meta($attachment_id, '_wp_attachment_wp_user_avatar', $this->user_id);
             $arr = wp_get_attachment_image_src($attachment_id, 'full');
             $this->avatar_url = $arr[0];
             $this->avatar_filename = basename($filepath);
             $this->resource = $attachment_id;
             $saved = $this->save();
             if (!$saved) {
                 $this->delete_attachment($attachment_id);
                 return $saved;
             }
             return $saved;
         }
     } else {
         return WP_Error('file_upload_problem', __("Media avatar could't uploading please check you have right permission for uploads folder.", 'wp-user-avatar-pro'));
     }
 }
Example #13
0
 public function regenerateThumbnails($image_id)
 {
     require_once 'wp-admin/includes/image.php';
     $fullsizepath = get_attached_file($image_id);
     $metadata = wp_generate_attachment_metadata($image_id, $fullsizepath);
     wp_update_attachment_metadata($image_id, $metadata);
 }
Example #14
0
 function atp_plupload_action()
 {
     // check ajax noonce
     $imgid = $_POST["imgid"];
     check_ajax_referer($imgid . 'pluploadan');
     $post_id = isset($_POST['post_id']) ? intval($_POST['post_id']) : 0;
     // handle file upload
     $filename = $_FILES[$imgid . 'async-upload']['name'];
     $status = wp_handle_upload($_FILES[$imgid . 'async-upload'], array('test_form' => true, 'action' => 'plupload_action'));
     if (!isset($status['file'])) {
         continue;
     }
     $file_name = $status['file'];
     $name_parts = pathinfo($file_name);
     $name = trim(substr($filename, 0, -(1 + strlen($name_parts['extension']))));
     $attachment = array('post_mime_type' => $status['type'], 'guid' => $status['url'], 'post_parent' => $post_id, 'post_title' => $name, 'post_content' => '');
     $id = wp_insert_attachment($attachment, $file_name, $post_id);
     if (!is_wp_error($id)) {
         wp_update_attachment_metadata($id, wp_generate_attachment_metadata($id, $file_name));
         $new[] = $id;
     }
     // send the uploaded file url in response
     $upload_path = wp_get_attachment_url($id, true);
     if (preg_match_all('/[^\\?]+\\.(jpg|JPG|jpe|JPE|jpeg|JPEG|gif|GIF|png|PNG)/', $upload_path, $matches)) {
         $image_attributes = wp_get_attachment_image_src($id, 'thumbnail');
         // returns an array
         $uplaod_url = $image_attributes[0];
     } else {
         $uplaod_url = $upload_path;
     }
     $imagetest = array('url' => $status['url'], 'link' => get_edit_post_link($id), 'audioid' => $id, 'name' => $name, 'img' => $uplaod_url);
     echo json_encode($imagetest);
     //print_r ($imagetest);
     exit;
 }
 static function post_attachment($download, $product_id)
 {
     // $filename should be the path to a file in the upload directory.
     // example $filename = 'woocommerce_uploads/2015/07/aka_Matrix42_Tool_CleanDatabase_7.2.1.20150625.aka.zip';
     $download = json_decode($download);
     $filename = $download->file;
     $web_url = $download->web_url;
     $wp_upload_dir = wp_upload_dir();
     $file = $wp_upload_dir['path'] . '/' . $filename;
     //Check the type of file. We'll use this as the 'post_mime_type'.
     $filetype = wp_check_filetype(basename($file), null);
     $attachment = array('guid' => $wp_upload_dir['url'] . '/' . basename($file), 'post_mime_type' => $filetype['type'], 'post_title' => preg_replace('/\\.[^.]+$/', '', basename($file)), 'post_content' => '', 'post_status' => 'inherit');
     // Insert the attachment.
     $attach_id = wp_insert_attachment($attachment, $file, $product_id);
     // 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, $file);
     wp_update_attachment_metadata($attach_id, $attach_data);
     // Get all existing post downloads and
     $files = array();
     $wc_product = wc_get_product($product_id);
     $untyped_array_of_downloads = $wc_product->get_files();
     foreach ($untyped_array_of_downloads as $download_key => $download_value) {
         $download_name = $download_value['name'];
         $download_url = $download_value['file'];
         $files[md5($download_url)] = array('name' => $download_name, 'file' => $download_url);
     }
     // Extend the existing post downloads by the new one
     $files[md5($download_url)] = array('name' => $filename, 'file' => $web_url);
     // Update post meta (_downloadable_files)
     update_post_meta($product_id, '_downloadable_files', $files);
     return 1;
 }
 /**
  * Upload an image via plupload.
  *
  * @return
  */
 function charitable_plupload_image_upload()
 {
     $post_id = (int) filter_input(INPUT_POST, 'post_id', FILTER_SANITIZE_NUMBER_INT);
     $field_id = (string) filter_input(INPUT_POST, 'field_id');
     check_ajax_referer('charitable-upload-images-' . $field_id);
     $file = $_FILES['async-upload'];
     $file_attr = wp_handle_upload($file, array('test_form' => false));
     if (isset($file_attr['error'])) {
         wp_send_json_error($file_attr);
     }
     $attachment = array('guid' => $file_attr['url'], 'post_mime_type' => $file_attr['type'], 'post_title' => preg_replace('/\\.[^.]+$/', '', basename($file['name'])), 'post_content' => '', 'post_status' => 'inherit');
     /**
      * Insert the file as an attachment.
      */
     $attachment_id = wp_insert_attachment($attachment, $file_attr['file'], $post_id);
     if (is_wp_error($attachment_id)) {
         wp_send_json_error();
     }
     wp_update_attachment_metadata($attachment_id, wp_generate_attachment_metadata($attachment_id, $file_attr['file']));
     $size = (string) filter_input(INPUT_POST, 'size');
     $max_uploads = (int) filter_input(INPUT_POST, 'max_uploads', FILTER_SANITIZE_NUMBER_INT);
     if (!$size) {
         $size = 'thumbnail';
     }
     ob_start();
     charitable_template('form-fields/picture-preview.php', array('image' => $attachment_id, 'field' => array('key' => $field_id, 'size' => $size, 'max_uploads' => $max_uploads)));
     wp_send_json_success(ob_get_clean());
 }
 /**
  * From regenerate thumbnails plugin
  */
 public function regenerate_thumbnail()
 {
     @error_reporting(0);
     // Don't break the JSON result
     header('Content-type: application/json');
     $id = (int) $_REQUEST['id'];
     $image = get_post($id);
     if (!$image || 'attachment' != $image->post_type || 'image/' != substr($image->post_mime_type, 0, 6)) {
         die(json_encode(array('error' => sprintf(__('Failed resize: %s is an invalid image ID.', 'wc_csv_import'), esc_html($_REQUEST['id'])))));
     }
     if (!current_user_can('manage_woocommerce')) {
         $this->die_json_error_msg($image->ID, __("Your user account doesn't have permission to resize images", 'wc_csv_import'));
     }
     $fullsizepath = get_attached_file($image->ID);
     if (false === $fullsizepath || !file_exists($fullsizepath)) {
         $this->die_json_error_msg($image->ID, sprintf(__('The originally uploaded image file cannot be found at %s', 'wc_csv_import'), '<code>' . esc_html($fullsizepath) . '</code>'));
     }
     @set_time_limit(900);
     // 5 minutes per image should be PLENTY
     $metadata = wp_generate_attachment_metadata($image->ID, $fullsizepath);
     if (is_wp_error($metadata)) {
         $this->die_json_error_msg($image->ID, $metadata->get_error_message());
     }
     if (empty($metadata)) {
         $this->die_json_error_msg($image->ID, __('Unknown failure reason.', 'wc_csv_import'));
     }
     // If this fails, then it just means that nothing was changed (old value == new value)
     wp_update_attachment_metadata($image->ID, $metadata);
     die(json_encode(array('success' => sprintf(__('&quot;%1$s&quot; (ID %2$s) was successfully resized in %3$s seconds.', 'wc_csv_import'), esc_html(get_the_title($image->ID)), $image->ID, timer_stop()))));
 }
Example #18
0
 /**
  * Upload
  * Ajax callback function
  *
  * @return error or (XML-)response
  */
 static function handle_upload()
 {
     header('Content-Type: text/html; charset=UTF-8');
     if (!defined('DOING_AJAX')) {
         define('DOING_AJAX', true);
     }
     check_ajax_referer('plupload_image');
     $post_id = 0;
     if (is_numeric($_REQUEST['post_id'])) {
         $post_id = (int) $_REQUEST['post_id'];
     }
     // you can use WP's wp_handle_upload() function:
     $file = $_FILES['async-upload'];
     $file_attr = wp_handle_upload($file, array('test_form' => true, 'action' => 'plupload_image_upload'));
     $attachment = array('post_mime_type' => $file_attr['type'], 'post_title' => preg_replace('/\\.[^.]+$/', '', basename($file['name'])), 'post_content' => '', 'post_status' => 'inherit');
     // Adds file as attachment to WordPress
     $id = wp_insert_attachment($attachment, $file_attr['file'], $post_id);
     if (!is_wp_error($id)) {
         $response = new WP_Ajax_Response();
         wp_update_attachment_metadata($id, wp_generate_attachment_metadata($id, $file_attr['file']));
         if (isset($_REQUEST['field_id'])) {
             // Save file ID in meta field
             add_post_meta($post_id, $_REQUEST['field_id'], $id, false);
         }
         $response->add(array('what' => 'rwmb_image_response', 'data' => self::img_html($id)));
         $response->send();
     }
     // faster than die();
     exit;
 }
Example #19
0
 /**
  * Upload
  * Ajax callback function
  *
  * @return string Error or (XML-)response
  */
 static function handle_upload()
 {
     global $wpdb;
     $post_id = isset($_REQUEST['post_id']) ? intval($_REQUEST['post_id']) : 0;
     $field_id = isset($_REQUEST['field_id']) ? $_REQUEST['field_id'] : '';
     check_ajax_referer("rwmb-upload-images_{$field_id}");
     // You can use WP's wp_handle_upload() function:
     $file = $_FILES['async-upload'];
     $file_attr = wp_handle_upload($file, array('test_form' => false));
     //Get next menu_order
     $meta = get_post_meta($post_id, $field_id, false);
     if (empty($meta)) {
         $next = 0;
     } else {
         $meta = implode(',', (array) $meta);
         $max = $wpdb->get_var("\n\t\t\t\t\tSELECT MAX(menu_order) FROM {$wpdb->posts}\n\t\t\t\t\tWHERE post_type = 'attachment'\n\t\t\t\t\tAND ID in ({$meta})\n\t\t\t\t");
         $next = is_numeric($max) ? (int) $max + 1 : 0;
     }
     $attachment = array('guid' => $file_attr['url'], 'post_mime_type' => $file_attr['type'], 'post_title' => preg_replace('/\\.[^.]+$/', '', basename($file['name'])), 'post_content' => '', 'post_status' => 'inherit', 'menu_order' => $next);
     // Adds file as attachment to WordPress
     $id = wp_insert_attachment($attachment, $file_attr['file'], $post_id);
     if (!is_wp_error($id)) {
         wp_update_attachment_metadata($id, wp_generate_attachment_metadata($id, $file_attr['file']));
         // Save file ID in meta field
         add_post_meta($post_id, $field_id, $id, false);
         wp_send_json_success(self::img_html($id));
     }
     exit;
 }
 public function do_save($return_val, $data, $module)
 {
     if (empty($data['attachment_url'])) {
         return false;
     }
     $bits = file_get_contents($data['attachment_url']);
     $filename = $this->faker->uuid() . '.jpg';
     $upload = wp_upload_bits($filename, null, $bits);
     $data['guid'] = $upload['url'];
     $data['post_mime_type'] = 'image/jpeg';
     // Insert the attachment.
     $attach_id = wp_insert_attachment($data, $upload['file'], 0);
     if (!is_numeric($attach_id)) {
         return false;
     }
     if (!function_exists('wp_generate_attachment_metadata')) {
         // 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.
     update_post_meta($attach_id, '_wp_attachment_metadata', wp_generate_attachment_metadata($attach_id, $upload['file']));
     // Flag the Object as FakerPress
     update_post_meta($attach_id, self::$flag, 1);
     return $attach_id;
 }
	function _make_attachment( $upload, $parent_post_id = 0 ) {

		$type = '';
		if ( !empty($upload['type']) ) {
			$type = $upload['type'];
		} else {
			$mime = wp_check_filetype( $upload['file'] );
			if ($mime)
				$type = $mime['type'];
		}

		$attachment = array(
			'post_title' => basename( $upload['file'] ),
			'post_content' => '',
			'post_type' => 'attachment',
			'post_parent' => $parent_post_id,
			'post_mime_type' => $type,
			'guid' => $upload[ 'url' ],
		);

		// Save the data
		$id = wp_insert_attachment( $attachment, $upload[ 'file' ], $parent_post_id );
		wp_update_attachment_metadata( $id, wp_generate_attachment_metadata( $id, $upload['file'] ) );

		return $this->ids[] = $id;

	}
Example #22
0
 /**
  * Generates a new attachemnt.
  *
  * @since 1.0.0
  *
  * @access protected
  * @param array $args The array of arguments to use during a new attachment creation.
  * @return int The newly created attachment's ID on success, otherwise 0.
  */
 protected function _createObject($args = array())
 {
     if (empty($args['post_mime_type'])) {
         if (!empty($args['file']) && is_readable($args['file'])) {
             $this->_debug('Reading mime type of the file: ' . $args['file']);
             $filetype = wp_check_filetype(basename($args['file']), null);
             if (!empty($filetype['type'])) {
                 $args['post_mime_type'] = $filetype['type'];
                 $this->_debug('Mime type found: ' . $filetype['type']);
             } else {
                 $this->_debug('Mime type not found');
             }
         }
     }
     $attachment_id = wp_insert_attachment($args);
     if ($attachment_id) {
         $this->_debug('Generated attachment ID: %d (file: %s)', $attachment_id, !empty($args['file']) ? $args['file'] : 'not-provided');
         $this->_debug('Generating attachment metadata');
         $metadata = wp_generate_attachment_metadata($attachment_id, $args['file']);
         if (is_wp_error($metadata)) {
             $this->_debug('Attachment metadata generation failed with error [%s] %s', $metadata->get_error_code(), $metadata->get_error_message());
         } elseif (empty($metadata)) {
             $this->_debug('Attachment metadata generation failed');
         } else {
             wp_update_attachment_metadata($attachment_id, $metadata);
         }
     } else {
         $this->_debug('Attachment generation failed');
     }
     return $attachment_id;
 }
 /**
  * Rebuild the attachment metadata for an attachment
  *
  * @param mixed $attachment
  *
  * @return bool
  */
 protected function upgrade_item($attachment)
 {
     $s3object = unserialize($attachment->s3object);
     if (false === $s3object) {
         AS3CF_Error::log('Failed to unserialize S3 meta for attachment ' . $attachment->ID . ': ' . $attachment->s3object);
         $this->error_count++;
         return false;
     }
     $file = get_attached_file($attachment->ID, true);
     if (!file_exists($file)) {
         // Copy back the file to the server if doesn't exist so we can successfully
         // regenerate the attachment metadata
         try {
             $args = array('Bucket' => $s3object['bucket'], 'Key' => $s3object['key'], 'SaveAs' => $file);
             $this->as3cf->get_s3client($s3object['region'], true)->getObject($args);
         } catch (Exception $e) {
             AS3CF_Error::log(sprintf(__('There was an error attempting to download the file %s from S3: %s', 'amazon-s3-and-cloudfront'), $s3object['key'], $e->getMessage()));
             return false;
         }
     }
     // Remove corrupted meta
     delete_post_meta($attachment->ID, '_wp_attachment_metadata');
     require_once ABSPATH . '/wp-admin/includes/image.php';
     // Generate new attachment meta
     wp_update_attachment_metadata($attachment->ID, wp_generate_attachment_metadata($attachment->ID, $file));
     return true;
 }
 /**
  * Helper function: insert an attachment to test properties of.
  *
  * @param int $parent_post_id
  * @param str path to image to use
  * @param array $post_fields Fields, in the format to be sent to `wp_insert_post()`
  * @return int Post ID of inserted attachment
  */
 private function insert_attachment($parent_post_id = 0, $image = null, $post_fields = array())
 {
     $filename = rand_str() . '.jpg';
     $contents = rand_str();
     if ($image) {
         // @codingStandardsIgnoreStart
         $filename = basename($image);
         $contents = file_get_contents($image);
         // @codingStandardsIgnoreEnd
     }
     $upload = wp_upload_bits($filename, null, $contents);
     $this->assertTrue(empty($upload['error']));
     $type = '';
     if (!empty($upload['type'])) {
         $type = $upload['type'];
     } else {
         $mime = wp_check_filetype($upload['file']);
         if ($mime) {
             $type = $mime['type'];
         }
     }
     $attachment = wp_parse_args($post_fields, array('post_title' => basename($upload['file']), 'post_content' => 'Test Attachment', 'post_type' => 'attachment', 'post_parent' => $parent_post_id, 'post_mime_type' => $type, 'guid' => $upload['url']));
     // Save the data
     $id = wp_insert_attachment($attachment, $upload['file'], $parent_post_id);
     wp_update_attachment_metadata($id, wp_generate_attachment_metadata($id, $upload['file']));
     return $id;
 }
 /**
  * Run the converter now
  *
  * @since 1.0
  *
  * @param array $args can be extension
  * @param array $vars
  */
 function update_attachments($args = array(), $vars = array())
 {
     $images = Tiff_Converter::get_images();
     $mime_type = 'image/jpg';
     // Maybe $args[0] for changing it
     if ($images) {
         $succeed = $failed = 0;
         foreach ($images as $image) {
             $file = get_attached_file($image->ID);
             $result = Tiff_Converter_Handle::convert_image($file, $mime_type);
             if (!is_wp_error($result)) {
                 $update_args = array('ID' => $image->ID, 'post_mime_type' => $result['mime-type']);
                 $result2 = wp_update_post($update_args, true);
                 if ($result2 && !is_wp_error($result2)) {
                     unlink($file);
                     update_attached_file($image->ID, $result['path']);
                     wp_update_attachment_metadata($image->ID, wp_generate_attachment_metadata($image->ID, $result['path']));
                     $succeed++;
                 } else {
                     unlink($result['path']);
                     $failed++;
                 }
             } else {
                 $failed++;
             }
         }
         WP_CLI::success(sprintf('%d images are converted and %s failed', $succeed, $failed));
     } else {
         WP_CLI::success('No images to convert');
     }
 }
 static function uploadImage($img_url)
 {
     include_once ABSPATH . 'wp-admin/includes/file.php';
     //Contains download_url
     //Download $img_url
     $temporary_file = download_url($img_url);
     if (is_wp_error($temporary_file)) {
         throw new Exception('Error: ' . $temporary_file->get_error_message());
     } else {
         $upload_dir = wp_upload_dir();
         $local_img_path = $upload_dir['path'] . DIRECTORY_SEPARATOR . basename($img_url);
         //Local name
         $local_img_url = $upload_dir['url'] . '/' . basename($img_url);
         $moved = @rename($temporary_file, $local_img_path);
         if ($moved) {
             $wp_filetype = wp_check_filetype(basename($img_url), null);
             //Get the filetype to set the mimetype
             $attachment = array('post_mime_type' => $wp_filetype['type'], 'post_title' => preg_replace('/\\.[^.]+$/', '', basename($img_url)), 'post_content' => '', 'post_status' => 'inherit');
             $attach_id = wp_insert_attachment($attachment, $local_img_path);
             //Insert the image in the database
             require_once ABSPATH . 'wp-admin/includes/image.php';
             $attach_data = wp_generate_attachment_metadata($attach_id, $local_img_path);
             wp_update_attachment_metadata($attach_id, $attach_data);
             //Update generated metadata
             return array('id' => $attach_id, 'url' => $local_img_url);
         }
     }
     if (file_exists($temporary_file)) {
         unlink($temporary_file);
     }
     return null;
 }
Example #27
0
 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;
 }
 function media_added($post_id)
 {
     $post = get_post($post_id);
     $linked = get_post_meta($post->post_parent, "CanvasLinked", true);
     if ($linked == 1) {
         if (get_post_meta($post_id, "CanvasCourseIDFileID", true) == "") {
             $course_id = get_post_meta($post->post_parent, "CanvasCourse", true);
             global $wpdb;
             $course_post = $wpdb->get_results("select post_id from " . $wpdb->prefix . "postmeta where meta_key='CourseID' and meta_value = '" . $course_id . "'");
             $course_post = get_post($course_post[0]->post_id);
             $file_system = get_post_meta($course_post->ID, "courseFileSystem", true);
             foreach ($file_system as $folder_id => $file_data) {
                 if (strpos($file_data['actual_path'], $course_id . "/course files/") === FALSE) {
                     $folder = $folder_id;
                     $actual_path = $file_data['actual_path'];
                 }
             }
             $file = get_attached_file($post_id);
             $parts = explode("/", $file);
             $new_name = $actual_path . "/" . array_pop($parts);
             rename($file, $new_name);
             $dir = wp_upload_dir();
             $change_path = str_replace("\\", "/", $dir['basedir']) . "/";
             $new_path = str_replace($change_path, "", $new_name);
             $data = wp_generate_attachment_metadata($post_id, $new_name);
             update_post_meta($post_id, "_wp_attached_file", $new_path);
             update_post_meta($post_id, "_wp_attachment_metadata", $data, true);
             require_once __DIR__ . "/../../API/Psr4AutoloaderClass.php";
             $loader = new Psr4AutoloaderClass();
             $loader->register();
             $loader->addNamespace('InstructureCanvasAPI', __DIR__ . "/../../API/InstructureCanvasAPI/src");
             $API = new InstructureCanvasAPI\InstructureCanvasAPI(array("site" => get_post_meta($course_post->ID, "courseURL", true), "token" => get_post_meta($course_post->ID, "courseToken", true), "webService" => "CURL"));
             $files = new InstructureCanvasAPI\Courses\Files\Files();
             $files->setAPI($API);
             $files->setCourseID($course_id);
             $parts = explode("/", $post->guid);
             $name = array_pop($parts);
             $data = $files->requestUpload(array("name" => $name, "content_type" => $post->post_mime_type, "parent_folder_id" => $folder));
             $file_data = array("file" => $change_path . $new_path);
             $file_data = $files->upload($data->content->upload_url, $data->content->upload_params, $file_data);
             $header_parts = explode("\n", $file_data->header);
             foreach ($header_parts as $part) {
                 if (strpos($part, "Location:") !== FALSE) {
                     $confirm_url = trim(substr($part, strpos($part, ":") + 1));
                 }
             }
             $confirm_data = $files->confirm($confirm_url);
             $parts = explode("verifier=", $confirm_data->content->url);
             $verifier = array_pop($parts);
             update_post_meta($course_post->ID, "molie_file_" . $confirm_data->content->id, $post_id);
             update_post_meta($post_id, "CanvasCourse", $course_id);
             update_post_meta($post_id, "CanvasFileVerifier", $verifier);
             update_post_meta($post_id, "CanvasCourseIDFileID", $course_id . "," . $_POST['item']);
             update_post_meta($post_id, "CanvasFileURL", $confirm_data->content->url);
         }
     }
 }
 public static function add(array $DATA_ = NULL)
 {
     $url = $DATA_['uri'];
     $name = @$DATA_['name'];
     $post_id = @$DATA_['post_id'];
     apply_filters('em_object_get_image_type', 'event', false, isset($this) ? $this : self);
     //Handle the attachment as a WP Post
     $attachment = '';
     $tmpfname = tempnam(ESS_IO::tmp(), "ESS_IMG_" . $post_id . "_");
     $h = fopen($tmpfname, "w");
     if ($h && strlen($url) > 5) {
         fwrite($h, file_get_contents($url));
         $image_ = getimagesize($tmpfname);
         switch ($image_['mime']) {
             case "image/gif":
                 $mime = "gif";
                 break;
             case "image/jpeg":
                 $mime = "jpg";
                 break;
             case "image/png":
                 $mime = "png";
                 break;
             case "image/bmp":
                 $mime = "bmp";
                 break;
         }
         $file = array('tmp_name' => $tmpfname, 'name' => basename($tmpfname), 'type' => $image_[2], 'mime' => $mime, 'width' => $image_[0], 'height' => $image_[1], 'size' => filesize($tmpfname), 'error' => 0);
         //var_dump( $file );
         if (file_exists($file['tmp_name']) && ESS_Images::image_validator($file)) {
             require_once ABSPATH . "wp-admin" . '/includes/file.php';
             require_once ABSPATH . "wp-admin" . '/includes/image.php';
             $attachment = ESS_Images::handle_upload($file);
             if ($attachment) {
                 //echo "DEBUG: <b>". __CLASS__.":".__LINE__."</b>";
                 //var_dump( $attachment );
                 $attachment_id = wp_insert_attachment(array('post_mime_type' => $image_['mime'], 'post_title' => $name, 'post_content' => '', 'post_status' => 'inherit'), $attachment['file'], $post_id);
                 $attachment_metadata = wp_generate_attachment_metadata($attachment_id, $attachment['file']);
                 wp_update_attachment_metadata($attachment_id, $attachment_metadata);
                 update_post_meta($post_id, '_thumbnail_id', $attachment_id);
                 update_post_meta($post_id, '_start_ts', date('U'));
                 update_post_meta($post_id, '_end_ts', intval(date('U') + 60 * 60 * 24 * 365));
                 @fclose($h);
                 if (file_exists($tmpfname)) {
                     @unlink($tmpfname);
                 }
                 return apply_filters('em_object_image_upload', $attachment_id, $this);
             }
         }
         @fclose($h);
         if (file_exists($tmpfname)) {
             @unlink($tmpfname);
         }
     }
     return apply_filters('em_object_image_upload', false, $this);
 }
 public function generate_intermediate_images($attachment)
 {
     $attachment_id = $attachment->ID;
     $file = get_attached_file($attachment_id);
     FW_Backup_Image_Recovery::$attachment_id = $attachment_id;
     if (file_exists($file)) {
         $metadata = wp_generate_attachment_metadata($attachment_id, $file);
         wp_update_attachment_metadata($attachment_id, $metadata);
     }
 }