Example #1
0
function image_downsize($id, $size = 'medium')
{
    if (!wp_attachment_is_image($id)) {
        return false;
    }
    $img_url = wp_get_attachment_url($id);
    $meta = wp_get_attachment_metadata($id);
    $width = $height = 0;
    // plugins can use this to provide resize services
    if ($out = apply_filters('image_downsize', false, $id, $size)) {
        return $out;
    }
    // try for a new style intermediate size
    if ($intermediate = image_get_intermediate_size($id, $size)) {
        $img_url = str_replace(basename($img_url), $intermediate['file'], $img_url);
        $width = $intermediate['width'];
        $height = $intermediate['height'];
    } elseif ($size == 'thumbnail') {
        // fall back to the old thumbnail
        if (($thumb_file = wp_get_attachment_thumb_file($id)) && ($info = getimagesize($thumb_file))) {
            $img_url = str_replace(basename($img_url), basename($thumb_file), $img_url);
            $width = $info[0];
            $height = $info[1];
        }
    }
    if (!$width && !$height && isset($meta['width'], $meta['height'])) {
        // any other type: use the real image and constrain it
        list($width, $height) = image_constrain_size_for_editor($meta['width'], $meta['height'], $size);
    }
    if ($img_url) {
        return array($img_url, $width, $height);
    }
    return false;
}
 function downsize($out, $id, $size)
 {
     $img_url = wp_get_attachment_url($id);
     $img_path = get_attached_file($id);
     $meta = wp_get_attachment_metadata($id);
     $width = $height = 0;
     $is_intermediate = false;
     $img_url_basename = wp_basename($img_url);
     $img_path_basename = wp_basename($img_path);
     // extract filter from size request
     if (!is_string($size)) {
         return $out;
     }
     $size_bits = explode(':', $size);
     $filter = isset($size_bits[1]) ? $size_bits[1] : false;
     $size = isset($size_bits[0]) ? $size_bits[0] : false;
     // start the reactor
     if ($filter) {
         // try for a new style intermediate size
         if ($intermediate = image_get_intermediate_size($id, $size)) {
             $img_url = str_replace($img_url_basename, $intermediate['file'], $img_url);
             $img_path = str_replace($img_path_basename, $intermediate['file'], $img_path);
             $width = $intermediate['width'];
             $height = $intermediate['height'];
             $is_intermediate = true;
         } elseif ($size == 'thumbnail') {
             // fall back to the old thumbnail
             if (($thumb_file = wp_get_attachment_thumb_file($id)) && ($info = getimagesize($thumb_file))) {
                 $img_url = str_replace($img_url_basename, wp_basename($thumb_file), $img_url);
                 $img_path = str_replace($img_path_basename, wp_basename($thumb_file), $img_path);
                 $width = $info[0];
                 $height = $info[1];
                 $is_intermediate = true;
             }
         }
         if (!$width && !$height && isset($meta['width'], $meta['height'])) {
             // any other type: use the real image
             $width = $meta['width'];
             $height = $meta['height'];
         }
         if ($img_url && $img_path) {
             $input = $img_path;
             $output = $this->filtered_url($input, $filter);
             // generate filtered thumb
             if (!file_exists($output)) {
                 $this->filter($filter, $input, $output);
             }
             // point to our new file
             $img_url = $this->filtered_url($img_url, $filter);
             // we have the actual image size, but might need to further constrain it if content_width is narrower
             list($width, $height) = image_constrain_size_for_editor($width, $height, $size);
             return array($img_url, $width, $height, $is_intermediate);
         }
         // don't continue the downsize funtion
         return true;
     }
     return $out;
 }
 public function image_downsize($out, $id, $size)
 {
     // we don't handle this
     if (is_array($size)) {
         return false;
     }
     $meta = wp_get_attachment_metadata($id);
     $wanted_width = $wanted_height = 0;
     if (empty($meta['file'])) {
         return false;
     }
     // get $size dimensions
     global $_wp_additional_image_sizes;
     if (isset($_wp_additional_image_sizes) && isset($_wp_additional_image_sizes[$size])) {
         $wanted_width = $_wp_additional_image_sizes[$size]['width'];
         $wanted_height = $_wp_additional_image_sizes[$size]['height'];
         $wanted_crop = isset($_wp_additional_image_sizes[$size]['crop']) ? $_wp_additional_image_sizes[$size]['crop'] : false;
     } else {
         if (in_array($size, array('thumbnail', 'medium', 'large'))) {
             $wanted_width = get_option($size . '_size_w');
             $wanted_height = get_option($size . '_size_h');
             $wanted_crop = 'thumbnail' === $size ? (bool) get_option('thumbnail_crop') : false;
         } else {
             // unknown size, bail out
             return false;
         }
     }
     if (0 === absint($wanted_width) && 0 === absint($wanted_height)) {
         return false;
     }
     if ($intermediate = image_get_intermediate_size($id, $size)) {
         return false;
     } else {
         // image size not found, create it
         $attachment_path = get_attached_file($id);
         $image_editor = wp_get_image_editor($attachment_path);
         if (!is_wp_error($image_editor)) {
             $image_editor->resize($wanted_width, $wanted_height, $wanted_crop);
             $result_image_size = $image_editor->get_size();
             $result_width = $result_image_size['width'];
             $result_height = $result_image_size['height'];
             $suffix = $result_width . 'x' . $result_height;
             $filename = $image_editor->generate_filename($suffix);
             $image_editor->save($filename);
             $meta['sizes'][$size] = array('file' => basename($filename), 'width' => $result_width, 'height' => $result_height, 'mime-type' => get_post_mime_type($id));
             wp_update_attachment_metadata($id, $meta);
         } else {
             return false;
         }
     }
     return false;
 }
Example #4
0
 function swift_delete_attachment($post_id)
 {
     if (!$this->swift_plugin_setup()) {
         return;
     }
     $backup_sizes = get_post_meta($post_id, '_wp_attachment_backup_sizes', true);
     $intermediate_sizes = array();
     foreach (get_intermediate_image_sizes() as $size) {
         if ($intermediate = image_get_intermediate_size($post_id, $size)) {
             $intermediate_sizes[] = $intermediate;
         }
     }
     if (!($swiftObject = $this->swift_get_attachment_info($post_id))) {
         return;
     }
     $swift_path = dirname($swiftObject['key']);
     $objects = array();
     // remove intermediate and backup images if there are any
     foreach ($intermediate_sizes as $intermediate) {
         $objects[] = array('Key' => path_join($swift_path, $intermediate['file']));
     }
     if (is_array($backup_sizes)) {
         foreach ($backup_sizes as $size) {
             $objects[] = array('Key' => $swift_path);
         }
     }
     // Try removing any @2x images but ignore any errors
     if ($objects) {
         $hidpi_images = array();
         foreach ($objects as $object) {
             $hidpi_images[] = array('Key' => $this->swift_get_hidpi_file_path($object['Key']));
         }
         try {
             foreach ($hidpi_images as $image) {
                 $this->swift_get_client()->getContainer($swiftObject['bucket'])->getObject($image['Key'])->delete();
             }
         } catch (Exception $e) {
         }
     }
     $objects[] = array('Key' => $swiftObject['key']);
     try {
         foreach ($objects as $object) {
             $this->swift_get_client()->getContainer($swiftObject['bucket'])->getObject($object['Key'])->delete();
         }
     } catch (Exception $e) {
         error_log('Error removing files from Swift: ' . $e->getMessage());
         return;
     }
     delete_post_meta($post_id, 'swift_info');
 }
Example #5
0
 function add_post_featured_image_as_rss_item_enclosure()
 {
     if (!has_post_thumbnail()) {
         return;
     }
     $thumbnail_size = apply_filters('rss_enclosure_image_size', 'thumbnail');
     $thumbnail_id = get_post_thumbnail_id(get_the_ID());
     $thumbnail = image_get_intermediate_size($thumbnail_id, $thumbnail_size);
     if (empty($thumbnail)) {
         return;
     }
     $upload_dir = wp_upload_dir();
     printf('<enclosure url="%s" length="%s" type="%s" />', $thumbnail['url'], filesize(path_join($upload_dir['basedir'], $thumbnail['path'])), get_post_mime_type($thumbnail_id));
 }
Example #6
0
File: Upload.php Project: EMRL/fire
 public function filePath($size = null)
 {
     if ($this->isImage() and !is_null($size)) {
         if ($size === 'thumb') {
             $size = 'thumbnail';
         }
         $base = wp_upload_dir();
         $data = image_get_intermediate_size($this->id(), $size);
         $path = isset($data['path']) ? $base['basedir'] . '/' . $data['path'] : null;
     } else {
         $path = get_attached_file($this->id(), true);
     }
     return $path;
 }
Example #7
0
 function delete_attachment($post_id)
 {
     if (!$this->is_plugin_setup()) {
         return;
     }
     $backup_sizes = get_post_meta($post_id, '_wp_attachment_backup_sizes', true);
     $intermediate_sizes = array();
     foreach (get_intermediate_image_sizes() as $size) {
         if ($intermediate = image_get_intermediate_size($post_id, $size)) {
             $intermediate_sizes[] = $intermediate;
         }
     }
     if (!($dsobject = $this->get_attachment_dreamspeed_info($post_id))) {
         return;
     }
     $amazon_path = dirname($dsobject['key']);
     $objects = array();
     // remove intermediate and backup images if there are any
     foreach ($intermediate_sizes as $intermediate) {
         $objects[] = array('Key' => path_join($amazon_path, $intermediate['file']));
     }
     if (is_array($backup_sizes)) {
         foreach ($backup_sizes as $size) {
             $objects[] = array('Key' => path_join($amazon_path, $del_file));
         }
     }
     // Try removing any @2x images but ignore any errors
     if ($objects) {
         $hidpi_images = array();
         foreach ($objects as $object) {
             $hidpi_images[] = array('Key' => $this->get_hidpi_file_path($object['Key']));
         }
         try {
             $this->get_doclient()->deleteObjects(array('Bucket' => $dsobject['bucket'], 'Objects' => $hidpi_images));
         } catch (Exception $e) {
         }
     }
     $objects[] = array('Key' => $dsobject['key']);
     try {
         $this->get_doclient()->deleteObjects(array('Bucket' => $dsobject['bucket'], 'Objects' => $objects));
     } catch (Exception $e) {
         error_log('Error removing files from DreamSpeed: ' . $e->getMessage());
         return;
     }
     delete_post_meta($post_id, 'amazonS3_info');
 }
