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;
 }
/**
 * Retrieve the image's intermediate size (resized) path, width, and height.
 *
 * The $size parameter can be an array with the width and height respectively.
 * If the size matches the 'sizes' metadata array for width and height, then it
 * will be used. If there is no direct match, then the nearest image size larger
 * than the specified size will be used. If nothing is found, then the function
 * will break out and return false.
 *
 * The metadata 'sizes' is used for compatible sizes that can be used for the
 * parameter $size value.
 *
 * The url path will be given, when the $size parameter is a string.
 *
 * @since 2.5.0
 *
 * @param int $post_id Attachment ID for image.
 * @param array|string $size Optional, default is 'thumbnail'. Size of image, either array or string.
 * @return bool|array False on failure or array of file path, width, and height on success.
 */
function image_get_intermediate_size($post_id, $size = 'thumbnail')
{
    if (!is_array($imagedata = wp_get_attachment_metadata($post_id))) {
        return false;
    }
    // get the best one for a specified set of dimensions
    if (is_array($size) && !empty($imagedata['sizes'])) {
        foreach ($imagedata['sizes'] as $_size => $data) {
            // already cropped to width or height; so use this size
            if ($data['width'] == $size[0] && $data['height'] <= $size[1] || $data['height'] == $size[1] && $data['width'] <= $size[0]) {
                $file = $data['file'];
                list($width, $height) = image_constrain_size_for_editor($data['width'], $data['height'], $size);
                return compact('file', 'width', 'height');
            }
            // add to lookup table: area => size
            $areas[$data['width'] * $data['height']] = $_size;
        }
        if (!$size || !empty($areas)) {
            // find for the smallest image not smaller than the desired size
            ksort($areas);
            foreach ($areas as $_size) {
                $data = $imagedata['sizes'][$_size];
                if ($data['width'] >= $size[0] || $data['height'] >= $size[1]) {
                    $file = $data['file'];
                    list($width, $height) = image_constrain_size_for_editor($data['width'], $data['height'], $size);
                    return compact('file', 'width', 'height');
                }
            }
        }
    }
    if (is_array($size) || empty($size) || empty($imagedata['sizes'][$size])) {
        return false;
    }
    $data = $imagedata['sizes'][$size];
    // include the full filesystem path of the intermediate file
    if (empty($data['path']) && !empty($data['file'])) {
        $file_url = wp_get_attachment_url($post_id);
        $data['path'] = path_join(dirname($imagedata['file']), $data['file']);
        $data['url'] = path_join(dirname($file_url), $data['file']);
    }
    return $data;
}
 /**
  * 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;
 }
/**
 * Prepares an attachment post object for JS, where it is expected
 * to be JSON-encoded and fit into an Attachment model.
 *
 * @since 3.5.0
 *
 * @param mixed $attachment Attachment ID or object.
 * @return array Array of attachment details.
 */
