'jpg',
'image/png' => 'png',
'image/webp' => 'webp',
);
const BACKUP_META = '_pictureeditor_backups';
/**
* Load WordPress admin media helpers (REST requests do not include them).
*/
private static function require_media() {
require_once ABSPATH . 'wp-admin/includes/file.php';
require_once ABSPATH . 'wp-admin/includes/media.php';
require_once ABSPATH . 'wp-admin/includes/image.php';
}
/**
* Validate an uploaded edited file: real image, allowed type, sane pixel count.
*
* @param array $file $_FILES entry.
* @return array|WP_Error { tmp, mime, ext, width, height }
*/
public static function validate_upload( $file ) {
if ( ! is_array( $file ) || empty( $file['tmp_name'] ) ) {
return new WP_Error( 'pictureeditor_no_file', __( 'No edited file was received.', 'pictureeditor' ), array( 'status' => 400 ) );
}
if ( ! empty( $file['error'] ) ) {
$msg = UPLOAD_ERR_INI_SIZE === (int) $file['error'] || UPLOAD_ERR_FORM_SIZE === (int) $file['error']
/* translators: %s: max upload size */
? sprintf( __( 'The edited file is larger than this site accepts (%s). Choose a smaller size or a lower quality.', 'pictureeditor' ), size_format( wp_max_upload_size() ) )
: __( 'The upload did not complete. Try again.', 'pictureeditor' );
return new WP_Error( 'pictureeditor_upload_error', $msg, array( 'status' => 413 === (int) $file['error'] ? 413 : 400 ) );
}
$tmp = $file['tmp_name'];
if ( ! is_uploaded_file( $tmp ) && ! apply_filters( 'pictureeditor_allow_non_uploaded_tmp', false, $tmp ) ) {
return new WP_Error( 'pictureeditor_bad_upload', __( 'The edited file was not received as an upload.', 'pictureeditor' ), array( 'status' => 400 ) );
}
if ( filesize( $tmp ) > wp_max_upload_size() ) {
/* translators: %s: max upload size */
return new WP_Error( 'pictureeditor_too_big', sprintf( __( 'The edited file is larger than this site accepts (%s).', 'pictureeditor' ), size_format( wp_max_upload_size() ) ), array( 'status' => 413 ) );
}
// Sniff the real type; never trust the name or the browser's content type.
$mime = wp_get_image_mime( $tmp );
if ( ! $mime || ! isset( self::OUTPUT_MIMES[ $mime ] ) ) {
return new WP_Error( 'pictureeditor_bad_type', __( 'The edited file is not a JPEG, PNG or WebP image.', 'pictureeditor' ), array( 'status' => 415 ) );
}
$allowed = (array) Settings::get( 'allowed_formats' );
if ( ! in_array( $mime, $allowed, true ) ) {
return new WP_Error( 'pictureeditor_format_disabled', __( 'This output format is turned off in Settings → PictureEditor.', 'pictureeditor' ), array( 'status' => 415 ) );
}
$size = wp_getimagesize( $tmp );
if ( ! $size || $size[0] < 1 || $size[1] < 1 ) {
return new WP_Error( 'pictureeditor_unreadable', __( 'The edited file could not be read as an image.', 'pictureeditor' ), array( 'status' => 415 ) );
}
$max_px = (int) apply_filters( 'pictureeditor_max_pixels', 50000000 );
if ( $size[0] * $size[1] > $max_px ) {
return new WP_Error( 'pictureeditor_too_many_pixels', __( 'The edited image has too many pixels for this site.', 'pictureeditor' ), array( 'status' => 413 ) );
}
return array(
'tmp' => $tmp,
'mime' => $mime,
'ext' => self::OUTPUT_MIMES[ $mime ],
'width' => (int) $size[0],
'height' => (int) $size[1],
);
}
/**
* Store a validated edit manifest (JSON, size-limited, no pixels).
*
* @param int $id Attachment ID.
* @param string $json Raw JSON.
*/
private static function store_manifest( $id, $json ) {
if ( ! is_string( $json ) || '' === $json || strlen( $json ) > 2000000 ) {
return;
}
$data = json_decode( $json, true );
if ( ! is_array( $data ) || ! isset( $data['schema'] ) || 'pictureeditor.edit-manifest' !== $data['schema'] ) {
return;
}
update_post_meta( $id, '_pictureeditor_manifest', wp_slash( wp_json_encode( $data ) ) );
}
/**
* Save as a new attachment. The source attachment is never modified.
*
* @param int $source_id Source attachment.
* @param array $upload Validated upload.
* @param string $name Requested file name.
* @param string $alt Alt text (null = keep source's per settings).
* @param string $manifest Edit manifest JSON.
* @param int $parent Post to attach to (0 = unattached).
* @return int|WP_Error New attachment ID.
*/
public static function create_new( $source_id, $upload, $name, $alt, $manifest, $parent = 0 ) {
self::require_media();
$source = get_post( $source_id );
$base = sanitize_file_name( pathinfo( (string) $name, PATHINFO_FILENAME ) );
if ( '' === $base ) {
$base = 'edited-image';
}
$filename = $base . '.' . $upload['ext'];
// media_handle_sideload moves the file, so work on a copy we own.
$tmp = wp_tempnam( $filename );
if ( ! $tmp || ! @copy( $upload['tmp'], $tmp ) ) { // phpcs:ignore WordPress.PHP.NoSilencedErrors
return new WP_Error( 'pictureeditor_tmp', __( 'The server could not store the edited file temporarily.', 'pictureeditor' ), array( 'status' => 500 ) );
}
$title = $source ? $source->post_title : $base;
/* translators: %s: original title */
$title = sprintf( __( '%s (edited)', 'pictureeditor' ), $title );
$post_data = array(
'post_title' => $title,
'post_excerpt' => $source ? $source->post_excerpt : '',
'post_content' => $source ? $source->post_content : '',
'post_mime_type' => $upload['mime'],
);
$new_id = media_handle_sideload(
array(
'name' => $filename,
'tmp_name' => $tmp,
'type' => $upload['mime'],
'size' => filesize( $tmp ),
'error' => 0,
),
absint( $parent ),
$title,
$post_data
);
if ( is_wp_error( $new_id ) ) {
if ( file_exists( $tmp ) ) {
wp_delete_file( $tmp );
}
$new_id->add_data( array( 'status' => 500 ) );
return $new_id;
}
$alt_text = null === $alt ? ( Settings::get( 'keep_alt' ) ? get_post_meta( $source_id, '_wp_attachment_image_alt', true ) : '' ) : $alt;
if ( '' !== (string) $alt_text ) {
update_post_meta( $new_id, '_wp_attachment_image_alt', sanitize_text_field( $alt_text ) );
}
update_post_meta( $new_id, '_pictureeditor_source', absint( $source_id ) );
self::store_manifest( $new_id, $manifest );
/**
* Fires after an edited copy was saved as a new attachment.
*
* @param int $new_id New attachment.
* @param int $source_id Source attachment.
*/
do_action( 'pictureeditor_saved_new', $new_id, $source_id );
return (int) $new_id;
}
/**
* Backup root. Backups can hold content someone deliberately edited out (a face, an
* address), so they must not be reachable from the web: the folder name carries a
* per-site secret, every level has an index.php, Apache/IIS are told to deny all, and
* file names inside are random.
*
* @return string Absolute path.
*/
private static function backup_root() {
$secret = get_option( 'pictureeditor_backup_secret' );
if ( ! is_string( $secret ) || strlen( $secret ) < 32 ) {
$secret = wp_generate_password( 32, false );
update_option( 'pictureeditor_backup_secret', $secret, false );
}
$up = wp_get_upload_dir();
$root = trailingslashit( $up['basedir'] ) . 'pictureeditor-backups-' . strtolower( $secret );
if ( ! is_dir( $root ) ) {
wp_mkdir_p( $root );
}
$guards = array(
'index.php' => " "# PictureEditor backups: never served.\n\nRequire all denied\n\n\nDeny from all\n\n",
'web.config' => "\n\n",
);
foreach ( $guards as $name => $body ) {
if ( ! file_exists( $root . '/' . $name ) ) {
file_put_contents( $root . '/' . $name, $body ); // phpcs:ignore WordPress.WP.AlternativeFunctions
}
}
return $root;
}
/**
* Backup directory for one attachment.
*
* @param int $id Attachment ID.
* @return string Absolute path.
*/
private static function backup_dir( $id ) {
$dir = self::backup_root() . '/' . absint( $id );
if ( ! is_dir( $dir ) ) {
wp_mkdir_p( $dir );
file_put_contents( $dir . '/index.php', " path], meta }
*/
private static function current_files( $id ) {
$main = get_attached_file( $id, true );
$meta = wp_get_attachment_metadata( $id );
$dir = dirname( $main );
$sizes = array();
if ( is_array( $meta ) && ! empty( $meta['sizes'] ) ) {
foreach ( $meta['sizes'] as $size => $s ) {
if ( ! empty( $s['file'] ) ) {
$sizes[ $size ] = array(
'path' => path_join( $dir, $s['file'] ),
'width' => (int) $s['width'],
'height' => (int) $s['height'],
);
}
}
}
$original = function_exists( 'wp_get_original_image_path' ) ? wp_get_original_image_path( $id ) : $main;
return array(
'main' => $main,
'original' => $original ? $original : $main,
'sizes' => $sizes,
'meta' => $meta,
);
}
/**
* Copy every file of an attachment into a timestamped backup with its metadata.
*
* @param int $id Attachment ID.
* @return array|WP_Error Backup record.
*/
private static function make_backup( $id ) {
$cur = self::current_files( $id );
$stamp = gmdate( 'Ymd-His' ) . '-' . strtolower( wp_generate_password( 20, false ) );
$dir = self::backup_dir( $id ) . '/' . $stamp;
if ( ! wp_mkdir_p( $dir ) || false === file_put_contents( $dir . '/index.php', " 500 ) );
}
$files = array();
$paths = array_unique( array_filter( array_merge( array( $cur['main'], $cur['original'] ), wp_list_pluck( $cur['sizes'], 'path' ) ) ) );
foreach ( $paths as $p ) {
if ( ! file_exists( $p ) ) {
continue;
}
// Random name: nothing in the path reveals or predicts the file.
$dest = $dir . '/' . strtolower( wp_generate_password( 24, false ) ) . '.bak';
if ( ! @copy( $p, $dest ) ) { // phpcs:ignore WordPress.PHP.NoSilencedErrors
return new WP_Error( 'pictureeditor_backup', __( 'Could not back up the original, so nothing was replaced.', 'pictureeditor' ), array( 'status' => 500 ) );
}
$files[ $p ] = $dest;
}
$record = array(
'time' => time(),
'user' => get_current_user_id(),
'dir' => $dir,
'files' => $files,
'attached_file' => get_post_meta( $id, '_wp_attached_file', true ),
'meta' => $cur['meta'],
'mime' => get_post_mime_type( $id ),
);
$backups = get_post_meta( $id, self::BACKUP_META, true );
$backups = is_array( $backups ) ? $backups : array();
array_unshift( $backups, $record );
update_post_meta( $id, self::BACKUP_META, wp_slash( array_slice( $backups, 0, (int) apply_filters( 'pictureeditor_backups_kept', 5 ) ) ) );
return $record;
}
/**
* WordPress filesystem in direct mode (we only touch the uploads folder).
*
* @return \WP_Filesystem_Base|null
*/
private static function fs() {
global $wp_filesystem;
if ( ! $wp_filesystem ) {
require_once ABSPATH . 'wp-admin/includes/file.php';
WP_Filesystem();
}
return $wp_filesystem;
}
/**
* Move a file over another (same folder → an atomic rename on local disks).
*
* @param string $from From.
* @param string $to To.
* @return bool
*/
private static function move( $from, $to ) {
$fs = self::fs();
return $fs ? (bool) $fs->move( $from, $to, true ) : false;
}
/**
* Write $src to $dest atomically (temp file in the same folder, then rename).
*
* @param string $src Source path.
* @param string $dest Destination path.
* @return bool
*/
private static function atomic_copy( $src, $dest ) {
$tmp = $dest . '.pe-tmp-' . wp_generate_password( 6, false );
if ( ! @copy( $src, $tmp ) ) { // phpcs:ignore WordPress.PHP.NoSilencedErrors
return false;
}
if ( ! self::move( $tmp, $dest ) ) {
wp_delete_file( $tmp );
return false;
}
return true;
}
/**
* Put a backup back exactly as it was.
*
* @param int $id Attachment ID.
* @param array $record Backup record.
* @return bool
*/
private static function restore_record( $id, $record ) {
$ok = true;
foreach ( (array) $record['files'] as $orig => $backup ) {
if ( file_exists( $backup ) ) {
$ok = self::atomic_copy( $backup, $orig ) && $ok;
}
}
update_post_meta( $id, '_wp_attached_file', wp_slash( $record['attached_file'] ) );
wp_update_attachment_metadata( $id, $record['meta'] );
clean_post_cache( $id );
return $ok;
}
/**
* Keep every previously published URL valid: any old size file that the new metadata
* did not regenerate is rewritten from the new image at that size by WordPress's own
* image editor, and an old main file name that disappeared gets the new main image.
*
* @param array $before Files before.
* @param int $id Attachment ID.
*/
private static function keep_old_urls( $before, $id ) {
$after = self::current_files( $id );
$new_paths = array_merge( array( $after['main'], $after['original'] ), wp_list_pluck( $after['sizes'], 'path' ) );
$source = $after['original'] && file_exists( $after['original'] ) ? $after['original'] : $after['main'];
foreach ( $before['sizes'] as $s ) {
if ( in_array( $s['path'], $new_paths, true ) ) {
continue;
}
$ed = wp_get_image_editor( $source );
if ( is_wp_error( $ed ) ) {
continue;
}
$ed->resize( $s['width'], $s['height'], true );
$saved = $ed->save( $s['path'] . '.pe-tmp.' . pathinfo( $s['path'], PATHINFO_EXTENSION ) );
if ( ! is_wp_error( $saved ) && ! empty( $saved['path'] ) ) {
self::move( $saved['path'], $s['path'] );
}
}
if ( $before['main'] && ! in_array( $before['main'], $new_paths, true ) ) {
self::atomic_copy( $after['main'], $before['main'] );
}
}
/**
* Replace an attachment's file with edited bytes, safely.
* Same format only (changing the extension would break every link). Backup first;
* roll back if any step fails.
*
* @param int $id Attachment ID.
* @param array $upload Validated upload.
* @param string $alt Alt text or null to keep.
* @param string $manifest Edit manifest JSON.
* @return int|WP_Error
*/
public static function replace( $id, $upload, $alt, $manifest ) {
self::require_media();
$blockers = Compat::replace_blockers( $id );
if ( $blockers ) {
return new WP_Error( 'pictureeditor_replace_unsafe', $blockers[0], array( 'status' => 409 ) );
}
$current_mime = get_post_mime_type( $id );
if ( $current_mime !== $upload['mime'] ) {
return new WP_Error(
'pictureeditor_replace_format',
__( 'Replacing must keep the original format so existing links keep working. Choose the original format, or save as a new image.', 'pictureeditor' ),
array( 'status' => 409 )
);
}
$before = self::current_files( $id );
$backup = self::make_backup( $id );
if ( is_wp_error( $backup ) ) {
return $backup;
}
// Write the new pixels where the full-resolution original lives, then let
// WordPress rebuild the scaled copy and every size from it.
$target = $before['original'] && file_exists( $before['original'] ) ? $before['original'] : $before['main'];
if ( ! self::atomic_copy( $upload['tmp'], $target ) ) {
self::restore_record( $id, $backup );
return new WP_Error( 'pictureeditor_write', __( 'The file could not be written. The original was restored.', 'pictureeditor' ), array( 'status' => 500 ) );
}
update_attached_file( $id, $target );
$meta = wp_generate_attachment_metadata( $id, $target );
if ( empty( $meta ) || empty( $meta['width'] ) ) {
self::restore_record( $id, $backup );
return new WP_Error( 'pictureeditor_meta', __( 'WordPress could not process the new image. The original was restored.', 'pictureeditor' ), array( 'status' => 500 ) );
}
wp_update_attachment_metadata( $id, $meta );
self::keep_old_urls( $before, $id );
if ( null !== $alt ) {
update_post_meta( $id, '_wp_attachment_image_alt', sanitize_text_field( $alt ) );
}
self::store_manifest( $id, $manifest );
wp_update_post(
array(
'ID' => $id,
'post_modified' => current_time( 'mysql' ),
)
);
clean_post_cache( $id );
/**
* Fires after an attachment's file was replaced. Cache/CDN plugins can purge here.
*
* @param int $id Attachment ID.
* @param array $backup Backup record.
*/
do_action( 'pictureeditor_replaced', $id, $backup );
return (int) $id;
}
/**
* Restore the most recent backup.
*
* @param int $id Attachment ID.
* @return true|WP_Error
*/
public static function restore_latest( $id ) {
self::require_media();
$backups = get_post_meta( $id, self::BACKUP_META, true );
if ( ! is_array( $backups ) || ! $backups ) {
return new WP_Error( 'pictureeditor_no_backup', __( 'There is no backup to restore.', 'pictureeditor' ), array( 'status' => 404 ) );
}
$record = array_shift( $backups );
if ( ! self::restore_record( $id, $record ) ) {
return new WP_Error( 'pictureeditor_restore', __( 'Some files could not be restored.', 'pictureeditor' ), array( 'status' => 500 ) );
}
update_post_meta( $id, self::BACKUP_META, wp_slash( $backups ) );
do_action( 'pictureeditor_restored', $id, $record );
return true;
}
/**
* Permanently delete every backup of an attachment (e.g. after removing sensitive content).
*
* @param int $id Attachment ID.
* @return int Files deleted.
*/
public static function delete_backups( $id ) {
$n = 0;
foreach ( self::backups( $id ) as $record ) {
foreach ( (array) $record['files'] as $backup ) {
if ( file_exists( $backup ) ) {
wp_delete_file( $backup );
++$n;
}
}
if ( ! empty( $record['dir'] ) && is_dir( $record['dir'] ) ) {
wp_delete_file( $record['dir'] . '/index.php' );
@rmdir( $record['dir'] ); // phpcs:ignore WordPress.PHP.NoSilencedErrors, WordPress.WP.AlternativeFunctions
}
}
delete_post_meta( $id, self::BACKUP_META );
do_action( 'pictureeditor_backups_deleted', $id );
return $n;
}
/**
* Backups available for an attachment (for the UI).
*
* @param int $id Attachment ID.
* @return array[]
*/
public static function backups( $id ) {
$b = get_post_meta( $id, self::BACKUP_META, true );
return is_array( $b ) ? $b : array();
}
}