PluginProbe ʕ •ᴥ•ʔ
Transferito: WP Migration / 12.0.0
Transferito: WP Migration v12.0.0
trunk 11.4.0 12.0.0 13.1.0 14.0.0 14.0.11 14.0.7 14.1.0 14.1.1 14.1.2 14.1.3 14.1.4
transferito / src / Views / Assets / js / transferito.js
transferito / src / Views / Assets / js Last commit date
transferito-sentry.js 1 year ago transferito.js 1 year ago
transferito.js
3189 lines
1 (function($) {
2
3 $(document).ready(function(){
4
5 function Transferito() {
6 this.mappedStatus = null;
7 this.validated = {
8 ftp: false,
9 database: false
10 };
11 this.ftpPath = '';
12 this.localUploadComplete = {
13 database: false,
14 codebase: false
15 };
16 this.transferMethodOptions = {
17 method: '',
18 cPanelAllowed: false,
19 };
20 this.currentStatus = 'backup.completed';
21 this.backupSize = 0;
22 this.backupPercentage = {
23 codebase: 0,
24 codebaseIncrement: 0,
25 database: 0,
26 databaseIncrement: 0,
27 };
28 this.utilities = {
29 tempMigrationDetails: {
30 key: '',
31 details: {}
32 },
33 selector: $('#transferitoTemplate'),
34 modalSelector: $('#transferitoModalTemplate'),
35 migrationSteps: {
36 amount: 0,
37 currentStep: -1,
38 stepSplit: 0
39 },
40 removeTrailingSlashes: function(url) {
41 return url.replace(/\/+$/, '');
42 },
43 removeProtocols: function(host) {
44 return host.replace(/sftp:\/\/|ftp:\/\//, '');
45 },
46 getFormValues: function(object, item) {
47 if (item.name.indexOf('[]') !== -1) {
48 var key = item.name.replace('[]', '');
49 var value = item.value;
50 (!object[key]) ? object[key] = [value] : object[key].push(value);
51 } else {
52 object[item.name] = (item.value === 'on') ? true : item.value;
53 }
54 return object;
55 },
56 validateFormFields: function() {
57 var errorCount = 0;
58 $('.transferito__field-required:visible').each(function (index, formElement) {
59 var formSelector = $(formElement);
60
61 /**
62 * If the field is empty
63 * Show the error
64 */
65 if (!formSelector.val()) {
66 errorCount += 1;
67 }
68 });
69 return errorCount === 0;
70 },
71 validateURL: function() {
72 var cleanedURL = this.selector.find('#domain').val().trim().replace(/\/$/, "");
73 var domain = cleanedURL.split('//');
74 return domain.length === 2 && ['http:', 'https:'].indexOf(domain[0]) !== -1;
75 },
76 changeTemplate: function(action, nonce, extraData = {}, clearTemplate = false, callback) {
77 var self = this;
78 var data = {
79 action: action,
80 actionKey: nonce,
81 data: extraData
82 };
83
84 if (clearTemplate) {
85 this.setTemplate('');
86 }
87
88 var templateChange = $.post(ajaxurl, data, function(response) {
89 var theResponse = response.data;
90 var hasAdditionalData = theResponse.hasOwnProperty('additionalData');
91 var template = theResponse.hasOwnProperty('htmlTemplate')
92 ? theResponse.htmlTemplate
93 : '';
94 self.setTemplate(template);
95
96 /**
97 *
98 */
99 if (callback) {
100 callback(theResponse);
101 }
102
103 /**
104 * Show the legend message
105 */
106 if (hasAdditionalData) {
107 self.displayHeaderLegend(null, theResponse.additionalData.mainMessage);
108 }
109
110 });
111 templateChange.fail(function(data) {
112 self.setTemplate('Something has gone wrong - Please refresh the page and try again');
113 });
114 },
115 setTemplate: function(template, elementSelector = false, fadeInTime = 1500, customContent = false) {
116 /**
117 * If the selector isn't present
118 * Default to replace the whole screen
119 */
120 if (!elementSelector) {
121 this.selector.html(template).fadeIn(1500);
122 }
123
124 /**
125 * Replace the HTML in the specified selector
126 */
127 if (elementSelector) {
128 elementSelector.html(template).fadeIn(fadeInTime);
129
130 /**
131 * If the customContent argument has been provided
132 * Update the modal content & the relevant selector
133 */
134 if (customContent) {
135 elementSelector.find(customContent.selector).html(customContent.content);
136 }
137 }
138 },
139 loadingOnlyHTML: function() {
140 var template = '<div class="transferito__one-column-container transferito__one-column-container--no-width transferito-loader">';
141 template += '<div class="transferito-loader__icon transferito-loader__icon--no-bottom-margin"></div>';
142 template += '</div>';
143 return template;
144 },
145 loadingScreenHTML: function(message, subMessage) {
146 var template = '<div class="transferito__one-column">';
147 template += '<div class="transferito__one-column-container transferito-loader">';
148 template += '<div class="transferito-loader__icon"></div>';
149 template += '<div class="transferito-loader__text transferito-text__p1--semi-bold">';
150 template += message;
151 template += '</div>';
152
153 if (subMessage) {
154 template += '<div class="transferito-loader__text transferito-text__p1--regular">';
155 template += subMessage;
156 template += '</div>';
157 }
158
159 template += '</div>';
160 template += '</div>';
161 return template;
162 },
163 showLoadingScreen: function(message = 'Loading...', subMessage) {
164 this.selector.html(this.loadingScreenHTML(message, subMessage));
165 },
166 buildPayload: function () {
167 var self = this;
168 var formElements = [];
169
170 /**
171 * Create array of form elements that aren't hidden
172 * Include check for hidden form elements
173 */
174 $('.transferito-form-element').each(function(index, formElement) {
175 var formSelector = $(formElement),
176 isVisible = formSelector.closest('table').css('display');
177
178 if (isVisible === 'table' || isVisible === undefined) {
179 formElements.push(formElement);
180 }
181 });
182
183 /**
184 * Turn array of form elements
185 * Into object with input names as properties & input values as value
186 */
187 return $(formElements)
188 .serializeArray()
189 .reduce(function(object, item) {
190 return self.getFormValues(object, item)
191 }, {});
192 },
193 filterPayload: function(payload, allowedProperties = []) {
194 /**
195 * Check if there are keys to filter
196 */
197 if (allowedProperties.length === 0) {
198 return payload;
199 }
200
201 for (var property in payload) {
202 if (payload.hasOwnProperty(property) && !allowedProperties.includes(property)) {
203 delete payload[property];
204 }
205 }
206
207 return payload;
208 },
209 setTransferMethodOptions: function (method, cPanelAllowed) {
210 transferito.transferMethodOptions.method = method;
211 transferito.transferMethodOptions.cPanelAllowed = cPanelAllowed;
212 },
213 checkMigrationProgressSteps: function () {
214 this.migrationSteps.amount = $('.transferito-migration-progress__step').not(':hidden').length - 1;
215 this.migrationSteps.stepSplit = Math.round(100 / this.migrationSteps.amount);
216 },
217 updateCurrentMigrationProgressStep: function() {
218 this.migrationSteps.currentStep = this.migrationSteps.currentStep + 1;
219 this.updateMigrationOverviewProgressPercentage(
220 this.migrationSteps.currentStep * this.migrationSteps.stepSplit
221 );
222 },
223 calculateOverviewProgressPercentage: function (percentage) {
224 var percentageAsDecimal = (percentage / 100);
225 var stepPercentage = Math.round(this.migrationSteps.stepSplit * percentageAsDecimal);
226 var currentOverviewPercentage = this.migrationSteps.currentStep * this.migrationSteps.stepSplit;
227 var total = currentOverviewPercentage + stepPercentage;
228
229 return (total > 99) ? 100 : total;
230 },
231 updateMigrationOverviewProgressPercentage: function(percentage) {
232 $('#progressOverviewPercentage').html(percentage);
233 $('.transferito-migration-progress__bar--value').css('width', percentage + '%');
234 },
235 updateProgressStep: function(status, selector, statusChanged) {
236 /**
237 * If the status doesn't equal one of the allowed
238 */
239 if (status !== 'completed' && status !== 'active') {
240 return false;
241 }
242
243 var elementID = selector.attr('id');
244 var hiddenElementClass = 'transferito__hide-element';
245 var disabledStepClass = 'transferito-migration-progress__disabled-text';
246
247 selector.removeClass(disabledStepClass);
248
249 /**
250 * If it's active only add the class
251 */
252 if (status === 'active') {
253 /**
254 * Move the counter to the next migration step when a step has been initialised
255 */
256 if (statusChanged) {
257 /**
258 * Log event
259 */
260 this.logEvent('migrationStatus', {
261 status: elementID
262 });
263
264 this.updateCurrentMigrationProgressStep();
265 }
266
267 /**
268 * Change the static image to a spinner on this step
269 */
270 if (elementID === 'progress__finalizingWPInstall') {
271 selector
272 .find('.transferito-migration-progress__step-percent > .transferito-migration-progress__final-step')
273 .removeClass('transferito-migration-progress__final-step--static')
274 }
275 }
276
277 /**
278 * If it's completed remove the active and add the completed
279 */
280 if (status === 'completed') {
281 /**
282 * Update the overview % to 100%
283 */
284 if (elementID === 'progress__finalizingWPInstall') {
285 this.updateMigrationOverviewProgressPercentage(100);
286 }
287
288 selector.find('.transferito-migration-progress__step-icon').removeClass(hiddenElementClass);
289 selector.find('.transferito-migration-progress__step-percent').addClass(hiddenElementClass);
290 }
291 },
292 updateProgressPercentage: function(percentage, selector) {
293 /**
294 * If percentage is null
295 */
296 if (!percentage) {
297 return false;
298 }
299
300 /**
301 * Calc the overview moving percentage
302 * Then update it
303 */
304 this.updateMigrationOverviewProgressPercentage(
305 this.calculateOverviewProgressPercentage(percentage)
306 );
307
308 /**
309 * Update the percentage for the progress bar
310 */
311 selector.html(percentage);
312 },
313 hideProgressPercentage: function(selector) {
314 /**
315 * Update the percentage for the progress bar
316 */
317 selector.closest('.transferito-migration-progress__step-percent').addClass('transferito__hide-element');
318 },
319 round: function(value, precision) {
320 var multiplier = Math.pow(10, precision || 0);
321 return Math.round(value * multiplier) / multiplier;
322 },
323 saveBackupPercentage: function(key, options) {
324 transferito.backupPercentage[key] = options.percentage;
325 transferito.backupPercentage[key + 'Increment'] = this.round(options.increment);
326 },
327 updateTheBackupProgress: function(type) {
328 transferito.backupSize += transferito.backupPercentage[type + 'Increment'];
329 var archiveSize = this.round(transferito.backupSize);
330 var usedArchiveSize = archiveSize > 99 ? 99 : archiveSize;
331 this.updateProgressPercentage(usedArchiveSize, $('#backupInstallationProgressPercentage'));
332 },
333 updateTheExecBackupProgress: function(amount, initialAmount) {
334 /**
335 * If the amount is truthy
336 * & it is greater than the initialAmount then & only then my friend should we proceed
337 */
338 if (amount && amount > initialAmount) {
339 /**
340 * If the amount is greater than the backup size
341 * Then we continue -
342 * The percentage should never decrease
343 */
344 if (amount > transferito.backupSize) {
345 transferito.backupSize = amount;
346 var archiveSize = this.round(transferito.backupSize);
347 var usedArchiveSize = archiveSize > 99 ? 99 : archiveSize;
348 this.updateProgressPercentage(usedArchiveSize, $('#backupInstallationProgressPercentage'));
349 }
350 }
351 },
352 changeProgressStep: function (migrationStatus, responseData, statusChanged) {
353 /**
354 * Move the status of the step
355 */
356 this.updateProgressStep(migrationStatus.status, migrationStatus.selector, statusChanged);
357
358 /**
359 * Check that the progress property exists and that the response data is there
360 */
361 if (migrationStatus.hasOwnProperty('progress') && responseData) {
362 var percentage = responseData.hasOwnProperty('metadata') && responseData.metadata && responseData.metadata.hasOwnProperty('value')
363 ? responseData.metadata.value
364 : null;
365
366 /**
367 * Update the progress
368 */
369 this.updateProgressPercentage(percentage, migrationStatus.progressSelector);
370 }
371
372 /**
373 * If progress completion property exists
374 */
375 if (migrationStatus.hasOwnProperty('progressComplete')) {
376 this.hideProgressPercentage(migrationStatus.progressSelector);
377 }
378 },
379 displayModal: function(modalName, customModalContent) {
380 /**
381 * Log event
382 */
383 this.logEvent('modalOpened', {
384 modalName: modalName
385 });
386
387 /**
388 * Get the HTML for the modal
389 */
390 var modalHTML = $('#' + modalName).html();
391
392 /**
393 * Remove the style attribute
394 */
395 this.modalSelector.removeAttr('style');
396
397 /**
398 * Remove the hidden element
399 */
400 this.modalSelector.removeClass('transferito__hide-element');
401
402 /**
403 * Move the HTML into the modal DIV
404 */
405 this.setTemplate(modalHTML, this.modalSelector, 500, customModalContent);
406 },
407 displayFormGuideModal: function(modalName, relatedGuideName) {
408 this.displayModal(modalName);
409 $('#hostingGuideName').val(relatedGuideName);
410 },
411 closeModal: function() {
412 /**
413 * Modal Selector
414 */
415 var modalTemplate = $('#transferitoModalTemplate');
416
417 /**
418 * Remove the hidden element
419 */
420 modalTemplate.addClass('transferito__hide-element');
421
422 /**
423 * Add the loading smaller loading indicator
424 */
425 this.setTemplate('', modalTemplate);
426
427 /**
428 * Remove the style attribute
429 */
430 modalTemplate.removeAttr('style');
431 },
432 displayMigrationProgressFailure: function (selector, message) {
433
434 var elementID = selector.attr('id');
435 var hiddenElementClass = 'transferito__hide-element';
436
437 /**
438 * Change the title
439 */
440 $('#migrationProgressTitle').html('Migration Failed');
441
442 /**
443 * Change the colour to red
444 */
445 $('#overviewProgressPercentageBar').addClass('transferito-migration-progress__bar--red');
446
447 /**
448 * Add the left align class
449 */
450 selector.addClass('transferito-migration-progress__step--left-align');
451
452 /**
453 * Display the main icon
454 * Hide the progress percentage
455 * Display the warning error icon
456 */
457 selector.find('.transferito-migration-progress__step-icon')
458 .html('<div class="transferito-icon transferito-icon--exclamation-mark"></div>')
459 .addClass('transferito-migration-progress__step-icon--extended');
460 selector.find('.transferito-migration-progress__step-percent').addClass(hiddenElementClass);
461 selector.find('.transferito-migration-progress__step-icon').removeClass(hiddenElementClass);
462
463 /**
464 * Display the error container
465 * & Add the message into the error container
466 */
467 selector.find('.transferito-migration-progress__step-title > .transferito-migration-progress__error-container')
468 .removeClass(hiddenElementClass)
469 .html(message);
470 },
471 buildMappedStatus: function() {
472 return {
473 'download.backup.started': {
474 progress: true,
475 progressSelector: $('#downloadBackupProgressPercentage'),
476 previous: [],
477 status: 'active',
478 selector: $('#progress__downloadingBackup')
479 },
480 'download.backup.completed': {
481 progressComplete: true,
482 progressSelector: $('#downloadBackupProgressPercentage'),
483 previous: [],
484 status: 'completed',
485 selector: $('#progress__downloadingBackup')
486 },
487 'extract.backup.started': {
488 progress: true,
489 progressSelector: $('#extractingBackupProgressPercentage'),
490 previous: ['download.backup.completed'],
491 status: 'active',
492 selector: $('#progress__extractingBackup')
493 },
494 'extract.backup.completed': {
495 progressComplete: true,
496 progressSelector: $('#extractingBackupProgressPercentage'),
497 previous: [
498 'download.backup.completed',
499 'extract.backup.started',
500 ],
501 status: 'completed',
502 selector: $('#progress__extractingBackup')
503 },
504 'import.database.started': {
505 progress: true,
506 progressSelector: $('#installDatabaseProgressPercentage'),
507 previous: [
508 'download.backup.completed',
509 'extract.backup.started',
510 'extract.backup.completed'
511 ],
512 status: 'active',
513 selector: $('#progress__installingWordPress')
514 },
515 'import.database.completed': {
516 progressComplete: true,
517 progressSelector: $('#installDatabaseProgressPercentage'),
518 previous: [
519 'download.backup.completed',
520 'extract.backup.started',
521 'extract.backup.completed',
522 'import.database.started'
523 ],
524 status: 'completed',
525 selector: $('#progress__installingWordPress')
526 },
527 'finalize.install': {
528 progressComplete: true,
529 progressSelector: $('#installDatabaseProgressPercentage'),
530 previous: [
531 'download.backup.completed',
532 'extract.backup.started',
533 'extract.backup.completed',
534 'import.database.started',
535 'import.database.completed'
536 ],
537 status: 'active',
538 selector: $('#progress__finalizingWPInstall')
539 },
540 'completed': {
541 previous: [
542 'download.backup.completed',
543 'extract.backup.started',
544 'extract.backup.completed',
545 'import.database.started',
546 'import.database.completed',
547 'finalize.install'
548 ],
549 status: 'completed',
550 selector: $('#progress__finalizingWPInstall')
551 },
552 'completed.with.errors': {
553 previous: [
554 'download.backup.completed',
555 'extract.backup.started',
556 'extract.backup.completed',
557 'import.database.started',
558 'import.database.completed',
559 'finalize.install'
560 ],
561 status: 'completed.with.errors',
562 selector: $('#progress__finalizingWPInstall')
563 }
564 };
565 },
566 displayHeaderLegend: function(state, message) {
567 var legendSelector = $('#transferitoHeaderLegend');
568 var legendState = {
569 error: 'transferito-legend--error',
570 warning: 'transferito-legend--warning',
571 success: 'transferito-legend--success'
572 };
573 var mappedLegendState = (!state) ? '' : legendState[state];
574
575 /**
576 * Remove all classes
577 */
578 legendSelector.removeClass();
579
580 /**
581 * Add the initial legend class back
582 */
583 legendSelector.addClass('transferito-legend');
584
585 /**
586 * Add the correct class on the element - if the state exists
587 */
588 if (mappedLegendState) {
589 legendSelector.addClass(mappedLegendState);
590 }
591
592 /**
593 * Add the message to the legend
594 */
595 legendSelector.html(message);
596 },
597 hideHeaderLegend: function() {
598 $('#transferitoHeaderLegend').addClass('transferito__hide-element')
599 },
600 logEvent: function(event, eventProperties) {
601 $.post(ajaxurl, {
602 action: 'log_transferito_event',
603 event,
604 eventProperties,
605 });
606 },
607 saveTempMigrationDetails: function(details, key) {
608 this.tempMigrationDetails.details = details;
609 this.tempMigrationDetails.key = key;
610 },
611 clearTempMigrationDetails: function() {
612 this.tempMigrationDetails.details = {};
613 this.tempMigrationDetails.key = '';
614 }
615 };
616
617 /**
618 * Check the site
619 */
620 this.checkSite = function() {
621 this.utilities.changeTemplate(
622 'check_current_site',
623 $('#nonce').val(),
624 {},
625 false,
626 function (response) {
627 if (!response?.hideWelcomeScreen) {
628 transferito.utilities.displayModal('firstMigrationInformation');
629 }
630 }
631 );
632 };
633
634 /**
635 * Get the migration status
636 *
637 * @param token
638 */
639 this.getStatus = function (token) {
640 var self = this;
641 this.mappedStatus = this.utilities.buildMappedStatus();
642 $.post(ajaxurl, { action: 'status_check', token: token }, function(response) {
643
644 /**
645 * If the status is false or null
646 * Retry the status check
647 *
648 * If not process the status as normal
649 */
650 if (!response.data) {
651 self.getStatus(token);
652 } else {
653
654 console.log(response.data);
655
656 /**
657 * Check the status has the properties to not fails
658 */
659 if (response.hasOwnProperty('data') && response.data.hasOwnProperty('completed')) {
660
661 /**
662 * Check the object has the status property
663 */
664 if (response.data.hasOwnProperty('status')) {
665
666 /**
667 * Check if the status has changed
668 */
669 var statusChanged = self.currentStatus !== response.data.status;
670
671 /**
672 * Assign the status to the current status
673 */
674 self.currentStatus = response.data.status;
675
676 /**
677 * Check that the status exists
678 */
679 var migrationStatus = self.mappedStatus.hasOwnProperty(response.data.status)
680 ? self.mappedStatus[response.data.status]
681 : null;
682
683 /**
684 * If the status exist - Update it
685 */
686 if (migrationStatus) {
687 /**
688 * If the previous property exists
689 */
690 if (migrationStatus.hasOwnProperty('previous')) {
691 for (let index = 0; index < migrationStatus.previous.length; index++) {
692 var migrationPreviousStatus = self.mappedStatus[migrationStatus.previous[index]];
693
694 /**
695 * Change the progress step
696 */
697 self.utilities.changeProgressStep(migrationPreviousStatus);
698 }
699 }
700
701 /**
702 * Change the progress step
703 */
704 self.utilities.changeProgressStep(migrationStatus, response.data, statusChanged);
705 }
706 }
707
708 /**
709 * If the migration is still in progress
710 */
711 if (!response.data.completed) {
712 self.getStatus(token);
713 }
714
715 /**
716 * If the migration has completed
717 */
718 if (response.data.completed) {
719 self.utilities.hideHeaderLegend();
720 self.utilities.logEvent('migrationCompleted', {
721 completed: true
722 });
723 self.cleanUp(
724 false,
725 [],
726 false,
727 {
728 status: response.data.status
729 });
730 }
731
732 }
733 }
734
735 })
736 .fail(function(error) {
737 if (error.hasOwnProperty('status') && error.status > 501) {
738 setTimeout(function () {
739 self.getStatus(token);
740 }, 10000, self, token);
741 } else {
742
743 var migrationStatus = self.mappedStatus.hasOwnProperty(self.currentStatus)
744 ? self.mappedStatus[self.currentStatus]
745 : self.mappedStatus['download.backup.started'];
746
747 self.utilities.logEvent('failedMigration', {
748 migrationStatus: self.currentStatus,
749 errorMessage: error?.responseJSON?.data
750 });
751
752 self.cleanUp(
753 'USE_CUSTOM_ERROR_MESSAGE',
754 error.responseJSON,
755 false,
756 null,
757 migrationStatus.selector
758 );
759 }
760 });
761 };
762
763 /**
764 * Start the migration
765 *
766 * @param wpNonce
767 */
768 this.startMigration = function(wpNonce) {
769 var self = this;
770 var data = {
771 action: 'start_migration',
772 security: wpNonce
773 };
774
775 var sendFiles = $.post(ajaxurl, data, function(response) {
776 /**
777 * Show the completion screen if a local migration
778 *
779 * If not - Listen to the status updates
780 */
781 if (response.data.localMigration) {
782 self.utilities.hideHeaderLegend();
783 self.utilities.logEvent('localMigrationPartiallyCompleted', { completed: true });
784 self.cleanUp(false, [], false, {}, null, true);
785 } else {
786 self.utilities.displayHeaderLegend('success', response.data.message);
787 self.getStatus(response.data.token);
788 }
789 });
790 sendFiles.fail(function(error) {
791 self.utilities.logEvent('failedMigration', {
792 migrationStatus: 'prepareBackup',
793 errorMessage: error?.responseJSON?.data
794 });
795 self.cleanUp(
796 'USE_CUSTOM_ERROR_MESSAGE',
797 error.responseJSON,
798 false,
799 null,
800 $('#progress__prepareBackup')
801 );
802 });
803 };
804
805 /**
806 * Start to prepare the migration
807 *
808 * @param migrationDetails
809 * @param key
810 */
811 this.prepareMigration = function (migrationDetails, key) {
812 var self = this;
813 var data = {
814 action: 'preparing_transfer',
815 security: key,
816 migrationDetails: migrationDetails
817 };
818 var backup = $.post(ajaxurl, data, function(response) {
819
820 /**
821 * Change the template
822 */
823 self.utilities.setTemplate(response.data.htmlTemplate);
824
825 /**
826 * Update the legend message
827 */
828 self.utilities.displayHeaderLegend('warning', response.data.message);
829
830 /**
831 * Count how many steps exist
832 */
833 self.utilities.checkMigrationProgressSteps();
834
835 /**
836 * Set the active
837 */
838 self.utilities.updateProgressStep('active', $('#progress__prepareBackup'), true);
839
840 /**
841 * If premium is required
842 */
843 if (response.data.upgradeRequired) {
844 self.inPluginPurchase(migrationDetails, key);
845 }
846
847 /**
848 * If no premium is not required progress as normal
849 */
850 if (!response.data.upgradeRequired) {
851 /**
852 * Start the ZIP
853 */
854 if (response.data.useZipFallback) {
855 self.prepareCodebaseBackup(key);
856 }
857
858 /**
859 * If we don't use the Fallback
860 */
861 if (!response.data.useZipFallback) {
862 /**
863 * Set prepare backup to completed
864 */
865 self.utilities.updateProgressStep('completed', $('#progress__prepareBackup'));
866
867 /**
868 * Set the backup started to active
869 */
870 self.utilities.updateProgressStep('active', $('#progress__backupInstallation'), true);
871
872 /**
873 * If the DB is excluded
874 * Go straight to the codebase archive
875 */
876 if (response.data.excludeDatabase) {
877 self.archiveCreationStart(key);
878 }
879
880 /**
881 * If the DB isn't excluded
882 */
883 if (!response.data.excludeDatabase) {
884 /**
885 * Set the initial percentage for the db
886 */
887 self.utilities.saveBackupPercentage('database', {
888 percentage: response.data.databasePercentage,
889 increment: 0,
890 });
891
892 /**
893 * Start the backup process
894 */
895 self.prepareDatabaseBackup(key, response.data.useZipFallback);
896 }
897 }
898 }
899 });
900 backup.fail(function(error) {
901 var transferMethod = data.migrationDetails.transferMethod;
902
903 self.utilities.logEvent('failedMigration', {
904 migrationStatus: 'backupInstallation',
905 errorMessage: error?.responseJSON?.data
906 });
907
908 /**
909 * For cPanel migrations - Populate the modal with the current error message
910 * When the API is unable to create the FTP & DB details
911 */
912 if (transferMethod === 'cpanel') {
913 self.screenRouting(
914 'cpanelDomainSelection',
915 '',
916 '',
917 'cPanelDomainSelectFailure',
918 {
919 content: '<b>Reason:</b> ' + error?.responseJSON?.data,
920 selector: '.transferito-text__p--regular'
921 }
922 );
923 } else {
924 self.cleanUp(
925 'USE_CUSTOM_ERROR_MESSAGE',
926 error.responseJSON,
927 false,
928 null,
929 $('#progress__backupInstallation')
930 );
931 }
932
933 });
934 };
935
936 /**
937 * Prepare the file list for the archive creation
938 *
939 * @param key
940 */
941 this.prepareCodebaseBackup = function(key) {
942 var self = this;
943 var data = {
944 action: 'preparing_codebase',
945 security: key
946 };
947 var codebasePreparation = $.post(ajaxurl, data, function(response) {
948 /**
949 * Set prepare backup to completed
950 */
951 self.utilities.updateProgressStep('completed', $('#progress__prepareBackup'));
952
953 /**
954 * Set the backup started to active
955 */
956 self.utilities.updateProgressStep('active', $('#progress__backupInstallation'), true);
957
958 /**
959 * Create the Codebase percent and increment value
960 */
961 self.utilities.saveBackupPercentage('codebase', {
962 percentage: response.data.codebasePercentage,
963 increment: (response.data.codebasePercentage / response.data.amount),
964 });
965
966 /**
967 * Create the Database percent and increment value
968 */
969 self.utilities.saveBackupPercentage('database', {
970 percentage: response.data.databasePercentage,
971 increment: 0,
972 });
973
974 /**
975 * Start adding files to the codebase
976 */
977 self.addFilesToCodebaseBackup(key, 1, response.data.amount);
978 });
979 codebasePreparation.fail(function(error) {
980 self.utilities.logEvent('failedMigration', {
981 migrationStatus: 'backupInstallation - preparing_codebase',
982 errorMessage: error?.responseJSON?.data
983 });
984 self.cleanUp(
985 'USE_CUSTOM_ERROR_MESSAGE',
986 error.responseJSON,
987 false,
988 null,
989 $('#progress__backupInstallation')
990 );
991 });
992 };
993
994 /**
995 * Add the files to the created archive
996 *
997 * @param key
998 * @param fileIndex
999 * @param maxAmount
1000 */
1001 this.addFilesToCodebaseBackup = function(key, fileIndex, maxAmount) {
1002 var self = this;
1003
1004 if (fileIndex > maxAmount) {
1005 self.codebaseCompleted(key);
1006 } else {
1007 /**
1008 * Update the progress for the codebase
1009 */
1010 self.utilities.updateTheBackupProgress('codebase');
1011
1012 var data = {
1013 action: 'add_files_to_codebase_archive',
1014 security: key,
1015 currentFileIndex: fileIndex
1016 };
1017 var addFiles = $.post(ajaxurl, data, function(response) {
1018 var newFileIndex = fileIndex + 1;
1019 self.addFilesToCodebaseBackup(key, newFileIndex, maxAmount);
1020 });
1021 addFiles.fail(function(error) {
1022 self.utilities.logEvent('failedMigration', {
1023 migrationStatus: 'backupInstallation - add_files_to_codebase_archive',
1024 errorMessage: error?.responseJSON?.data
1025 });
1026 self.cleanUp(
1027 'USE_CUSTOM_ERROR_MESSAGE',
1028 error.responseJSON,
1029 false,
1030 null,
1031 $('#progress__backupInstallation')
1032 );
1033 });
1034 }
1035 }
1036
1037 /**
1038 * Notification for codebase archive creation process
1039 *
1040 * @param key
1041 */
1042 this.codebaseCompleted = function(key) {
1043 var self = this;
1044 var data = {
1045 action: 'codebase_completion',
1046 security: key,
1047 };
1048 var codebaseCompletion = $.post(ajaxurl, data, function(response) {
1049 self.checkArchiveCompletion(key);
1050 /**
1051 * Initialise the database archive process
1052 * If the DB hasn't been excluded
1053 */
1054 if (!response.data.excludeDatabase) {
1055 self.prepareDatabaseBackup(key, true);
1056 }
1057 });
1058 codebaseCompletion.fail(function(error) {
1059 self.utilities.logEvent('failedMigration', {
1060 migrationStatus: 'backupInstallation - codebase_completion',
1061 errorMessage: error?.responseJSON?.data
1062 });
1063 self.cleanUp(
1064 'USE_CUSTOM_ERROR_MESSAGE',
1065 error.responseJSON,
1066 false,
1067 null,
1068 $('#progress__backupInstallation')
1069 );
1070 });
1071 }
1072
1073 /**
1074 * Prepare the DB to be backed up
1075 *
1076 * @param key
1077 * @param useZipFallback
1078 */
1079 this.prepareDatabaseBackup = function(key, useZipFallback) {
1080 var self = this;
1081 var data = {
1082 action: 'preparing_database',
1083 security: key
1084 };
1085 var databasePreparation = $.post(ajaxurl, data, function(response) {
1086 self.chunkDBExport(key, true, useZipFallback);
1087 });
1088 databasePreparation.fail(function(error) {
1089 self.utilities.logEvent('failedMigration', {
1090 migrationStatus: 'backupInstallation - preparing_database',
1091 errorMessage: error?.responseJSON?.data
1092 });
1093 self.cleanUp(
1094 'USE_CUSTOM_ERROR_MESSAGE',
1095 error.responseJSON,
1096 false,
1097 null,
1098 $('#progress__backupInstallation')
1099 );
1100 });
1101 };
1102
1103 /**
1104 * Create DB Export Files
1105 *
1106 * @param key
1107 * @param firstRun
1108 * @param useZipFallback
1109 */
1110 this.chunkDBExport = function(key, firstRun, useZipFallback) {
1111 var self = this;
1112 var data = {
1113 action: 'create_db_exports',
1114 security: key,
1115 firstRun: firstRun
1116 };
1117 var chunkedExport = $.post(ajaxurl, data, function(response) {
1118
1119 /**
1120 * Update our progress while we chunk
1121 * If exec is being used
1122 */
1123 if (!useZipFallback && response.data.hasOwnProperty('tableIndex')) {
1124
1125 /**
1126 * Only on the first run set the percentage
1127 */
1128 if (response.data.fileIndex === 2) {
1129 self.utilities.saveBackupPercentage('database', {
1130 percentage: transferito.backupPercentage.database,
1131 increment: (transferito.backupPercentage.database / response.data.tableIndex),
1132 });
1133 }
1134
1135 /**
1136 * Update the progress for the database
1137 */
1138 self.utilities.updateTheBackupProgress('database');
1139 }
1140
1141 /**
1142 * Keep running the export until the export flag is true
1143 */
1144 if (!response.data.completed) {
1145 self.chunkDBExport(key, false, useZipFallback);
1146 }
1147
1148 /**
1149 * When the chunked export has been completed
1150 * Notify the application that the DB has been completed
1151 */
1152 if (response.data.completed) {
1153 self.databaseCompleted(key);
1154 }
1155 });
1156 chunkedExport.fail(function(error) {
1157 self.utilities.logEvent('failedMigration', {
1158 migrationStatus: 'backupInstallation - create_db_exports',
1159 errorMessage: error?.responseJSON?.data
1160 });
1161 self.cleanUp(
1162 'USE_CUSTOM_ERROR_MESSAGE',
1163 error.responseJSON,
1164 false,
1165 null,
1166 $('#progress__backupInstallation')
1167 );
1168 });
1169 }
1170
1171 /**
1172 * Notification for database export completion
1173 *
1174 * @param key
1175 */
1176 this.databaseCompleted = function(key) {
1177 var self = this;
1178 var data = {
1179 action: 'database_completion',
1180 security: key,
1181 };
1182 var databaseCompletion = $.post(ajaxurl, data, function(response) {
1183 /**
1184 * If we are using the zip fallback
1185 * Run the archive completion
1186 */
1187 if (response.data.useZipFallback) {
1188 self.checkArchiveCompletion(key);
1189 }
1190
1191 /**
1192 * If zip fallback isn't used - Run the db move
1193 */
1194 if (!response.data.useZipFallback) {
1195 self.databaseFilesRelocation(key);
1196 }
1197 });
1198 databaseCompletion.fail(function(error) {
1199 self.utilities.logEvent('failedMigration', {
1200 migrationStatus: 'backupInstallation - database_completion',
1201 errorMessage: error?.responseJSON?.data
1202 });
1203 self.cleanUp(
1204 'USE_CUSTOM_ERROR_MESSAGE',
1205 error.responseJSON,
1206 false,
1207 null,
1208 $('#progress__backupInstallation')
1209 );
1210 });
1211 }
1212
1213 /**
1214 * Relocate the database files
1215 *
1216 * @param key
1217 */
1218 this.databaseFilesRelocation = function(key) {
1219 var self = this;
1220 var data = {
1221 action: 'database_relocation',
1222 security: key,
1223 };
1224 var databaseRelocation = $.post(ajaxurl, data, function(response) {
1225 self.checkDatabaseRelocation(key);
1226 });
1227 databaseRelocation.fail(function(error) {
1228 self.utilities.logEvent('failedMigration', {
1229 migrationStatus: 'backupInstallation - database_relocation',
1230 errorMessage: error?.responseJSON?.data
1231 });
1232 self.cleanUp(
1233 'USE_CUSTOM_ERROR_MESSAGE',
1234 error.responseJSON,
1235 false,
1236 null,
1237 $('#progress__backupInstallation')
1238 );
1239 });
1240 }
1241
1242 /**
1243 * Relocate the database files check
1244 *
1245 * @param key
1246 */
1247 this.checkDatabaseRelocation = function(key) {
1248 var self = this;
1249 var data = {
1250 action: 'database_relocation_check',
1251 security: key,
1252 };
1253 var databaseRelocationCheck = $.post(ajaxurl, data, function(response) {
1254 /**
1255 * If the DB isn't completed
1256 * Keep Polling until the job has completed
1257 */
1258 if (!response.data.completed) {
1259 self.checkDatabaseRelocation(key);
1260 }
1261
1262 /**
1263 * Once completed
1264 * Start the Archive creation
1265 */
1266 if (response.data.completed) {
1267 self.backupSize = response.data.siteInfo.databasePercentage;
1268 self.utilities.updateProgressPercentage(response.data.siteInfo.databasePercentage, $('#backupInstallationProgressPercentage'));
1269 self.archiveCreationStart(key);
1270 }
1271 });
1272 databaseRelocationCheck.fail(function(error) {
1273 self.utilities.logEvent('failedMigration', {
1274 migrationStatus: 'backupInstallation - database_relocation_check',
1275 errorMessage: error?.responseJSON?.data
1276 });
1277 self.cleanUp(
1278 'USE_CUSTOM_ERROR_MESSAGE',
1279 error.responseJSON,
1280 false,
1281 null,
1282 $('#progress__backupInstallation')
1283 );
1284 });
1285 }
1286
1287 /**
1288 * Start the creation of the Archive
1289 *
1290 * @param key
1291 */
1292 this.archiveCreationStart = function(key) {
1293 var self = this;
1294 var data = {
1295 action: 'archive_creation',
1296 security: key,
1297 };
1298 var archiveCreation = $.post(ajaxurl, data, function() {
1299 self.checkArchiveProgress(key, transferito.backupSize);
1300 });
1301 archiveCreation.fail(function(error) {
1302 self.utilities.logEvent('failedMigration', {
1303 migrationStatus: 'backupInstallation - archive_creation',
1304 errorMessage: error?.responseJSON?.data
1305 });
1306 self.cleanUp(
1307 'USE_CUSTOM_ERROR_MESSAGE',
1308 error.responseJSON,
1309 false,
1310 null,
1311 $('#progress__backupInstallation')
1312 );
1313 });
1314 }
1315
1316 /**
1317 * Check the progress of the archive creation
1318 *
1319 * @param key
1320 * @param initial
1321 */
1322 this.checkArchiveProgress = function(key, initial) {
1323 var self = this;
1324 var data = {
1325 action: 'archive_progress_check',
1326 security: key,
1327 };
1328 var archiveProgressCheck = $.post(ajaxurl, data, function(response) {
1329
1330 /**
1331 * Update the amount
1332 */
1333 self.utilities.updateTheExecBackupProgress(response.data.progress, initial);
1334
1335 /**
1336 * Poll every 5 second for the status
1337 */
1338 if (!response.data.completed) {
1339 setTimeout(function () {
1340 self.checkArchiveProgress(key, initial);
1341 }, 2500, self, key, initial);
1342 }
1343
1344 /**
1345 * Once the Archive has been completed progress
1346 */
1347 if (response.data.completed) {
1348 self.prepareMigrationStart(response.data.information);
1349 }
1350
1351 });
1352 archiveProgressCheck.fail(function(error) {
1353 self.utilities.logEvent('failedMigration', {
1354 migrationStatus: 'backupInstallation - archive_progress_check',
1355 errorMessage: error?.responseJSON?.data
1356 });
1357 self.cleanUp(
1358 'USE_CUSTOM_ERROR_MESSAGE',
1359 error.responseJSON,
1360 false,
1361 null,
1362 $('#progress__backupInstallation')
1363 );
1364 });
1365 }
1366
1367 /**
1368 * Archive Database exports
1369 *
1370 * @param key
1371 * @param information
1372 */
1373 this.archiveDatabaseExports = function(key, information) {
1374 var self = this;
1375 var data = {
1376 action: 'archive_db_exports',
1377 security: key,
1378 };
1379 var exportArchive = $.post(ajaxurl, data, function(response) {
1380
1381 /**
1382 * Create the Database percent and increment value
1383 */
1384 self.utilities.saveBackupPercentage('database', {
1385 percentage: transferito.backupPercentage.database,
1386 increment: (transferito.backupPercentage.database / response.data.amount),
1387 });
1388
1389 self.addDBExportsToCodebaseBackup(key, 1, response.data.amount, information)
1390 });
1391 exportArchive.fail(function(error) {
1392 self.utilities.logEvent('failedMigration', {
1393 migrationStatus: 'backupInstallation - archive_db_exports',
1394 errorMessage: error?.responseJSON?.data
1395 });
1396 self.cleanUp(
1397 'USE_CUSTOM_ERROR_MESSAGE',
1398 error.responseJSON,
1399 false,
1400 null,
1401 $('#progress__backupInstallation')
1402 );
1403 });
1404 }
1405
1406 /**
1407 * Add the files to the created archive
1408 *
1409 * @param key
1410 * @param fileIndex
1411 * @param maxAmount
1412 * @param information
1413 *
1414 * @todo Refactor to pass in a callback and request options - so "addFilesToCodebaseBackup" isn't duplicated
1415 */
1416 this.addDBExportsToCodebaseBackup = function(key, fileIndex, maxAmount, information) {
1417 var self = this;
1418
1419 if (fileIndex > maxAmount) {
1420 self.prepareMigrationStart(information);
1421 } else {
1422
1423 /**
1424 * Update the progress for the database
1425 */
1426 self.utilities.updateTheBackupProgress('database');
1427
1428 var data = {
1429 action: 'add_files_to_codebase_archive',
1430 security: key,
1431 currentFileIndex: fileIndex,
1432 addDatabaseExports: 1
1433 };
1434 var addFiles = $.post(ajaxurl, data, function(response) {
1435 var newFileIndex = fileIndex + 1;
1436 self.addDBExportsToCodebaseBackup(key, newFileIndex, maxAmount, information);
1437 });
1438 addFiles.fail(function(error) {
1439 self.utilities.logEvent('failedMigration', {
1440 migrationStatus: 'backupInstallation - add_files_to_codebase_archive',
1441 errorMessage: error?.responseJSON?.data
1442 });
1443 self.cleanUp(
1444 'USE_CUSTOM_ERROR_MESSAGE',
1445 error.responseJSON,
1446 false,
1447 null,
1448 $('#progress__backupInstallation')
1449 );
1450 });
1451 }
1452 }
1453
1454 /**
1455 * Fire the function to decide what action to perform when the archive creation is completed
1456 *
1457 * @param key
1458 */
1459 this.checkArchiveCompletion = function(key) {
1460 var self = this;
1461 var data = {
1462 action: 'check_archive_completion',
1463 security: key,
1464 };
1465 var archiveCompletion = $.post(ajaxurl, data, function(response) {
1466 /**
1467 * If the backup has completed
1468 * The zip export flag is truthy
1469 * Fire the start db zip export
1470 */
1471 if (response.data.backupComplete && response.data.zipDatabaseExport) {
1472 self.archiveDatabaseExports(key, response.data.information);
1473 }
1474
1475 /**
1476 * If the backup has been completed
1477 * The zip export flag is falsy
1478 * Upload or start the migration
1479 */
1480 if (response.data.backupComplete && !response.data.zipDatabaseExport) {
1481 self.prepareMigrationStart(response.data.information);
1482 }
1483 });
1484 archiveCompletion.fail(function(error) {
1485 self.utilities.logEvent('failedMigration', {
1486 migrationStatus: 'backupInstallation - check_archive_completion',
1487 errorMessage: error?.responseJSON?.data
1488 });
1489 self.cleanUp(
1490 'USE_CUSTOM_ERROR_MESSAGE',
1491 error.responseJSON,
1492 false,
1493 null,
1494 $('#progress__backupInstallation')
1495 );
1496 });
1497 }
1498
1499 /**
1500 * Make a decision on whether to do a direct migration or upload
1501 *
1502 * @param information
1503 */
1504 this.prepareMigrationStart = function (information) {
1505 /**
1506 * Set the backup started to active
1507 */
1508 this.utilities.updateProgressStep('completed', $('#progress__backupInstallation'));
1509
1510 /**
1511 * Hide the percentage on completion of codebase & database
1512 */
1513 this.utilities.hideProgressPercentage($('#backupInstallationProgressPercentage'));
1514
1515 /**
1516 * Fire the local upload to have an accessible file
1517 */
1518 if (information.uploadFiles) {
1519 /**
1520 * Set the backup to active
1521 */
1522 this.utilities.updateProgressStep('active', $('#progress__uploadBackup'), true);
1523
1524 /**
1525 * Start the upload
1526 */
1527 this.startUpload(information.securityKey);
1528 }
1529
1530 /**
1531 * Start the migration
1532 */
1533 if (!information.uploadFiles) {
1534 this.startMigration(information.securityKey);
1535 }
1536 }
1537
1538 /**
1539 * Start the local upload
1540 * @param wpNonce
1541 */
1542 this.startUpload = function(wpNonce) {
1543 var self = this;
1544 var data = {
1545 action: 'initiate_local_upload',
1546 security: wpNonce
1547 };
1548 var startLocalUpload = $.post(ajaxurl, data, function(response) {
1549 /**
1550 * Fire the process upload for the codebase
1551 */
1552 self.processLocalUpload(response.data.backup.archive, '#codebaseProgressBar');
1553 });
1554 startLocalUpload.fail(function(error) {
1555 self.utilities.logEvent('failedMigration', {
1556 migrationStatus: 'uploadBackup - initiate_local_upload',
1557 errorMessage: error?.responseJSON?.data
1558 });
1559 self.cleanUp(
1560 'UPLOAD_START_FAILURE',
1561 error.responseJSON,
1562 false,
1563 null,
1564 $('#progress__uploadBackup')
1565 );
1566 });
1567 };
1568
1569 /**
1570 * Process the Local upload
1571 *
1572 * @param uploadDetail
1573 * @param progressSelector
1574 * @param ignoreLocalUploadProperties - If the DB is excluded ignores the upload flags and process the start
1575 * StartMigration method straight after the completeUpload has succeeded
1576 */
1577 this.processLocalUpload = function(uploadDetail, progressSelector, ignoreLocalUploadProperties = false) {
1578 /**
1579 * Start the chunk upload
1580 */
1581 this.uploadChunk(1, uploadDetail, progressSelector, ignoreLocalUploadProperties);
1582 };
1583
1584 /**
1585 * Upload the chunk
1586 *
1587 * @param part
1588 * @param uploadDetail
1589 * @param progressSelector
1590 * @param ignoreLocalUploadProperties - If the DB is excluded ignores the upload flags and process the start
1591 * StartMigration method straight after the completeUpload has succeeded
1592 */
1593 this.uploadChunk = function(part, uploadDetail, progressSelector, ignoreLocalUploadProperties = false) {
1594 var self = this;
1595 var data = {
1596 action: 'upload_chunk',
1597 uploadId: uploadDetail.uploadId,
1598 archiveType: uploadDetail.type,
1599 partNumber: part
1600 };
1601 var chunkUpload = $.post(ajaxurl, data, function(response) {
1602
1603 /**
1604 * Get all the parts
1605 */
1606 var maxParts = uploadDetail.parts;
1607
1608 /**
1609 * Calculate the percentage of the uplaod
1610 */
1611 var percentage = Math.ceil((part / maxParts) * 100);
1612
1613
1614 /**
1615 * Update the percentage for the progress bar
1616 */
1617 self.utilities.updateProgressPercentage(percentage, $('#progressPercentage'));
1618
1619 /**
1620 * Call the chunk upload recursively
1621 */
1622 if (part < maxParts) {
1623 var nextPart = part + 1;
1624 self.uploadChunk(nextPart, uploadDetail, progressSelector, ignoreLocalUploadProperties);
1625 }
1626
1627 /**
1628 * Complete the upload
1629 */
1630 if (part === maxParts) {
1631 self.completeUpload(uploadDetail.uploadId, uploadDetail.type, ignoreLocalUploadProperties);
1632 }
1633
1634 });
1635 chunkUpload.fail(function(error) {
1636 self.utilities.logEvent('failedMigration', {
1637 migrationStatus: 'uploadBackup - upload_chunk',
1638 errorMessage: error?.responseJSON?.data
1639 });
1640 self.cleanUp(
1641 'UPLOAD_CHUNK_FAILURE',
1642 error.responseJSON,
1643 false,
1644 null,
1645 $('#progress__uploadBackup')
1646 );
1647 });
1648 };
1649
1650 /**
1651 * Fire the complete upload to finalize the upload process
1652 *
1653 * @param uploadId
1654 * @param type
1655 * @param ignoreLocalUploadProperties - If the DB is excluded ignores the upload flags and process the start
1656 * StartMigration method straight after the completeUpload has succeeded
1657 */
1658 this.completeUpload = function(uploadId, type, ignoreLocalUploadProperties) {
1659 var self = this;
1660 var data = {
1661 action: 'complete_upload',
1662 uploadId: uploadId,
1663 archiveType: type
1664 };
1665 var completeUpload = $.post(ajaxurl, data, function(response) {
1666
1667 /**
1668 * Set the backup to completed
1669 */
1670 self.utilities.updateProgressStep('completed', $('#progress__uploadBackup'));
1671
1672 /**
1673 * Hide the progress step
1674 */
1675 self.utilities.hideProgressPercentage($('#progressPercentage'));
1676
1677 /**
1678 * If the ignore upload properties flag has been set
1679 * Start the migration right away
1680 */
1681 if (ignoreLocalUploadProperties) {
1682 self.startMigration(response.data.securityKey);
1683 }
1684
1685 /**
1686 * If both backup archives are present
1687 * Update the flag
1688 */
1689 if (!ignoreLocalUploadProperties) {
1690 self.localUploadComplete[type] = true;
1691
1692 /**
1693 * Start the migration
1694 */
1695 self.startMigration(response.data.securityKey);
1696 }
1697
1698 });
1699 completeUpload.fail(function(error) {
1700 self.utilities.logEvent('failedMigration', {
1701 migrationStatus: 'uploadBackup - complete_upload',
1702 errorMessage: error?.responseJSON?.data
1703 });
1704 self.cleanUp(
1705 'UPLOAD_COMPLETION_FAILURE',
1706 error.responseJSON,
1707 false,
1708 null,
1709 $('#progress__uploadBackup')
1710 );
1711 });
1712 };
1713
1714 /**
1715 * Clean up either fail or complete
1716 */
1717 this.cleanUp = function (
1718 hasError = false,
1719 errors = [],
1720 ignoreTemplateSwitch = false,
1721 metadata = null,
1722 selector = null,
1723 localMigration = false
1724 ) {
1725
1726 var self = this;
1727 $.post(ajaxurl, {
1728 action: 'clean_up_files',
1729 hasError: hasError,
1730 errors: errors,
1731 metadata: metadata,
1732 localMigration: localMigration
1733 })
1734 .always(function(response) {
1735 /**
1736 * Only change the template if the flag exists
1737 */
1738 if (!ignoreTemplateSwitch && typeof response.data.htmlTemplate === 'string') {
1739 self.utilities.setTemplate(response.data.htmlTemplate);
1740 }
1741
1742 /**
1743 * Display inline error
1744 */
1745 if (!ignoreTemplateSwitch && typeof response.data.htmlTemplate !== 'string') {
1746 self.utilities.displayMigrationProgressFailure(
1747 selector,
1748 response.data.htmlTemplate.error
1749 );
1750 }
1751 });
1752 };
1753
1754 /**
1755 * Start looking for the WP installation directory
1756 */
1757 this.startDirectorySearch = function() {
1758 var self = this;
1759 var securityKey = $('#directoryKey').val();
1760 var directoryRequest = $.post(ajaxurl, {
1761 action: 'start_directory_search',
1762 securityKey: securityKey,
1763 });
1764
1765 directoryRequest.done(function(response) {
1766 var url = response?.data?.url;
1767 var directoryCheckId = response?.data?.directoryCheckId;
1768 self.getDirectoryCheckUpdate(url, directoryCheckId);
1769 });
1770
1771 directoryRequest.fail(function(response) {
1772 self.screenRouting(
1773 'ftpAuthentication',
1774 '',
1775 '',
1776 'errorFailedDirectorySearch'
1777 );
1778 });
1779 }
1780
1781 /**
1782 * Poll to update UI on the status of the directory check
1783 *
1784 * @param url
1785 * @param directoryCheckId
1786 */
1787 this.getDirectoryCheckUpdate = function(url, directoryCheckId) {
1788 var self = this;
1789 var securityKey = $('#directoryKey').val();
1790 var directoryRequest = $.post(ajaxurl, {
1791 action: 'get_directory_check_update',
1792 securityKey: securityKey,
1793 url: url,
1794 directoryCheckId: directoryCheckId
1795 });
1796
1797 directoryRequest.done(function(response) {
1798 /**
1799 * If the check is still in process
1800 */
1801 if (!response.data.complete && !response.data.found) {
1802 /**
1803 * Prefix an empty path
1804 */
1805 var path = !response?.data?.path ? '/' : response.data.path;
1806
1807 /**
1808 * Update the path in the UI
1809 */
1810 $('#currentFTPPathCheck').html(path);
1811
1812 /**
1813 * Continue to poll
1814 */
1815 self.getDirectoryCheckUpdate(url, directoryCheckId)
1816 }
1817
1818 /**
1819 * If the directory has been found
1820 */
1821 if (response.data.complete && response.data.found) {
1822 $('#manualDirectorySelection').prop('disabled', false);
1823 $('#ftpDirectorySelector').addClass('transferito__hide-element');
1824 $('#directorySelectionCheckSuccess').removeClass('transferito__hide-element');
1825 }
1826
1827 /**
1828 * The directory cant be found on this server
1829 */
1830 if (response.data.complete && !response.data.found) {
1831 self.screenRouting('ftpAuthentication', '', '', 'errorDirectoryNotFound');
1832 }
1833
1834 /**
1835 * The directory check has completed with a failure
1836 */
1837 if (response.data.complete && response.data.failed) {
1838 self.screenRouting('ftpAuthentication', '', '', 'errorDirectoryUpdateFailed');
1839 }
1840
1841 });
1842
1843 /**
1844 * The directory status update has failed
1845 */
1846 directoryRequest.fail(function(response) {
1847 self.screenRouting('ftpAuthentication', '', '', 'errorDirectoryUpdateFailed');
1848 });
1849 }
1850
1851 /**
1852 * Check the URL - To see if cPanel is available
1853 *
1854 * @param domain
1855 * @param localMigration
1856 * @param wpNonce
1857 * @param message
1858 * @param subMessage
1859 */
1860 this.checkCpanelAvailability = function (domain, localMigration, wpNonce, message, subMessage) {
1861 /**
1862 * Show the loading screen
1863 */
1864 this.utilities.showLoadingScreen(message, subMessage);
1865
1866 /**
1867 *
1868 */
1869 var self = this;
1870 var data = {
1871 action: 'check_cpanel_availability',
1872 domain: domain,
1873 localMigration: localMigration,
1874 securityKey: wpNonce
1875 };
1876 var cPanelCheck = $.post(ajaxurl, data, function(response) {
1877
1878 var transferMethod = response.data.transferMethod;
1879 var cPanelAllowed = response.data.cPanelAllowed;
1880
1881 self.utilities.setTransferMethodOptions(transferMethod, cPanelAllowed);
1882
1883 /**
1884 *
1885 */
1886 if (transferMethod === 'localSiteMigration') {
1887 /**
1888 * Create the migration payload
1889 */
1890 self.prepareMigration(
1891 {
1892 transferMethod: transferMethod,
1893 },
1894 response.data.securityToken
1895 );
1896 } else {
1897 self.utilities.setTemplate(response.data.htmlTemplate);
1898 }
1899 });
1900 cPanelCheck.fail(function(error) {
1901 self.utilities.logEvent('failedMigration', {
1902 migrationStatus: 'destinationURL',
1903 errorMessage: error?.responseJSON?.data
1904 });
1905 /**
1906 * Route to screen
1907 * No message
1908 * Display Error Modal
1909 */
1910 self.screenRouting('destinationURL', '', '', 'errorIncorrectModal');
1911 });
1912 };
1913
1914 /**
1915 * Switch the migration method
1916 *
1917 * @param transferMethod
1918 * @param message
1919 * @param subMessage
1920 */
1921 this.switchMode = function(transferMethod, message, subMessage) {
1922 /**
1923 * Show the loading screen
1924 */
1925 this.utilities.showLoadingScreen(message, subMessage);
1926
1927 /**
1928 * Call the API to switch the transfer method
1929 */
1930 var self = this;
1931 var data = {
1932 action: 'switch_mode',
1933 method: transferMethod
1934 };
1935 var switchMode = $.post(ajaxurl, data, function(response) {
1936 self.utilities.setTransferMethodOptions(response.data.transferMethod, response.data.cPanelAllowed);
1937 self.utilities.setTemplate(response.data.htmlTemplate);
1938 });
1939 switchMode.fail(function(error) {
1940 /**
1941 * @todo Remove - Display popup instead
1942 */
1943 self.cleanUp('SWITCH_METHOD_FAILED', error.responseJSON);
1944 });
1945 };
1946
1947 /**
1948 * Auth the cPanel request and move to the next step
1949 *
1950 * @param securityKey
1951 * @param message
1952 * @param cpanelDetails
1953 * @param selector
1954 */
1955 this.cpanelAuthentication = function(securityKey, cpanelDetails, message, subMessage) {
1956 /**
1957 * Show the loading screen
1958 */
1959 this.utilities.showLoadingScreen(message, subMessage);
1960
1961 /**
1962 *
1963 */
1964 var self = this;
1965 var data = {
1966 action: 'cpanel_authentication',
1967 auth: cpanelDetails,
1968 securityKey: securityKey
1969 };
1970 var cpanelAuth = $.post(ajaxurl, data, function(response) {
1971 /**
1972 * Show the new template
1973 */
1974 self.utilities.setTemplate(response.data.template);
1975
1976 });
1977 cpanelAuth.fail(function(error) {
1978 self.utilities.logEvent('failedMigration', {
1979 migrationStatus: 'cPanelAuth',
1980 errorMessage: error?.responseJSON?.data
1981 });
1982 /**
1983 * Route to screen
1984 * No message
1985 * Display Error Modal
1986 */
1987 self.screenRouting('cpanelAuthentication', '', '', 'errorFailedCpanelAuth');
1988 });
1989 };
1990
1991 /**
1992 * Validate the server detail
1993 *
1994 * @param securityKey
1995 * @param message
1996 * @param serverDetails
1997 * @param selector
1998 */
1999 this.manualServerDetailValidation = function(securityKey, serverDetails, message, subMessage) {
2000 /**
2001 * Show the loading screen
2002 */
2003 this.utilities.showLoadingScreen(message, subMessage);
2004
2005 /**
2006 * Validate the FTP details
2007 */
2008 var self = this;
2009 var data = {
2010 action: 'server_detail_validation',
2011 serverDetails: serverDetails,
2012 securityKey: securityKey
2013 };
2014 var serverDetailValidation = $.post(ajaxurl, data, function(response) {
2015
2016 /**
2017 * Show the new template
2018 */
2019 self.utilities.setTemplate(response.data.template);
2020
2021 /**
2022 * Disable the button
2023 */
2024 $('#manualDirectorySelection').prop('disabled', true);
2025
2026 /**
2027 * Start directory check call
2028 */
2029 self.startDirectorySearch();
2030 });
2031 serverDetailValidation.fail(function(error) {
2032 self.utilities.logEvent('failedMigration', {
2033 migrationStatus: 'ftpAuth',
2034 errorMessage: error?.responseJSON?.data
2035 });
2036 /**
2037 * Route to screen
2038 * No message
2039 * Display Error Modal
2040 */
2041 self.screenRouting('ftpAuthentication', '', '', 'errorFailedFTPAuth');
2042 });
2043 };
2044
2045 /**
2046 * Validate the database details
2047 *
2048 * @param securityKey
2049 * @param message
2050 * @param databaseDetail
2051 * @param selector
2052 */
2053 this.databaseDetailValidation = function(securityKey, databaseDetail, message, subMessage) {
2054 var self = this;
2055
2056 /**
2057 * Show the loading screen
2058 */
2059 this.utilities.showLoadingScreen(message, subMessage);
2060
2061 /**
2062 * Validate the correct directory
2063 */
2064 var data = {
2065 action: 'database_detail_validation',
2066 databaseDetail: databaseDetail,
2067 securityKey: securityKey
2068 };
2069 var databaseValidation = $.post(ajaxurl, data, function(response) {
2070 /**
2071 * Begin the migration process
2072 */
2073 self.prepareMigration(response.data.migrationDetail, response.data.securityKey);
2074 });
2075 databaseValidation.fail(function(error) {
2076 self.utilities.logEvent('failedMigration', {
2077 migrationStatus: 'databaseAuth',
2078 errorMessage: error?.responseJSON?.data
2079 });
2080 self.screenRouting('databaseAuthentication', '', '', 'errorFailedDatabaseAuth');
2081 });
2082 };
2083
2084 /**
2085 * Load the directory Selector
2086 */
2087 this.loadDirectoryTemplate = function() {
2088 var self = this;
2089 $.post(ajaxurl, { action: 'load_directory_template' })
2090 .always(function(response) {
2091 self.utilities.setTemplate(response.data.template, $('#manualScreenTemplate'));
2092
2093 /**
2094 * Update the navigation
2095 */
2096 $('#transferitoNav__manualFTPDirectorySelect')
2097 .removeClass('transferito-nav__item__indicator--in-complete')
2098 .removeClass('transferito-nav__item__indicator--completed');
2099
2100 /**
2101 * Fire directory call
2102 */
2103 self.getDirectories(response.data.path);
2104 });
2105 };
2106
2107 /**
2108 * Hide the quick start popup once they click the close button
2109 */
2110 this.hideQuickStartPopup = function () {
2111 $.post(ajaxurl, {
2112 action: 'hide_quickstart_popup'
2113 })
2114 .always(function(response) {})
2115 };
2116
2117 /**
2118 * Redirect a user to a particular screen
2119 *
2120 * @param route
2121 * @param message
2122 * @param subMessage
2123 * @param showModal
2124 * @param customizedModalContent
2125 */
2126 this.screenRouting = function(route, message, subMessage, showModal, customizedModalContent) {
2127 /**
2128 * Only show if a message exists
2129 */
2130 if (message) {
2131 /**
2132 * Show the loading screen
2133 */
2134 this.utilities.showLoadingScreen(message, subMessage);
2135 }
2136
2137 /**
2138 * Log event
2139 */
2140 this.utilities.logEvent('screenRouting', {
2141 screen: route
2142 });
2143
2144 var self = this;
2145 var data = {
2146 action: 'screen_route_redirection',
2147 route: route
2148 };
2149
2150 var routeScreen = $.post(ajaxurl, data, function(response) {
2151 self.utilities.setTemplate(response.data.htmlTemplate);
2152
2153 if (route === 'directorySelector') {
2154 $('#manualDirectorySelection').prop('disabled', true);
2155
2156 /**
2157 * Start directory check call
2158 */
2159 self.startDirectorySearch();
2160 }
2161
2162 if (showModal) {
2163 self.utilities.displayModal(showModal, customizedModalContent);
2164 }
2165 });
2166 routeScreen.fail(function(error) {
2167 self.utilities.logEvent('failedRouting', {
2168 route: route
2169 });
2170 });
2171 };
2172
2173 /**
2174 * Send the guide request
2175 */
2176 this.sendGuideRequestForm = function(hostingDetail, message, subMessage) {
2177 /**
2178 * Add a loader into the modal Div
2179 */
2180 this.utilities.setTemplate(this.utilities.loadingOnlyHTML(), this.utilities.modalSelector, 500);
2181
2182 var self = this;
2183 var data = {
2184 action: 'send_request_form',
2185 data: hostingDetail,
2186 securityKey: hostingDetail.securityKey
2187 };
2188
2189 var sendRequest = $.post(ajaxurl, data);
2190 sendRequest.always(function() {
2191 self.utilities.displayModal('successSentGuideRequest');
2192 });
2193 }
2194
2195 /**
2196 * Check the API Keys Validity
2197 */
2198 this.apiValidityCheck = function(apiCheckPayload, loadingSelector) {
2199 /**
2200 * Set the loading spinner
2201 */
2202 this.utilities.setTemplate(
2203 this.utilities.loadingScreenHTML(
2204 'Please wait...',
2205 'We are just validating your API Keys.'
2206 ),
2207 loadingSelector
2208 );
2209
2210 /**
2211 * Show the element
2212 */
2213 loadingSelector.removeClass('transferito__hide-element');
2214
2215 var self = this;
2216 var data = {
2217 action: 'check_premium_api_keys',
2218 data: apiCheckPayload,
2219 securityKey: apiCheckPayload.securityKey
2220 };
2221
2222 /**
2223 * The API Keys are valid
2224 */
2225 var sendRequest = $.post(ajaxurl, data, function(response) {
2226 /**
2227 * Clear the loading Selector
2228 */
2229 self.utilities.setTemplate('', loadingSelector);
2230
2231 /**
2232 * Display the Success Message
2233 */
2234 $('#upgradeToPremiumCheckComplete').removeClass('transferito__hide-element');
2235
2236 /**
2237 * Log event
2238 */
2239 self.utilities.logEvent('upgradeToPremiumModalSuccess', {
2240 upgraded: true
2241 });
2242 });
2243
2244 /**
2245 * The API Keys aren't valid
2246 */
2247 sendRequest.fail(function() {
2248 /**
2249 * Clear the loading Selector
2250 */
2251 self.utilities.setTemplate('', loadingSelector);
2252
2253 /**
2254 * Display the Entry Form
2255 */
2256 $('#upgradeToPremiumAPIKeyEntry').removeClass('transferito__hide-element');
2257
2258 /**
2259 * Display the Error Message
2260 */
2261 $('#upgradeToPremiumErrorMessage').removeClass('transferito__hide-element');
2262 });
2263
2264 }
2265
2266 /**
2267 * Send user through the premium upgrade flow
2268 */
2269 this.inPluginPurchase = function(migrationDetails, key) {
2270
2271 /**
2272 * Log event
2273 */
2274 transferito.utilities.logEvent('upgradeToPremiumModalFired', {
2275 fired: true
2276 });
2277
2278 /**
2279 * Save the migration details
2280 */
2281 transferito.utilities.saveTempMigrationDetails(migrationDetails, key);
2282
2283 /**
2284 * Fire the modal
2285 */
2286 transferito.utilities.displayModal('upgradeToPremiumPaymentModal');
2287 }
2288
2289 /**
2290 * Download the verification File to Connect to Destination Server
2291 */
2292 this.downloadVerificationFile = function(securityKey) {
2293
2294 var self = this;
2295 var data = {
2296 action: 'download_transferito_verification_file',
2297 securityKey: securityKey
2298 };
2299
2300 /**
2301 * The API Keys are valid
2302 */
2303 var sendRequest = $.post(ajaxurl, data, function(response) {
2304
2305 var anchor = document.createElement('a');
2306 anchor.href = response.data.url;
2307 anchor.target = '_blank';
2308 anchor.click();
2309
2310 $('#destinationServerConnectionCheckInProgress').removeClass('transferito__hide-element');
2311
2312 /**
2313 * Check connection
2314 */
2315 self.validateConnection(securityKey);
2316
2317 });
2318
2319 sendRequest.fail(function (res) {
2320 $('#destinationServerCheckStart').addClass('transferito__hide-element');
2321 $('#destinationServerConnectionCheckInProgress').addClass('transferito__hide-element');
2322 $('#destinationServerCheckCompletion').addClass('transferito__hide-element');
2323
2324 $('#destinationServerCheckFailure').removeClass('transferito__hide-element');
2325 });
2326 }
2327
2328 /**
2329 * Check the connection status
2330 */
2331 this.validateConnection = function(securityKey) {
2332 var self = this;
2333 var data = {
2334 action: 'transferito_validate_destination_server_connection',
2335 securityKey: securityKey
2336 };
2337
2338 /**
2339 * The API Keys are valid
2340 */
2341 var sendRequest = $.post(ajaxurl, data, function(response) {
2342 $('#destinationServerCheckStart').addClass('transferito__hide-element');
2343 $('#destinationServerConnectionCheckInProgress').addClass('transferito__hide-element');
2344 $('#destinationServerCheckCompletion').removeClass('transferito__hide-element');
2345 $('#proceedAfterDestinationServerConnection').prop('disabled', false);
2346 });
2347
2348 sendRequest.fail(function (res) {
2349 setTimeout(function (){
2350 self.validateConnection(securityKey)
2351 }, 5000);
2352 })
2353 }
2354
2355 this.hideWelcomeScreen = function(securityKey) {
2356 var data = {
2357 action: 'transferito_hide_welcome_screen',
2358 securityKey: securityKey
2359 };
2360 /**
2361 * The API Keys are valid
2362 */
2363 var sendRequest = $.post(ajaxurl, data, function(response) {});
2364 }
2365 }
2366
2367 /**
2368 * Initialize
2369 */
2370 var transferito = new Transferito();
2371
2372 /**
2373 * Check the status of the site
2374 * If it is a FREE Transfer or not
2375 */
2376 transferito.checkSite();
2377
2378 /**
2379 * @todo InAPP Modal Upgrade - Event Listener
2380 */
2381 window.addEventListener('message', (event) => {
2382 if (event?.data?.type === 'transferitoNotifyParent') {
2383
2384 /**
2385 * Log event
2386 */
2387 transferito.utilities.logEvent('upgradeToPremiumModalButtonClicked', {
2388 fired: true
2389 });
2390
2391 /**
2392 * Remove the iFRAME
2393 */
2394 $('#upgradeToPremiumIFrame').remove();
2395
2396 /**
2397 * Display the API Key Entry Form
2398 */
2399 $('#upgradeToPremiumAPIKeyEntry').removeClass('transferito__hide-element');
2400 }
2401 });
2402
2403
2404
2405 /**
2406 *
2407 */
2408 transferito.utilities.selector.on('click', '.transferito-ftp-authentication__folder-expander', function () {
2409 var childItems = $(this).next('.transferito-ftp-authentication__sub-folders');
2410 if (childItems.length === 0) {
2411 return false;
2412 }
2413 childItems.toggle();
2414 });
2415
2416 /**
2417 *
2418 */
2419 transferito.utilities.selector.on('change', '.show-selected-folder', function() {
2420 $('#selectedFoldersDetails').toggle();
2421 });
2422
2423 /**
2424 * Hide or show the Database Fields
2425 * Based on whether the checkbox is ticked or not
2426 */
2427 transferito.utilities.selector.on('change', '.transferito__hide-database-details', function() {
2428
2429 var excludeDatabaseSelector = $('#excludeDatabase');
2430 var useExistingDatabaseSelector = $('#useExistingDatabase');
2431 var selector = $(this);
2432
2433 var excludeDatabase = excludeDatabaseSelector.prop('checked');
2434 var useExistingDatabase = useExistingDatabaseSelector.prop('checked');
2435
2436 var oneSelected = (excludeDatabase || useExistingDatabase);
2437 var databaseFields = $('.transferito-database-authentication__input-fields');
2438
2439 var idToUncheck = selector.data('uncheckId');
2440 var checkboxChecked = selector.prop('checked');
2441
2442 if (checkboxChecked) {
2443 var uncheckableID = '#' + idToUncheck;
2444 $(uncheckableID).prop('checked', false)
2445 }
2446
2447 databaseFields.toggleClass('transferito-database-authentication__input-fields--hide', oneSelected);
2448 $('#manualServerMigrationStart').prop('disabled', !transferito.utilities.validateFormFields());
2449 });
2450
2451 /**
2452 * Remove the error from the validation fields
2453 */
2454 transferito.utilities.selector.on('keyup', '.transferito-input--error > .transferito-required', function() {
2455 var selector = $(this);
2456 if (selector.val()) {
2457 selector.parent().removeClass('transferito-input--error')
2458 }
2459 });
2460
2461 /**
2462 * Validation check for the domain input field
2463 * Disable or Enable the button based on the validity of the domain field
2464 */
2465 transferito.utilities.selector.on('keyup', '#domain', function() {
2466 var domainEntry = $(this).val();
2467 var domainIsEmpty = domainEntry.length === 0;
2468 $('#cpanelCheck').prop('disabled', domainIsEmpty);
2469 });
2470
2471 /**
2472 * Open the modal by ID
2473 */
2474 transferito.utilities.selector.on('click', '.transferito-open-modal', function() {
2475 var modalID = $(this).data('transferitoModal');
2476 transferito.utilities.displayModal(modalID);
2477 });
2478
2479 /**
2480 * Open the modal by ID
2481 */
2482 transferito.utilities.modalSelector.on('click', '.transferito-open-modal', function() {
2483 var modalID = $(this).data('transferitoModal');
2484 transferito.utilities.displayModal(modalID);
2485 });
2486
2487 /**
2488 * Close the open modal
2489 */
2490 transferito.utilities.modalSelector.on('click', '.transferito__modal--close', function() {
2491 transferito.utilities.closeModal();
2492 });
2493
2494 /**
2495 * Check to see if we can use cPanel
2496 */
2497 transferito.utilities.selector.on('click', '.transferito__check-cpanel-availability', function() {
2498 /**
2499 * Disable the Button to stop double checks
2500 */
2501 $(this).prop('disabled', true);
2502
2503 transferito.checkCpanelAvailability(
2504 $('#domainProtocol').val() + $('#domain').val(),
2505 $('#localSiteMigration').is(':checked'),
2506 $('#cPanelCheckSecurity').val(),
2507 'Please wait...',
2508 'We\'re just checking your URL'
2509 );
2510 });
2511
2512 /**
2513 * Toggle the password visibility
2514 */
2515 transferito.utilities.selector.on('click', '.transferito__password-visibility', function() {
2516
2517 var visibleClass = 'transferito__password-visibility--visible';
2518 var selector = $(this);
2519 var inputField = $('#' + selector.data('transferitoPasswordField'));
2520 var passwordMasked = !selector.hasClass(visibleClass);
2521
2522 /**
2523 * If the password is masked
2524 */
2525 if (passwordMasked) {
2526 /**
2527 * Add the visibility class
2528 */
2529 selector.addClass(visibleClass);
2530
2531 /**
2532 * Change the input type
2533 */
2534 inputField.prop('type', 'text');
2535 }
2536
2537 /**
2538 * If the password is visible
2539 */
2540 if (!passwordMasked) {
2541 /**
2542 * Remove the visibility class
2543 */
2544 selector.removeClass(visibleClass);
2545
2546 /**
2547 * Change the input type
2548 */
2549 inputField.prop('type', 'password');
2550 }
2551 });
2552
2553 /**
2554 * Switch the transfer method
2555 */
2556 transferito.utilities.selector.on('click', '.transferito__switch-mode', function() {
2557 /**
2558 * Disable the Button to stop double checks
2559 */
2560 $(this).prop('disabled', true);
2561
2562 /**
2563 * Switch the transfer method
2564 */
2565 transferito.switchMode(
2566 $(this).data('transferitoTransferMethod'),
2567 $(this).data('transferitoTransferMethodMessage')
2568 );
2569 });
2570
2571
2572 /**
2573 * Authenticate cPanel details
2574 */
2575 transferito.utilities.selector.on('click', '.transferito__cpanel-authentication', function() {
2576 /**
2577 * Disable the Button to stop double checks
2578 */
2579 $(this).prop('disabled', true);
2580
2581 /**
2582 * Validate that all required form fields have been completed
2583 */
2584 var validateFields = transferito.utilities.validateFormFields();
2585
2586 /**
2587 * If validation has passed
2588 */
2589 if (validateFields) {
2590 /**
2591 * Get the cPanel information
2592 */
2593 var cPanelDetails = transferito.utilities.buildPayload();
2594
2595 /**
2596 * Get the wpNonce
2597 */
2598 var securityKey = $('#cPanelMigration').val();
2599
2600 /**
2601 * Start the authentication
2602 */
2603 transferito.cpanelAuthentication(
2604 securityKey,
2605 cPanelDetails,
2606 'Please wait..',
2607 'We\'re just validating your cPanel details.',
2608 $('#cPanelScreenTemplate')
2609 );
2610
2611 $(this).prop('disabled', false);
2612 }
2613
2614 /**
2615 * Enable the button if validation has failed
2616 */
2617 if (!validateFields) {
2618 $(this).prop('disabled', false);
2619 }
2620 });
2621
2622 /**
2623 * Start the migration for cpanel
2624 */
2625 transferito.utilities.selector.on('click', '.transferito__cpanel-start-migration', function() {
2626 /**
2627 * Disable the Button to stop double migrations
2628 */
2629 $(this).prop('disabled', true);
2630
2631 /**
2632 * The migration security key
2633 */
2634 var securityKey = $('#prepareTransfer').val();
2635
2636 /**
2637 * Create the migration payload
2638 */
2639 var cpanelMigrationDetails = {
2640 transferMethod: 'cpanel',
2641 cpanelHost: $('#cpanelHost').val(),
2642 cpanelUser: $('#cpanelUser').val(),
2643 cpanelPass: $('#cpanelPass').val(),
2644 cpanelApiToken: $('#cpanelApiToken').val(),
2645 useApiToken: $('#useApiToken').val(),
2646 domain: $('#field__cpanelDomain').val()
2647 };
2648
2649 /**
2650 * Set the loading spinner
2651 */
2652 transferito.utilities.setTemplate(
2653 transferito
2654 .utilities
2655 .loadingScreenHTML('Please wait...', 'We are just creating your FTP & Database details.')
2656 );
2657
2658 /**
2659 * Start the migration
2660 */
2661 transferito.prepareMigration(cpanelMigrationDetails, securityKey);
2662 });
2663
2664 /**
2665 * Validate main server details
2666 */
2667 transferito.utilities.selector.on('click', '.transferito__manual-server-details', function() {
2668 /**
2669 * Disable the Button to stop double checks
2670 */
2671 $(this).prop('disabled', true);
2672
2673 /**
2674 * Validate that all required form fields have been completed
2675 */
2676 var validateFields = transferito.utilities.validateFormFields();
2677
2678 /**
2679 * If validation has passed
2680 */
2681 if (validateFields) {
2682 /**
2683 * Get the manual server details information
2684 */
2685 var serverDetail = transferito.utilities.buildPayload();
2686
2687 /**
2688 * Get the wpNonce
2689 */
2690 var securityKey = $('#manualMigrationServerDetail').val();
2691
2692 /**
2693 * Remove port numbers
2694 */
2695 var hostProtocolSplit = serverDetail.ftpHost.split('://');
2696
2697 /**
2698 * Remove the protocol from the host
2699 */
2700 var protocolRemoved = hostProtocolSplit.length === 1 ? hostProtocolSplit[0] : hostProtocolSplit[1];
2701
2702 /**
2703 * Remove the protocol
2704 */
2705 var hostPortSplit = protocolRemoved.split(':');
2706
2707 /**
2708 * Assign the modified host
2709 */
2710 serverDetail.ftpHost = hostPortSplit[0];
2711
2712 /**
2713 * Start the validation
2714 */
2715 transferito.manualServerDetailValidation(
2716 securityKey,
2717 serverDetail,
2718 'Please wait.. ',
2719 'We\'re just validating your FTP details.',
2720 );
2721 }
2722
2723 /**
2724 * Enable the button if validation has failed
2725 */
2726 if (!validateFields) {
2727 $(this).prop('disabled', false);
2728 }
2729 });
2730
2731 /**
2732 * Validate the correct directory
2733 * @todo Cleanup to mimic new search directories
2734 * @deprecated
2735 */
2736 transferito.utilities.selector.on('click', '.transferito__directory-selection-validation', function() {
2737 /**
2738 * Disable the Button to stop double checks
2739 */
2740 $(this).prop('disabled', true);
2741
2742 /**
2743 *
2744 */
2745 transferito.screenRouting(
2746 'databaseAuthentication',
2747 'Please wait...',
2748 'While we load the database details screen'
2749 );
2750 });
2751
2752 /**
2753 * Continue to the Database Entry Screen
2754 */
2755 transferito.utilities.selector.on('click', '.transferito__proceed-to_database-details', function() {
2756 /**
2757 * Disable the Button to stop double checks
2758 */
2759 $(this).prop('disabled', true);
2760
2761 /**
2762 *
2763 */
2764 transferito.screenRouting(
2765 'databaseAuthentication',
2766 'Please wait...',
2767 'While we load the database details screen'
2768 );
2769 });
2770
2771
2772 /**
2773 * Validate the database details
2774 */
2775 transferito.utilities.selector.on('click', '.transferito__start-manual-migration', function() {
2776 /**
2777 * Disable the Button to stop double checks
2778 */
2779 $(this).prop('disabled', true);
2780
2781 /**
2782 * Validate that all required form fields have been completed
2783 */
2784 var validateFields = transferito.utilities.validateFormFields();
2785
2786 /**
2787 * If validation has passed
2788 */
2789 if (validateFields) {
2790 /**
2791 * Get the manual server details information
2792 */
2793 var databaseDetail = transferito.utilities.buildPayload();
2794
2795 /**
2796 * Get the wpNonce
2797 */
2798 var securityKey = $('#manualMigrationDatabaseDetail').val();
2799
2800 /**
2801 * Start the validation
2802 */
2803 transferito.databaseDetailValidation(
2804 securityKey,
2805 databaseDetail,
2806 'Please wait..',
2807 'We\'re just validating your database details'
2808 );
2809 }
2810
2811 /**
2812 * Re enable the button
2813 */
2814 if (!validateFields) {
2815 $(this).prop('disabled', false);
2816 }
2817
2818 });
2819
2820 /**
2821 * Return to ftp screen
2822 */
2823 transferito.utilities.selector.on('click', '.transferito__edit-directory', function() {
2824 /**
2825 * Disable the Button to stop double checks
2826 */
2827 $(this).prop('disabled', true);
2828
2829 /**
2830 *
2831 */
2832 transferito.loadDirectoryTemplate();
2833 });
2834
2835 /**
2836 * Close the modal by clicking on the background
2837 */
2838 transferito.utilities.selector.on('click', '.transferito__modal', function(event) {
2839
2840 var parentClassList = $(event.target).parents();
2841
2842 /**
2843 * Only close the modal if the class list does not include the inner modal class
2844 */
2845 if (!parentClassList.hasClass('transferito__modal__inner')) {
2846 $(this).closest('.transferito__modal').addClass('transferito__modal--hide');
2847 }
2848 });
2849
2850 /**
2851 * Toggle cPanel API Token
2852 */
2853 transferito.utilities.selector.on('change', '.show-cpanel-password', function() {
2854 $('#cpanelPasswordElement').toggleClass('transferito__hide-element');
2855 $('#cpanelAPITokenElement').toggleClass('transferito__hide-element');
2856 $('#cpanelAuth').prop('disabled', !transferito.utilities.validateFormFields());
2857 });
2858
2859 /**
2860 * Close the quickstart
2861 */
2862 transferito.utilities.selector.on('click', '.transferito__modal--hide-quickstart', function() {
2863 $(this).closest('.transferito__modal--without').addClass('transferito__modal--hide');
2864 transferito.hideQuickStartPopup();
2865 });
2866
2867 /**
2868 * Welcome screen - Change the selected migration method
2869 * Display a video based on the method
2870 */
2871 transferito.utilities.modalSelector.on('click', '.transferito-migration-method__selection-method', function() {
2872 var selector = $(this);
2873 var videoID = selector.data('associatedTutorialVideoId');
2874 var selectedClass = 'transferito-migration-method__selection-method--selected';
2875 var hiddenElementClass = 'transferito__hide-element';
2876
2877 $('.transferito-migration-method__selection-method').removeClass(selectedClass);
2878 $('.transferito-migration-method__recommended').addClass(hiddenElementClass)
2879
2880 selector.addClass(selectedClass);
2881 selector.find('.transferito-migration-method__recommended').removeClass(hiddenElementClass);
2882
2883 var videoHTML = '<iframe allowFullScreen id="ytplayer" type="text/html" src="https://www.youtube.com/embed/'
2884 videoHTML += videoID;
2885 videoHTML += '?autoplay=0&fs=1&rel=0" frameBorder="0"></iframe>';
2886
2887 transferito.utilities.setTemplate(
2888 videoHTML,
2889 transferito.utilities.modalSelector.find('#welcomeScreenVideo')
2890 );
2891 });
2892
2893 /**
2894 * Switch to the correct migration method
2895 */
2896 transferito.utilities.selector.on('click', '#selectTransferitoMigrationMethod', function() {
2897 var migrationMethod = $('.transferito-migration-method__selection-method--selected').data('selectMigrationMethod');
2898 transferito.switchMode(migrationMethod, 'Please wait...', 'We\'re just preparing your migration method');
2899 });
2900
2901 /**
2902 * Route the screen back to a desired screen
2903 */
2904 transferito.utilities.selector.on('click', '.transferito__screen-routing', function() {
2905 transferito.screenRouting(
2906 $(this).data('screenRoute'),
2907 'Please wait...',
2908 'While we redirect you to the correct screen'
2909 );
2910 });
2911
2912 /**
2913 * Validate the cPanel auth screen form fields - by checking at least two have been completed
2914 */
2915 transferito.utilities.selector.on('change keyup paste', '.transferito-cpanel-authentication__input input', function() {
2916 setTimeout(function(){
2917 $('#cpanelAuth').prop('disabled', !transferito.utilities.validateFormFields());
2918 },0);
2919 });
2920
2921 /**
2922 * Validate the ftp auth screen form fields - by checking at least two have been completed
2923 */
2924 transferito.utilities.selector.on('change keyup paste', '.transferito-ftp-authentication__input input', function() {
2925 setTimeout(function(){
2926 $('#manualServerDetails').prop('disabled', !transferito.utilities.validateFormFields());
2927 },0);
2928 });
2929
2930 /**
2931 * Validate the database auth screen form fields - by checking at least two have been completed
2932 */
2933 transferito.utilities.selector.on('change keyup paste', '.transferito-database-authentication__input input', function() {
2934 setTimeout(function(){
2935 $('#manualServerMigrationStart').prop('disabled', !transferito.utilities.validateFormFields());
2936 },0);
2937 });
2938
2939 /**
2940 * Validate the hosting form fields - by checking at least two have been completed
2941 */
2942 transferito.utilities.modalSelector.on('change keyup transferito__field-required', '.transferito-information__form-field input', function() {
2943 $('#fireRequestHostingGuide').prop('disabled', !transferito.utilities.validateFormFields());
2944 });
2945
2946 /**
2947 * Switch the information instructions based on the dropdown result
2948 */
2949 transferito.utilities.modalSelector.on('change', '#selectHostingProvider', function() {
2950 var guideID = 'guideFor_' + $(this).val();
2951 var guideName = $('#tutorialName').val();
2952 var videoID = $(this).find(':selected').data('guideVideo');
2953
2954 $('.transferito-information__steps-list').each(function() {
2955 var currentID = $(this).attr('id');
2956
2957 if (currentID === guideID) {
2958 $(this).removeClass('transferito__hide-element');
2959 } else if (guideID === 'guideFor_not-listed') {
2960 transferito.utilities.displayFormGuideModal('requestHostingGuideForm', guideName);
2961 } else if (currentID !== guideID) {
2962 $(this).addClass('transferito__hide-element');
2963 }
2964 });
2965
2966 /**
2967 * If the option contains a videoID
2968 * Replace current video with the new videoID
2969 */
2970 if (videoID) {
2971 var videoURL = 'https://www.youtube.com/embed/' + videoID + '?autoplay=1&fs=1&rel=0';
2972 var videoIframe = $('.transferito-information__video iframe:visible');
2973 videoIframe.attr('src', videoURL);
2974 }
2975 });
2976
2977 /**
2978 * Process sending the guide details
2979 */
2980 transferito.utilities.modalSelector.on('click', '.transferito__request-hosting-guide', function() {
2981 /**
2982 * Disable the Button to stop double checks
2983 */
2984 $(this).prop('disabled', true);
2985
2986 /**
2987 * Validate that all required form fields have been completed
2988 */
2989 var validateFields = transferito.utilities.validateFormFields();
2990
2991 /**
2992 * If validation has passed
2993 */
2994 if (validateFields) {
2995 /**
2996 * Get the manual server details information
2997 */
2998 var hostingGuideDetail = {
2999 securityKey: $('#hostingGuideDetails').val(),
3000 guideName: $('#hostingGuideName').val(),
3001 hostingProvider: $('#field__hostingProvider').val(),
3002 emailAddress: $('#field__emailAddress').val()
3003 };
3004
3005 transferito.sendGuideRequestForm(
3006 hostingGuideDetail,
3007 'Please wait...',
3008 'We\'re just sending your request'
3009 );
3010 }
3011
3012 /**
3013 * Re-enable the button
3014 */
3015 if (!validateFields) {
3016 $(this).prop('disabled', false);
3017 }
3018 });
3019
3020 /**
3021 * Log Event on external links clicked
3022 */
3023 $('#wpwrap').on('click', '.transferito-log-event', function() {
3024 transferito.utilities.logEvent('externalLinkClicked', {
3025 destination: $(this).data('eventName')
3026 });
3027 });
3028
3029 /**
3030 * When the Destination URL is pasted or selected via input autofill dropdown
3031 * If the Destination URL has a protocol - Strip it and select the domain protocol
3032 */
3033 transferito.utilities.selector.on('paste change', '#domain', function(event) {
3034 var target = $(event.target);
3035
3036 setTimeout(function(){
3037 var pastedContent = target.val();
3038 var splitContent = pastedContent.trim().split('://');
3039
3040 /**
3041 * Validate the correct protocol will be selected
3042 */
3043 if (splitContent.length === 2) {
3044 var allowedProtocols = ['http://', 'https://'];
3045 var defaultProtocol = allowedProtocols[0];
3046 var protocol = splitContent[0] + '://';
3047 var domain = splitContent[1];
3048 var isUserSpecifiedProtocolAllowed = allowedProtocols.includes(protocol);
3049 var validatedProtocol = isUserSpecifiedProtocolAllowed ? protocol : defaultProtocol;
3050
3051 $('#domain').val(domain);
3052 $('#domainProtocol').val(validatedProtocol);
3053
3054 $('#cpanelCheck').prop('disabled', false);
3055 }
3056 },0);
3057
3058 });
3059
3060 /**
3061 * When the Upgrade API Keys are pasted or changed
3062 * Enable or Disable the "ResumeMigration" button
3063 */
3064 transferito.utilities.modalSelector.on('paste change keyup', '.transferito-input__upgrade-premium-api-keys', function(event) {
3065 setTimeout(function(){
3066 var validateFields = transferito.utilities.validateFormFields();
3067
3068 /**
3069 * If the fields are validated
3070 * The "validateFormFields" method returns true
3071 * Flip the response
3072 */
3073 $('#updateYourAPIKeys').prop('disabled', !validateFields);
3074 },0);
3075 });
3076
3077 /**
3078 * Process sending the guide details
3079 */
3080 transferito.utilities.modalSelector.on('click', '.transferito_upgrade-save-api-keys', function() {
3081 /**
3082 * Disable the Button to stop double checks
3083 */
3084 $(this).prop('disabled', true);
3085
3086 /**
3087 * Validate that all required form fields have been completed
3088 */
3089 var validateFields = transferito.utilities.validateFormFields();
3090
3091 /**
3092 * If validation has passed
3093 */
3094 if (validateFields) {
3095
3096 var loadingSelector = $('#upgradeToPremiumLoading');
3097 var apiKeyPayload = {
3098 publicKey: $('#upgradePremiumPublicKey').val(),
3099 secretKey: $('#upgradePremiumSecretKey').val(),
3100 securityKey: $('#upgradePremiumValidation').val()
3101 };
3102
3103 /**
3104 * Hide API Entry Screen
3105 */
3106 $('#upgradeToPremiumAPIKeyEntry').addClass('transferito__hide-element');
3107
3108 /**
3109 * Run the API Key Check
3110 */
3111 transferito.apiValidityCheck(apiKeyPayload, loadingSelector);
3112 }
3113
3114 });
3115
3116 /**
3117 * Process sending the guide details
3118 */
3119 transferito.utilities.modalSelector.on('click', '.transferito_upgraded-in-app-resume-migration', function() {
3120 /**
3121 * Disable the Button to stop double migrations being fired
3122 */
3123 $(this).prop('disabled', true);
3124
3125 /**
3126 * Fire the migration with the previous details
3127 */
3128 transferito.prepareMigration(
3129 transferito.utilities.tempMigrationDetails.details,
3130 transferito.utilities.tempMigrationDetails.key
3131 );
3132
3133 /**
3134 * Reset the temp migration details
3135 */
3136 transferito.utilities.clearTempMigrationDetails();
3137 });
3138
3139 /**
3140 *
3141 */
3142 transferito.utilities.selector.on('click', '.transferito__download-verification-file', function() {
3143
3144 /**
3145 * Disable the Button to stop double checks
3146 */
3147 $(this).prop('disabled', true);
3148
3149 var securityKey = $('#connectToServer').val();
3150 transferito.downloadVerificationFile(securityKey);
3151 });
3152
3153 /**
3154 * Welcome screen - Change the selected migration method
3155 * Display a video based on the method
3156 */
3157 transferito.utilities.modalSelector.on('click', '#hideWelcomeScreenPopup', function() {
3158 var selector = $(this);
3159 var checked = selector.prop('checked');
3160 var securityKey = $('#welcomeScreenSecurity').val();
3161
3162 /**
3163 * Perform action when the site is checked
3164 */
3165 if (checked) {
3166 /**
3167 * Close the modal - when this is checked
3168 */
3169 transferito.utilities.closeModal();
3170
3171 /**
3172 * Update users preference to not show the welcome screen again
3173 */
3174 transferito.hideWelcomeScreen(securityKey);
3175 }
3176 });
3177
3178 /**
3179 *
3180 */
3181 $('body').on('click', '.transferito-open-support-modal', function () {
3182 var modalName = $(this).data('transferitoModal');
3183 transferito.utilities.displayModal(modalName)
3184 });
3185
3186 });
3187
3188 })(jQuery);
3189