function wp_prepare_attachment_for_js( $attachment ) {
	if ( ! $attachment = get_post( $attachment ) )
		return;

	if ( 'attachment' != $attachment->post_type )
		return;

	$meta = wp_get_attachment_metadata( $attachment->ID );
	if ( false !== strpos( $attachment->post_mime_type, '/' ) )
		list( $type, $subtype ) = explode( '/', $attachment->post_mime_type );
	else
		list( $type, $subtype ) = array( $attachment->post_mime_type, '' );

	$attachment_url = wp_get_attachment_url( $attachment->ID );

	$response = array(
		'id'          => $attachment->ID,
		'title'       => $attachment->post_title,
		'filename'    => wp_basename( $attachment->guid ),
		'url'         => $attachment_url,
		'link'        => get_attachment_link( $attachment->ID ),
		'alt'         => get_post_meta( $attachment->ID, '_wp_attachment_image_alt', true ),
		'author'      => $attachment->post_author,
		'description' => $attachment->post_content,
		'caption'     => $attachment->post_excerpt,
		'name'        => $attachment->post_name,
		'status'      => $attachment->post_status,
		'uploadedTo'  => $attachment->post_parent,
		'date'        => strtotime( $attachment->post_date_gmt ) * 1000,
		'modified'    => strtotime( $attachment->post_modified_gmt ) * 1000,
		'menuOrder'   => $attachment->menu_order,
		'mime'        => $attachment->post_mime_type,
		'type'        => $type,
		'subtype'     => $subtype,
		'icon'        => wp_mime_type_icon( $attachment->ID ),
		'dateFormatted' => mysql2date( get_option('date_format'), $attachment->post_date ),
		'nonces'      => array(
			'update' => false,
			'delete' => false,
		),
		'editLink'   => false,
	);

	if ( current_user_can( 'edit_post', $attachment->ID ) ) {
		$response['nonces']['update'] = wp_create_nonce( 'update-post_' . $attachment->ID );
		$response['editLink'] = get_edit_post_link( $attachment->ID, 'raw' );
	}

	if ( current_user_can( 'delete_post', $attachment->ID ) )
		$response['nonces']['delete'] = wp_create_nonce( 'delete-post_' . $attachment->ID );

	if ( $meta && 'image' === $type ) {
		$sizes = array();
		/** This filter is documented in wp-admin/includes/media.php */
		$possible_sizes = apply_filters( 'image_size_names_choose', array(
			'thumbnail' => __('Thumbnail'),
			'medium'    => __('Medium'),
			'large'     => __('Large'),
			'full'      => __('Full Size'),
		) );
		unset( $possible_sizes['full'] );

		// Loop through all potential sizes that may be chosen. Try to do this with some efficiency.
		// First: run the image_downsize filter. If it returns something, we can use its data.
		// If the filter does not return something, then image_downsize() is just an expensive
		// way to check the image metadata, which we do second.
		foreach ( $possible_sizes as $size => $label ) {
			if ( $downsize = apply_filters( 'image_downsize', false, $attachment->ID, $size ) ) {
				if ( ! $downsize[3] )
					continue;
				$sizes[ $size ] = array(
					'height'      => $downsize[2],
					'width'       => $downsize[1],
					'url'         => $downsize[0],
					'orientation' => $downsize[2] > $downsize[1] ? 'portrait' : 'landscape',
				);
			} elseif ( isset( $meta['sizes'][ $size ] ) ) {
				if ( ! isset( $base_url ) )
					$base_url = str_replace( wp_basename( $attachment_url ), '', $attachment_url );

				// Nothing from the filter, so consult image metadata if we have it.
				$size_meta = $meta['sizes'][ $size ];

				// We have the actual image size, but might need to further constrain it if content_width is narrower.
				// Thumbnail, medium, and full sizes are also checked against the site's height/width options.
				list( $width, $height ) = image_constrain_size_for_editor( $size_meta['width'], $size_meta['height'], $size, 'edit' );

				$sizes[ $size ] = array(
					'height'      => $height,
					'width'       => $width,
					'url'         => $base_url . $size_meta['file'],
					'orientation' => $height > $width ? 'portrait' : 'landscape',
				);
			}
		}

		$sizes['full'] = array( 'url' => $attachment_url );

		if ( isset( $meta['height'], $meta['width'] ) ) {
			$sizes['full']['height'] = $meta['height'];
			$sizes['full']['width'] = $meta['width'];
			$sizes['full']['orientation'] = $meta['height'] > $meta['width'] ? 'portrait' : 'landscape';
		}

		$response = array_merge( $response, array( 'sizes' => $sizes ), $sizes['full'] );
	} elseif ( $meta && 'video' === $type ) {
		if ( isset( $meta['width'] ) )
			$response['width'] = (int) $meta['width'];
		if ( isset( $meta['height'] ) )
			$response['height'] = (int) $meta['height'];
	}

	if ( $meta && ( 'audio' === $type || 'video' === $type ) ) {
		if ( isset( $meta['length_formatted'] ) )
			$response['fileLength'] = $meta['length_formatted'];
	}

	if ( function_exists('get_compat_media_markup') )
		$response['compat'] = get_compat_media_markup( $attachment->ID, array( 'in_modal' => true ) );

	return apply_filters( 'wp_prepare_attachment_for_js', $response, $attachment, $meta );
}
Example #5
0
/**
 * Retrieve the image's intermediate size (resized) path, width, and height.
 *
 * The $size parameter can be an array with the width and height respectively.
 * If the size matches the 'sizes' metadata array for width and height, then it
 * will be used. If there is no direct match, then the nearest image size larger
 * than the specified size will be used. If nothing is found, then the function
 * will break out and return false.
 *
 * The metadata 'sizes' is used for compatible sizes that can be used for the
 * parameter $size value.
 *
 * The url path will be given, when the $size parameter is a string.
 *
 * If you are passing an array for the $size, you should consider using
 * add_image_size() so that a cropped version is generated. It's much more
 * efficient than having to find the closest-sized image and then having the
 * browser scale down the image.
 *
 * @since 2.5.0
 * @see add_image_size()
 *
 * @param int $post_id Attachment ID for image.
 * @param array|string $size Optional, default is 'thumbnail'. Size of image, either array or string.
 * @return bool|array False on failure or array of file path, width, and height on success.
 */
function image_get_intermediate_size($post_id, $size = 'thumbnail')
{
    if (!is_array($imagedata = wp_get_attachment_metadata($post_id))) {
        return false;
    }
    // get the best one for a specified set of dimensions
    if (is_array($size) && !empty($imagedata['sizes'])) {
        foreach ($imagedata['sizes'] as $_size => $data) {
            // already cropped to width or height; so use this size
            if ($data['width'] == $size[0] && $data['height'] <= $size[1] || $data['height'] == $size[1] && $data['width'] <= $size[0]) {
                $file = $data['file'];
                list($width, $height) = image_constrain_size_for_editor($data['width'], $data['height'], $size);
                return compact('file', 'width', 'height');
            }
            // add to lookup table: area => size
            $areas[$data['width'] * $data['height']] = $_size;
        }
        if (!$size || !empty($areas)) {
            // find for the smallest image not smaller than the desired size
            ksort($areas);
            foreach ($areas as $_size) {
                $data = $imagedata['sizes'][$_size];
                if ($data['width'] >= $size[0] || $data['height'] >= $size[1]) {
                    // Skip images with unexpectedly divergent aspect ratios (crops)
                    // First, we calculate what size the original image would be if constrained to a box the size of the current image in the loop
                    $maybe_cropped = image_resize_dimensions($imagedata['width'], $imagedata['height'], $data['width'], $data['height'], false);
                    // If the size doesn't match within one pixel, then it is of a different aspect ratio, so we skip it, unless it's the thumbnail size
                    if ('thumbnail' != $_size && (!$maybe_cropped || $maybe_cropped[4] != $data['width'] && $maybe_cropped[4] + 1 != $data['width'] || $maybe_cropped[5] != $data['height'] && $maybe_cropped[5] + 1 != $data['height'])) {
                        continue;
                    }
                    // If we're still here, then we're going to use this size
                    $file = $data['file'];
                    list($width, $height) = image_constrain_size_for_editor($data['width'], $data['height'], $size);
                    return compact('file', 'width', 'height');
                }
            }
        }
    }
    if (is_array($size) || empty($size) || empty($imagedata['sizes'][$size])) {
        return false;
    }
    $data = $imagedata['sizes'][$size];
    // include the full filesystem path of the intermediate file
    if (empty($data['path']) && !empty($data['file'])) {
        $file_url = wp_get_attachment_url($post_id);
        $data['path'] = path_join(dirname($imagedata['file']), $data['file']);
        $data['url'] = path_join(dirname($file_url), $data['file']);
    }
    return $data;
}
/**
 * Replace requested image with a Media Vault place-holder
 * if the user is not permitted to view them
 *
 * @since 0.8
 *
 * @param $img mixed false based on wp-includes/media.php or array if other filter has affected it
 * @param $attachment_id int ID of the attachment whose image is being requested
 * @param $size string name-id of the dimensions of the requested image
 * @return mixed return the $url if the image is not protected
 * @return array [0] string URL to the Media Vault replacement image of the requested size
 *               [1] string width of the Media Vault replacement image
 *               [2] string height of the Media Vault replacement image
 *               [3] bool whether the url is for a resized image or not
 */
