PluginProbe
WP-Optimize – Cache, Compress images, Minify & Clean database to boost page speed & performance / 3.7.1
WP-Optimize – Cache, Compress images, Minify & Clean database to boost page speed & performance v3.7.1
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.7.1, at js/wposmush.js

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