PluginProbe
WP-Optimize – Cache, Compress images, Minify & Clean database to boost page speed & performance / 4.7.0
WP-Optimize – Cache, Compress images, Minify & Clean database to boost page speed & performance v4.7.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
← All changes | js/wposmush.js +509 -330 3.3.2 → 4.7.0 View file →
@@ -5,16 +5,20 @@
5 5 var WP_Optimize_Smush = function() {
6 6
7 7 var $ = jQuery;
8 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 +
9 16 /**
10 17 * Variables for smushing.
11 18 */
12 - var smush_nav_tab = $('#wp-optimize-images-nav-tab-smush'),
13 - smush_images_grid = $('#wpo_smush_images_grid'),
19 + var smush_images_grid = $('#wpo_smush_images_grid'),
14 20 smush_images_optimization_message = $('#smush_info_images'),
15 - smush_images_pending_tasks_container = $('#wpo_smush_images_pending_tasks_container'),
16 - smush_images_pending_tasks_btn = $('#wpo_smush_images_pending_tasks_button'),
17 21 smush_images_refresh_btn = $('#wpo_smush_images_refresh'),
18 22 smush_images_select_all_btn = $('#wpo_smush_images_select_all'),
19 23 smush_images_select_none_btn = $('#wpo_smush_images_select_none'),
20 24 smush_images_stats_clear_btn = $('#wpo_smush_clear_stats_btn'),
@@ -19,11 +23,8 @@
19 23 smush_images_select_none_btn = $('#wpo_smush_images_select_none'),
20 24 smush_images_stats_clear_btn = $('#wpo_smush_clear_stats_btn'),
21 25 smush_selected_images_btn = $('#wpo_smush_images_btn'),
22 26 smush_mark_as_compressed_btn = $('#wpo_smush_mark_as_compressed'),
23 - smush_single_image_btn = $('.wpo_smush_single_image .button'),
24 - smush_single_restore_btn = $('.wpo_restore_single_image .button'),
25 - convert_to_webp_btn = $('.wpo_smush.column-wpo_smush .convert-to-webp');
26 27 smush_mark_all_as_uncompressed_btn = $('#wpo_smush_mark_all_as_uncompressed_btn'),
27 28 restore_all_compressed_images_btn = $('#wpo_smush_restore_all_compressed_images_btn'),
28 29 smush_view_logs_btn = $('.wpo_smush_get_logs'),
29 30 smush_delete_backup_images_btn = $('#wpo_smush_delete_backup_btn'),
@@ -35,8 +36,9 @@
35 36 smush_timer_locked = false,
36 37 smush_timer_handle = 0,
37 38 smush_image_list = [],
38 39 smush_completed = false,
40 + smush_from_media_library = false,
39 41 smush_mark_all_as_uncompressed = false,
40 42 smush_affected_images = {},
41 43 pending_tasks_cancel_btn = $('#wpo_smush_images_pending_tasks_cancel_button'),
42 44 uncompressed_images_sites_select = $('#wpo_uncompressed_images_sites_select');
@@ -41,11 +43,106 @@
41 43 pending_tasks_cancel_btn = $('#wpo_smush_images_pending_tasks_cancel_button'),
42 44 uncompressed_images_sites_select = $('#wpo_uncompressed_images_sites_select');
43 45
44 46 /**
47 + * These options used for block UI with custom content.
48 + */
49 + var block_ui_custom_options = {
50 + baseZ: 160001,
51 + css: {
52 + top: '50%',
53 + transform: 'translate(0, -50%)',
54 + width: '400px',
55 + padding: '20px',
56 + cursor: 'pointer'
57 + }
58 + }
59 +
60 + $('#doaction, #doaction2').on('click', function(e) {
61 + e.stopImmediatePropagation();
62 + var action = $(this).prev('select').val();
63 + if ('wp_optimize_bulk_compression' !== action && 'wp_optimize_bulk_restore' !== action ) return;
64 +
65 + var $selected_images = get_media_library_selected_images();
66 + if (0 === $selected_images.length) return;
67 + e.preventDefault();
68 + if ('wp_optimize_bulk_compression' === action) bulk_compression($selected_images);
69 + if ('wp_optimize_bulk_restore' === action) bulk_restore($selected_images);
70 + });
71 +
72 + /**
73 + * Handles bulk compression action from media library
74 + *
75 + * @param {Object} $selected_images
76 + */
77 + function bulk_compression($selected_images) {
78 + block_ui(wposmush.server_check);
79 +
80 + data = { 'server': wposmush.smush_settings.compression_server, skip_notice: true };
81 + smush_manager_send_command('check_server_status', data, function(resp) {
82 + if (resp.online) {
83 + $selected_images.each(function(index, element) {
84 + smush_image_list.push({
85 + 'attachment_id': parseInt(element.value),
86 + 'blog_id': wposmush.blog_id
87 + });
88 + });
89 +
90 + data = {
91 + optimization_id: 'smush',
92 + selected_images: smush_image_list,
93 + smush_options: {
94 + 'compression_server': wposmush.smush_settings.compression_server,
95 + 'image_quality': wposmush.smush_settings.image_quality,
96 + 'lossy_compression': wposmush.smush_settings.lossy_compression,
97 + 'back_up_original': wposmush.smush_settings.back_up_original,
98 + 'preserve_exif': wposmush.smush_settings.preserve_exif
99 + }
100 + }
101 + smush_from_media_library = true;
102 + smush_completed = false;
103 + if (smush_timer_locked) return;
104 + block_ui('', $.extend(block_ui_custom_options, {message: $('#wpo_smush_images_information_container')}), false, true);
105 + clear_smush_stats();
106 +
107 + smush_timer_handle = window.setInterval(smush_timer, 1000);
108 + smush_manager_send_command('process_bulk_smush', data);
109 + } else {
110 + error_message = resp.error ? resp.error + '<br>' + wposmush.server_error : wposmush.server_error;
111 + block_ui(error_message);
112 + }
113 + });
114 + }
115 +
116 + /**
117 + * Handles bulk restore action from media library
118 + *
119 + * @param {Object} $selected_images
120 + */
121 + function bulk_restore($selected_images) {
122 + smush_from_media_library = true;
123 +
124 + var processed_elements = [];
125 + var progress = function(element_id) {
126 + return function(callback) {
127 + processed_elements.push(element_id);
128 +
129 + if (1 < processed_elements.length && processed_elements.length === $selected_images.length) {
130 + callback(wposmush.images_restored_successfully);
131 + } else {
132 + callback();
133 + }
134 + }
135 + }
136 +
137 + $selected_images.each(function(index, element) {
138 + restore_selected_image(wposmush.blog_id, parseInt(element.value), progress(parseInt(element.value)));
139 + });
140 + }
141 +
142 + /**
45 143 * Handle Image Selection
46 144 */
47 -
48 145 smush_images_grid.on('click', '.thumbnail', function (e) {
49 146 $(this).closest('input[type="checkbox"]').prop('checked', true);
50 147 });
51 148
@@ -66,14 +163,13 @@
66 163
67 164 // Resets server rewrite capability
68 165 reset_webp_serving_method_btn.on('click', function(e) {
69 166 e.preventDefault();
70 - smush_manager_send_command('reset_webp_serving_method', {}, function(resp) {
167 + smush_manager_send_command('reset_webp_serving_method', { skip_notice: true }, function(resp) {
71 168 if (!resp.success) {
72 - console.log('[Failed] WebP server capability detection');
73 169 $('#enable_webp_conversion').prop("checked", false);
74 170 $('#smush-information-modal .smush-information').text(resp.error_message);
75 - update_view_modal_message($('#smush-information-modal'))
171 + block_ui('', $.extend(block_ui_custom_options, {message: $('#smush-information-modal')}), false, true);
76 172 } else {
77 173 $('#wpo_reset_webp_serving_method_done').show().delay(3000).fadeOut();
78 174 }
79 175 });
@@ -79,13 +175,21 @@
79 175 });
80 176 });
81 177
82 178 /**
179 + * Boolean flag to track whether uncompressed images have already been loaded,
180 + * preventing multiple unnecessary loads
181 + */
182 + var uncompressed_images_already_loaded = false;
183 +
184 + /**
83 185 * Checks if smush is active and loads images if yes - image tabs change.
84 186 */
85 187 $('#wp-optimize-nav-tab-wrapper__wpo_images .nav-tab').on('click', function() {
188 + if (uncompressed_images_already_loaded) return;
189 +
86 190 if ($(this).is('#wp-optimize-nav-tab-wpo_images-smush')) {
87 - get_info_from_smush_manager();
191 + get_info_from_smush_manager(false);
88 192 }
89 193 });
90 194
91 195 /**
@@ -91,11 +195,13 @@
91 195 /**
92 196 * Checks if smush is active and loads images if yes - main menu change.
93 197 */
94 198 $('#wp-optimize-wrap').on('page-change', function(e, params) {
199 + if (uncompressed_images_already_loaded) return;
200 +
95 201 if ('wpo_images' == params.page) {
96 202 if ($('#wp-optimize-nav-tab-wrapper__wpo_images .nav-tab-active').is('#wp-optimize-nav-tab-wpo_images-smush')) {
97 - get_info_from_smush_manager();
203 + get_info_from_smush_manager(false);
98 204 }
99 205 }
100 206 });
101 207
@@ -153,28 +259,21 @@
153 259 */
154 260 smush_selected_images_btn.off().on('click', function() {
155 261
156 262 if (0 == $('#wpo_smush_images_grid input[type="checkbox"]:checked').length) {
157 - $('#smush-information-modal .smush-information').text(wposmush.please_select_images)
158 - update_view_modal_message($('#smush-information-modal'), $.unblockUI);
263 + block_ui(wposmush.please_select_images);
159 264 return;
160 265 }
161 266
162 - $('#smush-information-modal .smush-information').text(wposmush.server_check);
163 - update_view_modal_message($('#smush-information-modal'));
267 + block_ui(wposmush.server_check);
164 268
165 - data = { 'server': $("input[name='compression_server']:checked").val() };
269 + data = { 'server': $("input[name='compression_server']:checked").val(), skip_notice: true };
166 270 smush_manager_send_command('check_server_status', data, function(resp) {
167 271 if (resp.online) {
168 272 bulk_smush_selected_images();
169 273 } else {
170 - if (resp.error) {
171 - error_message = resp.error + '<br>' + wposmush.server_error
172 - $('#smush-information-modal .smush-information').html(error_message);
173 - } else {
174 - $('#smush-information-modal .smush-information').text(wposmush.server_error);
175 - }
176 - update_view_modal_message($('#smush-information-modal'), $.unblockUI);
274 + error_message = resp.error ? resp.error + '<br>' + wposmush.server_error : wposmush.server_error;
275 + block_ui(error_message);
177 276 }
178 277 });
179 278 });
180 279
@@ -181,13 +280,8 @@
181 280 /**
182 281 * Mark as compressed
183 282 */
184 283 smush_mark_as_compressed_btn.off().on('click', function() {
185 - if (0 == $('#wpo_smush_images_grid input[type="checkbox"]:checked').length) {
186 - $('#smush-information-modal .smush-information').text(wposmush.please_select_compressed_images)
187 - update_view_modal_message($('#smush-information-modal'), $.unblockUI);
188 - return;
189 - }
190 284
191 285 var selected_images = [],
192 286 image;
193 287
@@ -198,15 +292,15 @@
198 292 };
199 293 selected_images.push(image);
200 294 });
201 295
202 - update_view_modal_message(wposmush.please_updating_images_info);
296 + block_ui(wposmush.please_updating_images_info);
203 297
204 298 smush_manager_send_command('mark_as_compressed', {selected_images: selected_images}, function(response) {
205 299 $('#smush-information-modal .smush-information').text(response.summary);
206 - update_view_modal_message($('#smush-information-modal'), $.unblockUI);
300 + block_ui('', $.extend(block_ui_custom_options, {message: $('#smush-information-modal')}));
207 301 // refresh images list.
208 - get_info_from_smush_manager();
302 + get_info_from_smush_manager(false);
209 303 });
210 304 });
211 305
212 306 /**
@@ -216,10 +310,9 @@
216 310 if (!confirm(wposmush.mark_all_images_uncompressed)) return;
217 311
218 312 var restore_backup = confirm(wposmush.restore_images_from_backup);
219 313
220 - update_view_modal_message($('#smush-information-modal-cancel-btn'));
221 - $('#smush-information-modal-cancel-btn .smush-information').text(wposmush.please_wait);
314 + block_ui(wposmush.please_wait);
222 315
223 316 smush_mark_all_as_uncompressed = true;
224 317 run_mark_all_as_uncompressed(restore_backup);
225 318 });
@@ -229,10 +322,9 @@
229 322 */
230 323 restore_all_compressed_images_btn.on('click', function() {
231 324 if (!confirm(wposmush.restore_all_compressed_images)) return;
232 325
233 - update_view_modal_message($('#smush-information-modal-cancel-btn'));
234 - $('#smush-information-modal-cancel-btn .smush-information').text(wposmush.please_wait);
326 + block_ui(wposmush.please_wait);
235 327
236 328 smush_mark_all_as_uncompressed = true;
237 329 run_mark_all_as_uncompressed(true, true);
238 330 });
@@ -249,17 +341,22 @@
249 341 /**
250 342 * Send command for mark all compressed images as uncompressed.
251 343 *
252 344 * @param {bool} restore_backup if set to true then images will restored from backup if possible.
345 + * @param {bool} delete_only_backups_meta if set to true the only backup meta will be deleted
253 346 */
254 347 function run_mark_all_as_uncompressed(restore_backup, delete_only_backups_meta) {
255 348 if (!smush_mark_all_as_uncompressed) return;
256 349
350 + restore_backup = restore_backup ? 1 : 0;
351 + delete_only_backups_meta = delete_only_backups_meta ? 1 : 0;
352 +
257 353 var info = $('#smush-information-modal-cancel-btn .smush-information');
258 354 smush_manager_send_command('mark_all_as_uncompressed',
259 355 {
260 - restore_backup: restore_backup ? 1 : 0,
261 - delete_only_backups_meta: delete_only_backups_meta ? 1 : 0
356 + restore_backup: restore_backup,
357 + delete_only_backups_meta: delete_only_backups_meta,
358 + skip_notice: true
262 359 },
263 360 function(resp) {
264 361 // if cancel button pressed then exit
265 362 if (!smush_mark_all_as_uncompressed) return;
@@ -265,10 +362,9 @@
265 362 if (!smush_mark_all_as_uncompressed) return;
266 363
267 364 // if we get an error then show it
268 365 if (resp.hasOwnProperty('error')) {
269 - update_view_modal_message($('#smush-information-modal'), $.unblockUI);
270 - $('#smush-information-modal .smush-information').text(resp.error);
366 + block_ui(resp.error);
271 367 get_info_from_smush_manager();
272 368 return;
273 369 }
274 370
@@ -273,14 +369,14 @@
273 369 }
274 370
275 371 // if completed then refresh uncompressed images list and show final message.
276 372 if (resp.completed) {
277 - update_view_modal_message($('#smush-information-modal'), $.unblockUI);
373 + block_ui('', $.extend(block_ui_custom_options, {message: $('#smush-information-modal')}));
278 374 $('#smush-information-modal .smush-information').text(resp.message);
279 375 get_info_from_smush_manager();
280 376 } else {
281 377 info.text(resp.message);
282 - run_mark_all_as_uncompressed(restore_backup);
378 + run_mark_all_as_uncompressed(restore_backup, delete_only_backups_meta);
283 379 }
284 380 }
285 381 );
286 382 }
@@ -288,9 +384,10 @@
288 384 /**
289 385 * Refresh image list
290 386 */
291 387 smush_images_refresh_btn.off().on('click', function() {
292 - get_info_from_smush_manager();
388 + // The refresh image list button should not fetch from cache but run the query
389 + get_info_from_smush_manager(false);
293 390 });
294 391
295 392 /**
296 393 * Bind select all / select none controls
@@ -364,44 +461,17 @@
364 461 });
365 462 });
366 463
367 464 /**
368 - * Binds pending tasks button
369 - */
370 - smush_images_pending_tasks_btn.off().on('click', function(e) {
371 - $('#smush-information-modal .smush-information').text(wposmush.server_check);
372 - update_view_modal_message($('#smush-information-modal'), $.unblockUI);
373 - data = { 'server': $("input[name='compression_server']:checked").val() };
374 - smush_manager_send_command('check_server_status', data, function(resp) {
375 - if (resp.online) {
376 - update_view_bulk_smush_start();
377 - smush_manager_send_command('process_pending_images', {}, function(resp) {
378 - handle_response_from_smush_manager(resp, update_view_bulk_smush_progress);
379 - });
380 - } else {
381 - if (resp.error) {
382 - error_message = resp.error + '<br>' + wposmush.server_error
383 - $('#smush-information-modal .smush-information').html(error_message);
384 - } else {
385 - $('#smush-information-modal .smush-information').text(wposmush.server_error);
386 - }
387 - update_view_modal_message($('#smush-information-modal'), $.unblockUI);
388 - }
389 - });
390 -
391 - });
392 -
393 -
394 - /**
395 465 * Binds smush cancel button
396 466 */
397 467 $('body').on('click', '#wpo_smush_images_pending_tasks_cancel_button', function(e) {
398 468
399 - if (wpoptimize.cancel === pending_tasks_cancel_btn.val()) {
400 - pending_tasks_cancel_btn.val(wpoptimize.cancelling);
469 + if (wposmush.cancel === pending_tasks_cancel_btn.val()) {
470 + pending_tasks_cancel_btn.val(wposmush.cancelling);
401 471 pending_tasks_cancel_btn.prop('disabled', true);
402 472 }
403 - smush_manager_send_command('clear_pending_images', {}, function(resp) {
473 + smush_manager_send_command('clear_pending_images', { restore_images: smush_image_list }, function(resp) {
404 474 $.unblockUI();
405 475 if (resp.status) {
406 476 get_info_from_smush_manager();
407 477 reset_view_bulk_smush();
@@ -407,14 +477,53 @@
407 477 reset_view_bulk_smush();
408 478 } else {
409 479 console.log('Cancelling pending images apparently failed.', resp);
410 480 }
411 - pending_tasks_cancel_btn.val(wpoptimize.cancel);
481 + pending_tasks_cancel_btn.val(wposmush.cancel);
412 482 pending_tasks_cancel_btn.prop('disabled', false);
413 483 });
414 484 });
415 485
416 486 /**
487 + * Handle the click on the 'Compress' button within the Media Library page and open a dialog for the image compression action.
488 + */
489 + $('.column-wpo_smush').on('click', '.wpo-smush-compress-popup-btn', function(e) {
490 + var attachment_id = $(this).data('id'),
491 + blog_id = $(this).data('blog');
492 +
493 + e.preventDefault();
494 +
495 + smush_manager_send_command('get_smush_settings_form', {
496 + attachment_id: attachment_id,
497 + blog_id: blog_id
498 + }, function(resp) {
499 + if (resp.success) {
500 + var html = [
501 + '<div class="wpo-smush-compress-popup-content">',
502 + '<h3>',wposmush.compress_image,'</h3>',
503 + resp.html,
504 + '</div>',
505 + '<div class="wpo_smush_single_image action_button" style="display:inline-block;">',
506 + '<input type="button" data-blog="',blog_id,'" data-id="',attachment_id,'" id="smush_compress_',attachment_id,'" class="button-primary button" value="',wposmush.compress,'">',
507 + '</div>',
508 + '&nbsp;&nbsp;',
509 + '<a href="#" class="button wpo-smush-popup-cancel-btn">',wposmush.close,'</a>'
510 + ].join('');
511 + block_ui('', $.extend(block_ui_custom_options, {message: html}));
512 + }
513 + });
514 +
515 + });
516 +
517 + /**
518 + * Handle the 'Cancel' button in the dialog for the image compression action.
519 + */
520 + $('body').on('click', '.wpo-smush-popup-cancel-btn', function(e) {
521 + e.preventDefault();
522 + $.unblockUI();
523 + });
524 +
525 + /**
417 526 * Single image compression
418 527 */
419 528 $('body').on('click', '.wpo_smush_single_image .button', function() {
420 529
@@ -439,20 +548,15 @@
439 548 'preserve_exif': $('#smush_exif_' + image.attachment_id).is(":checked")
440 549 }
441 550
442 551 data = { 'server': $("input[name='compression_server_" + $(this).attr('id').substring(15) + "']:checked").val() };
443 - update_view_modal_message(wposmush.server_check);
552 + block_ui(wposmush.server_check);
444 553 smush_manager_send_command('check_server_status', data, function(resp) {
445 554 if (resp.online) {
446 555 smush_selected_image(image, smush_options);
447 556 } else {
448 - if (resp.error) {
449 - error_message = resp.error + '<br>' + wposmush.server_error
450 -
451 - update_view_modal_message(error_message, $.unblockUI);
452 - } else {
453 - update_view_modal_message(wposmush.server_error, $.unblockUI);
454 - }
557 + error_message = resp.error ? resp.error + '<br>' + wposmush.server_error : wposmush.server_error;
558 + block_ui(error_message);
455 559 }
456 560 });
457 561 });
458 562
@@ -458,13 +562,15 @@
458 562
459 563 /**
460 564 * Single image restore
461 565 */
462 - $('body').on('click', '.wpo_restore_single_image .button', function() {
566 + $('body').on('click', '.wpo_restore_single_image .button, .wpo_restore_single_image a', function(e) {
463 567 var clicked_image = $(this);
464 568 blog_id = clicked_image.data('blog');
465 569 image_id = clicked_image.data('id');
466 570
571 + e.preventDefault();
572 +
467 573 if (!image_id || !blog_id) return;
468 574 restore_selected_image(blog_id, image_id);
469 575 });
470 576
@@ -470,58 +576,76 @@
470 576
471 577 /**
472 578 * Mark as compressed
473 579 */
474 - $('body').on('click', '.wpo_smush_mark_single_image .button', function() {
475 - var image = {
476 - 'attachment_id':$(this).data('id'),
477 - 'blog_id': $(this).data('blog')
478 - },
479 - wrapper = $(this).closest('#smush-metabox-inside-wrapper');
580 + $('body').on('click', '.wpo_smush_mark_single_image .button, .wpo_smush_mark_single_image a', function(e) {
581 + mark_unmark_as_compressed_handler($(this), e, true);
582 + });
480 583
481 - update_view_modal_message(wposmush.please_updating_images_info);
482 -
483 - smush_manager_send_command('mark_as_compressed', {selected_images: [ image ]}, function(response) {
484 - $('#smush-information-modal .smush-information').text(response.summary);
485 - update_view_modal_message($('#smush-information-modal'), $.unblockUI);
486 -
487 - if (response.status) {
488 - $('.wpo_smush_single_image', wrapper).hide();
489 - $('.wpo-toggle-advanced-options', wrapper).removeClass('opened');
490 - $('.wpo_smush_mark_single_image', wrapper).hide();
491 - $('.wpo_smush_unmark_single_image', wrapper).show();
492 - $('.wpo_restore_single_image', wrapper).show();
493 - $('#smush_info', wrapper).text(response.info);
494 - }
495 - });
584 + /**
585 + * Unmark as compressed
586 + */
587 + $('body').on('click', '.wpo_smush_unmark_single_image .button, .wpo_smush_unmark_single_image a', function(e) {
588 + mark_unmark_as_compressed_handler($(this), e, false);
496 589 });
497 590
498 591 /**
499 - * Unmark as uncompressed
592 + * Handler for Mark/Unmark as compressed event.
593 + *
594 + * @param {jQuery} target jQuery object for target element
595 + * @param {Event} e
596 + * @param {Boolean} mark True or false - mark / unmark
500 597 */
501 - $('body').on('click', '.wpo_smush_unmark_single_image .button', function() {
502 - var image = {
503 - 'attachment_id':$(this).data('id'),
504 - 'blog_id': $(this).data('blog')
598 + function mark_unmark_as_compressed_handler(target, e, mark) {
599 + var blog_id = target.data('blog'),
600 + attachment_id = target.data('id'),
601 + image = {
602 + 'attachment_id': attachment_id,
603 + 'blog_id': blog_id
505 604 },
506 - wrapper = $(this).closest('#smush-metabox-inside-wrapper');
605 + wrapper = target.closest('#smush-metabox-inside-wrapper')
606 + data = {selected_images: [ image ]};
507 607
508 - update_view_modal_message(wposmush.please_updating_images_info);
608 + if (mark === false) {
609 + data.unmark = true;
610 + }
611 +
612 + e.preventDefault();
613 +
614 + block_ui(wposmush.please_updating_images_info);
615 +
616 + smush_manager_send_command('mark_as_compressed', data, function(response) {
509 617
510 - smush_manager_send_command('mark_as_compressed', {selected_images: [ image ], unmark: true}, function(response) {
511 618 $('#smush-information-modal .smush-information').text(response.summary);
512 - update_view_modal_message($('#smush-information-modal'), $.unblockUI);
513 619
620 + block_ui('', $.extend(block_ui_custom_options, {message: $('#smush-information-modal')}));
621 +
514 622 if (response.status) {
515 - $('.wpo_smush_single_image', wrapper).show();
516 - $('.wpo_smush_mark_single_image', wrapper).show();
517 - $('.wpo_smush_unmark_single_image', wrapper).hide();
518 - $('.wpo_restore_single_image', wrapper).hide();
519 - $('#smush_info', wrapper).text('');
623 + if (wrapper.length) {
624 + if (mark) {
625 + $('.wpo_smush_single_image', wrapper).hide();
626 + $('.wpo-toggle-advanced-options', wrapper).removeClass('opened');
627 + $('.wpo_smush_mark_single_image', wrapper).hide();
628 + $('.wpo_smush_unmark_single_image', wrapper).show();
629 + $('.wpo_restore_single_image', wrapper).show();
630 + $('#smush_info', wrapper).text(response.info);
631 + } else {
632 + $('.wpo_smush_single_image', wrapper).show();
633 + $('.wpo_smush_mark_single_image', wrapper).show();
634 + $('.wpo_smush_unmark_single_image', wrapper).hide();
635 + $('.wpo_restore_single_image', wrapper).hide();
636 + $('#smush_info', wrapper).text(response.info);
637 + }
638 + }
639 +
640 + if (response.hasOwnProperty('media_column_html')) {
641 + update_smush_information_media_library_column(blog_id, attachment_id, response.media_column_html);
642 + }
520 643 }
521 644 });
522 - });
645 + }
523 646
647 +
524 648 $('body').on('click', '#wpo_smush_details .wpo-collapsible', toggle_smush_details);
525 649 $('body').on('click', '.column-wpo_smush .wpo-collapsible', toggle_smush_details);
526 650
527 651 function toggle_smush_details() {
@@ -534,14 +658,29 @@
534 658 }
535 659
536 660 $('body').on('click', '#smush-log-modal .close, #smush-information-modal .information-modal-close', function() {
537 661 $.unblockUI();
662 + if (smush_from_media_library) {
663 + reset_bulk_actions_dropdown();
664 + }
538 665 });
539 666
540 667 $('body').on('click', '.wpo_smush_stats_cta_btn, .wpo_smush_get_logs, #smush-complete-summary .close', function() {
541 668 $.unblockUI();
542 - get_info_from_smush_manager();
543 - setTimeout(reset_view_bulk_smush, 500);
669 + if (smush_from_media_library) {
670 + var selected_images_list = get_media_library_selected_images_list();
671 + smush_manager_send_command('get_smush_details', {selected_images: selected_images_list}, function(response) {
672 + if (response.success) {
673 + window.clearInterval(smush_timer_handle);
674 + update_media_library_screen(response.smush_details);
675 + } else {
676 + console.log(response)
677 + }
678 + });
679 + } else {
680 + get_info_from_smush_manager();
681 + setTimeout(reset_view_bulk_smush, 500);
682 + }
544 683 });
545 684
546 685 $('body').on('click', '.wpo-toggle-advanced-options', function(e) {
547 686 e.preventDefault();
@@ -571,8 +710,10 @@
571 710 $('#wpo_smush_images_save_options_spinner').show().delay(3000).fadeOut();
572 711 $('#enable_webp_conversion').prop("disabled", true);
573 712
574 713 var smush_options = get_smush_options();
714 + // Skip default notice and use popup to show error messages
715 + smush_options.skip_notice = true;
575 716
576 717 smush_manager_send_command('update_webp_options', smush_options, function(resp) {
577 718 $('#wpo_smush_images_save_options_spinner').hide();
578 719 if (resp.hasOwnProperty('saved') && resp.saved) {
@@ -581,9 +722,9 @@
581 722 $('#enable_webp_conversion').prop("checked", false);
582 723 if ('update_failed_no_working_webp_converter' === resp.error_code) {
583 724 var html_msg = '<p>'
584 725 + wposmush.webp_conversion_tool_error
585 - + ' <a href="https://getwpo.com/faqs/#How-can-I-get-WebP-conversion-tools-to-work-" target="_blank">'
726 + + ' <a href="https://teamupdraft.com/documentation/wp-optimize/topics/image-compression/troubleshooting/the-webp-conversion-tool-is-not-working/" target="_blank">'
586 727 + wposmush.webp_conversion_tool_how_to
587 728 + '</a></p>';
588 729 $('#smush-information-modal .smush-information').html(html_msg);
589 730 } else {
@@ -588,34 +729,30 @@
588 729 $('#smush-information-modal .smush-information').html(html_msg);
589 730 } else {
590 731 $('#smush-information-modal .smush-information').text(resp.error_message);
591 732 }
592 - update_view_modal_message($('#smush-information-modal'));
733 + block_ui('', $.extend(block_ui_custom_options, {message: $('#smush-information-modal')}), false, true);
593 734 }
594 735 $('#enable_webp_conversion').prop("disabled", false);
595 736 });
596 737 });
597 738
598 - convert_to_webp_btn.on('click', function(e){
739 + $('body').on('click', '.wpo_smush.column-wpo_smush .convert-to-webp', function(e){
599 740 e.preventDefault();
600 741 var $link = $(this);
601 742 data = {
602 - 'attachment_id': $(this).data('attachment-id')
743 + 'attachment_id': $(this).data('attachment-id'),
744 + skip_notice: true
603 745 };
604 - update_view_modal_message(wposmush.converting_to_webp);
746 + block_ui(wposmush.converting_to_webp, {}, 0, true);
605 747 smush_manager_send_command('convert_to_webp_format', data, function(response) {
606 - if (response.error) {
607 - update_view_modal_message(response.error, $.unblockUI);
608 - setTimeout(function() {
609 - $.unblockUI();
610 - }, 2000);
611 - } else {
612 - update_view_modal_message(response.success, $.unblockUI);
613 - setTimeout(function() {
614 - $.unblockUI();
615 - }, 2000);
748 + if (response.success) {
749 + block_ui(response.success, {}, 2000);
616 750 $link.next().remove();
751 + if ($link.prev().is('.wpo-action-separator')) $link.prev().remove();
617 752 $link.remove();
753 + } else {
754 + block_ui(response.error || response.error_message || wposmush.server_error , {}, 2000);
618 755 }
619 756 });
620 757 });
621 758
@@ -631,18 +768,25 @@
631 768 var use_cache = (typeof use_cache === 'undefined') ? true : use_cache;
632 769 var data = { 'use_cache': use_cache };
633 770
634 771 smush_images_optimization_message.html('...');
635 - smush_images_pending_tasks_container.hide();
636 772
637 773 disable_image_optimization_controls(true);
638 774
639 - smush_manager_send_command('get_ui_update', data, function(resp) {
640 - handle_response_from_smush_manager(resp, update_view_show_uncompressed_images);
641 - update_view_available_options();
642 - disable_image_optimization_controls(false);
643 - update_smush_action_buttons_state();
644 - });
775 + heartbeat_agents.push(heartbeat.add_agent({
776 + _wait: false,
777 + _keep: false,
778 + command: 'updraft_smush_ajax',
779 + command_data: {data: data, subaction: 'get_ui_update'},
780 + callback: function(resp) {
781 + handle_response_from_smush_manager(resp, update_view_show_uncompressed_images);
782 + update_view_available_options();
783 + disable_image_optimization_controls(false);
784 + update_smush_action_buttons_state();
785 + }
786 + }));
787 +
788 + uncompressed_images_already_loaded = true;
645 789 }
646 790
647 791
648 792 /**
@@ -672,9 +816,14 @@
672 816 }
673 817 }
674 818
675 819 update_view_bulk_smush_start();
676 - smush_manager_send_command('process_bulk_smush', data);
820 + heartbeat_agents.push(heartbeat.add_agent({
821 + _wait: false,
822 + _keep: false,
823 + command: 'updraft_smush_ajax',
824 + command_data: {data: data, subaction: 'process_bulk_smush'}
825 + }));
677 826 }
678 827
679 828 /**
680 829 * Save options in the DB
@@ -721,17 +870,26 @@
721 870 *
722 871 * @return void
723 872 */
724 873 function trigger_events(time_elapsed) {
725 -
726 874 if (0 == time_elapsed % 3) {
727 - update_smush_stats();
875 + update_smush_stats(time_elapsed);
728 876 }
729 877
730 878 if (0 == time_elapsed % 60) {
731 - smush_manager_send_command('process_pending_images', {}, function(resp) {
732 - handle_response_from_smush_manager(resp, update_view_bulk_smush_progress);
733 - });
879 + if (null != last_ui_update_agent_uid) {
880 + heartbeat.cancel_agent(last_ui_update_agent_uid);
881 + last_ui_update_agent_uid = null;
882 + }
883 +
884 + heartbeat_agents.push(heartbeat.add_agent({
885 + _wait: false,
886 + command: 'updraft_smush_ajax',
887 + command_data: {data: {}, subaction: 'process_pending_images'},
888 + callback: function(resp) {
889 + handle_response_from_smush_manager(resp, update_view_bulk_smush_progress);
890 + }
891 + }));
734 892 }
735 893 }
736 894
737 895 /**
@@ -736,30 +894,41 @@
736 894
737 895 /**
738 896 * Updates the UI with stats
739 897 *
740 - * @param {Boolean} use_cache Use the request cache
898 + * @param {Int} time_elapsed Elapsed time since process start
741 899 *
742 900 * @return void
743 901 */
744 - function update_smush_stats(use_cache) {
745 -
746 - var use_cache = (typeof use_cache === 'undefined') ? true : use_cache;
747 -
902 + function update_smush_stats(time_elapsed) {
748 903 data = {
749 904 update_ui: true,
750 905 use_cache: false
751 906 }
752 907
753 - smush_manager_send_command('get_ui_update', data, function(resp) {
754 - handle_response_from_smush_manager(resp, update_view_bulk_smush_progress);
908 + var initial_requests = time_elapsed < 5;
909 +
910 + var agent = heartbeat.add_agent({
911 + _wait: !initial_requests,
912 + _keep: false,
913 + command: 'updraft_smush_ajax',
914 + command_data: {data: data, subaction: 'get_ui_update'},
915 + callback: function(resp) {
916 + handle_response_from_smush_manager(resp, update_view_bulk_smush_progress);
917 + }
755 918 });
919 +
920 + if (null !== agent) {
921 + last_ui_update_agent_uid = agent;
922 +
923 + heartbeat_agents.push(agent);
924 + }
756 925 }
757 926
758 927 /**
759 928 * Update images optimization tab view with data returned from images optimization.
760 929 *
761 - * @param {Object} data - meta data returned from task manager
930 + * @param {Object} data - metadata returned from task manager
762 931 *
763 932 * @return void
764 933 */
765 934 function update_view_show_uncompressed_images(data) {
@@ -774,12 +943,8 @@
774 943 if (0 == unsmushed_images.length && 0 == pending_tasks) {
775 944 smush_images_grid.text(wposmush.all_images_compressed).wrapInner("<div class='wpo-fieldgroup'> </div>");
776 945 }
777 946
778 - if (0 != pending_tasks) {
779 - smush_images_pending_tasks_container.show().find('.red').text(data.pending);
780 - }
781 -
782 947 if (1 === data.is_multisite) {
783 948 blog_id = uncompressed_images_sites_select.find(":selected").val();
784 949 add_unsmushed_images_to_grid(blog_id, data);
785 950 } else {
@@ -821,22 +986,45 @@
821 986 * @return void
822 987 */
823 988 function update_view_bulk_smush_start() {
824 989 if (smush_timer_locked) return;
825 - update_view_modal_message($('#wpo_smush_images_information_container'));
826 990
827 - service = $('.compression_server input[type="radio"]:checked + label small').text();
828 - $('#wpo_smush_images_information_server').html(service);
991 + block_ui('', $.extend(block_ui_custom_options, {message: $('#wpo_smush_images_information_container')}), false, true);
829 992
830 - // Clear stats
993 + clear_smush_stats();
994 +
995 + smush_timer_handle = window.setInterval(smush_timer, 1000);
996 + disable_image_optimization_controls(true);
997 + }
998 +
999 + /**
1000 + * Clears the statistics for image smushing in popup.
1001 + *
1002 + * This function clears the statistics displayed on the popup for image smushing.
1003 + *
1004 + * @returns {void}
1005 + */
1006 + function clear_smush_stats() {
831 1007 $('#smush_stats_pending_images').html("...");
832 1008 $('#smush_stats_completed_images').html("...");
833 1009 $('#smush_stats_bytes_saved').html("...");
834 1010 $('#smush_stats_percent_saved').html("...");
835 1011 $('#smush_stats_timer').html("...");
1012 + }
836 1013
837 - smush_timer_handle = window.setInterval(smush_timer, 1000);
838 - disable_image_optimization_controls(true);
1014 + /**
1015 + * Updates the media library screen with the provided smush details.
1016 + *
1017 + * @param {Object} smush_details - The details of the smushed images
1018 + * @return {void}
1019 + */
1020 + function update_media_library_screen(smush_details) {
1021 + for (var image_id in smush_details) {
1022 + if(smush_details.hasOwnProperty(image_id)) {
1023 + $('#post-' + image_id + ' .column-wpo_smush').html(smush_details[image_id]);
1024 + }
1025 + }
1026 + reset_bulk_actions_dropdown();
839 1027 }
840 1028
841 1029 /**
842 1030 * Updates the view with progress related stats
@@ -855,9 +1043,11 @@
855 1043
856 1044 // Show summary and close the modal
857 1045 if (true == resp.smush_complete) {
858 1046 // Force a delay here to avoid stale data
859 - setTimeout(update_view_bulk_smush_complete, 1500);
1047 + setTimeout(function() {
1048 + update_view_bulk_smush_complete(function() { get_info_from_smush_manager(false); });
1049 + }, 1500);
860 1050 }
861 1051 }
862 1052
863 1053 /**
@@ -864,26 +1054,45 @@
864 1054 * Updates the view when bulk smush completes
865 1055 *
866 1056 * @return void
867 1057 */
868 - function update_view_bulk_smush_complete() {
1058 + function update_view_bulk_smush_complete(callback) {
869 1059
870 1060 data = {
871 1061 update_ui: true,
872 1062 use_cache: false,
873 1063 image_list: smush_image_list
874 - }
1064 + };
875 1065
876 - smush_manager_send_command('get_ui_update', data, function(resp) {
1066 + (function(single_callback) {
1067 + heartbeat_agents.push(heartbeat.add_agent({
1068 + // We have to use a non-unique agent in the complete action because the info update subactions
1069 + // have the same names, and the agent may not be added. This ensures that the "smush_complete" action will run.
1070 + _unique: false,
1071 + _wait: false,
1072 + _keep: false,
1073 + command: 'updraft_smush_ajax',
1074 + command_data: {data: data, subaction: 'get_ui_update'},
1075 + callback: function(resp) {
877 1076
878 - summary = resp.session_stats;
1077 + summary = resp.session_stats;
1078 + // Prevent pops with undefined headers
1079 + if (!resp.session_stats) {
1080 + return;
1081 + }
879 1082
880 - if (0 != resp.completed_task_count) {
881 - summary += '<hr>' + resp.summary;
1083 + if (0 != resp.completed_task_count) {
1084 + summary += '<hr>' + resp.summary;
1085 + }
1086 +
1087 + show_smush_summary(summary);
1088 +
1089 + if (single_callback instanceof Function) {
1090 + single_callback();
1091 + }
882 1092 }
883 -
884 - show_smush_summary(summary);
885 - });
1093 + }));
1094 + })(callback);
886 1095 }
887 1096
888 1097 /**
889 1098 * Displays a modal with compression data
@@ -897,10 +1106,12 @@
897 1106 if (smush_completed) return;
898 1107
899 1108 $('#summary-message').html(summary);
900 1109 reset_view_bulk_smush();
901 - update_view_modal_message($('#smush-complete-summary'));
1110 + block_ui('', $.extend(block_ui_custom_options, {message: $('#smush-complete-summary')}));
902 1111 smush_completed = true;
1112 +
1113 + heartbeat.cancel_agents(heartbeat_agents);
903 1114 }
904 1115
905 1116 /**
906 1117 * Updates the view when bulk smush completes
@@ -912,9 +1123,12 @@
912 1123 smush_total_seconds = 0;
913 1124 smush_timer_locked = false;
914 1125 smush_completed = false;
915 1126 smush_image_list = [];
916 - window.clearInterval(smush_timer_handle);
1127 +
1128 + heartbeat.cancel_agents(heartbeat_agents);
1129 + clearInterval(smush_timer_handle);
1130 +
917 1131 disable_image_optimization_controls(false);
918 1132 }
919 1133
920 1134 /**
@@ -977,9 +1191,8 @@
977 1191 smush_selected_images_btn,
978 1192 smush_images_select_all_btn,
979 1193 smush_images_select_none_btn,
980 1194 smush_images_refresh_btn,
981 - smush_images_pending_tasks_btn,
982 1195 smush_mark_as_compressed_btn,
983 1196 ], function(i, el) {
984 1197 el.prop('disabled', disable);
985 1198 });
@@ -1007,12 +1220,13 @@
1007 1220 if (0 == selected_image.length) return;
1008 1221
1009 1222 data = {
1010 1223 selected_image: selected_image,
1011 - smush_options: smush_options
1224 + smush_options: smush_options,
1225 + skip_notice: true
1012 1226 }
1013 1227
1014 - update_view_modal_message(wposmush.compress_single_image_dialog);
1228 + block_ui(wposmush.compress_single_image_dialog, {}, false, true);
1015 1229 smush_manager_send_command('compress_single_image', data, function(resp) {
1016 1230 handle_response_from_smush_manager(resp, update_view_single_image_complete);
1017 1231 });
1018 1232 }
@@ -1019,23 +1233,37 @@
1019 1233
1020 1234 /**
1021 1235 * Get selected image and make an ajax request to compress it.
1022 1236 *
1023 - * @param {Number} blog_id - The blog id
1024 - * @param {Number} selected_image - The image id
1237 + * @param {Number} blog_id - The blog id
1238 + * @param {Number} selected_image - The image id
1239 + * @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)
1025 1240 *
1026 1241 * @return void
1027 1242 */
1028 - function restore_selected_image(blog_id, selected_image) {
1243 + function restore_selected_image(blog_id, selected_image, done_callback) {
1029 1244
1030 1245 // if no selected images then exit.
1031 1246 if (0 == selected_image.length) return;
1032 1247
1033 - update_view_modal_message(wposmush.please_wait, $.unblockUI);
1034 - var data = { 'blog_id': blog_id, 'selected_image': selected_image };
1035 - smush_manager_send_command('restore_single_image', data, function(resp) {
1036 - handle_response_from_smush_manager(resp, update_view_single_image_complete);
1037 - });
1248 + block_ui(wposmush.please_wait);
1249 + var data = { 'blog_id': blog_id, 'selected_image': selected_image, skip_notice: true };
1250 +
1251 + smush_manager_send_command.apply({unique: false}, ['restore_single_image', data, function(resp) {
1252 + var done = function(resp_summary_alt) {
1253 + if ('undefined' != typeof(resp_summary_alt)) {
1254 + resp.summary = resp_summary_alt;
1255 + }
1256 +
1257 + handle_response_from_smush_manager(resp, update_view_single_image_complete);
1258 + }
1259 +
1260 + if (done_callback instanceof Function) {
1261 + done_callback(done);
1262 + } else {
1263 + done();
1264 + }
1265 + }]);
1038 1266 }
1039 1267
1040 1268 /**
1041 1269 * Updates the view once a single image is compressed or restored.
@@ -1047,9 +1275,9 @@
1047 1275 function update_view_single_image_complete(resp) {
1048 1276
1049 1277 if (resp.hasOwnProperty('success') && resp.success) {
1050 1278 $(".smush-information").text(resp.summary);
1051 - update_view_modal_message($("#smush-information-modal"), $.unblockUI);
1279 + block_ui('', $.extend(block_ui_custom_options, {message: $("#smush-information-modal")}));
1052 1280
1053 1281 $('.wpo-toggle-advanced-options.wpo_smush_single_image').removeClass('opened');
1054 1282
1055 1283 update_view_singe_image_compress(resp.operation, resp.summary, resp.restore_possible, resp);
@@ -1062,8 +1290,12 @@
1062 1290
1063 1291 if (!smush_affected_images.hasOwnProperty(blog_id)) smush_affected_images[blog_id] = {};
1064 1292 if (!smush_affected_images[blog_id].hasOwnProperty(image_id)) smush_affected_images[blog_id][image_id] = {};
1065 1293
1294 + if (resp.hasOwnProperty('media_column_html')) {
1295 + update_smush_information_media_library_column(blog_id, image_id, resp.media_column_html);
1296 + }
1297 +
1066 1298 if ('compress' == resp.operation) {
1067 1299 smush_affected_images[blog_id][image_id] = {
1068 1300 operation: resp.operation,
1069 1301 summary: resp.summary,
@@ -1069,19 +1301,34 @@
1069 1301 summary: resp.summary,
1070 1302 restore_possible: resp.restore_possible
1071 1303 }
1072 1304 } else {
1305 + if (image_id) {
1306 + reset_bulk_actions_dropdown();
1307 + }
1073 1308 smush_affected_images[blog_id][image_id] = {
1074 1309 operation: resp.operation
1075 1310 }
1076 1311 }
1077 1312 } else {
1078 - $(".smush-information").text(resp.error_message);
1079 - update_view_modal_message($("#smush-information-modal"), $.unblockUI);
1313 + // Update the error message to be user-friendly
1314 + if (/exceeded_max_filesize/.test(resp.error_message)) resp.error_message = wposmush.exceeded_max_filesize
1315 + block_ui(resp.error_message, {}, 4000);
1080 1316 }
1081 1317 }
1082 1318
1083 1319 /**
1320 + * Update information for the WP-Optimize column in the Media Library.
1321 + *
1322 + * @param {number} blog_id
1323 + * @param {number} image_id
1324 + * @param {string} html
1325 + */
1326 + function update_smush_information_media_library_column(blog_id, image_id, html) {
1327 + $(['.wpo-smush-media-library-column[data-blog="',blog_id,'"][data-id="',image_id,'"]'].join('')).parent().html(html);
1328 + }
1329 +
1330 + /**
1084 1331 * Update metabox view depending on a command response.
1085 1332 *
1086 1333 * @param {string} operation
1087 1334 * @param {string} summary
@@ -1090,8 +1337,10 @@
1090 1337 */
1091 1338 function update_view_singe_image_compress(operation, summary, restore_possible, smush_image_data) {
1092 1339 var wrapper = $("#smush_info").closest('#smush-metabox-inside-wrapper');
1093 1340
1341 + if (0 === wrapper.length) return;
1342 +
1094 1343 if ('compress' == operation) {
1095 1344 $(".wpo_smush_single_image").hide();
1096 1345 $(".wpo_restore_single_image").show();
1097 1346
@@ -1138,30 +1387,8 @@
1138 1387 }
1139 1388 });
1140 1389
1141 1390 /**
1142 - * Display a modal message
1143 - *
1144 - * @param {string} message The message or element to display
1145 - * @param {Function} callback Called when the overlay is clicked
1146 - *
1147 - * @return void
1148 - */
1149 - function update_view_modal_message(message, callback) {
1150 -
1151 - $.blockUI({
1152 - message: message,
1153 - onOverlayClick: callback,
1154 - baseZ: 160001,
1155 - css: {
1156 - width: '400px',
1157 - padding: '20px',
1158 - cursor: 'pointer'
1159 - }
1160 - });
1161 - }
1162 -
1163 - /**
1164 1391 * Check returned response from the smush manager and call update view callback.
1165 1392 *
1166 1393 * @param {Object} resp - response from smush manager.
1167 1394 * @param {Function} update_view_callback - callback function to update view.
@@ -1175,8 +1402,41 @@
1175 1402 alert(wposmush.error_unexpected_response);
1176 1403 console.log(resp);
1177 1404 }
1178 1405 }
1406 +
1407 + /**
1408 + * Retrieves the selected images from the media library.
1409 + *
1410 + * @return {jQuery} - The selected images as a jQuery object.
1411 + */
1412 + function get_media_library_selected_images() {
1413 + return $('input[name="media[]"]:checked');
1414 + }
1415 +
1416 + /**
1417 + * Retrieves the list of selected images from the media library.
1418 + *
1419 + * @return {Array.<number>} The list of selected image IDs.
1420 + */
1421 + function get_media_library_selected_images_list() {
1422 + var selected_images_list = [];
1423 + var $selected_images = get_media_library_selected_images();
1424 + $selected_images.each(function(index, element) {
1425 + selected_images_list.push(parseInt(element.value));
1426 + });
1427 + return selected_images_list;
1428 + }
1429 +
1430 + /**
1431 + * Resets the bulk action dropdown by setting its value to "-1" and unchecking all the selected checkboxes.
1432 + *
1433 + * @returns {void}
1434 + */
1435 + function reset_bulk_actions_dropdown() {
1436 + $('#bulk-action-selector-top, #bulk-action-selector-bottom').val("-1");
1437 + $('input[name="media[]"]:checked, #cb-select-all-1, #cb-select-all-2').prop('checked', false);
1438 + }
1179 1439
1180 1440 /**
1181 1441 * Send an action to the task manager via admin-ajax.php.
1182 1442 *
@@ -1183,60 +1443,53 @@
1183 1443 * @param {string} action The action to send
1184 1444 * @param {[type]} data Data to send
1185 1445 * @param {Function} callback Will be called with the results
1186 1446 * @param {boolean} json_parse JSON parse the results
1447 + * @param {boolean} wait Wait for the response
1187 1448 *
1188 1449 * @return {JSON}
1189 1450 */
1190 - function smush_manager_send_command(action, data, callback, json_parse) {
1451 + function smush_manager_send_command(action, data, callback, json_parse, wait) {
1191 1452
1192 1453 json_parse = ('undefined' === typeof json_parse) ? true : json_parse;
1193 - data = $.isEmptyObject(data) ? {'use_cache' : false} : data;
1454 + var _wait = ('undefined' === typeof wait) ? false : wait;
1194 1455
1195 - var ajax_data = {
1196 - action: 'updraft_smush_ajax',
1197 - subaction: action,
1198 - nonce: wposmush.smush_ajax_nonce,
1199 - data: data
1200 - };
1456 + var skip_notice = data.hasOwnProperty('skip_notice');
1457 + var data_has_only_skip_notice = skip_notice && 1 === Object.keys(data).length;
1458 + var is_data_empty = $.isEmptyObject(data);
1201 1459
1202 - var ajax_opts = {
1203 - type: 'POST',
1204 - url: ajaxurl,
1205 - data: ajax_data,
1206 - success: function(response) {
1460 + data = is_data_empty ? {'use_cache' : false} : data;
1461 + if (data_has_only_skip_notice) data.use_cache = false;
1207 1462
1208 - if (json_parse) {
1209 - try {
1210 - var resp = wpo_parse_json(response);
1211 - } catch (e) {
1212 - console.log("smush_manager_send_command JSON parse error");
1213 - console.log(e);
1214 - console.log(response);
1215 - alert(wposmush.error_unexpected_response);
1463 + (function(single_callback, _keep, _unique) {
1464 + heartbeat_agents.push(heartbeat.add_agent({
1465 + _wait: _wait,
1466 + _keep: _keep,
1467 + _unique: _unique,
1468 + command: 'updraft_smush_ajax',
1469 + command_data: {data: data, subaction: action},
1470 + callback: function(response) {
1471 + if (json_parse) {
1472 + try {
1473 + var resp = wpo_parse_json(response);
1474 + } catch (e) {
1475 + console.log("smush_manager_send_command JSON parse error");
1476 + console.log(e);
1477 + console.log(response);
1478 + alert(wposmush.error_unexpected_response);
1479 + }
1480 + if ('undefined' !== typeof single_callback) single_callback(resp);
1481 + } else {
1482 + if ('undefined' !== typeof single_callback) single_callback(response);
1216 1483 }
1217 - if ('undefined' !== typeof callback) callback(resp);
1218 - } else {
1219 - if ('undefined' !== typeof callback) callback(response);
1220 1484 }
1221 - },
1222 - error: function(response, status, error_code) {
1223 - console.log("smush_manager_send_command AJAX parse error: "+status+" ("+error_code+")");
1224 - if ('undefined' !== typeof callback) {
1225 - callback(response);
1226 - } else {
1227 - console.log(response);
1228 - alert(wposmush.error_unexpected_response);
1229 - }
1230 - },
1231 - dataType: 'text'
1485 + }));
1486 + })(callback, this.keep, this.unique);
1487 + };
1232 1488
1233 - }
1489 + // Attach heartbeat API events
1490 + heartbeat.setup();
1234 1491
1235 - $.ajax(ajax_opts);
1236 -
1237 - };
1238 -
1239 1492 // Gather smush options
1240 1493 var get_smush_options = function() {
1241 1494 var image_quality = '';
1242 1495 if ($('#enable_custom_compression').is(":checked")) {
@@ -1262,78 +1515,4 @@
1262 1515 }
1263 1516 wp_optimize.smush_settings = get_smush_options;
1264 1517 } // END WP_Optimize_Smush
1265 1518
1266 -/**
1267 - * Parse JSON string, including automatically detecting unwanted extra input and skipping it
1268 - *
1269 - * @param {string|object} json_mix_str - JSON string which need to parse and convert to object
1270 - *
1271 - * @throws SyntaxError|String (including passing on what JSON.parse may throw) if a parsing error occurs.
1272 - *
1273 - * @return mixed parsed JSON object. Will only return if parsing is successful (otherwise, will throw)
1274 - */
1275 -function wpo_parse_json(json_mix_str) {
1276 - // When using wp_send_json to return the value, the format is already parsed.
1277 - if ('object' === typeof json_mix_str) return json_mix_str;
1278 -
1279 - // Just try it - i.e. the 'default' case where things work (which can include extra whitespace/line-feeds, and simple strings, etc.).
1280 - try {
1281 - var result = JSON.parse(json_mix_str);
1282 - return result;
1283 - } catch (e) {
1284 - console.log("WPO: Exception when trying to parse JSON (1) - will attempt to fix/re-parse");
1285 - console.log(json_mix_str);
1286 - }
1287 -
1288 - var json_start_pos = json_mix_str.indexOf('{');
1289 - var json_last_pos = json_mix_str.lastIndexOf('}');
1290 -
1291 - // Case where some php notice may be added after or before json string
1292 - if (json_start_pos > -1 && json_last_pos > -1) {
1293 - var json_str = json_mix_str.slice(json_start_pos, json_last_pos + 1);
1294 - try {
1295 - var parsed = JSON.parse(json_str);
1296 - return parsed;
1297 - } catch (e) {
1298 - console.log("WPO: Exception when trying to parse JSON (2) - will attempt to fix/re-parse based upon bracket counting");
1299 -
1300 - var cursor = json_start_pos;
1301 - var open_count = 0;
1302 - var last_character = '';
1303 - var inside_string = false;
1304 -
1305 - // Don't mistake this for a real JSON parser. Its aim is to improve the odds in real-world cases seen, not to arrive at universal perfection.
1306 - while ((open_count > 0 || cursor == json_start_pos) && cursor <= json_last_pos) {
1307 -
1308 - var current_character = json_mix_str.charAt(cursor);
1309 -
1310 - if (!inside_string && '{' == current_character) {
1311 - open_count++;
1312 - } else if (!inside_string && '}' == current_character) {
1313 - open_count--;
1314 - } else if ('"' == current_character && '\\' != last_character) {
1315 - inside_string = inside_string ? false : true;
1316 - }
1317 -
1318 - last_character = current_character;
1319 - cursor++;
1320 - }
1321 -
1322 - console.log("Started at cursor="+json_start_pos+", ended at cursor="+cursor+" with result following:");
1323 - console.log(json_mix_str.substring(json_start_pos, cursor));
1324 -
1325 - try {
1326 - var parsed = JSON.parse(json_mix_str.substring(json_start_pos, cursor));
1327 - // console.log('WPO: JSON re-parse successful');
1328 - return parsed;
1329 - } catch (e) {
1330 - // Throw it again, so that our function works just like JSON.parse() in its behaviour.
1331 - throw e;
1332 - }
1333 -
1334 - }
1335 - }
1336 -
1337 - throw "WPO: could not parse the JSON";
1338 -
1339 -}