function mgjp_mv_replace_protected_image($img, $attachment_id, $size)
{
    $ir = get_option('mgjp_mv_ir');
    if (!isset($ir['is_on']) || !$ir['is_on']) {
        return $img;
    }
    $upload_dir = wp_upload_dir();
    if (isset($img[0]) && 0 !== strpos(ltrim($img[0], $upload_dir['baseurl']), mgjp_mv_upload_dir('/', true))) {
        return $img;
    }
    if (mgjp_mv_check_user_permitted($attachment_id)) {
        return $img;
    }
    if (isset($ir['id']) && !mgjp_mv_is_protected($ir['id'])) {
        remove_filter('image_downsize', 'mgjp_mv_replace_protected_image', 999, 3);
        $placeholder = wp_get_attachment_image_src($ir['id'], $size);
        add_filter('image_downsize', 'mgjp_mv_replace_protected_image', 999, 3);
        return $placeholder;
    } else {
        list($width, $height) = image_constrain_size_for_editor(1024, 1024, $size);
        return array(plugins_url('imgs/media-vault-ir.jpg', __FILE__), $width, $height, false);
    }
}
Example #7
0
/**
 * Prepare Media for JSON
 *  this is a copy from send json for attachment, we will improve it in our 1.1 release
 * @todo refactor
 * @param type $attachment
 * @return type
 */
