PastedIn
';
}
public static function formats() {
$allowed = get_allowed_mime_types();
$result = array();
foreach ( array( 'webp' => 'image/webp', 'avif' => 'image/avif', 'jpg' => 'image/jpeg', 'png' => 'image/png' ) as $ext => $mime ) {
$result[ $ext ] = in_array( $mime, $allowed, true ) && wp_image_editor_supports( array( 'mime_type' => $mime, 'methods' => array( 'save' ) ) );
}
return $result;
}
public static function assets() {
if ( ! current_user_can( 'upload_files' ) ) {
return;
}
wp_enqueue_style( 'pastedin', plugins_url( 'assets/pastedin.css', __FILE__ ), array(), self::VERSION );
wp_enqueue_script( 'pastedin', plugins_url( 'assets/pastedin.js', __FILE__ ), array( 'media-views', 'wp-i18n' ), self::VERSION, true );
wp_set_script_translations( 'pastedin', 'pastedin' );
wp_localize_script( 'pastedin', 'pastedInConfig', array(
'ajaxUrl' => admin_url( 'admin-ajax.php' ),
'nonce' => wp_create_nonce( 'pastedin_save' ),
'formats' => self::formats(),
'maxBytes' => min( wp_max_upload_size(), 20 * MB_IN_BYTES ),
'maxPixels' => self::PIXEL_LIMIT,
'postId' => isset( $GLOBALS['post']->ID ) ? (int) $GLOBALS['post']->ID : 0,
'logoUrl' => plugins_url( 'assets/pastedin-logo.png', __FILE__ ),
) );
}
private static function fail( $message, $status = 400 ) {
wp_send_json_error( array( 'message' => $message ), $status );
}
public static function save() {
if ( ! current_user_can( 'upload_files' ) ) {
self::fail( __( 'You do not have permission to upload images.', 'pastedin' ), 403 );
}
if ( ! check_ajax_referer( 'pastedin_save', 'nonce', false ) ) {
self::fail( __( 'Your session has expired. Reload the page and try again.', 'pastedin' ), 403 );
}
$format = isset( $_POST['format'] ) && is_string( $_POST['format'] ) ? sanitize_key( wp_unslash( $_POST['format'] ) ) : '';
$post_id = isset( $_POST['post_id'] ) && is_string( $_POST['post_id'] ) ? absint( wp_unslash( $_POST['post_id'] ) ) : 0;
$quality = isset( $_POST['quality'] ) && is_string( $_POST['quality'] ) ? max( 1, min( 100, absint( wp_unslash( $_POST['quality'] ) ) ) ) : 85;
$max_width = isset( $_POST['max_width'] ) && is_string( $_POST['max_width'] ) ? min( 8192, absint( wp_unslash( $_POST['max_width'] ) ) ) : 0;
$filename = isset( $_POST['filename'] ) && is_string( $_POST['filename'] ) ? sanitize_file_name( wp_unslash( $_POST['filename'] ) ) : '';
$title = isset( $_POST['title'] ) && is_string( $_POST['title'] ) ? sanitize_text_field( wp_unslash( $_POST['title'] ) ) : '';
$caption = isset( $_POST['caption'] ) && is_string( $_POST['caption'] ) ? sanitize_textarea_field( wp_unslash( $_POST['caption'] ) ) : '';
$description = isset( $_POST['description'] ) && is_string( $_POST['description'] ) ? sanitize_textarea_field( wp_unslash( $_POST['description'] ) ) : '';
$alt = isset( $_POST['alt'] ) && is_string( $_POST['alt'] ) ? sanitize_text_field( wp_unslash( $_POST['alt'] ) ) : '';
require_once ABSPATH . 'wp-admin/includes/file.php';
require_once ABSPATH . 'wp-admin/includes/image.php';
require_once ABSPATH . 'wp-admin/includes/media.php';
$types = array( 'webp' => 'image/webp', 'avif' => 'image/avif', 'jpg' => 'image/jpeg', 'png' => 'image/png' );
$formats = self::formats();
if ( ! isset( $types[ $format ] ) || empty( $formats[ $format ] ) ) {
self::fail( __( 'This output format is not supported by this server or is not allowed on this site.', 'pastedin' ) );
}
// phpcs:ignore WordPress.Security.NonceVerification.Missing,WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Nonce is checked above; uploaded file bytes and MIME are validated below.
if ( empty( $_FILES['image'] ) || ! is_array( $_FILES['image'] ) ) {
self::fail( __( 'No image was received. Large requests may exceed the server upload limit.', 'pastedin' ) );
}
// phpcs:ignore WordPress.Security.NonceVerification.Missing,WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Nonce is checked above; uploaded file bytes and MIME are validated below.
$file = $_FILES['image'];
if ( ! isset( $file['error'], $file['tmp_name'] ) || ! is_scalar( $file['error'] ) || UPLOAD_ERR_OK !== (int) $file['error'] || ! is_string( $file['tmp_name'] ) || ! is_uploaded_file( $file['tmp_name'] ) ) {
self::fail( __( 'The upload failed. Check the file size and try again.', 'pastedin' ) );
}
$source = $file['tmp_name'];
$bytes = filesize( $source );
if ( ! $bytes || $bytes > min( wp_max_upload_size(), 20 * MB_IN_BYTES ) ) {
self::fail( __( 'The image exceeds the allowed upload size.', 'pastedin' ) );
}
$mime = wp_get_image_mime( $source );
if ( ! in_array( $mime, array_values( $types ), true ) || ! in_array( $mime, get_allowed_mime_types(), true ) ) {
self::fail( __( 'Paste a PNG, JPEG, WebP or AVIF image. Links, HTML and SVG are not accepted.', 'pastedin' ) );
}
$size = wp_getimagesize( $source );
if ( ! $size || $size[0] < 1 || $size[1] < 1 || $size[0] > self::PIXEL_LIMIT / $size[1] ) {
self::fail( __( 'The image is invalid or exceeds 40 megapixels.', 'pastedin' ) );
}
// WordPress runs the sideload prefilter during media_handle_sideload().
// Do not trigger it here as well: other plugins may have side effects.
if ( $post_id && ( ! get_post( $post_id ) || ! current_user_can( 'edit_post', $post_id ) ) ) {
self::fail( __( 'You cannot attach an image to this post.', 'pastedin' ), 403 );
}
$editor = wp_get_image_editor( $source );
if ( is_wp_error( $editor ) ) {
self::fail( __( 'The server could not open this image. Try copying it as PNG.', 'pastedin' ) );
}
if ( ! $editor->supports_mime_type( $types[ $format ] ) ) {
self::fail( __( 'The image editor handling this image cannot create the selected format.', 'pastedin' ) );
}
$rotation = $editor->maybe_exif_rotate();
if ( is_wp_error( $rotation ) ) {
self::fail( __( 'The image orientation could not be processed.', 'pastedin' ) );
}
if ( $max_width ) {
$current = $editor->get_size();
if ( $current['width'] > $max_width ) {
$resized = $editor->resize( $max_width, null, false );
if ( is_wp_error( $resized ) ) {
self::fail( __( 'The image could not be resized.', 'pastedin' ) );
}
}
}
$set_quality = $editor->set_quality( $quality );
if ( is_wp_error( $set_quality ) ) {
self::fail( __( 'The selected quality could not be applied.', 'pastedin' ) );
}
$name = $filename;
$name = preg_replace( '/\.(webp|avif|jpe?g|png)$/i', '', $name );
$name = trim( $name, '.- ' );
if ( '' === $name ) {
$name = 'pastedin-' . current_time( 'Ymd-His' );
}
$name = wp_check_invalid_utf8( substr( $name, 0, 150 ), true );
if ( '' === $name ) {
$name = 'pastedin-' . current_time( 'Ymd-His' );
}
// Encode into a temporary file. Nothing enters uploads before validation.
$temp = wp_tempnam( 'pastedin' );
if ( ! $temp ) {
self::fail( __( 'A temporary file could not be created.', 'pastedin' ), 500 );
}
wp_delete_file( $temp );
$target = $temp . '.' . $format;
// WordPress can reset image quality when switching the output MIME type.
// Scope this override strictly to the current save and remove it even on failure.
$target_mime = $types[ $format ];
$quality_override = static function ( $default_quality, $output_mime ) use ( $target_mime, $quality ) {
return $output_mime === $target_mime ? $quality : $default_quality;
};
add_filter( 'wp_editor_set_quality', $quality_override, PHP_INT_MAX, 2 );
try {
$saved = $editor->save( $target, $target_mime );
} catch ( Throwable $error ) {
$saved = new WP_Error( 'pastedin_conversion_failed', __( 'Conversion failed. Try another format.', 'pastedin' ) );
} finally {
remove_filter( 'wp_editor_set_quality', $quality_override, PHP_INT_MAX );
unset( $editor );
}
if ( is_wp_error( $saved ) ) {
wp_delete_file( $target );
self::fail( __( 'Conversion failed. Try another format.', 'pastedin' ), 500 );
}
$converted = $saved['path'];
if ( wp_get_image_mime( $converted ) !== $types[ $format ] ) {
wp_delete_file( $converted );
wp_delete_file( $target );
self::fail( __( 'Another image tool changed the requested format. No attachment was created.', 'pastedin' ) );
}
if ( filesize( $converted ) > min( wp_max_upload_size(), 20 * MB_IN_BYTES ) || ( is_multisite() && ! is_upload_space_available() ) || ( is_multisite() && filesize( $converted ) > get_upload_space_available() ) ) {
wp_delete_file( $converted );
self::fail( __( 'The converted file exceeds the site upload limit or storage quota.', 'pastedin' ) );
}
if ( '' === $title ) {
$title = str_replace( array( '-', '_' ), ' ', $name );
}
$attachment = media_handle_sideload( array(
'name' => $name . '.' . $format,
'tmp_name' => $converted,
'type' => $types[ $format ],
'error' => 0,
'size' => filesize( $converted ),
), $post_id, null, array(
'post_title' => $title,
'post_excerpt' => $caption,
'post_content' => $description,
) );
// On failure media_handle_sideload may leave its temporary input behind.
wp_delete_file( $converted );
if ( $target !== $converted ) {
wp_delete_file( $target );
}
if ( is_wp_error( $attachment ) ) {
self::fail( $attachment->get_error_message(), 500 );
}
update_post_meta( $attachment, '_wp_attachment_image_alt', $alt );
update_post_meta( $attachment, '_pastedin_version', self::VERSION );
wp_send_json_success( array( 'attachment' => wp_prepare_attachment_for_js( $attachment ), 'editUrl' => get_edit_post_link( $attachment, 'raw' ) ) );
}
}
// An original idea by Martin Blais, mbim.ca.
PastedIn::boot();