Example #8
0
 function wpsc_product_image($attachment_id = 0, $width = null, $height = null)
 {
     $uploads = wp_upload_dir();
     // Do some dancing around the image size
     if ($width >= 10 && $height >= 10 && ($width <= 1024 && $height <= 1024)) {
         $intermediate_size = "wpsc-{$width}x{$height}";
     }
     // Get image url if we have enough info
     if ($attachment_id > 0 && !empty($intermediate_size)) {
         // Get all the required information about the attachment
         $image_meta = get_post_meta($attachment_id, '');
         $file_path = get_attached_file($attachment_id);
         // Clean up the meta array
         foreach ($image_meta as $meta_name => $meta_value) {
             $image_meta[$meta_name] = maybe_unserialize(array_pop($meta_value));
         }
         $attachment_metadata = $image_meta['_wp_attachment_metadata'];
         // Determine if we already have an image of this size
         if (isset($attachment_metadata['sizes']) && count($attachment_metadata['sizes']) > 0 && isset($attachment_metadata['sizes'][$intermediate_size])) {
             $intermediate_image_data = image_get_intermediate_size($attachment_id, $intermediate_size);
             $image_url = $intermediate_image_data['url'];
         } else {
             $image_url = home_url("index.php?wpsc_action=scale_image&attachment_id={$attachment_id}&width={$width}&height={$height}");
         }
         // Not enough info so attempt to fallback
     } else {
         if (!empty($attachment_id)) {
             $image_url = home_url("index.php?wpsc_action=scale_image&attachment_id={$attachment_id}&width={$width}&height={$height}");
         } else {
             $image_url = false;
         }
     }
     if (empty($image_url) && !empty($file_path)) {
         $image_meta = get_post_meta($attachment_id, '_wp_attached_file');
         if (!empty($image_meta)) {
             $image_url = $uploads['baseurl'] . '/' . $image_meta[0];
         }
     }
     if (is_ssl()) {
         str_replace('http://', 'https://', $image_url);
     }
     return apply_filters('wpsc_product_image', $image_url);
 }
/**
 * Uses WordPress filter for image_downsize, kill wp-image-dimension
 * code by Andrew Rickmann
 * http://www.wp-fun.co.uk/
 * @param $value, $id, $size
 */
function __wp_supercustom_cms_image_downsize($value = FALSE, $id = 0, $size = 'medium')
{
    if (!wp_attachment_is_image($id)) {
        return FALSE;
    }
    $img_url = wp_get_attachment_url($id);
    // Mimic functionality in image_downsize function in wp-includes/media.php
    if ($intermediate = image_get_intermediate_size($id, $size)) {
        $img_url = str_replace(basename($img_url), $intermediate['file'], $img_url);
    } elseif ($size == 'thumbnail') {
        // fall back to the old thumbnail
        if ($thumb_file = wp_get_attachment_thumb_file() && ($info = getimagesize($thumb_file))) {
            $img_url = str_replace(basename($img_url), basename($thumb_file), $img_url);
        }
    }
    if ($img_url) {
        return array($img_url, 0, 0);
    }
    return FALSE;
}
Example #10
0
/**
 * Get Image Source.
 *
 * Return a uri to a custom image size.
 *
 * If size doesn't exist, attempt to create a resized version.
 * The output of this function should be escaped before printing to the browser.
 *
 * @param     int       Image ID.
 * @return    string    URI of custom image on success; emtpy string otherwise.
 *
 * @access    private.
 * @since     2010-10-28
 */
function taxonomy_image_plugin_get_image_src($id)
{
    $detail = taxonomy_image_plugin_detail_image_size();
    /* Return url to custom intermediate size if it exists. */
    $img = image_get_intermediate_size($id, $detail['name']);
    if (isset($img['url'])) {
        return $img['url'];
    }
    /* Detail image does not exist, attempt to create it. */
    $wp_upload_dir = wp_upload_dir();
    if (isset($wp_upload_dir['basedir'])) {
        /* Create path to original uploaded image. */
        $path = trailingslashit($wp_upload_dir['basedir']) . get_post_meta($id, '_wp_attached_file', true);
        if (is_file($path)) {
            /* Attempt to create a new downsized version of the original image. */
            $new = image_resize($path, $detail['size'][0], $detail['size'][1], $detail['size'][2]);
            /* Image creation successful. Generate and cache image metadata. Return url. */
            if (!is_wp_error($new)) {
                $meta = wp_generate_attachment_metadata($id, $path);
                wp_update_attachment_metadata($id, $meta);
                $img = image_get_intermediate_size($id, $detail['name']);
                if (isset($img['url'])) {
                    return $img['url'];
                }
            }
        }
    }
    /* Custom intermediate size cannot be created, try for thumbnail. */
    $img = image_get_intermediate_size($id, 'thumbnail');
    if (isset($img['url'])) {
        return $img['url'];
    }
    /* Thumbnail cannot be found, try fullsize. */
    $url = wp_get_attachment_url($id);
    if (!empty($url)) {
        return $url;
    }
    /**
     * No image can be found.
     * This is most likely caused by a user deleting an attachment before deleting it's association with a taxonomy.
     * If we are in the administration panels:
     * - Delete the association.
     * - Return uri to default.png.
     */
    if (is_admin()) {
        $assoc = taxonomy_image_plugin_get_associations();
        foreach ($assoc as $term => $img) {
            if ($img === $id) {
                unset($assoc[$term]);
            }
        }
        update_option('taxonomy_image_plugin', $assoc);
        return taxonomy_image_plugin_url('default.png');
    }
    /*
     * No image can be found.
     * Return path to blank-image.png.
     */
    return taxonomy_image_plugin_url('blank.png');
}
/**
 * Queried Term Image Data.
 *
 * Returns a url to the image associated with the current queried
 * term. In the event that no image is found an empty string will
 * be returned.
 *
 * Designed to be used in archive templates including
 * (but not limited to) archive.php, category.php, tag.php,
 * taxonomy.php as well as derivatives of these templates.
 *
 * Recognized Arguments
 *
 * image_size (string) - May be any image size registered with
 * WordPress. If no image size is specified, 'thumbnail' will be
 * used as a default value. In the event that an unregistered size
 * is specified, this function will return an empty array.
 *
 * @param     mixed          Default value for apply_filters() to return. Unused.
 * @param     array          Named Arguments.
 * @return    array          Image data: url, width and height.
 *
 * @access    private        Use the 'taxonomy-images-queried-term-image-data' filter.
 * @since     0.7
 * @alter     0.7.2
 */
function taxonomy_images_plugin_get_queried_term_image_data( $default, $args = array() ) {
	$filter = 'taxonomy-images-queried-term-image-data';
	if ( current_filter() !== $filter ) {
		taxonomy_image_plugin_please_use_filter( __FUNCTION__, $filter );
	}

	$args = wp_parse_args( $args, array(
		'image_size' => 'thumbnail',
	) );

	$ID = apply_filters( 'taxonomy-images-queried-term-image-id', 0 );

	if ( empty( $ID ) ) {
		return array();
	}

	$data = array();

	if ( in_array( $args['image_size'], array( 'full', 'fullsize' ) ) ) {
		$src = wp_get_attachment_image_src( $ID, 'full' );

		if ( isset( $src[0] ) ) {
			$data['url'] = $src[0];
		}
		if ( isset( $src[1] ) ) {
			$data['width'] = $src[1];
		}
		if ( isset( $src[2] ) ) {
			$data['height'] = $src[2];
		}
	} else {
		$data = image_get_intermediate_size( $ID, $args['image_size'] );
	}

	if ( ! empty( $data ) ) {
		return $data;
	}

	return array();
}
Example #12
0
/**
 * Scale an image to fit a particular size (such as 'thumb' or 'medium').
 *
 * Array with image url, width, height, and whether is intermediate size, in
 * that order is returned on success is returned. $is_intermediate is true if
 * $url is a resized image, false if it is the original.
 *
 * The URL might be the original image, or it might be a resized version. This
 * function won't create a new resized copy, it will just return an already
 * resized one if it exists.
 *
 * A plugin may use the 'image_downsize' filter to hook into and offer image
 * resizing services for images. The hook must return an array with the same
 * elements that are returned in the function. The first element being the URL
 * to the new image that was resized.
 *
 * @since 2.5.0
 *
 * @param int          $id   Attachment ID for image.
 * @param array|string $size Optional. Image size to scale to. Accepts any valid image size,
 *                           or an array of width and height values in pixels (in that order).
 *                           Default 'medium'.
 * @return false|array Array containing the image URL, width, height, and boolean for whether
 *                     the image is an intermediate size. False on failure.
 */
function image_downsize($id, $size = 'medium')
{
    if (!wp_attachment_is_image($id)) {
        return false;
    }
    /**
     * Filter whether to preempt the output of image_downsize().
     *
     * Passing a truthy value to the filter will effectively short-circuit
     * down-sizing the image, returning that value as output instead.
     *
     * @since 2.5.0
     *
     * @param bool         $downsize Whether to short-circuit the image downsize. Default false.
     * @param int          $id       Attachment ID for image.
     * @param array|string $size     Size of image. Image size or array of width and height values (in that order).
     *                               Default 'medium'.
     */
    if ($out = apply_filters('image_downsize', false, $id, $size)) {
        return $out;
    }
    $img_url = wp_get_attachment_url($id);
    $meta = wp_get_attachment_metadata($id);
    $width = $height = 0;
    $is_intermediate = false;
    $img_url_basename = wp_basename($img_url);
    // try for a new style intermediate size
    if ($intermediate = image_get_intermediate_size($id, $size)) {
        $img_url = str_replace($img_url_basename, $intermediate['file'], $img_url);
        $width = $intermediate['width'];
        $height = $intermediate['height'];
        $is_intermediate = true;
    } elseif ($size == 'thumbnail') {
        // fall back to the old thumbnail
        if (($thumb_file = wp_get_attachment_thumb_file($id)) && ($info = getimagesize($thumb_file))) {
            $img_url = str_replace($img_url_basename, wp_basename($thumb_file), $img_url);
            $width = $info[0];
            $height = $info[1];
            $is_intermediate = true;
        }
    }
    if (!$width && !$height && isset($meta['width'], $meta['height'])) {
        // any other type: use the real image
        $width = $meta['width'];
        $height = $meta['height'];
    }
    if ($img_url) {
        // we have the actual image size, but might need to further constrain it if content_width is narrower
        list($width, $height) = image_constrain_size_for_editor($width, $height, $size);
        return array($img_url, $width, $height, $is_intermediate);
    }
    return false;
}
Example #13
0
/**
 * Retrieves a source size attribute for an image from an array of values.
 *
 * @since 4.4.0
 *
 * @param int    $attachment_id Image attachment ID.
 * @param string $size          Optional. Name of image size. Default value: 'medium'.
 * @param array  $args {
 *     Optional. Arguments to retrieve attachments.
 *
 *     @type array|string $sizes An array or string containing of size information.
 *     @type int          $width A single width value used in the default `sizes` string.
 * }
 * @return string|bool A valid source size value for use in a 'sizes' attribute or false.
 */