function mpp_media_to_json($attachment)
{
    if (!($attachment = get_post($attachment))) {
        return;
    }
    if ('attachment' != $attachment->post_type) {
        return;
    }
    //the attachment can be either a media or a cover
    //in case of media, if it is non photo, we need the thumb.url to point to the cover(or generated cover)
    //in case of cover, we don't care
    $media = mpp_get_media($attachment->ID);
    $meta = wp_get_attachment_metadata($attachment->ID);
    if (false !== strpos($attachment->post_mime_type, '/')) {
        list($type, $subtype) = explode('/', $attachment->post_mime_type);
    } else {
        list($type, $subtype) = array($attachment->post_mime_type, '');
    }
    $attachment_url = wp_get_attachment_url($attachment->ID);
    $response = array('id' => $media->id, 'title' => $media->title, 'filename' => wp_basename($attachment->guid), 'url' => $attachment_url, 'link' => mpp_get_media_permalink($media), 'alt' => $media->title, 'author' => $media->user_id, 'description' => $media->description, 'caption' => $media->excerpt, 'name' => $media->slug, 'status' => $media->status, 'parent_id' => $media->gallery_id, 'date' => strtotime($attachment->post_date_gmt) * 1000, 'modified' => strtotime($attachment->post_modified_gmt) * 1000, 'menuOrder' => $attachment->menu_order, 'mime' => $attachment->post_mime_type, 'type' => $media->type, 'subtype' => $subtype, 'dateFormatted' => mysql2date(get_option('date_format'), $attachment->post_date), 'meta' => false);
    if ($attachment->post_parent) {
        $post_parent = get_post($attachment->post_parent);
        $parent_type = get_post_type_object($post_parent->post_type);
        if ($parent_type && $parent_type->show_ui && current_user_can('edit_post', $attachment->post_parent)) {
            $response['uploadedToLink'] = get_edit_post_link($attachment->post_parent, 'raw');
        }
        $response['uploadedToTitle'] = $post_parent->post_title ? $post_parent->post_title : __('(no title)');
    }
    $attached_file = get_attached_file($attachment->ID);
    if (file_exists($attached_file)) {
        $bytes = filesize($attached_file);
        $response['filesizeInBytes'] = $bytes;
        $response['filesizeHumanReadable'] = size_format($bytes);
    }
    if ($meta && 'image' === $type) {
        $sizes = array();
        /** This filter is documented in wp-admin/includes/media.php */
        $possible_sizes = apply_filters('image_size_names_choose', array('thumbnail' => __('Thumbnail'), 'medium' => __('Medium'), 'large' => __('Large'), 'full' => __('Full Size')));
        unset($possible_sizes['full']);
        // Loop through all potential sizes that may be chosen. Try to do this with some efficiency.
        // First: run the image_downsize filter. If it returns something, we can use its data.
        // If the filter does not return something, then image_downsize() is just an expensive
        // way to check the image metadata, which we do second.
        foreach ($possible_sizes as $size => $label) {
            /** This filter is documented in wp-includes/media.php */
            if ($downsize = apply_filters('image_downsize', false, $attachment->ID, $size)) {
                if (!$downsize[3]) {
                    continue;
                }
                $sizes[$size] = array('height' => $downsize[2], 'width' => $downsize[1], 'url' => $downsize[0], 'orientation' => $downsize[2] > $downsize[1] ? 'portrait' : 'landscape');
            } elseif (isset($meta['sizes'][$size])) {
                if (!isset($base_url)) {
                    $base_url = str_replace(wp_basename($attachment_url), '', $attachment_url);
                }
                // Nothing from the filter, so consult image metadata if we have it.
                $size_meta = $meta['sizes'][$size];
                // We have the actual image size, but might need to further constrain it if content_width is narrower.
                // Thumbnail, medium, and full sizes are also checked against the site's height/width options.
                list($width, $height) = image_constrain_size_for_editor($size_meta['width'], $size_meta['height'], $size, 'edit');
                $sizes[$size] = array('height' => $height, 'width' => $width, 'url' => $base_url . $size_meta['file'], 'orientation' => $height > $width ? 'portrait' : 'landscape');
            }
        }
        $sizes['full'] = array('url' => $attachment_url);
        if (isset($meta['height'], $meta['width'])) {
            $sizes['full']['height'] = $meta['height'];
            $sizes['full']['width'] = $meta['width'];
            $sizes['full']['orientation'] = $meta['height'] > $meta['width'] ? 'portrait' : 'landscape';
        }
        $response = array_merge($response, array('sizes' => $sizes), $sizes['full']);
    } elseif ($meta && 'video' === $type) {
        if (isset($meta['width'])) {
            $response['width'] = (int) $meta['width'];
        }
        if (isset($meta['height'])) {
            $response['height'] = (int) $meta['height'];
        }
    }
    if ($meta && ('audio' === $type || 'video' === $type)) {
        if (isset($meta['length_formatted'])) {
            $response['fileLength'] = $meta['length_formatted'];
        }
        $response['meta'] = array();
        foreach (wp_get_attachment_id3_keys($attachment, 'js') as $key => $label) {
            $response['meta'][$key] = false;
            if (!empty($meta[$key])) {
                $response['meta'][$key] = $meta[$key];
            }
        }
        $id = mpp_get_media_cover_id($attachment->ID);
        if (!empty($id)) {
            list($url, $width, $height) = wp_get_attachment_image_src($id, 'full');
            $response['image'] = compact('url', 'width', 'height');
            list($url, $width, $height) = wp_get_attachment_image_src($id, 'thumbnail');
            $response['thumb'] = compact('url', 'width', 'height');
        } else {
            $url = mpp_get_media_cover_src('thumbnail', $media->id);
            $width = 48;
            $height = 64;
            $response['image'] = compact('url', 'width', 'height');
            $response['thumb'] = compact('url', 'width', 'height');
        }
    }
    if (!in_array($type, array('image', 'audio', 'video'))) {
        //inject thumbnail
        $url = mpp_get_media_cover_src('thumbnail', $media->id);
        $width = 48;
        $height = 64;
        $response['image'] = compact('url', 'width', 'height');
        $response['thumb'] = compact('url', 'width', 'height');
    }
    return apply_filters('mpp_prepare_media_for_js', $response, $attachment, $meta);
}
Example #8
0
 public function get_cloud_storage_image_downsize($size = 'thumbnail')
 {
     $gcs_url = $this->get_cloud_storage_url();
     if (!$gcs_url) {
         return false;
     }
     $gcs_sizes = $this->get_cloud_storage_image_sizes();
     if (!in_array($size, $gcs_sizes, true)) {
         return false;
     }
     $meta = wp_get_attachment_metadata($this->id);
     $width = $height = 0;
     $is_intermediate = false;
     $gcs_url_basename = wp_basename($gcs_url);
     if ($intermediate = image_get_intermediate_size($this->id, $size)) {
         $gcs_url = str_replace($gcs_url_basename, $intermediate['file'], $gcs_url);
         $width = $intermediate['width'];
         $height = $intermediate['height'];
         $is_intermediate = true;
     } elseif ('thumbnail' === $size) {
         //TODO: can we handle this?
     }
     if (!$width && !$height && $meta && isset($meta['width']) && isset($meta['height'])) {
         $width = $meta['width'];
         $height = $meta['height'];
     }
     list($width, $height) = image_constrain_size_for_editor($width, $height, $size);
     return array($gcs_url, $width, $height, $is_intermediate);
 }
