(function ( $ ) {
'use strict';
window.InlineShortcodeView_vc_pie = window.InlineShortcodeView.extend( {
render: function () {
_.bindAll( this, 'parentChanged' );
window.InlineShortcodeView_vc_pie.__super__.render.call( this );
this.unbindResize();
vc.frame_window.vc_iframe.addActivity( function () {
this.vc_iframe.vc_pieChart();
} );
return this;
},
unbindResize: function () {
vc.frame_window.jQuery( vc.frame_window ).unbind( 'resize.vcPieChartEditable' );
},
parentChanged: function () {
this.$el.find( '.vc_pie_chart' ).removeClass( 'vc_ready' );
vc.frame_window.vc_pieChart();
},
rowsColumnsConverted: function () {
window.setTimeout( this.parentChanged, 200 );
this.parentChanged();
}
} );
})( window.jQuery );
/*! elementor - v3.13.1 - 09-05-2023 */
.elementor-column .elementor-spacer-inner{height:var(--spacer-size)}.e-con{--container-widget-width:100%}.e-con-inner>.elementor-widget-spacer,.e-con>.elementor-widget-spacer{width:var(--container-widget-width,var(--spacer-size));--align-self:var(--container-widget-align-self,initial);--flex-shrink:0}.e-con-inner>.elementor-widget-spacer>.elementor-widget-container,.e-con-inner>.elementor-widget-spacer>.elementor-widget-container>.elementor-spacer,.e-con>.elementor-widget-spacer>.elementor-widget-container,.e-con>.elementor-widget-spacer>.elementor-widget-container>.elementor-spacer{height:100%}.e-con-inner>.elementor-widget-spacer>.elementor-widget-container>.elementor-spacer>.elementor-spacer-inner,.e-con>.elementor-widget-spacer>.elementor-widget-container>.elementor-spacer>.elementor-spacer-inner{height:var(--container-widget-height,var(--spacer-size))} /**
* Gutenberg Blocks
*
* All blocks should be included here since this is the file that
* Webpack is compiling as the input file.
*/
import './google-fonts/index.js';
.gutenverse-banner:not(.fetch) {
background: url('gutenverse-background.svg');
display: inline-block;
width: 300px;
height: 300px;
}
.gutenverse-banner .banner-content {
background: rgba(255, 255, 255, 0.18);
backdrop-filter: blur(10px);
/* Note: backdrop-filter has minimal browser support */
border-radius: 8px;
margin: 30px;
padding: 42px 16px 40px 17px;
text-align: center;
font-family: 'Roboto';
font-weight: 500;
}
.gutenverse-banner .banner-content .logo-wrapper {
margin-bottom: 18.47px;
}
.gutenverse-banner .banner-content .main-content {
color: #FFFFFF;
font-size: 14px;
line-height: 20.33px;
margin-bottom: 20px;
display: inline-block;
font-weight: 400;
}
.gutenverse-banner .buttons {
font-size: 12px;
line-height: 14.06px;
}
.gutenverse-banner .buttons a {
padding: 11px 24px;
background: #FFFFFF;
border-radius: 50px;
text-decoration: none;
display: inline-block;
font-weight: 500;
color: #0051DD;
}
.gutenverse-banner.fetch a img {
border-radius: 5px;
}
The MIT License (MIT)
Copyright (c) 2016 - 2018 Paragon Initiative Enterprises
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
This library was based on the work of Steve "Sc00bz" Thomas.
------------------------------------------------------------------------------
The MIT License (MIT)
Copyright (c) 2014 Steve Thomas
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
/*!
*
* Package: php-parser
* Parse PHP code from JS and returns its AST
* Build: 546cb0da384f6fc5d54c - 12/31/2024
* Copyright (C) 2021 Glayzzle (BSD-3-Clause)
* @authors https://github.com/glayzzle/php-parser/graphs/contributors
* @url http://glayzzle.com
*
*/
Warning : Undefined variable $message in /home/cafepikk21/public_html/wp-content/themes/betheme/functions/modules/class-mfn-dynamic-data.php on line 24
/**
* Advanced Headers
*
* @include
* 1 - Advanced Headers Common
* 2 - Advanced Headers Style 1
* 3 - Advanced Headers Style 2
*/
/*---------- Media Query min-width Structure ----------*/
/*---------- Media Query max-width Structure ----------*/
/*---------- Break-point min-width Structure ----------*/
/*---------- Break-point max-width Structure ----------*/
/** 1 - Advanced Headers Common */
/**
* Advanced Headers Common
*
* Contents
*/
/*---------- Media Query min-width Structure ----------*/
/*---------- Media Query max-width Structure ----------*/
/*---------- Break-point min-width Structure ----------*/
/*---------- Break-point max-width Structure ----------*/
.ast-title-bar-wrap {
position: relative;
background-color: #eaeaea;
}
.ast-custom-post-type .ast-title-bar-wrap ~ .site-content .entry-header {
margin-bottom: 0;
}
.ast-advanced-headers-title {
line-height: 1.2;
}
.ast-advanced-headers-title .entry-subtitle {
margin-top: 15px;
}
.ast-advanced-headers-wrap,
.ast-advanced-headers-title,
.ast-advanced-headers-breadcrumb,
.ast-advanced-headers-breadcrumb a {
color: #eaeaea;
}
.ast-advanced-headers-breadcrumb a:hover {
color: #ffffff;
}
.ast-advanced-headers-wrap,
.ast-advanced-headers-breadcrumb {
z-index: 1;
position: relative;
}
/* Tax Description */
.taxonomy-description {
margin-top: 1em;
}
.taxonomy-description p {
margin: 0;
}
.ast-advanced-headers-wrap,
.ast-advanced-headers-breadcrumb {
word-wrap: break-word;
}
.ast-advanced-headers-layout {
padding-top: 1.33333em;
padding-bottom: 1.33333em;
}
/* Merge Advanced Headers */
.ast-merged-advanced-header .main-header-bar,
.ast-merged-advanced-header .ast-above-header,
.ast-merged-advanced-header .ast-below-header {
background: transparent;
}
.ast-merged-advanced-header.ast-full-advanced-header {
height: 100vh;
}
.ast-advanced-headers-vertical-center {
-js-display: flex;
display: flex;
flex-direction: column;
flex-wrap: nowrap;
height: 100%;
}
.ast-full-advanced-header .ast-inside-advanced-header-content {
-js-display: flex;
display: flex;
flex-direction: column;
flex-grow: 1;
width: 100%;
align-items: center;
justify-content: center;
}
/* Both Page Header & Transparent Header is enabled then override the transparent header styling */
.ast-advanced-headers.ast-theme-transparent-header #masthead {
position: static;
right: auto;
left: auto;
}
!function(t,e){for(var n in e)t[n]=e[n]}(window,function(t){function e(e){for(var n,r,o=e[0],a=e[1],s=0,c=[];s0&&void 0!==f[0]?f[0]:".swiper-container",r=f.length>1&&void 0!==f[1]?f[1]:{},o=f.length>2&&void 0!==f[2]?f[2]:{},a={effect:"slide",grabCursor:!0,init:!0,initialSlide:0,navigation:{nextEl:".swiper-button-next",prevEl:".swiper-button-prev"},pagination:{bulletElement:"button",clickable:!0,el:".swiper-pagination",type:"bullets"},preventClicksPropagation:!1,releaseFormElements:!1,setWrapperSize:!0,touchStartPreventDefault:!1,on:Object(s.mapValues)(o,(function(t){return function(){t(this)}}))},t.next=6,Promise.all([n.e(29).then(n.t.bind(null,438,7)),n.e(29).then(n.t.bind(null,439,7))]);case 6:return c=t.sent,u=i()(c,1),l=u[0].default,t.abrupt("return",new l(e,Object(s.merge)({},a,r)));case 10:case"end":return t.stop()}}),t)})))).apply(this,arguments)}},239:function(t,e,n){},26:function(t,e){function n(t,e,n,r,i,o,a){try{var s=t[o](a),c=s.value}catch(u){return void n(u)}s.done?e(c):Promise.resolve(c).then(r,i)}t.exports=function(t){return function(){var e=this,r=arguments;return new Promise((function(i,o){var a=t.apply(e,r);function s(t){n(a,i,o,s,c,"next",t)}function c(t){n(a,i,o,s,c,"throw",t)}s(void 0)}))}}},3:function(t,e){t.exports=window.lodash},48:function(t,e,n){"object"==typeof window&&window.Jetpack_Block_Assets_Base_Url&&window.Jetpack_Block_Assets_Base_Url.url&&(n.p=window.Jetpack_Block_Assets_Base_Url.url)},514:function(t,e,n){n(52),t.exports=n(515)},515:function(t,e,n){"use strict";n.r(e);var r=n(3),i=n(57),o=n.n(i),a=n(72),s=n(154),c=n(71);"undefined"!=typeof window&&o()((function(){var t=document.getElementsByClassName("wp-block-jetpack-slideshow");Object(r.forEach)(t,(function(t){if("true"!==t.getAttribute("data-jetpack-block-initialized")){var e=t.dataset,n=e.autoplay,r=e.delay,i=e.effect,o=window.matchMedia("(prefers-reduced-motion: reduce)").matches,u=n&&!o,l=t.getElementsByClassName("swiper-container")[0],f=null;Object(s.a)(l,{autoplay:!!u&&{delay:1e3*r,disableOnInteraction:!1},effect:i,init:!0,initialSlide:0,loop:!0,keyboard:{enabled:!0,onlyInViewport:!0}},{init:c.b,imagesReady:c.d,paginationRender:c.c,transitionEnd:c.a}).then((function(t){new a.a((function(){f&&(cancelAnimationFrame(f),f=null),f=requestAnimationFrame((function(){Object(c.d)(t),t.update()}))})).observe(t.el)})).catch((function(){t.querySelector(".wp-block-jetpack-slideshow_container").classList.add("wp-swiper-initialized")})),t.setAttribute("data-jetpack-block-initialized","true")}}))}))},52:function(t,e,n){"use strict";n.r(e);n(48)},57:function(t,e){t.exports=window.wp.domReady},71:function(t,e,n){"use strict";n.d(e,"a",(function(){return c})),n.d(e,"b",(function(){return a})),n.d(e,"c",(function(){return u})),n.d(e,"d",(function(){return s}));var r=n(113),i=n(3),o="wp-block-jetpack-slideshow_autoplay-paused";function a(t){s(t),c(t),document.querySelector("body").dispatchEvent(new Event("jetpack-lazy-images-load")),t.el.querySelector(".wp-block-jetpack-slideshow_button-pause").addEventListener("click",(function(){t.el&&(t.el.classList.contains(o)?(t.el.classList.remove(o),t.autoplay.start(),this.setAttribute("aria-label","Pause Slideshow")):(t.el.classList.add(o),t.autoplay.stop(),this.setAttribute("aria-label","Play Slideshow")))}))}function s(t){if(t&&t.el){var e=t.el.querySelector('.swiper-slide[data-swiper-slide-index="0"] img');if(e){var n=e.clientWidth/e.clientHeight,r=Math.max(Math.min(n,1.7777777777777777),1),i="undefined"!=typeof window?.8*window.innerHeight:600,o=Math.min(t.width/r,i),a="".concat(Math.floor(o),"px"),s="".concat(Math.floor(o/2),"px");t.el.classList.add("wp-swiper-initialized"),t.wrapperEl.style.height=a,t.el.querySelector(".wp-block-jetpack-slideshow_button-prev").style.top=s,t.el.querySelector(".wp-block-jetpack-slideshow_button-next").style.top=s}}}function c(t){Object(i.forEach)(t.slides,(function(e,n){e.setAttribute("aria-hidden",n===t.activeIndex?"false":"true"),n===t.activeIndex?e.setAttribute("tabindex","-1"):e.removeAttribute("tabindex")})),function(t){var e=t.slides[t.activeIndex];if(e){var n=e.getElementsByTagName("FIGCAPTION")[0],i=e.getElementsByTagName("IMG")[0];t.a11y.liveRegion&&(t.a11y.liveRegion[0].innerHTML=n?n.innerHTML:Object(r.escapeHTML)(i.alt))}}(t)}function u(t){Object(i.forEach)(t.pagination.bullets,(function(e){e.addEventListener("click",(function(){var e=t.slides[t.realIndex];setTimeout((function(){e.focus()}),500)}))}))}},72:function(t,e,n){"use strict";var r=function(){if("undefined"!=typeof Map)return Map;function t(t,e){var n=-1;return t.some((function(t,r){return t[0]===e&&(n=r,!0)})),n}return function(){function e(){this.__entries__=[]}return Object.defineProperty(e.prototype,"size",{get:function(){return this.__entries__.length},enumerable:!0,configurable:!0}),e.prototype.get=function(e){var n=t(this.__entries__,e),r=this.__entries__[n];return r&&r[1]},e.prototype.set=function(e,n){var r=t(this.__entries__,e);~r?this.__entries__[r][1]=n:this.__entries__.push([e,n])},e.prototype.delete=function(e){var n=this.__entries__,r=t(n,e);~r&&n.splice(r,1)},e.prototype.has=function(e){return!!~t(this.__entries__,e)},e.prototype.clear=function(){this.__entries__.splice(0)},e.prototype.forEach=function(t,e){void 0===e&&(e=null);for(var n=0,r=this.__entries__;n0},t.prototype.connect_=function(){i&&!this.connected_&&(document.addEventListener("transitionend",this.onTransitionEnd_),window.addEventListener("resize",this.refresh),c?(this.mutationsObserver_=new MutationObserver(this.refresh),this.mutationsObserver_.observe(document,{attributes:!0,childList:!0,characterData:!0,subtree:!0})):(document.addEventListener("DOMSubtreeModified",this.refresh),this.mutationEventsAdded_=!0),this.connected_=!0)},t.prototype.disconnect_=function(){i&&this.connected_&&(document.removeEventListener("transitionend",this.onTransitionEnd_),window.removeEventListener("resize",this.refresh),this.mutationsObserver_&&this.mutationsObserver_.disconnect(),this.mutationEventsAdded_&&document.removeEventListener("DOMSubtreeModified",this.refresh),this.mutationsObserver_=null,this.mutationEventsAdded_=!1,this.connected_=!1)},t.prototype.onTransitionEnd_=function(t){var e=t.propertyName,n=void 0===e?"":e;s.some((function(t){return!!~n.indexOf(t)}))&&this.refresh()},t.getInstance=function(){return this.instance_||(this.instance_=new t),this.instance_},t.instance_=null,t}(),l=function(t,e){for(var n=0,r=Object.keys(e);n0},t}(),E="undefined"!=typeof WeakMap?new WeakMap:new r,O=function t(e){if(!(this instanceof t))throw new TypeError("Cannot call a class as a function.");if(!arguments.length)throw new TypeError("1 argument required, but only 0 present.");var n=u.getInstance(),r=new g(e,n,this);E.set(this,r)};["observe","unobserve","disconnect"].forEach((function(t){O.prototype[t]=function(){var e;return(e=E.get(this))[t].apply(e,arguments)}}));var k=void 0!==o.ResizeObserver?o.ResizeObserver:O;e.a=k},75:function(t,e,n){var r=n(84);t.exports=function(t,e){if(t){if("string"==typeof t)return r(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?r(t,e):void 0}}},84:function(t,e){t.exports=function(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n {
const { nextStep } = useNavigateSteps();
const [ showProgressBar, setShowProgressBar ] = useState( true );
const [ isReadyForImport, setIsReadyForImport ] = useState( false );
const [ isFetchingStatus, setIsFetchingStatus ] = useState( false );
const {
websiteInfo,
aiStepData: {
businessName,
selectedTemplate,
selectedImages,
siteLanguageList,
siteLanguage,
},
aiSiteLogo,
aiSiteTitleVisible,
aiActiveTypography,
aiActivePallette,
siteFeatures,
siteFeaturesData,
} = useSelect( ( select ) => {
const {
getWebsiteInfo,
getAIStepData,
getSiteLogo,
getSiteTitleVisible,
getActiveTypography,
getActiveColorPalette,
getSiteFeatures,
getSiteFeaturesData,
} = select( STORE_KEY );
return {
websiteInfo: getWebsiteInfo(),
aiStepData: getAIStepData(),
aiSiteLogo: getSiteLogo(),
aiSiteTitleVisible: getSiteTitleVisible(),
aiActiveTypography: getActiveTypography(),
aiActivePallette: getActiveColorPalette(),
siteFeatures: getSiteFeatures(),
siteFeaturesData: getSiteFeaturesData(),
};
}, [] );
const {
importEnd,
importPercent,
templateResponse,
reset,
themeStatus,
importError,
customizerImportFlag,
widgetImportFlag,
contentImportFlag,
themeActivateFlag,
requiredPluginsDone,
requiredPlugins,
notInstalledList,
notActivatedList,
tryAgainCount,
xmlImportDone,
pluginInstallationAttempts,
importErrorMessages,
templateId,
} = useSelect( ( select ) => {
const { getImportSiteProgressData } = select( STORE_KEY );
return {
...getImportSiteProgressData(),
};
}, [] );
const { updateImportAiSiteData: dispatch } = useDispatch( STORE_KEY );
const percentage = useRef( importPercent );
const randomMessage = useMemo( getMessage, [] );
let currentStep = 0;
/**
*
* @param {string} primary Primary text for the error.
* @param {string} secondary Secondary text for the error.
* @param {string} text Text received from the AJAX call.
* @param {string} code Error code received from the AJAX call.
* @param {string} solution Solution provided for the current error.
* @param {string} stack
*/
const report = (
primary = '',
secondary = '',
text = '',
code = '',
solution = '',
stack = ''
) => {
dispatch( {
importError: true,
importErrorMessages: {
primaryText: primary,
secondaryText: secondary,
errorCode: code,
errorText:
typeof text === 'string' ? text : JSON.stringify( text ),
solutionText: solution,
tryAgain: true,
},
} );
localStorage.removeItem( 'st-import-start' );
localStorage.removeItem( 'st-import-end' );
sendErrorReport(
primary,
secondary,
text,
code,
solution,
stack,
tryAgainCount
);
};
const sendErrorReport = (
primary = '',
secondary = '',
text = '',
code = '',
solution = '',
stack = ''
) => {
const error = JSON.stringify( {
primaryText: primary,
secondaryText: secondary,
errorCode: code,
errorText: text,
solutionText: solution,
tryAgain: true,
stack,
tryAgainCount,
} );
if ( tryAgainCount >= 2 ) {
generateAnalyticsLead( tryAgainCount, false, {
id: templateId,
page_builder: stepsData?.pageBuilder,
template_type: stepsData?.selectedTemplateIsPremium
? 'premium'
: 'free',
error,
} );
}
if ( ! reportError ) {
return;
}
const reportErr = new FormData();
reportErr.append( 'action', 'astra-sites-report_error' );
reportErr.append( '_ajax_nonce', aiBuilderVars._ajax_nonce );
reportErr.append( 'type', 'ai-builder' );
reportErr.append( 'page_builder', stepsData?.pageBuilder );
reportErr.append(
'template_type',
stepsData?.selectedTemplateIsPremium ? 'premium' : 'free'
);
reportErr.append(
'local_storage',
JSON.stringify(
getLocalStorageItem( 'ai-builder-onboarding-details' )
)
);
reportErr.append( 'error', error );
reportErr.append( 'id', templateId );
reportErr.append( 'plugins', JSON.stringify( requiredPlugins ) );
fetch( ajaxurl, {
method: 'post',
body: reportErr,
} );
};
const customizeWebsite = async () => {
const languageItem = siteLanguageList.find(
( item ) => item.code === siteLanguage
);
await setSiteLogo( aiSiteLogo );
await setColorPalettes( JSON.stringify( aiActivePallette ) );
await setSiteTitle( businessName, aiSiteTitleVisible );
await saveTypography( aiActiveTypography );
await setSiteLanguage( languageItem?.[ 'wordpress-code' ] ?? 'en_US' );
};
const { stepsData } = useSelect( ( select ) => {
const { getAIStepData } = select( STORE_KEY );
return {
stepsData: getAIStepData(),
};
}, [] );
/**
* Start Import Part 1.
*/
const importPart1 = async () => {
let resetStatus = false;
let customizerStatus = false;
let spectraStatus = false;
let sureCartStatus = false;
let imageDownloadStatus = false;
resetStatus = await resetOldSite();
if ( resetStatus ) {
imageDownloadStatus = await downloadImages();
}
if ( imageDownloadStatus ) {
customizerStatus = await importCustomizerJson();
}
if ( customizerStatus ) {
spectraStatus = await importSpectraSettings();
}
if ( spectraStatus ) {
sureCartStatus = await importSureCartSettings();
}
if ( sureCartStatus ) {
await importSiteContent();
}
};
/**
* Start Import Part 2.
*/
const importPart2 = async () => {
let optionsStatus = false;
let widgetStatus = false;
let finalStepStatus = false;
let gtReplaceBatch = false;
let imagesReplaceBatch = false;
let setSiteOptions = false;
optionsStatus = await importSiteOptions();
if ( optionsStatus ) {
widgetStatus = await importWidgets();
}
if ( widgetStatus ) {
gtReplaceBatch = await gtBatch();
}
if ( gtReplaceBatch ) {
imagesReplaceBatch = await replaceImagebatch();
}
if ( imagesReplaceBatch ) {
finalStepStatus = await importDone();
}
if ( finalStepStatus ) {
setSiteOptions = await waitForFullMigration();
}
if ( setSiteOptions ) {
await importSuccess();
generateAnalyticsLead( tryAgainCount, true, {
id: templateId,
page_builder: stepsData?.pageBuilder,
template_type: stepsData?.selectedTemplateIsPremium
? 'premium'
: 'free',
} );
}
};
/**
* Import Success.
*/
const importSuccess = async () => {
const data = new FormData();
data.append( 'action', 'astra-sites-import_success' );
data.append( '_ajax_nonce', aiBuilderVars._ajax_nonce );
const status = await fetch( ajaxurl, {
method: 'post',
body: data,
} )
.then( ( response ) => response.json() )
.then( async ( response ) => {
if ( response.success ) {
return true;
}
return false;
} );
return status;
};
/**
* Install Required plugins.
*/
const installRequiredPlugins = () => {
// Install Bulk.
if ( notInstalledList.length <= 0 ) {
dispatch( {
requiredPluginsDone: true,
} );
return;
}
percentage.current += 2;
dispatch( {
importStatus: __( 'Installing Required Plugins.', 'ai-builder' ),
importPercent: percentage.current,
} );
const copiedList = [ ...notInstalledList ];
notInstalledList.forEach( ( plugin ) => {
wp.updates.queue.push( {
action: 'install-plugin', // Required action.
data: {
slug: plugin.slug,
init: plugin.init,
name: plugin.name,
clear_destination: true,
ajax_nonce: aiBuilderVars._ajax_nonce,
success() {
dispatch( {
importStatus: sprintf(
// translators: Plugin Name.
__(
'%1$s plugin installed successfully.',
'ai-builder'
),
plugin.name
),
} );
const inactiveList = [ ...notActivatedList ];
inactiveList.push( plugin );
dispatch( {
notActivatedList: inactiveList,
} );
const notInstalledPluginList = copiedList;
notInstalledPluginList.forEach(
( singlePlugin, index ) => {
if ( singlePlugin.slug === plugin.slug ) {
notInstalledPluginList.splice( index, 1 );
}
}
);
dispatch( {
notInstalledList: notInstalledPluginList,
} );
},
error( err ) {
dispatch( {
pluginInstallationAttempts:
pluginInstallationAttempts + 1,
} );
let errText = err;
if ( err && undefined !== err.errorMessage ) {
errText = err.errorMessage;
if ( undefined !== err.errorCode ) {
errText = err.errorCode + ': ' + errText;
}
}
report(
sprintf(
// translators: Plugin Name.
__(
'Could not install the plugin - %s',
'ai-builder'
),
plugin.name
),
'',
errText,
'',
'',
err
);
},
},
} );
} );
// Required to set queue.
wp.updates.queueChecker();
};
/**
* Activate Plugin
*
* @param {Object} plugin
*/
const activatePlugin = ( plugin ) => {
percentage.current += 2;
dispatch( {
importStatus: sprintf(
// translators: Plugin Name.
__( 'Activating %1$s plugin.', 'ai-builder' ),
plugin.name
),
importPercent: percentage.current,
} );
const activatePluginOptions = new FormData();
activatePluginOptions.append(
'action',
'astra-sites-required_plugin_activate'
);
activatePluginOptions.append( 'init', plugin.init );
activatePluginOptions.append(
'_ajax_nonce',
aiBuilderVars._ajax_nonce
);
activatePluginOptions.append( 'slug', plugin.slug );
fetch( ajaxurl, {
method: 'post',
body: activatePluginOptions,
} )
.then( ( response ) => response.text() )
.then( ( text ) => {
let cloneResponse = [];
let errorReported = false;
try {
const response = JSON.parse( text );
cloneResponse = response;
if ( response.success ) {
const notActivatedPluginList = [ ...notActivatedList ];
notActivatedPluginList.forEach(
( singlePlugin, index ) => {
if ( singlePlugin.slug === plugin.slug ) {
notActivatedPluginList.splice( index, 1 );
}
}
);
dispatch( {
notActivatedList: notActivatedPluginList,
} );
percentage.current += 2;
dispatch( {
importStatus: sprintf(
// translators: Plugin Name.
__( '%1$s activated.', 'ai-builder' ),
plugin.name
),
importPercent: percentage.current,
} );
}
} catch ( error ) {
report(
sprintf(
// translators: Plugin name.
__(
`JSON_Error: Could not activate the required plugin - %1$s.`,
'ai-builder'
),
plugin.name
),
'',
error,
'',
sprintf(
// translators: %1$s is the opening tag with the URL, %2$s is the closing tag.
__(
'%1$sRead article%2$s to resolve the issue and continue importing the template.',
'ai-builder'
),
'',
' '
),
text
);
errorReported = true;
}
if ( ! cloneResponse.success && errorReported === false ) {
throw cloneResponse;
}
} )
.catch( ( error ) => {
dispatch( {
pluginInstallationAttempts: pluginInstallationAttempts + 1,
} );
report(
sprintf(
// translators: Plugin name.
__(
`Could not activate the required plugin - %1$s.`,
'ai-builder'
),
plugin.name
),
'',
error?.data?.message,
'',
sprintf(
// translators: %1$s is the opening tag, %2$s is the closing tag.
__(
'%1$sRead article%2$s to resolve the issue and continue importing the template.',
'ai-builder'
),
'',
' '
),
error
);
} );
};
/**
* 1. Reset.
* The following steps are covered here.
* 1. Settings backup file store.
* 2. Reset Customizer
* 3. Reset Site Options
* 4. Reset Widgets
* 5. Reset Forms and Terms
* 6. Reset all posts
*/
const resetOldSite = async () => {
if ( ! reset ) {
return true;
}
percentage.current += 2;
dispatch( {
importStatus: __( 'Resetting site.', 'ai-builder' ),
importPercent: percentage.current,
} );
let backupFileStatus = false;
let resetCustomizerStatus = false;
let resetWidgetStatus = false;
let resetOptionsStatus = false;
let reseteTermsStatus = false;
let resetPostsStatus = false;
/**
* Settings backup file store.
*/
backupFileStatus = await performSettingsBackup();
/**
* Reset Customizer.
*/
if ( backupFileStatus ) {
resetCustomizerStatus = await performResetCustomizer();
}
/**
* Reset Site Options.
*/
if ( resetCustomizerStatus ) {
resetOptionsStatus = await performResetSiteOptions();
}
/**
* Reset Widgets.
*/
if ( resetOptionsStatus ) {
resetWidgetStatus = await performResetWidget();
}
/**
* Reset Terms, Forms.
*/
if ( resetWidgetStatus ) {
reseteTermsStatus = await performResetTermsAndForms();
}
/**
* Reset Posts.
*/
if ( reseteTermsStatus ) {
resetPostsStatus = await performResetPosts();
}
if (
! (
resetCustomizerStatus &&
resetOptionsStatus &&
resetWidgetStatus &&
reseteTermsStatus &&
resetPostsStatus
)
) {
return false;
}
percentage.current += 10;
dispatch( {
importPercent: percentage.current >= 50 ? 50 : percentage.current,
importStatus: __( 'Reset for old website is done.', 'ai-builder' ),
} );
return true;
};
/**
* Reset a chunk of posts.
*
* @param {Object} chunk
*/
const performPostsReset = async ( chunk ) => {
const data = new FormData();
data.append( 'action', 'astra-sites-get_deleted_post_ids' );
data.append( '_ajax_nonce', aiBuilderVars._ajax_nonce );
dispatch( {
importStatus: __( `Resetting posts.`, 'ai-builder' ),
} );
const formOption = new FormData();
formOption.append( 'action', 'astra-sites-reset_posts' );
formOption.append( 'ids', JSON.stringify( chunk ) );
formOption.append( '_ajax_nonce', aiBuilderVars._ajax_nonce );
await fetch( ajaxurl, {
method: 'post',
body: formOption,
} )
.then( ( resp ) => resp.text() )
.then( ( text ) => {
let cloneData = [];
let errorReported = false;
try {
const result = JSON.parse( text );
cloneData = result;
if ( result.success ) {
percentage.current += 2;
dispatch( {
importPercent:
percentage.current >= 50
? 50
: percentage.current,
} );
} else {
throw result;
}
} catch ( error ) {
report(
__( 'Resetting posts failed.', 'ai-builder' ),
'',
error,
'',
'',
text
);
errorReported = true;
return false;
}
if ( ! cloneData.success && errorReported === false ) {
throw cloneData.data;
}
} )
.catch( ( error ) => {
report(
__( 'Resetting posts failed.', 'ai-builder' ),
'',
error?.message,
'',
'',
error
);
return false;
} );
return true;
};
/**
* 1.0 Perform Settings backup file stored.
*/
const performSettingsBackup = async () => {
dispatch( {
importStatus: __( 'Taking settings backup.', 'ai-builder' ),
} );
const customizerContent = new FormData();
customizerContent.append( 'action', 'astra-sites-backup_settings' );
customizerContent.append( '_ajax_nonce', aiBuilderVars._ajax_nonce );
const status = await fetch( ajaxurl, {
method: 'post',
body: customizerContent,
} )
.then( ( response ) => response.text() )
.then( ( text ) => {
const response = JSON.parse( text );
if ( response.success ) {
percentage.current += 2;
dispatch( {
importPercent: percentage.current,
} );
return true;
}
throw response.data;
} )
.catch( ( error ) => {
report(
__( 'Taking settings backup failed.', 'ai-builder' ),
'',
error?.message,
'',
'',
error
);
return false;
} );
return status;
};
/**
* 1.1 Perform Reset for Customizer.
*/
const performResetCustomizer = async () => {
dispatch( {
importStatus: __( 'Resetting customizer.', 'ai-builder' ),
} );
const customizerContent = new FormData();
customizerContent.append(
'action',
'astra-sites-reset_customizer_data'
);
customizerContent.append( '_ajax_nonce', aiBuilderVars._ajax_nonce );
const status = await fetch( ajaxurl, {
method: 'post',
body: customizerContent,
} )
.then( ( response ) => response.text() )
.then( ( text ) => {
try {
const response = JSON.parse( text );
if ( response.success ) {
percentage.current += 2;
dispatch( {
importPercent: percentage.current,
} );
return true;
}
throw response.data;
} catch ( error ) {
report(
__( 'Resetting customizer failed.', 'ai-builder' ),
'',
error?.message,
'',
'',
text
);
return false;
}
} )
.catch( ( error ) => {
report(
__( 'Resetting customizer failed.', 'ai-builder' ),
'',
error?.message,
'',
'',
error
);
return false;
} );
return status;
};
/**
* 1.2 Perform reset Site options
*/
const performResetSiteOptions = async () => {
dispatch( {
importStatus: __( 'Resetting site options.', 'ai-builder' ),
} );
const siteOptions = new FormData();
siteOptions.append( 'action', 'astra-sites-reset_site_options' );
siteOptions.append( '_ajax_nonce', aiBuilderVars._ajax_nonce );
const status = await fetch( ajaxurl, {
method: 'post',
body: siteOptions,
} )
.then( ( response ) => response.text() )
.then( ( text ) => {
try {
const data = JSON.parse( text );
if ( data.success ) {
percentage.current += 2;
dispatch( {
importPercent: percentage.current,
} );
return true;
}
throw data.data;
} catch ( error ) {
report(
__( 'Resetting site options Failed.', 'ai-builder' ),
'',
error?.message,
'',
'',
text
);
return false;
}
} )
.catch( ( error ) => {
report(
__( 'Resetting site options Failed.', 'ai-builder' ),
'',
error?.message,
'',
'',
error
);
return false;
} );
return status;
};
/**
* 1.3 Perform Reset for Widgets
*/
const performResetWidget = async () => {
const widgets = new FormData();
widgets.append( 'action', 'astra-sites-reset_widgets_data' );
widgets.append( '_ajax_nonce', aiBuilderVars._ajax_nonce );
dispatch( {
importStatus: __( 'Resetting widgets.', 'ai-builder' ),
} );
const status = await fetch( ajaxurl, {
method: 'post',
body: widgets,
} )
.then( ( response ) => response.text() )
.then( ( text ) => {
try {
const response = JSON.parse( text );
if ( response.success ) {
percentage.current += 2;
dispatch( {
importPercent: percentage.current,
} );
return true;
}
throw response.data;
} catch ( error ) {
report(
__(
'Resetting widgets JSON parse failed.',
'ai-builder'
),
'',
error,
'',
'',
text
);
return false;
}
} )
.catch( ( error ) => {
report(
__( 'Resetting widgets failed.', 'ai-builder' ),
'',
error,
'',
'',
error
);
return false;
} );
return status;
};
/**
* 1.4 Reset Terms and Forms.
*/
const performResetTermsAndForms = async () => {
const formOption = new FormData();
formOption.append( 'action', 'astra-sites-reset_terms_and_forms' );
formOption.append( '_ajax_nonce', aiBuilderVars._ajax_nonce );
dispatch( {
importStatus: __( 'Resetting terms and forms.', 'ai-builder' ),
} );
const status = await fetch( ajaxurl, {
method: 'post',
body: formOption,
} )
.then( ( response ) => response.text() )
.then( ( text ) => {
try {
const response = JSON.parse( text );
if ( response.success ) {
percentage.current += 2;
dispatch( {
importPercent: percentage.current,
} );
return true;
}
throw response.data;
} catch ( error ) {
report(
__( 'Resetting terms and forms failed.', 'ai-builder' ),
'',
error,
'',
'',
text
);
return false;
}
} )
.catch( ( error ) => {
report(
__( 'Resetting terms and forms failed.', 'ai-builder' ),
'',
error?.message,
'',
'',
error
);
return false;
} );
return status;
};
/**
* 1.5 Reset Posts.
*/
const performResetPosts = async () => {
const data = new FormData();
data.append( 'action', 'astra-sites-get_deleted_post_ids' );
data.append( '_ajax_nonce', aiBuilderVars._ajax_nonce );
dispatch( {
importStatus: __( 'Gathering posts for deletions.', 'ai-builder' ),
} );
let err = '';
const status = await fetch( ajaxurl, {
method: 'post',
body: data,
} )
.then( ( response ) => response.json() )
.then( async ( response ) => {
if ( response.success ) {
const chunkArray = divideIntoChunks( 10, response.data );
if ( chunkArray.length > 0 ) {
for (
let index = 0;
index < chunkArray.length;
index++
) {
await performPostsReset( chunkArray[ index ] );
}
}
return true;
}
err = response;
return false;
} );
if ( status ) {
dispatch( {
importStatus: __( 'Resetting posts done.', 'ai-builder' ),
} );
} else {
showErrorToast(
__( 'Resetting posts failed.', 'ai-builder' ),
err
);
}
return status;
};
const importCustomizerJson = async () => {
if ( ! customizerImportFlag ) {
percentage.current += 5;
dispatch( {
importPercent:
percentage.current >= 65 ? 65 : percentage.current,
} );
return true;
}
dispatch( {
importStatus: __( 'Importing forms.', 'ai-builder' ),
} );
const forms = new FormData();
forms.append( 'action', 'astra-sites-import_customizer_settings' );
forms.append( '_ajax_nonce', aiBuilderVars._ajax_nonce );
const status = await fetch( ajaxurl, {
method: 'post',
body: forms,
} )
.then( ( response ) => response.text() )
.then( ( text ) => {
try {
const data = JSON.parse( text );
if ( data.success ) {
percentage.current += 5;
dispatch( {
importPercent:
percentage.current >= 65
? 65
: percentage.current,
} );
return true;
}
throw data.data;
} catch ( error ) {
report(
__(
'Importing Customizer failed due to parse JSON error.',
'ai-builder'
),
'',
error,
'',
'',
text
);
return false;
}
} )
.catch( ( error ) => {
report(
__( 'Importing Customizer Failed.', 'ai-builder' ),
'',
error
);
return false;
} );
return status;
};
const downloadImages = async () => {
for ( let index = 0; index < selectedImages.length; index++ ) {
const formData = new FormData();
formData.append( 'action', 'astra-sites-download_image' );
formData.append( '_ajax_nonce', aiBuilderVars._ajax_nonce );
formData.append( 'index', index );
try {
dispatch( {
importStatus: sprintf(
//translators: %s: Image number.
__( 'Downloading Image %s', 'ai-builder' ),
index + 1
),
} );
const response = await fetch( ajaxurl, {
method: 'POST',
body: formData,
} );
const data = await response.json();
if ( ! data.success ) {
report(
__( 'Downloading images failed.', 'ai-builder' ),
'',
''
);
}
} catch ( error ) {
showErrorToast(
__( 'Downloading images failed.', 'ai-builder' ),
error
);
}
}
return true;
};
/**
* 5. Import Site Content XML.
*/
const importSiteContent = async () => {
if ( ! contentImportFlag ) {
percentage.current += 20;
dispatch( {
importPercent:
percentage.current >= 78 ? 78 : percentage.current,
xmlImportDone: true,
} );
return true;
}
dispatch( {
importStatus: __( 'Importing Site Content.', 'ai-builder' ),
} );
const wxr = await apiFetch( {
path: 'zipwp/v1/wxr',
method: 'POST',
data: {
template: selectedTemplate,
business_name: businessName,
},
} );
if ( wxr.success ) {
importXML( wxr.data );
} else {
report(
'Importing Site Content Failed.',
'',
JSON.stringify( wxr.data ?? wxr, null, 4 )
);
}
return true;
};
/**
* 6. Import Spectra Settings.
*/
const importSpectraSettings = async () => {
const spectraSettings =
templateResponse[ 'astra-site-spectra-options' ] || '';
if (
'' === spectraSettings ||
'null' === spectraSettings ||
spectraSettings?.length === 0
) {
return true;
}
dispatch( {
importStatus: __( 'Importing Spectra Settings.', 'ai-builder' ),
} );
const spectra = new FormData();
spectra.append( 'action', 'astra-sites-import_spectra_settings' );
spectra.append( '_ajax_nonce', aiBuilderVars._ajax_nonce );
const status = await fetch( ajaxurl, {
method: 'post',
body: spectra,
} )
.then( ( response ) => response.text() )
.then( ( text ) => {
try {
const data = JSON.parse( text );
if ( data.success ) {
percentage.current =
percentage.current < 70
? 70
: percentage.current + 2;
dispatch( {
importPercent:
percentage.current >= 70
? 70
: percentage.current,
} );
return true;
}
throw data.data;
} catch ( error ) {
report(
__(
'Importing Spectra Settings failed due to parse JSON error.',
'ai-builder'
),
'',
error,
'',
'',
text
);
return false;
}
} )
.catch( ( error ) => {
report(
__( 'Importing Spectra Settings Failed.', 'ai-builder' ),
'',
error
);
return false;
} );
return status;
};
/**
* 7. Import Surecart Settings.
*/
const importSureCartSettings = async () => {
const sourceID =
templateResponse?.[ 'astra-site-surecart-settings' ]?.id || '';
const sourceCurrency =
templateResponse?.[ 'astra-site-surecart-settings' ]?.currency ||
'usd';
const surecart = new FormData();
surecart.append( 'action', 'astra-sites-import_surecart_settings' );
surecart.append( '_ajax_nonce', aiBuilderVars._ajax_nonce );
if ( '' === sourceID || 'null' === sourceID ) {
const enabledFeatures = siteFeatures
.filter( ( feature ) => feature?.enabled )
.map( ( feature ) => feature?.id );
if (
enabledFeatures?.includes( 'ecommerce' ) &&
siteFeaturesData?.ecommerce_type === 'surecart'
) {
surecart.append( 'create_account', true );
} else {
return true;
}
}
surecart.append( 'source_id', sourceID );
surecart.append( 'source_currency', sourceCurrency );
const status = await fetch( ajaxurl, {
method: 'post',
body: surecart,
} )
.then( ( response ) => response.text() )
.then( ( text ) => {
try {
const data = JSON.parse( text );
if ( data.success ) {
percentage.current =
percentage.current < 75
? 75
: percentage.current + 2;
dispatch( {
importPercent:
percentage.current >= 75
? 75
: percentage.current,
} );
return true;
}
throw data.data;
} catch ( error ) {
report(
__(
'Importing Surecart Settings failed.',
'ai-builder'
),
'',
error,
'',
'',
text
);
return false;
}
} )
.catch( ( error ) => {
report(
__( 'Importing Surecart Settings Failed.', 'ai-builder' ),
'',
error
);
return false;
} );
return status;
};
/**
* Imports XML using EventSource.
*
* @param {JSON} data JSON object for all the content in XML
*/
const importXML = ( data ) => {
// Import XML though Event Source.
sseImport.data = data;
sseImport.render( dispatch, percentage.current );
const evtSource = new EventSource( sseImport.data.url );
evtSource.onmessage = ( message ) => {
const eventData = JSON.parse( message.data );
switch ( eventData.action ) {
case 'updateDelta':
sseImport.updateDelta( eventData.type, eventData.delta );
break;
case 'complete':
if ( false === eventData.error ) {
evtSource.close();
dispatch( {
xmlImportDone: true,
} );
} else {
report(
aiBuilderVars.xml_import_interrupted_primary,
'',
aiBuilderVars.xml_import_interrupted_error,
'',
aiBuilderVars.xml_import_interrupted_secondary
);
}
break;
}
};
evtSource.onerror = ( error ) => {
if ( ! ( error && error?.isTrusted ) ) {
evtSource.close();
report(
__(
'Importing Site Content Failed. - Import Process Interrupted',
'ai-builder'
),
'',
error
);
}
};
evtSource.addEventListener( 'log', function ( message ) {
const eventLogData = JSON.parse( message.data );
let importMessage = eventLogData.message || '';
if ( importMessage && 'info' === eventLogData.level ) {
importMessage = importMessage.replace( /"/g, function () {
return '';
} );
}
dispatch( {
importStatus: sprintf(
// translators: Response importMessage
__( 'Importing - %1$s', 'ai-builder' ),
importMessage
),
} );
} );
};
/**
* 6. Import Site Option table values.
*/
const importSiteOptions = async () => {
dispatch( {
importStatus: __( 'Importing Site Options.', 'ai-builder' ),
} );
const siteOptions = new FormData();
siteOptions.append( 'action', 'astra-sites-import_options' );
siteOptions.append( '_ajax_nonce', aiBuilderVars._ajax_nonce );
const status = await fetch( ajaxurl, {
method: 'post',
body: siteOptions,
} )
.then( ( response ) => response.text() )
.then( ( text ) => {
try {
const data = JSON.parse( text );
if ( data.success ) {
percentage.current = 80;
dispatch( {
importPercent: percentage.current,
} );
return true;
}
throw data.data;
} catch ( error ) {
report(
__(
'Importing Site Options failed due to parse JSON error.',
'ai-builder'
),
'',
error,
'',
'',
text
);
return false;
}
} )
.catch( ( error ) => {
report(
__( 'Importing Site Options Failed.', 'ai-builder' ),
'',
error
);
return false;
} );
return status;
};
/**
* 7. Import Site Widgets.
*/
const importWidgets = async () => {
if ( ! widgetImportFlag ) {
percentage.current += 3;
dispatch( {
importPercent:
percentage.current >= 83 ? 83 : percentage.current,
} );
return true;
}
dispatch( {
importStatus: __( 'Importing Widgets.', 'ai-builder' ),
} );
const widgetsData = templateResponse[ 'astra-site-widgets-data' ] || '';
const widgets = new FormData();
widgets.append( 'action', 'astra-sites-import_widgets' );
widgets.append( 'widgets_data', widgetsData );
widgets.append( '_ajax_nonce', aiBuilderVars._ajax_nonce );
const status = await fetch( ajaxurl, {
method: 'post',
body: widgets,
} )
.then( ( response ) => response.text() )
.then( ( text ) => {
try {
const data = JSON.parse( text );
if ( data.success ) {
percentage.current += 2;
dispatch( {
importPercent:
percentage.current >= 85
? 85
: percentage.current,
} );
return true;
}
throw data.data;
} catch ( error ) {
report(
__(
'Importing Widgets failed due to parse JSON error.',
'ai-builder'
),
'',
error,
'',
'',
text
);
return false;
}
} )
.catch( ( error ) => {
report(
__( 'Importing Widgets Failed.', 'ai-builder' ),
'',
error
);
return false;
} );
return status;
};
const gtBatch = async () => {
dispatch( {
importStatus: __( 'Processing content for pages.', 'ai-builder' ),
} );
const finalSteps = new FormData();
finalSteps.append( 'action', 'astra-sites-page_builder_batch' );
finalSteps.append( '_ajax_nonce', aiBuilderVars._ajax_nonce );
const status = await fetch( ajaxurl, {
method: 'post',
body: finalSteps,
} )
.then( ( response ) => response.text() )
.then( ( text ) => {
try {
const data = JSON.parse( text );
if ( data.success ) {
setTimeout( function () {
percentage.current =
percentage.current < 90
? 90
: percentage.current;
dispatch( {
importPercent:
percentage.current >= 90
? 90
: percentage.current,
} );
}, successMessageDelay );
return true;
}
throw data.data;
} catch ( error ) {
report(
__( 'Batch process failed.', 'ai-builder' ),
'',
error,
'',
'',
text
);
setTimeout( function () {
percentage.current =
percentage.current > 90
? 90
: percentage.current + 1;
dispatch( {
importPercent: percentage.current,
} );
}, successMessageDelay );
return false;
}
} )
.catch( ( error ) => {
report(
__( 'Batch process failed.', 'ai-builder' ),
'',
error
);
return false;
} );
return status;
};
const replaceImagebatch = async () => {
dispatch( {
importStatus: __( 'Processing images.', 'ai-builder' ),
} );
const finalSteps = new FormData();
finalSteps.append( 'action', 'astra-sites-image_replacement_batch' );
finalSteps.append( '_ajax_nonce', aiBuilderVars._ajax_nonce );
const status = await fetch( ajaxurl, {
method: 'post',
body: finalSteps,
} )
.then( ( response ) => response.text() )
.then( ( text ) => {
try {
const data = JSON.parse( text );
if ( data.success ) {
setTimeout( function () {
percentage.current =
percentage.current < 90
? 90
: percentage.current;
dispatch( {
importPercent:
percentage.current >= 90
? 90
: percentage.current,
} );
}, successMessageDelay );
return true;
}
throw data.data;
} catch ( error ) {
report(
__( 'Image processing failed.', 'ai-builder' ),
'',
error,
'',
'',
text
);
setTimeout( function () {
percentage.current =
percentage.current > 90
? 90
: percentage.current + 1;
dispatch( {
importPercent: percentage.current,
} );
}, successMessageDelay );
return false;
}
} )
.catch( ( error ) => {
report(
__( 'Image processing failed.', 'ai-builder' ),
'',
error
);
return false;
} );
return status;
};
/**
* 9. Final setup - Invoking Batch process.
*/
const importDone = async () => {
dispatch( {
importStatus: __( 'Final finishing.', 'ai-builder' ),
} );
const finalSteps = new FormData();
finalSteps.append( 'action', 'astra-sites-import_end' );
finalSteps.append( '_ajax_nonce', aiBuilderVars._ajax_nonce );
const status = await fetch( ajaxurl, {
method: 'post',
body: finalSteps,
} )
.then( ( response ) => response.text() )
.then( ( text ) => {
try {
const data = JSON.parse( text );
if ( data.success ) {
localStorage.setItem( 'st-import-end', +new Date() );
setTimeout( function () {
percentage.current =
percentage.current < 90
? 90
: percentage.current;
dispatch( {
importPercent:
percentage.current >= 90
? 90
: percentage.current,
} );
}, successMessageDelay );
return true;
}
throw data.data;
} catch ( error ) {
report(
__(
'Final finishing failed due to parse JSON error.',
'ai-builder'
),
'',
error,
'',
'',
text
);
setTimeout( function () {
percentage.current =
percentage.current > 90
? 90
: percentage.current + 1;
dispatch( {
importPercent: percentage.current,
} );
}, successMessageDelay );
localStorage.setItem( 'st-import-end', +new Date() );
return false;
}
} )
.catch( ( error ) => {
report(
__( 'Final finishing Failed.', 'ai-builder' ),
'',
error
);
return false;
} );
return status;
};
const waitForFullMigration = async () => {
try {
const randomToken = ( Math.random() * 200 )?.toString(); // to avoid response caching
const response = await apiFetch( {
path: `zipwp/v1/migration-status?uuid=${ websiteInfo.uuid }&token=${ randomToken }`,
method: 'GET',
headers: {
'X-WP-Nonce': aiBuilderVars.rest_api_nonce,
_ajax_nonce: aiBuilderVars._ajax_nonce,
},
} );
if ( response?.data?.data === 'yes' ) {
// Save customizations.
await customizeWebsite();
dispatch( {
importPercent: 100,
importEnd: true,
} );
setShowProgressBar( false );
return true;
} else if ( response?.data?.data === 'no' ) {
percentage.current += 2;
dispatch( {
importPercent:
percentage.current >= 98 ? 98 : percentage.current,
importStatus: randomMessage.next()?.value,
} );
setTimeout( () => {
waitForFullMigration();
}, 10000 );
}
} catch ( error ) {
percentage.current += 2;
dispatch( {
importPercent:
percentage.current >= 98 ? 98 : percentage.current,
importStatus: randomMessage.next()?.value,
} );
setTimeout( () => {
waitForFullMigration();
}, 10000 );
}
};
const preventRefresh = ( event ) => {
if ( importPercent < 100 ) {
event.returnValue = __(
'Are you sure you want to cancel the site import process?',
'ai-builder'
);
return event;
}
};
useEffect( () => {
window.addEventListener( 'beforeunload', preventRefresh ); // eslint-disable-line
return () => {
window.removeEventListener( 'beforeunload', preventRefresh ); // eslint-disable-line
};
}, [ importPercent ] ); // Add importPercent as a dependency.
// Add a useEffect to remove the event listener when importPercent is 100%.
useEffect( () => {
if ( importPercent === 100 ) {
window.removeEventListener( 'beforeunload', preventRefresh );
}
}, [ importPercent ] );
/**
* When try again button is clicked:
* There is a possibility that few/all the required plugins list is already installed.
* We cre-check the status of the required plugins here.
*/
useEffect( () => {
if ( tryAgainCount > 0 ) {
dispatch( {
importPercent: 0,
importStatus: __( 'Retrying Import.', 'ai-builder' ),
} );
handleImport();
}
}, [ tryAgainCount ] );
const setStartFlag = async () => {
const content = new FormData();
content.append( 'action', 'astra-sites-set_start_flag' );
content.append( '_ajax_nonce', aiBuilderVars._ajax_nonce );
content.append( 'uuid', websiteInfo.uuid );
content.append( 'template_type', 'ai' );
await fetch( ajaxurl, {
method: 'post',
body: content,
} );
};
const handleImport = async () => {
if ( ! importError ) {
localStorage.setItem( 'st-import-start', +new Date() );
dispatch( {
importStart: true,
importPercent: 0,
importStatus: __(
'Preparing your site for import…',
'ai-builder'
),
} );
percentage.current += 2;
dispatch( {
importStart: true,
importPercent: percentage.current,
importStatus: __(
'Preparing your site for import…',
'ai-builder'
),
} );
await setStartFlag();
setIsReadyForImport( true );
}
};
const handleImportStart = async () => {
// Get the import data from the AI site.
await getAiDemo( stepsData, dispatch, websiteInfo );
await checkRequiredPlugins( dispatch );
checkFileSystemPermissions( dispatch );
percentage.current += 3;
dispatch( {
importPercent: percentage.current,
importStatus: __( 'Starting Import.', 'ai-builder' ),
} );
if ( themeActivateFlag && false === themeStatus ) {
installAstra( percentage.current, dispatch );
} else {
dispatch( {
themeStatus: true,
} );
}
};
const tryAainCallback = () => {
dispatch( {
// Reset errors.
importErrorMessages: {},
importErrorResponse: [],
importError: false,
// Try again count.
tryAgainCount: tryAgainCount + 1,
// Reset import flags.
xmlImportDone: false,
resetData: [],
importStart: false,
importEnd: false,
importPercent: 0,
requiredPluginsDone: false,
themeStatus: false,
notInstalledList: [],
notActivatedList: [],
} );
};
const updateProgressBar = ( step, totalSteps ) => {
if ( step >= totalSteps ) {
percentage.current = 5;
dispatch( {
importPercent: percentage.current,
} );
return;
}
percentage.current = Math.floor( ( step / totalSteps ) * 5 );
dispatch( {
importPercent: percentage.current,
} );
};
const getDemoWithRetry = async () => {
try {
return getAiDemo( stepsData, dispatch, websiteInfo );
} catch ( error ) {
report( error );
}
};
const handleStatusResponse = async ( response ) => {
const responseCode = response?.data?.data?.code;
if ( ! ( responseCode in SITE_CREATION_STATUS_CODES ) ) {
dispatch( {
importStatus: __( 'Preparing the site…', 'ai-builder' ),
} );
await new Promise( ( resolve ) => setTimeout( resolve, 7000 ) );
return await fetchImportStatus();
}
const msg = SITE_CREATION_STATUS_CODES[ responseCode ]?.trim();
if ( response?.success ) {
const step = +responseCode?.slice( 1 );
// Avoid progress bar going back
if ( step > currentStep ) {
currentStep = step;
updateProgressBar( currentStep, TOTAL_STEPS );
}
// Make sure msg is not empty
if ( msg && msg !== 'Done' ) {
dispatch( {
importStatus: msg,
} );
// Refresh status after 7 seconds.
await new Promise( ( resolve ) => setTimeout( resolve, 7000 ) );
return await fetchImportStatus();
}
if ( msg === 'Done' ) {
dispatch( {
importStatus: __( 'Please wait a moment…', 'ai-builder' ),
} );
const reqResponse = await getDemoWithRetry();
if (
! reqResponse.success ||
( reqResponse.success &&
Object.keys?.( reqResponse )?.length === 0 )
) {
report(
__( 'Failed to create website', 'ai-builder' ),
'',
reqResponse?.data
);
return;
}
await checkRequiredPlugins( dispatch );
checkFileSystemPermissions( dispatch );
dispatch( {
importStatus: __(
'The website is created successfully!',
'ai-builder'
),
createSiteStatus: true,
} );
/**
* Start the pre import process.
* 1. Install Astra Theme
* 2. Install Required Plugins.
*/
handleImport();
}
} else {
report( msg );
}
};
const fetchImportStatus = async () => {
if ( isFetchingStatus ) {
return;
}
setIsFetchingStatus( true );
try {
const randomToken = ( Math.random() * 200 )?.toString(); // to avoid response caching
const response = await apiFetch( {
path: `zipwp/v1/import-status?uuid=${ websiteInfo.uuid }&token=${ randomToken }`,
method: 'GET',
headers: {
'X-WP-Nonce': aiBuilderVars.rest_api_nonce,
_ajax_nonce: aiBuilderVars._ajax_nonce,
},
} );
// explicit check
if ( response?.success === true ) {
await handleStatusResponse( response );
} else if ( response?.success === false ) {
report( __( 'Failed to create website', 'ai-builder' ) );
}
} catch ( error ) {
report( error );
} finally {
setIsFetchingStatus( false );
}
};
useEffect( () => {
fetchImportStatus();
}, [] );
useEffect( () => {
if ( isReadyForImport ) {
handleImportStart();
setIsReadyForImport( false );
}
}, [ isReadyForImport ] );
/**
* Start the process only when:
* 1. Required plugins are installed and activated.
* 2. Astra Theme is installed
*/
useEffect( () => {
if ( requiredPluginsDone && themeStatus ) {
importPart1();
}
}, [ requiredPluginsDone, themeStatus ] );
useEffect( () => {
if ( themeStatus ) {
installRequiredPlugins();
}
}, [ themeStatus, tryAgainCount ] );
/**
* Start Part 2 of the import once the XML is imported sucessfully.
*/
useEffect( () => {
if ( xmlImportDone ) {
importPart2();
}
}, [ xmlImportDone ] );
// This checks if all the required plugins are installed and activated.
useEffect( () => {
if (
! requiredPlugins ||
( requiredPlugins && ! Object.values( requiredPlugins ).length )
) {
return;
}
if ( notActivatedList.length <= 0 && notInstalledList.length <= 0 ) {
dispatch( {
requiredPluginsDone: true,
} );
}
}, [ notActivatedList, notInstalledList, requiredPlugins, tryAgainCount ] );
// Whenever a plugin is installed, this code sends an activation request.
useEffect( () => {
if (
! requiredPlugins ||
( requiredPlugins && ! Object.values( requiredPlugins ).length )
) {
return;
}
// Installed all required plugins.
if ( notActivatedList.length > 0 ) {
activatePlugin( notActivatedList[ 0 ] );
}
}, [ notActivatedList, requiredPlugins ] );
// Confirmation before leaving the page.
useEffect( () => {
const handleBeforeUnload = () => importPercent < 100;
window.onbeforeunload = handleBeforeUnload;
return () => {
window.onbeforeunload = null;
};
}, [ importPercent ] );
return (
<>
{ showProgressBar && ! importError && (
) }
{ importError && (
) }
{ ! importEnd && ! importError && (
{ __(
'We are building your website…',
'ai-builder'
) }
) }
{ ! importError && (
) }
{ ! importError && (
<>
>
) }
>
);
};
export default ImportAiSite;
!function(c){function r(){l.hide(),T.onerror=T.onload=null,j&&j.abort(),h.empty()}function s(){if(!1===v.onError(I,x,v))return l.hide(),N=!1;v.titleShow=!1,v.width="auto",v.height="auto",h.html('The requested content cannot be loaded. Please try again later.
'),L()}function a(){var n,t,e,i,a,o,d=I[x];if(r(),v=c.extend({},c.fn.fancybox.defaults,void 0===c(d).data("fancybox")?v:c(d).data("fancybox")),!1!==(o=v.onStart(I,x,v)))if("object"==typeof o&&(v=c.extend(v,o)),e=v.title||(d.nodeName?c(d).attr("title"):d.title)||"",d.nodeName&&!v.orig&&(v.orig=c(d).children("img:first").length?c(d).children("img:first"):c(d)),""===e&&v.orig&&v.titleFromAlt&&(e=v.orig.attr("alt")),n=v.href||(d.nodeName?c(d).attr("href"):d.href)||null,!/^(?:javascript)/i.test(n)&&"#"!=n||(n=null),v.type?(t=v.type,n=n||v.content):v.content?t="html":n&&(t=n.match(S)?"image":n.match(A)?"swf":c(d).hasClass("iframe")||function(t){var e=t.match(/(?:(?:http|https):\/\/)?(?:www\.)?youtube.com\/watch\?v=([a-zA-Z0-9\-_]+)/);if(e)return m="//www.youtube.com/embed/"+e[1],!0;var i=t.match(/(?:(?:http|https):\/\/)?(?:www\.)?vimeo.com\/([0-9]+)/);return!!i&&(m="//player.vimeo.com/video/"+i[1],!0)}(c(d).attr("href"))?"iframe":0===n.indexOf("#")?"inline":"ajax"),t)switch("inline"==t&&(d=n.substr(n.indexOf("#")),t=0 ').hide().insertBefore(c(d)).on("fancybox-cleanup",function(){c(this).replaceWith(f.children())}).on("fancybox-cancel",function(){c(this).replaceWith(h.children())}),c(d).appendTo(h),L();break;case"image":N=!1,c.fancybox.showActivity(),(T=new Image).onerror=function(){s()},T.onload=function(){N=!0,T.onerror=T.onload=null,M()},T.src=n;break;case"swf":v.scrolling="no",i=' ',a="",c.each(v.swf,function(t,e){i+=' ',a+=" "+t+'="'+e+'"'}),i+=' ",h.html(i),L();break;case"ajax":N=!1,c.fancybox.showActivity(),v.ajax.win=v.ajax.success,j=c.ajax(c.extend({},v.ajax,{url:n,data:v.ajax.data||{},error:function(t,e,i){0 ")[0],{prop:0}),P=navigator.userAgent.match(/msie [6]/i)&&!window.XMLHttpRequest,L=function(){var t=v.width,e=v.height,t=-1'),v.width=h.width(),v.height=h.height(),z()},M=function(){v.width=T.width,v.height=T.height,c(" ").attr({id:"fancybox-img",src:T.src,alt:v.title}).appendTo(h),z()},z=function(){var t,e;return l.hide(),n.is(":visible")&&!1===k.onCleanup(O,C,k)?(c.event.trigger("fancybox-cancel"),void(N=!1)):(N=!0,c(f.add(i)).off(),c(window).off("resize.fb scroll.fb"),c(document).off("keydown.fb"),n.is(":visible")&&"outside"!==k.titlePosition&&n.css("height",n.height()),O=I,C=x,(k=v).overlayShow?(i.css({"background-color":k.overlayColor,opacity:k.overlayOpacity,cursor:k.hideOnOverlayClick?"pointer":"auto",height:c(document).height()}),i.is(":visible")||(P&&c("select:not(#fancybox-tmp select)").filter(function(){return"hidden"!==this.style.visibility}).css({visibility:"hidden"}).one("fancybox-cleanup",function(){this.style.visibility="inherit"}),i.show())):i.hide(),w=q(),H(),n.is(":visible")?(c(d.add(g).add(b)).hide(),t=n.position(),u={top:t.top,left:t.left,width:n.width(),height:n.height()},e=u.width==w.width&&u.height==w.height,void f.fadeTo(k.changeFade,.3,function(){function t(){f.html(h.contents()).fadeTo(k.changeFade,1,R)}c.event.trigger("fancybox-change"),f.empty().removeAttr("filter").css({"border-width":k.padding,width:w.width-2*k.padding,height:v.autoDimensions?"auto":w.height-E-2*k.padding}),e?t():(B.prop=0,c(B).animate({prop:1},{duration:k.changeSpeed,easing:k.easingChange,step:W,complete:t}))})):(n.removeAttr("style"),f.css("border-width",k.padding),"elastic"==k.transitionIn?(u=Q(),f.html(h.contents()),n.show(),k.opacity&&(w.opacity=0),B.prop=0,void c(B).animate({prop:1},{duration:k.speedIn,easing:k.easingIn,step:W,complete:R})):("inside"==k.titlePosition&&0'+t+' ':''+t+"
"))&&""!==F){switch(p.addClass("fancybox-title-"+k.titlePosition).html(F).appendTo("body").show(),k.titlePosition){case"inside":p.css({width:w.width-2*k.padding,marginLeft:k.padding,marginRight:k.padding}),E=p.outerHeight(!0),p.appendTo(e),w.height+=E;break;case"over":p.css({marginLeft:k.padding,width:w.width-4*k.padding,bottom:k.padding}).appendTo(e);break;case"float":p.css("left",-1*parseInt((p.width()-w.width-40)/2,10)).appendTo(n);break;default:p.css({width:w.width-2*k.padding,paddingLeft:k.padding,paddingRight:k.padding}).appendTo(n)}p.hide()}else p.hide();else p.hide()},R=function(){c.support.opacity||(f.css("filter",""),n.css("filter","")),v.autoDimensions&&f.css("height","auto"),n.css("height","auto"),F&&F.length&&p.show(),k.showCloseButton&&d.show(),function(){if((k.enableEscapeButton||k.enableKeyboardNav)&&c(document).on("keydown.fb",function(t){27==t.keyCode&&k.enableEscapeButton?(t.preventDefault(),c.fancybox.close()):37!=t.keyCode&&39!=t.keyCode||!k.enableKeyboardNav||"INPUT"===t.target.tagName||"TEXTAREA"===t.target.tagName||"SELECT"===t.target.tagName||(t.preventDefault(),c.fancybox[37==t.keyCode?"prev":"next"]())}),!k.showNavArrows)return g.hide(),b.hide();(k.cyclic&&1').appendTo(f),m=""),n.show(),N=!1,c.fancybox.center(),k.onComplete(O,C,k),K()},K=function(){var t;O.length-1>C&&void 0!==(t=O[C+1].href)&&t.match(S)&&((new Image).src=t),0e[0]||i.height>e[1])&&("image"==v.type||"swf"==v.type?(t=k.width/k.height,i.width>e[0]&&(i.width=e[0],i.height=parseInt((i.width-a)/t+a,10)),i.height>e[1]&&(i.height=e[1],i.width=parseInt((i.height-a)*t+a,10))):(i.width=Math.min(i.width,e[0]),i.height=Math.min(i.height,e[1]))),i.top=parseInt(Math.max(e[3]-20,e[3]+.5*(e[1]-i.height-40)),10),i.left=parseInt(Math.max(e[2]-20,e[2]+.5*(e[0]-i.width-40)),10),i},Q=function(){var t,e,i,n=!!v.orig&&c(v.orig);return n&&n.length?((i=(e=n).offset()).top+=parseInt(e.css("paddingTop"),10)||0,i.left+=parseInt(e.css("paddingLeft"),10)||0,i.top+=parseInt(e.css("border-top-width"),10)||0,i.left+=parseInt(e.css("border-left-width"),10)||0,i.width=e.width(),i.height=e.height(),{width:i.width+2*k.padding,height:i.height+2*k.padding,top:i.top-k.padding-20,left:i.left-k.padding-20}):(t=o(),{width:2*k.padding,height:2*k.padding,top:parseInt(t[3]+.5*t[1],10),left:parseInt(t[2]+.5*t[0],10)})};c.fn.fancybox=function(t){return c(this).length&&c(this).data("fancybox",c.extend({},t,c.metadata?c(this).metadata():{})).off("click.fb").on("click.fb",function(t){var e;t.preventDefault(),N||(N=!0,c(this).trigger("blur"),I=[],x=0,(e=c(this).attr("rel")||c(this).data("rel"))&&""!=e&&"nofollow"!==e?(I=c('a[rel="'+e+'"], area[rel="'+e+'"], a[data-rel="'+e+'"]'),x=I.index(this)):I.push(this),a())}),this},c.fancybox=function(t){var e;if(!N){if(N=!0,e=void 0!==arguments[1]?arguments[1]:{},I=[],x=parseInt(e.index,10)||0,Array.isArray(t)){for(var i=0,n=t.length;iI.length||x<0)&&(x=0),a()}},c.fancybox.showActivity=function(){clearInterval(y),l.show(),y=setInterval(t,66)},c.fancybox.hideActivity=function(){l.hide()},c.fancybox.next=function(){return c.fancybox.pos(C+1)},c.fancybox.prev=function(){return c.fancybox.pos(C-1)},c.fancybox.pos=function(t){N||(t=parseInt(t),I=O,-1=O.length?0:O.length-1,a()))},c.fancybox.cancel=function(){N||(N=!0,c.event.trigger("fancybox-cancel"),r(),v.onCancel(I,x,v),N=!1)},c.fancybox.close=function(){var t;function e(){i.fadeOut("fast"),p.empty().hide(),n.hide(),c.event.trigger("fancybox-cleanup"),f.empty(),k.onClosed(O,C,k),O=v=[],C=x=0,k=v={},N=!1}N||n.is(":hidden")||(N=!0,k&&!1===k.onCleanup(O,C,k)?N=!1:(r(),c(d.add(g).add(b)).hide(),c(f.add(i)).off(),c(window).off("resize.fb scroll.fb"),c(document).off("keydown.fb"),f.find("iframe").attr("src",P&&/^https/i.test(window.location.href||"")?"javascript:void(false)":"about:blank"),"inside"!==k.titlePosition&&p.empty(),n.stop(),"elastic"==k.transitionOut?(u=Q(),t=n.position(),w={top:t.top,left:t.left,width:n.width(),height:n.height()},k.opacity&&(w.opacity=1),p.empty().hide(),B.prop=1,c(B).animate({prop:0},{duration:k.speedOut,easing:k.easingOut,step:W,complete:e})):n.fadeOut("none"==k.transitionOut?0:k.speedOut,e)))},c.fancybox.resize=function(){i.is(":visible")&&i.css("height",c(document).height()),c.fancybox.center(!0)},c.fancybox.center=function(){var t,e;N||(e=!0===arguments[0]?1:0,t=o(),!e&&(n.width()>t[0]||n.height()>t[1])||n.stop().animate({top:parseInt(Math.max(t[3]-20,t[3]+.5*(t[1]-f.height()-40)-k.padding)),left:parseInt(Math.max(t[2]-20,t[2]+.5*(t[0]-f.width()-40)-k.padding))},"number"==typeof arguments[0]?arguments[0]:200))},c.fancybox.init=function(){c("#fancybox-wrap").length||(c("body").append(h=c('
'),l=c(''),i=c('
'),n=c('
')),(e=c('
').append('
').appendTo(n)).append(f=c('
'),d=c(' '),p=c('
'),g=c(' '),b=c(' ')),d.on("click",c.fancybox.close),l.on("click",c.fancybox.cancel),g.on("click",function(t){t.preventDefault(),c.fancybox.prev()}),b.on("click",function(t){t.preventDefault(),c.fancybox.next()}),c.fn.mousewheel&&n.on("mousewheel.fb",function(t,e){N?t.preventDefault():0!=c(t.target).get(0).clientHeight&&c(t.target).get(0).scrollHeight!==c(t.target).get(0).clientHeight||(t.preventDefault(),c.fancybox[0').prependTo(e)))},c.fn.fancybox.defaults={padding:10,margin:40,opacity:!1,modal:!1,cyclic:!1,scrolling:"auto",width:560,height:340,autoScale:!0,autoDimensions:!0,centerOnScroll:!1,ajax:{},swf:{wmode:"transparent"},hideOnOverlayClick:!0,hideOnContentClick:!1,overlayShow:!0,overlayOpacity:.7,overlayColor:"#777",titleShow:!0,titlePosition:"float",titleFormat:null,titleFromAlt:!1,transitionIn:"fade",transitionOut:"fade",speedIn:300,speedOut:300,changeSpeed:300,changeFade:"fast",easingIn:"swing",easingOut:"swing",showCloseButton:!0,showNavArrows:!0,enableEscapeButton:!0,enableKeyboardNav:!0,onStart:function(){},onCancel:function(){},onComplete:function(){},onCleanup:function(){},onClosed:function(){},onError:function(){}},c(document).ready(function(){c.fancybox.init()})}(jQuery);No access.