function wp_get_attachment_image_sizes($attachment_id, $size = 'medium', $args = null)
{
    $img_width = 0;
    // Try to get the image width from $args.
    if (is_array($args) && !empty($args['width'])) {
        $img_width = (int) $args['width'];
    } elseif ($img = image_get_intermediate_size($attachment_id, $size)) {
        list($img_width) = image_constrain_size_for_editor($img['width'], $img['height'], $size);
    }
    // Bail early if $image_width isn't set.
    if (!$img_width) {
        return false;
    }
    // Set the image width in pixels.
    $img_width = $img_width . 'px';
    // Set up our default values.
    $defaults = array('sizes' => array(array('size_value' => '100vw', 'mq_value' => $img_width, 'mq_name' => 'max-width'), array('size_value' => $img_width)));
    $args = wp_parse_args($args, $defaults);
    /**
     * Filter arguments used to create 'sizes' attribute.
     *
     * @since 4.4.0
     *
     * @param array   $args          An array of arguments used to create a 'sizes' attribute.
     * @param int     $attachment_id Post ID of the original image.
     * @param string  $size          Name of the image size being used.
     */
    $args = apply_filters('wp_image_sizes_args', $args, $attachment_id, $size);
    // If sizes is passed as a string, just use the string.
    if (is_string($args['sizes'])) {
        $size_list = $args['sizes'];
        // Otherwise, breakdown the array and build a sizes string.
    } elseif (is_array($args['sizes'])) {
        $size_list = '';
        foreach ($args['sizes'] as $size) {
            // Use 100vw as the size value unless something else is specified.
            $size_value = $size['size_value'] ? $size['size_value'] : '100vw';
            // If a media length is specified, build the media query.
            if (!empty($size['mq_value'])) {
                $media_length = $size['mq_value'];
                // Use max-width as the media condition unless min-width is specified.
                $media_condition = !empty($size['mq_name']) ? $size['mq_name'] : 'max-width';
                // If a media_length was set, create the media query.
                $media_query = '(' . $media_condition . ": " . $media_length . ') ';
            } else {
                // If no media length was set, $media_query is blank.
                $media_query = '';
            }
            // Add to the source size list string.
            $size_list .= $media_query . $size_value . ', ';
        }
        // Remove the trailing comma and space from the end of the string.
        $size_list = substr($size_list, 0, -2);
    }
    // Return the sizes value as $size_list or false.
    return $size_list ? $size_list : false;
}
 function test_insert_image_delete()
 {
     if (!function_exists('imagejpeg')) {
         $this->markTestSkipped('jpeg support unavailable');
     }
     update_option('medium_size_w', 400);
     update_option('medium_size_h', 0);
     update_option('medium_large_size_w', 600);
     update_option('medium_large_size_h', 0);
     $filename = DIR_TESTDATA . '/images/2007-06-17DSC_4173.JPG';
     $contents = file_get_contents($filename);
     $upload = wp_upload_bits(basename($filename), null, $contents);
     $this->assertTrue(empty($upload['error']));
     $id = $this->_make_attachment($upload);
     $uploads = wp_upload_dir();
     // check that the file and intermediates exist
     $thumb = image_get_intermediate_size($id, 'thumbnail');
     $this->assertEquals('2007-06-17DSC_4173-150x150.jpg', $thumb['file']);
     $this->assertTrue(is_file($uploads['basedir'] . DIRECTORY_SEPARATOR . $thumb['path']));
     $medium = image_get_intermediate_size($id, 'medium');
     $this->assertEquals('2007-06-17DSC_4173-400x602.jpg', $medium['file']);
     $this->assertTrue(is_file($uploads['basedir'] . DIRECTORY_SEPARATOR . $medium['path']));
     $medium_large = image_get_intermediate_size($id, 'medium_large');
     $this->assertEquals('2007-06-17DSC_4173-600x904.jpg', $medium_large['file']);
     $this->assertTrue(is_file($uploads['basedir'] . DIRECTORY_SEPARATOR . $medium_large['path']));
     $meta = wp_get_attachment_metadata($id);
     $original = $meta['file'];
     $this->assertTrue(is_file($uploads['basedir'] . DIRECTORY_SEPARATOR . $original));
     // now delete the attachment and make sure all files are gone
     wp_delete_attachment($id);
     $this->assertFalse(is_file($thumb['path']));
     $this->assertFalse(is_file($medium['path']));
     $this->assertFalse(is_file($medium_large['path']));
     $this->assertFalse(is_file($original));
 }
/**
 * wpmlm scale image function, dynamically resizes an image oif no image already exists of that size.
 */
function wpmlm_scale_image()
{
    global $wpdb;
    if (!isset($_REQUEST['wpmlm_action']) || !isset($_REQUEST['attachment_id']) || 'scale_image' != $_REQUEST['wpmlm_action'] || !is_numeric($_REQUEST['attachment_id'])) {
        return false;
    }
    require_once ABSPATH . 'wp-admin/includes/image.php';
    $attachment_id = absint($_REQUEST['attachment_id']);
    $width = absint($_REQUEST['width']);
    $height = absint($_REQUEST['height']);
    $intermediate_size = '';
    if ($width >= 10 && $height >= 10 && ($width <= 1024 && $height <= 1024)) {
        $intermediate_size = "wpmlm-{$width}x{$height}";
        $generate_thumbnail = true;
    } else {
        if (isset($_REQUEST['intermediate_size'])) {
            $intermediate_size = esc_attr($_REQUEST['intermediate_size']);
        }
        $generate_thumbnail = false;
    }
    // If the attachment ID is greater than 0, and the width and height is greater than or equal to 10, and less than or equal to 1024
    if ($attachment_id > 0 && $intermediate_size != '') {
        // Get all the required information about the attachment
        $uploads = wp_upload_dir();
        $image_meta = get_post_meta($attachment_id, '');
        $file_path = get_attached_file($attachment_id);
        foreach ($image_meta as $meta_name => $meta_value) {
            // clean up the meta array
            $image_meta[$meta_name] = maybe_unserialize(array_pop($meta_value));
        }
        if (!isset($image_meta['_wp_attachment_metadata'])) {
            $image_meta['_wp_attachment_metadata'] = '';
        }
        $attachment_metadata = $image_meta['_wp_attachment_metadata'];
        if (!isset($attachment_metadata['sizes'])) {
            $attachment_metadata['sizes'] = '';
        }
        if (!isset($attachment_metadata['sizes'][$intermediate_size])) {
            $attachment_metadata['sizes'][$intermediate_size] = '';
        }
        // determine if we already have an image of this size
        if (count($attachment_metadata['sizes']) > 0 && $attachment_metadata['sizes'][$intermediate_size]) {
            $intermediate_image_data = image_get_intermediate_size($attachment_id, $intermediate_size);
            if (file_exists($file_path)) {
                $original_modification_time = filemtime($file_path);
                $cache_modification_time = filemtime($uploads['basedir'] . "/" . $intermediate_image_data['path']);
                if ($original_modification_time < $cache_modification_time) {
                    $generate_thumbnail = false;
                }
            }
        }
        if ($generate_thumbnail == true) {
            //JS - 7.1.2010 - Added true parameter to function to not crop - causing issues on WPShop
            $intermediate_size_data = image_make_intermediate_size($file_path, $width, $height, true);
            $attachment_metadata['sizes'][$intermediate_size] = $intermediate_size_data;
            wp_update_attachment_metadata($attachment_id, $attachment_metadata);
            $intermediate_image_data = image_get_intermediate_size($attachment_id, $intermediate_size);
        }
        /// if we are serving the page using SSL, we have to use for the image too.
        if (is_ssl()) {
            $output_url = str_replace("http://", "https://", $intermediate_image_data['url']);
        } else {
            $output_url = $intermediate_image_data['url'];
        }
        wp_redirect($output_url);
    } else {
        _e("Invalid Image parameters", 'wpmlm');
    }
    exit;
}
/**
 * Get Image Source.
 *
 * Return a uri to a custom image size.
 *
 * If size doesn't exist, attempt to create a resized version.
 * The output of this function should be escaped before printing to the browser.
 *
 * @param     int       Image ID.
 * @return    string    URI of custom image on success; emtpy string otherwise.
 *
 * @access    private.
 * @since     2010-10-28
 */
function taxonomy_image_plugin_get_image_src($id)
{
    $detail = taxonomy_image_plugin_detail_image_size();
    /* Return url to custom intermediate size if it exists. */
    $img = image_get_intermediate_size($id, $detail['name']);
    if (isset($img['url'])) {
        return $img['url'];
    }
    /* Detail image does not exist, attempt to create it. */
    $fullsizepath = get_attached_file($id);
    if (false != $fullsizepath && file_exists($fullsizepath)) {
        $metadata = wp_generate_attachment_metadata($id, $fullsizepath);
        if (!is_wp_error($metadata) && !empty($metadata)) {
            wp_update_attachment_metadata($id, $metadata);
        }
        /* Let's try the custom intermediate size again after the regeneration */
        $img = image_get_intermediate_size($id, $detail['name']);
        if (isset($img['url'])) {
            return $img['url'];
        }
    }
    /* Allow third party code to provide a proper detail image url */
    $url = apply_filters('taxonomy_image_detail_image_url', '', $id);
    if (!empty($url)) {
        return $url;
    }
    /* Custom intermediate size cannot be created, try for thumbnail. */
    $img = image_get_intermediate_size($id, 'thumbnail');
    if (isset($img['url'])) {
        return $img['url'];
    }
    /* Thumbnail cannot be found, try fullsize. */
    $url = wp_get_attachment_url($id);
    if (!empty($url)) {
        return $url;
    }
    /*
     * No image can be found.
     * This is most likely caused by a user deleting an attachment before deleting it's association with a taxonomy.
     * If we are in the administration panels:
     * - Delete the association.
     * - Return uri to default.png.
     */
    if (is_admin()) {
        $assoc = taxonomy_image_plugin_get_associations();
        foreach ($assoc as $term => $img) {
            if ($img === $id) {
                unset($assoc[$term]);
            }
        }
        update_option('taxonomy_image_plugin', $assoc);
        return taxonomy_image_plugin_url('default.png');
    }
    /*
     * No image can be found.
     * Return path to blank-image.png.
     */
    return taxonomy_image_plugin_url('blank.png');
}
 /**
  * Filter all thumbnails and image attachments typically used in template parts, archive loops, and widgets
  */
 static function convert_get_attachment_to_cloudinary_pull_request($override, $id, $size)
 {
     $account = static::get_option_value('cloud_name');
     //if no account is set, do not continue
     if (empty($account)) {
         return false;
     }
     //prepare values for string replacements
     $img_url = wp_get_attachment_url($id);
     $meta = wp_get_attachment_metadata($id);
     $width = $height = 0;
     $is_intermediate = false;
     $img_url_basename = wp_basename($img_url);
     $cdn_fetch_prefix = static::get_cdn_prefix($account);
     // try for a new style intermediate size
     if ($intermediate = image_get_intermediate_size($id, $size)) {
         $width = $intermediate['width'];
         $height = $intermediate['height'];
         $original = image_get_intermediate_size($id, 'full');
         $is_intermediate = true;
     } elseif ($size == 'thumbnail') {
         if (($thumb_file = wp_get_attachment_thumb_file($id)) && ($info = getimagesize($thumb_file))) {
             $width = $info[0];
             $height = $info[1];
             $is_intermediate = true;
         }
     }
     //make sure we have height and width values
     if (!$width && !$height && isset($meta['width'], $meta['height'])) {
         // any other type: use the real image
         $width = $meta['width'];
         $height = $meta['height'];
     }
     //if image found then modify it with cloudinary optimimized replacement
     if ($img_url) {
         $site_url = get_bloginfo('url');
         // get_bloginfo( 'url' ) is called a few time, it should be move to a property of this class, i.e. $this->blogurl, or something
         $site_url_no_protocal = preg_replace('/http[s]?:\\/\\//', '', $site_url);
         // we have the actual image size, but might need to further constrain it if content_width is narrower
         list($width, $height) = image_constrain_size_for_editor($width, $height, $size);
         $cdn_fetch_options = static::get_cdn_options($height, $width);
         //strip protocal from image URL
         $cdn_img_url = preg_replace('/(http:|https:)?\\/\\/(.*)/i', '$1' . $cdn_fetch_prefix . $cdn_fetch_options . "/\$2", $img_url);
         // do you need the double quotes on /$2 here or would single quotes work?
         return array($cdn_img_url, $width, $height, $is_intermediate);
     }
     //if for some reason $img_url fails, disable filter by returning false
     return false;
 }