Example #9
0
function media_sfc_photos_form($errors)
{
    global $redir_tab, $type;
    $redir_tab = 'sfcphotos';
    media_upload_header();
    $post_id = intval($_REQUEST['post_id']);
    $user = sfc_cookie_parse();
    if (!isset($user['user_id'])) {
        ?>
<p><?php 
        _e("You don't appear to be logged into Facebook. Click the button below to login and grant photo access.", 'sfc');
        ?>
</p>
		<fb:login-button v="2" scope="offline_access,user_photos" onlogin="******"><?php 
        _e('Connect with Facebook', 'sfc');
        ?>
</fb:login-button><?php 
    }
    if (isset($_GET['send']) && !preg_match('/^[0-9]+$/i', $_GET['send'])) {
        // photo ids are bigints
        unset($_GET['send']);
    }
    if (isset($_GET['send'])) {
        $send_id = $_GET['send'];
        $photo = sfc_photo_get_photo($send_id, $user['code']);
        $photo = apply_filters('sfc_photo_insert', $photo);
        list($width, $height) = image_constrain_size_for_editor($photo['width'], $photo['height'], 'large');
        $alt = '';
        if (!empty($photo['name'])) {
            $alt = esc_attr($photo['name']);
        }
        $html = "<a href='{$photo['link']}'><img src='{$photo['source']}' alt='{$alt}' width='{$width}' height='{$height}' class='size-full fb-image-{$photo['id']}'/></a>";
        if (!empty($photo['name'])) {
            $html = "[caption id='fb_attachment_{$photo['id']}' width='{$width}' caption='{$alt}']" . $html . '[/caption]';
        }
        return media_send_to_editor($html);
    }
    if (!empty($_GET['album']) && !preg_match('/^[0-9]+$/i', $_GET['album'])) {
        // album ids are bigints
        unset($_GET['album']);
    }
    if (!empty($_GET['album'])) {
        // show an album
        $album = $_GET['album'];
        if (false === ($photos = get_transient('sfcphotos-' . $album))) {
            $photos = sfc_remote($album, 'photos', array('code' => $user['code'], 'timeout' => 60, 'limit' => 0));
            if ($photos === false) {
                ?>
<p><?php 
                _e('Facebook is being really, really slow and not responding to requests in a reasonable period of time. Try again later.', 'sfc');
                ?>
</p><?php 
                return;
            }
            // cache the data because Facebook's Graph API is slow as hell
            if (!empty($photos)) {
                set_transient('sfcphotos-' . $album, $photos, 6 * 60 * 60);
            }
            // 6 hours
        }
        if (empty($photos['data'])) {
            ?>
<p><?php 
            _e('This album appears to be empty', 'sfc');
            ?>
</p><?php 
            $link = admin_url("media-upload.php?post_id={$post_id}&type={$type}&tab={$redir_tab}");
            echo "<p><a href='{$link}'>" . __('Go Back', 'sfc') . "</a></p>";
            return;
        }
        $photos = $photos['data'];
        $link = admin_url("media-upload.php?post_id={$post_id}&type={$type}&tab={$redir_tab}");
        echo "<p><a href='{$link}'>" . __('Go Back', 'sfc') . "</a></p>";
        echo '<table><tr>';
        $i = 1;
        foreach ($photos as $photo) {
            echo '<td>';
            $link = admin_url("media-upload.php?post_id={$post_id}&type={$type}&tab={$redir_tab}&album={$album['id']}&send={$photo['id']}");
            echo "<p><a href='{$link}'><img src='{$photo['picture']}' /></a></p>";
            echo '</td>';
            if ($i % 3 == 0) {
                echo '</tr><tr>';
            }
            $i++;
        }
        echo '</tr></table>';
    } else {
        if (false === ($albums = get_transient('sfcphotos-' . $user['user_id']))) {
            $albums = sfc_remote($user['user_id'], 'albums', array('code' => $user['code'], 'timeout' => 60, 'limit' => 0));
            if ($albums === false) {
                ?>
<p><?php 
                _e('Facebook is being really, really slow and not responding to requests in a reasonable period of time. Try again later.', 'sfc');
                ?>
</p><?php 
                return;
            }
            // cache the data because Facebook's Graph API is slow as hell
            if (!empty($albums['data'])) {
                set_transient('sfcphotos-' . $user['user_id'], $albums, 6 * 60 * 60);
            }
            // 6 hours
        }
        if (empty($albums['data'])) {
            ?>
<p><?php 
            _e('Either you have no photo albums on Facebook, or you have not granted the site permission to access them. Either way, click the button below to login and grant access.', 'sfc');
            ?>
</p>
			<fb:login-button v="2" scope="offline_access,user_photos" onlogin="******"><?php 
            _e('Connect with Facebook', 'sfc');
            ?>
</fb:login-button><?php 
        } else {
            $albums = $albums['data'];
            echo '<table><tr>';
            $i = 1;
            foreach ($albums as $album) {
                echo '<td>';
                $link = admin_url("media-upload.php?post_id={$post_id}&type={$type}&tab={$redir_tab}&album={$album['id']}");
                // retrieve the cover image for the album
                if (false !== ($photo = sfc_photo_get_photo($album['cover_photo'], $user['code']))) {
                    echo "<p><a href='{$link}'><img src='{$photo['picture']}' /></a></p>";
                } else {
                    // TODO cover not available
                }
                echo "<p><a href='{$link}'>{$album['name']}</a></p>";
                echo '</td>';
                if ($i % 3 == 0) {
                    echo '</tr><tr>';
                }
                $i++;
            }
            echo '</tr></table>';
        }
    }
}
Example #10
0
/**
 *
 * Modifying the orignial image_downsize function located in wp-includes/media.php
 *
 * Checks if the file with the specified dimesnions exists, before image_get_intermediate_size()
 * and if the file doesnt exist, it creates the file and updates the image metadata. So
 * image_get_intermediate_size()vwill always find the exact image user wants.
 */
