PluginProbe
WP-Optimize – Cache, Compress images, Minify & Clean database to boost page speed & performance / 3.5.0
WP-Optimize – Cache, Compress images, Minify & Clean database to boost page speed & performance v3.5.0
4.7.0 4.6.1 4.6.0 4.5.5 4.5.4 4.5.3 4.5.2 3.2.20 3.2.21 3.2.22 3.2.3 3.2.5 3.2.6 3.2.7 3.2.9 3.3.0 3.3.1 3.3.2 3.4.0 3.4.1 3.4.2 3.5.0 3.6.0 3.7.0 3.7.1 All 111 releases
wp-optimize / js / wposmush.js

wposmush.js in WP-Optimize – Cache, Compress images, Minify & Clean database to boost page speed & performance 3.5.0, at js/wposmush.js

1,518 lines 46.6 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 jQuery(function($) {
2 WP_Optimize_Smush = WP_Optimize_Smush();
3 });
4
5 var WP_Optimize_Smush = function() {
6
7 var $ = jQuery;
8
9 var heartbeat = WP_Optimize_Heartbeat();
10 var heartbeat_agents = [];
11
12 var last_ui_update_agent_uid = null;
13
14 /**
15 * Variables for smushing.
16 */
17 var smush_nav_tab = $('#wp-optimize-images-nav-tab-smush'),
18 smush_images_grid = $('#wpo_smush_images_grid'),
19 smush_images_optimization_message = $('#smush_info_images'),
20 smush_images_pending_tasks_container = $('#wpo_smush_images_pending_tasks_container'),
21 smush_images_pending_tasks_btn = $('#wpo_smush_images_pending_tasks_button'),
22 smush_images_refresh_btn = $('#wpo_smush_images_refresh'),
23 smush_images_select_all_btn = $('#wpo_smush_images_select_all'),
24 smush_images_select_none_btn = $('#wpo_smush_images_select_none'),
25 smush_images_stats_clear_btn = $('#wpo_smush_clear_stats_btn'),
26 smush_selected_images_btn = $('#wpo_smush_images_btn'),
27 smush_mark_as_compressed_btn = $('#wpo_smush_mark_as_compressed'),
28 smush_single_image_btn = $('.wpo_smush_single_image .button'),
29 smush_single_restore_btn = $('.wpo_restore_single_image .button'),
30 convert_to_webp_btn = $('.wpo_smush.column-wpo_smush .convert-to-webp');
31 smush_mark_all_as_uncompressed_btn = $('#wpo_smush_mark_all_as_uncompressed_btn'),
32 restore_all_compressed_images_btn = $('#wpo_smush_restore_all_compressed_images_btn'),
33 smush_view_logs_btn = $('.wpo_smush_get_logs'),
34 smush_delete_backup_images_btn = $('#wpo_smush_delete_backup_btn'),
35 compression_server_select = $('.compression_server'),
36 reset_webp_serving_method_btn = $('#wpo_reset_webp_serving_method'),
37 smush_images_tab_loaded = false,
38 smush_service_features = [],
39 smush_total_seconds = 0,
40 smush_timer_locked = false,
41 smush_timer_handle = 0,
42 smush_image_list = [],
43 smush_completed = false,
44 smush_from_media_library = false,
45 smush_mark_all_as_uncompressed = false,
46 smush_affected_images = {},
47 pending_tasks_cancel_btn = $('#wpo_smush_images_pending_tasks_cancel_button'),
48 uncompressed_images_sites_select = $('#wpo_uncompressed_images_sites_select');
49
50 $('#doaction, #doaction2').on('click', function(e) {
51 e.stopImmediatePropagation();
52 var action = $(this).prev('select').val();
53 if ('wp_optimize_bulk_compression' !== action && 'wp_optimize_bulk_restore' !== action ) return;
54
55 var $selected_images = get_media_library_selected_images();
56 if (0 === $selected_images.length) return;
57 e.preventDefault();
58 if ('wp_optimize_bulk_compression' === action) bulk_compression($selected_images);
59 if ('wp_optimize_bulk_restore' === action) bulk_restore($selected_images);
60 });
61
62 /**
63 * Handles bulk compression action from media library
64 *
65 * @param {Object} $selected_images
66 */
67 function bulk_compression($selected_images) {
68 $('#smush-information-modal .smush-information').text(wposmush.server_check);
69 update_view_modal_message($('#smush-information-modal'));
70
71 data = { 'server': wposmush.smush_settings.compression_server };
72 smush_manager_send_command('check_server_status', data, function(resp) {
73 if (resp.online) {
74 $selected_images.each(function(index, element) {
75 smush_image_list.push({
76 'attachment_id': parseInt(element.value),
77 'blog_id': wposmush.blog_id
78 });
79 });
80
81 data = {
82 optimization_id: 'smush',
83 selected_images: smush_image_list,
84 smush_options: {
85 'compression_server': wposmush.smush_settings.compression_server,
86 'image_quality': wposmush.smush_settings.image_quality,
87 'lossy_compression': wposmush.smush_settings.lossy_compression,
88 'back_up_original': wposmush.smush_settings.back_up_original,
89 'preserve_exif': wposmush.smush_settings.preserve_exif
90 }
91 }
92 smush_from_media_library = true;
93 smush_completed = false;
94 if (smush_timer_locked) return;
95 update_view_modal_message($('#wpo_smush_images_information_container'));
96
97 $('#wpo_smush_images_information_server').html(wposmush.smush_settings.compression_server);
98
99 clear_smush_stats();
100
101 smush_timer_handle = window.setInterval(smush_timer, 1000);
102 smush_manager_send_command('process_bulk_smush', data);
103 } else {
104 if (resp.error) {
105 error_message = resp.error + '<br>' + wposmush.server_error
106 $('#smush-information-modal .smush-information').html(error_message);
107 } else {
108 $('#smush-information-modal .smush-information').text(wposmush.server_error);
109 }
110 update_view_modal_message($('#smush-information-modal'), $.unblockUI);
111 }
112 });
113 }
114
115 /**
116 * Handles bulk restore action from media library
117 *
118 * @param {Object} $selected_images
119 */
120 function bulk_restore($selected_images) {
121 smush_from_media_library = true;
122
123 var processed_elements = [];
124 var progress = function(element_id) {
125 return function(callback) {
126 processed_elements.push(element_id);
127
128 if (1 < processed_elements.length && processed_elements.length === $selected_images.length) {
129 callback(wposmush.images_restored_successfully);
130 } else {
131 callback();
132 }
133 }
134 }
135
136 $selected_images.each(function(index, element) {
137 restore_selected_image(wposmush.blog_id, parseInt(element.value), progress(parseInt(element.value)));
138 });
139 }
140
141 /**
142 * Handle Image Selection
143 */
144
145 smush_images_grid.on('click', '.thumbnail', function (e) {
146 $(this).closest('input[type="checkbox"]').prop('checked', true);
147 });
148
149
150 /**
151 * Handle Shift Ctrl keys state.
152 */
153 var ctrl_shift_on_image_held = false;
154
155
156 smush_images_grid.on('mousedown', '.thumbnail', function (e) {
157 ctrl_shift_on_image_held = e.shiftKey || e.ctrlKey;
158 });
159
160 smush_images_grid.on('mouseup', '.thumbnail', function (e) {
161 ctrl_shift_on_image_held = e.shiftKey || e.ctrlKey;
162 });
163
164 // Resets server rewrite capability
165 reset_webp_serving_method_btn.on('click', function(e) {
166 e.preventDefault();
167 smush_manager_send_command('reset_webp_serving_method', {}, function(resp) {
168 if (!resp.success) {
169 console.log('[Failed] WebP server capability detection');
170 $('#enable_webp_conversion').prop("checked", false);
171 $('#smush-information-modal .smush-information').text(resp.error_message);
172 update_view_modal_message($('#smush-information-modal'))
173 } else {
174 $('#wpo_reset_webp_serving_method_done').show().delay(3000).fadeOut();
175 }
176 });
177 });
178
179 /**
180 * Boolean flag to track whether uncompressed images have already been loaded,
181 * preventing multiple unnecessary loads
182 */
183 var uncompressed_images_already_loaded = false;
184
185 /**
186 * Checks if smush is active and loads images if yes - image tabs change.
187 */
188 $('#wp-optimize-nav-tab-wrapper__wpo_images .nav-tab').on('click', function() {
189 if (uncompressed_images_already_loaded) return;
190
191 if ($(this).is('#wp-optimize-nav-tab-wpo_images-smush')) {
192 get_info_from_smush_manager(false);
193 }
194 });
195
196 /**
197 * Checks if smush is active and loads images if yes - main menu change.
198 */
199 $('#wp-optimize-wrap').on('page-change', function(e, params) {
200 if (uncompressed_images_already_loaded) return;
201
202 if ('wpo_images' == params.page) {
203 if ($('#wp-optimize-nav-tab-wrapper__wpo_images .nav-tab-active').is('#wp-optimize-nav-tab-wpo_images-smush')) {
204 get_info_from_smush_manager(false);
205 }
206 }
207 });
208
209 if ($('#smush-metabox').length > 0) {
210 update_view_available_options();
211 }
212
213
214 var lastclick = null;
215 smush_images_grid.on('click' , '.wpo_smush_image' , function(e) {
216 var grid_input = $('#wpo_smush_images_grid input[type="checkbox"]');
217 var input = $(this).find('.wpo_smush_image__input');
218 var input_val = (!(input.prop('checked')));
219 if (!lastclick) {
220 $(this).find('.wpo_smush_image__input').prop('checked',input_val);
221 lastclick = input;
222 }
223 if (true === ctrl_shift_on_image_held) {
224 var start = grid_input.index(input);
225 var end = grid_input.index(lastclick);
226 if (start === end) {
227 grid_input.slice(Math.min(start,end), Math.max(start,end)+ 1).prop('checked', input_val);
228 } else {
229 if (true === lastclick.prop('checked')) {
230 grid_input.slice(Math.min(start,end), Math.max(start,end)+ 1).prop('checked', input_val);
231 }
232 }
233 }
234 lastclick = input;
235 update_smush_action_buttons_state();
236 });
237
238 /**
239 * Disable smush actions buttons if no images selected.
240 */
241 function update_smush_action_buttons_state() {
242 var state = (0 == $('input[type="checkbox"]:checked', smush_images_grid).length);
243
244 smush_selected_images_btn.prop('disabled', state);
245 smush_mark_as_compressed_btn.prop('disabled', state);
246 }
247
248 update_smush_action_buttons_state();
249
250 /**
251 * Handles change of smush service provider
252 */
253 compression_server_select.on('change', function(e) {
254 update_view_available_options();
255 save_options();
256 });
257
258 /**
259 * Process bulk smush
260 */
261 smush_selected_images_btn.off().on('click', function() {
262
263 if (0 == $('#wpo_smush_images_grid input[type="checkbox"]:checked').length) {
264 $('#smush-information-modal .smush-information').text(wposmush.please_select_images)
265 update_view_modal_message($('#smush-information-modal'), $.unblockUI);
266 return;
267 }
268
269 $('#smush-information-modal .smush-information').text(wposmush.server_check);
270 update_view_modal_message($('#smush-information-modal'));
271
272 data = { 'server': $("input[name='compression_server']:checked").val() };
273 smush_manager_send_command('check_server_status', data, function(resp) {
274 if (resp.online) {
275 bulk_smush_selected_images();
276 } else {
277 if (resp.error) {
278 error_message = resp.error + '<br>' + wposmush.server_error
279 $('#smush-information-modal .smush-information').html(error_message);
280 } else {
281 $('#smush-information-modal .smush-information').text(wposmush.server_error);
282 }
283 update_view_modal_message($('#smush-information-modal'), $.unblockUI);
284 }
285 });
286 });
287
288 /**
289 * Mark as compressed
290 */
291 smush_mark_as_compressed_btn.off().on('click', function() {
292 if (0 == $('#wpo_smush_images_grid input[type="checkbox"]:checked').length) {
293 $('#smush-information-modal .smush-information').text(wposmush.please_select_compressed_images)
294 update_view_modal_message($('#smush-information-modal'), $.unblockUI);
295 return;
296 }
297
298 var selected_images = [],
299 image;
300
301 $('#wpo_smush_images_grid input:checked').each(function() {
302 image = {
303 'attachment_id':$(this).val(),
304 'blog_id': $(this).data('blog')
305 };
306 selected_images.push(image);
307 });
308
309 update_view_modal_message(wposmush.please_updating_images_info);
310
311 smush_manager_send_command('mark_as_compressed', {selected_images: selected_images}, function(response) {
312 $('#smush-information-modal .smush-information').text(response.summary);
313 update_view_modal_message($('#smush-information-modal'), $.unblockUI);
314 // refresh images list.
315 get_info_from_smush_manager();
316 });
317 });
318
319 /**
320 * Handle "Mark all images as uncompressed" click.
321 */
322 smush_mark_all_as_uncompressed_btn.on('click', function() {
323 if (!confirm(wposmush.mark_all_images_uncompressed)) return;
324
325 var restore_backup = confirm(wposmush.restore_images_from_backup);
326
327 update_view_modal_message($('#smush-information-modal-cancel-btn'));
328 $('#smush-information-modal-cancel-btn .smush-information').text(wposmush.please_wait);
329
330 smush_mark_all_as_uncompressed = true;
331 run_mark_all_as_uncompressed(restore_backup);
332 });
333
334 /**
335 * Handle "Restore all compressed images" click.
336 */
337 restore_all_compressed_images_btn.on('click', function() {
338 if (!confirm(wposmush.restore_all_compressed_images)) return;
339
340 update_view_modal_message($('#smush-information-modal-cancel-btn'));
341 $('#smush-information-modal-cancel-btn .smush-information').text(wposmush.please_wait);
342
343 smush_mark_all_as_uncompressed = true;
344 run_mark_all_as_uncompressed(true, true);
345 });
346
347 /**
348 * Handle "Cancel" button click for mark all images as uncompressed process
349 */
350 $('#smush-information-modal-cancel-btn input[type="button"]').on('click', function() {
351 smush_mark_all_as_uncompressed = false;
352 get_info_from_smush_manager();
353 $.unblockUI();
354 });
355
356 /**
357 * Send command for mark all compressed images as uncompressed.
358 *
359 * @param {bool} restore_backup if set to true then images will restored from backup if possible.
360 * @param {bool} delete_only_backups_meta if set to true the only backup meta will be deleted
361 */
362 function run_mark_all_as_uncompressed(restore_backup, delete_only_backups_meta) {
363 if (!smush_mark_all_as_uncompressed) return;
364
365 restore_backup = restore_backup ? 1 : 0;
366 delete_only_backups_meta = delete_only_backups_meta ? 1 : 0;
367
368 var info = $('#smush-information-modal-cancel-btn .smush-information');
369 smush_manager_send_command('mark_all_as_uncompressed',
370 {
371 restore_backup: restore_backup,
372 delete_only_backups_meta: delete_only_backups_meta
373 },
374 function(resp) {
375 // if cancel button pressed then exit
376 if (!smush_mark_all_as_uncompressed) return;
377
378 // if we get an error then show it
379 if (resp.hasOwnProperty('error')) {
380 update_view_modal_message($('#smush-information-modal'), $.unblockUI);
381 $('#smush-information-modal .smush-information').text(resp.error);
382 get_info_from_smush_manager();
383 return;
384 }
385
386 // if completed then refresh uncompressed images list and show final message.
387 if (resp.completed) {
388 update_view_modal_message($('#smush-information-modal'), $.unblockUI);
389 $('#smush-information-modal .smush-information').text(resp.message);
390 get_info_from_smush_manager();
391 } else {
392 info.text(resp.message);
393 run_mark_all_as_uncompressed(restore_backup, delete_only_backups_meta);
394 }
395 }
396 );
397 }
398
399 /**
400 * Refresh image list
401 */
402 smush_images_refresh_btn.off().on('click', function() {
403 // The refresh image list button should not fetch from cache but run the query
404 get_info_from_smush_manager(false);
405 });
406
407 /**
408 * Bind select all / select none controls
409 */
410 smush_images_select_all_btn.off().on('click', function() {
411 $('#wpo_smush_images_grid input[type="checkbox"]').prop("checked", true);
412 lastclick = null;
413 update_smush_action_buttons_state();
414 });
415
416
417 /**
418 * Bind select all / select none controls
419 */
420 smush_images_select_none_btn.off().on('click', function() {
421 $('#wpo_smush_images_grid input[type="checkbox"]').prop("checked", false);
422 lastclick = null;
423 update_smush_action_buttons_state();
424 });
425
426 /**
427 * Displays logs in a modal
428 */
429 smush_view_logs_btn.off().on('click', function() {
430 $("#log-panel").text("Please wait, fetching logs.");
431 smush_manager_send_command('get_smush_logs', {}, function(resp) {
432 $.blockUI({
433 message: $("#smush-log-modal"),
434 onOverlayClick: $.unblockUI(),
435 css: {
436 width: '80%',
437 height: '80%',
438 top: '15%',
439 left: '15%'
440 }
441 });
442 $("#log-panel").html("<pre>" + resp + "</pre>");
443 download_link = ajaxurl + "?action=updraft_smush_ajax&subaction=get_smush_logs&nonce=" + wposmush.smush_ajax_nonce;
444 $("#smush-log-modal a").attr('href', download_link);
445 }, false);
446 });
447
448 /**
449 * Handle delete all backup images button click.
450 */
451 smush_delete_backup_images_btn.on('click', function() {
452
453 if (!confirm(wposmush.delete_image_backup_confirm)) return;
454 smush_delete_backup_images_btn.prop('disabled', true);
455 var spinner = $('#wpo_smush_delete_backup_spinner'),
456 done = $('#wpo_smush_delete_backup_done');
457
458 spinner.show();
459
460 smush_manager_send_command('clean_all_backup_images', {}, function() {
461 spinner.hide();
462 smush_delete_backup_images_btn.prop('disabled', false);
463 done.css('display', 'inline-block').delay(3000).fadeOut();
464 });
465 });
466
467 /**
468 * Binds clear stats button
469 */
470 smush_images_stats_clear_btn.off().on('click', function(e) {
471 $('#wpo_smush_images_clear_stats_spinner').show().delay(3000).fadeOut();
472
473 smush_manager_send_command('clear_smush_stats', {}, function(resp) {
474 $('#wpo_smush_images_clear_stats_spinner').hide();
475 $('#wpo_smush_images_clear_stats_done').show().delay(3000).fadeOut();
476 });
477 });
478
479 /**
480 * Binds pending tasks button
481 */
482 smush_images_pending_tasks_btn.off().on('click', function(e) {
483 $('#smush-information-modal .smush-information').text(wposmush.server_check);
484 update_view_modal_message($('#smush-information-modal'), $.unblockUI);
485 data = { 'server': $("input[name='compression_server']:checked").val() };
486 smush_manager_send_command('check_server_status', data, function(resp) {
487 if (resp.online) {
488 update_view_bulk_smush_start();
489 smush_manager_send_command('process_pending_images', {}, function(resp) {
490 handle_response_from_smush_manager(resp, update_view_bulk_smush_progress);
491 });
492 } else {
493 if (resp.error) {
494 error_message = resp.error + '<br>' + wposmush.server_error
495 $('#smush-information-modal .smush-information').html(error_message);
496 } else {
497 $('#smush-information-modal .smush-information').text(wposmush.server_error);
498 }
499 update_view_modal_message($('#smush-information-modal'), $.unblockUI);
500 }
501 });
502
503 });
504
505
506 /**
507 * Binds smush cancel button
508 */
509 $('body').on('click', '#wpo_smush_images_pending_tasks_cancel_button', function(e) {
510
511 if (wposmush.cancel === pending_tasks_cancel_btn.val()) {
512 pending_tasks_cancel_btn.val(wposmush.cancelling);
513 pending_tasks_cancel_btn.prop('disabled', true);
514 }
515 smush_manager_send_command('clear_pending_images', {}, function(resp) {
516 $.unblockUI();
517 if (resp.status) {
518 get_info_from_smush_manager();
519 reset_view_bulk_smush();
520 } else {
521 console.log('Cancelling pending images apparently failed.', resp);
522 }
523 pending_tasks_cancel_btn.val(wposmush.cancel);
524 pending_tasks_cancel_btn.prop('disabled', false);
525 });
526 });
527
528 /**
529 * Single image compression
530 */
531 $('body').on('click', '.wpo_smush_single_image .button', function() {
532
533 image = {
534 'attachment_id':$(this).data('id'),
535 'blog_id': $(this).data('blog')
536 };
537
538 if ($('#enable_custom_compression').is(":checked")) {
539 image_quality = $('#custom_compression_slider').val();
540 } else {
541 // The '60' here has to be kept in sync with WP_Optimize::admin_page_wpo_images_smush()
542 image_quality = $('#enable_lossy_compression').is(":checked") ? 60 : 92;
543 }
544 lossy_compression = image_quality < 92 ? true : false;
545
546 smush_options = {
547 'compression_server': $("input[name='compression_server_" + image.attachment_id + "']:checked").val(),
548 'image_quality': image_quality,
549 'lossy_compression': lossy_compression,
550 'back_up_original': $('#smush_backup_' + image.attachment_id).is(":checked"),
551 'preserve_exif': $('#smush_exif_' + image.attachment_id).is(":checked")
552 }
553
554 data = { 'server': $("input[name='compression_server_" + $(this).attr('id').substring(15) + "']:checked").val() };
555 update_view_modal_message(wposmush.server_check);
556 smush_manager_send_command('check_server_status', data, function(resp) {
557 if (resp.online) {
558 smush_selected_image(image, smush_options);
559 } else {
560 if (resp.error) {
561 error_message = resp.error + '<br>' + wposmush.server_error
562
563 update_view_modal_message(error_message, $.unblockUI);
564 } else {
565 update_view_modal_message(wposmush.server_error, $.unblockUI);
566 }
567 }
568 });
569 });
570
571 /**
572 * Single image restore
573 */
574 $('body').on('click', '.wpo_restore_single_image .button', function() {
575 var clicked_image = $(this);
576 blog_id = clicked_image.data('blog');
577 image_id = clicked_image.data('id');
578
579 if (!image_id || !blog_id) return;
580 restore_selected_image(blog_id, image_id);
581 });
582
583 /**
584 * Mark as compressed
585 */
586 $('body').on('click', '.wpo_smush_mark_single_image .button', function() {
587 var image = {
588 'attachment_id':$(this).data('id'),
589 'blog_id': $(this).data('blog')
590 },
591 wrapper = $(this).closest('#smush-metabox-inside-wrapper');
592
593 update_view_modal_message(wposmush.please_updating_images_info);
594
595 smush_manager_send_command('mark_as_compressed', {selected_images: [ image ]}, function(response) {
596 $('#smush-information-modal .smush-information').text(response.summary);
597 update_view_modal_message($('#smush-information-modal'), $.unblockUI);
598
599 if (response.status) {
600 $('.wpo_smush_single_image', wrapper).hide();
601 $('.wpo-toggle-advanced-options', wrapper).removeClass('opened');
602 $('.wpo_smush_mark_single_image', wrapper).hide();
603 $('.wpo_smush_unmark_single_image', wrapper).show();
604 $('.wpo_restore_single_image', wrapper).show();
605 $('#smush_info', wrapper).text(response.info);
606 }
607 });
608 });
609
610 /**
611 * Unmark as uncompressed
612 */
613 $('body').on('click', '.wpo_smush_unmark_single_image .button', function() {
614 var image = {
615 'attachment_id':$(this).data('id'),
616 'blog_id': $(this).data('blog')
617 },
618 wrapper = $(this).closest('#smush-metabox-inside-wrapper');
619
620 update_view_modal_message(wposmush.please_updating_images_info);
621
622 smush_manager_send_command('mark_as_compressed', {selected_images: [ image ], unmark: true}, function(response) {
623 $('#smush-information-modal .smush-information').text(response.summary);
624 update_view_modal_message($('#smush-information-modal'), $.unblockUI);
625
626 if (response.status) {
627 $('.wpo_smush_single_image', wrapper).show();
628 $('.wpo_smush_mark_single_image', wrapper).show();
629 $('.wpo_smush_unmark_single_image', wrapper).hide();
630 $('.wpo_restore_single_image', wrapper).hide();
631 $('#smush_info', wrapper).text('');
632 }
633 });
634 });
635
636 $('body').on('click', '#wpo_smush_details .wpo-collapsible', toggle_smush_details);
637 $('body').on('click', '.column-wpo_smush .wpo-collapsible', toggle_smush_details);
638
639 function toggle_smush_details() {
640 $(this).toggleClass('opened');
641 if ($(this).hasClass('opened')) {
642 $(this).text(wposmush.less);
643 } else {
644 $(this).text(wposmush.more);
645 }
646 }
647
648 $('body').on('click', '#smush-log-modal .close, #smush-information-modal .information-modal-close', function() {
649 $.unblockUI();
650 if (smush_from_media_library) {
651 reset_bulk_actions_dropdown();
652 }
653 });
654
655 $('body').on('click', '.wpo_smush_stats_cta_btn, .wpo_smush_get_logs, #smush-complete-summary .close', function() {
656 $.unblockUI();
657 if (smush_from_media_library) {
658 var selected_images_list = get_media_library_selected_images_list();
659 smush_manager_send_command('get_smush_details', {selected_images: selected_images_list}, function(response) {
660 if (response.success) {
661 window.clearInterval(smush_timer_handle);
662 update_media_library_screen(response.smush_details);
663 } else {
664 console.log(response)
665 }
666 });
667 } else {
668 get_info_from_smush_manager();
669 setTimeout(reset_view_bulk_smush, 500);
670 }
671 });
672
673 $('body').on('click', '.wpo-toggle-advanced-options', function(e) {
674 e.preventDefault();
675 $(this).toggleClass('opened');
676 });
677
678 $('.wpo-fieldgroup .autosmush input, .wpo-fieldgroup .compression_level, .wpo-fieldgroup .image_options, #smush-show-metabox').on('change', function(e) {
679 save_options();
680 });
681
682 $('body').on('change', '.smush-options.compression_level', function() {
683 if ($('#enable_custom_compression').is(':checked')) {
684 $('.smush-options.custom_compression').show();
685 } else {
686 $('.smush-options.custom_compression').hide();
687 }
688 });
689
690 $('body').on('change', '.smush-advanced input[type="radio"]', function() {
691 update_view_available_options();
692 });
693
694 $('#enable_webp_conversion').on('change', function(e) {
695 // only save when changing the options on the wpo dashboard.
696 if (!$('#wp-optimize-wrap').length) return;
697
698 $('#wpo_smush_images_save_options_spinner').show().delay(3000).fadeOut();
699 $('#enable_webp_conversion').prop("disabled", true);
700
701 var smush_options = get_smush_options();
702
703 smush_manager_send_command('update_webp_options', smush_options, function(resp) {
704 $('#wpo_smush_images_save_options_spinner').hide();
705 if (resp.hasOwnProperty('saved') && resp.saved) {
706 $('#wpo_smush_images_save_options_done').show().delay(3000).fadeOut();
707 } else {
708 $('#enable_webp_conversion').prop("checked", false);
709 if ('update_failed_no_working_webp_converter' === resp.error_code) {
710 var html_msg = '<p>'
711 + wposmush.webp_conversion_tool_error
712 + ' <a href="https://getwpo.com/faqs/#How-can-I-get-WebP-conversion-tools-to-work-" target="_blank">'
713 + wposmush.webp_conversion_tool_how_to
714 + '</a></p>';
715 $('#smush-information-modal .smush-information').html(html_msg);
716 } else {
717 $('#smush-information-modal .smush-information').text(resp.error_message);
718 }
719 update_view_modal_message($('#smush-information-modal'));
720 }
721 $('#enable_webp_conversion').prop("disabled", false);
722 });
723 });
724
725 convert_to_webp_btn.on('click', function(e){
726 e.preventDefault();
727 var $link = $(this);
728 data = {
729 'attachment_id': $(this).data('attachment-id')
730 };
731 update_view_modal_message(wposmush.converting_to_webp);
732 smush_manager_send_command('convert_to_webp_format', data, function(response) {
733 if (response.error) {
734 update_view_modal_message(response.error, $.unblockUI);
735 setTimeout(function() {
736 $.unblockUI();
737 }, 2000);
738 } else {
739 update_view_modal_message(response.success, $.unblockUI);
740 setTimeout(function() {
741 $.unblockUI();
742 }, 2000);
743 $link.next().remove();
744 $link.remove();
745 }
746 });
747 });
748
749 /**
750 * Load and show information about uncompressed images.
751 *
752 * @param {Boolean} use_cache Use the request cache
753 *
754 * @return void
755 */
756 function get_info_from_smush_manager(use_cache) {
757
758 var use_cache = (typeof use_cache === 'undefined') ? true : use_cache;
759 var data = { 'use_cache': use_cache };
760
761 smush_images_optimization_message.html('...');
762 smush_images_pending_tasks_container.hide();
763
764 disable_image_optimization_controls(true);
765
766 heartbeat_agents.push(heartbeat.add_agent({
767 _wait: false,
768 _keep: false,
769 command: 'updraft_smush_ajax',
770 command_data: {data: data, subaction: 'get_ui_update'},
771 callback: function(resp) {
772 handle_response_from_smush_manager(resp, update_view_show_uncompressed_images);
773 update_view_available_options();
774 disable_image_optimization_controls(false);
775 update_smush_action_buttons_state();
776 }
777 }));
778
779 uncompressed_images_already_loaded = true;
780 }
781
782
783 /**
784 * Get selected images and make an ajax request to compress them.
785 *
786 * @return void
787 */
788 function bulk_smush_selected_images() {
789
790 $('#wpo_smush_images_grid input:checked').each(function() {
791 image = {
792 'attachment_id':$(this).val(),
793 'blog_id': $(this).data('blog')
794 };
795 smush_image_list.push(image);
796 });
797
798 data = {
799 optimization_id: 'smush',
800 selected_images: smush_image_list,
801 smush_options: {
802 'compression_server': $("input[name='compression_server']:checked").val(),
803 'image_quality': $('#image_quality').val(),
804 'lossy_compression': $('#smush-lossy-compression').is(":checked"),
805 'back_up_original': $('#smush-backup-original').is(":checked"),
806 'preserve_exif': $('#smush-preserve-exif').is(":checked")
807 }
808 }
809
810 update_view_bulk_smush_start();
811 heartbeat_agents.push(heartbeat.add_agent({
812 _wait: false,
813 _keep: false,
814 command: 'updraft_smush_ajax',
815 command_data: {data: data, subaction: 'process_bulk_smush'}
816 }));
817 }
818
819 /**
820 * Save options in the DB
821 *
822 * @return void
823 */
824 function save_options() {
825 // only save when changing the options on the wpo dashboard.
826 if (!$('#wp-optimize-wrap').length) return;
827
828 $('#wpo_smush_images_save_options_spinner').show().delay(3000).fadeOut();
829
830 var smush_options = get_smush_options();
831
832 smush_manager_send_command('update_smush_options', smush_options, function(resp) {
833 $('#wpo_smush_images_save_options_spinner').hide();
834 if (resp.hasOwnProperty('saved') && resp.saved) {
835 $('#wpo_smush_images_save_options_done').show().delay(3000).fadeOut();
836 } else {
837 $('#wpo_smush_images_save_options_fail').show().delay(3000).fadeOut();
838 }
839 });
840 }
841
842 /**
843 * A timer to run for the duration of the bulk smush operation.
844 *
845 * @return void
846 */
847 function smush_timer() {
848 smush_timer_locked = true;
849 smush_total_seconds++;
850 seconds = (smush_total_seconds % 60) + '' < 10 ? '0' + (smush_total_seconds % 60) : (smush_total_seconds % 60);
851 minutes = parseInt(smush_total_seconds / 60) + '' < 10 ? '0' + parseInt(smush_total_seconds / 60) : parseInt(smush_total_seconds / 60);
852
853 $('#smush_stats_timer').text(minutes + ":" + seconds);
854 trigger_events(smush_total_seconds);
855 }
856
857 /**
858 * A timer to run for the duration of the bulk smush operation.
859 *
860 * @param {Number} time_elapsed - time in seconds
861 *
862 * @return void
863 */
864 function trigger_events(time_elapsed) {
865 if (0 == time_elapsed % 3) {
866 update_smush_stats(time_elapsed);
867 }
868
869 if (0 == time_elapsed % 60) {
870 if (null != last_ui_update_agent_uid) {
871 heartbeat.cancel_agent(last_ui_update_agent_uid);
872 last_ui_update_agent_uid = null;
873 }
874
875 heartbeat_agents.push(heartbeat.add_agent({
876 _wait: false,
877 command: 'updraft_smush_ajax',
878 command_data: {data: {}, subaction: 'process_pending_images'},
879 callback: function(resp) {
880 handle_response_from_smush_manager(resp, update_view_bulk_smush_progress);
881 }
882 }));
883 }
884 }
885
886 /**
887 * Updates the UI with stats
888 *
889 * @param {Int} time_elapsed Elapsed time since process start
890 *
891 * @return void
892 */
893 function update_smush_stats(time_elapsed) {
894 data = {
895 update_ui: true,
896 use_cache: false
897 }
898
899 var initial_requests = time_elapsed < 5;
900
901 var agent = heartbeat.add_agent({
902 _wait: !initial_requests,
903 _keep: false,
904 command: 'updraft_smush_ajax',
905 command_data: {data: data, subaction: 'get_ui_update'},
906 callback: function(resp) {
907 handle_response_from_smush_manager(resp, update_view_bulk_smush_progress);
908 }
909 });
910
911 if (null !== agent) {
912 last_ui_update_agent_uid = agent;
913
914 heartbeat_agents.push(agent);
915 }
916 }
917
918 /**
919 * Update images optimization tab view with data returned from images optimization.
920 *
921 * @param {Object} data - meta data returned from task manager
922 *
923 * @return void
924 */
925 function update_view_show_uncompressed_images(data) {
926 smush_images_grid.html('');
927
928 if (!data || !data.hasOwnProperty('unsmushed_images')) return;
929
930 var unsmushed_images = data.unsmushed_images,
931 pending_tasks = data.pending_tasks,
932 blog_id = 0;
933
934 if (0 == unsmushed_images.length && 0 == pending_tasks) {
935 smush_images_grid.text(wposmush.all_images_compressed).wrapInner("<div class='wpo-fieldgroup'> </div>");
936 }
937
938 if (0 != pending_tasks) {
939 smush_images_pending_tasks_container.show().find('.red').text(data.pending);
940 }
941
942 if (1 === data.is_multisite) {
943 blog_id = uncompressed_images_sites_select.find(":selected").val();
944 add_unsmushed_images_to_grid(blog_id, data);
945 } else {
946 for (blog_id in data.unsmushed_images) {
947 add_unsmushed_images_to_grid(blog_id, data);
948 }
949 }
950 }
951
952 function sort_unsmushed_images(a, b) {
953 return a.id - b.id;
954 }
955
956 function add_unsmushed_images_to_grid(blog_id, data) {
957 // Used to have upload.php?item= on multisite (using data.is_multisite), and no suffix
958 var admin_url_pre_id = 'post.php?post=',
959 admin_url_post_id = '&action=edit',
960 admin_url = data.admin_urls[blog_id],
961 unsmushed_images = data.unsmushed_images[blog_id];
962
963 if ('undefined' !== typeof unsmushed_images) {
964 unsmushed_images.sort(sort_unsmushed_images);
965 }
966
967 for (i in unsmushed_images) {
968 if (!unsmushed_images.hasOwnProperty(i)) continue;
969 var image = unsmushed_images[i];
970 add_image_to_grid(image, blog_id, admin_url + admin_url_pre_id + image.id + admin_url_post_id);
971 }
972 }
973
974 uncompressed_images_sites_select.on('change', function() {
975 get_info_from_smush_manager();
976 });
977
978 /**
979 * Updates the view when bulk smush starts
980 *
981 * @return void
982 */
983 function update_view_bulk_smush_start() {
984 if (smush_timer_locked) return;
985 update_view_modal_message($('#wpo_smush_images_information_container'));
986
987 service = $('.compression_server input[type="radio"]:checked + label small').text();
988 $('#wpo_smush_images_information_server').html(service);
989
990 clear_smush_stats();
991
992 smush_timer_handle = window.setInterval(smush_timer, 1000);
993 disable_image_optimization_controls(true);
994 }
995
996 /**
997 * Clears the statistics for image smushing in popup.
998 *
999 * This function clears the statistics displayed on the popup for image smushing.
1000 *
1001 * @returns {void}
1002 */
1003 function clear_smush_stats() {
1004 $('#smush_stats_pending_images').html("...");
1005 $('#smush_stats_completed_images').html("...");
1006 $('#smush_stats_bytes_saved').html("...");
1007 $('#smush_stats_percent_saved').html("...");
1008 $('#smush_stats_timer').html("...");
1009 }
1010
1011 /**
1012 * Updates the media library screen with the provided smush details.
1013 *
1014 * @param {Object} smush_details - The details of the smushed images
1015 * @return {void}
1016 */
1017 function update_media_library_screen(smush_details) {
1018 for (var image_id in smush_details) {
1019 if(smush_details.hasOwnProperty(image_id)) {
1020 $('#post-' + image_id + ' .column-wpo_smush').html(smush_details[image_id]);
1021 }
1022 }
1023 reset_bulk_actions_dropdown();
1024 }
1025
1026 /**
1027 * Updates the view with progress related stats
1028 *
1029 * @param {Object} resp - response from smush manager.
1030 *
1031 * @return void
1032 */
1033 function update_view_bulk_smush_progress(resp) {
1034
1035 // Update stats
1036 $('#smush_stats_pending_images').html(resp.pending_tasks);
1037 $('#smush_stats_completed_images').html(resp.completed_task_count);
1038 $('#smush_stats_bytes_saved').html(resp.bytes_saved);
1039 $('#smush_stats_percent_saved').html(resp.percent_saved);
1040
1041 // Show summary and close the modal
1042 if (true == resp.smush_complete) {
1043 // Force a delay here to avoid stale data
1044 setTimeout(function() {
1045 update_view_bulk_smush_complete(function() { get_info_from_smush_manager(false); });
1046 }, 1500);
1047 }
1048 }
1049
1050 /**
1051 * Updates the view when bulk smush completes
1052 *
1053 * @return void
1054 */
1055 function update_view_bulk_smush_complete(callback) {
1056
1057 data = {
1058 update_ui: true,
1059 use_cache: false,
1060 image_list: smush_image_list
1061 };
1062
1063 (function(single_callback) {
1064 heartbeat_agents.push(heartbeat.add_agent({
1065 _wait: false,
1066 _keep: false,
1067 command: 'updraft_smush_ajax',
1068 command_data: {data: data, subaction: 'get_ui_update'},
1069 callback: function(resp) {
1070
1071 summary = resp.session_stats;
1072
1073 if (0 != resp.completed_task_count) {
1074 summary += '<hr>' + resp.summary;
1075 }
1076
1077 show_smush_summary(summary);
1078
1079 if (single_callback instanceof Function) {
1080 single_callback();
1081 }
1082 }
1083 }));
1084 })(callback);
1085 }
1086
1087 /**
1088 * Displays a modal with compression data
1089 *
1090 * @param {string} summary - stats and info
1091 *
1092 * @return void
1093 */
1094 function show_smush_summary(summary) {
1095
1096 if (smush_completed) return;
1097
1098 $('#summary-message').html(summary);
1099 reset_view_bulk_smush();
1100 update_view_modal_message($('#smush-complete-summary'));
1101 smush_completed = true;
1102
1103 heartbeat.cancel_agents(heartbeat_agents);
1104 }
1105
1106 /**
1107 * Updates the view when bulk smush completes
1108 *
1109 * @return void
1110 */
1111 function reset_view_bulk_smush() {
1112 // Reset timer and locks
1113 smush_total_seconds = 0;
1114 smush_timer_locked = false;
1115 smush_completed = false;
1116 smush_image_list = [];
1117
1118 heartbeat.cancel_agents(heartbeat_agents);
1119 clearInterval(smush_timer_handle);
1120
1121 disable_image_optimization_controls(false);
1122 }
1123
1124 /**
1125 * Append the image to the grid
1126 *
1127 * @param {Object} image - image data returned from smush manager
1128 * @param {int} blog_id - The blog id the image
1129 * @param {String} admin_url - The URL to link to for viewing the image
1130 *
1131 * @return void
1132 */
1133 function add_image_to_grid(image, blog_id, admin_url) {
1134
1135 var dom_id = ['wpo_smush_', blog_id, '_', image.id].join('');
1136
1137 image_html = '<div class="wpo_smush_image" data-filesize="'+image.filesize+'">';
1138 image_html += '<a class="button" href="'+admin_url+'" target="_blank"> ' + wposmush.view_image + ' </a>';
1139 image_html += '<input id="' + dom_id + '" type="checkbox" data-blog="'+blog_id+ '" class="wpo_smush_image__input" value="'+image.id+'">';
1140 image_html += '<label for="' + dom_id + '"></a>';
1141 image_html += '<div class="thumbnail">';
1142 image_html += '<img class="lazyload" src="'+image.thumb_url+'">';
1143 image_html += '</div></label></div>';
1144
1145 smush_images_grid.append(image_html);
1146 }
1147
1148 /**
1149 * Updates UI based on service provider selected
1150 *
1151 * @param {Object} features - image data returned from smush manager
1152 *
1153 * @return void
1154 */
1155 function update_view_available_options() {
1156 features = wposmush.features;
1157 service = $("input[name^='compression_server']:checked").val();
1158
1159 for (feature in features[service]) {
1160 $('.' + feature).prop('disabled', !features[service][feature]);
1161 }
1162
1163 $('.wpo_smush_image').each(function() {
1164 if ($(this).data('filesize') > wposmush.features[service]["max_filesize"]) {
1165 $(this).hide();
1166 } else {
1167 $(this).show();
1168 }
1169 })
1170 }
1171
1172 /**
1173 * Disable smush controls (buttons, checkboxes) in bulk mode
1174 *
1175 * @param {boolean} disable - if true then disable controls, false - enable.
1176 *
1177 * @return void
1178 */
1179 function disable_image_optimization_controls(disable) {
1180 $.each([
1181 smush_selected_images_btn,
1182 smush_images_select_all_btn,
1183 smush_images_select_none_btn,
1184 smush_images_refresh_btn,
1185 smush_images_pending_tasks_btn,
1186 smush_mark_as_compressed_btn,
1187 ], function(i, el) {
1188 el.prop('disabled', disable);
1189 });
1190
1191 if (disable) {
1192 $('#wpo_smush_images_refresh').hide();
1193 $('.wpo_smush_images_loader').show();
1194 } else {
1195 $('#wpo_smush_images_refresh').show();
1196 $('.wpo_smush_images_loader').hide();
1197 }
1198 }
1199
1200 /**
1201 * Gets selected image and make an ajax request to compress it.
1202 *
1203 * @param {Object} selected_image - { attachment_id: ..., blog_id: ... }
1204 * @param {Array} smush_options - The options to use
1205 *
1206 * @return void
1207 */
1208 function smush_selected_image(selected_image, smush_options) {
1209
1210 // if no selected images then exit.
1211 if (0 == selected_image.length) return;
1212
1213 data = {
1214 selected_image: selected_image,
1215 smush_options: smush_options
1216 }
1217
1218 update_view_modal_message(wposmush.compress_single_image_dialog);
1219 smush_manager_send_command('compress_single_image', data, function(resp) {
1220 handle_response_from_smush_manager(resp, update_view_single_image_complete);
1221 });
1222 }
1223
1224 /**
1225 * Get selected image and make an ajax request to compress it.
1226 *
1227 * @param {Number} blog_id - The blog id
1228 * @param {Number} selected_image - The image id
1229 * @param {Function} done_callback - Optional. It will be called when the AJAX command is done, used for multiple calls that need a single `done` action (like bulk_restore)
1230 *
1231 * @return void
1232 */
1233 function restore_selected_image(blog_id, selected_image, done_callback) {
1234
1235 // if no selected images then exit.
1236 if (0 == selected_image.length) return;
1237
1238 update_view_modal_message(wposmush.please_wait, $.unblockUI);
1239 var data = { 'blog_id': blog_id, 'selected_image': selected_image };
1240
1241 smush_manager_send_command.apply({unique: false}, ['restore_single_image', data, function(resp) {
1242 var done = function(resp_summary_alt) {
1243 if ('undefined' != typeof(resp_summary_alt)) {
1244 resp.summary = resp_summary_alt;
1245 }
1246
1247 handle_response_from_smush_manager(resp, update_view_single_image_complete);
1248 }
1249
1250 if (done_callback instanceof Function) {
1251 done_callback(done);
1252 } else {
1253 done();
1254 }
1255 }]);
1256 }
1257
1258 /**
1259 * Updates the view once a single image is compressed or restored.
1260 *
1261 * @param {Object} resp - response from smush manager.
1262 *
1263 * @return void
1264 */
1265 function update_view_single_image_complete(resp) {
1266
1267 if (resp.hasOwnProperty('success') && resp.success) {
1268 $(".smush-information").text(resp.summary);
1269 update_view_modal_message($("#smush-information-modal"), $.unblockUI);
1270
1271 $('.wpo-toggle-advanced-options.wpo_smush_single_image').removeClass('opened');
1272
1273 update_view_singe_image_compress(resp.operation, resp.summary, resp.restore_possible, resp);
1274
1275 // here we store data from the the response
1276 // this information will be used to show correct UI elements
1277 // when smush metabox will shown again without reloading main page
1278 var blog_id = resp.blog_id || resp.options.blog_id,
1279 image_id = resp.image || resp.options.attachment_id;
1280
1281 if (!smush_affected_images.hasOwnProperty(blog_id)) smush_affected_images[blog_id] = {};
1282 if (!smush_affected_images[blog_id].hasOwnProperty(image_id)) smush_affected_images[blog_id][image_id] = {};
1283
1284 if ('compress' == resp.operation) {
1285 smush_affected_images[blog_id][image_id] = {
1286 operation: resp.operation,
1287 summary: resp.summary,
1288 restore_possible: resp.restore_possible
1289 }
1290 } else {
1291 if (image_id) {
1292 update_media_library_wp_optimize_column(image_id);
1293 reset_bulk_actions_dropdown();
1294 }
1295 smush_affected_images[blog_id][image_id] = {
1296 operation: resp.operation
1297 }
1298 }
1299 } else {
1300 $(".smush-information").text(resp.error_message);
1301 update_view_modal_message($("#smush-information-modal"), $.unblockUI);
1302 }
1303 }
1304
1305 /**
1306 * Update metabox view depending on a command response.
1307 *
1308 * @param {string} operation
1309 * @param {string} summary
1310 * @param {boolean} restore_possible
1311 * @param {object} smush_image_data
1312 */
1313 function update_view_singe_image_compress(operation, summary, restore_possible, smush_image_data) {
1314 var wrapper = $("#smush_info").closest('#smush-metabox-inside-wrapper');
1315
1316 if ('compress' == operation) {
1317 $(".wpo_smush_single_image").hide();
1318 $(".wpo_restore_single_image").show();
1319
1320 if (smush_image_data && smush_image_data.hasOwnProperty('sizes-info')) {
1321 $("#smush_info").text(summary);
1322 $("#wpo_smush_details").html(smush_image_data['sizes-info']);
1323 } else {
1324 $("#smush_info").text(summary);
1325 $("#wpo_smush_details").text('').hide();
1326 }
1327
1328 $('.wpo_smush_mark_single_image').hide();
1329
1330 if (restore_possible) {
1331 $(".restore_possible").show();
1332 } else {
1333 $(".restore_possible").hide();
1334 }
1335 } else {
1336 $(".wpo_smush_single_image").show();
1337 $(".wpo_restore_single_image").hide();
1338
1339 $('.wpo_smush_mark_single_image').show();
1340 $('.wpo_smush_unmark_single_image', wrapper).hide();
1341 }
1342 }
1343
1344 /**
1345 * Handle smush metabox load event. This handler is used to restore correct smush metabox view.
1346 */
1347 $(document).on('admin-metabox-smush-loaded', function() {
1348 var image_data = $('.wpo_restore_single_image input[type="button"]').first().data();
1349
1350 if (!image_data) return;
1351
1352 if (smush_affected_images.hasOwnProperty(image_data.blog) && smush_affected_images[image_data.blog].hasOwnProperty(image_data.id)) {
1353 var smush_image_data = smush_affected_images[image_data.blog][image_data.id];
1354
1355 if ('compress' == smush_image_data.operation) {
1356 update_view_singe_image_compress(smush_image_data.operation, smush_image_data.summary, smush_image_data.restore_possible, smush_image_data);
1357 } else {
1358 update_view_singe_image_compress(smush_image_data.operation);
1359 }
1360 }
1361 });
1362
1363 /**
1364 * Display a modal message
1365 *
1366 * @param {string} message The message or element to display
1367 * @param {Function} callback Called when the overlay is clicked
1368 *
1369 * @return void
1370 */
1371 function update_view_modal_message(message, callback) {
1372
1373 $.blockUI({
1374 message: message,
1375 onOverlayClick: callback,
1376 baseZ: 160001,
1377 css: {
1378 width: '400px',
1379 padding: '20px',
1380 cursor: 'pointer'
1381 }
1382 });
1383 }
1384
1385 /**
1386 * Check returned response from the smush manager and call update view callback.
1387 *
1388 * @param {Object} resp - response from smush manager.
1389 * @param {Function} update_view_callback - callback function to update view.
1390 *
1391 * @return void
1392 */
1393 function handle_response_from_smush_manager(resp, update_view_callback) {
1394 if (resp && resp.hasOwnProperty('status') && resp.status) {
1395 if (update_view_callback) update_view_callback(resp);
1396 } else {
1397 alert(wposmush.error_unexpected_response);
1398 console.log(resp);
1399 }
1400 }
1401
1402 /**
1403 * Retrieves the selected images from the media library.
1404 *
1405 * @return {jQuery} - The selected images as a jQuery object.
1406 */
1407 function get_media_library_selected_images() {
1408 return $('input[name="media[]"]:checked');
1409 }
1410
1411 /**
1412 * Retrieves the list of selected images from the media library.
1413 *
1414 * @return {Array.<number>} The list of selected image IDs.
1415 */
1416 function get_media_library_selected_images_list() {
1417 var selected_images_list = [];
1418 var $selected_images = get_media_library_selected_images();
1419 $selected_images.each(function(index, element) {
1420 selected_images_list.push(parseInt(element.value));
1421 });
1422 return selected_images_list;
1423 }
1424
1425 /**
1426 * Updates the media library WP Optimize column for a specified image.
1427 *
1428 * @param {number} image_id - The ID of the image to update the column for.
1429 */
1430 function update_media_library_wp_optimize_column(image_id) {
1431 var admin_url = ajaxurl.replace('/admin-ajax.php', '/');
1432 admin_url += 'post.php?post=' + image_id + '&action=edit';
1433 $('#post-' + image_id + ' .column-wpo_smush').html('<a href="' + admin_url + '">' + wposmush.compress + '</a><br>');
1434 }
1435
1436
1437 /**
1438 * Resets the bulk action dropdown by setting its value to "-1" and unchecking all the selected checkboxes.
1439 *
1440 * @returns {void}
1441 */
1442 function reset_bulk_actions_dropdown() {
1443 $('#bulk-action-selector-top, #bulk-action-selector-bottom').val("-1");
1444 $('input[name="media[]"]:checked, #cb-select-all-1, #cb-select-all-2').prop('checked', false);
1445 }
1446
1447 /**
1448 * Send an action to the task manager via admin-ajax.php.
1449 *
1450 * @param {string} action The action to send
1451 * @param {[type]} data Data to send
1452 * @param {Function} callback Will be called with the results
1453 * @param {boolean} json_parse JSON parse the results
1454 *
1455 * @return {JSON}
1456 */
1457 function smush_manager_send_command(action, data, callback, json_parse) {
1458
1459 json_parse = ('undefined' === typeof json_parse) ? true : json_parse;
1460 data = $.isEmptyObject(data) ? {'use_cache' : false} : data;
1461
1462 (function(single_callback, _keep, _unique) {
1463 heartbeat_agents.push(heartbeat.add_agent({
1464 _wait: false,
1465 _keep: _keep,
1466 _unique: _unique,
1467 command: 'updraft_smush_ajax',
1468 command_data: {data: data, subaction: action},
1469 callback: function(response) {
1470 if (json_parse) {
1471 try {
1472 var resp = wpo_parse_json(response);
1473 } catch (e) {
1474 console.log("smush_manager_send_command JSON parse error");
1475 console.log(e);
1476 console.log(response);
1477 alert(wposmush.error_unexpected_response);
1478 }
1479 if ('undefined' !== typeof single_callback) single_callback(resp);
1480 } else {
1481 if ('undefined' !== typeof single_callback) single_callback(response);
1482 }
1483 }
1484 }));
1485 })(callback, this.keep, this.unique);
1486 };
1487
1488 // Attach heartbeat API events
1489 heartbeat.setup();
1490
1491 // Gather smush options
1492 var get_smush_options = function() {
1493 var image_quality = '';
1494 if ($('#enable_custom_compression').is(":checked")) {
1495 image_quality = $('#custom_compression_slider').val();
1496 } else {
1497 // The '90' here has to be kept in sync with WP_Optimize::admin_page_wpo_images_smush()
1498 image_quality = $('#enable_lossy_compression').is(":checked") ? 60 : 92;
1499 }
1500 var lossy_compression = image_quality < 92 ? true : false;
1501
1502 return {
1503 'compression_server': $("input[name='compression_server']:checked").val(),
1504 'image_quality': image_quality,
1505 'lossy_compression': lossy_compression,
1506 'back_up_original': $('#smush-backup-original').is(":checked"),
1507 'back_up_delete_after': $('#smush-backup-delete').is(":checked"),
1508 'back_up_delete_after_days': $('#smush-backup-delete-days').val(),
1509 'preserve_exif': $('#smush-preserve-exif').is(":checked"),
1510 'autosmush': $('#smush-automatically').is(":checked"),
1511 'show_smush_metabox': $('#smush-show-metabox').is(":checked"),
1512 'webp_conversion': $('#enable_webp_conversion').is(":checked")
1513 };
1514 }
1515 wp_optimize.smush_settings = get_smush_options;
1516 } // END WP_Optimize_Smush
1517
1518