Example #18
0
/**
 * Trashes or deletes an attachment.
 *
 * When an attachment is permanently deleted, the file will also be removed.
 * Deletion removes all post meta fields, taxonomy, comments, etc. associated
 * with the attachment (except the main post).
 *
 * The attachment is moved to the trash instead of permanently deleted unless trash
 * for media is disabled, item is already in the trash, or $force_delete is true.
 *
 * @since 2.0.0
 * @uses $wpdb
 *
 * @param int $post_id Attachment ID.
 * @param bool $force_delete Whether to bypass trash and force deletion. Defaults to false.
 * @return mixed False on failure. Post data on success.
 */
function wp_delete_attachment($post_id, $force_delete = false)
{
    global $wpdb;
    if (!($post = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$wpdb->posts} WHERE ID = %d", $post_id)))) {
        return $post;
    }
    if ('attachment' != $post->post_type) {
        return false;
    }
    if (!$force_delete && EMPTY_TRASH_DAYS && MEDIA_TRASH && 'trash' != $post->post_status) {
        return wp_trash_post($post_id);
    }
    delete_post_meta($post_id, '_wp_trash_meta_status');
    delete_post_meta($post_id, '_wp_trash_meta_time');
    $meta = wp_get_attachment_metadata($post_id);
    $backup_sizes = get_post_meta($post->ID, '_wp_attachment_backup_sizes', true);
    $file = get_attached_file($post_id);
    $intermediate_sizes = array();
    foreach (get_intermediate_image_sizes() as $size) {
        if ($intermediate = image_get_intermediate_size($post_id, $size)) {
            $intermediate_sizes[] = $intermediate;
        }
    }
    if (is_multisite()) {
        delete_transient('dirsize_cache');
    }
    /**
     * Fires before an attachment is deleted, at the start of wp_delete_attachment().
     *
     * @since 2.0.0
     *
     * @param int $post_id Attachment ID.
     */
    do_action('delete_attachment', $post_id);
    wp_delete_object_term_relationships($post_id, array('category', 'post_tag'));
    wp_delete_object_term_relationships($post_id, get_object_taxonomies($post->post_type));
    delete_metadata('post', null, '_thumbnail_id', $post_id, true);
    // delete all for any posts.
    $comment_ids = $wpdb->get_col($wpdb->prepare("SELECT comment_ID FROM {$wpdb->comments} WHERE comment_post_ID = %d", $post_id));
    foreach ($comment_ids as $comment_id) {
        wp_delete_comment($comment_id, true);
    }
    $post_meta_ids = $wpdb->get_col($wpdb->prepare("SELECT meta_id FROM {$wpdb->postmeta} WHERE post_id = %d ", $post_id));
    foreach ($post_meta_ids as $mid) {
        delete_metadata_by_mid('post', $mid);
    }
    /** This action is documented in wp-includes/post.php */
    do_action('delete_post', $post_id);
    $result = $wpdb->delete($wpdb->posts, array('ID' => $post_id));
    if (!$result) {
        return false;
    }
    /** This action is documented in wp-includes/post.php */
    do_action('deleted_post', $post_id);
    $uploadpath = wp_upload_dir();
    if (!empty($meta['thumb'])) {
        // Don't delete the thumb if another attachment uses it
        if (!$wpdb->get_row($wpdb->prepare("SELECT meta_id FROM {$wpdb->postmeta} WHERE meta_key = '_wp_attachment_metadata' AND meta_value LIKE %s AND post_id <> %d", '%' . $meta['thumb'] . '%', $post_id))) {
            $thumbfile = str_replace(basename($file), $meta['thumb'], $file);
            /** This filter is documented in wp-admin/custom-header.php */
            $thumbfile = apply_filters('wp_delete_file', $thumbfile);
            @unlink(path_join($uploadpath['basedir'], $thumbfile));
        }
    }
    // remove intermediate and backup images if there are any
    foreach ($intermediate_sizes as $intermediate) {
        /** This filter is documented in wp-admin/custom-header.php */
        $intermediate_file = apply_filters('wp_delete_file', $intermediate['path']);
        @unlink(path_join($uploadpath['basedir'], $intermediate_file));
    }
    if (is_array($backup_sizes)) {
        foreach ($backup_sizes as $size) {
            $del_file = path_join(dirname($meta['file']), $size['file']);
            /** This filter is documented in wp-admin/custom-header.php */
            $del_file = apply_filters('wp_delete_file', $del_file);
            @unlink(path_join($uploadpath['basedir'], $del_file));
        }
    }
    /** This filter is documented in wp-admin/custom-header.php */
    $file = apply_filters('wp_delete_file', $file);
    if (!empty($file)) {
        @unlink($file);
    }
    clean_post_cache($post);
    return $post;
}
/**
 * wpsc product thumbnail function
 *
 * Show the thumbnail image for the product
 *
 * @return string - the URL to the thumbnail image
 */
function wpsc_the_product_thumbnail($width = null, $height = null, $product_id = 0, $page = false)
{
    $thumbnail = false;
    $display = wpsc_check_display_type();
    // Get the product ID if none was passed
    if (empty($product_id)) {
        $product_id = get_the_ID();
    }
    // Load the product
    $product = get_post($product_id);
    $thumbnail_id = wpsc_the_product_thumbnail_id($product_id);
    // If no thumbnail found for item, get its parent image
    if (!$thumbnail_id && (is_a($product, 'WP_Post') && $product->post_parent)) {
        $thumbnail_id = wpsc_the_product_thumbnail_id($product->post_parent);
    }
    // if still no thumbnail ID is found, return our fallback function
    if (!$thumbnail_id) {
        return wpsc_product_image();
    }
    if (!$page) {
        $page = is_single() ? 'single' : 'products-page';
    }
    if (!$width && !$height) {
        $width = get_option('product_image_width');
        $height = get_option('product_image_height');
        // Overwrite height & width if custom dimensions exist for thumbnail_id
        if ('grid' != $display && 'products-page' == $page && isset($thumbnail_id)) {
            $custom_width = get_post_meta($thumbnail_id, '_wpsc_custom_thumb_w', true);
            $custom_height = get_post_meta($thumbnail_id, '_wpsc_custom_thumb_h', true);
            if (!empty($custom_width) && !empty($custom_height)) {
                $width = $custom_width;
                $height = $custom_height;
            }
        } elseif ($page == 'single' && isset($thumbnail_id)) {
            $custom_thumbnail = get_post_meta($thumbnail_id, '_wpsc_selected_image_size', true);
            if (!$custom_thumbnail) {
                $custom_thumbnail = 'medium-single-product';
            }
            $src = wp_get_attachment_image_src($thumbnail_id, $custom_thumbnail);
            if (!$src) {
                $custom_thumbnail = 'medium-single-product';
                $current_size = image_get_intermediate_size($thumbnail_id, $custom_thumbnail);
                $settings_width = get_option('single_view_image_width');
                $settings_height = get_option('single_view_image_height');
                if (!$current_size || $current_size['width'] != $settings_width && $current_size['height'] != $settings_height) {
                    _wpsc_regenerate_thumbnail_size($thumbnail_id, $custom_thumbnail);
                }
                $src = wp_get_attachment_image_src($thumbnail_id, $custom_thumbnail);
            }
            if (!empty($src) && is_string($src[0])) {
                $thumbnail = $src[0];
            }
        } elseif ($page == 'manage-products' && isset($thumbnail_id)) {
            $current_size = image_get_intermediate_size($thumbnail_id, 'admin-product-thumbnails');
            if (!$current_size) {
                _wpsc_regenerate_thumbnail_size($thumbnail_id, 'admin-product-thumbnails');
            }
            $src = wp_get_attachment_image_src($thumbnail_id, 'admin-product-thumbnails');
            if (!empty($src) && is_string($src[0])) {
                $thumbnail = $src[0];
            }
        }
    }
    // Calculate the height based on the ratio of the original dimensions.
    if ($height == 0 || $width == 0) {
        $attachment_meta = get_post_meta($thumbnail_id, '_wp_attachment_metadata', true);
        $original_width = isset($attachment_meta['width']) ? absint($attachment_meta['width']) : 0;
        $original_height = isset($attachment_meta['height']) ? absint($attachment_meta['height']) : 0;
        // bail if either original value is zero. can't divide by zero.
        if ($original_width == 0 || $original_height == 0) {
            return;
        }
        if ($width != 0) {
            $height = $original_height / $original_width * $width;
            $height = round($height, 0);
        } elseif ($height != 0) {
            $width = $original_width / $original_height * $height;
            $width = round($width, 0);
        }
    }
    if (!$thumbnail && isset($thumbnail_id)) {
        $thumbnail = wpsc_product_image($thumbnail_id, $width, $height);
    }
    // WordPress's esc_url() function strips out spaces, so encode them here to ensure they don't get stripped out
    // Ref: http://core.trac.wordpress.org/ticket/23605
    $thumbnail = str_replace(' ', '%20', $thumbnail);
    return apply_filters('wpsc_the_product_thumbnail', set_url_scheme($thumbnail), $product_id, $product);
}
/**
 * wpsc product thumbnail function
 *
 * Show the thumbnail image for the product
 *
 * @return string - the URL to the thumbnail image
 */
