| 1 |
<?php |
| 2 |
/** Remote library transport. The free plugin contains no licensing SDK. */ |
| 3 |
defined('ABSPATH') || exit; |
| 4 |
|
| 5 |
function bkbg_library_endpoint() { |
| 6 |
return defined('BKBG_TEMPLATE_LIBRARY_ENDPOINT') ? BKBG_TEMPLATE_LIBRARY_ENDPOINT : 'https://templates.blockenberg.com/template-library/v1/index.php'; |
| 7 |
} |
| 8 |
function bkbg_library_pro_enabled() { |
| 9 |
return (bool) apply_filters('bkbg_templates_pro_enabled', false); |
| 10 |
} |
| 11 |
function bkbg_library_credentials() { |
| 12 |
$value = apply_filters('bkbg_template_download_credentials', array()); |
| 13 |
if (!is_array($value) || empty($value['install_id']) || empty($value['license_key']) || empty($value['site_url'])) return array(); |
| 14 |
return array('install_id' => absint($value['install_id']), 'license_key' => (string) $value['license_key'], 'site_url' => (string) $value['site_url']); |
| 15 |
} |
| 16 |
function bkbg_library_request($action, $body = null) { |
| 17 |
$url = add_query_arg('action', $action, bkbg_library_endpoint()); |
| 18 |
if (wp_parse_url($url, PHP_URL_SCHEME) !== 'https') return new WP_Error('bkbg_library_https', __('The template library requires HTTPS.', 'blockenberg')); |
| 19 |
$args = array('timeout' => $action === 'catalog' ? 10 : 60, 'redirection' => 0, 'limit_response_size' => 20 * MB_IN_BYTES, 'headers' => array('Accept' => 'application/json')); |
| 20 |
if ($body !== null) { |
| 21 |
$args['headers']['Content-Type'] = 'application/json'; |
| 22 |
$args['body'] = wp_json_encode($body); |
| 23 |
$response = wp_safe_remote_post($url, $args); |
| 24 |
} else $response = wp_safe_remote_get($url, $args); |
| 25 |
if (is_wp_error($response)) return new WP_Error('bkbg_library_connection', __('Cannot connect to the template library. Please try again.', 'blockenberg')); |
| 26 |
$status = wp_remote_retrieve_response_code($response); |
| 27 |
if ($status !== 200) { |
| 28 |
if ($status === 401 || $status === 403) return new WP_Error('bkbg_library_license', __('Activate a valid Blockenberg Pro license to import this template.', 'blockenberg')); |
| 29 |
return new WP_Error('bkbg_library_response', sprintf(__('The template library returned HTTP %d. Please try again.', 'blockenberg'), $status)); |
| 30 |
} |
| 31 |
$data = json_decode(wp_remote_retrieve_body($response), true); |
| 32 |
if (!is_array($data) || (int) ($data['schemaVersion'] ?? 0) !== 1) return new WP_Error('bkbg_library_schema', __('The template library returned an invalid response.', 'blockenberg')); |
| 33 |
return $data; |
| 34 |
} |
| 35 |
function bkbg_library_catalog_valid($value) { |
| 36 |
if (!is_array($value) || empty($value['templates']) || !is_array($value['templates']) || !is_array($value['collections'] ?? null)) return false; |
| 37 |
foreach ($value['templates'] as $key => $entry) { |
| 38 |
if (!is_string($key) || !preg_match('/^[a-z0-9][a-z0-9-]{0,159}$/D', $key) || !is_array($entry) || ($entry['key'] ?? '') !== $key || !in_array($entry['plan'] ?? '', array('free', 'premium'), true) || !preg_match('/^[a-f0-9]{64}$/D', $entry['sha256'] ?? '') || !preg_match('/^[a-f0-9]{64}$/D', $entry['cssSha256'] ?? '')) return false; |
| 39 |
} |
| 40 |
return true; |
| 41 |
} |
| 42 |
function bkbg_library_catalog($refresh = false) { |
| 43 |
static $memory = null; |
| 44 |
if (!$refresh && $memory !== null) return $memory; |
| 45 |
$cached = get_transient('bkbg_remote_library_catalog_v2'); |
| 46 |
if (!$refresh && bkbg_library_catalog_valid($cached)) return $memory = $cached; |
| 47 |
// Only catalog visits/downloads refresh metadata; no scheduled jobs or frontend HTTP. |
| 48 |
if ((is_admin() || (defined('WP_CLI') && WP_CLI)) && ($refresh || !get_transient('bkbg_remote_library_unavailable_v2'))) { |
| 49 |
$remote = bkbg_library_request('catalog'); |
| 50 |
if (!is_wp_error($remote) && bkbg_library_catalog_valid($remote)) { |
| 51 |
delete_transient('bkbg_remote_library_unavailable_v2'); |
| 52 |
set_transient('bkbg_remote_library_catalog_v2', $remote, DAY_IN_SECONDS); |
| 53 |
update_option('bkbg_remote_library_last_catalog_v2', $remote, false); |
| 54 |
return $memory = $remote; |
| 55 |
} |
| 56 |
set_transient('bkbg_remote_library_unavailable_v2', true, 5 * MINUTE_IN_SECONDS); |
| 57 |
} |
| 58 |
$last = get_option('bkbg_remote_library_last_catalog_v2', array()); |
| 59 |
if (bkbg_library_catalog_valid($last)) return $memory = $last; |
| 60 |
$fallback = dirname(__DIR__, 2) . '/templates/catalog.json'; |
| 61 |
$value = is_file($fallback) ? json_decode(file_get_contents($fallback), true) : array(); |
| 62 |
if (bkbg_library_catalog_valid($value)) return $memory = $value; |
| 63 |
return $memory = array('schemaVersion' => 1, 'templates' => array(), 'collections' => array(), 'assetsBaseUrl' => 'https://templates.blockenberg.com/template-library/assets/'); |
| 64 |
} |
| 65 |
function bkbg_library_authoring_file($key, $extension) { |
| 66 |
// Explicit developer-only override; never configured in distributed builds. |
| 67 |
if (!defined('BKBG_TEMPLATE_AUTHORING_DIR') || !preg_match('/^[a-z0-9][a-z0-9-]{0,159}$/D', $key)) return ''; |
| 68 |
$path = trailingslashit(BKBG_TEMPLATE_AUTHORING_DIR) . $key . '.' . $extension; |
| 69 |
return is_file($path) ? $path : ''; |
| 70 |
} |
| 71 |
function bkbg_library_assets_url() { |
| 72 |
$catalog = bkbg_library_catalog(); |
| 73 |
$url = $catalog['assetsBaseUrl'] ?? ''; |
| 74 |
return bkbg_library_asset_url_allowed($url) ? trailingslashit($url) : 'https://templates.blockenberg.com/template-library/assets/'; |
| 75 |
} |
| 76 |
function bkbg_library_asset_url_allowed($url) { |
| 77 |
return is_string($url) && wp_parse_url($url, PHP_URL_SCHEME) === 'https' && wp_parse_url($url, PHP_URL_HOST) === 'templates.blockenberg.com' && strpos(wp_parse_url($url, PHP_URL_PATH) ?? '', '/template-library/assets/') === 0; |
| 78 |
} |
| 79 |
function bkbg_library_style_allowed($url) { |
| 80 |
$uploads = wp_upload_dir(); |
| 81 |
$base = trailingslashit($uploads['baseurl']) . 'blockenberg-library/'; |
| 82 |
return is_string($url) && strpos($url, $base) === 0 && !preg_match('~(?:\.\.|%2e|%2f|%5c|[?#\\\\])~i', substr($url, strlen($base))) && substr($url, -4) === '.css'; |
| 83 |
} |
| 84 |
function bkbg_library_resolve_css_assets($css) { |
| 85 |
$assets = bkbg_library_assets_url(); |
| 86 |
$css = str_replace('{{assets}}/', $assets, $css); |
| 87 |
return preg_replace_callback('~url\\(\\s*([\"\']?)(assets/[a-zA-Z0-9._-]+)\\1\\s*\\)~', function($match) use ($assets) { |
| 88 |
return 'url("' . $assets . substr($match[2], 7) . '")'; |
| 89 |
}, $css); |
| 90 |
} |
| 91 |
function bkbg_library_store_css($key, $css, $hash) { |
| 92 |
// Frontend previews do not load the admin file helpers automatically. |
| 93 |
if (!function_exists('wp_tempnam')) require_once ABSPATH . 'wp-admin/includes/file.php'; |
| 94 |
$uploads = wp_upload_dir(); |
| 95 |
if (!empty($uploads['error'])) return new WP_Error('bkbg_library_storage', __('Cannot access the uploads directory.', 'blockenberg')); |
| 96 |
$folder = trailingslashit($uploads['basedir']) . 'blockenberg-library/'; |
| 97 |
if (!wp_mkdir_p($folder)) return new WP_Error('bkbg_library_storage', __('Cannot create the template style directory.', 'blockenberg')); |
| 98 |
$name = $key . '.' . $hash . '.css'; |
| 99 |
$path = $folder . $name; |
| 100 |
if (!is_file($path) || !hash_equals($hash, hash_file('sha256', $path))) { |
| 101 |
$tmp = wp_tempnam($name, $folder); |
| 102 |
if (!$tmp || file_put_contents($tmp, $css, LOCK_EX) !== strlen($css) || !@rename($tmp, $path)) { |
| 103 |
if ($tmp) wp_delete_file($tmp); |
| 104 |
return new WP_Error('bkbg_library_storage', __('Cannot save the template stylesheet.', 'blockenberg')); |
| 105 |
} |
| 106 |
@chmod($path, 0644); |
| 107 |
} |
| 108 |
$url = trailingslashit($uploads['baseurl']) . 'blockenberg-library/' . $name; |
| 109 |
$styles = get_option('bkbg_imported_template_styles_v1', array()); |
| 110 |
$styles[$key] = $url; |
| 111 |
update_option('bkbg_imported_template_styles_v1', $styles, false); |
| 112 |
return $url; |
| 113 |
} |
| 114 |
function bkbg_library_template_bundle($key, $authoring_preview = false, $retried = false) { |
| 115 |
$manifest = bkbg_template_manifest(); |
| 116 |
if (!isset($manifest[$key]) || ($manifest[$key]['status'] ?? '') !== 'ready') return new WP_Error('missing_template', __('Template is not available.', 'blockenberg')); |
| 117 |
$entry = $manifest[$key]; |
| 118 |
$source = $authoring_preview ? bkbg_library_authoring_file($key, 'json') : ''; |
| 119 |
if ($source) { |
| 120 |
$json = file_get_contents($source); |
| 121 |
$css_file = bkbg_library_authoring_file($key, 'css'); |
| 122 |
if (!$css_file) return new WP_Error('bkbg_library_css', __('Template stylesheet is missing.', 'blockenberg')); |
| 123 |
$css = file_get_contents($css_file); |
| 124 |
} else { |
| 125 |
$request = array('key' => $key); |
| 126 |
if ($entry['plan'] !== 'free') { |
| 127 |
if (!bkbg_library_pro_enabled() || !$credentials = bkbg_library_credentials()) return new WP_Error('bkbg_library_license', __('Activate a valid Blockenberg Pro license to import this template.', 'blockenberg')); |
| 128 |
$request['credentials'] = $credentials; |
| 129 |
} |
| 130 |
// No reusable premium bundle cache: the server authorizes every new import. |
| 131 |
$response = bkbg_library_request('download', $request); |
| 132 |
if (is_wp_error($response)) return $response; |
| 133 |
if (($response['key'] ?? '') !== $key || !is_string($response['templateJson'] ?? null) || !is_string($response['css'] ?? null)) return new WP_Error('bkbg_library_bundle', __('Invalid template download.', 'blockenberg')); |
| 134 |
$json = $response['templateJson']; $css = $response['css']; |
| 135 |
if (!hash_equals($entry['sha256'], hash('sha256', $json)) || !hash_equals($entry['cssSha256'], hash('sha256', $css))) { |
| 136 |
// A release can change while this site's catalog is cached. Refresh once; |
| 137 |
// the second download still requires authorization and matching hashes. |
| 138 |
if (!$retried) { |
| 139 |
bkbg_library_catalog(true); |
| 140 |
return bkbg_library_template_bundle($key, false, true); |
| 141 |
} |
| 142 |
return new WP_Error('bkbg_library_integrity', __('Template download verification failed. Refresh the library and try again.', 'blockenberg')); |
| 143 |
} |
| 144 |
} |
| 145 |
$data = json_decode($json, true); |
| 146 |
if (!is_array($data) || ($data['key'] ?? '') !== $key || empty($data['blocks']) || !is_array($data['blocks'])) return new WP_Error('bkbg_library_bundle', __('Invalid template data.', 'blockenberg')); |
| 147 |
$valid = bkbg_template_validate_nodes($data['blocks']); if (is_wp_error($valid)) return $valid; |
| 148 |
$assets = bkbg_library_assets_url(); |
| 149 |
$css = bkbg_library_resolve_css_assets($css); |
| 150 |
$style_url = bkbg_library_store_css($key, $css, hash('sha256', $css)); |
| 151 |
if (is_wp_error($style_url)) return $style_url; |
| 152 |
foreach ($data['blocks'] as &$node) if (($node['blockName'] ?? '') === 'blockenberg/template-page') $node['attrs']['templateStyleUrl'] = $style_url; |
| 153 |
return $data; |
| 154 |
} |
| 155 |
function bkbg_library_enqueue_template_style($key, $explicit = '') { |
| 156 |
$styles = get_option('bkbg_imported_template_styles_v1', array()); |
| 157 |
$url = $explicit ?: ($styles[$key] ?? ''); |
| 158 |
if (!bkbg_library_style_allowed($url)) { |
| 159 |
// Compatibility for developer previews and older imports, using only local files. |
| 160 |
$css_file = bkbg_library_authoring_file($key, 'css'); |
| 161 |
if (!$css_file) return; |
| 162 |
$css = bkbg_library_resolve_css_assets(file_get_contents($css_file)); |
| 163 |
$url = bkbg_library_store_css($key, $css, hash('sha256', $css)); |
| 164 |
if (is_wp_error($url)) return; |
| 165 |
} |
| 166 |
wp_enqueue_style('bkbg-template-' . $key . '-' . substr(hash('sha256', $url), 0, 10), $url, array('bkbg-template-pilot'), null); |
| 167 |
} |
| 168 |
|
| 169 |
add_action('admin_post_bkbg_refresh_template_library', function(){ |
| 170 |
if(!current_user_can('manage_options'))wp_die('Insufficient permissions.'); |
| 171 |
check_admin_referer('bkbg_refresh_template_library'); |
| 172 |
delete_transient('bkbg_remote_library_catalog_v2'); |
| 173 |
delete_transient('bkbg_remote_library_unavailable_v2'); |
| 174 |
$remote=bkbg_library_request('catalog'); |
| 175 |
if(is_wp_error($remote)||!bkbg_library_catalog_valid($remote))wp_die(esc_html(is_wp_error($remote)?$remote->get_error_message():'Invalid library catalog.')); |
| 176 |
set_transient('bkbg_remote_library_catalog_v2',$remote,DAY_IN_SECONDS); |
| 177 |
update_option('bkbg_remote_library_last_catalog_v2',$remote,false); |
| 178 |
wp_safe_redirect(admin_url('admin.php?page=blockenberg-templates'));exit; |
| 179 |
}); |
| 180 |
|