PluginProbe
Imsanity / 2.9.1
Imsanity v2.9.1
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.1, at imsanity.php

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