function wpsc_the_product_thumbnail($width = null, $height = null, $product_id = 0, $page = 'products-page')
{
    $thumbnail = false;
    $display = wpsc_check_display_type();
    // Get the product ID if none was passed
    if (empty($product_id)) {
        $product_id = get_the_ID();
    }
    // Load the product
    $product = get_post($product_id);
    // Get ID of parent product if one exists
    if (!empty($product->post_parent)) {
        $product_id = $product->post_parent;
    }
    // Load image proportions if none were passed
    if ($width < 10 || $height < 10) {
        $width = get_option('product_image_width');
        $height = get_option('product_image_height');
    }
    // Use product thumbnail
    if (has_post_thumbnail($product_id)) {
        $thumbnail_id = get_post_thumbnail_id($product_id);
        // Use first product image
    } else {
        // Get all attached images to this product
        $attached_images = (array) get_posts(array('post_type' => 'attachment', 'numberposts' => 1, 'post_status' => null, 'post_parent' => $product_id, 'orderby' => 'menu_order', 'order' => 'ASC'));
        if (!empty($attached_images)) {
            $thumbnail_id = $attached_images[0]->ID;
        }
    }
    //Overwrite height & width if custom dimensions exist for thumbnail_id
    if ('grid' != $display && 'products-page' == $page && isset($thumbnail_id)) {
        $custom_width = get_post_meta($thumbnail_id, '_wpsc_custom_thumb_w', true);
        $custom_height = get_post_meta($thumbnail_id, '_wpsc_custom_thumb_h', true);
        if (!empty($custom_width) && !empty($custom_height)) {
            $width = $custom_width;
            $height = $custom_height;
        }
    } elseif ($page == 'single' && isset($thumbnail_id)) {
        $custom_thumbnail = get_post_meta($thumbnail_id, '_wpsc_selected_image_size', true);
        if (!$custom_thumbnail) {
            $custom_thumbnail = 'medium-single-product';
            $current_size = image_get_intermediate_size($thumbnail_id, $custom_thumbnail);
            $settings_width = get_option('single_view_image_width');
            $settings_height = get_option('single_view_image_height');
            // regenerate size metadata in case it's missing
            if (!$current_size || $current_size['width'] != $settings_width || $current_size['height'] != $settings_height) {
                require_once ABSPATH . 'wp-admin/includes/image.php';
                if (!($metadata = wp_get_attachment_metadata($thumbnail_id))) {
                    $metadata = array();
                }
                if (empty($metadata['sizes'])) {
                    $metadata['sizes'] = array();
                }
                $file = get_attached_file($thumbnail_id);
                $generated = wp_generate_attachment_metadata($thumbnail_id, $file);
                $metadata['sizes'] = array_merge($metadata['sizes'], $generated['sizes']);
                wp_update_attachment_metadata($thumbnail_id, $metadata);
            }
        }
        $src = wp_get_attachment_image_src($thumbnail_id, $custom_thumbnail);
        if (!empty($src) && is_string($src[0])) {
            $thumbnail = $src[0];
        }
    }
    // calculate the height based on the ratio of the original demensions
    // blame Cameron if this is buggy :P
    if ($height == 0 || $width == 0) {
        $attachment_meta = get_post_meta($thumbnail_id, '_wp_attachment_metadata', false);
        $original_width = $attachment_meta[0]['width'];
        $original_height = $attachment_meta[0]['height'];
        if ($width != 0) {
            $height = $original_height / $original_width * $width;
            $height = round($height, 0);
        } elseif ($height != 0) {
            $width = $original_width / $original_height * $height;
            $width = round($width, 0);
        }
    }
    if (!$thumbnail && isset($thumbnail_id)) {
        $thumbnail = wpsc_product_image($thumbnail_id, $width, $height);
    }
    if (!empty($thumbnail) && is_ssl()) {
        $thumbnail = str_replace('http://', 'https://', $thumbnail);
    }
    return $thumbnail;
}
Example #21
0
function load_image_to_edit($post_id, $mime_type, $size = 'full')
{
    $filepath = get_attached_file($post_id);
    if ($filepath && file_exists($filepath)) {
        if ('full' != $size && ($data = image_get_intermediate_size($post_id, $size))) {
            $filepath = apply_filters('load_image_to_edit_filesystempath', path_join(dirname($filepath), $data['file']), $post_id, $size);
        }
    } elseif (function_exists('fopen') && function_exists('ini_get') && true == ini_get('allow_url_fopen')) {
        $filepath = apply_filters('load_image_to_edit_attachmenturl', wp_get_attachment_url($post_id), $post_id, $size);
    }
    $filepath = apply_filters('load_image_to_edit_path', $filepath, $post_id, $size);
    if (empty($filepath)) {
        return false;
    }
    switch ($mime_type) {
        case 'image/jpeg':
            $image = imagecreatefromjpeg($filepath);
            break;
        case 'image/png':
            $image = imagecreatefrompng($filepath);
            break;
        case 'image/gif':
            $image = imagecreatefromgif($filepath);
            break;
        default:
            $image = false;
            break;
    }
    if (is_resource($image)) {
        $image = apply_filters('load_image_to_edit', $image, $post_id, $size);
        if (function_exists('imagealphablending') && function_exists('imagesavealpha')) {
            imagealphablending($image, false);
            imagesavealpha($image, true);
        }
    }
    return $image;
}
 /**
  * Calculate the HTML for showing the thumb of a post item.
  *
  * Used as a filter for the thumb wordpress API to add css based stretching and cropping
  * when the image is not at the requested dimensions
  *
  * @param  string $html The original HTML generated by the core APIS
  * @param  int    $post_id the ID of the post of which the thumb is a featured image
  * @param  int    $post_thumbnail_id The id of the featured image attachment
  * @param  string|array    $size The requested size identified by name or (width, height) array
  * @param  mixed  $attr ignored in this context
  * @return string The HTML for the thumb related to the post
  *
  * @since 4.1
  */
 function post_thumbnail_html($html, $post_id, $post_thumbnail_id, $size, $attr)
 {
     if (empty($this->instance['thumb_w']) || empty($this->instance['thumb_h'])) {
         return $html;
     }
     // bail out if no full dimensions defined
     $meta = image_get_intermediate_size($post_thumbnail_id, $size);
     if (empty($meta)) {
         $post_img = wp_get_attachment_metadata($post_thumbnail_id, $size);
         $meta['file'] = basename($post_img['file']);
     }
     $origfile = get_attached_file($post_thumbnail_id, true);
     // the location of the full file
     $file = dirname($origfile) . '/' . $meta['file'];
     // the location of the file displayed as thumb
     list($width, $height) = getimagesize($file);
     // get actual size of the thumb file
     if ($width / $height == $this->instance['thumb_w'] / $this->instance['thumb_h']) {
         // image is same ratio as asked for, nothing to do here as the browser will handle it correctly
     } else {
         if (isset($this->instance['use_css_cropping']) && $this->instance['use_css_cropping']) {
             $image = get_image_size($this->instance['thumb_w'], $this->instance['thumb_h'], $width, $height);
             // replace srcset
             $array = array();
             preg_match('/width="([^"]*)"/i', $html, $array);
             $pattern = "/" . $array[1] . "w/";
             $html = preg_replace($pattern, $image['image_w'] . "w", $html);
             // replace size
             $pattern = "/" . $array[1] . "px/";
             $html = preg_replace($pattern, $image['image_w'] . "px", $html);
             // replace width
             $pattern = "/width=\"[0-9]*\"/";
             $html = preg_replace($pattern, "width='" . $image['image_w'] . "'", $html);
             // replace height
             $pattern = "/height=\"[0-9]*\"/";
             $html = preg_replace($pattern, "height='" . $image['image_h'] . "'", $html);
             // set margin
             $html = str_replace('<img ', '<img style="' . $image['marginAttr'] . ':-' . $image['marginVal'] . 'px;height:' . $image['image_h'] . 'px;clip:rect(auto,' . ($this->instance['thumb_w'] + $image['marginVal']) . 'px,auto,' . $image['marginVal'] . 'px);width:auto;max-width:initial;" ', $html);
             // wrap span
             $html = '<span style="width:' . $this->instance['thumb_w'] . 'px;height:' . $this->instance['thumb_h'] . 'px;">' . $html . '</span>';
         } else {
             // if use_css_cropping not used
             // no interface changes: leave without change
         }
     }
     return $html;
 }
