[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

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


Generated: Tue Oct 22 08:20:01 2019 Cross-referenced by PHPXref 0.7