PluginProbe
Imsanity / 2.8.6
Imsanity v2.8.6
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.8.6, at imsanity.php

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