function swift_image_downsize($content, $id, $size)
{
    global $_wp_additional_image_sizes;
    global $swift_design_options;
    if (!wp_attachment_is_image($id)) {
        return false;
    }
    $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);
    if (isset($_wp_additional_image_sizes)) {
        $intermediate_image_names = array_keys($_wp_additional_image_sizes);
    } else {
        $intermediate_image_names = array('');
    }
    if (is_array($size)) {
        $width = $size[0];
        $height = $size[1];
    } elseif (in_array($size, $intermediate_image_names)) {
        $width = $_wp_additional_image_sizes[$size]['width'];
        $height = $_wp_additional_image_sizes[$size]['height'];
    } else {
        return;
    }
    if (is_array($size) || in_array($size, $intermediate_image_names)) {
        $uploads = wp_upload_dir();
        if (!isset($meta['file'])) {
            return;
        }
        $file_path = $uploads['basedir'] . '/' . $meta['file'];
        if (file_exists($file_path)) {
            $orig_size = @getimagesize($file_path);
            /*
             * $path_parts = pathinfo('/www/htdocs/inc/lib.inc.php');
             * echo $path_parts['dirname'], "\n";
             * echo $path_parts['basename'], "\n";
             * echo $path_parts['extension'], "\n";
             * echo $path_parts['filename'], "\n"; // since PHP 5.2.0
             * The above example will output:
             *
             * /www/htdocs/inc
             * lib.inc.php
             * php
             * lib.inc
             *
             */
            $file_info = pathinfo($file_path);
            $extension = '.' . $file_info['extension'];
            if ($extension == '.jpeg') {
                $extension = '.jpg';
            }
            // the image path without the extension
            $no_ext_path = $file_info['dirname'] . '/' . $file_info['filename'];
            // If height is set to zero, we will crop the image proportinally
            if ($height == 0) {
                $size[1] = $height = (int) ($width / $orig_size[0] * $orig_size[1]);
            }
            //Generate the cropped image path, and use it check if the image exists
            $cropped_img_path = $no_ext_path . '-' . $width . 'x' . $height . $extension;
            $cropped_img_name = $file_info['filename'] . '-' . $width . 'x' . $height . $extension;
            $cropped_img_path_2x = $no_ext_path . '-' . $width . 'x' . $height . '@2x' . $extension;
            $cropped_img_name_2x = $file_info['filename'] . '-' . $width . 'x' . $height . '@2x' . $extension;
            if ($orig_size[0] > $width && $orig_size[1] > $height) {
                // If the file doesn't exist, we generate it
                if (!file_exists($cropped_img_path)) {
                    $intermediate = image_make_intermediate_size($file_path, $width, $height, true);
                    if (!is_array($size) && $intermediate) {
                        $meta['sizes'][$size] = $intermediate;
                        wp_update_attachment_metadata($id, $meta);
                    }
                }
                $img_url = preg_replace('/' . $file_info['basename'] . '/', $cropped_img_name, $img_url);
            }
            if ($swift_design_options['enable_retina_support'] && ($orig_size[0] > 2 * $width && 2 * $orig_size[1] > $height)) {
                if (!file_exists($cropped_img_path_2x)) {
                    if ($width || $height) {
                        $editor = wp_get_image_editor($file_path);
                        if (!is_wp_error($editor) && !is_wp_error($editor->resize(2 * $width, 2 * $height, true))) {
                            $editor->save($cropped_img_path_2x);
                        }
                    }
                }
            }
        }
    }
    if ($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;
}
 public function filter_attachment_link()
 {
     global $_wp_additional_image_sizes, $extrp_settings;
     if (is_admin()) {
         return;
     }
     if ($this->permalink) {
         $url = esc_url(get_permalink($this->post_id));
         $default_attr = array('href' => $url, 'title' => the_title_attribute('echo=0&post=' . $this->post_id), 'class' => '', 'style' => '');
     }
     if ($this->text) {
         $this->link_text = $this->text;
     } elseif ($this->size && 'none' != $this->size) {
         $this->link_text = $this->get_attachment_image()['link_text'];
         $default_attr['class'] = 'link-' . $this->attachment_id;
         if (-1 == $this->attachment_id) {
             $style = '';
             if (@GetImageSize($this->img_src)) {
                 list($width, $height) = @GetImageSize($this->img_src);
                 list($_w, $_h) = image_constrain_size_for_editor($width, $height, $this->size);
                 $style = 'width:' . $_w . 'px;height:' . $_h . 'px;display:block;';
                 if ($this->crop) {
                     if (isset($_wp_additional_image_sizes[$this->size])) {
                         $this->img_width = $_wp_additional_image_sizes[$this->size]['width'];
                         $this->img_height = $_wp_additional_image_sizes[$this->size]['height'];
                     } else {
                         $this->img_width = get_option($this->size . '_size_w');
                         $this->img_height = get_option($this->size . '_size_h');
                     }
                     $style = 'display:block;width:' . intval($this->img_width) . 'px;height:' . intval($this->img_height) . 'px';
                 }
             }
             $default_attr['class'] = 'link-' . $this->attachment_id;
             $default_attr['style'] = $style;
         } else {
             unset($default_attr['style']);
         }
     } else {
         $this->link_text = '';
     }
     if (trim($this->link_text) == '') {
         $this->link_text = $this->attachment->post_title;
     }
     $this->attr_link = wp_parse_args($default_attr, $this->attr_link);
     $this->attr_link = array_map('esc_attr', $this->attr_link);
     $link = rtrim("<a ");
     foreach ($this->attr_link as $name => $value) {
         $link .= " {$name}=" . '"' . $value . '"';
     }
     $link .= '>';
     $link .= $this->link_text . '</a>';
     return $link;
 }