Example #23
0
 /**
  * Filter post thumbnail image retrieval, passing images through Photon
  *
  * @param string|bool $image
  * @param int $attachment_id
  * @param string|array $size
  * @uses is_admin, apply_filters, wp_get_attachment_url, self::validate_image_url, this::image_sizes, jetpack_photon_url
  * @filter image_downsize
  * @return string|bool
  */
 public function filter_image_downsize($image, $attachment_id, $size)
 {
     // Don't foul up the admin side of things, and provide plugins a way of preventing Photon from being applied to images.
     if (is_admin() || apply_filters('jetpack_photon_override_image_downsize', false, compact('image', 'attachment_id', 'size'))) {
         return $image;
     }
     // Get the image URL and proceed with Photon-ification if successful
     $image_url = wp_get_attachment_url($attachment_id);
     // Set this to true later when we know we have size meta.
     $has_size_meta = false;
     if ($image_url) {
         // Check if image URL should be used with Photon
         if (!self::validate_image_url($image_url)) {
             return $image;
         }
         $intermediate = true;
         // For the fourth array item returned by the image_downsize filter.
         // If an image is requested with a size known to WordPress, use that size's settings with Photon
         if ((is_string($size) || is_int($size)) && array_key_exists($size, self::image_sizes())) {
             $image_args = self::image_sizes();
             $image_args = $image_args[$size];
             $photon_args = array();
             $image_meta = image_get_intermediate_size($attachment_id, $size);
             // 'full' is a special case: We need consistent data regardless of the requested size.
             if ('full' == $size) {
                 $image_meta = wp_get_attachment_metadata($attachment_id);
                 $intermediate = false;
             } elseif (!$image_meta) {
                 // If we still don't have any image meta at this point, it's probably from a custom thumbnail size
                 // for an image that was uploaded before the custom image was added to the theme.  Try to determine the size manually.
                 $image_meta = wp_get_attachment_metadata($attachment_id);
                 if (isset($image_meta['width'], $image_meta['height'])) {
                     $image_resized = image_resize_dimensions($image_meta['width'], $image_meta['height'], $image_args['width'], $image_args['height'], $image_args['crop']);
                     if ($image_resized) {
                         // This could be false when the requested image size is larger than the full-size image.
                         $image_meta['width'] = $image_resized[6];
                         $image_meta['height'] = $image_resized[7];
                     }
                 }
             }
             if (isset($image_meta['width'], $image_meta['height'])) {
                 $image_args['width'] = $image_meta['width'];
                 $image_args['height'] = $image_meta['height'];
                 list($image_args['width'], $image_args['height']) = image_constrain_size_for_editor($image_args['width'], $image_args['height'], $size, 'display');
                 $has_size_meta = true;
             }
             // Expose determined arguments to a filter before passing to Photon
             $transform = $image_args['crop'] ? 'resize' : 'fit';
             // Check specified image dimensions and account for possible zero values; photon fails to resize if a dimension is zero.
             if (0 == $image_args['width'] || 0 == $image_args['height']) {
                 if (0 == $image_args['width'] && 0 < $image_args['height']) {
                     $photon_args['h'] = $image_args['height'];
                 } elseif (0 == $image_args['height'] && 0 < $image_args['width']) {
                     $photon_args['w'] = $image_args['width'];
                 }
             } else {
                 if ('resize' === $transform && ($image_meta = wp_get_attachment_metadata($attachment_id))) {
                     if (isset($image_meta['width'], $image_meta['height'])) {
                         // Lets make sure that we don't upscale images since wp never upscales them as well
                         $smaller_width = $image_meta['width'] < $image_args['width'] ? $image_meta['width'] : $image_args['width'];
                         $smaller_height = $image_meta['height'] < $image_args['height'] ? $image_meta['height'] : $image_args['height'];
                         $photon_args[$transform] = $smaller_width . ',' . $smaller_height;
                     }
                 } else {
                     $photon_args[$transform] = $image_args['width'] . ',' . $image_args['height'];
                 }
             }
             /**
              * Filter the Photon Arguments added to an image when going through Photon, when that image size is a string.
              * Image size will be a string (e.g. "full", "medium") when it is known to WordPress.
              *
              * @module photon
              *
              * @since 2.0.0
              *
              * @param array $photon_args Array of Photon arguments.
              * @param array $args {
              * 	 Array of image details.
              *
              * 	 @type $image_args Array of Image arguments (width, height, crop).
              * 	 @type $image_url Image URL.
              * 	 @type $attachment_id Attachment ID of the image.
              * 	 @type $size Image size. Can be a string (name of the image size, e.g. full) or an integer.
              * 	 @type $transform Value can be resize or fit.
              *                    @see https://developer.wordpress.com/docs/photon/api
              * }
              */
             $photon_args = apply_filters('jetpack_photon_image_downsize_string', $photon_args, compact('image_args', 'image_url', 'attachment_id', 'size', 'transform'));
             // Generate Photon URL
             $image = array(jetpack_photon_url($image_url, $photon_args), $has_size_meta ? $image_args['width'] : false, $has_size_meta ? $image_args['height'] : false, $intermediate);
         } elseif (is_array($size)) {
             // Pull width and height values from the provided array, if possible
             $width = isset($size[0]) ? (int) $size[0] : false;
             $height = isset($size[1]) ? (int) $size[1] : false;
             // Don't bother if necessary parameters aren't passed.
             if (!$width || !$height) {
                 return $image;
             }
             $image_meta = wp_get_attachment_metadata($attachment_id);
             if (isset($image_meta['width'], $image_meta['height'])) {
                 $image_resized = image_resize_dimensions($image_meta['width'], $image_meta['height'], $width, $height);
                 if ($image_resized) {
                     // This could be false when the requested image size is larger than the full-size image.
                     $width = $image_resized[6];
                     $height = $image_resized[7];
                 } else {
                     $width = $image_meta['width'];
                     $height = $image_meta['height'];
                 }
                 $has_size_meta = true;
             }
             list($width, $height) = image_constrain_size_for_editor($width, $height, $size);
             // Expose arguments to a filter before passing to Photon
             $photon_args = array('fit' => $width . ',' . $height);
             /**
              * Filter the Photon Arguments added to an image when going through Photon,
              * when the image size is an array of height and width values.
              *
              * @module photon
              *
              * @since 2.0.0
              *
              * @param array $photon_args Array of Photon arguments.
              * @param array $args {
              * 	 Array of image details.
              *
              * 	 @type $width Image width.
              * 	 @type height Image height.
              * 	 @type $image_url Image URL.
              * 	 @type $attachment_id Attachment ID of the image.
              * }
              */
             $photon_args = apply_filters('jetpack_photon_image_downsize_array', $photon_args, compact('width', 'height', 'image_url', 'attachment_id'));
             // Generate Photon URL
             $image = array(jetpack_photon_url($image_url, $photon_args), $has_size_meta ? $width : false, $has_size_meta ? $height : false, $intermediate);
         }
     }
     return $image;
 }
Example #24
0
function pte_get_image_data($id, $size, $size_data)
{
    $logger = PteLogger::singleton();
    $fullsizepath = get_attached_file($id);
    $path_information = image_get_intermediate_size($id, $size);
    if ($path_information && @file_exists(dirname($fullsizepath) . DIRECTORY_SEPARATOR . $path_information['file'])) {
        return $path_information;
    }
    // We don't really care how it gets generated, just that it is...
    // see ajax-thumbnail-rebuild plugin for inspiration
    if (FALSE !== $fullsizepath && @file_exists($fullsizepath)) {
        // Create the image and update the wordpress metadata
        $resized = image_make_intermediate_size($fullsizepath, $size_data['width'], $size_data['height'], $size_data['crop']);
        if ($resized) {
            $metadata = wp_get_attachment_metadata($id, true);
            $metadata['sizes'][$size] = $resized;
            wp_update_attachment_metadata($id, $metadata);
        }
    }
    // Finish how we started
    $path_information = image_get_intermediate_size($id, $size);
    if ($path_information) {
        return $path_information;
    } else {
        $logger->warn("Couldn't find or generate metadata for image: {$id}-{$size}");
    }
    return false;
}
Example #25
0
/**
 * Retrieve the path or url of an attachment's attached file.
 *
 * If the attached file is not present on the local filesystem (usually due to replication plugins),
 * then the url of the file is returned if url fopen is supported.
 *
 * @since 3.4.0
 * @access private
 *
 * @param string $attachment_id Attachment ID.
 * @param string $size Optional. Image size, defaults to 'full'.
 * @return string|false File path or url on success, false on failure.
 */
function _load_image_to_edit_path($attachment_id, $size = 'full')
{
    $filepath = get_attached_file($attachment_id);
    if ($filepath && file_exists($filepath)) {
        if ('full' != $size && ($data = image_get_intermediate_size($attachment_id, $size))) {
            $filepath = apply_filters('load_image_to_edit_filesystempath', path_join(dirname($filepath), $data['file']), $attachment_id, $size);
        }
    } elseif (function_exists('fopen') && function_exists('ini_get') && true == ini_get('allow_url_fopen')) {
        $filepath = apply_filters('load_image_to_edit_attachmenturl', wp_get_attachment_url($attachment_id), $attachment_id, $size);
    }
    return apply_filters('load_image_to_edit_path', $filepath, $attachment_id, $size);
}
/**
 * wp_delete_attachment() - Delete an attachment
 *
 * {@internal Missing Long Description}}
 *
 * @package WordPress
 * @subpackage Post
 * @since 2.0
 * @uses $wpdb
 *
 * @param int $postid attachment Id
 * @return mixed {@internal Missing Description}}
 */
function wp_delete_attachment($postid)
{
    global $wpdb;
    if (!($post = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$wpdb->posts} WHERE ID = %d", $postid)))) {
        return $post;
    }
    if ('attachment' != $post->post_type) {
        return false;
    }
    $meta = wp_get_attachment_metadata($postid);
    $file = get_attached_file($postid);
    /** @todo Delete for pluggable post taxonomies too */
    wp_delete_object_term_relationships($postid, array('category', 'post_tag'));
    $wpdb->query($wpdb->prepare("DELETE FROM {$wpdb->posts} WHERE ID = %d", $postid));
    $wpdb->query($wpdb->prepare("DELETE FROM {$wpdb->comments} WHERE comment_post_ID = %d", $postid));
    $wpdb->query($wpdb->prepare("DELETE FROM {$wpdb->postmeta} WHERE post_id = %d ", $postid));
    if (!empty($meta['thumb'])) {
        // Don't delete the thumb if another attachment uses it
        if (!$wpdb->get_row($wpdb->prepare("SELECT meta_id FROM {$wpdb->postmeta} WHERE meta_key = '_wp_attachment_metadata' AND meta_value LIKE %s AND post_id <> %d", '%' . $meta['thumb'] . '%', $postid))) {
            $thumbfile = str_replace(basename($file), $meta['thumb'], $file);
            $thumbfile = apply_filters('wp_delete_file', $thumbfile);
            @unlink($thumbfile);
        }
    }
    // remove intermediate images if there are any
    $sizes = apply_filters('intermediate_image_sizes', array('thumbnail', 'medium'));
    foreach ($sizes as $size) {
        if ($intermediate = image_get_intermediate_size($postid, $size)) {
            $intermediate_file = apply_filters('wp_delete_file', $intermediate['path']);
            @unlink($intermediate_file);
        }
    }
    $file = apply_filters('wp_delete_file', $file);
    if (!empty($file)) {
        @unlink($file);
    }
    clean_post_cache($postid);
    do_action('delete_attachment', $postid);
    return $post;
}
Example #27
0
/**
 * Loads the WP image-editing interface.
 *
 * @param int         $post_id Post ID.
 * @param bool|object $msg     Optional. Message to display for image editor updates or errors.
 *                             Default false.
 */
