[ 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 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 esc_url( $thumb['url'] ); ?>" width="<?php echo esc_attr( $thumb_img[0] ); ?>" height="<?php echo esc_attr( $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              if ( PHP_VERSION_ID < 80000 ) { // imagedestroy() has no effect as of PHP 8.0.
 549                  imagedestroy( $img );
 550              }
 551  
 552              $img = $rotated;
 553          }
 554      }
 555  
 556      return $img;
 557  }
 558  
 559  /**
 560   * Flips an image resource. Internal use only.
 561   *
 562   * @since 2.9.0
 563   * @deprecated 3.5.0 Use WP_Image_Editor::flip()
 564   * @see WP_Image_Editor::flip()
 565   *
 566   * @ignore
 567   * @param resource|GdImage $img  Image resource or GdImage instance.
 568   * @param bool             $horz Whether to flip horizontally.
 569   * @param bool             $vert Whether to flip vertically.
 570   * @return resource|GdImage (maybe) flipped image resource or GdImage instance.
 571   */
 572  function _flip_image_resource( $img, $horz, $vert ) {
 573      _deprecated_function( __FUNCTION__, '3.5.0', 'WP_Image_Editor::flip()' );
 574  
 575      $w   = imagesx( $img );
 576      $h   = imagesy( $img );
 577      $dst = wp_imagecreatetruecolor( $w, $h );
 578  
 579      if ( is_gd_image( $dst ) ) {
 580          $sx = $vert ? ( $w - 1 ) : 0;
 581          $sy = $horz ? ( $h - 1 ) : 0;
 582          $sw = $vert ? -$w : $w;
 583          $sh = $horz ? -$h : $h;
 584  
 585          if ( imagecopyresampled( $dst, $img, 0, 0, $sx, $sy, $w, $h, $sw, $sh ) ) {
 586              if ( PHP_VERSION_ID < 80000 ) { // imagedestroy() has no effect as of PHP 8.0.
 587                  imagedestroy( $img );
 588              }
 589  
 590              $img = $dst;
 591          }
 592      }
 593  
 594      return $img;
 595  }
 596  
 597  /**
 598   * Crops an image resource. Internal use only.
 599   *
 600   * @since 2.9.0
 601   *
 602   * @ignore
 603   * @param resource|GdImage $img Image resource or GdImage instance.
 604   * @param float            $x   Source point x-coordinate.
 605   * @param float            $y   Source point y-coordinate.
 606   * @param float            $w   Source width.
 607   * @param float            $h   Source height.
 608   * @return resource|GdImage (maybe) cropped image resource or GdImage instance.
 609   */
 610  function _crop_image_resource( $img, $x, $y, $w, $h ) {
 611      $dst = wp_imagecreatetruecolor( $w, $h );
 612  
 613      if ( is_gd_image( $dst ) ) {
 614          if ( imagecopy( $dst, $img, 0, 0, $x, $y, $w, $h ) ) {
 615              if ( PHP_VERSION_ID < 80000 ) { // imagedestroy() has no effect as of PHP 8.0.
 616                  imagedestroy( $img );
 617              }
 618  
 619              $img = $dst;
 620          }
 621      }
 622  
 623      return $img;
 624  }
 625  
 626  /**
 627   * Performs group of changes on Editor specified.
 628   *
 629   * @since 2.9.0
 630   *
 631   * @param WP_Image_Editor $image   WP_Image_Editor instance.
 632   * @param array           $changes Array of change operations.
 633   * @return WP_Image_Editor WP_Image_Editor instance with changes applied.
 634   */
 635  function image_edit_apply_changes( $image, $changes ) {
 636      if ( is_gd_image( $image ) ) {
 637          /* translators: 1: $image, 2: WP_Image_Editor */
 638          _deprecated_argument( __FUNCTION__, '3.5.0', sprintf( __( '%1$s needs to be a %2$s object.' ), '$image', 'WP_Image_Editor' ) );
 639      }
 640  
 641      if ( ! is_array( $changes ) ) {
 642          return $image;
 643      }
 644  
 645      // Expand change operations.
 646      foreach ( $changes as $key => $obj ) {
 647          if ( isset( $obj->r ) ) {
 648              $obj->type  = 'rotate';
 649              $obj->angle = $obj->r;
 650              unset( $obj->r );
 651          } elseif ( isset( $obj->f ) ) {
 652              $obj->type = 'flip';
 653              $obj->axis = $obj->f;
 654              unset( $obj->f );
 655          } elseif ( isset( $obj->c ) ) {
 656              $obj->type = 'crop';
 657              $obj->sel  = $obj->c;
 658              unset( $obj->c );
 659          }
 660  
 661          $changes[ $key ] = $obj;
 662      }
 663  
 664      // Combine operations.
 665      if ( count( $changes ) > 1 ) {
 666          $filtered = array( $changes[0] );
 667  
 668          for ( $i = 0, $j = 1, $c = count( $changes ); $j < $c; $j++ ) {
 669              $combined = false;
 670  
 671              if ( $filtered[ $i ]->type === $changes[ $j ]->type ) {
 672                  switch ( $filtered[ $i ]->type ) {
 673                      case 'rotate':
 674                          $filtered[ $i ]->angle += $changes[ $j ]->angle;
 675                          $combined               = true;
 676                          break;
 677                      case 'flip':
 678                          $filtered[ $i ]->axis ^= $changes[ $j ]->axis;
 679                          $combined              = true;
 680                          break;
 681                  }
 682              }
 683  
 684              if ( ! $combined ) {
 685                  $filtered[ ++$i ] = $changes[ $j ];
 686              }
 687          }
 688  
 689          $changes = $filtered;
 690          unset( $filtered );
 691      }
 692  
 693      // Image resource before applying the changes.
 694      if ( $image instanceof WP_Image_Editor ) {
 695  
 696          /**
 697           * Filters the WP_Image_Editor instance before applying changes to the image.
 698           *
 699           * @since 3.5.0
 700           *
 701           * @param WP_Image_Editor $image   WP_Image_Editor instance.
 702           * @param array           $changes Array of change operations.
 703           */
 704          $image = apply_filters( 'wp_image_editor_before_change', $image, $changes );
 705      } elseif ( is_gd_image( $image ) ) {
 706  
 707          /**
 708           * Filters the GD image resource before applying changes to the image.
 709           *
 710           * @since 2.9.0
 711           * @deprecated 3.5.0 Use {@see 'wp_image_editor_before_change'} instead.
 712           *
 713           * @param resource|GdImage $image   GD image resource or GdImage instance.
 714           * @param array            $changes Array of change operations.
 715           */
 716          $image = apply_filters_deprecated( 'image_edit_before_change', array( $image, $changes ), '3.5.0', 'wp_image_editor_before_change' );
 717      }
 718  
 719      foreach ( $changes as $operation ) {
 720          switch ( $operation->type ) {
 721              case 'rotate':
 722                  if ( 0 !== $operation->angle ) {
 723                      if ( $image instanceof WP_Image_Editor ) {
 724                          $image->rotate( $operation->angle );
 725                      } else {
 726                          $image = _rotate_image_resource( $image, $operation->angle );
 727                      }
 728                  }
 729                  break;
 730              case 'flip':
 731                  if ( 0 !== $operation->axis ) {
 732                      if ( $image instanceof WP_Image_Editor ) {
 733                          $image->flip( ( $operation->axis & 1 ) !== 0, ( $operation->axis & 2 ) !== 0 );
 734                      } else {
 735                          $image = _flip_image_resource( $image, ( $operation->axis & 1 ) !== 0, ( $operation->axis & 2 ) !== 0 );
 736                      }
 737                  }
 738                  break;
 739              case 'crop':
 740                  $sel = $operation->sel;
 741  
 742                  if ( $image instanceof WP_Image_Editor ) {
 743                      $size = $image->get_size();
 744                      $w    = $size['width'];
 745                      $h    = $size['height'];
 746  
 747                      $scale = isset( $sel->r ) ? $sel->r : 1 / _image_get_preview_ratio( $w, $h ); // Discard preview scaling.
 748                      $image->crop( (int) ( $sel->x * $scale ), (int) ( $sel->y * $scale ), (int) ( $sel->w * $scale ), (int) ( $sel->h * $scale ) );
 749                  } else {
 750                      $scale = isset( $sel->r ) ? $sel->r : 1 / _image_get_preview_ratio( imagesx( $image ), imagesy( $image ) ); // Discard preview scaling.
 751                      $image = _crop_image_resource( $image, $sel->x * $scale, $sel->y * $scale, $sel->w * $scale, $sel->h * $scale );
 752                  }
 753                  break;
 754          }
 755      }
 756  
 757      return $image;
 758  }
 759  
 760  
 761  /**
 762   * Streams image in post to browser, along with enqueued changes
 763   * in `$_REQUEST['history']`.
 764   *
 765   * @since 2.9.0
 766   *
 767   * @param int $post_id Attachment post ID.
 768   * @return bool True on success, false on failure.
 769   */
 770  function stream_preview_image( $post_id ) {
 771      $post = get_post( $post_id );
 772  
 773      wp_raise_memory_limit( 'admin' );
 774  
 775      $img = wp_get_image_editor( _load_image_to_edit_path( $post_id ) );
 776  
 777      if ( is_wp_error( $img ) ) {
 778          return false;
 779      }
 780  
 781      $changes = ! empty( $_REQUEST['history'] ) ? json_decode( wp_unslash( $_REQUEST['history'] ) ) : null;
 782      if ( $changes ) {
 783          $img = image_edit_apply_changes( $img, $changes );
 784      }
 785  
 786      // Scale the image.
 787      $size = $img->get_size();
 788      $w    = $size['width'];
 789      $h    = $size['height'];
 790  
 791      $ratio = _image_get_preview_ratio( $w, $h );
 792      $w2    = max( 1, $w * $ratio );
 793      $h2    = max( 1, $h * $ratio );
 794  
 795      if ( is_wp_error( $img->resize( $w2, $h2 ) ) ) {
 796          return false;
 797      }
 798  
 799      return wp_stream_image( $img, $post->post_mime_type, $post_id );
 800  }
 801  
 802  /**
 803   * Restores the metadata for a given attachment.
 804   *
 805   * @since 2.9.0
 806   *
 807   * @param int $post_id Attachment post ID.
 808   * @return stdClass Image restoration message object.
 809   */
 810  function wp_restore_image( $post_id ) {
 811      $meta             = wp_get_attachment_metadata( $post_id );
 812      $file             = get_attached_file( $post_id );
 813      $backup_sizes     = get_post_meta( $post_id, '_wp_attachment_backup_sizes', true );
 814      $old_backup_sizes = $backup_sizes;
 815      $restored         = false;
 816      $msg              = new stdClass();
 817  
 818      if ( ! is_array( $backup_sizes ) ) {
 819          $msg->error = __( 'Cannot load image metadata.' );
 820          return $msg;
 821      }
 822  
 823      $parts         = pathinfo( $file );
 824      $suffix        = time() . rand( 100, 999 );
 825      $default_sizes = get_intermediate_image_sizes();
 826  
 827      if ( isset( $backup_sizes['full-orig'] ) && is_array( $backup_sizes['full-orig'] ) ) {
 828          $data = $backup_sizes['full-orig'];
 829  
 830          if ( $parts['basename'] !== $data['file'] ) {
 831              if ( defined( 'IMAGE_EDIT_OVERWRITE' ) && IMAGE_EDIT_OVERWRITE ) {
 832                  // Delete only if it's an edited image.
 833                  if ( preg_match( '/-e[0-9]{13}\./', $parts['basename'] ) ) {
 834                      wp_delete_file( $file );
 835                  }
 836              } elseif ( isset( $meta['width'], $meta['height'] ) ) {
 837                  $backup_sizes[ "full-$suffix" ] = array(
 838                      'width'    => $meta['width'],
 839                      'height'   => $meta['height'],
 840                      'filesize' => $meta['filesize'],
 841                      'file'     => $parts['basename'],
 842                  );
 843              }
 844          }
 845  
 846          $restored_file = path_join( $parts['dirname'], $data['file'] );
 847          $restored      = update_attached_file( $post_id, $restored_file );
 848  
 849          $meta['file']   = _wp_relative_upload_path( $restored_file );
 850          $meta['width']  = $data['width'];
 851          $meta['height'] = $data['height'];
 852          if ( isset( $data['filesize'] ) ) {
 853              /*
 854               * Restore the original filesize if it was backed up.
 855               *
 856               * See https://core.trac.wordpress.org/ticket/59684.
 857               */
 858              $meta['filesize'] = $data['filesize'];
 859          }
 860      }
 861  
 862      foreach ( $default_sizes as $default_size ) {
 863          if ( isset( $backup_sizes[ "$default_size-orig" ] ) ) {
 864              $data = $backup_sizes[ "$default_size-orig" ];
 865  
 866              if ( isset( $meta['sizes'][ $default_size ] ) && $meta['sizes'][ $default_size ]['file'] !== $data['file'] ) {
 867                  if ( defined( 'IMAGE_EDIT_OVERWRITE' ) && IMAGE_EDIT_OVERWRITE ) {
 868                      // Delete only if it's an edited image.
 869                      if ( preg_match( '/-e[0-9]{13}-/', $meta['sizes'][ $default_size ]['file'] ) ) {
 870                          $delete_file = path_join( $parts['dirname'], $meta['sizes'][ $default_size ]['file'] );
 871                          wp_delete_file( $delete_file );
 872                      }
 873                  } else {
 874                      $backup_sizes[ "$default_size-{$suffix}" ] = $meta['sizes'][ $default_size ];
 875                  }
 876              }
 877  
 878              $meta['sizes'][ $default_size ] = $data;
 879          } else {
 880              unset( $meta['sizes'][ $default_size ] );
 881          }
 882      }
 883  
 884      if ( ! wp_update_attachment_metadata( $post_id, $meta )
 885          || ( $old_backup_sizes !== $backup_sizes && ! update_post_meta( $post_id, '_wp_attachment_backup_sizes', $backup_sizes ) )
 886      ) {
 887          $msg->error = __( 'Cannot save image metadata.' );
 888          return $msg;
 889      }
 890  
 891      if ( ! $restored ) {
 892          $msg->error = __( 'Image metadata is inconsistent.' );
 893      } else {
 894          $msg->msg = __( 'Image restored successfully.' );
 895  
 896          if ( defined( 'IMAGE_EDIT_OVERWRITE' ) && IMAGE_EDIT_OVERWRITE ) {
 897              delete_post_meta( $post_id, '_wp_attachment_backup_sizes' );
 898          }
 899      }
 900  
 901      return $msg;
 902  }
 903  
 904  /**
 905   * Saves image to post, along with enqueued changes
 906   * in `$_REQUEST['history']`.
 907   *
 908   * @since 2.9.0
 909   *
 910   * @param int $post_id Attachment post ID.
 911   * @return stdClass
 912   */
 913  function wp_save_image( $post_id ) {
 914      $_wp_additional_image_sizes = wp_get_additional_image_sizes();
 915  
 916      $return  = new stdClass();
 917      $success = false;
 918      $delete  = false;
 919      $scaled  = false;
 920      $nocrop  = false;
 921      $post    = get_post( $post_id );
 922  
 923      $img = wp_get_image_editor( _load_image_to_edit_path( $post_id, 'full' ) );
 924  
 925      if ( is_wp_error( $img ) ) {
 926          $return->error = esc_js( __( 'Unable to create new image.' ) );
 927          return $return;
 928      }
 929  
 930      $full_width  = ! empty( $_REQUEST['fwidth'] ) ? (int) $_REQUEST['fwidth'] : 0;
 931      $full_height = ! empty( $_REQUEST['fheight'] ) ? (int) $_REQUEST['fheight'] : 0;
 932      $target      = ! empty( $_REQUEST['target'] ) ? preg_replace( '/[^a-z0-9_-]+/i', '', $_REQUEST['target'] ) : '';
 933      $scale       = ! empty( $_REQUEST['do'] ) && 'scale' === $_REQUEST['do'];
 934  
 935      /** This filter is documented in wp-admin/includes/image-edit.php */
 936      $edit_thumbnails_separately = (bool) apply_filters( 'image_edit_thumbnails_separately', false );
 937  
 938      if ( $scale ) {
 939          $size            = $img->get_size();
 940          $original_width  = $size['width'];
 941          $original_height = $size['height'];
 942  
 943          if ( $full_width > $original_width || $full_height > $original_height ) {
 944              $return->error = esc_js( __( 'Images cannot be scaled to a size larger than the original.' ) );
 945              return $return;
 946          }
 947  
 948          if ( $full_width > 0 && $full_height > 0 ) {
 949              // Check if it has roughly the same w / h ratio.
 950              $diff = round( $original_width / $original_height, 2 ) - round( $full_width / $full_height, 2 );
 951              if ( -0.1 < $diff && $diff < 0.1 ) {
 952                  // Scale the full size image.
 953                  if ( $img->resize( $full_width, $full_height ) ) {
 954                      $scaled = true;
 955                  }
 956              }
 957  
 958              if ( ! $scaled ) {
 959                  $return->error = esc_js( __( 'Error while saving the scaled image. Please reload the page and try again.' ) );
 960                  return $return;
 961              }
 962          }
 963      } elseif ( ! empty( $_REQUEST['history'] ) ) {
 964          $changes = json_decode( wp_unslash( $_REQUEST['history'] ) );
 965          if ( $changes ) {
 966              $img = image_edit_apply_changes( $img, $changes );
 967          }
 968      } else {
 969          $return->error = esc_js( __( 'Nothing to save, the image has not changed.' ) );
 970          return $return;
 971      }
 972  
 973      $meta         = wp_get_attachment_metadata( $post_id );
 974      $backup_sizes = get_post_meta( $post->ID, '_wp_attachment_backup_sizes', true );
 975  
 976      if ( ! is_array( $meta ) ) {
 977          $return->error = esc_js( __( 'Image data does not exist. Please re-upload the image.' ) );
 978          return $return;
 979      }
 980  
 981      if ( ! is_array( $backup_sizes ) ) {
 982          $backup_sizes = array();
 983      }
 984  
 985      // Generate new filename.
 986      $path = get_attached_file( $post_id );
 987  
 988      $basename = pathinfo( $path, PATHINFO_BASENAME );
 989      $dirname  = pathinfo( $path, PATHINFO_DIRNAME );
 990      $ext      = pathinfo( $path, PATHINFO_EXTENSION );
 991      $filename = pathinfo( $path, PATHINFO_FILENAME );
 992      $suffix   = time() . rand( 100, 999 );
 993  
 994      if ( defined( 'IMAGE_EDIT_OVERWRITE' ) && IMAGE_EDIT_OVERWRITE
 995          && isset( $backup_sizes['full-orig'] ) && $backup_sizes['full-orig']['file'] !== $basename
 996      ) {
 997  
 998          if ( $edit_thumbnails_separately && 'thumbnail' === $target ) {
 999              $new_path = "{$dirname}/{$filename}-temp.{$ext}";
1000          } else {
1001              $new_path = $path;
1002          }
1003      } else {
1004          while ( true ) {
1005              $filename     = preg_replace( '/-e([0-9]+)$/', '', $filename );
1006              $filename    .= "-e{$suffix}";
1007              $new_filename = "{$filename}.{$ext}";
1008              $new_path     = "{$dirname}/$new_filename";
1009  
1010              if ( file_exists( $new_path ) ) {
1011                  ++$suffix;
1012              } else {
1013                  break;
1014              }
1015          }
1016      }
1017  
1018      $saved_image = wp_save_image_file( $new_path, $img, $post->post_mime_type, $post_id );
1019      // Save the full-size file, also needed to create sub-sizes.
1020      if ( ! $saved_image ) {
1021          $return->error = esc_js( __( 'Unable to save the image.' ) );
1022          return $return;
1023      }
1024  
1025      if ( 'nothumb' === $target || 'all' === $target || 'full' === $target || $scaled ) {
1026          $tag = false;
1027  
1028          if ( isset( $backup_sizes['full-orig'] ) ) {
1029              if ( ( ! defined( 'IMAGE_EDIT_OVERWRITE' ) || ! IMAGE_EDIT_OVERWRITE )
1030                  && $backup_sizes['full-orig']['file'] !== $basename
1031              ) {
1032                  $tag = "full-$suffix";
1033              }
1034          } else {
1035              $tag = 'full-orig';
1036          }
1037  
1038          if ( $tag ) {
1039              $backup_sizes[ $tag ] = array(
1040                  'width'    => $meta['width'],
1041                  'height'   => $meta['height'],
1042                  'filesize' => $meta['filesize'],
1043                  'file'     => $basename,
1044              );
1045          }
1046  
1047          $success = ( $path === $new_path ) || update_attached_file( $post_id, $new_path );
1048  
1049          $meta['file'] = _wp_relative_upload_path( $new_path );
1050  
1051          $size             = $img->get_size();
1052          $meta['width']    = $size['width'];
1053          $meta['height']   = $size['height'];
1054          $meta['filesize'] = $saved_image['filesize'];
1055  
1056          if ( $success && ( 'nothumb' === $target || 'all' === $target ) ) {
1057              $sizes = get_intermediate_image_sizes();
1058  
1059              if ( $edit_thumbnails_separately && 'nothumb' === $target ) {
1060                  $sizes = array_diff( $sizes, array( 'thumbnail' ) );
1061              }
1062          }
1063  
1064          $return->fw = $meta['width'];
1065          $return->fh = $meta['height'];
1066      } elseif ( $edit_thumbnails_separately && 'thumbnail' === $target ) {
1067          $sizes   = array( 'thumbnail' );
1068          $success = true;
1069          $delete  = true;
1070          $nocrop  = true;
1071      }
1072  
1073      /*
1074       * We need to remove any existing resized image files because
1075       * a new crop or rotate could generate different sizes (and hence, filenames),
1076       * keeping the new resized images from overwriting the existing image files.
1077       * https://core.trac.wordpress.org/ticket/32171
1078       */
1079      if ( defined( 'IMAGE_EDIT_OVERWRITE' ) && IMAGE_EDIT_OVERWRITE && ! empty( $meta['sizes'] ) ) {
1080          foreach ( $meta['sizes'] as $size ) {
1081              if ( ! empty( $size['file'] ) && preg_match( '/-e[0-9]{13}-/', $size['file'] ) ) {
1082                  $delete_file = path_join( $dirname, $size['file'] );
1083                  wp_delete_file( $delete_file );
1084              }
1085          }
1086      }
1087  
1088      if ( isset( $sizes ) ) {
1089          $_sizes = array();
1090  
1091          foreach ( $sizes as $size ) {
1092              $tag = false;
1093  
1094              if ( isset( $meta['sizes'][ $size ] ) ) {
1095                  if ( isset( $backup_sizes[ "$size-orig" ] ) ) {
1096                      if ( ( ! defined( 'IMAGE_EDIT_OVERWRITE' ) || ! IMAGE_EDIT_OVERWRITE )
1097                          && $backup_sizes[ "$size-orig" ]['file'] !== $meta['sizes'][ $size ]['file']
1098                      ) {
1099                          $tag = "$size-$suffix";
1100                      }
1101                  } else {
1102                      $tag = "$size-orig";
1103                  }
1104  
1105                  if ( $tag ) {
1106                      $backup_sizes[ $tag ] = $meta['sizes'][ $size ];
1107                  }
1108              }
1109  
1110              if ( isset( $_wp_additional_image_sizes[ $size ] ) ) {
1111                  $width  = (int) $_wp_additional_image_sizes[ $size ]['width'];
1112                  $height = (int) $_wp_additional_image_sizes[ $size ]['height'];
1113                  $crop   = ( $nocrop ) ? false : $_wp_additional_image_sizes[ $size ]['crop'];
1114              } else {
1115                  $height = get_option( "{$size}_size_h" );
1116                  $width  = get_option( "{$size}_size_w" );
1117                  $crop   = ( $nocrop ) ? false : get_option( "{$size}_crop" );
1118              }
1119  
1120              $_sizes[ $size ] = array(
1121                  'width'  => $width,
1122                  'height' => $height,
1123                  'crop'   => $crop,
1124              );
1125          }
1126  
1127          $meta['sizes'] = array_merge( $meta['sizes'], $img->multi_resize( $_sizes ) );
1128      }
1129  
1130      unset( $img );
1131  
1132      if ( $success ) {
1133          wp_update_attachment_metadata( $post_id, $meta );
1134          update_post_meta( $post_id, '_wp_attachment_backup_sizes', $backup_sizes );
1135  
1136          if ( 'thumbnail' === $target || 'all' === $target || 'full' === $target ) {
1137              // Check if it's an image edit from attachment edit screen.
1138              if ( ! empty( $_REQUEST['context'] ) && 'edit-attachment' === $_REQUEST['context'] ) {
1139                  $thumb_url = wp_get_attachment_image_src( $post_id, array( 900, 600 ), true );
1140  
1141                  $return->thumbnail = $thumb_url[0];
1142              } else {
1143                  $file_url = wp_get_attachment_url( $post_id );
1144  
1145                  if ( ! empty( $meta['sizes']['thumbnail'] ) ) {
1146                      $thumb             = $meta['sizes']['thumbnail'];
1147                      $return->thumbnail = path_join( dirname( $file_url ), $thumb['file'] );
1148                  } else {
1149                      $return->thumbnail = "$file_url?w=128&h=128";
1150                  }
1151              }
1152          }
1153      } else {
1154          $delete = true;
1155      }
1156  
1157      if ( $delete ) {
1158          wp_delete_file( $new_path );
1159      }
1160  
1161      $return->msg = esc_js( __( 'Image saved' ) );
1162  
1163      return $return;
1164  }


Generated : Tue Sep 9 08:20:04 2025 Cross-referenced by PHPXref