Make WordPress Core


Ignore:
Timestamp:
11/30/2017 11:09:33 PM (7 years ago)
Author:
pento
Message:

Code is Poetry.
WordPress' code just... wasn't.
This is now dealt with.

Props jrf, pento, netweb, GaryJ, jdgrimes, westonruter, Greg Sherwood from PHPCS, and everyone who's ever contributed to WPCS and PHPCS.
Fixes #41057.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/wp-admin/includes/image-edit.php

    r41288 r42343  
    1414 *                             Default false.
    1515 */
    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'] ) )
     16function 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'] ) ) {
    2424        $big = max( $meta['width'], $meta['height'] );
    25     else
    26         die( __('Image data does not exist. Please re-upload the image.') );
     25    } else {
     26        die( __( 'Image data does not exist. Please re-upload the image.' ) );
     27    }
    2728
    2829    $sizer = $big > 400 ? 400 / $big : 1;
    2930
    3031    $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'] ) )
     32    $can_restore  = false;
     33    if ( ! empty( $backup_sizes ) && isset( $backup_sizes['full-orig'], $meta['file'] ) ) {
    3334        $can_restore = $backup_sizes['full-orig']['file'] != basename( $meta['file'] );
     35    }
    3436
    3537    if ( $msg ) {
    36         if ( isset($msg->error) )
     38        if ( isset( $msg->error ) ) {
    3739            $note = "<div class='error'><p>$msg->error</p></div>";
    38         elseif ( isset($msg->msg) )
     40        } elseif ( isset( $msg->msg ) ) {
    3941            $note = "<div class='updated'><p>$msg->msg</p></div>";
     42        }
    4043    }
    4144
     
    5053        <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>
    5154        <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>
     55        <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>
    5356        </div>
    54         <?php if ( isset( $meta['width'], $meta['height'] ) ): ?>
    55         <p><?php printf( __('Original dimensions %s'), $meta['width'] . ' &times; ' . $meta['height'] ); ?></p>
     57        <?php if ( isset( $meta['width'], $meta['height'] ) ) : ?>
     58        <p><?php printf( __( 'Original dimensions %s' ), $meta['width'] . ' &times; ' . $meta['height'] ); ?></p>
    5659        <?php endif ?>
    5760        <div class="imgedit-submit">
     
    6972        <span class="imgedit-scale-warn" id="imgedit-scale-warn-<?php echo $post_id; ?>">!</span>
    7073        <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>
     74         </div>
    7275        </fieldset>
    7376
     
    8285        <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>
    8386        <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>
     87        <p>
     88        <?php
     89        _e( 'Discard any changes and restore the original image.' );
     90
     91        if ( ! defined( 'IMAGE_EDIT_OVERWRITE' ) || ! IMAGE_EDIT_OVERWRITE ) {
     92            echo ' ' . __( 'Previously edited copies of the image will not be deleted.' );
     93        }
     94
     95        ?>
     96        </p>
    9097        <div class="imgedit-submit">
    9198        <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; ?> />
     
    103110
    104111        <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        <p><?php _e( 'To crop the image, click on it and drag to make your selection.' ); ?></p>
     113
     114        <p><strong><?php _e( 'Crop Aspect Ratio' ); ?></strong><br />
     115        <?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>
     116
     117        <p><strong><?php _e( 'Crop Selection' ); ?></strong><br />
     118        <?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>
    112119        </div>
    113120    </div>
     
    141148    </div>
    142149
    143     <?php if ( $thumb && $sub_sizes ) {
     150    <?php
     151    if ( $thumb && $sub_sizes ) {
    144152        $thumb_img = wp_constrain_dimensions( $thumb['width'], $thumb['height'], 160, 120 );
    145153    ?>
     
    149157        <h2><?php _e( 'Thumbnail Settings' ); ?></h2>
    150158        <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>
     159        <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>
    152160    </div>
    153161
     
    163171        <label class="imgedit-label">
    164172        <input type="radio" name="imgedit-target-<?php echo $post_id; ?>" value="all" checked="checked" />
    165         <?php _e('All image sizes'); ?></label>
     173        <?php _e( 'All image sizes' ); ?></label>
    166174
    167175        <label class="imgedit-label">
    168176        <input type="radio" name="imgedit-target-<?php echo $post_id; ?>" value="thumbnail" />
    169         <?php _e('Thumbnail'); ?></label>
     177        <?php _e( 'Thumbnail' ); ?></label>
    170178
    171179        <label class="imgedit-label">
    172180        <input type="radio" name="imgedit-target-<?php echo $post_id; ?>" value="nothumb" />
    173         <?php _e('All sizes except thumbnail'); ?></label>
     181        <?php _e( 'All sizes except thumbnail' ); ?></label>
    174182    </fieldset>
    175183    </div>
     
    183191        <?php echo $note; ?>
    184192        <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>
     193            <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>
     194                                                                        <?php
     195
     196                                                                        // On some setups GD library does not provide imagerotate() - Ticket #11536
     197                                                                        if ( wp_image_editor_supports(
     198                                                                            array(
     199                                                                                'mime_type' => get_post_mime_type( $post_id ),
     200                                                                                'methods'   => array( 'rotate' ),
     201                                                                            )
     202                                                                        ) ) {
     203                                                                            $note_no_rotate = '';
     204                                                                    ?>
     205                                                                        <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>
    192206            <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 } ?>
     207                                                                <?php
     208                                                                        } else {
     209                                                                                    $note_no_rotate = '<p class="note-no-rotate"><em>' . __( 'Image rotation is not supported by your web host.' ) . '</em></p>';
     210                                                                        ?>
     211                                                                                <button type="button" class="imgedit-rleft button disabled" disabled></button>
     212                                                                                <button type="button" class="imgedit-rright button disabled" disabled></button>
     213                                                                        <?php } ?>
    199214
    200215            <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>
     
    214229
    215230        <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="" />
     231        <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="" />
    217232        </div>
    218233
     
    225240    </div>
    226241    <div class="imgedit-wait" id="imgedit-wait-<?php echo $post_id; ?>"></div>
    227     <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>
     242    <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>
    228243    </div>
    229244<?php
     
    251266        $image = apply_filters( 'image_editor_save_pre', $image, $attachment_id );
    252267
    253         if ( is_wp_error( $image->stream( $mime_type ) ) )
     268        if ( is_wp_error( $image->stream( $mime_type ) ) ) {
    254269            return false;
     270        }
    255271
    256272        return true;
     
    316332        $saved = apply_filters( 'wp_save_image_editor_file', null, $filename, $image, $mime_type, $post_id );
    317333
    318         if ( null !== $saved )
     334        if ( null !== $saved ) {
    319335            return $saved;
     336        }
    320337
    321338        return $image->save( $filename, $mime_type );
     
    343360        $saved = apply_filters( 'wp_save_image_file', null, $filename, $image, $mime_type, $post_id );
    344361
    345         if ( null !== $saved )
     362        if ( null !== $saved ) {
    346363            return $saved;
     364        }
    347365
    348366        switch ( $mime_type ) {
    349367            case 'image/jpeg':
    350 
    351368                /** This filter is documented in wp-includes/class-wp-image-editor.php */
    352369                return imagejpeg( $image, $filename, apply_filters( 'jpeg_quality', 90, 'edit_image' ) );
     
    371388 * @return float|int Image preview ratio.
    372389 */
    373 function _image_get_preview_ratio($w, $h) {
    374     $max = max($w, $h);
    375     return $max > 400 ? (400 / $max) : 1;
     390function _image_get_preview_ratio( $w, $h ) {
     391    $max = max( $w, $h );
     392    return $max > 400 ? ( 400 / $max ) : 1;
    376393}
    377394
     
    388405 * @return resource|false GD image resource, false otherwise.
    389406 */
    390 function _rotate_image_resource($img, $angle) {
     407function _rotate_image_resource( $img, $angle ) {
    391408    _deprecated_function( __FUNCTION__, '3.5.0', 'WP_Image_Editor::rotate()' );
    392     if ( function_exists('imagerotate') ) {
    393         $rotated = imagerotate($img, $angle, 0);
    394         if ( is_resource($rotated) ) {
    395             imagedestroy($img);
     409    if ( function_exists( 'imagerotate' ) ) {
     410        $rotated = imagerotate( $img, $angle, 0 );
     411        if ( is_resource( $rotated ) ) {
     412            imagedestroy( $img );
    396413            $img = $rotated;
    397414        }
     
    413430 * @return resource (maybe) flipped image resource.
    414431 */
    415 function _flip_image_resource($img, $horz, $vert) {
     432function _flip_image_resource( $img, $horz, $vert ) {
    416433    _deprecated_function( __FUNCTION__, '3.5.0', 'WP_Image_Editor::flip()' );
    417     $w = imagesx($img);
    418     $h = imagesy($img);
    419     $dst = wp_imagecreatetruecolor($w, $h);
    420     if ( is_resource($dst) ) {
    421         $sx = $vert ? ($w - 1) : 0;
    422         $sy = $horz ? ($h - 1) : 0;
     434    $w   = imagesx( $img );
     435    $h   = imagesy( $img );
     436    $dst = wp_imagecreatetruecolor( $w, $h );
     437    if ( is_resource( $dst ) ) {
     438        $sx = $vert ? ( $w - 1 ) : 0;
     439        $sy = $horz ? ( $h - 1 ) : 0;
    423440        $sw = $vert ? -$w : $w;
    424441        $sh = $horz ? -$h : $h;
    425442
    426         if ( imagecopyresampled($dst, $img, 0, 0, $sx, $sy, $w, $h, $sw, $sh) ) {
    427             imagedestroy($img);
     443        if ( imagecopyresampled( $dst, $img, 0, 0, $sx, $sy, $w, $h, $sw, $sh ) ) {
     444            imagedestroy( $img );
    428445            $img = $dst;
    429446        }
     
    445462 * @return resource (maybe) cropped image resource.
    446463 */
    447 function _crop_image_resource($img, $x, $y, $w, $h) {
    448     $dst = wp_imagecreatetruecolor($w, $h);
    449     if ( is_resource($dst) ) {
    450         if ( imagecopy($dst, $img, 0, 0, $x, $y, $w, $h) ) {
    451             imagedestroy($img);
     464function _crop_image_resource( $img, $x, $y, $w, $h ) {
     465    $dst = wp_imagecreatetruecolor( $w, $h );
     466    if ( is_resource( $dst ) ) {
     467        if ( imagecopy( $dst, $img, 0, 0, $x, $y, $w, $h ) ) {
     468            imagedestroy( $img );
    452469            $img = $dst;
    453470        }
     
    466483 */
    467484function image_edit_apply_changes( $image, $changes ) {
    468     if ( is_resource( $image ) )
     485    if ( is_resource( $image ) ) {
    469486        _deprecated_argument( __FUNCTION__, '3.5.0', __( '$image needs to be an WP_Image_Editor object' ) );
    470 
    471     if ( !is_array($changes) )
     487    }
     488
     489    if ( ! is_array( $changes ) ) {
    472490        return $image;
     491    }
    473492
    474493    // Expand change operations.
    475494    foreach ( $changes as $key => $obj ) {
    476         if ( isset($obj->r) ) {
    477             $obj->type = 'rotate';
     495        if ( isset( $obj->r ) ) {
     496            $obj->type  = 'rotate';
    478497            $obj->angle = $obj->r;
    479             unset($obj->r);
    480         } elseif ( isset($obj->f) ) {
     498            unset( $obj->r );
     499        } elseif ( isset( $obj->f ) ) {
    481500            $obj->type = 'flip';
    482501            $obj->axis = $obj->f;
    483             unset($obj->f);
    484         } elseif ( isset($obj->c) ) {
     502            unset( $obj->f );
     503        } elseif ( isset( $obj->c ) ) {
    485504            $obj->type = 'crop';
    486             $obj->sel = $obj->c;
    487             unset($obj->c);
    488         }
    489         $changes[$key] = $obj;
     505            $obj->sel  = $obj->c;
     506            unset( $obj->c );
     507        }
     508        $changes[ $key ] = $obj;
    490509    }
    491510
    492511    // Combine operations.
    493     if ( count($changes) > 1 ) {
    494         $filtered = array($changes[0]);
     512    if ( count( $changes ) > 1 ) {
     513        $filtered = array( $changes[0] );
    495514        for ( $i = 0, $j = 1, $c = count( $changes ); $j < $c; $j++ ) {
    496515            $combined = false;
    497             if ( $filtered[$i]->type == $changes[$j]->type ) {
    498                 switch ( $filtered[$i]->type ) {
     516            if ( $filtered[ $i ]->type == $changes[ $j ]->type ) {
     517                switch ( $filtered[ $i ]->type ) {
    499518                    case 'rotate':
    500                         $filtered[$i]->angle += $changes[$j]->angle;
    501                         $combined = true;
     519                        $filtered[ $i ]->angle += $changes[ $j ]->angle;
     520                        $combined               = true;
    502521                        break;
    503522                    case 'flip':
    504                         $filtered[$i]->axis ^= $changes[$j]->axis;
    505                         $combined = true;
     523                        $filtered[ $i ]->axis ^= $changes[ $j ]->axis;
     524                        $combined              = true;
    506525                        break;
    507526                }
    508527            }
    509             if ( !$combined )
    510                 $filtered[++$i] = $changes[$j];
     528            if ( ! $combined ) {
     529                $filtered[ ++$i ] = $changes[ $j ];
     530            }
    511531        }
    512532        $changes = $filtered;
    513         unset($filtered);
     533        unset( $filtered );
    514534    }
    515535
     
    523543         *
    524544         * @param WP_Image_Editor $image   WP_Image_Editor instance.
    525          * @param array           $changes Array of change operations.
     545         * @param array           $changes Array of change operations.
    526546         */
    527547        $image = apply_filters( 'wp_image_editor_before_change', $image, $changes );
     
    535555         *
    536556         * @param resource $image   GD image resource.
    537          * @param array    $changes Array of change operations.
     557         * @param array    $changes Array of change operations.
    538558         */
    539559        $image = apply_filters( 'image_edit_before_change', $image, $changes );
     
    544564            case 'rotate':
    545565                if ( $operation->angle != 0 ) {
    546                     if ( $image instanceof WP_Image_Editor )
     566                    if ( $image instanceof WP_Image_Editor ) {
    547567                        $image->rotate( $operation->angle );
    548                     else
     568                    } else {
    549569                        $image = _rotate_image_resource( $image, $operation->angle );
     570                    }
    550571                }
    551572                break;
    552573            case 'flip':
    553                 if ( $operation->axis != 0 )
    554                     if ( $image instanceof WP_Image_Editor )
    555                         $image->flip( ($operation->axis & 1) != 0, ($operation->axis & 2) != 0 );
    556                     else
     574                if ( $operation->axis != 0 ) {
     575                    if ( $image instanceof WP_Image_Editor ) {
     576                        $image->flip( ( $operation->axis & 1 ) != 0, ( $operation->axis & 2 ) != 0 );
     577                    } else {
    557578                        $image = _flip_image_resource( $image, ( $operation->axis & 1 ) != 0, ( $operation->axis & 2 ) != 0 );
     579                    }
     580                }
    558581                break;
    559582            case 'crop':
     
    562585                if ( $image instanceof WP_Image_Editor ) {
    563586                    $size = $image->get_size();
    564                     $w = $size['width'];
    565                     $h = $size['height'];
     587                    $w    = $size['width'];
     588                    $h    = $size['height'];
    566589
    567590                    $scale = 1 / _image_get_preview_ratio( $w, $h ); // discard preview scaling
     
    597620    }
    598621
    599     $changes = !empty($_REQUEST['history']) ? json_decode( wp_unslash($_REQUEST['history']) ) : null;
    600     if ( $changes )
     622    $changes = ! empty( $_REQUEST['history'] ) ? json_decode( wp_unslash( $_REQUEST['history'] ) ) : null;
     623    if ( $changes ) {
    601624        $img = image_edit_apply_changes( $img, $changes );
     625    }
    602626
    603627    // Scale the image.
    604628    $size = $img->get_size();
    605     $w = $size['width'];
    606     $h = $size['height'];
     629    $w    = $size['width'];
     630    $h    = $size['height'];
    607631
    608632    $ratio = _image_get_preview_ratio( $w, $h );
    609     $w2 = max ( 1, $w * $ratio );
    610     $h2 = max ( 1, $h * $ratio );
    611 
    612     if ( is_wp_error( $img->resize( $w2, $h2 ) ) )
     633    $w2    = max( 1, $w * $ratio );
     634    $h2    = max( 1, $h * $ratio );
     635
     636    if ( is_wp_error( $img->resize( $w2, $h2 ) ) ) {
    613637        return false;
     638    }
    614639
    615640    return wp_stream_image( $img, $post->post_mime_type, $post_id );
     
    624649 * @return stdClass Image restoration message object.
    625650 */
    626 function wp_restore_image($post_id) {
    627     $meta = wp_get_attachment_metadata($post_id);
    628     $file = get_attached_file($post_id);
     651function wp_restore_image( $post_id ) {
     652    $meta         = wp_get_attachment_metadata( $post_id );
     653    $file         = get_attached_file( $post_id );
    629654    $backup_sizes = $old_backup_sizes = get_post_meta( $post_id, '_wp_attachment_backup_sizes', true );
    630     $restored = false;
    631     $msg = new stdClass;
    632 
    633     if ( !is_array($backup_sizes) ) {
    634         $msg->error = __('Cannot load image metadata.');
     655    $restored     = false;
     656    $msg          = new stdClass;
     657
     658    if ( ! is_array( $backup_sizes ) ) {
     659        $msg->error = __( 'Cannot load image metadata.' );
    635660        return $msg;
    636661    }
    637662
    638     $parts = pathinfo($file);
    639     $suffix = time() . rand(100, 999);
     663    $parts         = pathinfo( $file );
     664    $suffix        = time() . rand( 100, 999 );
    640665    $default_sizes = get_intermediate_image_sizes();
    641666
    642     if ( isset($backup_sizes['full-orig']) && is_array($backup_sizes['full-orig']) ) {
     667    if ( isset( $backup_sizes['full-orig'] ) && is_array( $backup_sizes['full-orig'] ) ) {
    643668        $data = $backup_sizes['full-orig'];
    644669
    645670        if ( $parts['basename'] != $data['file'] ) {
    646             if ( defined('IMAGE_EDIT_OVERWRITE') && IMAGE_EDIT_OVERWRITE ) {
     671            if ( defined( 'IMAGE_EDIT_OVERWRITE' ) && IMAGE_EDIT_OVERWRITE ) {
    647672
    648673                // Delete only if it's an edited image.
    649                 if ( preg_match('/-e[0-9]{13}\./', $parts['basename']) ) {
     674                if ( preg_match( '/-e[0-9]{13}\./', $parts['basename'] ) ) {
    650675                    wp_delete_file( $file );
    651676                }
    652677            } elseif ( isset( $meta['width'], $meta['height'] ) ) {
    653                 $backup_sizes["full-$suffix"] = array('width' => $meta['width'], 'height' => $meta['height'], 'file' => $parts['basename']);
    654             }
    655         }
    656 
    657         $restored_file = path_join($parts['dirname'], $data['file']);
    658         $restored = update_attached_file($post_id, $restored_file);
    659 
    660         $meta['file'] = _wp_relative_upload_path( $restored_file );
    661         $meta['width'] = $data['width'];
     678                $backup_sizes[ "full-$suffix" ] = array(
     679                    'width'  => $meta['width'],
     680                    'height' => $meta['height'],
     681                    'file'   => $parts['basename'],
     682                );
     683            }
     684        }
     685
     686        $restored_file = path_join( $parts['dirname'], $data['file'] );
     687        $restored      = update_attached_file( $post_id, $restored_file );
     688
     689        $meta['file']   = _wp_relative_upload_path( $restored_file );
     690        $meta['width']  = $data['width'];
    662691        $meta['height'] = $data['height'];
    663692    }
    664693
    665694    foreach ( $default_sizes as $default_size ) {
    666         if ( isset($backup_sizes["$default_size-orig"]) ) {
    667             $data = $backup_sizes["$default_size-orig"];
    668             if ( isset($meta['sizes'][$default_size]) && $meta['sizes'][$default_size]['file'] != $data['file'] ) {
    669                 if ( defined('IMAGE_EDIT_OVERWRITE') && IMAGE_EDIT_OVERWRITE ) {
     695        if ( isset( $backup_sizes[ "$default_size-orig" ] ) ) {
     696            $data = $backup_sizes[ "$default_size-orig" ];
     697            if ( isset( $meta['sizes'][ $default_size ] ) && $meta['sizes'][ $default_size ]['file'] != $data['file'] ) {
     698                if ( defined( 'IMAGE_EDIT_OVERWRITE' ) && IMAGE_EDIT_OVERWRITE ) {
    670699
    671700                    // Delete only if it's an edited image.
    672                     if ( preg_match('/-e[0-9]{13}-/', $meta['sizes'][$default_size]['file']) ) {
    673                         $delete_file = path_join( $parts['dirname'], $meta['sizes'][$default_size]['file'] );
     701                    if ( preg_match( '/-e[0-9]{13}-/', $meta['sizes'][ $default_size ]['file'] ) ) {
     702                        $delete_file = path_join( $parts['dirname'], $meta['sizes'][ $default_size ]['file'] );
    674703                        wp_delete_file( $delete_file );
    675704                    }
    676705                } else {
    677                     $backup_sizes["$default_size-{$suffix}"] = $meta['sizes'][$default_size];
     706                    $backup_sizes[ "$default_size-{$suffix}" ] = $meta['sizes'][ $default_size ];
    678707                }
    679708            }
    680709
    681             $meta['sizes'][$default_size] = $data;
     710            $meta['sizes'][ $default_size ] = $data;
    682711        } else {
    683             unset($meta['sizes'][$default_size]);
     712            unset( $meta['sizes'][ $default_size ] );
    684713        }
    685714    }
     
    688717        ( $old_backup_sizes !== $backup_sizes && ! update_post_meta( $post_id, '_wp_attachment_backup_sizes', $backup_sizes ) ) ) {
    689718
    690         $msg->error = __('Cannot save image metadata.');
     719        $msg->error = __( 'Cannot save image metadata.' );
    691720        return $msg;
    692721    }
    693722
    694     if ( !$restored )
    695         $msg->error = __('Image metadata is inconsistent.');
    696     else
    697         $msg->msg = __('Image restored successfully.');
     723    if ( ! $restored ) {
     724        $msg->error = __( 'Image metadata is inconsistent.' );
     725    } else {
     726        $msg->msg = __( 'Image restored successfully.' );
     727    }
    698728
    699729    return $msg;
     
    710740    $_wp_additional_image_sizes = wp_get_additional_image_sizes();
    711741
    712     $return = new stdClass;
     742    $return  = new stdClass;
    713743    $success = $delete = $scaled = $nocrop = false;
    714     $post = get_post( $post_id );
     744    $post    = get_post( $post_id );
    715745
    716746    $img = wp_get_image_editor( _load_image_to_edit_path( $post_id, 'full' ) );
    717747    if ( is_wp_error( $img ) ) {
    718         $return->error = esc_js( __('Unable to create new image.') );
     748        $return->error = esc_js( __( 'Unable to create new image.' ) );
    719749        return $return;
    720750    }
    721751
    722     $fwidth = !empty($_REQUEST['fwidth']) ? intval($_REQUEST['fwidth']) : 0;
    723     $fheight = !empty($_REQUEST['fheight']) ? intval($_REQUEST['fheight']) : 0;
    724     $target = !empty($_REQUEST['target']) ? preg_replace('/[^a-z0-9_-]+/i', '', $_REQUEST['target']) : '';
    725     $scale = !empty($_REQUEST['do']) && 'scale' == $_REQUEST['do'];
     752    $fwidth  = ! empty( $_REQUEST['fwidth'] ) ? intval( $_REQUEST['fwidth'] ) : 0;
     753    $fheight = ! empty( $_REQUEST['fheight'] ) ? intval( $_REQUEST['fheight'] ) : 0;
     754    $target  = ! empty( $_REQUEST['target'] ) ? preg_replace( '/[^a-z0-9_-]+/i', '', $_REQUEST['target'] ) : '';
     755    $scale   = ! empty( $_REQUEST['do'] ) && 'scale' == $_REQUEST['do'];
    726756
    727757    if ( $scale && $fwidth > 0 && $fheight > 0 ) {
    728758        $size = $img->get_size();
    729         $sX = $size['width'];
    730         $sY = $size['height'];
     759        $sX   = $size['width'];
     760        $sY   = $size['height'];
    731761
    732762        // Check if it has roughly the same w / h ratio.
    733         $diff = round($sX / $sY, 2) - round($fwidth / $fheight, 2);
     763        $diff = round( $sX / $sY, 2 ) - round( $fwidth / $fheight, 2 );
    734764        if ( -0.1 < $diff && $diff < 0.1 ) {
    735765            // Scale the full size image.
    736             if ( $img->resize( $fwidth, $fheight ) )
     766            if ( $img->resize( $fwidth, $fheight ) ) {
    737767                $scaled = true;
    738         }
    739 
    740         if ( !$scaled ) {
    741             $return->error = esc_js( __('Error while saving the scaled image. Please reload the page and try again.') );
     768            }
     769        }
     770
     771        if ( ! $scaled ) {
     772            $return->error = esc_js( __( 'Error while saving the scaled image. Please reload the page and try again.' ) );
    742773            return $return;
    743774        }
    744     } elseif ( !empty($_REQUEST['history']) ) {
    745         $changes = json_decode( wp_unslash($_REQUEST['history']) );
    746         if ( $changes )
    747             $img = image_edit_apply_changes($img, $changes);
     775    } elseif ( ! empty( $_REQUEST['history'] ) ) {
     776        $changes = json_decode( wp_unslash( $_REQUEST['history'] ) );
     777        if ( $changes ) {
     778            $img = image_edit_apply_changes( $img, $changes );
     779        }
    748780    } else {
    749         $return->error = esc_js( __('Nothing to save, the image has not changed.') );
     781        $return->error = esc_js( __( 'Nothing to save, the image has not changed.' ) );
    750782        return $return;
    751783    }
    752784
    753     $meta = wp_get_attachment_metadata($post_id);
     785    $meta         = wp_get_attachment_metadata( $post_id );
    754786    $backup_sizes = get_post_meta( $post->ID, '_wp_attachment_backup_sizes', true );
    755787
    756     if ( !is_array($meta) ) {
    757         $return->error = esc_js( __('Image data does not exist. Please re-upload the image.') );
     788    if ( ! is_array( $meta ) ) {
     789        $return->error = esc_js( __( 'Image data does not exist. Please re-upload the image.' ) );
    758790        return $return;
    759791    }
    760792
    761     if ( !is_array($backup_sizes) )
     793    if ( ! is_array( $backup_sizes ) ) {
    762794        $backup_sizes = array();
     795    }
    763796
    764797    // Generate new filename.
     
    766799
    767800    $basename = pathinfo( $path, PATHINFO_BASENAME );
    768     $dirname = pathinfo( $path, PATHINFO_DIRNAME );
    769     $ext = pathinfo( $path, PATHINFO_EXTENSION );
     801    $dirname  = pathinfo( $path, PATHINFO_DIRNAME );
     802    $ext      = pathinfo( $path, PATHINFO_EXTENSION );
    770803    $filename = pathinfo( $path, PATHINFO_FILENAME );
    771     $suffix = time() . rand(100, 999);
    772 
    773     if ( defined('IMAGE_EDIT_OVERWRITE') && IMAGE_EDIT_OVERWRITE &&
    774         isset($backup_sizes['full-orig']) && $backup_sizes['full-orig']['file'] != $basename ) {
     804    $suffix   = time() . rand( 100, 999 );
     805
     806    if ( defined( 'IMAGE_EDIT_OVERWRITE' ) && IMAGE_EDIT_OVERWRITE &&
     807        isset( $backup_sizes['full-orig'] ) && $backup_sizes['full-orig']['file'] != $basename ) {
    775808
    776809        if ( 'thumbnail' == $target ) {
     
    781814    } else {
    782815        while ( true ) {
    783             $filename = preg_replace( '/-e([0-9]+)$/', '', $filename );
    784             $filename .= "-e{$suffix}";
     816            $filename     = preg_replace( '/-e([0-9]+)$/', '', $filename );
     817            $filename    .= "-e{$suffix}";
    785818            $new_filename = "{$filename}.{$ext}";
    786             $new_path = "{$dirname}/$new_filename";
    787             if ( file_exists($new_path) ) {
     819            $new_path     = "{$dirname}/$new_filename";
     820            if ( file_exists( $new_path ) ) {
    788821                $suffix++;
    789822            } else {
     
    794827
    795828    // Save the full-size file, also needed to create sub-sizes.
    796     if ( !wp_save_image_file($new_path, $img, $post->post_mime_type, $post_id) ) {
    797         $return->error = esc_js( __('Unable to save the image.') );
     829    if ( ! wp_save_image_file( $new_path, $img, $post->post_mime_type, $post_id ) ) {
     830        $return->error = esc_js( __( 'Unable to save the image.' ) );
    798831        return $return;
    799832    }
     
    810843
    811844        if ( $tag ) {
    812             $backup_sizes[$tag] = array('width' => $meta['width'], 'height' => $meta['height'], 'file' => $basename );
     845            $backup_sizes[ $tag ] = array(
     846                'width'  => $meta['width'],
     847                'height' => $meta['height'],
     848                'file'   => $basename,
     849            );
    813850        }
    814851        $success = ( $path === $new_path ) || update_attached_file( $post_id, $new_path );
     
    816853        $meta['file'] = _wp_relative_upload_path( $new_path );
    817854
    818         $size = $img->get_size();
    819         $meta['width'] = $size['width'];
     855        $size           = $img->get_size();
     856        $meta['width']  = $size['width'];
    820857        $meta['height'] = $size['height'];
    821858
    822         if ( $success && ('nothumb' == $target || 'all' == $target) ) {
     859        if ( $success && ( 'nothumb' == $target || 'all' == $target ) ) {
    823860            $sizes = get_intermediate_image_sizes();
    824             if ( 'nothumb' == $target )
    825                 $sizes = array_diff( $sizes, array('thumbnail') );
     861            if ( 'nothumb' == $target ) {
     862                $sizes = array_diff( $sizes, array( 'thumbnail' ) );
     863            }
    826864        }
    827865
     
    829867        $return->fh = $meta['height'];
    830868    } elseif ( 'thumbnail' == $target ) {
    831         $sizes = array( 'thumbnail' );
     869        $sizes   = array( 'thumbnail' );
    832870        $success = $delete = $nocrop = true;
    833871    }
     
    853891        foreach ( $sizes as $size ) {
    854892            $tag = false;
    855             if ( isset( $meta['sizes'][$size] ) ) {
    856                 if ( isset($backup_sizes["$size-orig"]) ) {
    857                     if ( ( !defined('IMAGE_EDIT_OVERWRITE') || !IMAGE_EDIT_OVERWRITE ) && $backup_sizes["$size-orig"]['file'] != $meta['sizes'][$size]['file'] )
     893            if ( isset( $meta['sizes'][ $size ] ) ) {
     894                if ( isset( $backup_sizes[ "$size-orig" ] ) ) {
     895                    if ( ( ! defined( 'IMAGE_EDIT_OVERWRITE' ) || ! IMAGE_EDIT_OVERWRITE ) && $backup_sizes[ "$size-orig" ]['file'] != $meta['sizes'][ $size ]['file'] ) {
    858896                        $tag = "$size-$suffix";
     897                    }
    859898                } else {
    860899                    $tag = "$size-orig";
    861900                }
    862901
    863                 if ( $tag )
    864                     $backup_sizes[$tag] = $meta['sizes'][$size];
     902                if ( $tag ) {
     903                    $backup_sizes[ $tag ] = $meta['sizes'][ $size ];
     904                }
    865905            }
    866906
     
    875915            }
    876916
    877             $_sizes[ $size ] = array( 'width' => $width, 'height' => $height, 'crop' => $crop );
     917            $_sizes[ $size ] = array(
     918                'width'  => $width,
     919                'height' => $height,
     920                'crop'   => $crop,
     921            );
    878922        }
    879923
     
    885929    if ( $success ) {
    886930        wp_update_attachment_metadata( $post_id, $meta );
    887         update_post_meta( $post_id, '_wp_attachment_backup_sizes', $backup_sizes);
     931        update_post_meta( $post_id, '_wp_attachment_backup_sizes', $backup_sizes );
    888932
    889933        if ( $target == 'thumbnail' || $target == 'all' || $target == 'full' ) {
    890934            // Check if it's an image edit from attachment edit screen
    891935            if ( ! empty( $_REQUEST['context'] ) && 'edit-attachment' == $_REQUEST['context'] ) {
    892                 $thumb_url = wp_get_attachment_image_src( $post_id, array( 900, 600 ), true );
     936                $thumb_url         = wp_get_attachment_image_src( $post_id, array( 900, 600 ), true );
    893937                $return->thumbnail = $thumb_url[0];
    894938            } else {
    895                 $file_url = wp_get_attachment_url($post_id);
     939                $file_url = wp_get_attachment_url( $post_id );
    896940                if ( ! empty( $meta['sizes']['thumbnail'] ) && $thumb = $meta['sizes']['thumbnail'] ) {
    897                     $return->thumbnail = path_join( dirname($file_url), $thumb['file'] );
     941                    $return->thumbnail = path_join( dirname( $file_url ), $thumb['file'] );
    898942                } else {
    899943                    $return->thumbnail = "$file_url?w=128&h=128";
     
    909953    }
    910954
    911     $return->msg = esc_js( __('Image saved') );
     955    $return->msg = esc_js( __( 'Image saved' ) );
    912956    return $return;
    913957}
Note: See TracChangeset for help on using the changeset viewer.