function wp_image_editor($post_id, $msg = false)
{
    $nonce = wp_create_nonce("image_editor-{$post_id}");
    $meta = wp_get_attachment_metadata($post_id);
    $thumb = image_get_intermediate_size($post_id, 'thumbnail');
    $sub_sizes = isset($meta['sizes']) && is_array($meta['sizes']);
    $note = '';
    if (isset($meta['width'], $meta['height'])) {
        $big = max($meta['width'], $meta['height']);
    } else {
        die(__('Image data does not exist. Please re-upload the image.'));
    }
    $sizer = $big > 400 ? 400 / $big : 1;
    $backup_sizes = get_post_meta($post_id, '_wp_attachment_backup_sizes', true);
    $can_restore = false;
    if (!empty($backup_sizes) && isset($backup_sizes['full-orig'], $meta['file'])) {
        $can_restore = $backup_sizes['full-orig']['file'] != basename($meta['file']);
    }
    if ($msg) {
        if (isset($msg->error)) {
            $note = "<div class='error'><p>{$msg->error}</p></div>";
        } elseif (isset($msg->msg)) {
            $note = "<div class='updated'><p>{$msg->msg}</p></div>";
        }
    }
    ?>
	<div class="imgedit-wrap">
	<div id="imgedit-panel-<?php 
    echo $post_id;
    ?>
">

	<div class="imgedit-settings">
	<div class="imgedit-group">
	<div class="imgedit-group-top">
		<h3><?php 
    _e('Scale Image');
    ?>
 <a href="#" class="dashicons dashicons-editor-help imgedit-help-toggle" onclick="imageEdit.toggleHelp(this);return false;"></a></h3>
		<div class="imgedit-help">
		<p><?php 
    _e('You can proportionally scale the original image. For best results, scaling should be done before you crop, flip, or rotate. Images can only be scaled down, not up.');
    ?>
</p>
		</div>
		<?php 
    if (isset($meta['width'], $meta['height'])) {
        ?>
		<p><?php 
        printf(__('Original dimensions %s'), $meta['width'] . ' &times; ' . $meta['height']);
        ?>
</p>
		<?php 
    }
    ?>
		<div class="imgedit-submit">
		<span class="nowrap"><input type="text" id="imgedit-scale-width-<?php 
    echo $post_id;
    ?>
" onkeyup="imageEdit.scaleChanged(<?php 
    echo $post_id;
    ?>
, 1)" onblur="imageEdit.scaleChanged(<?php 
    echo $post_id;
    ?>
, 1)" style="width:4em;" value="<?php 
    echo isset($meta['width']) ? $meta['width'] : 0;
    ?>
" /> &times; <input type="text" id="imgedit-scale-height-<?php 
    echo $post_id;
    ?>
" onkeyup="imageEdit.scaleChanged(<?php 
    echo $post_id;
    ?>
, 0)" onblur="imageEdit.scaleChanged(<?php 
    echo $post_id;
    ?>
, 0)" style="width:4em;" value="<?php 
    echo isset($meta['height']) ? $meta['height'] : 0;
    ?>
" />
		<span class="imgedit-scale-warn" id="imgedit-scale-warn-<?php 
    echo $post_id;
    ?>
">!</span></span>
		<input type="button" onclick="imageEdit.action(<?php 
    echo "{$post_id}, '{$nonce}'";
    ?>
, 'scale')" class="button button-primary" value="<?php 
    esc_attr_e('Scale');
    ?>
" />
		</div>
	</div>
	</div>

<?php 
    if ($can_restore) {
        ?>

	<div class="imgedit-group">
	<div class="imgedit-group-top">
		<h3><a onclick="imageEdit.toggleHelp(this);return false;" href="#"><?php 
        _e('Restore Original Image');
        ?>
 <span class="dashicons dashicons-arrow-down imgedit-help-toggle"></span></a></h3>
		<div class="imgedit-help">
		<p><?php 
        _e('Discard any changes and restore the original image.');
        if (!defined('IMAGE_EDIT_OVERWRITE') || !IMAGE_EDIT_OVERWRITE) {
            echo ' ' . __('Previously edited copies of the image will not be deleted.');
        }
        ?>
</p>
		<div class="imgedit-submit">
		<input type="button" onclick="imageEdit.action(<?php 
        echo "{$post_id}, '{$nonce}'";
        ?>
, 'restore')" class="button button-primary" value="<?php 
        esc_attr_e('Restore image');
        ?>
" <?php 
        echo $can_restore;
        ?>
 />
		</div>
		</div>
	</div>
	</div>

<?php 
    }
    ?>

	<div class="imgedit-group">
	<div class="imgedit-group-top">
		<h3><?php 
    _e('Image Crop');
    ?>
 <a href="#" class="dashicons dashicons-editor-help imgedit-help-toggle" onclick="imageEdit.toggleHelp(this);return false;"></a></h3>

		<div class="imgedit-help">
		<p><?php 
    _e('To crop the image, click on it and drag to make your selection.');
    ?>
</p>

		<p><strong><?php 
    _e('Crop Aspect Ratio');
    ?>
</strong><br />
		<?php 
    _e('The aspect ratio is the relationship between the width and height. You can preserve the aspect ratio by holding down the shift key while resizing your selection. Use the input box to specify the aspect ratio, e.g. 1:1 (square), 4:3, 16:9, etc.');
    ?>
</p>

		<p><strong><?php 
    _e('Crop Selection');
    ?>
</strong><br />
		<?php 
    _e('Once you have made your selection, you can adjust it by entering the size in pixels. The minimum selection size is the thumbnail size as set in the Media settings.');
    ?>
</p>
		</div>
	</div>

	<p>
		<?php 
    _e('Aspect ratio:');
    ?>
		<span  class="nowrap">
		<input type="text" id="imgedit-crop-width-<?php 
    echo $post_id;
    ?>
" onkeyup="imageEdit.setRatioSelection(<?php 
    echo $post_id;
    ?>
, 0, this)" style="width:3em;" />
		:
		<input type="text" id="imgedit-crop-height-<?php 
    echo $post_id;
    ?>
" onkeyup="imageEdit.setRatioSelection(<?php 
    echo $post_id;
    ?>
, 1, this)" style="width:3em;" />
		</span>
	</p>

	<p id="imgedit-crop-sel-<?php 
    echo $post_id;
    ?>
">
		<?php 
    _e('Selection:');
    ?>
		<span  class="nowrap">
		<input type="text" id="imgedit-sel-width-<?php 
    echo $post_id;
    ?>
" onkeyup="imageEdit.setNumSelection(<?php 
    echo $post_id;
    ?>
)" style="width:4em;" />
		&times;
		<input type="text" id="imgedit-sel-height-<?php 
    echo $post_id;
    ?>
" onkeyup="imageEdit.setNumSelection(<?php 
    echo $post_id;
    ?>
)" style="width:4em;" />
		</span>
	</p>
	</div>

	<?php 
    if ($thumb && $sub_sizes) {
        $thumb_img = wp_constrain_dimensions($thumb['width'], $thumb['height'], 160, 120);
        ?>

	<div class="imgedit-group imgedit-applyto">
	<div class="imgedit-group-top">
		<h3><?php 
        _e('Thumbnail Settings');
        ?>
 <a href="#" class="dashicons dashicons-editor-help imgedit-help-toggle" onclick="imageEdit.toggleHelp(this);return false;"></a></h3>
		<p class="imgedit-help"><?php 
        _e('You can edit the image while preserving the thumbnail. For example, you may wish to have a square thumbnail that displays just a section of the image.');
        ?>
</p>
	</div>

	<p>
		<img src="<?php 
        echo $thumb['url'];
        ?>
" width="<?php 
        echo $thumb_img[0];
        ?>
" height="<?php 
        echo $thumb_img[1];
        ?>
" class="imgedit-size-preview" alt="" draggable="false" />
		<br /><?php 
        _e('Current thumbnail');
        ?>
	</p>

	<p id="imgedit-save-target-<?php 
        echo $post_id;
        ?>
">
		<strong><?php 
        _e('Apply changes to:');
        ?>
</strong><br />

		<label class="imgedit-label">
		<input type="radio" name="imgedit-target-<?php 
        echo $post_id;
        ?>
" value="all" checked="checked" />
		<?php 
        _e('All image sizes');
        ?>
</label>

		<label class="imgedit-label">
		<input type="radio" name="imgedit-target-<?php 
        echo $post_id;
        ?>
" value="thumbnail" />
		<?php 
        _e('Thumbnail');
        ?>
</label>

		<label class="imgedit-label">
		<input type="radio" name="imgedit-target-<?php 
        echo $post_id;
        ?>
" value="nothumb" />
		<?php 
        _e('All sizes except thumbnail');
        ?>
</label>
	</p>
	</div>

	<?php 
    }
    ?>

	</div>

	<div class="imgedit-panel-content">
		<?php 
    echo $note;
    ?>
		<div class="imgedit-menu">
			<div onclick="imageEdit.crop(<?php 
    echo "{$post_id}, '{$nonce}'";
    ?>
, this)" class="imgedit-crop disabled" title="<?php 
    esc_attr_e('Crop');
    ?>
"></div><?php 
    // On some setups GD library does not provide imagerotate() - Ticket #11536
    if (wp_image_editor_supports(array('mime_type' => get_post_mime_type($post_id), 'methods' => array('rotate')))) {
        ?>
			<div class="imgedit-rleft"  onclick="imageEdit.rotate( 90, <?php 
        echo "{$post_id}, '{$nonce}'";
        ?>
, this)" title="<?php 
        esc_attr_e('Rotate counter-clockwise');
        ?>
"></div>
			<div class="imgedit-rright" onclick="imageEdit.rotate(-90, <?php 
        echo "{$post_id}, '{$nonce}'";
        ?>
, this)" title="<?php 
        esc_attr_e('Rotate clockwise');
        ?>
"></div>
	<?php 
    } else {
        $note_no_rotate = esc_attr__('Image rotation is not supported by your web host.');
        ?>
		    <div class="imgedit-rleft disabled"  title="<?php 
        echo $note_no_rotate;
        ?>
"></div>
		    <div class="imgedit-rright disabled" title="<?php 
        echo $note_no_rotate;
        ?>
"></div>
	<?php 
    }
    ?>

			<div onclick="imageEdit.flip(1, <?php 
    echo "{$post_id}, '{$nonce}'";
    ?>
, this)" class="imgedit-flipv" title="<?php 
    esc_attr_e('Flip vertically');
    ?>
"></div>
			<div onclick="imageEdit.flip(2, <?php 
    echo "{$post_id}, '{$nonce}'";
    ?>
, this)" class="imgedit-fliph" title="<?php 
    esc_attr_e('Flip horizontally');
    ?>
"></div>

			<div id="image-undo-<?php 
    echo $post_id;
    ?>
" onclick="imageEdit.undo(<?php 
    echo "{$post_id}, '{$nonce}'";
    ?>
, this)" class="imgedit-undo disabled" title="<?php 
    esc_attr_e('Undo');
    ?>
"></div>
			<div id="image-redo-<?php 
    echo $post_id;
    ?>
" onclick="imageEdit.redo(<?php 
    echo "{$post_id}, '{$nonce}'";
    ?>
, this)" class="imgedit-redo disabled" title="<?php 
    esc_attr_e('Redo');
    ?>
"></div>
			<br class="clear" />
		</div>

		<input type="hidden" id="imgedit-sizer-<?php 
    echo $post_id;
    ?>
" value="<?php 
    echo $sizer;
    ?>
" />
		<input type="hidden" id="imgedit-history-<?php 
    echo $post_id;
    ?>
