| 1 |
<?php |
| 2 |
// Exit if accessed directly. |
| 3 |
if (!defined('ABSPATH')) { |
| 4 |
exit; |
| 5 |
} |
| 6 |
|
| 7 |
add_action('wp_ajax_squeeze_update_attachment', 'squeeze_update_attachment'); |
| 8 |
/** |
| 9 |
* Update attachment with compressed image |
| 10 |
* https://gist.github.com/cyberwani/ad5452b040001878d692c3165836ebff |
| 11 |
*/ |
| 12 |
function squeeze_update_attachment() { |
| 13 |
check_ajax_referer( 'squeeze-nonce', '_ajax_nonce' ); |
| 14 |
if (!current_user_can('upload_files')) { |
| 15 |
wp_send_json_error('❌ '.__('You do not have permission to upload files', 'squeeze')); |
| 16 |
} |
| 17 |
if (isset($_POST["base64"]) && !empty($_POST["base64"])) { |
| 18 |
|
| 19 |
$base64 = sanitize_text_field($_POST["base64"]); |
| 20 |
$sizes = $_POST["base64Sizes"]; |
| 21 |
$file_format = sanitize_text_field($_POST["format"]); |
| 22 |
$filename = sanitize_text_field($_POST["filename"]); |
| 23 |
$extension = pathinfo($filename, PATHINFO_EXTENSION); |
| 24 |
|
| 25 |
if (!in_array($extension, explode(',', SQUEEZE_ALLOWED_IMAGE_FORMATS))) { |
| 26 |
wp_send_json_error('❌ '.__('Invalid image format', 'squeeze')); |
| 27 |
} |
| 28 |
|
| 29 |
$attach_id = (int) $_POST["attachmentID"]; |
| 30 |
$meta_data = wp_get_attachment_metadata($attach_id); |
| 31 |
$url = sanitize_url($_POST["url"]); |
| 32 |
$process = sanitize_text_field($_POST["process"]); // process: all, uncompressed, path |
| 33 |
|
| 34 |
$options = get_option( 'squeeze_options' ); |
| 35 |
$is_backup_original = isset($options['backup_original']) ? $options['backup_original'] : squeeze_get_default_value('backup_original'); |
| 36 |
|
| 37 |
// Upload dir. |
| 38 |
// TBD: fix if non-latin characters in filename |
| 39 |
if ($attach_id > 0) { |
| 40 |
$upload_dir = str_replace($filename, "", wp_get_original_image_path($attach_id)); // get upload dir from attachment path |
| 41 |
} else { |
| 42 |
$upload_url = str_replace($filename, "", $url); |
| 43 |
$upload_dir = str_replace(home_url(), ABSPATH, $upload_url); |
| 44 |
} |
| 45 |
$upload_path = str_replace('/', DIRECTORY_SEPARATOR, $upload_dir) . DIRECTORY_SEPARATOR; |
| 46 |
|
| 47 |
$img = str_replace('data:image/'.$file_format.';base64,', '', $base64); |
| 48 |
$img = str_replace(' ', '+', $img); |
| 49 |
$decoded = base64_decode($img); |
| 50 |
|
| 51 |
if ($is_backup_original && $process !== 'path') { |
| 52 |
// backup original |
| 53 |
// TBD: check if .bak already in filename |
| 54 |
$backup_filename = preg_replace("/(\.(?!.*\.))/", '.bak.', $filename); // add .bak. before extension |
| 55 |
|
| 56 |
if ( !file_exists($upload_path . $backup_filename) ) { |
| 57 |
$upload_backup_file = copy($upload_path . $filename, $upload_path . $backup_filename); |
| 58 |
|
| 59 |
if (!$upload_backup_file) { |
| 60 |
wp_send_json_error('❌ '.__('Backup original image failed', 'squeeze') . ': '. $upload_path . $backup_filename); |
| 61 |
} |
| 62 |
} |
| 63 |
} |
| 64 |
|
| 65 |
// Save the image in the uploads directory. |
| 66 |
|
| 67 |
global $wp_filesystem; |
| 68 |
// Initialize the WP filesystem, no more using 'file-put-contents' function |
| 69 |
if (empty($wp_filesystem)) { |
| 70 |
require_once (ABSPATH . '/wp-admin/includes/file.php'); |
| 71 |
WP_Filesystem(); |
| 72 |
} |
| 73 |
|
| 74 |
$sizes['original']['original_size'] = filesize($upload_path . $filename); |
| 75 |
$upload_file = $wp_filesystem->put_contents($upload_path . $filename, $decoded); |
| 76 |
$sizes['original']['compressed_size'] = strlen($decoded); |
| 77 |
|
| 78 |
if (!$upload_file) { |
| 79 |
wp_send_json_error('❌ '.__('Upload image failed', 'squeeze'). ': '. $upload_path . '::' . $filename . '::' . $upload_dir . '::' . $upload_url); |
| 80 |
} |
| 81 |
|
| 82 |
// upload thumbnails |
| 83 |
if ($process !== 'path') { |
| 84 |
update_post_meta($attach_id, "squeeze_is_compressed", true); |
| 85 |
|
| 86 |
foreach ($sizes as $size_name => $size_data) { |
| 87 |
if ($size_name === 'original') { |
| 88 |
continue; |
| 89 |
} |
| 90 |
$size_base64 = sanitize_text_field($size_data['base64']); |
| 91 |
$size_base64 = str_replace('data:image/'.$file_format.';base64,', '', $size_base64); |
| 92 |
$size_base64 = str_replace(' ', '+', $size_base64); |
| 93 |
$size_decoded = base64_decode($size_base64); |
| 94 |
$size_filename = basename(sanitize_url($size_data['url'])); |
| 95 |
|
| 96 |
if ($size_name === 'full') { |
| 97 |
$size_name = 'scaled'; |
| 98 |
unset($sizes['full']); |
| 99 |
} |
| 100 |
|
| 101 |
$sizes[$size_name]['original_size'] = filesize($upload_path . $size_filename); |
| 102 |
|
| 103 |
$upload_size_file = $wp_filesystem->put_contents($upload_path . $size_filename, $size_decoded); |
| 104 |
|
| 105 |
if (!$upload_size_file) { |
| 106 |
wp_send_json_error('❌ '.__('Attachment not updated', 'squeeze'). ': ' . $upload_path . $size_filename); |
| 107 |
} else { |
| 108 |
$sizes[$size_name]['compressed_size'] = strlen($size_decoded); |
| 109 |
} |
| 110 |
} |
| 111 |
|
| 112 |
$response_msg = squeeze_get_comparison_table($sizes); //$filename. ',<br>' . rtrim($response_msg, ',<br> '); |
| 113 |
$response_msg = '<strong>� |
| 114 |
'.__('Squeezed successfully', 'squeeze') . ':</strong> ' . $response_msg; |
| 115 |
|
| 116 |
wp_send_json_success($response_msg); |
| 117 |
} else { |
| 118 |
wp_send_json_success('� |
| 119 |
'.__('Squeezed successfully', 'squeeze')); |
| 120 |
} |
| 121 |
|
| 122 |
} |
| 123 |
wp_die(); |
| 124 |
} |
| 125 |
|
| 126 |
//add_filter('wp_redirect', 'squeeze_single_upload_redirect', 10, 2); |
| 127 |
/** |
| 128 |
* TBD: Handle single upload |
| 129 |
* Redirect to compressing image after single upload |
| 130 |
* |
| 131 |
* @param string $location |
| 132 |
* @param int $status |
| 133 |
* @return string |
| 134 |
*/ |
| 135 |
function squeeze_single_upload_redirect($location, $status) { |
| 136 |
if (is_admin() && $location === admin_url('upload.php')) { |
| 137 |
//print_r($_REQUEST); |
| 138 |
print_r($_POST); |
| 139 |
print_r($_FILES); |
| 140 |
$location = '';//admin_url('upload.php?page=squeeze&attachmentID=123'); |
| 141 |
} |
| 142 |
return $location; |
| 143 |
} |
| 144 |
|
| 145 |
/** |
| 146 |
* Get comparison table of original and compressed image |
| 147 |
*/ |
| 148 |
function squeeze_get_comparison_table($sizes) { |
| 149 |
$table = '<style>.squeeze-comparison-table table tr {display: table-row;}</style>'; |
| 150 |
$table .= '<div class="squeeze-comparison-table">'; |
| 151 |
$table .= '<table class="wp-list-table widefat striped">'; |
| 152 |
$table .= '<thead><tr><th>'.__('Size', 'squeeze').'</th><th>'.__('Original', 'squeeze').'</th><th>'.__('Squeezed', 'squeeze').'</th><th>'.__('Savings', 'squeeze').'</th></tr></thead>'; |
| 153 |
$table .= '<tbody>'; |
| 154 |
|
| 155 |
foreach ($sizes as $size_name => $size_data) { |
| 156 |
$size_filename = basename(sanitize_url($size_data['url'])); |
| 157 |
$original_size = $size_data['original_size']; |
| 158 |
$compressed_size = $size_data['compressed_size']; |
| 159 |
$savings = $original_size - $compressed_size; |
| 160 |
$savings_percent = round(($savings / $original_size) * 100, 2); |
| 161 |
|
| 162 |
$table .= '<tr>'; |
| 163 |
$table .= '<td><strong>'.$size_name.'</strong></td>'; |
| 164 |
$table .= '<td>'.size_format($original_size, 0).'</td>'; |
| 165 |
$table .= '<td>'.size_format($compressed_size, 0).'</td>'; |
| 166 |
$table .= '<td>'.$savings_percent.'%</td>'; |
| 167 |
$table .= '</tr>'; |
| 168 |
} |
| 169 |
|
| 170 |
$table .= '</tbody></table></div>'; |
| 171 |
|
| 172 |
return $table; |
| 173 |
} |
| 174 |
|
| 175 |
add_action('wp_ajax_squeeze_restore_attachment', 'squeeze_restore_attachment'); |
| 176 |
/** |
| 177 |
* Restore original attachment |
| 178 |
*/ |
| 179 |
function squeeze_restore_attachment() { |
| 180 |
check_ajax_referer( 'squeeze-nonce', '_ajax_nonce' ); |
| 181 |
if (isset($_POST["attachmentID"]) && !empty($_POST["attachmentID"]) && wp_get_attachment_url($_POST["attachmentID"])) { |
| 182 |
$attach_id = (int) $_POST["attachmentID"]; |
| 183 |
$can_restore = squeeze_can_restore($attach_id); |
| 184 |
|
| 185 |
if ($can_restore) { |
| 186 |
$is_restore_attachment = _squeeze_restore_attachment($attach_id); |
| 187 |
|
| 188 |
if ($is_restore_attachment) { |
| 189 |
wp_send_json_success('� |
| 190 |
'.__('Restored successfully', 'squeeze')); |
| 191 |
} else { |
| 192 |
wp_send_json_error('❌ '.__('Attachment not restored', 'squeeze')); |
| 193 |
} |
| 194 |
|
| 195 |
} |
| 196 |
} else { |
| 197 |
wp_send_json_error('❌ '.__('Attachment not found', 'squeeze')); |
| 198 |
} |
| 199 |
wp_die(); |
| 200 |
} |
| 201 |
|
| 202 |
add_action('wp_ajax_squeeze_get_attachment', 'squeeze_get_attachment'); |
| 203 |
/** |
| 204 |
* Get attachment data |
| 205 |
*/ |
| 206 |
function squeeze_get_attachment() { |
| 207 |
check_ajax_referer( 'squeeze-nonce', '_ajax_nonce' ); |
| 208 |
|
| 209 |
if (isset($_POST["attachmentID"]) && !empty($_POST["attachmentID"]) && wp_get_attachment_url($_POST["attachmentID"])) { |
| 210 |
$attach_id = (int) $_POST["attachmentID"]; |
| 211 |
$sizes = wp_get_attachment_metadata($attach_id); |
| 212 |
$sizes = $sizes['sizes']; |
| 213 |
$full_image = wp_get_attachment_image_src($attach_id, 'full'); |
| 214 |
$sizes['full'] = array( |
| 215 |
'url' => $full_image[0], |
| 216 |
'width' => $full_image[1], |
| 217 |
'height' => $full_image[2], |
| 218 |
); |
| 219 |
foreach ($sizes as $size_name => $size_data) { |
| 220 |
$sizes[$size_name]['url'] = wp_get_attachment_image_url($attach_id, $size_name); |
| 221 |
} |
| 222 |
$attach_data = array( |
| 223 |
'id' => $attach_id, |
| 224 |
'url' => wp_get_original_image_url($attach_id), //TBD |
| 225 |
'mime' => get_post_mime_type($attach_id), |
| 226 |
'name' => get_the_title($attach_id), |
| 227 |
'filename' => basename( wp_get_original_image_path( $attach_id ) ), |
| 228 |
'sizes' => $sizes, |
| 229 |
); |
| 230 |
|
| 231 |
wp_send_json_success($attach_data); |
| 232 |
|
| 233 |
} else { |
| 234 |
wp_send_json_error('❌ '.__('Attachment not found', 'squeeze')); |
| 235 |
} |
| 236 |
|
| 237 |
wp_die(); |
| 238 |
} |
| 239 |
|
| 240 |
add_action('wp_ajax_squeeze_get_attachment_by_path', 'squeeze_get_attachment_by_path'); |
| 241 |
/** |
| 242 |
* Get attachment data by path |
| 243 |
*/ |
| 244 |
function squeeze_get_attachment_by_path() { |
| 245 |
check_ajax_referer( 'squeeze-nonce', '_ajax_nonce' ); |
| 246 |
|
| 247 |
if (isset($_POST["path"]) && !empty($_POST["path"])) { |
| 248 |
$path = sanitize_text_field($_POST["path"]); |
| 249 |
$images = glob( ABSPATH . $path . '*.{'.SQUEEZE_ALLOWED_IMAGE_FORMATS.'}', GLOB_BRACE); |
| 250 |
$attach_data = array(); |
| 251 |
|
| 252 |
if (empty($images)) { |
| 253 |
wp_send_json_error('❌ '.__('Images not found in the path', 'squeeze') . ' ' . $path); |
| 254 |
} |
| 255 |
|
| 256 |
foreach ($images as $image) { |
| 257 |
$attach_id = attachment_url_to_postid($image); |
| 258 |
$attach_mime = image_type_to_mime_type(exif_imagetype($image)); |
| 259 |
$attach_url = str_replace(ABSPATH, home_url(), $image); |
| 260 |
$attach_name = pathinfo($image, PATHINFO_FILENAME); |
| 261 |
$attach_data[] = array( |
| 262 |
'id' => $attach_id, |
| 263 |
'url' => $attach_url, |
| 264 |
'mime' => $attach_mime, |
| 265 |
'name' => $attach_name, |
| 266 |
'filename' => basename( $image ), |
| 267 |
); |
| 268 |
} |
| 269 |
|
| 270 |
wp_send_json_success($attach_data); |
| 271 |
|
| 272 |
} else { |
| 273 |
wp_send_json_error('❌ '.__('Path not found', 'squeeze')); |
| 274 |
} |
| 275 |
|
| 276 |
wp_die(); |
| 277 |
} |
| 278 |
|
| 279 |
/** |
| 280 |
* Check if attachment can be restored |
| 281 |
* |
| 282 |
* @param int $attach_id |
| 283 |
* @return bool |
| 284 |
*/ |
| 285 |
function squeeze_can_restore($attach_id) { |
| 286 |
$original_img_path = wp_get_original_image_path((int) $attach_id); |
| 287 |
$backup_img_path = preg_replace("/(\.(?!.*\.))/", '.bak.', $original_img_path); |
| 288 |
$can_restore = file_exists($backup_img_path); |
| 289 |
|
| 290 |
return $can_restore; |
| 291 |
} |
| 292 |
|
| 293 |
/** |
| 294 |
* Handle restore attachment |
| 295 |
* Internal function |
| 296 |
* |
| 297 |
* @param int $attach_id |
| 298 |
* @return bool |
| 299 |
*/ |
| 300 |
function _squeeze_restore_attachment($attach_id, $is_bulk = false) { |
| 301 |
$original_img_path = wp_get_original_image_path($attach_id); |
| 302 |
$backup_img_path = preg_replace("/(\.(?!.*\.))/", '.bak.', $original_img_path); |
| 303 |
$upload_restore_file = copy($backup_img_path, $original_img_path); |
| 304 |
|
| 305 |
if (!$upload_restore_file) { |
| 306 |
if ($is_bulk) { |
| 307 |
wp_die('❌ '.__('Restore original image failed', 'squeeze')); |
| 308 |
} else { |
| 309 |
wp_send_json_error('❌ '.__('Restore original image failed', 'squeeze')); |
| 310 |
} |
| 311 |
return false; |
| 312 |
} |
| 313 |
|
| 314 |
// create thumbnails from original image |
| 315 |
$attach_data = wp_create_image_subsizes($original_img_path, $attach_id); |
| 316 |
|
| 317 |
$is_update_attachment = delete_post_meta($attach_id, "squeeze_is_compressed"); |
| 318 |
|
| 319 |
if ($is_update_attachment) { |
| 320 |
wp_delete_file($backup_img_path); // delete backup file |
| 321 |
return true; |
| 322 |
} else { |
| 323 |
return false; |
| 324 |
} |
| 325 |
} |
| 326 |
|
| 327 |
add_action('delete_attachment', 'squeeze_delete_attachment'); |
| 328 |
/** |
| 329 |
* Delete backup image when attachment is deleted |
| 330 |
* |
| 331 |
* @param int $attach_id |
| 332 |
*/ |
| 333 |
function squeeze_delete_attachment($attach_id) { |
| 334 |
$original_img_path = wp_get_original_image_path((int) $attach_id); |
| 335 |
$backup_img_path = preg_replace("/(\.(?!.*\.))/", '.bak.', $original_img_path); |
| 336 |
|
| 337 |
if (file_exists($backup_img_path)) { |
| 338 |
wp_delete_file($backup_img_path); |
| 339 |
} |
| 340 |
} |
| 341 |
|
| 342 |
add_filter('bulk_actions-upload', 'squeeze_bulk_actions'); |
| 343 |
/** |
| 344 |
* Add bulk action to media library |
| 345 |
* |
| 346 |
* @param array $actions |
| 347 |
* @return array |
| 348 |
*/ |
| 349 |
function squeeze_bulk_actions($actions) { |
| 350 |
$actions['squeeze_bulk_restore'] = __('Restore Original Image', 'squeeze'); |
| 351 |
$actions['squeeze_bulk_compress'] = __('Squeeze Image', 'squeeze'); |
| 352 |
return $actions; |
| 353 |
} |
| 354 |
|
| 355 |
add_filter('handle_bulk_actions-upload', 'squeeze_handle_bulk_actions', 10, 3); |
| 356 |
/** |
| 357 |
* Handle bulk action |
| 358 |
* |
| 359 |
* @param string $redirect_to |
| 360 |
* @param string $doaction |
| 361 |
* @param array $post_ids |
| 362 |
* @return string |
| 363 |
*/ |
| 364 |
function squeeze_handle_bulk_actions($redirect_to, $doaction, $post_ids) { |
| 365 |
if ($doaction === 'squeeze_bulk_restore') { |
| 366 |
foreach ($post_ids as $post_id) { |
| 367 |
$can_restore = squeeze_can_restore($post_id); |
| 368 |
|
| 369 |
if ($can_restore) { |
| 370 |
$is_restore_attachment = _squeeze_restore_attachment($post_id, true); |
| 371 |
} |
| 372 |
} |
| 373 |
|
| 374 |
$redirect_to = add_query_arg('squeeze_bulk_restored', count($post_ids), $redirect_to); |
| 375 |
} |
| 376 |
|
| 377 |
if ($doaction === 'squeeze_bulk_compress') { |
| 378 |
foreach ($post_ids as $post_id) { |
| 379 |
$redirect_to = add_query_arg('squeeze_bulk_compressed', count($post_ids), $redirect_to); |
| 380 |
} |
| 381 |
} |
| 382 |
|
| 383 |
|
| 384 |
return $redirect_to; |
| 385 |
} |
| 386 |
|
| 387 |
add_action('admin_notices', 'squeeze_bulk_action_admin_notice'); |
| 388 |
/** |
| 389 |
* Display admin notice after bulk action |
| 390 |
*/ |
| 391 |
function squeeze_bulk_action_admin_notice() { |
| 392 |
if (!empty($_REQUEST['squeeze_bulk_restored'])) { |
| 393 |
$message = sprintf( |
| 394 |
_n( |
| 395 |
'Attachment restored.', |
| 396 |
'%d attachments restored.', |
| 397 |
$_REQUEST['squeeze_bulk_restored'], |
| 398 |
'squeeze' |
| 399 |
), |
| 400 |
number_format_i18n($_REQUEST['squeeze_bulk_restored']) |
| 401 |
); |
| 402 |
printf('<div class="notice notice-success is-dismissible"><p>%s</p></div>', $message); |
| 403 |
} |
| 404 |
if (!empty($_REQUEST['squeeze_bulk_compressed'])) { |
| 405 |
$message = sprintf( |
| 406 |
_n( |
| 407 |
'Attachment squeezed.', |
| 408 |
'%d attachments squeezed.', |
| 409 |
$_REQUEST['squeeze_bulk_compressed'], |
| 410 |
'squeeze' |
| 411 |
), |
| 412 |
number_format_i18n($_REQUEST['squeeze_bulk_compressed']) |
| 413 |
); |
| 414 |
printf('<div class="notice notice-success is-dismissible"><p>%s</p></div>', $message); |
| 415 |
} |
| 416 |
} |
| 417 |
|
| 418 |
add_filter('image_size_names_choose', 'squeeze_custom_image_sizes'); |
| 419 |
/** |
| 420 |
* Add custom image sizes to media library |
| 421 |
* |
| 422 |
* @param array $sizes |
| 423 |
* @return array |
| 424 |
*/ |
| 425 |
function squeeze_custom_image_sizes($sizes) { |
| 426 |
$available_sizes = wp_get_registered_image_subsizes(); |
| 427 |
|
| 428 |
foreach ($available_sizes as $size_name => $size_data) { |
| 429 |
$sizes[$size_name] = $size_data['width'] . 'x' . $size_data['height']; |
| 430 |
} |
| 431 |
|
| 432 |
return $sizes; |
| 433 |
} |