PluginProbe ʕ •ᴥ•ʔ
WP STAGING – WordPress Backup, Restore, Migration & Clone / 3.3.1
WP STAGING – WordPress Backup, Restore, Migration & Clone v3.3.1
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 2 years ago notices 2 years ago analytics-consent-modal.js 2 years ago analytics-consent-modal.js.map 2 years ago analytics-consent-modal.min.js 2 years ago analytics-consent-modal.min.js.map 2 years ago wpstg-admin-beta.js 2 years ago wpstg-admin-beta.js.map 2 years ago wpstg-admin-beta.min.js 5 years ago wpstg-admin-beta.min.js.map 2 years ago wpstg-admin-corrupt-settings.js 2 years ago wpstg-admin-corrupt-settings.js.map 2 years ago wpstg-admin-corrupt-settings.min.js 2 years ago wpstg-admin-corrupt-settings.min.js.map 2 years ago wpstg-admin-plugins.js 2 years ago wpstg-admin-plugins.js.map 2 years ago wpstg-admin-plugins.min.js 2 years ago wpstg-admin-plugins.min.js.map 2 years ago wpstg-admin-rating.js 2 years ago wpstg-admin-rating.js.map 2 years ago wpstg-admin-rating.min.js 2 years ago wpstg-admin-rating.min.js.map 2 years ago wpstg-admin.js 2 years ago wpstg-admin.js.map 2 years ago wpstg-admin.min.js 2 years ago wpstg-admin.min.js.map 2 years ago wpstg-blank-loader.js 2 years ago wpstg-blank-loader.js.map 2 years ago wpstg-blank-loader.min.js 2 years ago wpstg-blank-loader.min.js.map 2 years ago wpstg-sweetalert2.js 2 years ago wpstg-sweetalert2.js.map 2 years ago wpstg-sweetalert2.min.js 2 years ago wpstg-sweetalert2.min.js.map 2 years ago wpstg.js 2 years ago wpstg.js.map 2 years ago wpstg.min.js 2 years ago wpstg.min.js.map 2 years ago
wpstg-admin.js
5759 lines
1 (function () {
2 'use strict';
3
4 function _regeneratorRuntime() {
5 _regeneratorRuntime = function () {
6 return exports;
7 };
8 var exports = {},
9 Op = Object.prototype,
10 hasOwn = Op.hasOwnProperty,
11 defineProperty = Object.defineProperty || function (obj, key, desc) {
12 obj[key] = desc.value;
13 },
14 $Symbol = "function" == typeof Symbol ? Symbol : {},
15 iteratorSymbol = $Symbol.iterator || "@@iterator",
16 asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator",
17 toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
18 function define(obj, key, value) {
19 return Object.defineProperty(obj, key, {
20 value: value,
21 enumerable: !0,
22 configurable: !0,
23 writable: !0
24 }), obj[key];
25 }
26 try {
27 define({}, "");
28 } catch (err) {
29 define = function (obj, key, value) {
30 return obj[key] = value;
31 };
32 }
33 function wrap(innerFn, outerFn, self, tryLocsList) {
34 var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator,
35 generator = Object.create(protoGenerator.prototype),
36 context = new Context(tryLocsList || []);
37 return defineProperty(generator, "_invoke", {
38 value: makeInvokeMethod(innerFn, self, context)
39 }), generator;
40 }
41 function tryCatch(fn, obj, arg) {
42 try {
43 return {
44 type: "normal",
45 arg: fn.call(obj, arg)
46 };
47 } catch (err) {
48 return {
49 type: "throw",
50 arg: err
51 };
52 }
53 }
54 exports.wrap = wrap;
55 var ContinueSentinel = {};
56 function Generator() {}
57 function GeneratorFunction() {}
58 function GeneratorFunctionPrototype() {}
59 var IteratorPrototype = {};
60 define(IteratorPrototype, iteratorSymbol, function () {
61 return this;
62 });
63 var getProto = Object.getPrototypeOf,
64 NativeIteratorPrototype = getProto && getProto(getProto(values([])));
65 NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype);
66 var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype);
67 function defineIteratorMethods(prototype) {
68 ["next", "throw", "return"].forEach(function (method) {
69 define(prototype, method, function (arg) {
70 return this._invoke(method, arg);
71 });
72 });
73 }
74 function AsyncIterator(generator, PromiseImpl) {
75 function invoke(method, arg, resolve, reject) {
76 var record = tryCatch(generator[method], generator, arg);
77 if ("throw" !== record.type) {
78 var result = record.arg,
79 value = result.value;
80 return value && "object" == typeof value && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) {
81 invoke("next", value, resolve, reject);
82 }, function (err) {
83 invoke("throw", err, resolve, reject);
84 }) : PromiseImpl.resolve(value).then(function (unwrapped) {
85 result.value = unwrapped, resolve(result);
86 }, function (error) {
87 return invoke("throw", error, resolve, reject);
88 });
89 }
90 reject(record.arg);
91 }
92 var previousPromise;
93 defineProperty(this, "_invoke", {
94 value: function (method, arg) {
95 function callInvokeWithMethodAndArg() {
96 return new PromiseImpl(function (resolve, reject) {
97 invoke(method, arg, resolve, reject);
98 });
99 }
100 return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();
101 }
102 });
103 }
104 function makeInvokeMethod(innerFn, self, context) {
105 var state = "suspendedStart";
106 return function (method, arg) {
107 if ("executing" === state) throw new Error("Generator is already running");
108 if ("completed" === state) {
109 if ("throw" === method) throw arg;
110 return doneResult();
111 }
112 for (context.method = method, context.arg = arg;;) {
113 var delegate = context.delegate;
114 if (delegate) {
115 var delegateResult = maybeInvokeDelegate(delegate, context);
116 if (delegateResult) {
117 if (delegateResult === ContinueSentinel) continue;
118 return delegateResult;
119 }
120 }
121 if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) {
122 if ("suspendedStart" === state) throw state = "completed", context.arg;
123 context.dispatchException(context.arg);
124 } else "return" === context.method && context.abrupt("return", context.arg);
125 state = "executing";
126 var record = tryCatch(innerFn, self, context);
127 if ("normal" === record.type) {
128 if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue;
129 return {
130 value: record.arg,
131 done: context.done
132 };
133 }
134 "throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg);
135 }
136 };
137 }
138 function maybeInvokeDelegate(delegate, context) {
139 var methodName = context.method,
140 method = delegate.iterator[methodName];
141 if (undefined === method) return context.delegate = null, "throw" === methodName && delegate.iterator.return && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method) || "return" !== methodName && (context.method = "throw", context.arg = new TypeError("The iterator does not provide a '" + methodName + "' method")), ContinueSentinel;
142 var record = tryCatch(method, delegate.iterator, context.arg);
143 if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel;
144 var info = record.arg;
145 return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel);
146 }
147 function pushTryEntry(locs) {
148 var entry = {
149 tryLoc: locs[0]
150 };
151 1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry);
152 }
153 function resetTryEntry(entry) {
154 var record = entry.completion || {};
155 record.type = "normal", delete record.arg, entry.completion = record;
156 }
157 function Context(tryLocsList) {
158 this.tryEntries = [{
159 tryLoc: "root"
160 }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0);
161 }
162 function values(iterable) {
163 if (iterable) {
164 var iteratorMethod = iterable[iteratorSymbol];
165 if (iteratorMethod) return iteratorMethod.call(iterable);
166 if ("function" == typeof iterable.next) return iterable;
167 if (!isNaN(iterable.length)) {
168 var i = -1,
169 next = function next() {
170 for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next;
171 return next.value = undefined, next.done = !0, next;
172 };
173 return next.next = next;
174 }
175 }
176 return {
177 next: doneResult
178 };
179 }
180 function doneResult() {
181 return {
182 value: undefined,
183 done: !0
184 };
185 }
186 return GeneratorFunction.prototype = GeneratorFunctionPrototype, defineProperty(Gp, "constructor", {
187 value: GeneratorFunctionPrototype,
188 configurable: !0
189 }), defineProperty(GeneratorFunctionPrototype, "constructor", {
190 value: GeneratorFunction,
191 configurable: !0
192 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) {
193 var ctor = "function" == typeof genFun && genFun.constructor;
194 return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name));
195 }, exports.mark = function (genFun) {
196 return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun;
197 }, exports.awrap = function (arg) {
198 return {
199 __await: arg
200 };
201 }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () {
202 return this;
203 }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) {
204 void 0 === PromiseImpl && (PromiseImpl = Promise);
205 var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl);
206 return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) {
207 return result.done ? result.value : iter.next();
208 });
209 }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () {
210 return this;
211 }), define(Gp, "toString", function () {
212 return "[object Generator]";
213 }), exports.keys = function (val) {
214 var object = Object(val),
215 keys = [];
216 for (var key in object) keys.push(key);
217 return keys.reverse(), function next() {
218 for (; keys.length;) {
219 var key = keys.pop();
220 if (key in object) return next.value = key, next.done = !1, next;
221 }
222 return next.done = !0, next;
223 };
224 }, exports.values = values, Context.prototype = {
225 constructor: Context,
226 reset: function (skipTempReset) {
227 if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) "t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined);
228 },
229 stop: function () {
230 this.done = !0;
231 var rootRecord = this.tryEntries[0].completion;
232 if ("throw" === rootRecord.type) throw rootRecord.arg;
233 return this.rval;
234 },
235 dispatchException: function (exception) {
236 if (this.done) throw exception;
237 var context = this;
238 function handle(loc, caught) {
239 return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught;
240 }
241 for (var i = this.tryEntries.length - 1; i >= 0; --i) {
242 var entry = this.tryEntries[i],
243 record = entry.completion;
244 if ("root" === entry.tryLoc) return handle("end");
245 if (entry.tryLoc <= this.prev) {
246 var hasCatch = hasOwn.call(entry, "catchLoc"),
247 hasFinally = hasOwn.call(entry, "finallyLoc");
248 if (hasCatch && hasFinally) {
249 if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);
250 if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);
251 } else if (hasCatch) {
252 if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);
253 } else {
254 if (!hasFinally) throw new Error("try statement without catch or finally");
255 if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);
256 }
257 }
258 }
259 },
260 abrupt: function (type, arg) {
261 for (var i = this.tryEntries.length - 1; i >= 0; --i) {
262 var entry = this.tryEntries[i];
263 if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) {
264 var finallyEntry = entry;
265 break;
266 }
267 }
268 finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null);
269 var record = finallyEntry ? finallyEntry.completion : {};
270 return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record);
271 },
272 complete: function (record, afterLoc) {
273 if ("throw" === record.type) throw record.arg;
274 return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel;
275 },
276 finish: function (finallyLoc) {
277 for (var i = this.tryEntries.length - 1; i >= 0; --i) {
278 var entry = this.tryEntries[i];
279 if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel;
280 }
281 },
282 catch: function (tryLoc) {
283 for (var i = this.tryEntries.length - 1; i >= 0; --i) {
284 var entry = this.tryEntries[i];
285 if (entry.tryLoc === tryLoc) {
286 var record = entry.completion;
287 if ("throw" === record.type) {
288 var thrown = record.arg;
289 resetTryEntry(entry);
290 }
291 return thrown;
292 }
293 }
294 throw new Error("illegal catch attempt");
295 },
296 delegateYield: function (iterable, resultName, nextLoc) {
297 return this.delegate = {
298 iterator: values(iterable),
299 resultName: resultName,
300 nextLoc: nextLoc
301 }, "next" === this.method && (this.arg = undefined), ContinueSentinel;
302 }
303 }, exports;
304 }
305 function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
306 try {
307 var info = gen[key](arg);
308 var value = info.value;
309 } catch (error) {
310 reject(error);
311 return;
312 }
313 if (info.done) {
314 resolve(value);
315 } else {
316 Promise.resolve(value).then(_next, _throw);
317 }
318 }
319 function _asyncToGenerator(fn) {
320 return function () {
321 var self = this,
322 args = arguments;
323 return new Promise(function (resolve, reject) {
324 var gen = fn.apply(self, args);
325 function _next(value) {
326 asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
327 }
328 function _throw(err) {
329 asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
330 }
331 _next(undefined);
332 });
333 };
334 }
335 function _extends() {
336 _extends = Object.assign ? Object.assign.bind() : function (target) {
337 for (var i = 1; i < arguments.length; i++) {
338 var source = arguments[i];
339 for (var key in source) {
340 if (Object.prototype.hasOwnProperty.call(source, key)) {
341 target[key] = source[key];
342 }
343 }
344 }
345 return target;
346 };
347 return _extends.apply(this, arguments);
348 }
349 function _unsupportedIterableToArray(o, minLen) {
350 if (!o) return;
351 if (typeof o === "string") return _arrayLikeToArray(o, minLen);
352 var n = Object.prototype.toString.call(o).slice(8, -1);
353 if (n === "Object" && o.constructor) n = o.constructor.name;
354 if (n === "Map" || n === "Set") return Array.from(o);
355 if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
356 }
357 function _arrayLikeToArray(arr, len) {
358 if (len == null || len > arr.length) len = arr.length;
359 for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
360 return arr2;
361 }
362 function _createForOfIteratorHelperLoose(o, allowArrayLike) {
363 var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
364 if (it) return (it = it.call(o)).next.bind(it);
365 if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
366 if (it) o = it;
367 var i = 0;
368 return function () {
369 if (i >= o.length) return {
370 done: true
371 };
372 return {
373 done: false,
374 value: o[i++]
375 };
376 };
377 }
378 throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
379 }
380
381 /**
382 * Polyfills the `Element.prototype.closest` function if not available in the browser.
383 *
384 * @return {Function} A function that will return the closest element, by selector, to this element.
385 */
386 function polyfillClosest() {
387 if (Element.prototype.closest) {
388 if (!Element.prototype.matches) {
389 Element.prototype.matches = Element.prototype.msMatchesSelector || Element.prototype.webkitMatchesSelector;
390 }
391 Element.prototype.closest = function (s) {
392 var el = this;
393 do {
394 if (Element.prototype.matches.call(el, s)) return el;
395 el = el.parentElement || el.parentNode;
396 } while (el !== null && el.nodeType === 1);
397 return null;
398 };
399 }
400 return function (element, selector) {
401 return element instanceof Element ? element.closest(selector) : null;
402 };
403 }
404 var closest = polyfillClosest();
405
406 /**
407 * This is a namespaced port of https://github.com/tristen/hoverintent,
408 * with slight modification to accept selector with dynamically added element in dom,
409 * instead of just already present element.
410 *
411 * @param {HTMLElement} parent
412 * @param {string} selector
413 * @param {CallableFunction} onOver
414 * @param {CallableFunction} onOut
415 *
416 * @return {object}
417 */
418 function wpstgHoverIntent (parent, selector, onOver, onOut) {
419 var x;
420 var y;
421 var pX;
422 var pY;
423 var mouseOver = false;
424 var focused = false;
425 var h = {};
426 var state = 0;
427 var timer = 0;
428 var options = {
429 sensitivity: 7,
430 interval: 100,
431 timeout: 0,
432 handleFocus: false
433 };
434 function delay(el, e) {
435 if (timer) {
436 timer = clearTimeout(timer);
437 }
438 state = 0;
439 return focused ? undefined : onOut(el, e);
440 }
441 function tracker(e) {
442 x = e.clientX;
443 y = e.clientY;
444 }
445 function compare(el, e) {
446 if (timer) timer = clearTimeout(timer);
447 if (Math.abs(pX - x) + Math.abs(pY - y) < options.sensitivity) {
448 state = 1;
449 return focused ? undefined : onOver(el, e);
450 } else {
451 pX = x;
452 pY = y;
453 timer = setTimeout(function () {
454 compare(el, e);
455 }, options.interval);
456 }
457 }
458
459 // Public methods
460 h.options = function (opt) {
461 var focusOptionChanged = opt.handleFocus !== options.handleFocus;
462 options = Object.assign({}, options, opt);
463 if (focusOptionChanged) {
464 options.handleFocus ? addFocus() : removeFocus();
465 }
466 return h;
467 };
468 function dispatchOver(el, e) {
469 mouseOver = true;
470 if (timer) {
471 timer = clearTimeout(timer);
472 }
473 el.removeEventListener('mousemove', tracker, false);
474 if (state !== 1) {
475 pX = e.clientX;
476 pY = e.clientY;
477 el.addEventListener('mousemove', tracker, false);
478 timer = setTimeout(function () {
479 compare(el, e);
480 }, options.interval);
481 }
482 return this;
483 }
484
485 /**
486 * Newly added method,
487 * A wrapper around dispatchOver to support dynamically added elements to dom
488 */
489 function onMouseOver(event) {
490 if (event.target.matches(selector + ', ' + selector + ' *')) {
491 dispatchOver(event.target.closest(selector), event);
492 }
493 }
494 function dispatchOut(el, e) {
495 mouseOver = false;
496 if (timer) {
497 timer = clearTimeout(timer);
498 }
499 el.removeEventListener('mousemove', tracker, false);
500 if (state === 1) {
501 timer = setTimeout(function () {
502 delay(el, e);
503 }, options.timeout);
504 }
505 return this;
506 }
507
508 /**
509 * Newly added method,
510 * A wrapper around dispatchOut to support dynamically added elements to dom
511 */
512 function onMouseOut(event) {
513 if (event.target.matches(selector + ', ' + selector + ' *')) {
514 dispatchOut(event.target.closest(selector), event);
515 }
516 }
517 function dispatchFocus(el, e) {
518 if (!mouseOver) {
519 focused = true;
520 onOver(el, e);
521 }
522 }
523
524 /**
525 * Newly added method,
526 * A wrapper around dispatchFocus to support dynamically added elements to dom
527 */
528 function onFocus(event) {
529 if (event.target.matches(selector + ', ' + selector + ' *')) {
530 dispatchFocus(event.target.closest(selector), event);
531 }
532 }
533 function dispatchBlur(el, e) {
534 if (!mouseOver && focused) {
535 focused = false;
536 onOut(el, e);
537 }
538 }
539
540 /**
541 * Newly added method,
542 * A wrapper around dispatchBlur to support dynamically added elements to dom
543 */
544 function onBlur(event) {
545 if (event.target.matches(selector + ', ' + selector + ' *')) {
546 dispatchBlur(event.target.closest(selector), event);
547 }
548 }
549
550 /**
551 * Modified to support dynamically added element
552 */
553 function addFocus() {
554 parent.addEventListener('focus', onFocus, false);
555 parent.addEventListener('blur', onBlur, false);
556 }
557
558 /**
559 * Modified to support dynamically added element
560 */
561 function removeFocus() {
562 parent.removeEventListener('focus', onFocus, false);
563 parent.removeEventListener('blur', onBlur, false);
564 }
565
566 /**
567 * Modified to support dynamically added element
568 */
569 h.remove = function () {
570 if (!parent) {
571 return;
572 }
573 parent.removeEventListener('mouseover', onMouseOver, false);
574 parent.removeEventListener('mouseout', onMouseOut, false);
575 removeFocus();
576 };
577
578 /**
579 * Modified to support dynamically added element
580 */
581 if (parent) {
582 parent.addEventListener('mouseover', onMouseOver, false);
583 parent.addEventListener('mouseout', onMouseOut, false);
584 }
585 return h;
586 }
587
588 /**
589 * Detect memory exhaustion and show warning.
590 */
591 var WpstgDetectMemoryExhaust = /*#__PURE__*/function () {
592 function WpstgDetectMemoryExhaust(wpstgObject) {
593 if (wpstgObject === void 0) {
594 wpstgObject = wpstg;
595 }
596 this.wpstgObject = wpstgObject;
597 }
598 var _proto = WpstgDetectMemoryExhaust.prototype;
599 _proto.sendRequest = /*#__PURE__*/function () {
600 var _sendRequest = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(requestType) {
601 var response, data;
602 return _regeneratorRuntime().wrap(function _callee$(_context) {
603 while (1) switch (_context.prev = _context.next) {
604 case 0:
605 _context.prev = 0;
606 _context.next = 3;
607 return fetch(this.wpstgObject.ajaxUrl, {
608 method: 'POST',
609 credentials: 'same-origin',
610 body: new URLSearchParams({
611 action: 'wpstg--detect-memory-exhaust',
612 requestType: requestType,
613 accessToken: this.wpstgObject.accessToken,
614 nonce: this.wpstgObject.nonce
615 }),
616 headers: {
617 'Content-Type': 'application/x-www-form-urlencoded'
618 }
619 });
620 case 3:
621 response = _context.sent;
622 _context.next = 6;
623 return response.json();
624 case 6:
625 data = _context.sent;
626 if (!('undefined' !== typeof data.status && data.status && data.error)) {
627 _context.next = 9;
628 break;
629 }
630 return _context.abrupt("return", data);
631 case 9:
632 console.warn(data.message);
633 _context.next = 15;
634 break;
635 case 12:
636 _context.prev = 12;
637 _context.t0 = _context["catch"](0);
638 console.warn(this.wpstgObject.i18n['somethingWentWrong'], _context.t0);
639 case 15:
640 return _context.abrupt("return", false);
641 case 16:
642 case "end":
643 return _context.stop();
644 }
645 }, _callee, this, [[0, 12]]);
646 }));
647 function sendRequest(_x) {
648 return _sendRequest.apply(this, arguments);
649 }
650 return sendRequest;
651 }();
652 return WpstgDetectMemoryExhaust;
653 }();
654
655 var WPStagingCommon = (function ($) {
656 var WPStagingCommon = {
657 continueErrorHandle: true,
658 retry: {
659 currentDelay: 0,
660 count: 0,
661 max: 10,
662 retryOnErrors: [401, 403, 404, 429, 502, 503, 504],
663 performingRequest: false,
664 incrementRetry: function incrementRetry(incrementRatio) {
665 if (incrementRatio === void 0) {
666 incrementRatio = 1.25;
667 }
668 WPStagingCommon.retry.performingRequest = true;
669 if (WPStagingCommon.retry.currentDelay === 0) {
670 // start with a delay of 1sec
671 WPStagingCommon.retry.currentDelay = 1000;
672 WPStagingCommon.retry.count = 1;
673 }
674 WPStagingCommon.retry.currentDelay += 500 * WPStagingCommon.retry.count * incrementRatio;
675 WPStagingCommon.retry.count++;
676 },
677 canRetry: function canRetry() {
678 return WPStagingCommon.retry.count < WPStagingCommon.retry.max;
679 },
680 reset: function reset() {
681 WPStagingCommon.retry.currentDelay = 0;
682 WPStagingCommon.retry.count = 0;
683 WPStagingCommon.retry.performingRequest = false;
684 }
685 },
686 memoryExhaustArticleLink: 'https://wp-staging.com/docs/php-fatal-error-allowed-memory-size-of-134217728-bytes-exhausted/',
687 cache: {
688 elements: [],
689 get: function get(selector) {
690 // It is already cached!
691 if ($.inArray(selector, this.elements) !== -1) {
692 return this.elements[selector];
693 }
694
695 // Create cache and return
696 this.elements[selector] = $(selector);
697 return this.elements[selector];
698 },
699 refresh: function refresh(selector) {
700 selector.elements[selector] = $(selector);
701 }
702 },
703 setJobId: function setJobId(jobId) {
704 localStorage.setItem('jobIdBeingProcessed', jobId);
705 },
706 getJobId: function getJobId() {
707 return localStorage.getItem('jobIdBeingProcessed');
708 },
709 checkMemoryExhaustion: function checkMemoryExhaustion(requestType) {
710 return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
711 var detectMemoryExhaust, response;
712 return _regeneratorRuntime().wrap(function _callee$(_context) {
713 while (1) switch (_context.prev = _context.next) {
714 case 0:
715 detectMemoryExhaust = new WpstgDetectMemoryExhaust();
716 _context.next = 3;
717 return detectMemoryExhaust.sendRequest(requestType);
718 case 3:
719 response = _context.sent;
720 if (response) {
721 _context.next = 6;
722 break;
723 }
724 return _context.abrupt("return", false);
725 case 6:
726 return _context.abrupt("return", response);
727 case 10:
728 case "end":
729 return _context.stop();
730 }
731 }, _callee);
732 }))();
733 },
734 listenTooltip: function listenTooltip() {
735 wpstgHoverIntent(document, '.wpstg--tooltip', function (target, event) {
736 target.querySelector('.wpstg--tooltiptext').style.visibility = 'visible';
737 }, function (target, event) {
738 target.querySelector('.wpstg--tooltiptext').style.visibility = 'hidden';
739 });
740 },
741 // Get the custom themed Swal Modal for WP Staging
742 // Easy to maintain now in one place now
743 getSwalModal: function getSwalModal(isContentCentered, customClasses) {
744 if (isContentCentered === void 0) {
745 isContentCentered = false;
746 }
747 if (customClasses === void 0) {
748 customClasses = {};
749 }
750 // common style for all swal modal used in WP Staging
751 var defaultCustomClasses = {
752 confirmButton: 'wpstg--btn--confirm wpstg-blue-primary wpstg-button wpstg-link-btn wpstg-100-width',
753 cancelButton: 'wpstg--btn--cancel wpstg-blue-primary wpstg-link-btn wpstg-100-width',
754 actions: 'wpstg--modal--actions',
755 popup: isContentCentered ? 'wpstg-swal-popup wpstg-centered-modal' : 'wpstg-swal-popup'
756 };
757
758 // If an attribute exists in both default and additional attributes,
759 // The class(es) of the additional attribute will overwrite the default one.
760 var options = {
761 customClass: Object.assign(defaultCustomClasses, customClasses),
762 buttonsStyling: false,
763 reverseButtons: true,
764 showClass: {
765 popup: 'wpstg--swal2-show wpstg-swal-show'
766 }
767 };
768 return wpstgSwal.mixin(options);
769 },
770 showSuccessModal: function showSuccessModal(htmlContent) {
771 this.getSwalModal().fire({
772 showConfirmButton: false,
773 showCancelButton: true,
774 cancelButtonText: 'OK',
775 icon: 'success',
776 title: 'Success!',
777 html: '<div class="wpstg--grey" style="text-align: left; margin-top: 8px;">' + htmlContent + '</div>'
778 });
779 },
780 showWarningModal: function showWarningModal(htmlContent) {
781 this.getSwalModal().fire({
782 showConfirmButton: false,
783 showCancelButton: true,
784 cancelButtonText: 'OK',
785 icon: 'warning',
786 title: '',
787 html: '<div class="wpstg--grey" style="text-align: left; margin-top: 8px;">' + htmlContent + '</div>'
788 });
789 },
790 showErrorModal: function showErrorModal(htmlContent) {
791 this.getSwalModal().fire({
792 showConfirmButton: false,
793 showCancelButton: true,
794 cancelButtonText: 'OK',
795 icon: 'error',
796 title: 'Error!',
797 html: '<div class="wpstg--grey" style="text-align: left; margin-top: 8px;">' + htmlContent + '</div>'
798 });
799 },
800 getSwalContainer: function getSwalContainer() {
801 return wpstgSwal.getContainer();
802 },
803 closeSwalModal: function closeSwalModal() {
804 wpstgSwal.close();
805 },
806 /**
807 * Treats a default response object generated by WordPress's
808 * wp_send_json_success() or wp_send_json_error() functions in
809 * PHP, parses it in JavaScript, and either throws if it's an error,
810 * or returns the data if the response is successful.
811 *
812 * @param {object} response
813 * @return {*}
814 */
815 getDataFromWordPressResponse: function getDataFromWordPressResponse(response) {
816 if (typeof response !== 'object') {
817 throw new Error('Unexpected response (ERR 1341)');
818 }
819 if (!response.hasOwnProperty('success')) {
820 throw new Error('Unexpected response (ERR 1342)');
821 }
822 if (!response.hasOwnProperty('data')) {
823 throw new Error('Unexpected response (ERR 1343)');
824 }
825 if (response.success === false) {
826 if (response.data instanceof Array && response.data.length > 0) {
827 throw new Error(response.data.shift());
828 } else {
829 throw new Error('Response was not successful');
830 }
831 } else {
832 // Successful response. Return the data.
833 return response.data;
834 }
835 },
836 isLoading: function isLoading(_isLoading) {
837 if (!_isLoading || _isLoading === false) {
838 WPStagingCommon.cache.get('.wpstg-loader').hide();
839 } else {
840 WPStagingCommon.cache.get('.wpstg-loader').show();
841 }
842 },
843 /**
844 * Convert the given url to make it slug compatible
845 * @param {string} url
846 * @return {string}
847 */
848 slugify: function slugify(url) {
849 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(/-*$/, '');
850 },
851 showAjaxFatalError: function showAjaxFatalError(response, prependMessage, appendMessage) {
852 prependMessage = prependMessage ? prependMessage + '<br/><br/>' : 'Something went wrong! <br/><br/>';
853 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.';
854 if (response === false) {
855 WPStagingCommon.showError(prependMessage + ' Error: No response.' + appendMessage);
856 window.removeEventListener('beforeunload', WPStaging.warnIfClosingDuringProcess);
857 return;
858 }
859 if (typeof response.error !== 'undefined' && response.error) {
860 WPStagingCommon.showError(prependMessage + ' Error: ' + response.message + appendMessage);
861 window.removeEventListener('beforeunload', WPStaging.warnIfClosingDuringProcess);
862 return;
863 }
864 },
865 handleFetchErrors: function handleFetchErrors(response) {
866 if (!response.ok) {
867 WPStagingCommon.showError('Error: ' + response.status + ' - ' + response.statusText + '. Please try again or contact support.');
868 }
869 return response;
870 },
871 showError: function showError(message) {
872 // If retry request no need to show Error;
873 if (WPStagingCommon.retry.performingRequest) {
874 return;
875 }
876 WPStagingCommon.cache.get('#wpstg-try-again').css('display', 'inline-block');
877 WPStagingCommon.cache.get('#wpstg-cancel-cloning').text('Reset');
878 WPStagingCommon.cache.get('#wpstg-resume-cloning').show();
879 WPStagingCommon.cache.get('#wpstg-error-wrapper').show();
880 WPStagingCommon.cache.get('#wpstg-error-details').show().html(message);
881 WPStagingCommon.cache.get('#wpstg-removing-clone').removeClass('loading');
882 WPStagingCommon.cache.get('.wpstg-loader').hide();
883 $('.wpstg--modal--process--generic-problem').show().html(message);
884 },
885 resetErrors: function resetErrors() {
886 WPStagingCommon.cache.get('#wpstg-error-details').hide().html('');
887 },
888 /**
889 * Ajax Requests
890 * @param {Object} data
891 * @param {Function} callback
892 * @param {string} dataType
893 * @param {bool} showErrors
894 * @param {int} tryCount
895 * @param {float} incrementRatio
896 * @param {function} errorCallback
897 */
898 ajax: function ajax(data, callback, dataType, showErrors, tryCount, incrementRatio, errorCallback) {
899 if (incrementRatio === void 0) {
900 incrementRatio = null;
901 }
902 if (errorCallback === void 0) {
903 errorCallback = null;
904 }
905 if ('undefined' === typeof dataType) {
906 dataType = 'json';
907 }
908 if (false !== showErrors) {
909 showErrors = true;
910 }
911 tryCount = 'undefined' === typeof tryCount ? 0 : tryCount;
912 var retryLimit = 10;
913 var retryTimeout = 10000 * tryCount;
914 incrementRatio = parseInt(incrementRatio);
915 if (!isNaN(incrementRatio)) {
916 retryTimeout *= incrementRatio;
917 }
918 $.ajax({
919 url: ajaxurl + '?action=wpstg_processing&_=' + Date.now() / 1000,
920 type: 'POST',
921 dataType: dataType,
922 cache: false,
923 data: data,
924 error: function error(xhr, textStatus, errorThrown) {
925 console.log(xhr.status + ' ' + xhr.statusText + '---' + textStatus);
926 if (typeof errorCallback === 'function') {
927 // Custom error handler
928 errorCallback(xhr, textStatus, errorThrown);
929 if (!WPStagingCommon.continueErrorHandle) {
930 // Reset state
931 WPStagingCommon.continueErrorHandle = true;
932 return;
933 }
934 }
935
936 // Default error handler
937 tryCount++;
938 if (tryCount <= retryLimit) {
939 setTimeout(function () {
940 WPStagingCommon.ajax(data, callback, dataType, showErrors, tryCount, incrementRatio);
941 return;
942 }, retryTimeout);
943 } else {
944 var errorCode = 'undefined' === typeof xhr.status ? 'Unknown' : xhr.status;
945 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.');
946 }
947 },
948 success: function success(data) {
949 if ('function' === typeof callback) {
950 callback(data);
951 }
952 },
953 statusCode: {
954 404: function _() {
955 if (tryCount >= retryLimit) {
956 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.');
957 }
958 },
959 500: function _() {
960 if (tryCount >= retryLimit) {
961 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.');
962 }
963 },
964 504: function _() {
965 if (tryCount > retryLimit) {
966 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\ ');
967 }
968 },
969 502: function _() {
970 if (tryCount >= retryLimit) {
971 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\ ');
972 }
973 },
974 503: function _() {
975 if (tryCount >= retryLimit) {
976 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\ ');
977 }
978 },
979 429: function _() {
980 if (tryCount >= retryLimit) {
981 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\ ');
982 }
983 },
984 403: function _() {
985 if (tryCount >= retryLimit) {
986 WPStagingCommon.showError('Refresh page or login again! The process should be finished successfully. \n\ ');
987 }
988 }
989 }
990 });
991 }
992 };
993 return WPStagingCommon;
994 })(jQuery);
995
996 /**
997 * WP STAGING basic jQuery replacement
998 */
999
1000 /**
1001 * Shortcut for document.querySelector() or jQuery's $()
1002 * Return single element only
1003 */
1004 function qs(selector) {
1005 return document.querySelector(selector);
1006 }
1007
1008 /**
1009 * Shortcut for document.querySelector() or jQuery's $()
1010 * Return collection of elements
1011 */
1012 function all(selector) {
1013 return document.querySelectorAll(selector);
1014 }
1015
1016 /**
1017 * alternative of jQuery - $(parent).on(event, selector, handler)
1018 */
1019 function addEvent(parent, evt, selector, handler) {
1020 if (!parent instanceof Element) {
1021 return;
1022 }
1023 parent.addEventListener(evt, function (event) {
1024 if (event.target.matches(selector + ', ' + selector + ' *')) {
1025 handler(event.target.closest(selector), event);
1026 }
1027 }, false);
1028 }
1029 function slideDown(element, duration) {
1030 if (duration === void 0) {
1031 duration = 400;
1032 }
1033 element.style.display = 'block';
1034 element.style.overflow = 'hidden';
1035 var height = element.offsetHeight;
1036 element.style.height = '0px';
1037 element.style.transitionProperty = 'height';
1038 element.style.transitionDuration = duration + 'ms';
1039 setTimeout(function () {
1040 element.style.height = height + 'px';
1041 window.setTimeout(function () {
1042 element.style.removeProperty('height');
1043 element.style.removeProperty('overflow');
1044 element.style.removeProperty('transition-duration');
1045 element.style.removeProperty('transition-property');
1046 }, duration);
1047 }, 0);
1048 }
1049 function slideUp(element, duration) {
1050 if (duration === void 0) {
1051 duration = 400;
1052 }
1053 element.style.display = 'block';
1054 element.style.overflow = 'hidden';
1055 var height = element.offsetHeight;
1056 element.style.height = height + 'px';
1057 element.style.transitionProperty = 'height';
1058 element.style.transitionDuration = duration + 'ms';
1059 setTimeout(function () {
1060 element.style.height = '0px';
1061 window.setTimeout(function () {
1062 element.style.display = 'none';
1063 element.style.removeProperty('height');
1064 element.style.removeProperty('overflow');
1065 element.style.removeProperty('transition-duration');
1066 element.style.removeProperty('transition-property');
1067 }, duration);
1068 }, 0);
1069 }
1070 function fadeOut(element, duration) {
1071 if (duration === void 0) {
1072 duration = 300;
1073 }
1074 element.style.opacity = 1;
1075 element.style.transitionProperty = 'opacity';
1076 element.style.transitionDuration = duration + 'ms';
1077 setTimeout(function () {
1078 element.style.opacity = 0;
1079 window.setTimeout(function () {
1080 element.style.display = 'none';
1081 element.style.removeProperty('opacity');
1082 element.style.removeProperty('transition-duration');
1083 element.style.removeProperty('transition-property');
1084 }, duration);
1085 }, 0);
1086 }
1087 function getNextSibling(element, selector) {
1088 var sibling = element.nextElementSibling;
1089 while (sibling) {
1090 if (sibling.matches(selector)) {
1091 return sibling;
1092 }
1093 sibling = sibling.nextElementSibling;
1094 }
1095 }
1096 function getPreviousSibling(element, selector) {
1097 var sibling = element.previousElementSibling;
1098 while (sibling) {
1099 if (sibling.matches(selector)) {
1100 return sibling;
1101 }
1102 sibling = sibling.previousElementSibling;
1103 }
1104 }
1105 function getParents(element, selector) {
1106 var result = [];
1107 for (var parent = element && element.parentElement; parent; parent = parent.parentElement) {
1108 if (parent.matches(selector)) {
1109 result.push(parent);
1110 }
1111 }
1112 return result;
1113 }
1114
1115 /**
1116 * Dispatches a change on an element that will trigger, depending on the element type,
1117 * cascading changes on elements dependant on the one that triggered the change and that
1118 * belong in the same container.
1119 *
1120 * @param {Element} element A reference to the Element the change was triggered from.
1121 *
1122 * @return {void} The function does not return any value and will have the side-effect of
1123 * hiding or showing dependant elements.
1124 */
1125 function handleDisplayDependencies(element) {
1126 if (!element instanceof Element || !element.id) {
1127 return;
1128 }
1129 var containerSelector = '.wpstg-container';
1130 // Use the default WordPress CSS class to hide and show the objects.
1131 var hiddenClass = 'hidden';
1132 var elementType = element.getAttribute('type');
1133 switch (elementType) {
1134 case 'checkbox':
1135 // Go as high as the container that contains this element.
1136 var container = closest(element, containerSelector);
1137 if (container === null) {
1138 return;
1139 }
1140 var showIfChecked = container.querySelectorAll("[data-show-if-checked=\"" + element.id + "\"]");
1141 var showIfUnchecked = container.querySelectorAll("[data-show-if-unchecked=\"" + element.id + "\"]");
1142 var checked = element.checked;
1143 if (showIfChecked.length) {
1144 for (var _iterator = _createForOfIteratorHelperLoose(showIfChecked), _step; !(_step = _iterator()).done;) {
1145 var el = _step.value;
1146 if (checked) {
1147 el.classList.remove(hiddenClass);
1148 } else {
1149 el.classList.add(hiddenClass);
1150 }
1151 }
1152 }
1153 if (showIfUnchecked.length) {
1154 for (var _iterator2 = _createForOfIteratorHelperLoose(showIfUnchecked), _step2; !(_step2 = _iterator2()).done;) {
1155 var _el = _step2.value;
1156 if (checked) {
1157 _el.classList.add(hiddenClass);
1158 } else {
1159 _el.classList.remove(hiddenClass);
1160 }
1161 }
1162 }
1163 return;
1164 default:
1165 // Not a type we handle.
1166 return;
1167 }
1168 }
1169
1170 /**
1171 * Toggle target element set in data-wpstg-target of the given element
1172 *
1173 * @param {Element} element A reference to the Element the change was triggered from.
1174 *
1175 * @return {void} The function does not return any value and will have the side-effect of
1176 * hiding or showing dependant elements.
1177 */
1178 function handleToggleElement(element) {
1179 if (!element instanceof Element || !element.getAttribute('data-wpstg-target')) {
1180 return;
1181 }
1182 var containerSelector = '.wpstg_admin';
1183 // Use the default WordPress CSS class to hide and show the objects.
1184 var hiddenClass = 'hidden';
1185
1186 // Go as high as the container that contains this element.
1187 var container = closest(element, containerSelector);
1188 if (container === null) {
1189 return;
1190 }
1191 var elements = container.querySelectorAll(element.getAttribute('data-wpstg-target'));
1192 if (elements.length) {
1193 for (var _iterator4 = _createForOfIteratorHelperLoose(elements), _step4; !(_step4 = _iterator4()).done;) {
1194 var el = _step4.value;
1195 el.classList.toggle(hiddenClass);
1196 }
1197 }
1198 }
1199
1200 /**
1201 * Copy text in data-wpstg-copy to element(s) in data-wpstg-target
1202 *
1203 * @param {Element} element
1204 *
1205 * @return {void}
1206 */
1207 function handleCopyPaste(element) {
1208 if (!element instanceof Element || !element.getAttribute('data-wpstg-target') || !element.getAttribute('data-wpstg-copy')) {
1209 return;
1210 }
1211 var containerSelector = '.wpstg_admin';
1212
1213 // Go as high as the container that contains this element.
1214 var container = closest(element, containerSelector);
1215 if (container === null) {
1216 return;
1217 }
1218 navigator.clipboard.writeText(element.getAttribute('data-wpstg-copy'));
1219 var elements = container.querySelectorAll(element.getAttribute('data-wpstg-target'));
1220 if (elements.length) {
1221 for (var _iterator5 = _createForOfIteratorHelperLoose(elements), _step5; !(_step5 = _iterator5()).done;) {
1222 var el = _step5.value;
1223 el.value = element.getAttribute('data-wpstg-copy', '');
1224 }
1225 }
1226 }
1227
1228 /**
1229 * Copy text in data-wpstg-source to clipboard
1230 *
1231 * @param {Element} element
1232 *
1233 * @return {void}
1234 */
1235 function handleCopyToClipboard(element) {
1236 if (!element instanceof Element || !element.getAttribute('data-wpstg-source')) {
1237 return;
1238 }
1239 var containerSelector = '.wpstg_admin';
1240
1241 // Go as high as the container that contains this element.
1242 var container = closest(element, containerSelector);
1243 if (container === null) {
1244 return;
1245 }
1246 var el = container.querySelector(element.getAttribute('data-wpstg-source'));
1247 if (el) {
1248 navigator.clipboard.writeText(el.value);
1249 }
1250 }
1251
1252 /**
1253 * Hides elements in the DOM that match the given selector by setting their display style to 'none'.
1254 *
1255 * @param {string} selector - CSS selector for the elements to be hidden.
1256 * @return {void}
1257 */
1258 function hide(selector) {
1259 var elements = document.querySelectorAll(selector);
1260 elements.forEach(function (element) {
1261 element.style.display = 'none';
1262 });
1263 }
1264
1265 /**
1266 * Displays elements in the DOM that match the given selector by setting their display style to 'block'.
1267 *
1268 * @param {string} selector - CSS selector for the elements to be displayed.
1269 * @return {void}
1270 */
1271 function show(selector) {
1272 var elements = document.querySelectorAll(selector);
1273 elements.forEach(function (element) {
1274 element.style.display = 'block';
1275 });
1276 }
1277
1278 /**
1279 * @param visibility
1280 * @return {void}
1281 */
1282 function loadingBar(visibility) {
1283 if (visibility === void 0) {
1284 visibility = 'visible';
1285 }
1286 var loader = document.querySelectorAll('.wpstg-loading-bar-container');
1287 loader.forEach(function (element) {
1288 if (element) {
1289 element.style.visibility = visibility;
1290 }
1291 });
1292 }
1293
1294 /**
1295 * Enable side bar menu and set url on tab click
1296 */
1297 var WpstgSidebarMenu = /*#__PURE__*/function () {
1298 function WpstgSidebarMenu() {
1299 this.init();
1300 }
1301 var _proto = WpstgSidebarMenu.prototype;
1302 _proto.init = function init() {
1303 this.wpstdStagingTab = document.querySelector('#wpstg--tab--toggle--staging');
1304 this.wpstdBackupTab = document.querySelector('#wpstg--tab--toggle--backup');
1305 this.wpstdSidebarMenu = document.querySelector('#toplevel_page_wpstg_clone');
1306 this.addEvents();
1307 };
1308 _proto.addEvents = function addEvents() {
1309 var _this = this;
1310 if (this.wpstdStagingTab !== null) {
1311 this.wpstdStagingTab.addEventListener('click', function () {
1312 _this.setPageUrl('wpstg_clone');
1313 _this.setSidebarMenu('wpstg_clone');
1314 });
1315 }
1316 if (this.wpstdBackupTab !== null) {
1317 this.wpstdBackupTab.addEventListener('click', function () {
1318 _this.setPageUrl('wpstg_backup');
1319 _this.setSidebarMenu('wpstg_backup');
1320 });
1321 }
1322 };
1323 _proto.setPageUrl = function setPageUrl(page) {
1324 window.history.pushState(null, null, window.location.pathname + '?page=' + page);
1325 };
1326 _proto.setSidebarMenu = function setSidebarMenu(page) {
1327 var wpstgSidebarMenuElements = this.wpstdSidebarMenu.querySelector('ul').querySelectorAll('li');
1328 if (wpstgSidebarMenuElements.length > 0) {
1329 for (var i = 0; i < wpstgSidebarMenuElements.length; i++) {
1330 wpstgSidebarMenuElements[i].classList.remove('current');
1331 if (wpstgSidebarMenuElements[i].querySelector('a') !== null) {
1332 if (wpstgSidebarMenuElements[i].querySelector('a').getAttribute('href') === 'admin.php?page=' + page) {
1333 wpstgSidebarMenuElements[i].classList.add('current');
1334 }
1335 }
1336 }
1337 }
1338 };
1339 return WpstgSidebarMenu;
1340 }();
1341
1342 /**
1343 * Handle toggle of contact us modal
1344 */
1345 var WpstgContactUs = /*#__PURE__*/function () {
1346 function WpstgContactUs(modalType, wpstgObject) {
1347 if (modalType === void 0) {
1348 modalType = 'contact-us';
1349 }
1350 if (wpstgObject === void 0) {
1351 wpstgObject = wpstg;
1352 }
1353 this.wpstgObject = wpstgObject;
1354 this.characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
1355 this.currentDate = new Date();
1356 this.modalType = modalType;
1357 this.init();
1358 }
1359 var _proto = WpstgContactUs.prototype;
1360 _proto.init = function init() {
1361 this.contactUsModal = '#wpstg-' + this.modalType + '-modal';
1362 this.askInTheForumForm = this.contactUsModal + ' #wpstg-' + this.modalType + '-report-issue-form';
1363 this.contactUsSuccessPopup = this.contactUsModal + ' #wpstg-' + this.modalType + '-success-form';
1364 this.contactUsLoader = this.contactUsModal + ' #wpstg-' + this.modalType + '-report-issue-loader';
1365 this.contactUsSupport = this.contactUsModal + ' #wpstg-' + this.modalType + '-support-forum';
1366 this.contactUsButton = document.querySelector('#wpstg-' + this.modalType + '-button');
1367 this.contactUsButtonBackupTab = document.querySelector('#wpstg--tab--backup #wpstg-' + this.modalType + '-button');
1368 this.reportIssueButton = document.querySelector('#wpstg-contact-us-report-issue');
1369 this.successForm = document.querySelector(this.contactUsModal + ' #wpstg-' + this.modalType + '-success-form');
1370 this.contactUsReportIssueBtn = document.querySelector(this.contactUsModal + ' #wpstg-' + this.modalType + '-report-issue-btn');
1371 this.contactUsCloseButton = document.querySelector(this.contactUsModal + ' #wpstg-modal-close');
1372 this.contactUsSuccessPopupClose = document.querySelector(this.contactUsModal + ' #wpstg-' + this.modalType + '-success-modal-close');
1373 this.debugCodeCopyButton = document.querySelector(this.contactUsModal + ' #wpstg-' + this.modalType + '-debug-code-copy');
1374 this.contactUsResponse = document.querySelector(this.contactUsModal + ' #wpstg-' + this.modalType + '-debug-response');
1375 this.contactUsDebugCodeField = document.querySelector(this.contactUsModal + ' #wpstg-' + this.modalType + '-debug-code');
1376 this.isDebugWindowOpened = false;
1377 this.addEvents();
1378 this.notyf = new Notyf({
1379 duration: 6000,
1380 position: {
1381 x: 'center',
1382 y: 'bottom'
1383 },
1384 dismissible: true,
1385 types: [{
1386 type: 'warning',
1387 background: 'orange',
1388 icon: true
1389 }]
1390 });
1391 };
1392 _proto.addEvents = function addEvents() {
1393 var _this = this;
1394 document.addEventListener('keydown', function (event) {
1395 if (event.key === 'Escape') {
1396 hide(_this.contactUsModal);
1397 hide(_this.askInTheForumForm);
1398 hide(_this.contactUsSuccessPopup);
1399 hide(_this.contactUsSupport);
1400 _this.isDebugWindowOpened = false;
1401 }
1402 });
1403 if (this.contactUsButton !== null) {
1404 this.contactUsButton.addEventListener('click', function () {
1405 show(_this.contactUsModal);
1406 });
1407 }
1408 if (this.contactUsButtonBackupTab !== null) {
1409 this.contactUsButtonBackupTab.addEventListener('click', function () {
1410 show(_this.contactUsModal);
1411 });
1412 }
1413 if (this.reportIssueButton !== null) {
1414 this.reportIssueButton.addEventListener('click', function () {
1415 if (_this.isDebugWindowOpened) {
1416 hide(_this.askInTheForumForm);
1417 } else {
1418 show(_this.askInTheForumForm);
1419 }
1420 _this.isDebugWindowOpened = !_this.isDebugWindowOpened;
1421 });
1422 }
1423 if (this.contactUsReportIssueBtn !== null) {
1424 this.contactUsReportIssueBtn.addEventListener('click', function () {
1425 _this.sendDebugInfo();
1426 });
1427 }
1428 if (this.contactUsSuccessPopupClose !== null) {
1429 this.contactUsSuccessPopupClose.addEventListener('click', function () {
1430 hide(_this.contactUsSuccessPopup);
1431 });
1432 }
1433 if (this.contactUsCloseButton !== null) {
1434 this.contactUsCloseButton.addEventListener('click', function () {
1435 hide(_this.contactUsModal);
1436 hide(_this.contactUsSupport);
1437 hide(_this.askInTheForumForm);
1438 _this.isDebugWindowOpened = false;
1439 });
1440 }
1441 if (this.debugCodeCopyButton !== null) {
1442 this.debugCodeCopyButton.addEventListener('click', function () {
1443 _this.copyDebugCode();
1444 _this.notyf.success('Debug code copied to clipboard');
1445 });
1446 }
1447 };
1448 _proto.copyDebugCode = function copyDebugCode() {
1449 this.contactUsDebugCodeField.select();
1450 this.contactUsDebugCodeField.setSelectionRange(0, 99999);
1451 navigator.clipboard.writeText(this.contactUsDebugCodeField.value);
1452 };
1453 _proto.generateDebugCode = function generateDebugCode(length) {
1454 var result = '';
1455 for (var i = 0; i < length; i++) {
1456 result += this.characters.charAt(Math.floor(Math.random() * this.characters.length));
1457 }
1458 return 'wpstg-' + result + '-' + this.currentDate.getHours() + this.currentDate.getMinutes() + this.currentDate.getSeconds();
1459 };
1460 _proto.sendDebugInfo = function sendDebugInfo() {
1461 var _this2 = this;
1462 show(this.contactUsLoader);
1463 this.contactUsReportIssueBtn.disabled = true;
1464 var debugCode = this.generateDebugCode(8);
1465 fetch(this.wpstgObject.ajaxUrl, {
1466 method: 'POST',
1467 credentials: 'same-origin',
1468 body: new URLSearchParams({
1469 action: 'wpstg_send_debug_log_report',
1470 accessToken: this.wpstgObject.accessToken,
1471 nonce: this.wpstgObject.nonce,
1472 debugCode: debugCode
1473 }),
1474 headers: {
1475 'Content-Type': 'application/x-www-form-urlencoded'
1476 }
1477 }).then(function (response) {
1478 _this2.contactUsReportIssueBtn.disabled = false;
1479 if (response.ok) {
1480 return response.json();
1481 }
1482 }).then(function (data) {
1483 if (data.response && data.response.sent === true) {
1484 _this2.contactUsDebugCodeField.value = debugCode;
1485 show(_this2.contactUsSuccessPopup);
1486 window.debugCode = debugCode;
1487 } else {
1488 _this2.contactUsDebugCodeField.value = window.debugCode === undefined ? debugCode : window.debugCode;
1489 show(_this2.contactUsSuccessPopup);
1490 }
1491 hide(_this2.contactUsLoader);
1492 })["catch"](function (error) {
1493 hide(_this2.contactUsLoader);
1494 show(_this2.contactUsSupport);
1495 console.warn(_this2.wpstgObject.i18n['somethingWentWrong'], error);
1496 });
1497 };
1498 return WpstgContactUs;
1499 }();
1500
1501 /**
1502 * Enable/Disable cloning for staging site
1503 */
1504 var WpstgCloneStaging = /*#__PURE__*/function () {
1505 function WpstgCloneStaging(pageWrapperId, wpstgObject) {
1506 if (pageWrapperId === void 0) {
1507 pageWrapperId = '#wpstg-clonepage-wrapper';
1508 }
1509 if (wpstgObject === void 0) {
1510 wpstgObject = wpstg;
1511 }
1512 this.pageWrapper = qs(pageWrapperId);
1513 this.wpstgObject = wpstgObject;
1514 this.enableButtonId = '#wpstg-enable-staging-cloning';
1515 this.enableAction = 'wpstg_enable_staging_cloning';
1516 this.notyf = new Notyf({
1517 duration: 10000,
1518 position: {
1519 x: 'center',
1520 y: 'bottom'
1521 },
1522 dismissible: true,
1523 types: [{
1524 type: 'warning',
1525 background: 'orange',
1526 icon: false
1527 }]
1528 });
1529 this.init();
1530 }
1531 var _proto = WpstgCloneStaging.prototype;
1532 _proto.addEvents = function addEvents() {
1533 var _this = this;
1534 if (this.pageWrapper === null) {
1535 return;
1536 }
1537 addEvent(this.pageWrapper, 'click', this.enableButtonId, function () {
1538 _this.sendRequest(_this.enableAction);
1539 });
1540 new WpstgSidebarMenu();
1541 };
1542 _proto.init = function init() {
1543 this.addEvents();
1544 };
1545 _proto.sendRequest = function sendRequest(action) {
1546 var _this2 = this;
1547 fetch(this.wpstgObject.ajaxUrl, {
1548 method: 'POST',
1549 credentials: 'same-origin',
1550 body: new URLSearchParams({
1551 action: action,
1552 accessToken: this.wpstgObject.accessToken,
1553 nonce: this.wpstgObject.nonce
1554 }),
1555 headers: {
1556 'Content-Type': 'application/x-www-form-urlencoded'
1557 }
1558 }).then(function (response) {
1559 if (response.ok) {
1560 return response.json();
1561 }
1562 return Promise.reject(response);
1563 }).then(function (data) {
1564 // Reload current page if successful.
1565 if ('undefined' !== typeof data.success && data.success) {
1566 location.reload();
1567 return;
1568 }
1569
1570 // There will be message probably in case of error
1571 if ('undefined' !== typeof data.message) {
1572 _this2.notyf.error(data.message);
1573 return;
1574 }
1575 _this2.notyf.error(_this2.wpstgObject.i18n['somethingWentWrong']);
1576 })["catch"](function (error) {
1577 console.warn(_this2.wpstgObject.i18n['somethingWentWrong'], error);
1578 });
1579 };
1580 return WpstgCloneStaging;
1581 }();
1582
1583 /**
1584 * Fetch directory direct child directories
1585 */
1586 var WpstgDirectoryNavigation = /*#__PURE__*/function () {
1587 function WpstgDirectoryNavigation(directoryListingSelector, wpstgObject, notyf) {
1588 if (directoryListingSelector === void 0) {
1589 directoryListingSelector = '#wpstg-directories-listing';
1590 }
1591 if (wpstgObject === void 0) {
1592 wpstgObject = WPStagingCommon;
1593 }
1594 if (notyf === void 0) {
1595 notyf = null;
1596 }
1597 this.directoryListingContainer = qs(directoryListingSelector);
1598 this.wpstgObject = wpstgObject;
1599 this.dirCheckboxSelector = '.wpstg-check-dir';
1600 this.dirExpandSelector = '.wpstg-expand-dirs';
1601 this.unselectAllDirsSelector = '.wpstg-unselect-dirs';
1602 this.selectDefaultDirsSelector = '.wpstg-select-dirs-default';
1603 this.fetchChildrenAction = 'wpstg_fetch_dir_children';
1604 this.currentCheckboxElement = null;
1605 this.currentParentDiv = null;
1606 this.currentLoader = null;
1607 this.existingExcludes = [];
1608 this.excludedDirectories = [];
1609 this.isDefaultSelected = false;
1610 this.notyf = notyf;
1611 this.init();
1612 }
1613 var _proto = WpstgDirectoryNavigation.prototype;
1614 _proto.addEvents = function addEvents() {
1615 var _this = this;
1616 if (this.directoryListingContainer === null) {
1617 console.log('Error: Unable to add directory navigation events.');
1618 return;
1619 }
1620 addEvent(this.directoryListingContainer, 'change', this.dirCheckboxSelector, function (element, event) {
1621 event.preventDefault();
1622 });
1623 addEvent(this.directoryListingContainer, 'click', this.dirExpandSelector, function (element, event) {
1624 event.preventDefault();
1625 if (_this.toggleDirExpand(element)) {
1626 _this.sendRequest(_this.fetchChildrenAction, element);
1627 }
1628 });
1629 addEvent(this.directoryListingContainer, 'click', this.unselectAllDirsSelector, function () {
1630 _this.unselectAll();
1631 });
1632 addEvent(this.directoryListingContainer, 'click', this.selectDefaultDirsSelector, function () {
1633 _this.selectDefault();
1634 });
1635 addEvent(this.directoryListingContainer, 'click', '.wpstg-expand-dirs', function (target, event) {
1636 event.preventDefault();
1637 _this.toggleDirectoryNavigation(target);
1638 });
1639 addEvent(this.directoryListingContainer, 'change', 'input.wpstg-check-dir', function (target) {
1640 _this.updateDirectorySelection(target);
1641 });
1642 };
1643 _proto.init = function init() {
1644 this.addEvents();
1645 this.parseExcludes();
1646 }
1647
1648 /**
1649 * Toggle Dir Expand,
1650 * Return true if children aren't fetched
1651 * @param {HTMLElement} element
1652 * @return {boolean}
1653 */;
1654 _proto.toggleDirExpand = function toggleDirExpand(element) {
1655 this.currentParentDiv = element.parentElement;
1656 this.currentCheckboxElement = getPreviousSibling(element, 'input');
1657 this.currentLoader = this.currentParentDiv.querySelector('.wpstg-is-dir-loading');
1658 if (this.currentCheckboxElement.getAttribute('wpstg-data-navigateable', 'false') === 'false') {
1659 return false;
1660 }
1661 if (this.currentCheckboxElement.getAttribute('wpstg-data-scanned', 'false') === 'false') {
1662 return true;
1663 }
1664 return false;
1665 };
1666 _proto.sendRequest = function sendRequest(action) {
1667 var _this2 = this;
1668 if (this.currentLoader !== null) {
1669 this.currentLoader.style.display = 'inline-block';
1670 }
1671 var changed = this.currentCheckboxElement.getAttribute('wpstg-data-changed');
1672 var path = this.currentCheckboxElement.getAttribute('wpstg-data-path');
1673 var prefix = this.currentCheckboxElement.getAttribute('wpstg-data-prefix');
1674 fetch(this.wpstgObject.ajaxUrl, {
1675 method: 'POST',
1676 credentials: 'same-origin',
1677 body: new URLSearchParams({
1678 action: action,
1679 accessToken: this.wpstgObject.accessToken,
1680 nonce: this.wpstgObject.nonce,
1681 dirPath: path,
1682 prefix: prefix,
1683 isChecked: this.currentCheckboxElement.checked,
1684 forceDefault: changed === 'true'
1685 }),
1686 headers: {
1687 'Content-Type': 'application/x-www-form-urlencoded'
1688 }
1689 }).then(function (response) {
1690 if (response.ok) {
1691 return response.json();
1692 }
1693 return Promise.reject(response);
1694 }).then(function (data) {
1695 if ('undefined' !== typeof data.success && data.success) {
1696 _this2.currentCheckboxElement.setAttribute('wpstg-data-scanned', true);
1697 var dirContainer = document.createElement('div');
1698 dirContainer.classList.add('wpstg-dir');
1699 dirContainer.classList.add('wpstg-subdir');
1700 dirContainer.innerHTML = JSON.parse(data.directoryListing);
1701 _this2.currentParentDiv.appendChild(dirContainer);
1702 if (_this2.currentLoader !== null) {
1703 _this2.currentLoader.style.display = 'none';
1704 }
1705 slideDown(dirContainer);
1706 return;
1707 }
1708 if (_this2.notyf !== null) {
1709 _this2.notyf.error(_this2.wpstgObject.i18n['somethingWentWrong']);
1710 } else {
1711 alert('Error: ' + _this2.wpstgObject.i18n['somethingWentWrong']);
1712 }
1713 })["catch"](function (error) {
1714 console.warn(_this2.wpstgObject.i18n['somethingWentWrong'], error);
1715 });
1716 };
1717 _proto.getExcludedDirectories = function getExcludedDirectories() {
1718 var _this3 = this,
1719 _this$wpstgObject$set;
1720 this.excludedDirectories = [];
1721 this.directoryListingContainer.querySelectorAll('.wpstg-dir input:not(:checked)').forEach(function (element) {
1722 if (!_this3.isParentExcluded(element.value)) {
1723 _this3.excludedDirectories.push(element.value);
1724 }
1725 });
1726 if (!this.existingExcludes) {
1727 this.existingExcludes = [];
1728 }
1729 this.existingExcludes.forEach(function (exclude) {
1730 if (!_this3.isParentExcluded(exclude) && !_this3.isScanned(exclude)) {
1731 _this3.excludedDirectories.push(exclude);
1732 }
1733 });
1734 return this.excludedDirectories.join((_this$wpstgObject$set = this.wpstgObject.settings) == null ? void 0 : _this$wpstgObject$set.directorySeparator);
1735 }
1736
1737 /**
1738 * @param {string} path
1739 * @return {bool}
1740 */;
1741 _proto.isParentExcluded = function isParentExcluded(path) {
1742 var isParentAlreadyExcluded = false;
1743 this.excludedDirectories.forEach(function (dir) {
1744 if (path.startsWith(dir + '/')) {
1745 isParentAlreadyExcluded = true;
1746 }
1747 });
1748 return isParentAlreadyExcluded;
1749 };
1750 _proto.getExtraDirectoriesRootOnly = function getExtraDirectoriesRootOnly() {
1751 this.getExcludedDirectories();
1752 var extraDirectories = [];
1753 this.directoryListingContainer.querySelectorAll(':not(.wpstg-subdir)>.wpstg-dir>input.wpstg-wp-non-core-dir:checked').forEach(function (element) {
1754 extraDirectories.push(element.value);
1755 });
1756
1757 // Check if extra directories text area exists
1758 // TODO: remove extraCustomDirectories code if no one require extraCustomDirectories...
1759 var extraDirectoriesTextArea = qs('#wpstg_extraDirectories');
1760 if (extraDirectoriesTextArea === null || extraDirectoriesTextArea.value === '') {
1761 var _this$wpstgObject$set2;
1762 return extraDirectories.join((_this$wpstgObject$set2 = this.wpstgObject.settings) == null ? void 0 : _this$wpstgObject$set2.directorySeparator);
1763 }
1764 var extraCustomDirectories = extraDirectoriesTextArea.value.split(/\r?\n/);
1765 return extraDirectories.concat(extraCustomDirectories).join(this.wpstgObject.settings.directorySeparator);
1766 };
1767 _proto.unselectAll = function unselectAll() {
1768 this.directoryListingContainer.querySelectorAll('.wpstg-dir input').forEach(function (element) {
1769 element.checked = false;
1770 });
1771 this.countSelectedFiles();
1772 };
1773 _proto.selectDefault = function selectDefault() {
1774 // unselect all checkboxes
1775 this.unselectAll();
1776
1777 // only select those checkboxes whose class is wpstg-wp-core-dir
1778 this.directoryListingContainer.querySelectorAll('.wpstg-dir input.wpstg-wp-core-dir').forEach(function (element) {
1779 element.checked = true;
1780 });
1781
1782 // then unselect those checkboxes whose parent has wpstg extra checkbox
1783 this.directoryListingContainer.querySelectorAll('.wpstg-dir > .wpstg-wp-non-core-dir').forEach(function (element) {
1784 element.parentElement.querySelectorAll('input.wpstg-wp-core-dir').forEach(function (element) {
1785 element.checked = false;
1786 });
1787 });
1788 this.isDefaultSelected = true;
1789 this.countSelectedFiles();
1790 };
1791 _proto.parseExcludes = function parseExcludes() {
1792 this.existingExcludes = this.directoryListingContainer.getAttribute('wpstg-data-existing-excludes', []);
1793 if (typeof this.existingExcludes === 'undefined' || !this.existingExcludes) {
1794 this.existingExcludes = [];
1795 return;
1796 }
1797 if (this.existingExcludes.length === 0) {
1798 this.existingExcludes = [];
1799 return;
1800 }
1801 var existingExcludes = this.existingExcludes.split(',');
1802 this.existingExcludes = existingExcludes.map(function (exclude) {
1803 if (exclude.substr(0, 1) === '/') {
1804 return exclude.slice(1);
1805 }
1806 return exclude;
1807 });
1808 };
1809 _proto.isScanned = function isScanned(exclude) {
1810 var scanned = false;
1811 this.directoryListingContainer.querySelectorAll('.wpstg-dir>input').forEach(function (element) {
1812 if (element.value === exclude) {
1813 scanned = true;
1814 }
1815 });
1816 return scanned;
1817 };
1818 _proto.toggleDirectoryNavigation = function toggleDirectoryNavigation(element) {
1819 var cbElement = getPreviousSibling(element, 'input');
1820 if (cbElement.getAttribute('wpstg-data-navigateable', 'false') === 'false') {
1821 return;
1822 }
1823 if (cbElement.getAttribute('wpstg-data-scanned', 'false') === 'false') {
1824 return;
1825 }
1826 var subDirectories = getNextSibling(element, '.wpstg-subdir');
1827 if (subDirectories.style.display === 'none') {
1828 slideDown(subDirectories);
1829 } else {
1830 slideUp(subDirectories);
1831 }
1832 };
1833 _proto.updateDirectorySelection = function updateDirectorySelection(element) {
1834 var parent = element.parentElement;
1835 element.setAttribute('wpstg-data-changed', 'true');
1836 if (element.checked) {
1837 getParents(parent, '.wpstg-dir').forEach(function (parElem) {
1838 for (var i = 0; i < parElem.children.length; i++) {
1839 if (parElem.children[i].matches('.wpstg-check-dir')) {
1840 parElem.children[i].checked = true;
1841 }
1842 }
1843 });
1844 parent.querySelectorAll('.wpstg-expand-dirs').forEach(function (x) {
1845 if (x.textContent === 'wp-admin' || x.textContent === 'wp-includes') {
1846 return;
1847 }
1848 x.classList.remove('disabled');
1849 });
1850 parent.querySelectorAll('.wpstg-subdir .wpstg-check-dir').forEach(function (x) {
1851 x.checked = true;
1852 });
1853 } else {
1854 parent.querySelectorAll('.wpstg-expand-dirs, .wpstg-check-subdirs').forEach(function (x) {
1855 x.classList.add('disabled');
1856 });
1857 parent.querySelectorAll('.wpstg-dir .wpstg-check-dir').forEach(function (x) {
1858 x.checked = false;
1859 });
1860 }
1861 this.countSelectedFiles();
1862 };
1863 _proto.countSelectedFiles = function countSelectedFiles() {
1864 var themesCount = this.directoryListingContainer.querySelectorAll('[wpstg-data-dir-type="theme"]:checked').length;
1865 var pluginsCount = this.directoryListingContainer.querySelectorAll('[wpstg-data-dir-type="plugin"]:checked').length;
1866 var filesCountElement = qs('#wpstg-files-count');
1867 if (themesCount === 0 && pluginsCount === 0) {
1868 filesCountElement.classList.add('danger');
1869 filesCountElement.innerHTML = this.wpstgObject.i18n['noFileSelected'];
1870 } else {
1871 filesCountElement.classList.remove('danger');
1872 filesCountElement.innerHTML = this.wpstgObject.i18n['filesSelected'].replace('{t}', themesCount).replace('{p}', pluginsCount);
1873 }
1874 };
1875 return WpstgDirectoryNavigation;
1876 }();
1877
1878 /**
1879 * Database tables selection
1880 */
1881 var WpstgTableSelection = /*#__PURE__*/function () {
1882 function WpstgTableSelection(databaseTableSectionSelector, workflowSelector, networkCloneSelector, inputSelector, wpstgObject) {
1883 if (databaseTableSectionSelector === void 0) {
1884 databaseTableSectionSelector = '#wpstg-scanning-db';
1885 }
1886 if (workflowSelector === void 0) {
1887 workflowSelector = '#wpstg-workflow';
1888 }
1889 if (networkCloneSelector === void 0) {
1890 networkCloneSelector = '#wpstg_network_clone';
1891 }
1892 if (inputSelector === void 0) {
1893 inputSelector = '#wpstg_select_tables_cloning';
1894 }
1895 if (wpstgObject === void 0) {
1896 wpstgObject = wpstg;
1897 }
1898 this.databaseTableSection = qs(databaseTableSectionSelector);
1899 this.workflow = qs(workflowSelector);
1900 this.networkCloneSelector = networkCloneSelector;
1901 this.networkCloneCheckbox = qs(networkCloneSelector);
1902 this.wpstgObject = wpstgObject;
1903 this.isAllTablesChecked = true;
1904 this.isMultisite = this.wpstgObject.isMultisite === '1';
1905 this.isNetworkClone = false;
1906 this.inputSelector = inputSelector;
1907 this.input = qs(this.inputSelector);
1908 this.init();
1909 }
1910 var _proto = WpstgTableSelection.prototype;
1911 _proto.setNetworkClone = function setNetworkClone(isNetworkClone) {
1912 this.isNetworkClone = isNetworkClone;
1913 };
1914 _proto.addEvents = function addEvents() {
1915 var _this = this;
1916 if (this.workflow === null) {
1917 console.log('Error: database table section is null. Cannot register events');
1918 return;
1919 }
1920 addEvent(this.workflow, 'change', this.networkCloneSelector, function () {
1921 _this.selectDefaultTables();
1922 });
1923 addEvent(this.workflow, 'change', this.inputSelector, function () {
1924 _this.countSelectedTables();
1925 });
1926 addEvent(this.workflow, 'click', '.wpstg-button-select', function (target, event) {
1927 event.preventDefault();
1928 _this.selectDefaultTables();
1929 });
1930 addEvent(this.workflow, 'click', '.wpstg-button-unselect', function (target, event) {
1931 event.preventDefault();
1932 _this.toggleTableSelection();
1933 });
1934 addEvent(this.workflow, 'click', '.wpstg-button-unselect-wpstg', function (target, event) {
1935 event.preventDefault();
1936 _this.unselectWPSTGTables();
1937 });
1938 };
1939 _proto.init = function init() {
1940 this.addEvents();
1941 };
1942 _proto.getRegexPattern = function getRegexPattern() {
1943 var pattern = '^' + this.wpstgObject.tblprefix;
1944 var isNetwork = false;
1945 if (this.networkCloneCheckbox !== undefined && this.networkCloneCheckbox !== null) {
1946 isNetwork = this.networkCloneCheckbox.checked;
1947 }
1948
1949 // Force network clone true if set explicitly
1950 if (this.isNetworkClone) {
1951 isNetwork = true;
1952 }
1953 if (this.isMultisite && !isNetwork) {
1954 pattern += '([^0-9])_*';
1955 }
1956 return pattern;
1957 };
1958 _proto.selectDefaultTables = function selectDefaultTables() {
1959 var options = this.databaseTableSection.querySelectorAll('#wpstg_select_tables_cloning .wpstg-db-table');
1960 var regexPattern = this.getRegexPattern();
1961 options.forEach(function (option) {
1962 var name = option.getAttribute('name', '');
1963 if (name.match(regexPattern)) {
1964 option.selected = true;
1965 } else {
1966 option.selected = false;
1967 }
1968 });
1969 this.countSelectedTables();
1970 };
1971 _proto.toggleTableSelection = function toggleTableSelection() {
1972 if (false === this.isAllTablesChecked) {
1973 this.databaseTableSection.querySelectorAll('#wpstg_select_tables_cloning .wpstg-db-table').forEach(function (option) {
1974 option.selected = true;
1975 });
1976 this.databaseTableSection.querySelector('.wpstg-button-unselect').innerHTML = 'Unselect All';
1977 // cache.get('.wpstg-db-table-checkboxes').prop('checked', true);
1978 this.isAllTablesChecked = true;
1979 } else {
1980 this.databaseTableSection.querySelectorAll('#wpstg_select_tables_cloning .wpstg-db-table').forEach(function (option) {
1981 option.selected = false;
1982 });
1983 this.databaseTableSection.querySelector('.wpstg-button-unselect').innerHTML = 'Select All';
1984 // cache.get('.wpstg-db-table-checkboxes').prop('checked', false);
1985 this.isAllTablesChecked = false;
1986 }
1987 this.countSelectedTables();
1988 };
1989 _proto.unselectWPSTGTables = function unselectWPSTGTables() {
1990 var _this2 = this;
1991 var options = this.databaseTableSection.querySelectorAll('#wpstg_select_tables_cloning .wpstg-db-table');
1992 var regexPattern = 'wpstg';
1993 options.forEach(function (option) {
1994 var name = option.getAttribute('name', '');
1995 if (name.match(regexPattern) && !name.match(_this2.wpstgObject.tblprefix + 'wpstg_queue')) {
1996 option.selected = false;
1997 }
1998 });
1999 this.countSelectedTables();
2000 };
2001 _proto.getSelectedTablesWithoutPrefix = function getSelectedTablesWithoutPrefix() {
2002 var selectedTablesWithoutPrefix = [];
2003 var options = this.databaseTableSection.querySelectorAll('#wpstg_select_tables_cloning option:checked');
2004 var regexPattern = this.getRegexPattern();
2005 options.forEach(function (option) {
2006 var name = option.getAttribute('name', '');
2007 if (!name.match(regexPattern)) {
2008 selectedTablesWithoutPrefix.push(option.value);
2009 }
2010 });
2011 return selectedTablesWithoutPrefix.join(this.wpstgObject.settings.directorySeparator);
2012 };
2013 _proto.getIncludedTables = function getIncludedTables() {
2014 var includedTables = [];
2015 var options = this.databaseTableSection.querySelectorAll('#wpstg_select_tables_cloning option:checked');
2016 var regexPattern = this.getRegexPattern();
2017 options.forEach(function (option) {
2018 var name = option.getAttribute('name', '');
2019 if (name.match(regexPattern)) {
2020 includedTables.push(option.value);
2021 }
2022 });
2023 return includedTables.join(this.wpstgObject.settings.directorySeparator);
2024 };
2025 _proto.getExcludedTables = function getExcludedTables() {
2026 var excludedTables = [];
2027 var options = this.databaseTableSection.querySelectorAll('#wpstg_select_tables_cloning option:not(:checked)');
2028 var regexPattern = this.getRegexPattern();
2029 options.forEach(function (option) {
2030 var name = option.getAttribute('name', '');
2031 if (name.match(regexPattern)) {
2032 excludedTables.push(option.value);
2033 }
2034 });
2035 return excludedTables.join(this.wpstgObject.settings.directorySeparator);
2036 };
2037 _proto.countSelectedTables = function countSelectedTables() {
2038 var tablesCount = this.input.querySelectorAll('option:checked').length;
2039 var tablesCountElement = qs('#wpstg-tables-count');
2040 if (tablesCount === 0) {
2041 tablesCountElement.classList.add('danger');
2042 tablesCountElement.innerHTML = this.wpstgObject.i18n['noTableSelected'];
2043 } else {
2044 tablesCountElement.classList.remove('danger');
2045 tablesCountElement.innerHTML = this.wpstgObject.i18n['tablesSelected'].replace('{d}', tablesCount);
2046 }
2047 };
2048 return WpstgTableSelection;
2049 }();
2050
2051 /**
2052 * Rich Exclude Filter Module
2053 */
2054 var WpstgExcludeFilters = /*#__PURE__*/function () {
2055 function WpstgExcludeFilters(excludeFilterContainerSelector, wpstgObject) {
2056 if (excludeFilterContainerSelector === void 0) {
2057 excludeFilterContainerSelector = '#wpstg-exclude-filters-container';
2058 }
2059 if (wpstgObject === void 0) {
2060 wpstgObject = wpstg;
2061 }
2062 this.excludeContainer = qs(excludeFilterContainerSelector);
2063 this.excludeTableBody = qs(excludeFilterContainerSelector + " tbody");
2064 this.wpstgObject = wpstgObject;
2065 this.init();
2066 }
2067 var _proto = WpstgExcludeFilters.prototype;
2068 _proto.addEvents = function addEvents() {
2069 var _this = this;
2070 addEvent(this.excludeContainer, 'click', '.wpstg-file-size-rule', function () {
2071 _this.addFileSizeExclude();
2072 });
2073 addEvent(this.excludeContainer, 'click', '.wpstg-file-ext-rule', function () {
2074 _this.addFileExtExclude();
2075 });
2076 addEvent(this.excludeContainer, 'click', '.wpstg-file-name-rule', function () {
2077 _this.addFileNameExclude();
2078 });
2079 addEvent(this.excludeContainer, 'click', '.wpstg-dir-name-rule', function () {
2080 _this.addDirNameExclude();
2081 });
2082 addEvent(this.excludeContainer, 'click', '.wpstg-clear-all-rules', function () {
2083 _this.clearExcludes();
2084 });
2085 addEvent(this.excludeContainer, 'click', '.wpstg-remove-exclude-rule', function (target) {
2086 _this.removeExclude(target);
2087 });
2088 };
2089 _proto.init = function init() {
2090 if (this.excludeContainer === null) {
2091 console.log('Error: Given table selector not found!');
2092 return;
2093 }
2094 this.addEvents();
2095 };
2096 _proto.addFileSizeExclude = function addFileSizeExclude() {
2097 this.addExcludeRuleRow('#wpstg-file-size-exclude-filter-template');
2098 };
2099 _proto.addFileExtExclude = function addFileExtExclude() {
2100 this.addExcludeRuleRow('#wpstg-file-ext-exclude-filter-template');
2101 };
2102 _proto.addFileNameExclude = function addFileNameExclude() {
2103 this.addExcludeRuleRow('#wpstg-file-name-exclude-filter-template');
2104 };
2105 _proto.addDirNameExclude = function addDirNameExclude() {
2106 this.addExcludeRuleRow('#wpstg-dir-name-exclude-filter-template');
2107 };
2108 _proto.addExcludeRuleRow = function addExcludeRuleRow(templateName) {
2109 var excludeRowTemplate = qs(templateName);
2110 if (excludeRowTemplate !== null) {
2111 var clone = excludeRowTemplate.content.cloneNode(true);
2112 var excludeRow = clone.querySelector('tr');
2113 this.excludeTableBody.appendChild(excludeRow);
2114 all('.wpstg-has-exclude-rules').forEach(function (e) {
2115 e.style.display = 'inherit';
2116 });
2117 }
2118 };
2119 _proto.clearExcludes = function clearExcludes() {
2120 this.excludeTableBody.innerHTML = '';
2121 all('.wpstg-has-exclude-rules').forEach(function (e) {
2122 e.style.display = 'none';
2123 });
2124 };
2125 _proto.removeExclude = function removeExclude(target) {
2126 if (target.parentElement !== null && target.parentElement.parentElement !== null) {
2127 this.excludeTableBody.removeChild(target.parentElement.parentElement);
2128 }
2129 if (this.excludeTableBody.innerHTML.trim() === '') {
2130 all('.wpstg-has-exclude-rules').forEach(function (e) {
2131 e.style.display = 'none';
2132 });
2133 }
2134 }
2135
2136 /**
2137 * Converts all the exclude filters arrays into one single string to keep size of post request small
2138 * @return {string}
2139 */;
2140 _proto.getExcludeFilters = function getExcludeFilters() {
2141 var _this2 = this;
2142 var globExcludes = [];
2143 var sizeExcludes = [];
2144 var sizeCompares = this.excludeTableBody.querySelectorAll('select[name="wpstgFileSizeExcludeRuleCompare[]"]');
2145 var sizeSizes = this.excludeTableBody.querySelectorAll('input[name="wpstgFileSizeExcludeRuleSize[]"]');
2146 var sizeByte = this.excludeTableBody.querySelectorAll('select[name="wpstgFileSizeExcludeRuleByte[]"]');
2147 for (var _i = 0, _Object$entries = Object.entries(sizeSizes); _i < _Object$entries.length; _i++) {
2148 var _Object$entries$_i = _Object$entries[_i],
2149 key = _Object$entries$_i[0],
2150 sizeInput = _Object$entries$_i[1];
2151 if (sizeInput.value !== '') {
2152 sizeExcludes.push(sizeCompares[key].value + ' ' + sizeInput.value + sizeByte[key].value);
2153 }
2154 }
2155 var extensionInputs = this.excludeTableBody.querySelectorAll('input[name="wpstgFileExtExcludeRule[]"]');
2156 extensionInputs.forEach(function (x) {
2157 var ext = _this2.cleanStringForGlob(x.value);
2158 if (ext !== '') {
2159 globExcludes.push('ext:' + ext.trim());
2160 }
2161 });
2162 var fileNamesPos = this.excludeTableBody.querySelectorAll('select[name="wpstgFileNameExcludeRulePos[]"]');
2163 var fileNames = this.excludeTableBody.querySelectorAll('input[name="wpstgFileNameExcludeRulePath[]"]');
2164 for (var _i2 = 0, _Object$entries2 = Object.entries(fileNames); _i2 < _Object$entries2.length; _i2++) {
2165 var _Object$entries2$_i = _Object$entries2[_i2],
2166 _key = _Object$entries2$_i[0],
2167 fileInput = _Object$entries2$_i[1];
2168 var fileName = this.cleanStringForGlob(fileInput.value);
2169 if (fileName !== '') {
2170 globExcludes.push('file:' + fileNamesPos[_key].value + ' ' + fileName.trim());
2171 }
2172 }
2173 var dirNamesPos = this.excludeTableBody.querySelectorAll('select[name="wpstgDirNameExcludeRulePos[]"]');
2174 var dirNames = this.excludeTableBody.querySelectorAll('input[name="wpstgDirNameExcludeRulePath[]"]');
2175 for (var _i3 = 0, _Object$entries3 = Object.entries(dirNames); _i3 < _Object$entries3.length; _i3++) {
2176 var _Object$entries3$_i = _Object$entries3[_i3],
2177 _key2 = _Object$entries3$_i[0],
2178 dirInput = _Object$entries3$_i[1];
2179 var dirName = this.cleanStringForGlob(dirInput.value);
2180 if (dirName !== '') {
2181 globExcludes.push('dir:' + dirNamesPos[_key2].value + ' ' + dirName.trim());
2182 }
2183 }
2184 return {
2185 'sizes': sizeExcludes.filter(this.onlyUnique).join(','),
2186 // return set of unique rules
2187 'globs': globExcludes.filter(this.onlyUnique).join(',')
2188 };
2189 };
2190 _proto.onlyUnique = function onlyUnique(value, index, self) {
2191 return self.indexOf(value) === index;
2192 }
2193
2194 /**
2195 * Remove most of the comment glob characters from the string
2196 * @param {String} value
2197 * @return {String}
2198 */;
2199 _proto.cleanStringForGlob = function cleanStringForGlob(value) {
2200 // will replace character like * ^ / \ ! ? [ from the string
2201 return value.replace(/[*^//!\[?]/g, '');
2202 };
2203 return WpstgExcludeFilters;
2204 }();
2205
2206 /**
2207 * Basic WP Staging Modal implemented with help of Sweetalerts
2208 */
2209 var WpstgModal = /*#__PURE__*/function () {
2210 function WpstgModal(confirmAction, wpstgObject) {
2211 if (wpstgObject === void 0) {
2212 wpstgObject = wpstg;
2213 }
2214 this.confirmAction = confirmAction;
2215 this.wpstgObject = wpstgObject;
2216 }
2217 var _proto = WpstgModal.prototype;
2218 _proto.show = function show(swalOptions, additionalParams, callback) {
2219 var _this = this;
2220 if (additionalParams === void 0) {
2221 additionalParams = {};
2222 }
2223 if (callback === void 0) {
2224 callback = null;
2225 }
2226 wpstgSwal.fire(swalOptions).then(function (result) {
2227 if (result.value && _this.error !== null) {
2228 _this.triggerConfirmAction(additionalParams, callback);
2229 }
2230 });
2231 };
2232 _proto.triggerConfirmAction = function triggerConfirmAction(additionalParams, callback) {
2233 var _this2 = this;
2234 if (additionalParams === void 0) {
2235 additionalParams = {};
2236 }
2237 if (callback === void 0) {
2238 callback = null;
2239 }
2240 fetch(this.wpstgObject.ajaxUrl, {
2241 method: 'POST',
2242 credentials: 'same-origin',
2243 body: new URLSearchParams(Object.assign({
2244 action: this.confirmAction,
2245 accessToken: this.wpstgObject.accessToken,
2246 nonce: this.wpstgObject.nonce
2247 }, additionalParams)),
2248 headers: {
2249 'Content-Type': 'application/x-www-form-urlencoded'
2250 }
2251 }).then(function (response) {
2252 if (response.ok) {
2253 return response.json();
2254 }
2255 return Promise.reject(response);
2256 }).then(function (response) {
2257 if (callback !== null) {
2258 callback(response);
2259 }
2260 })["catch"](function (error) {
2261 console.log(_this2.wpstgObject.i18n['somethingWentWrong'], error);
2262 });
2263 };
2264 return WpstgModal;
2265 }();
2266
2267 /**
2268 * Manage RESET MODAL
2269 */
2270 var WpstgResetModal = /*#__PURE__*/function () {
2271 function WpstgResetModal(cloneID, workflowSelector, fetchExcludeSettingsAction, modalErrorAction, wpstgObject) {
2272 if (workflowSelector === void 0) {
2273 workflowSelector = '#wpstg-workflow';
2274 }
2275 if (fetchExcludeSettingsAction === void 0) {
2276 fetchExcludeSettingsAction = 'wpstg_clone_excludes_settings';
2277 }
2278 if (modalErrorAction === void 0) {
2279 modalErrorAction = 'wpstg_modal_error';
2280 }
2281 if (wpstgObject === void 0) {
2282 wpstgObject = wpstg;
2283 }
2284 this.cloneID = cloneID;
2285 this.workflow = qs(workflowSelector);
2286 this.wpstgObject = wpstgObject;
2287 this.fetchExcludeSettingsAction = fetchExcludeSettingsAction;
2288 this.modalErrorAction = modalErrorAction;
2289 this.resetButtonClass = 'wpstg-confirm-reset-clone';
2290 this.resetModalContainerClass = 'wpstg-reset-confirmation';
2291 this.resetTabSelector = '.wpstg-reset-exclude-tab';
2292 this.directoryNavigator = null;
2293 this.excludeFilters = null;
2294 this.tableSelector = null;
2295 this.isNetworkClone = false;
2296 }
2297 var _proto = WpstgResetModal.prototype;
2298 _proto.addEvents = function addEvents() {
2299 var _this = this;
2300 var resetModalContainer = qs('.' + this.resetModalContainerClass);
2301 if (resetModalContainer === null) {
2302 console.log('Exit');
2303 return;
2304 }
2305 addEvent(resetModalContainer, 'click', this.resetTabSelector, function (target) {
2306 _this.toggleContent(target);
2307 });
2308 };
2309 _proto.init = function init() {
2310 this.addEvents();
2311 };
2312 _proto.setNetworkClone = function setNetworkClone(isNetworkClone) {
2313 this.isNetworkClone = isNetworkClone;
2314 };
2315 _proto.toggleContent = function toggleContent(target) {
2316 var resetModalContainer = qs('.' + this.resetModalContainerClass);
2317 var contentId = target.getAttribute('data-id');
2318 var tabTriangle = target.querySelector('.wpstg-tab-triangle');
2319 var isCollapsed = target.getAttribute('data-collapsed', 'true');
2320 var content = qs(contentId);
2321 if (isCollapsed === 'true') {
2322 if (resetModalContainer.classList.contains('has-collapsible-open')) {
2323 resetModalContainer.classList.add('has-collapsible-open-2');
2324 } else {
2325 resetModalContainer.classList.add('has-collapsible-open');
2326 }
2327 slideDown(content);
2328 tabTriangle.style.transform = 'rotate(90deg)';
2329 target.setAttribute('data-collapsed', 'false');
2330 } else {
2331 if (resetModalContainer.classList.contains('has-collapsible-open-2')) {
2332 resetModalContainer.classList.remove('has-collapsible-open-2');
2333 } else {
2334 resetModalContainer.classList.remove('has-collapsible-open');
2335 }
2336 slideUp(content);
2337 tabTriangle.style.removeProperty('transform');
2338 target.setAttribute('data-collapsed', 'true');
2339 }
2340 }
2341
2342 /**
2343 * Show Swal alert with loader and send ajax request to fetch content of alert.
2344 * @return Promise
2345 */;
2346 _proto.showModal = function showModal() {
2347 var swalPromise = this.loadModal();
2348 this.init();
2349 this.fetchCloneExcludes();
2350 return swalPromise;
2351 };
2352 _proto.loadModal = function loadModal() {
2353 return WPStagingCommon.getSwalModal(false, {
2354 confirmButton: this.resetButtonClass + ' wpstg-confirm-reset-clone wpstg--btn--confirm wpstg-blue-primary wpstg-button wpstg-link-btn',
2355 container: this.resetModalContainerClass + ' wpstg-swal2-container wpstg-swal2-loading'
2356 }).fire({
2357 title: '',
2358 icon: 'warning',
2359 html: this.getAjaxLoader(),
2360 width: '400px',
2361 focusConfirm: false,
2362 confirmButtonText: this.wpstgObject.i18n.resetClone,
2363 showCancelButton: true
2364 });
2365 };
2366 _proto.fetchCloneExcludes = function fetchCloneExcludes() {
2367 var _this2 = this;
2368 this.error = null;
2369 // send ajax request and fetch preserved exclude settings
2370 fetch(this.wpstgObject.ajaxUrl, {
2371 method: 'POST',
2372 credentials: 'same-origin',
2373 body: new URLSearchParams({
2374 action: this.fetchExcludeSettingsAction,
2375 accessToken: this.wpstgObject.accessToken,
2376 nonce: this.wpstgObject.nonce,
2377 clone: this.cloneID,
2378 job: 'resetting'
2379 }),
2380 headers: {
2381 'Content-Type': 'application/x-www-form-urlencoded'
2382 }
2383 }).then(function (response) {
2384 if (response.ok) {
2385 return response.json();
2386 }
2387 return Promise.reject(response);
2388 }).then(function (data) {
2389 if (!data.success) {
2390 var errorModal = new WpstgModal(_this2.modalErrorAction, _this2.wpstgObject);
2391 errorModal.show(Object.assign({
2392 title: 'Error',
2393 icon: 'error',
2394 html: _this2.wpstgObject.i18n['somethingWentWrong'],
2395 width: '500px',
2396 confirmButtonText: 'Ok',
2397 showCancelButton: false,
2398 customClass: {
2399 confirmButton: 'wpstg--btn--confirm wpstg-blue-primary wpstg-button wpstg-link-btn',
2400 cancelButton: 'wpstg--btn--cancel wpstg-blue-primary wpstg-link-btn',
2401 actions: 'wpstg--modal--actions',
2402 popup: 'wpstg-swal-popup wpstg-centered-modal'
2403 },
2404 buttonsStyling: false,
2405 reverseButtons: true
2406 }, data.swalOptions), {
2407 type: data.type
2408 });
2409 return;
2410 }
2411 var modal = qs('.wpstg-reset-confirmation');
2412 modal.classList.remove('wpstg-swal2-loading');
2413 modal.querySelector('.wpstg--swal2-popup').style.width = '540px';
2414 modal.querySelector('.wpstg--swal2-content').innerHTML = data.html;
2415 _this2.directoryNavigator = new WpstgDirectoryNavigation('#wpstg-directories-listing', wpstg, null);
2416 _this2.directoryNavigator.countSelectedFiles();
2417 _this2.excludeFilters = new WpstgExcludeFilters();
2418 _this2.tableSelector = new WpstgTableSelection('#wpstg-reset-excluded-tables', '.' + _this2.resetModalContainerClass);
2419 _this2.tableSelector.setNetworkClone(_this2.isNetworkClone);
2420 _this2.tableSelector.countSelectedTables();
2421 })["catch"](function (error) {
2422 _this2.renderError({
2423 'html': _this2.wpstgObject.i18n['somethingWentWrong'] + ' ' + error
2424 });
2425 });
2426 };
2427 _proto.getDirectoryNavigator = function getDirectoryNavigator() {
2428 return this.directoryNavigator;
2429 };
2430 _proto.getExcludeFilters = function getExcludeFilters() {
2431 return this.excludeFilters;
2432 };
2433 _proto.getTableSelector = function getTableSelector() {
2434 return this.tableSelector;
2435 };
2436 _proto.getAjaxLoader = function getAjaxLoader() {
2437 return '<div class="wpstg-swal2-ajax-loader"><img src="' + this.wpstgObject.wpstgIcon + '" /></div>';
2438 };
2439 return WpstgResetModal;
2440 }();
2441
2442 /**
2443 * Handle toggle of advance settings checkboxes
2444 */
2445 var WpstgCloningAdvanceSettings = /*#__PURE__*/function () {
2446 function WpstgCloningAdvanceSettings(baseContainerSelector) {
2447 if (baseContainerSelector === void 0) {
2448 baseContainerSelector = '#wpstg-clonepage-wrapper';
2449 }
2450 this.baseContainer = qs(baseContainerSelector);
2451 this.checkBoxSettingTogglerSelector = '.wpstg-toggle-advance-settings-section';
2452 this.init();
2453 }
2454
2455 /**
2456 * Add events
2457 * @return {void}
2458 */
2459 var _proto = WpstgCloningAdvanceSettings.prototype;
2460 _proto.addEvents = function addEvents() {
2461 var _this = this;
2462 if (this.baseContainer === null) {
2463 return;
2464 }
2465 addEvent(this.baseContainer, 'change', this.checkBoxSettingTogglerSelector, function (element) {
2466 _this.toggleSettings(element);
2467 });
2468 }
2469
2470 /**
2471 * @return {void}
2472 */;
2473 _proto.init = function init() {
2474 this.addEvents();
2475 }
2476
2477 /**
2478 * Expand/Collapse checkbox content on change
2479 * @return {void}
2480 */;
2481 _proto.toggleSettings = function toggleSettings(element) {
2482 var target = qs('#' + element.getAttribute('data-id'));
2483 if (element.checked) {
2484 slideDown(target);
2485 } else {
2486 slideUp(target);
2487 }
2488 };
2489 return WpstgCloningAdvanceSettings;
2490 }();
2491
2492 var WpstgMainMenu = /*#__PURE__*/function () {
2493 function WpstgMainMenu() {
2494 this.activeTabClass = 'wpstg--tab--active';
2495 this.mainMenu();
2496 }
2497 var _proto = WpstgMainMenu.prototype;
2498 _proto.mainMenu = function mainMenu() {
2499 var _this = this;
2500 var tabHeader = qs('.wpstg--tab--header');
2501 // Early bail if tab header is not available
2502 if (tabHeader === null) {
2503 return;
2504 }
2505 var workflowContainer = qs('#wpstg-workflow');
2506 if (workflowContainer !== null) {
2507 addEvent(workflowContainer, 'click', '.wpstg-navigate-button', function (element) {
2508 var $this = element;
2509 var target = $this.getAttribute('data-target');
2510 if (target === '') {
2511 return;
2512 }
2513 if ('#wpstg--tab--backup' === target) {
2514 // trigger click for .wpsg--tab--header a[data-target="#wpstg--tab--backup"]
2515 qs('.wpstg--tab--header a[data-target="#wpstg--tab--backup"]').click();
2516 }
2517 });
2518 }
2519 addEvent(qs('.wpstg--tab--header'), 'click', '.wpstg-button', function (element) {
2520 var $this = element;
2521 var target = $this.getAttribute('data-target');
2522 if (target === '') {
2523 return;
2524 }
2525 var targetElements = all(target);
2526 var menuItems = all('.wpstg--tab--header a[data-target]');
2527 var contents = all('.wpstg--tab--contents > .wpstg--tab--content');
2528 contents.forEach(function (content) {
2529 // active tab class is without the css dot class prefix
2530 if (content.matches('.' + _this.activeTabClass + ':not(' + target + ')')) {
2531 content.classList.remove(_this.activeTabClass);
2532 }
2533 });
2534 menuItems.forEach(function (menuItem) {
2535 if (menuItem !== $this) {
2536 menuItem.classList.remove(_this.activeTabClass);
2537 }
2538 });
2539 $this.classList.add(_this.activeTabClass);
2540 targetElements.forEach(function (targetElement) {
2541 targetElement.classList.add(_this.activeTabClass);
2542 });
2543 if ('#wpstg--tab--backup' === target) {
2544 window.dispatchEvent(new Event('backups-tab'));
2545 }
2546 });
2547 };
2548 return WpstgMainMenu;
2549 }();
2550
2551 /**
2552 * Copyright (c) 2014-present, Facebook, Inc.
2553 *
2554 * This source code is licensed under the MIT license found in the
2555 * LICENSE file in the root directory of this source tree.
2556 */
2557
2558 var runtime = (function (exports) {
2559
2560 var Op = Object.prototype;
2561 var hasOwn = Op.hasOwnProperty;
2562 var defineProperty = Object.defineProperty || function (obj, key, desc) { obj[key] = desc.value; };
2563 var undefined$1; // More compressible than void 0.
2564 var $Symbol = typeof Symbol === "function" ? Symbol : {};
2565 var iteratorSymbol = $Symbol.iterator || "@@iterator";
2566 var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator";
2567 var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
2568
2569 function define(obj, key, value) {
2570 Object.defineProperty(obj, key, {
2571 value: value,
2572 enumerable: true,
2573 configurable: true,
2574 writable: true
2575 });
2576 return obj[key];
2577 }
2578 try {
2579 // IE 8 has a broken Object.defineProperty that only works on DOM objects.
2580 define({}, "");
2581 } catch (err) {
2582 define = function(obj, key, value) {
2583 return obj[key] = value;
2584 };
2585 }
2586
2587 function wrap(innerFn, outerFn, self, tryLocsList) {
2588 // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.
2589 var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;
2590 var generator = Object.create(protoGenerator.prototype);
2591 var context = new Context(tryLocsList || []);
2592
2593 // The ._invoke method unifies the implementations of the .next,
2594 // .throw, and .return methods.
2595 defineProperty(generator, "_invoke", { value: makeInvokeMethod(innerFn, self, context) });
2596
2597 return generator;
2598 }
2599 exports.wrap = wrap;
2600
2601 // Try/catch helper to minimize deoptimizations. Returns a completion
2602 // record like context.tryEntries[i].completion. This interface could
2603 // have been (and was previously) designed to take a closure to be
2604 // invoked without arguments, but in all the cases we care about we
2605 // already have an existing method we want to call, so there's no need
2606 // to create a new function object. We can even get away with assuming
2607 // the method takes exactly one argument, since that happens to be true
2608 // in every case, so we don't have to touch the arguments object. The
2609 // only additional allocation required is the completion record, which
2610 // has a stable shape and so hopefully should be cheap to allocate.
2611 function tryCatch(fn, obj, arg) {
2612 try {
2613 return { type: "normal", arg: fn.call(obj, arg) };
2614 } catch (err) {
2615 return { type: "throw", arg: err };
2616 }
2617 }
2618
2619 var GenStateSuspendedStart = "suspendedStart";
2620 var GenStateSuspendedYield = "suspendedYield";
2621 var GenStateExecuting = "executing";
2622 var GenStateCompleted = "completed";
2623
2624 // Returning this object from the innerFn has the same effect as
2625 // breaking out of the dispatch switch statement.
2626 var ContinueSentinel = {};
2627
2628 // Dummy constructor functions that we use as the .constructor and
2629 // .constructor.prototype properties for functions that return Generator
2630 // objects. For full spec compliance, you may wish to configure your
2631 // minifier not to mangle the names of these two functions.
2632 function Generator() {}
2633 function GeneratorFunction() {}
2634 function GeneratorFunctionPrototype() {}
2635
2636 // This is a polyfill for %IteratorPrototype% for environments that
2637 // don't natively support it.
2638 var IteratorPrototype = {};
2639 define(IteratorPrototype, iteratorSymbol, function () {
2640 return this;
2641 });
2642
2643 var getProto = Object.getPrototypeOf;
2644 var NativeIteratorPrototype = getProto && getProto(getProto(values([])));
2645 if (NativeIteratorPrototype &&
2646 NativeIteratorPrototype !== Op &&
2647 hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {
2648 // This environment has a native %IteratorPrototype%; use it instead
2649 // of the polyfill.
2650 IteratorPrototype = NativeIteratorPrototype;
2651 }
2652
2653 var Gp = GeneratorFunctionPrototype.prototype =
2654 Generator.prototype = Object.create(IteratorPrototype);
2655 GeneratorFunction.prototype = GeneratorFunctionPrototype;
2656 defineProperty(Gp, "constructor", { value: GeneratorFunctionPrototype, configurable: true });
2657 defineProperty(
2658 GeneratorFunctionPrototype,
2659 "constructor",
2660 { value: GeneratorFunction, configurable: true }
2661 );
2662 GeneratorFunction.displayName = define(
2663 GeneratorFunctionPrototype,
2664 toStringTagSymbol,
2665 "GeneratorFunction"
2666 );
2667
2668 // Helper for defining the .next, .throw, and .return methods of the
2669 // Iterator interface in terms of a single ._invoke method.
2670 function defineIteratorMethods(prototype) {
2671 ["next", "throw", "return"].forEach(function(method) {
2672 define(prototype, method, function(arg) {
2673 return this._invoke(method, arg);
2674 });
2675 });
2676 }
2677
2678 exports.isGeneratorFunction = function(genFun) {
2679 var ctor = typeof genFun === "function" && genFun.constructor;
2680 return ctor
2681 ? ctor === GeneratorFunction ||
2682 // For the native GeneratorFunction constructor, the best we can
2683 // do is to check its .name property.
2684 (ctor.displayName || ctor.name) === "GeneratorFunction"
2685 : false;
2686 };
2687
2688 exports.mark = function(genFun) {
2689 if (Object.setPrototypeOf) {
2690 Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);
2691 } else {
2692 genFun.__proto__ = GeneratorFunctionPrototype;
2693 define(genFun, toStringTagSymbol, "GeneratorFunction");
2694 }
2695 genFun.prototype = Object.create(Gp);
2696 return genFun;
2697 };
2698
2699 // Within the body of any async function, `await x` is transformed to
2700 // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test
2701 // `hasOwn.call(value, "__await")` to determine if the yielded value is
2702 // meant to be awaited.
2703 exports.awrap = function(arg) {
2704 return { __await: arg };
2705 };
2706
2707 function AsyncIterator(generator, PromiseImpl) {
2708 function invoke(method, arg, resolve, reject) {
2709 var record = tryCatch(generator[method], generator, arg);
2710 if (record.type === "throw") {
2711 reject(record.arg);
2712 } else {
2713 var result = record.arg;
2714 var value = result.value;
2715 if (value &&
2716 typeof value === "object" &&
2717 hasOwn.call(value, "__await")) {
2718 return PromiseImpl.resolve(value.__await).then(function(value) {
2719 invoke("next", value, resolve, reject);
2720 }, function(err) {
2721 invoke("throw", err, resolve, reject);
2722 });
2723 }
2724
2725 return PromiseImpl.resolve(value).then(function(unwrapped) {
2726 // When a yielded Promise is resolved, its final value becomes
2727 // the .value of the Promise<{value,done}> result for the
2728 // current iteration.
2729 result.value = unwrapped;
2730 resolve(result);
2731 }, function(error) {
2732 // If a rejected Promise was yielded, throw the rejection back
2733 // into the async generator function so it can be handled there.
2734 return invoke("throw", error, resolve, reject);
2735 });
2736 }
2737 }
2738
2739 var previousPromise;
2740
2741 function enqueue(method, arg) {
2742 function callInvokeWithMethodAndArg() {
2743 return new PromiseImpl(function(resolve, reject) {
2744 invoke(method, arg, resolve, reject);
2745 });
2746 }
2747
2748 return previousPromise =
2749 // If enqueue has been called before, then we want to wait until
2750 // all previous Promises have been resolved before calling invoke,
2751 // so that results are always delivered in the correct order. If
2752 // enqueue has not been called before, then it is important to
2753 // call invoke immediately, without waiting on a callback to fire,
2754 // so that the async generator function has the opportunity to do
2755 // any necessary setup in a predictable way. This predictability
2756 // is why the Promise constructor synchronously invokes its
2757 // executor callback, and why async functions synchronously
2758 // execute code before the first await. Since we implement simple
2759 // async functions in terms of async generators, it is especially
2760 // important to get this right, even though it requires care.
2761 previousPromise ? previousPromise.then(
2762 callInvokeWithMethodAndArg,
2763 // Avoid propagating failures to Promises returned by later
2764 // invocations of the iterator.
2765 callInvokeWithMethodAndArg
2766 ) : callInvokeWithMethodAndArg();
2767 }
2768
2769 // Define the unified helper method that is used to implement .next,
2770 // .throw, and .return (see defineIteratorMethods).
2771 defineProperty(this, "_invoke", { value: enqueue });
2772 }
2773
2774 defineIteratorMethods(AsyncIterator.prototype);
2775 define(AsyncIterator.prototype, asyncIteratorSymbol, function () {
2776 return this;
2777 });
2778 exports.AsyncIterator = AsyncIterator;
2779
2780 // Note that simple async functions are implemented on top of
2781 // AsyncIterator objects; they just return a Promise for the value of
2782 // the final result produced by the iterator.
2783 exports.async = function(innerFn, outerFn, self, tryLocsList, PromiseImpl) {
2784 if (PromiseImpl === void 0) PromiseImpl = Promise;
2785
2786 var iter = new AsyncIterator(
2787 wrap(innerFn, outerFn, self, tryLocsList),
2788 PromiseImpl
2789 );
2790
2791 return exports.isGeneratorFunction(outerFn)
2792 ? iter // If outerFn is a generator, return the full iterator.
2793 : iter.next().then(function(result) {
2794 return result.done ? result.value : iter.next();
2795 });
2796 };
2797
2798 function makeInvokeMethod(innerFn, self, context) {
2799 var state = GenStateSuspendedStart;
2800
2801 return function invoke(method, arg) {
2802 if (state === GenStateExecuting) {
2803 throw new Error("Generator is already running");
2804 }
2805
2806 if (state === GenStateCompleted) {
2807 if (method === "throw") {
2808 throw arg;
2809 }
2810
2811 // Be forgiving, per 25.3.3.3.3 of the spec:
2812 // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume
2813 return doneResult();
2814 }
2815
2816 context.method = method;
2817 context.arg = arg;
2818
2819 while (true) {
2820 var delegate = context.delegate;
2821 if (delegate) {
2822 var delegateResult = maybeInvokeDelegate(delegate, context);
2823 if (delegateResult) {
2824 if (delegateResult === ContinueSentinel) continue;
2825 return delegateResult;
2826 }
2827 }
2828
2829 if (context.method === "next") {
2830 // Setting context._sent for legacy support of Babel's
2831 // function.sent implementation.
2832 context.sent = context._sent = context.arg;
2833
2834 } else if (context.method === "throw") {
2835 if (state === GenStateSuspendedStart) {
2836 state = GenStateCompleted;
2837 throw context.arg;
2838 }
2839
2840 context.dispatchException(context.arg);
2841
2842 } else if (context.method === "return") {
2843 context.abrupt("return", context.arg);
2844 }
2845
2846 state = GenStateExecuting;
2847
2848 var record = tryCatch(innerFn, self, context);
2849 if (record.type === "normal") {
2850 // If an exception is thrown from innerFn, we leave state ===
2851 // GenStateExecuting and loop back for another invocation.
2852 state = context.done
2853 ? GenStateCompleted
2854 : GenStateSuspendedYield;
2855
2856 if (record.arg === ContinueSentinel) {
2857 continue;
2858 }
2859
2860 return {
2861 value: record.arg,
2862 done: context.done
2863 };
2864
2865 } else if (record.type === "throw") {
2866 state = GenStateCompleted;
2867 // Dispatch the exception by looping back around to the
2868 // context.dispatchException(context.arg) call above.
2869 context.method = "throw";
2870 context.arg = record.arg;
2871 }
2872 }
2873 };
2874 }
2875
2876 // Call delegate.iterator[context.method](context.arg) and handle the
2877 // result, either by returning a { value, done } result from the
2878 // delegate iterator, or by modifying context.method and context.arg,
2879 // setting context.delegate to null, and returning the ContinueSentinel.
2880 function maybeInvokeDelegate(delegate, context) {
2881 var methodName = context.method;
2882 var method = delegate.iterator[methodName];
2883 if (method === undefined$1) {
2884 // A .throw or .return when the delegate iterator has no .throw
2885 // method, or a missing .next mehtod, always terminate the
2886 // yield* loop.
2887 context.delegate = null;
2888
2889 // Note: ["return"] must be used for ES3 parsing compatibility.
2890 if (methodName === "throw" && delegate.iterator["return"]) {
2891 // If the delegate iterator has a return method, give it a
2892 // chance to clean up.
2893 context.method = "return";
2894 context.arg = undefined$1;
2895 maybeInvokeDelegate(delegate, context);
2896
2897 if (context.method === "throw") {
2898 // If maybeInvokeDelegate(context) changed context.method from
2899 // "return" to "throw", let that override the TypeError below.
2900 return ContinueSentinel;
2901 }
2902 }
2903 if (methodName !== "return") {
2904 context.method = "throw";
2905 context.arg = new TypeError(
2906 "The iterator does not provide a '" + methodName + "' method");
2907 }
2908
2909 return ContinueSentinel;
2910 }
2911
2912 var record = tryCatch(method, delegate.iterator, context.arg);
2913
2914 if (record.type === "throw") {
2915 context.method = "throw";
2916 context.arg = record.arg;
2917 context.delegate = null;
2918 return ContinueSentinel;
2919 }
2920
2921 var info = record.arg;
2922
2923 if (! info) {
2924 context.method = "throw";
2925 context.arg = new TypeError("iterator result is not an object");
2926 context.delegate = null;
2927 return ContinueSentinel;
2928 }
2929
2930 if (info.done) {
2931 // Assign the result of the finished delegate to the temporary
2932 // variable specified by delegate.resultName (see delegateYield).
2933 context[delegate.resultName] = info.value;
2934
2935 // Resume execution at the desired location (see delegateYield).
2936 context.next = delegate.nextLoc;
2937
2938 // If context.method was "throw" but the delegate handled the
2939 // exception, let the outer generator proceed normally. If
2940 // context.method was "next", forget context.arg since it has been
2941 // "consumed" by the delegate iterator. If context.method was
2942 // "return", allow the original .return call to continue in the
2943 // outer generator.
2944 if (context.method !== "return") {
2945 context.method = "next";
2946 context.arg = undefined$1;
2947 }
2948
2949 } else {
2950 // Re-yield the result returned by the delegate method.
2951 return info;
2952 }
2953
2954 // The delegate iterator is finished, so forget it and continue with
2955 // the outer generator.
2956 context.delegate = null;
2957 return ContinueSentinel;
2958 }
2959
2960 // Define Generator.prototype.{next,throw,return} in terms of the
2961 // unified ._invoke helper method.
2962 defineIteratorMethods(Gp);
2963
2964 define(Gp, toStringTagSymbol, "Generator");
2965
2966 // A Generator should always return itself as the iterator object when the
2967 // @@iterator function is called on it. Some browsers' implementations of the
2968 // iterator prototype chain incorrectly implement this, causing the Generator
2969 // object to not be returned from this call. This ensures that doesn't happen.
2970 // See https://github.com/facebook/regenerator/issues/274 for more details.
2971 define(Gp, iteratorSymbol, function() {
2972 return this;
2973 });
2974
2975 define(Gp, "toString", function() {
2976 return "[object Generator]";
2977 });
2978
2979 function pushTryEntry(locs) {
2980 var entry = { tryLoc: locs[0] };
2981
2982 if (1 in locs) {
2983 entry.catchLoc = locs[1];
2984 }
2985
2986 if (2 in locs) {
2987 entry.finallyLoc = locs[2];
2988 entry.afterLoc = locs[3];
2989 }
2990
2991 this.tryEntries.push(entry);
2992 }
2993
2994 function resetTryEntry(entry) {
2995 var record = entry.completion || {};
2996 record.type = "normal";
2997 delete record.arg;
2998 entry.completion = record;
2999 }
3000
3001 function Context(tryLocsList) {
3002 // The root entry object (effectively a try statement without a catch
3003 // or a finally block) gives us a place to store values thrown from
3004 // locations where there is no enclosing try statement.
3005 this.tryEntries = [{ tryLoc: "root" }];
3006 tryLocsList.forEach(pushTryEntry, this);
3007 this.reset(true);
3008 }
3009
3010 exports.keys = function(val) {
3011 var object = Object(val);
3012 var keys = [];
3013 for (var key in object) {
3014 keys.push(key);
3015 }
3016 keys.reverse();
3017
3018 // Rather than returning an object with a next method, we keep
3019 // things simple and return the next function itself.
3020 return function next() {
3021 while (keys.length) {
3022 var key = keys.pop();
3023 if (key in object) {
3024 next.value = key;
3025 next.done = false;
3026 return next;
3027 }
3028 }
3029
3030 // To avoid creating an additional object, we just hang the .value
3031 // and .done properties off the next function object itself. This
3032 // also ensures that the minifier will not anonymize the function.
3033 next.done = true;
3034 return next;
3035 };
3036 };
3037
3038 function values(iterable) {
3039 if (iterable) {
3040 var iteratorMethod = iterable[iteratorSymbol];
3041 if (iteratorMethod) {
3042 return iteratorMethod.call(iterable);
3043 }
3044
3045 if (typeof iterable.next === "function") {
3046 return iterable;
3047 }
3048
3049 if (!isNaN(iterable.length)) {
3050 var i = -1, next = function next() {
3051 while (++i < iterable.length) {
3052 if (hasOwn.call(iterable, i)) {
3053 next.value = iterable[i];
3054 next.done = false;
3055 return next;
3056 }
3057 }
3058
3059 next.value = undefined$1;
3060 next.done = true;
3061
3062 return next;
3063 };
3064
3065 return next.next = next;
3066 }
3067 }
3068
3069 // Return an iterator with no values.
3070 return { next: doneResult };
3071 }
3072 exports.values = values;
3073
3074 function doneResult() {
3075 return { value: undefined$1, done: true };
3076 }
3077
3078 Context.prototype = {
3079 constructor: Context,
3080
3081 reset: function(skipTempReset) {
3082 this.prev = 0;
3083 this.next = 0;
3084 // Resetting context._sent for legacy support of Babel's
3085 // function.sent implementation.
3086 this.sent = this._sent = undefined$1;
3087 this.done = false;
3088 this.delegate = null;
3089
3090 this.method = "next";
3091 this.arg = undefined$1;
3092
3093 this.tryEntries.forEach(resetTryEntry);
3094
3095 if (!skipTempReset) {
3096 for (var name in this) {
3097 // Not sure about the optimal order of these conditions:
3098 if (name.charAt(0) === "t" &&
3099 hasOwn.call(this, name) &&
3100 !isNaN(+name.slice(1))) {
3101 this[name] = undefined$1;
3102 }
3103 }
3104 }
3105 },
3106
3107 stop: function() {
3108 this.done = true;
3109
3110 var rootEntry = this.tryEntries[0];
3111 var rootRecord = rootEntry.completion;
3112 if (rootRecord.type === "throw") {
3113 throw rootRecord.arg;
3114 }
3115
3116 return this.rval;
3117 },
3118
3119 dispatchException: function(exception) {
3120 if (this.done) {
3121 throw exception;
3122 }
3123
3124 var context = this;
3125 function handle(loc, caught) {
3126 record.type = "throw";
3127 record.arg = exception;
3128 context.next = loc;
3129
3130 if (caught) {
3131 // If the dispatched exception was caught by a catch block,
3132 // then let that catch block handle the exception normally.
3133 context.method = "next";
3134 context.arg = undefined$1;
3135 }
3136
3137 return !! caught;
3138 }
3139
3140 for (var i = this.tryEntries.length - 1; i >= 0; --i) {
3141 var entry = this.tryEntries[i];
3142 var record = entry.completion;
3143
3144 if (entry.tryLoc === "root") {
3145 // Exception thrown outside of any try block that could handle
3146 // it, so set the completion value of the entire function to
3147 // throw the exception.
3148 return handle("end");
3149 }
3150
3151 if (entry.tryLoc <= this.prev) {
3152 var hasCatch = hasOwn.call(entry, "catchLoc");
3153 var hasFinally = hasOwn.call(entry, "finallyLoc");
3154
3155 if (hasCatch && hasFinally) {
3156 if (this.prev < entry.catchLoc) {
3157 return handle(entry.catchLoc, true);
3158 } else if (this.prev < entry.finallyLoc) {
3159 return handle(entry.finallyLoc);
3160 }
3161
3162 } else if (hasCatch) {
3163 if (this.prev < entry.catchLoc) {
3164 return handle(entry.catchLoc, true);
3165 }
3166
3167 } else if (hasFinally) {
3168 if (this.prev < entry.finallyLoc) {
3169 return handle(entry.finallyLoc);
3170 }
3171
3172 } else {
3173 throw new Error("try statement without catch or finally");
3174 }
3175 }
3176 }
3177 },
3178
3179 abrupt: function(type, arg) {
3180 for (var i = this.tryEntries.length - 1; i >= 0; --i) {
3181 var entry = this.tryEntries[i];
3182 if (entry.tryLoc <= this.prev &&
3183 hasOwn.call(entry, "finallyLoc") &&
3184 this.prev < entry.finallyLoc) {
3185 var finallyEntry = entry;
3186 break;
3187 }
3188 }
3189
3190 if (finallyEntry &&
3191 (type === "break" ||
3192 type === "continue") &&
3193 finallyEntry.tryLoc <= arg &&
3194 arg <= finallyEntry.finallyLoc) {
3195 // Ignore the finally entry if control is not jumping to a
3196 // location outside the try/catch block.
3197 finallyEntry = null;
3198 }
3199
3200 var record = finallyEntry ? finallyEntry.completion : {};
3201 record.type = type;
3202 record.arg = arg;
3203
3204 if (finallyEntry) {
3205 this.method = "next";
3206 this.next = finallyEntry.finallyLoc;
3207 return ContinueSentinel;
3208 }
3209
3210 return this.complete(record);
3211 },
3212
3213 complete: function(record, afterLoc) {
3214 if (record.type === "throw") {
3215 throw record.arg;
3216 }
3217
3218 if (record.type === "break" ||
3219 record.type === "continue") {
3220 this.next = record.arg;
3221 } else if (record.type === "return") {
3222 this.rval = this.arg = record.arg;
3223 this.method = "return";
3224 this.next = "end";
3225 } else if (record.type === "normal" && afterLoc) {
3226 this.next = afterLoc;
3227 }
3228
3229 return ContinueSentinel;
3230 },
3231
3232 finish: function(finallyLoc) {
3233 for (var i = this.tryEntries.length - 1; i >= 0; --i) {
3234 var entry = this.tryEntries[i];
3235 if (entry.finallyLoc === finallyLoc) {
3236 this.complete(entry.completion, entry.afterLoc);
3237 resetTryEntry(entry);
3238 return ContinueSentinel;
3239 }
3240 }
3241 },
3242
3243 "catch": function(tryLoc) {
3244 for (var i = this.tryEntries.length - 1; i >= 0; --i) {
3245 var entry = this.tryEntries[i];
3246 if (entry.tryLoc === tryLoc) {
3247 var record = entry.completion;
3248 if (record.type === "throw") {
3249 var thrown = record.arg;
3250 resetTryEntry(entry);
3251 }
3252 return thrown;
3253 }
3254 }
3255
3256 // The context.catch method must only be called with a location
3257 // argument that corresponds to a known catch block.
3258 throw new Error("illegal catch attempt");
3259 },
3260
3261 delegateYield: function(iterable, resultName, nextLoc) {
3262 this.delegate = {
3263 iterator: values(iterable),
3264 resultName: resultName,
3265 nextLoc: nextLoc
3266 };
3267
3268 if (this.method === "next") {
3269 // Deliberately forget the last sent value so that we don't
3270 // accidentally pass it on to the delegate.
3271 this.arg = undefined$1;
3272 }
3273
3274 return ContinueSentinel;
3275 }
3276 };
3277
3278 // Regardless of whether this script is executing as a CommonJS module
3279 // or not, return the runtime object so that we can declare the variable
3280 // regeneratorRuntime in the outer scope, which allows this module to be
3281 // injected easily by `bin/regenerator --include-runtime script.js`.
3282 return exports;
3283
3284 }(
3285 // If this script is executing as a CommonJS module, use module.exports
3286 // as the regeneratorRuntime namespace. Otherwise create a new empty
3287 // object. Either way, the resulting object will be used to initialize
3288 // the regeneratorRuntime variable at the top of this file.
3289 typeof module === "object" ? module.exports : {}
3290 ));
3291
3292 try {
3293 regeneratorRuntime = runtime;
3294 } catch (accidentalStrictMode) {
3295 // This module should not be running in strict mode, so the above
3296 // assignment should always work unless something is misconfigured. Just
3297 // in case runtime.js accidentally runs in strict mode, in modern engines
3298 // we can explicitly access globalThis. In older engines we can escape
3299 // strict mode using a global Function call. This could conceivably fail
3300 // if a Content Security Policy forbids using Function, but in that case
3301 // the proper solution is to fix the accidental strict mode problem. If
3302 // you've misconfigured your bundler to force strict mode and applied a
3303 // CSP to forbid Function, and you're not willing to fix either of those
3304 // problems, please detail your unique predicament in a GitHub issue.
3305 if (typeof globalThis === "object") {
3306 globalThis.regeneratorRuntime = runtime;
3307 } else {
3308 Function("r", "regeneratorRuntime = r")(runtime);
3309 }
3310 }
3311
3312 var WpstgReAuth = /*#__PURE__*/function () {
3313 function WpstgReAuth() {
3314 this.wrap = '';
3315 this.tempHidden = '';
3316 this.tempHiddenTimeout = '';
3317 }
3318
3319 /**
3320 * @return {void}
3321 */
3322 var _proto = WpstgReAuth.prototype;
3323 _proto.shows = function shows() {
3324 this.wrap = document.getElementById('wpstg-auth-check-wrap');
3325 this.parentElement = document.getElementById('wpstg-auth-check');
3326 this.formElement = document.getElementById('wpstg-auth-check-form');
3327 this.wrapElement = document.getElementById('wpstg-auth-check-wrap');
3328 this.noFrameElement = this.wrapElement.querySelector('.wpstg-auth-fallback-expired');
3329 this.iframeElement = '';
3330 this.isIframeLoaded = false;
3331 if (this.formElement) {
3332 this.addUnloadEvent();
3333 this.iframeElement = this.createIframeElement();
3334 this.formElement.appendChild(this.iframeElement);
3335 }
3336 this.openModal();
3337 if (this.iframeElement) {
3338 this.focusIframe();
3339 this.setIframeLoadTimeout();
3340 } else {
3341 this.focusFallbackElement();
3342 }
3343 }
3344
3345 /**
3346 * @return {void}
3347 */;
3348 _proto.addUnloadEvent = function addUnloadEvent() {
3349 window.addEventListener('beforeunload', function (event) {
3350 event.returnValue = 'Your session has expired. You can log in again from this page or go to the login page.';
3351 });
3352 }
3353
3354 /**
3355 * @return {void}
3356 */;
3357 _proto.createIframeElement = function createIframeElement() {
3358 var _this = this;
3359 this.iframeElement = document.createElement('iframe');
3360 this.iframeElement.id = 'wpstg-auth-check-frame';
3361 this.iframeElement.style.border = '0px';
3362 this.iframeElement.title = this.noFrameElement.textContent;
3363 this.iframeElement.onload = function () {
3364 return _this.handleIframeLoad();
3365 };
3366 this.iframeElement.src = this.formElement.dataset.src;
3367 return this.iframeElement;
3368 }
3369
3370 /**
3371 * @return {void}
3372 */;
3373 _proto.handleIframeLoad = function handleIframeLoad() {
3374 var height;
3375 var body;
3376 this.isIframeLoaded = true;
3377 this.formElement.classList.remove('loading');
3378 try {
3379 body = this.iframeElement.contentDocument.querySelector('body');
3380 height = body.offsetHeight;
3381 } catch (er) {
3382 this.handleIframeLoadError();
3383 return;
3384 }
3385 if (!body || !height) {
3386 this.handleIframeLoadError();
3387 return;
3388 }
3389 if (!body.classList.contains('interim-login-success')) {
3390 this.parentElement.style.maxHeight = height + 40 + 'px';
3391 return;
3392 }
3393 this.hide();
3394 }
3395
3396 /**
3397 * @return {void}
3398 */;
3399 _proto.handleIframeLoadError = function handleIframeLoadError() {
3400 this.wrapElement.classList.add('fallback');
3401 this.parentElement.style.maxHeight = '';
3402 this.formElement.remove();
3403 this.noFrameElement.focus();
3404 }
3405
3406 /**
3407 * @return {void}
3408 */;
3409 _proto.openModal = function openModal() {
3410 document.body.classList.add('modal-open');
3411 this.wrapElement.classList.remove('hidden');
3412 }
3413
3414 /**
3415 * @return {void}
3416 */;
3417 _proto.focusIframe = function focusIframe() {
3418 this.iframeElement.focus();
3419 }
3420
3421 /**
3422 * @return {void}
3423 */;
3424 _proto.setIframeLoadTimeout = function setIframeLoadTimeout() {
3425 var _this2 = this;
3426 setTimeout(function () {
3427 if (!_this2.isIframeLoaded) {
3428 _this2.wrapElement.classList.add('fallback');
3429 _this2.formElement.remove();
3430 _this2.noFrameElement.focus();
3431 }
3432 }, 2000);
3433 }
3434
3435 /**
3436 * @return {void}
3437 */;
3438 _proto.focusFallbackElement = function focusFallbackElement() {
3439 this.noFrameElement.focus();
3440 }
3441
3442 /**
3443 * @return {void}
3444 */;
3445 _proto.hide = function hide() {
3446 window.removeEventListener('beforeunload', function (event) {
3447 event.returnValue = null;
3448 });
3449 fadeOut(this.wrap, 200);
3450 wpstgAuthCheck.checkUserAuthentication();
3451 };
3452 return WpstgReAuth;
3453 }();
3454 var wpstgReAuth = new WpstgReAuth();
3455
3456 var WpstgAuthCheck = /*#__PURE__*/function () {
3457 function WpstgAuthCheck(wpstgObject) {
3458 if (wpstgObject === void 0) {
3459 wpstgObject = wpstg;
3460 }
3461 this.wpstgObject = wpstgObject;
3462 this.count = 0;
3463 this.status = true;
3464 this.isAuthenticated = true;
3465 }
3466
3467 /**
3468 * Start checking user authentication
3469 *
3470 * @return {void}
3471 */
3472 var _proto = WpstgAuthCheck.prototype;
3473 _proto.start = function start() {
3474 var _this = this;
3475 if (this.status) {
3476 setTimeout(function () {
3477 _this.checkUserAuthentication();
3478 }, 1000);
3479 }
3480 }
3481
3482 /**
3483 * @return {void}
3484 */;
3485 _proto.stop = function stop() {
3486 this.resetCount();
3487 this.status = false;
3488 }
3489
3490 /**
3491 * @return {void}
3492 */;
3493 _proto.resetCount = function resetCount() {
3494 this.count = 0;
3495 }
3496
3497 /**
3498 * @return {void}
3499 */;
3500 _proto.checkUserAuthentication =
3501 /*#__PURE__*/
3502 function () {
3503 var _checkUserAuthentication = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
3504 var _this2 = this;
3505 return _regeneratorRuntime().wrap(function _callee$(_context) {
3506 while (1) switch (_context.prev = _context.next) {
3507 case 0:
3508 fetch(this.wpstgObject.ajaxUrl, {
3509 method: 'POST',
3510 credentials: 'same-origin',
3511 body: new URLSearchParams({
3512 action: 'wpstg_check_user_is_authenticated',
3513 accessToken: this.wpstgObject.accessToken,
3514 nonce: this.wpstgObject.nonce
3515 }),
3516 headers: {
3517 'Content-Type': 'application/x-www-form-urlencoded'
3518 }
3519 }).then(function (response) {
3520 if (response.ok) {
3521 return response.json();
3522 }
3523 return Promise.reject(response);
3524 }).then(function (data) {
3525 if (data.wpAuthCheck === false) {
3526 _this2.count++;
3527 }
3528 _this2.isAuthenticated = data.wpAuthCheck;
3529 if (_this2.count === 2) {
3530 _this2.stop();
3531 _this2.createAuthCheckElements(data.redirectUrl);
3532 return;
3533 }
3534 _this2.start();
3535 })["catch"](function (error) {
3536 console.error('Error:', error);
3537 });
3538 case 1:
3539 case "end":
3540 return _context.stop();
3541 }
3542 }, _callee, this);
3543 }));
3544 function checkUserAuthentication() {
3545 return _checkUserAuthentication.apply(this, arguments);
3546 }
3547 return checkUserAuthentication;
3548 }()
3549 /**
3550 * @param redirectUrl
3551 * @return {void}
3552 */
3553 ;
3554 _proto.createAuthCheckElements = function createAuthCheckElements(redirectUrl) {
3555 var isAlreadyAppended = document.getElementById('wpstg-auth-check-wrap') !== null;
3556 if (isAlreadyAppended) {
3557 document.getElementById('wpstg-auth-check-wrap').remove();
3558 }
3559 var wpAuthCheckWrap = document.createElement('div');
3560 wpAuthCheckWrap.id = 'wpstg-auth-check-wrap';
3561 wpAuthCheckWrap.classList.add('hidden');
3562 var wpAuthCheckBg = document.createElement('div');
3563 wpAuthCheckBg.id = 'wpstg-auth-check-bg';
3564 var wpAuthCheckDialog = document.createElement('div');
3565 wpAuthCheckDialog.id = 'wpstg-auth-check';
3566 var wpAuthCheckForm = document.createElement('div');
3567 wpAuthCheckForm.id = 'wpstg-auth-check-form';
3568 wpAuthCheckForm.classList.add('loading');
3569 wpAuthCheckForm.dataset.src = redirectUrl + '?interim-login=1&wp_lang=en_US';
3570 var wpAuthCheckFallback = document.createElement('div');
3571 wpAuthCheckFallback.classList.add('wpstg-auth-fallback');
3572 var wpAuthCheckExpired = document.createElement('p');
3573 wpAuthCheckExpired.innerHTML = '<b class="wpstg-auth-fallback-expired" tabindex="0">Session expired</b>';
3574 var wpAuthCheckLoginLink = document.createElement('p');
3575 wpAuthCheckLoginLink.innerHTML = "<a href=\"" + redirectUrl + "\" target=\"_blank\">Please log in again.</a> The login page will open in a new tab. After logging in you can close it and return to this page.";
3576 wpAuthCheckDialog.append(wpAuthCheckForm, wpAuthCheckFallback);
3577 wpAuthCheckFallback.append(wpAuthCheckExpired, wpAuthCheckLoginLink);
3578 wpAuthCheckWrap.append(wpAuthCheckBg, wpAuthCheckDialog);
3579 document.body.appendChild(wpAuthCheckWrap);
3580 wpstgReAuth.shows();
3581 };
3582 return WpstgAuthCheck;
3583 }();
3584 var wpstgAuthCheck = new WpstgAuthCheck();
3585
3586 /**
3587 * Represents a class for managing and displaying process and success modals in WPStaging.
3588 * This class provides methods to start, open, initialize, update, and stop process modals.
3589 *
3590 * @class
3591 */
3592 var WpstgProcessModal = /*#__PURE__*/function () {
3593 function WpstgProcessModal(wpstgObject) {
3594 if (wpstgObject === void 0) {
3595 wpstgObject = wpstg;
3596 }
3597 this.wpstgObject = wpstgObject;
3598 this.action = '';
3599 this.isProcessCancelled = false;
3600 this.isProcessFinished = false;
3601 this.processTime = 0;
3602 this.processInterval = '';
3603 this.modal = null;
3604 this.disableCancelButton = false;
3605 this.title = '';
3606 this.showCancelButton = false;
3607 this.percentage = 0;
3608 this.cloneId = '';
3609 this.successModal = '';
3610 this.showProcessLogs = true;
3611 this.stagingSiteUrl = '';
3612 }
3613
3614 /**
3615 * Starts the process, initializes intervals, and modifies UI elements as needed.
3616 *
3617 * @return {void}
3618 */
3619 var _proto = WpstgProcessModal.prototype;
3620 _proto.start = function start() {
3621 var _this = this;
3622 this.showCancelButton = true;
3623 this.processInterval = setInterval(function () {
3624 if (wpstgAuthCheck.isAuthenticated || _this.action === 'wpstg_push_processing') {
3625 _this.processTime++;
3626 _this.updateElapsedTime();
3627 }
3628 }, 1000);
3629 if (this.action === 'wpstg_delete_clone') {
3630 hide('.wpstg--modal--process--logs--tail');
3631 this.showCancelButton = false;
3632 var container = WPStagingCommon.getSwalContainer();
3633 var processPercentageElement = container.querySelector('.wpstg--modal--process--percent');
3634 processPercentageElement.textContent = 100;
3635 }
3636 if (this.action === 'wpstg_cloning' || this.action === 'wpstg_push_processing') {
3637 wpstgAuthCheck.status = true;
3638 wpstgAuthCheck.start();
3639 }
3640 hide('.wpstg-prev-step-link, #wpstg-start-updating, .wpstg-loader, #wpstg-cancel-cloning, .wpstg-log-details, .wpstg-progress-bar, #wpstg-processing-header');
3641 hide('.wpstg-processing-timer, #wpstg-cancel-pushing, .wpstg-progress-bar-wrapper, #wpstg-cancel-cloning-update, #wpstg-removing-clone');
3642 }
3643
3644 /**
3645 * Stops the ongoing process, resets values, and clears intervals.
3646 *
3647 * @return {void}
3648 */;
3649 _proto.stop = function stop() {
3650 this.processTime = 0;
3651 this.modal = null;
3652 this.percentage = '';
3653 this.resetCancelChecks();
3654 clearInterval(this.processInterval);
3655 WPStagingCommon.closeSwalModal();
3656 loadingBar();
3657 hide('#wpstg-try-again, #wpstg-home-link, #wpstg-show-log-button, .wpstg-loader');
3658 if (this.action === 'wpstg_cloning' || this.action === 'wpstg_push_processing') {
3659 wpstgAuthCheck.stop();
3660 }
3661 };
3662 _proto.resetCancelChecks = function resetCancelChecks() {
3663 var _this2 = this;
3664 var element = document.getElementById('wpstg-new-clone');
3665 if (element === null) {
3666 setTimeout(function () {
3667 _this2.resetCancelChecks();
3668 }, 1000);
3669 return;
3670 }
3671 setTimeout(function () {
3672 _this2.isProcessCancelled = false;
3673 WPStaging.isCancelled = false;
3674 }, 2000);
3675 loadingBar('hidden');
3676 }
3677
3678 /**
3679 * Cancels the ongoing process if confirmed by the user.
3680 *
3681 * @return {void}
3682 */;
3683 _proto.cancelProcess = function cancelProcess() {
3684 if (confirm('Are you sure you want to cancel cloning process?')) {
3685 WPStaging.isCancelled = true;
3686 this.isProcessCancelled = true;
3687 if (this.action === 'wpstg_push_processing') {
3688 var container = WPStagingCommon.getSwalContainer();
3689 var processTitleElement = container.querySelector('.wpstg--modal--process--title');
3690 processTitleElement.textContent = 'Canceling Please wait....';
3691 this.stop();
3692 show('#wpstg-workflow');
3693 WPStaging.messages = [];
3694 } else {
3695 this.cancelCloneAction();
3696 }
3697 }
3698 }
3699
3700 /**
3701 * Sets the title and cancellation status based on the response job or status.
3702 *
3703 * @param {Object} response - The response object containing information about the process job and status.
3704 * @return {void}
3705 */;
3706 _proto.setTitle = function setTitle(response) {
3707 this.title = response.job;
3708 if (response.job === 'database' || response.job === 'jobCopyDatabaseTmp') {
3709 this.title = 'Copying Database';
3710 this.disableCancelButton = false;
3711 } else if (response.job === 'SearchReplace') {
3712 this.title = 'Processing Data';
3713 this.disableCancelButton = false;
3714 } else if (response.job === 'directories' || response.job === 'jobFileScanning') {
3715 this.title = 'Scanning Files';
3716 this.disableCancelButton = false;
3717 } else if (response.job === 'files' || response.job === 'data' || response.job === 'jobCopy' || response.job === 'jobSearchReplace') {
3718 this.title = 'Copying Files';
3719 this.disableCancelButton = false;
3720 } else if (response.job === 'Backup') {
3721 this.title = 'Backup Files Scanning';
3722 this.disableCancelButton = false;
3723 } else if (response.job === 'finish' || response.status === 'finished') {
3724 this.title = 'Process Finished';
3725 this.disableCancelButton = false;
3726 } else if (response.job === 'jobDatabaseRename') {
3727 this.title = 'Renaming Database';
3728 this.disableCancelButton = true;
3729 } else if (response.job === 'jobData') {
3730 this.title = 'Updating Database Data';
3731 this.disableCancelButton = true;
3732 }
3733 }
3734
3735 /**
3736 * Sets the stored percentage value if the provided parameter is not null.
3737 *
3738 * @param {Object} params - Parameters containing the percentage value.
3739 * @return {void}
3740 */;
3741 _proto.setPercentage = function setPercentage(params) {
3742 if (params.percentage !== null) {
3743 this.percentage = params.percentage;
3744 }
3745 }
3746
3747 /**
3748 * Initializes the process modal with specific behavior and appearance configurations.
3749 *
3750 * @return {void}
3751 */;
3752 _proto.initializeProcessModal = function initializeProcessModal() {
3753 var _this3 = this;
3754 var modal = document.querySelector('#wpstg--modal--backup--process');
3755 var html = modal.innerHTML;
3756 modal.parentNode.removeChild(modal);
3757 this.modal = {
3758 html: null,
3759 cancelBtnTxt: null,
3760 processTime: 0,
3761 instance: WPStagingCommon.getSwalModal(true, {
3762 content: 'wpstg--process--content'
3763 }).fire({
3764 html: html,
3765 cancelButtonText: 'Cancel',
3766 showCancelButton: this.showCancelButton,
3767 showConfirmButton: false,
3768 showCloseButton: false,
3769 showLoaderOnConfirm: false,
3770 allowEscapeKey: false,
3771 allowOutsideClick: false,
3772 onRender: function onRender() {
3773 var cancelButton = WPStagingCommon.getSwalContainer().getElementsByClassName('wpstg--swal2-cancel wpstg--btn--cancel')[0];
3774 var btnCancel = cancelButton.cloneNode(true);
3775 cancelButton.parentNode.replaceChild(btnCancel, cancelButton);
3776 btnCancel.addEventListener('click', function () {
3777 _this3.cancelProcess();
3778 });
3779 }
3780 })
3781 };
3782 this.start();
3783 }
3784
3785 /**
3786 * Sets the content of the process modal based on the stored title, percentage, and cancellation status.
3787 *
3788 * @return {void}
3789 */;
3790 _proto.setProcessModal = function setProcessModal() {
3791 var container = WPStagingCommon.getSwalContainer();
3792 var cancelButton = container.getElementsByClassName('wpstg--swal2-cancel wpstg--btn--cancel')[0];
3793 var processTitleElement = container.querySelector('.wpstg--modal--process--title');
3794 var processPercentageElement = container.querySelector('.wpstg--modal--process--percent');
3795 processTitleElement.textContent = this.title;
3796 processPercentageElement.textContent = this.percentage;
3797 cancelButton.disabled = this.disableCancelButton;
3798 }
3799
3800 /**
3801 * Opens and initializes a process modal with the provided data and parameters.
3802 *
3803 * @param {Object|undefined} data - Data related to the process.
3804 * @param {Object} params - Parameters for configuring the process modal.
3805 * @param {boolean} [showLogs=false] - Whether to display logs in the modal.
3806 * @param {boolean} [showCancelButton=true] - Whether to show the cancel button in the modal.
3807 * @return {void}
3808 */;
3809 _proto.openProcessModal = function openProcessModal(data, params, showLogs, showCancelButton) {
3810 if (showLogs === void 0) {
3811 showLogs = false;
3812 }
3813 if (showCancelButton === void 0) {
3814 showCancelButton = true;
3815 }
3816 if (!this.isProcessCancelled && !WPStaging.isCancelled) {
3817 if (data !== undefined) {
3818 this.action = data.action;
3819 this.cloneId = data.cloneID;
3820 }
3821 this.showCancelButton = showCancelButton;
3822 this.showLogs = showLogs;
3823 if (!this.modal) {
3824 this.initializeProcessModal();
3825 } else {
3826 if (params.job) {
3827 this.setTitle(params);
3828 this.setPercentage(params);
3829 this.setProcessModal();
3830 if (params.job === 'finish') {
3831 this.stop();
3832 }
3833 } else {
3834 if (params.status === 'finished') {
3835 this.stop();
3836 }
3837 }
3838 }
3839 }
3840 };
3841 /**
3842 * Formats the given time duration (in seconds) into a string representation (HH:mm:ss).
3843 *
3844 * @return {string} The formatted time duration string.
3845 */
3846 _proto.formatTimeDuration = function formatTimeDuration() {
3847 return new Date(this.processTime * 1000).toISOString().slice(11, 19) + 's';
3848 }
3849
3850 /**
3851 * Updates the displayed elapsed time in the modal if a process interval is set.
3852 *
3853 * @return {void}
3854 */;
3855 _proto.updateElapsedTime = function updateElapsedTime() {
3856 if (this.processInterval !== null) {
3857 var container = WPStagingCommon.getSwalContainer();
3858 var elapsedTimeElement = container.querySelector('.wpstg--modal--process--elapsed-time');
3859 elapsedTimeElement.textContent = this.formatTimeDuration();
3860 }
3861 };
3862 /**
3863 * Determines the corresponding cancellation action name based on the current action.
3864 *
3865 * @return {string|undefined} The cancellation action name or undefined if no match is found.
3866 */
3867 _proto.getCancelCloneAction = function getCancelCloneAction() {
3868 var _this4 = this;
3869 var actions = [{
3870 name: 'wpstg_cloning',
3871 cancel: 'wpstg_cancel_clone'
3872 }, {
3873 name: 'wpstg_reset',
3874 cancel: 'wpstg_cancel_update'
3875 }, {
3876 name: 'wpstg_update',
3877 cancel: 'wpstg_cancel_update'
3878 }, {
3879 name: 'wpstg_push_processing',
3880 cancel: 'wpstg_cancel_push_processing'
3881 }];
3882 if (this.action !== '') {
3883 var result = actions.find(function (action) {
3884 return action.name === _this4.action;
3885 });
3886 return result.cancel;
3887 }
3888 }
3889
3890 /**
3891 * Cancels the ongoing clone action if there is one, using a fetch request.
3892 * If the cancellation is successful, it stops the action and optionally reloads the page.
3893 * If there are further actions or the cancellation is not successful, it retries the cancellation process recursively.
3894 *
3895 * @return {void}
3896 */;
3897 _proto.cancelCloneAction = function cancelCloneAction() {
3898 var _this5 = this;
3899 if (this.action) {
3900 fetch(this.wpstgObject.ajaxUrl, {
3901 method: 'POST',
3902 credentials: 'same-origin',
3903 body: new URLSearchParams({
3904 action: this.getCancelCloneAction(),
3905 accessToken: this.wpstgObject.accessToken,
3906 nonce: this.wpstgObject.nonce,
3907 clone: this.cloneId
3908 }),
3909 headers: {
3910 'Content-Type': 'application/x-www-form-urlencoded'
3911 }
3912 }).then(function (response) {
3913 if (response.ok) {
3914 return response.json();
3915 }
3916 return Promise.reject(response);
3917 }).then(function (response) {
3918 if (response && 'undefined' !== typeof response["delete"] && response["delete"] === 'finished' || response === true) {
3919 _this5.stop();
3920 WPStaging.loadOverview();
3921 WPStaging.messages = [];
3922 }
3923 if (response !== true) {
3924 _this5.cancelCloneAction();
3925 }
3926 })["catch"](function (error) {
3927 console.log(_this5.wpstgObject.i18n['somethingWentWrong'], error);
3928 });
3929 }
3930 }
3931
3932 /**
3933 * Initializes the success modal with the provided parameters and displays it.
3934 *
3935 * @param {Object} params - The parameters for configuring the success modal content.
3936 * @return {void}
3937 */;
3938 _proto.initializeSuccessModal = function initializeSuccessModal(params) {
3939 var _this6 = this;
3940 this.successModal = this.setSuccessModalContent(params);
3941 WPStagingCommon.getSwalModal(true, {
3942 confirmButton: 'wpstg--btn--confirm wpstg-green-button wpstg-button wpstg-link-btn wpstg-100-width'
3943 }).fire({
3944 'icon': 'success',
3945 'html': this.successModal.innerHTML,
3946 'confirmButtonText': 'Close',
3947 'showCancelButton': false,
3948 'showConfirmButton': true,
3949 'allowOutsideClick': false
3950 }).then(function (result) {
3951 if (result.value) {
3952 WPStagingCommon.closeSwalModal();
3953 hide('.wpstg-loader');
3954 WPStaging.messages = [];
3955 if (_this6.action === 'wpstg_push_processing') {
3956 location.reload();
3957 }
3958 _this6.action = '';
3959 }
3960 });
3961 if (this.showProcessLogs) {
3962 show('.wpstg--modal--download--logs--wrapper');
3963 }
3964 hide('.wpstg-loader');
3965 if (this.action !== 'wpstg_delete_clone') {
3966 WPStaging.loadOverview();
3967 }
3968 }
3969
3970 /**
3971 * Sets the content of the success modal based on the provided parameters.
3972 *
3973 * @param {Object} params - The parameters for configuring the modal content.
3974 * @param {string|null} params.title - The title to be displayed in the modal.
3975 * @param {string|null|undefined} params.body - The body content of the modal.
3976 * @returns {HTMLElement} The modified modal element.
3977 */;
3978 _proto.setSuccessModalContent = function setSuccessModalContent(params) {
3979 var modal = document.getElementById('wpstg--modal--backup--download');
3980 if (params.title !== null) {
3981 modal.innerHTML = modal.innerHTML.replace('{title}', params.title);
3982 }
3983 if (this.showProcessLogs) {
3984 modal.innerHTML = modal.innerHTML.replace('{btnTxtLog}', '<span style="text-decoration: underline">Show Logs</span>');
3985 }
3986 if (params.body !== null && typeof params.body !== 'undefined') {
3987 var messageBody = params.body;
3988 if (this.stagingSiteUrl !== null) {
3989 messageBody += '<br><strong><a href="' + this.stagingSiteUrl + '" target="_blank" id="wpstg-clone-url">' + this.stagingSiteUrl + '</a></strong>';
3990 }
3991 modal.innerHTML = modal.innerHTML.replace('{text}', messageBody);
3992 } else {
3993 modal.innerHTML = modal.innerHTML.replace('{text}', '');
3994 }
3995 return modal;
3996 }
3997
3998 /**
3999 * Opens a success modal after successfully cloning process.
4000 *
4001 * @param {Object} params - The parameters for initializing the success modal.
4002 * @param {boolean} [showLogs=false] - Whether to display process logs in the modal.
4003 * @param {string|null} [siteUrl=null] - The URL of the staging site, if applicable.
4004 * @return {void}
4005 */;
4006 _proto.openSuccessModal = function openSuccessModal(params, showLogs, siteUrl) {
4007 if (showLogs === void 0) {
4008 showLogs = false;
4009 }
4010 if (siteUrl === void 0) {
4011 siteUrl = null;
4012 }
4013 this.stagingSiteUrl = siteUrl;
4014 this.showProcessLogs = showLogs;
4015 this.initializeSuccessModal(params);
4016 };
4017 return WpstgProcessModal;
4018 }();
4019
4020 var BackupPluginsNotice = /*#__PURE__*/function () {
4021 function BackupPluginsNotice(wpstgObject) {
4022 if (wpstgObject === void 0) {
4023 wpstgObject = wpstg;
4024 }
4025 this.wpstgObject = wpstgObject;
4026 this.wpstgBackupNoticeCloseButton = null;
4027 this.wpstgBackupNoticeReminderButton = null;
4028 this.init();
4029 }
4030 var _proto = BackupPluginsNotice.prototype;
4031 _proto.init = function init() {
4032 var _this = this;
4033 document.addEventListener('DOMContentLoaded', function () {
4034 _this.wpstgBackupNoticeCloseButton = document.getElementById('wpstg-backup-plugin-notice-close');
4035 _this.wpstgBackupNoticeReminderButton = document.getElementById('wpstg-backup-plugin-notice-remind-me');
4036 _this.addEvent();
4037 });
4038 };
4039 _proto.addEvent = function addEvent() {
4040 var _this2 = this;
4041 if (this.wpstgBackupNoticeCloseButton !== null) {
4042 this.wpstgBackupNoticeCloseButton.addEventListener('click', function () {
4043 _this2.closeBackupPluginNotice();
4044 });
4045 }
4046 if (this.wpstgBackupNoticeReminderButton !== null) {
4047 this.wpstgBackupNoticeReminderButton.addEventListener('click', function () {
4048 _this2.closeBackupPluginNotice('wpstg_backup_plugin_notice_remind_me');
4049 });
4050 }
4051 };
4052 _proto.closeBackupPluginNotice = function closeBackupPluginNotice(action) {
4053 if (action === void 0) {
4054 action = 'wpstg_backup_plugin_notice_close';
4055 }
4056 fetch(this.wpstgObject.ajaxUrl, {
4057 method: 'POST',
4058 credentials: 'same-origin',
4059 body: new URLSearchParams({
4060 action: action,
4061 nonce: this.wpstgObject.nonce
4062 }),
4063 headers: {
4064 'Content-Type': 'application/x-www-form-urlencoded'
4065 }
4066 }).then(function (response) {
4067 if (response.ok) {
4068 return response.json();
4069 }
4070 }).then(function (data) {
4071 if (data.success) {
4072 qs('.wpstg-backup-plugin-notice-container').style.opacity = 0;
4073 }
4074 })["catch"](function (error) {
4075 qs('.wpstg-backup-plugin-notice-container').style.opacity = 0;
4076 });
4077 };
4078 return BackupPluginsNotice;
4079 }();
4080 new BackupPluginsNotice();
4081
4082 var WPStaging$1 = function ($) {
4083 var that = {
4084 isCancelled: false,
4085 isFinished: false,
4086 getLogs: false,
4087 time: 1,
4088 executionTime: false,
4089 progressBar: 0,
4090 cloneExcludeFilters: null,
4091 directoryNavigator: null,
4092 tableSelector: null,
4093 notyf: null,
4094 areAllTablesChecked: true,
4095 handleDisplayDependencies: handleDisplayDependencies,
4096 handleToggleElement: handleToggleElement,
4097 handleCopyPaste: handleCopyPaste,
4098 handleCopyToClipboard: handleCopyToClipboard,
4099 messages: [],
4100 requestType: '',
4101 modal: {
4102 instance: '',
4103 processTime: 0,
4104 processInterval: '',
4105 currentJob: ''
4106 }
4107 };
4108 that.wpstgProcessModal = new WpstgProcessModal();
4109 var cache = {
4110 elements: []
4111 };
4112 var ajaxSpinner;
4113
4114 /**
4115 * Get / Set Cache for Selector
4116 * @param {String} selector
4117 * @return {*}
4118 */
4119 cache.get = function (selector) {
4120 // It is already cached!
4121 if ($.inArray(selector, cache.elements) !== -1) {
4122 return cache.elements[selector];
4123 }
4124
4125 // Create cache and return
4126 cache.elements[selector] = jQuery(selector);
4127 return cache.elements[selector];
4128 };
4129
4130 /**
4131 * Refreshes given cache
4132 * @param {String} selector
4133 */
4134 cache.refresh = function (selector) {
4135 selector.elements[selector] = jQuery(selector);
4136 };
4137
4138 /**
4139 * Show and Log Error Message
4140 * @param {String} message
4141 */
4142 var showError = function showError(message) {
4143 cache.get('#wpstg-try-again').css('display', 'inline-block');
4144 cache.get('#wpstg-cancel-cloning').text('Reset');
4145 cache.get('#wpstg-resume-cloning').show();
4146 cache.get('#wpstg-error-wrapper').show();
4147 cache.get('#wpstg-error-details').show().html(message);
4148 cache.get('.wpstg-loading-bar-container').css('visibility', 'hidden');
4149 cache.get('.wpstg-loader').hide();
4150 $('.wpstg--modal--process--generic-problem').show().html(message);
4151
4152 // Error event information for Staging
4153 $.ajax({
4154 url: ajaxurl,
4155 type: 'POST',
4156 dataType: 'json',
4157 data: {
4158 'action': 'wpstg_staging_job_error',
4159 'accessToken': wpstg.accessToken,
4160 'nonce': wpstg.nonce,
4161 'error_message': message
4162 }
4163 });
4164 };
4165
4166 /**
4167 * Show warning during cloning or push process when closing tab or browser, or changing page
4168 * @param {beforeunload} event
4169 * @return {null}
4170 */
4171 that.warnIfClosingDuringProcess = function (event) {
4172 // 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?"
4173 event.returnValue = 'You MUST leave this window open while cloning/pushing. Please wait...';
4174 return null;
4175 };
4176
4177 /**
4178 *
4179 * @param response the error object
4180 * @param prependMessage Overwrite default error message at beginning
4181 * @param appendMessage Overwrite default error message at end
4182 * @returns void
4183 */
4184
4185 var showAjaxFatalError = function showAjaxFatalError(response, prependMessage, appendMessage) {
4186 prependMessage = prependMessage ? prependMessage + '<br/><br/>' : 'Something went wrong! <br/><br/>';
4187 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.';
4188 if (response === false) {
4189 showError(prependMessage + ' Error: No response.' + appendMessage);
4190 window.removeEventListener('beforeunload', WPStaging$1.warnIfClosingDuringProcess);
4191 return;
4192 }
4193 if (typeof response.error !== 'undefined' && response.error) {
4194 console.error(response.message);
4195 showError(prependMessage + ' Error: ' + response.message + appendMessage);
4196 window.removeEventListener('beforeunload', WPStaging$1.warnIfClosingDuringProcess);
4197 return;
4198 }
4199 };
4200
4201 /** Hide and reset previous thrown visible errors */
4202 var resetErrors = function resetErrors() {
4203 cache.get('#wpstg-error-details').hide().html('');
4204 };
4205
4206 /**
4207 * Common Elements
4208 */
4209 var elements = function elements() {
4210 var $workFlow = cache.get('#wpstg-workflow');
4211 var urlSpinner = ajaxurl.replace('/admin-ajax.php', '') + '/images/spinner';
4212 var timer;
4213 if (2 < window.devicePixelRatio) {
4214 urlSpinner += '-2x';
4215 }
4216 urlSpinner += '.gif';
4217 ajaxSpinner = '<img src=\'\'' + urlSpinner + '\' alt=\'\' class=\'ajax-spinner general-spinner\' />';
4218 $workFlow
4219 // Check / Un-check All Database Tables New
4220 .on('click', '.wpstg-button-unselect', function (e) {
4221 e.preventDefault();
4222 if (false === that.areAllTablesChecked) {
4223 cache.get('#wpstg_select_tables_cloning .wpstg-db-table').prop('selected', 'selected');
4224 cache.get('.wpstg-button-unselect').text('Unselect All');
4225 cache.get('.wpstg-db-table-checkboxes').prop('checked', true);
4226 that.areAllTablesChecked = true;
4227 } else {
4228 cache.get('#wpstg_select_tables_cloning .wpstg-db-table').prop('selected', false);
4229 cache.get('.wpstg-button-unselect').text('Select All');
4230 cache.get('.wpstg-db-table-checkboxes').prop('checked', false);
4231 that.areAllTablesChecked = false;
4232 }
4233 })
4234
4235 // Check the max length of the clone name and if the clone name already exists
4236 .on('keyup', '#wpstg-new-clone-id', function () {
4237 // Hide previous errors
4238 document.getElementById('wpstg-error-details').style.display = 'none';
4239
4240 // This request was already sent, clear it up!
4241 if ('number' === typeof timer) {
4242 clearInterval(timer);
4243 }
4244
4245 // Early bail if site name is empty
4246 if (this.value === undefined || this.value === '') {
4247 cache.get('#wpstg-new-clone-id').removeClass('wpstg-error-input');
4248 cache.get('#wpstg-start-cloning').removeAttr('disabled');
4249 cache.get('#wpstg-clone-id-error').text('').hide();
4250 return;
4251 }
4252
4253 // Convert the site name to directory name (slugify the site name to create directory name)
4254 var cloneDirectoryName = WPStagingCommon.slugify(this.value);
4255 timer = setTimeout(function () {
4256 ajax({
4257 action: 'wpstg_check_clone',
4258 accessToken: wpstg.accessToken,
4259 nonce: wpstg.nonce,
4260 directoryName: cloneDirectoryName
4261 }, function (response) {
4262 if (response.status === 'success') {
4263 cache.get('#wpstg-new-clone-id').removeClass('wpstg-error-input');
4264 cache.get('#wpstg-start-cloning').removeAttr('disabled');
4265 cache.get('#wpstg-clone-id-error').text('').hide();
4266 } else {
4267 cache.get('#wpstg-new-clone-id').addClass('wpstg-error-input');
4268 cache.get('#wpstg-start-cloning').prop('disabled', true);
4269 cache.get('#wpstg-clone-id-error').text(response.message).show();
4270 }
4271 });
4272 }, 500);
4273 })
4274 // Restart cloning process
4275 .on('click', '#wpstg-start-cloning', function () {
4276 resetErrors();
4277 that.isCancelled = false;
4278 that.progressBar = 0;
4279 }).on('input', '#wpstg-new-clone-id', function () {
4280 if ($('#wpstg-clone-directory').length < 1) {
4281 return;
4282 }
4283 var slug = WPStagingCommon.slugify(this.value).substring(0, 16);
4284 var $targetDir = $('#wpstg-use-target-dir');
4285 var $targetUri = $('#wpstg-use-target-hostname');
4286 var path = $targetDir.data('base-path');
4287 var uri = $targetUri.data('base-uri');
4288 if (path) {
4289 path = path.replace(/\/+$/g, '') + '/' + slug + '/';
4290 }
4291 if (uri) {
4292 uri = uri.replace(/\/+$/g, '') + '/' + slug;
4293 }
4294 $('.wpstg-use-target-dir--value').text(path);
4295 $('.wpstg-use-target-hostname--value').text(uri);
4296 $targetDir.attr('data-path', path);
4297 $targetUri.attr('data-uri', uri);
4298 $('#wpstg_clone_dir').attr('placeholder', path);
4299 $('#wpstg_clone_hostname').attr('placeholder', uri);
4300 }).on('input', '#wpstg_clone_hostname', function () {
4301 if ($(this).val() === '' || validateTargetHost()) {
4302 $('#wpstg_clone_hostname_error').remove();
4303 return;
4304 }
4305 if (!validateTargetHost() && !$('#wpstg_clone_hostname_error').length) {
4306 $('#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>');
4307 }
4308 });
4309 cloneActions();
4310 };
4311
4312 /* @returns {boolean} */
4313 var validateTargetHost = function validateTargetHost() {
4314 var the_domain = $('#wpstg_clone_hostname').val();
4315 if (the_domain === '') {
4316 return true;
4317 }
4318 var reg = /^http(s)?:\/\/.*$/;
4319 if (reg.test(the_domain) === false) {
4320 return false;
4321 }
4322 return true;
4323 };
4324
4325 /**
4326 * Clone actions
4327 */
4328 var cloneActions = function cloneActions() {
4329 var $workFlow = cache.get('#wpstg-workflow');
4330 $workFlow
4331 // Cancel cloning
4332 .on('click', '#wpstg-cancel-cloning', function () {
4333 if (!confirm('Are you sure you want to cancel cloning process?')) {
4334 return false;
4335 }
4336 var $this = $(this);
4337 $('#wpstg-try-again, #wpstg-home-link').hide();
4338 $this.prop('disabled', true);
4339 that.isCancelled = true;
4340 that.progressBar = 0;
4341 $('#wpstg-processing-status').text('Please wait...this can take up a while.');
4342 $('.wpstg-loader, #wpstg-show-log-button').hide();
4343 $this.parent().append(ajaxSpinner);
4344 cancelCloning();
4345 })
4346 // Resume cloning
4347 .on('click', '#wpstg-resume-cloning', function () {
4348 resetErrors();
4349 var $this = $(this);
4350 $('#wpstg-try-again, #wpstg-home-link').hide();
4351 that.isCancelled = false;
4352 $('#wpstg-processing-status').text('Try to resume cloning process...');
4353 $('#wpstg-error-details').hide();
4354 $('.wpstg-loader').show();
4355 $this.parent().append(ajaxSpinner);
4356 that.startCloning();
4357 })
4358 // Cancel update cloning
4359 .on('click', '#wpstg-cancel-cloning-update', function () {
4360 resetErrors();
4361 var $this = $(this);
4362 $('#wpstg-try-again, #wpstg-home-link').hide();
4363 $this.prop('disabled', true);
4364 that.isCancelled = true;
4365 $('#wpstg-cloning-result').text('Please wait...this can take up a while.');
4366 $('.wpstg-loader, #wpstg-show-log-button').hide();
4367 $this.parent().append(ajaxSpinner);
4368 cancelCloningUpdate();
4369 })
4370 // Restart cloning
4371 .on('click', '#wpstg-restart-cloning', function () {
4372 resetErrors();
4373 var $this = $(this);
4374 $('#wpstg-try-again, #wpstg-home-link').hide();
4375 $this.prop('disabled', true);
4376 that.isCancelled = true;
4377 $('#wpstg-cloning-result').text('Please wait...this can take up a while.');
4378 $('.wpstg-loader, #wpstg-show-log-button').hide();
4379 $this.parent().append(ajaxSpinner);
4380 restart();
4381 })
4382 // Delete clone - confirmation
4383 .on('click', '.wpstg-remove-clone[data-clone]', function (e) {
4384 resetErrors();
4385 e.preventDefault();
4386 $workFlow.removeClass('active');
4387 cache.get('.wpstg-loader').show();
4388 var cloneData = $(this).data('clone');
4389 var stagingSiteName = $(this).data('name');
4390 ajax({
4391 action: 'wpstg_confirm_delete_clone',
4392 accessToken: wpstg.accessToken,
4393 nonce: wpstg.nonce,
4394 clone: $(this).data('clone')
4395 }, function (response) {
4396 WPStagingCommon.getSwalModal(true, {
4397 popup: 'wpstg-swal-popup wpstg-centered-modal wpstg-delete-staging-site-modal',
4398 content: 'wpstg--process--content'
4399 }).fire({
4400 title: 'Delete staging site "' + stagingSiteName + '"',
4401 icon: 'error',
4402 html: response,
4403 width: '100%',
4404 focusConfirm: false,
4405 confirmButtonText: 'Delete',
4406 confirmButtonColor: '#e01e5a',
4407 showCancelButton: true,
4408 onRender: function onRender() {
4409 var wpstgUnselectAllTables = document.getElementById('wpstg-unselect-all-tables');
4410 var wpstgUnselectAllTablesId = document.getElementById('wpstg-unselect-all-tables-id');
4411 if (wpstgUnselectAllTables !== null) {
4412 wpstgUnselectAllTables.addEventListener('click', function (e) {
4413 if (that.areAllTablesChecked === false) {
4414 cache.get('#wpstg_select_tables_cloning .wpstg-db-table').prop('selected', 'selected');
4415 cache.get('#wpstgUnselectAllTablesId').text('Unselect All');
4416 wpstgUnselectAllTablesId.textContent = 'Unselect All';
4417 cache.get('.wpstg-db-table-checkboxes').prop('checked', true);
4418 that.areAllTablesChecked = true;
4419 } else {
4420 cache.get('#wpstg_select_tables_cloning .wpstg-db-table').prop('selected', false);
4421 cache.get('#wpstgUnselectAllTablesId').text('Select All');
4422 wpstgUnselectAllTablesId.textContent = 'Select All';
4423 cache.get('.wpstg-db-table-checkboxes').prop('checked', false);
4424 that.areAllTablesChecked = false;
4425 }
4426 });
4427 }
4428 var swalContainer = document.querySelector('.wpstg--swal2-html-container');
4429 swalContainer.classList.remove('wpstg--swal2-html-container');
4430 var _deleteButton = document.querySelector('.wpstg--swal2-confirm');
4431 _deleteButton.style.background = '#e01e5a';
4432 document.querySelector('.wpstg--swal2-x-mark-line-left').style.background = '#e01e5a';
4433 document.querySelector('.wpstg--swal2-x-mark-line-right').style.background = '#e01e5a';
4434 document.querySelector('.wpstg--swal2-icon.wpstg--swal2-error').style.borderColor = '#e01e5a';
4435 var _btnCancel = WPStagingCommon.getSwalContainer().getElementsByClassName('wpstg--swal2-cancel wpstg--btn--cancel')[0];
4436 var btnCancel = _btnCancel.cloneNode(true);
4437 _btnCancel.parentNode.replaceChild(btnCancel, _btnCancel);
4438 btnCancel.addEventListener('click', function (e) {
4439 WPStagingCommon.closeSwalModal();
4440 that.modal.instance = null;
4441 cache.get('.wpstg-loader').removeClass('wpstg-finished');
4442 cache.get('.wpstg-loader').hide();
4443 });
4444 }
4445 }).then(function (result) {
4446 if (result.value) {
4447 var deleteDirectory = document.querySelector('#deleteDirectory:checked');
4448 var deleteDir = '';
4449 var excludedTables = [];
4450 if (deleteDirectory !== null) {
4451 deleteDir = deleteDirectory.getAttribute('data-deletepath');
4452 }
4453 $('.wpstg-db-table input:not(:checked)').each(function () {
4454 excludedTables.push(this.name);
4455 });
4456
4457 // WPStagingCommon.closeSwalModal();
4458 that.modal.instance = null;
4459 var params = {
4460 'job': 'delete'
4461 };
4462 that.wpstgProcessModal.openProcessModal({
4463 'action': 'wpstg_delete_clone',
4464 'cloneID': cloneData
4465 }, params, false, false);
4466 deleteClone(cloneData, deleteDir, excludedTables);
4467 }
4468 });
4469 }, 'HTML');
4470 })
4471 // Delete clone - confirmed
4472 .on('click', '#wpstg-remove-clone', function (e) {
4473 resetErrors();
4474 e.preventDefault();
4475 cache.get('.wpstg-loader').show();
4476 deleteClone($(this).data('clone'));
4477 })
4478 // Cancel deleting clone
4479 .on('click', '#wpstg-cancel-removing', function (e) {
4480 e.preventDefault();
4481 $('.wpstg-clone').removeClass('active');
4482 cache.get('#wpstg-removing-clone').html('');
4483 })
4484 // Update
4485 .on('click', '.wpstg-execute-clone', function (e) {
4486 e.preventDefault();
4487 var clone = $(this).data('clone');
4488 that.cloneExcludeFilters = null;
4489 ajax({
4490 action: 'wpstg_scanning',
4491 clone: clone,
4492 accessToken: wpstg.accessToken,
4493 nonce: wpstg.nonce
4494 }, function (response) {
4495 if (response.length < 1) {
4496 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.');
4497 }
4498 var jsonResponse = tryParseJson(response);
4499 if (jsonResponse !== false && jsonResponse.success === false) {
4500 showErrorModal(jsonResponse);
4501 return;
4502 }
4503 $workFlow.html(response);
4504 // register check disk space function for clone update process.
4505 checkDiskSpace();
4506 that.directoryNavigator = new WpstgDirectoryNavigation('#wpstg-directories-listing', wpstg, that.notyf);
4507 that.directoryNavigator.countSelectedFiles();
4508 that.tableSelector = new WpstgTableSelection('#wpstg-scanning-db', '#wpstg-workflow', '#wpstg_network_clone', '#wpstg_select_tables_cloning', wpstg, that.notyf);
4509 that.tableSelector.countSelectedTables();
4510 that.cloneExcludeFilters = new WpstgExcludeFilters();
4511 that.switchStep(2);
4512 }, 'HTML');
4513 }).on('click', '#wpstg-update-cloning-site-button', function (e) {
4514 window.open(that.data.cloneHostname, '_blank');
4515 })
4516 // Reset Clone
4517 .on('click', '.wpstg-reset-clone', function (e) {
4518 e.preventDefault();
4519 var clone = $(this).data('clone');
4520 var resetModal = new WpstgResetModal(clone);
4521 resetModal.setNetworkClone($(this).data('network') === 'yes');
4522 var promise = resetModal.showModal();
4523 that.areAllTablesChecked = true;
4524 promise.then(function (result) {
4525 if (result.value) {
4526 var dirNavigator = resetModal.getDirectoryNavigator();
4527 var tableSelector = resetModal.getTableSelector();
4528 var exclFilters = resetModal.getExcludeFilters().getExcludeFilters();
4529 var includedTables = '';
4530 var excludedTables = '';
4531 var selectedTablesWithoutPrefix = '';
4532 var allTablesExcluded = false;
4533 if (tableSelector !== null) {
4534 includedTables = tableSelector.getIncludedTables();
4535 excludedTables = tableSelector.getExcludedTables();
4536 selectedTablesWithoutPrefix = tableSelector.getSelectedTablesWithoutPrefix();
4537 }
4538 if (includedTables.length > excludedTables.length) {
4539 includedTables = '';
4540 } else if (excludedTables.length > includedTables.length) {
4541 excludedTables = '';
4542 allTablesExcluded = includedTables === '';
4543 }
4544 resetClone(clone, {
4545 includedTables: includedTables,
4546 excludedTables: excludedTables,
4547 allTablesExcluded: allTablesExcluded,
4548 selectedTablesWithoutPrefix: selectedTablesWithoutPrefix,
4549 excludeSizeRules: encodeURIComponent(exclFilters.sizes),
4550 excludeGlobRules: encodeURIComponent(exclFilters.globs),
4551 excludedDirectories: dirNavigator.getExcludedDirectories(),
4552 extraDirectories: dirNavigator.getExtraDirectoriesRootOnly()
4553 });
4554 }
4555 });
4556 return;
4557 });
4558 };
4559
4560 /**
4561 * Ajax Requests
4562 * @param Object data
4563 * @param Function callback
4564 * @param string dataType
4565 * @param bool showErrors
4566 * @param int tryCount
4567 * @param float incrementRatio
4568 */
4569 var ajax = function ajax(data, callback, dataType, showErrors, tryCount, incrementRatio) {
4570 if (incrementRatio === void 0) {
4571 incrementRatio = null;
4572 }
4573 if ('undefined' === typeof dataType) {
4574 dataType = 'json';
4575 }
4576 if (false !== showErrors) {
4577 showErrors = true;
4578 }
4579 tryCount = 'undefined' === typeof tryCount ? 0 : tryCount;
4580 var retryLimit = 5;
4581 var retryTimeout = 10000 * tryCount;
4582 incrementRatio = parseInt(incrementRatio);
4583 if (!isNaN(incrementRatio)) {
4584 retryTimeout *= incrementRatio;
4585 }
4586 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>';
4587 $.ajax({
4588 url: ajaxurl + '?action=wpstg_processing&_=' + Date.now() / 1000,
4589 type: 'POST',
4590 dataType: dataType,
4591 cache: false,
4592 data: data,
4593 error: function () {
4594 var _error = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(xhr, textStatus, errorThrown) {
4595 var result, helpContent, errorCode;
4596 return _regeneratorRuntime().wrap(function _callee$(_context) {
4597 while (1) switch (_context.prev = _context.next) {
4598 case 0:
4599 if (!(WPStaging$1.requestType === 'wpstg_cloning')) {
4600 _context.next = 13;
4601 break;
4602 }
4603 _context.next = 3;
4604 return WPStagingCommon.checkMemoryExhaustion(WPStaging$1.requestType);
4605 case 3:
4606 result = _context.sent;
4607 helpContent = '<br/><br/><button class="wpstg-btn wpstg-primary-btn wpstg-report-issue-button" type="button">CONTACT US</button> for help in solving this issue.';
4608 if (wpstg.isPro) {
4609 helpContent = '<br/><br/>Read <a target="_blank" href="' + WPStagingCommon.memoryExhaustArticleLink + '">this article</a> for solving this issue.<br/><br/>Please contact WP Staging support if you need further assistance.';
4610 }
4611 if (!(result !== false)) {
4612 _context.next = 13;
4613 break;
4614 }
4615 window.removeEventListener('beforeunload', WPStaging$1.warnIfClosingDuringProcess);
4616 WPStaging$1.requestType = '';
4617 // Refetch staging sites and stop all processing
4618 cache.get('.wpstg-loader').hide();
4619 loadOverview();
4620 WPStagingCommon.showErrorModal(result.message + '.' + helpContent);
4621 return _context.abrupt("return");
4622 case 13:
4623 // try again after 10 seconds
4624 tryCount++;
4625 if (tryCount <= retryLimit) {
4626 console.log('RETRYING ' + tryCount + '/' + retryLimit);
4627 setTimeout(function () {
4628 ajax(data, callback, dataType, showErrors, tryCount, incrementRatio);
4629 return;
4630 }, retryTimeout);
4631 } else {
4632 WPStaging$1.requestType = '';
4633 console.log('RETRYING LIMIT');
4634 errorCode = 'undefined' === typeof xhr.status ? 'Unknown' : xhr.status;
4635 showError('Fatal Error: ' + errorCode + ' ' + errorMsgFooter);
4636 }
4637 case 15:
4638 case "end":
4639 return _context.stop();
4640 }
4641 }, _callee);
4642 }));
4643 function error(_x, _x2, _x3) {
4644 return _error.apply(this, arguments);
4645 }
4646 return error;
4647 }(),
4648 success: function success(data) {
4649 if ('function' === typeof callback) {
4650 callback(data);
4651 }
4652 },
4653 statusCode: {
4654 404: function _() {
4655 if (tryCount >= retryLimit) {
4656 showError('Error 404 - Can\'t find ajax request URL! ' + errorMsgFooter);
4657 }
4658 },
4659 500: function _() {
4660 if (tryCount >= retryLimit) {
4661 showError('Fatal Error 500 - Internal server error while processing the request! ' + errorMsgFooter);
4662 }
4663 },
4664 504: function _() {
4665 if (tryCount > retryLimit) {
4666 showError('Error 504 - It seems your server is rate limiting ajax requests. Please try to resume after a minute. ' + errorMsgFooter);
4667 }
4668 },
4669 502: function _() {
4670 if (tryCount >= retryLimit) {
4671 showError('Error 502 - It seems your server is rate limiting ajax requests. Please try to resume after a minute. ' + errorMsgFooter);
4672 }
4673 },
4674 503: function _() {
4675 if (tryCount >= retryLimit) {
4676 showError('Error 503 - It seem your server is rate limiting ajax requests. Please try to resume after a minute. ' + errorMsgFooter);
4677 }
4678 },
4679 429: function _() {
4680 if (tryCount >= retryLimit) {
4681 showError('Error 429 - It seems your server is rate limiting ajax requests. Please try to resume after a minute. ' + errorMsgFooter);
4682 }
4683 },
4684 403: function _() {
4685 if (tryCount >= retryLimit) {
4686 showError('Refresh page or login again! The process should be finished successfully. \n\ ');
4687 }
4688 },
4689 400: function _() {
4690 if (tryCount >= retryLimit) {
4691 showError('Error 400: ' + '<strong>It looks like you have been logged out.</strong><br/><br/> <a href=\'/wp-login.php\' target=\'_blank\' id="wpstg-login-link">Log in again and try again!</a>');
4692 }
4693 }
4694 }
4695 });
4696 };
4697
4698 /**
4699 * Next / Previous Step Clicks to Navigate Through Staging Job
4700 */
4701 var stepButtons = function stepButtons() {
4702 var $workFlow = cache.get('#wpstg-workflow');
4703 $workFlow
4704 // Next Button
4705 .on('click', '.wpstg-next-step-link', function (e) {
4706 e.preventDefault();
4707 var $this = $(this);
4708 if ($('#wpstg_clone_hostname').length && !validateTargetHost()) {
4709 $('#wpstg_clone_hostname').focus();
4710 return false;
4711 }
4712 if ($this.data('action') === 'wpstg_update' || $this.data('action') === 'wpstg_reset') {
4713 // Update / Reset Clone - confirmed
4714 if ($this.data('action') === 'wpstg_update') {
4715 var selectedSite = $this;
4716 var selectedSiteWorkFlow = $workFlow;
4717 var selectedAction = $this.data('action');
4718 WPStagingCommon.getSwalModal(false, {
4719 popup: 'wpstg-update-staging-site-modal wpstg-swal-popup wpstg-centered-modal',
4720 content: 'wpstg--process--content'
4721 }).fire({
4722 title: 'Do you want to update the staging site?',
4723 icon: 'warning',
4724 html: '<div class="wpstg-confirm-text-line-height wpstg-mt-10px">This will overwrite 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> ' + 'Unselect all tables and folders that you do not want to overwrite.<br>Do not cancel the update process! This could destroy 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>',
4725 width: '610px',
4726 focusConfirm: false,
4727 confirmButtonText: 'Update',
4728 showCancelButton: true,
4729 onRender: function onRender() {
4730 var swalContainer = document.querySelector('.wpstg--swal2-html-container');
4731 swalContainer.classList.remove('wpstg--swal2-html-container');
4732 var _btnCancel = WPStagingCommon.getSwalContainer().getElementsByClassName('wpstg--swal2-cancel wpstg--btn--cancel')[0];
4733 var btnCancel = _btnCancel.cloneNode(true);
4734 _btnCancel.parentNode.replaceChild(btnCancel, _btnCancel);
4735 btnCancel.addEventListener('click', function (e) {
4736 WPStagingCommon.closeSwalModal();
4737 });
4738 }
4739 }).then(function (result) {
4740 if (result.value) {
4741 var selectedSiteDbCheck = document.querySelector('#wpstg-ext-db');
4742 if (selectedAction === 'wpstg_cloning') {
4743 if (selectedSiteDbCheck.checked) {
4744 verifyExternalDatabase(selectedSite, selectedSiteWorkFlow);
4745 return;
4746 }
4747 }
4748 WPStagingCommon.closeSwalModal();
4749 proceedCloning(selectedSite, selectedSiteWorkFlow);
4750 }
4751 });
4752 return false;
4753 }
4754 }
4755 if ($this.attr('disabled')) {
4756 return false;
4757 }
4758 if ($this.data('action') === 'wpstg_cloning') {
4759 // Verify External Database If Checked and Not Skipped
4760 if ($('#wpstg-ext-db').is(':checked')) {
4761 verifyExternalDatabase($this, $workFlow);
4762 return;
4763 }
4764 }
4765 proceedCloning($this, $workFlow);
4766 })
4767 // Previous Button
4768 .on('click', '.wpstg-prev-step-link', function (e) {
4769 e.preventDefault();
4770 cache.get('.wpstg-loader').hide();
4771 cache.get('.wpstg-loader').removeClass('wpstg-finished');
4772 loadOverview();
4773 });
4774 };
4775
4776 /**
4777 * Check if clone destination dir is writable
4778 */
4779 var isWritableCloneDestinationDir = function isWritableCloneDestinationDir() {
4780 return new Promise(function (resolve) {
4781 ajax({
4782 action: 'wpstg_is_writable_clone_destination_dir',
4783 accessToken: wpstg.accessToken,
4784 nonce: wpstg.nonce,
4785 cloneDir: $('#wpstg_clone_dir').val()
4786 }, function (response) {
4787 if (response.success) {
4788 cache.get('.wpstg-loader').hide();
4789 resolve(true);
4790 } else {
4791 var _response$data;
4792 showError('Something went wrong! Error: ' + ((_response$data = response.data) == null ? void 0 : _response$data.message));
4793 cache.get('.wpstg-loader').hide();
4794 document.getElementById('wpstg-error-wrapper').scrollIntoView();
4795 resolve(false);
4796 }
4797 }, 'json', false);
4798 });
4799 };
4800
4801 /**
4802 * Get Excluded (Unchecked) Database Tables
4803 * Not used anymore!
4804 * @return {Array}
4805 */
4806 var getExcludedTables = function getExcludedTables() {
4807 var excludedTables = [];
4808 $('.wpstg-db-table input:not(:checked)').each(function () {
4809 excludedTables.push(this.name);
4810 });
4811 return excludedTables;
4812 };
4813
4814 /**
4815 * Verify External Database for Cloning
4816 */
4817 var verifyExternalDatabase = function verifyExternalDatabase($this, workflow) {
4818 cache.get('.wpstg-loader').show();
4819 ajax({
4820 action: 'wpstg_database_verification',
4821 accessToken: wpstg.accessToken,
4822 nonce: wpstg.nonce,
4823 databaseUser: cache.get('#wpstg_db_username').val(),
4824 databasePassword: cache.get('#wpstg_db_password').val(),
4825 databaseServer: cache.get('#wpstg_db_server').val(),
4826 databaseDatabase: cache.get('#wpstg_db_database').val(),
4827 databaseSsl: cache.get('#wpstg_db_ssl').is(':checked')
4828 }, function (response) {
4829 // Undefined Error
4830 if (false === response) {
4831 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> ');
4832 cache.get('.wpstg-loader').hide();
4833 return;
4834 }
4835
4836 // Throw Error
4837 if ('undefined' === typeof response.success) {
4838 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> ');
4839 cache.get('.wpstg-loader').hide();
4840 return;
4841 }
4842 if (response.success) {
4843 cache.get('.wpstg-loader').hide();
4844 proceedCloning($this, workflow);
4845 return;
4846 }
4847 if (response.error_type === 'comparison') {
4848 cache.get('.wpstg-loader').hide();
4849 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>';
4850 response.checks.forEach(function (x) {
4851 var icon = '<span class="wpstg-css-tick"></span>';
4852 if (x.production !== x.staging) {
4853 icon = '<span class="wpstg-css-cross"></span>';
4854 }
4855 render += '<tr><td>' + x.name + '</td><td>' + x.production + '</td><td>' + x.staging + '</td><td>' + icon + '</td></tr>';
4856 });
4857 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>';
4858 WPStagingCommon.getSwalModal(true, {
4859 popup: 'wpstg-swal-popup wpstg-db-comparison-modal wpstg-centered-modal'
4860 }).fire({
4861 title: 'Different Database Properties',
4862 icon: 'warning',
4863 html: render,
4864 width: '650px',
4865 focusConfirm: false,
4866 confirmButtonText: 'Proceed',
4867 showCancelButton: true
4868 }).then(function (result) {
4869 if (result.value) {
4870 proceedCloning($this, workflow);
4871 }
4872 });
4873 return;
4874 }
4875 WPStagingCommon.getSwalModal(true).fire({
4876 title: 'Different Database Properties',
4877 icon: 'error',
4878 html: response.message,
4879 focusConfirm: true,
4880 confirmButtonText: 'Ok',
4881 showCancelButton: false
4882 });
4883 cache.get('.wpstg-loader').hide();
4884 }, 'json', false);
4885 };
4886
4887 /**
4888 * Get Cloning Step Data
4889 */
4890 var getCloningData = function getCloningData() {
4891 if ('wpstg_cloning' !== that.data.action && 'wpstg_update' !== that.data.action && 'wpstg_reset' !== that.data.action) {
4892 return;
4893 }
4894 that.data.cloneID = new Date().getTime().toString();
4895 if ('wpstg_update' === that.data.action) {
4896 that.data.cloneID = $('#wpstg-new-clone-id').data('clone');
4897 }
4898 that.data.cloneName = $('#wpstg-new-clone-id').val() || that.data.cloneID;
4899 if (that.directoryNavigator !== null) {
4900 that.data.excludedDirectories = encodeURIComponent(that.directoryNavigator.getExcludedDirectories());
4901 that.data.extraDirectories = encodeURIComponent(that.directoryNavigator.getExtraDirectoriesRootOnly());
4902 }
4903 that.data.excludeGlobRules = '';
4904 that.data.excludeSizeRules = '';
4905 if (that.cloneExcludeFilters instanceof WpstgExcludeFilters) {
4906 var rules = that.cloneExcludeFilters.getExcludeFilters();
4907 that.data.excludeGlobRules = encodeURIComponent(rules.globs);
4908 that.data.excludeSizeRules = encodeURIComponent(rules.sizes);
4909 }
4910 that.data.includedTables = '';
4911 that.data.excludedTables = '';
4912 that.data.allTablesExcluded = false;
4913 if (that.tableSelector !== null) {
4914 that.data.includedTables = that.tableSelector.getIncludedTables();
4915 that.data.excludedTables = that.tableSelector.getExcludedTables();
4916 that.data.selectedTablesWithoutPrefix = that.tableSelector.getSelectedTablesWithoutPrefix();
4917 }
4918 if (that.data.includedTables.length > that.data.excludedTables.length) {
4919 that.data.includedTables = '';
4920 } else if (that.data.excludedTables.length > that.data.includedTables.length) {
4921 that.data.excludedTables = '';
4922 that.data.allTablesExcluded = that.data.includedTables === '';
4923 }
4924 that.data.databaseServer = $('#wpstg_db_server').val();
4925 that.data.databaseUser = $('#wpstg_db_username').val();
4926 that.data.databasePassword = $('#wpstg_db_password').val();
4927 that.data.databaseDatabase = $('#wpstg_db_database').val();
4928 that.data.databasePrefix = $('#wpstg_db_prefix').val();
4929 that.data.databaseSsl = $('#wpstg_db_ssl').is(':checked');
4930 var cloneDir = $('#wpstg_clone_dir').val();
4931 that.data.cloneDir = encodeURIComponent($.trim(cloneDir));
4932 that.data.cloneHostname = $('#wpstg_clone_hostname').val();
4933 that.data.cronDisabled = $('#wpstg_disable_cron').is(':checked');
4934 that.data.emailsAllowed = $('#wpstg_allow_emails').is(':checked');
4935 that.data.networkClone = $('#wpstg_network_clone').is(':checked');
4936 that.data.uploadsSymlinked = $('#wpstg_symlink_upload').is(':checked');
4937 that.data.cleanPluginsThemes = $('#wpstg-clean-plugins-themes').is(':checked');
4938 that.data.cleanUploadsDir = $('#wpstg-clean-uploads').is(':checked');
4939 };
4940 var proceedCloning = function proceedCloning($this, workflow) {
4941 if ($this.data('action') === 'wpstg_cloning') {
4942 isWritableCloneDestinationDir().then(function (result) {
4943 if (!result) {
4944 return;
4945 }
4946 runCloningSteps($this, workflow);
4947 });
4948 } else {
4949 runCloningSteps($this, workflow);
4950 }
4951 };
4952 var runCloningSteps = function runCloningSteps($this, workflow) {
4953 var animatedLoader = cache.get('.wpstg-loading-bar-container');
4954 animatedLoader.css('visibility', 'visible');
4955
4956 // Prepare data
4957 that.data = {
4958 action: $this.data('action'),
4959 accessToken: wpstg.accessToken,
4960 nonce: wpstg.nonce
4961 };
4962
4963 // Cloning data
4964 getCloningData();
4965 sendCloningAjax(workflow);
4966 };
4967 var sendCloningAjax = function sendCloningAjax(workflow) {
4968 var animatedLoader = cache.get('.wpstg-loading-bar-container');
4969
4970 // Send ajax request
4971 ajax(that.data, function (response) {
4972 // Undefined Error
4973 if (false === response) {
4974 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> ');
4975 }
4976 if (response.length < 1) {
4977 animatedLoader.css('visibility', 'hidden');
4978 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> ');
4979 }
4980 var jsonResponse = tryParseJson(response);
4981 if (jsonResponse !== false && jsonResponse.success === false) {
4982 animatedLoader.css('visibility', 'hidden');
4983 showErrorModal(jsonResponse);
4984 return;
4985 }
4986 animatedLoader.css('visibility', 'hidden');
4987 workflow.html(response);
4988 that.cloneExcludeFilters = null;
4989 if (that.data.action === 'wpstg_scanning') {
4990 that.areAllTablesChecked = true;
4991 that.directoryNavigator = new WpstgDirectoryNavigation('#wpstg-directories-listing', wpstg, that.notyf);
4992 that.tableSelector = new WpstgTableSelection('#wpstg-scanning-db', '#wpstg-workflow', '#wpstg_network_clone', '#wpstg_select_tables_cloning', wpstg);
4993 that.switchStep(2);
4994 that.cloneExcludeFilters = new WpstgExcludeFilters();
4995 that.directoryNavigator.countSelectedFiles();
4996 that.tableSelector.countSelectedTables();
4997 } else if (that.data.action === 'wpstg_cloning' || that.data.action === 'wpstg_update' || that.data.action === 'wpstg_reset') {
4998 that.switchStep(3);
4999 }
5000
5001 // Start cloning
5002 that.startCloning();
5003 }, 'HTML');
5004 };
5005 var showErrorModal = function showErrorModal(response) {
5006 var errorModal = new WpstgModal('wpstg_modal_error', wpstg);
5007 errorModal.show(Object.assign({
5008 title: 'Error',
5009 icon: 'error',
5010 html: wpstg.i18n['somethingWentWrong'] + (response.message !== undefined ? '<br/>' + response.message : ''),
5011 width: '500px',
5012 confirmButtonText: 'Ok',
5013 showCancelButton: false,
5014 customClass: {
5015 confirmButton: 'wpstg--btn--confirm wpstg-blue-primary wpstg-button wpstg-link-btn',
5016 cancelButton: 'wpstg--btn--cancel wpstg-blue-primary wpstg-link-btn',
5017 actions: 'wpstg--modal--actions',
5018 popup: 'wpstg-swal-popup wpstg-centered-modal'
5019 },
5020 buttonsStyling: false,
5021 reverseButtons: true
5022 }, response.swalOptions), {
5023 type: response.type
5024 });
5025 };
5026 var tryParseJson = function tryParseJson(json) {
5027 // early bail if not string
5028 if (!json) {
5029 return false;
5030 }
5031 try {
5032 var object = JSON.parse(json);
5033 if (object && typeof object === 'object') {
5034 return object;
5035 }
5036 } catch (e) {
5037 // do nothing on catch
5038 }
5039 return false;
5040 };
5041 var resetClone = function resetClone(clone, excludeOptions) {
5042 that.data = {
5043 action: 'wpstg_reset',
5044 accessToken: wpstg.accessToken,
5045 nonce: wpstg.nonce,
5046 cloneID: clone
5047 };
5048 that.data = _extends({}, that.data, excludeOptions);
5049 var $workFlow = cache.get('#wpstg-workflow');
5050 sendCloningAjax($workFlow);
5051 };
5052
5053 /**
5054 * Loads Overview (first step) of Staging Job
5055 */
5056 var loadOverview = function loadOverview() {
5057 var $workFlow = cache.get('#wpstg-workflow');
5058 var animatedLoader = cache.get('.wpstg-loading-bar-container');
5059 animatedLoader.css('visibility', 'visible');
5060 ajax({
5061 action: 'wpstg_overview',
5062 accessToken: wpstg.accessToken,
5063 nonce: wpstg.nonce
5064 }, function (response) {
5065 if (response.length < 1) {
5066 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.');
5067 }
5068 cache.get('.wpstg-current-step');
5069 animatedLoader.css('visibility', 'hidden');
5070 $workFlow.html(response);
5071 }, 'HTML');
5072 that.switchStep(1);
5073 cache.get('.wpstg-step3-cloning').show();
5074 cache.get('.wpstg-step3-pushing').hide();
5075 };
5076
5077 /**
5078 * Load Tabs
5079 */
5080 var tabs = function tabs() {
5081 cache.get('#wpstg-workflow').on('click', '.wpstg-tab-header', function (e) {
5082 e.preventDefault();
5083 var $this = $(this);
5084 var $section = cache.get($this.data('id'));
5085 $this.toggleClass('expand');
5086 $section.slideToggle();
5087 var tabTriangle = $this.find('.wpstg-tab-triangle');
5088 if ($this.hasClass('expand')) {
5089 tabTriangle.removeClass('wpstg-no-icon');
5090 tabTriangle.text('');
5091 tabTriangle.addClass('wpstg-rotate-90');
5092 } else {
5093 tabTriangle.removeClass('wpstg-rotate-90');
5094 }
5095 });
5096 };
5097
5098 /**
5099 * Delete Clone
5100 * @param {String} clone
5101 * @param {String} deleteDir
5102 * @param {array} excludedTables
5103 */
5104 var deleteClone = function deleteClone(clone, deleteDir, excludedTables) {
5105 ajax({
5106 action: 'wpstg_delete_clone',
5107 clone: clone,
5108 accessToken: wpstg.accessToken,
5109 nonce: wpstg.nonce,
5110 excludedTables: excludedTables,
5111 deleteDir: deleteDir
5112 }, function (response) {
5113 if (response) {
5114 showAjaxFatalError(response);
5115
5116 // Finished
5117 if ('undefined' !== typeof response["delete"] && (response["delete"] === 'finished' || response["delete"] === 'unfinished')) {
5118 if (response["delete"] === 'finished' && response.error === undefined) {
5119 $('.wpstg-clone[data-clone-id="' + clone + '"]').remove();
5120 }
5121
5122 // No staging site message is also of type/class .wpstg-class but hidden
5123 // We have just excluded that from search when counting no of clones
5124 if ($('#wpstg-existing-clones .wpstg-clone').length < 1) {
5125 cache.get('#wpstg-existing-clones').find('h3').text('');
5126 cache.get('#wpstg-no-staging-site-results').show();
5127 }
5128 cache.get('.wpstg-loader').hide();
5129 // finish modal popup
5130 if (wpstg.i18n.wpstg_delete_clone !== null && response["delete"] === 'finished') {
5131 var params = {
5132 'status': 'finished'
5133 };
5134 that.wpstgProcessModal.openProcessModal({
5135 'action': 'wpstg_delete_clone',
5136 'cloneID': clone
5137 }, params, false, false);
5138 WPStagingCommon.getSwalModal(true, {
5139 confirmButton: 'wpstg--btn--confirm wpstg-green-button wpstg-button wpstg-link-btn wpstg-100-width'
5140 }).fire({
5141 'icon': 'success',
5142 'html': '<div style="display:block"><h2 style="color: #565656;">' + wpstg.i18n.wpstg_delete_clone.title + '</h2></div>',
5143 'confirmButtonText': 'Close',
5144 'showCancelButton': false,
5145 'showConfirmButton': true
5146 }).then(function (result) {
5147 if (result.value) {
5148 WPStagingCommon.closeSwalModal();
5149 loadingBar('hidden');
5150 }
5151 });
5152 }
5153 return;
5154 }
5155 }
5156 // continue
5157 if (true !== response) {
5158 deleteClone(clone, deleteDir, excludedTables);
5159 return;
5160 }
5161 });
5162 };
5163
5164 /**
5165 * Cancel Cloning Process
5166 */
5167 var cancelCloning = function cancelCloning() {
5168 that.timer('stop');
5169 if (true === that.isFinished) {
5170 return true;
5171 }
5172 ajax({
5173 action: 'wpstg_cancel_clone',
5174 clone: that.data.cloneID,
5175 accessToken: wpstg.accessToken,
5176 nonce: wpstg.nonce
5177 }, function (response) {
5178 if (response && 'undefined' !== typeof response["delete"] && response["delete"] === 'finished') {
5179 cache.get('.wpstg-loader').hide();
5180 // Load overview
5181 loadOverview();
5182 return;
5183 }
5184 if (true !== response) {
5185 // continue
5186 cancelCloning();
5187 return;
5188 }
5189
5190 // Load overview
5191 loadOverview();
5192 });
5193 };
5194
5195 /**
5196 * Cancel Cloning Process
5197 */
5198 var cancelCloningUpdate = function cancelCloningUpdate() {
5199 if (true === that.isFinished) {
5200 return true;
5201 }
5202 ajax({
5203 action: 'wpstg_cancel_update',
5204 clone: that.data.cloneID,
5205 accessToken: wpstg.accessToken,
5206 nonce: wpstg.nonce
5207 }, function (response) {
5208 if (response && 'undefined' !== typeof response["delete"] && response["delete"] === 'finished') {
5209 // Load overview
5210 loadOverview();
5211 return;
5212 }
5213 if (true !== response) {
5214 // continue
5215 cancelCloningUpdate();
5216 return;
5217 }
5218
5219 // Load overview
5220 loadOverview();
5221 });
5222 };
5223
5224 /**
5225 * Cancel Cloning Process
5226 */
5227 var restart = function restart() {
5228 if (true === that.isFinished) {
5229 return true;
5230 }
5231 ajax({
5232 action: 'wpstg_restart',
5233 // clone: that.data.cloneID,
5234 accessToken: wpstg.accessToken,
5235 nonce: wpstg.nonce
5236 }, function (response) {
5237 if (response && 'undefined' !== typeof response["delete"] && response["delete"] === 'finished') {
5238 // Load overview
5239 loadOverview();
5240 return;
5241 }
5242 if (true !== response) {
5243 // continue
5244 cancelCloningUpdate();
5245 return;
5246 }
5247
5248 // Load overview
5249 loadOverview();
5250 });
5251 };
5252
5253 /**
5254 * Append the log to the logging window
5255 * @param string log
5256 * @return void
5257 */
5258 var getLogs = function getLogs(log) {
5259 if (Array.isArray(log)) {
5260 log.forEach(function (logMessage) {
5261 if (logMessage !== null) {
5262 if (!that.messages.find(function (_ref) {
5263 var message = _ref.message;
5264 return message === logMessage.message;
5265 })) {
5266 that.messages.push(logMessage);
5267 var $logsContainer = $('.wpstg--modal--process--logs');
5268 var msgClass = "wpstg--modal--process--msg--" + (logMessage.type.toLowerCase() || 'info');
5269 $logsContainer.append("<p class=\"" + msgClass + "\">[" + (logMessage.type || 'info') + "] - [" + logMessage.date + "] - " + logMessage.message + "</p>");
5270 }
5271 }
5272 });
5273 } else {
5274 if (!that.messages.find(function (_ref2) {
5275 var message = _ref2.message;
5276 return message === log.message;
5277 })) {
5278 that.messages.push(log);
5279 var $logsContainer = $('.wpstg--modal--process--logs');
5280 var msgClass = "wpstg--modal--process--msg--" + (log.type.toLowerCase() || 'info');
5281 $logsContainer.append("<p class=\"" + msgClass + "\">[" + (log.type || 'info') + "] - [" + log.date + "] - " + log.message + "</p>");
5282 }
5283 }
5284 document.querySelectorAll('.wpstg--modal--process--logs').forEach(function (element) {
5285 element.scrollTop = element.scrollHeight;
5286 });
5287 };
5288
5289 /**
5290 * Check disk space
5291 * @return string json
5292 */
5293 var checkDiskSpace = function checkDiskSpace() {
5294 cache.get('#wpstg-check-space').on('click', function (e) {
5295 cache.get('.wpstg-loader').show();
5296 var excludedDirectories = encodeURIComponent(that.directoryNavigator.getExcludedDirectories());
5297 var extraDirectories = encodeURIComponent(that.directoryNavigator.getExtraDirectoriesRootOnly());
5298 ajax({
5299 action: 'wpstg_check_disk_space',
5300 accessToken: wpstg.accessToken,
5301 nonce: wpstg.nonce,
5302 excludedDirectories: excludedDirectories,
5303 extraDirectories: extraDirectories
5304 }, function (response) {
5305 if (false === response) {
5306 cache.get('#wpstg-clone-id-error').text('Can not detect required disk space').show();
5307 cache.get('.wpstg-loader').hide();
5308 return;
5309 }
5310
5311 // Show required disk space
5312 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();
5313 cache.get('.wpstg-loader').hide();
5314 }, 'json', false);
5315 });
5316 };
5317
5318 /**
5319 * Show or hide animated loading icon
5320 * @param isLoading bool
5321 */
5322 var isLoading = function isLoading(_isLoading) {
5323 if (!_isLoading || _isLoading === false) {
5324 cache.get('.wpstg-loader').hide();
5325 } else {
5326 cache.get('.wpstg-loader').show();
5327 }
5328 };
5329
5330 /**
5331 * Count up processing execution time
5332 * @param string status
5333 * @return html
5334 */
5335 that.timer = function (status) {
5336 if (status === 'stop') {
5337 var time = that.time;
5338 that.time = 1;
5339 clearInterval(that.executionTime);
5340 return that.convertSeconds(time);
5341 }
5342 that.executionTime = setInterval(function () {
5343 if (null !== document.getElementById('wpstg-processing-timer')) {
5344 document.getElementById('wpstg-processing-timer').innerHTML = 'Elapsed Time: ' + that.convertSeconds(that.time);
5345 }
5346 that.time++;
5347 if (status === 'stop') {
5348 that.time = 1;
5349 clearInterval(that.executionTime);
5350 }
5351 }, 1000);
5352 };
5353
5354 /**
5355 * Convert seconds to hourly format
5356 * @param int seconds
5357 * @return string
5358 */
5359 that.convertSeconds = function (seconds) {
5360 var date = new Date(null);
5361 date.setSeconds(seconds); // specify value for SECONDS here
5362 return date.toISOString().substr(11, 8);
5363 };
5364
5365 /**
5366 * Start Cloning Process
5367 * @type {Function}
5368 */
5369 that.startCloning = function () {
5370 resetErrors();
5371
5372 // Register function for checking disk space
5373 checkDiskSpace();
5374 if ('wpstg_cloning' !== that.data.action && 'wpstg_update' !== that.data.action && 'wpstg_reset' !== that.data.action) {
5375 return;
5376 }
5377 that.isCancelled = false;
5378
5379 // Start the process
5380 start();
5381
5382 // Functions
5383 // Start
5384 function start() {
5385 cache.get('.wpstg-loader').show();
5386 cache.get('#wpstg-cancel-cloning').text('Cancel');
5387 cache.get('#wpstg-resume-cloning').hide();
5388 cache.get('#wpstg-error-details').hide();
5389
5390 // Clone Database
5391 setTimeout(function () {
5392 // cloneDatabase();
5393 window.addEventListener('beforeunload', WPStaging$1.warnIfClosingDuringProcess);
5394 processing();
5395 }, wpstg.delayReq);
5396 }
5397
5398 /**
5399 * Start ajax processing
5400 * @return string
5401 */
5402 var processing = function processing() {
5403 if (true === that.isCancelled) {
5404 window.removeEventListener('beforeunload', WPStaging$1.warnIfClosingDuringProcess);
5405 return false;
5406 }
5407 isLoading(true);
5408 var excludedDirectories = '';
5409 var extraDirectories = '';
5410 if (that.directoryNavigator !== null) {
5411 excludedDirectories = that.directoryNavigator.getExcludedDirectories();
5412 extraDirectories = that.directoryNavigator.getExtraDirectoriesRootOnly();
5413 }
5414
5415 // Show logging window
5416
5417 WPStaging$1.requestType = 'wpstg_cloning';
5418 WPStaging$1.ajax({
5419 action: 'wpstg_processing',
5420 accessToken: wpstg.accessToken,
5421 nonce: wpstg.nonce,
5422 excludedTables: getExcludedTables(),
5423 excludedDirectories: encodeURIComponent(excludedDirectories),
5424 extraDirectories: encodeURIComponent(extraDirectories)
5425 }, function (response) {
5426 showAjaxFatalError(response);
5427
5428 // Add Log messages
5429 if ('undefined' !== typeof response.last_msg && response.last_msg) {
5430 getLogs(response.last_msg);
5431 }
5432 // Continue processing
5433 if (false === response.status) {
5434 progressBar(response);
5435 setTimeout(function () {
5436 processing();
5437 }, wpstg.delayReq);
5438 } else if (true === response.status && 'finished' !== response.status) {
5439 cache.get('#wpstg-error-details').hide();
5440 cache.get('#wpstg-error-wrapper').hide();
5441 progressBar(response);
5442 processing();
5443 } else if ('finished' === response.status || 'undefined' !== typeof response.job_done && response.job_done) {
5444 window.removeEventListener('beforeunload', WPStaging$1.warnIfClosingDuringProcess);
5445 WPStaging$1.requestType = '';
5446 finish(response);
5447 }
5448 }, 'json', false);
5449 };
5450
5451 // Finish
5452 function finish(response) {
5453 if (true === that.getLogs) {
5454 getLogs();
5455 }
5456 progressBar(response);
5457
5458 // Add Log
5459 if ('undefined' !== typeof response.last_msg) {
5460 getLogs(response.last_msg);
5461 }
5462 if (wpstg.i18n[that.data.action] !== null) {
5463 that.wpstgProcessModal.openSuccessModal(wpstg.i18n[that.data.action], true, response.url);
5464 }
5465 }
5466
5467 /**
5468 * Add percentage progress bar
5469 * @param object response
5470 * @return {Boolean}
5471 */
5472 var progressBar = function progressBar(response, restart) {
5473 if (response !== null) {
5474 that.wpstgProcessModal.openProcessModal(that.data, response, true);
5475 }
5476 };
5477 };
5478 that.switchStep = function (step) {
5479 cache.get('.wpstg-current-step').removeClass('wpstg-current-step');
5480 cache.get('.wpstg-step' + step).addClass('wpstg-current-step');
5481 };
5482 that.checkUserDbPermissions = function checkUserDbPermissions(operationType) {
5483 return new Promise(function (resolve) {
5484 WPStaging$1.ajax({
5485 action: 'wpstg_check_user_permissions',
5486 accessToken: wpstg.accessToken,
5487 nonce: wpstg.nonce,
5488 type: operationType
5489 }, function (response) {
5490 if (response.success) {
5491 resolve(true);
5492 } else {
5493 WPStagingCommon.getSwalModal(true, {
5494 container: 'wpstg-swal-push-container'
5495 }).fire({
5496 title: '',
5497 icon: 'warning',
5498 html: response.data.message,
5499 width: '750px',
5500 focusConfirm: false,
5501 confirmButtonText: 'Proceed',
5502 showCancelButton: true
5503 }).then(function (result) {
5504 if (result.isConfirmed) {
5505 resolve(true);
5506 }
5507 });
5508 $('#wpstg-db-permission-show-full-message').click(function () {
5509 $('#wpstg-permission-info-output').html($('#wpstg-permission-info-data').html());
5510 });
5511 }
5512 }, 'json', false);
5513 });
5514 };
5515
5516 /**
5517 * Initiation
5518 * @type {Function}
5519 */
5520 that.init = function () {
5521 loadOverview();
5522 elements();
5523 stepButtons();
5524 tabs();
5525 WPStagingCommon.listenTooltip();
5526 new WpstgMainMenu();
5527 new WpstgCloneStaging();
5528 new WpstgCloningAdvanceSettings();
5529 new WpstgProcessModal();
5530 that.notyf = new Notyf({
5531 duration: 10000,
5532 position: {
5533 x: 'center',
5534 y: 'bottom'
5535 },
5536 dismissible: true,
5537 types: [{
5538 type: 'warning',
5539 background: 'orange',
5540 icon: false
5541 }]
5542 });
5543 };
5544 /**
5545 * Ajax call
5546 * @type {ajax}
5547 */
5548 that.ajax = ajax;
5549 that.showError = showError;
5550 that.getLogs = getLogs;
5551 that.loadOverview = loadOverview;
5552 return that;
5553 }(jQuery);
5554 jQuery(document).ready(function () {
5555 WPStaging$1.init();
5556 // This is necessary to make WPStaging var accessible in WP Staging PRO js script
5557 window.WPStaging = WPStaging$1;
5558 });
5559
5560 /**
5561 * Report Issue modal
5562 */
5563 jQuery(document).ready(function ($) {
5564 $('body').on('click', '.wpstg-report-issue-button', function (e) {
5565 var contactUsModal = document.querySelector('#wpstg-contact-us-modal');
5566 if (contactUsModal != null && typeof contactUsModal !== 'undefined') {
5567 show('#wpstg-contact-us-modal');
5568 new WpstgContactUs();
5569 }
5570 $('.wpstg-report-issue-form').toggleClass('wpstg-report-show');
5571 e.preventDefault();
5572 });
5573 $('body').on('click', '.wpstg-backups-report-issue-button', function (e) {
5574 $('.wpstg-report-issue-form').toggleClass('wpstg-report-show');
5575 e.preventDefault();
5576 });
5577 $('body').on('click', '#wpstg-report-cancel', function (e) {
5578 $('.wpstg-report-issue-form').removeClass('wpstg-report-show');
5579 e.preventDefault();
5580 });
5581 $('body').on('click', '#wpstg-report-submit', function (e) {
5582 var self = $(this);
5583 sendIssueReport(self, 'false');
5584 e.preventDefault();
5585 });
5586 $('body').on('click', '.wpstg--modal--process--logs--tail', function (e) {
5587 showProcessLogs();
5588 var logBtn = $(this);
5589 e.preventDefault();
5590 var container = WPStagingCommon.getSwalContainer();
5591 var $logs = $(container).find('.wpstg--modal--process--logs');
5592 $logs.toggle();
5593 if ($logs.is(':visible')) {
5594 logBtn.text(wpstg.i18n.hideLogs);
5595 container.childNodes[0].style.width = '97%';
5596 container.style['z-index'] = 9999;
5597 } else {
5598 logBtn.text(wpstg.i18n.showLogs);
5599 container.childNodes[0].style.width = '600px';
5600 }
5601 });
5602 /*
5603 * Close Success Modal
5604 */
5605 $('body').on('click', '#wpstg-success-button', function (e) {
5606 e.preventDefault();
5607 $('.wpstg-report-issue-form').removeClass('wpstg-report-show');
5608 });
5609 function sendIssueReport(button, forceSend) {
5610 if (forceSend === void 0) {
5611 forceSend = 'false';
5612 }
5613 var spinner = button.next();
5614 var email = $('.wpstg--tab--header .wpstg-report-email').val();
5615 var hosting_provider = $('.wpstg--tab--header .wpstg-report-hosting-provider').val();
5616 var message = $('.wpstg--tab--header .wpstg-report-description').val();
5617 var syslog = $('.wpstg--tab--header .wpstg-report-syslog').is(':checked');
5618 var terms = $('.wpstg--tab--header .wpstg-report-terms').is(':checked');
5619 button.attr('disabled', true);
5620 spinner.css('visibility', 'visible');
5621 $.ajax({
5622 url: ajaxurl,
5623 type: 'POST',
5624 dataType: 'json',
5625 async: true,
5626 data: {
5627 'action': 'wpstg_send_report',
5628 'accessToken': wpstg.accessToken,
5629 'nonce': wpstg.nonce,
5630 'wpstg_email': email,
5631 'wpstg_provider': hosting_provider,
5632 'wpstg_message': message,
5633 'wpstg_syslog': +syslog,
5634 'wpstg_terms': +terms,
5635 'wpstg_force_send': forceSend
5636 }
5637 }).done(function (data) {
5638 button.attr('disabled', false);
5639 spinner.css('visibility', 'hidden');
5640 if (data.errors.length > 0) {
5641 $('.wpstg-report-issue-form .wpstg-message').remove();
5642 var errorMessage = $('<div />').addClass('wpstg-message wpstg-error-message');
5643 $.each(data.errors, function (key, value) {
5644 if (value.status === 'already_submitted') {
5645 errorMessage = '';
5646 // TODO: remove default custom classes
5647 WPStagingCommon.getSwalModal(true, {
5648 container: 'wpstg-issue-resubmit-confirmation'
5649 }).fire({
5650 title: '',
5651 icon: 'warning',
5652 html: value.message,
5653 showCancelButton: true,
5654 focusConfirm: false,
5655 confirmButtonText: 'Yes',
5656 cancelButtonText: 'No'
5657 }).then(function (result) {
5658 if (result.isConfirmed) {
5659 sendIssueReport(button, 'true');
5660 }
5661 });
5662 } else {
5663 errorMessage.append('<p>' + value + '</p>');
5664 }
5665 });
5666 $('.wpstg-report-issue-form').prepend(errorMessage);
5667 } else {
5668 var successMessage = $('<div />').addClass('wpstg-message wpstg-success-message');
5669 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>');
5670 $('.wpstg--tab--header .wpstg-report-issue-form').html(successMessage);
5671 if (document.getElementById('wpstg-modal-close') === null || document.getElementById('wpstg-modal-close') === undefined) {
5672 $('.wpstg--tab--header .wpstg-success-message').append('<div class="wpstg-mt-10px wpstg-float-right"><a id="wpstg-success-button" href="#" class="wpstg--red"><span class="wpstg-ml-8px">Close</span></a></div>');
5673 }
5674
5675 // Hide message
5676 setTimeout(function () {
5677 $('.wpstg--tab--header .wpstg-report-issue-form').removeClass('wpstg-report-active');
5678 }, 2000);
5679 }
5680 });
5681 }
5682
5683 // Open/close actions drop down menu
5684 $(document).on('click', '.wpstg-dropdown>.wpstg-dropdown-toggler', function (e) {
5685 e.preventDefault();
5686 $(e.target).next('.wpstg-dropdown-menu').toggleClass('shown');
5687 $(e.target).find('.wpstg-caret').toggleClass('wpstg-caret-up');
5688 });
5689 $(document).on('click', '.wpstg-caret', function (e) {
5690 e.preventDefault();
5691 var toggler = $(e.target).closest('.wpstg-dropdown-toggler');
5692 if (toggler) {
5693 toggler.trigger('click');
5694 }
5695 });
5696
5697 // Close action drop down menu if clicked anywhere outside
5698 document.addEventListener('click', function (event) {
5699 var isClickInside = event.target.closest('.wpstg-dropdown-toggler');
5700 if (!isClickInside) {
5701 var dropDown = document.getElementsByClassName('wpstg-dropdown-menu');
5702 for (var i = 0; i < dropDown.length; i++) {
5703 dropDown[i].classList.remove('shown');
5704 }
5705 $('.wpstg-caret').removeClass('wpstg-caret-up');
5706 }
5707 });
5708
5709 // "Event info" for backup errors
5710 window.addEventListener('finishedProcessWithError', function (customEvent) {
5711 $.ajax({
5712 url: ajaxurl,
5713 type: 'POST',
5714 dataType: 'json',
5715 data: {
5716 'action': 'wpstg_job_error',
5717 'accessToken': wpstg.accessToken,
5718 'nonce': wpstg.nonce,
5719 'error_message': customEvent.detail.error,
5720 'job_id': WPStagingCommon.getJobId()
5721 }
5722 });
5723 });
5724
5725 /**
5726 * Display logs in a modal.
5727 * and avoid mixing of different processes logs
5728 * @return {void}
5729 */
5730 function showProcessLogs() {
5731 if (window.WPStaging.messages.length !== 0) {
5732 var container = WPStagingCommon.getSwalContainer();
5733 var logsContainer = container.querySelector('.wpstg--modal--process--logs');
5734 logsContainer.innerHTML = '';
5735 window.WPStaging.messages.forEach(function (message) {
5736 var msgClass = "wpstg--modal--process--msg--" + message.type.toLowerCase();
5737 var pElement = document.createElement('p');
5738 pElement.className = msgClass;
5739 pElement.textContent = "[" + message.type + "] - [" + message.date + "] - " + message.message;
5740 logsContainer.appendChild(pElement);
5741 });
5742 }
5743 }
5744 document.addEventListener('click', function (event) {
5745 if (event.target.id !== 'wpstg-login-link') {
5746 return;
5747 }
5748 event.preventDefault();
5749 window.open('/wp-login.php', '_blank');
5750 if (window.WPStaging && window.WPStaging.wpstgProcessModal) {
5751 window.WPStaging.wpstgProcessModal.stop();
5752 window.WPStaging.loadOverview();
5753 }
5754 });
5755 });
5756
5757 })();
5758 //# sourceMappingURL=wpstg-admin.js.map
5759