Example #12
0
 function build_resize_url($url, $metadata, $size)
 {
     if (preg_match('#(.*?)/(v[0-9]+/.*)$#', $url, $matches)) {
         if (!$size) {
             return array($url, $metadata["width"], $metadata["height"], true);
         }
         if (is_array($size)) {
             $wanted = array("width" => $size[0], "height" => $size[1]);
             $crop = false;
         } else {
             $sizes = $this->get_wp_sizes();
             $wanted = $sizes[$size];
             $crop = $wanted["crop"];
         }
         $transformation = "";
         $src_w = $dst_w = $metadata["width"];
         $src_h = $dst_h = $metadata["height"];
         if ($crop) {
             $resized = image_resize_dimensions($metadata['width'], $metadata['height'], $wanted['width'], $wanted['height'], true);
             if ($resized) {
                 list($dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h) = $resized;
                 $transformation = "c_crop,h_{$src_h},w_{$src_w},x_{$src_x},y_{$src_y}/";
             }
         }
         list($width, $height) = image_constrain_size_for_editor($dst_w, $dst_h, $size);
         if ($width != $src_w || $height != $src_h) {
             $transformation = $transformation . "h_{$height},w_{$width}/";
         }
         $url = "{$matches['1']}/{$transformation}{$matches['2']}";
         return array($url, $width, $height, true);
     } else {
         return false;
     }
 }
	function test_constrain_size_for_editor_full() {
		global $content_width;
		$content_width = 400;
		$out = image_constrain_size_for_editor(600, 400, 'full');
		$this->assertEquals(array(600, 400), $out);

		$out = image_constrain_size_for_editor(64, 64, 'full');
		$this->assertEquals(array(64, 64), $out);

		// content_width default is 500
		$content_width = 0;

		$out = image_constrain_size_for_editor(600, 400, 'full');
		$this->assertEquals(array(600, 400), $out);

		$out = image_constrain_size_for_editor(64, 64, 'full');
		$this->assertEquals(array(64, 64), $out);
	}
Example #14
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;
 }
 /**
  * Return image info for the pledge thumbnail.
  * This uses the provided image id, enabling the SharingMetadata class to call it
  * with the id set in its metadata.
  *
  * @param int $screenWidth - pass 0 for default screen width
  * @param int $imageId
  * @return array - URL, width, height
  */
 public static function getPledgeThumbnailById($screenWidth, $imageId)
 {
     $width = self::getPledgeThumbnailWidth($screenWidth);
     // disable photon - we don't want to serve those images from the CDN
     if (class_exists('Jetpack_Photon')) {
         $photon_removed = remove_filter('image_downsize', array(\Jetpack_Photon::instance(), 'filter_image_downsize'));
     }
     // use the "large" image size.  Picking a pre-determined size will allow us to watermark those specific images,
     // even though the selected size may be too large for the device
     $image = image_downsize($imageId, AWC_SOCIAL_PLEDGE_SHARE_IMAGE_SIZE);
     // re-enable photon
     if (!empty($photon_removed)) {
         add_filter('image_downsize', array(\Jetpack_Photon::instance(), 'filter_image_downsize'), 10, 3);
     }
     // scale the image via width / height
     $size = image_constrain_size_for_editor($image[1], $image[2], [$width, $width]);
     return [$image[0], $size[0], $size[1]];
 }
Example #16
0
/**
 * Prepares an attachment post object for JS, where it is expected
 * to be JSON-encoded and fit into an Attachment model.
 *
 * @since 3.5.0
 *
 * @param mixed $attachment Attachment ID or object.
 * @return array|void Array of attachment details.
 */
