[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

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

   1  <?php
   2  /**
   3   * WordPress Image Editor
   4   *
   5   * @package WordPress
   6   * @subpackage Administration
   7   */
   8  
   9  /**
  10   * Loads the WP image-editing interface.
  11   *
  12   * @since 2.9.0
  13   *
  14   * @param int          $post_id Attachment post ID.
  15   * @param false|object $msg     Optional. Message to display for image editor updates or errors.
  16   *                              Default false.
  17   */
  18  function wp_image_editor( $post_id, $msg = false ) {
  19      $nonce     = wp_create_nonce( "image_editor-$post_id" );
  20      $meta      = wp_get_attachment_metadata( $post_id );
  21      $thumb     = image_get_intermediate_size( $post_id, 'thumbnail' );
  22      $sub_sizes = isset( $meta['sizes'] ) && is_array( $meta['sizes'] );
  23      $note      = '';
  24  
  25      if ( isset( $meta['width'], $meta['height'] ) ) {
  26          $big = max( $meta['width'], $meta['height'] );
  27      } else {
  28          die( __( 'Image data does not exist. Please re-upload the image.' ) );
  29      }
  30  
  31      $sizer = $big > 600 ? 600 / $big : 1;
  32  
  33      $backup_sizes = get_post_meta( $post_id, '_wp_attachment_backup_sizes', true );
  34      $can_restore  = false;
  35  
  36      if ( ! empty( $backup_sizes ) && isset( $backup_sizes['full-orig'], $meta['file'] ) ) {
  37          $can_restore = wp_basename( $meta['file'] ) !== $backup_sizes['full-orig']['file'];
  38      }
  39  
  40      if ( $msg ) {
  41          if ( isset( $msg->error ) ) {
  42              $note = "<div class='notice notice-error' role='alert'><p>$msg->error</p></div>";
  43          } elseif ( isset( $msg->msg ) ) {
  44              $note = "<div class='notice notice-success' role='alert'><p>$msg->msg</p></div>";
  45          }
  46      }
  47  
  48      /**
  49       * Shows the settings in the Image Editor that allow selecting to edit only the thumbnail of an image.
  50       *
  51       * @since 6.3.0
  52       *
  53       * @param bool $show Whether to show the settings in the Image Editor. Default false.
  54       */
  55      $edit_thumbnails_separately = (bool) apply_filters( 'image_edit_thumbnails_separately', false );
  56  
  57      ?>
  58      <div class="imgedit-wrap wp-clearfix">
  59      <div id="imgedit-panel-<?php echo $post_id; ?>">
  60      <?php echo $note; ?>
  61      <div class="imgedit-panel-content imgedit-panel-tools wp-clearfix">
  62          <div class="imgedit-menu wp-clearfix">
  63              <button type="button" onclick="imageEdit.toggleCropTool( <?php echo "$post_id, '$nonce'"; ?>, this );" aria-expanded="false" aria-controls="imgedit-crop" class="imgedit-crop button disabled" disabled><?php esc_html_e( 'Crop' ); ?></button>
  64              <button type="button" class="imgedit-scale button" onclick="imageEdit.toggleControls(this);" aria-expanded="false" aria-controls="imgedit-scale"><?php esc_html_e( 'Scale' ); ?></button>
  65              <div class="imgedit-rotate-menu-container">
  66                  <button type="button" aria-controls="imgedit-rotate-menu" class="imgedit-rotate button" aria-expanded="false" onclick="imageEdit.togglePopup(this)" onblur="imageEdit.monitorPopup()"><?php esc_html_e( 'Image Rotation' ); ?></button>
  67                  <div id="imgedit-rotate-menu" class="imgedit-popup-menu">
  68              <?php
  69              // On some setups GD library does not provide imagerotate() - Ticket #11536.
  70              if ( wp_image_editor_supports(
  71                  array(
  72                      'mime_type' => get_post_mime_type( $post_id ),
  73                      'methods'   => array( 'rotate' ),
  74                  )
  75              ) ) {
  76                  $note_no_rotate = '';
  77                  ?>
  78                      <button type="button" class="imgedit-rleft button" onkeydown="imageEdit.browsePopup(event, this)" onclick="imageEdit.rotate( 90, <?php echo "$post_id, '$nonce'"; ?>, this)" onblur="imageEdit.monitorPopup()"><?php esc_html_e( 'Rotate 90&deg; left' ); ?></button>
  79                      <button type="button" class="imgedit-rright button" onkeydown="imageEdit.browsePopup(event, this)" onclick="imageEdit.rotate(-90, <?php echo "$post_id, '$nonce'"; ?>, this)" onblur="imageEdit.monitorPopup()"><?php esc_html_e( 'Rotate 90&deg; right' ); ?></button>
  80                      <button type="button" class="imgedit-rfull button" onkeydown="imageEdit.browsePopup(event, this)" onclick="imageEdit.rotate(180, <?php echo "$post_id, '$nonce'"; ?>, this)" onblur="imageEdit.monitorPopup()"><?php esc_html_e( 'Rotate 180&deg;' ); ?></button>
  81                  <?php
  82              } else {
  83                  $note_no_rotate = '<p class="note-no-rotate"><em>' . __( 'Image rotation is not supported by your web host.' ) . '</em></p>';
  84                  ?>
  85                      <button type="button" class="imgedit-rleft button disabled" disabled></button>
  86                      <button type="button" class="imgedit-rright button disabled" disabled></button>
  87                  <?php
  88              }
  89              ?>
  90                      <hr />
  91                      <button type="button" onkeydown="imageEdit.browsePopup(event, this)" onclick="imageEdit.flip(1, <?php echo "$post_id, '$nonce'"; ?>, this)" onblur="imageEdit.monitorPopup()" class="imgedit-flipv button"><?php esc_html_e( 'Flip vertical' ); ?></button>
  92                      <button type="button" onkeydown="imageEdit.browsePopup(event, this)" onclick="imageEdit.flip(2, <?php echo "$post_id, '$nonce'"; ?>, this)" onblur="imageEdit.monitorPopup()" class="imgedit-fliph button"><?php esc_html_e( 'Flip horizontal' ); ?></button>
  93                      <?php echo $note_no_rotate; ?>
  94                  </div>
  95              </div>
  96          </div>
  97          <div class="imgedit-submit imgedit-menu">
  98              <button type="button" id="image-undo-<?php echo $post_id; ?>" onclick="imageEdit.undo(<?php echo "$post_id, '$nonce'"; ?>, this)" class="imgedit-undo button disabled" disabled><?php esc_html_e( 'Undo' ); ?></button>
  99              <button type="button" id="image-redo-<?php echo $post_id; ?>" onclick="imageEdit.redo(<?php echo "$post_id, '$nonce'"; ?>, this)" class="imgedit-redo button disabled" disabled><?php esc_html_e( 'Redo' ); ?></button>
 100              <button type="button" onclick="imageEdit.close(<?php echo $post_id; ?>, 1)" class="button imgedit-cancel-btn"><?php esc_html_e( 'Cancel Editing' ); ?></button>
 101              <button type="button" onclick="imageEdit.save(<?php echo "$post_id, '$nonce'"; ?>)" disabled="disabled" class="button button-primary imgedit-submit-btn"><?php esc_html_e( 'Save Edits' ); ?></button>
 102          </div>
 103      </div>
 104  
 105      <div class="imgedit-panel-content wp-clearfix">
 106          <div class="imgedit-tools">
 107              <input type="hidden" id="imgedit-nonce-<?php echo $post_id; ?>" value="<?php echo $nonce; ?>" />
 108              <input type="hidden" id="imgedit-sizer-<?php echo $post_id; ?>" value="<?php echo $sizer; ?>" />
 109              <input type="hidden" id="imgedit-history-<?php echo $post_id; ?>" value="" />
 110              <input type="hidden" id="imgedit-undone-<?php echo $post_id; ?>" value="0" />
 111              <input type="hidden" id="imgedit-selection-<?php echo $post_id; ?>" value="" />
 112              <input type="hidden" id="imgedit-x-<?php echo $post_id; ?>" value="<?php echo isset( $meta['width'] ) ? $meta['width'] : 0; ?>" />
 113              <input type="hidden" id="imgedit-y-<?php echo $post_id; ?>" value="<?php echo isset( $meta['height'] ) ? $meta['height'] : 0; ?>" />
 114  
 115              <div id="imgedit-crop-<?php echo $post_id; ?>" class="imgedit-crop-wrap">
 116              <div class="imgedit-crop-grid"></div>
 117              <img id="image-preview-<?php echo $post_id; ?>" onload="imageEdit.imgLoaded('<?php echo $post_id; ?>')"
 118                  src="<?php echo esc_url( admin_url( 'admin-ajax.php', 'relative' ) ) . '?action=imgedit-preview&amp;_ajax_nonce=' . $nonce . '&amp;postid=' . $post_id . '&amp;rand=' . rand( 1, 99999 ); ?>" alt="" />
 119              </div>
 120          </div>
 121          <div class="imgedit-settings">
 122              <div class="imgedit-tool-active">
 123                  <div class="imgedit-group">
 124                  <div id="imgedit-scale" tabindex="-1" class="imgedit-group-controls">
 125                      <div class="imgedit-group-top">
 126                          <h2><?php _e( 'Scale Image' ); ?></h2>
 127                          <button type="button" class="dashicons dashicons-editor-help imgedit-help-toggle" onclick="imageEdit.toggleHelp(this);" aria-expanded="false"><span class="screen-reader-text">
 128                          <?php
 129                          /* translators: Hidden accessibility text. */
 130                          esc_html_e( 'Scale Image Help' );
 131                          ?>
 132                          </span></button>
 133                          <div class="imgedit-help">
 134                          <p><?php _e( 'You can proportionally scale the original image. For best results, scaling should be done before you crop, flip, or rotate. Images can only be scaled down, not up.' ); ?></p>
 135                          </div>
 136                          <?php if ( isset( $meta['width'], $meta['height'] ) ) : ?>
 137                          <p>
 138                              <?php
 139                              printf(
 140                                  /* translators: %s: Image width and height in pixels. */
 141                                  __( 'Original dimensions %s' ),
 142                                  '<span class="imgedit-original-dimensions">' . $meta['width'] . ' &times; ' . $meta['height'] . '</span>'
 143                              );
 144                              ?>
 145                          </p>
 146                          <?php endif; ?>
 147                          <div class="imgedit-submit">
 148                          <fieldset class="imgedit-scale-controls">
 149                              <legend><?php _e( 'New dimensions:' ); ?></legend>
 150                              <div class="nowrap">
 151                              <label for="imgedit-scale-width-<?php echo $post_id; ?>" class="screen-reader-text">
 152                              <?php
 153                              /* translators: Hidden accessibility text. */
 154                              _e( 'scale height' );
 155                              ?>
 156                              </label>
 157                              <input type="number" step="1" min="0" max="<?php echo isset( $meta['width'] ) ? $meta['width'] : ''; ?>" aria-describedby="imgedit-scale-warn-<?php echo $post_id; ?>"  id="imgedit-scale-width-<?php echo $post_id; ?>" onkeyup="imageEdit.scaleChanged(<?php echo $post_id; ?>, 1, this)" onblur="imageEdit.scaleChanged(<?php echo $post_id; ?>, 1, this)" value="<?php echo isset( $meta['width'] ) ? $meta['width'] : 0; ?>" />
 158                              <span class="imgedit-separator" aria-hidden="true">&times;</span>
 159                              <label for="imgedit-scale-height-<?php echo $post_id; ?>" class="screen-reader-text"><?php _e( 'scale height' ); ?></label>
 160                              <input type="number" step="1" min="0" max="<?php echo isset( $meta['height'] ) ? $meta['height'] : ''; ?>" aria-describedby="imgedit-scale-warn-<?php echo $post_id; ?>" id="imgedit-scale-height-<?php echo $post_id; ?>" onkeyup="imageEdit.scaleChanged(<?php echo $post_id; ?>, 0, this)" onblur="imageEdit.scaleChanged(<?php echo $post_id; ?>, 0, this)" value="<?php echo isset( $meta['height'] ) ? $meta['height'] : 0; ?>" />
 161                              <button id="imgedit-scale-button" type="button" onclick="imageEdit.action(<?php echo "$post_id, '$nonce'"; ?>, 'scale')" class="button button-primary"><?php esc_html_e( 'Scale' ); ?></button>
 162                              </div>
 163                              <span class="imgedit-scale-warn" id="imgedit-scale-warn-<?php echo $post_id; ?>"><span class="dashicons dashicons-warning" aria-hidden="true"></span><?php esc_html_e( 'Images cannot be scaled to a size larger than the original.' ); ?></span>
 164                          </fieldset>
 165                          </div>
 166                      </div>
 167                  </div>
 168              </div>
 169  
 170          <?php if ( $can_restore ) { ?>
 171                  <div class="imgedit-group">
 172                  <div class="imgedit-group-top">
 173                      <h2><button type="button" onclick="imageEdit.toggleHelp(this);" class="button-link" aria-expanded="false"><?php _e( 'Restore original image' ); ?> <span class="dashicons dashicons-arrow-down imgedit-help-toggle"></span></button></h2>
 174                      <div class="imgedit-help imgedit-restore">
 175                      <p>
 176                      <?php
 177                      _e( 'Discard any changes and restore the original image.' );
 178                      if ( ! defined( 'IMAGE_EDIT_OVERWRITE' ) || ! IMAGE_EDIT_OVERWRITE ) {
 179                          echo ' ' . __( 'Previously edited copies of the image will not be deleted.' );
 180                      }
 181                      ?>
 182                      </p>
 183                      <div class="imgedit-submit">
 184                          <input type="button" onclick="imageEdit.action(<?php echo "$post_id, '$nonce'"; ?>, 'restore')" class="button button-primary" value="<?php esc_attr_e( 'Restore image' ); ?>" <?php echo $can_restore; ?> />
 185                      </div>
 186                  </div>
 187              </div>
 188              </div>
 189          <?php } ?>
 190              <div class="imgedit-group">
 191                  <div id="imgedit-crop" tabindex="-1" class="imgedit-group-controls">
 192                  <div class="imgedit-group-top">
 193                      <h2><?php _e( 'Crop Image' ); ?></h2>
 194                      <button type="button" class="dashicons dashicons-editor-help imgedit-help-toggle" onclick="imageEdit.toggleHelp(this);" aria-expanded="false"><span class="screen-reader-text">
 195                      <?php
 196                      /* translators: Hidden accessibility text. */
 197                      _e( 'Image Crop Help' );
 198                      ?>
 199                      </span></button>
 200                      <div class="imgedit-help">
 201                          <p><?php _e( 'To crop the image, click on it and drag to make your selection.' ); ?></p>
 202                          <p><strong><?php _e( 'Crop Aspect Ratio' ); ?></strong><br />
 203                          <?php _e( 'The aspect ratio is the relationship between the width and height. You can preserve the aspect ratio by holding down the shift key while resizing your selection. Use the input box to specify the aspect ratio, e.g. 1:1 (square), 4:3, 16:9, etc.' ); ?></p>
 204  
 205                          <p><strong><?php _e( 'Crop Selection' ); ?></strong><br />
 206                          <?php _e( 'Once you have made your selection, you can adjust it by entering the size in pixels. The minimum selection size is the thumbnail size as set in the Media settings.' ); ?></p>
 207                      </div>
 208                  </div>
 209                  <fieldset class="imgedit-crop-ratio">
 210                      <legend><?php _e( 'Aspect ratio:' ); ?></legend>
 211                      <div class="nowrap">
 212                      <label for="imgedit-crop-width-<?php echo $post_id; ?>" class="screen-reader-text">
 213                      <?php
 214                      /* translators: Hidden accessibility text. */
 215                      _e( 'crop ratio width' );
 216                      ?>
 217                      </label>
 218                      <input type="number" step="1" min="1" id="imgedit-crop-width-<?php echo $post_id; ?>" onkeyup="imageEdit.setRatioSelection(<?php echo $post_id; ?>, 0, this)" onblur="imageEdit.setRatioSelection(<?php echo $post_id; ?>, 0, this)" />
 219                      <span class="imgedit-separator" aria-hidden="true">:</span>
 220                      <label for="imgedit-crop-height-<?php echo $post_id; ?>" class="screen-reader-text">
 221                      <?php
 222                      /* translators: Hidden accessibility text. */
 223                      _e( 'crop ratio height' );
 224                      ?>
 225                      </label>
 226                      <input  type="number" step="1" min="0" id="imgedit-crop-height-<?php echo $post_id; ?>" onkeyup="imageEdit.setRatioSelection(<?php echo $post_id; ?>, 1, this)" onblur="imageEdit.setRatioSelection(<?php echo $post_id; ?>, 1, this)" />
 227                      </div>
 228                  </fieldset>
 229                  <fieldset id="imgedit-crop-sel-<?php echo $post_id; ?>" class="imgedit-crop-sel">
 230                      <legend><?php _e( 'Selection:' ); ?></legend>
 231                      <div class="nowrap">
 232                      <label for="imgedit-sel-width-<?php echo $post_id; ?>" class="screen-reader-text">
 233                      <?php
 234                      /* translators: Hidden accessibility text. */
 235                      _e( 'selection width' );
 236                      ?>
 237                      </label>
 238                      <input  type="number" step="1" min="0" id="imgedit-sel-width-<?php echo $post_id; ?>" onkeyup="imageEdit.setNumSelection(<?php echo $post_id; ?>, this)" onblur="imageEdit.setNumSelection(<?php echo $post_id; ?>, this)" />
 239                      <span class="imgedit-separator" aria-hidden="true">&times;</span>
 240                      <label for="imgedit-sel-height-<?php echo $post_id; ?>" class="screen-reader-text">
 241                      <?php
 242                      /* translators: Hidden accessibility text. */
 243                      _e( 'selection height' );
 244                      ?>
 245                      </label>
 246                      <input  type="number" step="1" min="0" id="imgedit-sel-height-<?php echo $post_id; ?>" onkeyup="imageEdit.setNumSelection(<?php echo $post_id; ?>, this)" onblur="imageEdit.setNumSelection(<?php echo $post_id; ?>, this)" />
 247                      </div>
 248                  </fieldset>
 249                  <fieldset id="imgedit-crop-sel-<?php echo $post_id; ?>" class="imgedit-crop-sel">
 250                      <legend><?php _e( 'Starting Coordinates:' ); ?></legend>
 251                      <div class="nowrap">
 252                      <label for="imgedit-start-x-<?php echo $post_id; ?>" class="screen-reader-text">
 253                      <?php
 254                      /* translators: Hidden accessibility text. */
 255                      _e( 'horizontal start position' );
 256                      ?>
 257                      </label>
 258                      <input  type="number" step="1" min="0" id="imgedit-start-x-<?php echo $post_id; ?>" onkeyup="imageEdit.setNumSelection(<?php echo $post_id; ?>, this)" onblur="imageEdit.setNumSelection(<?php echo $post_id; ?>, this)" value="0" />
 259                      <span class="imgedit-separator" aria-hidden="true">&times;</span>
 260                      <label for="imgedit-start-y-<?php echo $post_id; ?>" class="screen-reader-text">
 261                      <?php
 262                      /* translators: Hidden accessibility text. */
 263                      _e( 'vertical start position' );
 264                      ?>
 265                      </label>
 266                      <input  type="number" step="1" min="0" id="imgedit-start-y-<?php echo $post_id; ?>" onkeyup="imageEdit.setNumSelection(<?php echo $post_id; ?>, this)" onblur="imageEdit.setNumSelection(<?php echo $post_id; ?>, this)" value="0" />
 267                      </div>
 268                  </fieldset>
 269                  <div class="imgedit-crop-apply imgedit-menu container">
 270                      <button class="button-primary" type="button" onclick="imageEdit.handleCropToolClick( <?php echo "$post_id, '$nonce'"; ?>, this );" class="imgedit-crop-apply button"><?php esc_html_e( 'Apply Crop' ); ?></button> <button type="button" onclick="imageEdit.handleCropToolClick( <?php echo "$post_id, '$nonce'"; ?>, this );" class="imgedit-crop-clear button" disabled="disabled"><?php esc_html_e( 'Clear Crop' ); ?></button>
 271                  </div>
 272              </div>
 273          </div>
 274      </div>
 275  
 276      <?php
 277      if ( $edit_thumbnails_separately && $thumb && $sub_sizes ) {
 278          $thumb_img = wp_constrain_dimensions( $thumb['width'], $thumb['height'], 160, 120 );
 279          ?>
 280  
 281      <div class="imgedit-group imgedit-applyto">
 282          <div class="imgedit-group-top">
 283              <h2><?php _e( 'Thumbnail Settings' ); ?></h2>
 284              <button type="button" class="dashicons dashicons-editor-help imgedit-help-toggle" onclick="imageEdit.toggleHelp(this);" aria-expanded="false"><span class="screen-reader-text">
 285              <?php
 286              /* translators: Hidden accessibility text. */
 287              esc_html_e( 'Thumbnail Settings Help' );
 288              ?>
 289              </span></button>
 290              <div class="imgedit-help">
 291              <p><?php _e( 'You can edit the image while preserving the thumbnail. For example, you may wish to have a square thumbnail that displays just a section of the image.' ); ?></p>
 292              </div>
 293          </div>
 294          <div class="imgedit-thumbnail-preview-group">
 295              <figure class="imgedit-thumbnail-preview">
 296                  <img src="<?php echo $thumb['url']; ?>" width="<?php echo $thumb_img[0]; ?>" height="<?php echo $thumb_img[1]; ?>" class="imgedit-size-preview" alt="" draggable="false" />
 297                  <figcaption class="imgedit-thumbnail-preview-caption"><?php _e( 'Current thumbnail' ); ?></figcaption>
 298              </figure>
 299              <div id="imgedit-save-target-<?php echo $post_id; ?>" class="imgedit-save-target">
 300              <fieldset>
 301                  <legend><?php _e( 'Apply changes to:' ); ?></legend>
 302  
 303                  <span class="imgedit-label">
 304                      <input type="radio" id="imgedit-target-all" name="imgedit-target-<?php echo $post_id; ?>" value="all" checked="checked" />
 305                      <label for="imgedit-target-all"><?php _e( 'All image sizes' ); ?></label>
 306                  </span>
 307  
 308                  <span class="imgedit-label">
 309                      <input type="radio" id="imgedit-target-thumbnail" name="imgedit-target-<?php echo $post_id; ?>" value="thumbnail" />
 310                      <label for="imgedit-target-thumbnail"><?php _e( 'Thumbnail' ); ?></label>
 311                  </span>
 312  
 313                  <span class="imgedit-label">
 314                      <input type="radio" id="imgedit-target-nothumb" name="imgedit-target-<?php echo $post_id; ?>" value="nothumb" />
 315                      <label for="imgedit-target-nothumb"><?php _e( 'All sizes except thumbnail' ); ?></label>
 316                  </span>
 317  
 318                  </fieldset>
 319              </div>
 320          </div>
 321      </div>
 322      <?php } ?>
 323          </div>
 324      </div>
 325  
 326      </div>
 327  
 328      <div class="imgedit-wait" id="imgedit-wait-<?php echo $post_id; ?>"></div>
 329      <div class="hidden" id="imgedit-leaving-<?php echo $post_id; ?>"><?php _e( "There are unsaved changes that will be lost. 'OK' to continue, 'Cancel' to return to the Image Editor." ); ?></div>
 330      </div>
 331      <?php
 332  }
 333  
 334  /**
 335   * Streams image in WP_Image_Editor to browser.
 336   *
 337   * @since 2.9.0
 338   *
 339   * @param WP_Image_Editor $image         The image editor instance.
 340   * @param string          $mime_type     The mime type of the image.
 341   * @param int             $attachment_id The image's attachment post ID.
 342   * @return bool True on success, false on failure.
 343   */
 344  function wp_stream_image( $image, $mime_type, $attachment_id ) {
 345      if ( $image instanceof WP_Image_Editor ) {
 346  
 347          /**
 348           * Filters the WP_Image_Editor instance for the image to be streamed to the browser.
 349           *
 350           * @since 3.5.0
 351           *
 352           * @param WP_Image_Editor $image         The image editor instance.
 353           * @param int             $attachment_id The attachment post ID.
 354           */
 355          $image = apply_filters( 'image_editor_save_pre', $image, $attachment_id );
 356  
 357          if ( is_wp_error( $image->stream( $mime_type ) ) ) {
 358              return false;
 359          }
 360  
 361          return true;
 362      } else {
 363          /* translators: 1: $image, 2: WP_Image_Editor */
 364          _deprecated_argument( __FUNCTION__, '3.5.0', sprintf( __( '%1$s needs to be a %2$s object.' ), '$image', 'WP_Image_Editor' ) );
 365  
 366          /**
 367           * Filters the GD image resource to be streamed to the browser.
 368           *
 369           * @since 2.9.0
 370           * @deprecated 3.5.0 Use {@see 'image_editor_save_pre'} instead.
 371           *
 372           * @param resource|GdImage $image         Image resource to be streamed.
 373           * @param int              $attachment_id The attachment post ID.
 374           */
 375          $image = apply_filters_deprecated( 'image_save_pre', array( $image, $attachment_id ), '3.5.0', 'image_editor_save_pre' );
 376  
 377          switch ( $mime_type ) {
 378              case 'image/jpeg':
 379                  header( 'Content-Type: image/jpeg' );
 380                  return imagejpeg( $image, null, 90 );
 381              case 'image/png':
 382                  header( 'Content-Type: image/png' );
 383                  return imagepng( $image );
 384              case 'image/gif':
 385                  header( 'Content-Type: image/gif' );
 386                  return imagegif( $image );
 387              case 'image/webp':
 388                  if ( function_exists( 'imagewebp' ) ) {
 389                      header( 'Content-Type: image/webp' );
 390                      return imagewebp( $image, null, 90 );
 391                  }
 392                  return false;
 393              case 'image/avif':
 394                  if ( function_exists( 'imageavif' ) ) {
 395                      header( 'Content-Type: image/avif' );
 396                      return imageavif( $image, null, 90 );
 397                  }
 398                  return false;
 399              default:
 400                  return false;
 401          }
 402      }
 403  }
 404  
 405  /**
 406   * Saves image to file.
 407   *
 408   * @since 2.9.0
 409   * @since 3.5.0 The `$image` parameter expects a `WP_Image_Editor` instance.
 410   * @since 6.0.0 The `$filesize` value was added to the returned array.
 411   *
 412   * @param string          $filename  Name of the file to be saved.
 413   * @param WP_Image_Editor $image     The image editor instance.
 414   * @param string          $mime_type The mime type of the image.
 415   * @param int             $post_id   Attachment post ID.
 416   * @return array|WP_Error|bool {
 417   *     Array on success or WP_Error if the file failed to save.
 418   *     When called with a deprecated value for the `$image` parameter,
 419   *     i.e. a non-`WP_Image_Editor` image resource or `GdImage` instance,
 420   *     the function will return true on success, false on failure.
 421   *
 422   *     @type string $path      Path to the image file.
 423   *     @type string $file      Name of the image file.
 424   *     @type int    $width     Image width.
 425   *     @type int    $height    Image height.
 426   *     @type string $mime-type The mime type of the image.
 427   *     @type int    $filesize  File size of the image.
 428   * }
 429   */
 430  function wp_save_image_file( $filename, $image, $mime_type, $post_id ) {
 431      if ( $image instanceof WP_Image_Editor ) {
 432  
 433          /** This filter is documented in wp-admin/includes/image-edit.php */
 434          $image = apply_filters( 'image_editor_save_pre', $image, $post_id );
 435  
 436          /**
 437           * Filters whether to skip saving the image file.
 438           *
 439           * Returning a non-null value will short-circuit the save method,
 440           * returning that value instead.
 441           *
 442           * @since 3.5.0
 443           *
 444           * @param bool|null       $override  Value to return instead of saving. Default null.
 445           * @param string          $filename  Name of the file to be saved.
 446           * @param WP_Image_Editor $image     The image editor instance.
 447           * @param string          $mime_type The mime type of the image.
 448           * @param int             $post_id   Attachment post ID.
 449           */
 450          $saved = apply_filters( 'wp_save_image_editor_file', null, $filename, $image, $mime_type, $post_id );
 451  
 452          if ( null !== $saved ) {
 453              return $saved;
 454          }
 455  
 456          return $image->save( $filename, $mime_type );
 457      } else {
 458          /* translators: 1: $image, 2: WP_Image_Editor */
 459          _deprecated_argument( __FUNCTION__, '3.5.0', sprintf( __( '%1$s needs to be a %2$s object.' ), '$image', 'WP_Image_Editor' ) );
 460  
 461          /** This filter is documented in wp-admin/includes/image-edit.php */
 462          $image = apply_filters_deprecated( 'image_save_pre', array( $image, $post_id ), '3.5.0', 'image_editor_save_pre' );
 463  
 464          /**
 465           * Filters whether to skip saving the image file.
 466           *
 467           * Returning a non-null value will short-circuit the save method,
 468           * returning that value instead.
 469           *
 470           * @since 2.9.0
 471           * @deprecated 3.5.0 Use {@see 'wp_save_image_editor_file'} instead.
 472           *
 473           * @param bool|null        $override  Value to return instead of saving. Default null.
 474           * @param string           $filename  Name of the file to be saved.
 475           * @param resource|GdImage $image     Image resource or GdImage instance.
 476           * @param string           $mime_type The mime type of the image.
 477           * @param int              $post_id   Attachment post ID.
 478           */
 479          $saved = apply_filters_deprecated(
 480              'wp_save_image_file',
 481              array( null, $filename, $image, $mime_type, $post_id ),
 482              '3.5.0',
 483              'wp_save_image_editor_file'
 484          );
 485  
 486          if ( null !== $saved ) {
 487              return $saved;
 488          }
 489  
 490          switch ( $mime_type ) {
 491              case 'image/jpeg':
 492                  /** This filter is documented in wp-includes/class-wp-image-editor.php */
 493                  return imagejpeg( $image, $filename, apply_filters( 'jpeg_quality', 90, 'edit_image' ) );
 494              case 'image/png':
 495                  return imagepng( $image, $filename );
 496              case 'image/gif':
 497                  return imagegif( $image, $filename );
 498              case 'image/webp':
 499                  if ( function_exists( 'imagewebp' ) ) {
 500                      return imagewebp( $image, $filename );
 501                  }
 502                  return false;
 503              case 'image/avif':
 504                  if ( function_exists( 'imageavif' ) ) {
 505                      return imageavif( $image, $filename );
 506                  }
 507                  return false;
 508              default:
 509                  return false;
 510          }
 511      }
 512  }
 513  
 514  /**
 515   * Image preview ratio. Internal use only.
 516   *
 517   * @since 2.9.0
 518   *
 519   * @ignore
 520   * @param int $w Image width in pixels.
 521   * @param int $h Image height in pixels.
 522   * @return float|int Image preview ratio.
 523   */
 524  function _image_get_preview_ratio( $w, $h ) {
 525      $max = max( $w, $h );
 526      return $max > 600 ? ( 600 / $max ) : 1;
 527  }
 528  
 529  /**
 530   * Returns an image resource. Internal use only.
 531   *
 532   * @since 2.9.0
 533   * @deprecated 3.5.0 Use WP_Image_Editor::rotate()
 534   * @see WP_Image_Editor::rotate()
 535   *
 536   * @ignore
 537   * @param resource|GdImage  $img   Image resource.
 538   * @param float|int         $angle Image rotation angle, in degrees.
 539   * @return resource|GdImage|false GD image resource or GdImage instance, false otherwise.
 540   */
 541  function _rotate_image_resource( $img, $angle ) {
 542      _deprecated_function( __FUNCTION__, '3.5.0', 'WP_Image_Editor::rotate()' );
 543  
 544      if ( function_exists( 'imagerotate' ) ) {
 545          $rotated = imagerotate( $img, $angle, 0 );
 546  
 547          if ( is_gd_image( $rotated ) ) {
 548              imagedestroy( $img );
 549              $img = $rotated;
 550          }
 551      }
 552  
 553      return $img;
 554  }
 555  
 556  /**
 557   * Flips an image resource. Internal use only.
 558   *
 559   * @since 2.9.0
 560   * @deprecated 3.5.0 Use WP_Image_Editor::flip()
 561   * @see WP_Image_Editor::flip()
 562   *
 563   * @ignore
 564   * @param resource|GdImage $img  Image resource or GdImage instance.
 565   * @param bool             $horz Whether to flip horizontally.
 566   * @param bool             $vert Whether to flip vertically.
 567   * @return resource|GdImage (maybe) flipped image resource or GdImage instance.
 568   */
 569  function _flip_image_resource( $img, $horz, $vert ) {
 570      _deprecated_function( __FUNCTION__, '3.5.0', 'WP_Image_Editor::flip()' );
 571  
 572      $w   = imagesx( $img );
 573      $h   = imagesy( $img );
 574      $dst = wp_imagecreatetruecolor( $w, $h );
 575  
 576      if ( is_gd_image( $dst ) ) {
 577          $sx = $vert ? ( $w - 1 ) : 0;
 578          $sy = $horz ? ( $h - 1 ) : 0;
 579          $sw = $vert ? -$w : $w;
 580          $sh = $horz ? -$h : $h;
 581  
 582          if ( imagecopyresampled( $dst, $img, 0, 0, $sx, $sy, $w, $h, $sw, $sh ) ) {
 583              imagedestroy( $img );
 584              $img = $dst;
 585          }
 586      }
 587  
 588      return $img;
 589  }
 590  
 591  /**
 592   * Crops an image resource. Internal use only.
 593   *
 594   * @since 2.9.0
 595   *
 596   * @ignore
 597   * @param resource|GdImage $img Image resource or GdImage instance.
 598   * @param float            $x   Source point x-coordinate.
 599   * @param float            $y   Source point y-coordinate.
 600   * @param float            $w   Source width.
 601   * @param float            $h   Source height.
 602   * @return resource|GdImage (maybe) cropped image resource or GdImage instance.
 603   */
 604  function _crop_image_resource( $img, $x, $y, $w, $h ) {
 605      $dst = wp_imagecreatetruecolor( $w, $h );
 606  
 607      if ( is_gd_image( $dst ) ) {
 608          if ( imagecopy( $dst, $img, 0, 0, $x, $y, $w, $h ) ) {
 609              imagedestroy( $img );
 610              $img = $dst;
 611          }
 612      }
 613  
 614      return $img;
 615  }
 616  
 617  /**
 618   * Performs group of changes on Editor specified.
 619   *
 620   * @since 2.9.0
 621   *
 622   * @param WP_Image_Editor $image   WP_Image_Editor instance.
 623   * @param array           $changes Array of change operations.
 624   * @return WP_Image_Editor WP_Image_Editor instance with changes applied.
 625   */
 626  function image_edit_apply_changes( $image, $changes ) {
 627      if ( is_gd_image( $image ) ) {
 628          /* translators: 1: $image, 2: WP_Image_Editor */
 629          _deprecated_argument( __FUNCTION__, '3.5.0', sprintf( __( '%1$s needs to be a %2$s object.' ), '$image', 'WP_Image_Editor' ) );
 630      }
 631  
 632      if ( ! is_array( $changes ) ) {
 633          return $image;
 634      }
 635  
 636      // Expand change operations.
 637      foreach ( $changes as $key => $obj ) {
 638          if ( isset( $obj->r ) ) {
 639              $obj->type  = 'rotate';
 640              $obj->angle = $obj->r;
 641              unset( $obj->r );
 642          } elseif ( isset( $obj->f ) ) {
 643              $obj->type = 'flip';
 644              $obj->axis = $obj->f;
 645              unset( $obj->f );
 646          } elseif ( isset( $obj->c ) ) {
 647              $obj->type = 'crop';
 648              $obj->sel  = $obj->c;
 649              unset( $obj->c );
 650          }
 651  
 652          $changes[ $key ] = $obj;
 653      }
 654  
 655      // Combine operations.
 656      if ( count( $changes ) > 1 ) {
 657          $filtered = array( $changes[0] );
 658  
 659          for ( $i = 0, $j = 1, $c = count( $changes ); $j < $c; $j++ ) {
 660              $combined = false;
 661  
 662              if ( $filtered[ $i ]->type === $changes[ $j ]->type ) {
 663                  switch ( $filtered[ $i ]->type ) {
 664                      case 'rotate':
 665                          $filtered[ $i ]->angle += $changes[ $j ]->angle;
 666                          $combined               = true;
 667                          break;
 668                      case 'flip':
 669                          $filtered[ $i ]->axis ^= $changes[ $j ]->axis;
 670                          $combined              = true;
 671                          break;
 672                  }
 673              }
 674  
 675              if ( ! $combined ) {
 676                  $filtered[ ++$i ] = $changes[ $j ];
 677              }
 678          }
 679  
 680          $changes = $filtered;
 681          unset( $filtered );
 682      }
 683  
 684      // Image resource before applying the changes.
 685      if ( $image instanceof WP_Image_Editor ) {
 686  
 687          /**
 688           * Filters the WP_Image_Editor instance before applying changes to the image.
 689           *
 690           * @since 3.5.0
 691           *
 692           * @param WP_Image_Editor $image   WP_Image_Editor instance.
 693           * @param array           $changes Array of change operations.
 694           */
 695          $image = apply_filters( 'wp_image_editor_before_change', $image, $changes );
 696      } elseif ( is_gd_image( $image ) ) {
 697  
 698          /**
 699           * Filters the GD image resource before applying changes to the image.
 700           *
 701           * @since 2.9.0
 702           * @deprecated 3.5.0 Use {@see 'wp_image_editor_before_change'} instead.
 703           *
 704           * @param resource|GdImage $image   GD image resource or GdImage instance.
 705           * @param array            $changes Array of change operations.
 706           */
 707          $image = apply_filters_deprecated( 'image_edit_before_change', array( $image, $changes ), '3.5.0', 'wp_image_editor_before_change' );
 708      }
 709  
 710      foreach ( $changes as $operation ) {
 711          switch ( $operation->type ) {
 712              case 'rotate':
 713                  if ( 0 !== $operation->angle ) {
 714                      if ( $image instanceof WP_Image_Editor ) {
 715                          $image->rotate( $operation->angle );
 716                      } else {
 717                          $image = _rotate_image_resource( $image, $operation->angle );
 718                      }
 719                  }
 720                  break;
 721              case 'flip':
 722                  if ( 0 !== $operation->axis ) {
 723                      if ( $image instanceof WP_Image_Editor ) {
 724                          $image->flip( ( $operation->axis & 1 ) !== 0, ( $operation->axis & 2 ) !== 0 );
 725                      } else {
 726                          $image = _flip_image_resource( $image, ( $operation->axis & 1 ) !== 0, ( $operation->axis & 2 ) !== 0 );
 727                      }
 728                  }
 729                  break;
 730              case 'crop':
 731                  $sel = $operation->sel;
 732  
 733                  if ( $image instanceof WP_Image_Editor ) {
 734                      $size = $image->get_size();
 735                      $w    = $size['width'];
 736                      $h    = $size['height'];
 737  
 738                      $scale = isset( $sel->r ) ? $sel->r : 1 / _image_get_preview_ratio( $w, $h ); // Discard preview scaling.
 739                      $image->crop( (int) ( $sel->x * $scale ), (int) ( $sel->y * $scale ), (int) ( $sel->w * $scale ), (int) ( $sel->h * $scale ) );
 740                  } else {
 741                      $scale = isset( $sel->r ) ? $sel->r : 1 / _image_get_preview_ratio( imagesx( $image ), imagesy( $image ) ); // Discard preview scaling.
 742                      $image = _crop_image_resource( $image, $sel->x * $scale, $sel->y * $scale, $sel->w * $scale, $sel->h * $scale );
 743                  }
 744                  break;
 745          }
 746      }
 747  
 748      return $image;
 749  }
 750  
 751  
 752  /**
 753   * Streams image in post to browser, along with enqueued changes
 754   * in `$_REQUEST['history']`.
 755   *
 756   * @since 2.9.0
 757   *
 758   * @param int $post_id Attachment post ID.
 759   * @return bool True on success, false on failure.
 760   */
 761  function stream_preview_image( $post_id ) {
 762      $post = get_post( $post_id );
 763  
 764      wp_raise_memory_limit( 'admin' );
 765  
 766      $img = wp_get_image_editor( _load_image_to_edit_path( $post_id ) );
 767  
 768      if ( is_wp_error( $img ) ) {
 769          return false;
 770      }
 771  
 772      $changes = ! empty( $_REQUEST['history'] ) ? json_decode( wp_unslash( $_REQUEST['history'] ) ) : null;
 773      if ( $changes ) {
 774          $img = image_edit_apply_changes( $img, $changes );
 775      }
 776  
 777      // Scale the image.
 778      $size = $img->get_size();
 779      $w    = $size['width'];
 780      $h    = $size['height'];
 781  
 782      $ratio = _image_get_preview_ratio( $w, $h );
 783      $w2    = max( 1, $w * $ratio );
 784      $h2    = max( 1, $h * $ratio );
 785  
 786      if ( is_wp_error( $img->resize( $w2, $h2 ) ) ) {
 787          return false;
 788      }
 789  
 790      return wp_stream_image( $img, $post->post_mime_type, $post_id );
 791  }
 792  
 793  /**
 794   * Restores the metadata for a given attachment.
 795   *
 796   * @since 2.9.0
 797   *
 798   * @param int $post_id Attachment post ID.
 799   * @return stdClass Image restoration message object.
 800   */
 801  function wp_restore_image( $post_id ) {
 802      $meta             = wp_get_attachment_metadata( $post_id );
 803      $file             = get_attached_file( $post_id );
 804      $backup_sizes     = get_post_meta( $post_id, '_wp_attachment_backup_sizes', true );
 805      $old_backup_sizes = $backup_sizes;
 806      $restored         = false;
 807      $msg              = new stdClass();
 808  
 809      if ( ! is_array( $backup_sizes ) ) {
 810          $msg->error = __( 'Cannot load image metadata.' );
 811          return $msg;
 812      }
 813  
 814      $parts         = pathinfo( $file );
 815      $suffix        = time() . rand( 100, 999 );
 816      $default_sizes = get_intermediate_image_sizes();
 817  
 818      if ( isset( $backup_sizes['full-orig'] ) && is_array( $backup_sizes['full-orig'] ) ) {
 819          $data = $backup_sizes['full-orig'];
 820  
 821          if ( $parts['basename'] !== $data['file'] ) {
 822              if ( defined( 'IMAGE_EDIT_OVERWRITE' ) && IMAGE_EDIT_OVERWRITE ) {
 823                  // Delete only if it's an edited image.
 824                  if ( preg_match( '/-e[0-9]{13}\./', $parts['basename'] ) ) {
 825                      wp_delete_file( $file );
 826                  }
 827              } elseif ( isset( $meta['width'], $meta['height'] ) ) {
 828                  $backup_sizes[ "full-$suffix" ] = array(
 829                      'width'    => $meta['width'],
 830                      'height'   => $meta['height'],
 831                      'filesize' => $meta['filesize'],
 832                      'file'     => $parts['basename'],
 833                  );
 834              }
 835          }
 836  
 837          $restored_file = path_join( $parts['dirname'], $data['file'] );
 838          $restored      = update_attached_file( $post_id, $restored_file );
 839  
 840          $meta['file']   = _wp_relative_upload_path( $restored_file );
 841          $meta['width']  = $data['width'];
 842          $meta['height'] = $data['height'];
 843          if ( isset( $data['filesize'] ) ) {
 844              /*
 845               * Restore the original filesize if it was backed up.
 846               *
 847               * See https://core.trac.wordpress.org/ticket/59684.
 848               */
 849              $meta['filesize'] = $data['filesize'];
 850          }
 851      }
 852  
 853      foreach ( $default_sizes as $default_size ) {
 854          if ( isset( $backup_sizes[ "$default_size-orig" ] ) ) {
 855              $data = $backup_sizes[ "$default_size-orig" ];
 856  
 857              if ( isset( $meta['sizes'][ $default_size ] ) && $meta['sizes'][ $default_size ]['file'] !== $data['file'] ) {
 858                  if ( defined( 'IMAGE_EDIT_OVERWRITE' ) && IMAGE_EDIT_OVERWRITE ) {
 859                      // Delete only if it's an edited image.
 860                      if ( preg_match( '/-e[0-9]{13}-/', $meta['sizes'][ $default_size ]['file'] ) ) {
 861                          $delete_file = path_join( $parts['dirname'], $meta['sizes'][ $default_size ]['file'] );
 862                          wp_delete_file( $delete_file );
 863                      }
 864                  } else {
 865                      $backup_sizes[ "$default_size-{$suffix}" ] = $meta['sizes'][ $default_size ];
 866                  }
 867              }
 868  
 869              $meta['sizes'][ $default_size ] = $data;
 870          } else {
 871              unset( $meta['sizes'][ $default_size ] );
 872          }
 873      }
 874  
 875      if ( ! wp_update_attachment_metadata( $post_id, $meta )
 876          || ( $old_backup_sizes !== $backup_sizes && ! update_post_meta( $post_id, '_wp_attachment_backup_sizes', $backup_sizes ) )
 877      ) {
 878          $msg->error = __( 'Cannot save image metadata.' );
 879          return $msg;
 880      }
 881  
 882      if ( ! $restored ) {
 883          $msg->error = __( 'Image metadata is inconsistent.' );
 884      } else {
 885          $msg->msg = __( 'Image restored successfully.' );
 886  
 887          if ( defined( 'IMAGE_EDIT_OVERWRITE' ) && IMAGE_EDIT_OVERWRITE ) {
 888              delete_post_meta( $post_id, '_wp_attachment_backup_sizes' );
 889          }
 890      }
 891  
 892      return $msg;
 893  }
 894  
 895  /**
 896   * Saves image to post, along with enqueued changes
 897   * in `$_REQUEST['history']`.
 898   *
 899   * @since 2.9.0
 900   *
 901   * @param int $post_id Attachment post ID.
 902   * @return stdClass
 903   */
 904  function wp_save_image( $post_id ) {
 905      $_wp_additional_image_sizes = wp_get_additional_image_sizes();
 906  
 907      $return  = new stdClass();
 908      $success = false;
 909      $delete  = false;
 910      $scaled  = false;
 911      $nocrop  = false;
 912      $post    = get_post( $post_id );
 913  
 914      $img = wp_get_image_editor( _load_image_to_edit_path( $post_id, 'full' ) );
 915  
 916      if ( is_wp_error( $img ) ) {
 917          $return->error = esc_js( __( 'Unable to create new image.' ) );
 918          return $return;
 919      }
 920  
 921      $full_width  = ! empty( $_REQUEST['fwidth'] ) ? (int) $_REQUEST['fwidth'] : 0;
 922      $full_height = ! empty( $_REQUEST['fheight'] ) ? (int) $_REQUEST['fheight'] : 0;
 923      $target      = ! empty( $_REQUEST['target'] ) ? preg_replace( '/[^a-z0-9_-]+/i', '', $_REQUEST['target'] ) : '';
 924      $scale       = ! empty( $_REQUEST['do'] ) && 'scale' === $_REQUEST['do'];
 925  
 926      /** This filter is documented in wp-admin/includes/image-edit.php */
 927      $edit_thumbnails_separately = (bool) apply_filters( 'image_edit_thumbnails_separately', false );
 928  
 929      if ( $scale ) {
 930          $size            = $img->get_size();
 931          $original_width  = $size['width'];
 932          $original_height = $size['height'];
 933  
 934          if ( $full_width > $original_width || $full_height > $original_height ) {
 935              $return->error = esc_js( __( 'Images cannot be scaled to a size larger than the original.' ) );
 936              return $return;
 937          }
 938  
 939          if ( $full_width > 0 && $full_height > 0 ) {
 940              // Check if it has roughly the same w / h ratio.
 941              $diff = round( $original_width / $original_height, 2 ) - round( $full_width / $full_height, 2 );
 942              if ( -0.1 < $diff && $diff < 0.1 ) {
 943                  // Scale the full size image.
 944                  if ( $img->resize( $full_width, $full_height ) ) {
 945                      $scaled = true;
 946                  }
 947              }
 948  
 949              if ( ! $scaled ) {
 950                  $return->error = esc_js( __( 'Error while saving the scaled image. Please reload the page and try again.' ) );
 951                  return $return;
 952              }
 953          }
 954      } elseif ( ! empty( $_REQUEST['history'] ) ) {
 955          $changes = json_decode( wp_unslash( $_REQUEST['history'] ) );
 956          if ( $changes ) {
 957              $img = image_edit_apply_changes( $img, $changes );
 958          }
 959      } else {
 960          $return->error = esc_js( __( 'Nothing to save, the image has not changed.' ) );
 961          return $return;
 962      }
 963  
 964      $meta         = wp_get_attachment_metadata( $post_id );
 965      $backup_sizes = get_post_meta( $post->ID, '_wp_attachment_backup_sizes', true );
 966  
 967      if ( ! is_array( $meta ) ) {
 968          $return->error = esc_js( __( 'Image data does not exist. Please re-upload the image.' ) );
 969          return $return;
 970      }
 971  
 972      if ( ! is_array( $backup_sizes ) ) {
 973          $backup_sizes = array();
 974      }
 975  
 976      // Generate new filename.
 977      $path = get_attached_file( $post_id );
 978  
 979      $basename = pathinfo( $path, PATHINFO_BASENAME );
 980      $dirname  = pathinfo( $path, PATHINFO_DIRNAME );
 981      $ext      = pathinfo( $path, PATHINFO_EXTENSION );
 982      $filename = pathinfo( $path, PATHINFO_FILENAME );
 983      $suffix   = time() . rand( 100, 999 );
 984  
 985      if ( defined( 'IMAGE_EDIT_OVERWRITE' ) && IMAGE_EDIT_OVERWRITE
 986          && isset( $backup_sizes['full-orig'] ) && $backup_sizes['full-orig']['file'] !== $basename
 987      ) {
 988  
 989          if ( $edit_thumbnails_separately && 'thumbnail' === $target ) {
 990              $new_path = "{$dirname}/{$filename}-temp.{$ext}";
 991          } else {
 992              $new_path = $path;
 993          }
 994      } else {
 995          while ( true ) {
 996              $filename     = preg_replace( '/-e([0-9]+)$/', '', $filename );
 997              $filename    .= "-e{$suffix}";
 998              $new_filename = "{$filename}.{$ext}";
 999              $new_path     = "{$dirname}/$new_filename";
1000  
1001              if ( file_exists( $new_path ) ) {
1002                  ++$suffix;
1003              } else {
1004                  break;
1005              }
1006          }
1007      }
1008  
1009      $saved_image = wp_save_image_file( $new_path, $img, $post->post_mime_type, $post_id );
1010      // Save the full-size file, also needed to create sub-sizes.
1011      if ( ! $saved_image ) {
1012          $return->error = esc_js( __( 'Unable to save the image.' ) );
1013          return $return;
1014      }
1015  
1016      if ( 'nothumb' === $target || 'all' === $target || 'full' === $target || $scaled ) {
1017          $tag = false;
1018  
1019          if ( isset( $backup_sizes['full-orig'] ) ) {
1020              if ( ( ! defined( 'IMAGE_EDIT_OVERWRITE' ) || ! IMAGE_EDIT_OVERWRITE )
1021                  && $backup_sizes['full-orig']['file'] !== $basename
1022              ) {
1023                  $tag = "full-$suffix";
1024              }
1025          } else {
1026              $tag = 'full-orig';
1027          }
1028  
1029          if ( $tag ) {
1030              $backup_sizes[ $tag ] = array(
1031                  'width'    => $meta['width'],
1032                  'height'   => $meta['height'],
1033                  'filesize' => $meta['filesize'],
1034                  'file'     => $basename,
1035              );
1036          }
1037  
1038          $success = ( $path === $new_path ) || update_attached_file( $post_id, $new_path );
1039  
1040          $meta['file'] = _wp_relative_upload_path( $new_path );
1041  
1042          $size             = $img->get_size();
1043          $meta['width']    = $size['width'];
1044          $meta['height']   = $size['height'];
1045          $meta['filesize'] = $saved_image['filesize'];
1046  
1047          if ( $success && ( 'nothumb' === $target || 'all' === $target ) ) {
1048              $sizes = get_intermediate_image_sizes();
1049  
1050              if ( $edit_thumbnails_separately && 'nothumb' === $target ) {
1051                  $sizes = array_diff( $sizes, array( 'thumbnail' ) );
1052              }
1053          }
1054  
1055          $return->fw = $meta['width'];
1056          $return->fh = $meta['height'];
1057      } elseif ( $edit_thumbnails_separately && 'thumbnail' === $target ) {
1058          $sizes   = array( 'thumbnail' );
1059          $success = true;
1060          $delete  = true;
1061          $nocrop  = true;
1062      }
1063  
1064      /*
1065       * We need to remove any existing resized image files because
1066       * a new crop or rotate could generate different sizes (and hence, filenames),
1067       * keeping the new resized images from overwriting the existing image files.
1068       * https://core.trac.wordpress.org/ticket/32171
1069       */
1070      if ( defined( 'IMAGE_EDIT_OVERWRITE' ) && IMAGE_EDIT_OVERWRITE && ! empty( $meta['sizes'] ) ) {
1071          foreach ( $meta['sizes'] as $size ) {
1072              if ( ! empty( $size['file'] ) && preg_match( '/-e[0-9]{13}-/', $size['file'] ) ) {
1073                  $delete_file = path_join( $dirname, $size['file'] );
1074                  wp_delete_file( $delete_file );
1075              }
1076          }
1077      }
1078  
1079      if ( isset( $sizes ) ) {
1080          $_sizes = array();
1081  
1082          foreach ( $sizes as $size ) {
1083              $tag = false;
1084  
1085              if ( isset( $meta['sizes'][ $size ] ) ) {
1086                  if ( isset( $backup_sizes[ "$size-orig" ] ) ) {
1087                      if ( ( ! defined( 'IMAGE_EDIT_OVERWRITE' ) || ! IMAGE_EDIT_OVERWRITE )
1088                          && $backup_sizes[ "$size-orig" ]['file'] !== $meta['sizes'][ $size ]['file']
1089                      ) {
1090                          $tag = "$size-$suffix";
1091                      }
1092                  } else {
1093                      $tag = "$size-orig";
1094                  }
1095  
1096                  if ( $tag ) {
1097                      $backup_sizes[ $tag ] = $meta['sizes'][ $size ];
1098                  }
1099              }
1100  
1101              if ( isset( $_wp_additional_image_sizes[ $size ] ) ) {
1102                  $width  = (int) $_wp_additional_image_sizes[ $size ]['width'];
1103                  $height = (int) $_wp_additional_image_sizes[ $size ]['height'];
1104                  $crop   = ( $nocrop ) ? false : $_wp_additional_image_sizes[ $size ]['crop'];
1105              } else {
1106                  $height = get_option( "{$size}_size_h" );
1107                  $width  = get_option( "{$size}_size_w" );
1108                  $crop   = ( $nocrop ) ? false : get_option( "{$size}_crop" );
1109              }
1110  
1111              $_sizes[ $size ] = array(
1112                  'width'  => $width,
1113                  'height' => $height,
1114                  'crop'   => $crop,
1115              );
1116          }
1117  
1118          $meta['sizes'] = array_merge( $meta['sizes'], $img->multi_resize( $_sizes ) );
1119      }
1120  
1121      unset( $img );
1122  
1123      if ( $success ) {
1124          wp_update_attachment_metadata( $post_id, $meta );
1125          update_post_meta( $post_id, '_wp_attachment_backup_sizes', $backup_sizes );
1126  
1127          if ( 'thumbnail' === $target || 'all' === $target || 'full' === $target ) {
1128              // Check if it's an image edit from attachment edit screen.
1129              if ( ! empty( $_REQUEST['context'] ) && 'edit-attachment' === $_REQUEST['context'] ) {
1130                  $thumb_url = wp_get_attachment_image_src( $post_id, array( 900, 600 ), true );
1131  
1132                  $return->thumbnail = $thumb_url[0];
1133              } else {
1134                  $file_url = wp_get_attachment_url( $post_id );
1135  
1136                  if ( ! empty( $meta['sizes']['thumbnail'] ) ) {
1137                      $thumb             = $meta['sizes']['thumbnail'];
1138                      $return->thumbnail = path_join( dirname( $file_url ), $thumb['file'] );
1139                  } else {
1140                      $return->thumbnail = "$file_url?w=128&h=128";
1141                  }
1142              }
1143          }
1144      } else {
1145          $delete = true;
1146      }
1147  
1148      if ( $delete ) {
1149          wp_delete_file( $new_path );
1150      }
1151  
1152      $return->msg = esc_js( __( 'Image saved' ) );
1153  
1154      return $return;
1155  }


Generated : Thu Nov 21 08:20:01 2024 Cross-referenced by PHPXref