Parsed: 110453

function wp_restore_image( $post_id ) {
  $meta             = wp_get_attachment_metadata( $post_id );
  $file             = get_attached_file( $post_id );
  $backup_sizes     = get_post_meta( $post_id, '_wp_attachment_backup_sizes', true );
  $old_backup_sizes = $backup_sizes;
  $restored         = false;
  $msg              = new stdClass;

  if ( ! is_array( $backup_sizes ) ) {
    $msg->error = __( 'Cannot load image metadata.' );
    return $msg;
  }

  $parts         = pathinfo( $file );
  $suffix        = time() . rand( 100, 999 );
  $default_sizes = get_intermediate_image_sizes();

  if ( isset( $backup_sizes['full-orig'] ) && is_array( $backup_sizes['full-orig'] ) ) {
    $data = $backup_sizes['full-orig'];

    if ( $parts['basename'] != $data['file'] ) {
      if ( defined( 'IMAGE_EDIT_OVERWRITE' ) && IMAGE_EDIT_OVERWRITE ) {

        // Delete only if it's an edited image.
        if ( preg_match( '/-e[0-9]{13}\./', $parts['basename'] ) ) {
          wp_delete_file( $file );
        }
      } elseif ( isset( $meta['width'], $meta['height'] ) ) {
        $backup_sizes[ "full-$suffix" ] = array(
          'width'  => $meta['width'],
          'height' => $meta['height'],
          'file'   => $parts['basename'],
        );
      }
    }

    $restored_file = path_join( $parts['dirname'], $data['file'] );
    $restored      = update_attached_file( $post_id, $restored_file );

    $meta['file']   = _wp_relative_upload_path( $restored_file );
    $meta['width']  = $data['width'];
    $meta['height'] = $data['height'];
  }

  foreach ( $default_sizes as $default_size ) {
    if ( isset( $backup_sizes[ "$default_size-orig" ] ) ) {
      $data = $backup_sizes[ "$default_size-orig" ];
      if ( isset( $meta['sizes'][ $default_size ] ) && $meta['sizes'][ $default_size ]['file'] != $data['file'] ) {
        if ( defined( 'IMAGE_EDIT_OVERWRITE' ) && IMAGE_EDIT_OVERWRITE ) {

          // Delete only if it's an edited image.
          if ( preg_match( '/-e[0-9]{13}-/', $meta['sizes'][ $default_size ]['file'] ) ) {
            $delete_file = path_join( $parts['dirname'], $meta['sizes'][ $default_size ]['file'] );
            wp_delete_file( $delete_file );
          }
        } else {
          $backup_sizes[ "$default_size-{$suffix}" ] = $meta['sizes'][ $default_size ];
        }
      }

      $meta['sizes'][ $default_size ] = $data;
    } else {
      unset( $meta['sizes'][ $default_size ] );
    }
  }

  if ( ! wp_update_attachment_metadata( $post_id, $meta ) ||
    ( $old_backup_sizes !== $backup_sizes && ! update_post_meta( $post_id, '_wp_attachment_backup_sizes', $backup_sizes ) ) ) {

    $msg->error = __( 'Cannot save image metadata.' );
    return $msg;
  }

  if ( ! $restored ) {
    $msg->error = __( 'Image metadata is inconsistent.' );
  } else {
    $msg->msg = __( 'Image restored successfully.' );
  }

  return $msg;
}