Skip to content

Commit

Permalink
get categories
Browse files Browse the repository at this point in the history
  • Loading branch information
kadencewp committed Feb 14, 2024
1 parent f76ad98 commit 9eb8f61
Show file tree
Hide file tree
Showing 6 changed files with 262 additions and 69 deletions.
159 changes: 153 additions & 6 deletions includes/class-kadence-blocks-prebuilt-library-rest-api.php
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,14 @@ class Kadence_Blocks_Prebuilt_Library_REST_Controller extends WP_REST_Controller
*/
protected $remote_url = 'https://patterns.startertemplatecloud.com/wp-json/kadence-cloud/v1/get/';

/**
* The remote URL.
*
* @access protected
* @var string
*/
protected $remote_cat_url = 'https://patterns.startertemplatecloud.com/wp-json/kadence-cloud/v1/categories/';

/**
* The remote URL.
*
Expand All @@ -192,6 +200,14 @@ class Kadence_Blocks_Prebuilt_Library_REST_Controller extends WP_REST_Controller
*/
protected $remote_pages_url = 'https://patterns.startertemplatecloud.com/wp-json/kadence-cloud/v1/pages/';

/**
* The remote URL.
*
* @access protected
* @var string
*/
protected $remote_pages_cat_url = 'https://patterns.startertemplatecloud.com/wp-json/kadence-cloud/v1/pages-categories/';

