wp/wp-includes/media.php
changeset 16 a86126ab1dd4
parent 9 177826044cd9
child 18 be944660c56a
--- a/wp/wp-includes/media.php	Tue Oct 22 16:11:46 2019 +0200
+++ b/wp/wp-includes/media.php	Tue Dec 15 13:49:49 2020 +0100
@@ -17,9 +17,11 @@
  */
 function wp_get_additional_image_sizes() {
 	global $_wp_additional_image_sizes;
+
 	if ( ! $_wp_additional_image_sizes ) {
 		$_wp_additional_image_sizes = array();
 	}
+
 	return $_wp_additional_image_sizes;
 }
 
@@ -36,10 +38,7 @@
  * not set.
  *
  * Finally, there is a filter named {@see 'editor_max_image_size'}, that will be
- * called on the calculated array for width and height, respectively. The second
- * parameter will be the value that was in the $size parameter. The returned
- * type for the hook is an array with the width as the first element and the
- * height as the second element.
+ * called on the calculated array for width and height, respectively.
  *
  * @since 2.5.0
  *
@@ -52,7 +51,12 @@
  *                              Default 'medium'.
  * @param string       $context Optional. Could be 'display' (like in a theme) or 'edit'
  *                              (like inserting into an editor). Default null.
- * @return array Width and height of what the result image should resize to.
+ * @return int[] {
+ *     An array of width and height values.
+ *
+ *     @type int $0 The maximum width in pixels.
+ *     @type int $1 The maximum height in pixels.
+ * }
  */
 function image_constrain_size_for_editor( $width, $height, $size = 'medium', $context = null ) {
 	global $content_width;
@@ -66,26 +70,26 @@
 	if ( is_array( $size ) ) {
 		$max_width  = $size[0];
 		$max_height = $size[1];
-	} elseif ( $size == 'thumb' || $size == 'thumbnail' ) {
+	} elseif ( 'thumb' === $size || 'thumbnail' === $size ) {
 		$max_width  = intval( get_option( 'thumbnail_size_w' ) );
 		$max_height = intval( get_option( 'thumbnail_size_h' ) );
-		// last chance thumbnail size defaults
+		// Last chance thumbnail size defaults.
 		if ( ! $max_width && ! $max_height ) {
 			$max_width  = 128;
 			$max_height = 96;
 		}
-	} elseif ( $size == 'medium' ) {
+	} elseif ( 'medium' === $size ) {
 		$max_width  = intval( get_option( 'medium_size_w' ) );
 		$max_height = intval( get_option( 'medium_size_h' ) );
 
-	} elseif ( $size == 'medium_large' ) {
+	} elseif ( 'medium_large' === $size ) {
 		$max_width  = intval( get_option( 'medium_large_size_w' ) );
 		$max_height = intval( get_option( 'medium_large_size_h' ) );
 
 		if ( intval( $content_width ) > 0 ) {
 			$max_width = min( intval( $content_width ), $max_width );
 		}
-	} elseif ( $size == 'large' ) {
+	} elseif ( 'large' === $size ) {
 		/*
 		 * We're inserting a large size image into the editor. If it's a really
 		 * big image we'll scale it down to fit reasonably within the editor
@@ -94,17 +98,18 @@
 		 */
 		$max_width  = intval( get_option( 'large_size_w' ) );
 		$max_height = intval( get_option( 'large_size_h' ) );
+
 		if ( intval( $content_width ) > 0 ) {
 			$max_width = min( intval( $content_width ), $max_width );
 		}
-	} elseif ( ! empty( $_wp_additional_image_sizes ) && in_array( $size, array_keys( $_wp_additional_image_sizes ) ) ) {
+	} elseif ( ! empty( $_wp_additional_image_sizes ) && in_array( $size, array_keys( $_wp_additional_image_sizes ), true ) ) {
 		$max_width  = intval( $_wp_additional_image_sizes[ $size ]['width'] );
 		$max_height = intval( $_wp_additional_image_sizes[ $size ]['height'] );
 		// Only in admin. Assume that theme authors know what they're doing.
 		if ( intval( $content_width ) > 0 && 'edit' === $context ) {
 			$max_width = min( intval( $content_width ), $max_width );
 		}
-	} else { // $size == 'full' has no constraint
+	} else { // $size === 'full' has no constraint.
 		$max_width  = $width;
 		$max_height = $height;
 	}
@@ -114,8 +119,12 @@
 	 *
 	 * @since 2.5.0
 	 *
-	 * @param array        $max_image_size An array with the width as the first element,
-	 *                                     and the height as the second element.
+	 * @param int[]        $max_image_size {
+	 *     An array of width and height values.
+	 *
+	 *     @type int $0 The maximum width in pixels.
+	 *     @type int $1 The maximum height in pixels.
+	 * }
 	 * @param string|array $size           Size of what the result image should be.
 	 * @param string       $context        The context the image is being resized for.
 	 *                                     Possible values are 'display' (like in a theme)
@@ -157,27 +166,28 @@
 /**
  * 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 {@see '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.
+ * elements that are normally returned from the function.
  *
  * @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,
+ * @param string|int[] $size Optional. Image size to scale to. Accepts any valid image size name,
  *                           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.
+ * @return array|false {
+ *     Array of image data, or boolean false if no image is available.
+ *
+ *     @type string $0 Image source URL.
+ *     @type int    $1 Image width in pixels.
+ *     @type int    $2 Image height in pixels.
+ *     @type bool   $3 Whether the image is a resized image.
+ * }
  */
 function image_downsize( $id, $size = 'medium' ) {
 	$is_image = wp_attachment_is_image( $id );
@@ -185,30 +195,33 @@
 	/**
 	 * Filters 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.
+	 * Returning a truthy value from the filter will effectively short-circuit
+	 * down-sizing the image, returning that value instead.
 	 *
 	 * @since 2.5.0
 	 *
-	 * @param bool         $downsize Whether to short-circuit the image downsize. Default false.
+	 * @param bool|array   $downsize Whether to short-circuit the image downsize.
 	 * @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'.
+	 * @param array|string $size     Requested size of image. Image size name, or array of width
+	 *                               and height values (in that order).
 	 */
-	if ( $out = apply_filters( 'image_downsize', false, $id, $size ) ) {
+	$out = apply_filters( 'image_downsize', false, $id, $size );
+
+	if ( $out ) {
 		return $out;
 	}
 
 	$img_url          = wp_get_attachment_url( $id );
 	$meta             = wp_get_attachment_metadata( $id );
-	$width            = $height = 0;
+	$width            = 0;
+	$height           = 0;
 	$is_intermediate  = false;
 	$img_url_basename = wp_basename( $img_url );
 
 	// If the file isn't an image, attempt to replace its URL with a rendered image from its meta.
 	// Otherwise, a non-image type could be returned.
 	if ( ! $is_image ) {
-		if ( ! empty( $meta['sizes'] ) ) {
+		if ( ! empty( $meta['sizes']['full'] ) ) {
 			$img_url          = str_replace( $img_url_basename, $meta['sizes']['full']['file'], $img_url );
 			$img_url_basename = $meta['sizes']['full']['file'];
 			$width            = $meta['sizes']['full']['width'];
@@ -218,48 +231,50 @@
 		}
 	}
 
-	// try for a new style intermediate size
-	if ( $intermediate = image_get_intermediate_size( $id, $size ) ) {
+	// Try for a new style intermediate size.
+	$intermediate = image_get_intermediate_size( $id, $size );
+
+	if ( $intermediate ) {
 		$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 ) ) {
+	} elseif ( 'thumbnail' === $size ) {
+		// Fall back to the old thumbnail.
+		$thumb_file = wp_get_attachment_thumb_file( $id );
+		$info       = null;
+
+		if ( $thumb_file ) {
+			$info = @getimagesize( $thumb_file );
+		}
+
+		if ( $thumb_file && $info ) {
 			$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
+		// 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
+		// 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;
-
 }
 
 /**
  * Register a new image size.
  *
- * Cropping behavior for the image size is dependent on the value of $crop:
- * 1. If false (default), images will be scaled, not cropped.
- * 2. If an array in the form of array( x_crop_position, y_crop_position ):
- *    - x_crop_position accepts 'left' 'center', or 'right'.
- *    - y_crop_position accepts 'top', 'center', or 'bottom'.
- *    Images will be cropped to the specified dimensions within the defined crop area.
- * 3. If true, images will be cropped to the specified dimensions using center positions.
- *
  * @since 2.9.0
  *
  * @global array $_wp_additional_image_sizes Associative array of additional image sizes.
@@ -267,8 +282,12 @@
  * @param string     $name   Image size identifier.
  * @param int        $width  Optional. Image width in pixels. Default 0.
  * @param int        $height Optional. Image height in pixels. Default 0.
- * @param bool|array $crop   Optional. Whether to crop images to specified width and height or resize.
- *                           An array can specify positioning of the crop area. Default false.
+ * @param bool|array $crop   Optional. Image cropping behavior. If false, the image will be scaled (default),
+ *                           If true, image will be cropped to the specified dimensions using center positions.
+ *                           If an array, the image will be cropped using the array to specify the crop location.
+ *                           Array values must be in the format: array( x_crop_position, y_crop_position ) where:
+ *                               - x_crop_position accepts: 'left', 'center', or 'right'.
+ *                               - y_crop_position accepts: 'top', 'center', or 'bottom'.
  */
 function add_image_size( $name, $width = 0, $height = 0, $crop = false ) {
 	global $_wp_additional_image_sizes;
@@ -345,8 +364,8 @@
  * @since 2.5.0
  *
  * @param int          $id    Attachment ID.
- * @param string       $alt   Image Description for the alt attribute.
- * @param string       $title Image Description for the title attribute.
+ * @param string       $alt   Image description for the alt attribute.
+ * @param string       $title Image description for the title attribute.
  * @param string       $align Part of the class name for aligning the image.
  * @param string|array $size  Optional. Registered image size to retrieve a tag for. Accepts any
  *                            valid image size, or an array of width and height values in pixels
@@ -384,8 +403,8 @@
 	 *
 	 * @param string       $html  HTML content for the image.
 	 * @param int          $id    Attachment ID.
-	 * @param string       $alt   Alternate text.
-	 * @param string       $title Attachment title.
+	 * @param string       $alt   Image description for the alt attribute.
+	 * @param string       $title Image description for the title attribute.
 	 * @param string       $align Part of the class name for aligning the image.
 	 * @param string|array $size  Size of image. Image size or array of width and height values (in that order).
 	 *                            Default 'medium'.
@@ -405,15 +424,22 @@
  * @param int $current_height Current height of the image.
  * @param int $max_width      Optional. Max width in pixels to constrain to. Default 0.
  * @param int $max_height     Optional. Max height in pixels to constrain to. Default 0.
- * @return array First item is the width, the second item is the height.
+ * @return int[] {
+ *     An array of width and height values.
+ *
+ *     @type int $0 The width in pixels.
+ *     @type int $1 The height in pixels.
+ * }
  */
 function wp_constrain_dimensions( $current_width, $current_height, $max_width = 0, $max_height = 0 ) {
 	if ( ! $max_width && ! $max_height ) {
 		return array( $current_width, $current_height );
 	}
 
-	$width_ratio = $height_ratio = 1.0;
-	$did_width   = $did_height = false;
+	$width_ratio  = 1.0;
+	$height_ratio = 1.0;
+	$did_width    = false;
+	$did_height   = false;
 
 	if ( $max_width > 0 && $current_width > 0 && $current_width > $max_width ) {
 		$width_ratio = $max_width / $current_width;
@@ -425,7 +451,7 @@
 		$did_height   = true;
 	}
 
-	// Calculate the larger/smaller ratios
+	// Calculate the larger/smaller ratios.
 	$smaller_ratio = min( $width_ratio, $height_ratio );
 	$larger_ratio  = max( $width_ratio, $height_ratio );
 
@@ -441,18 +467,22 @@
 	$w = max( 1, (int) round( $current_width * $ratio ) );
 	$h = max( 1, (int) round( $current_height * $ratio ) );
 
-	// Sometimes, due to rounding, we'll end up with a result like this: 465x700 in a 177x177 box is 117x176... a pixel short
-	// We also have issues with recursive calls resulting in an ever-changing result. Constraining to the result of a constraint should yield the original result.
-	// Thus we look for dimensions that are one pixel shy of the max value and bump them up
+	/*
+	 * Sometimes, due to rounding, we'll end up with a result like this:
+	 * 465x700 in a 177x177 box is 117x176... a pixel short.
+	 * We also have issues with recursive calls resulting in an ever-changing result.
+	 * Constraining to the result of a constraint should yield the original result.
+	 * Thus we look for dimensions that are one pixel shy of the max value and bump them up.
+	 */
 
 	// Note: $did_width means it is possible $smaller_ratio == $width_ratio.
-	if ( $did_width && $w == $max_width - 1 ) {
-		$w = $max_width; // Round it up
+	if ( $did_width && $w === $max_width - 1 ) {
+		$w = $max_width; // Round it up.
 	}
 
 	// Note: $did_height means it is possible $smaller_ratio == $height_ratio.
-	if ( $did_height && $h == $max_height - 1 ) {
-		$h = $max_height; // Round it up
+	if ( $did_height && $h === $max_height - 1 ) {
+		$h = $max_height; // Round it up.
 	}
 
 	/**
@@ -460,7 +490,12 @@
 	 *
 	 * @since 4.1.0
 	 *
-	 * @param array $dimensions     The image width and height.
+	 * @param int[] $dimensions     {
+	 *     An array of width and height values.
+	 *
+	 *     @type int $0 The width in pixels.
+	 *     @type int $1 The height in pixels.
+	 * }
 	 * @param int   $current_width  The current width of the image.
 	 * @param int   $current_height The current height of the image.
 	 * @param int   $max_width      The maximum width permitted.
@@ -491,14 +526,14 @@
  * @param int        $dest_h New height in pixels.
  * @param bool|array $crop   Optional. Whether to crop image to specified width and height or resize.
  *                           An array can specify positioning of the crop area. Default false.
- * @return false|array False on failure. Returned array matches parameters for `imagecopyresampled()`.
+ * @return array|false Returned array matches parameters for `imagecopyresampled()`. False on failure.
  */
 function image_resize_dimensions( $orig_w, $orig_h, $dest_w, $dest_h, $crop = false ) {
 
 	if ( $orig_w <= 0 || $orig_h <= 0 ) {
 		return false;
 	}
-	// at least one of dest_w or dest_h must be specific
+	// At least one of $dest_w or $dest_h must be specific.
 	if ( $dest_w <= 0 && $dest_h <= 0 ) {
 		return false;
 	}
@@ -506,7 +541,7 @@
 	/**
 	 * Filters whether to preempt calculating the image resize dimensions.
 	 *
-	 * Passing a non-null value to the filter will effectively short-circuit
+	 * Returning a non-null value from the filter will effectively short-circuit
 	 * image_resize_dimensions(), returning that value instead.
 	 *
 	 * @since 3.4.0
@@ -520,12 +555,35 @@
 	 *                           An array can specify positioning of the crop area. Default false.
 	 */
 	$output = apply_filters( 'image_resize_dimensions', null, $orig_w, $orig_h, $dest_w, $dest_h, $crop );
+
 	if ( null !== $output ) {
 		return $output;
 	}
 
+	// Stop if the destination size is larger than the original image dimensions.
+	if ( empty( $dest_h ) ) {
+		if ( $orig_w < $dest_w ) {
+			return false;
+		}
+	} elseif ( empty( $dest_w ) ) {
+		if ( $orig_h < $dest_h ) {
+			return false;
+		}
+	} else {
+		if ( $orig_w < $dest_w && $orig_h < $dest_h ) {
+			return false;
+		}
+	}
+
 	if ( $crop ) {
-		// crop the largest possible portion of the original image that we can size to $dest_w x $dest_h
+		/*
+		 * Crop the largest possible portion of the original image that we can size to $dest_w x $dest_h.
+		 * Note that the requested crop dimensions are used as a maximum bounding box for the original image.
+		 * If the original image's width or height is less than the requested width or height
+		 * only the greater one will be cropped.
+		 * For example when the original image is 600x300, and the requested crop dimensions are 400x400,
+		 * the resulting image will be 400x300.
+		 */
 		$aspect_ratio = $orig_w / $orig_h;
 		$new_w        = min( $dest_w, $orig_w );
 		$new_h        = min( $dest_h, $orig_h );
@@ -565,7 +623,7 @@
 			$s_y = floor( ( $orig_h - $crop_h ) / 2 );
 		}
 	} else {
-		// don't crop, just resize using $dest_w x $dest_h as a maximum bounding box
+		// Resize using $dest_w x $dest_h as a maximum bounding box.
 		$crop_w = $orig_w;
 		$crop_h = $orig_h;
 
@@ -575,15 +633,29 @@
 		list( $new_w, $new_h ) = wp_constrain_dimensions( $orig_w, $orig_h, $dest_w, $dest_h );
 	}
 
-	// if the resulting image would be the same size or larger we don't want to resize it
-	if ( $new_w >= $orig_w && $new_h >= $orig_h && $dest_w != $orig_w && $dest_h != $orig_h ) {
-		return false;
+	if ( wp_fuzzy_number_match( $new_w, $orig_w ) && wp_fuzzy_number_match( $new_h, $orig_h ) ) {
+		// The new size has virtually the same dimensions as the original image.
+
+		/**
+		 * Filters whether to proceed with making an image sub-size with identical dimensions
+		 * with the original/source image. Differences of 1px may be due to rounding and are ignored.
+		 *
+		 * @since 5.3.0
+		 *
+		 * @param bool $proceed The filtered value.
+		 * @param int  $orig_w  Original image width.
+		 * @param int  $orig_h  Original image height.
+		 */
+		$proceed = (bool) apply_filters( 'wp_image_resize_identical_dimensions', false, $orig_w, $orig_h );
+
+		if ( ! $proceed ) {
+			return false;
+		}
 	}
 
-	// the return array matches the parameters to imagecopyresampled()
+	// The return array matches the parameters to imagecopyresampled().
 	// int dst_x, int dst_y, int src_x, int src_y, int dst_w, int dst_h, int src_w, int src_h
 	return array( 0, 0, (int) $s_x, (int) $s_y, (int) $new_w, (int) $new_h, (int) $crop_w, (int) $crop_h );
-
 }
 
 /**
@@ -600,7 +672,7 @@
  * @param int    $height Image height.
  * @param bool   $crop   Optional. Whether to crop image to specified width and height or resize.
  *                       Default false.
- * @return false|array False, if no image was created. Metadata array on success.
+ * @return array|false Metadata array on success. False if no image was created.
  */
 function image_make_intermediate_size( $file, $width, $height, $crop = false ) {
 	if ( $width || $height ) {
@@ -645,7 +717,7 @@
 	}
 
 	// If the image dimensions are within 1px of the expected size, we consider it a match.
-	$matched = ( abs( $constrained_size[0] - $expected_size[0] ) <= 1 && abs( $constrained_size[1] - $expected_size[1] ) <= 1 );
+	$matched = ( wp_fuzzy_number_match( $constrained_size[0], $expected_size[0] ) && wp_fuzzy_number_match( $constrained_size[1], $expected_size[1] ) );
 
 	return $matched;
 }
@@ -675,7 +747,7 @@
  * @param array|string $size    Optional. Image size. Accepts any valid image size, or an array
  *                              of width and height values in pixels (in that order).
  *                              Default 'thumbnail'.
- * @return false|array $data {
+ * @return array|false {
  *     Array of file relative path, width, and height on success. Additionally includes absolute
  *     path and URL if registered size is passed to $size parameter. False on failure.
  *
@@ -687,7 +759,9 @@
  * }
  */
 function image_get_intermediate_size( $post_id, $size = 'thumbnail' ) {
-	if ( ! $size || ! is_array( $imagedata = wp_get_attachment_metadata( $post_id ) ) || empty( $imagedata['sizes'] ) ) {
+	$imagedata = wp_get_attachment_metadata( $post_id );
+
+	if ( ! $size || ! is_array( $imagedata ) || empty( $imagedata['sizes'] ) ) {
 		return false;
 	}
 
@@ -704,7 +778,7 @@
 
 		foreach ( $imagedata['sizes'] as $_size => $data ) {
 			// If there's an exact match to an existing image size, short circuit.
-			if ( $data['width'] == $size[0] && $data['height'] == $size[1] ) {
+			if ( intval( $data['width'] ) === intval( $size[0] ) && intval( $data['height'] ) === intval( $size[1] ) ) {
 				$candidates[ $data['width'] * $data['height'] ] = $data;
 				break;
 			}
@@ -754,7 +828,7 @@
 		return false;
 	}
 
-	// include the full filesystem path of the intermediate file
+	// Include the full filesystem path of the intermediate file.
 	if ( empty( $data['path'] ) && ! empty( $data['file'] ) && ! empty( $imagedata['file'] ) ) {
 		$file_url     = wp_get_attachment_url( $post_id );
 		$data['path'] = path_join( dirname( $imagedata['file'] ), $data['file'] );
@@ -778,17 +852,18 @@
 }
 
 /**
- * Gets the available intermediate image sizes.
+ * Gets the available intermediate image size names.
  *
  * @since 3.0.0
  *
- * @return array Returns a filtered array of image size strings.
+ * @return string[] An array of image size names.
  */
 function get_intermediate_image_sizes() {
-	$_wp_additional_image_sizes = wp_get_additional_image_sizes();
-	$image_sizes                = array( 'thumbnail', 'medium', 'medium_large', 'large' ); // Standard sizes
-	if ( ! empty( $_wp_additional_image_sizes ) ) {
-		$image_sizes = array_merge( $image_sizes, array_keys( $_wp_additional_image_sizes ) );
+	$default_sizes    = array( 'thumbnail', 'medium', 'medium_large', 'large' );
+	$additional_sizes = wp_get_additional_image_sizes();
+
+	if ( ! empty( $additional_sizes ) ) {
+		$default_sizes = array_merge( $default_sizes, array_keys( $additional_sizes ) );
 	}
 
 	/**
@@ -796,58 +871,124 @@
 	 *
 	 * @since 2.5.0
 	 *
-	 * @param array $image_sizes An array of intermediate image sizes. Defaults
-	 *                           are 'thumbnail', 'medium', 'medium_large', 'large'.
+	 * @param string[] $default_sizes An array of intermediate image size names. Defaults
+	 *                                are 'thumbnail', 'medium', 'medium_large', 'large'.
 	 */
-	return apply_filters( 'intermediate_image_sizes', $image_sizes );
+	return apply_filters( 'intermediate_image_sizes', $default_sizes );
 }
 
 /**
- * Retrieve an image to represent an attachment.
- *
- * A mime icon for files, thumbnail or intermediate size for images.
- *
- * The returned array contains four values: the URL of the attachment image src,
- * the width of the image file, the height of the image file, and a boolean
- * representing whether the returned array describes an intermediate (generated)
- * image size or the original, full-sized upload.
+ * Returns a normalized list of all currently registered image sub-sizes.
+ *
+ * @since 5.3.0
+ * @uses wp_get_additional_image_sizes()
+ * @uses get_intermediate_image_sizes()
+ *
+ * @return array Associative array of the registered image sub-sizes.
+ */
+function wp_get_registered_image_subsizes() {
+	$additional_sizes = wp_get_additional_image_sizes();
+	$all_sizes        = array();
+
+	foreach ( get_intermediate_image_sizes() as $size_name ) {
+		$size_data = array(
+			'width'  => 0,
+			'height' => 0,
+			'crop'   => false,
+		);
+
+		if ( isset( $additional_sizes[ $size_name ]['width'] ) ) {
+			// For sizes added by plugins and themes.
+			$size_data['width'] = intval( $additional_sizes[ $size_name ]['width'] );
+		} else {
+			// For default sizes set in options.
+			$size_data['width'] = intval( get_option( "{$size_name}_size_w" ) );
+		}
+
+		if ( isset( $additional_sizes[ $size_name ]['height'] ) ) {
+			$size_data['height'] = intval( $additional_sizes[ $size_name ]['height'] );
+		} else {
+			$size_data['height'] = intval( get_option( "{$size_name}_size_h" ) );
+		}
+
+		if ( empty( $size_data['width'] ) && empty( $size_data['height'] ) ) {
+			// This size isn't set.
+			continue;
+		}
+
+		if ( isset( $additional_sizes[ $size_name ]['crop'] ) ) {
+			$size_data['crop'] = $additional_sizes[ $size_name ]['crop'];
+		} else {
+			$size_data['crop'] = get_option( "{$size_name}_crop" );
+		}
+
+		if ( ! is_array( $size_data['crop'] ) || empty( $size_data['crop'] ) ) {
+			$size_data['crop'] = (bool) $size_data['crop'];
+		}
+
+		$all_sizes[ $size_name ] = $size_data;
+	}
+
+	return $all_sizes;
+}
+
+/**
+ * Retrieves an image to represent an attachment.
  *
  * @since 2.5.0
  *
  * @param int          $attachment_id Image attachment ID.
- * @param string|array $size          Optional. Image size. Accepts any valid image size, or an array of width
+ * @param string|int[] $size          Optional. Image size. Accepts any valid image size name, or an array of width
  *                                    and height values in pixels (in that order). Default 'thumbnail'.
- * @param bool         $icon          Optional. Whether the image should be treated as an icon. Default false.
- * @return false|array Returns an array (url, width, height, is_intermediate), or false, if no image is available.
+ * @param bool         $icon          Optional. Whether the image should fall back to a mime type icon. Default false.
+ * @return array|false {
+ *     Array of image data, or boolean false if no image is available.
+ *
+ *     @type string $0 Image source URL.
+ *     @type int    $1 Image width in pixels.
+ *     @type int    $2 Image height in pixels.
+ *     @type bool   $3 Whether the image is a resized image.
+ * }
  */
 function wp_get_attachment_image_src( $attachment_id, $size = 'thumbnail', $icon = false ) {
-	// get a thumbnail or intermediate image if there is one
+	// Get a thumbnail or intermediate image if there is one.
 	$image = image_downsize( $attachment_id, $size );
 	if ( ! $image ) {
 		$src = false;
 
-		if ( $icon && $src = wp_mime_type_icon( $attachment_id ) ) {
-			/** This filter is documented in wp-includes/post.php */
-			$icon_dir = apply_filters( 'icon_dir', ABSPATH . WPINC . '/images/media' );
-
-			$src_file                = $icon_dir . '/' . wp_basename( $src );
-			@list( $width, $height ) = getimagesize( $src_file );
+		if ( $icon ) {
+			$src = wp_mime_type_icon( $attachment_id );
+
+			if ( $src ) {
+				/** This filter is documented in wp-includes/post.php */
+				$icon_dir = apply_filters( 'icon_dir', ABSPATH . WPINC . '/images/media' );
+
+				$src_file               = $icon_dir . '/' . wp_basename( $src );
+				list( $width, $height ) = @getimagesize( $src_file );
+			}
 		}
 
 		if ( $src && $width && $height ) {
-			$image = array( $src, $width, $height );
+			$image = array( $src, $width, $height, false );
 		}
 	}
 	/**
-	 * Filters the image src result.
+	 * Filters the attachment image source result.
 	 *
 	 * @since 4.3.0
 	 *
-	 * @param array|false  $image         Either array with src, width & height, icon src, or false.
+	 * @param array|false  $image         {
+	 *     Array of image data, or boolean false if no image is available.
+	 *
+	 *     @type string $0 Image source URL.
+	 *     @type int    $1 Image width in pixels.
+	 *     @type int    $2 Image height in pixels.
+	 *     @type bool   $3 Whether the image is a resized image.
+	 * }
 	 * @param int          $attachment_id Image attachment ID.
-	 * @param string|array $size          Size of image. Image size or array of width and height values
-	 *                                    (in that order). Default 'thumbnail'.
-	 * @param bool         $icon          Whether the image should be treated as an icon. Default false.
+	 * @param string|int[] $size          Requested size of image. Image size name, or array of width
+	 *                                    and height values (in that order).
+	 * @param bool         $icon          Whether the image should be treated as an icon.
 	 */
 	return apply_filters( 'wp_get_attachment_image_src', $image, $attachment_id, $size, $icon );
 }
@@ -861,33 +1002,63 @@
  * browser scale down the image.
  *
  * @since 2.5.0
+ * @since 4.4.0 The `$srcset` and `$sizes` attributes were added.
+ * @since 5.5.0 The `$loading` attribute was added.
  *
  * @param int          $attachment_id Image attachment ID.
  * @param string|array $size          Optional. Image size. Accepts any valid image size, or an array of width
  *                                    and height values in pixels (in that order). Default 'thumbnail'.
  * @param bool         $icon          Optional. Whether the image should be treated as an icon. Default false.
- * @param string|array $attr          Optional. Attributes for the image markup. Default empty.
+ * @param string|array $attr {
+ *     Optional. Attributes for the image markup.
+ *
+ *     @type string       $src     Image attachment URL.
+ *     @type string       $class   CSS class name or space-separated list of classes.
+ *                                 Default `attachment-$size_class size-$size_class`,
+ *                                 where `$size_class` is the image size being requested.
+ *     @type string       $alt     Image description for the alt attribute.
+ *     @type string       $srcset  The 'srcset' attribute value.
+ *     @type string       $sizes   The 'sizes' attribute value.
+ *     @type string|false $loading The 'loading' attribute value. Passing a value of false
+ *                                 will result in the attribute being omitted for the image.
+ *                                 Defaults to 'lazy', depending on wp_lazy_loading_enabled().
+ * }
  * @return string HTML img element or empty string on failure.
  */
 function wp_get_attachment_image( $attachment_id, $size = 'thumbnail', $icon = false, $attr = '' ) {
 	$html  = '';
 	$image = wp_get_attachment_image_src( $attachment_id, $size, $icon );
+
 	if ( $image ) {
-		list($src, $width, $height) = $image;
-		$hwstring                   = image_hwstring( $width, $height );
-		$size_class                 = $size;
+		list( $src, $width, $height ) = $image;
+
+		$attachment = get_post( $attachment_id );
+		$hwstring   = image_hwstring( $width, $height );
+		$size_class = $size;
+
 		if ( is_array( $size_class ) ) {
 			$size_class = join( 'x', $size_class );
 		}
-		$attachment   = get_post( $attachment_id );
+
 		$default_attr = array(
 			'src'   => $src,
 			'class' => "attachment-$size_class size-$size_class",
 			'alt'   => trim( strip_tags( get_post_meta( $attachment_id, '_wp_attachment_image_alt', true ) ) ),
 		);
 
+		// Add `loading` attribute.
+		if ( wp_lazy_loading_enabled( 'img', 'wp_get_attachment_image' ) ) {
+			$default_attr['loading'] = 'lazy';
+		}
+
 		$attr = wp_parse_args( $attr, $default_attr );
 
+		// If the default value of `lazy` for the `loading` attribute is overridden
+		// to omit the attribute for this image, ensure it is not included.
+		if ( array_key_exists( 'loading', $attr ) && ! $attr['loading'] ) {
+			unset( $attr['loading'] );
+		}
+
 		// Generate 'srcset' and 'sizes' if not already present.
 		if ( empty( $attr['srcset'] ) ) {
 			$image_meta = wp_get_attachment_metadata( $attachment_id );
@@ -912,17 +1083,21 @@
 		 *
 		 * @since 2.8.0
 		 *
-		 * @param array        $attr       Attributes for the image markup.
+		 * @param array        $attr       Array of attribute values for the image markup, keyed by attribute name.
+		 *                                 See wp_get_attachment_image().
 		 * @param WP_Post      $attachment Image attachment post.
 		 * @param string|array $size       Requested size. Image size or array of width and height values
 		 *                                 (in that order). Default 'thumbnail'.
 		 */
 		$attr = apply_filters( 'wp_get_attachment_image_attributes', $attr, $attachment, $size );
+
 		$attr = array_map( 'esc_attr', $attr );
 		$html = rtrim( "<img $hwstring" );
+
 		foreach ( $attr as $name => $value ) {
 			$html .= " $name=" . '"' . $value . '"';
 		}
+
 		$html .= ' />';
 	}
 
@@ -962,7 +1137,7 @@
 	}
 
 	if ( false !== strpos( $dirname, 'wp-content/uploads' ) ) {
-		// Get the directory name relative to the upload directory (back compat for pre-2.7 uploads)
+		// Get the directory name relative to the upload directory (back compat for pre-2.7 uploads).
 		$dirname = substr( $dirname, strpos( $dirname, 'wp-content/uploads' ) + 18 );
 		$dirname = ltrim( $dirname, '/' );
 	}
@@ -980,11 +1155,10 @@
  *
  * @param string $size_name  Image size. Accepts any valid image size name ('thumbnail', 'medium', etc.).
  * @param array  $image_meta The image meta data.
- * @return array|bool Array of width and height values in pixels (in that order)
- *                    or false if the size doesn't exist.
+ * @return array|bool The image meta data as returned by `wp_get_attachment_metadata()`.
  */
 function _wp_get_image_size_from_meta( $size_name, $image_meta ) {
-	if ( $size_name === 'full' ) {
+	if ( 'full' === $size_name ) {
 		return array(
 			absint( $image_meta['width'] ),
 			absint( $image_meta['height'] ),
@@ -1014,7 +1188,9 @@
  * @return string|bool A 'srcset' value string or false.
  */
 function wp_get_attachment_image_srcset( $attachment_id, $size = 'medium', $image_meta = null ) {
-	if ( ! $image = wp_get_attachment_image_src( $attachment_id, $size ) ) {
+	$image = wp_get_attachment_image_src( $attachment_id, $size );
+
+	if ( ! $image ) {
 		return false;
 	}
 
@@ -1036,10 +1212,15 @@
  *
  * @since 4.4.0
  *
- * @param array  $size_array    Array of width and height values in pixels (in that order).
+ * @param int[]  $size_array    {
+ *     An array of width and height values.
+ *
+ *     @type int $0 The width in pixels.
+ *     @type int $1 The height in pixels.
+ * }
  * @param string $image_src     The 'src' of the image.
  * @param array  $image_meta    The image meta data as returned by 'wp_get_attachment_metadata()'.
- * @param int    $attachment_id Optional. The image attachment ID to pass to the filter. Default 0.
+ * @param int    $attachment_id Optional. The image attachment ID. Default 0.
  * @return string|bool          The 'srcset' attribute value. False on error or when only one source exists.
  */
 function wp_calculate_image_srcset( $size_array, $image_src, $image_meta, $attachment_id = 0 ) {
@@ -1049,7 +1230,12 @@
 	 * @since 4.5.0
 	 *
 	 * @param array  $image_meta    The image meta data as returned by 'wp_get_attachment_metadata()'.
-	 * @param array  $size_array    Array of width and height values in pixels (in that order).
+	 * @param int[]  $size_array    {
+	 *     An array of requested width and height values.
+	 *
+	 *     @type int $0 The width in pixels.
+	 *     @type int $1 The height in pixels.
+	 * }
 	 * @param string $image_src     The 'src' of the image.
 	 * @param int    $attachment_id The image attachment ID or 0 if not supplied.
 	 */
@@ -1117,10 +1303,15 @@
 	 *
 	 * @since 4.4.0
 	 *
-	 * @param int   $max_width  The maximum image width to be included in the 'srcset'. Default '1600'.
-	 * @param array $size_array Array of width and height values in pixels (in that order).
+	 * @param int   $max_width  The maximum image width to be included in the 'srcset'. Default '2048'.
+	 * @param int[] $size_array {
+	 *     An array of requested width and height values.
+	 *
+	 *     @type int $0 The width in pixels.
+	 *     @type int $1 The height in pixels.
+	 * }
 	 */
-	$max_srcset_image_width = apply_filters( 'max_srcset_image_width', 1600, $size_array );
+	$max_srcset_image_width = apply_filters( 'max_srcset_image_width', 2048, $size_array );
 
 	// Array to hold URL candidates.
 	$sources = array();
@@ -1146,7 +1337,8 @@
 
 		// If the file name is part of the `src`, we've confirmed a match.
 		if ( ! $src_matched && false !== strpos( $image_src, $dirname . $image['file'] ) ) {
-			$src_matched = $is_src = true;
+			$src_matched = true;
+			$is_src      = true;
 		}
 
 		// Filter out images that are from previous edits.
@@ -1196,7 +1388,12 @@
 	 *                                  pixel density value if paired with an 'x' descriptor.
 	 *     }
 	 * }
-	 * @param array  $size_array    Array of width and height values in pixels (in that order).
+	 * @param array $size_array     {
+	 *     An array of requested width and height values.
+	 *
+	 *     @type int $0 The width in pixels.
+	 *     @type int $1 The height in pixels.
+	 * }
 	 * @param string $image_src     The 'src' of the image.
 	 * @param array  $image_meta    The image meta data as returned by 'wp_get_attachment_metadata()'.
 	 * @param int    $attachment_id Image attachment ID or 0.
@@ -1232,7 +1429,9 @@
  * @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', $image_meta = null ) {
-	if ( ! $image = wp_get_attachment_image_src( $attachment_id, $size ) ) {
+	$image = wp_get_attachment_image_src( $attachment_id, $size );
+
+	if ( ! $image ) {
 		return false;
 	}
 
@@ -1304,50 +1503,112 @@
 }
 
 /**
- * Filters 'img' elements in post content to add 'srcset' and 'sizes' attributes.
- *
- * @since 4.4.0
- *
- * @see wp_image_add_srcset_and_sizes()
- *
- * @param string $content The raw post content to be filtered.
- * @return string Converted content with 'srcset' and 'sizes' attributes added to images.
+ * Determines if the image meta data is for the image source file.
+ *
+ * The image meta data is retrieved by attachment post ID. In some cases the post IDs may change.
+ * For example when the website is exported and imported at another website. Then the
+ * attachment post IDs that are in post_content for the exported website may not match
+ * the same attachments at the new website.
+ *
+ * @since 5.5.0
+ *
+ * @param string $image_location The full path or URI to the image file.
+ * @param array  $image_meta     The attachment meta data as returned by 'wp_get_attachment_metadata()'.
+ * @param int    $attachment_id  Optional. The image attachment ID. Default 0.
+ * @return bool Whether the image meta is for this image file.
  */
-function wp_make_content_images_responsive( $content ) {
-	if ( ! preg_match_all( '/<img [^>]+>/', $content, $matches ) ) {
-		return $content;
-	}
-
-	$selected_images = $attachment_ids = array();
-
-	foreach ( $matches[0] as $image ) {
-		if ( false === strpos( $image, ' srcset=' ) && preg_match( '/wp-image-([0-9]+)/i', $image, $class_id ) &&
-			( $attachment_id = absint( $class_id[1] ) ) ) {
-
-			/*
-			 * If exactly the same image tag is used more than once, overwrite it.
-			 * All identical tags will be replaced later with 'str_replace()'.
-			 */
-			$selected_images[ $image ] = $attachment_id;
-			// Overwrite the ID when the same image is included more than once.
-			$attachment_ids[ $attachment_id ] = true;
+function wp_image_file_matches_image_meta( $image_location, $image_meta, $attachment_id = 0 ) {
+	$match = false;
+
+	// Ensure the $image_meta is valid.
+	if ( isset( $image_meta['file'] ) && strlen( $image_meta['file'] ) > 4 ) {
+		// Remove quiery args if image URI.
+		list( $image_location ) = explode( '?', $image_location );
+
+		// Check if the relative image path from the image meta is at the end of $image_location.
+		if ( strrpos( $image_location, $image_meta['file'] ) === strlen( $image_location ) - strlen( $image_meta['file'] ) ) {
+			$match = true;
+		} else {
+			// Retrieve the uploads sub-directory from the full size image.
+			$dirname = _wp_get_attachment_relative_path( $image_meta['file'] );
+
+			if ( $dirname ) {
+				$dirname = trailingslashit( $dirname );
+			}
+
+			if ( ! empty( $image_meta['original_image'] ) ) {
+				$relative_path = $dirname . $image_meta['original_image'];
+
+				if ( strrpos( $image_location, $relative_path ) === strlen( $image_location ) - strlen( $relative_path ) ) {
+					$match = true;
+				}
+			}
+
+			if ( ! $match && ! empty( $image_meta['sizes'] ) ) {
+				foreach ( $image_meta['sizes'] as $image_size_data ) {
+					$relative_path = $dirname . $image_size_data['file'];
+
+					if ( strrpos( $image_location, $relative_path ) === strlen( $image_location ) - strlen( $relative_path ) ) {
+						$match = true;
+						break;
+					}
+				}
+			}
 		}
 	}
 
-	if ( count( $attachment_ids ) > 1 ) {
-		/*
-		 * Warm the object cache with post and meta information for all found
-		 * images to avoid making individual database calls.
-		 */
-		_prime_post_caches( array_keys( $attachment_ids ), false, true );
+	/**
+	 * Filter whether an image path or URI matches image meta.
+	 *
+	 * @since 5.5.0
+	 *
+	 * @param bool   $match          Whether the image relative path from the image meta
+	 *                               matches the end of the URI or path to the image file.
+	 * @param string $image_location Full path or URI to the tested image file.
+	 * @param array  $image_meta     The image meta data as returned by 'wp_get_attachment_metadata()'.
+	 * @param int    $attachment_id  The image attachment ID or 0 if not supplied.
+	 */
+	return apply_filters( 'wp_image_file_matches_image_meta', $match, $image_location, $image_meta, $attachment_id );
+}
+
+/**
+ * Determines an image's width and height dimensions based on the source file.
+ *
+ * @since 5.5.0
+ *
+ * @param string $image_src     The image source file.
+ * @param array  $image_meta    The image meta data as returned by 'wp_get_attachment_metadata()'.
+ * @param int    $attachment_id Optional. The image attachment ID. Default 0.
+ * @return array|false Array with first element being the width and second element being the height,
+ *                     or false if dimensions cannot be determined.
+ */
+function wp_image_src_get_dimensions( $image_src, $image_meta, $attachment_id = 0 ) {
+	if ( ! wp_image_file_matches_image_meta( $image_src, $image_meta, $attachment_id ) ) {
+		return false;
 	}
 
-	foreach ( $selected_images as $image => $attachment_id ) {
-		$image_meta = wp_get_attachment_metadata( $attachment_id );
-		$content    = str_replace( $image, wp_image_add_srcset_and_sizes( $image, $image_meta, $attachment_id ), $content );
+	// Is it a full size image?
+	if ( strpos( $image_src, $image_meta['file'] ) !== false ) {
+		return array(
+			(int) $image_meta['width'],
+			(int) $image_meta['height'],
+		);
 	}
 
-	return $content;
+	if ( ! empty( $image_meta['sizes'] ) ) {
+		$src_filename = wp_basename( $image_src );
+
+		foreach ( $image_meta['sizes'] as $image_size_data ) {
+			if ( $src_filename === $image_size_data['file'] ) {
+				return array(
+					(int) $image_size_data['width'],
+					(int) $image_size_data['height'],
+				);
+			}
+		}
+	}
+
+	return false;
 }
 
 /**
@@ -1387,33 +1648,16 @@
 	$width  = preg_match( '/ width="([0-9]+)"/', $image, $match_width ) ? (int) $match_width[1] : 0;
 	$height = preg_match( '/ height="([0-9]+)"/', $image, $match_height ) ? (int) $match_height[1] : 0;
 
-	if ( ! $width || ! $height ) {
-		/*
-		 * If attempts to parse the size value failed, attempt to use the image meta data to match
-		 * the image file name from 'src' against the available sizes for an attachment.
-		 */
-		$image_filename = wp_basename( $image_src );
-
-		if ( $image_filename === wp_basename( $image_meta['file'] ) ) {
-			$width  = (int) $image_meta['width'];
-			$height = (int) $image_meta['height'];
-		} else {
-			foreach ( $image_meta['sizes'] as $image_size_data ) {
-				if ( $image_filename === $image_size_data['file'] ) {
-					$width  = (int) $image_size_data['width'];
-					$height = (int) $image_size_data['height'];
-					break;
-				}
-			}
+	if ( $width && $height ) {
+		$size_array = array( $width, $height );
+	} else {
+		$size_array = wp_image_src_get_dimensions( $image_src, $image_meta, $attachment_id );
+		if ( ! $size_array ) {
+			return $image;
 		}
 	}
 
-	if ( ! $width || ! $height ) {
-		return $image;
-	}
-
-	$size_array = array( $width, $height );
-	$srcset     = wp_calculate_image_srcset( $size_array, $image_src, $image_meta, $attachment_id );
+	$srcset = wp_calculate_image_srcset( $size_array, $image_src, $image_meta, $attachment_id );
 
 	if ( $srcset ) {
 		// Check if there is already a 'sizes' attribute.
@@ -1432,8 +1676,243 @@
 			$attr .= sprintf( ' sizes="%s"', esc_attr( $sizes ) );
 		}
 
-		// Add 'srcset' and 'sizes' attributes to the image markup.
-		$image = preg_replace( '/<img ([^>]+?)[\/ ]*>/', '<img $1' . $attr . ' />', $image );
+		// Add the srcset and sizes attributes to the image markup.
+		return preg_replace( '/<img ([^>]+?)[\/ ]*>/', '<img $1' . $attr . ' />', $image );
+	}
+
+	return $image;
+}
+
+/**
+ * Determine whether to add the `loading` attribute to the specified tag in the specified context.
+ *
+ * @since 5.5.0
+ *
+ * @param string $tag_name The tag name.
+ * @param string $context  Additional context, like the current filter name or the function name from where this was called.
+ * @return bool Whether to add the attribute.
+ */
+function wp_lazy_loading_enabled( $tag_name, $context ) {
+	// By default add to all 'img' tags.
+	// See https://html.spec.whatwg.org/multipage/embedded-content.html#attr-img-loading
+	$default = ( 'img' === $tag_name );
+
+	/**
+	 * Filters whether to add the `loading` attribute to the specified tag in the specified context.
+	 *
+	 * @since 5.5.0
+	 *
+	 * @param bool   $default  Default value.
+	 * @param string $tag_name The tag name.
+	 * @param string $context  Additional context, like the current filter name or the function name from where this was called.
+	 */
+	return (bool) apply_filters( 'wp_lazy_loading_enabled', $default, $tag_name, $context );
+}
+
+/**
+ * Filters specific tags in post content and modifies their markup.
+ *
+ * Modifies HTML tags in post content to include new browser and HTML technologies
+ * that may not have existed at the time of post creation. These modifications currently
+ * include adding `srcset`, `sizes`, and `loading` attributes to `img` HTML tags.
+ * Future similar optimizations should be added/expected here.
+ *
+ * @since 5.5.0
+ *
+ * @see wp_img_tag_add_width_and_height_attr()
+ * @see wp_img_tag_add_srcset_and_sizes_attr()
+ * @see wp_img_tag_add_loading_attr()
+ *
+ * @param string $content The HTML content to be filtered.
+ * @param string $context Optional. Additional context to pass to the filters.
+ *                        Defaults to `current_filter()` when not set.
+ * @return string Converted content with images modified.
+ */
+function wp_filter_content_tags( $content, $context = null ) {
+	if ( null === $context ) {
+		$context = current_filter();
+	}
+
+	$add_loading_attr = wp_lazy_loading_enabled( 'img', $context );
+
+	if ( false === strpos( $content, '<img' ) ) {
+		return $content;
+	}
+
+	if ( ! preg_match_all( '/<img\s[^>]+>/', $content, $matches ) ) {
+		return $content;
+	}
+
+	// List of the unique `img` tags found in $content.
+	$images = array();
+
+	foreach ( $matches[0] as $image ) {
+		if ( preg_match( '/wp-image-([0-9]+)/i', $image, $class_id ) ) {
+			$attachment_id = absint( $class_id[1] );
+
+			if ( $attachment_id ) {
+				// If exactly the same image tag is used more than once, overwrite it.
+				// All identical tags will be replaced later with 'str_replace()'.
+				$images[ $image ] = $attachment_id;
+				continue;
+			}
+		}
+
+		$images[ $image ] = 0;
+	}
+
+	// Reduce the array to unique attachment IDs.
+	$attachment_ids = array_unique( array_filter( array_values( $images ) ) );
+
+	if ( count( $attachment_ids ) > 1 ) {
+		/*
+		 * Warm the object cache with post and meta information for all found
+		 * images to avoid making individual database calls.
+		 */
+		_prime_post_caches( $attachment_ids, false, true );
+	}
+
+	foreach ( $images as $image => $attachment_id ) {
+		$filtered_image = $image;
+
+		// Add 'width' and 'height' attributes if applicable.
+		if ( $attachment_id > 0 && false === strpos( $filtered_image, ' width=' ) && false === strpos( $filtered_image, ' height=' ) ) {
+			$filtered_image = wp_img_tag_add_width_and_height_attr( $filtered_image, $context, $attachment_id );
+		}
+
+		// Add 'srcset' and 'sizes' attributes if applicable.
+		if ( $attachment_id > 0 && false === strpos( $filtered_image, ' srcset=' ) ) {
+			$filtered_image = wp_img_tag_add_srcset_and_sizes_attr( $filtered_image, $context, $attachment_id );
+		}
+
+		// Add 'loading' attribute if applicable.
+		if ( $add_loading_attr && false === strpos( $filtered_image, ' loading=' ) ) {
+			$filtered_image = wp_img_tag_add_loading_attr( $filtered_image, $context );
+		}
+
+		if ( $filtered_image !== $image ) {
+			$content = str_replace( $image, $filtered_image, $content );
+		}
+	}
+
+	return $content;
+}
+
+/**
+ * Adds `loading` attribute to an `img` HTML tag.
+ *
+ * @since 5.5.0
+ *
+ * @param string $image   The HTML `img` tag where the attribute should be added.
+ * @param string $context Additional context to pass to the filters.
+ * @return string Converted `img` tag with `loading` attribute added.
+ */
+function wp_img_tag_add_loading_attr( $image, $context ) {
+	/**
+	 * Filters the `loading` attribute value. Default `lazy`.
+	 *
+	 * Returning `false` or an empty string will not add the attribute.
+	 * Returning `true` will add the default value.
+	 *
+	 * @since 5.5.0
+	 *
+	 * @param string|bool $value   The `loading` attribute value. Returning a falsey value will result in
+	 *                             the attribute being omitted for the image. Default is `lazy`.
+	 * @param string      $image   The HTML `img` tag to be filtered.
+	 * @param string      $context Additional context about how the function was called or where the img tag is.
+	 */
+	$value = apply_filters( 'wp_img_tag_add_loading_attr', 'lazy', $image, $context );
+
+	if ( $value ) {
+		if ( ! in_array( $value, array( 'lazy', 'eager' ), true ) ) {
+			$value = 'lazy';
+		}
+
+		// Images should have source and dimension attributes for the `loading` attribute to be added.
+		if ( false === strpos( $image, ' src="' ) || false === strpos( $image, ' width="' ) || false === strpos( $image, ' height="' ) ) {
+			return $image;
+		}
+
+		return str_replace( '<img', '<img loading="' . esc_attr( $value ) . '"', $image );
+	}
+
+	return $image;
+}
+
+/**
+ * Adds `width` and `height` attributes to an `img` HTML tag.
+ *
+ * @since 5.5.0
+ *
+ * @param string $image         The HTML `img` tag where the attribute should be added.
+ * @param string $context       Additional context to pass to the filters.
+ * @param int    $attachment_id Image attachment ID.
+ * @return string Converted 'img' element with 'width' and 'height' attributes added.
+ */
+function wp_img_tag_add_width_and_height_attr( $image, $context, $attachment_id ) {
+	$image_src         = preg_match( '/src="([^"]+)"/', $image, $match_src ) ? $match_src[1] : '';
+	list( $image_src ) = explode( '?', $image_src );
+
+	// Return early if we couldn't get the image source.
+	if ( ! $image_src ) {
+		return $image;
+	}
+
+	/**
+	 * Filters whether to add the missing `width` and `height` HTML attributes to the img tag. Default `true`.
+	 *
+	 * Returning anything else than `true` will not add the attributes.
+	 *
+	 * @since 5.5.0
+	 *
+	 * @param bool   $value         The filtered value, defaults to `true`.
+	 * @param string $image         The HTML `img` tag where the attribute should be added.
+	 * @param string $context       Additional context about how the function was called or where the img tag is.
+	 * @param int    $attachment_id The image attachment ID.
+	 */
+	$add = apply_filters( 'wp_img_tag_add_width_and_height_attr', true, $image, $context, $attachment_id );
+
+	if ( true === $add ) {
+		$image_meta = wp_get_attachment_metadata( $attachment_id );
+		$size_array = wp_image_src_get_dimensions( $image_src, $image_meta, $attachment_id );
+
+		if ( $size_array ) {
+			$hw = trim( image_hwstring( $size_array[0], $size_array[1] ) );
+			return str_replace( '<img', "<img {$hw}", $image );
+		}
+	}
+
+	return $image;
+}
+
+/**
+ * Adds `srcset` and `sizes` attributes to an existing `img` HTML tag.
+ *
+ * @since 5.5.0
+ *
+ * @param string $image         The HTML `img` tag where the attribute should be added.
+ * @param string $context       Additional context to pass to the filters.
+ * @param int    $attachment_id Image attachment ID.
+ * @return string Converted 'img' element with 'loading' attribute added.
+ */
+function wp_img_tag_add_srcset_and_sizes_attr( $image, $context, $attachment_id ) {
+	/**
+	 * Filters whether to add the `srcset` and `sizes` HTML attributes to the img tag. Default `true`.
+	 *
+	 * Returning anything else than `true` will not add the attributes.
+	 *
+	 * @since 5.5.0
+	 *
+	 * @param bool   $value         The filtered value, defaults to `true`.
+	 * @param string $image         The HTML `img` tag where the attribute should be added.
+	 * @param string $context       Additional context about how the function was called or where the img tag is.
+	 * @param int    $attachment_id The image attachment ID.
+	 */
+	$add = apply_filters( 'wp_img_tag_add_srcset_and_sizes_attr', true, $image, $context, $attachment_id );
+
+	if ( true === $add ) {
+		$image_meta = wp_get_attachment_metadata( $attachment_id );
+		return wp_image_add_srcset_and_sizes( $image, $image_meta, $attachment_id );
 	}
 
 	return $image;
@@ -1448,8 +1927,8 @@
  * @ignore
  * @since 2.9.0
  *
- * @param array $attr Thumbnail attributes including src, class, alt, title.
- * @return array Modified array of attributes including the new 'wp-post-image' class.
+ * @param string[] $attr Array of thumbnail attributes including src, class, alt, title, keyed by attribute name.
+ * @return string[] Modified array of attributes including the new 'wp-post-image' class.
  */
 function _wp_post_thumbnail_class_filter( $attr ) {
 	$attr['class'] .= ' wp-post-image';
@@ -1463,7 +1942,7 @@
  * @ignore
  * @since 2.9.0
  *
- * @param array $attr Thumbnail attributes including src, class, alt, title.
+ * @param string[] $attr Array of thumbnail attributes including src, class, alt, title, keyed by attribute name.
  */
 function _wp_post_thumbnail_class_filter_add( $attr ) {
 	add_filter( 'wp_get_attachment_image_attributes', '_wp_post_thumbnail_class_filter' );
@@ -1476,7 +1955,7 @@
  * @ignore
  * @since 2.9.0
  *
- * @param array $attr Thumbnail attributes including src, class, alt, title.
+ * @param string[] $attr Array of thumbnail attributes including src, class, alt, title, keyed by attribute name.
  */
 function _wp_post_thumbnail_class_filter_remove( $attr ) {
 	remove_filter( 'wp_get_attachment_image_attributes', '_wp_post_thumbnail_class_filter' );
@@ -1539,7 +2018,8 @@
 	 * @param string $content The image element, possibly wrapped in a hyperlink.
 	 */
 	$output = apply_filters( 'img_caption_shortcode', '', $attr, $content );
-	if ( $output != '' ) {
+
+	if ( ! empty( $output ) ) {
 		return $output;
 	}
 
@@ -1557,11 +2037,14 @@
 	);
 
 	$atts['width'] = (int) $atts['width'];
+
 	if ( $atts['width'] < 1 || empty( $atts['caption'] ) ) {
 		return $content;
 	}
 
-	$id = $caption_id = $describedby = '';
+	$id          = '';
+	$caption_id  = '';
+	$describedby = '';
 
 	if ( $atts['id'] ) {
 		$atts['id'] = sanitize_html_class( $atts['id'] );
@@ -1582,7 +2065,7 @@
 	$class = trim( 'wp-caption ' . $atts['align'] . ' ' . $atts['class'] );
 
 	$html5 = current_theme_supports( 'html5', 'caption' );
-	// HTML5 captions never added the extra 10px to the image width
+	// HTML5 captions never added the extra 10px to the image width.
 	$width = $html5 ? $atts['width'] : ( 10 + $atts['width'] );
 
 	/**
@@ -1603,6 +2086,7 @@
 	$caption_width = apply_filters( 'img_caption_shortcode_width', $width, $atts, $content );
 
 	$style = '';
+
 	if ( $caption_width ) {
 		$style = 'style="width: ' . (int) $caption_width . 'px" ';
 	}
@@ -1649,8 +2133,6 @@
  *
  * @since 2.5.0
  *
- * @staticvar int $instance
- *
  * @param array $attr {
  *     Attributes of the gallery shortcode.
  *
@@ -1705,7 +2187,8 @@
 	 * @param int    $instance Unique numeric ID of this gallery shortcode instance.
 	 */
 	$output = apply_filters( 'post_gallery', '', $attr, $instance );
-	if ( $output != '' ) {
+
+	if ( ! empty( $output ) ) {
 		return $output;
 	}
 
@@ -1778,7 +2261,16 @@
 	if ( is_feed() ) {
 		$output = "\n";
 		foreach ( $attachments as $att_id => $attachment ) {
-			$output .= wp_get_attachment_link( $att_id, $atts['size'], true ) . "\n";
+			if ( ! empty( $atts['link'] ) ) {
+				if ( 'none' === $atts['link'] ) {
+					$output .= wp_get_attachment_image( $att_id, $atts['size'], false, $attr );
+				} else {
+					$output .= wp_get_attachment_link( $att_id, $atts['size'], false );
+				}
+			} else {
+				$output .= wp_get_attachment_link( $att_id, $atts['size'], true );
+			}
+			$output .= "\n";
 		}
 		return $output;
 	}
@@ -1815,8 +2307,10 @@
 	 *                    Otherwise, defaults to true.
 	 */
 	if ( apply_filters( 'use_default_gallery_style', ! $html5 ) ) {
+		$type_attr = current_theme_supports( 'html5', 'style' ) ? '' : ' type="text/css"';
+
 		$gallery_style = "
-		<style type='text/css'>
+		<style{$type_attr}>
 			#{$selector} {
 				margin: auto;
 			}
@@ -1850,9 +2344,11 @@
 	$output = apply_filters( 'gallery_style', $gallery_style . $gallery_div );
 
 	$i = 0;
+
 	foreach ( $attachments as $id => $attachment ) {
 
 		$attr = ( trim( $attachment->post_excerpt ) ) ? array( 'aria-describedby' => "$selector-$id" ) : '';
+
 		if ( ! empty( $atts['link'] ) && 'file' === $atts['link'] ) {
 			$image_output = wp_get_attachment_link( $id, $atts['size'], false, false, false, $attr );
 		} elseif ( ! empty( $atts['link'] ) && 'none' === $atts['link'] ) {
@@ -1860,30 +2356,36 @@
 		} else {
 			$image_output = wp_get_attachment_link( $id, $atts['size'], true, false, false, $attr );
 		}
+
 		$image_meta = wp_get_attachment_metadata( $id );
 
 		$orientation = '';
+
 		if ( isset( $image_meta['height'], $image_meta['width'] ) ) {
 			$orientation = ( $image_meta['height'] > $image_meta['width'] ) ? 'portrait' : 'landscape';
 		}
+
 		$output .= "<{$itemtag} class='gallery-item'>";
 		$output .= "
 			<{$icontag} class='gallery-icon {$orientation}'>
 				$image_output
 			</{$icontag}>";
+
 		if ( $captiontag && trim( $attachment->post_excerpt ) ) {
 			$output .= "
 				<{$captiontag} class='wp-caption-text gallery-caption' id='$selector-$id'>
 				" . wptexturize( $attachment->post_excerpt ) . "
 				</{$captiontag}>";
 		}
+
 		$output .= "</{$itemtag}>";
-		if ( ! $html5 && $columns > 0 && ++$i % $columns == 0 ) {
+
+		if ( ! $html5 && $columns > 0 && 0 === ++$i % $columns ) {
 			$output .= '<br style="clear: both" />';
 		}
 	}
 
-	if ( ! $html5 && $columns > 0 && $i % $columns !== 0 ) {
+	if ( ! $html5 && $columns > 0 && 0 !== $i % $columns ) {
 		$output .= "
 			<br style='clear: both' />";
 	}
@@ -1908,7 +2410,7 @@
 	<div class="wp-playlist-caption">
 		<span class="wp-playlist-item-meta wp-playlist-item-title">
 		<?php
-			/* translators: playlist item title */
+			/* translators: %s: Playlist item title. */
 			printf( _x( '&#8220;%s&#8221;', 'playlist item title' ), '{{ data.title }}' );
 		?>
 		</span>
@@ -1925,7 +2427,7 @@
 			<# } else { #>
 				<span class="wp-playlist-item-title">
 				<?php
-					/* translators: playlist item title */
+					/* translators: %s: Playlist item title. */
 					printf( _x( '&#8220;%s&#8221;', 'playlist item title' ), '{{{ data.title }}}' );
 				?>
 				</span>
@@ -1968,7 +2470,6 @@
  * @since 3.9.0
  *
  * @global int $content_width
- * @staticvar int $instance
  *
  * @param array $attr {
  *     Array of default playlist attributes.
@@ -2014,7 +2515,7 @@
 	/**
 	 * Filters the playlist output.
 	 *
-	 * Passing a non-empty value to the filter will short-circuit generation
+	 * Returning a non-empty value from the filter will short-circuit generation
 	 * of the default playlist output, returning the passed value instead.
 	 *
 	 * @since 3.9.0
@@ -2025,7 +2526,8 @@
 	 * @param int    $instance Unique numeric ID of this playlist shortcode instance.
 	 */
 	$output = apply_filters( 'post_playlist', '', $attr, $instance );
-	if ( $output != '' ) {
+
+	if ( ! empty( $output ) ) {
 		return $output;
 	}
 
@@ -2049,7 +2551,7 @@
 
 	$id = intval( $atts['id'] );
 
-	if ( $atts['type'] !== 'audio' ) {
+	if ( 'audio' !== $atts['type'] ) {
 		$atts['type'] = 'video';
 	}
 
@@ -2090,7 +2592,7 @@
 		return $output;
 	}
 
-	$outer = 22; // default padding and border of wrapper
+	$outer = 22; // Default padding and border of wrapper.
 
 	$default_width  = 640;
 	$default_height = 360;
@@ -2100,7 +2602,7 @@
 
 	$data = array(
 		'type'         => $atts['type'],
-		// don't pass strings to JSON, will be truthy in JS
+		// Don't pass strings to JSON, will be truthy in JS.
 		'tracklist'    => wp_validate_boolean( $atts['tracklist'] ),
 		'tracknumbers' => wp_validate_boolean( $atts['tracknumbers'] ),
 		'images'       => wp_validate_boolean( $atts['images'] ),
@@ -2240,11 +2742,11 @@
 }
 
 /**
- * Returns a filtered list of WP-supported audio formats.
+ * Returns a filtered list of supported audio formats.
  *
  * @since 3.6.0
  *
- * @return array Supported audio formats.
+ * @return string[] Supported audio formats.
  */
 function wp_get_audio_extensions() {
 	/**
@@ -2252,8 +2754,8 @@
 	 *
 	 * @since 3.6.0
 	 *
-	 * @param array $extensions An array of supported audio formats. Defaults are
-	 *                          'mp3', 'ogg', 'flac', 'm4a', 'wav'.
+	 * @param string[] $extensions An array of supported audio formats. Defaults are
+	 *                            'mp3', 'ogg', 'flac', 'm4a', 'wav'.
 	 */
 	return apply_filters( 'wp_audio_extensions', array( 'mp3', 'ogg', 'flac', 'm4a', 'wav' ) );
 }
@@ -2265,7 +2767,7 @@
  *
  * @param WP_Post $attachment The current attachment, provided for context.
  * @param string  $context    Optional. The context. Accepts 'edit', 'display'. Default 'display'.
- * @return array Key/value pairs of field keys to labels.
+ * @return string[] Key/value pairs of field keys to labels.
  */
 function wp_get_attachment_id3_keys( $attachment, $context = 'display' ) {
 	$fields = array(
@@ -2301,8 +2803,6 @@
  *
  * @since 3.6.0
  *
- * @staticvar int $instance
- *
  * @param array  $attr {
  *     Attributes of the audio shortcode.
  *
@@ -2335,6 +2835,7 @@
 	 * @param int    $instance Unique numeric ID of this audio shortcode instance.
 	 */
 	$override = apply_filters( 'wp_audio_shortcode_override', '', $attr, $content, $instance );
+
 	if ( '' !== $override ) {
 		return $override;
 	}
@@ -2359,15 +2860,18 @@
 	$primary = false;
 	if ( ! empty( $atts['src'] ) ) {
 		$type = wp_check_filetype( $atts['src'], wp_get_mime_types() );
-		if ( ! in_array( strtolower( $type['ext'] ), $default_types ) ) {
+
+		if ( ! in_array( strtolower( $type['ext'] ), $default_types, true ) ) {
 			return sprintf( '<a class="wp-embedded-audio" href="%s">%s</a>', esc_url( $atts['src'] ), esc_html( $atts['src'] ) );
 		}
+
 		$primary = true;
 		array_unshift( $default_types, 'src' );
 	} else {
 		foreach ( $default_types as $ext ) {
 			if ( ! empty( $atts[ $ext ] ) ) {
 				$type = wp_check_filetype( $atts[ $ext ], wp_get_mime_types() );
+
 				if ( strtolower( $type['ext'] ) === $ext ) {
 					$primary = true;
 				}
@@ -2377,12 +2881,14 @@
 
 	if ( ! $primary ) {
 		$audios = get_attached_media( 'audio', $post_id );
+
 		if ( empty( $audios ) ) {
 			return;
 		}
 
 		$audio       = reset( $audios );
 		$atts['src'] = wp_get_attachment_url( $audio->ID );
+
 		if ( empty( $atts['src'] ) ) {
 			return;
 		}
@@ -2398,6 +2904,7 @@
 	 * @param string $library Media library used for the audio shortcode.
 	 */
 	$library = apply_filters( 'wp_audio_shortcode_library', 'mediaelement' );
+
 	if ( 'mediaelement' === $library && did_action( 'init' ) ) {
 		wp_enqueue_style( 'wp-mediaelement' );
 		wp_enqueue_script( 'wp-mediaelement' );
@@ -2423,7 +2930,7 @@
 		'style'    => $atts['style'],
 	);
 
-	// These ones should just be omitted altogether if they are blank
+	// These ones should just be omitted altogether if they are blank.
 	foreach ( array( 'loop', 'autoplay', 'preload' ) as $a ) {
 		if ( empty( $html_atts[ $a ] ) ) {
 			unset( $html_atts[ $a ] );
@@ -2431,23 +2938,28 @@
 	}
 
 	$attr_strings = array();
+
 	foreach ( $html_atts as $k => $v ) {
 		$attr_strings[] = $k . '="' . esc_attr( $v ) . '"';
 	}
 
 	$html = '';
+
 	if ( 'mediaelement' === $library && 1 === $instance ) {
 		$html .= "<!--[if lt IE 9]><script>document.createElement('audio');</script><![endif]-->\n";
 	}
+
 	$html .= sprintf( '<audio %s controls="controls">', join( ' ', $attr_strings ) );
 
 	$fileurl = '';
 	$source  = '<source type="%s" src="%s" />';
+
 	foreach ( $default_types as $fallback ) {
 		if ( ! empty( $atts[ $fallback ] ) ) {
 			if ( empty( $fileurl ) ) {
 				$fileurl = $atts[ $fallback ];
 			}
+
 			$type  = wp_check_filetype( $atts[ $fallback ], wp_get_mime_types() );
 			$url   = add_query_arg( '_', $instance, $atts[ $fallback ] );
 			$html .= sprintf( $source, $type['type'], esc_url( $url ) );
@@ -2457,6 +2969,7 @@
 	if ( 'mediaelement' === $library ) {
 		$html .= wp_mediaelement_fallback( $fileurl );
 	}
+
 	$html .= '</audio>';
 
 	/**
@@ -2475,11 +2988,11 @@
 add_shortcode( 'audio', 'wp_audio_shortcode' );
 
 /**
- * Returns a filtered list of WP-supported video formats.
+ * Returns a filtered list of supported video formats.
  *
  * @since 3.6.0
  *
- * @return array List of supported video formats.
+ * @return string[] List of supported video formats.
  */
 function wp_get_video_extensions() {
 	/**
@@ -2487,8 +3000,8 @@
 	 *
 	 * @since 3.6.0
 	 *
-	 * @param array $extensions An array of supported video formats. Defaults are
-	 *                          'mp4', 'm4v', 'webm', 'ogv', 'flv'.
+	 * @param string[] $extensions An array of supported video formats. Defaults are
+	 *                             'mp4', 'm4v', 'webm', 'ogv', 'flv'.
 	 */
 	return apply_filters( 'wp_video_extensions', array( 'mp4', 'm4v', 'webm', 'ogv', 'flv' ) );
 }
@@ -2502,7 +3015,6 @@
  * @since 3.6.0
  *
  * @global int $content_width
- * @staticvar int $instance
  *
  * @param array  $attr {
  *     Attributes of the shortcode.
@@ -2544,6 +3056,7 @@
 	 * @param int    $instance Unique numeric ID of this video shortcode instance.
 	 */
 	$override = apply_filters( 'wp_video_shortcode_override', '', $attr, $content, $instance );
+
 	if ( '' !== $override ) {
 		return $override;
 	}
@@ -2569,20 +3082,21 @@
 	$atts = shortcode_atts( $defaults_atts, $attr, 'video' );
 
 	if ( is_admin() ) {
-		// shrink the video so it isn't huge in the admin
+		// Shrink the video so it isn't huge in the admin.
 		if ( $atts['width'] > $defaults_atts['width'] ) {
 			$atts['height'] = round( ( $atts['height'] * $defaults_atts['width'] ) / $atts['width'] );
 			$atts['width']  = $defaults_atts['width'];
 		}
 	} else {
-		// if the video is bigger than the theme
+		// If the video is bigger than the theme.
 		if ( ! empty( $content_width ) && $atts['width'] > $content_width ) {
 			$atts['height'] = round( ( $atts['height'] * $content_width ) / $atts['width'] );
 			$atts['width']  = $content_width;
 		}
 	}
 
-	$is_vimeo      = $is_youtube = false;
+	$is_vimeo      = false;
+	$is_youtube    = false;
 	$yt_pattern    = '#^https?://(?:www\.)?(?:youtube\.com/watch|youtu\.be/)#';
 	$vimeo_pattern = '#^https?://(.+\.)?vimeo\.com/.*#';
 
@@ -2590,9 +3104,11 @@
 	if ( ! empty( $atts['src'] ) ) {
 		$is_vimeo   = ( preg_match( $vimeo_pattern, $atts['src'] ) );
 		$is_youtube = ( preg_match( $yt_pattern, $atts['src'] ) );
+
 		if ( ! $is_youtube && ! $is_vimeo ) {
 			$type = wp_check_filetype( $atts['src'], wp_get_mime_types() );
-			if ( ! in_array( strtolower( $type['ext'] ), $default_types ) ) {
+
+			if ( ! in_array( strtolower( $type['ext'] ), $default_types, true ) ) {
 				return sprintf( '<a class="wp-embedded-video" href="%s">%s</a>', esc_url( $atts['src'] ), esc_html( $atts['src'] ) );
 			}
 		}
@@ -2643,8 +3159,8 @@
 		wp_enqueue_script( 'mediaelement-vimeo' );
 	}
 
-	// Mediaelement has issues with some URL formats for Vimeo and YouTube, so
-	// update the URL to prevent the ME.js player from breaking.
+	// MediaElement.js has issues with some URL formats for Vimeo and YouTube,
+	// so update the URL to prevent the ME.js player from breaking.
 	if ( 'mediaelement' === $library ) {
 		if ( $is_youtube ) {
 			// Remove `feature` query arg and force SSL - see #40866.
@@ -2683,7 +3199,7 @@
 		'preload'  => $atts['preload'],
 	);
 
-	// These ones should just be omitted altogether if they are blank
+	// These ones should just be omitted altogether if they are blank.
 	foreach ( array( 'poster', 'loop', 'autoplay', 'preload' ) as $a ) {
 		if ( empty( $html_atts[ $a ] ) ) {
 			unset( $html_atts[ $a ] );
@@ -2813,7 +3329,7 @@
 	);
 
 	foreach ( $attachments as $k => $attachment ) {
-		if ( $attachment->ID == $post->ID ) {
+		if ( intval( $attachment->ID ) === intval( $post->ID ) ) {
 			break;
 		}
 	}
@@ -2858,7 +3374,7 @@
  * @param string           $output     Output type. 'names' to return an array of taxonomy names,
  *                                     or 'objects' to return an array of taxonomy objects.
  *                                     Default is 'names'.
- * @return array Empty array on failure. List of taxonomies on success.
+ * @return string[]|WP_Taxonomy[] List of taxonomies or taxonomy names. Empty array on failure.
  */
 function get_attachment_taxonomies( $attachment, $output = 'names' ) {
 	if ( is_int( $attachment ) ) {
@@ -2866,6 +3382,7 @@
 	} elseif ( is_array( $attachment ) ) {
 		$attachment = (object) $attachment;
 	}
+
 	if ( ! is_object( $attachment ) ) {
 		return array();
 	}
@@ -2878,8 +3395,10 @@
 	if ( false !== strpos( $filename, '.' ) ) {
 		$objects[] = 'attachment:' . substr( $filename, strrpos( $filename, '.' ) + 1 );
 	}
+
 	if ( ! empty( $attachment->post_mime_type ) ) {
 		$objects[] = 'attachment:' . $attachment->post_mime_type;
+
 		if ( false !== strpos( $attachment->post_mime_type, '/' ) ) {
 			foreach ( explode( '/', $attachment->post_mime_type ) as $token ) {
 				if ( ! empty( $token ) ) {
@@ -2890,8 +3409,11 @@
 	}
 
 	$taxonomies = array();
+
 	foreach ( $objects as $object ) {
-		if ( $taxes = get_object_taxonomies( $object, $output ) ) {
+		$taxes = get_object_taxonomies( $object, $output );
+
+		if ( $taxes ) {
 			$taxonomies = array_merge( $taxonomies, $taxes );
 		}
 	}
@@ -2909,6 +3431,7 @@
  * Handles mime-type-specific taxonomies such as attachment:image and attachment:video.
  *
  * @since 3.5.0
+ *
  * @see get_taxonomies()
  *
  * @param string $output Optional. The type of taxonomy output to return. Accepts 'names' or 'objects'.
@@ -2917,10 +3440,11 @@
  */
 function get_taxonomies_for_attachments( $output = 'names' ) {
 	$taxonomies = array();
+
 	foreach ( get_taxonomies( array(), 'objects' ) as $taxonomy ) {
 		foreach ( $taxonomy->object_type as $object_type ) {
-			if ( 'attachment' == $object_type || 0 === strpos( $object_type, 'attachment:' ) ) {
-				if ( 'names' == $output ) {
+			if ( 'attachment' === $object_type || 0 === strpos( $object_type, 'attachment:' ) ) {
+				if ( 'names' === $output ) {
 					$taxonomies[] = $taxonomy->name;
 				} else {
 					$taxonomies[ $taxonomy->name ] = $taxonomy;
@@ -2936,7 +3460,7 @@
 /**
  * Create new GD image resource with transparency support
  *
- * @todo: Deprecate if possible.
+ * @todo Deprecate if possible.
  *
  * @since 2.9.0
  *
@@ -2964,7 +3488,12 @@
  * @param int $example_height The height of an example embed.
  * @param int $max_width      The maximum allowed width.
  * @param int $max_height     The maximum allowed height.
- * @return array The maximum possible width and height based on the example ratio.
+ * @return int[] {
+ *     An array of maximum width and height values.
+ *
+ *     @type int $0 The maximum width in pixels.
+ *     @type int $1 The maximum height in pixels.
+ * }
  */
 function wp_expand_dimensions( $example_width, $example_height, $max_width, $max_height ) {
 	$example_width  = (int) $example_width;
@@ -3070,8 +3599,8 @@
 	 *
 	 * @since 3.5.0
 	 *
-	 * @param array $image_editors List of available image editors. Defaults are
-	 *                             'WP_Image_Editor_Imagick', 'WP_Image_Editor_GD'.
+	 * @param string[] $image_editors Array of available image editor class names. Defaults are
+	 *                                'WP_Image_Editor_Imagick', 'WP_Image_Editor_GD'.
 	 */
 	$implementations = apply_filters( 'wp_image_editors', array( 'WP_Image_Editor_Imagick', 'WP_Image_Editor_GD' ) );
 
@@ -3125,7 +3654,7 @@
 	 * and the `flash_swf_url` and `silverlight_xap_url` are not used.
 	 */
 	$defaults = array(
-		'file_data_name' => 'async-upload', // key passed to $_FILE.
+		'file_data_name' => 'async-upload', // Key passed to $_FILE.
 		'url'            => admin_url( 'async-upload.php', 'relative' ),
 		'filters'        => array(
 			'max_file_size' => $max_upload_size . 'b',
@@ -3133,8 +3662,11 @@
 		),
 	);
 
-	// Currently only iOS Safari supports multiple files uploading but iOS 7.x has a bug that prevents uploading of videos
-	// when enabled. See #29602.
+	/*
+	 * Currently only iOS Safari supports multiple files uploading,
+	 * but iOS 7.x has a bug that prevents uploading of videos when enabled.
+	 * See #29602.
+	 */
 	if ( wp_is_mobile() && strpos( $_SERVER['HTTP_USER_AGENT'], 'OS 7_' ) !== false &&
 		strpos( $_SERVER['HTTP_USER_AGENT'], 'like Mac OS X' ) !== false ) {
 
@@ -3161,8 +3693,10 @@
 	 *
 	 * @param array $params Default Plupload parameters array.
 	 */
-	$params                       = apply_filters( 'plupload_default_params', $params );
-	$params['_wpnonce']           = wp_create_nonce( 'media-form' );
+	$params = apply_filters( 'plupload_default_params', $params );
+
+	$params['_wpnonce'] = wp_create_nonce( 'media-form' );
+
 	$defaults['multipart_params'] = $params;
 
 	$settings = array(
@@ -3193,11 +3727,13 @@
  * @return array|void Array of attachment details.
  */
 function wp_prepare_attachment_for_js( $attachment ) {
-	if ( ! $attachment = get_post( $attachment ) ) {
+	$attachment = get_post( $attachment );
+
+	if ( ! $attachment ) {
 		return;
 	}
 
-	if ( 'attachment' != $attachment->post_type ) {
+	if ( 'attachment' !== $attachment->post_type ) {
 		return;
 	}
 
@@ -3309,14 +3845,18 @@
 		);
 		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.
+		/*
+		 * 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 ) ) {
+			$downsize = apply_filters( 'image_downsize', false, $attachment->ID, $size );
+
+			if ( $downsize ) {
 				if ( empty( $downsize[3] ) ) {
 					continue;
 				}
@@ -3345,6 +3885,11 @@
 		}
 
 		if ( 'image' === $type ) {
+			if ( ! empty( $meta['original_image'] ) ) {
+				$response['originalImageURL']  = wp_get_original_image_url( $attachment->ID );
+				$response['originalImageName'] = wp_basename( wp_get_original_image_path( $attachment->ID ) );
+			}
+
 			$sizes['full'] = array( 'url' => $attachment_url );
 
 			if ( isset( $meta['height'], $meta['width'] ) ) {
@@ -3428,8 +3973,8 @@
  * @since 3.5.0
  *
  * @global int       $content_width
- * @global wpdb      $wpdb
- * @global WP_Locale $wp_locale
+ * @global wpdb      $wpdb          WordPress database abstraction object.
+ * @global WP_Locale $wp_locale     WordPress date and time locale object.
  *
  * @param array $args {
  *     Arguments for enqueuing media scripts.
@@ -3465,9 +4010,9 @@
 	unset( $tabs['type'], $tabs['type_url'], $tabs['gallery'], $tabs['library'] );
 
 	$props = array(
-		'link'  => get_option( 'image_default_link_type' ), // db default is 'file'
-		'align' => get_option( 'image_default_align' ), // empty default
-		'size'  => get_option( 'image_default_size' ),  // empty default
+		'link'  => get_option( 'image_default_link_type' ), // DB default is 'file'.
+		'align' => get_option( 'image_default_align' ),     // Empty default.
+		'size'  => get_option( 'image_default_size' ),      // Empty default.
 	);
 
 	$exts      = array_merge( wp_get_audio_extensions(), wp_get_video_extensions() );
@@ -3496,8 +4041,8 @@
 	 *
 	 * @link https://core.trac.wordpress.org/ticket/31071
 	 *
-	 * @param bool|null Whether to show the button, or `null` to decide based
-	 *                  on whether any audio files exist in the media library.
+	 * @param bool|null $show Whether to show the button, or `null` to decide based
+	 *                        on whether any audio files exist in the media library.
 	 */
 	$show_audio_playlist = apply_filters( 'media_library_show_audio_playlist', true );
 	if ( null === $show_audio_playlist ) {
@@ -3526,8 +4071,8 @@
 	 *
 	 * @link https://core.trac.wordpress.org/ticket/31071
 	 *
-	 * @param bool|null Whether to show the button, or `null` to decide based
-	 *                  on whether any video files exist in the media library.
+	 * @param bool|null $show Whether to show the button, or `null` to decide based
+	 *                        on whether any video files exist in the media library.
 	 */
 	$show_video_playlist = apply_filters( 'media_library_show_video_playlist', true );
 	if ( null === $show_video_playlist ) {
@@ -3554,9 +4099,9 @@
 	 *
 	 * @link https://core.trac.wordpress.org/ticket/31071
 	 *
-	 * @param array|null An array of objects with `month` and `year`
-	 *                   properties, or `null` (or any other non-array value)
-	 *                   for default behavior.
+	 * @param array|null $months An array of objects with `month` and `year`
+	 *                           properties, or `null` (or any other non-array value)
+	 *                           for default behavior.
 	 */
 	$months = apply_filters( 'media_library_months_with_files', null );
 	if ( ! is_array( $months ) ) {
@@ -3573,7 +4118,12 @@
 		);
 	}
 	foreach ( $months as $month_year ) {
-		$month_year->text = sprintf( __( '%1$s %2$d' ), $wp_locale->get_month( $month_year->month ), $month_year->year );
+		$month_year->text = sprintf(
+			/* translators: 1: Month, 2: Year. */
+			__( '%1$s %2$d' ),
+			$wp_locale->get_month( $month_year->month ),
+			$month_year->year
+		);
 	}
 
 	$settings = array(
@@ -3631,9 +4181,10 @@
 	}
 
 	$strings = array(
-		// Generic
+		// Generic.
+		'mediaFrameDefaultTitle'      => __( 'Media' ),
 		'url'                         => __( 'URL' ),
-		'addMedia'                    => __( 'Add Media' ),
+		'addMedia'                    => __( 'Add media' ),
 		'search'                      => __( 'Search' ),
 		'select'                      => __( 'Select' ),
 		'cancel'                      => __( 'Cancel' ),
@@ -3649,13 +4200,13 @@
 		'selected'                    => __( '%d selected' ),
 		'dragInfo'                    => __( 'Drag and drop to reorder media files.' ),
 
-		// Upload
-		'uploadFilesTitle'            => __( 'Upload Files' ),
-		'uploadImagesTitle'           => __( 'Upload Images' ),
-
-		// Library
+		// Upload.
+		'uploadFilesTitle'            => __( 'Upload files' ),
+		'uploadImagesTitle'           => __( 'Upload images' ),
+
+		// Library.
 		'mediaLibraryTitle'           => __( 'Media Library' ),
-		'insertMediaTitle'            => __( 'Add Media' ),
+		'insertMediaTitle'            => __( 'Add media' ),
 		'createNewGallery'            => __( 'Create a new gallery' ),
 		'createNewPlaylist'           => __( 'Create a new playlist' ),
 		'createNewVideoPlaylist'      => __( 'Create a new video playlist' ),
@@ -3671,90 +4222,95 @@
 		'warnDelete'                  => __( "You are about to permanently delete this item from your site.\nThis action cannot be undone.\n 'Cancel' to stop, 'OK' to delete." ),
 		'warnBulkDelete'              => __( "You are about to permanently delete these items from your site.\nThis action cannot be undone.\n 'Cancel' to stop, 'OK' to delete." ),
 		'warnBulkTrash'               => __( "You are about to trash these items.\n  'Cancel' to stop, 'OK' to delete." ),
-		'bulkSelect'                  => __( 'Bulk Select' ),
+		'bulkSelect'                  => __( 'Bulk select' ),
 		'trashSelected'               => __( 'Move to Trash' ),
 		'restoreSelected'             => __( 'Restore from Trash' ),
-		'deletePermanently'           => __( 'Delete Permanently' ),
+		'deletePermanently'           => __( 'Delete permanently' ),
 		'apply'                       => __( 'Apply' ),
 		'filterByDate'                => __( 'Filter by date' ),
 		'filterByType'                => __( 'Filter by type' ),
-		'searchMediaLabel'            => __( 'Search Media' ),
-		'searchMediaPlaceholder'      => __( 'Search media items...' ), // placeholder (no ellipsis)
-		'noMedia'                     => __( 'No media files found.' ),
-
-		// Library Details
-		'attachmentDetails'           => __( 'Attachment Details' ),
-
-		// From URL
+		'searchLabel'                 => __( 'Search' ),
+		'searchMediaLabel'            => __( 'Search media' ),          // Backward compatibility pre-5.3.
+		'searchMediaPlaceholder'      => __( 'Search media items...' ), // Placeholder (no ellipsis), backward compatibility pre-5.3.
+		'mediaFound'                  => __( 'Number of media items found: %d' ),
+		'mediaFoundHasMoreResults'    => __( 'Number of media items displayed: %d. Scroll the page for more results.' ),
+		'noMedia'                     => __( 'No media items found.' ),
+		'noMediaTryNewSearch'         => __( 'No media items found. Try a different search.' ),
+
+		// Library Details.
+		'attachmentDetails'           => __( 'Attachment details' ),
+
+		// From URL.
 		'insertFromUrlTitle'          => __( 'Insert from URL' ),
 
-		// Featured Images
+		// Featured Images.
 		'setFeaturedImageTitle'       => $post_type_object->labels->featured_image,
 		'setFeaturedImage'            => $post_type_object->labels->set_featured_image,
 
-		// Gallery
-		'createGalleryTitle'          => __( 'Create Gallery' ),
-		'editGalleryTitle'            => __( 'Edit Gallery' ),
-		'cancelGalleryTitle'          => __( '&#8592; Cancel Gallery' ),
+		// Gallery.
+		'createGalleryTitle'          => __( 'Create gallery' ),
+		'editGalleryTitle'            => __( 'Edit gallery' ),
+		'cancelGalleryTitle'          => __( '&#8592; Cancel gallery' ),
 		'insertGallery'               => __( 'Insert gallery' ),
 		'updateGallery'               => __( 'Update gallery' ),
 		'addToGallery'                => __( 'Add to gallery' ),
-		'addToGalleryTitle'           => __( 'Add to Gallery' ),
+		'addToGalleryTitle'           => __( 'Add to gallery' ),
 		'reverseOrder'                => __( 'Reverse order' ),
 
-		// Edit Image
-		'imageDetailsTitle'           => __( 'Image Details' ),
-		'imageReplaceTitle'           => __( 'Replace Image' ),
-		'imageDetailsCancel'          => __( 'Cancel Edit' ),
-		'editImage'                   => __( 'Edit Image' ),
-
-		// Crop Image
-		'chooseImage'                 => __( 'Choose Image' ),
-		'selectAndCrop'               => __( 'Select and Crop' ),
-		'skipCropping'                => __( 'Skip Cropping' ),
-		'cropImage'                   => __( 'Crop Image' ),
+		// Edit Image.
+		'imageDetailsTitle'           => __( 'Image details' ),
+		'imageReplaceTitle'           => __( 'Replace image' ),
+		'imageDetailsCancel'          => __( 'Cancel edit' ),
+		'editImage'                   => __( 'Edit image' ),
+
+		// Crop Image.
+		'chooseImage'                 => __( 'Choose image' ),
+		'selectAndCrop'               => __( 'Select and crop' ),
+		'skipCropping'                => __( 'Skip cropping' ),
+		'cropImage'                   => __( 'Crop image' ),
 		'cropYourImage'               => __( 'Crop your image' ),
 		'cropping'                    => __( 'Cropping&hellip;' ),
-		/* translators: 1: suggested width number, 2: suggested height number. */
+		/* translators: 1: Suggested width number, 2: Suggested height number. */
 		'suggestedDimensions'         => __( 'Suggested image dimensions: %1$s by %2$s pixels.' ),
 		'cropError'                   => __( 'There has been an error cropping your image.' ),
 
-		// Edit Audio
-		'audioDetailsTitle'           => __( 'Audio Details' ),
-		'audioReplaceTitle'           => __( 'Replace Audio' ),
-		'audioAddSourceTitle'         => __( 'Add Audio Source' ),
-		'audioDetailsCancel'          => __( 'Cancel Edit' ),
-
-		// Edit Video
-		'videoDetailsTitle'           => __( 'Video Details' ),
-		'videoReplaceTitle'           => __( 'Replace Video' ),
-		'videoAddSourceTitle'         => __( 'Add Video Source' ),
-		'videoDetailsCancel'          => __( 'Cancel Edit' ),
-		'videoSelectPosterImageTitle' => __( 'Select Poster Image' ),
-		'videoAddTrackTitle'          => __( 'Add Subtitles' ),
-
-		// Playlist
+		// Edit Audio.
+		'audioDetailsTitle'           => __( 'Audio details' ),
+		'audioReplaceTitle'           => __( 'Replace audio' ),
+		'audioAddSourceTitle'         => __( 'Add audio source' ),
+		'audioDetailsCancel'          => __( 'Cancel edit' ),
+
+		// Edit Video.
+		'videoDetailsTitle'           => __( 'Video details' ),
+		'videoReplaceTitle'           => __( 'Replace video' ),
+		'videoAddSourceTitle'         => __( 'Add video source' ),
+		'videoDetailsCancel'          => __( 'Cancel edit' ),
+		'videoSelectPosterImageTitle' => __( 'Select poster image' ),
+		'videoAddTrackTitle'          => __( 'Add subtitles' ),
+
+		// Playlist.
 		'playlistDragInfo'            => __( 'Drag and drop to reorder tracks.' ),
-		'createPlaylistTitle'         => __( 'Create Audio Playlist' ),
-		'editPlaylistTitle'           => __( 'Edit Audio Playlist' ),
-		'cancelPlaylistTitle'         => __( '&#8592; Cancel Audio Playlist' ),
+		'createPlaylistTitle'         => __( 'Create audio playlist' ),
+		'editPlaylistTitle'           => __( 'Edit audio playlist' ),
+		'cancelPlaylistTitle'         => __( '&#8592; Cancel audio playlist' ),
 		'insertPlaylist'              => __( 'Insert audio playlist' ),
 		'updatePlaylist'              => __( 'Update audio playlist' ),
 		'addToPlaylist'               => __( 'Add to audio playlist' ),
 		'addToPlaylistTitle'          => __( 'Add to Audio Playlist' ),
 
-		// Video Playlist
+		// Video Playlist.
 		'videoPlaylistDragInfo'       => __( 'Drag and drop to reorder videos.' ),
-		'createVideoPlaylistTitle'    => __( 'Create Video Playlist' ),
-		'editVideoPlaylistTitle'      => __( 'Edit Video Playlist' ),
-		'cancelVideoPlaylistTitle'    => __( '&#8592; Cancel Video Playlist' ),
+		'createVideoPlaylistTitle'    => __( 'Create video playlist' ),
+		'editVideoPlaylistTitle'      => __( 'Edit video playlist' ),
+		'cancelVideoPlaylistTitle'    => __( '&#8592; Cancel video playlist' ),
 		'insertVideoPlaylist'         => __( 'Insert video playlist' ),
 		'updateVideoPlaylist'         => __( 'Update video playlist' ),
 		'addToVideoPlaylist'          => __( 'Add to video playlist' ),
-		'addToVideoPlaylistTitle'     => __( 'Add to Video Playlist' ),
-
-		// Headings
-		'attachmentsList'             => __( 'Attachments list' ),
+		'addToVideoPlaylistTitle'     => __( 'Add to video Playlist' ),
+
+		// Headings.
+		'filterAttachments'           => __( 'Filter media' ),
+		'attachmentsList'             => __( 'Media list' ),
 	);
 
 	/**
@@ -3772,15 +4328,15 @@
 	 *
 	 * @since 3.5.0
 	 *
-	 * @param array   $strings List of media view strings.
-	 * @param WP_Post $post    Post object.
+	 * @param string[] $strings Array of media view strings keyed by the name they'll be referenced by in JavaScript.
+	 * @param WP_Post  $post    Post object.
 	 */
 	$strings = apply_filters( 'media_view_strings', $strings, $post );
 
 	$strings['settings'] = $settings;
 
-	// Ensure we enqueue media-editor first, that way media-views is
-	// registered internally before we try to localize it. see #24724.
+	// Ensure we enqueue media-editor first, that way media-views
+	// is registered internally before we try to localize it. See #24724.
 	wp_enqueue_script( 'media-editor' );
 	wp_localize_script( 'media-views', '_wpMediaViewsL10n', $strings );
 
@@ -3813,10 +4369,12 @@
  *
  * @param string      $type Mime type.
  * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global $post.
- * @return array Found attachments.
+ * @return WP_Post[] Array of media attached to the given post.
  */
 function get_attached_media( $type, $post = 0 ) {
-	if ( ! $post = get_post( $post ) ) {
+	$post = get_post( $post );
+
+	if ( ! $post ) {
 		return array();
 	}
 
@@ -3834,9 +4392,9 @@
 	 *
 	 * @since 3.6.0
 	 *
-	 * @param array  $args Post query arguments.
-	 * @param string $type Mime type of the desired media.
-	 * @param mixed  $post Post ID or object.
+	 * @param array   $args Post query arguments.
+	 * @param string  $type Mime type of the desired media.
+	 * @param WP_Post $post Post object.
 	 */
 	$args = apply_filters( 'get_attached_media_args', $args, $type, $post );
 
@@ -3847,21 +4405,21 @@
 	 *
 	 * @since 3.6.0
 	 *
-	 * @param array  $children Associative array of media attached to the given post.
-	 * @param string $type     Mime type of the media desired.
-	 * @param mixed  $post     Post ID or object.
+	 * @param WP_Post[] $children Array of media attached to the given post.
+	 * @param string    $type     Mime type of the media desired.
+	 * @param WP_Post   $post     Post object.
 	 */
 	return (array) apply_filters( 'get_attached_media', $children, $type, $post );
 }
 
 /**
- * Check the content blob for an audio, video, object, embed, or iframe tags.
+ * Check the content HTML for a audio, video, object, embed, or iframe tags.
  *
  * @since 3.6.0
  *
- * @param string $content A string which might contain media data.
- * @param array  $types   An array of media types: 'audio', 'video', 'object', 'embed', or 'iframe'.
- * @return array A list of found HTML media embeds.
+ * @param string   $content A string of HTML which might contain media elements.
+ * @param string[] $types   An array of media types: 'audio', 'video', 'object', 'embed', or 'iframe'.
+ * @return string[] Array of found HTML media elements.
  */
 function get_media_embedded_in_content( $content, $types = null ) {
 	$html = array();
@@ -3871,8 +4429,8 @@
 	 *
 	 * @since 4.2.0
 	 *
-	 * @param array $allowed_media_types An array of allowed media types. Default media types are
-	 *                                   'audio', 'video', 'object', 'embed', and 'iframe'.
+	 * @param string[] $allowed_media_types An array of allowed media types. Default media types are
+	 *                                      'audio', 'video', 'object', 'embed', and 'iframe'.
 	 */
 	$allowed_media_types = apply_filters( 'media_embedded_in_content_allowed_types', array( 'audio', 'video', 'object', 'embed', 'iframe' ) );
 
@@ -3906,7 +4464,9 @@
  *               from the expanded shortcode.
  */
 function get_post_galleries( $post, $html = true ) {
-	if ( ! $post = get_post( $post ) ) {
+	$post = get_post( $post );
+
+	if ( ! $post ) {
 		return array();
 	}
 
@@ -3925,7 +4485,7 @@
 					$shortcode_attrs = array();
 				}
 
-				// Specify the post id of the gallery we're viewing if the shortcode doesn't reference another post already.
+				// Specify the post ID of the gallery we're viewing if the shortcode doesn't reference another post already.
 				if ( ! isset( $shortcode_attrs['id'] ) ) {
 					$shortcode[3] .= ' id="' . intval( $post->ID ) . '"';
 				}
@@ -4012,7 +4572,7 @@
  * @see get_post_gallery()
  *
  * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global `$post`.
- * @return array A list of a gallery's image srcs in order.
+ * @return string[] A list of a gallery's image srcs in order.
  */
 function get_post_gallery_images( $post = 0 ) {
 	$gallery = get_post_gallery( $post, false );
@@ -4027,19 +4587,22 @@
  * @param WP_Post $attachment Attachment object.
  */
 function wp_maybe_generate_attachment_metadata( $attachment ) {
-	if ( empty( $attachment ) || ( empty( $attachment->ID ) || ! $attachment_id = (int) $attachment->ID ) ) {
+	if ( empty( $attachment ) || empty( $attachment->ID ) ) {
 		return;
 	}
 
-	$file = get_attached_file( $attachment_id );
-	$meta = wp_get_attachment_metadata( $attachment_id );
+	$attachment_id = (int) $attachment->ID;
+	$file          = get_attached_file( $attachment_id );
+	$meta          = wp_get_attachment_metadata( $attachment_id );
+
 	if ( empty( $meta ) && file_exists( $file ) ) {
-		$_meta             = get_post_meta( $attachment_id );
-		$regeneration_lock = 'wp_generating_att_' . $attachment_id;
-		if ( ! array_key_exists( '_wp_attachment_metadata', $_meta ) && ! get_transient( $regeneration_lock ) ) {
-			set_transient( $regeneration_lock, $file );
+		$_meta = get_post_meta( $attachment_id );
+		$_lock = 'wp_generating_att_' . $attachment_id;
+
+		if ( ! array_key_exists( '_wp_attachment_metadata', $_meta ) && ! get_transient( $_lock ) ) {
+			set_transient( $_lock, $file );
 			wp_update_attachment_metadata( $attachment_id, wp_generate_attachment_metadata( $attachment_id, $file ) );
-			delete_transient( $regeneration_lock );
+			delete_transient( $_lock );
 		}
 	}
 }
@@ -4063,7 +4626,7 @@
 	$site_url   = parse_url( $dir['url'] );
 	$image_path = parse_url( $path );
 
-	//force the protocols to match if needed
+	// Force the protocols to match if needed.
 	if ( isset( $image_path['scheme'] ) && ( $image_path['scheme'] !== $site_url['scheme'] ) ) {
 		$path = str_replace( $image_path['scheme'], $site_url['scheme'], $path );
 	}
@@ -4072,14 +4635,30 @@
 		$path = substr( $path, strlen( $dir['baseurl'] . '/' ) );
 	}
 
-	$sql     = $wpdb->prepare(
-		"SELECT post_id FROM $wpdb->postmeta WHERE meta_key = '_wp_attached_file' AND meta_value = %s",
+	$sql = $wpdb->prepare(
+		"SELECT post_id, meta_value FROM $wpdb->postmeta WHERE meta_key = '_wp_attached_file' AND meta_value = %s",
 		$path
 	);
-	$post_id = $wpdb->get_var( $sql );
+
+	$results = $wpdb->get_results( $sql );
+	$post_id = null;
+
+	if ( $results ) {
+		// Use the first available result, but prefer a case-sensitive match, if exists.
+		$post_id = reset( $results )->post_id;
+
+		if ( count( $results ) > 1 ) {
+			foreach ( $results as $result ) {
+				if ( $path === $result->meta_value ) {
+					$post_id = $result->post_id;
+					break;
+				}
+			}
+		}
+	}
 
 	/**
-	 * Filters an attachment id found by URL.
+	 * Filters an attachment ID found by URL.
 	 *
 	 * @since 4.2.0
 	 *
@@ -4094,7 +4673,7 @@
  *
  * @since 4.0.0
  *
- * @return array The relevant CSS file URLs.
+ * @return string[] The relevant CSS file URLs.
  */
 function wpview_media_sandbox_styles() {
 	$version        = 'ver=' . get_bloginfo( 'version' );
@@ -4105,10 +4684,10 @@
 }
 
 /**
- * Registers the personal data exporter for media
- *
- * @param array   $exporters   An array of personal data exporters.
- * @return array  An array of personal data exporters.
+ * Registers the personal data exporter for media.
+ *
+ * @param array[] $exporters An array of personal data exporters, keyed by their ID.
+ * @return array[] Updated array of personal data exporters.
  */
 function wp_register_media_personal_data_exporter( $exporters ) {
 	$exporters['wordpress-media'] = array(
@@ -4124,9 +4703,9 @@
  *
  * @since 4.9.6
  *
- * @param  string $email_address The attachment owner email address.
- * @param  int    $page          Attachment page.
- * @return array  $return        An array of personal data.
+ * @param string $email_address The attachment owner email address.
+ * @param int    $page          Attachment page.
+ * @return array An array of personal data.
  */
 function wp_media_personal_data_exporter( $email_address, $page = 1 ) {
 	// Limit us to 50 attachments at a time to avoid timing out.
@@ -4167,10 +4746,11 @@
 			);
 
 			$data_to_export[] = array(
-				'group_id'    => 'media',
-				'group_label' => __( 'Media' ),
-				'item_id'     => "post-{$post->ID}",
-				'data'        => $post_data_to_export,
+				'group_id'          => 'media',
+				'group_label'       => __( 'Media' ),
+				'group_description' => __( 'User&#8217;s media data.' ),
+				'item_id'           => "post-{$post->ID}",
+				'data'              => $post_data_to_export,
 			);
 		}
 	}
@@ -4182,3 +4762,36 @@
 		'done' => $done,
 	);
 }
+
+/**
+ * Add additional default image sub-sizes.
+ *
+ * These sizes are meant to enhance the way WordPress displays images on the front-end on larger,
+ * high-density devices. They make it possible to generate more suitable `srcset` and `sizes` attributes
+ * when the users upload large images.
+ *
+ * The sizes can be changed or removed by themes and plugins but that is not recommended.
+ * The size "names" reflect the image dimensions, so changing the sizes would be quite misleading.
+ *
+ * @since 5.3.0
+ * @access private
+ */
+function _wp_add_additional_image_sizes() {
+	// 2x medium_large size.
+	add_image_size( '1536x1536', 1536, 1536 );
+	// 2x large size.
+	add_image_size( '2048x2048', 2048, 2048 );
+}
+
+/**
+ * Callback to enable showing of the user error when uploading .heic images.
+ *
+ * @since 5.5.0
+ *
+ * @param array[] $plupload_settings The settings for Plupload.js.
+ * @return array[] Modified settings for Plupload.js.
+ */
+function wp_show_heic_upload_error( $plupload_settings ) {
+	$plupload_settings['heic_upload_error'] = true;
+	return $plupload_settings;
+}