PluginProbe ʕ •ᴥ•ʔ
WP STAGING – WordPress Backups, Restore, Migration & Clone / 3.0.2
WP STAGING – WordPress Backups, Restore, Migration & Clone v3.0.2
4.11.2 4.11.1 4.11.0 4.10.0 4.9.5 4.9.4 4.9.3 4.9.2 4.9.1 4.9.0 4.8.1 trunk 3.0.0 3.0.1 3.0.2 3.0.3 3.0.4 3.0.5 3.0.6 3.1.0 3.1.1 3.1.2 3.1.3 3.1.4 3.10.0 3.2.0 3.3.1 3.3.2 3.3.3 3.4.1 3.4.3 3.5.0 3.6.0 3.7.1 3.8.0 3.8.1 3.8.2 3.8.3 3.8.4 3.8.5 3.8.6 3.8.7 3.9.0 3.9.1 3.9.2 3.9.3 3.9.4 4.0.0 4.1.0 4.1.1 4.1.2 4.1.3 4.1.4 4.2.0 4.2.1 4.3.0 4.3.1 4.3.2 4.4.0 4.5.0 4.6.0 4.7.0 4.7.1 4.7.2 4.7.3 4.8.0
wp-staging / assets / js / dist / wpstg-admin.js
wp-staging / assets / js / dist Last commit date
backup 3 years ago wpstg-admin-beta.js 3 years ago wpstg-admin-beta.js.map 3 years ago wpstg-admin-beta.min.js 5 years ago wpstg-admin-beta.min.js.map 3 years ago wpstg-admin-corrupt-settings.js 3 years ago wpstg-admin-corrupt-settings.js.map 3 years ago wpstg-admin-corrupt-settings.min.js 3 years ago wpstg-admin-corrupt-settings.min.js.map 3 years ago wpstg-admin-plugins.js 3 years ago wpstg-admin-plugins.js.map 3 years ago wpstg-admin-plugins.min.js 3 years ago wpstg-admin-plugins.min.js.map 3 years ago wpstg-admin-rating.js 3 years ago wpstg-admin-rating.js.map 3 years ago wpstg-admin-rating.min.js 3 years ago wpstg-admin-rating.min.js.map 3 years ago wpstg-admin.js 3 years ago wpstg-admin.js.map 3 years ago wpstg-admin.min.js 3 years ago wpstg-admin.min.js.map 3 years ago wpstg-blank-loader.js 3 years ago wpstg-blank-loader.js.map 3 years ago wpstg-blank-loader.min.js 3 years ago wpstg-blank-loader.min.js.map 3 years ago wpstg-sweetalert2.js 3 years ago wpstg-sweetalert2.js.map 3 years ago wpstg-sweetalert2.min.js 3 years ago wpstg-sweetalert2.min.js.map 3 years ago wpstg.js 3 years ago wpstg.js.map 3 years ago wpstg.min.js 3 years ago wpstg.min.js.map 3 years ago
wpstg-admin.js
3738 lines
1 (function () {
2 'use strict';
3
4 function _extends() {
5 _extends = Object.assign ? Object.assign.bind() : function (target) {
6 for (var i = 1; i < arguments.length; i++) {
7 var source = arguments[i];
8 for (var key in source) {
9 if (Object.prototype.hasOwnProperty.call(source, key)) {
10 target[key] = source[key];
11 }
12 }
13 }
14 return target;
15 };
16 return _extends.apply(this, arguments);
17 }
18 function _unsupportedIterableToArray(o, minLen) {
19 if (!o) return;
20 if (typeof o === "string") return _arrayLikeToArray(o, minLen);
21 var n = Object.prototype.toString.call(o).slice(8, -1);
22 if (n === "Object" && o.constructor) n = o.constructor.name;
23 if (n === "Map" || n === "Set") return Array.from(o);
24 if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
25 }
26 function _arrayLikeToArray(arr, len) {
27 if (len == null || len > arr.length) len = arr.length;
28 for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
29 return arr2;
30 }
31 function _createForOfIteratorHelperLoose(o, allowArrayLike) {
32 var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
33 if (it) return (it = it.call(o)).next.bind(it);
34 if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
35 if (it) o = it;
36 var i = 0;
37 return function () {
38 if (i >= o.length) return {
39 done: true
40 };
41 return {
42 done: false,
43 value: o[i++]
44 };
45 };
46 }
47 throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
48 }
49
50 /**
51 * Polyfills the `Element.prototype.closest` function if not available in the browser.
52 *
53 * @return {Function} A function that will return the closest element, by selector, to this element.
54 */
55 function polyfillClosest() {
56 if (Element.prototype.closest) {
57 if (!Element.prototype.matches) {
58 Element.prototype.matches = Element.prototype.msMatchesSelector || Element.prototype.webkitMatchesSelector;
59 }
60 Element.prototype.closest = function (s) {
61 var el = this;
62 do {
63 if (Element.prototype.matches.call(el, s)) return el;
64 el = el.parentElement || el.parentNode;
65 } while (el !== null && el.nodeType === 1);
66 return null;
67 };
68 }
69 return function (element, selector) {
70 return element instanceof Element ? element.closest(selector) : null;
71 };
72 }
73 var closest = polyfillClosest();
74
75 /**
76 * This is a namespaced port of https://github.com/tristen/hoverintent,
77 * with slight modification to accept selector with dynamically added element in dom,
78 * instead of just already present element.
79 *
80 * @param {HTMLElement} parent
81 * @param {string} selector
82 * @param {CallableFunction} onOver
83 * @param {CallableFunction} onOut
84 *
85 * @return {object}
86 */
87 function wpstgHoverIntent (parent, selector, onOver, onOut) {
88 var x;
89 var y;
90 var pX;
91 var pY;
92 var mouseOver = false;
93 var focused = false;
94 var h = {};
95 var state = 0;
96 var timer = 0;
97 var options = {
98 sensitivity: 7,
99 interval: 100,
100 timeout: 0,
101 handleFocus: false
102 };
103 function delay(el, e) {
104 if (timer) {
105 timer = clearTimeout(timer);
106 }
107 state = 0;
108 return focused ? undefined : onOut(el, e);
109 }
110 function tracker(e) {
111 x = e.clientX;
112 y = e.clientY;
113 }
114 function compare(el, e) {
115 if (timer) timer = clearTimeout(timer);
116 if (Math.abs(pX - x) + Math.abs(pY - y) < options.sensitivity) {
117 state = 1;
118 return focused ? undefined : onOver(el, e);
119 } else {
120 pX = x;
121 pY = y;
122 timer = setTimeout(function () {
123 compare(el, e);
124 }, options.interval);
125 }
126 }
127
128 // Public methods
129 h.options = function (opt) {
130 var focusOptionChanged = opt.handleFocus !== options.handleFocus;
131 options = Object.assign({}, options, opt);
132 if (focusOptionChanged) {
133 options.handleFocus ? addFocus() : removeFocus();
134 }
135 return h;
136 };
137 function dispatchOver(el, e) {
138 mouseOver = true;
139 if (timer) {
140 timer = clearTimeout(timer);
141 }
142 el.removeEventListener('mousemove', tracker, false);
143 if (state !== 1) {
144 pX = e.clientX;
145 pY = e.clientY;
146 el.addEventListener('mousemove', tracker, false);
147 timer = setTimeout(function () {
148 compare(el, e);
149 }, options.interval);
150 }
151 return this;
152 }
153
154 /**
155 * Newly added method,
156 * A wrapper around dispatchOver to support dynamically added elements to dom
157 */
158 function onMouseOver(event) {
159 if (event.target.matches(selector + ', ' + selector + ' *')) {
160 dispatchOver(event.target.closest(selector), event);
161 }
162 }
163 function dispatchOut(el, e) {
164 mouseOver = false;
165 if (timer) {
166 timer = clearTimeout(timer);
167 }
168 el.removeEventListener('mousemove', tracker, false);
169 if (state === 1) {
170 timer = setTimeout(function () {
171 delay(el, e);
172 }, options.timeout);
173 }
174 return this;
175 }
176
177 /**
178 * Newly added method,
179 * A wrapper around dispatchOut to support dynamically added elements to dom
180 */
181 function onMouseOut(event) {
182 if (event.target.matches(selector + ', ' + selector + ' *')) {
183 dispatchOut(event.target.closest(selector), event);
184 }
185 }
186 function dispatchFocus(el, e) {
187 if (!mouseOver) {
188 focused = true;
189 onOver(el, e);
190 }
191 }
192
193 /**
194 * Newly added method,
195 * A wrapper around dispatchFocus to support dynamically added elements to dom
196 */
197 function onFocus(event) {
198 if (event.target.matches(selector + ', ' + selector + ' *')) {
199 dispatchFocus(event.target.closest(selector), event);
200 }
201 }
202 function dispatchBlur(el, e) {
203 if (!mouseOver && focused) {
204 focused = false;
205 onOut(el, e);
206 }
207 }
208
209 /**
210 * Newly added method,
211 * A wrapper around dispatchBlur to support dynamically added elements to dom
212 */
213 function onBlur(event) {
214 if (event.target.matches(selector + ', ' + selector + ' *')) {
215 dispatchBlur(event.target.closest(selector), event);
216 }
217 }
218
219 /**
220 * Modified to support dynamically added element
221 */
222 function addFocus() {
223 parent.addEventListener('focus', onFocus, false);
224 parent.addEventListener('blur', onBlur, false);
225 }
226
227 /**
228 * Modified to support dynamically added element
229 */
230 function removeFocus() {
231 parent.removeEventListener('focus', onFocus, false);
232 parent.removeEventListener('blur', onBlur, false);
233 }
234
235 /**
236 * Modified to support dynamically added element
237 */
238 h.remove = function () {
239 if (!parent) {
240 return;
241 }
242 parent.removeEventListener('mouseover', onMouseOver, false);
243 parent.removeEventListener('mouseout', onMouseOut, false);
244 removeFocus();
245 };
246
247 /**
248 * Modified to support dynamically added element
249 */
250 if (parent) {
251 parent.addEventListener('mouseover', onMouseOver, false);
252 parent.addEventListener('mouseout', onMouseOut, false);
253 }
254 return h;
255 }
256
257 var WPStagingCommon = (function ($) {
258 var WPStagingCommon = {
259 continueErrorHandle: true,
260 retry: {
261 currentDelay: 0,
262 count: 0,
263 max: 10,
264 retryOnErrors: [401, 403, 404, 429, 502, 503, 504],
265 performingRequest: false,
266 incrementRetry: function incrementRetry(incrementRatio) {
267 if (incrementRatio === void 0) {
268 incrementRatio = 1.25;
269 }
270 WPStagingCommon.retry.performingRequest = true;
271 if (WPStagingCommon.retry.currentDelay === 0) {
272 // start with a delay of 1sec
273 WPStagingCommon.retry.currentDelay = 1000;
274 WPStagingCommon.retry.count = 1;
275 }
276 WPStagingCommon.retry.currentDelay += 500 * WPStagingCommon.retry.count * incrementRatio;
277 WPStagingCommon.retry.count++;
278 },
279 canRetry: function canRetry() {
280 return WPStagingCommon.retry.count < WPStagingCommon.retry.max;
281 },
282 reset: function reset() {
283 WPStagingCommon.retry.currentDelay = 0;
284 WPStagingCommon.retry.count = 0;
285 WPStagingCommon.retry.performingRequest = false;
286 }
287 },
288 memoryExhaustArticleLink: 'https://wp-staging.com/docs/php-fatal-error-allowed-memory-size-of-134217728-bytes-exhausted/',
289 cache: {
290 elements: [],
291 get: function get(selector) {
292 // It is already cached!
293 if ($.inArray(selector, this.elements) !== -1) {
294 return this.elements[selector];
295 }
296
297 // Create cache and return
298 this.elements[selector] = $(selector);
299 return this.elements[selector];
300 },
301 refresh: function refresh(selector) {
302 selector.elements[selector] = $(selector);
303 }
304 },
305 setJobId: function setJobId(jobId) {
306 localStorage.setItem('jobIdBeingProcessed', jobId);
307 },
308 getJobId: function getJobId() {
309 return localStorage.getItem('jobIdBeingProcessed');
310 },
311 listenTooltip: function listenTooltip() {
312 wpstgHoverIntent(document, '.wpstg--tooltip', function (target, event) {
313 target.querySelector('.wpstg--tooltiptext').style.visibility = 'visible';
314 }, function (target, event) {
315 target.querySelector('.wpstg--tooltiptext').style.visibility = 'hidden';
316 });
317 },
318 // Get the custom themed Swal Modal for WP Staging
319 // Easy to maintain now in one place now
320 getSwalModal: function getSwalModal(isContentCentered, customClasses) {
321 if (isContentCentered === void 0) {
322 isContentCentered = false;
323 }
324 if (customClasses === void 0) {
325 customClasses = {};
326 }
327 // common style for all swal modal used in WP Staging
328 var defaultCustomClasses = {
329 confirmButton: 'wpstg--btn--confirm wpstg-blue-primary wpstg-button wpstg-link-btn wpstg-100-width',
330 cancelButton: 'wpstg--btn--cancel wpstg-blue-primary wpstg-link-btn wpstg-100-width',
331 actions: 'wpstg--modal--actions',
332 popup: isContentCentered ? 'wpstg-swal-popup centered-modal' : 'wpstg-swal-popup'
333 };
334
335 // If a attribute exists in both default and additional attributes,
336 // The class(es) of the additional attribute will overrite the default one.
337 var options = {
338 customClass: Object.assign(defaultCustomClasses, customClasses),
339 buttonsStyling: false,
340 reverseButtons: true,
341 showClass: {
342 popup: 'wpstg--swal2-show wpstg-swal-show'
343 }
344 };
345 return wpstgSwal.mixin(options);
346 },
347 showSuccessModal: function showSuccessModal(htmlContent) {
348 this.getSwalModal().fire({
349 showConfirmButton: false,
350 showCancelButton: true,
351 cancelButtonText: 'OK',
352 icon: 'success',
353 title: 'Success!',
354 html: '<div class="wpstg--grey" style="text-align: left; margin-top: 8px;">' + htmlContent + '</div>'
355 });
356 },
357 showWarningModal: function showWarningModal(htmlContent) {
358 this.getSwalModal().fire({
359 showConfirmButton: false,
360 showCancelButton: true,
361 cancelButtonText: 'OK',
362 icon: 'warning',
363 title: '',
364 html: '<div class="wpstg--grey" style="text-align: left; margin-top: 8px;">' + htmlContent + '</div>'
365 });
366 },
367 showErrorModal: function showErrorModal(htmlContent) {
368 this.getSwalModal().fire({
369 showConfirmButton: false,
370 showCancelButton: true,
371 cancelButtonText: 'OK',
372 icon: 'error',
373 title: 'Error!',
374 html: '<div class="wpstg--grey" style="text-align: left; margin-top: 8px;">' + htmlContent + '</div>'
375 });
376 },
377 getSwalContainer: function getSwalContainer() {
378 return wpstgSwal.getContainer();
379 },
380 closeSwalModal: function closeSwalModal() {
381 wpstgSwal.close();
382 },
383 /**
384 * Treats a default response object generated by WordPress's
385 * wp_send_json_success() or wp_send_json_error() functions in
386 * PHP, parses it in JavaScript, and either throws if it's an error,
387 * or returns the data if the response is successful.
388 *
389 * @param {object} response
390 * @return {*}
391 */
392 getDataFromWordPressResponse: function getDataFromWordPressResponse(response) {
393 if (typeof response !== 'object') {
394 throw new Error('Unexpected response (ERR 1341)');
395 }
396 if (!response.hasOwnProperty('success')) {
397 throw new Error('Unexpected response (ERR 1342)');
398 }
399 if (!response.hasOwnProperty('data')) {
400 throw new Error('Unexpected response (ERR 1343)');
401 }
402 if (response.success === false) {
403 if (response.data instanceof Array && response.data.length > 0) {
404 throw new Error(response.data.shift());
405 } else {
406 throw new Error('Response was not successful');
407 }
408 } else {
409 // Successful response. Return the data.
410 return response.data;
411 }
412 },
413 isLoading: function isLoading(_isLoading) {
414 if (!_isLoading || _isLoading === false) {
415 WPStagingCommon.cache.get('.wpstg-loader').hide();
416 } else {
417 WPStagingCommon.cache.get('.wpstg-loader').show();
418 }
419 },
420 /**
421 * Convert the given url to make it slug compatible
422 * @param {string} url
423 * @return {string}
424 */
425 slugify: function slugify(url) {
426 return url.toString().toLowerCase().normalize('NFD').replace(/[\u0300-\u036f]/g, '').replace(/\s+/g, '-').replace(/&/g, '-and-').replace(/[^a-z0-9\-]/g, '').replace(/-+/g, '-').replace(/^-*/, '').replace(/-*$/, '');
427 },
428 showAjaxFatalError: function showAjaxFatalError(response, prependMessage, appendMessage) {
429 prependMessage = prependMessage ? prependMessage + '<br/><br/>' : 'Something went wrong! <br/><br/>';
430 appendMessage = appendMessage ? appendMessage + '<br/><br/>' : '<br/><br/>Please try the <a href=\'https://wp-staging.com/docs/wp-staging-settings-for-small-servers/\' target=\'_blank\'>WP Staging Small Server Settings</a> or submit an error report and contact us.';
431 if (response === false) {
432 WPStagingCommon.showError(prependMessage + ' Error: No response.' + appendMessage);
433 window.removeEventListener('beforeunload', WPStaging.warnIfClosingDuringProcess);
434 return;
435 }
436 if (typeof response.error !== 'undefined' && response.error) {
437 WPStagingCommon.showError(prependMessage + ' Error: ' + response.message + appendMessage);
438 window.removeEventListener('beforeunload', WPStaging.warnIfClosingDuringProcess);
439 return;
440 }
441 },
442 handleFetchErrors: function handleFetchErrors(response) {
443 if (!response.ok) {
444 WPStagingCommon.showError('Error: ' + response.status + ' - ' + response.statusText + '. Please try again or contact support.');
445 }
446 return response;
447 },
448 showError: function showError(message) {
449 // If retry request no need to show Error;
450 if (WPStagingCommon.retry.performingRequest) {
451 return;
452 }
453 WPStagingCommon.cache.get('#wpstg-try-again').css('display', 'inline-block');
454 WPStagingCommon.cache.get('#wpstg-cancel-cloning').text('Reset');
455 WPStagingCommon.cache.get('#wpstg-resume-cloning').show();
456 WPStagingCommon.cache.get('#wpstg-error-wrapper').show();
457 WPStagingCommon.cache.get('#wpstg-error-details').show().html(message);
458 WPStagingCommon.cache.get('#wpstg-removing-clone').removeClass('loading');
459 WPStagingCommon.cache.get('.wpstg-loader').hide();
460 $('.wpstg--modal--process--generic-problem').show().html(message);
461 },
462 resetErrors: function resetErrors() {
463 WPStagingCommon.cache.get('#wpstg-error-details').hide().html('');
464 },
465 /**
466 * Ajax Requests
467 * @param {Object} data
468 * @param {Function} callback
469 * @param {string} dataType
470 * @param {bool} showErrors
471 * @param {int} tryCount
472 * @param {float} incrementRatio
473 * @param {function} errorCallback
474 */
475 ajax: function ajax(data, callback, dataType, showErrors, tryCount, incrementRatio, errorCallback) {
476 if (incrementRatio === void 0) {
477 incrementRatio = null;
478 }
479 if (errorCallback === void 0) {
480 errorCallback = null;
481 }
482 if ('undefined' === typeof dataType) {
483 dataType = 'json';
484 }
485 if (false !== showErrors) {
486 showErrors = true;
487 }
488 tryCount = 'undefined' === typeof tryCount ? 0 : tryCount;
489 var retryLimit = 10;
490 var retryTimeout = 10000 * tryCount;
491 incrementRatio = parseInt(incrementRatio);
492 if (!isNaN(incrementRatio)) {
493 retryTimeout *= incrementRatio;
494 }
495 $.ajax({
496 url: ajaxurl + '?action=wpstg_processing&_=' + Date.now() / 1000,
497 type: 'POST',
498 dataType: dataType,
499 cache: false,
500 data: data,
501 error: function error(xhr, textStatus, errorThrown) {
502 console.log(xhr.status + ' ' + xhr.statusText + '---' + textStatus);
503 if (typeof errorCallback === 'function') {
504 // Custom error handler
505 errorCallback(xhr, textStatus, errorThrown);
506 if (!WPStagingCommon.continueErrorHandle) {
507 // Reset state
508 WPStagingCommon.continueErrorHandle = true;
509 return;
510 }
511 }
512
513 // Default error handler
514 tryCount++;
515 if (tryCount <= retryLimit) {
516 setTimeout(function () {
517 WPStagingCommon.ajax(data, callback, dataType, showErrors, tryCount, incrementRatio);
518 return;
519 }, retryTimeout);
520 } else {
521 var errorCode = 'undefined' === typeof xhr.status ? 'Unknown' : xhr.status;
522 WPStagingCommon.showError('Fatal Error: ' + errorCode + ' Please try the <a href=\'https://wp-staging.com/docs/wp-staging-settings-for-small-servers/\' target=\'_blank\'>WP Staging Small Server Settings</a> or submit an error report and contact us.');
523 }
524 },
525 success: function success(data) {
526 if ('function' === typeof callback) {
527 callback(data);
528 }
529 },
530 statusCode: {
531 404: function _() {
532 if (tryCount >= retryLimit) {
533 WPStagingCommon.showError('Error 404 - Can\'t find ajax request URL! Please try the <a href=\'https://wp-staging.com/docs/wp-staging-settings-for-small-servers/\' target=\'_blank\'>WP Staging Small Server Settings</a> or submit an error report and contact us.');
534 }
535 },
536 500: function _() {
537 if (tryCount >= retryLimit) {
538 WPStagingCommon.showError('Fatal Error 500 - Internal server error while processing the request! Please try the <a href=\'https://wp-staging.com/docs/wp-staging-settings-for-small-servers/\' target=\'_blank\'>WP Staging Small Server Settings</a> or submit an error report and contact us.');
539 }
540 },
541 504: function _() {
542 if (tryCount > retryLimit) {
543 WPStagingCommon.showError('Error 504 - It looks like your server is rate limiting ajax requests. Please try to resume after a minute. If this still not works try the <a href=\'https://wp-staging.com/docs/wp-staging-settings-for-small-servers/\' target=\'_blank\'>WP Staging Small Server Settings</a> or submit an error report and contact us.\n\ ');
544 }
545 },
546 502: function _() {
547 if (tryCount >= retryLimit) {
548 WPStagingCommon.showError('Error 502 - It looks like your server is rate limiting ajax requests. Please try to resume after a minute. If this still not works try the <a href=\'https://wp-staging.com/docs/wp-staging-settings-for-small-servers/\' target=\'_blank\'>WP Staging Small Server Settings</a> or submit an error report and contact us.\n\ ');
549 }
550 },
551 503: function _() {
552 if (tryCount >= retryLimit) {
553 WPStagingCommon.showError('Error 503 - It looks like your server is rate limiting ajax requests. Please try to resume after a minute. If this still not works try the <a href=\'https://wp-staging.com/docs/wp-staging-settings-for-small-servers/\' target=\'_blank\'>WP Staging Small Server Settings</a> or submit an error report and contact us.\n\ ');
554 }
555 },
556 429: function _() {
557 if (tryCount >= retryLimit) {
558 WPStagingCommon.showError('Error 429 - It looks like your server is rate limiting ajax requests. Please try to resume after a minute. If this still not works try the <a href=\'https://wp-staging.com/docs/wp-staging-settings-for-small-servers/\' target=\'_blank\'>WP Staging Small Server Settings</a> or submit an error report and contact us.\n\ ');
559 }
560 },
561 403: function _() {
562 if (tryCount >= retryLimit) {
563 WPStagingCommon.showError('Refresh page or login again! The process should be finished successfully. \n\ ');
564 }
565 }
566 }
567 });
568 }
569 };
570 return WPStagingCommon;
571 })(jQuery);
572
573 /**
574 * WP STAGING basic jQuery replacement
575 */
576
577 /**
578 * Shortcut for document.querySelector() or jQuery's $()
579 * Return single element only
580 */
581 function qs(selector) {
582 return document.querySelector(selector);
583 }
584
585 /**
586 * Shortcut for document.querySelector() or jQuery's $()
587 * Return collection of elements
588 */
589 function all(selector) {
590 return document.querySelectorAll(selector);
591 }
592
593 /**
594 * alternative of jQuery - $(parent).on(event, selector, handler)
595 */
596 function addEvent(parent, evt, selector, handler) {
597 if (!parent instanceof Element) {
598 return;
599 }
600 parent.addEventListener(evt, function (event) {
601 if (event.target.matches(selector + ', ' + selector + ' *')) {
602 handler(event.target.closest(selector), event);
603 }
604 }, false);
605 }
606 function slideDown(element, duration) {
607 if (duration === void 0) {
608 duration = 400;
609 }
610 element.style.display = 'block';
611 element.style.overflow = 'hidden';
612 var height = element.offsetHeight;
613 element.style.height = '0px';
614 element.style.transitionProperty = 'height';
615 element.style.transitionDuration = duration + 'ms';
616 setTimeout(function () {
617 element.style.height = height + 'px';
618 window.setTimeout(function () {
619 element.style.removeProperty('height');
620 element.style.removeProperty('overflow');
621 element.style.removeProperty('transition-duration');
622 element.style.removeProperty('transition-property');
623 }, duration);
624 }, 0);
625 }
626 function slideUp(element, duration) {
627 if (duration === void 0) {
628 duration = 400;
629 }
630 element.style.display = 'block';
631 element.style.overflow = 'hidden';
632 var height = element.offsetHeight;
633 element.style.height = height + 'px';
634 element.style.transitionProperty = 'height';
635 element.style.transitionDuration = duration + 'ms';
636 setTimeout(function () {
637 element.style.height = '0px';
638 window.setTimeout(function () {
639 element.style.display = 'none';
640 element.style.removeProperty('height');
641 element.style.removeProperty('overflow');
642 element.style.removeProperty('transition-duration');
643 element.style.removeProperty('transition-property');
644 }, duration);
645 }, 0);
646 }
647 function getNextSibling(element, selector) {
648 var sibling = element.nextElementSibling;
649 while (sibling) {
650 if (sibling.matches(selector)) {
651 return sibling;
652 }
653 sibling = sibling.nextElementSibling;
654 }
655 }
656 function getPreviousSibling(element, selector) {
657 var sibling = element.previousElementSibling;
658 while (sibling) {
659 if (sibling.matches(selector)) {
660 return sibling;
661 }
662 sibling = sibling.previousElementSibling;
663 }
664 }
665 function getParents(element, selector) {
666 var result = [];
667 for (var parent = element && element.parentElement; parent; parent = parent.parentElement) {
668 if (parent.matches(selector)) {
669 result.push(parent);
670 }
671 }
672 return result;
673 }
674
675 /**
676 * Dispatches a change on an element that will trigger, depending on the element type,
677 * cascading changes on elements dependant on the one that triggered the change and that
678 * belong in the same container.
679 *
680 * @param {Element} element A reference to the Element the change was triggered from.
681 *
682 * @return {void} The function does not return any value and will have the side-effect of
683 * hiding or showing dependant elements.
684 */
685 function handleDisplayDependencies(element) {
686 if (!element instanceof Element || !element.id) {
687 return;
688 }
689 var containerSelector = '.wpstg-container';
690 // Use the default WordPress CSS class to hide and show the objects.
691 var hiddenClass = 'hidden';
692 var elementType = element.getAttribute('type');
693 switch (elementType) {
694 case 'checkbox':
695 // Go as high as the container that contains this element.
696 var container = closest(element, containerSelector);
697 if (container === null) {
698 return;
699 }
700 var showIfChecked = container.querySelectorAll("[data-show-if-checked=\"" + element.id + "\"]");
701 var showIfUnchecked = container.querySelectorAll("[data-show-if-unchecked=\"" + element.id + "\"]");
702 var checked = element.checked;
703 if (showIfChecked.length) {
704 for (var _iterator = _createForOfIteratorHelperLoose(showIfChecked), _step; !(_step = _iterator()).done;) {
705 var el = _step.value;
706 if (checked) {
707 el.classList.remove(hiddenClass);
708 } else {
709 el.classList.add(hiddenClass);
710 }
711 }
712 }
713 if (showIfUnchecked.length) {
714 for (var _iterator2 = _createForOfIteratorHelperLoose(showIfUnchecked), _step2; !(_step2 = _iterator2()).done;) {
715 var _el = _step2.value;
716 if (checked) {
717 _el.classList.add(hiddenClass);
718 } else {
719 _el.classList.remove(hiddenClass);
720 }
721 }
722 }
723 return;
724 default:
725 // Not a type we handle.
726 return;
727 }
728 }
729
730 /**
731 * Toggle target element set in data-wpstg-target of the given element
732 *
733 * @param {Element} element A reference to the Element the change was triggered from.
734 *
735 * @return {void} The function does not return any value and will have the side-effect of
736 * hiding or showing dependant elements.
737 */
738 function handleToggleElement(element) {
739 if (!element instanceof Element || !element.getAttribute('data-wpstg-target')) {
740 return;
741 }
742 var containerSelector = '.wpstg_admin';
743 // Use the default WordPress CSS class to hide and show the objects.
744 var hiddenClass = 'hidden';
745
746 // Go as high as the container that contains this element.
747 var container = closest(element, containerSelector);
748 if (container === null) {
749 return;
750 }
751 var elements = container.querySelectorAll(element.getAttribute('data-wpstg-target'));
752 if (elements.length) {
753 for (var _iterator4 = _createForOfIteratorHelperLoose(elements), _step4; !(_step4 = _iterator4()).done;) {
754 var el = _step4.value;
755 el.classList.toggle(hiddenClass);
756 }
757 }
758 }
759
760 /**
761 * Copy text in data-wpstg-copy to element(s) in data-wpstg-target
762 *
763 * @param {Element} element
764 *
765 * @return {void}
766 */
767 function handleCopyPaste(element) {
768 if (!element instanceof Element || !element.getAttribute('data-wpstg-target') || !element.getAttribute('data-wpstg-copy')) {
769 return;
770 }
771 var containerSelector = '.wpstg_admin';
772
773 // Go as high as the container that contains this element.
774 var container = closest(element, containerSelector);
775 if (container === null) {
776 return;
777 }
778 navigator.clipboard.writeText(element.getAttribute('data-wpstg-copy'));
779 var elements = container.querySelectorAll(element.getAttribute('data-wpstg-target'));
780 if (elements.length) {
781 for (var _iterator5 = _createForOfIteratorHelperLoose(elements), _step5; !(_step5 = _iterator5()).done;) {
782 var el = _step5.value;
783 el.value = element.getAttribute('data-wpstg-copy', '');
784 }
785 }
786 }
787
788 /**
789 * Copy text in data-wpstg-source to clipboard
790 *
791 * @param {Element} element
792 *
793 * @return {void}
794 */
795 function handleCopyToClipboard(element) {
796 if (!element instanceof Element || !element.getAttribute('data-wpstg-source')) {
797 return;
798 }
799 var containerSelector = '.wpstg_admin';
800
801 // Go as high as the container that contains this element.
802 var container = closest(element, containerSelector);
803 if (container === null) {
804 return;
805 }
806 var el = container.querySelector(element.getAttribute('data-wpstg-source'));
807 if (el) {
808 navigator.clipboard.writeText(el.value);
809 }
810 }
811
812 /**
813 * Enable side bar menu and set url on tab click
814 */
815 var WpstgSidebarMenu = /*#__PURE__*/function () {
816 function WpstgSidebarMenu() {
817 this.init();
818 }
819 var _proto = WpstgSidebarMenu.prototype;
820 _proto.init = function init() {
821 this.wpstdStagingTab = document.querySelector('#wpstg--tab--toggle--staging');
822 this.wpstdBackupTab = document.querySelector('#wpstg--tab--toggle--backup');
823 this.wpstdSidebarMenu = document.querySelector('#toplevel_page_wpstg_clone');
824 this.addEvents();
825 };
826 _proto.addEvents = function addEvents() {
827 var _this = this;
828 if (this.wpstdStagingTab !== null) {
829 this.wpstdStagingTab.addEventListener('click', function () {
830 _this.setPageUrl('wpstg_clone');
831 _this.setSidebarMenu('wpstg_clone');
832 });
833 }
834 if (this.wpstdBackupTab !== null) {
835 this.wpstdBackupTab.addEventListener('click', function () {
836 _this.setPageUrl('wpstg_backup');
837 _this.setSidebarMenu('wpstg_backup');
838 });
839 }
840 };
841 _proto.setPageUrl = function setPageUrl(page) {
842 window.history.pushState(null, null, window.location.pathname + '?page=' + page);
843 };
844 _proto.setSidebarMenu = function setSidebarMenu(page) {
845 var wpstgSidebarMenuElements = this.wpstdSidebarMenu.querySelector('ul').querySelectorAll('li');
846 if (wpstgSidebarMenuElements.length > 0) {
847 for (var i = 0; i < wpstgSidebarMenuElements.length; i++) {
848 wpstgSidebarMenuElements[i].classList.remove('current');
849 if (wpstgSidebarMenuElements[i].querySelector('a') !== null) {
850 if (wpstgSidebarMenuElements[i].querySelector('a').getAttribute('href') === 'admin.php?page=' + page) {
851 wpstgSidebarMenuElements[i].classList.add('current');
852 }
853 }
854 }
855 }
856 };
857 return WpstgSidebarMenu;
858 }();
859
860 /**
861 * Enable/Disable cloning for staging site
862 */
863 var WpstgCloneStaging = /*#__PURE__*/function () {
864 function WpstgCloneStaging(pageWrapperId, wpstgObject) {
865 if (pageWrapperId === void 0) {
866 pageWrapperId = '#wpstg-clonepage-wrapper';
867 }
868 if (wpstgObject === void 0) {
869 wpstgObject = wpstg;
870 }
871 this.pageWrapper = qs(pageWrapperId);
872 this.wpstgObject = wpstgObject;
873 this.enableButtonId = '#wpstg-enable-staging-cloning';
874 this.enableAction = 'wpstg_enable_staging_cloning';
875 this.notyf = new Notyf({
876 duration: 10000,
877 position: {
878 x: 'center',
879 y: 'bottom'
880 },
881 dismissible: true,
882 types: [{
883 type: 'warning',
884 background: 'orange',
885 icon: false
886 }]
887 });
888 this.init();
889 }
890 var _proto = WpstgCloneStaging.prototype;
891 _proto.addEvents = function addEvents() {
892 var _this = this;
893 if (this.pageWrapper === null) {
894 return;
895 }
896 addEvent(this.pageWrapper, 'click', this.enableButtonId, function () {
897 _this.sendRequest(_this.enableAction);
898 });
899 new WpstgSidebarMenu();
900 };
901 _proto.init = function init() {
902 this.addEvents();
903 };
904 _proto.sendRequest = function sendRequest(action) {
905 var _this2 = this;
906 fetch(this.wpstgObject.ajaxUrl, {
907 method: 'POST',
908 credentials: 'same-origin',
909 body: new URLSearchParams({
910 action: action,
911 accessToken: this.wpstgObject.accessToken,
912 nonce: this.wpstgObject.nonce
913 }),
914 headers: {
915 'Content-Type': 'application/x-www-form-urlencoded'
916 }
917 }).then(function (response) {
918 if (response.ok) {
919 return response.json();
920 }
921 return Promise.reject(response);
922 }).then(function (data) {
923 // Reload current page if successful.
924 if ('undefined' !== typeof data.success && data.success) {
925 location.reload();
926 return;
927 }
928
929 // There will be message probably in case of error
930 if ('undefined' !== typeof data.message) {
931 _this2.notyf.error(data.message);
932 return;
933 }
934 _this2.notyf.error(_this2.wpstgObject.i18n['somethingWentWrong']);
935 })["catch"](function (error) {
936 console.warn(_this2.wpstgObject.i18n['somethingWentWrong'], error);
937 });
938 };
939 return WpstgCloneStaging;
940 }();
941
942 /**
943 * Fetch directory direct child directories
944 */
945 var WpstgDirectoryNavigation = /*#__PURE__*/function () {
946 function WpstgDirectoryNavigation(directoryListingSelector, wpstgObject, notyf) {
947 if (directoryListingSelector === void 0) {
948 directoryListingSelector = '#wpstg-directories-listing';
949 }
950 if (wpstgObject === void 0) {
951 wpstgObject = WPStagingCommon;
952 }
953 if (notyf === void 0) {
954 notyf = null;
955 }
956 this.directoryListingContainer = qs(directoryListingSelector);
957 this.wpstgObject = wpstgObject;
958 this.dirCheckboxSelector = '.wpstg-check-dir';
959 this.dirExpandSelector = '.wpstg-expand-dirs';
960 this.unselectAllDirsSelector = '.wpstg-unselect-dirs';
961 this.selectDefaultDirsSelector = '.wpstg-select-dirs-default';
962 this.fetchChildrenAction = 'wpstg_fetch_dir_children';
963 this.currentCheckboxElement = null;
964 this.currentParentDiv = null;
965 this.currentLoader = null;
966 this.existingExcludes = [];
967 this.excludedDirectories = [];
968 this.isDefaultSelected = false;
969 this.notyf = notyf;
970 this.init();
971 }
972 var _proto = WpstgDirectoryNavigation.prototype;
973 _proto.addEvents = function addEvents() {
974 var _this = this;
975 if (this.directoryListingContainer === null) {
976 console.log('Error: Unable to add directory navigation events.');
977 return;
978 }
979 addEvent(this.directoryListingContainer, 'change', this.dirCheckboxSelector, function (element, event) {
980 event.preventDefault();
981 });
982 addEvent(this.directoryListingContainer, 'click', this.dirExpandSelector, function (element, event) {
983 event.preventDefault();
984 if (_this.toggleDirExpand(element)) {
985 _this.sendRequest(_this.fetchChildrenAction, element);
986 }
987 });
988 addEvent(this.directoryListingContainer, 'click', this.unselectAllDirsSelector, function () {
989 _this.unselectAll();
990 });
991 addEvent(this.directoryListingContainer, 'click', this.selectDefaultDirsSelector, function () {
992 _this.selectDefault();
993 });
994 addEvent(this.directoryListingContainer, 'click', '.wpstg-expand-dirs', function (target, event) {
995 event.preventDefault();
996 _this.toggleDirectoryNavigation(target);
997 });
998 addEvent(this.directoryListingContainer, 'change', 'input.wpstg-check-dir', function (target) {
999 _this.updateDirectorySelection(target);
1000 });
1001 };
1002 _proto.init = function init() {
1003 this.addEvents();
1004 this.parseExcludes();
1005 }
1006
1007 /**
1008 * Toggle Dir Expand,
1009 * Return true if children aren't fetched
1010 * @param {HTMLElement} element
1011 * @return {boolean}
1012 */;
1013 _proto.toggleDirExpand = function toggleDirExpand(element) {
1014 this.currentParentDiv = element.parentElement;
1015 this.currentCheckboxElement = getPreviousSibling(element, 'input');
1016 this.currentLoader = this.currentParentDiv.querySelector('.wpstg-is-dir-loading');
1017 if (this.currentCheckboxElement.getAttribute('wpstg-data-navigateable', 'false') === 'false') {
1018 return false;
1019 }
1020 if (this.currentCheckboxElement.getAttribute('wpstg-data-scanned', 'false') === 'false') {
1021 return true;
1022 }
1023 return false;
1024 };
1025 _proto.sendRequest = function sendRequest(action) {
1026 var _this2 = this;
1027 if (this.currentLoader !== null) {
1028 this.currentLoader.style.display = 'inline-block';
1029 }
1030 var changed = this.currentCheckboxElement.getAttribute('wpstg-data-changed');
1031 var path = this.currentCheckboxElement.getAttribute('wpstg-data-path');
1032 var prefix = this.currentCheckboxElement.getAttribute('wpstg-data-prefix');
1033 fetch(this.wpstgObject.ajaxUrl, {
1034 method: 'POST',
1035 credentials: 'same-origin',
1036 body: new URLSearchParams({
1037 action: action,
1038 accessToken: this.wpstgObject.accessToken,
1039 nonce: this.wpstgObject.nonce,
1040 dirPath: path,
1041 prefix: prefix,
1042 isChecked: this.currentCheckboxElement.checked,
1043 forceDefault: changed === 'true'
1044 }),
1045 headers: {
1046 'Content-Type': 'application/x-www-form-urlencoded'
1047 }
1048 }).then(function (response) {
1049 if (response.ok) {
1050 return response.json();
1051 }
1052 return Promise.reject(response);
1053 }).then(function (data) {
1054 if ('undefined' !== typeof data.success && data.success) {
1055 _this2.currentCheckboxElement.setAttribute('wpstg-data-scanned', true);
1056 var dirContainer = document.createElement('div');
1057 dirContainer.classList.add('wpstg-dir');
1058 dirContainer.classList.add('wpstg-subdir');
1059 dirContainer.innerHTML = JSON.parse(data.directoryListing);
1060 _this2.currentParentDiv.appendChild(dirContainer);
1061 if (_this2.currentLoader !== null) {
1062 _this2.currentLoader.style.display = 'none';
1063 }
1064 slideDown(dirContainer);
1065 return;
1066 }
1067 if (_this2.notyf !== null) {
1068 _this2.notyf.error(_this2.wpstgObject.i18n['somethingWentWrong']);
1069 } else {
1070 alert('Error: ' + _this2.wpstgObject.i18n['somethingWentWrong']);
1071 }
1072 })["catch"](function (error) {
1073 console.warn(_this2.wpstgObject.i18n['somethingWentWrong'], error);
1074 });
1075 };
1076 _proto.getExcludedDirectories = function getExcludedDirectories() {
1077 var _this3 = this,
1078 _this$wpstgObject$set;
1079 this.excludedDirectories = [];
1080 this.directoryListingContainer.querySelectorAll('.wpstg-dir input:not(:checked)').forEach(function (element) {
1081 if (!_this3.isParentExcluded(element.value)) {
1082 _this3.excludedDirectories.push(element.value);
1083 }
1084 });
1085 if (!this.existingExcludes) {
1086 this.existingExcludes = [];
1087 }
1088 this.existingExcludes.forEach(function (exclude) {
1089 if (!_this3.isParentExcluded(exclude) && !_this3.isScanned(exclude)) {
1090 _this3.excludedDirectories.push(exclude);
1091 }
1092 });
1093 return this.excludedDirectories.join((_this$wpstgObject$set = this.wpstgObject.settings) == null ? void 0 : _this$wpstgObject$set.directorySeparator);
1094 }
1095
1096 /**
1097 * @param {string} path
1098 * @return {bool}
1099 */;
1100 _proto.isParentExcluded = function isParentExcluded(path) {
1101 var isParentAlreadyExcluded = false;
1102 this.excludedDirectories.forEach(function (dir) {
1103 if (path.startsWith(dir + '/')) {
1104 isParentAlreadyExcluded = true;
1105 }
1106 });
1107 return isParentAlreadyExcluded;
1108 };
1109 _proto.getExtraDirectoriesRootOnly = function getExtraDirectoriesRootOnly() {
1110 this.getExcludedDirectories();
1111 var extraDirectories = [];
1112 this.directoryListingContainer.querySelectorAll(':not(.wpstg-subdir)>.wpstg-dir>input.wpstg-wp-non-core-dir:checked').forEach(function (element) {
1113 extraDirectories.push(element.value);
1114 });
1115
1116 // Check if extra directories text area exists
1117 // TODO: remove extraCustomDirectories code if no one require extraCustomDirectories...
1118 var extraDirectoriesTextArea = qs('#wpstg_extraDirectories');
1119 if (extraDirectoriesTextArea === null || extraDirectoriesTextArea.value === '') {
1120 var _this$wpstgObject$set2;
1121 return extraDirectories.join((_this$wpstgObject$set2 = this.wpstgObject.settings) == null ? void 0 : _this$wpstgObject$set2.directorySeparator);
1122 }
1123 var extraCustomDirectories = extraDirectoriesTextArea.value.split(/\r?\n/);
1124 return extraDirectories.concat(extraCustomDirectories).join(this.wpstgObject.settings.directorySeparator);
1125 };
1126 _proto.unselectAll = function unselectAll() {
1127 this.directoryListingContainer.querySelectorAll('.wpstg-dir input').forEach(function (element) {
1128 element.checked = false;
1129 });
1130 this.countSelectedFiles();
1131 };
1132 _proto.selectDefault = function selectDefault() {
1133 // unselect all checkboxes
1134 this.unselectAll();
1135
1136 // only select those checkboxes whose class is wpstg-wp-core-dir
1137 this.directoryListingContainer.querySelectorAll('.wpstg-dir input.wpstg-wp-core-dir').forEach(function (element) {
1138 element.checked = true;
1139 });
1140
1141 // then unselect those checkboxes whose parent has wpstg extra checkbox
1142 this.directoryListingContainer.querySelectorAll('.wpstg-dir > .wpstg-wp-non-core-dir').forEach(function (element) {
1143 element.parentElement.querySelectorAll('input.wpstg-wp-core-dir').forEach(function (element) {
1144 element.checked = false;
1145 });
1146 });
1147 this.isDefaultSelected = true;
1148 this.countSelectedFiles();
1149 };
1150 _proto.parseExcludes = function parseExcludes() {
1151 this.existingExcludes = this.directoryListingContainer.getAttribute('wpstg-data-existing-excludes', []);
1152 if (typeof this.existingExcludes === 'undefined' || !this.existingExcludes) {
1153 this.existingExcludes = [];
1154 return;
1155 }
1156 if (this.existingExcludes.length === 0) {
1157 this.existingExcludes = [];
1158 return;
1159 }
1160 var existingExcludes = this.existingExcludes.split(',');
1161 this.existingExcludes = existingExcludes.map(function (exclude) {
1162 if (exclude.substr(0, 1) === '/') {
1163 return exclude.slice(1);
1164 }
1165 return exclude;
1166 });
1167 };
1168 _proto.isScanned = function isScanned(exclude) {
1169 var scanned = false;
1170 this.directoryListingContainer.querySelectorAll('.wpstg-dir>input').forEach(function (element) {
1171 if (element.value === exclude) {
1172 scanned = true;
1173 }
1174 });
1175 return scanned;
1176 };
1177 _proto.toggleDirectoryNavigation = function toggleDirectoryNavigation(element) {
1178 var cbElement = getPreviousSibling(element, 'input');
1179 if (cbElement.getAttribute('wpstg-data-navigateable', 'false') === 'false') {
1180 return;
1181 }
1182 if (cbElement.getAttribute('wpstg-data-scanned', 'false') === 'false') {
1183 return;
1184 }
1185 var subDirectories = getNextSibling(element, '.wpstg-subdir');
1186 if (subDirectories.style.display === 'none') {
1187 slideDown(subDirectories);
1188 } else {
1189 slideUp(subDirectories);
1190 }
1191 };
1192 _proto.updateDirectorySelection = function updateDirectorySelection(element) {
1193 var parent = element.parentElement;
1194 element.setAttribute('wpstg-data-changed', 'true');
1195 if (element.checked) {
1196 getParents(parent, '.wpstg-dir').forEach(function (parElem) {
1197 for (var i = 0; i < parElem.children.length; i++) {
1198 if (parElem.children[i].matches('.wpstg-check-dir')) {
1199 parElem.children[i].checked = true;
1200 }
1201 }
1202 });
1203 parent.querySelectorAll('.wpstg-expand-dirs').forEach(function (x) {
1204 if (x.textContent === 'wp-admin' || x.textContent === 'wp-includes') {
1205 return;
1206 }
1207 x.classList.remove('disabled');
1208 });
1209 parent.querySelectorAll('.wpstg-subdir .wpstg-check-dir').forEach(function (x) {
1210 x.checked = true;
1211 });
1212 } else {
1213 parent.querySelectorAll('.wpstg-expand-dirs, .wpstg-check-subdirs').forEach(function (x) {
1214 x.classList.add('disabled');
1215 });
1216 parent.querySelectorAll('.wpstg-dir .wpstg-check-dir').forEach(function (x) {
1217 x.checked = false;
1218 });
1219 }
1220 this.countSelectedFiles();
1221 };
1222 _proto.countSelectedFiles = function countSelectedFiles() {
1223 var themesCount = this.directoryListingContainer.querySelectorAll('[wpstg-data-dir-type="theme"]:checked').length;
1224 var pluginsCount = this.directoryListingContainer.querySelectorAll('[wpstg-data-dir-type="plugin"]:checked').length;
1225 var filesCountElement = qs('#wpstg-files-count');
1226 if (themesCount === 0 && pluginsCount === 0) {
1227 filesCountElement.classList.add('danger');
1228 filesCountElement.innerHTML = this.wpstgObject.i18n['noFileSelected'];
1229 } else {
1230 filesCountElement.classList.remove('danger');
1231 filesCountElement.innerHTML = this.wpstgObject.i18n['filesSelected'].replace('{t}', themesCount).replace('{p}', pluginsCount);
1232 }
1233 };
1234 return WpstgDirectoryNavigation;
1235 }();
1236
1237 /**
1238 * Database tables selection
1239 */
1240 var WpstgTableSelection = /*#__PURE__*/function () {
1241 function WpstgTableSelection(databaseTableSectionSelector, workflowSelector, networkCloneSelector, inputSelector, wpstgObject) {
1242 if (databaseTableSectionSelector === void 0) {
1243 databaseTableSectionSelector = '#wpstg-scanning-db';
1244 }
1245 if (workflowSelector === void 0) {
1246 workflowSelector = '#wpstg-workflow';
1247 }
1248 if (networkCloneSelector === void 0) {
1249 networkCloneSelector = '#wpstg_network_clone';
1250 }
1251 if (inputSelector === void 0) {
1252 inputSelector = '#wpstg_select_tables_cloning';
1253 }
1254 if (wpstgObject === void 0) {
1255 wpstgObject = wpstg;
1256 }
1257 this.databaseTableSection = qs(databaseTableSectionSelector);
1258 this.workflow = qs(workflowSelector);
1259 this.networkCloneSelector = networkCloneSelector;
1260 this.networkCloneCheckbox = qs(networkCloneSelector);
1261 this.wpstgObject = wpstgObject;
1262 this.isAllTablesChecked = true;
1263 this.isMultisite = this.wpstgObject.isMultisite === '1';
1264 this.isNetworkClone = false;
1265 this.inputSelector = inputSelector;
1266 this.input = qs(this.inputSelector);
1267 this.init();
1268 }
1269 var _proto = WpstgTableSelection.prototype;
1270 _proto.setNetworkClone = function setNetworkClone(isNetworkClone) {
1271 this.isNetworkClone = isNetworkClone;
1272 };
1273 _proto.addEvents = function addEvents() {
1274 var _this = this;
1275 if (this.workflow === null) {
1276 console.log('Error: database table section is null. Cannot register events');
1277 return;
1278 }
1279 addEvent(this.workflow, 'change', this.networkCloneSelector, function () {
1280 _this.selectDefaultTables();
1281 });
1282 addEvent(this.workflow, 'change', this.inputSelector, function () {
1283 _this.countSelectedTables();
1284 });
1285 addEvent(this.workflow, 'click', '.wpstg-button-select', function (target, event) {
1286 event.preventDefault();
1287 _this.selectDefaultTables();
1288 });
1289 addEvent(this.workflow, 'click', '.wpstg-button-unselect', function (target, event) {
1290 event.preventDefault();
1291 _this.toggleTableSelection();
1292 });
1293 addEvent(this.workflow, 'click', '.wpstg-button-unselect-wpstg', function (target, event) {
1294 event.preventDefault();
1295 _this.unselectWPSTGTables();
1296 });
1297 };
1298 _proto.init = function init() {
1299 this.addEvents();
1300 };
1301 _proto.getRegexPattern = function getRegexPattern() {
1302 var pattern = '^' + this.wpstgObject.tblprefix;
1303 var isNetwork = false;
1304 if (this.networkCloneCheckbox !== undefined && this.networkCloneCheckbox !== null) {
1305 isNetwork = this.networkCloneCheckbox.checked;
1306 }
1307
1308 // Force network clone true if set explicitly
1309 if (this.isNetworkClone) {
1310 isNetwork = true;
1311 }
1312 if (this.isMultisite && !isNetwork) {
1313 pattern += '([^0-9])_*';
1314 }
1315 return pattern;
1316 };
1317 _proto.selectDefaultTables = function selectDefaultTables() {
1318 var options = this.databaseTableSection.querySelectorAll('#wpstg_select_tables_cloning .wpstg-db-table');
1319 var regexPattern = this.getRegexPattern();
1320 options.forEach(function (option) {
1321 var name = option.getAttribute('name', '');
1322 if (name.match(regexPattern)) {
1323 option.selected = true;
1324 } else {
1325 option.selected = false;
1326 }
1327 });
1328 this.countSelectedTables();
1329 };
1330 _proto.toggleTableSelection = function toggleTableSelection() {
1331 if (false === this.isAllTablesChecked) {
1332 this.databaseTableSection.querySelectorAll('#wpstg_select_tables_cloning .wpstg-db-table').forEach(function (option) {
1333 option.selected = true;
1334 });
1335 this.databaseTableSection.querySelector('.wpstg-button-unselect').innerHTML = 'Unselect All';
1336 // cache.get('.wpstg-db-table-checkboxes').prop('checked', true);
1337 this.isAllTablesChecked = true;
1338 } else {
1339 this.databaseTableSection.querySelectorAll('#wpstg_select_tables_cloning .wpstg-db-table').forEach(function (option) {
1340 option.selected = false;
1341 });
1342 this.databaseTableSection.querySelector('.wpstg-button-unselect').innerHTML = 'Select All';
1343 // cache.get('.wpstg-db-table-checkboxes').prop('checked', false);
1344 this.isAllTablesChecked = false;
1345 }
1346 this.countSelectedTables();
1347 };
1348 _proto.unselectWPSTGTables = function unselectWPSTGTables() {
1349 var _this2 = this;
1350 var options = this.databaseTableSection.querySelectorAll('#wpstg_select_tables_cloning .wpstg-db-table');
1351 var regexPattern = 'wpstg';
1352 options.forEach(function (option) {
1353 var name = option.getAttribute('name', '');
1354 if (name.match(regexPattern) && !name.match(_this2.wpstgObject.tblprefix + 'wpstg_queue')) {
1355 option.selected = false;
1356 }
1357 });
1358 this.countSelectedTables();
1359 };
1360 _proto.getSelectedTablesWithoutPrefix = function getSelectedTablesWithoutPrefix() {
1361 var selectedTablesWithoutPrefix = [];
1362 var options = this.databaseTableSection.querySelectorAll('#wpstg_select_tables_cloning option:checked');
1363 var regexPattern = this.getRegexPattern();
1364 options.forEach(function (option) {
1365 var name = option.getAttribute('name', '');
1366 if (!name.match(regexPattern)) {
1367 selectedTablesWithoutPrefix.push(option.value);
1368 }
1369 });
1370 return selectedTablesWithoutPrefix.join(this.wpstgObject.settings.directorySeparator);
1371 };
1372 _proto.getIncludedTables = function getIncludedTables() {
1373 var includedTables = [];
1374 var options = this.databaseTableSection.querySelectorAll('#wpstg_select_tables_cloning option:checked');
1375 var regexPattern = this.getRegexPattern();
1376 options.forEach(function (option) {
1377 var name = option.getAttribute('name', '');
1378 if (name.match(regexPattern)) {
1379 includedTables.push(option.value);
1380 }
1381 });
1382 return includedTables.join(this.wpstgObject.settings.directorySeparator);
1383 };
1384 _proto.getExcludedTables = function getExcludedTables() {
1385 var excludedTables = [];
1386 var options = this.databaseTableSection.querySelectorAll('#wpstg_select_tables_cloning option:not(:checked)');
1387 var regexPattern = this.getRegexPattern();
1388 options.forEach(function (option) {
1389 var name = option.getAttribute('name', '');
1390 if (name.match(regexPattern)) {
1391 excludedTables.push(option.value);
1392 }
1393 });
1394 return excludedTables.join(this.wpstgObject.settings.directorySeparator);
1395 };
1396 _proto.countSelectedTables = function countSelectedTables() {
1397 var tablesCount = this.input.querySelectorAll('option:checked').length;
1398 var tablesCountElement = qs('#wpstg-tables-count');
1399 if (tablesCount === 0) {
1400 tablesCountElement.classList.add('danger');
1401 tablesCountElement.innerHTML = this.wpstgObject.i18n['noTableSelected'];
1402 } else {
1403 tablesCountElement.classList.remove('danger');
1404 tablesCountElement.innerHTML = this.wpstgObject.i18n['tablesSelected'].replace('{d}', tablesCount);
1405 }
1406 };
1407 return WpstgTableSelection;
1408 }();
1409
1410 /**
1411 * Rich Exclude Filter Module
1412 */
1413 var WpstgExcludeFilters = /*#__PURE__*/function () {
1414 function WpstgExcludeFilters(excludeFilterContainerSelector, wpstgObject) {
1415 if (excludeFilterContainerSelector === void 0) {
1416 excludeFilterContainerSelector = '#wpstg-exclude-filters-container';
1417 }
1418 if (wpstgObject === void 0) {
1419 wpstgObject = wpstg;
1420 }
1421 this.excludeContainer = qs(excludeFilterContainerSelector);
1422 this.excludeTableBody = qs(excludeFilterContainerSelector + " tbody");
1423 this.wpstgObject = wpstgObject;
1424 this.init();
1425 }
1426 var _proto = WpstgExcludeFilters.prototype;
1427 _proto.addEvents = function addEvents() {
1428 var _this = this;
1429 addEvent(this.excludeContainer, 'click', '.wpstg-file-size-rule', function () {
1430 _this.addFileSizeExclude();
1431 });
1432 addEvent(this.excludeContainer, 'click', '.wpstg-file-ext-rule', function () {
1433 _this.addFileExtExclude();
1434 });
1435 addEvent(this.excludeContainer, 'click', '.wpstg-file-name-rule', function () {
1436 _this.addFileNameExclude();
1437 });
1438 addEvent(this.excludeContainer, 'click', '.wpstg-dir-name-rule', function () {
1439 _this.addDirNameExclude();
1440 });
1441 addEvent(this.excludeContainer, 'click', '.wpstg-clear-all-rules', function () {
1442 _this.clearExcludes();
1443 });
1444 addEvent(this.excludeContainer, 'click', '.wpstg-remove-exclude-rule', function (target) {
1445 _this.removeExclude(target);
1446 });
1447 };
1448 _proto.init = function init() {
1449 if (this.excludeContainer === null) {
1450 console.log('Error: Given table selector not found!');
1451 return;
1452 }
1453 this.addEvents();
1454 };
1455 _proto.addFileSizeExclude = function addFileSizeExclude() {
1456 this.addExcludeRuleRow('#wpstg-file-size-exclude-filter-template');
1457 };
1458 _proto.addFileExtExclude = function addFileExtExclude() {
1459 this.addExcludeRuleRow('#wpstg-file-ext-exclude-filter-template');
1460 };
1461 _proto.addFileNameExclude = function addFileNameExclude() {
1462 this.addExcludeRuleRow('#wpstg-file-name-exclude-filter-template');
1463 };
1464 _proto.addDirNameExclude = function addDirNameExclude() {
1465 this.addExcludeRuleRow('#wpstg-dir-name-exclude-filter-template');
1466 };
1467 _proto.addExcludeRuleRow = function addExcludeRuleRow(templateName) {
1468 var excludeRowTemplate = qs(templateName);
1469 if (excludeRowTemplate !== null) {
1470 var clone = excludeRowTemplate.content.cloneNode(true);
1471 var excludeRow = clone.querySelector('tr');
1472 this.excludeTableBody.appendChild(excludeRow);
1473 all('.wpstg-has-exclude-rules').forEach(function (e) {
1474 e.style.display = 'inherit';
1475 });
1476 }
1477 };
1478 _proto.clearExcludes = function clearExcludes() {
1479 this.excludeTableBody.innerHTML = '';
1480 all('.wpstg-has-exclude-rules').forEach(function (e) {
1481 e.style.display = 'none';
1482 });
1483 };
1484 _proto.removeExclude = function removeExclude(target) {
1485 if (target.parentElement !== null && target.parentElement.parentElement !== null) {
1486 this.excludeTableBody.removeChild(target.parentElement.parentElement);
1487 }
1488 if (this.excludeTableBody.innerHTML.trim() === '') {
1489 all('.wpstg-has-exclude-rules').forEach(function (e) {
1490 e.style.display = 'none';
1491 });
1492 }
1493 }
1494
1495 /**
1496 * Converts all the exclude filters arrays into one single string to keep size of post request small
1497 * @return {string}
1498 */;
1499 _proto.getExcludeFilters = function getExcludeFilters() {
1500 var _this2 = this;
1501 var globExcludes = [];
1502 var sizeExcludes = [];
1503 var sizeCompares = this.excludeTableBody.querySelectorAll('select[name="wpstgFileSizeExcludeRuleCompare[]"]');
1504 var sizeSizes = this.excludeTableBody.querySelectorAll('input[name="wpstgFileSizeExcludeRuleSize[]"]');
1505 var sizeByte = this.excludeTableBody.querySelectorAll('select[name="wpstgFileSizeExcludeRuleByte[]"]');
1506 for (var _i = 0, _Object$entries = Object.entries(sizeSizes); _i < _Object$entries.length; _i++) {
1507 var _Object$entries$_i = _Object$entries[_i],
1508 key = _Object$entries$_i[0],
1509 sizeInput = _Object$entries$_i[1];
1510 if (sizeInput.value !== '') {
1511 sizeExcludes.push(sizeCompares[key].value + ' ' + sizeInput.value + sizeByte[key].value);
1512 }
1513 }
1514 var extensionInputs = this.excludeTableBody.querySelectorAll('input[name="wpstgFileExtExcludeRule[]"]');
1515 extensionInputs.forEach(function (x) {
1516 var ext = _this2.cleanStringForGlob(x.value);
1517 if (ext !== '') {
1518 globExcludes.push('ext:' + ext.trim());
1519 }
1520 });
1521 var fileNamesPos = this.excludeTableBody.querySelectorAll('select[name="wpstgFileNameExcludeRulePos[]"]');
1522 var fileNames = this.excludeTableBody.querySelectorAll('input[name="wpstgFileNameExcludeRulePath[]"]');
1523 for (var _i2 = 0, _Object$entries2 = Object.entries(fileNames); _i2 < _Object$entries2.length; _i2++) {
1524 var _Object$entries2$_i = _Object$entries2[_i2],
1525 _key = _Object$entries2$_i[0],
1526 fileInput = _Object$entries2$_i[1];
1527 var fileName = this.cleanStringForGlob(fileInput.value);
1528 if (fileName !== '') {
1529 globExcludes.push('file:' + fileNamesPos[_key].value + ' ' + fileName.trim());
1530 }
1531 }
1532 var dirNamesPos = this.excludeTableBody.querySelectorAll('select[name="wpstgDirNameExcludeRulePos[]"]');
1533 var dirNames = this.excludeTableBody.querySelectorAll('input[name="wpstgDirNameExcludeRulePath[]"]');
1534 for (var _i3 = 0, _Object$entries3 = Object.entries(dirNames); _i3 < _Object$entries3.length; _i3++) {
1535 var _Object$entries3$_i = _Object$entries3[_i3],
1536 _key2 = _Object$entries3$_i[0],
1537 dirInput = _Object$entries3$_i[1];
1538 var dirName = this.cleanStringForGlob(dirInput.value);
1539 if (dirName !== '') {
1540 globExcludes.push('dir:' + dirNamesPos[_key2].value + ' ' + dirName.trim());
1541 }
1542 }
1543 return {
1544 'sizes': sizeExcludes.filter(this.onlyUnique).join(','),
1545 // return set of unique rules
1546 'globs': globExcludes.filter(this.onlyUnique).join(',')
1547 };
1548 };
1549 _proto.onlyUnique = function onlyUnique(value, index, self) {
1550 return self.indexOf(value) === index;
1551 }
1552
1553 /**
1554 * Remove most of the comment glob characters from the string
1555 * @param {String} value
1556 * @return {String}
1557 */;
1558 _proto.cleanStringForGlob = function cleanStringForGlob(value) {
1559 // will replace character like * ^ / \ ! ? [ from the string
1560 return value.replace(/[*^//!\[?]/g, '');
1561 };
1562 return WpstgExcludeFilters;
1563 }();
1564
1565 /**
1566 * Basic WP Staging Modal implemented with help of Sweetalerts
1567 */
1568 var WpstgModal = /*#__PURE__*/function () {
1569 function WpstgModal(confirmAction, wpstgObject) {
1570 if (wpstgObject === void 0) {
1571 wpstgObject = wpstg;
1572 }
1573 this.confirmAction = confirmAction;
1574 this.wpstgObject = wpstgObject;
1575 }
1576 var _proto = WpstgModal.prototype;
1577 _proto.show = function show(swalOptions, additionalParams, callback) {
1578 var _this = this;
1579 if (additionalParams === void 0) {
1580 additionalParams = {};
1581 }
1582 if (callback === void 0) {
1583 callback = null;
1584 }
1585 wpstgSwal.fire(swalOptions).then(function (result) {
1586 if (result.value && _this.error !== null) {
1587 _this.triggerConfirmAction(additionalParams, callback);
1588 }
1589 });
1590 };
1591 _proto.triggerConfirmAction = function triggerConfirmAction(additionalParams, callback) {
1592 var _this2 = this;
1593 if (additionalParams === void 0) {
1594 additionalParams = {};
1595 }
1596 if (callback === void 0) {
1597 callback = null;
1598 }
1599 fetch(this.wpstgObject.ajaxUrl, {
1600 method: 'POST',
1601 credentials: 'same-origin',
1602 body: new URLSearchParams(Object.assign({
1603 action: this.confirmAction,
1604 accessToken: this.wpstgObject.accessToken,
1605 nonce: this.wpstgObject.nonce
1606 }, additionalParams)),
1607 headers: {
1608 'Content-Type': 'application/x-www-form-urlencoded'
1609 }
1610 }).then(function (response) {
1611 if (response.ok) {
1612 return response.json();
1613 }
1614 return Promise.reject(response);
1615 }).then(function (response) {
1616 if (callback !== null) {
1617 callback(response);
1618 }
1619 })["catch"](function (error) {
1620 console.log(_this2.wpstgObject.i18n['somethingWentWrong'], error);
1621 });
1622 };
1623 return WpstgModal;
1624 }();
1625
1626 /**
1627 * Manage RESET MODAL
1628 */
1629 var WpstgResetModal = /*#__PURE__*/function () {
1630 function WpstgResetModal(cloneID, workflowSelector, fetchExcludeSettingsAction, modalErrorAction, wpstgObject) {
1631 if (workflowSelector === void 0) {
1632 workflowSelector = '#wpstg-workflow';
1633 }
1634 if (fetchExcludeSettingsAction === void 0) {
1635 fetchExcludeSettingsAction = 'wpstg_clone_excludes_settings';
1636 }
1637 if (modalErrorAction === void 0) {
1638 modalErrorAction = 'wpstg_modal_error';
1639 }
1640 if (wpstgObject === void 0) {
1641 wpstgObject = wpstg;
1642 }
1643 this.cloneID = cloneID;
1644 this.workflow = qs(workflowSelector);
1645 this.wpstgObject = wpstgObject;
1646 this.fetchExcludeSettingsAction = fetchExcludeSettingsAction;
1647 this.modalErrorAction = modalErrorAction;
1648 this.resetButtonClass = 'wpstg-confirm-reset-clone';
1649 this.resetModalContainerClass = 'wpstg-reset-confirmation';
1650 this.resetTabSelector = '.wpstg-reset-exclude-tab';
1651 this.directoryNavigator = null;
1652 this.excludeFilters = null;
1653 this.tableSelector = null;
1654 this.isNetworkClone = false;
1655 }
1656 var _proto = WpstgResetModal.prototype;
1657 _proto.addEvents = function addEvents() {
1658 var _this = this;
1659 var resetModalContainer = qs('.' + this.resetModalContainerClass);
1660 if (resetModalContainer === null) {
1661 console.log('Exit');
1662 return;
1663 }
1664 addEvent(resetModalContainer, 'click', this.resetTabSelector, function (target) {
1665 _this.toggleContent(target);
1666 });
1667 };
1668 _proto.init = function init() {
1669 this.addEvents();
1670 };
1671 _proto.setNetworkClone = function setNetworkClone(isNetworkClone) {
1672 this.isNetworkClone = isNetworkClone;
1673 };
1674 _proto.toggleContent = function toggleContent(target) {
1675 var resetModalContainer = qs('.' + this.resetModalContainerClass);
1676 var contentId = target.getAttribute('data-id');
1677 var tabTriangle = target.querySelector('.wpstg-tab-triangle');
1678 var isCollapsed = target.getAttribute('data-collapsed', 'true');
1679 var content = qs(contentId);
1680 if (isCollapsed === 'true') {
1681 if (resetModalContainer.classList.contains('has-collapsible-open')) {
1682 resetModalContainer.classList.add('has-collapsible-open-2');
1683 } else {
1684 resetModalContainer.classList.add('has-collapsible-open');
1685 }
1686 slideDown(content);
1687 tabTriangle.style.transform = 'rotate(90deg)';
1688 target.setAttribute('data-collapsed', 'false');
1689 } else {
1690 if (resetModalContainer.classList.contains('has-collapsible-open-2')) {
1691 resetModalContainer.classList.remove('has-collapsible-open-2');
1692 } else {
1693 resetModalContainer.classList.remove('has-collapsible-open');
1694 }
1695 slideUp(content);
1696 tabTriangle.style.removeProperty('transform');
1697 target.setAttribute('data-collapsed', 'true');
1698 }
1699 }
1700
1701 /**
1702 * Show Swal alert with loader and send ajax request to fetch content of alert.
1703 * @return Promise
1704 */;
1705 _proto.showModal = function showModal() {
1706 var swalPromise = this.loadModal();
1707 this.init();
1708 this.fetchCloneExcludes();
1709 return swalPromise;
1710 };
1711 _proto.loadModal = function loadModal() {
1712 return WPStagingCommon.getSwalModal(false, {
1713 confirmButton: this.resetButtonClass + ' wpstg-confirm-reset-clone wpstg--btn--confirm wpstg-blue-primary wpstg-button wpstg-link-btn',
1714 container: this.resetModalContainerClass + ' wpstg-swal2-container wpstg-swal2-loading'
1715 }).fire({
1716 title: '',
1717 icon: 'warning',
1718 html: this.getAjaxLoader(),
1719 width: '400px',
1720 focusConfirm: false,
1721 confirmButtonText: this.wpstgObject.i18n.resetClone,
1722 showCancelButton: true
1723 });
1724 };
1725 _proto.fetchCloneExcludes = function fetchCloneExcludes() {
1726 var _this2 = this;
1727 this.error = null;
1728 // send ajax request and fetch preserved exclude settings
1729 fetch(this.wpstgObject.ajaxUrl, {
1730 method: 'POST',
1731 credentials: 'same-origin',
1732 body: new URLSearchParams({
1733 action: this.fetchExcludeSettingsAction,
1734 accessToken: this.wpstgObject.accessToken,
1735 nonce: this.wpstgObject.nonce,
1736 clone: this.cloneID,
1737 job: 'resetting'
1738 }),
1739 headers: {
1740 'Content-Type': 'application/x-www-form-urlencoded'
1741 }
1742 }).then(function (response) {
1743 if (response.ok) {
1744 return response.json();
1745 }
1746 return Promise.reject(response);
1747 }).then(function (data) {
1748 if (!data.success) {
1749 var errorModal = new WpstgModal(_this2.modalErrorAction, _this2.wpstgObject);
1750 errorModal.show(Object.assign({
1751 title: 'Error',
1752 icon: 'error',
1753 html: _this2.wpstgObject.i18n['somethingWentWrong'],
1754 width: '500px',
1755 confirmButtonText: 'Ok',
1756 showCancelButton: false,
1757 customClass: {
1758 confirmButton: 'wpstg--btn--confirm wpstg-blue-primary wpstg-button wpstg-link-btn',
1759 cancelButton: 'wpstg--btn--cancel wpstg-blue-primary wpstg-link-btn',
1760 actions: 'wpstg--modal--actions',
1761 popup: 'wpstg-swal-popup centered-modal'
1762 },
1763 buttonsStyling: false,
1764 reverseButtons: true
1765 }, data.swalOptions), {
1766 type: data.type
1767 });
1768 return;
1769 }
1770 var modal = qs('.wpstg-reset-confirmation');
1771 modal.classList.remove('wpstg-swal2-loading');
1772 modal.querySelector('.wpstg--swal2-popup').style.width = '540px';
1773 modal.querySelector('.wpstg--swal2-content').innerHTML = data.html;
1774 _this2.directoryNavigator = new WpstgDirectoryNavigation('#wpstg-directories-listing', wpstg, null);
1775 _this2.directoryNavigator.countSelectedFiles();
1776 _this2.excludeFilters = new WpstgExcludeFilters();
1777 _this2.tableSelector = new WpstgTableSelection('#wpstg-reset-excluded-tables', '.' + _this2.resetModalContainerClass);
1778 _this2.tableSelector.setNetworkClone(_this2.isNetworkClone);
1779 _this2.tableSelector.countSelectedTables();
1780 })["catch"](function (error) {
1781 _this2.renderError({
1782 'html': _this2.wpstgObject.i18n['somethingWentWrong'] + ' ' + error
1783 });
1784 });
1785 };
1786 _proto.getDirectoryNavigator = function getDirectoryNavigator() {
1787 return this.directoryNavigator;
1788 };
1789 _proto.getExcludeFilters = function getExcludeFilters() {
1790 return this.excludeFilters;
1791 };
1792 _proto.getTableSelector = function getTableSelector() {
1793 return this.tableSelector;
1794 };
1795 _proto.getAjaxLoader = function getAjaxLoader() {
1796 return '<div class="wpstg-swal2-ajax-loader"><img src="' + this.wpstgObject.wpstgIcon + '" /></div>';
1797 };
1798 return WpstgResetModal;
1799 }();
1800
1801 /**
1802 * Handle toggle of advance settings checkboxes
1803 */
1804 var WpstgCloningAdvanceSettings = /*#__PURE__*/function () {
1805 function WpstgCloningAdvanceSettings(baseContainerSelector) {
1806 if (baseContainerSelector === void 0) {
1807 baseContainerSelector = '#wpstg-clonepage-wrapper';
1808 }
1809 this.baseContainer = qs(baseContainerSelector);
1810 this.checkBoxSettingTogglerSelector = '.wpstg-toggle-advance-settings-section';
1811 this.init();
1812 }
1813
1814 /**
1815 * Add events
1816 * @return {void}
1817 */
1818 var _proto = WpstgCloningAdvanceSettings.prototype;
1819 _proto.addEvents = function addEvents() {
1820 var _this = this;
1821 if (this.baseContainer === null) {
1822 return;
1823 }
1824 addEvent(this.baseContainer, 'change', this.checkBoxSettingTogglerSelector, function (element) {
1825 _this.toggleSettings(element);
1826 });
1827 }
1828
1829 /**
1830 * @return {void}
1831 */;
1832 _proto.init = function init() {
1833 this.addEvents();
1834 }
1835
1836 /**
1837 * Expand/Collapse checkbox content on change
1838 * @return {void}
1839 */;
1840 _proto.toggleSettings = function toggleSettings(element) {
1841 var target = qs('#' + element.getAttribute('data-id'));
1842 if (element.checked) {
1843 slideDown(target);
1844 } else {
1845 slideUp(target);
1846 }
1847 };
1848 return WpstgCloningAdvanceSettings;
1849 }();
1850
1851 var WpstgMainMenu = /*#__PURE__*/function () {
1852 function WpstgMainMenu() {
1853 this.activeTabClass = 'wpstg--tab--active';
1854 this.mainMenu();
1855 }
1856 var _proto = WpstgMainMenu.prototype;
1857 _proto.mainMenu = function mainMenu() {
1858 var _this = this;
1859 var tabHeader = qs('.wpstg--tab--header');
1860 // Early bail if tab header is not available
1861 if (tabHeader === null) {
1862 return;
1863 }
1864 addEvent(qs('.wpstg--tab--header'), 'click', '.wpstg-button', function (element) {
1865 var $this = element;
1866 var target = $this.getAttribute('data-target');
1867 if (target === '') {
1868 return;
1869 }
1870 var targetElements = all(target);
1871 var menuItems = all('.wpstg--tab--header a[data-target]');
1872 var contents = all('.wpstg--tab--contents > .wpstg--tab--content');
1873 contents.forEach(function (content) {
1874 // active tab class is without the css dot class prefix
1875 if (content.matches('.' + _this.activeTabClass + ':not(' + target + ')')) {
1876 content.classList.remove(_this.activeTabClass);
1877 }
1878 });
1879 menuItems.forEach(function (menuItem) {
1880 if (menuItem !== $this) {
1881 menuItem.classList.remove(_this.activeTabClass);
1882 }
1883 });
1884 $this.classList.add(_this.activeTabClass);
1885 targetElements.forEach(function (targetElement) {
1886 targetElement.classList.add(_this.activeTabClass);
1887 });
1888 if ('#wpstg--tab--backup' === target) {
1889 window.dispatchEvent(new Event('backups-tab'));
1890 }
1891 });
1892 };
1893 return WpstgMainMenu;
1894 }();
1895
1896 var WPStaging$1 = function ($) {
1897 var that = {
1898 isCancelled: false,
1899 isFinished: false,
1900 getLogs: false,
1901 time: 1,
1902 executionTime: false,
1903 progressBar: 0,
1904 cloneExcludeFilters: null,
1905 directoryNavigator: null,
1906 tableSelector: null,
1907 notyf: null,
1908 areAllTablesChecked: true,
1909 handleDisplayDependencies: handleDisplayDependencies,
1910 handleToggleElement: handleToggleElement,
1911 handleCopyPaste: handleCopyPaste,
1912 handleCopyToClipboard: handleCopyToClipboard,
1913 messages: [],
1914 modal: {
1915 instance: '',
1916 processTime: 0,
1917 processInterval: '',
1918 currentJob: ''
1919 }
1920 };
1921 var cache = {
1922 elements: []
1923 };
1924 var ajaxSpinner;
1925
1926 /**
1927 * Get / Set Cache for Selector
1928 * @param {String} selector
1929 * @return {*}
1930 */
1931 cache.get = function (selector) {
1932 // It is already cached!
1933 if ($.inArray(selector, cache.elements) !== -1) {
1934 return cache.elements[selector];
1935 }
1936
1937 // Create cache and return
1938 cache.elements[selector] = jQuery(selector);
1939 return cache.elements[selector];
1940 };
1941
1942 /**
1943 * Refreshes given cache
1944 * @param {String} selector
1945 */
1946 cache.refresh = function (selector) {
1947 selector.elements[selector] = jQuery(selector);
1948 };
1949
1950 /**
1951 * Show and Log Error Message
1952 * @param {String} message
1953 */
1954 var showError = function showError(message) {
1955 cache.get('#wpstg-try-again').css('display', 'inline-block');
1956 cache.get('#wpstg-cancel-cloning').text('Reset');
1957 cache.get('#wpstg-resume-cloning').show();
1958 cache.get('#wpstg-error-wrapper').show();
1959 cache.get('#wpstg-error-details').show().html(message);
1960 cache.get('#wpstg-removing-clone').removeClass('wpstg-loading');
1961 cache.get('.wpstg-loader').hide();
1962 $('.wpstg--modal--process--generic-problem').show().html(message);
1963
1964 // Error event information for Staging
1965 $.ajax({
1966 url: ajaxurl,
1967 type: 'POST',
1968 dataType: 'json',
1969 data: {
1970 'action': 'wpstg_staging_job_error',
1971 'accessToken': wpstg.accessToken,
1972 'nonce': wpstg.nonce,
1973 'error_message': message
1974 }
1975 });
1976 };
1977
1978 /**
1979 * Show warning during cloning or push process when closing tab or browser, or changing page
1980 * @param {beforeunload} event
1981 * @return {null}
1982 */
1983 that.warnIfClosingDuringProcess = function (event) {
1984 // Only some browsers show the message below, most say something like "Changes you made may not be saved" (Chrome) or "You have unsaved changes. Exit?"
1985 event.returnValue = 'You MUST leave this window open while cloning/pushing. Please wait...';
1986 return null;
1987 };
1988
1989 /**
1990 *
1991 * @param response the error object
1992 * @param prependMessage Overwrite default error message at beginning
1993 * @param appendMessage Overwrite default error message at end
1994 * @returns void
1995 */
1996
1997 var showAjaxFatalError = function showAjaxFatalError(response, prependMessage, appendMessage) {
1998 prependMessage = prependMessage ? prependMessage + '<br/><br/>' : 'Something went wrong! <br/><br/>';
1999 appendMessage = appendMessage ? appendMessage + '<br/><br/>' : '<br/><br/>Please try the <a href=\'https://wp-staging.com/docs/wp-staging-settings-for-small-servers/\' target=\'_blank\'>WP Staging Small Server Settings</a> or submit an error report and contact us.';
2000 if (response === false) {
2001 showError(prependMessage + ' Error: No response.' + appendMessage);
2002 window.removeEventListener('beforeunload', WPStaging$1.warnIfClosingDuringProcess);
2003 return;
2004 }
2005 if (typeof response.error !== 'undefined' && response.error) {
2006 console.error(response.message);
2007 showError(prependMessage + ' Error: ' + response.message + appendMessage);
2008 window.removeEventListener('beforeunload', WPStaging$1.warnIfClosingDuringProcess);
2009 return;
2010 }
2011 };
2012
2013 /** Hide and reset previous thrown visible errors */
2014 var resetErrors = function resetErrors() {
2015 cache.get('#wpstg-error-details').hide().html('');
2016 };
2017
2018 /**
2019 * Common Elements
2020 */
2021 var elements = function elements() {
2022 var $workFlow = cache.get('#wpstg-workflow');
2023 var urlSpinner = ajaxurl.replace('/admin-ajax.php', '') + '/images/spinner';
2024 var timer;
2025 if (2 < window.devicePixelRatio) {
2026 urlSpinner += '-2x';
2027 }
2028 urlSpinner += '.gif';
2029 ajaxSpinner = '<img src=\'\'' + urlSpinner + '\' alt=\'\' class=\'ajax-spinner general-spinner\' />';
2030 $workFlow
2031 /**
2032 .on('change', '#wpstg_network_clone', function(e) {
2033 e.preventDefault();
2034 $('.wpstg-button-select').trigger('click');
2035 })
2036 */
2037 // Check / Un-check All Database Tables New
2038 .on('click', '.wpstg-button-unselect', function (e) {
2039 e.preventDefault();
2040 if (false === that.areAllTablesChecked) {
2041 cache.get('#wpstg_select_tables_cloning .wpstg-db-table').prop('selected', 'selected');
2042 cache.get('.wpstg-button-unselect').text('Unselect All');
2043 cache.get('.wpstg-db-table-checkboxes').prop('checked', true);
2044 that.areAllTablesChecked = true;
2045 } else {
2046 cache.get('#wpstg_select_tables_cloning .wpstg-db-table').prop('selected', false);
2047 cache.get('.wpstg-button-unselect').text('Select All');
2048 cache.get('.wpstg-db-table-checkboxes').prop('checked', false);
2049 that.areAllTablesChecked = false;
2050 }
2051 })
2052
2053 /**
2054 * Select tables with certain tbl prefix | NEW
2055 * @param obj e
2056 * @returns {undefined}
2057 */
2058 /**
2059 .on('click', '.wpstg-button-select', function(e) {
2060 e.preventDefault();
2061 $('#wpstg_select_tables_cloning .wpstg-db-table').each(function() {
2062 let regex = '^' + wpstg.tblprefix;
2063 if (wpstg.isMultisite === '1' && !$('#wpstg_network_clone').is(':checked')) {
2064 regex += '([^0-9])_*';
2065 }
2066 if ($(this).attr('name').match(regex)) {
2067 $(this).prop('selected', 'selected');
2068 } else {
2069 $(this).prop('selected', false);
2070 }
2071 });
2072 })
2073 // Expand Directories
2074 .on('click', '.wpstg-expand-dirs', function(e) {
2075 e.preventDefault();
2076 const $this = $(this);
2077 $this.siblings('.wpstg-subdir').slideToggle();
2078 })
2079 // When a directory checkbox is Selected
2080 .on('change', 'input.wpstg-check-dir', function() {
2081 const $directory = $(this).parent('.wpstg-dir');
2082 if (this.checked) {
2083 $directory.parents('.wpstg-dir').children('.wpstg-check-dir').prop('checked', true);
2084 $directory.find('.wpstg-expand-dirs').removeClass('disabled');
2085 $directory.find('.wpstg-subdir .wpstg-check-dir').prop('checked', true);
2086 } else {
2087 $directory.find('.wpstg-dir .wpstg-check-dir').prop('checked', false);
2088 $directory.find('.wpstg-expand-dirs, .wpstg-check-subdirs').addClass('disabled');
2089 $directory.find('.wpstg-check-subdirs').data('action', 'check').text('check');
2090 }
2091 })
2092 // When a directory name is Selected
2093 .on('change', 'href.wpstg-check-dir', function() {
2094 const $directory = $(this).parent('.wpstg-dir');
2095 if (this.checked) {
2096 $directory.parents('.wpstg-dir').children('.wpstg-check-dir').prop('checked', true);
2097 $directory.find('.wpstg-expand-dirs').removeClass('disabled');
2098 $directory.find('.wpstg-subdir .wpstg-check-dir').prop('checked', true);
2099 } else {
2100 $directory.find('.wpstg-dir .wpstg-check-dir').prop('checked', false);
2101 $directory.find('.wpstg-expand-dirs, .wpstg-check-subdirs').addClass('disabled');
2102 $directory.find('.wpstg-check-subdirs').data('action', 'check').text('check');
2103 }
2104 })
2105 */
2106 // Check the max length of the clone name and if the clone name already exists
2107 .on('keyup', '#wpstg-new-clone-id', function () {
2108 // Hide previous errors
2109 document.getElementById('wpstg-error-details').style.display = 'none';
2110
2111 // This request was already sent, clear it up!
2112 if ('number' === typeof timer) {
2113 clearInterval(timer);
2114 }
2115
2116 // Early bail if site name is empty
2117 if (this.value === undefined || this.value === '') {
2118 cache.get('#wpstg-new-clone-id').removeClass('wpstg-error-input');
2119 cache.get('#wpstg-start-cloning').removeAttr('disabled');
2120 cache.get('#wpstg-clone-id-error').text('').hide();
2121 return;
2122 }
2123
2124 // Convert the site name to directory name (slugify the site name to create directory name)
2125 var cloneDirectoryName = WPStagingCommon.slugify(this.value);
2126 timer = setTimeout(function () {
2127 ajax({
2128 action: 'wpstg_check_clone',
2129 accessToken: wpstg.accessToken,
2130 nonce: wpstg.nonce,
2131 directoryName: cloneDirectoryName
2132 }, function (response) {
2133 if (response.status === 'success') {
2134 cache.get('#wpstg-new-clone-id').removeClass('wpstg-error-input');
2135 cache.get('#wpstg-start-cloning').removeAttr('disabled');
2136 cache.get('#wpstg-clone-id-error').text('').hide();
2137 } else {
2138 cache.get('#wpstg-new-clone-id').addClass('wpstg-error-input');
2139 cache.get('#wpstg-start-cloning').prop('disabled', true);
2140 cache.get('#wpstg-clone-id-error').text(response.message).show();
2141 }
2142 });
2143 }, 500);
2144 })
2145 // Restart cloning process
2146 .on('click', '#wpstg-start-cloning', function () {
2147 resetErrors();
2148 that.isCancelled = false;
2149 that.getLogs = false;
2150 that.progressBar = 0;
2151 }).on('input', '#wpstg-new-clone-id', function () {
2152 if ($('#wpstg-clone-directory').length < 1) {
2153 return;
2154 }
2155 var slug = WPStagingCommon.slugify(this.value).substring(0, 16);
2156 var $targetDir = $('#wpstg-use-target-dir');
2157 var $targetUri = $('#wpstg-use-target-hostname');
2158 var path = $targetDir.data('base-path');
2159 var uri = $targetUri.data('base-uri');
2160 if (path) {
2161 path = path.replace(/\/+$/g, '') + '/' + slug + '/';
2162 }
2163 if (uri) {
2164 uri = uri.replace(/\/+$/g, '') + '/' + slug;
2165 }
2166 $('.wpstg-use-target-dir--value').text(path);
2167 $('.wpstg-use-target-hostname--value').text(uri);
2168 $targetDir.attr('data-path', path);
2169 $targetUri.attr('data-uri', uri);
2170 $('#wpstg_clone_dir').attr('placeholder', path);
2171 $('#wpstg_clone_hostname').attr('placeholder', uri);
2172 }).on('input', '#wpstg_clone_hostname', function () {
2173 if ($(this).val() === '' || validateTargetHost()) {
2174 $('#wpstg_clone_hostname_error').remove();
2175 return;
2176 }
2177 if (!validateTargetHost() && !$('#wpstg_clone_hostname_error').length) {
2178 $('#wpstg-clone-directory tr:last-of-type').after('<tr><td>&nbsp;</td><td><p id="wpstg_clone_hostname_error" style="color: red;">&nbsp;Invalid host name. Please provide it in a format like http://example.com</p></td></tr>');
2179 }
2180 });
2181 cloneActions();
2182 };
2183
2184 /* @returns {boolean} */
2185 var validateTargetHost = function validateTargetHost() {
2186 var the_domain = $('#wpstg_clone_hostname').val();
2187 if (the_domain === '') {
2188 return true;
2189 }
2190 var reg = /^http(s)?:\/\/.*$/;
2191 if (reg.test(the_domain) === false) {
2192 return false;
2193 }
2194 return true;
2195 };
2196
2197 /**
2198 * Clone actions
2199 */
2200 var cloneActions = function cloneActions() {
2201 var $workFlow = cache.get('#wpstg-workflow');
2202 $workFlow
2203 // Cancel cloning
2204 .on('click', '#wpstg-cancel-cloning', function () {
2205 if (!confirm('Are you sure you want to cancel cloning process?')) {
2206 return false;
2207 }
2208 var $this = $(this);
2209 $('#wpstg-try-again, #wpstg-home-link').hide();
2210 $this.prop('disabled', true);
2211 that.isCancelled = true;
2212 that.progressBar = 0;
2213 $('#wpstg-processing-status').text('Please wait...this can take up a while.');
2214 $('.wpstg-loader, #wpstg-show-log-button').hide();
2215 $this.parent().append(ajaxSpinner);
2216 cancelCloning();
2217 })
2218 // Resume cloning
2219 .on('click', '#wpstg-resume-cloning', function () {
2220 resetErrors();
2221 var $this = $(this);
2222 $('#wpstg-try-again, #wpstg-home-link').hide();
2223 that.isCancelled = false;
2224 $('#wpstg-processing-status').text('Try to resume cloning process...');
2225 $('#wpstg-error-details').hide();
2226 $('.wpstg-loader').show();
2227 $this.parent().append(ajaxSpinner);
2228 that.startCloning();
2229 })
2230 // Cancel update cloning
2231 .on('click', '#wpstg-cancel-cloning-update', function () {
2232 resetErrors();
2233 var $this = $(this);
2234 $('#wpstg-try-again, #wpstg-home-link').hide();
2235 $this.prop('disabled', true);
2236 that.isCancelled = true;
2237 $('#wpstg-cloning-result').text('Please wait...this can take up a while.');
2238 $('.wpstg-loader, #wpstg-show-log-button').hide();
2239 $this.parent().append(ajaxSpinner);
2240 cancelCloningUpdate();
2241 })
2242 // Restart cloning
2243 .on('click', '#wpstg-restart-cloning', function () {
2244 resetErrors();
2245 var $this = $(this);
2246 $('#wpstg-try-again, #wpstg-home-link').hide();
2247 $this.prop('disabled', true);
2248 that.isCancelled = true;
2249 $('#wpstg-cloning-result').text('Please wait...this can take up a while.');
2250 $('.wpstg-loader, #wpstg-show-log-button').hide();
2251 $this.parent().append(ajaxSpinner);
2252 restart();
2253 })
2254 // Delete clone - confirmation
2255 .on('click', '.wpstg-remove-clone[data-clone]', function (e) {
2256 resetErrors();
2257 e.preventDefault();
2258 cache.get('#wpstg-existing-clones');
2259 $workFlow.removeClass('active');
2260 cache.get('.wpstg-loader').show();
2261 var cloneData = $(this).data('clone');
2262 var stagingSiteName = '';
2263 if (document.getElementsByClassName('wpstg-clone').length > 0) {
2264 stagingSiteName = '"' + document.getElementsByClassName('wpstg-clone')[0].id + '"';
2265 }
2266 ajax({
2267 action: 'wpstg_confirm_delete_clone',
2268 accessToken: wpstg.accessToken,
2269 nonce: wpstg.nonce,
2270 clone: $(this).data('clone')
2271 }, function (response) {
2272 WPStagingCommon.getSwalModal(true, {
2273 popup: 'wpstg-swal-popup wpstg-db-comparison-modal centered-modal',
2274 content: 'wpstg--process--content'
2275 }).fire({
2276 title: 'Do you want to delete staging site ' + stagingSiteName + '?',
2277 icon: 'error',
2278 html: response,
2279 width: '100%',
2280 focusConfirm: false,
2281 confirmButtonText: 'Delete',
2282 confirmButtonColor: '#e01e5a',
2283 showCancelButton: true,
2284 onRender: function onRender() {
2285 var wpstgUnselectAllTables = document.getElementById('wpstg-unselect-all-tables');
2286 var wpstgUnselectAllTablesId = document.getElementById('wpstg-unselect-all-tables-id');
2287 if (wpstgUnselectAllTables !== null) {
2288 wpstgUnselectAllTables.addEventListener('click', function (e) {
2289 if (that.areAllTablesChecked === false) {
2290 cache.get('#wpstg_select_tables_cloning .wpstg-db-table').prop('selected', 'selected');
2291 cache.get('#wpstgUnselectAllTablesId').text('Unselect All');
2292 wpstgUnselectAllTablesId.textContent = 'Unselect All';
2293 cache.get('.wpstg-db-table-checkboxes').prop('checked', true);
2294 that.areAllTablesChecked = true;
2295 } else {
2296 cache.get('#wpstg_select_tables_cloning .wpstg-db-table').prop('selected', false);
2297 cache.get('#wpstgUnselectAllTablesId').text('Select All');
2298 wpstgUnselectAllTablesId.textContent = 'Select All';
2299 cache.get('.wpstg-db-table-checkboxes').prop('checked', false);
2300 that.areAllTablesChecked = false;
2301 }
2302 });
2303 }
2304 var swalContainer = document.querySelector('.wpstg--swal2-html-container');
2305 swalContainer.classList.remove('wpstg--swal2-html-container');
2306 var _deleteButton = document.querySelector('.wpstg--swal2-confirm');
2307 _deleteButton.style.background = '#e01e5a';
2308 document.querySelector('.wpstg--swal2-x-mark-line-left').style.background = '#e01e5a';
2309 document.querySelector('.wpstg--swal2-x-mark-line-right').style.background = '#e01e5a';
2310 document.querySelector('.wpstg--swal2-icon.wpstg--swal2-error').style.borderColor = '#e01e5a';
2311 var _btnCancel = WPStagingCommon.getSwalContainer().getElementsByClassName('wpstg--swal2-cancel wpstg--btn--cancel')[0];
2312 var btnCancel = _btnCancel.cloneNode(true);
2313 _btnCancel.parentNode.replaceChild(btnCancel, _btnCancel);
2314 btnCancel.addEventListener('click', function (e) {
2315 WPStagingCommon.closeSwalModal();
2316 that.modal.instance = null;
2317 cache.get('.wpstg-loader').removeClass('wpstg-finished');
2318 cache.get('.wpstg-loader').hide();
2319 });
2320 }
2321 }).then(function (result) {
2322 if (result.value) {
2323 var deleteDirectory = document.querySelector('#deleteDirectory:checked');
2324 var deleteDir = '';
2325 var excludedTables = [];
2326 if (deleteDirectory !== null) {
2327 deleteDir = deleteDirectory.getAttribute('data-deletepath');
2328 }
2329 $('.wpstg-db-table input:not(:checked)').each(function () {
2330 excludedTables.push(this.name);
2331 });
2332 WPStagingCommon.closeSwalModal();
2333 that.modal.instance = null;
2334 var params = {
2335 'job': 'delete'
2336 };
2337 that.wpstgProcessingModal(params, false, false);
2338 deleteClone(cloneData, deleteDir, excludedTables);
2339 }
2340 });
2341 }, 'HTML');
2342 })
2343 // Delete clone - confirmed
2344 .on('click', '#wpstg-remove-clone', function (e) {
2345 resetErrors();
2346 e.preventDefault();
2347 cache.get('#wpstg-removing-clone').addClass('wpstg-loading');
2348 cache.get('.wpstg-loader').show();
2349 deleteClone($(this).data('clone'));
2350 })
2351 // Cancel deleting clone
2352 .on('click', '#wpstg-cancel-removing', function (e) {
2353 e.preventDefault();
2354 $('.wpstg-clone').removeClass('active');
2355 cache.get('#wpstg-removing-clone').html('');
2356 })
2357 // Update
2358 .on('click', '.wpstg-execute-clone', function (e) {
2359 e.preventDefault();
2360 var clone = $(this).data('clone');
2361 $workFlow.addClass('wpstg-loading');
2362 that.cloneExcludeFilters = null;
2363 ajax({
2364 action: 'wpstg_scanning',
2365 clone: clone,
2366 accessToken: wpstg.accessToken,
2367 nonce: wpstg.nonce
2368 }, function (response) {
2369 if (response.length < 1) {
2370 showError('Something went wrong! Error: No response. Please try the <a href=\'https://wp-staging.com/docs/wp-staging-settings-for-small-servers/\' target=\'_blank\'>WP Staging Small Server Settings</a> or submit an error report and contact us.');
2371 }
2372 var jsonResponse = tryParseJson(response);
2373 if (jsonResponse !== false && jsonResponse.success === false) {
2374 $workFlow.removeClass('wpstg-loading');
2375 showErrorModal(jsonResponse);
2376 return;
2377 }
2378 $workFlow.removeClass('wpstg-loading').html(response);
2379 // register check disk space function for clone update process.
2380 checkDiskSpace();
2381 that.directoryNavigator = new WpstgDirectoryNavigation('#wpstg-directories-listing', wpstg, that.notyf);
2382 that.directoryNavigator.countSelectedFiles();
2383 that.tableSelector = new WpstgTableSelection('#wpstg-scanning-db', '#wpstg-workflow', '#wpstg_network_clone', '#wpstg_select_tables_cloning', wpstg, that.notyf);
2384 that.tableSelector.countSelectedTables();
2385 that.cloneExcludeFilters = new WpstgExcludeFilters();
2386 that.switchStep(2);
2387 }, 'HTML');
2388 }).on('click', '#wpstg-update-cloning-site-button', function (e) {
2389 window.open(that.data.cloneHostname, '_blank');
2390 })
2391 // Reset Clone
2392 .on('click', '.wpstg-reset-clone', function (e) {
2393 e.preventDefault();
2394 var clone = $(this).data('clone');
2395 var resetModal = new WpstgResetModal(clone);
2396 resetModal.setNetworkClone($(this).data('network') === 'yes');
2397 var promise = resetModal.showModal();
2398 that.areAllTablesChecked = true;
2399 promise.then(function (result) {
2400 if (result.value) {
2401 var dirNavigator = resetModal.getDirectoryNavigator();
2402 var tableSelector = resetModal.getTableSelector();
2403 var exclFilters = resetModal.getExcludeFilters().getExcludeFilters();
2404 var includedTables = '';
2405 var excludedTables = '';
2406 var selectedTablesWithoutPrefix = '';
2407 var allTablesExcluded = false;
2408 if (tableSelector !== null) {
2409 includedTables = tableSelector.getIncludedTables();
2410 excludedTables = tableSelector.getExcludedTables();
2411 selectedTablesWithoutPrefix = tableSelector.getSelectedTablesWithoutPrefix();
2412 }
2413 if (includedTables.length > excludedTables.length) {
2414 includedTables = '';
2415 } else if (excludedTables.length > includedTables.length) {
2416 excludedTables = '';
2417 allTablesExcluded = includedTables === '';
2418 }
2419 resetClone(clone, {
2420 includedTables: includedTables,
2421 excludedTables: excludedTables,
2422 allTablesExcluded: allTablesExcluded,
2423 selectedTablesWithoutPrefix: selectedTablesWithoutPrefix,
2424 excludeSizeRules: encodeURIComponent(exclFilters.sizes),
2425 excludeGlobRules: encodeURIComponent(exclFilters.globs),
2426 excludedDirectories: dirNavigator.getExcludedDirectories(),
2427 extraDirectories: dirNavigator.getExtraDirectoriesRootOnly()
2428 });
2429 }
2430 });
2431 return;
2432 });
2433 };
2434
2435 /**
2436 * Ajax Requests
2437 * @param Object data
2438 * @param Function callback
2439 * @param string dataType
2440 * @param bool showErrors
2441 * @param int tryCount
2442 * @param float incrementRatio
2443 */
2444 var ajax = function ajax(data, callback, dataType, showErrors, tryCount, incrementRatio) {
2445 if (incrementRatio === void 0) {
2446 incrementRatio = null;
2447 }
2448 if ('undefined' === typeof dataType) {
2449 dataType = 'json';
2450 }
2451 if (false !== showErrors) {
2452 showErrors = true;
2453 }
2454 tryCount = 'undefined' === typeof tryCount ? 0 : tryCount;
2455 var retryLimit = 5;
2456 var retryTimeout = 10000 * tryCount;
2457 incrementRatio = parseInt(incrementRatio);
2458 if (!isNaN(incrementRatio)) {
2459 retryTimeout *= incrementRatio;
2460 }
2461 var errorMsgFooter = 'Please try the <a href=\'https://wp-staging.com/docs/wp-staging-settings-for-small-servers/\' target=\'_blank\'>WP STAGING Small Server Settings</a> or submit an error report and contact us. <br/><br/><strong>Tip:</strong> If you get this error while pushing, you can also use the <strong>BACKUP & MIGRATION</strong> feature to move your staging site to live. <a href=\'https://wp-staging.com/docs/how-to-migrate-your-wordpress-site-to-a-new-host/\' target=\'_blank\'>Read more.</a>';
2462 $.ajax({
2463 url: ajaxurl + '?action=wpstg_processing&_=' + Date.now() / 1000,
2464 type: 'POST',
2465 dataType: dataType,
2466 cache: false,
2467 data: data,
2468 error: function error(xhr, textStatus, errorThrown) {
2469 // try again after 10 seconds
2470 tryCount++;
2471 if (tryCount <= retryLimit) {
2472 console.log('RETRYING ' + tryCount + '/' + retryLimit);
2473 setTimeout(function () {
2474 ajax(data, callback, dataType, showErrors, tryCount, incrementRatio);
2475 return;
2476 }, retryTimeout);
2477 } else {
2478 console.log('RETRYING LIMIT');
2479 var errorCode = 'undefined' === typeof xhr.status ? 'Unknown' : xhr.status;
2480 showError('Fatal Error: ' + errorCode + ' ' + errorMsgFooter);
2481 }
2482 },
2483 success: function success(data) {
2484 if ('function' === typeof callback) {
2485 callback(data);
2486 }
2487 },
2488 statusCode: {
2489 404: function _() {
2490 if (tryCount >= retryLimit) {
2491 showError('Error 404 - Can\'t find ajax request URL! ' + errorMsgFooter);
2492 }
2493 },
2494 500: function _() {
2495 if (tryCount >= retryLimit) {
2496 showError('Fatal Error 500 - Internal server error while processing the request! ' + errorMsgFooter);
2497 }
2498 },
2499 504: function _() {
2500 if (tryCount > retryLimit) {
2501 showError('Error 504 - It seems your server is rate limiting ajax requests. Please try to resume after a minute. ' + errorMsgFooter);
2502 }
2503 },
2504 502: function _() {
2505 if (tryCount >= retryLimit) {
2506 showError('Error 502 - It seems your server is rate limiting ajax requests. Please try to resume after a minute. ' + errorMsgFooter);
2507 }
2508 },
2509 503: function _() {
2510 if (tryCount >= retryLimit) {
2511 showError('Error 503 - It seem your server is rate limiting ajax requests. Please try to resume after a minute. ' + errorMsgFooter);
2512 }
2513 },
2514 429: function _() {
2515 if (tryCount >= retryLimit) {
2516 showError('Error 429 - It seems your server is rate limiting ajax requests. Please try to resume after a minute. ' + errorMsgFooter);
2517 }
2518 },
2519 403: function _() {
2520 if (tryCount >= retryLimit) {
2521 showError('Refresh page or login again! The process should be finished successfully. \n\ ');
2522 }
2523 }
2524 }
2525 });
2526 };
2527
2528 /**
2529 * Next / Previous Step Clicks to Navigate Through Staging Job
2530 */
2531 var stepButtons = function stepButtons() {
2532 var $workFlow = cache.get('#wpstg-workflow');
2533 $workFlow
2534 // Next Button
2535 .on('click', '.wpstg-next-step-link', function (e) {
2536 e.preventDefault();
2537 var $this = $(this);
2538 if ($('#wpstg_clone_hostname').length && !validateTargetHost()) {
2539 $('#wpstg_clone_hostname').focus();
2540 return false;
2541 }
2542 if ($this.data('action') === 'wpstg_update' || $this.data('action') === 'wpstg_reset') {
2543 // Update / Reset Clone - confirmed
2544 if ($this.data('action') === 'wpstg_update') {
2545 var selectedSite = $this;
2546 var selectedSiteWorkFlow = $workFlow;
2547 var selectedAction = $this.data('action');
2548 WPStagingCommon.getSwalModal(true, {
2549 popup: 'wpstg-swal-popup wpstg-db-comparison-modal centered-modal',
2550 content: 'wpstg--process--content'
2551 }).fire({
2552 title: 'Do you want to update the staging site?',
2553 icon: 'warning',
2554 html: '<div class="wpstg-confirm-text-line-height wpstg-mt-10px">This overwrites the staging site with all the selected data from the live site.<br>Use this only if you want to clone the live site again.<br><br> ' + 'Uncheck all tables and folders that you do not want to overwrite.<br>Do not cancel the update process! This could break the staging site.<br>' + 'If you are unsure, create a backup of the staging site before proceeding.<br>' + 'There is no automatic merging of database data!</div>',
2555 width: '650px',
2556 focusConfirm: false,
2557 confirmButtonText: 'Update',
2558 showCancelButton: true,
2559 onRender: function onRender() {
2560 var swalContainer = document.querySelector('.wpstg--swal2-html-container');
2561 swalContainer.classList.remove('wpstg--swal2-html-container');
2562 var _btnCancel = WPStagingCommon.getSwalContainer().getElementsByClassName('wpstg--swal2-cancel wpstg--btn--cancel')[0];
2563 var btnCancel = _btnCancel.cloneNode(true);
2564 _btnCancel.parentNode.replaceChild(btnCancel, _btnCancel);
2565 btnCancel.addEventListener('click', function (e) {
2566 WPStagingCommon.closeSwalModal();
2567 });
2568 }
2569 }).then(function (result) {
2570 if (result.value) {
2571 var selectedSiteDbCheck = document.querySelector('#wpstg-ext-db');
2572 if (selectedAction === 'wpstg_cloning') {
2573 if (selectedSiteDbCheck.checked) {
2574 verifyExternalDatabase(selectedSite, selectedSiteWorkFlow);
2575 return;
2576 }
2577 }
2578 WPStagingCommon.closeSwalModal();
2579 proceedCloning(selectedSite, selectedSiteWorkFlow);
2580 }
2581 });
2582 return false;
2583 }
2584 }
2585 if ($this.attr('disabled')) {
2586 return false;
2587 }
2588 if ($this.data('action') === 'wpstg_cloning') {
2589 // Verify External Database If Checked and Not Skipped
2590 if ($('#wpstg-ext-db').is(':checked')) {
2591 verifyExternalDatabase($this, $workFlow);
2592 return;
2593 }
2594 }
2595 proceedCloning($this, $workFlow);
2596 })
2597 // Previous Button
2598 .on('click', '.wpstg-prev-step-link', function (e) {
2599 e.preventDefault();
2600 cache.get('.wpstg-loader').removeClass('wpstg-finished');
2601 cache.get('.wpstg-loader').hide();
2602 loadOverview();
2603 });
2604 };
2605
2606 /**
2607 * Get Excluded (Unchecked) Database Tables
2608 * Not used anymore!
2609 * @return {Array}
2610 */
2611 var getExcludedTables = function getExcludedTables() {
2612 var excludedTables = [];
2613 $('.wpstg-db-table input:not(:checked)').each(function () {
2614 excludedTables.push(this.name);
2615 });
2616 return excludedTables;
2617 };
2618
2619 /**
2620 * Verify External Database for Cloning
2621 */
2622 var verifyExternalDatabase = function verifyExternalDatabase($this, workflow) {
2623 cache.get('.wpstg-loader').show();
2624 ajax({
2625 action: 'wpstg_database_verification',
2626 accessToken: wpstg.accessToken,
2627 nonce: wpstg.nonce,
2628 databaseUser: cache.get('#wpstg_db_username').val(),
2629 databasePassword: cache.get('#wpstg_db_password').val(),
2630 databaseServer: cache.get('#wpstg_db_server').val(),
2631 databaseDatabase: cache.get('#wpstg_db_database').val(),
2632 databaseSsl: cache.get('#wpstg_db_ssl').is(':checked')
2633 }, function (response) {
2634 // Undefined Error
2635 if (false === response) {
2636 showError('Something went wrong! Error: No response.' + 'Please try again. If that does not help, ' + '<a href=\'https://wp-staging.com/support/\' target=\'_blank\'>open a support ticket</a> ');
2637 cache.get('.wpstg-loader').hide();
2638 return;
2639 }
2640
2641 // Throw Error
2642 if ('undefined' === typeof response.success) {
2643 showError('Something went wrong! Error: Invalid response.' + 'Please try again. If that does not help, ' + '<a href=\'https://wp-staging.com/support/\' target=\'_blank\'>open a support ticket</a> ');
2644 cache.get('.wpstg-loader').hide();
2645 return;
2646 }
2647 if (response.success) {
2648 cache.get('.wpstg-loader').hide();
2649 proceedCloning($this, workflow);
2650 return;
2651 }
2652 if (response.error_type === 'comparison') {
2653 cache.get('.wpstg-loader').hide();
2654 var render = '<table class="wpstg-db-comparison-table"><thead><tr><th>Property</th><th>Production DB</th><th>Staging DB</th><th>Status</th></tr></thead><tbody>';
2655 response.checks.forEach(function (x) {
2656 var icon = '<span class="wpstg-css-tick"></span>';
2657 if (x.production !== x.staging) {
2658 icon = '<span class="wpstg-css-cross"></span>';
2659 }
2660 render += '<tr><td>' + x.name + '</td><td>' + x.production + '</td><td>' + x.staging + '</td><td>' + icon + '</td></tr>';
2661 });
2662 render += '</tbody></table><p>Note: Some MySQL/MariaDB properties do not match. You may proceed but the staging site may not work as expected.</p>';
2663 WPStagingCommon.getSwalModal(true, {
2664 popup: 'wpstg-swal-popup wpstg-db-comparison-modal centered-modal'
2665 }).fire({
2666 title: 'Different Database Properties',
2667 icon: 'warning',
2668 html: render,
2669 width: '650px',
2670 focusConfirm: false,
2671 confirmButtonText: 'Proceed',
2672 showCancelButton: true
2673 }).then(function (result) {
2674 if (result.value) {
2675 proceedCloning($this, workflow);
2676 }
2677 });
2678 return;
2679 }
2680 WPStagingCommon.getSwalModal(true).fire({
2681 title: 'Different Database Properties',
2682 icon: 'error',
2683 html: response.message,
2684 focusConfirm: true,
2685 confirmButtonText: 'Ok',
2686 showCancelButton: false
2687 });
2688 cache.get('.wpstg-loader').hide();
2689 }, 'json', false);
2690 };
2691
2692 /**
2693 * Get Cloning Step Data
2694 */
2695 var getCloningData = function getCloningData() {
2696 if ('wpstg_cloning' !== that.data.action && 'wpstg_update' !== that.data.action && 'wpstg_reset' !== that.data.action) {
2697 return;
2698 }
2699 that.data.cloneID = new Date().getTime().toString();
2700 if ('wpstg_update' === that.data.action) {
2701 that.data.cloneID = $('#wpstg-new-clone-id').data('clone');
2702 }
2703 that.data.cloneName = $('#wpstg-new-clone-id').val() || that.data.cloneID;
2704 if (that.directoryNavigator !== null) {
2705 that.data.excludedDirectories = encodeURIComponent(that.directoryNavigator.getExcludedDirectories());
2706 that.data.extraDirectories = encodeURIComponent(that.directoryNavigator.getExtraDirectoriesRootOnly());
2707 }
2708 that.data.excludeGlobRules = '';
2709 that.data.excludeSizeRules = '';
2710 if (that.cloneExcludeFilters instanceof WpstgExcludeFilters) {
2711 var rules = that.cloneExcludeFilters.getExcludeFilters();
2712 that.data.excludeGlobRules = encodeURIComponent(rules.globs);
2713 that.data.excludeSizeRules = encodeURIComponent(rules.sizes);
2714 }
2715 that.data.includedTables = '';
2716 that.data.excludedTables = '';
2717 that.data.allTablesExcluded = false;
2718 if (that.tableSelector !== null) {
2719 that.data.includedTables = that.tableSelector.getIncludedTables();
2720 that.data.excludedTables = that.tableSelector.getExcludedTables();
2721 that.data.selectedTablesWithoutPrefix = that.tableSelector.getSelectedTablesWithoutPrefix();
2722 }
2723 if (that.data.includedTables.length > that.data.excludedTables.length) {
2724 that.data.includedTables = '';
2725 } else if (that.data.excludedTables.length > that.data.includedTables.length) {
2726 that.data.excludedTables = '';
2727 that.data.allTablesExcluded = that.data.includedTables === '';
2728 }
2729 that.data.databaseServer = $('#wpstg_db_server').val();
2730 that.data.databaseUser = $('#wpstg_db_username').val();
2731 that.data.databasePassword = $('#wpstg_db_password').val();
2732 that.data.databaseDatabase = $('#wpstg_db_database').val();
2733 that.data.databasePrefix = $('#wpstg_db_prefix').val();
2734 that.data.databaseSsl = $('#wpstg_db_ssl').is(':checked');
2735 var cloneDir = $('#wpstg_clone_dir').val();
2736 that.data.cloneDir = encodeURIComponent($.trim(cloneDir));
2737 that.data.cloneHostname = $('#wpstg_clone_hostname').val();
2738 that.data.cronDisabled = $('#wpstg_disable_cron').is(':checked');
2739 that.data.emailsAllowed = $('#wpstg_allow_emails').is(':checked');
2740 that.data.networkClone = $('#wpstg_network_clone').is(':checked');
2741 that.data.uploadsSymlinked = $('#wpstg_symlink_upload').is(':checked');
2742 that.data.cleanPluginsThemes = $('#wpstg-clean-plugins-themes').is(':checked');
2743 that.data.cleanUploadsDir = $('#wpstg-clean-uploads').is(':checked');
2744 };
2745 var proceedCloning = function proceedCloning($this, workflow) {
2746 // Add loading overlay
2747 workflow.addClass('wpstg-loading');
2748
2749 // Prepare data
2750 that.data = {
2751 action: $this.data('action'),
2752 accessToken: wpstg.accessToken,
2753 nonce: wpstg.nonce
2754 };
2755
2756 // Cloning data
2757 getCloningData();
2758 sendCloningAjax(workflow);
2759 };
2760 var sendCloningAjax = function sendCloningAjax(workflow) {
2761 // Send ajax request
2762 ajax(that.data, function (response) {
2763 // Undefined Error
2764 if (false === response) {
2765 showError('Something went wrong!<br/><br/> Go to WP Staging > Settings and lower \'File Copy Limit\' and \'DB Query Limit\'. Also set \'CPU Load Priority to low \'' + 'and try again. If that does not help, ' + '<a href=\'https://wp-staging.com/support/\' target=\'_blank\'>open a support ticket</a> ');
2766 }
2767 if (response.length < 1) {
2768 showError('Something went wrong! No response. Go to WP Staging > Settings and lower \'File Copy Limit\' and \'DB Query Limit\'. Also set \'CPU Load Priority to low \'' + 'and try again. If that does not help, ' + '<a href=\'https://wp-staging.com/support/\' target=\'_blank\'>open a support ticket</a> ');
2769 }
2770 var jsonResponse = tryParseJson(response);
2771 if (jsonResponse !== false && jsonResponse.success === false) {
2772 workflow.removeClass('wpstg-loading');
2773 showErrorModal(jsonResponse);
2774 return;
2775 }
2776
2777 // Styling of elements
2778 workflow.removeClass('wpstg-loading').html(response);
2779 that.cloneExcludeFilters = null;
2780 if (that.data.action === 'wpstg_scanning') {
2781 that.areAllTablesChecked = true;
2782 that.directoryNavigator = new WpstgDirectoryNavigation('#wpstg-directories-listing', wpstg, that.notyf);
2783 that.tableSelector = new WpstgTableSelection('#wpstg-scanning-db', '#wpstg-workflow', '#wpstg_network_clone', '#wpstg_select_tables_cloning', wpstg);
2784 that.switchStep(2);
2785 that.cloneExcludeFilters = new WpstgExcludeFilters();
2786 that.directoryNavigator.countSelectedFiles();
2787 that.tableSelector.countSelectedTables();
2788 } else if (that.data.action === 'wpstg_cloning' || that.data.action === 'wpstg_update' || that.data.action === 'wpstg_reset') {
2789 that.switchStep(3);
2790 }
2791
2792 // Start cloning
2793 that.startCloning();
2794 }, 'HTML');
2795 };
2796 var showErrorModal = function showErrorModal(response) {
2797 var errorModal = new WpstgModal('wpstg_modal_error', wpstg);
2798 errorModal.show(Object.assign({
2799 title: 'Error',
2800 icon: 'error',
2801 html: wpstg.i18n['somethingWentWrong'] + (response.message !== undefined ? '<br/>' + response.message : ''),
2802 width: '500px',
2803 confirmButtonText: 'Ok',
2804 showCancelButton: false,
2805 customClass: {
2806 confirmButton: 'wpstg--btn--confirm wpstg-blue-primary wpstg-button wpstg-link-btn',
2807 cancelButton: 'wpstg--btn--cancel wpstg-blue-primary wpstg-link-btn',
2808 actions: 'wpstg--modal--actions',
2809 popup: 'wpstg-swal-popup centered-modal'
2810 },
2811 buttonsStyling: false,
2812 reverseButtons: true
2813 }, response.swalOptions), {
2814 type: response.type
2815 });
2816 };
2817 var tryParseJson = function tryParseJson(json) {
2818 // early bail if not string
2819 if (!json) {
2820 return false;
2821 }
2822 try {
2823 var object = JSON.parse(json);
2824 if (object && typeof object === 'object') {
2825 return object;
2826 }
2827 } catch (e) {
2828 // do nothing on catch
2829 }
2830 return false;
2831 };
2832 var resetClone = function resetClone(clone, excludeOptions) {
2833 that.data = {
2834 action: 'wpstg_reset',
2835 accessToken: wpstg.accessToken,
2836 nonce: wpstg.nonce,
2837 cloneID: clone
2838 };
2839 that.data = _extends({}, that.data, excludeOptions);
2840 var $workFlow = cache.get('#wpstg-workflow');
2841 sendCloningAjax($workFlow);
2842 };
2843
2844 /**
2845 * Loads Overview (first step) of Staging Job
2846 */
2847 var loadOverview = function loadOverview() {
2848 var $workFlow = cache.get('#wpstg-workflow');
2849 $workFlow.addClass('wpstg-loading');
2850 ajax({
2851 action: 'wpstg_overview',
2852 accessToken: wpstg.accessToken,
2853 nonce: wpstg.nonce
2854 }, function (response) {
2855 if (response.length < 1) {
2856 showError('Something went wrong! No response. Please try the <a href=\'https://wp-staging.com/docs/wp-staging-settings-for-small-servers/\' target=\'_blank\'>WP Staging Small Server Settings</a> or submit an error report.');
2857 }
2858 cache.get('.wpstg-current-step');
2859
2860 // Styling of elements
2861 $workFlow.removeClass('wpstg-loading').html(response);
2862 }, 'HTML');
2863 that.switchStep(1);
2864 cache.get('.wpstg-step3-cloning').show();
2865 cache.get('.wpstg-step3-pushing').hide();
2866 };
2867
2868 /**
2869 * Load Tabs
2870 */
2871 var tabs = function tabs() {
2872 cache.get('#wpstg-workflow').on('click', '.wpstg-tab-header', function (e) {
2873 e.preventDefault();
2874 var $this = $(this);
2875 var $section = cache.get($this.data('id'));
2876 $this.toggleClass('expand');
2877 $section.slideToggle();
2878 var tabTriangle = $this.find('.wpstg-tab-triangle');
2879 if ($this.hasClass('expand')) {
2880 tabTriangle.removeClass('wpstg-no-icon');
2881 tabTriangle.text('');
2882 tabTriangle.addClass('wpstg-rotate-90');
2883 } else {
2884 tabTriangle.removeClass('wpstg-rotate-90');
2885 }
2886 });
2887 };
2888
2889 /**
2890 * Delete Clone
2891 * @param {String} clone
2892 * @param {String} deleteDir
2893 * @param {array} excludedTables
2894 */
2895 var deleteClone = function deleteClone(clone, deleteDir, excludedTables) {
2896 ajax({
2897 action: 'wpstg_delete_clone',
2898 clone: clone,
2899 accessToken: wpstg.accessToken,
2900 nonce: wpstg.nonce,
2901 excludedTables: excludedTables,
2902 deleteDir: deleteDir
2903 }, function (response) {
2904 if (response) {
2905 showAjaxFatalError(response);
2906
2907 // Finished
2908 if ('undefined' !== typeof response["delete"] && (response["delete"] === 'finished' || response["delete"] === 'unfinished')) {
2909 cache.get('#wpstg-removing-clone').removeClass('wpstg-loading').html('');
2910 if (response["delete"] === 'finished' && response.error === undefined) {
2911 $('.wpstg-clone[data-clone-id="' + clone + '"]').remove();
2912 }
2913
2914 // No staging site message is also of type/class .wpstg-class but hidden
2915 // We have just excluded that from search when counting no of clones
2916 if ($('#wpstg-existing-clones .wpstg-clone').length < 1) {
2917 cache.get('#wpstg-existing-clones').find('h3').text('');
2918 cache.get('#wpstg-no-staging-site-results').show();
2919 }
2920 cache.get('.wpstg-loader').hide();
2921 // finish modal popup
2922 if (wpstg.i18n.wpstg_delete_clone !== null && response["delete"] === 'finished') {
2923 var params = {
2924 'job': 'finish'
2925 };
2926 that.wpstgProcessingModal(params, false, false);
2927 WPStagingCommon.getSwalModal(true, {
2928 confirmButton: 'wpstg--btn--confirm wpstg-green-button wpstg-button wpstg-link-btn wpstg-100-width'
2929 }).fire({
2930 'icon': 'success',
2931 'html': '<div style="display:block"><h2 style="color: #565656;">' + wpstg.i18n.wpstg_delete_clone.title + '</h2></div>',
2932 'confirmButtonText': 'Close',
2933 'showCancelButton': false,
2934 'showConfirmButton': true
2935 }).then(function (result) {
2936 if (result.value) {
2937 WPStagingCommon.closeSwalModal();
2938 }
2939 });
2940 }
2941 return;
2942 }
2943 }
2944 // continue
2945 if (true !== response) {
2946 deleteClone(clone, deleteDir, excludedTables);
2947 return;
2948 }
2949 });
2950 };
2951
2952 /**
2953 * Cancel Cloning Process
2954 */
2955 var cancelCloning = function cancelCloning() {
2956 that.timer('stop');
2957 if (true === that.isFinished) {
2958 return true;
2959 }
2960 ajax({
2961 action: 'wpstg_cancel_clone',
2962 clone: that.data.cloneID,
2963 accessToken: wpstg.accessToken,
2964 nonce: wpstg.nonce
2965 }, function (response) {
2966 if (response && 'undefined' !== typeof response["delete"] && response["delete"] === 'finished') {
2967 cache.get('.wpstg-loader').hide();
2968 // Load overview
2969 loadOverview();
2970 return;
2971 }
2972 if (true !== response) {
2973 // continue
2974 cancelCloning();
2975 return;
2976 }
2977
2978 // Load overview
2979 loadOverview();
2980 });
2981 };
2982
2983 /**
2984 * Cancel Cloning Process
2985 */
2986 var cancelCloningUpdate = function cancelCloningUpdate() {
2987 if (true === that.isFinished) {
2988 return true;
2989 }
2990 ajax({
2991 action: 'wpstg_cancel_update',
2992 clone: that.data.cloneID,
2993 accessToken: wpstg.accessToken,
2994 nonce: wpstg.nonce
2995 }, function (response) {
2996 if (response && 'undefined' !== typeof response["delete"] && response["delete"] === 'finished') {
2997 // Load overview
2998 loadOverview();
2999 return;
3000 }
3001 if (true !== response) {
3002 // continue
3003 cancelCloningUpdate();
3004 return;
3005 }
3006
3007 // Load overview
3008 loadOverview();
3009 });
3010 };
3011
3012 /**
3013 * Cancel Cloning Process
3014 */
3015 var restart = function restart() {
3016 if (true === that.isFinished) {
3017 return true;
3018 }
3019 ajax({
3020 action: 'wpstg_restart',
3021 // clone: that.data.cloneID,
3022 accessToken: wpstg.accessToken,
3023 nonce: wpstg.nonce
3024 }, function (response) {
3025 if (response && 'undefined' !== typeof response["delete"] && response["delete"] === 'finished') {
3026 // Load overview
3027 loadOverview();
3028 return;
3029 }
3030 if (true !== response) {
3031 // continue
3032 cancelCloningUpdate();
3033 return;
3034 }
3035
3036 // Load overview
3037 loadOverview();
3038 });
3039 };
3040
3041 /**
3042 * Append the log to the logging window
3043 * @param string log
3044 * @return void
3045 */
3046 var getLogs = function getLogs(log) {
3047 if (Array.isArray(log)) {
3048 log.forEach(function (logMessage) {
3049 if (logMessage !== null) {
3050 if (!that.messages.find(function (_ref) {
3051 var message = _ref.message;
3052 return message === logMessage.message;
3053 })) {
3054 that.messages.push(logMessage);
3055 var $logsContainer = $('.wpstg--modal--process--logs');
3056 var msgClass = "wpstg--modal--process--msg--" + (logMessage.type.toLowerCase() || 'info');
3057 $logsContainer.append("<p class=\"" + msgClass + "\">[" + (logMessage.type || 'info') + "] - [" + logMessage.date + "] - " + logMessage.message + "</p>");
3058 }
3059 }
3060 });
3061 } else {
3062 if (!that.messages.find(function (_ref2) {
3063 var message = _ref2.message;
3064 return message === log.message;
3065 })) {
3066 that.messages.push(log);
3067 var $logsContainer = $('.wpstg--modal--process--logs');
3068 var msgClass = "wpstg--modal--process--msg--" + (log.type.toLowerCase() || 'info');
3069 $logsContainer.append("<p class=\"" + msgClass + "\">[" + (log.type || 'info') + "] - [" + log.date + "] - " + log.message + "</p>");
3070 }
3071 }
3072 document.querySelectorAll('.wpstg--modal--process--logs').forEach(function (element) {
3073 element.scrollTop = element.scrollHeight;
3074 });
3075 };
3076
3077 /**
3078 * Check disk space
3079 * @return string json
3080 */
3081 var checkDiskSpace = function checkDiskSpace() {
3082 cache.get('#wpstg-check-space').on('click', function (e) {
3083 cache.get('.wpstg-loader').show();
3084 var excludedDirectories = encodeURIComponent(that.directoryNavigator.getExcludedDirectories());
3085 var extraDirectories = encodeURIComponent(that.directoryNavigator.getExtraDirectoriesRootOnly());
3086 ajax({
3087 action: 'wpstg_check_disk_space',
3088 accessToken: wpstg.accessToken,
3089 nonce: wpstg.nonce,
3090 excludedDirectories: excludedDirectories,
3091 extraDirectories: extraDirectories
3092 }, function (response) {
3093 if (false === response) {
3094 cache.get('#wpstg-clone-id-error').text('Can not detect required disk space').show();
3095 cache.get('.wpstg-loader').hide();
3096 return;
3097 }
3098
3099 // Show required disk space
3100 cache.get('#wpstg-clone-id-error').html('<strong>Estimated necessary disk space: ' + response.requiredSpace + '</strong>' + (response.errorMessage !== null ? '<br>' + response.errorMessage : '') + '<br> <span style="color:#444;">Before you proceed ensure your account has enough free disk space to hold the entire instance of the production site. You can check the available space from your hosting account (e.g. cPanel).</span>').show();
3101 cache.get('.wpstg-loader').hide();
3102 }, 'json', false);
3103 });
3104 };
3105
3106 /**
3107 * Show or hide animated loading icon
3108 * @param isLoading bool
3109 */
3110 var isLoading = function isLoading(_isLoading) {
3111 if (!_isLoading || _isLoading === false) {
3112 cache.get('.wpstg-loader').hide();
3113 } else {
3114 cache.get('.wpstg-loader').show();
3115 }
3116 };
3117
3118 /**
3119 * Count up processing execution time
3120 * @param string status
3121 * @return html
3122 */
3123 that.timer = function (status) {
3124 if (status === 'stop') {
3125 var time = that.time;
3126 that.time = 1;
3127 clearInterval(that.executionTime);
3128 return that.convertSeconds(time);
3129 }
3130 that.executionTime = setInterval(function () {
3131 if (null !== document.getElementById('wpstg-processing-timer')) {
3132 document.getElementById('wpstg-processing-timer').innerHTML = 'Elapsed Time: ' + that.convertSeconds(that.time);
3133 }
3134 that.time++;
3135 if (status === 'stop') {
3136 that.time = 1;
3137 clearInterval(that.executionTime);
3138 }
3139 }, 1000);
3140 };
3141
3142 /**
3143 * Convert seconds to hourly format
3144 * @param int seconds
3145 * @return string
3146 */
3147 that.convertSeconds = function (seconds) {
3148 var date = new Date(null);
3149 date.setSeconds(seconds); // specify value for SECONDS here
3150 return date.toISOString().substr(11, 8);
3151 };
3152
3153 /**
3154 * Start Cloning Process
3155 * @type {Function}
3156 */
3157 that.startCloning = function () {
3158 resetErrors();
3159
3160 // Register function for checking disk space
3161 checkDiskSpace();
3162 if ('wpstg_cloning' !== that.data.action && 'wpstg_update' !== that.data.action && 'wpstg_reset' !== that.data.action) {
3163 return;
3164 }
3165 that.isCancelled = false;
3166
3167 // Start the process
3168 start();
3169
3170 // Functions
3171 // Start
3172 function start() {
3173 cache.get('.wpstg-loader').show();
3174 cache.get('#wpstg-cancel-cloning').text('Cancel');
3175 cache.get('#wpstg-resume-cloning').hide();
3176 cache.get('#wpstg-error-details').hide();
3177
3178 // Clone Database
3179 setTimeout(function () {
3180 // cloneDatabase();
3181 window.addEventListener('beforeunload', WPStaging$1.warnIfClosingDuringProcess);
3182 processing();
3183 }, wpstg.delayReq);
3184 }
3185
3186 /**
3187 * Start ajax processing
3188 * @return string
3189 */
3190 var processing = function processing() {
3191 if (true === that.isCancelled) {
3192 window.removeEventListener('beforeunload', WPStaging$1.warnIfClosingDuringProcess);
3193 return false;
3194 }
3195 isLoading(true);
3196 var excludedDirectories = '';
3197 var extraDirectories = '';
3198 if (that.directoryNavigator !== null) {
3199 excludedDirectories = that.directoryNavigator.getExcludedDirectories();
3200 extraDirectories = that.directoryNavigator.getExtraDirectoriesRootOnly();
3201 }
3202
3203 // Show logging window
3204
3205 WPStaging$1.ajax({
3206 action: 'wpstg_processing',
3207 accessToken: wpstg.accessToken,
3208 nonce: wpstg.nonce,
3209 excludedTables: getExcludedTables(),
3210 excludedDirectories: encodeURIComponent(excludedDirectories),
3211 extraDirectories: encodeURIComponent(extraDirectories)
3212 }, function (response) {
3213 showAjaxFatalError(response);
3214
3215 // Add Log messages
3216 if ('undefined' !== typeof response.last_msg && response.last_msg) {
3217 getLogs(response.last_msg);
3218 }
3219 // Continue processing
3220 if (false === response.status) {
3221 progressBar(response);
3222 setTimeout(function () {
3223 // cache.get('.wpstg-loader').show();
3224 processing();
3225 }, wpstg.delayReq);
3226 } else if (true === response.status && 'finished' !== response.status) {
3227 cache.get('#wpstg-error-details').hide();
3228 cache.get('#wpstg-error-wrapper').hide();
3229 progressBar(response);
3230 processing();
3231 } else if ('finished' === response.status || 'undefined' !== typeof response.job_done && response.job_done) {
3232 window.removeEventListener('beforeunload', WPStaging$1.warnIfClosingDuringProcess);
3233 finish(response);
3234 }
3235 }, 'json', false);
3236 };
3237
3238 // Finish
3239 function finish(response) {
3240 if (true === that.getLogs) {
3241 getLogs();
3242 }
3243 progressBar(response);
3244
3245 // Add Log
3246 if ('undefined' !== typeof response.last_msg) {
3247 getLogs(response.last_msg);
3248 }
3249 cache.get('.wpstg-loader').hide();
3250 cache.get('#wpstg-processing-header').html('Processing Complete');
3251 $('#wpstg-processing-status').text('Succesfully finished');
3252 cache.get('#wpstg_staging_name').html(that.data.cloneID);
3253 cache.get('#wpstg-finished-result').show();
3254 cache.get('#wpstg-cancel-cloning').hide();
3255 cache.get('#wpstg-resume-cloning').hide();
3256 cache.get('#wpstg-cancel-cloning-update').prop('disabled', true);
3257 var $link1 = cache.get('#wpstg-clone-url-1');
3258 var $link = cache.get('#wpstg-clone-url');
3259 $link1.attr('href', response.url);
3260 $link1.html(response.url);
3261 $link.attr('href', response.url);
3262 cache.get('#wpstg-remove-clone').data('clone', that.data.cloneID);
3263
3264 // Finished
3265 that.isFinished = true;
3266 that.timer('stop');
3267 cache.get('.wpstg-loader').hide();
3268 cache.get('#wpstg-processing-header').html('Processing Complete');
3269
3270 // show alert
3271 wpstg.i18n.cloneResetComplete;
3272 if (that.data.action === 'wpstg_update') {
3273 wpstg.i18n.cloneUpdateComplete;
3274 cache.get('#wpstg-update-cloning-site-button').show();
3275 }
3276 if (wpstg.i18n[that.data.action] !== null) {
3277 that.openSuccessModalPopup(wpstg.i18n[that.data.action], true, response.url);
3278 }
3279 return false;
3280 }
3281
3282 /**
3283 * Add percentage progress bar
3284 * @param object response
3285 * @return {Boolean}
3286 */
3287 var progressBar = function progressBar(response, restart) {
3288 if (response !== null) {
3289 that.wpstgProcessingModal(response, true);
3290 }
3291 return false;
3292 };
3293 };
3294 that.switchStep = function (step) {
3295 cache.get('.wpstg-current-step').removeClass('wpstg-current-step');
3296 cache.get('.wpstg-step' + step).addClass('wpstg-current-step');
3297 };
3298 that.checkUserDbPermissions = function checkUserDbPermissions(operationType) {
3299 return new Promise(function (resolve) {
3300 WPStaging$1.ajax({
3301 action: 'wpstg_check_user_permissions',
3302 accessToken: wpstg.accessToken,
3303 nonce: wpstg.nonce,
3304 type: operationType
3305 }, function (response) {
3306 if (response.success) {
3307 resolve(true);
3308 } else {
3309 WPStagingCommon.getSwalModal(true, {
3310 container: 'wpstg-swal-push-container'
3311 }).fire({
3312 title: '',
3313 icon: 'warning',
3314 html: response.data.message,
3315 width: '750px',
3316 focusConfirm: false,
3317 confirmButtonText: 'Proceed',
3318 showCancelButton: true
3319 }).then(function (result) {
3320 if (result.isConfirmed) {
3321 resolve(true);
3322 }
3323 });
3324 $('#wpstg-db-permission-show-full-message').click(function () {
3325 $('#wpstg-permission-info-output').html($('#wpstg-permission-info-data').html());
3326 });
3327 }
3328 }, 'json', false);
3329 });
3330 };
3331
3332 /**
3333 * open success modal popup on staging site create, update, delete, reset and push
3334 * @param object message to display title and body of modal popup, show logs and site url
3335 */
3336 that.openSuccessModalPopup = function (message, showLogs, siteUrl) {
3337 if (showLogs === void 0) {
3338 showLogs = false;
3339 }
3340 if (siteUrl === void 0) {
3341 siteUrl = null;
3342 }
3343 var modal = document.getElementById('wpstg--modal--backup--download');
3344 if (message.title !== null) {
3345 modal.innerHTML = modal.innerHTML.replace('{title}', message.title);
3346 }
3347 if (showLogs) {
3348 modal.innerHTML = modal.innerHTML.replace('{btnTxtLog}', '<span style="text-decoration: underline">Show Logs</span>');
3349 }
3350 if (message.body !== null && typeof message.body !== 'undefined') {
3351 var messageBody = message.body;
3352 if (siteUrl !== null) {
3353 messageBody += '<br><strong><a href="' + siteUrl + '" target="_blank" id="wpstg-clone-url">' + siteUrl + '</a></strong>';
3354 }
3355 modal.innerHTML = modal.innerHTML.replace('{text}', messageBody);
3356 } else {
3357 modal.innerHTML = modal.innerHTML.replace('{text}', '');
3358 }
3359 WPStagingCommon.getSwalModal(true, {
3360 confirmButton: 'wpstg--btn--confirm wpstg-green-button wpstg-button wpstg-link-btn wpstg-100-width'
3361 }).fire({
3362 'icon': 'success',
3363 'html': modal.innerHTML,
3364 'confirmButtonText': 'Close',
3365 'showCancelButton': false,
3366 'showConfirmButton': true
3367 }).then(function (result) {
3368 if (result.value) {
3369 WPStagingCommon.closeSwalModal();
3370 cache.get('.wpstg-loader').removeClass('wpstg-finished');
3371 cache.get('.wpstg-loader').hide();
3372 that.messages = [];
3373 that.isProcessModalLoaded = false;
3374 if (typeof that.data !== 'undefined' && that.data.action === 'wpstg_cloning') {
3375 location.reload();
3376 }
3377 }
3378 });
3379 if (showLogs) {
3380 $('.wpstg--modal--download--logs--wrapper').show();
3381 }
3382 cache.get('.wpstg-loader').removeClass('wpstg-finished');
3383 cache.get('.wpstg-loader').hide();
3384 that.messages = [];
3385 that.isProcessModalLoaded = false;
3386 if (message.title !== null && message.title !== 'Staging Site Deleted Successfully!') {
3387 loadOverview();
3388 }
3389 };
3390
3391 /**
3392 * open process modal popup on staging site create, update, delete, reset and push
3393 * @param object message to display title and body of modal popup, show logs and site url
3394 */
3395 that.wpstgProcessingModal = function (response, showLogs, showCancelButton) {
3396 if (showCancelButton === void 0) {
3397 showCancelButton = true;
3398 }
3399 if (that.modal.processInterval === null || that.modal.processInterval === '') {
3400 that.modal.processTime = 0;
3401 that.modal.processInterval = setInterval(function () {
3402 that.modal.processTime++;
3403 }, 1000);
3404 }
3405 cache.get('.wpstg-prev-step-link').hide();
3406 cache.get('#wpstg-start-updating').hide();
3407 cache.get('.wpstg-loader').hide();
3408 cache.get('#wpstg-cancel-cloning').hide();
3409 cache.get('.wpstg-log-details').hide();
3410 cache.get('.wpstg-log-details').hide();
3411 cache.get('.wpstg-progress-bar').hide();
3412 cache.get('#wpstg-processing-header').hide();
3413 cache.get('.wpstg-processing-timer').hide();
3414 cache.get('#wpstg-cancel-pushing').hide();
3415 cache.get('.wpstg-progress-bar-wrapper').hide();
3416 cache.get('#wpstg-cancel-pushing').hide();
3417 if (document.getElementById('wpstg-cancel-cloning-update') !== null) {
3418 document.getElementById('wpstg-cancel-cloning-update').style.display = 'none';
3419 }
3420 that.modal.currentJob = response.job;
3421 if (that.isCancelled) {
3422 WPStagingCommon.closeSwalModal();
3423 that.modal.instance = null;
3424 that.modal.processTime = 0;
3425 that.modal.processInterval = null;
3426 loadOverview();
3427 setTimeout(function () {
3428 that.isCancelled = false;
3429 $('#wpstg-try-again, #wpstg-home-link, #wpstg-show-log-button, .wpstg-loader').hide();
3430 }, 1000);
3431 } else {
3432 // console.log(showCancelButton);
3433 if (!that.modal || !that.modal.instance) {
3434 if (response.job === 'delete') {
3435 $('.wpstg--modal--process--subtitle').remove();
3436 $('#wpstg--modal--backup--process button').remove();
3437 }
3438 var $modal = $('#wpstg--modal--backup--process');
3439 var html = $modal.html();
3440 $modal.remove();
3441 that.modal = {
3442 html: null,
3443 cancelBtnTxt: null,
3444 processTime: 0,
3445 instance: WPStagingCommon.getSwalModal(true, {
3446 content: 'wpstg--process--content'
3447 }).fire({
3448 html: html,
3449 cancelButtonText: 'Cancel',
3450 showCancelButton: showCancelButton,
3451 showConfirmButton: false,
3452 showCloseButton: false,
3453 showLoaderOnConfirm: false,
3454 allowEscapeKey: false,
3455 allowOutsideClick: false,
3456 onRender: function onRender() {
3457 var _btnCancel = WPStagingCommon.getSwalContainer().getElementsByClassName('wpstg--swal2-cancel wpstg--btn--cancel')[0];
3458 var btnCancel = _btnCancel.cloneNode(true);
3459 _btnCancel.parentNode.replaceChild(btnCancel, _btnCancel);
3460 btnCancel.addEventListener('click', function (e) {
3461 if (confirm('Are you sure you want to cancel cloning process?')) {
3462 that.progressBar = 0;
3463 if (that.data.action === 'wpstg_cloning') {
3464 that.isCancelled = true;
3465 cancelCloning();
3466 } else if (that.data.action === 'wpstg_update' || that.data.action === 'wpstg_reset') {
3467 that.isCancelled = true;
3468 cancelCloningUpdate();
3469 } else if (that.data.action === 'wpstg_push_processing') {
3470 var $container = $(WPStagingCommon.getSwalContainer());
3471 $container.find('.wpstg--modal--process--title').html('Canceling Please wait....');
3472 that.isCancelled = true;
3473 }
3474 }
3475 });
3476 }
3477 })
3478 };
3479 } else {
3480 var $container = $(WPStagingCommon.getSwalContainer());
3481 var cancelButton = WPStagingCommon.getSwalContainer().getElementsByClassName('wpstg--swal2-cancel wpstg--btn--cancel')[0];
3482 $container.find('.wpstg--modal--process--elapsed-time').text(that.modal.processTime + 's');
3483 if (response.job) {
3484 var title = response.job;
3485 if (response.percentage !== null) {
3486 $container.find('.wpstg--modal--process--percent').text(response.percentage);
3487 }
3488 if (response.job === 'database' || response.job === 'jobCopyDatabaseTmp') {
3489 title = 'Copying Database';
3490 cancelButton.disabled = false;
3491 } else if (response.job === 'SearchReplace') {
3492 title = 'Processing Data';
3493 cancelButton.disabled = false;
3494 } else if (response.job === 'directories' || response.job === 'jobFileScanning') {
3495 title = 'Scanning Files';
3496 cancelButton.disabled = false;
3497 } else if (response.job === 'files' || response.job === 'data' || response.job === 'jobCopy' || response.job === 'jobSearchReplace') {
3498 title = 'Copying Files';
3499 cancelButton.disabled = false;
3500 } else if (response.job === 'Backup') {
3501 title = 'Backup Files Scanning';
3502 cancelButton.disabled = false;
3503 } else if (response.job === 'finish' || response.status === 'finished') {
3504 title = 'Process Finished';
3505 cancelButton.disabled = false;
3506 } else if (response.job === 'jobDatabaseRename') {
3507 title = 'Renaming Database';
3508 cancelButton.disabled = true;
3509 }
3510 if (title !== response.job) {
3511 $container.find('.wpstg--modal--process--title').html(title);
3512 }
3513 if (response.job === 'finish') {
3514 that.modal.instance = null;
3515 that.modal.processTime = 0;
3516 that.modal.processInterval = null;
3517 clearInterval(that.modal.processInterval);
3518 WPStagingCommon.closeSwalModal();
3519 }
3520 } else {
3521 if (response.status === 'finished') {
3522 that.modal.instance = null;
3523 that.modal.processTime = 0;
3524 that.modal.processInterval = null;
3525 clearInterval(that.modal.processInterval);
3526 WPStagingCommon.closeSwalModal();
3527 }
3528 }
3529 }
3530 }
3531 };
3532
3533 /**
3534 * Initiation
3535 * @type {Function}
3536 */
3537 that.init = function () {
3538 loadOverview();
3539 elements();
3540 stepButtons();
3541 tabs();
3542 WPStagingCommon.listenTooltip();
3543 new WpstgMainMenu();
3544 new WpstgCloneStaging();
3545 new WpstgCloningAdvanceSettings();
3546 that.notyf = new Notyf({
3547 duration: 10000,
3548 position: {
3549 x: 'center',
3550 y: 'bottom'
3551 },
3552 dismissible: true,
3553 types: [{
3554 type: 'warning',
3555 background: 'orange',
3556 icon: false
3557 }]
3558 });
3559 };
3560 /**
3561 * Ajax call
3562 * @type {ajax}
3563 */
3564 that.ajax = ajax;
3565 that.showError = showError;
3566 that.getLogs = getLogs;
3567 that.loadOverview = loadOverview;
3568 return that;
3569 }(jQuery);
3570 jQuery(document).ready(function () {
3571 WPStaging$1.init();
3572 // This is necessary to make WPStaging var accessible in WP Staging PRO js script
3573 window.WPStaging = WPStaging$1;
3574 });
3575
3576 /**
3577 * Report Issue modal
3578 */
3579 jQuery(document).ready(function ($) {
3580 $('body').on('click', '.wpstg-report-issue-button', function (e) {
3581 console.log('REPORT ISSUE.');
3582 $('.wpstg-report-issue-form').toggleClass('wpstg-report-show');
3583 e.preventDefault();
3584 });
3585 $('body').on('click', '.wpstg-backups-report-issue-button', function (e) {
3586 $('.wpstg-report-issue-form').toggleClass('wpstg-report-show');
3587 e.preventDefault();
3588 });
3589 $('body').on('click', '#wpstg-report-cancel', function (e) {
3590 $('.wpstg-report-issue-form').removeClass('wpstg-report-show');
3591 e.preventDefault();
3592 });
3593 $('body').on('click', '#wpstg-report-submit', function (e) {
3594 var self = $(this);
3595 sendIssueReport(self, 'false');
3596 e.preventDefault();
3597 });
3598 $('body').on('click', '.wpstg--modal--process--logs--tail', function (e) {
3599 var logBtn = $(this);
3600 e.preventDefault();
3601 var container = WPStagingCommon.getSwalContainer();
3602 var $logs = $(container).find('.wpstg--modal--process--logs');
3603 $logs.toggle();
3604 if ($logs.is(':visible')) {
3605 logBtn.text(wpstg.i18n.hideLogs);
3606 container.childNodes[0].style.width = '97%';
3607 container.style['z-index'] = 9999;
3608 } else {
3609 logBtn.text(wpstg.i18n.showLogs);
3610 container.childNodes[0].style.width = '600px';
3611 }
3612 });
3613 /*
3614 * Close Success Modal
3615 */
3616 $('body').on('click', '#wpstg-success-button', function (e) {
3617 e.preventDefault();
3618 $('.wpstg-report-issue-form').removeClass('wpstg-report-show');
3619 });
3620 function sendIssueReport(button, forceSend) {
3621 if (forceSend === void 0) {
3622 forceSend = 'false';
3623 }
3624 var spinner = button.next();
3625 var email = $('.wpstg--tab--active .wpstg-report-email').val();
3626 var hosting_provider = $('.wpstg--tab--active .wpstg-report-hosting-provider').val();
3627 var message = $('.wpstg--tab--active .wpstg-report-description').val();
3628 var syslog = $('.wpstg--tab--active .wpstg-report-syslog').is(':checked');
3629 var terms = $('.wpstg--tab--active .wpstg-report-terms').is(':checked');
3630 console.log(hosting_provider);
3631 button.attr('disabled', true);
3632 spinner.css('visibility', 'visible');
3633 $.ajax({
3634 url: ajaxurl,
3635 type: 'POST',
3636 dataType: 'json',
3637 async: true,
3638 data: {
3639 'action': 'wpstg_send_report',
3640 'accessToken': wpstg.accessToken,
3641 'nonce': wpstg.nonce,
3642 'wpstg_email': email,
3643 'wpstg_provider': hosting_provider,
3644 'wpstg_message': message,
3645 'wpstg_syslog': +syslog,
3646 'wpstg_terms': +terms,
3647 'wpstg_force_send': forceSend
3648 }
3649 }).done(function (data) {
3650 button.attr('disabled', false);
3651 spinner.css('visibility', 'hidden');
3652 if (data.errors.length > 0) {
3653 $('.wpstg-report-issue-form .wpstg-message').remove();
3654 var errorMessage = $('<div />').addClass('wpstg-message wpstg-error-message');
3655 $.each(data.errors, function (key, value) {
3656 if (value.status === 'already_submitted') {
3657 errorMessage = '';
3658 // TODO: remove default custom classes
3659 WPStagingCommon.getSwalModal(true, {
3660 container: 'wpstg-issue-resubmit-confirmation'
3661 }).fire({
3662 title: '',
3663 icon: 'warning',
3664 html: value.message,
3665 showCancelButton: true,
3666 focusConfirm: false,
3667 confirmButtonText: 'Yes',
3668 cancelButtonText: 'No'
3669 }).then(function (result) {
3670 if (result.isConfirmed) {
3671 sendIssueReport(button, 'true');
3672 }
3673 });
3674 } else {
3675 errorMessage.append('<p>' + value + '</p>');
3676 }
3677 });
3678 $('.wpstg-report-issue-form').prepend(errorMessage);
3679 } else {
3680 var successMessage = $('<div />').addClass('wpstg-message wpstg-success-message');
3681 successMessage.append('<p>Thanks for submitting your request! You should receive an auto reply mail with your ticket ID immediately for confirmation!<br><br>If you do not get that mail please contact us directly at <strong>support@wp-staging.com</strong></p>');
3682 $('.wpstg--tab--active .wpstg-report-issue-form').html(successMessage);
3683 $('.wpstg--tab--active .wpstg-success-message').append('<div style="float:right;margin-top:10px;"><a id="wpstg-success-button" href="#" class="wpstg--red">[X] CLOSE</a></div>');
3684
3685 // Hide message
3686 setTimeout(function () {
3687 $('.wpstg--tab--active .wpstg-report-issue-form').removeClass('wpstg-report-active');
3688 }, 2000);
3689 }
3690 });
3691 }
3692
3693 // Open/close actions drop down menu
3694 $(document).on('click', '.wpstg-dropdown>.wpstg-dropdown-toggler', function (e) {
3695 e.preventDefault();
3696 $(e.target).next('.wpstg-dropdown-menu').toggleClass('shown');
3697 $(e.target).find('.wpstg-caret').toggleClass('wpstg-caret-up');
3698 });
3699 $(document).on('click', '.wpstg-caret', function (e) {
3700 e.preventDefault();
3701 var toggler = $(e.target).closest('.wpstg-dropdown-toggler');
3702 if (toggler) {
3703 toggler.trigger('click');
3704 }
3705 });
3706
3707 // Close action drop down menu if clicked anywhere outside
3708 document.addEventListener('click', function (event) {
3709 var isClickInside = event.target.closest('.wpstg-dropdown-toggler');
3710 if (!isClickInside) {
3711 var dropDown = document.getElementsByClassName('wpstg-dropdown-menu');
3712 for (var i = 0; i < dropDown.length; i++) {
3713 dropDown[i].classList.remove('shown');
3714 }
3715 $('.wpstg-caret').removeClass('wpstg-caret-up');
3716 }
3717 });
3718
3719 // "Event info" for backup errors
3720 window.addEventListener('finishedProcessWithError', function (customEvent) {
3721 $.ajax({
3722 url: ajaxurl,
3723 type: 'POST',
3724 dataType: 'json',
3725 data: {
3726 'action': 'wpstg_job_error',
3727 'accessToken': wpstg.accessToken,
3728 'nonce': wpstg.nonce,
3729 'error_message': customEvent.detail.error,
3730 'job_id': WPStagingCommon.getJobId()
3731 }
3732 });
3733 });
3734 });
3735
3736 })();
3737 //# sourceMappingURL=wpstg-admin.js.map
3738