WordPress 4.5
[autoinstalls/wordpress.git] / wp-admin / includes / image-edit.php
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  * @param int         $post_id Post ID.
13  * @param bool|object $msg     Optional. Message to display for image editor updates or errors.
14  *                             Default false.
15  */
16 function wp_image_editor($post_id, $msg = false) {
17         $nonce = wp_create_nonce("image_editor-$post_id");
18         $meta = wp_get_attachment_metadata($post_id);
19         $thumb = image_get_intermediate_size($post_id, 'thumbnail');
20         $sub_sizes = isset($meta['sizes']) && is_array($meta['sizes']);
21         $note = '';
22
23         if ( isset( $meta['width'], $meta['height'] ) )
24                 $big = max( $meta['width'], $meta['height'] );
25         else
26                 die( __('Image data does not exist. Please re-upload the image.') );
27
28         $sizer = $big > 400 ? 400 / $big : 1;
29
30         $backup_sizes = get_post_meta( $post_id, '_wp_attachment_backup_sizes', true );
31         $can_restore = false;
32         if ( ! empty( $backup_sizes ) && isset( $backup_sizes['full-orig'], $meta['file'] ) )
33                 $can_restore = $backup_sizes['full-orig']['file'] != basename( $meta['file'] );
34
35         if ( $msg ) {
36                 if ( isset($msg->error) )
37                         $note = "<div class='error'><p>$msg->error</p></div>";
38                 elseif ( isset($msg->msg) )
39                         $note = "<div class='updated'><p>$msg->msg</p></div>";
40         }
41
42         ?>
43         <div class="imgedit-wrap wp-clearfix">
44         <div id="imgedit-panel-<?php echo $post_id; ?>">
45
46         <div class="imgedit-settings">
47         <div class="imgedit-group">
48         <div class="imgedit-group-top">
49                 <h2><?php _e( 'Scale Image' ); ?></h2>
50                 <button type="button" class="dashicons dashicons-editor-help imgedit-help-toggle" onclick="imageEdit.toggleHelp(this);return false;" aria-expanded="false"><span class="screen-reader-text"><?php esc_html_e( 'Scale Image Help' ); ?></span></button>
51                 <div class="imgedit-help">
52                 <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>
53                 </div>
54                 <?php if ( isset( $meta['width'], $meta['height'] ) ): ?>
55                 <p><?php printf( __('Original dimensions %s'), $meta['width'] . ' &times; ' . $meta['height'] ); ?></p>
56                 <?php endif ?>
57                 <div class="imgedit-submit">
58
59                 <fieldset class="imgedit-scale">
60                 <legend><?php _e( 'New dimensions:' ); ?></legend>
61                 <div class="nowrap">
62                 <label><span class="screen-reader-text"><?php _e( 'scale width' ); ?></span>
63                 <input type="text" id="imgedit-scale-width-<?php echo $post_id; ?>" onkeyup="imageEdit.scaleChanged(<?php echo $post_id; ?>, 1)" onblur="imageEdit.scaleChanged(<?php echo $post_id; ?>, 1)" value="<?php echo isset( $meta['width'] ) ? $meta['width'] : 0; ?>" />
64                 </label>
65                 <span class="imgedit-separator">&times;</span>
66                 <label><span class="screen-reader-text"><?php _e( 'scale height' ); ?></span>
67                 <input type="text" id="imgedit-scale-height-<?php echo $post_id; ?>" onkeyup="imageEdit.scaleChanged(<?php echo $post_id; ?>, 0)" onblur="imageEdit.scaleChanged(<?php echo $post_id; ?>, 0)" value="<?php echo isset( $meta['height'] ) ? $meta['height'] : 0; ?>" />
68                 </label>
69                 <span class="imgedit-scale-warn" id="imgedit-scale-warn-<?php echo $post_id; ?>">!</span>
70                 <input id="imgedit-scale-button" type="button" onclick="imageEdit.action(<?php echo "$post_id, '$nonce'"; ?>, 'scale')" class="button button-primary" value="<?php esc_attr_e( 'Scale' ); ?>" />
71                 </div>
72                 </fieldset>
73
74                 </div>
75         </div>
76         </div>
77
78 <?php if ( $can_restore ) { ?>
79
80         <div class="imgedit-group">
81         <div class="imgedit-group-top">
82                 <h2><button type="button" onclick="imageEdit.toggleHelp(this);" class="button-link"><?php _e( 'Restore Original Image' ); ?> <span class="dashicons dashicons-arrow-down imgedit-help-toggle"></span></button></h2>
83                 <div class="imgedit-help">
84                 <p><?php _e('Discard any changes and restore the original image.');
85
86                 if ( !defined('IMAGE_EDIT_OVERWRITE') || !IMAGE_EDIT_OVERWRITE )
87                         echo ' '.__('Previously edited copies of the image will not be deleted.');
88
89                 ?></p>
90                 <div class="imgedit-submit">
91                 <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; ?> />
92                 </div>
93                 </div>
94         </div>
95         </div>
96
97 <?php } ?>
98
99         <div class="imgedit-group">
100         <div class="imgedit-group-top">
101                 <h2><?php _e( 'Image Crop' ); ?></h2>
102                 <button type="button" class="dashicons dashicons-editor-help imgedit-help-toggle" onclick="imageEdit.toggleHelp(this);return false;" aria-expanded="false"><span class="screen-reader-text"><?php esc_html_e( 'Image Crop Help' ); ?></span></button>
103
104                 <div class="imgedit-help">
105                 <p><?php _e('To crop the image, click on it and drag to make your selection.'); ?></p>
106
107                 <p><strong><?php _e('Crop Aspect Ratio'); ?></strong><br />
108                 <?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>
109
110                 <p><strong><?php _e('Crop Selection'); ?></strong><br />
111                 <?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>
112                 </div>
113         </div>
114
115         <fieldset class="imgedit-crop-ratio">
116                 <legend><?php _e( 'Aspect ratio:' ); ?></legend>
117                 <div class="nowrap">
118                 <label><span class="screen-reader-text"><?php _e( 'crop ratio width' ); ?></span>
119                 <input type="text" id="imgedit-crop-width-<?php echo $post_id; ?>" onkeyup="imageEdit.setRatioSelection(<?php echo $post_id; ?>, 0, this)" />
120                 </label>
121                 <span class="imgedit-separator">:</span>
122                 <label><span class="screen-reader-text"><?php _e( 'crop ratio height' ); ?></span>
123                 <input type="text" id="imgedit-crop-height-<?php echo $post_id; ?>" onkeyup="imageEdit.setRatioSelection(<?php echo $post_id; ?>, 1, this)" />
124                 </label>
125                 </div>
126         </fieldset>
127
128         <fieldset id="imgedit-crop-sel-<?php echo $post_id; ?>" class="imgedit-crop-sel">
129                 <legend><?php _e( 'Selection:' ); ?></legend>
130                 <div class="nowrap">
131                 <label><span class="screen-reader-text"><?php _e( 'selection width' ); ?></span>
132                 <input type="text" id="imgedit-sel-width-<?php echo $post_id; ?>" onkeyup="imageEdit.setNumSelection(<?php echo $post_id; ?>)" />
133                 </label>
134                 <span class="imgedit-separator">&times;</span>
135                 <label><span class="screen-reader-text"><?php _e( 'selection height' ); ?></span>
136                 <input type="text" id="imgedit-sel-height-<?php echo $post_id; ?>" onkeyup="imageEdit.setNumSelection(<?php echo $post_id; ?>)" />
137                 </label>
138                 </div>
139         </fieldset>
140
141         </div>
142
143         <?php if ( $thumb && $sub_sizes ) {
144                 $thumb_img = wp_constrain_dimensions( $thumb['width'], $thumb['height'], 160, 120 );
145         ?>
146
147         <div class="imgedit-group imgedit-applyto">
148         <div class="imgedit-group-top">
149                 <h2><?php _e( 'Thumbnail Settings' ); ?></h2>
150                 <button type="button" class="dashicons dashicons-editor-help imgedit-help-toggle" onclick="imageEdit.toggleHelp(this);return false;" aria-expanded="false"><span class="screen-reader-text"><?php esc_html_e( 'Thumbnail Settings Help' ); ?></span></button>
151                 <p class="imgedit-help"><?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>
152         </div>
153
154         <figure class="imgedit-thumbnail-preview">
155                 <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" />
156                 <figcaption class="imgedit-thumbnail-preview-caption"><?php _e( 'Current thumbnail' ); ?></figcaption>
157         </figure>
158
159         <div id="imgedit-save-target-<?php echo $post_id; ?>" class="imgedit-save-target">
160         <fieldset>
161                 <legend><strong><?php _e( 'Apply changes to:' ); ?></strong></legend>
162
163                 <label class="imgedit-label">
164                 <input type="radio" name="imgedit-target-<?php echo $post_id; ?>" value="all" checked="checked" />
165                 <?php _e('All image sizes'); ?></label>
166
167                 <label class="imgedit-label">
168                 <input type="radio" name="imgedit-target-<?php echo $post_id; ?>" value="thumbnail" />
169                 <?php _e('Thumbnail'); ?></label>
170
171                 <label class="imgedit-label">
172                 <input type="radio" name="imgedit-target-<?php echo $post_id; ?>" value="nothumb" />
173                 <?php _e('All sizes except thumbnail'); ?></label>
174         </fieldset>
175         </div>
176         </div>
177
178         <?php } ?>
179
180         </div>
181
182         <div class="imgedit-panel-content wp-clearfix">
183                 <?php echo $note; ?>
184                 <div class="imgedit-menu wp-clearfix">
185                         <button type="button" onclick="imageEdit.crop(<?php echo "$post_id, '$nonce'"; ?>, this)" class="imgedit-crop button disabled" disabled><span class="screen-reader-text"><?php esc_html_e( 'Crop' ); ?></span></button><?php
186
187                 // On some setups GD library does not provide imagerotate() - Ticket #11536
188                 if ( wp_image_editor_supports( array( 'mime_type' => get_post_mime_type( $post_id ), 'methods' => array( 'rotate' ) ) ) ) {
189                         $note_no_rotate = '';
190         ?>
191                         <button type="button" class="imgedit-rleft button" onclick="imageEdit.rotate( 90, <?php echo "$post_id, '$nonce'"; ?>, this)"><span class="screen-reader-text"><?php esc_html_e( 'Rotate counter-clockwise' ); ?></span></button>
192                         <button type="button" class="imgedit-rright button" onclick="imageEdit.rotate(-90, <?php echo "$post_id, '$nonce'"; ?>, this)"><span class="screen-reader-text"><?php esc_html_e( 'Rotate clockwise' ); ?></span></button>
193         <?php } else {
194                         $note_no_rotate = '<p class="note-no-rotate"><em>' . __( 'Image rotation is not supported by your web host.' ) . '</em></p>';
195         ?>
196                         <button type="button" class="imgedit-rleft button disabled" disabled></button>
197                         <button type="button" class="imgedit-rright button disabled" disabled></button>
198         <?php } ?>
199
200                         <button type="button" onclick="imageEdit.flip(1, <?php echo "$post_id, '$nonce'"; ?>, this)" class="imgedit-flipv button"><span class="screen-reader-text"><?php esc_html_e( 'Flip vertically' ); ?></span></button>
201                         <button type="button" onclick="imageEdit.flip(2, <?php echo "$post_id, '$nonce'"; ?>, this)" class="imgedit-fliph button"><span class="screen-reader-text"><?php esc_html_e( 'Flip horizontally' ); ?></span></button>
202
203                         <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><span class="screen-reader-text"><?php esc_html_e( 'Undo' ); ?></span></button>
204                         <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><span class="screen-reader-text"><?php esc_html_e( 'Redo' ); ?></span></button>
205                         <?php echo $note_no_rotate; ?>
206                 </div>
207
208                 <input type="hidden" id="imgedit-sizer-<?php echo $post_id; ?>" value="<?php echo $sizer; ?>" />
209                 <input type="hidden" id="imgedit-history-<?php echo $post_id; ?>" value="" />
210                 <input type="hidden" id="imgedit-undone-<?php echo $post_id; ?>" value="0" />
211                 <input type="hidden" id="imgedit-selection-<?php echo $post_id; ?>" value="" />
212                 <input type="hidden" id="imgedit-x-<?php echo $post_id; ?>" value="<?php echo isset( $meta['width'] ) ? $meta['width'] : 0; ?>" />
213                 <input type="hidden" id="imgedit-y-<?php echo $post_id; ?>" value="<?php echo isset( $meta['height'] ) ? $meta['height'] : 0; ?>" />
214
215                 <div id="imgedit-crop-<?php echo $post_id; ?>" class="imgedit-crop-wrap">
216                 <img id="image-preview-<?php echo $post_id; ?>" onload="imageEdit.imgLoaded('<?php echo $post_id; ?>')" src="<?php echo admin_url( 'admin-ajax.php', 'relative' ); ?>?action=imgedit-preview&amp;_ajax_nonce=<?php echo $nonce; ?>&amp;postid=<?php echo $post_id; ?>&amp;rand=<?php echo rand(1, 99999); ?>" alt="" />
217                 </div>
218
219                 <div class="imgedit-submit">
220                         <input type="button" onclick="imageEdit.close(<?php echo $post_id; ?>, 1)" class="button imgedit-cancel-btn" value="<?php esc_attr_e( 'Cancel' ); ?>" />
221                         <input type="button" onclick="imageEdit.save(<?php echo "$post_id, '$nonce'"; ?>)" disabled="disabled" class="button button-primary imgedit-submit-btn" value="<?php esc_attr_e( 'Save' ); ?>" />
222                 </div>
223         </div>
224
225         </div>
226         <div class="imgedit-wait" id="imgedit-wait-<?php echo $post_id; ?>"></div>
227         <script type="text/javascript">jQuery( function() { imageEdit.init(<?php echo $post_id; ?>); });</script>
228         <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>
229         </div>
230 <?php
231 }
232
233 /**
234  * Streams image in WP_Image_Editor to browser.
235  * Provided for backcompat reasons
236  *
237  * @param WP_Image_Editor $image
238  * @param string $mime_type
239  * @param int $post_id
240  * @return bool
241  */
242 function wp_stream_image( $image, $mime_type, $post_id ) {
243         if ( $image instanceof WP_Image_Editor ) {
244
245                 /**
246                  * Filter the WP_Image_Editor instance for the image to be streamed to the browser.
247                  *
248                  * @since 3.5.0
249                  *
250                  * @param WP_Image_Editor $image   WP_Image_Editor instance.
251                  * @param int             $post_id Post ID.
252                  */
253                 $image = apply_filters( 'image_editor_save_pre', $image, $post_id );
254
255                 if ( is_wp_error( $image->stream( $mime_type ) ) )
256                         return false;
257
258                 return true;
259         } else {
260                 _deprecated_argument( __FUNCTION__, '3.5', __( '$image needs to be an WP_Image_Editor object' ) );
261
262                 /**
263                  * Filter the GD image resource to be streamed to the browser.
264                  *
265                  * @since 2.9.0
266                  * @deprecated 3.5.0 Use image_editor_save_pre instead.
267                  *
268                  * @param resource $image   Image resource to be streamed.
269                  * @param int      $post_id Post ID.
270                  */
271                 $image = apply_filters( 'image_save_pre', $image, $post_id );
272
273                 switch ( $mime_type ) {
274                         case 'image/jpeg':
275                                 header( 'Content-Type: image/jpeg' );
276                                 return imagejpeg( $image, null, 90 );
277                         case 'image/png':
278                                 header( 'Content-Type: image/png' );
279                                 return imagepng( $image );
280                         case 'image/gif':
281                                 header( 'Content-Type: image/gif' );
282                                 return imagegif( $image );
283                         default:
284                                 return false;
285                 }
286         }
287 }
288
289 /**
290  * Saves Image to File
291  *
292  * @param string $filename
293  * @param WP_Image_Editor $image
294  * @param string $mime_type
295  * @param int $post_id
296  * @return bool
297  */
298 function wp_save_image_file( $filename, $image, $mime_type, $post_id ) {
299         if ( $image instanceof WP_Image_Editor ) {
300
301                 /** This filter is documented in wp-admin/includes/image-edit.php */
302                 $image = apply_filters( 'image_editor_save_pre', $image, $post_id );
303
304                 /**
305                  * Filter whether to skip saving the image file.
306                  *
307                  * Returning a non-null value will short-circuit the save method,
308                  * returning that value instead.
309                  *
310                  * @since 3.5.0
311                  *
312                  * @param mixed           $override  Value to return instead of saving. Default null.
313                  * @param string          $filename  Name of the file to be saved.
314                  * @param WP_Image_Editor $image     WP_Image_Editor instance.
315                  * @param string          $mime_type Image mime type.
316                  * @param int             $post_id   Post ID.
317                  */
318                 $saved = apply_filters( 'wp_save_image_editor_file', null, $filename, $image, $mime_type, $post_id );
319
320                 if ( null !== $saved )
321                         return $saved;
322
323                 return $image->save( $filename, $mime_type );
324         } else {
325                 _deprecated_argument( __FUNCTION__, '3.5', __( '$image needs to be an WP_Image_Editor object' ) );
326
327                 /** This filter is documented in wp-admin/includes/image-edit.php */
328                 $image = apply_filters( 'image_save_pre', $image, $post_id );
329
330                 /**
331                  * Filter whether to skip saving the image file.
332                  *
333                  * Returning a non-null value will short-circuit the save method,
334                  * returning that value instead.
335                  *
336                  * @since 2.9.0
337                  * @deprecated 3.5.0 Use wp_save_image_editor_file instead.
338                  *
339                  * @param mixed           $override  Value to return instead of saving. Default null.
340                  * @param string          $filename  Name of the file to be saved.
341                  * @param WP_Image_Editor $image     WP_Image_Editor instance.
342                  * @param string          $mime_type Image mime type.
343                  * @param int             $post_id   Post ID.
344                  */
345                 $saved = apply_filters( 'wp_save_image_file', null, $filename, $image, $mime_type, $post_id );
346
347                 if ( null !== $saved )
348                         return $saved;
349
350                 switch ( $mime_type ) {
351                         case 'image/jpeg':
352
353                                 /** This filter is documented in wp-includes/class-wp-image-editor.php */
354                                 return imagejpeg( $image, $filename, apply_filters( 'jpeg_quality', 90, 'edit_image' ) );
355                         case 'image/png':
356                                 return imagepng( $image, $filename );
357                         case 'image/gif':
358                                 return imagegif( $image, $filename );
359                         default:
360                                 return false;
361                 }
362         }
363 }
364
365 /**
366  * Image preview ratio. Internal use only.
367  *
368  * @since 2.9.0
369  *
370  * @ignore
371  * @param int $w Image width in pixels.
372  * @param int $h Image height in pixels.
373  * @return float|int Image preview ratio.
374  */
375 function _image_get_preview_ratio($w, $h) {
376         $max = max($w, $h);
377         return $max > 400 ? (400 / $max) : 1;
378 }
379
380 /**
381  * Returns an image resource. Internal use only.
382  *
383  * @since 2.9.0
384  *
385  * @ignore
386  * @param resource  $img   Image resource.
387  * @param float|int $angle Image rotation angle, in degrees.
388  * @return resource|false GD image resource, false otherwise.
389  */
390 function _rotate_image_resource($img, $angle) {
391         _deprecated_function( __FUNCTION__, '3.5', __( 'Use WP_Image_Editor::rotate' ) );
392         if ( function_exists('imagerotate') ) {
393                 $rotated = imagerotate($img, $angle, 0);
394                 if ( is_resource($rotated) ) {
395                         imagedestroy($img);
396                         $img = $rotated;
397                 }
398         }
399         return $img;
400 }
401
402 /**
403  * Flips an image resource. Internal use only.
404  *
405  * @since 2.9.0
406  *
407  * @ignore
408  * @param resource $img  Image resource.
409  * @param bool     $horz Whether to flip horizontally.
410  * @param bool     $vert Whether to flip vertically.
411  * @return resource (maybe) flipped image resource.
412  */
413 function _flip_image_resource($img, $horz, $vert) {
414         _deprecated_function( __FUNCTION__, '3.5', __( 'Use WP_Image_Editor::flip' ) );
415         $w = imagesx($img);
416         $h = imagesy($img);
417         $dst = wp_imagecreatetruecolor($w, $h);
418         if ( is_resource($dst) ) {
419                 $sx = $vert ? ($w - 1) : 0;
420                 $sy = $horz ? ($h - 1) : 0;
421                 $sw = $vert ? -$w : $w;
422                 $sh = $horz ? -$h : $h;
423
424                 if ( imagecopyresampled($dst, $img, 0, 0, $sx, $sy, $w, $h, $sw, $sh) ) {
425                         imagedestroy($img);
426                         $img = $dst;
427                 }
428         }
429         return $img;
430 }
431
432 /**
433  * Crops an image resource. Internal use only.
434  *
435  * @since 2.9.0
436  *
437  * @ignore
438  * @param resource $img Image resource.
439  * @param float    $x   Source point x-coordinate.
440  * @param float    $y   Source point y-cooredinate.
441  * @param float    $w   Source width.
442  * @param float    $h   Source height.
443  * @return resource (maybe) cropped image resource.
444  */
445 function _crop_image_resource($img, $x, $y, $w, $h) {
446         $dst = wp_imagecreatetruecolor($w, $h);
447         if ( is_resource($dst) ) {
448                 if ( imagecopy($dst, $img, 0, 0, $x, $y, $w, $h) ) {
449                         imagedestroy($img);
450                         $img = $dst;
451                 }
452         }
453         return $img;
454 }
455
456 /**
457  * Performs group of changes on Editor specified.
458  *
459  * @since 2.9.0
460  *
461  * @param WP_Image_Editor $image   {@see WP_Image_Editor} instance.
462  * @param array           $changes Array of change operations.
463  * @return WP_Image_Editor {@see WP_Image_Editor} instance with changes applied.
464  */
465 function image_edit_apply_changes( $image, $changes ) {
466         if ( is_resource( $image ) )
467                 _deprecated_argument( __FUNCTION__, '3.5', __( '$image needs to be an WP_Image_Editor object' ) );
468
469         if ( !is_array($changes) )
470                 return $image;
471
472         // Expand change operations.
473         foreach ( $changes as $key => $obj ) {
474                 if ( isset($obj->r) ) {
475                         $obj->type = 'rotate';
476                         $obj->angle = $obj->r;
477                         unset($obj->r);
478                 } elseif ( isset($obj->f) ) {
479                         $obj->type = 'flip';
480                         $obj->axis = $obj->f;
481                         unset($obj->f);
482                 } elseif ( isset($obj->c) ) {
483                         $obj->type = 'crop';
484                         $obj->sel = $obj->c;
485                         unset($obj->c);
486                 }
487                 $changes[$key] = $obj;
488         }
489
490         // Combine operations.
491         if ( count($changes) > 1 ) {
492                 $filtered = array($changes[0]);
493                 for ( $i = 0, $j = 1, $c = count( $changes ); $j < $c; $j++ ) {
494                         $combined = false;
495                         if ( $filtered[$i]->type == $changes[$j]->type ) {
496                                 switch ( $filtered[$i]->type ) {
497                                         case 'rotate':
498                                                 $filtered[$i]->angle += $changes[$j]->angle;
499                                                 $combined = true;
500                                                 break;
501                                         case 'flip':
502                                                 $filtered[$i]->axis ^= $changes[$j]->axis;
503                                                 $combined = true;
504                                                 break;
505                                 }
506                         }
507                         if ( !$combined )
508                                 $filtered[++$i] = $changes[$j];
509                 }
510                 $changes = $filtered;
511                 unset($filtered);
512         }
513
514         // Image resource before applying the changes.
515         if ( $image instanceof WP_Image_Editor ) {
516
517                 /**
518                  * Filter the WP_Image_Editor instance before applying changes to the image.
519                  *
520                  * @since 3.5.0
521                  *
522                  * @param WP_Image_Editor $image   WP_Image_Editor instance.
523                  * @param array           $changes Array of change operations.
524                  */
525                 $image = apply_filters( 'wp_image_editor_before_change', $image, $changes );
526         } elseif ( is_resource( $image ) ) {
527
528                 /**
529                  * Filter the GD image resource before applying changes to the image.
530                  *
531                  * @since 2.9.0
532                  * @deprecated 3.5.0 Use wp_image_editor_before_change instead.
533                  *
534                  * @param resource $image   GD image resource.
535                  * @param array    $changes Array of change operations.
536                  */
537                 $image = apply_filters( 'image_edit_before_change', $image, $changes );
538         }
539
540         foreach ( $changes as $operation ) {
541                 switch ( $operation->type ) {
542                         case 'rotate':
543                                 if ( $operation->angle != 0 ) {
544                                         if ( $image instanceof WP_Image_Editor )
545                                                 $image->rotate( $operation->angle );
546                                         else
547                                                 $image = _rotate_image_resource( $image, $operation->angle );
548                                 }
549                                 break;
550                         case 'flip':
551                                 if ( $operation->axis != 0 )
552                                         if ( $image instanceof WP_Image_Editor )
553                                                 $image->flip( ($operation->axis & 1) != 0, ($operation->axis & 2) != 0 );
554                                         else
555                                                 $image = _flip_image_resource( $image, ( $operation->axis & 1 ) != 0, ( $operation->axis & 2 ) != 0 );
556                                 break;
557                         case 'crop':
558                                 $sel = $operation->sel;
559
560                                 if ( $image instanceof WP_Image_Editor ) {
561                                         $size = $image->get_size();
562                                         $w = $size['width'];
563                                         $h = $size['height'];
564
565                                         $scale = 1 / _image_get_preview_ratio( $w, $h ); // discard preview scaling
566                                         $image->crop( $sel->x * $scale, $sel->y * $scale, $sel->w * $scale, $sel->h * $scale );
567                                 } else {
568                                         $scale = 1 / _image_get_preview_ratio( imagesx( $image ), imagesy( $image ) ); // discard preview scaling
569                                         $image = _crop_image_resource( $image, $sel->x * $scale, $sel->y * $scale, $sel->w * $scale, $sel->h * $scale );
570                                 }
571                                 break;
572                 }
573         }
574
575         return $image;
576 }
577
578
579 /**
580  * Streams image in post to browser, along with enqueued changes
581  * in $_REQUEST['history']
582  *
583  * @param int $post_id
584  * @return bool
585  */
586 function stream_preview_image( $post_id ) {
587         $post = get_post( $post_id );
588
589         /** This filter is documented in wp-admin/admin.php */
590         @ini_set( 'memory_limit', apply_filters( 'admin_memory_limit', WP_MAX_MEMORY_LIMIT ) );
591
592         $img = wp_get_image_editor( _load_image_to_edit_path( $post_id ) );
593
594         if ( is_wp_error( $img ) ) {
595                 return false;
596         }
597
598         $changes = !empty($_REQUEST['history']) ? json_decode( wp_unslash($_REQUEST['history']) ) : null;
599         if ( $changes )
600                 $img = image_edit_apply_changes( $img, $changes );
601
602         // Scale the image.
603         $size = $img->get_size();
604         $w = $size['width'];
605         $h = $size['height'];
606
607         $ratio = _image_get_preview_ratio( $w, $h );
608         $w2 = max ( 1, $w * $ratio );
609         $h2 = max ( 1, $h * $ratio );
610
611         if ( is_wp_error( $img->resize( $w2, $h2 ) ) )
612                 return false;
613
614         return wp_stream_image( $img, $post->post_mime_type, $post_id );
615 }
616
617 /**
618  * Restores the metadata for a given attachment.
619  *
620  * @since 2.9.0
621  *
622  * @param int $post_id Attachment post ID.
623  * @return stdClass Image restoration message object.
624  */
625 function wp_restore_image($post_id) {
626         $meta = wp_get_attachment_metadata($post_id);
627         $file = get_attached_file($post_id);
628         $backup_sizes = $old_backup_sizes = get_post_meta( $post_id, '_wp_attachment_backup_sizes', true );
629         $restored = false;
630         $msg = new stdClass;
631
632         if ( !is_array($backup_sizes) ) {
633                 $msg->error = __('Cannot load image metadata.');
634                 return $msg;
635         }
636
637         $parts = pathinfo($file);
638         $suffix = time() . rand(100, 999);
639         $default_sizes = get_intermediate_image_sizes();
640
641         if ( isset($backup_sizes['full-orig']) && is_array($backup_sizes['full-orig']) ) {
642                 $data = $backup_sizes['full-orig'];
643
644                 if ( $parts['basename'] != $data['file'] ) {
645                         if ( defined('IMAGE_EDIT_OVERWRITE') && IMAGE_EDIT_OVERWRITE ) {
646
647                                 // Delete only if it's an edited image.
648                                 if ( preg_match('/-e[0-9]{13}\./', $parts['basename']) ) {
649                                         wp_delete_file( $file );
650                                 }
651                         } elseif ( isset( $meta['width'], $meta['height'] ) ) {
652                                 $backup_sizes["full-$suffix"] = array('width' => $meta['width'], 'height' => $meta['height'], 'file' => $parts['basename']);
653                         }
654                 }
655
656                 $restored_file = path_join($parts['dirname'], $data['file']);
657                 $restored = update_attached_file($post_id, $restored_file);
658
659                 $meta['file'] = _wp_relative_upload_path( $restored_file );
660                 $meta['width'] = $data['width'];
661                 $meta['height'] = $data['height'];
662         }
663
664         foreach ( $default_sizes as $default_size ) {
665                 if ( isset($backup_sizes["$default_size-orig"]) ) {
666                         $data = $backup_sizes["$default_size-orig"];
667                         if ( isset($meta['sizes'][$default_size]) && $meta['sizes'][$default_size]['file'] != $data['file'] ) {
668                                 if ( defined('IMAGE_EDIT_OVERWRITE') && IMAGE_EDIT_OVERWRITE ) {
669
670                                         // Delete only if it's an edited image.
671                                         if ( preg_match('/-e[0-9]{13}-/', $meta['sizes'][$default_size]['file']) ) {
672                                                 $delete_file = path_join( $parts['dirname'], $meta['sizes'][$default_size]['file'] );
673                                                 wp_delete_file( $delete_file );
674                                         }
675                                 } else {
676                                         $backup_sizes["$default_size-{$suffix}"] = $meta['sizes'][$default_size];
677                                 }
678                         }
679
680                         $meta['sizes'][$default_size] = $data;
681                 } else {
682                         unset($meta['sizes'][$default_size]);
683                 }
684         }
685
686         if ( ! wp_update_attachment_metadata( $post_id, $meta ) ||
687                 ( $old_backup_sizes !== $backup_sizes && ! update_post_meta( $post_id, '_wp_attachment_backup_sizes', $backup_sizes ) ) ) {
688
689                 $msg->error = __('Cannot save image metadata.');
690                 return $msg;
691         }
692
693         if ( !$restored )
694                 $msg->error = __('Image metadata is inconsistent.');
695         else
696                 $msg->msg = __('Image restored successfully.');
697
698         return $msg;
699 }
700
701 /**
702  * Saves image to post along with enqueued changes
703  * in $_REQUEST['history']
704  *
705  * @global array $_wp_additional_image_sizes
706  *
707  * @param int $post_id
708  * @return \stdClass
709  */
710 function wp_save_image( $post_id ) {
711         global $_wp_additional_image_sizes;
712
713         $return = new stdClass;
714         $success = $delete = $scaled = $nocrop = false;
715         $post = get_post( $post_id );
716
717         $img = wp_get_image_editor( _load_image_to_edit_path( $post_id, 'full' ) );
718         if ( is_wp_error( $img ) ) {
719                 $return->error = esc_js( __('Unable to create new image.') );
720                 return $return;
721         }
722
723         $fwidth = !empty($_REQUEST['fwidth']) ? intval($_REQUEST['fwidth']) : 0;
724         $fheight = !empty($_REQUEST['fheight']) ? intval($_REQUEST['fheight']) : 0;
725         $target = !empty($_REQUEST['target']) ? preg_replace('/[^a-z0-9_-]+/i', '', $_REQUEST['target']) : '';
726         $scale = !empty($_REQUEST['do']) && 'scale' == $_REQUEST['do'];
727
728         if ( $scale && $fwidth > 0 && $fheight > 0 ) {
729                 $size = $img->get_size();
730                 $sX = $size['width'];
731                 $sY = $size['height'];
732
733                 // Check if it has roughly the same w / h ratio.
734                 $diff = round($sX / $sY, 2) - round($fwidth / $fheight, 2);
735                 if ( -0.1 < $diff && $diff < 0.1 ) {
736                         // Scale the full size image.
737                         if ( $img->resize( $fwidth, $fheight ) )
738                                 $scaled = true;
739                 }
740
741                 if ( !$scaled ) {
742                         $return->error = esc_js( __('Error while saving the scaled image. Please reload the page and try again.') );
743                         return $return;
744                 }
745         } elseif ( !empty($_REQUEST['history']) ) {
746                 $changes = json_decode( wp_unslash($_REQUEST['history']) );
747                 if ( $changes )
748                         $img = image_edit_apply_changes($img, $changes);
749         } else {
750                 $return->error = esc_js( __('Nothing to save, the image has not changed.') );
751                 return $return;
752         }
753
754         $meta = wp_get_attachment_metadata($post_id);
755         $backup_sizes = get_post_meta( $post->ID, '_wp_attachment_backup_sizes', true );
756
757         if ( !is_array($meta) ) {
758                 $return->error = esc_js( __('Image data does not exist. Please re-upload the image.') );
759                 return $return;
760         }
761
762         if ( !is_array($backup_sizes) )
763                 $backup_sizes = array();
764
765         // Generate new filename.
766         $path = get_attached_file($post_id);
767         $path_parts = pathinfo( $path );
768         $filename = $path_parts['filename'];
769         $suffix = time() . rand(100, 999);
770
771         if ( defined('IMAGE_EDIT_OVERWRITE') && IMAGE_EDIT_OVERWRITE &&
772                 isset($backup_sizes['full-orig']) && $backup_sizes['full-orig']['file'] != $path_parts['basename'] ) {
773
774                 if ( 'thumbnail' == $target )
775                         $new_path = "{$path_parts['dirname']}/{$filename}-temp.{$path_parts['extension']}";
776                 else
777                         $new_path = $path;
778         } else {
779                 while( true ) {
780                         $filename = preg_replace( '/-e([0-9]+)$/', '', $filename );
781                         $filename .= "-e{$suffix}";
782                         $new_filename = "{$filename}.{$path_parts['extension']}";
783                         $new_path = "{$path_parts['dirname']}/$new_filename";
784                         if ( file_exists($new_path) )
785                                 $suffix++;
786                         else
787                                 break;
788                 }
789         }
790
791         // Save the full-size file, also needed to create sub-sizes.
792         if ( !wp_save_image_file($new_path, $img, $post->post_mime_type, $post_id) ) {
793                 $return->error = esc_js( __('Unable to save the image.') );
794                 return $return;
795         }
796
797         if ( 'nothumb' == $target || 'all' == $target || 'full' == $target || $scaled ) {
798                 $tag = false;
799                 if ( isset($backup_sizes['full-orig']) ) {
800                         if ( ( !defined('IMAGE_EDIT_OVERWRITE') || !IMAGE_EDIT_OVERWRITE ) && $backup_sizes['full-orig']['file'] != $path_parts['basename'] )
801                                 $tag = "full-$suffix";
802                 } else {
803                         $tag = 'full-orig';
804                 }
805
806                 if ( $tag )
807                         $backup_sizes[$tag] = array('width' => $meta['width'], 'height' => $meta['height'], 'file' => $path_parts['basename']);
808
809                 $success = ( $path === $new_path ) || update_attached_file( $post_id, $new_path );
810
811                 $meta['file'] = _wp_relative_upload_path( $new_path );
812
813                 $size = $img->get_size();
814                 $meta['width'] = $size['width'];
815                 $meta['height'] = $size['height'];
816
817                 if ( $success && ('nothumb' == $target || 'all' == $target) ) {
818                         $sizes = get_intermediate_image_sizes();
819                         if ( 'nothumb' == $target )
820                                 $sizes = array_diff( $sizes, array('thumbnail') );
821                 }
822
823                 $return->fw = $meta['width'];
824                 $return->fh = $meta['height'];
825         } elseif ( 'thumbnail' == $target ) {
826                 $sizes = array( 'thumbnail' );
827                 $success = $delete = $nocrop = true;
828         }
829
830         if ( isset( $sizes ) ) {
831                 $_sizes = array();
832
833                 foreach ( $sizes as $size ) {
834                         $tag = false;
835                         if ( isset( $meta['sizes'][$size] ) ) {
836                                 if ( isset($backup_sizes["$size-orig"]) ) {
837                                         if ( ( !defined('IMAGE_EDIT_OVERWRITE') || !IMAGE_EDIT_OVERWRITE ) && $backup_sizes["$size-orig"]['file'] != $meta['sizes'][$size]['file'] )
838                                                 $tag = "$size-$suffix";
839                                 } else {
840                                         $tag = "$size-orig";
841                                 }
842
843                                 if ( $tag )
844                                         $backup_sizes[$tag] = $meta['sizes'][$size];
845                         }
846
847                         if ( isset( $_wp_additional_image_sizes[ $size ] ) ) {
848                                 $width  = intval( $_wp_additional_image_sizes[ $size ]['width'] );
849                                 $height = intval( $_wp_additional_image_sizes[ $size ]['height'] );
850                                 $crop   = ( $nocrop ) ? false : $_wp_additional_image_sizes[ $size ]['crop'];
851                         } else {
852                                 $height = get_option( "{$size}_size_h" );
853                                 $width  = get_option( "{$size}_size_w" );
854                                 $crop   = ( $nocrop ) ? false : get_option( "{$size}_crop" );
855                         }
856
857                         $_sizes[ $size ] = array( 'width' => $width, 'height' => $height, 'crop' => $crop );
858                 }
859
860                 $meta['sizes'] = array_merge( $meta['sizes'], $img->multi_resize( $_sizes ) );
861         }
862
863         unset( $img );
864
865         if ( $success ) {
866                 wp_update_attachment_metadata( $post_id, $meta );
867                 update_post_meta( $post_id, '_wp_attachment_backup_sizes', $backup_sizes);
868
869                 if ( $target == 'thumbnail' || $target == 'all' || $target == 'full' ) {
870                         // Check if it's an image edit from attachment edit screen
871                         if ( ! empty( $_REQUEST['context'] ) && 'edit-attachment' == $_REQUEST['context'] ) {
872                                 $thumb_url = wp_get_attachment_image_src( $post_id, array( 900, 600 ), true );
873                                 $return->thumbnail = $thumb_url[0];
874                         } else {
875                                 $file_url = wp_get_attachment_url($post_id);
876                                 if ( ! empty( $meta['sizes']['thumbnail'] ) && $thumb = $meta['sizes']['thumbnail'] ) {
877                                         $return->thumbnail = path_join( dirname($file_url), $thumb['file'] );
878                                 } else {
879                                         $return->thumbnail = "$file_url?w=128&h=128";
880                                 }
881                         }
882                 }
883         } else {
884                 $delete = true;
885         }
886
887         if ( $delete ) {
888                 wp_delete_file( $new_path );
889         }
890
891         $return->msg = esc_js( __('Image saved') );
892         return $return;
893 }