" value="" />
		<input type="hidden" id="imgedit-undone-<?php 
    echo $post_id;
    ?>
" value="0" />
		<input type="hidden" id="imgedit-selection-<?php 
    echo $post_id;
    ?>
" value="" />
		<input type="hidden" id="imgedit-x-<?php 
    echo $post_id;
    ?>
" value="<?php 
    echo isset($meta['width']) ? $meta['width'] : 0;
    ?>
" />
		<input type="hidden" id="imgedit-y-<?php 
    echo $post_id;
    ?>
" value="<?php 
    echo isset($meta['height']) ? $meta['height'] : 0;
    ?>
" />

		<div id="imgedit-crop-<?php 
    echo $post_id;
    ?>
" class="imgedit-crop-wrap">
		<img id="image-preview-<?php 
    echo $post_id;
    ?>
" onload="imageEdit.imgLoaded('<?php 
    echo $post_id;
    ?>
')" src="<?php 
    echo admin_url('admin-ajax.php', 'relative');
    ?>
?action=imgedit-preview&amp;_ajax_nonce=<?php 
    echo $nonce;
    ?>
&amp;postid=<?php 
    echo $post_id;
    ?>
&amp;rand=<?php 
    echo rand(1, 99999);
    ?>
" />
		</div>

		<div class="imgedit-submit">
			<input type="button" onclick="imageEdit.close(<?php 
    echo $post_id;
    ?>
, 1)" class="button" value="<?php 
    esc_attr_e('Cancel');
    ?>
" />
			<input type="button" onclick="imageEdit.save(<?php 
    echo "{$post_id}, '{$nonce}'";
    ?>
)" disabled="disabled" class="button button-primary imgedit-submit-btn" value="<?php 
    esc_attr_e('Save');
    ?>
" />
		</div>
	</div>

	</div>
	<div class="imgedit-wait" id="imgedit-wait-<?php 
    echo $post_id;
    ?>
"></div>
	<script type="text/javascript">jQuery( function() { imageEdit.init(<?php 
    echo $post_id;
    ?>
); });</script>
	<div class="hidden" id="imgedit-leaving-<?php 
    echo $post_id;
    ?>
"><?php 
    _e("There are unsaved changes that will be lost. 'OK' to continue, 'Cancel' to return to the Image Editor.");
    ?>
</div>
	</div>
<?php 
}
Example #28
0
/**
 * Generate post thumbnail attachment meta data.
 *
 * @since 2.1.0
 *
 * @param int $attachment_id Attachment Id to process.
 * @param string $file Filepath of the Attached image.
 * @return mixed Metadata for attachment.
 */
function wp_generate_attachment_metadata_custom($attachment_id, $file, $thumbnails = NULL)
{
    $attachment = get_post($attachment_id);
    $metadata = array();
    if (preg_match('!^image/!', get_post_mime_type($attachment)) && file_is_displayable_image($file)) {
        $imagesize = getimagesize($file);
        $metadata['width'] = $imagesize[0];
        $metadata['height'] = $imagesize[1];
        list($uwidth, $uheight) = wp_constrain_dimensions($metadata['width'], $metadata['height'], 128, 96);
        $metadata['hwstring_small'] = "height='{$uheight}' width='{$uwidth}'";
        // Make the file path relative to the upload dir
        $metadata['file'] = _wp_relative_upload_path($file);
        $sizes = ajax_thumbnail_rebuild_get_sizes();
        $sizes = apply_filters('intermediate_image_sizes_advanced', $sizes);
        foreach ($sizes as $size => $size_data) {
            if (isset($thumbnails) && !in_array($size, $thumbnails)) {
                $intermediate_size = image_get_intermediate_size($attachment_id, $size_data['name']);
            } else {
                $intermediate_size = image_make_intermediate_size($file, $size_data['width'], $size_data['height'], $size_data['crop']);
            }
            if ($intermediate_size) {
                $metadata['sizes'][$size] = $intermediate_size;
            }
        }
        // fetch additional metadata from exif/iptc
        $image_meta = wp_read_image_metadata($file);
        if ($image_meta) {
            $metadata['image_meta'] = $image_meta;
        }
    }
    return apply_filters('wp_generate_attachment_metadata', $metadata, $attachment_id);
}
Example #29
0
/**
 * Trashes or deletes an attachment.
 *
 * When an attachment is permanently deleted, the file will also be removed.
 * Deletion removes all post meta fields, taxonomy, comments, etc. associated
 * with the attachment (except the main post).
 *
 * The attachment is moved to the trash instead of permanently deleted unless trash
 * for media is disabled, item is already in the trash, or $force_delete is true.
 *
 * @since 2.0.0
 * @uses $wpdb
 * @uses do_action() Calls 'delete_attachment' hook on Attachment ID.
 *
 * @param int $post_id Attachment ID.
 * @param bool $force_delete Whether to bypass trash and force deletion. Defaults to false.
 * @return mixed False on failure. Post data on success.
 */
function wp_delete_attachment($post_id, $force_delete = false)
{
    global $wpdb;
    if (!($post = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$wpdb->posts} WHERE ID = %d", $post_id)))) {
        return $post;
    }
    if ('attachment' != $post->post_type) {
        return false;
    }
    if (!$force_delete && EMPTY_TRASH_DAYS && MEDIA_TRASH && 'trash' != $post->post_status) {
        return wp_trash_post($post_id);
    }
    delete_post_meta($post_id, '_wp_trash_meta_status');
    delete_post_meta($post_id, '_wp_trash_meta_time');
    $meta = wp_get_attachment_metadata($post_id);
    $backup_sizes = get_post_meta($post->ID, '_wp_attachment_backup_sizes', true);
    $file = get_attached_file($post_id);
    if (is_multisite()) {
        delete_transient('dirsize_cache');
    }
    do_action('delete_attachment', $post_id);
    wp_delete_object_term_relationships($post_id, array('category', 'post_tag'));
    wp_delete_object_term_relationships($post_id, get_object_taxonomies($post->post_type));
    $wpdb->query($wpdb->prepare("DELETE FROM {$wpdb->postmeta} WHERE meta_key = '_thumbnail_id' AND meta_value = %d", $post_id));
    $comment_ids = $wpdb->get_col($wpdb->prepare("SELECT comment_ID FROM {$wpdb->comments} WHERE comment_post_ID = %d", $post_id));
    if (!empty($comment_ids)) {
        do_action('delete_comment', $comment_ids);
        foreach ($comment_ids as $comment_id) {
            wp_delete_comment($comment_id, true);
        }
        do_action('deleted_comment', $comment_ids);
    }
    $post_meta_ids = $wpdb->get_col($wpdb->prepare("SELECT meta_id FROM {$wpdb->postmeta} WHERE post_id = %d ", $post_id));
    if (!empty($post_meta_ids)) {
        do_action('delete_postmeta', $post_meta_ids);
        $in_post_meta_ids = "'" . implode("', '", $post_meta_ids) . "'";
        $wpdb->query("DELETE FROM {$wpdb->postmeta} WHERE meta_id IN({$in_post_meta_ids})");
        do_action('deleted_postmeta', $post_meta_ids);
    }
    do_action('delete_post', $post_id);
    $wpdb->query($wpdb->prepare("DELETE FROM {$wpdb->posts} WHERE ID = %d", $post_id));
    do_action('deleted_post', $post_id);
    $uploadpath = wp_upload_dir();
    if (!empty($meta['thumb'])) {
        // Don't delete the thumb if another attachment uses it
        if (!$wpdb->get_row($wpdb->prepare("SELECT meta_id FROM {$wpdb->postmeta} WHERE meta_key = '_wp_attachment_metadata' AND meta_value LIKE %s AND post_id <> %d", '%' . $meta['thumb'] . '%', $post_id))) {
            $thumbfile = str_replace(basename($file), $meta['thumb'], $file);
            $thumbfile = apply_filters('wp_delete_file', $thumbfile);
            @unlink(path_join($uploadpath['basedir'], $thumbfile));
        }
    }
    // remove intermediate and backup images if there are any
    foreach (get_intermediate_image_sizes() as $size) {
        if ($intermediate = image_get_intermediate_size($post_id, $size)) {
            $intermediate_file = apply_filters('wp_delete_file', $intermediate['path']);
            @unlink(path_join($uploadpath['basedir'], $intermediate_file));
        }
    }
    if (is_array($backup_sizes)) {
        foreach ($backup_sizes as $size) {
            $del_file = path_join(dirname($meta['file']), $size['file']);
            $del_file = apply_filters('wp_delete_file', $del_file);
            @unlink(path_join($uploadpath['basedir'], $del_file));
        }
    }
    $file = apply_filters('wp_delete_file', $file);
    if (!empty($file)) {
        @unlink($file);
    }
    clean_post_cache($post_id);
    return $post;
}
Example #30
0
/**
 * Retrieve the path or url of an attachment's attached file.
 *
 * If the attached file is not present on the local filesystem (usually due to replication plugins),
 * then the url of the file is returned if url fopen is supported.
 *
 * @since 3.4.0
 * @access private
 *
 * @param string $attachment_id Attachment ID.
 * @param string $size Optional. Image size, defaults to 'full'.
 * @return string|false File path or url on success, false on failure.
 */
function _load_image_to_edit_path($attachment_id, $size = 'full')
{
    $filepath = get_attached_file($attachment_id);
    if ($filepath && file_exists($filepath)) {
        if ('full' != $size && ($data = image_get_intermediate_size($attachment_id, $size))) {
            /**
             * Filter the path to the current image.
             *
             * The filter is evaluated for all image sizes except 'full'.
             *
             * @since 3.1.0
             *
             * @param string $path          Path to the current image.
             * @param string $attachment_id Attachment ID.
             * @param string $size          Size of the image.
             */
            $filepath = apply_filters('load_image_to_edit_filesystempath', path_join(dirname($filepath), $data['file']), $attachment_id, $size);
        }
    } elseif (function_exists('fopen') && function_exists('ini_get') && true == ini_get('allow_url_fopen')) {
        /**
         * Filter the image URL if not in the local filesystem.
         *
         * The filter is only evaluated if fopen is enabled on the server.
         *
         * @since 3.1.0
         *
         * @param string $image_url     Current image URL.
         * @param string $attachment_id Attachment ID.
         * @param string $size          Size of the image.
         */
        $filepath = apply_filters('load_image_to_edit_attachmenturl', wp_get_attachment_url($attachment_id), $attachment_id, $size);
    }
    /**
     * Filter the returned path or URL of the current image.
     *
     * @since 2.9.0
     *
     * @param string|bool $filepath      File path or URL to current image, or false.
     * @param string      $attachment_id Attachment ID.
     * @param string      $size          Size of the image.
     */
    return apply_filters('load_image_to_edit_path', $filepath, $attachment_id, $size);
}