/**
* The remote URL.
*
Expand Down Expand Up @@ -368,6 +384,18 @@ public function register_routes() {
),
)
);
register_rest_route(
$this->namespace,
'/get_library_categories',
array(
array(
'methods' => WP_REST_Server::READABLE,
'callback' => array( $this, 'get_library_categories' ),
'permission_callback' => array( $this, 'get_items_permission_check' ),
'args' => $this->get_collection_params(),
),
)
);
register_rest_route(
$this->namespace,
'/get_local_contexts',
Expand Down Expand Up @@ -964,7 +992,7 @@ public function get_pattern_content( WP_REST_Request $request ) {
}
// Get the response.
$api_url = add_query_arg( $args, $library_url );
$response = wp_safe_remote_get(
$response = wp_remote_get(
$api_url,
array(
'timeout' => 20,
Expand All @@ -989,7 +1017,79 @@ public function get_pattern_content( WP_REST_Request $request ) {

return rest_ensure_response( 'error' );
}
/**
* Retrieves a collection of objects.
*
* @param WP_REST_Request $request Full details about the request.
* @return WP_REST_Response Response object on success, or WP_Error object on failure.
*/
public function get_library_categories( WP_REST_Request $request ) {
$this->get_license_keys();
$reload = $request->get_param( self::PROP_FORCE_RELOAD );
$library = $request->get_param( self::PROP_LIBRARY );
$library_url = $request->get_param( self::PROP_LIBRARY_URL );
$key = $request->get_param( self::PROP_KEY );

if ( ! empty( $library_url ) ) {
$library_url = rtrim( $library_url, '/' ) . '/wp-json/kadence-cloud/v1/categories/';
} elseif ( ! empty( $library ) && 'pages' === $library ) {
$library_url = $this->remote_pages_cat_url;
$key = 'new-pages';
} else {
$library_url = $this->remote_cat_url;
}

$identifier = 'library-categories' . $library;

if ( ! empty( $this->api_key ) ) {
$identifier .= '_' . $this->api_key;
}

if ( ! empty( $key ) ) {
$identifier .= '_' . $key;
}

if ( 'templates' !== $library && 'pages' !== $library && 'section' !== $library && 'template' !== $library ) {
$cloud_settings = json_decode( get_option( 'kadence_blocks_cloud' ), true );
if ( ! empty( $cloud_settings['connections'][ $library ]['expires'] ) ) {
$expires = strtotime( get_date_from_gmt( $cloud_settings['connections'][ $library ]['expires'] ) );
$now = strtotime( get_date_from_gmt( current_time( 'Y-m-d H:i:s' ) ) );

if ( $expires < $now ) {
$refresh = ( ! empty( $cloud_settings['connections'][ $library ]['refresh'] ) ? $cloud_settings['connections'][ $library ]['refresh'] : 'month' );
if ( 'day' === $refresh ) {
$expires_add = DAY_IN_SECONDS;
} elseif ( 'week' === $refresh ) {
$expires_add = WEEK_IN_SECONDS;
} else {
$expires_add = MONTH_IN_SECONDS;
}
$cloud_settings['connections'][ $library ]['expires'] = gmdate( 'Y-m-d H:i:s', strtotime( current_time( 'mysql' ) ) + $expires_add );
update_option( 'kadence_blocks_cloud', json_encode( $cloud_settings ) );
$reload = true;
}
}
}

// Check if we have a local file.
if ( ! $reload ) {
try {
return rest_ensure_response( $this->block_library_cache->get( $identifier ) );
} catch ( NotFoundException $e ) {
}
}

// Access via remote.
$response = $this->get_remote_library_categories( $library, $library_url, $key );

if ( 'error' === $response ) {
return rest_ensure_response( 'error' );
}

$this->block_library_cache->cache( $identifier, $response );

return rest_ensure_response( $response );
}
/**
* Retrieves a collection of objects.
*
Expand Down Expand Up @@ -1688,7 +1788,54 @@ public function get_remote_library_contents( $library, $library_url, $key ) {
}
// Get the response.
$api_url = add_query_arg( $args, $library_url );
$response = wp_safe_remote_get(
$response = wp_remote_get(
$api_url,
array(
'timeout' => 30,
)
);
// Early exit if there was an error.
if ( is_wp_error( $response ) || $this->is_response_code_error( $response ) ) {
return 'error';
}

// Get the CSS from our response.
$contents = wp_remote_retrieve_body( $response );
// Early exit if there was an error.
if ( is_wp_error( $contents ) ) {
return 'error';
}

return $contents;
}

/**
* Get remote file contents.
*
* @access public
* @return string Returns the remote URL contents.
*/
public function get_remote_library_categories( $library, $library_url, $key ) {
$site_url = get_original_domain();
$args = array(
'key' => $key,
'site' => $site_url,
);
if ( 'templates' === $library || 'section' === $library || 'pages' === $library || 'template' === $library ) {
$args['api_email'] = $this->api_email;
$args['api_key'] = $this->api_key;
$args['product_id'] = $this->product_id;

if ( 'iThemes' === $this->api_email ) {
$args['site_url'] = $site_url;
}
}
if ( 'templates' === $library ) {
$args['request'] = 'blocks';
}
// Get the response.
$api_url = add_query_arg( $args, $library_url );
$response = wp_remote_get(
$api_url,
array(
'timeout' => 30,
Expand Down Expand Up @@ -1838,7 +1985,7 @@ public function get_remote_remaining_credits() {
$args['email'] = $this->api_email;
}
$api_url = add_query_arg( $args, $this->remote_credits_url . 'get-remaining' );
$response = wp_safe_remote_get(
$response = wp_remote_get(
$api_url,
array(
'timeout' => 20,
Expand Down Expand Up @@ -1866,7 +2013,7 @@ public function get_remote_remaining_credits() {
*/
public function get_remote_image_collections() {
$api_url = $this->remote_ai_url . 'images/collections';
$response = wp_safe_remote_get(
$response = wp_remote_get(
$api_url,
array(
'timeout' => 20,
Expand Down Expand Up @@ -1975,7 +2122,7 @@ public function get_keyword_suggestions( WP_REST_Request $request ) {
*/
public function get_remote_industry_verticals() {
$api_url = $this->remote_ai_url . 'verticals';
$response = wp_safe_remote_get(
$response = wp_remote_get(
$api_url,
array(
'timeout' => 20,
Expand Down Expand Up @@ -2136,7 +2283,7 @@ public function import_image( $image_data ) {
return $local_image['image'];
}
$file_content = wp_remote_retrieve_body(
wp_safe_remote_get(
wp_remote_get(
$image_data['url'],
array(
'timeout' => '60',
Expand Down
72 changes: 40 additions & 32 deletions src/plugins/prebuilt-library/cloud-library.js
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ function CloudSections ( {
} );
setPageContextListOptions( tempPageContexts );
}, [ pagesCategories ] );
const { getPatterns, getPattern, processPattern } = getAsyncData();
const { getPatterns, getPattern, processPattern, getPatternCategories } = getAsyncData();
const forceRefreshLibrary = () => {
if ( ! isLoading && patterns ) {
setPatterns( JSON.parse(JSON.stringify(patterns)) );
Expand Down Expand Up @@ -190,7 +190,6 @@ function CloudSections ( {
try {
const tempContent = JSON.parse( response );
if ( tempContent ) {
console.log( tempContent );
pattern.content = tempContent;
}
} catch ( e ) { }
Expand Down Expand Up @@ -295,34 +294,45 @@ function CloudSections ( {
} else {
const o = SafeParseJSON( response, false );
if ( o ) {
if ( subTab === 'pages' ) {
const pageCats = {};
kadence_blocks_params.library_pages = o;
{ Object.keys( o ).map( function( key, index ) {
if ( o[ key ].categories && typeof o[ key ].categories === "object") {
{ Object.keys( o[ key ].categories ).map( function( ckey, i ) {
if ( ! pageCats.hasOwnProperty( ckey ) ) {
pageCats[ ckey ] = o[ key ].categories[ ckey ];
}
} ) }
}
} ) }
setPages( o );
setPagesCategories( JSON.parse(JSON.stringify( pageCats ) ) );
const categories = await getPatternCategories( tab, tempReload, action?.[0]?.url ? action[0].url : '', action?.[0]?.key ? action[0].key : '' );
if ( categories ) {
const catOrder = SafeParseJSON( categories, false );
if ( subTab === 'pages' ) {
const pageCats = catOrder ? catOrder : {};
kadence_blocks_params.library_pages = o;
{ Object.keys( o ).map( function( key, index ) {
if ( o[ key ].categories && typeof o[ key ].categories === "object") {
{ Object.keys( o[ key ].categories ).map( function( ckey, i ) {
if ( ! pageCats.hasOwnProperty( ckey ) ) {
pageCats[ ckey ] = o[ key ].categories[ ckey ];
}
} ) }
}
} ) }
setPages( o );
setPagesCategories( JSON.parse(JSON.stringify( pageCats ) ) );
} else {
const cats = catOrder ? catOrder : {};
kadence_blocks_params.library_sections = o;
{ Object.keys( o ).map( function( key, index ) {
if ( o[ key ].categories && typeof o[ key ].categories === "object") {
{ Object.keys( o[ key ].categories ).map( function( ckey, i ) {
if ( ! cats.hasOwnProperty( ckey ) ) {
cats[ ckey ] = o[ key ].categories[ ckey ];
}
} ) }
}
} ) }
setPatterns( o );
setCategories( JSON.parse(JSON.stringify( cats ) ) );
}
} else {
const cats = {};
kadence_blocks_params.library_sections = o;
{ Object.keys( o ).map( function( key, index ) {
if ( o[ key ].categories && typeof o[ key ].categories === "object") {
{ Object.keys( o[ key ].categories ).map( function( ckey, i ) {
if ( ! cats.hasOwnProperty( ckey ) ) {
cats[ ckey ] = o[ key ].categories[ ckey ];
}
} ) }
}
} ) }
setPatterns( o );
setCategories( JSON.parse(JSON.stringify( cats ) ) );
if ( subTab === 'pages' ) {
setPages( 'error' );
} else {
setPatterns( 'error' );
}
setIsError( true );
}
} else {
if ( subTab === 'pages' ) {
Expand All @@ -342,7 +352,7 @@ function CloudSections ( {
} else if ( ! isLoading ) {
getLibraryContent( false );
}
}, [reload, selectedSubTab] );
}, [reload, tab] );
const activePanel = SafeParseJSON( localStorage.getItem( 'kadenceBlocksPrebuilt' ), true );
const sidebar_saved_enabled = ( activePanel && activePanel['sidebar'] ? activePanel['sidebar'] : 'show' );
const sidebarEnabled = ( sidebar ? sidebar : sidebar_saved_enabled );
Expand Down Expand Up @@ -544,7 +554,6 @@ function CloudSections ( {
{ Object.keys( patterns ).map( function( key, index ) {
const name = patterns[key].name;
const slug = patterns[key].slug;
const content = patterns[key].content;
const image = patterns[key].image;
const imageWidth = patterns[key].imageW;
const imageHeight = patterns[key].imageH;
Expand All @@ -554,7 +563,6 @@ function CloudSections ( {
const pro = patterns[key].pro;
const locked = patterns[key].locked;
const descriptionId = `${ slug }_kb_cloud__item-description`;
console.log( patterns[key] );
if ( ( 'all' === getActiveCat || Object.keys( categories ).includes( getActiveCat ) ) && ( ! search || ( keywords && keywords.some( x => x.toLowerCase().includes( search.toLowerCase() ) ) ) ) ) {
return (
<div className="kb-css-masonry-inner">
Expand Down
25 changes: 25 additions & 0 deletions src/plugins/prebuilt-library/data-fetch/get-async-data.js
Original file line number Diff line number Diff line change
Expand Up @@ -362,6 +362,30 @@ export function getAsyncData() {
return 'failed';
}
}
/**
* Get library data.
*
* @param {(object)} userData
*
* @return {Promise<object>} Promise returns object
*/
async function getPatternCategories( library, reload, library_url = null, key = null ) {
try {
const response = await apiFetch( {
path: addQueryArgs( '/kb-design-library/v1/get_library_categories', {
force_reload: reload,
library: library,
library_url: library_url ? library_url : '',
key: key ? key : library,
} ),
} );
return response;
} catch (error) {
const message = error?.message ? error.message : error;
console.log(`ERROR: ${ message }`);
return 'failed';
}
}

/**
* Get library data.
Expand Down Expand Up @@ -446,6 +470,7 @@ export function getAsyncData() {
getAIWizardData,
getCollectionByIndustry,
getPatterns,
getPatternCategories,
getPattern,
processPattern,
getLocalAIContexts,
Expand Down
5 changes: 0 additions & 5 deletions src/plugins/prebuilt-library/editor.scss
Original file line number Diff line number Diff line change
Expand Up @@ -1054,11 +1054,6 @@ button.components-button.kb-trigger-ai.has-icon {
max-height: calc(95vh - 80px);
padding: 5px 20px 0px;
}
.kb-cloud-library-sidebar .kb-library-sidebar-bottom {
overflow: auto;
height: 100%;
max-height: calc(95vh - 284px);
}
.kb-wizard-advanced-text {
flex-grow: 1;
}
Expand Down
Loading

0 comments on commit 9eb8f61

Please sign in to comment.