uments 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; } /** * Filters an array of image `srcset` values, replacing each URL with its Photon equivalent. * * @since 3.8.0 * @since 4.0.4 Added automatically additional sizes beyond declared image sizes. * @param array $sources An array of image urls and widths. * @uses self::validate_image_url, jetpack_photon_url, Jetpack_Photon::parse_from_filename * @uses Jetpack_Photon::strip_image_dimensions_maybe, Jetpack::get_content_width * @return array An array of Photon image urls and widths. */ public function filter_srcset_array( $sources = array(), $size_array = array(), $image_src = array(), $image_meta = array(), $attachment_id = 0 ) { if ( ! is_array( $sources ) ) { return $sources; } $upload_dir = wp_get_upload_dir(); foreach ( $sources as $i => $source ) { if ( ! self::validate_image_url( $source['url'] ) ) { continue; } /** This filter is already documented in class.photon.php */ if ( apply_filters( 'jetpack_photon_skip_image', false, $source['url'], $source ) ) { continue; } $url = $source['url']; list( $width, $height ) = self::parse_dimensions_from_filename( $url ); // It's quicker to get the full size with the data we have already, if available if ( ! empty( $attachment_id ) ) { $url = wp_get_attachment_url( $attachment_id ); } else { $url = self::strip_image_dimensions_maybe( $url ); } $args = array(); if ( 'w' === $source['descriptor'] ) { if ( $height && ( $source['value'] == $width ) ) { $args['resize'] = $width . ',' . $height; } else { $args['w'] = $source['value']; } } $sources[ $i ]['url'] = jetpack_photon_url( $url, $args ); } /** * At this point, $sources is the original srcset with Photonized URLs. * Now, we're going to construct additional sizes based on multiples of the content_width. * This will reduce the gap between the largest defined size and the original image. */ /** * Filter the multiplier Photon uses to create new srcset items. * Return false to short-circuit and bypass auto-generation. * * @module photon * * @since 4.0.4 * * @param array|bool $multipliers Array of multipliers to use or false to bypass. */ $multipliers = apply_filters( 'jetpack_photon_srcset_multipliers', array( 2, 3 ) ); $url = trailingslashit( $upload_dir['baseurl'] ) . $image_meta['file']; if ( /** Short-circuit via jetpack_photon_srcset_multipliers filter. */ is_array( $multipliers ) /** This filter is already documented in class.photon.php */ && ! apply_filters( 'jetpack_photon_skip_image', false, $url, null ) /** Verify basic meta is intact. */ && isset( $image_meta['width'] ) && isset( $image_meta['height'] ) && isset( $image_meta['file'] ) /** Verify we have the requested width/height. */ && isset( $size_array[0] ) && isset( $size_array[1] ) ) { $fullwidth = $image_meta['width']; $fullheight = $image_meta['height']; $reqwidth = $size_array[0]; $reqheight = $size_array[1]; $constrained_size = wp_constrain_dimensions( $fullwidth, $fullheight, $reqwidth ); $expected_size = array( $reqwidth, $reqheight ); if ( abs( $constrained_size[0] - $expected_size[0] ) <= 1 && abs( $constrained_size[1] - $expected_size[1] ) <= 1 ) { $crop = 'soft'; $base = Jetpack::get_content_width() ? Jetpack::get_content_width() : 1000; // Provide a default width if none set by the theme. } else { $crop = 'hard'; $base = $reqwidth; } $currentwidths = array_keys( $sources ); $newsources = null; foreach ( $multipliers as $multiplier ) { $newwidth = $base * $multiplier; foreach ( $currentwidths as $currentwidth ) { // If a new width would be within 100 pixes of an existing one or larger than the full size image, skip. if ( abs( $currentwidth - $newwidth ) < 50 || ( $newwidth > $fullwidth ) ) { continue 2; // Back to the foreach ( $multipliers as $multiplier ) } } // foreach ( $currentwidths as $currentwidth ){ if ( 'soft' == $crop ) { $args = array( 'w' => $newwidth, ); } else { // hard crop, e.g. add_image_size( 'example', 200, 200, true ); $args = array( 'zoom' => $multiplier, 'resize' => $reqwidth . ',' . $reqheight, ); } $newsources[ $newwidth ] = array( 'url' => jetpack_photon_url( $url, $args ), 'descriptor' => 'w', 'value' => $newwidth, ); } // foreach ( $multipliers as $multiplier ) if ( is_array( $newsources ) ) { $sources = array_replace( $sources, $newsources ); } } // if ( isset( $image_meta['width'] ) && isset( $image_meta['file'] ) ) return $sources; } /** * Filters an array of image `sizes` values, using $content_width instead of image's full size. * * @since 4.0.4 * @since 4.1.0 Returns early for images not within the_content. * @param array $sizes An array of media query breakpoints. * @param array $size Width and height of the image * @uses Jetpack::get_content_width * @return array An array of media query breakpoints. */ public function filter_sizes( $sizes, $size ) { if ( ! doing_filter( 'the_content' ) ) { return $sizes; } $content_width = Jetpack::get_content_width(); if ( ! $content_width ) { $content_width = 1000; } if ( ( is_array( $size ) && $size[0] < $content_width ) ) { return $sizes; } return sprintf( '(max-width: %1$dpx) 100vw, %1$dpx', $content_width ); } /** * * GENERAL FUNCTIONS **/ /** * Ensure image URL is valid for Photon. * Though Photon functions address some of the URL issues, we should avoid unnecessary processing if we know early on that the image isn't supported. * * @param string $url * @uses wp_parse_args * @return bool */ protected static function validate_image_url( $url ) { $parsed_url = @parse_url( $url ); if ( ! $parsed_url ) { return false; } // Parse URL and ensure needed keys exist, since the array returned by `parse_url` only includes the URL components it finds. $url_info = wp_parse_args( $parsed_url, array( 'scheme' => null, 'host' => null, 'port' => null, 'path' => null, ) ); // Bail if scheme isn't http or port is set that isn't port 80 if ( ( 'http' != $url_info['scheme'] || ! in_array( $url_info['port'], array( 80, null ) ) ) && /** * Allow Photon to fetch images that are served via HTTPS. * * @module photon * * @since 2.4.0 * @since 3.9.0 Default to false. * * @param bool $reject_https Should Photon ignore images using the HTTPS scheme. Default to false. */ apply_filters( 'jetpack_photon_reject_https', false ) ) { return false; } // Bail if no host is found if ( is_null( $url_info['host'] ) ) { return false; } // Bail if the image alredy went through Photon if ( preg_match( '#^i[\d]{1}.wp.com$#i', $url_info['host'] ) ) { return false; } // Bail if no path is found if ( is_null( $url_info['path'] ) ) { return false; } // Ensure image extension is acceptable if ( ! in_array( strtolower( pathinfo( $url_info['path'], PATHINFO_EXTENSION ) ), self::$extensions ) ) { return false; } // If we got this far, we should have an acceptable image URL // But let folks filter to decline if they prefer. /** * Overwrite the results of the validation steps an image goes through before to be considered valid to be used by Photon. * * @module photon * * @since 3.0.0 * * @param bool true Is the image URL valid and can it be used by Photon. Default to true. * @param string $url Image URL. * @param array $parsed_url Array of information about the image. */ return apply_filters( 'photon_validate_image_url', true, $url, $parsed_url ); } /** * Checks if the file exists before it passes the file to photon * * @param string $src The image URL * @return string **/ public static function strip_image_dimensions_maybe( $src ) { $stripped_src = $src; // Build URL, first removing WP's resized string so we pass the original image to Photon if ( preg_match( '#(-\d+x\d+)\.(' . implode( '|', self::$extensions ) . '){1}$#i', $src, $src_parts ) ) { $stripped_src = str_replace( $src_parts[1], '', $src ); $upload_dir = wp_get_upload_dir(); // Extracts the file path to the image minus the base url $file_path = substr( $stripped_src, strlen( $upload_dir['baseurl'] ) ); if ( file_exists( $upload_dir['basedir'] . $file_path ) ) { $src = $stripped_src; } } return $src; } /** * Provide an array of available image sizes and corresponding dimensions. * Similar to get_intermediate_image_sizes() except that it includes image sizes' dimensions, not just their names. * * @global $wp_additional_image_sizes * @uses get_option * @return array */ protected static function image_sizes() { if ( null == self::$image_sizes ) { global $_wp_additional_image_sizes; // Populate an array matching the data structure of $_wp_additional_image_sizes so we have a consistent structure for image sizes $images = array( 'thumb' => array( 'width' => intval( get_option( 'thumbnail_size_w' ) ), 'height' => intval( get_option( 'thumbnail_size_h' ) ), 'crop' => (bool) get_option( 'thumbnail_crop' ), ), 'medium' => array( 'width' => intval( get_option( 'medium_size_w' ) ), 'height' => intval( get_option( 'medium_size_h' ) ), 'crop' => false, ), 'medium_large' => array( 'width' => intval( get_option( 'medium_large_size_w' ) ), 'height' => intval( get_option( 'medium_large_size_h' ) ), 'crop' => false, ), 'large' => array( 'width' => intval( get_option( 'large_size_w' ) ), 'height' => intval( get_option( 'large_size_h' ) ), 'crop' => false, ), 'full' => array( 'width' => null, 'height' => null, 'crop' => false, ), ); // Compatibility mapping as found in wp-includes/media.php $images['thumbnail'] = $images['thumb']; // Update class variable, merging in $_wp_additional_image_sizes if any are set if ( is_array( $_wp_additional_image_sizes ) && ! empty( $_wp_additional_image_sizes ) ) { self::$image_sizes = array_merge( $images, $_wp_additional_image_sizes ); } else { self::$image_sizes = $images; } } return is_array( self::$image_sizes ) ? self::$image_sizes : array(); } /** * Pass og:image URLs through Photon * * @param array $tags * @param array $parameters * @uses jetpack_photon_url * @return array */ function filter_open_graph_tags( $tags, $parameters ) { if ( empty( $tags['og:image'] ) ) { return $tags; } $photon_args = array( 'fit' => sprintf( '%d,%d', 2 * $parameters['image_width'], 2 * $parameters['image_height'] ), ); if ( is_array( $tags['og:image'] ) ) { $images = array(); foreach ( $tags['og:image'] as $image ) { $images[] = jetpack_photon_url( $image, $photon_args ); } $tags['og:image'] = $images; } else { $tags['og:image'] = jetpack_photon_url( $tags['og:image'], $photon_args ); } return $tags; } public function noresize_intermediate_sizes( $sizes ) { return __return_empty_array(); } /** * Enqueue Photon helper script * * @uses wp_enqueue_script, plugins_url * @action wp_enqueue_script * @return null */ public function action_wp_enqueue_scripts() { if ( self::is_amp_endpoint() ) { return; } wp_enqueue_script( 'jetpack-photon', Assets::get_file_url_for_environment( '_inc/build/photon/photon.min.js', 'modules/photon/photon.js' ), array( 'wp-dom-ready' ), 20190901, true ); } /** * Determine if image_downsize should utilize Photon via REST API. * * The WordPress Block Editor (Gutenberg) and other REST API consumers using the wp/v2/media endpoint, especially in the "edit" * context is more akin to the is_admin usage of Photon (see filter_image_downsize). Since consumers are trying to edit content in posts, * Photon should not fire as it will fire later on display. By aborting an attempt to Photonize an image here, we * prevents issues like https://github.com/Automattic/jetpack/issues/10580 . * * To determine if we're using the wp/v2/media endpoint, we hook onto the `rest_request_before_callbacks` filter and * if determined we are using it in the edit context, we'll false out the `jetpack_photon_override_image_downsize` filter. * * @see Jetpack_Photon::filter_image_downsize() * * @param null|WP_Error $response * @param array $endpoint_data * @param WP_REST_Request $request Request used to generate the response. * * @return null|WP_Error The original response object without modification. */ public function should_rest_photon_image_downsize( $response, $endpoint_data, $request ) { if ( ! is_a( $request, 'WP_REST_Request' ) ) { return $response; // Something odd is happening. Do nothing and return the response. } if ( is_wp_error( $response ) ) { // If we're going to return an error, we don't need to do anything with Photon. return $response; } $route = $request->get_route(); if ( false !== strpos( $route, 'wp/v2/media' ) && 'edit' === $request['context'] ) { // Don't use `__return_true()`: Use something unique. See ::_override_image_downsize_in_rest_edit_context() // Late execution to avoid conflict with other plugins as we really don't want to run in this situation. add_filter( 'jetpack_photon_override_image_downsize', array( $this, '_override_image_downsize_in_rest_edit_context' ), 999999 ); } return $response; } /** * Remove the override we may have added in ::should_rest_photon_image_downsize() * Since ::_override_image_downsize_in_rest_edit_context() is only * every used here, we can always remove it without ever worrying * about breaking any other configuration. * * @param mixed $response * @return mixed Unchanged $response */ public function cleanup_rest_photon_image_downsize( $response ) { remove_filter( 'jetpack_photon_override_image_downsize', array( $this, '_override_image_downsize_in_rest_edit_context' ), 999999 ); return $response; } /** * Used internally by ::should_rest_photon_image_downsize() to not photonize * image URLs in ?context=edit REST requests. * MUST NOT be used anywhere else. * We use a unique function instead of __return_true so that we can clean up * after ourselves without breaking anyone else's filters. * * @internal * @return true */ public function _override_image_downsize_in_rest_edit_context() { return true; } /** * Return whether the current page is AMP. * * This is only present for the sake of WordPress.com where the Jetpack_AMP_Support * class does not yet exist. This mehod may only be called at the wp action or later. * * @return bool Whether AMP page. */ private static function is_amp_endpoint() { return class_exists( 'Jetpack_AMP_Support' ) && Jetpack_AMP_Support::is_amp_request(); } }