[ Index ]

PHP Cross Reference of WordPress

title

Body

[close]

/wp-admin/includes/ -> image.php (source)

   1  <?php
   2  /**
   3   * File contains all the administration image manipulation functions.
   4   *
   5   * @package WordPress
   6   * @subpackage Administration
   7   */
   8  
   9  /**
  10   * Crops an image to a given size.
  11   *
  12   * @since 2.1.0
  13   *
  14   * @param string|int   $src      The source file or Attachment ID.
  15   * @param int          $src_x    The start x position to crop from.
  16   * @param int          $src_y    The start y position to crop from.
  17   * @param int          $src_w    The width to crop.
  18   * @param int          $src_h    The height to crop.
  19   * @param int          $dst_w    The destination width.
  20   * @param int          $dst_h    The destination height.
  21   * @param bool|false   $src_abs  Optional. If the source crop points are absolute.
  22   * @param string|false $dst_file Optional. The destination file to write to.
  23   * @return string|WP_Error New filepath on success, WP_Error on failure.
  24   */
  25  function wp_crop_image( $src, $src_x, $src_y, $src_w, $src_h, $dst_w, $dst_h, $src_abs = false, $dst_file = false ) {
  26      $src_file = $src;
  27      if ( is_numeric( $src ) ) { // Handle int as attachment ID.
  28          $src_file = get_attached_file( $src );
  29  
  30          if ( ! file_exists( $src_file ) ) {
  31              // If the file doesn't exist, attempt a URL fopen on the src link.
  32              // This can occur with certain file replication plugins.
  33              $src = _load_image_to_edit_path( $src, 'full' );
  34          } else {
  35              $src = $src_file;
  36          }
  37      }
  38  
  39      $editor = wp_get_image_editor( $src );
  40      if ( is_wp_error( $editor ) ) {
  41          return $editor;
  42      }
  43  
  44      $src = $editor->crop( $src_x, $src_y, $src_w, $src_h, $dst_w, $dst_h, $src_abs );
  45      if ( is_wp_error( $src ) ) {
  46          return $src;
  47      }
  48  
  49      if ( ! $dst_file ) {
  50          $dst_file = str_replace( wp_basename( $src_file ), 'cropped-' . wp_basename( $src_file ), $src_file );
  51      }
  52  
  53      /*
  54       * The directory containing the original file may no longer exist when
  55       * using a replication plugin.
  56       */
  57      wp_mkdir_p( dirname( $dst_file ) );
  58  
  59      $dst_file = dirname( $dst_file ) . '/' . wp_unique_filename( dirname( $dst_file ), wp_basename( $dst_file ) );
  60  
  61      $result = $editor->save( $dst_file );
  62      if ( is_wp_error( $result ) ) {
  63          return $result;
  64      }
  65  
  66      return $dst_file;
  67  }
  68  
  69  /**
  70   * Compare the existing image sub-sizes (as saved in the attachment meta)
  71   * to the currently registered image sub-sizes, and return the difference.
  72   *
  73   * Registered sub-sizes that are larger than the image are skipped.
  74   *
  75   * @since 5.3.0
  76   *
  77   * @param int $attachment_id The image attachment post ID.
  78   * @return array[] Associative array of arrays of image sub-size information for
  79   *                 missing image sizes, keyed by image size name.
  80   */
  81  function wp_get_missing_image_subsizes( $attachment_id ) {
  82      if ( ! wp_attachment_is_image( $attachment_id ) ) {
  83          return array();
  84      }
  85  
  86      $registered_sizes = wp_get_registered_image_subsizes();
  87      $image_meta       = wp_get_attachment_metadata( $attachment_id );
  88  
  89      // Meta error?
  90      if ( empty( $image_meta ) ) {
  91          return $registered_sizes;
  92      }
  93  
  94      // Use the originally uploaded image dimensions as full_width and full_height.
  95      if ( ! empty( $image_meta['original_image'] ) ) {
  96          $image_file = wp_get_original_image_path( $attachment_id );
  97          $imagesize  = wp_getimagesize( $image_file );
  98      }
  99  
 100      if ( ! empty( $imagesize ) ) {
 101          $full_width  = $imagesize[0];
 102          $full_height = $imagesize[1];
 103      } else {
 104          $full_width  = (int) $image_meta['width'];
 105          $full_height = (int) $image_meta['height'];
 106      }
 107  
 108      $possible_sizes = array();
 109  
 110      // Skip registered sizes that are too large for the uploaded image.
 111      foreach ( $registered_sizes as $size_name => $size_data ) {
 112          if ( image_resize_dimensions( $full_width, $full_height, $size_data['width'], $size_data['height'], $size_data['crop'] ) ) {
 113              $possible_sizes[ $size_name ] = $size_data;
 114          }
 115      }
 116  
 117      if ( empty( $image_meta['sizes'] ) ) {
 118          $image_meta['sizes'] = array();
 119      }
 120  
 121      /*
 122       * Remove sizes that already exist. Only checks for matching "size names".
 123       * It is possible that the dimensions for a particular size name have changed.
 124       * For example the user has changed the values on the Settings -> Media screen.
 125       * However we keep the old sub-sizes with the previous dimensions
 126       * as the image may have been used in an older post.
 127       */
 128      $missing_sizes = array_diff_key( $possible_sizes, $image_meta['sizes'] );
 129  
 130      /**
 131       * Filters the array of missing image sub-sizes for an uploaded image.
 132       *
 133       * @since 5.3.0
 134       *
 135       * @param array[] $missing_sizes Associative array of arrays of image sub-size information for
 136       *                               missing image sizes, keyed by image size name.
 137       * @param array   $image_meta    The image meta data.
 138       * @param int     $attachment_id The image attachment post ID.
 139       */
 140      return apply_filters( 'wp_get_missing_image_subsizes', $missing_sizes, $image_meta, $attachment_id );
 141  }
 142  
 143  /**
 144   * If any of the currently registered image sub-sizes are missing,
 145   * create them and update the image meta data.
 146   *
 147   * @since 5.3.0
 148   *
 149   * @param int $attachment_id The image attachment post ID.
 150   * @return array|WP_Error The updated image meta data array or WP_Error object
 151   *                        if both the image meta and the attached file are missing.
 152   */
 153  function wp_update_image_subsizes( $attachment_id ) {
 154      $image_meta = wp_get_attachment_metadata( $attachment_id );
 155      $image_file = wp_get_original_image_path( $attachment_id );
 156  
 157      if ( empty( $image_meta ) || ! is_array( $image_meta ) ) {
 158          // Previously failed upload?
 159          // If there is an uploaded file, make all sub-sizes and generate all of the attachment meta.
 160          if ( ! empty( $image_file ) ) {
 161              $image_meta = wp_create_image_subsizes( $image_file, $attachment_id );
 162          } else {
 163              return new WP_Error( 'invalid_attachment', __( 'The attached file cannot be found.' ) );
 164          }
 165      } else {
 166          $missing_sizes = wp_get_missing_image_subsizes( $attachment_id );
 167  
 168          if ( empty( $missing_sizes ) ) {
 169              return $image_meta;
 170          }
 171  
 172          // This also updates the image meta.
 173          $image_meta = _wp_make_subsizes( $missing_sizes, $image_file, $image_meta, $attachment_id );
 174      }
 175  
 176      /** This filter is documented in wp-admin/includes/image.php */
 177      $image_meta = apply_filters( 'wp_generate_attachment_metadata', $image_meta, $attachment_id, 'update' );
 178  
 179      // Save the updated metadata.
 180      wp_update_attachment_metadata( $attachment_id, $image_meta );
 181  
 182      return $image_meta;
 183  }
 184  
 185  /**
 186   * Updates the attached file and image meta data when the original image was edited.
 187   *
 188   * @since 5.3.0
 189   * @access private
 190   *
 191   * @param array  $saved_data    The data returned from WP_Image_Editor after successfully saving an image.
 192   * @param string $original_file Path to the original file.
 193   * @param array  $image_meta    The image meta data.
 194   * @param int    $attachment_id The attachment post ID.
 195   * @return array The updated image meta data.
 196   */
 197  function _wp_image_meta_replace_original( $saved_data, $original_file, $image_meta, $attachment_id ) {
 198      $new_file = $saved_data['path'];
 199  
 200      // Update the attached file meta.
 201      update_attached_file( $attachment_id, $new_file );
 202  
 203      // Width and height of the new image.
 204      $image_meta['width']  = $saved_data['width'];
 205      $image_meta['height'] = $saved_data['height'];
 206  
 207      // Make the file path relative to the upload dir.
 208      $image_meta['file'] = _wp_relative_upload_path( $new_file );
 209  
 210      // Store the original image file name in image_meta.
 211      $image_meta['original_image'] = wp_basename( $original_file );
 212  
 213      return $image_meta;
 214  }
 215  
 216  /**
 217   * Creates image sub-sizes, adds the new data to the image meta `sizes` array, and updates the image metadata.
 218   *
 219   * Intended for use after an image is uploaded. Saves/updates the image metadata after each
 220   * sub-size is created. If there was an error, it is added to the returned image metadata array.
 221   *
 222   * @since 5.3.0
 223   *
 224   * @param string $file          Full path to the image file.
 225   * @param int    $attachment_id Attachment ID to process.
 226   * @return array The image attachment meta data.
 227   */
 228  function wp_create_image_subsizes( $file, $attachment_id ) {
 229      $imagesize = wp_getimagesize( $file );
 230  
 231      if ( empty( $imagesize ) ) {
 232          // File is not an image.
 233          return array();
 234      }
 235  
 236      // Default image meta.
 237      $image_meta = array(
 238          'width'  => $imagesize[0],
 239          'height' => $imagesize[1],
 240          'file'   => _wp_relative_upload_path( $file ),
 241          'sizes'  => array(),
 242      );
 243  
 244      // Fetch additional metadata from EXIF/IPTC.
 245      $exif_meta = wp_read_image_metadata( $file );
 246  
 247      if ( $exif_meta ) {
 248          $image_meta['image_meta'] = $exif_meta;
 249      }
 250  
 251      // Do not scale (large) PNG images. May result in sub-sizes that have greater file size than the original. See #48736.
 252      if ( 'image/png' !== $imagesize['mime'] ) {
 253  
 254          /**
 255           * Filters the "BIG image" threshold value.
 256           *
 257           * If the original image width or height is above the threshold, it will be scaled down. The threshold is
 258           * used as max width and max height. The scaled down image will be used as the largest available size, including
 259           * the `_wp_attached_file` post meta value.
 260           *
 261           * Returning `false` from the filter callback will disable the scaling.
 262           *
 263           * @since 5.3.0
 264           *
 265           * @param int    $threshold     The threshold value in pixels. Default 2560.
 266           * @param array  $imagesize     {
 267           *     Indexed array of the image width and height in pixels.
 268           *
 269           *     @type int $0 The image width.
 270           *     @type int $1 The image height.
 271           * }
 272           * @param string $file          Full path to the uploaded image file.
 273           * @param int    $attachment_id Attachment post ID.
 274           */
 275          $threshold = (int) apply_filters( 'big_image_size_threshold', 2560, $imagesize, $file, $attachment_id );
 276  
 277          // If the original image's dimensions are over the threshold,
 278          // scale the image and use it as the "full" size.
 279          if ( $threshold && ( $image_meta['width'] > $threshold || $image_meta['height'] > $threshold ) ) {
 280              $editor = wp_get_image_editor( $file );
 281  
 282              if ( is_wp_error( $editor ) ) {
 283                  // This image cannot be edited.
 284                  return $image_meta;
 285              }
 286  
 287              // Resize the image.
 288              $resized = $editor->resize( $threshold, $threshold );
 289              $rotated = null;
 290  
 291              // If there is EXIF data, rotate according to EXIF Orientation.
 292              if ( ! is_wp_error( $resized ) && is_array( $exif_meta ) ) {
 293                  $resized = $editor->maybe_exif_rotate();
 294                  $rotated = $resized;
 295              }
 296  
 297              if ( ! is_wp_error( $resized ) ) {
 298                  // Append "-scaled" to the image file name. It will look like "my_image-scaled.jpg".
 299                  // This doesn't affect the sub-sizes names as they are generated from the original image (for best quality).
 300                  $saved = $editor->save( $editor->generate_filename( 'scaled' ) );
 301  
 302                  if ( ! is_wp_error( $saved ) ) {
 303                      $image_meta = _wp_image_meta_replace_original( $saved, $file, $image_meta, $attachment_id );
 304  
 305                      // If the image was rotated update the stored EXIF data.
 306                      if ( true === $rotated && ! empty( $image_meta['image_meta']['orientation'] ) ) {
 307                          $image_meta['image_meta']['orientation'] = 1;
 308                      }
 309                  } else {
 310                      // TODO: Log errors.
 311                  }
 312              } else {
 313                  // TODO: Log errors.
 314              }
 315          } elseif ( ! empty( $exif_meta['orientation'] ) && 1 !== (int) $exif_meta['orientation'] ) {
 316              // Rotate the whole original image if there is EXIF data and "orientation" is not 1.
 317  
 318              $editor = wp_get_image_editor( $file );
 319  
 320              if ( is_wp_error( $editor ) ) {
 321                  // This image cannot be edited.
 322                  return $image_meta;
 323              }
 324  
 325              // Rotate the image.
 326              $rotated = $editor->maybe_exif_rotate();
 327  
 328              if ( true === $rotated ) {
 329                  // Append `-rotated` to the image file name.
 330                  $saved = $editor->save( $editor->generate_filename( 'rotated' ) );
 331  
 332                  if ( ! is_wp_error( $saved ) ) {
 333                      $image_meta = _wp_image_meta_replace_original( $saved, $file, $image_meta, $attachment_id );
 334  
 335                      // Update the stored EXIF data.
 336                      if ( ! empty( $image_meta['image_meta']['orientation'] ) ) {
 337                          $image_meta['image_meta']['orientation'] = 1;
 338                      }
 339                  } else {
 340                      // TODO: Log errors.
 341                  }
 342              }
 343          }
 344      }
 345  
 346      /*
 347       * Initial save of the new metadata.
 348       * At this point the file was uploaded and moved to the uploads directory
 349       * but the image sub-sizes haven't been created yet and the `sizes` array is empty.
 350       */
 351      wp_update_attachment_metadata( $attachment_id, $image_meta );
 352  
 353      $new_sizes = wp_get_registered_image_subsizes();
 354  
 355      /**
 356       * Filters the image sizes automatically generated when uploading an image.
 357       *
 358       * @since 2.9.0
 359       * @since 4.4.0 Added the `$image_meta` argument.
 360       * @since 5.3.0 Added the `$attachment_id` argument.
 361       *
 362       * @param array $new_sizes     Associative array of image sizes to be created.
 363       * @param array $image_meta    The image meta data: width, height, file, sizes, etc.
 364       * @param int   $attachment_id The attachment post ID for the image.
 365       */
 366      $new_sizes = apply_filters( 'intermediate_image_sizes_advanced', $new_sizes, $image_meta, $attachment_id );
 367  
 368      return _wp_make_subsizes( $new_sizes, $file, $image_meta, $attachment_id );
 369  }
 370  
 371  /**
 372   * Low-level function to create image sub-sizes.
 373   *
 374   * Updates the image meta after each sub-size is created.
 375   * Errors are stored in the returned image metadata array.
 376   *
 377   * @since 5.3.0
 378   * @access private
 379   *
 380   * @param array  $new_sizes     Array defining what sizes to create.
 381   * @param string $file          Full path to the image file.
 382   * @param array  $image_meta    The attachment meta data array.
 383   * @param int    $attachment_id Attachment ID to process.
 384   * @return array The attachment meta data with updated `sizes` array. Includes an array of errors encountered while resizing.
 385   */
 386  function _wp_make_subsizes( $new_sizes, $file, $image_meta, $attachment_id ) {
 387      if ( empty( $image_meta ) || ! is_array( $image_meta ) ) {
 388          // Not an image attachment.
 389          return array();
 390      }
 391  
 392      // Check if any of the new sizes already exist.
 393      if ( isset( $image_meta['sizes'] ) && is_array( $image_meta['sizes'] ) ) {
 394          foreach ( $image_meta['sizes'] as $size_name => $size_meta ) {
 395              /*
 396               * Only checks "size name" so we don't override existing images even if the dimensions
 397               * don't match the currently defined size with the same name.
 398               * To change the behavior, unset changed/mismatched sizes in the `sizes` array in image meta.
 399               */
 400              if ( array_key_exists( $size_name, $new_sizes ) ) {
 401                  unset( $new_sizes[ $size_name ] );
 402              }
 403          }
 404      } else {
 405          $image_meta['sizes'] = array();
 406      }
 407  
 408      if ( empty( $new_sizes ) ) {
 409          // Nothing to do...
 410          return $image_meta;
 411      }
 412  
 413      /*
 414       * Sort the image sub-sizes in order of priority when creating them.
 415       * This ensures there is an appropriate sub-size the user can access immediately
 416       * even when there was an error and not all sub-sizes were created.
 417       */
 418      $priority = array(
 419          'medium'       => null,
 420          'large'        => null,
 421          'thumbnail'    => null,
 422          'medium_large' => null,
 423      );
 424  
 425      $new_sizes = array_filter( array_merge( $priority, $new_sizes ) );
 426  
 427      $editor = wp_get_image_editor( $file );
 428  
 429      if ( is_wp_error( $editor ) ) {
 430          // The image cannot be edited.
 431          return $image_meta;
 432      }
 433  
 434      // If stored EXIF data exists, rotate the source image before creating sub-sizes.
 435      if ( ! empty( $image_meta['image_meta'] ) ) {
 436          $rotated = $editor->maybe_exif_rotate();
 437  
 438          if ( is_wp_error( $rotated ) ) {
 439              // TODO: Log errors.
 440          }
 441      }
 442  
 443      if ( method_exists( $editor, 'make_subsize' ) ) {
 444          foreach ( $new_sizes as $new_size_name => $new_size_data ) {
 445              $new_size_meta = $editor->make_subsize( $new_size_data );
 446  
 447              if ( is_wp_error( $new_size_meta ) ) {
 448                  // TODO: Log errors.
 449              } else {
 450                  // Save the size meta value.
 451                  $image_meta['sizes'][ $new_size_name ] = $new_size_meta;
 452                  wp_update_attachment_metadata( $attachment_id, $image_meta );
 453              }
 454          }
 455      } else {
 456          // Fall back to `$editor->multi_resize()`.
 457          $created_sizes = $editor->multi_resize( $new_sizes );
 458  
 459          if ( ! empty( $created_sizes ) ) {
 460              $image_meta['sizes'] = array_merge( $image_meta['sizes'], $created_sizes );
 461              wp_update_attachment_metadata( $attachment_id, $image_meta );
 462          }
 463      }
 464  
 465      return $image_meta;
 466  }
 467  
 468  /**
 469   * Generate attachment meta data and create image sub-sizes for images.
 470   *
 471   * @since 2.1.0
 472   *
 473   * @param int    $attachment_id Attachment ID to process.
 474   * @param string $file          Filepath of the attached image.
 475   * @return array Metadata for attachment.
 476   */
 477  function wp_generate_attachment_metadata( $attachment_id, $file ) {
 478      $attachment = get_post( $attachment_id );
 479  
 480      $metadata  = array();
 481      $support   = false;
 482      $mime_type = get_post_mime_type( $attachment );
 483  
 484      if ( preg_match( '!^image/!', $mime_type ) && file_is_displayable_image( $file ) ) {
 485          // Make thumbnails and other intermediate sizes.
 486          $metadata = wp_create_image_subsizes( $file, $attachment_id );
 487      } elseif ( wp_attachment_is( 'video', $attachment ) ) {
 488          $metadata = wp_read_video_metadata( $file );
 489          $support  = current_theme_supports( 'post-thumbnails', 'attachment:video' ) || post_type_supports( 'attachment:video', 'thumbnail' );
 490      } elseif ( wp_attachment_is( 'audio', $attachment ) ) {
 491          $metadata = wp_read_audio_metadata( $file );
 492          $support  = current_theme_supports( 'post-thumbnails', 'attachment:audio' ) || post_type_supports( 'attachment:audio', 'thumbnail' );
 493      }
 494  
 495      /*
 496       * wp_read_video_metadata() and wp_read_audio_metadata() return `false`
 497       * if the attachment does not exist in the local filesystem,
 498       * so make sure to convert the value to an array.
 499       */
 500      if ( ! is_array( $metadata ) ) {
 501          $metadata = array();
 502      }
 503  
 504      if ( $support && ! empty( $metadata['image']['data'] ) ) {
 505          // Check for existing cover.
 506          $hash   = md5( $metadata['image']['data'] );
 507          $posts  = get_posts(
 508              array(
 509                  'fields'         => 'ids',
 510                  'post_type'      => 'attachment',
 511                  'post_mime_type' => $metadata['image']['mime'],
 512                  'post_status'    => 'inherit',
 513                  'posts_per_page' => 1,
 514                  'meta_key'       => '_cover_hash',
 515                  'meta_value'     => $hash,
 516              )
 517          );
 518          $exists = reset( $posts );
 519  
 520          if ( ! empty( $exists ) ) {
 521              update_post_meta( $attachment_id, '_thumbnail_id', $exists );
 522          } else {
 523              $ext = '.jpg';
 524              switch ( $metadata['image']['mime'] ) {
 525                  case 'image/gif':
 526                      $ext = '.gif';
 527                      break;
 528                  case 'image/png':
 529                      $ext = '.png';
 530                      break;
 531                  case 'image/webp':
 532                      $ext = '.webp';
 533                      break;
 534              }
 535              $basename = str_replace( '.', '-', wp_basename( $file ) ) . '-image' . $ext;
 536              $uploaded = wp_upload_bits( $basename, '', $metadata['image']['data'] );
 537              if ( false === $uploaded['error'] ) {
 538                  $image_attachment = array(
 539                      'post_mime_type' => $metadata['image']['mime'],
 540                      'post_type'      => 'attachment',
 541                      'post_content'   => '',
 542                  );
 543                  /**
 544                   * Filters the parameters for the attachment thumbnail creation.
 545                   *
 546                   * @since 3.9.0
 547                   *
 548                   * @param array $image_attachment An array of parameters to create the thumbnail.
 549                   * @param array $metadata         Current attachment metadata.
 550                   * @param array $uploaded         {
 551                   *     Information about the newly-uploaded file.
 552                   *
 553                   *     @type string $file  Filename of the newly-uploaded file.
 554                   *     @type string $url   URL of the uploaded file.
 555                   *     @type string $type  File type.
 556                   * }
 557                   */
 558                  $image_attachment = apply_filters( 'attachment_thumbnail_args', $image_attachment, $metadata, $uploaded );
 559  
 560                  $sub_attachment_id = wp_insert_attachment( $image_attachment, $uploaded['file'] );
 561                  add_post_meta( $sub_attachment_id, '_cover_hash', $hash );
 562                  $attach_data = wp_generate_attachment_metadata( $sub_attachment_id, $uploaded['file'] );
 563                  wp_update_attachment_metadata( $sub_attachment_id, $attach_data );
 564                  update_post_meta( $attachment_id, '_thumbnail_id', $sub_attachment_id );
 565              }
 566          }
 567      } elseif ( 'application/pdf' === $mime_type ) {
 568          // Try to create image thumbnails for PDFs.
 569  
 570          $fallback_sizes = array(
 571              'thumbnail',
 572              'medium',
 573              'large',
 574          );
 575  
 576          /**
 577           * Filters the image sizes generated for non-image mime types.
 578           *
 579           * @since 4.7.0
 580           *
 581           * @param string[] $fallback_sizes An array of image size names.
 582           * @param array    $metadata       Current attachment metadata.
 583           */
 584          $fallback_sizes = apply_filters( 'fallback_intermediate_image_sizes', $fallback_sizes, $metadata );
 585  
 586          $registered_sizes = wp_get_registered_image_subsizes();
 587          $merged_sizes     = array_intersect_key( $registered_sizes, array_flip( $fallback_sizes ) );
 588  
 589          // Force thumbnails to be soft crops.
 590          if ( isset( $merged_sizes['thumbnail'] ) && is_array( $merged_sizes['thumbnail'] ) ) {
 591              $merged_sizes['thumbnail']['crop'] = false;
 592          }
 593  
 594          // Only load PDFs in an image editor if we're processing sizes.
 595          if ( ! empty( $merged_sizes ) ) {
 596              $editor = wp_get_image_editor( $file );
 597  
 598              if ( ! is_wp_error( $editor ) ) { // No support for this type of file.
 599                  /*
 600                   * PDFs may have the same file filename as JPEGs.
 601                   * Ensure the PDF preview image does not overwrite any JPEG images that already exist.
 602                   */
 603                  $dirname      = dirname( $file ) . '/';
 604                  $ext          = '.' . pathinfo( $file, PATHINFO_EXTENSION );
 605                  $preview_file = $dirname . wp_unique_filename( $dirname, wp_basename( $file, $ext ) . '-pdf.jpg' );
 606  
 607                  $uploaded = $editor->save( $preview_file, 'image/jpeg' );
 608                  unset( $editor );
 609  
 610                  // Resize based on the full size image, rather than the source.
 611                  if ( ! is_wp_error( $uploaded ) ) {
 612                      $image_file = $uploaded['path'];
 613                      unset( $uploaded['path'] );
 614  
 615                      $metadata['sizes'] = array(
 616                          'full' => $uploaded,
 617                      );
 618  
 619                      // Save the meta data before any image post-processing errors could happen.
 620                      wp_update_attachment_metadata( $attachment_id, $metadata );
 621  
 622                      // Create sub-sizes saving the image meta after each.
 623                      $metadata = _wp_make_subsizes( $merged_sizes, $image_file, $metadata, $attachment_id );
 624                  }
 625              }
 626          }
 627      }
 628  
 629      // Remove the blob of binary data from the array.
 630      unset( $metadata['image']['data'] );
 631  
 632      /**
 633       * Filters the generated attachment meta data.
 634       *
 635       * @since 2.1.0
 636       * @since 5.3.0 The `$context` parameter was added.
 637       *
 638       * @param array  $metadata      An array of attachment meta data.
 639       * @param int    $attachment_id Current attachment ID.
 640       * @param string $context       Additional context. Can be 'create' when metadata was initially created for new attachment
 641       *                              or 'update' when the metadata was updated.
 642       */
 643      return apply_filters( 'wp_generate_attachment_metadata', $metadata, $attachment_id, 'create' );
 644  }
 645  
 646  /**
 647   * Convert a fraction string to a decimal.
 648   *
 649   * @since 2.5.0
 650   *
 651   * @param string $str Fraction string.
 652   * @return int|float Returns calculated fraction or integer 0 on invalid input.
 653   */
 654  function wp_exif_frac2dec( $str ) {
 655      if ( ! is_scalar( $str ) || is_bool( $str ) ) {
 656          return 0;
 657      }
 658  
 659      if ( ! is_string( $str ) ) {
 660          return $str; // This can only be an integer or float, so this is fine.
 661      }
 662  
 663      // Fractions passed as a string must contain a single `/`.
 664      if ( substr_count( $str, '/' ) !== 1 ) {
 665          if ( is_numeric( $str ) ) {
 666              return (float) $str;
 667          }
 668  
 669          return 0;
 670      }
 671  
 672      list( $numerator, $denominator ) = explode( '/', $str );
 673  
 674      // Both the numerator and the denominator must be numbers.
 675      if ( ! is_numeric( $numerator ) || ! is_numeric( $denominator ) ) {
 676          return 0;
 677      }
 678  
 679      // The denominator must not be zero.
 680      if ( 0 == $denominator ) { // phpcs:ignore WordPress.PHP.StrictComparisons.LooseComparison -- Deliberate loose comparison.
 681          return 0;
 682      }
 683  
 684      return $numerator / $denominator;
 685  }
 686  
 687  /**
 688   * Convert the exif date format to a unix timestamp.
 689   *
 690   * @since 2.5.0
 691   *
 692   * @param string $str A date string expected to be in Exif format (Y:m:d H:i:s).
 693   * @return int|false The unix timestamp, or false on failure.
 694   */
 695  function wp_exif_date2ts( $str ) {
 696      list( $date, $time ) = explode( ' ', trim( $str ) );
 697      list( $y, $m, $d )   = explode( ':', $date );
 698  
 699      return strtotime( "{$y}-{$m}-{$d} {$time}" );
 700  }
 701  
 702  /**
 703   * Get extended image metadata, exif or iptc as available.
 704   *
 705   * Retrieves the EXIF metadata aperture, credit, camera, caption, copyright, iso
 706   * created_timestamp, focal_length, shutter_speed, and title.
 707   *
 708   * The IPTC metadata that is retrieved is APP13, credit, byline, created date
 709   * and time, caption, copyright, and title. Also includes FNumber, Model,
 710   * DateTimeDigitized, FocalLength, ISOSpeedRatings, and ExposureTime.
 711   *
 712   * @todo Try other exif libraries if available.
 713   * @since 2.5.0
 714   *
 715   * @param string $file
 716   * @return array|false Image metadata array on success, false on failure.
 717   */
 718  function wp_read_image_metadata( $file ) {
 719      if ( ! file_exists( $file ) ) {
 720          return false;
 721      }
 722  
 723      list( , , $image_type ) = wp_getimagesize( $file );
 724  
 725      /*
 726       * EXIF contains a bunch of data we'll probably never need formatted in ways
 727       * that are difficult to use. We'll normalize it and just extract the fields
 728       * that are likely to be useful. Fractions and numbers are converted to
 729       * floats, dates to unix timestamps, and everything else to strings.
 730       */
 731      $meta = array(
 732          'aperture'          => 0,
 733          'credit'            => '',
 734          'camera'            => '',
 735          'caption'           => '',
 736          'created_timestamp' => 0,
 737          'copyright'         => '',
 738          'focal_length'      => 0,
 739          'iso'               => 0,
 740          'shutter_speed'     => 0,
 741          'title'             => '',
 742          'orientation'       => 0,
 743          'keywords'          => array(),
 744      );
 745  
 746      $iptc = array();
 747      $info = array();
 748      /*
 749       * Read IPTC first, since it might contain data not available in exif such
 750       * as caption, description etc.
 751       */
 752      if ( is_callable( 'iptcparse' ) ) {
 753          wp_getimagesize( $file, $info );
 754  
 755          if ( ! empty( $info['APP13'] ) ) {
 756              // Don't silence errors when in debug mode, unless running unit tests.
 757              if ( defined( 'WP_DEBUG' ) && WP_DEBUG
 758                  && ! defined( 'WP_RUN_CORE_TESTS' )
 759              ) {
 760                  $iptc = iptcparse( $info['APP13'] );
 761              } else {
 762                  // phpcs:ignore WordPress.PHP.NoSilencedErrors -- Silencing notice and warning is intentional. See https://core.trac.wordpress.org/ticket/42480
 763                  $iptc = @iptcparse( $info['APP13'] );
 764              }
 765  
 766              // Headline, "A brief synopsis of the caption".
 767              if ( ! empty( $iptc['2#105'][0] ) ) {
 768                  $meta['title'] = trim( $iptc['2#105'][0] );
 769                  /*
 770                  * Title, "Many use the Title field to store the filename of the image,
 771                  * though the field may be used in many ways".
 772                  */
 773              } elseif ( ! empty( $iptc['2#005'][0] ) ) {
 774                  $meta['title'] = trim( $iptc['2#005'][0] );
 775              }
 776  
 777              if ( ! empty( $iptc['2#120'][0] ) ) { // Description / legacy caption.
 778                  $caption = trim( $iptc['2#120'][0] );
 779  
 780                  mbstring_binary_safe_encoding();
 781                  $caption_length = strlen( $caption );
 782                  reset_mbstring_encoding();
 783  
 784                  if ( empty( $meta['title'] ) && $caption_length < 80 ) {
 785                      // Assume the title is stored in 2:120 if it's short.
 786                      $meta['title'] = $caption;
 787                  }
 788  
 789                  $meta['caption'] = $caption;
 790              }
 791  
 792              if ( ! empty( $iptc['2#110'][0] ) ) { // Credit.
 793                  $meta['credit'] = trim( $iptc['2#110'][0] );
 794              } elseif ( ! empty( $iptc['2#080'][0] ) ) { // Creator / legacy byline.
 795                  $meta['credit'] = trim( $iptc['2#080'][0] );
 796              }
 797  
 798              if ( ! empty( $iptc['2#055'][0] ) && ! empty( $iptc['2#060'][0] ) ) { // Created date and time.
 799                  $meta['created_timestamp'] = strtotime( $iptc['2#055'][0] . ' ' . $iptc['2#060'][0] );
 800              }
 801  
 802              if ( ! empty( $iptc['2#116'][0] ) ) { // Copyright.
 803                  $meta['copyright'] = trim( $iptc['2#116'][0] );
 804              }
 805  
 806              if ( ! empty( $iptc['2#025'][0] ) ) { // Keywords array.
 807                  $meta['keywords'] = array_values( $iptc['2#025'] );
 808              }
 809          }
 810      }
 811  
 812      $exif = array();
 813  
 814      /**
 815       * Filters the image types to check for exif data.
 816       *
 817       * @since 2.5.0
 818       *
 819       * @param int[] $image_types Array of image types to check for exif data. Each value
 820       *                           is usually one of the `IMAGETYPE_*` constants.
 821       */
 822      $exif_image_types = apply_filters( 'wp_read_image_metadata_types', array( IMAGETYPE_JPEG, IMAGETYPE_TIFF_II, IMAGETYPE_TIFF_MM ) );
 823  
 824      if ( is_callable( 'exif_read_data' ) && in_array( $image_type, $exif_image_types, true ) ) {
 825          // Don't silence errors when in debug mode, unless running unit tests.
 826          if ( defined( 'WP_DEBUG' ) && WP_DEBUG
 827              && ! defined( 'WP_RUN_CORE_TESTS' )
 828          ) {
 829              $exif = exif_read_data( $file );
 830          } else {
 831              // phpcs:ignore WordPress.PHP.NoSilencedErrors -- Silencing notice and warning is intentional. See https://core.trac.wordpress.org/ticket/42480
 832              $exif = @exif_read_data( $file );
 833          }
 834  
 835          if ( ! empty( $exif['ImageDescription'] ) ) {
 836              mbstring_binary_safe_encoding();
 837              $description_length = strlen( $exif['ImageDescription'] );
 838              reset_mbstring_encoding();
 839  
 840              if ( empty( $meta['title'] ) && $description_length < 80 ) {
 841                  // Assume the title is stored in ImageDescription.
 842                  $meta['title'] = trim( $exif['ImageDescription'] );
 843              }
 844  
 845              if ( empty( $meta['caption'] ) && ! empty( $exif['COMPUTED']['UserComment'] ) ) {
 846                  $meta['caption'] = trim( $exif['COMPUTED']['UserComment'] );
 847              }
 848  
 849              if ( empty( $meta['caption'] ) ) {
 850                  $meta['caption'] = trim( $exif['ImageDescription'] );
 851              }
 852          } elseif ( empty( $meta['caption'] ) && ! empty( $exif['Comments'] ) ) {
 853              $meta['caption'] = trim( $exif['Comments'] );
 854          }
 855  
 856          if ( empty( $meta['credit'] ) ) {
 857              if ( ! empty( $exif['Artist'] ) ) {
 858                  $meta['credit'] = trim( $exif['Artist'] );
 859              } elseif ( ! empty( $exif['Author'] ) ) {
 860                  $meta['credit'] = trim( $exif['Author'] );
 861              }
 862          }
 863  
 864          if ( empty( $meta['copyright'] ) && ! empty( $exif['Copyright'] ) ) {
 865              $meta['copyright'] = trim( $exif['Copyright'] );
 866          }
 867          if ( ! empty( $exif['FNumber'] ) && is_scalar( $exif['FNumber'] ) ) {
 868              $meta['aperture'] = round( wp_exif_frac2dec( $exif['FNumber'] ), 2 );
 869          }
 870          if ( ! empty( $exif['Model'] ) ) {
 871              $meta['camera'] = trim( $exif['Model'] );
 872          }
 873          if ( empty( $meta['created_timestamp'] ) && ! empty( $exif['DateTimeDigitized'] ) ) {
 874              $meta['created_timestamp'] = wp_exif_date2ts( $exif['DateTimeDigitized'] );
 875          }
 876          if ( ! empty( $exif['FocalLength'] ) ) {
 877              $meta['focal_length'] = (string) $exif['FocalLength'];
 878              if ( is_scalar( $exif['FocalLength'] ) ) {
 879                  $meta['focal_length'] = (string) wp_exif_frac2dec( $exif['FocalLength'] );
 880              }
 881          }
 882          if ( ! empty( $exif['ISOSpeedRatings'] ) ) {
 883              $meta['iso'] = is_array( $exif['ISOSpeedRatings'] ) ? reset( $exif['ISOSpeedRatings'] ) : $exif['ISOSpeedRatings'];
 884              $meta['iso'] = trim( $meta['iso'] );
 885          }
 886          if ( ! empty( $exif['ExposureTime'] ) ) {
 887              $meta['shutter_speed'] = (string) $exif['ExposureTime'];
 888              if ( is_scalar( $exif['ExposureTime'] ) ) {
 889                  $meta['shutter_speed'] = (string) wp_exif_frac2dec( $exif['ExposureTime'] );
 890              }
 891          }
 892          if ( ! empty( $exif['Orientation'] ) ) {
 893              $meta['orientation'] = $exif['Orientation'];
 894          }
 895      }
 896  
 897      foreach ( array( 'title', 'caption', 'credit', 'copyright', 'camera', 'iso' ) as $key ) {
 898          if ( $meta[ $key ] && ! seems_utf8( $meta[ $key ] ) ) {
 899              $meta[ $key ] = utf8_encode( $meta[ $key ] );
 900          }
 901      }
 902  
 903      foreach ( $meta['keywords'] as $key => $keyword ) {
 904          if ( ! seems_utf8( $keyword ) ) {
 905              $meta['keywords'][ $key ] = utf8_encode( $keyword );
 906          }
 907      }
 908  
 909      $meta = wp_kses_post_deep( $meta );
 910  
 911      /**
 912       * Filters the array of meta data read from an image's exif data.
 913       *
 914       * @since 2.5.0
 915       * @since 4.4.0 The `$iptc` parameter was added.
 916       * @since 5.0.0 The `$exif` parameter was added.
 917       *
 918       * @param array  $meta       Image meta data.
 919       * @param string $file       Path to image file.
 920       * @param int    $image_type Type of image, one of the `IMAGETYPE_XXX` constants.
 921       * @param array  $iptc       IPTC data.
 922       * @param array  $exif       EXIF data.
 923       */
 924      return apply_filters( 'wp_read_image_metadata', $meta, $file, $image_type, $iptc, $exif );
 925  
 926  }
 927  
 928  /**
 929   * Validate that file is an image.
 930   *
 931   * @since 2.5.0
 932   *
 933   * @param string $path File path to test if valid image.
 934   * @return bool True if valid image, false if not valid image.
 935   */
 936  function file_is_valid_image( $path ) {
 937      $size = wp_getimagesize( $path );
 938      return ! empty( $size );
 939  }
 940  
 941  /**
 942   * Validate that file is suitable for displaying within a web page.
 943   *
 944   * @since 2.5.0
 945   *
 946   * @param string $path File path to test.
 947   * @return bool True if suitable, false if not suitable.
 948   */
 949  function file_is_displayable_image( $path ) {
 950      $displayable_image_types = array( IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_BMP, IMAGETYPE_ICO, IMAGETYPE_WEBP );
 951  
 952      $info = wp_getimagesize( $path );
 953      if ( empty( $info ) ) {
 954          $result = false;
 955      } elseif ( ! in_array( $info[2], $displayable_image_types, true ) ) {
 956          $result = false;
 957      } else {
 958          $result = true;
 959      }
 960  
 961      /**
 962       * Filters whether the current image is displayable in the browser.
 963       *
 964       * @since 2.5.0
 965       *
 966       * @param bool   $result Whether the image can be displayed. Default true.
 967       * @param string $path   Path to the image.
 968       */
 969      return apply_filters( 'file_is_displayable_image', $result, $path );
 970  }
 971  
 972  /**
 973   * Load an image resource for editing.
 974   *
 975   * @since 2.9.0
 976   *
 977   * @param int          $attachment_id Attachment ID.
 978   * @param string       $mime_type     Image mime type.
 979   * @param string|int[] $size          Optional. Image size. Accepts any registered image size name, or an array
 980   *                                    of width and height values in pixels (in that order). Default 'full'.
 981   * @return resource|GdImage|false The resulting image resource or GdImage instance on success,
 982   *                                false on failure.
 983   */
 984  function load_image_to_edit( $attachment_id, $mime_type, $size = 'full' ) {
 985      $filepath = _load_image_to_edit_path( $attachment_id, $size );
 986      if ( empty( $filepath ) ) {
 987          return false;
 988      }
 989  
 990      switch ( $mime_type ) {
 991          case 'image/jpeg':
 992              $image = imagecreatefromjpeg( $filepath );
 993              break;
 994          case 'image/png':
 995              $image = imagecreatefrompng( $filepath );
 996              break;
 997          case 'image/gif':
 998              $image = imagecreatefromgif( $filepath );
 999              break;
1000          case 'image/webp':
1001              $image = false;
1002              if ( function_exists( 'imagecreatefromwebp' ) ) {
1003                  $image = imagecreatefromwebp( $filepath );
1004              }
1005              break;
1006          default:
1007              $image = false;
1008              break;
1009      }
1010  
1011      if ( is_gd_image( $image ) ) {
1012          /**
1013           * Filters the current image being loaded for editing.
1014           *
1015           * @since 2.9.0
1016           *
1017           * @param resource|GdImage $image         Current image.
1018           * @param int              $attachment_id Attachment ID.
1019           * @param string|int[]     $size          Requested image size. Can be any registered image size name, or
1020           *                                        an array of width and height values in pixels (in that order).
1021           */
1022          $image = apply_filters( 'load_image_to_edit', $image, $attachment_id, $size );
1023  
1024          if ( function_exists( 'imagealphablending' ) && function_exists( 'imagesavealpha' ) ) {
1025              imagealphablending( $image, false );
1026              imagesavealpha( $image, true );
1027          }
1028      }
1029  
1030      return $image;
1031  }
1032  
1033  /**
1034   * Retrieve the path or URL of an attachment's attached file.
1035   *
1036   * If the attached file is not present on the local filesystem (usually due to replication plugins),
1037   * then the URL of the file is returned if `allow_url_fopen` is supported.
1038   *
1039   * @since 3.4.0
1040   * @access private
1041   *
1042   * @param int          $attachment_id Attachment ID.
1043   * @param string|int[] $size          Optional. Image size. Accepts any registered image size name, or an array
1044   *                                    of width and height values in pixels (in that order). Default 'full'.
1045   * @return string|false File path or URL on success, false on failure.
1046   */
1047  function _load_image_to_edit_path( $attachment_id, $size = 'full' ) {
1048      $filepath = get_attached_file( $attachment_id );
1049  
1050      if ( $filepath && file_exists( $filepath ) ) {
1051          if ( 'full' !== $size ) {
1052              $data = image_get_intermediate_size( $attachment_id, $size );
1053  
1054              if ( $data ) {
1055                  $filepath = path_join( dirname( $filepath ), $data['file'] );
1056  
1057                  /**
1058                   * Filters the path to an attachment's file when editing the image.
1059                   *
1060                   * The filter is evaluated for all image sizes except 'full'.
1061                   *
1062                   * @since 3.1.0
1063                   *
1064                   * @param string       $path          Path to the current image.
1065                   * @param int          $attachment_id Attachment ID.
1066                   * @param string|int[] $size          Requested image size. Can be any registered image size name, or
1067                   *                                    an array of width and height values in pixels (in that order).
1068                   */
1069                  $filepath = apply_filters( 'load_image_to_edit_filesystempath', $filepath, $attachment_id, $size );
1070              }
1071          }
1072      } elseif ( function_exists( 'fopen' ) && ini_get( 'allow_url_fopen' ) ) {
1073          /**
1074           * Filters the path to an attachment's URL when editing the image.
1075           *
1076           * The filter is only evaluated if the file isn't stored locally and `allow_url_fopen` is enabled on the server.
1077           *
1078           * @since 3.1.0
1079           *
1080           * @param string|false $image_url     Current image URL.
1081           * @param int          $attachment_id Attachment ID.
1082           * @param string|int[] $size          Requested image size. Can be any registered image size name, or
1083           *                                    an array of width and height values in pixels (in that order).
1084           */
1085          $filepath = apply_filters( 'load_image_to_edit_attachmenturl', wp_get_attachment_url( $attachment_id ), $attachment_id, $size );
1086      }
1087  
1088      /**
1089       * Filters the returned path or URL of the current image.
1090       *
1091       * @since 2.9.0
1092       *
1093       * @param string|false $filepath      File path or URL to current image, or false.
1094       * @param int          $attachment_id Attachment ID.
1095       * @param string|int[] $size          Requested image size. Can be any registered image size name, or
1096       *                                    an array of width and height values in pixels (in that order).
1097       */
1098      return apply_filters( 'load_image_to_edit_path', $filepath, $attachment_id, $size );
1099  }
1100  
1101  /**
1102   * Copy an existing image file.
1103   *
1104   * @since 3.4.0
1105   * @access private
1106   *
1107   * @param int $attachment_id Attachment ID.
1108   * @return string|false New file path on success, false on failure.
1109   */
1110  function _copy_image_file( $attachment_id ) {
1111      $dst_file = get_attached_file( $attachment_id );
1112      $src_file = $dst_file;
1113  
1114      if ( ! file_exists( $src_file ) ) {
1115          $src_file = _load_image_to_edit_path( $attachment_id );
1116      }
1117  
1118      if ( $src_file ) {
1119          $dst_file = str_replace( wp_basename( $dst_file ), 'copy-' . wp_basename( $dst_file ), $dst_file );
1120          $dst_file = dirname( $dst_file ) . '/' . wp_unique_filename( dirname( $dst_file ), wp_basename( $dst_file ) );
1121  
1122          /*
1123           * The directory containing the original file may no longer
1124           * exist when using a replication plugin.
1125           */
1126          wp_mkdir_p( dirname( $dst_file ) );
1127  
1128          if ( ! copy( $src_file, $dst_file ) ) {
1129              $dst_file = false;
1130          }
1131      } else {
1132          $dst_file = false;
1133      }
1134  
1135      return $dst_file;
1136  }


Generated: Tue Jan 18 01:00:03 2022 Cross-referenced by PHPXref 0.7.1