PluginProbe
Imsanity / 2.9.0
Imsanity v2.9.0
2.9.4 2.9.3 2.9.2 trunk 2.4.3 2.5.0 2.6.0 2.7.0 2.7.2 2.8.0 2.8.1 2.8.2 2.8.3 2.8.4 2.8.5 2.8.6 2.8.7 2.9.0 2.9.1
imsanity / imsanity.php

imsanity.php in Imsanity 2.9.0, at imsanity.php

409 lines 15.3 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * Main file for Imsanity plugin.
4 *
5 * This file includes the core of Imsanity and the top-level image handler.
6 *
7 * @link https://wordpress.org/plugins/imsanity/
8 * @package Imsanity
9 */
10
11 /*
12 Plugin Name: Imsanity
13 Plugin URI: https://wordpress.org/plugins/imsanity/
14 Description: Imsanity stops insanely huge image uploads
15 Author: Exactly WWW
16 Domain Path: /languages
17 Version: 2.9.0
18 Requires at least: 6.6
19 Requires PHP: 7.4
20 Author URI: https://ewww.io/about/
21 License: GPLv3
22 */
23
24 if ( ! defined( 'ABSPATH' ) ) {
25 exit;
26 }
27
28 define( 'IMSANITY_VERSION', '2.9.0' );
29 define( 'IMSANITY_SCHEMA_VERSION', '1.1' );
30
31 define( 'IMSANITY_DEFAULT_MAX_WIDTH', 1920 );
32 define( 'IMSANITY_DEFAULT_MAX_HEIGHT', 1920 );
33 define( 'IMSANITY_DEFAULT_BMP_TO_JPG', true );
34 define( 'IMSANITY_DEFAULT_PNG_TO_JPG', false );
35 define( 'IMSANITY_DEFAULT_QUALITY', 82 );
36 define( 'IMSANITY_DEFAULT_AVIF_QUALITY', 86 );
37 define( 'IMSANITY_DEFAULT_WEBP_QUALITY', 86 );
38
39 define( 'IMSANITY_SOURCE_POST', 1 );
40 define( 'IMSANITY_SOURCE_LIBRARY', 2 );
41 define( 'IMSANITY_SOURCE_OTHER', 4 );
42
43 /**
44 * The full path of the main plugin file.
45 *
46 * @var string IMSANITY_PLUGIN_FILE
47 */
48 define( 'IMSANITY_PLUGIN_FILE', __FILE__ );
49
50 /**
51 * The directory path of the main plugin file.
52 *
53 * @var string IMSANITY_PLUGIN_DIR
54 */
55 define( 'IMSANITY_PLUGIN_DIR', plugin_dir_path( __FILE__ ) );
56
57 /**
58 * The path of the main plugin file, relative to the plugins/ folder.
59 *
60 * @var string IMSANITY_PLUGIN_FILE_REL
61 */
62 define( 'IMSANITY_PLUGIN_FILE_REL', plugin_basename( __FILE__ ) );
63
64 /**
65 * Load translations for Imsanity.
66 */
67 function imsanity_init() {
68 load_plugin_textdomain( 'imsanity', false, dirname( plugin_basename( __FILE__ ) ) . '/languages/' );
69 }
70
71 /**
72 * Import supporting libraries.
73 */
74 require_once plugin_dir_path( __FILE__ ) . 'libs/debug.php';
75 require_once plugin_dir_path( __FILE__ ) . 'libs/utils.php';
76 require_once plugin_dir_path( __FILE__ ) . 'settings.php';
77 require_once plugin_dir_path( __FILE__ ) . 'ajax.php';
78 require_once plugin_dir_path( __FILE__ ) . 'media.php';
79 if ( defined( 'WP_CLI' ) && WP_CLI ) {
80 require_once plugin_dir_path( __FILE__ ) . 'class-imsanity-cli.php';
81 }
82
83 /**
84 * Inspects the request and determines where the upload came from.
85 *
86 * @return IMSANITY_SOURCE_POST | IMSANITY_SOURCE_LIBRARY | IMSANITY_SOURCE_OTHER
87 */
88 function imsanity_get_source() {
89 imsanity_debug( __FUNCTION__ );
90 $id = array_key_exists( 'post_id', $_REQUEST ) ? (int) $_REQUEST['post_id'] : ''; // phpcs:ignore WordPress.Security.NonceVerification
91 $action = ! empty( $_REQUEST['action'] ) ? sanitize_key( $_REQUEST['action'] ) : ''; // phpcs:ignore WordPress.Security.NonceVerification
92 imsanity_debug( "getting source for id=$id and action=$action" );
93
94 // Uncomment this (and remove the trailing .) to temporarily check the full $_SERVER vars.
95 // imsanity_debug( $_SERVER );.
96 $referer = '';
97 if ( ! empty( $_SERVER['HTTP_REFERER'] ) ) {
98 $referer = sanitize_text_field( wp_unslash( $_SERVER['HTTP_REFERER'] ) );
99 imsanity_debug( "http_referer: $referer" );
100 }
101
102 $request_uri = wp_referer_field( false );
103 imsanity_debug( "request URI: $request_uri" );
104
105 // A post_id indicates image is attached to a post.
106 if ( $id > 0 ) {
107 imsanity_debug( 'from a post (id)' );
108 return IMSANITY_SOURCE_POST;
109 }
110
111 // If the referrer is the post editor, that's a good indication the image is attached to a post.
112 if ( false !== strpos( $referer, '/post.php' ) ) {
113 imsanity_debug( 'from a post.php' );
114 return IMSANITY_SOURCE_POST;
115 }
116 // If the referrer is the (new) post editor, that's a good indication the image is attached to a post.
117 if ( false !== strpos( $referer, '/post-new.php' ) ) {
118 imsanity_debug( 'from a new post' );
119 return IMSANITY_SOURCE_POST;
120 }
121
122 // Post_id of 0 is 3.x otherwise use the action parameter.
123 if ( 0 === $id || 'upload-attachment' === $action ) {
124 imsanity_debug( 'from the library' );
125 return IMSANITY_SOURCE_LIBRARY;
126 }
127
128 // We don't know where this one came from but $_REQUEST['_wp_http_referer'] may contain info.
129 imsanity_debug( 'unknown source' );
130 return IMSANITY_SOURCE_OTHER;
131 }
132
133 /**
134 * Given the source, returns the max width/height.
135 *
136 * @example: list( $w, $h ) = imsanity_get_max_width_height( IMSANITY_SOURCE_LIBRARY );
137 * @param int $source One of IMSANITY_SOURCE_POST | IMSANITY_SOURCE_LIBRARY | IMSANITY_SOURCE_OTHER.
138 */
139 function imsanity_get_max_width_height( $source ) {
140 $w = (int) imsanity_get_option( 'imsanity_max_width', IMSANITY_DEFAULT_MAX_WIDTH );
141 $h = (int) imsanity_get_option( 'imsanity_max_height', IMSANITY_DEFAULT_MAX_HEIGHT );
142
143 switch ( $source ) {
144 case IMSANITY_SOURCE_POST:
145 break;
146 case IMSANITY_SOURCE_LIBRARY:
147 $w = (int) imsanity_get_option( 'imsanity_max_width_library', $w );
148 $h = (int) imsanity_get_option( 'imsanity_max_height_library', $h );
149 break;
150 default:
151 $w = (int) imsanity_get_option( 'imsanity_max_width_other', $w );
152 $h = (int) imsanity_get_option( 'imsanity_max_height_other', $h );
153 break;
154 }
155
156 // NOTE: filters MUST return an array of 2 items, or the defaults will be used.
157 return apply_filters( 'imsanity_get_max_width_height', array( $w, $h ), $source );
158 }
159
160 /**
161 * Handler after a file has been uploaded. If the file is an image, check the size
162 * to see if it is too big and, if so, resize and overwrite the original.
163 *
164 * @param Array $params The parameters submitted with the upload.
165 */
166 function imsanity_handle_upload( $params ) {
167 imsanity_debug( __FUNCTION__ );
168
169 if ( empty( $params['file'] ) || empty( $params['type'] ) ) {
170 imsanity_debug( 'missing file or type parameter, skipping' );
171 return $params;
172 }
173
174 // If "noresize" is included in the filename then we will bypass imsanity scaling.
175 if ( strpos( $params['file'], 'noresize' ) !== false ) {
176 imsanity_debug( "skipping {$params['file']}" );
177 return $params;
178 }
179
180 if ( apply_filters( 'imsanity_skip_image', false, $params['file'] ) ) {
181 imsanity_debug( "skipping {$params['file']} per filter" );
182 return $params;
183 }
184
185 // If preferences specify so then we can convert an original bmp or png file into jpg.
186 if ( ( 'image/bmp' === $params['type'] || 'image/x-ms-bmp' === $params['type'] ) && imsanity_get_option( 'imsanity_bmp_to_jpg', IMSANITY_DEFAULT_BMP_TO_JPG ) ) {
187 $params = imsanity_convert_to_jpg( 'bmp', $params );
188 }
189
190 if ( 'image/png' === $params['type'] && imsanity_get_option( 'imsanity_png_to_jpg', IMSANITY_DEFAULT_PNG_TO_JPG ) ) {
191 $params = imsanity_convert_to_jpg( 'png', $params );
192 }
193
194 // Store the path for reference in case $params is modified.
195 $oldpath = $params['file'];
196
197 // Let folks filter the allowed mime-types for resizing.
198 // Also allows conditional support for WebP and AVIF if the server supports it.
199 $allowed_types = apply_filters( 'imsanity_allowed_mimes', array( 'image/png', 'image/gif', 'image/jpeg' ), $oldpath );
200 if ( is_string( $allowed_types ) ) {
201 $allowed_types = array( $allowed_types );
202 } elseif ( ! is_array( $allowed_types ) ) {
203 $allowed_types = array();
204 }
205
206 if (
207 ( ! is_wp_error( $params ) ) &&
208 is_file( $oldpath ) &&
209 is_readable( $oldpath ) &&
210 is_writable( $oldpath ) &&
211 filesize( $oldpath ) > 0 &&
212 in_array( $params['type'], $allowed_types, true )
213 ) {
214 // If the Modern Image Formats plugin is active but fallback mode is disabled, permit conversion to AVIF/WebP during upload by defining IMSANITY_ALLOW_CONVERSION.
215 // Otherwise, no conversion should be allowed at all. The upload handler will still check for conversion and work with it if it happens somehow.
216 if ( ! defined( 'IMSANITY_ALLOW_CONVERSION' ) && function_exists( 'webp_uploads_is_fallback_enabled' ) && ! webp_uploads_is_fallback_enabled() ) {
217 define( 'IMSANITY_ALLOW_CONVERSION', true );
218 }
219
220 // figure out where the upload is coming from.
221 $source = imsanity_get_source();
222
223 $maxw = IMSANITY_DEFAULT_MAX_WIDTH;
224 $maxh = IMSANITY_DEFAULT_MAX_HEIGHT;
225 $max_width_height = imsanity_get_max_width_height( $source );
226 if ( is_array( $max_width_height ) && 2 === count( $max_width_height ) ) {
227 list( $maxw, $maxh ) = $max_width_height;
228 }
229 $maxw = (int) $maxw;
230 $maxh = (int) $maxh;
231
232 $dimensions = getimagesize( $oldpath );
233 if ( is_array( $dimensions ) && count( $dimensions ) >= 2 ) {
234 $oldw = $dimensions[0];
235 $oldh = $dimensions[1];
236 } else {
237 imsanity_debug( "could not get dimensions for $oldpath, skipping" );
238 return $params;
239 }
240
241 if ( ( $oldw > $maxw + 1 && $maxw > 0 ) || ( $oldh > $maxh + 1 && $maxh > 0 ) ) {
242
243 $ftype = imsanity_quick_mimetype( $oldpath );
244 $orientation = imsanity_get_orientation( $oldpath, $ftype );
245 // If we are going to rotate the image 90 degrees during the resize, swap the existing image dimensions.
246 if ( 6 === (int) $orientation || 8 === (int) $orientation ) {
247 $old_oldw = $oldw;
248 $oldw = $oldh;
249 $oldh = $old_oldw;
250 }
251
252 if ( $maxw > 0 && $maxh > 0 && $oldw >= $maxw && $oldh >= $maxh && ( $oldh > $maxh || $oldw > $maxw ) && apply_filters( 'imsanity_crop_image', false ) ) {
253 $neww = $maxw;
254 $newh = $maxh;
255 } else {
256 list( $neww, $newh ) = wp_constrain_dimensions( $oldw, $oldh, $maxw, $maxh );
257 }
258
259 global $ewww_preempt_editor;
260 if ( ! isset( $ewww_preempt_editor ) ) {
261 $ewww_preempt_editor = false;
262 }
263 $original_preempt = $ewww_preempt_editor;
264 $ewww_preempt_editor = true;
265 $resizeresult = imsanity_image_resize( $oldpath, $neww, $newh, apply_filters( 'imsanity_crop_image', false ) );
266 $ewww_preempt_editor = $original_preempt;
267
268 if ( $resizeresult && ! is_wp_error( $resizeresult ) ) {
269 $newpath = $resizeresult;
270 $new_type = $params['type'];
271
272 imsanity_debug( "checking $newpath to see if resize was successful" );
273 if ( is_file( $newpath ) && filesize( $newpath ) < filesize( $oldpath ) ) {
274 imsanity_debug( 'resized image is smaller, replacing original' );
275 // We saved some file space. remove original and replace with resized image.
276 $new_type = imsanity_mimetype( $newpath );
277 unlink( $oldpath );
278 rename( $newpath, $oldpath );
279 if ( $new_type && $new_type !== $params['type'] ) {
280 imsanity_debug( "mimetype changed from {$params['type']} to $new_type" );
281 $params['type'] = $new_type;
282 $params['file'] = imsanity_update_extension( $oldpath, $new_type );
283 if ( $params['file'] !== $oldpath ) {
284 rename( $oldpath, $params['file'] );
285 }
286 $params['url'] = imsanity_update_extension( $params['url'], $new_type );
287 imsanity_debug( "renamed file to match new extension: {$params['file']} / {$params['url']}" );
288 }
289 } elseif ( is_file( $newpath ) ) {
290 imsanity_debug( 'resized image is bigger, discarding' );
291 // The resized image is actually bigger in filesize (most likely due to jpg quality).
292 // Keep the old one and just get rid of the resized image.
293 unlink( $newpath );
294 }
295 } elseif ( false === $resizeresult ) {
296 imsanity_debug( 'resize returned false, unknown error' );
297 return $params;
298 } elseif ( is_wp_error( $resizeresult ) ) {
299 // resize didn't work, likely because the image processing libraries are missing.
300 // remove the old image so we don't leave orphan files hanging around.
301 unlink( $oldpath );
302
303 $params = wp_handle_upload_error(
304 $oldpath,
305 sprintf(
306 /* translators: 1: error message 2: link to support forums */
307 esc_html__( 'Imsanity was unable to resize this image for the following reason: %1$s. If you continue to see this error message, you may need to install missing server components. If you think you have discovered a bug, please report it on the Imsanity support forum: %2$s', 'imsanity' ),
308 $resizeresult->get_error_message(),
309 'https://wordpress.org/support/plugin/imsanity'
310 )
311 );
312 imsanity_debug( 'resize result is wp_error, should have already output error to log' );
313 } else {
314 imsanity_debug( 'unknown resize result, inconceivable!' );
315 return $params;
316 }
317 }
318 }
319 clearstatcache();
320 return $params;
321 }
322
323
324 /**
325 * Read in the image file from the params and then save as a new jpg file.
326 * if successful, remove the original image and alter the return
327 * parameters to return the new jpg instead of the original
328 *
329 * @param string $type Type of the image to be converted: 'bmp' or 'png'.
330 * @param array $params The upload parameters.
331 * @return array altered params
332 */
333 function imsanity_convert_to_jpg( $type, $params ) {
334 imsanity_debug( __FUNCTION__ );
335
336 if ( apply_filters( 'imsanity_disable_convert', false, $type, $params ) ) {
337 imsanity_debug( "skipping conversion for {$params['file']}" );
338 return $params;
339 }
340
341 $img = null;
342
343 if ( 'bmp' === $type ) {
344 if ( ! function_exists( 'imagecreatefrombmp' ) ) {
345 imsanity_debug( 'imagecreatefrombmp does not exist' );
346 return $params;
347 }
348 $img = imagecreatefrombmp( $params['file'] );
349 } elseif ( 'png' === $type ) {
350 // Prevent converting PNG images with alpha/transparency, unless overridden by the user.
351 if ( apply_filters( 'imsanity_skip_alpha', imsanity_has_alpha( $params['file'] ), $params['file'] ) ) {
352 return $params;
353 }
354 if ( ! function_exists( 'imagecreatefrompng' ) ) {
355 return wp_handle_upload_error( $params['file'], esc_html__( 'Imsanity requires the GD library to convert PNG images to JPG', 'imsanity' ) );
356 }
357
358 $input = imagecreatefrompng( $params['file'] );
359 // convert png transparency to white.
360 $img = imagecreatetruecolor( imagesx( $input ), imagesy( $input ) );
361 imagefill( $img, 0, 0, imagecolorallocate( $img, 255, 255, 255 ) );
362 imagealphablending( $img, true );
363 imagecopy( $img, $input, 0, 0, 0, 0, imagesx( $input ), imagesy( $input ) );
364 } else {
365 return wp_handle_upload_error( $params['file'], esc_html__( 'Unknown image type specified in imsanity_convert_to_jpg', 'imsanity' ) );
366 }
367
368 // We need to change the extension from the original to .jpg so we have to ensure it will be a unique filename.
369 $uploads = wp_upload_dir();
370 $oldfilename = wp_basename( $params['file'] );
371 $newfilename = wp_basename( str_ireplace( '.' . $type, '.jpg', $oldfilename ) );
372 $newfilename = wp_unique_filename( $uploads['path'], $newfilename );
373
374 $quality = imsanity_get_option( 'imsanity_quality', IMSANITY_DEFAULT_QUALITY );
375
376 if ( imagejpeg( $img, $uploads['path'] . '/' . $newfilename, $quality ) ) {
377 // Conversion succeeded: remove the original bmp & remap the params.
378 unlink( $params['file'] );
379
380 $params['file'] = $uploads['path'] . '/' . $newfilename;
381 $params['url'] = $uploads['url'] . '/' . $newfilename;
382 $params['type'] = 'image/jpeg';
383 } else {
384 unlink( $params['file'] );
385
386 return wp_handle_upload_error(
387 $oldfilename,
388 /* translators: %s: the image mime type */
389 sprintf( esc_html__( 'Imsanity was unable to process the %s file. If you continue to see this error you may need to disable the conversion option in the Imsanity settings.', 'imsanity' ), $type )
390 );
391 }
392
393 return $params;
394 }
395
396 // Add filter to hook into uploads.
397 add_filter( 'wp_handle_upload', 'imsanity_handle_upload' );
398 // Run necessary actions on init (loading translations mostly).
399 add_action( 'plugins_loaded', 'imsanity_init' );
400
401 // Adds a column to the media library list view to display optimization results.
402 add_filter( 'manage_media_columns', 'imsanity_media_columns' );
403 // Outputs the actual column information for each attachment.
404 add_action( 'manage_media_custom_column', 'imsanity_custom_column', 10, 2 );
405 // Checks for AVIF support and adds it to the allowed mime types.
406 add_filter( 'imsanity_allowed_mimes', 'imsanity_add_avif_support' );
407 // Checks for WebP support and adds it to the allowed mime types.
408 add_filter( 'imsanity_allowed_mimes', 'imsanity_add_webp_support' );
409