function wp_prepare_attachment_for_js($attachment)
{
    if (!($attachment = get_post($attachment))) {
        return;
    }
    if ('attachment' != $attachment->post_type) {
        return;
    }
    $meta = wp_get_attachment_metadata($attachment->ID);
    if (false !== strpos($attachment->post_mime_type, '/')) {
        list($type, $subtype) = explode('/', $attachment->post_mime_type);
    } else {
        list($type, $subtype) = array($attachment->post_mime_type, '');
    }
    $attachment_url = wp_get_attachment_url($attachment->ID);
    $response = array('id' => $attachment->ID, 'title' => $attachment->post_title, 'filename' => wp_basename(get_attached_file($attachment->ID)), 'url' => $attachment_url, 'link' => get_attachment_link($attachment->ID), 'alt' => get_post_meta($attachment->ID, '_wp_attachment_image_alt', true), 'author' => $attachment->post_author, 'description' => $attachment->post_content, 'caption' => $attachment->post_excerpt, 'name' => $attachment->post_name, 'status' => $attachment->post_status, 'uploadedTo' => $attachment->post_parent, 'date' => strtotime($attachment->post_date_gmt) * 1000, 'modified' => strtotime($attachment->post_modified_gmt) * 1000, 'menuOrder' => $attachment->menu_order, 'mime' => $attachment->post_mime_type, 'type' => $type, 'subtype' => $subtype, 'icon' => wp_mime_type_icon($attachment->ID), 'dateFormatted' => mysql2date(get_option('date_format'), $attachment->post_date), 'nonces' => array('update' => false, 'delete' => false, 'edit' => false), 'editLink' => false, 'meta' => false);
    $author = new WP_User($attachment->post_author);
    $response['authorName'] = $author->display_name;
    if ($attachment->post_parent) {
        $post_parent = get_post($attachment->post_parent);
    } else {
        $post_parent = false;
    }
    if ($post_parent) {
        $parent_type = get_post_type_object($post_parent->post_type);
        if ($parent_type && $parent_type->show_ui && current_user_can('edit_post', $attachment->post_parent)) {
            $response['uploadedToLink'] = get_edit_post_link($attachment->post_parent, 'raw');
        }
        $response['uploadedToTitle'] = $post_parent->post_title ? $post_parent->post_title : __('(no title)');
    }
    $attached_file = get_attached_file($attachment->ID);
    if (isset($meta['filesize'])) {
        $bytes = $meta['filesize'];
    } elseif (file_exists($attached_file)) {
        $bytes = filesize($attached_file);
    } else {
        $bytes = '';
    }
    if ($bytes) {
        $response['filesizeInBytes'] = $bytes;
        $response['filesizeHumanReadable'] = size_format($bytes);
    }
    if (current_user_can('edit_post', $attachment->ID)) {
        $response['nonces']['update'] = wp_create_nonce('update-post_' . $attachment->ID);
        $response['nonces']['edit'] = wp_create_nonce('image_editor-' . $attachment->ID);
        $response['editLink'] = get_edit_post_link($attachment->ID, 'raw');
    }
    if (current_user_can('delete_post', $attachment->ID)) {
        $response['nonces']['delete'] = wp_create_nonce('delete-post_' . $attachment->ID);
    }
    if ($meta && 'image' === $type) {
        $sizes = array();
        /** This filter is documented in wp-admin/includes/media.php */
        $possible_sizes = apply_filters('image_size_names_choose', array('thumbnail' => __('Thumbnail'), 'medium' => __('Medium'), 'large' => __('Large'), 'full' => __('Full Size')));
        unset($possible_sizes['full']);
        // Loop through all potential sizes that may be chosen. Try to do this with some efficiency.
        // First: run the image_downsize filter. If it returns something, we can use its data.
        // If the filter does not return something, then image_downsize() is just an expensive
        // way to check the image metadata, which we do second.
        foreach ($possible_sizes as $size => $label) {
            /** This filter is documented in wp-includes/media.php */
            if ($downsize = apply_filters('image_downsize', false, $attachment->ID, $size)) {
                if (!$downsize[3]) {
                    continue;
                }
                $sizes[$size] = array('height' => $downsize[2], 'width' => $downsize[1], 'url' => $downsize[0], 'orientation' => $downsize[2] > $downsize[1] ? 'portrait' : 'landscape');
            } elseif (isset($meta['sizes'][$size])) {
                if (!isset($base_url)) {
                    $base_url = str_replace(wp_basename($attachment_url), '', $attachment_url);
                }
                // Nothing from the filter, so consult image metadata if we have it.
                $size_meta = $meta['sizes'][$size];
                // We have the actual image size, but might need to further constrain it if content_width is narrower.
                // Thumbnail, medium, and full sizes are also checked against the site's height/width options.
                list($width, $height) = image_constrain_size_for_editor($size_meta['width'], $size_meta['height'], $size, 'edit');
                $sizes[$size] = array('height' => $height, 'width' => $width, 'url' => $base_url . $size_meta['file'], 'orientation' => $height > $width ? 'portrait' : 'landscape');
            }
        }
        $sizes['full'] = array('url' => $attachment_url);
        if (isset($meta['height'], $meta['width'])) {
            $sizes['full']['height'] = $meta['height'];
            $sizes['full']['width'] = $meta['width'];
            $sizes['full']['orientation'] = $meta['height'] > $meta['width'] ? 'portrait' : 'landscape';
        }
        $response = array_merge($response, array('sizes' => $sizes), $sizes['full']);
    } elseif ($meta && 'video' === $type) {
        if (isset($meta['width'])) {
            $response['width'] = (int) $meta['width'];
        }
        if (isset($meta['height'])) {
            $response['height'] = (int) $meta['height'];
        }
    }
    if ($meta && ('audio' === $type || 'video' === $type)) {
        if (isset($meta['length_formatted'])) {
            $response['fileLength'] = $meta['length_formatted'];
        }
        $response['meta'] = array();
        foreach (wp_get_attachment_id3_keys($attachment, 'js') as $key => $label) {
            $response['meta'][$key] = false;
            if (!empty($meta[$key])) {
                $response['meta'][$key] = $meta[$key];
            }
        }
        $id = get_post_thumbnail_id($attachment->ID);
        if (!empty($id)) {
            list($src, $width, $height) = wp_get_attachment_image_src($id, 'full');
            $response['image'] = compact('src', 'width', 'height');
            list($src, $width, $height) = wp_get_attachment_image_src($id, 'thumbnail');
            $response['thumb'] = compact('src', 'width', 'height');
        } else {
            $src = wp_mime_type_icon($attachment->ID);
            $width = 48;
            $height = 64;
            $response['image'] = compact('src', 'width', 'height');
            $response['thumb'] = compact('src', 'width', 'height');
        }
    }
    if (function_exists('get_compat_media_markup')) {
        $response['compat'] = get_compat_media_markup($attachment->ID, array('in_modal' => true));
    }
    /**
     * Filter the attachment data prepared for JavaScript.
     *
     * @since 3.5.0
     *
     * @param array      $response   Array of prepared attachment data.
     * @param int|object $attachment Attachment ID or object.
     * @param array      $meta       Array of attachment meta data.
     */
    return apply_filters('wp_prepare_attachment_for_js', $response, $attachment, $meta);
}
Example #17
0
function hello_img($value, $id, $size = 'medium')
{
    $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) {
        $header_response = get_headers($img_url, 1);
        if (strpos($header_response[0], "404") == false) {
            // 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);
        } else {
            $html = get_template_directory_uri() . '/assets/img/placeholder/' . $size . '.png';
            return array($html, $width, $height, $is_intermediate);
        }
    }
    return false;
}