Commit inicial, se subio el proyecto
This commit is contained in:
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Jooosi Fon package.
|
||||
*
|
||||
* (c) Joshua Gugun Siagian <suabahasa@gmail.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
declare (strict_types=1);
|
||||
namespace JooosiFon\Api;
|
||||
|
||||
use JooosiFonDeps\JOOOSI_FON;
|
||||
use WP_REST_Request;
|
||||
class AbstractApi
|
||||
{
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
public const API_NAMESPACE = JOOOSI_FON::REST_NAMESPACE;
|
||||
/**
|
||||
* The API is currently an administrator-only surface used by the plugin's
|
||||
* wp-admin application. Keep both checks explicit so custom authentication
|
||||
* integrations cannot accidentally bypass the CSRF boundary.
|
||||
*/
|
||||
protected function permission_callback(WP_REST_Request $request): bool
|
||||
{
|
||||
return wp_verify_nonce($request->get_header('X-WP-Nonce'), 'wp_rest') && current_user_can('manage_options');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Jooosi Fon package.
|
||||
*
|
||||
* (c) Joshua Gugun Siagian <suabahasa@gmail.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
declare (strict_types=1);
|
||||
namespace JooosiFon\Api;
|
||||
|
||||
interface ApiInterface
|
||||
{
|
||||
/**
|
||||
* Get the API endpoint prefix.
|
||||
*/
|
||||
public function get_prefix(): string;
|
||||
/**
|
||||
* Register custom REST API endpoints as described in the [WordPress REST API Handbook](https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/).
|
||||
*
|
||||
* @see https://developer.wordpress.org/reference/functions/register_rest_route/
|
||||
*/
|
||||
public function register_custom_endpoints(): void;
|
||||
}
|
||||
@@ -0,0 +1,894 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Jooosi Fon package.
|
||||
*
|
||||
* (c) Joshua Gugun Siagian <suabahasa@gmail.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
declare (strict_types=1);
|
||||
namespace JooosiFon\Api;
|
||||
|
||||
use JooosiFonDeps\JOOOSI_FON;
|
||||
use JooosiFon\Api\Support\FontCodec;
|
||||
use JooosiFon\Api\Support\FontEvents;
|
||||
use JooosiFon\Api\Support\FontRepository;
|
||||
use JooosiFon\Api\Support\GoogleFontFileSelector;
|
||||
use JooosiFon\Api\Support\GoogleFontsClient;
|
||||
use JooosiFon\Api\Support\MediaImportService;
|
||||
use JooosiFon\Api\Support\RequestValidator;
|
||||
use JooosiFon\Builder\Integration;
|
||||
use JooosiFon\Core\Cache;
|
||||
use JooosiFon\Utils\Common;
|
||||
use JooosiFon\Utils\Config;
|
||||
use JooosiFon\Utils\Upload;
|
||||
use JooosiFonDeps\Sabberworm\CSS\Parser;
|
||||
use stdClass;
|
||||
use WP_REST_Request;
|
||||
use WP_REST_Response;
|
||||
use WP_REST_Server;
|
||||
use wpdb;
|
||||
/**
|
||||
* @todo Remove all legacy Yabe Webfont filter shims completely in Jooosi Fon 3.0.0.
|
||||
*/
|
||||
class Font extends \JooosiFon\Api\AbstractApi implements \JooosiFon\Api\ApiInterface
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
}
|
||||
public function get_prefix(): string
|
||||
{
|
||||
return 'fonts';
|
||||
}
|
||||
public function register_custom_endpoints(): void
|
||||
{
|
||||
$id_args = ['id' => ['required' => \true, 'sanitize_callback' => 'absint', 'validate_callback' => [RequestValidator::class, 'positiveInteger']]];
|
||||
$custom_font_args = ['title' => ['required' => \true, 'sanitize_callback' => 'sanitize_text_field', 'validate_callback' => [RequestValidator::class, 'nonEmptyString']], 'family' => ['required' => \true, 'sanitize_callback' => 'sanitize_text_field', 'validate_callback' => [RequestValidator::class, 'nonEmptyString']], 'status' => ['required' => \true, 'sanitize_callback' => 'rest_sanitize_boolean', 'validate_callback' => [RequestValidator::class, 'boolean']], 'metadata' => ['required' => \true, 'validate_callback' => [RequestValidator::class, 'arrayValue']], 'font_faces' => ['required' => \true, 'sanitize_callback' => [RequestValidator::class, 'sanitizeFontFaces'], 'validate_callback' => [RequestValidator::class, 'fontFaces']]];
|
||||
$google_font_args = ['title' => $custom_font_args['title'], 'status' => $custom_font_args['status'], 'metadata' => ['required' => \true, 'validate_callback' => [RequestValidator::class, 'googleMetadata']]];
|
||||
register_rest_route(self::API_NAMESPACE, $this->get_prefix() . '/index', ['methods' => WP_REST_Server::READABLE, 'callback' => fn(\WP_REST_Request $wprestRequest): \WP_REST_Response => $this->index($wprestRequest), 'permission_callback' => fn(\WP_REST_Request $wprestRequest): bool => $this->permission_callback($wprestRequest), 'args' => ['page' => ['default' => 1, 'sanitize_callback' => 'absint', 'validate_callback' => [RequestValidator::class, 'positiveInteger']], 'per_page' => ['default' => 20, 'sanitize_callback' => 'absint', 'validate_callback' => [RequestValidator::class, 'pageSize']], 'search' => ['default' => '', 'sanitize_callback' => 'sanitize_text_field'], 'soft_deleted' => ['default' => \false, 'sanitize_callback' => 'rest_sanitize_boolean', 'validate_callback' => [RequestValidator::class, 'boolean']]]]);
|
||||
register_rest_route(self::API_NAMESPACE, $this->get_prefix() . '/custom/store', ['methods' => WP_REST_Server::CREATABLE, 'callback' => fn(\WP_REST_Request $wprestRequest): \WP_REST_Response => $this->custom_store($wprestRequest), 'permission_callback' => fn(\WP_REST_Request $wprestRequest): bool => $this->permission_callback($wprestRequest), 'args' => $custom_font_args]);
|
||||
register_rest_route(self::API_NAMESPACE, $this->get_prefix() . '/update-status/(?P<id>\d+)', ['methods' => WP_REST_Server::EDITABLE, 'callback' => fn(\WP_REST_Request $wprestRequest): \WP_REST_Response => $this->update_status($wprestRequest), 'permission_callback' => fn(\WP_REST_Request $wprestRequest): bool => $this->permission_callback($wprestRequest), 'args' => array_merge($id_args, ['status' => ['required' => \true, 'sanitize_callback' => 'rest_sanitize_boolean', 'validate_callback' => [RequestValidator::class, 'boolean']]])]);
|
||||
register_rest_route(self::API_NAMESPACE, $this->get_prefix() . '/delete/(?P<id>\d+)', ['methods' => 'POST, DELETE', 'callback' => fn(\WP_REST_Request $wprestRequest): \WP_REST_Response => $this->destroy($wprestRequest), 'permission_callback' => fn(\WP_REST_Request $wprestRequest): bool => $this->permission_callback($wprestRequest), 'args' => $id_args]);
|
||||
register_rest_route(self::API_NAMESPACE, $this->get_prefix() . '/restore/(?P<id>\d+)', ['methods' => WP_REST_Server::CREATABLE, 'callback' => fn(\WP_REST_Request $wprestRequest): \WP_REST_Response => $this->restore($wprestRequest), 'permission_callback' => fn(\WP_REST_Request $wprestRequest): bool => $this->permission_callback($wprestRequest), 'args' => $id_args]);
|
||||
register_rest_route(self::API_NAMESPACE, $this->get_prefix() . '/export', ['methods' => WP_REST_Server::CREATABLE, 'callback' => fn(\WP_REST_Request $wprestRequest): \WP_REST_Response => $this->export($wprestRequest), 'permission_callback' => fn(\WP_REST_Request $wprestRequest): bool => $this->permission_callback($wprestRequest), 'args' => ['items' => ['required' => \true, 'validate_callback' => [RequestValidator::class, 'positiveIntegerList'], 'sanitize_callback' => static fn($items): array => array_values(array_unique(array_map('absint', $items)))]]]);
|
||||
register_rest_route(self::API_NAMESPACE, $this->get_prefix() . '/import', ['methods' => WP_REST_Server::CREATABLE, 'callback' => fn(\WP_REST_Request $wprestRequest): \WP_REST_Response => $this->import($wprestRequest), 'permission_callback' => fn(\WP_REST_Request $wprestRequest): bool => $this->permission_callback($wprestRequest), 'args' => ['site_url' => ['required' => \true, 'sanitize_callback' => 'esc_url_raw', 'validate_callback' => 'wp_http_validate_url'], 'version' => ['required' => \true, 'sanitize_callback' => 'sanitize_text_field', 'validate_callback' => [RequestValidator::class, 'nonEmptyString']], 'is_bundled' => ['required' => \true, 'sanitize_callback' => 'rest_sanitize_boolean', 'validate_callback' => [RequestValidator::class, 'boolean']], 'item' => ['required' => \true, 'validate_callback' => [RequestValidator::class, 'importItem']]]]);
|
||||
register_rest_route(self::API_NAMESPACE, $this->get_prefix() . '/detail/(?P<id>\d+)', ['methods' => WP_REST_Server::READABLE, 'callback' => fn(\WP_REST_Request $wprestRequest): \WP_REST_Response => $this->detail($wprestRequest), 'permission_callback' => fn(\WP_REST_Request $wprestRequest): bool => $this->permission_callback($wprestRequest), 'args' => $id_args]);
|
||||
register_rest_route(self::API_NAMESPACE, $this->get_prefix() . '/custom/update/(?P<id>\d+)', ['methods' => WP_REST_Server::EDITABLE, 'callback' => fn(\WP_REST_Request $wprestRequest): \WP_REST_Response => $this->custom_update($wprestRequest), 'permission_callback' => fn(\WP_REST_Request $wprestRequest): bool => $this->permission_callback($wprestRequest), 'args' => array_merge($id_args, $custom_font_args)]);
|
||||
register_rest_route(self::API_NAMESPACE, $this->get_prefix() . '/google-fonts/store', ['methods' => WP_REST_Server::CREATABLE, 'callback' => fn(\WP_REST_Request $wprestRequest): \WP_REST_Response => $this->google_fonts_store($wprestRequest), 'permission_callback' => fn(\WP_REST_Request $wprestRequest): bool => $this->permission_callback($wprestRequest), 'args' => $google_font_args]);
|
||||
register_rest_route(self::API_NAMESPACE, $this->get_prefix() . '/google-fonts/update/(?P<id>\d+)', ['methods' => WP_REST_Server::EDITABLE, 'callback' => fn(\WP_REST_Request $wprestRequest): \WP_REST_Response => $this->google_fonts_update($wprestRequest), 'permission_callback' => fn(\WP_REST_Request $wprestRequest): bool => $this->permission_callback($wprestRequest), 'args' => array_merge($id_args, $google_font_args)]);
|
||||
register_rest_route(self::API_NAMESPACE, $this->get_prefix() . '/google-fonts/metadata', ['methods' => WP_REST_Server::READABLE, 'callback' => fn(\WP_REST_Request $wprestRequest): \WP_REST_Response => $this->google_fonts_metadata($wprestRequest), 'permission_callback' => fn(\WP_REST_Request $wprestRequest): bool => $this->permission_callback($wprestRequest), 'args' => ['force' => ['default' => \false, 'sanitize_callback' => 'rest_sanitize_boolean', 'validate_callback' => [RequestValidator::class, 'boolean']]]]);
|
||||
register_rest_route(self::API_NAMESPACE, $this->get_prefix() . '/google-fonts/webfonts/(?P<slug>[a-zA-Z0-9_\-+\.]+)', ['methods' => WP_REST_Server::READABLE, 'callback' => fn(\WP_REST_Request $wprestRequest): \WP_REST_Response => $this->google_fonts_webfonts($wprestRequest), 'permission_callback' => fn(\WP_REST_Request $wprestRequest): bool => $this->permission_callback($wprestRequest), 'args' => ['slug' => ['required' => \true, 'sanitize_callback' => 'sanitize_key', 'validate_callback' => [RequestValidator::class, 'nonEmptyString']], 'subsets' => ['default' => '', 'sanitize_callback' => 'sanitize_text_field', 'validate_callback' => [RequestValidator::class, 'subsets']]]]);
|
||||
}
|
||||
private function index(WP_REST_Request $wprestRequest): WP_REST_Response
|
||||
{
|
||||
/** @var wpdb $wpdb */
|
||||
global $wpdb;
|
||||
$soft_deleted = rest_sanitize_boolean($wprestRequest->get_param('soft_deleted'));
|
||||
$page = max(1, (int) $wprestRequest->get_param('page'));
|
||||
$per_page = min(100, max(1, (int) $wprestRequest->get_param('per_page')));
|
||||
$offset = $page * $per_page - $per_page;
|
||||
$search = trim((string) $wprestRequest->get_param('search'));
|
||||
$search = $search !== '' ? $search : null;
|
||||
$items = [];
|
||||
$where_clause = [];
|
||||
if ($search) {
|
||||
$escaped_search = '%' . $wpdb->esc_like($search) . '%';
|
||||
$where_clause[] = $wpdb->prepare("( title LIKE '%1\$s' OR family LIKE '%1\$s' )", $escaped_search);
|
||||
}
|
||||
$where_clause[] = $soft_deleted ? 'deleted_at IS NOT NULL' : 'deleted_at IS NULL';
|
||||
$where_clause = 'WHERE ' . implode(' AND ', $where_clause);
|
||||
$sql = "\n SELECT * FROM {$wpdb->prefix}jooosi_fon_fonts\n {$where_clause}\n ORDER BY id DESC\n LIMIT %d OFFSET %d\n ";
|
||||
$sql = $wpdb->prepare($sql, $per_page, $offset);
|
||||
$result = $wpdb->get_results($sql);
|
||||
foreach ($result as $row) {
|
||||
$metadata = FontCodec::decode((string) $row->metadata);
|
||||
$font_faces = FontCodec::decode((string) $row->font_faces);
|
||||
$items[] = ['id' => $row->id, 'type' => $row->type, 'title' => $row->title, 'slug' => $row->slug, 'family' => $row->family, 'metadata' => $metadata, 'font_faces' => Upload::refresh_font_faces_attachment_url($font_faces), 'status' => (bool) $row->status, 'created_at' => strtotime($row->created_at), 'updated_at' => strtotime($row->updated_at), 'deleted_at' => $row->deleted_at ? strtotime($row->deleted_at) : null];
|
||||
}
|
||||
$totals = $wpdb->get_row("\n SELECT\n SUM(CASE WHEN deleted_at IS NULL THEN 1 ELSE 0 END) AS total_exists,\n SUM(CASE WHEN status = 1 AND deleted_at IS NULL THEN 1 ELSE 0 END) AS total_active,\n SUM(CASE WHEN type = 'adobe-fonts' AND deleted_at IS NULL THEN 1 ELSE 0 END) AS total_adobe_fonts,\n SUM(CASE WHEN deleted_at IS NOT NULL THEN 1 ELSE 0 END) AS total_deleted\n FROM {$wpdb->prefix}jooosi_fon_fonts\n ");
|
||||
$total_exists = (int) ($totals->total_exists ?? 0);
|
||||
$total_active = (int) ($totals->total_active ?? 0);
|
||||
$total_adobe_fonts = (int) ($totals->total_adobe_fonts ?? 0);
|
||||
$total_deleted = (int) ($totals->total_deleted ?? 0);
|
||||
$total_filtered = (int) $wpdb->get_var("\n SELECT COUNT(*) FROM {$wpdb->prefix}jooosi_fon_fonts\n {$where_clause}\n ");
|
||||
$total_pages = (int) ceil($total_filtered / $per_page);
|
||||
$from = $items !== [] ? ($page - 1) * $per_page + 1 : null;
|
||||
$to = $items !== [] ? $from + count($items) - 1 : null;
|
||||
return new WP_REST_Response(['data' => $items, 'meta' => ['page' => $page, 'per_page' => $per_page, 'search' => $search, 'total_pages' => $total_pages, 'from' => $from, 'to' => $to, 'total_filtered' => $total_filtered, 'total_deleted' => $total_deleted, 'total_exists' => $total_exists, 'infrastructure' => ['google_fonts' => $this->get_google_fonts_catalog_stats(), 'active_fonts' => ['total' => $total_active], 'adobe_fonts' => ['active' => trim((string) Config::get('adobe_fonts.project_id', '')) !== '', 'total' => $total_adobe_fonts], 'integrations' => ['total' => Integration::get_registered_count()]]]], 200, ['X-WP-Total' => $total_filtered, 'X-WP-TotalPages' => $total_pages]);
|
||||
}
|
||||
/**
|
||||
* @return array{total: int, cache_updated_at: int|null}
|
||||
*/
|
||||
private function get_google_fonts_catalog_stats(): array
|
||||
{
|
||||
$cache_path = Cache::get_cache_path('webfonts.json');
|
||||
$has_cache = file_exists($cache_path) && is_readable($cache_path);
|
||||
$source_path = $has_cache ? $cache_path : dirname(JOOOSI_FON::FILE) . '/google-fonts.json';
|
||||
$source_updated_at = is_readable($source_path) ? filemtime($source_path) : \false;
|
||||
$source_updated_at = is_int($source_updated_at) ? $source_updated_at : null;
|
||||
$cache_updated_at = $has_cache ? $source_updated_at : null;
|
||||
$transient_key = 'jooosi_fon_google_fonts_catalog_stats';
|
||||
$cached = get_transient($transient_key);
|
||||
if (is_array($cached) && ($cached['source_path'] ?? null) === $source_path && ($cached['source_updated_at'] ?? null) === $source_updated_at) {
|
||||
return ['total' => (int) ($cached['total'] ?? 0), 'cache_updated_at' => $cache_updated_at];
|
||||
}
|
||||
$total = 0;
|
||||
if (is_readable($source_path)) {
|
||||
try {
|
||||
$catalog = json_decode(file_get_contents($source_path), \true, 512, \JSON_THROW_ON_ERROR);
|
||||
$total = is_array($catalog) ? count($catalog) : 0;
|
||||
} catch (\JsonException $e) {
|
||||
$total = 0;
|
||||
}
|
||||
}
|
||||
set_transient($transient_key, ['source_path' => $source_path, 'source_updated_at' => $source_updated_at, 'total' => $total], \DAY_IN_SECONDS);
|
||||
return ['total' => $total, 'cache_updated_at' => $cache_updated_at];
|
||||
}
|
||||
private function detail(WP_REST_Request $wprestRequest): WP_REST_Response
|
||||
{
|
||||
/** @var wpdb $wpdb */
|
||||
global $wpdb;
|
||||
$url_params = $wprestRequest->get_url_params();
|
||||
$id = (int) $url_params['id'];
|
||||
$sql = "\n SELECT * FROM {$wpdb->prefix}jooosi_fon_fonts\n WHERE id = %d\n ";
|
||||
$sql = $wpdb->prepare($sql, $id);
|
||||
$row = $wpdb->get_row($sql);
|
||||
if (!$row) {
|
||||
return new WP_REST_Response(['message' => 'Font not found'], 404, []);
|
||||
}
|
||||
$metadata = FontCodec::decode((string) $row->metadata);
|
||||
$font_faces = FontCodec::decode((string) $row->font_faces);
|
||||
$payload = ['id' => $row->id, 'type' => $row->type, 'title' => $row->title, 'slug' => $row->slug, 'family' => $row->family, 'metadata' => $metadata, 'font_faces' => Upload::refresh_font_faces_attachment_url($font_faces), 'status' => (bool) $row->status, 'created_at' => strtotime($row->created_at), 'updated_at' => strtotime($row->updated_at), 'deleted_at' => $row->deleted_at ? strtotime($row->deleted_at) : null];
|
||||
if (is_object($payload['metadata']) && property_exists($payload['metadata'], 'google_fonts')) {
|
||||
$payload['metadata']->google_fonts->font_files = Upload::refresh_google_fonts_attachment_url($payload['metadata']->google_fonts->font_files);
|
||||
}
|
||||
return new WP_REST_Response($payload, 200, []);
|
||||
}
|
||||
private function custom_store(WP_REST_Request $wprestRequest): WP_REST_Response
|
||||
{
|
||||
try {
|
||||
$repository = new FontRepository();
|
||||
$id = $repository->insert(['type' => 'custom', 'title' => (string) $wprestRequest->get_param('title'), 'slug' => Common::random_slug(10), 'family' => (string) $wprestRequest->get_param('family'), 'status' => rest_sanitize_boolean($wprestRequest->get_param('status')), 'metadata' => FontCodec::encode((array) $wprestRequest->get_param('metadata')), 'font_faces' => FontCodec::encode((array) $wprestRequest->get_param('font_faces'))], ['%s', '%s', '%s', '%s', '%d', '%s', '%s']);
|
||||
} catch (\Throwable $throwable) {
|
||||
return $this->operation_error($throwable, __('Unable to create the font.', 'jooosi-fon'));
|
||||
}
|
||||
FontEvents::dispatch('custom_store', $id);
|
||||
return new WP_REST_Response(['id' => $id], 200, []);
|
||||
}
|
||||
private function update_status(WP_REST_Request $wprestRequest): WP_REST_Response
|
||||
{
|
||||
$id = (int) $wprestRequest->get_param('id');
|
||||
$status = rest_sanitize_boolean($wprestRequest->get_param('status'));
|
||||
$repository = new FontRepository();
|
||||
if (!$repository->find($id)) {
|
||||
return new WP_REST_Response(['message' => __('Font not found', 'jooosi-fon')], 404, []);
|
||||
}
|
||||
try {
|
||||
$repository->update($id, ['status' => $status], ['%d']);
|
||||
} catch (\Throwable $throwable) {
|
||||
return $this->operation_error($throwable, __('Unable to update the font status.', 'jooosi-fon'));
|
||||
}
|
||||
FontEvents::dispatch('update_status', $id);
|
||||
return new WP_REST_Response(['id' => $id, 'status' => $status], 200, []);
|
||||
}
|
||||
private function destroy(WP_REST_Request $wprestRequest): WP_REST_Response
|
||||
{
|
||||
$id = (int) $wprestRequest->get_param('id');
|
||||
$repository = new FontRepository();
|
||||
$item = $repository->find($id);
|
||||
if (!$item) {
|
||||
return new WP_REST_Response(['message' => __('Font not found', 'jooosi-fon')], 404, []);
|
||||
}
|
||||
try {
|
||||
if ($item->deleted_at) {
|
||||
$fontFaces = FontCodec::decode((string) $item->font_faces);
|
||||
$attachmentIds = MediaImportService::attachmentIds($fontFaces);
|
||||
$repository->delete($id);
|
||||
MediaImportService::deleteAttachments($attachmentIds);
|
||||
} else {
|
||||
$repository->update($id, ['deleted_at' => current_time('mysql')], ['%s']);
|
||||
}
|
||||
} catch (\Throwable $throwable) {
|
||||
return $this->operation_error($throwable, __('Unable to delete the font.', 'jooosi-fon'));
|
||||
}
|
||||
FontEvents::dispatch('destroy', $item);
|
||||
return new WP_REST_Response(null, 200, []);
|
||||
}
|
||||
private function restore(WP_REST_Request $wprestRequest): WP_REST_Response
|
||||
{
|
||||
$id = (int) $wprestRequest->get_param('id');
|
||||
$repository = new FontRepository();
|
||||
if (!$repository->find($id)) {
|
||||
return new WP_REST_Response(['message' => __('Font not found', 'jooosi-fon')], 404, []);
|
||||
}
|
||||
try {
|
||||
$repository->update($id, ['deleted_at' => null], ['%s']);
|
||||
} catch (\Throwable $throwable) {
|
||||
return $this->operation_error($throwable, __('Unable to restore the font.', 'jooosi-fon'));
|
||||
}
|
||||
FontEvents::dispatch('restore', $id);
|
||||
return new WP_REST_Response(['id' => $id], 200, []);
|
||||
}
|
||||
private function custom_update(WP_REST_Request $wprestRequest): WP_REST_Response
|
||||
{
|
||||
$id = (int) $wprestRequest->get_param('id');
|
||||
$repository = new FontRepository();
|
||||
$existing = $repository->findOfType($id, 'custom');
|
||||
if (!$existing) {
|
||||
return new WP_REST_Response(['message' => __('Font not found', 'jooosi-fon')], 404, []);
|
||||
}
|
||||
$fontFaces = (array) $wprestRequest->get_param('font_faces');
|
||||
try {
|
||||
$oldAttachmentIds = MediaImportService::attachmentIds(FontCodec::decode((string) $existing->font_faces));
|
||||
$newAttachmentIds = MediaImportService::attachmentIds($fontFaces);
|
||||
$repository->update($id, ['title' => (string) $wprestRequest->get_param('title'), 'family' => (string) $wprestRequest->get_param('family'), 'status' => rest_sanitize_boolean($wprestRequest->get_param('status')), 'metadata' => FontCodec::encode((array) $wprestRequest->get_param('metadata')), 'font_faces' => FontCodec::encode($fontFaces)], ['%s', '%s', '%d', '%s', '%s']);
|
||||
MediaImportService::deleteAttachments(array_diff($oldAttachmentIds, $newAttachmentIds));
|
||||
} catch (\Throwable $throwable) {
|
||||
return $this->operation_error($throwable, __('Unable to update the font.', 'jooosi-fon'));
|
||||
}
|
||||
FontEvents::dispatch('custom_update', $id);
|
||||
return new WP_REST_Response(['id' => $id], 200, []);
|
||||
}
|
||||
private function google_fonts_store(WP_REST_Request $wprestRequest): WP_REST_Response
|
||||
{
|
||||
$payload = $wprestRequest->get_json_params();
|
||||
$media = new MediaImportService();
|
||||
$type = 'google-fonts';
|
||||
$title = sanitize_text_field($payload['title']);
|
||||
$slug = Common::random_slug(10);
|
||||
$status = (bool) $payload['status'];
|
||||
$metadata = $payload['metadata'];
|
||||
$family = $metadata['google_fonts']['font_data']['family'];
|
||||
$font_faces = [];
|
||||
add_filter('wp_check_filetype_and_ext', static fn($data, $file, $filename, $mimes) => Upload::disable_real_mime_check($data, $file, $filename, $mimes), 10, 4);
|
||||
add_filter('upload_mimes', static fn($mime_types) => Upload::upload_mimes($mime_types, \true), 1000001);
|
||||
$m_font_faces = $metadata['google_fonts']['font_faces'];
|
||||
$m_font_files = $metadata['google_fonts']['font_files'];
|
||||
foreach ($m_font_faces as $k => $m_face) {
|
||||
if (!$m_face['isEnabled']) {
|
||||
continue;
|
||||
}
|
||||
if ($metadata['google_fonts']['variable']) {
|
||||
if ($m_face['weight'] !== 0) {
|
||||
continue;
|
||||
}
|
||||
$all_filtered_m_font_files = GoogleFontFileSelector::variableFiles($m_font_files, $m_face, $metadata['google_fonts']['subsets'], $metadata['google_fonts']['formats']);
|
||||
foreach ($all_filtered_m_font_files as $filtered_m_font_file) {
|
||||
$wght = array_filter($metadata['google_fonts']['font_data']['axes'], static fn($a) => $a['tag'] === 'wght');
|
||||
$wdth = array_filter($metadata['google_fonts']['font_data']['axes'], static fn($a) => $a['tag'] === 'wdth');
|
||||
$slnt = array_filter($metadata['google_fonts']['font_data']['axes'], static fn($a) => $a['tag'] === 'slnt');
|
||||
$wdth = array_values($wdth);
|
||||
$wght = array_values($wght);
|
||||
$slnt = array_values($slnt);
|
||||
$font_face = ['id' => Common::random_slug(10), 'weight' => $wght !== [] ? sprintf('%s %s', $wght[0]['min'], $wght[0]['max']) : '400', 'width' => $wdth !== [] ? sprintf('%s%% %s%%', $wdth[0]['min'], $wdth[0]['max']) : '100%', 'style' => $slnt !== [] ? sprintf('oblique %sdeg %sdeg', $slnt[0]['max'] * -1, $slnt[0]['min'] * -1) : $m_face['style'], 'display' => $m_face['display'], 'selector' => $m_face['selector'], 'comment' => $m_face['comment'], 'preload' => $m_face['preload']];
|
||||
$file_name = sanitize_title_with_dashes(sprintf(
|
||||
'google-fonts-%s-%s-%s-var-%s-%s',
|
||||
$metadata['google_fonts']['font_data']['slug'],
|
||||
// family
|
||||
$metadata['google_fonts']['font_data']['version'] ?? 'latest',
|
||||
implode('_', $filtered_m_font_file['subsets']),
|
||||
Common::random_slug(5),
|
||||
time()
|
||||
)) . '.' . $filtered_m_font_file['format'];
|
||||
try {
|
||||
$file = $media->remote($filtered_m_font_file['url'], $file_name, $filtered_m_font_file['format'], ['fonts.gstatic.com']);
|
||||
} catch (\Throwable $throwable) {
|
||||
$media->rollback();
|
||||
return $this->operation_error($throwable, __('Unable to download the Google font files.', 'jooosi-fon'));
|
||||
}
|
||||
$metadata['google_fonts']['font_files'] = array_map(static fn($f) => $f['uid'] === $filtered_m_font_file['uid'] ? array_merge($f, ['file' => $file]) : $f, $metadata['google_fonts']['font_files']);
|
||||
$metadata['google_fonts']['font_faces'][$k]['attached_font_files'][] = $filtered_m_font_file['uid'];
|
||||
$font_face['files'] = [$file];
|
||||
$font_face['unicodeRange'] = $filtered_m_font_file['unicodeRange'] ?? '';
|
||||
$font_faces[] = $font_face;
|
||||
}
|
||||
} else {
|
||||
if ($m_face['weight'] === 0) {
|
||||
continue;
|
||||
}
|
||||
$font_face = ['id' => Common::random_slug(10), 'weight' => $m_face['weight'], 'width' => $m_face['width'] ?: '100%', 'style' => $m_face['style'], 'display' => $m_face['display'], 'selector' => $m_face['selector'], 'comment' => $m_face['comment'], 'unicodeRange' => '', 'preload' => $m_face['preload']];
|
||||
$files = [];
|
||||
$filtered_m_font_files = array_filter($m_font_files, static fn($f) => $f['weight'] === $m_face['weight'] && $f['style'] === $m_face['style'] && array_diff($metadata['google_fonts']['subsets'], $f['subsets']) === array_diff($f['subsets'], $metadata['google_fonts']['subsets']) && in_array($f['format'], $metadata['google_fonts']['formats'], \true));
|
||||
$format_precedence = ['woff2' => 1, 'woff' => 2, 'ttf' => 3, 'otf' => 4, 'eot' => 5];
|
||||
usort($filtered_m_font_files, static fn($a, $b) => $format_precedence[$a['format']] <=> $format_precedence[$b['format']]);
|
||||
foreach ($filtered_m_font_files as $filtered_m_font_file) {
|
||||
$file_name = sanitize_title_with_dashes(sprintf(
|
||||
'google-fonts-%s-%s-%s-%s-%s-%s',
|
||||
$metadata['google_fonts']['font_data']['slug'],
|
||||
// family
|
||||
$metadata['google_fonts']['font_data']['version'] ?? 'latest',
|
||||
implode('-', $metadata['google_fonts']['subsets']),
|
||||
$filtered_m_font_file['weight'],
|
||||
$filtered_m_font_file['style'],
|
||||
time()
|
||||
)) . '.' . $filtered_m_font_file['format'];
|
||||
try {
|
||||
$file = $media->remote($filtered_m_font_file['url'], $file_name, $filtered_m_font_file['format'], ['fonts.gstatic.com']);
|
||||
} catch (\Throwable $throwable) {
|
||||
$media->rollback();
|
||||
return $this->operation_error($throwable, __('Unable to download the Google font files.', 'jooosi-fon'));
|
||||
}
|
||||
$metadata['google_fonts']['font_files'] = array_map(static fn($f) => $f['uid'] === $filtered_m_font_file['uid'] ? array_merge($f, ['file' => $file]) : $f, $metadata['google_fonts']['font_files']);
|
||||
$metadata['google_fonts']['font_faces'][$k]['attached_font_files'][] = $filtered_m_font_file['uid'];
|
||||
$files[] = $file;
|
||||
}
|
||||
$font_face['files'] = $files;
|
||||
$font_faces[] = $font_face;
|
||||
}
|
||||
}
|
||||
try {
|
||||
$repository = new FontRepository();
|
||||
$id = $repository->insert(['type' => $type, 'title' => $title, 'slug' => $slug, 'family' => $family, 'status' => $status, 'metadata' => FontCodec::encode($metadata), 'font_faces' => FontCodec::encode($font_faces)], ['%s', '%s', '%s', '%s', '%d', '%s', '%s']);
|
||||
$media->commit();
|
||||
} catch (\Throwable $throwable) {
|
||||
$media->rollback();
|
||||
return $this->operation_error($throwable, __('Unable to create the Google font.', 'jooosi-fon'));
|
||||
}
|
||||
FontEvents::dispatch('google_fonts_store', $id);
|
||||
return new WP_REST_Response(['id' => $id], 200, []);
|
||||
}
|
||||
private function google_fonts_update(WP_REST_Request $wprestRequest): WP_REST_Response
|
||||
{
|
||||
$payload = $wprestRequest->get_json_params();
|
||||
$id = (int) $wprestRequest->get_param('id');
|
||||
$repository = new FontRepository();
|
||||
$existing = $repository->findOfType($id, 'google-fonts');
|
||||
if (!$existing) {
|
||||
return new WP_REST_Response(['message' => __('Font not found', 'jooosi-fon')], 404, []);
|
||||
}
|
||||
$title = sanitize_text_field($payload['title']);
|
||||
$status = (bool) $payload['status'];
|
||||
$metadata = $payload['metadata'];
|
||||
$font_faces = [];
|
||||
add_filter('wp_check_filetype_and_ext', static fn($data, $file, $filename, $mimes) => Upload::disable_real_mime_check($data, $file, $filename, $mimes), 10, 4);
|
||||
add_filter('upload_mimes', static fn($mime_types) => Upload::upload_mimes($mime_types, \true), 1000001);
|
||||
$media = new MediaImportService();
|
||||
try {
|
||||
$oldAttachmentIds = MediaImportService::attachmentIds(FontCodec::decode((string) $existing->font_faces));
|
||||
$this->google_fonts_update_filter($metadata, $font_faces, $media);
|
||||
$newAttachmentIds = MediaImportService::attachmentIds($font_faces);
|
||||
$repository->update($id, ['title' => $title, 'status' => $status, 'metadata' => FontCodec::encode($metadata), 'font_faces' => FontCodec::encode($font_faces)], ['%s', '%d', '%s', '%s']);
|
||||
$media->commit();
|
||||
MediaImportService::deleteAttachments(array_diff($oldAttachmentIds, $newAttachmentIds));
|
||||
} catch (\Throwable $throwable) {
|
||||
$media->rollback();
|
||||
return $this->operation_error($throwable, __('Unable to update the Google font.', 'jooosi-fon'));
|
||||
}
|
||||
FontEvents::dispatch('google_fonts_update', $id);
|
||||
return new WP_REST_Response(['id' => $id], 200, []);
|
||||
}
|
||||
private function export(WP_REST_Request $wprestRequest): WP_REST_Response
|
||||
{
|
||||
/** @var wpdb $wpdb */
|
||||
global $wpdb;
|
||||
$params = $wprestRequest->get_json_params();
|
||||
$items = $params['items'];
|
||||
if (!is_array($items) || $items === []) {
|
||||
return new WP_REST_Response(['message' => 'No items to export'], 400, []);
|
||||
}
|
||||
$is_bundled = Config::get('misc.export_bundle_binary', \false);
|
||||
$placeholder = implode(',', array_fill(0, count($items), '%d'));
|
||||
$sql = "\n SELECT * FROM {$wpdb->prefix}jooosi_fon_fonts\n WHERE id IN ({$placeholder})\n ";
|
||||
$sql = $wpdb->prepare($sql, $items);
|
||||
$rows = $wpdb->get_results($sql);
|
||||
$items = [];
|
||||
$bundledBytes = 0;
|
||||
foreach ($rows as $row) {
|
||||
$font_faces = FontCodec::decode((string) $row->font_faces);
|
||||
$metadata = FontCodec::decode((string) $row->metadata);
|
||||
if ($row->type === 'adobe-fonts') {
|
||||
continue;
|
||||
} elseif ($row->type === 'custom') {
|
||||
foreach ($font_faces as $i => $font_face) {
|
||||
foreach ($font_face->files as $j => $file) {
|
||||
// bundle binary and encode it to base64 if enabled
|
||||
if ($is_bundled) {
|
||||
$file_path = get_attached_file($file->attachment_id);
|
||||
if ($file_path) {
|
||||
$fileSize = filesize($file_path);
|
||||
if (!is_int($fileSize) || $fileSize < 1) {
|
||||
return new WP_REST_Response(['message' => __('A font attachment is missing or unreadable.', 'jooosi-fon')], 409);
|
||||
}
|
||||
$bundledBytes += $fileSize;
|
||||
if ($bundledBytes > 50 * \MB_IN_BYTES) {
|
||||
return new WP_REST_Response(['message' => __('The bundled export exceeds the 50 MB limit. Export fewer fonts or disable bundled binaries.', 'jooosi-fon')], 413);
|
||||
}
|
||||
$binary = file_get_contents($file_path);
|
||||
if (!is_string($binary)) {
|
||||
return new WP_REST_Response(['message' => __('A font attachment could not be read.', 'jooosi-fon')], 409);
|
||||
}
|
||||
$font_faces[$i]->files[$j]->binary = base64_encode($binary);
|
||||
} else {
|
||||
return new WP_REST_Response(['message' => __('A font attachment is missing or unreadable.', 'jooosi-fon')], 409);
|
||||
}
|
||||
unset($font_faces[$i]->files[$j]->attachment_url);
|
||||
} else {
|
||||
$attachment_url = wp_get_attachment_url($file->attachment_id);
|
||||
if ($attachment_url) {
|
||||
$parsed = parse_url($attachment_url);
|
||||
$font_faces[$i]->files[$j]->attachment_url = $parsed['path'];
|
||||
}
|
||||
}
|
||||
unset($font_faces[$i]->files[$j]->attachment_id);
|
||||
}
|
||||
}
|
||||
} elseif ($row->type === 'google-fonts') {
|
||||
// minimize metadata
|
||||
$font_faces = [];
|
||||
if (property_exists($metadata, 'google_fonts')) {
|
||||
foreach ($metadata->google_fonts->font_files as $i => $font_file) {
|
||||
if (property_exists($font_file, 'file')) {
|
||||
unset($metadata->google_fonts->font_files[$i]->file);
|
||||
}
|
||||
}
|
||||
foreach ($metadata->google_fonts->font_faces as $i => $font_face) {
|
||||
if (property_exists($font_face, 'attached_font_files')) {
|
||||
unset($metadata->google_fonts->font_faces[$i]->attached_font_files);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
$item = ['type' => $row->type, 'title' => $row->title, 'slug' => $row->slug, 'family' => $row->family];
|
||||
$item['font_faces'] = base64_encode(json_encode($font_faces, \JSON_THROW_ON_ERROR));
|
||||
$item['metadata'] = base64_encode(json_encode($metadata, \JSON_THROW_ON_ERROR));
|
||||
$items[] = $item;
|
||||
}
|
||||
$data = ['module_id' => JOOOSI_FON::WP_OPTION, 'version' => JOOOSI_FON::VERSION, 'export_time' => time(), 'site_url' => site_url(), 'is_bundled' => $is_bundled, 'items' => $items];
|
||||
return new WP_REST_Response(['data' => $data], 200);
|
||||
}
|
||||
private function import(WP_REST_Request $wprestRequest): WP_REST_Response
|
||||
{
|
||||
$params = $wprestRequest->get_json_params();
|
||||
$site_url = $params['site_url'];
|
||||
$is_bundled = rest_sanitize_boolean($params['is_bundled']);
|
||||
$item = $params['item'];
|
||||
$type = $item['type'];
|
||||
$title = sanitize_text_field($item['title']);
|
||||
$slug = Common::random_slug(10);
|
||||
$family = sanitize_text_field($item['family']);
|
||||
$status = \true;
|
||||
try {
|
||||
$encodedFontFaces = base64_decode($item['font_faces'], \true);
|
||||
$encodedMetadata = base64_decode($item['metadata'], \true);
|
||||
if (!is_string($encodedFontFaces) || !is_string($encodedMetadata)) {
|
||||
throw new \UnexpectedValueException('The import payload is not valid base64.');
|
||||
}
|
||||
$font_faces = json_decode($encodedFontFaces, \false, 512, \JSON_THROW_ON_ERROR);
|
||||
$metadata = json_decode($encodedMetadata, \false, 512, \JSON_THROW_ON_ERROR);
|
||||
} catch (\Throwable $throwable) {
|
||||
return $this->operation_error($throwable, __('The font import payload is invalid.', 'jooosi-fon'), 400);
|
||||
}
|
||||
add_filter('wp_check_filetype_and_ext', static fn($data, $file, $filename, $mimes) => Upload::disable_real_mime_check($data, $file, $filename, $mimes), 10, 4);
|
||||
add_filter('upload_mimes', static fn($mime_types) => Upload::upload_mimes($mime_types, \true), 1000001);
|
||||
$media = new MediaImportService();
|
||||
if ($item['type'] === 'adobe-fonts') {
|
||||
return new WP_REST_Response(['message' => 'Adobe Fonts is not importable'], 400, []);
|
||||
} elseif ($item['type'] === 'google-fonts') {
|
||||
$font_faces = json_decode($encodedFontFaces, \true, 512, \JSON_THROW_ON_ERROR);
|
||||
$metadata = json_decode($encodedMetadata, \true, 512, \JSON_THROW_ON_ERROR);
|
||||
try {
|
||||
$this->google_fonts_update_filter($metadata, $font_faces, $media);
|
||||
} catch (\Throwable $throwable) {
|
||||
$media->rollback();
|
||||
return $this->operation_error($throwable, __('Unable to download the Google font files.', 'jooosi-fon'));
|
||||
}
|
||||
} elseif ($item['type'] === 'custom') {
|
||||
try {
|
||||
$sourceHost = (string) wp_parse_url($site_url, \PHP_URL_HOST);
|
||||
foreach ($font_faces as $i => $font_face) {
|
||||
foreach ($font_face->files as $j => $file) {
|
||||
// if not first-hand
|
||||
$font_faces[$i]->files[$j]->name = preg_replace('#\-[\_\-a-zA-Z0-9]{5}\-\d{10}$#', '', $file->name);
|
||||
// if explicit using a Google Fonts file
|
||||
$font_faces[$i]->files[$j]->name = preg_replace('#\-\d{10}\-(woff2|woff|ttf)$#', '', $file->name);
|
||||
$file_name = sanitize_title_with_dashes(sprintf('%s-%s-%s', $font_faces[$i]->files[$j]->name, Common::random_slug(5), time())) . '.' . $file->extension;
|
||||
if ($is_bundled) {
|
||||
$binary = base64_decode((string) ($file->binary ?? ''), \true);
|
||||
if (!is_string($binary) || strlen($binary) > 20 * \MB_IN_BYTES) {
|
||||
throw new \UnexpectedValueException('The bundled font file is invalid or exceeds 20 MB.');
|
||||
}
|
||||
$attachment = $media->binary($binary, $file_name, (string) $file->extension);
|
||||
unset($font_faces[$i]->files[$j]->binary);
|
||||
} else {
|
||||
$attachmentPath = (string) ($file->attachment_url ?? '');
|
||||
if ($attachmentPath === '' || $attachmentPath[0] !== '/' || wp_parse_url($attachmentPath, \PHP_URL_HOST) !== null) {
|
||||
throw new \UnexpectedValueException('The imported attachment path is invalid.');
|
||||
}
|
||||
$attachment = $media->remote(untrailingslashit($site_url) . $attachmentPath, $file_name, (string) $file->extension, [$sourceHost]);
|
||||
}
|
||||
foreach ($attachment as $key => $value) {
|
||||
$font_faces[$i]->files[$j]->{$key} = $value;
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (\Throwable $throwable) {
|
||||
$media->rollback();
|
||||
return $this->operation_error($throwable, __('Unable to import the custom font files.', 'jooosi-fon'));
|
||||
}
|
||||
} else {
|
||||
return new WP_REST_Response(['message' => 'Invalid item type'], 400, []);
|
||||
}
|
||||
try {
|
||||
$repository = new FontRepository();
|
||||
$id = $repository->insert(['type' => $type, 'title' => $title, 'slug' => $slug, 'family' => $family, 'status' => $status, 'metadata' => FontCodec::encode($metadata), 'font_faces' => FontCodec::encode($font_faces)], ['%s', '%s', '%s', '%s', '%d', '%s', '%s']);
|
||||
$media->commit();
|
||||
} catch (\Throwable $throwable) {
|
||||
$media->rollback();
|
||||
return $this->operation_error($throwable, __('Unable to create the imported font.', 'jooosi-fon'));
|
||||
}
|
||||
FontEvents::dispatch('import', $id);
|
||||
return new WP_REST_Response(['id' => $id], 200, []);
|
||||
}
|
||||
private function google_fonts_update_filter(&$metadata, &$font_faces, MediaImportService $media): void
|
||||
{
|
||||
$m_font_faces = $metadata['google_fonts']['font_faces'];
|
||||
$m_font_files = $metadata['google_fonts']['font_files'];
|
||||
foreach ($m_font_faces as $k => $m_face) {
|
||||
$metadata['google_fonts']['font_faces'][$k]['attached_font_files'] = [];
|
||||
if (!$m_face['isEnabled']) {
|
||||
continue;
|
||||
}
|
||||
if ($metadata['google_fonts']['variable']) {
|
||||
if ($m_face['weight'] !== 0) {
|
||||
continue;
|
||||
}
|
||||
$all_filtered_m_font_files = GoogleFontFileSelector::variableFiles($m_font_files, $m_face, $metadata['google_fonts']['subsets'], $metadata['google_fonts']['formats']);
|
||||
foreach ($all_filtered_m_font_files as $filtered_m_font_file) {
|
||||
$wght = array_filter($metadata['google_fonts']['font_data']['axes'], static fn($a) => $a['tag'] === 'wght');
|
||||
$wdth = array_filter($metadata['google_fonts']['font_data']['axes'], static fn($a) => $a['tag'] === 'wdth');
|
||||
$slnt = array_filter($metadata['google_fonts']['font_data']['axes'], static fn($a) => $a['tag'] === 'slnt');
|
||||
$wdth = array_values($wdth);
|
||||
$wght = array_values($wght);
|
||||
$slnt = array_values($slnt);
|
||||
$font_face = ['id' => Common::random_slug(10), 'weight' => $wght !== [] ? sprintf('%s %s', $wght[0]['min'], $wght[0]['max']) : '400', 'width' => $wdth !== [] ? sprintf('%s%% %s%%', $wdth[0]['min'], $wdth[0]['max']) : '100%', 'style' => $slnt !== [] ? sprintf('oblique %sdeg %sdeg', $slnt[0]['max'] * -1, $slnt[0]['min'] * -1) : $m_face['style'], 'display' => $m_face['display'], 'selector' => $m_face['selector'], 'comment' => $m_face['comment'], 'preload' => $m_face['preload']];
|
||||
if (array_key_exists('file', $filtered_m_font_file)) {
|
||||
$file = $filtered_m_font_file['file'];
|
||||
} else {
|
||||
$file_name = sanitize_title_with_dashes(sprintf(
|
||||
'google-fonts-%s-%s-%s-var-%s-%s',
|
||||
$metadata['google_fonts']['font_data']['slug'],
|
||||
// family
|
||||
$metadata['google_fonts']['font_data']['version'] ?? 'latest',
|
||||
implode('_', $filtered_m_font_file['subsets']),
|
||||
Common::random_slug(5),
|
||||
time()
|
||||
)) . '.' . $filtered_m_font_file['format'];
|
||||
$file = $media->remote($filtered_m_font_file['url'], $file_name, $filtered_m_font_file['format'], ['fonts.gstatic.com']);
|
||||
$metadata['google_fonts']['font_files'] = array_map(static fn($f) => $f['uid'] === $filtered_m_font_file['uid'] ? array_merge($f, ['file' => $file]) : $f, $metadata['google_fonts']['font_files']);
|
||||
}
|
||||
$metadata['google_fonts']['font_faces'][$k]['attached_font_files'][] = $filtered_m_font_file['uid'];
|
||||
$font_face['files'] = [$file];
|
||||
$font_face['unicodeRange'] = $filtered_m_font_file['unicodeRange'] ?? '';
|
||||
$font_faces[] = $font_face;
|
||||
}
|
||||
} else {
|
||||
if ($m_face['weight'] === 0) {
|
||||
continue;
|
||||
}
|
||||
$font_face = ['id' => Common::random_slug(10), 'weight' => $m_face['weight'], 'width' => $m_face['width'] ?: '100%', 'style' => $m_face['style'], 'display' => $m_face['display'], 'selector' => $m_face['selector'], 'comment' => $m_face['comment'], 'unicodeRange' => '', 'preload' => $m_face['preload']];
|
||||
$files = [];
|
||||
$filtered_m_font_files = array_filter($m_font_files, static fn($f) => $f['weight'] === $m_face['weight'] && $f['style'] === $m_face['style'] && array_diff($metadata['google_fonts']['subsets'], $f['subsets']) === array_diff($f['subsets'], $metadata['google_fonts']['subsets']) && in_array($f['format'], $metadata['google_fonts']['formats'], \true));
|
||||
$format_precedence = ['woff2' => 1, 'woff' => 2, 'ttf' => 3, 'otf' => 4, 'eot' => 5];
|
||||
usort($filtered_m_font_files, static fn($a, $b) => $format_precedence[$a['format']] <=> $format_precedence[$b['format']]);
|
||||
foreach ($filtered_m_font_files as $filtered_m_font_file) {
|
||||
if (array_key_exists('file', $filtered_m_font_file)) {
|
||||
$file = $filtered_m_font_file['file'];
|
||||
} else {
|
||||
$file_name = sanitize_title_with_dashes(sprintf(
|
||||
'google-fonts-%s-%s-%s-%s-%s-%s',
|
||||
$metadata['google_fonts']['font_data']['slug'],
|
||||
// family
|
||||
$metadata['google_fonts']['font_data']['version'] ?? 'latest',
|
||||
implode('-', $metadata['google_fonts']['subsets']),
|
||||
$filtered_m_font_file['weight'],
|
||||
$filtered_m_font_file['style'],
|
||||
time()
|
||||
)) . '.' . $filtered_m_font_file['format'];
|
||||
$file = $media->remote($filtered_m_font_file['url'], $file_name, $filtered_m_font_file['format'], ['fonts.gstatic.com']);
|
||||
$metadata['google_fonts']['font_files'] = array_map(static fn($f) => $f['uid'] === $filtered_m_font_file['uid'] ? array_merge($f, ['file' => $file]) : $f, $metadata['google_fonts']['font_files']);
|
||||
}
|
||||
$metadata['google_fonts']['font_faces'][$k]['attached_font_files'][] = $filtered_m_font_file['uid'];
|
||||
$files[] = $file;
|
||||
}
|
||||
$font_face['files'] = $files;
|
||||
$font_faces[] = $font_face;
|
||||
}
|
||||
}
|
||||
}
|
||||
private function update_google_fonts_metadata()
|
||||
{
|
||||
$file_path = Cache::get_cache_path('webfonts.json');
|
||||
// The bundled and cached catalogs remain available while the canonical repository is being migrated.
|
||||
$cdn_url = apply_filters('f!jooosi/fon/font:google_fonts.metadata.file_url', 'https://cdn.jsdelivr.net/gh/jooosi-project/jooosi-fon@master/google-fonts.json');
|
||||
$cdn_url = apply_filters_deprecated('f!yabe/webfont/font:google_fonts.metadata.file_url', [$cdn_url], '2.1.0', 'f!jooosi/fon/font:google_fonts.metadata.file_url');
|
||||
if (!wp_http_validate_url($cdn_url)) {
|
||||
throw new \Exception(__('The metadata URL is not safe', 'jooosi-fon'));
|
||||
}
|
||||
$temp_file = download_url($cdn_url, 30);
|
||||
if (is_wp_error($temp_file)) {
|
||||
throw new \Exception(__('Failed to download metadata file', 'jooosi-fon'));
|
||||
}
|
||||
$staging_file = $file_path . '.tmp-' . wp_generate_uuid4();
|
||||
try {
|
||||
$contents = file_get_contents($temp_file);
|
||||
if (!is_string($contents)) {
|
||||
throw new \RuntimeException('The downloaded metadata file is not readable.');
|
||||
}
|
||||
json_decode($contents, \true, 512, \JSON_THROW_ON_ERROR);
|
||||
Common::save_file($contents, $staging_file);
|
||||
if (!@rename($staging_file, $file_path)) {
|
||||
throw new \RuntimeException('The metadata cache could not be replaced atomically.');
|
||||
}
|
||||
delete_transient('jooosi_fon_google_fonts_catalog_stats');
|
||||
} finally {
|
||||
if (is_string($temp_file) && file_exists($temp_file)) {
|
||||
unlink($temp_file);
|
||||
}
|
||||
if (file_exists($staging_file)) {
|
||||
unlink($staging_file);
|
||||
}
|
||||
}
|
||||
}
|
||||
private function google_fonts_metadata(WP_REST_Request $wprestRequest): WP_REST_Response
|
||||
{
|
||||
$file_path = Cache::get_cache_path('webfonts.json');
|
||||
$query = $wprestRequest->get_query_params();
|
||||
$force_update = filter_var($query['force'] ?? \false, \FILTER_VALIDATE_BOOLEAN);
|
||||
$force_cdn = apply_filters('f!jooosi/fon/font:google_fonts.metadata.force_cdn', \false);
|
||||
$force_cdn = apply_filters_deprecated('f!yabe/webfont/font:google_fonts.metadata.force_cdn', [$force_cdn], '2.1.0', 'f!jooosi/fon/font:google_fonts.metadata.force_cdn');
|
||||
if ($force_update || $force_cdn) {
|
||||
try {
|
||||
$this->update_google_fonts_metadata();
|
||||
} catch (\Exception $e) {
|
||||
return new WP_REST_Response(['message' => $e->getMessage()], 500, []);
|
||||
}
|
||||
$metadata = json_decode(file_get_contents($file_path), null, 512, \JSON_THROW_ON_ERROR);
|
||||
return new WP_REST_Response(['fonts' => $metadata], 200, []);
|
||||
}
|
||||
if (!file_exists($file_path)) {
|
||||
$payload = file_get_contents(dirname(JOOOSI_FON::FILE) . '/google-fonts.json');
|
||||
Common::save_file($payload, $file_path);
|
||||
}
|
||||
$enable_update = apply_filters('f!jooosi/fon/font:google_fonts.metadata.enable_update', \true);
|
||||
$enable_update = apply_filters_deprecated('f!yabe/webfont/font:google_fonts.metadata.enable_update', [$enable_update], '2.1.0', 'f!jooosi/fon/font:google_fonts.metadata.enable_update');
|
||||
if ($enable_update !== \false) {
|
||||
if (filemtime($file_path) < strtotime('-1 day')) {
|
||||
try {
|
||||
$this->update_google_fonts_metadata();
|
||||
} catch (\Exception $e) {
|
||||
// Keep serving the cached catalog when an automatic refresh is unavailable.
|
||||
}
|
||||
}
|
||||
}
|
||||
$metadata = json_decode(file_get_contents($file_path), null, 512, \JSON_THROW_ON_ERROR);
|
||||
return new WP_REST_Response(['fonts' => $metadata], 200, []);
|
||||
}
|
||||
private function google_fonts_webfonts(WP_REST_Request $wprestRequest): WP_REST_Response
|
||||
{
|
||||
$url_params = $wprestRequest->get_url_params();
|
||||
$query = $wprestRequest->get_query_params();
|
||||
$slug = $url_params['slug'] ?? '';
|
||||
if (trim($slug) === '') {
|
||||
return new WP_REST_Response(['message' => __('Slug is required', 'jooosi-fon')], 400, []);
|
||||
}
|
||||
// retrieve metadata
|
||||
$file_path = Cache::get_cache_path('webfonts.json');
|
||||
if (!file_exists($file_path)) {
|
||||
$payload = file_get_contents(dirname(JOOOSI_FON::FILE) . '/google-fonts.json');
|
||||
Common::save_file($payload, $file_path);
|
||||
}
|
||||
$enable_update = apply_filters('f!jooosi/fon/font:google_fonts.metadata.enable_update', \true);
|
||||
$enable_update = apply_filters_deprecated('f!yabe/webfont/font:google_fonts.metadata.enable_update', [$enable_update], '2.1.0', 'f!jooosi/fon/font:google_fonts.metadata.enable_update');
|
||||
if ($enable_update !== \false) {
|
||||
if (filemtime($file_path) < strtotime('-1 day')) {
|
||||
try {
|
||||
$this->update_google_fonts_metadata();
|
||||
} catch (\Exception $e) {
|
||||
// Keep serving the cached catalog when an automatic refresh is unavailable.
|
||||
}
|
||||
}
|
||||
}
|
||||
$metadata = json_decode(file_get_contents($file_path), null, 512, \JSON_THROW_ON_ERROR);
|
||||
// search for the font by slug
|
||||
$font = array_filter($metadata, static fn($font) => $font->slug === $slug);
|
||||
if (empty($font)) {
|
||||
return new WP_REST_Response(['message' => __('Font not found', 'jooosi-fon')], 404, []);
|
||||
}
|
||||
$font = array_values($font)[0];
|
||||
// get the first element of the array
|
||||
$subsets = $query['subsets'] ?? '';
|
||||
if (!$subsets) {
|
||||
$subsets = in_array('latin', $font->subsets, \true) ? ['latin'] : [$font->subsets[0]];
|
||||
} else {
|
||||
$querySubsets = explode(',', $subsets);
|
||||
$subsets = array_intersect($font->subsets, $querySubsets);
|
||||
}
|
||||
$subsets = array_unique($subsets);
|
||||
sort($subsets);
|
||||
if ($subsets === []) {
|
||||
return new WP_REST_Response(['message' => __('None of the requested subsets are available for this font.', 'jooosi-fon')], 400, []);
|
||||
}
|
||||
$cache_key = 'jooosi_fon_google_fonts_files_' . md5($slug . ':' . implode(',', $subsets));
|
||||
$cachedFontFiles = get_transient($cache_key);
|
||||
if ($cachedFontFiles !== \false) {
|
||||
return new WP_REST_Response(['font' => $font, 'files' => array_values($cachedFontFiles)], 200, []);
|
||||
}
|
||||
$variantKeys = $font->variants;
|
||||
$fontFormats = ['woff2', 'woff', 'ttf'];
|
||||
try {
|
||||
foreach ($variantKeys as $variantKey) {
|
||||
foreach ($fontFormats as $fontFormat) {
|
||||
$fontUrl = $this->fetch_google_font_file($font, $fontFormat, $variantKey, $subsets);
|
||||
$newFontFile = new stdClass();
|
||||
$newFontFile->format = $fontFormat;
|
||||
$newFontFile->weight = intval($variantKey);
|
||||
switch (preg_replace('/\d/', '', (string) $variantKey)) {
|
||||
case 'i':
|
||||
$newFontFile->style = 'italic';
|
||||
break;
|
||||
case 'o':
|
||||
$newFontFile->style = 'oblique';
|
||||
break;
|
||||
default:
|
||||
$newFontFile->style = 'normal';
|
||||
}
|
||||
$newFontFile->subsets = $subsets;
|
||||
$newFontFile->url = $fontUrl;
|
||||
$font->files[] = $newFontFile;
|
||||
}
|
||||
}
|
||||
if (!empty($font->axes)) {
|
||||
$italics = [];
|
||||
if (count(array_filter($variantKeys, static fn(string $variantKey) => preg_replace('/\d/', '', $variantKey) === '')) > 0) {
|
||||
array_push($italics, 0);
|
||||
}
|
||||
if (count(array_filter($variantKeys, static fn(string $variantKey) => preg_replace('/\d/', '', $variantKey) === 'i')) > 0) {
|
||||
array_push($italics, 1);
|
||||
}
|
||||
foreach ($italics as $italic) {
|
||||
switch ($italic) {
|
||||
case 0:
|
||||
$style = 'normal';
|
||||
break;
|
||||
case 1:
|
||||
$style = 'italic';
|
||||
break;
|
||||
default:
|
||||
$style = 'normal';
|
||||
}
|
||||
$filteredFontFilesVariable = array_filter($font->files, function ($fontFile) use ($style, $subsets) {
|
||||
return $fontFile->format === 'woff2' && $fontFile->weight === 0 && $fontFile->style === $style && array_intersect($fontFile->subsets, $subsets) !== [];
|
||||
});
|
||||
if (count($filteredFontFilesVariable) < count($subsets)) {
|
||||
$fetchedVariableFonts = $this->fetch_google_font_variable_file($font, $italic, $font->axes);
|
||||
foreach ($fetchedVariableFonts as $fetchedVariableFont) {
|
||||
$existFilteredFontFilesVariable = array_filter($filteredFontFilesVariable, function ($fontFile) use ($fetchedVariableFont, $style) {
|
||||
return $fontFile->format === 'woff2' && $fontFile->weight === 0 && $fontFile->style === $style && in_array($fetchedVariableFont['subset'], $fontFile->subsets, \true);
|
||||
});
|
||||
if (empty($existFilteredFontFilesVariable)) {
|
||||
$newFontFile = new stdClass();
|
||||
$newFontFile->format = 'woff2';
|
||||
$newFontFile->weight = 0;
|
||||
$newFontFile->style = $style;
|
||||
$newFontFile->subsets = [$fetchedVariableFont['subset']];
|
||||
$newFontFile->url = $fetchedVariableFont['url'];
|
||||
$newFontFile->unicodeRange = $fetchedVariableFont['unicodeRange'];
|
||||
$font->files[] = $newFontFile;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (\Throwable $throwable) {
|
||||
return $this->operation_error($throwable, __('Unable to fetch the Google font stylesheets.', 'jooosi-fon'), 502);
|
||||
}
|
||||
$filteredFontFiles = array_filter($font->files, static function ($fontFile) use ($subsets) {
|
||||
$fontFileSubsets = array_unique($fontFile->subsets);
|
||||
sort($fontFileSubsets);
|
||||
$variableNumberedSubsets = \false;
|
||||
if ($fontFile->weight === 0) {
|
||||
foreach ($fontFile->subsets as $ffSubset) {
|
||||
if (preg_match('/\d/', $ffSubset)) {
|
||||
$variableNumberedSubsets = \true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return $fontFileSubsets === $subsets || $variableNumberedSubsets || $fontFile->weight === 0 && array_intersect($fontFileSubsets, $subsets) !== [];
|
||||
});
|
||||
// Cache the result for 1 day
|
||||
set_transient($cache_key, $filteredFontFiles, \DAY_IN_SECONDS);
|
||||
unset($font->files);
|
||||
return new WP_REST_Response(['font' => $font, 'files' => array_values($filteredFontFiles)], 200, []);
|
||||
}
|
||||
private function fetch_google_font_file($font, string $format, string $variant, array $subsets): string
|
||||
{
|
||||
switch ($format) {
|
||||
case 'woff2':
|
||||
$userAgent = JOOOSI_FON::USER_AGENTS['WOFF2'];
|
||||
break;
|
||||
case 'woff':
|
||||
$userAgent = JOOOSI_FON::USER_AGENTS['WOFF'];
|
||||
break;
|
||||
case 'ttf':
|
||||
$userAgent = JOOOSI_FON::USER_AGENTS['TTF'];
|
||||
break;
|
||||
default:
|
||||
$userAgent = apply_filters('f!jooosi/fon/font:google_fonts.fetch.user_agent.default', JOOOSI_FON::USER_AGENTS['CURRENT']);
|
||||
$userAgent = apply_filters_deprecated('f!yabe/webfont/font:google_fonts.fetch.user_agent.default', [$userAgent], '2.1.0', 'f!jooosi/fon/font:google_fonts.fetch.user_agent.default');
|
||||
}
|
||||
$family = str_replace(' ', '+', $font->family);
|
||||
$url = sprintf('https://fonts.googleapis.com/css?family=%s:%s&subset=%s', $family, $variant, implode(',', $subsets));
|
||||
$body = (new GoogleFontsClient())->fetchCss($url, $userAgent);
|
||||
$cssDocument = (new Parser($body))->parse();
|
||||
$contents = $cssDocument->getContents();
|
||||
if ($contents === [] || $contents[0]->getRules('src') === []) {
|
||||
throw new \RuntimeException(__('Google Fonts returned an invalid stylesheet', 'jooosi-fon'));
|
||||
}
|
||||
$fontUrl = $contents[0]->getRules('src')[0]->getValue()->getListComponents()[0]->getURL()->getString();
|
||||
return $fontUrl;
|
||||
}
|
||||
private function negative_case(string $string): string
|
||||
{
|
||||
$arr = str_split($string);
|
||||
foreach ($arr as $key => $char) {
|
||||
$arr[$key] = ctype_upper($char) ? strtolower($char) : strtoupper($char);
|
||||
}
|
||||
return implode('', $arr);
|
||||
}
|
||||
private function operation_error(\Throwable $throwable, string $message, int $status = 500): WP_REST_Response
|
||||
{
|
||||
do_action('a!jooosi/fon/api:error', $throwable, $message, $status);
|
||||
if (defined('WP_DEBUG') && \WP_DEBUG) {
|
||||
$message = sprintf('%s %s', $message, $throwable->getMessage());
|
||||
}
|
||||
return new WP_REST_Response(['message' => $message], $status);
|
||||
}
|
||||
/**
|
||||
* @see https://developers.google.com/fonts/docs/css2#api_url_specification
|
||||
*/
|
||||
private function fetch_google_font_variable_file($font, int $italic, array $axes): array
|
||||
{
|
||||
$axis_tag_list = [];
|
||||
$axis_tuple_list = [];
|
||||
$family = str_replace(' ', '+', $font->family);
|
||||
// convert axes to array
|
||||
$axes = array_map(static fn($axis) => ['tag' => $axis->tag, 'min' => $axis->min ?? null, 'max' => $axis->max ?? null, 'defaultValue' => $axis->defaultValue ?? null], $axes);
|
||||
// add ital axis
|
||||
$axes[] = ['tag' => 'ital', 'defaultValue' => $italic];
|
||||
// sort axes by "tag" alphabetically (e.g. a,b,c,A,B,C)
|
||||
usort($axes, fn(array $a, array $b) => strcmp((string) $this->negative_case($a['tag']), (string) $this->negative_case($b['tag'])));
|
||||
foreach ($axes as $a) {
|
||||
$axis_tag_list[] = $a['tag'];
|
||||
if (array_key_exists('min', $a) && array_key_exists('max', $a)) {
|
||||
$axis_tuple_list[] = sprintf('%s..%s', $a['min'], $a['max']);
|
||||
} else {
|
||||
$axis_tuple_list[] = sprintf('%s', $a['defaultValue']);
|
||||
}
|
||||
}
|
||||
$url = sprintf('https://fonts.googleapis.com/css2?family=%s:%s@%s', $family, implode(',', $axis_tag_list), implode(',', $axis_tuple_list));
|
||||
$parsedFiles = [];
|
||||
$userAgent = apply_filters('f!jooosi/fon/font:google_fonts.fetch.user_agent.default', JOOOSI_FON::USER_AGENTS['CURRENT']);
|
||||
$userAgent = apply_filters_deprecated('f!yabe/webfont/font:google_fonts.fetch.user_agent.default', [$userAgent], '2.1.0', 'f!jooosi/fon/font:google_fonts.fetch.user_agent.default');
|
||||
$body = (new GoogleFontsClient())->fetchCss($url, $userAgent);
|
||||
// parse the css
|
||||
$cssDocument = (new Parser($body))->parse();
|
||||
// match all comment /* comment */
|
||||
preg_match_all('/\/\*(.*?)\*\//s', $body, $parsedComments);
|
||||
$comments = array_map(static fn(string $comment) => trim($comment), $parsedComments[1]);
|
||||
$cssContents = $cssDocument->getContents();
|
||||
for ($i = 0; $i < count($cssContents); $i++) {
|
||||
if (!isset($comments[$i]) || $cssContents[$i]->getRules('src') === [] || $cssContents[$i]->getRules('unicode-range') === []) {
|
||||
continue;
|
||||
}
|
||||
$subset = $comments[$i];
|
||||
$url = $cssContents[$i]->getRules('src')[0]->getValue()->getListComponents()[0]->getURL()->getString();
|
||||
$unicodeRangeRuleSet = $cssContents[$i]->getRules('unicode-range')[0]->getValue();
|
||||
$unicodeRange = $unicodeRangeRuleSet instanceof \JooosiFonDeps\Sabberworm\CSS\Value\RuleValueList ? implode(', ', $unicodeRangeRuleSet->getListComponents()) : $unicodeRangeRuleSet;
|
||||
$parsedFiles[] = ['subset' => $subset, 'url' => $url, 'unicodeRange' => $unicodeRange];
|
||||
}
|
||||
return $parsedFiles;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
<?php
|
||||
|
||||
declare (strict_types=1);
|
||||
namespace JooosiFon\Api\Migrations;
|
||||
|
||||
use JooosiFon\Api\AbstractApi;
|
||||
use JooosiFon\Api\ApiInterface;
|
||||
use JooosiFon\Api\Migrations\Support\SourceFontNormalizer;
|
||||
use JooosiFon\Api\Support\FontCodec;
|
||||
use JooosiFon\Api\Support\FontEvents;
|
||||
use JooosiFon\Api\Support\FontRepository;
|
||||
use JooosiFon\Api\Support\MediaImportService;
|
||||
use JooosiFon\Api\Support\RequestValidator;
|
||||
use JooosiFon\Utils\Common;
|
||||
use JooosiFon\Utils\Upload;
|
||||
use WP_REST_Request;
|
||||
use WP_REST_Response;
|
||||
use WP_REST_Server;
|
||||
final class BrainstormForceCustomFonts extends AbstractApi implements ApiInterface
|
||||
{
|
||||
public function get_prefix(): string
|
||||
{
|
||||
return 'migrations/brainstorm-force-custom-fonts';
|
||||
}
|
||||
public function register_custom_endpoints(): void
|
||||
{
|
||||
register_rest_route(self::API_NAMESPACE, $this->get_prefix() . '/import-fonts', ['methods' => WP_REST_Server::CREATABLE, 'callback' => fn(WP_REST_Request $request): WP_REST_Response => $this->import_fonts($request), 'permission_callback' => fn(WP_REST_Request $request): bool => $this->permission_callback($request)]);
|
||||
register_rest_route(self::API_NAMESPACE, $this->get_prefix() . '/clean-up', ['methods' => WP_REST_Server::CREATABLE, 'callback' => fn(WP_REST_Request $request): WP_REST_Response => $this->clean_up($request), 'permission_callback' => fn(WP_REST_Request $request): bool => $this->permission_callback($request), 'args' => ['confirm' => ['required' => \true, 'sanitize_callback' => 'rest_sanitize_boolean', 'validate_callback' => [RequestValidator::class, 'confirmed']]]]);
|
||||
}
|
||||
public function import_fonts(WP_REST_Request $request): WP_REST_Response
|
||||
{
|
||||
if (!defined('BSF_CUSTOM_FONTS_POST_TYPE')) {
|
||||
return new WP_REST_Response(['message' => __('Custom Fonts by Brainstorm Force is not activated.', 'jooosi-fon')], 404);
|
||||
}
|
||||
$fontIds = get_posts(['post_type' => \BSF_CUSTOM_FONTS_POST_TYPE, 'post_status' => 'publish', 'posts_per_page' => -1, 'fields' => 'ids', 'no_found_rows' => \true]);
|
||||
$preload = filter_var(get_option('bcf_preloading_fonts', \false), \FILTER_VALIDATE_BOOLEAN);
|
||||
add_filter('wp_check_filetype_and_ext', static fn($data, $file, $filename, $mimes) => Upload::disable_real_mime_check($data, $file, $filename, $mimes), 10, 4);
|
||||
add_filter('upload_mimes', static fn($mimeTypes) => Upload::upload_mimes($mimeTypes, \true), 1000001);
|
||||
$repository = new FontRepository();
|
||||
$media = new MediaImportService();
|
||||
$records = [];
|
||||
$insertedIds = [];
|
||||
$skipped = 0;
|
||||
try {
|
||||
foreach ($fontIds as $fontId) {
|
||||
$fontId = absint($fontId);
|
||||
$migrationSlug = 'migration-brainstorm-force-' . $fontId;
|
||||
if ($fontId < 1 || $repository->findBySlug($migrationSlug)) {
|
||||
continue;
|
||||
}
|
||||
$post = get_post($fontId);
|
||||
$source = get_post_meta($fontId, 'fonts-data', \true);
|
||||
if (!$post || !is_array($source)) {
|
||||
++$skipped;
|
||||
continue;
|
||||
}
|
||||
$family = sanitize_text_field($post->post_title);
|
||||
if ($family === '') {
|
||||
++$skipped;
|
||||
continue;
|
||||
}
|
||||
$normalized = SourceFontNormalizer::brainstormForce($source);
|
||||
$skipped += $normalized['skipped'];
|
||||
$fontFaces = [];
|
||||
foreach ($normalized['faces'] as $sourceFace) {
|
||||
$files = [];
|
||||
foreach ($sourceFace['files'] as $sourceFile) {
|
||||
$fileName = sanitize_title_with_dashes(sprintf('%s-%s-%s-%s-%s', $post->post_title, $sourceFace['weight'], $sourceFace['style'], Common::random_slug(5), time())) . '.' . $sourceFile['extension'];
|
||||
$files[] = $media->remote($sourceFile['location'], $fileName, $sourceFile['extension']);
|
||||
}
|
||||
if ($files === []) {
|
||||
continue;
|
||||
}
|
||||
$fontFaces[] = ['id' => Common::random_slug(10), 'weight' => $sourceFace['weight'], 'width' => $sourceFace['width'], 'style' => $sourceFace['style'], 'display' => '', 'selector' => '', 'comment' => '', 'unicodeRange' => '', 'preload' => \false, 'files' => $files];
|
||||
}
|
||||
if ($fontFaces === []) {
|
||||
++$skipped;
|
||||
continue;
|
||||
}
|
||||
$selector = $normalized['fallback'] === '' ? '' : '| ' . sanitize_text_field($normalized['fallback']);
|
||||
$records[] = ['type' => 'custom', 'title' => $family, 'slug' => $migrationSlug, 'family' => $family, 'status' => \true, 'metadata' => FontCodec::encode(['preload' => $preload, 'selector' => $selector, 'display' => $normalized['display']]), 'font_faces' => FontCodec::encode($fontFaces)];
|
||||
}
|
||||
if ($skipped > 0) {
|
||||
$media->rollback();
|
||||
return new WP_REST_Response(['message' => __('Some Brainstorm Force font records had no supported, readable files. Nothing was imported so the source records remain safe.', 'jooosi-fon'), 'skipped' => $skipped], 422);
|
||||
}
|
||||
$insertedIds = $repository->transaction(static function (FontRepository $repository) use ($records): array {
|
||||
$ids = [];
|
||||
foreach ($records as $record) {
|
||||
$ids[] = $repository->insert($record, ['%s', '%s', '%s', '%s', '%d', '%s', '%s']);
|
||||
}
|
||||
return $ids;
|
||||
});
|
||||
} catch (\Throwable $throwable) {
|
||||
$media->rollback();
|
||||
return new WP_REST_Response(['message' => __('The Brainstorm Force Custom Fonts migration failed; newly created Jooosi Fon records were rolled back.', 'jooosi-fon')], 500);
|
||||
}
|
||||
$media->commit();
|
||||
FontEvents::dispatch('migration', ['source' => 'brainstorm-force-custom-fonts', 'ids' => $insertedIds], \true);
|
||||
return new WP_REST_Response(['message' => __('Brainstorm Force Custom Fonts imported. Source records were preserved.', 'jooosi-fon'), 'imported' => count($insertedIds), 'skipped' => $skipped, 'source_preserved' => \true]);
|
||||
}
|
||||
public function clean_up(WP_REST_Request $request): WP_REST_Response
|
||||
{
|
||||
if (!defined('BSF_CUSTOM_FONTS_POST_TYPE')) {
|
||||
return new WP_REST_Response(['message' => __('Custom Fonts by Brainstorm Force is not activated.', 'jooosi-fon')], 404);
|
||||
}
|
||||
$fontIds = get_posts(['post_type' => \BSF_CUSTOM_FONTS_POST_TYPE, 'post_status' => 'publish', 'posts_per_page' => -1, 'fields' => 'ids', 'no_found_rows' => \true]);
|
||||
$trashedIds = [];
|
||||
foreach ($fontIds as $fontId) {
|
||||
$fontId = absint($fontId);
|
||||
if ($fontId < 1 || !wp_trash_post($fontId)) {
|
||||
foreach ($trashedIds as $trashedId) {
|
||||
wp_untrash_post($trashedId);
|
||||
}
|
||||
return new WP_REST_Response(['message' => __('Brainstorm Force source cleanup failed and previously trashed records were restored.', 'jooosi-fon')], 500);
|
||||
}
|
||||
$trashedIds[] = $fontId;
|
||||
}
|
||||
FontEvents::dispatch('clean_up', ['source' => 'brainstorm-force-custom-fonts', 'ids' => $trashedIds], \true);
|
||||
return new WP_REST_Response(['message' => __('Brainstorm Force Custom Fonts source records moved to the trash.', 'jooosi-fon'), 'cleaned' => count($trashedIds)]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Jooosi Fon package.
|
||||
*
|
||||
* (c) Joshua Gugun Siagian <suabahasa@gmail.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
declare (strict_types=1);
|
||||
namespace JooosiFon\Api\Migrations;
|
||||
|
||||
use JooosiFon\Api\AbstractApi;
|
||||
use JooosiFon\Api\ApiInterface;
|
||||
use JooosiFon\Api\Support\FontCodec;
|
||||
use JooosiFon\Api\Support\FontEvents;
|
||||
use JooosiFon\Api\Support\FontRepository;
|
||||
use JooosiFon\Api\Support\MediaImportService;
|
||||
use JooosiFon\Api\Support\RequestValidator;
|
||||
use JooosiFon\Utils\Common;
|
||||
use JooosiFon\Utils\Upload;
|
||||
use WP_REST_Request;
|
||||
use WP_REST_Response;
|
||||
use WP_REST_Server;
|
||||
class BricksCustomFonts extends AbstractApi implements ApiInterface
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
}
|
||||
public function get_prefix(): string
|
||||
{
|
||||
return 'migrations/bricks-custom-fonts';
|
||||
}
|
||||
public function register_custom_endpoints(): void
|
||||
{
|
||||
register_rest_route(self::API_NAMESPACE, $this->get_prefix() . '/import-fonts', ['methods' => WP_REST_Server::CREATABLE, 'callback' => fn(\WP_REST_Request $wprestRequest): \WP_REST_Response => $this->import_fonts($wprestRequest), 'permission_callback' => fn(\WP_REST_Request $wprestRequest): bool => $this->permission_callback($wprestRequest)]);
|
||||
register_rest_route(self::API_NAMESPACE, $this->get_prefix() . '/clean-up', ['methods' => WP_REST_Server::CREATABLE, 'callback' => fn(\WP_REST_Request $wprestRequest): \WP_REST_Response => $this->clean_up($wprestRequest), 'permission_callback' => fn(\WP_REST_Request $wprestRequest): bool => $this->permission_callback($wprestRequest), 'args' => ['confirm' => ['required' => \true, 'sanitize_callback' => 'rest_sanitize_boolean', 'validate_callback' => [RequestValidator::class, 'confirmed']]]]);
|
||||
}
|
||||
/**
|
||||
* @see Bricks\Custom_Fonts::get_custom_fonts()
|
||||
* @see JooosiFon\Api\Font::import()
|
||||
*/
|
||||
public function import_fonts(WP_REST_Request $wprestRequest): WP_REST_Response
|
||||
{
|
||||
if (!defined('BRICKS_DB_CUSTOM_FONTS') || !defined('BRICKS_DB_CUSTOM_FONT_FACES')) {
|
||||
return new WP_REST_Response(['message' => 'Bricks theme not activated'], 404);
|
||||
}
|
||||
$font_ids = get_posts(['post_type' => \BRICKS_DB_CUSTOM_FONTS, 'posts_per_page' => -1, 'fields' => 'ids', 'no_found_rows' => \true]);
|
||||
add_filter('wp_check_filetype_and_ext', static fn($data, $file, $filename, $mimes) => Upload::disable_real_mime_check($data, $file, $filename, $mimes), 10, 4);
|
||||
add_filter('upload_mimes', static fn($mime_types) => Upload::upload_mimes($mime_types, \true), 1000001);
|
||||
$repository = new FontRepository();
|
||||
$media = new MediaImportService();
|
||||
$insertedIds = [];
|
||||
$records = [];
|
||||
try {
|
||||
foreach ($font_ids as $font_id) {
|
||||
$migrationSlug = 'migration-bricks-' . absint($font_id);
|
||||
if ($repository->findBySlug($migrationSlug)) {
|
||||
continue;
|
||||
}
|
||||
$bricks_font_faces = get_post_meta($font_id, \BRICKS_DB_CUSTOM_FONT_FACES, \true);
|
||||
if ($bricks_font_faces === \false || empty($bricks_font_faces)) {
|
||||
continue;
|
||||
}
|
||||
$post = get_post($font_id);
|
||||
if (!$post) {
|
||||
throw new \RuntimeException('A Bricks font record could not be loaded.');
|
||||
}
|
||||
$font_faces = [];
|
||||
// $key: font-weight + variant (e.g.: 700italic)
|
||||
foreach ($bricks_font_faces as $key => $bricks_font_face) {
|
||||
$font_weight = filter_var($key, \FILTER_SANITIZE_NUMBER_INT);
|
||||
$font_style = str_replace($font_weight, '', $key);
|
||||
$font_face = ['id' => Common::random_slug(10), 'weight' => $font_weight, 'width' => '', 'style' => empty($font_style) ? 'normal' : $font_style, 'display' => '', 'selector' => '', 'comment' => '', 'unicodeRange' => '', 'preload' => \false, 'files' => []];
|
||||
foreach ($bricks_font_face as $key_format => $bricks_font_face_file) {
|
||||
$file_name = sanitize_title_with_dashes(sprintf('%s-%s-%s-%s-%s', $post->post_title, $font_weight, empty($font_style) ? 'normal' : $font_style, Common::random_slug(5), time())) . '.' . $key_format;
|
||||
$old_attachment_url = wp_get_attachment_url($bricks_font_face_file);
|
||||
if ($old_attachment_url === \false) {
|
||||
continue;
|
||||
}
|
||||
$font_face['files'][] = $media->remote($old_attachment_url, $file_name, $key_format);
|
||||
}
|
||||
$font_faces[] = $font_face;
|
||||
}
|
||||
$metadata = ['preload' => \false, 'selector' => '', 'display' => 'auto'];
|
||||
$records[] = ['type' => 'custom', 'title' => $post->post_title, 'slug' => $migrationSlug, 'family' => $post->post_title, 'status' => \true, 'metadata' => FontCodec::encode($metadata), 'font_faces' => FontCodec::encode($font_faces)];
|
||||
}
|
||||
$insertedIds = $repository->transaction(static function (FontRepository $repository) use ($records): array {
|
||||
$ids = [];
|
||||
foreach ($records as $record) {
|
||||
$ids[] = $repository->insert($record, ['%s', '%s', '%s', '%s', '%d', '%s', '%s']);
|
||||
}
|
||||
return $ids;
|
||||
});
|
||||
} catch (\Throwable $throwable) {
|
||||
$media->rollback();
|
||||
return new WP_REST_Response(['message' => __('The Bricks migration failed; newly created Jooosi Fon records were rolled back.', 'jooosi-fon')], 500);
|
||||
}
|
||||
$media->commit();
|
||||
FontEvents::dispatch('migration', ['source' => 'bricks-custom-fonts', 'ids' => $insertedIds], \true);
|
||||
return new WP_REST_Response(['message' => __('Bricks fonts imported. Source records were preserved.', 'jooosi-fon'), 'imported' => count($insertedIds), 'source_preserved' => \true]);
|
||||
}
|
||||
public function clean_up(WP_REST_Request $wprestRequest): WP_REST_Response
|
||||
{
|
||||
if (!defined('BRICKS_DB_CUSTOM_FONTS')) {
|
||||
return new WP_REST_Response(['message' => 'Bricks theme not activated'], 404);
|
||||
}
|
||||
$font_ids = get_posts(['post_type' => \BRICKS_DB_CUSTOM_FONTS, 'posts_per_page' => -1, 'fields' => 'ids', 'no_found_rows' => \true]);
|
||||
$trashedIds = [];
|
||||
foreach ($font_ids as $font_id) {
|
||||
if (!wp_trash_post($font_id)) {
|
||||
foreach ($trashedIds as $trashedId) {
|
||||
wp_untrash_post($trashedId);
|
||||
}
|
||||
return new WP_REST_Response(['message' => __('Bricks source cleanup failed and previously trashed records were restored.', 'jooosi-fon')], 500);
|
||||
}
|
||||
$trashedIds[] = $font_id;
|
||||
}
|
||||
FontEvents::dispatch('clean_up', ['source' => 'bricks-custom-fonts', 'ids' => $trashedIds], \true);
|
||||
return new WP_REST_Response(['message' => __('Bricks source records moved to the trash.', 'jooosi-fon'), 'cleaned' => count($trashedIds)]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
<?php
|
||||
|
||||
declare (strict_types=1);
|
||||
namespace JooosiFon\Api\Migrations;
|
||||
|
||||
use JooosiFonDeps\JOOOSI_FON;
|
||||
use JooosiFon\Api\AbstractApi;
|
||||
use JooosiFon\Api\ApiInterface;
|
||||
use JooosiFon\Api\Migrations\Support\SourceFontNormalizer;
|
||||
use JooosiFon\Api\Support\FontCodec;
|
||||
use JooosiFon\Api\Support\FontEvents;
|
||||
use JooosiFon\Api\Support\FontRepository;
|
||||
use JooosiFon\Api\Support\RequestValidator;
|
||||
use WP_REST_Request;
|
||||
use WP_REST_Response;
|
||||
use WP_REST_Server;
|
||||
final class CustomAdobeFonts extends AbstractApi implements ApiInterface
|
||||
{
|
||||
private const SOURCE_OPTION = 'custom-typekit-fonts';
|
||||
public function get_prefix(): string
|
||||
{
|
||||
return 'migrations/custom-adobe-fonts';
|
||||
}
|
||||
public function register_custom_endpoints(): void
|
||||
{
|
||||
register_rest_route(self::API_NAMESPACE, $this->get_prefix() . '/import-fonts', ['methods' => WP_REST_Server::CREATABLE, 'callback' => fn(WP_REST_Request $request): WP_REST_Response => $this->import_fonts($request), 'permission_callback' => fn(WP_REST_Request $request): bool => $this->permission_callback($request)]);
|
||||
register_rest_route(self::API_NAMESPACE, $this->get_prefix() . '/clean-up', ['methods' => WP_REST_Server::CREATABLE, 'callback' => fn(WP_REST_Request $request): WP_REST_Response => $this->clean_up($request), 'permission_callback' => fn(WP_REST_Request $request): bool => $this->permission_callback($request), 'args' => ['confirm' => ['required' => \true, 'sanitize_callback' => 'rest_sanitize_boolean', 'validate_callback' => [RequestValidator::class, 'confirmed']]]]);
|
||||
}
|
||||
public function import_fonts(WP_REST_Request $request): WP_REST_Response
|
||||
{
|
||||
if (!defined('CUSTOM_TYPEKIT_FONTS_VER')) {
|
||||
return new WP_REST_Response(['message' => __('Custom Adobe Fonts is not activated.', 'jooosi-fon')], 404);
|
||||
}
|
||||
$source = get_option(self::SOURCE_OPTION, null);
|
||||
if (!is_array($source)) {
|
||||
return new WP_REST_Response(['message' => __('Custom Adobe Fonts records could not be read.', 'jooosi-fon')], 500);
|
||||
}
|
||||
$kit = SourceFontNormalizer::customAdobeKit($source);
|
||||
if (!RequestValidator::projectId($kit['id']) || !RequestValidator::adobeKit($kit) || $kit['families'] === []) {
|
||||
return new WP_REST_Response(['message' => __('The Custom Adobe Fonts project has no usable published families.', 'jooosi-fon')], 422);
|
||||
}
|
||||
$options = $this->jooosi_options();
|
||||
if ($options === null) {
|
||||
return new WP_REST_Response(['message' => __('Jooosi Fon settings are invalid, so the Adobe project was not changed.', 'jooosi-fon')], 500);
|
||||
}
|
||||
$adobeOptions = isset($options['adobe_fonts']) && is_array($options['adobe_fonts']) ? $options['adobe_fonts'] : [];
|
||||
$currentProjectId = trim((string) ($adobeOptions['project_id'] ?? ''));
|
||||
if ($currentProjectId !== '' && $currentProjectId !== $kit['id']) {
|
||||
return new WP_REST_Response(['message' => __('Jooosi Fon is already connected to a different Adobe Fonts project. Disconnect it before migrating this source.', 'jooosi-fon')], 409);
|
||||
}
|
||||
$options['adobe_fonts'] = ['project_id' => $kit['id'], 'kit' => $kit];
|
||||
$repository = new FontRepository();
|
||||
$insertedIds = [];
|
||||
try {
|
||||
$insertedIds = $repository->transaction(function (FontRepository $repository) use ($kit, $options): array {
|
||||
$repository->deleteByType('adobe-fonts');
|
||||
$ids = [];
|
||||
foreach ($kit['families'] as $family) {
|
||||
$ids[] = $repository->insert(['status' => 1, 'type' => 'adobe-fonts', 'title' => sanitize_text_field($family['name']), 'slug' => sanitize_key($family['id']), 'family' => sanitize_text_field($family['slug']), 'metadata' => FontCodec::encode($family), 'font_faces' => FontCodec::encode([])], ['%d', '%s', '%s', '%s', '%s', '%s', '%s']);
|
||||
}
|
||||
$this->store_jooosi_options($options);
|
||||
return $ids;
|
||||
});
|
||||
} catch (\Throwable $throwable) {
|
||||
wp_cache_delete(JOOOSI_FON::WP_OPTION . '_options', 'options');
|
||||
return new WP_REST_Response(['message' => __('The Custom Adobe Fonts migration failed; the previous Adobe project and families were preserved.', 'jooosi-fon')], 500);
|
||||
}
|
||||
FontEvents::dispatch('migration', ['source' => 'custom-adobe-fonts', 'ids' => $insertedIds], \true);
|
||||
return new WP_REST_Response(['message' => __('Custom Adobe Fonts project and families imported. Source settings were preserved.', 'jooosi-fon'), 'imported' => count($insertedIds), 'source_preserved' => \true]);
|
||||
}
|
||||
public function clean_up(WP_REST_Request $request): WP_REST_Response
|
||||
{
|
||||
if (!defined('CUSTOM_TYPEKIT_FONTS_VER')) {
|
||||
return new WP_REST_Response(['message' => __('Custom Adobe Fonts is not activated.', 'jooosi-fon')], 404);
|
||||
}
|
||||
$source = get_option(self::SOURCE_OPTION, null);
|
||||
if ($source !== null && !delete_option(self::SOURCE_OPTION)) {
|
||||
return new WP_REST_Response(['message' => __('Custom Adobe Fonts cleanup failed and its source settings were preserved.', 'jooosi-fon')], 500);
|
||||
}
|
||||
FontEvents::dispatch('clean_up', ['source' => 'custom-adobe-fonts'], \true);
|
||||
return new WP_REST_Response(['message' => __('Custom Adobe Fonts source settings were removed. The migrated Jooosi Fon Adobe project remains connected.', 'jooosi-fon'), 'cleaned' => is_array($source) ? 1 : 0]);
|
||||
}
|
||||
/**
|
||||
* @return array<string, mixed>|null
|
||||
*/
|
||||
private function jooosi_options(): ?array
|
||||
{
|
||||
$stored = get_option(JOOOSI_FON::WP_OPTION . '_options', '{}');
|
||||
if (!is_string($stored)) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
$options = json_decode($stored, \true, 512, \JSON_THROW_ON_ERROR);
|
||||
} catch (\JsonException $exception) {
|
||||
return null;
|
||||
}
|
||||
return is_array($options) ? $options : null;
|
||||
}
|
||||
/**
|
||||
* @param array<string, mixed> $options
|
||||
*/
|
||||
private function store_jooosi_options(array $options): void
|
||||
{
|
||||
$encoded = json_encode($options, \JSON_THROW_ON_ERROR);
|
||||
$option = JOOOSI_FON::WP_OPTION . '_options';
|
||||
if (!update_option($option, $encoded) && get_option($option) !== $encoded) {
|
||||
throw new \RuntimeException('The Jooosi Fon Adobe settings could not be stored.');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Jooosi Fon package.
|
||||
*
|
||||
* (c) Joshua Gugun Siagian <suabahasa@gmail.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
declare (strict_types=1);
|
||||
namespace JooosiFon\Api\Migrations;
|
||||
|
||||
use JooosiFon\Api\AbstractApi;
|
||||
use JooosiFon\Api\ApiInterface;
|
||||
use JooosiFon\Api\Support\FontCodec;
|
||||
use JooosiFon\Api\Support\FontEvents;
|
||||
use JooosiFon\Api\Support\FontRepository;
|
||||
use JooosiFon\Api\Support\MediaImportService;
|
||||
use JooosiFon\Api\Support\RequestValidator;
|
||||
use JooosiFon\Utils\Common;
|
||||
use JooosiFon\Utils\Upload;
|
||||
use WP_REST_Request;
|
||||
use WP_REST_Response;
|
||||
use WP_REST_Server;
|
||||
use wpdb;
|
||||
class DpluginsFontHero extends AbstractApi implements ApiInterface
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
}
|
||||
public function get_prefix(): string
|
||||
{
|
||||
return 'migrations/font-hero-dplugins';
|
||||
}
|
||||
public function register_custom_endpoints(): void
|
||||
{
|
||||
register_rest_route(self::API_NAMESPACE, $this->get_prefix() . '/import-fonts', ['methods' => WP_REST_Server::CREATABLE, 'callback' => fn(\WP_REST_Request $wprestRequest): \WP_REST_Response => $this->import_fonts($wprestRequest), 'permission_callback' => fn(\WP_REST_Request $wprestRequest): bool => $this->permission_callback($wprestRequest)]);
|
||||
register_rest_route(self::API_NAMESPACE, $this->get_prefix() . '/clean-up', ['methods' => WP_REST_Server::CREATABLE, 'callback' => fn(\WP_REST_Request $wprestRequest): \WP_REST_Response => $this->clean_up($wprestRequest), 'permission_callback' => fn(\WP_REST_Request $wprestRequest): bool => $this->permission_callback($wprestRequest), 'args' => ['confirm' => ['required' => \true, 'sanitize_callback' => 'rest_sanitize_boolean', 'validate_callback' => [RequestValidator::class, 'confirmed']]]]);
|
||||
}
|
||||
/**
|
||||
* @see JooosiFon\Api\Font::import()
|
||||
*/
|
||||
public function import_fonts(WP_REST_Request $wprestRequest): WP_REST_Response
|
||||
{
|
||||
if (!defined('DP_FH_BASE')) {
|
||||
return new WP_REST_Response(['message' => 'Font Hero plugin is not activated'], 404);
|
||||
}
|
||||
/** @var wpdb $wpdb */
|
||||
global $wpdb;
|
||||
add_filter('wp_check_filetype_and_ext', static fn($data, $file, $filename, $mimes) => Upload::disable_real_mime_check($data, $file, $filename, $mimes), 10, 4);
|
||||
add_filter('upload_mimes', static fn($mime_types) => Upload::upload_mimes($mime_types, \true), 1000001);
|
||||
$dpfh_fonts = $wpdb->get_results(sprintf('SELECT * FROM %sdp_fh_fonts', $wpdb->prefix));
|
||||
if ($wpdb->last_error) {
|
||||
return new WP_REST_Response(['message' => __('Font Hero records could not be read.', 'jooosi-fon')], 500);
|
||||
}
|
||||
$repository = new FontRepository();
|
||||
$media = new MediaImportService();
|
||||
$insertedIds = [];
|
||||
$records = [];
|
||||
try {
|
||||
foreach ($dpfh_fonts as $dpfh_font) {
|
||||
$migrationSlug = 'migration-font-hero-' . absint($dpfh_font->id);
|
||||
if ($repository->findBySlug($migrationSlug)) {
|
||||
continue;
|
||||
}
|
||||
$font_faces = [];
|
||||
$dpfh_font_faces = $wpdb->get_results($wpdb->prepare(sprintf('SELECT * FROM %sdp_fh_font_faces WHERE font_id = %%d', $wpdb->prefix), $dpfh_font->id));
|
||||
if ($wpdb->last_error) {
|
||||
throw new \RuntimeException('Font Hero font faces could not be read.');
|
||||
}
|
||||
foreach ($dpfh_font_faces as $dpfh_font_face) {
|
||||
$f_weight = filter_var($dpfh_font_face->font_weight, \FILTER_SANITIZE_NUMBER_INT) ?: 100;
|
||||
$f_style = empty($dpfh_font_face->font_style) ? 'normal' : sanitize_text_field($dpfh_font_face->font_style);
|
||||
$font_face = array_filter($font_faces, static fn($ff) => $ff['weight'] === $f_weight && $ff['style'] === $f_style);
|
||||
if ($font_face !== []) {
|
||||
$font_face = array_shift($font_face);
|
||||
$font_faces = array_filter($font_faces, static fn($ff) => $ff['id'] !== $font_face['id']);
|
||||
} else {
|
||||
$font_face = ['id' => Common::random_slug(10), 'weight' => $f_weight, 'width' => '', 'style' => $f_style, 'display' => empty($dpfh_font_face->font_display) ? '' : sanitize_text_field($dpfh_font_face->font_display), 'selector' => '', 'comment' => '', 'unicodeRange' => '', 'preload' => $dpfh_font_face->font_preload === 'yes', 'files' => []];
|
||||
}
|
||||
if (!empty($dpfh_font_face->font_file)) {
|
||||
$f_ext = pathinfo((string) wp_parse_url($dpfh_font_face->font_file, \PHP_URL_PATH), \PATHINFO_EXTENSION);
|
||||
$file_name = sanitize_title_with_dashes(sprintf('%s-%s-%s-%s-%s', sanitize_text_field($dpfh_font->font_name), $f_weight, $f_style, Common::random_slug(5), time())) . '.' . $f_ext;
|
||||
$font_face['files'][] = $media->remote($dpfh_font_face->font_file, $file_name, $f_ext);
|
||||
}
|
||||
if (!empty($dpfh_font_face->font_file_2)) {
|
||||
$f_ext = pathinfo((string) wp_parse_url($dpfh_font_face->font_file_2, \PHP_URL_PATH), \PATHINFO_EXTENSION);
|
||||
$file_name = sanitize_title_with_dashes(sprintf('%s-%s-%s-%s-%s', sanitize_text_field($dpfh_font->font_name), $f_weight, $f_style, Common::random_slug(5), time())) . '.' . $f_ext;
|
||||
$font_face['files'][] = $media->remote($dpfh_font_face->font_file_2, $file_name, $f_ext);
|
||||
}
|
||||
if (!empty($dpfh_font_face->font_file_3)) {
|
||||
$f_ext = pathinfo((string) wp_parse_url($dpfh_font_face->font_file_3, \PHP_URL_PATH), \PATHINFO_EXTENSION);
|
||||
$file_name = sanitize_title_with_dashes(sprintf('%s-%s-%s-%s-%s', sanitize_text_field($dpfh_font->font_name), $f_weight, $f_style, Common::random_slug(5), time())) . '.' . $f_ext;
|
||||
$font_face['files'][] = $media->remote($dpfh_font_face->font_file_3, $file_name, $f_ext);
|
||||
}
|
||||
$font_faces[] = $font_face;
|
||||
}
|
||||
$metadata = ['preload' => \false, 'selector' => '', 'display' => 'auto'];
|
||||
$records[] = ['type' => 'custom', 'title' => sanitize_text_field($dpfh_font->font_name), 'slug' => $migrationSlug, 'family' => sanitize_text_field($dpfh_font->font_name), 'status' => \true, 'metadata' => FontCodec::encode($metadata), 'font_faces' => FontCodec::encode($font_faces)];
|
||||
}
|
||||
$insertedIds = $repository->transaction(static function (FontRepository $repository) use ($records): array {
|
||||
$ids = [];
|
||||
foreach ($records as $record) {
|
||||
$ids[] = $repository->insert($record, ['%s', '%s', '%s', '%s', '%d', '%s', '%s']);
|
||||
}
|
||||
return $ids;
|
||||
});
|
||||
} catch (\Throwable $throwable) {
|
||||
$media->rollback();
|
||||
return new WP_REST_Response(['message' => __('The Font Hero migration failed; newly created Jooosi Fon records were rolled back.', 'jooosi-fon')], 500);
|
||||
}
|
||||
$media->commit();
|
||||
FontEvents::dispatch('migration', ['source' => 'font-hero-dplugins', 'ids' => $insertedIds], \true);
|
||||
return new WP_REST_Response(['message' => __('Font Hero fonts imported. Source records were preserved.', 'jooosi-fon'), 'imported' => count($insertedIds), 'source_preserved' => \true]);
|
||||
}
|
||||
public function clean_up(WP_REST_Request $wprestRequest): WP_REST_Response
|
||||
{
|
||||
if (!defined('DP_FH_BASE')) {
|
||||
return new WP_REST_Response(['message' => 'Font Hero plugin is not activated'], 404);
|
||||
}
|
||||
/** @var wpdb $wpdb */
|
||||
global $wpdb;
|
||||
if ($wpdb->query('START TRANSACTION') === \false) {
|
||||
return new WP_REST_Response(['message' => __('Font Hero cleanup could not start a database transaction.', 'jooosi-fon')], 500);
|
||||
}
|
||||
try {
|
||||
if ($wpdb->query(sprintf('DELETE FROM %sdp_fh_font_faces', $wpdb->prefix)) === \false || $wpdb->query(sprintf('DELETE FROM %sdp_fh_fonts', $wpdb->prefix)) === \false || $wpdb->query('COMMIT') === \false) {
|
||||
throw new \RuntimeException($wpdb->last_error ?: 'Font Hero cleanup failed.');
|
||||
}
|
||||
} catch (\Throwable $throwable) {
|
||||
$wpdb->query('ROLLBACK');
|
||||
return new WP_REST_Response(['message' => __('Font Hero cleanup failed; the source transaction was rolled back.', 'jooosi-fon')], 500);
|
||||
}
|
||||
FontEvents::dispatch('clean_up', ['source' => 'font-hero-dplugins'], \true);
|
||||
return new WP_REST_Response(['message' => __('Font Hero source records deleted.', 'jooosi-fon')]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
<?php
|
||||
|
||||
declare (strict_types=1);
|
||||
namespace JooosiFon\Api\Migrations;
|
||||
|
||||
use JooosiFon\Api\AbstractApi;
|
||||
use JooosiFon\Api\ApiInterface;
|
||||
use JooosiFon\Api\Migrations\Support\SourceFontNormalizer;
|
||||
use JooosiFon\Api\Support\FontCodec;
|
||||
use JooosiFon\Api\Support\FontEvents;
|
||||
use JooosiFon\Api\Support\FontRepository;
|
||||
use JooosiFon\Api\Support\MediaImportService;
|
||||
use JooosiFon\Api\Support\RequestValidator;
|
||||
use JooosiFon\Utils\Common;
|
||||
use JooosiFon\Utils\Upload;
|
||||
use WP_REST_Request;
|
||||
use WP_REST_Response;
|
||||
use WP_REST_Server;
|
||||
final class ElementorProCustomFonts extends AbstractApi implements ApiInterface
|
||||
{
|
||||
private const LEGACY_POST_TYPE = 'elementor_font';
|
||||
private const FONT_FACE_POST_TYPE = 'elementor_font_face';
|
||||
private const LEGACY_META_KEY = 'elementor_font_files';
|
||||
public function get_prefix(): string
|
||||
{
|
||||
return 'migrations/elementor-pro-custom-fonts';
|
||||
}
|
||||
public function register_custom_endpoints(): void
|
||||
{
|
||||
register_rest_route(self::API_NAMESPACE, $this->get_prefix() . '/import-fonts', ['methods' => WP_REST_Server::CREATABLE, 'callback' => fn(WP_REST_Request $request): WP_REST_Response => $this->import_fonts($request), 'permission_callback' => fn(WP_REST_Request $request): bool => $this->permission_callback($request)]);
|
||||
register_rest_route(self::API_NAMESPACE, $this->get_prefix() . '/clean-up', ['methods' => WP_REST_Server::CREATABLE, 'callback' => fn(WP_REST_Request $request): WP_REST_Response => $this->clean_up($request), 'permission_callback' => fn(WP_REST_Request $request): bool => $this->permission_callback($request), 'args' => ['confirm' => ['required' => \true, 'sanitize_callback' => 'rest_sanitize_boolean', 'validate_callback' => [RequestValidator::class, 'confirmed']]]]);
|
||||
}
|
||||
public function import_fonts(WP_REST_Request $request): WP_REST_Response
|
||||
{
|
||||
if (!$this->is_active()) {
|
||||
return new WP_REST_Response(['message' => __('Elementor Pro Custom Fonts is not activated.', 'jooosi-fon')], 404);
|
||||
}
|
||||
$sourceRecords = $this->source_records();
|
||||
add_filter('wp_check_filetype_and_ext', static fn($data, $file, $filename, $mimes) => Upload::disable_real_mime_check($data, $file, $filename, $mimes), 10, 4);
|
||||
add_filter('upload_mimes', static fn($mimeTypes) => Upload::upload_mimes($mimeTypes, \true), 1000001);
|
||||
$repository = new FontRepository();
|
||||
$media = new MediaImportService();
|
||||
$records = [];
|
||||
$insertedIds = [];
|
||||
$skipped = 0;
|
||||
try {
|
||||
foreach ($sourceRecords as $sourceRecord) {
|
||||
$family = sanitize_text_field((string) $sourceRecord['title']);
|
||||
$fontId = (int) $sourceRecord['id'];
|
||||
$postType = (string) $sourceRecord['post_type'];
|
||||
if ($family === '' || $fontId < 1) {
|
||||
++$skipped;
|
||||
continue;
|
||||
}
|
||||
$display = (string) apply_filters('elementor_pro/custom_fonts/font_display', 'auto', $family, $sourceRecord['variants']);
|
||||
$normalized = SourceFontNormalizer::elementor($sourceRecord['variants'], $display);
|
||||
$skipped += $normalized['skipped'];
|
||||
if ($normalized['faces'] === []) {
|
||||
if ($normalized['skipped'] === 0) {
|
||||
++$skipped;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
$migrationSlug = sprintf('migration-elementor-pro-%s-%d', $postType === self::FONT_FACE_POST_TYPE ? 'font-face' : 'font', $fontId);
|
||||
if ($repository->findBySlug($migrationSlug)) {
|
||||
continue;
|
||||
}
|
||||
$fontFaces = [];
|
||||
foreach ($normalized['faces'] as $sourceFace) {
|
||||
$files = [];
|
||||
foreach ($sourceFace['files'] as $sourceFile) {
|
||||
$fileName = sanitize_title_with_dashes(sprintf('%s-%s-%s-%s-%s', $family, $sourceFace['weight'], $sourceFace['style'], Common::random_slug(5), time())) . '.' . $sourceFile['extension'];
|
||||
$files[] = $this->import_file($media, $sourceFile, $fileName);
|
||||
}
|
||||
if ($files === []) {
|
||||
++$skipped;
|
||||
continue;
|
||||
}
|
||||
$fontFaces[] = ['id' => Common::random_slug(10), 'weight' => $sourceFace['weight'], 'width' => $sourceFace['width'], 'style' => $sourceFace['style'], 'display' => '', 'selector' => '', 'comment' => '', 'unicodeRange' => '', 'preload' => (bool) $sourceFace['preload'], 'files' => $files];
|
||||
}
|
||||
$records[] = ['type' => 'custom', 'title' => $family, 'slug' => $migrationSlug, 'family' => $family, 'status' => \true, 'metadata' => FontCodec::encode(['preload' => \false, 'selector' => '', 'display' => $normalized['display']]), 'font_faces' => FontCodec::encode($fontFaces)];
|
||||
}
|
||||
if ($skipped > 0) {
|
||||
$media->rollback();
|
||||
return new WP_REST_Response(['message' => __('Some Elementor Pro font variants had no supported files. Nothing was imported so the source records remain safe.', 'jooosi-fon'), 'skipped' => $skipped], 422);
|
||||
}
|
||||
$insertedIds = $repository->transaction(static function (FontRepository $repository) use ($records): array {
|
||||
$ids = [];
|
||||
foreach ($records as $record) {
|
||||
$ids[] = $repository->insert($record, ['%s', '%s', '%s', '%s', '%d', '%s', '%s']);
|
||||
}
|
||||
return $ids;
|
||||
});
|
||||
} catch (\Throwable $throwable) {
|
||||
$media->rollback();
|
||||
return new WP_REST_Response(['message' => __('The Elementor Pro Custom Fonts migration failed; newly created Jooosi Fon records were rolled back.', 'jooosi-fon')], 500);
|
||||
}
|
||||
$media->commit();
|
||||
FontEvents::dispatch('migration', ['source' => 'elementor-pro-custom-fonts', 'ids' => $insertedIds], \true);
|
||||
return new WP_REST_Response(['message' => __('Elementor Pro custom font families imported. Source records were preserved.', 'jooosi-fon'), 'imported' => count($insertedIds), 'skipped' => $skipped, 'source_preserved' => \true]);
|
||||
}
|
||||
public function clean_up(WP_REST_Request $request): WP_REST_Response
|
||||
{
|
||||
if (!$this->is_active()) {
|
||||
return new WP_REST_Response(['message' => __('Elementor Pro Custom Fonts is not activated.', 'jooosi-fon')], 404);
|
||||
}
|
||||
$fontIds = array_values(array_unique(array_map(static fn(array $sourceRecord): int => (int) $sourceRecord['id'], $this->source_records())));
|
||||
$trashedIds = [];
|
||||
foreach ($fontIds as $fontId) {
|
||||
if ($fontId < 1 || !wp_trash_post($fontId)) {
|
||||
foreach ($trashedIds as $trashedId) {
|
||||
wp_untrash_post($trashedId);
|
||||
}
|
||||
return new WP_REST_Response(['message' => __('Elementor Pro source cleanup failed and previously trashed records were restored.', 'jooosi-fon')], 500);
|
||||
}
|
||||
$trashedIds[] = $fontId;
|
||||
}
|
||||
FontEvents::dispatch('clean_up', ['source' => 'elementor-pro-custom-fonts', 'ids' => $trashedIds], \true);
|
||||
return new WP_REST_Response(['message' => __('Elementor Pro custom-font records moved to the trash. Original media files were left in place.', 'jooosi-fon'), 'cleaned' => count($trashedIds)]);
|
||||
}
|
||||
private function is_active(): bool
|
||||
{
|
||||
return defined('ELEMENTOR_PRO_VERSION') && (post_type_exists(self::LEGACY_POST_TYPE) || post_type_exists(self::FONT_FACE_POST_TYPE));
|
||||
}
|
||||
/**
|
||||
* @return array<int, array{id: int, post_type: string, title: string, variants: array<int, mixed>}>
|
||||
*/
|
||||
private function source_records(): array
|
||||
{
|
||||
$records = [];
|
||||
foreach ([self::LEGACY_POST_TYPE, self::FONT_FACE_POST_TYPE] as $postType) {
|
||||
if (!post_type_exists($postType)) {
|
||||
continue;
|
||||
}
|
||||
$fontIds = get_posts(['post_type' => $postType, 'post_status' => 'publish', 'posts_per_page' => -1, 'fields' => 'ids', 'no_found_rows' => \true]);
|
||||
foreach ($fontIds as $fontId) {
|
||||
$fontId = absint($fontId);
|
||||
$post = get_post($fontId);
|
||||
if ($fontId < 1 || !$post) {
|
||||
continue;
|
||||
}
|
||||
$variants = $postType === self::LEGACY_POST_TYPE ? get_post_meta($fontId, self::LEGACY_META_KEY, \true) : get_post_meta($fontId, 'font_face', \true);
|
||||
if (!is_array($variants) || $variants === []) {
|
||||
$variant = $this->font_face_variant($fontId);
|
||||
$variants = $variant === [] ? [] : [$variant];
|
||||
} elseif (isset($variants['font_weight']) || isset($variants['weight']) || array_intersect(['woff2', 'woff', 'ttf', 'otf', 'eot'], array_keys($variants)) !== []) {
|
||||
$variants = [$variants];
|
||||
}
|
||||
$records[] = ['id' => $fontId, 'post_type' => $postType, 'title' => (string) $post->post_title, 'variants' => array_values($variants)];
|
||||
}
|
||||
}
|
||||
return $records;
|
||||
}
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function font_face_variant(int $fontId): array
|
||||
{
|
||||
$variant = ['font_weight' => $this->first_meta($fontId, ['font_face_weight', 'font_weight', 'weight'], '400'), 'font_style' => $this->first_meta($fontId, ['font_face_style', 'font_style', 'style'], 'normal'), 'font_stretch' => $this->first_meta($fontId, ['font_face_stretch', 'font_stretch', 'stretch'], 'normal')];
|
||||
$hasFile = \false;
|
||||
foreach (['woff2', 'woff', 'ttf', 'otf', 'eot'] as $extension) {
|
||||
$source = $this->first_meta($fontId, ['font_face_file_' . $extension, 'font_file_' . $extension, $extension], null);
|
||||
if (is_numeric($source) && (int) $source > 0) {
|
||||
$source = ['id' => (int) $source, 'url' => wp_get_attachment_url((int) $source) ?: ''];
|
||||
} elseif (is_array($source) && empty($source['url']) && !empty($source['id'])) {
|
||||
$source['url'] = wp_get_attachment_url((int) $source['id']) ?: '';
|
||||
}
|
||||
if (is_string($source) && $source !== '' || is_array($source) && !empty($source['url'])) {
|
||||
$variant[$extension] = $source;
|
||||
$hasFile = \true;
|
||||
}
|
||||
}
|
||||
return $hasFile ? $variant : [];
|
||||
}
|
||||
/**
|
||||
* @param string[] $keys
|
||||
* @return mixed
|
||||
*/
|
||||
private function first_meta(int $fontId, array $keys, $default)
|
||||
{
|
||||
foreach ($keys as $key) {
|
||||
$value = get_post_meta($fontId, $key, \true);
|
||||
if ($value !== '' && $value !== null && $value !== \false) {
|
||||
return $value;
|
||||
}
|
||||
}
|
||||
return $default;
|
||||
}
|
||||
/**
|
||||
* @param array<string, mixed> $sourceFile
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function import_file(MediaImportService $media, array $sourceFile, string $fileName): array
|
||||
{
|
||||
$location = (string) ($sourceFile['location'] ?? '');
|
||||
$extension = (string) ($sourceFile['extension'] ?? '');
|
||||
$attachmentId = (int) ($sourceFile['attachment_id'] ?? attachment_url_to_postid($location));
|
||||
$path = $attachmentId > 0 ? get_attached_file($attachmentId) : \false;
|
||||
if (is_string($path) && is_readable($path)) {
|
||||
return $media->local($path, $fileName, $extension);
|
||||
}
|
||||
return $media->remote($location, $fileName, $extension);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
<?php
|
||||
|
||||
declare (strict_types=1);
|
||||
namespace JooosiFon\Api\Migrations;
|
||||
|
||||
use JooosiFon\Api\AbstractApi;
|
||||
use JooosiFon\Api\ApiInterface;
|
||||
use JooosiFon\Api\Migrations\Support\SourceFontNormalizer;
|
||||
use JooosiFon\Api\Support\FontCodec;
|
||||
use JooosiFon\Api\Support\FontEvents;
|
||||
use JooosiFon\Api\Support\FontRepository;
|
||||
use JooosiFon\Api\Support\MediaImportService;
|
||||
use JooosiFon\Api\Support\RequestValidator;
|
||||
use JooosiFon\Utils\Common;
|
||||
use JooosiFon\Utils\Upload;
|
||||
use WP_REST_Request;
|
||||
use WP_REST_Response;
|
||||
use WP_REST_Server;
|
||||
final class FontsPlugin extends AbstractApi implements ApiInterface
|
||||
{
|
||||
private const TAXONOMY = 'ogf_custom_fonts';
|
||||
public function get_prefix(): string
|
||||
{
|
||||
return 'migrations/fonts-plugin';
|
||||
}
|
||||
public function register_custom_endpoints(): void
|
||||
{
|
||||
register_rest_route(self::API_NAMESPACE, $this->get_prefix() . '/import-fonts', ['methods' => WP_REST_Server::CREATABLE, 'callback' => fn(WP_REST_Request $request): WP_REST_Response => $this->import_fonts($request), 'permission_callback' => fn(WP_REST_Request $request): bool => $this->permission_callback($request)]);
|
||||
register_rest_route(self::API_NAMESPACE, $this->get_prefix() . '/clean-up', ['methods' => WP_REST_Server::CREATABLE, 'callback' => fn(WP_REST_Request $request): WP_REST_Response => $this->clean_up($request), 'permission_callback' => fn(WP_REST_Request $request): bool => $this->permission_callback($request), 'args' => ['confirm' => ['required' => \true, 'sanitize_callback' => 'rest_sanitize_boolean', 'validate_callback' => [RequestValidator::class, 'confirmed']]]]);
|
||||
}
|
||||
public function import_fonts(WP_REST_Request $request): WP_REST_Response
|
||||
{
|
||||
if (!$this->is_active()) {
|
||||
return new WP_REST_Response(['message' => __('Fonts Plugin is not activated.', 'jooosi-fon')], 404);
|
||||
}
|
||||
$terms = $this->source_terms();
|
||||
if (is_wp_error($terms)) {
|
||||
return new WP_REST_Response(['message' => __('Fonts Plugin records could not be read.', 'jooosi-fon')], 500);
|
||||
}
|
||||
$rows = [];
|
||||
foreach ($terms as $term) {
|
||||
$data = get_option($this->term_option_name((int) $term->term_id), []);
|
||||
if (!is_array($data)) {
|
||||
continue;
|
||||
}
|
||||
$rows[] = array_merge($data, ['source_key' => (string) $term->slug, 'name' => (string) $term->name]);
|
||||
}
|
||||
$families = SourceFontNormalizer::fontsPlugin($rows, $this->selector_assignments(), (string) get_theme_mod('ogf_font_display', 'swap'));
|
||||
$normalizedFaceCount = array_sum(array_map(static fn(array $family): int => count($family['faces']), $families));
|
||||
$skipped = max(0, count($terms) - $normalizedFaceCount);
|
||||
add_filter('wp_check_filetype_and_ext', static fn($data, $file, $filename, $mimes) => Upload::disable_real_mime_check($data, $file, $filename, $mimes), 10, 4);
|
||||
add_filter('upload_mimes', static fn($mimeTypes) => Upload::upload_mimes($mimeTypes, \true), 1000001);
|
||||
$repository = new FontRepository();
|
||||
$media = new MediaImportService();
|
||||
$records = [];
|
||||
$insertedIds = [];
|
||||
try {
|
||||
foreach ($families as $sourceFamily) {
|
||||
$family = sanitize_text_field((string) $sourceFamily['family']);
|
||||
$familySlug = sanitize_title_with_dashes($family);
|
||||
if ($family === '' || $familySlug === '') {
|
||||
++$skipped;
|
||||
continue;
|
||||
}
|
||||
$migrationSlug = 'migration-fonts-plugin-' . $familySlug;
|
||||
if ($repository->findBySlug($migrationSlug)) {
|
||||
continue;
|
||||
}
|
||||
$fontFaces = [];
|
||||
foreach ($sourceFamily['faces'] as $sourceFace) {
|
||||
$files = [];
|
||||
foreach ($sourceFace['files'] as $sourceFile) {
|
||||
$fileName = sanitize_title_with_dashes(sprintf('%s-%s-%s-%s-%s', $family, $sourceFace['weight'], $sourceFace['style'], Common::random_slug(5), time())) . '.' . $sourceFile['extension'];
|
||||
$files[] = $this->import_file($media, $sourceFile, $fileName);
|
||||
}
|
||||
if ($files === []) {
|
||||
++$skipped;
|
||||
continue;
|
||||
}
|
||||
$fontFaces[] = ['id' => Common::random_slug(10), 'weight' => $sourceFace['weight'], 'width' => $sourceFace['width'], 'style' => $sourceFace['style'], 'display' => '', 'selector' => '', 'comment' => '', 'unicodeRange' => '', 'preload' => (bool) $sourceFace['preload'], 'files' => $files];
|
||||
}
|
||||
if ($fontFaces === []) {
|
||||
++$skipped;
|
||||
continue;
|
||||
}
|
||||
$records[] = ['type' => 'custom', 'title' => $family, 'slug' => $migrationSlug, 'family' => $family, 'status' => \true, 'metadata' => FontCodec::encode(['preload' => (bool) $sourceFamily['preload'], 'selector' => $sourceFamily['selector'], 'display' => $sourceFamily['display']]), 'font_faces' => FontCodec::encode($fontFaces)];
|
||||
}
|
||||
if ($skipped > 0) {
|
||||
$media->rollback();
|
||||
return new WP_REST_Response(['message' => __('Some Fonts Plugin variants had no supported font files. Nothing was imported so the source records remain safe.', 'jooosi-fon'), 'skipped' => $skipped], 422);
|
||||
}
|
||||
$insertedIds = $repository->transaction(static function (FontRepository $repository) use ($records): array {
|
||||
$ids = [];
|
||||
foreach ($records as $record) {
|
||||
$ids[] = $repository->insert($record, ['%s', '%s', '%s', '%s', '%d', '%s', '%s']);
|
||||
}
|
||||
return $ids;
|
||||
});
|
||||
} catch (\Throwable $throwable) {
|
||||
$media->rollback();
|
||||
return new WP_REST_Response(['message' => __('The Fonts Plugin migration failed; newly created Jooosi Fon records were rolled back.', 'jooosi-fon')], 500);
|
||||
}
|
||||
$media->commit();
|
||||
FontEvents::dispatch('migration', ['source' => 'fonts-plugin', 'ids' => $insertedIds], \true);
|
||||
return new WP_REST_Response(['message' => __('Fonts Plugin uploaded families imported. Source records were preserved.', 'jooosi-fon'), 'imported' => count($insertedIds), 'skipped' => $skipped, 'source_preserved' => \true]);
|
||||
}
|
||||
public function clean_up(WP_REST_Request $request): WP_REST_Response
|
||||
{
|
||||
if (!$this->is_active()) {
|
||||
return new WP_REST_Response(['message' => __('Fonts Plugin is not activated.', 'jooosi-fon')], 404);
|
||||
}
|
||||
$terms = $this->source_terms();
|
||||
if (is_wp_error($terms)) {
|
||||
return new WP_REST_Response(['message' => __('Fonts Plugin records could not be read.', 'jooosi-fon')], 500);
|
||||
}
|
||||
global $wpdb;
|
||||
if ($wpdb->query('START TRANSACTION') === \false) {
|
||||
return new WP_REST_Response(['message' => __('Fonts Plugin cleanup could not start a database transaction.', 'jooosi-fon')], 500);
|
||||
}
|
||||
$termIds = array_map(static fn($term): int => (int) $term->term_id, $terms);
|
||||
$termOptionNames = array_map(fn(int $termId): string => $this->term_option_name($termId), $termIds);
|
||||
$assignedThemeMods = $this->assigned_theme_mods();
|
||||
try {
|
||||
foreach ($terms as $term) {
|
||||
delete_option($this->term_option_name((int) $term->term_id));
|
||||
$deleted = wp_delete_term((int) $term->term_id, self::TAXONOMY);
|
||||
if ($deleted === \false || is_wp_error($deleted)) {
|
||||
throw new \RuntimeException('A Fonts Plugin term could not be deleted.');
|
||||
}
|
||||
}
|
||||
foreach (array_keys($assignedThemeMods) as $themeMod) {
|
||||
remove_theme_mod($themeMod);
|
||||
}
|
||||
if ($wpdb->query('COMMIT') === \false) {
|
||||
throw new \RuntimeException($wpdb->last_error ?: 'Fonts Plugin cleanup could not be committed.');
|
||||
}
|
||||
} catch (\Throwable $throwable) {
|
||||
$wpdb->query('ROLLBACK');
|
||||
clean_term_cache($termIds, self::TAXONOMY);
|
||||
foreach ($termOptionNames as $termOptionName) {
|
||||
wp_cache_delete($termOptionName, 'options');
|
||||
}
|
||||
foreach ($assignedThemeMods as $themeMod => $value) {
|
||||
set_theme_mod($themeMod, $value);
|
||||
}
|
||||
return new WP_REST_Response(['message' => __('Fonts Plugin cleanup failed and the source transaction was rolled back.', 'jooosi-fon')], 500);
|
||||
}
|
||||
FontEvents::dispatch('clean_up', ['source' => 'fonts-plugin', 'ids' => $termIds], \true);
|
||||
return new WP_REST_Response(['message' => __('Fonts Plugin uploaded-font records and their selector assignments were removed. Original media files were left in place.', 'jooosi-fon'), 'cleaned' => count($termIds)]);
|
||||
}
|
||||
private function is_active(): bool
|
||||
{
|
||||
return defined('OGF_VERSION') && taxonomy_exists(self::TAXONOMY) && function_exists('ogf_get_elements') && function_exists('ogf_get_custom_elements');
|
||||
}
|
||||
/**
|
||||
* @return array<int, object>|\WP_Error
|
||||
*/
|
||||
private function source_terms()
|
||||
{
|
||||
return get_terms(['taxonomy' => self::TAXONOMY, 'hide_empty' => \false]);
|
||||
}
|
||||
/**
|
||||
* @return array<int, array{source_key: string, selector: string}>
|
||||
*/
|
||||
private function selector_assignments(): array
|
||||
{
|
||||
$assignments = [];
|
||||
foreach ($this->source_elements() as $elementId => $element) {
|
||||
$fontId = get_theme_mod((string) $elementId . '_font', '');
|
||||
if (!is_string($fontId) || strpos($fontId, 'cf-') !== 0) {
|
||||
continue;
|
||||
}
|
||||
$selector = is_array($element) ? $element['selectors'] ?? '' : '';
|
||||
$assignments[] = ['source_key' => substr($fontId, 3), 'selector' => is_string($selector) ? $selector : ''];
|
||||
}
|
||||
return $assignments;
|
||||
}
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function assigned_theme_mods(): array
|
||||
{
|
||||
$themeMods = [];
|
||||
foreach ($this->source_elements() as $elementId => $element) {
|
||||
$themeMod = (string) $elementId . '_font';
|
||||
$value = get_theme_mod($themeMod, null);
|
||||
if (is_string($value) && strpos($value, 'cf-') === 0) {
|
||||
$themeMods[$themeMod] = $value;
|
||||
}
|
||||
}
|
||||
return $themeMods;
|
||||
}
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function source_elements(): array
|
||||
{
|
||||
$standard = ogf_get_elements();
|
||||
$custom = ogf_get_custom_elements();
|
||||
return array_merge(is_array($standard) ? $standard : [], is_array($custom) ? $custom : []);
|
||||
}
|
||||
private function term_option_name(int $termId): string
|
||||
{
|
||||
return 'taxonomy_' . self::TAXONOMY . '_' . $termId;
|
||||
}
|
||||
/**
|
||||
* @param array<string, mixed> $sourceFile
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function import_file(MediaImportService $media, array $sourceFile, string $fileName): array
|
||||
{
|
||||
$location = (string) ($sourceFile['location'] ?? '');
|
||||
$extension = (string) ($sourceFile['extension'] ?? '');
|
||||
$attachmentId = (int) ($sourceFile['attachment_id'] ?? attachment_url_to_postid($location));
|
||||
$path = $attachmentId > 0 ? get_attached_file($attachmentId) : \false;
|
||||
if (is_string($path) && is_readable($path)) {
|
||||
return $media->local($path, $fileName, $extension);
|
||||
}
|
||||
return $media->remote($location, $fileName, $extension);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,310 @@
|
||||
<?php
|
||||
|
||||
declare (strict_types=1);
|
||||
namespace JooosiFon\Api\Migrations\Support;
|
||||
|
||||
/**
|
||||
* Converts third-party plugin records into a small, source-agnostic shape.
|
||||
* Keeping this work free of WordPress side effects makes the source schemas
|
||||
* straightforward to test without booting a complete WordPress installation.
|
||||
*/
|
||||
final class SourceFontNormalizer
|
||||
{
|
||||
private const SUPPORTED_EXTENSIONS = ['woff2', 'woff', 'ttf', 'otf', 'eot'];
|
||||
/**
|
||||
* @param array<string, mixed> $fontData
|
||||
* @return array{
|
||||
* display: string,
|
||||
* fallback: string,
|
||||
* skipped: int,
|
||||
* faces: array<int, array{
|
||||
* weight: string,
|
||||
* width: string,
|
||||
* style: string,
|
||||
* files: array<int, array{location: string, extension: string}>
|
||||
* }>
|
||||
* }
|
||||
*/
|
||||
public static function brainstormForce(array $fontData): array
|
||||
{
|
||||
$faces = [];
|
||||
$skipped = 0;
|
||||
$variations = isset($fontData['variations']) && is_array($fontData['variations']) ? $fontData['variations'] : [];
|
||||
foreach ($variations as $variation) {
|
||||
if (!is_array($variation)) {
|
||||
++$skipped;
|
||||
continue;
|
||||
}
|
||||
$weightSource = (string) ($variation['font_weight'] ?? '400');
|
||||
$files = self::remoteFiles($variation['font_url'] ?? []);
|
||||
if ($files === []) {
|
||||
++$skipped;
|
||||
continue;
|
||||
}
|
||||
$faces[] = ['weight' => self::weight($weightSource), 'width' => '100%', 'style' => self::style((string) ($variation['font_style'] ?? ''), $weightSource), 'files' => $files];
|
||||
}
|
||||
$display = $fontData['font_display'] ?? 'auto';
|
||||
$fallback = $fontData['font_fallback'] ?? '';
|
||||
return ['display' => self::display(is_string($display) ? $display : 'auto'), 'fallback' => is_string($fallback) ? trim($fallback) : '', 'skipped' => $skipped, 'faces' => $faces];
|
||||
}
|
||||
/**
|
||||
* @param array<string|int, mixed> $fontRows
|
||||
* @param array<string|int, mixed> $assignments
|
||||
* @return array<string, array{
|
||||
* family: string,
|
||||
* display: string,
|
||||
* selector: string,
|
||||
* faces: array<int, array{
|
||||
* source_key: string,
|
||||
* weight: string,
|
||||
* width: string,
|
||||
* style: string,
|
||||
* files: array<int, array{location: string, extension: string}>
|
||||
* }>
|
||||
* }>
|
||||
*/
|
||||
public static function useAnyFont(array $fontRows, array $assignments, string $baseDirectory, string $display): array
|
||||
{
|
||||
$families = [];
|
||||
$rowFamilies = [];
|
||||
$baseDirectory = rtrim($baseDirectory, '/\\') . \DIRECTORY_SEPARATOR;
|
||||
foreach ($fontRows as $sourceKey => $fontRow) {
|
||||
if (!is_array($fontRow)) {
|
||||
continue;
|
||||
}
|
||||
$family = trim((string) ($fontRow['font_name'] ?? ''));
|
||||
$fontPath = basename(str_replace('\\', '/', trim((string) ($fontRow['font_path'] ?? ''))));
|
||||
if ($family === '' || $fontPath === '') {
|
||||
continue;
|
||||
}
|
||||
if (!isset($families[$family])) {
|
||||
$families[$family] = ['family' => $family, 'display' => self::display($display), 'selector' => '', 'faces' => []];
|
||||
}
|
||||
$key = (string) $sourceKey;
|
||||
$rowFamilies[$key] = $family;
|
||||
$files = [];
|
||||
foreach (['woff2', 'woff', 'eot'] as $extension) {
|
||||
$files[] = ['location' => $baseDirectory . $fontPath . '.' . $extension, 'extension' => $extension];
|
||||
}
|
||||
$families[$family]['faces'][] = ['source_key' => $key, 'weight' => self::weight((string) ($fontRow['font_weight'] ?? '400')), 'width' => self::width((string) ($fontRow['font_stretch'] ?? 'normal')), 'style' => self::style((string) ($fontRow['font_style'] ?? '')), 'files' => $files];
|
||||
}
|
||||
$selectors = [];
|
||||
foreach ($assignments as $assignment) {
|
||||
if (!is_array($assignment)) {
|
||||
continue;
|
||||
}
|
||||
$family = trim((string) ($assignment['font_name'] ?? ''));
|
||||
$sourceKey = (string) ($assignment['font_key'] ?? '');
|
||||
if ($family === '' && isset($rowFamilies[$sourceKey])) {
|
||||
$family = $rowFamilies[$sourceKey];
|
||||
}
|
||||
$selector = self::selector((string) ($assignment['font_elements'] ?? ''));
|
||||
if ($family === '' || $selector === '' || !isset($families[$family])) {
|
||||
continue;
|
||||
}
|
||||
$selectors[$family][] = $selector;
|
||||
}
|
||||
foreach ($selectors as $family => $familySelectors) {
|
||||
$families[$family]['selector'] = self::selector(implode(', ', array_unique($familySelectors)));
|
||||
}
|
||||
return $families;
|
||||
}
|
||||
/**
|
||||
* @param array<int, array<string, mixed>> $fontRows
|
||||
* @param array<int, array<string, mixed>> $assignments
|
||||
* @return array<string, array<string, mixed>>
|
||||
*/
|
||||
public static function fontsPlugin(array $fontRows, array $assignments, string $display): array
|
||||
{
|
||||
$families = [];
|
||||
$rowFamilies = [];
|
||||
foreach ($fontRows as $fontRow) {
|
||||
if (!is_array($fontRow)) {
|
||||
continue;
|
||||
}
|
||||
$family = trim(self::stringValue($fontRow['family'] ?? ''));
|
||||
if ($family === '') {
|
||||
$family = trim(self::stringValue($fontRow['name'] ?? ''));
|
||||
}
|
||||
$sourceKey = trim(self::stringValue($fontRow['source_key'] ?? $fontRow['slug'] ?? ''));
|
||||
$files = self::remoteFiles([$fontRow['woff2'] ?? '', $fontRow['woff'] ?? '', $fontRow['ttf'] ?? '', $fontRow['otf'] ?? '', $fontRow['eot'] ?? '']);
|
||||
if ($family === '' || $files === []) {
|
||||
continue;
|
||||
}
|
||||
if (!isset($families[$family])) {
|
||||
$families[$family] = ['family' => $family, 'display' => self::display($display), 'selector' => '', 'preload' => \false, 'faces' => []];
|
||||
}
|
||||
if ($sourceKey !== '') {
|
||||
$rowFamilies[$sourceKey] = $family;
|
||||
}
|
||||
$preload = filter_var($fontRow['preload'] ?? \false, \FILTER_VALIDATE_BOOLEAN);
|
||||
$families[$family]['preload'] = $families[$family]['preload'] || $preload;
|
||||
$families[$family]['faces'][] = ['source_key' => $sourceKey, 'weight' => self::weight(self::stringValue($fontRow['weight'] ?? '400', '400')), 'width' => self::width(self::stringValue($fontRow['stretch'] ?? 'normal', 'normal')), 'style' => self::style(self::stringValue($fontRow['style'] ?? 'normal', 'normal')), 'preload' => $preload, 'files' => $files];
|
||||
}
|
||||
$selectors = [];
|
||||
foreach ($assignments as $assignment) {
|
||||
if (!is_array($assignment)) {
|
||||
continue;
|
||||
}
|
||||
$sourceKey = trim(self::stringValue($assignment['source_key'] ?? ''));
|
||||
$family = trim(self::stringValue($assignment['family'] ?? ''));
|
||||
if ($family === '' && isset($rowFamilies[$sourceKey])) {
|
||||
$family = $rowFamilies[$sourceKey];
|
||||
}
|
||||
$selector = self::selector(self::stringValue($assignment['selector'] ?? ''));
|
||||
if ($family !== '' && $selector !== '' && isset($families[$family])) {
|
||||
$selectors[$family][] = $selector;
|
||||
}
|
||||
}
|
||||
foreach ($selectors as $family => $familySelectors) {
|
||||
$families[$family]['selector'] = self::selector(implode(', ', array_unique($familySelectors)));
|
||||
}
|
||||
return $families;
|
||||
}
|
||||
/**
|
||||
* @param array<int, mixed> $variants
|
||||
* @return array{display: string, skipped: int, faces: array<int, array<string, mixed>>}
|
||||
*/
|
||||
public static function elementor(array $variants, string $display = 'auto'): array
|
||||
{
|
||||
$faces = [];
|
||||
$skipped = 0;
|
||||
foreach ($variants as $variant) {
|
||||
if (!is_array($variant)) {
|
||||
++$skipped;
|
||||
continue;
|
||||
}
|
||||
$fontWeight = (string) ($variant['font_weight'] ?? $variant['weight'] ?? '400');
|
||||
$files = [];
|
||||
foreach (self::SUPPORTED_EXTENSIONS as $extension) {
|
||||
$source = $variant[$extension] ?? $variant['font_face_file_' . $extension] ?? null;
|
||||
if (is_array($source)) {
|
||||
$source = ['url' => $source['url'] ?? $source['location'] ?? '', 'id' => $source['id'] ?? $source['attachment_id'] ?? 0];
|
||||
}
|
||||
$files[] = $source;
|
||||
}
|
||||
$files = self::remoteFiles($files);
|
||||
if ($files === []) {
|
||||
++$skipped;
|
||||
continue;
|
||||
}
|
||||
$faces[] = ['weight' => self::weight($fontWeight), 'width' => self::width((string) ($variant['font_stretch'] ?? $variant['stretch'] ?? 'normal')), 'style' => self::style((string) ($variant['font_style'] ?? $variant['style'] ?? 'normal'), $fontWeight), 'preload' => filter_var($variant['preload'] ?? \false, \FILTER_VALIDATE_BOOLEAN), 'files' => $files];
|
||||
}
|
||||
return ['display' => self::display($display), 'skipped' => $skipped, 'faces' => $faces];
|
||||
}
|
||||
/**
|
||||
* @param array<string, mixed> $source
|
||||
* @return array{id: string, families: array<int, array<string, mixed>>}
|
||||
*/
|
||||
public static function customAdobeKit(array $source): array
|
||||
{
|
||||
$projectId = trim(self::stringValue($source['custom-typekit-font-id'] ?? ''));
|
||||
$details = isset($source['custom-typekit-font-details']) && is_array($source['custom-typekit-font-details']) ? $source['custom-typekit-font-details'] : [];
|
||||
$families = [];
|
||||
foreach ($details as $sourceName => $detail) {
|
||||
if (!is_array($detail)) {
|
||||
continue;
|
||||
}
|
||||
$cssNames = array_values(array_filter(array_map('strval', (array) ($detail['css_names'] ?? [])), static fn(string $name): bool => trim($name) !== ''));
|
||||
$slug = trim((string) ($detail['slug'] ?? $cssNames[0] ?? ''));
|
||||
$family = trim((string) ($detail['family'] ?? $sourceName));
|
||||
if ($slug === '' || $family === '') {
|
||||
continue;
|
||||
}
|
||||
$name = ucwords(str_replace(['-', '_'], ' ', $family));
|
||||
$weights = array_values(array_unique(array_map(static fn($weight): string => self::weight((string) $weight), (array) ($detail['weights'] ?? []))));
|
||||
$families[] = ['id' => $slug, 'name' => $name, 'slug' => $cssNames[0] ?? $slug, 'css_names' => $cssNames, 'css_stack' => trim((string) ($detail['fallback'] ?? '')), 'weights' => $weights];
|
||||
}
|
||||
return ['id' => $projectId, 'families' => $families];
|
||||
}
|
||||
/**
|
||||
* @param mixed $urls
|
||||
* @return array<int, array{location: string, extension: string, attachment_id?: int}>
|
||||
*/
|
||||
private static function remoteFiles($urls): array
|
||||
{
|
||||
if (is_string($urls)) {
|
||||
$urls = [$urls];
|
||||
}
|
||||
if (!is_array($urls)) {
|
||||
return [];
|
||||
}
|
||||
$files = [];
|
||||
$seenExtensions = [];
|
||||
foreach ($urls as $url) {
|
||||
$attachmentId = 0;
|
||||
if (is_array($url)) {
|
||||
$attachmentId = max(0, (int) ($url['id'] ?? $url['attachment_id'] ?? 0));
|
||||
$url = $url['url'] ?? $url['location'] ?? '';
|
||||
}
|
||||
if (!is_string($url) || trim($url) === '') {
|
||||
continue;
|
||||
}
|
||||
$path = parse_url(trim($url), \PHP_URL_PATH);
|
||||
$extension = is_string($path) ? strtolower(pathinfo($path, \PATHINFO_EXTENSION)) : '';
|
||||
if (!in_array($extension, self::SUPPORTED_EXTENSIONS, \true) || isset($seenExtensions[$extension])) {
|
||||
continue;
|
||||
}
|
||||
$file = ['location' => trim($url), 'extension' => $extension];
|
||||
if ($attachmentId > 0) {
|
||||
$file['attachment_id'] = $attachmentId;
|
||||
}
|
||||
$seenExtensions[$extension] = \true;
|
||||
$files[] = $file;
|
||||
}
|
||||
return $files;
|
||||
}
|
||||
private static function display(string $display): string
|
||||
{
|
||||
$display = strtolower(trim($display));
|
||||
return in_array($display, ['auto', 'block', 'swap', 'fallback', 'optional'], \true) ? $display : 'auto';
|
||||
}
|
||||
/**
|
||||
* @param mixed $value
|
||||
*/
|
||||
private static function stringValue($value, string $default = ''): string
|
||||
{
|
||||
return is_string($value) || is_int($value) || is_float($value) ? (string) $value : $default;
|
||||
}
|
||||
private static function style(string $style, string $weight = ''): string
|
||||
{
|
||||
$style = strtolower(trim($style));
|
||||
if ($style === 'italic' || stripos($weight, 'italic') !== \false) {
|
||||
return 'italic';
|
||||
}
|
||||
return $style === 'oblique' ? 'oblique' : 'normal';
|
||||
}
|
||||
private static function weight(string $weight): string
|
||||
{
|
||||
$weight = strtolower(trim($weight));
|
||||
if ($weight === 'normal' || $weight === 'regular') {
|
||||
return '400';
|
||||
}
|
||||
if ($weight === 'bold') {
|
||||
return '700';
|
||||
}
|
||||
if (preg_match('/^([1-9]\d{0,3})(?:\s+([1-9]\d{0,3}))?/', $weight, $matches) !== 1) {
|
||||
return '400';
|
||||
}
|
||||
$minimum = (int) $matches[1];
|
||||
$maximum = isset($matches[2]) ? (int) $matches[2] : null;
|
||||
if ($minimum > 1000 || $maximum !== null && ($maximum > 1000 || $minimum > $maximum)) {
|
||||
return '400';
|
||||
}
|
||||
return $maximum === null ? (string) $minimum : $minimum . ' ' . $maximum;
|
||||
}
|
||||
private static function width(string $stretch): string
|
||||
{
|
||||
$widths = ['ultra-condensed' => '50%', 'extra-condensed' => '62.5%', 'condensed' => '75%', 'semi-condensed' => '87.5%', 'normal' => '100%', 'semi-expanded' => '112.5%', 'expanded' => '125%', 'extra-expanded' => '150%', 'ultra-expanded' => '200%'];
|
||||
$stretch = strtolower(trim($stretch));
|
||||
return $widths[$stretch] ?? '100%';
|
||||
}
|
||||
private static function selector(string $selector): string
|
||||
{
|
||||
$selector = trim($selector);
|
||||
if ($selector === '' || strlen($selector) > 1000 || preg_match('/[<{};@]|\/\*|\*\/|[\x00-\x08\x0B\x0C\x0E-\x1F]/', $selector) !== 0) {
|
||||
return '';
|
||||
}
|
||||
return $selector;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
<?php
|
||||
|
||||
declare (strict_types=1);
|
||||
namespace JooosiFon\Api\Migrations;
|
||||
|
||||
use JooosiFon\Api\AbstractApi;
|
||||
use JooosiFon\Api\ApiInterface;
|
||||
use JooosiFon\Api\Migrations\Support\SourceFontNormalizer;
|
||||
use JooosiFon\Api\Support\FontCodec;
|
||||
use JooosiFon\Api\Support\FontEvents;
|
||||
use JooosiFon\Api\Support\FontRepository;
|
||||
use JooosiFon\Api\Support\MediaImportService;
|
||||
use JooosiFon\Api\Support\RequestValidator;
|
||||
use JooosiFon\Utils\Common;
|
||||
use JooosiFon\Utils\Upload;
|
||||
use WP_REST_Request;
|
||||
use WP_REST_Response;
|
||||
use WP_REST_Server;
|
||||
final class UseAnyFont extends AbstractApi implements ApiInterface
|
||||
{
|
||||
public function get_prefix(): string
|
||||
{
|
||||
return 'migrations/use-any-font';
|
||||
}
|
||||
public function register_custom_endpoints(): void
|
||||
{
|
||||
register_rest_route(self::API_NAMESPACE, $this->get_prefix() . '/import-fonts', ['methods' => WP_REST_Server::CREATABLE, 'callback' => fn(WP_REST_Request $request): WP_REST_Response => $this->import_fonts($request), 'permission_callback' => fn(WP_REST_Request $request): bool => $this->permission_callback($request)]);
|
||||
register_rest_route(self::API_NAMESPACE, $this->get_prefix() . '/clean-up', ['methods' => WP_REST_Server::CREATABLE, 'callback' => fn(WP_REST_Request $request): WP_REST_Response => $this->clean_up($request), 'permission_callback' => fn(WP_REST_Request $request): bool => $this->permission_callback($request), 'args' => ['confirm' => ['required' => \true, 'sanitize_callback' => 'rest_sanitize_boolean', 'validate_callback' => [RequestValidator::class, 'confirmed']]]]);
|
||||
}
|
||||
public function import_fonts(WP_REST_Request $request): WP_REST_Response
|
||||
{
|
||||
if (!$this->is_active()) {
|
||||
return new WP_REST_Response(['message' => __('Use Any Font is not activated.', 'jooosi-fon')], 404);
|
||||
}
|
||||
$fontRows = $this->decode_option('uaf_font_data');
|
||||
$assignments = $this->decode_option('uaf_font_implement');
|
||||
if ($fontRows === null || $assignments === null) {
|
||||
return new WP_REST_Response(['message' => __('Use Any Font records could not be read.', 'jooosi-fon')], 500);
|
||||
}
|
||||
/** @var array{dir?: mixed} $paths */
|
||||
$paths = uaf_path_details();
|
||||
$directory = isset($paths['dir']) && is_string($paths['dir']) ? $paths['dir'] : '';
|
||||
if ($directory === '') {
|
||||
return new WP_REST_Response(['message' => __('Use Any Font storage could not be located.', 'jooosi-fon')], 500);
|
||||
}
|
||||
$families = SourceFontNormalizer::useAnyFont($fontRows, $assignments, $directory, (string) get_option('uaf_font_display_property', 'auto'));
|
||||
add_filter('wp_check_filetype_and_ext', static fn($data, $file, $filename, $mimes) => Upload::disable_real_mime_check($data, $file, $filename, $mimes), 10, 4);
|
||||
add_filter('upload_mimes', static fn($mimeTypes) => Upload::upload_mimes($mimeTypes, \true), 1000001);
|
||||
$repository = new FontRepository();
|
||||
$media = new MediaImportService();
|
||||
$records = [];
|
||||
$insertedIds = [];
|
||||
$normalizedFaceCount = array_sum(array_map(static fn(array $sourceFamily): int => count($sourceFamily['faces']), $families));
|
||||
$skipped = max(0, count($fontRows) - $normalizedFaceCount);
|
||||
try {
|
||||
foreach ($families as $sourceFamily) {
|
||||
$family = sanitize_text_field($sourceFamily['family']);
|
||||
$familySlug = sanitize_title_with_dashes($family);
|
||||
if ($family === '' || $familySlug === '') {
|
||||
++$skipped;
|
||||
continue;
|
||||
}
|
||||
$migrationSlug = 'migration-use-any-font-' . $familySlug;
|
||||
if ($repository->findBySlug($migrationSlug)) {
|
||||
continue;
|
||||
}
|
||||
$fontFaces = [];
|
||||
foreach ($sourceFamily['faces'] as $sourceFace) {
|
||||
$files = [];
|
||||
foreach ($sourceFace['files'] as $sourceFile) {
|
||||
if (!is_file($sourceFile['location']) || !is_readable($sourceFile['location'])) {
|
||||
continue;
|
||||
}
|
||||
$fileName = sanitize_title_with_dashes(sprintf('%s-%s-%s-%s-%s', $family, $sourceFace['weight'], $sourceFace['style'], Common::random_slug(5), time())) . '.' . $sourceFile['extension'];
|
||||
$files[] = $media->local($sourceFile['location'], $fileName, $sourceFile['extension']);
|
||||
}
|
||||
if ($files === []) {
|
||||
++$skipped;
|
||||
continue;
|
||||
}
|
||||
$fontFaces[] = ['id' => Common::random_slug(10), 'weight' => $sourceFace['weight'], 'width' => $sourceFace['width'], 'style' => $sourceFace['style'], 'display' => '', 'selector' => '', 'comment' => '', 'unicodeRange' => '', 'preload' => \false, 'files' => $files];
|
||||
}
|
||||
if ($fontFaces === []) {
|
||||
++$skipped;
|
||||
continue;
|
||||
}
|
||||
$records[] = ['type' => 'custom', 'title' => $family, 'slug' => $migrationSlug, 'family' => $family, 'status' => \true, 'metadata' => FontCodec::encode(['preload' => \false, 'selector' => $sourceFamily['selector'], 'display' => $sourceFamily['display']]), 'font_faces' => FontCodec::encode($fontFaces)];
|
||||
}
|
||||
if ($skipped > 0) {
|
||||
$media->rollback();
|
||||
return new WP_REST_Response(['message' => __('Some Use Any Font records had no supported, readable files. Nothing was imported so the source records remain safe.', 'jooosi-fon'), 'skipped' => $skipped], 422);
|
||||
}
|
||||
$insertedIds = $repository->transaction(static function (FontRepository $repository) use ($records): array {
|
||||
$ids = [];
|
||||
foreach ($records as $record) {
|
||||
$ids[] = $repository->insert($record, ['%s', '%s', '%s', '%s', '%d', '%s', '%s']);
|
||||
}
|
||||
return $ids;
|
||||
});
|
||||
} catch (\Throwable $throwable) {
|
||||
$media->rollback();
|
||||
return new WP_REST_Response(['message' => __('The Use Any Font migration failed; newly created Jooosi Fon records were rolled back.', 'jooosi-fon')], 500);
|
||||
}
|
||||
$media->commit();
|
||||
FontEvents::dispatch('migration', ['source' => 'use-any-font', 'ids' => $insertedIds], \true);
|
||||
return new WP_REST_Response(['message' => __('Use Any Font families imported. Source records were preserved.', 'jooosi-fon'), 'imported' => count($insertedIds), 'skipped' => $skipped, 'source_preserved' => \true]);
|
||||
}
|
||||
public function clean_up(WP_REST_Request $request): WP_REST_Response
|
||||
{
|
||||
if (!$this->is_active()) {
|
||||
return new WP_REST_Response(['message' => __('Use Any Font is not activated.', 'jooosi-fon')], 404);
|
||||
}
|
||||
$fontData = get_option('uaf_font_data', null);
|
||||
$assignments = get_option('uaf_font_implement', null);
|
||||
try {
|
||||
$this->replace_option('uaf_font_data', $fontData, '[]');
|
||||
$this->replace_option('uaf_font_implement', $assignments, '[]');
|
||||
if (function_exists('uaf_write_css')) {
|
||||
uaf_write_css();
|
||||
}
|
||||
} catch (\Throwable $throwable) {
|
||||
$this->restore_option('uaf_font_data', $fontData);
|
||||
$this->restore_option('uaf_font_implement', $assignments);
|
||||
return new WP_REST_Response(['message' => __('Use Any Font cleanup failed and the source options were restored.', 'jooosi-fon')], 500);
|
||||
}
|
||||
$decodedFontData = $this->decode_value($fontData);
|
||||
$cleaned = is_array($decodedFontData) ? count($decodedFontData) : 0;
|
||||
FontEvents::dispatch('clean_up', ['source' => 'use-any-font'], \true);
|
||||
return new WP_REST_Response(['message' => __('Use Any Font source records and selector assignments were removed. Original font files were left in place.', 'jooosi-fon'), 'cleaned' => $cleaned]);
|
||||
}
|
||||
private function is_active(): bool
|
||||
{
|
||||
return defined('UAF_FILE_PATH') && function_exists('uaf_path_details');
|
||||
}
|
||||
/**
|
||||
* @return array<string|int, mixed>|null
|
||||
*/
|
||||
private function decode_option(string $option): ?array
|
||||
{
|
||||
return $this->decode_value(get_option($option, '[]'));
|
||||
}
|
||||
/**
|
||||
* @param mixed $value
|
||||
* @return array<string|int, mixed>|null
|
||||
*/
|
||||
private function decode_value($value): ?array
|
||||
{
|
||||
if (is_array($value)) {
|
||||
return $value;
|
||||
}
|
||||
if ($value === \false || $value === null || $value === '') {
|
||||
return [];
|
||||
}
|
||||
if (!is_string($value)) {
|
||||
return null;
|
||||
}
|
||||
$decoded = json_decode($value, \true);
|
||||
return is_array($decoded) ? $decoded : null;
|
||||
}
|
||||
/**
|
||||
* @param mixed $original
|
||||
*/
|
||||
private function replace_option(string $option, $original, string $replacement): void
|
||||
{
|
||||
if ($original === $replacement) {
|
||||
return;
|
||||
}
|
||||
if (!update_option($option, $replacement)) {
|
||||
throw new \RuntimeException('The Use Any Font source option could not be updated.');
|
||||
}
|
||||
}
|
||||
/**
|
||||
* @param mixed $value
|
||||
*/
|
||||
private function restore_option(string $option, $value): void
|
||||
{
|
||||
if ($value === null || $value === \false) {
|
||||
delete_option($option);
|
||||
return;
|
||||
}
|
||||
update_option($option, $value);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Jooosi Fon package.
|
||||
*
|
||||
* (c) Joshua Gugun Siagian <suabahasa@gmail.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
declare (strict_types=1);
|
||||
namespace JooosiFon\Api;
|
||||
|
||||
use JooosiFon\Api\Migrations\BrainstormForceCustomFonts;
|
||||
use JooosiFon\Api\Migrations\BricksCustomFonts;
|
||||
use JooosiFon\Api\Migrations\CustomAdobeFonts;
|
||||
use JooosiFon\Api\Migrations\DpluginsFontHero;
|
||||
use JooosiFon\Api\Migrations\ElementorProCustomFonts;
|
||||
use JooosiFon\Api\Migrations\FontsPlugin;
|
||||
use JooosiFon\Api\Migrations\UseAnyFont;
|
||||
use JooosiFon\Api\Setting\AdobeFonts;
|
||||
use JooosiFon\Api\Setting\Cache;
|
||||
use JooosiFon\Api\Setting\License;
|
||||
use JooosiFon\Api\Setting\Option;
|
||||
use ReflectionClass;
|
||||
use JooosiFonDeps\Symfony\Component\Finder\Finder;
|
||||
/**
|
||||
* @todo Remove all legacy Yabe Webfont hook shims completely in Jooosi Fon 3.0.0.
|
||||
*/
|
||||
class Router
|
||||
{
|
||||
/**
|
||||
* @var array<string, array{name: string, file_path: string|false, class_name: class-string<ApiInterface>}>
|
||||
*/
|
||||
private array $apis = [];
|
||||
public function __construct()
|
||||
{
|
||||
$this->scan_apis();
|
||||
add_action('rest_api_init', function (): void {
|
||||
$this->register_apis();
|
||||
});
|
||||
}
|
||||
public function scan_apis(): void
|
||||
{
|
||||
/** @param array<string, class-string<ApiInterface>> $classes */
|
||||
$classes = apply_filters('f!jooosi/fon/api/router:classes', ['fonts' => \JooosiFon\Api\Font::class, 'setting/adobe-fonts' => AdobeFonts::class, 'setting/cache' => Cache::class, 'setting/license' => License::class, 'setting/option' => Option::class, 'migrations/bricks-custom-fonts' => BricksCustomFonts::class, 'migrations/brainstorm-force-custom-fonts' => BrainstormForceCustomFonts::class, 'migrations/custom-adobe-fonts' => CustomAdobeFonts::class, 'migrations/elementor-pro-custom-fonts' => ElementorProCustomFonts::class, 'migrations/font-hero-dplugins' => DpluginsFontHero::class, 'migrations/fonts-plugin' => FontsPlugin::class, 'migrations/use-any-font' => UseAnyFont::class]);
|
||||
$classes = apply_filters_deprecated('f!yabe/webfont/api/router:classes', [$classes], '2.1.0', 'f!jooosi/fon/api/router:classes');
|
||||
foreach ((array) $classes as $prefix => $className) {
|
||||
$this->addApi((string) $prefix, $className);
|
||||
}
|
||||
$this->scanLegacyExtensionDirectories();
|
||||
}
|
||||
public function register_apis(): void
|
||||
{
|
||||
/** @var array<string, array{name: string, file_path: string|false, class_name: class-string<ApiInterface>}> $apis */
|
||||
$apis = apply_filters('f!jooosi/fon/api/router:register_apis', $this->apis);
|
||||
$apis = apply_filters_deprecated('f!yabe/webfont/api/router:register_apis', [$apis], '2.1.0', 'f!jooosi/fon/api/router:register_apis');
|
||||
foreach ((array) $apis as $api) {
|
||||
$className = $api['class_name'] ?? null;
|
||||
if (!is_string($className) || !is_a($className, \JooosiFon\Api\ApiInterface::class, \true)) {
|
||||
do_action('a!jooosi/fon/api/router:invalid_api', $api);
|
||||
continue;
|
||||
}
|
||||
$reflector = new ReflectionClass($className);
|
||||
if (!$reflector->isInstantiable()) {
|
||||
do_action('a!jooosi/fon/api/router:invalid_api', $api);
|
||||
continue;
|
||||
}
|
||||
/** @var ApiInterface $instance */
|
||||
$instance = $reflector->newInstance();
|
||||
$instance->register_custom_endpoints();
|
||||
}
|
||||
}
|
||||
/**
|
||||
* @param mixed $className
|
||||
*/
|
||||
private function addApi(string $prefix, $className): void
|
||||
{
|
||||
if ($prefix === '' || !is_string($className) || !is_a($className, \JooosiFon\Api\ApiInterface::class, \true)) {
|
||||
do_action('a!jooosi/fon/api/router:invalid_api', $prefix, $className);
|
||||
return;
|
||||
}
|
||||
$reflector = new ReflectionClass($className);
|
||||
if (!$reflector->isInstantiable()) {
|
||||
do_action('a!jooosi/fon/api/router:invalid_api', $prefix, $className);
|
||||
return;
|
||||
}
|
||||
$this->apis[$prefix] = ['name' => $prefix, 'file_path' => $reflector->getFileName(), 'class_name' => $className];
|
||||
}
|
||||
/**
|
||||
* Compatibility path for extensions still using the old Finder hook. It is
|
||||
* only activated when a listener exists and is never cached, preventing a
|
||||
* class name from surviving without its defining file on the next request.
|
||||
*
|
||||
* @todo Remove this legacy extension scan completely in Jooosi Fon 3.0.0.
|
||||
*/
|
||||
private function scanLegacyExtensionDirectories(): void
|
||||
{
|
||||
$hook = 'a!jooosi/fon/api/router:before_scan';
|
||||
$legacyHook = 'a!yabe/webfont/api/router:before_scan';
|
||||
if (!has_action($hook) && !has_action($legacyHook)) {
|
||||
return;
|
||||
}
|
||||
$finder = new Finder();
|
||||
$finder->files()->in(__DIR__)->name('*.php');
|
||||
do_action($hook, $finder);
|
||||
do_action_deprecated($legacyHook, [$finder], '2.1.0', $hook);
|
||||
foreach ($finder as $file) {
|
||||
if ($file->isReadable()) {
|
||||
require_once $file->getPathname();
|
||||
}
|
||||
}
|
||||
foreach (get_declared_classes() as $className) {
|
||||
if (!is_a($className, \JooosiFon\Api\ApiInterface::class, \true)) {
|
||||
continue;
|
||||
}
|
||||
$reflector = new ReflectionClass($className);
|
||||
if (!$reflector->isInstantiable()) {
|
||||
continue;
|
||||
}
|
||||
/** @var ApiInterface $instance */
|
||||
$instance = $reflector->newInstanceWithoutConstructor();
|
||||
$this->addApi($instance->get_prefix(), $className);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Jooosi Fon package.
|
||||
*
|
||||
* (c) Joshua Gugun Siagian <suabahasa@gmail.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
declare (strict_types=1);
|
||||
namespace JooosiFon\Api\Setting;
|
||||
|
||||
use JooosiFon\Api\AbstractApi;
|
||||
use JooosiFon\Api\ApiInterface;
|
||||
use JooosiFon\Api\Support\FontCodec;
|
||||
use JooosiFon\Api\Support\FontEvents;
|
||||
use JooosiFon\Api\Support\FontRepository;
|
||||
use JooosiFon\Api\Support\RequestValidator;
|
||||
use WP_REST_Request;
|
||||
use WP_REST_Response;
|
||||
use WP_REST_Server;
|
||||
class AdobeFonts extends AbstractApi implements ApiInterface
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
}
|
||||
public function get_prefix(): string
|
||||
{
|
||||
return 'setting/adobe-fonts';
|
||||
}
|
||||
public function register_custom_endpoints(): void
|
||||
{
|
||||
register_rest_route(self::API_NAMESPACE, $this->get_prefix() . '/get-kits', ['methods' => WP_REST_Server::CREATABLE, 'callback' => fn(\WP_REST_Request $wprestRequest): \WP_REST_Response => $this->get_kits($wprestRequest), 'permission_callback' => fn(\WP_REST_Request $wprestRequest): bool => $this->permission_callback($wprestRequest), 'args' => ['project_id' => ['required' => \true, 'sanitize_callback' => 'sanitize_text_field', 'validate_callback' => [RequestValidator::class, 'projectId']]]]);
|
||||
register_rest_route(self::API_NAMESPACE, $this->get_prefix() . '/sync', ['methods' => WP_REST_Server::CREATABLE, 'callback' => fn(\WP_REST_Request $wprestRequest): \WP_REST_Response => $this->sync($wprestRequest), 'permission_callback' => fn(\WP_REST_Request $wprestRequest): bool => $this->permission_callback($wprestRequest), 'args' => ['kit' => ['required' => \true, 'validate_callback' => [RequestValidator::class, 'adobeKit']]]]);
|
||||
register_rest_route(self::API_NAMESPACE, $this->get_prefix() . '/destroy', ['methods' => WP_REST_Server::CREATABLE, 'callback' => fn(\WP_REST_Request $wprestRequest): \WP_REST_Response => $this->destroy($wprestRequest), 'permission_callback' => fn(\WP_REST_Request $wprestRequest): bool => $this->permission_callback($wprestRequest)]);
|
||||
}
|
||||
public function get_kits(WP_REST_Request $wprestRequest): WP_REST_Response
|
||||
{
|
||||
$project_id = (string) $wprestRequest->get_param('project_id');
|
||||
$response = wp_safe_remote_get(sprintf('https://typekit.com/api/v1/json/kits/%s/published', rawurlencode($project_id)), ['timeout' => 15, 'redirection' => 2, 'limit_response_size' => 2 * \MB_IN_BYTES]);
|
||||
if (is_wp_error($response)) {
|
||||
return new WP_REST_Response(['message' => 'Failed to get kits'], 500);
|
||||
}
|
||||
$status_code = wp_remote_retrieve_response_code($response);
|
||||
if ($status_code !== 200) {
|
||||
return new WP_REST_Response(['message' => 'Kits not found'], $status_code);
|
||||
}
|
||||
$body = wp_remote_retrieve_body($response);
|
||||
try {
|
||||
$kits = json_decode($body, \true, 512, \JSON_THROW_ON_ERROR);
|
||||
} catch (\JsonException $exception) {
|
||||
return new WP_REST_Response(['message' => __('Adobe Fonts returned an invalid response.', 'jooosi-fon')], 502);
|
||||
}
|
||||
return new WP_REST_Response(['data' => $kits]);
|
||||
}
|
||||
public function sync(WP_REST_Request $wprestRequest): WP_REST_Response
|
||||
{
|
||||
$kit = (array) $wprestRequest->get_param('kit');
|
||||
$repository = new FontRepository();
|
||||
try {
|
||||
$repository->transaction(static function (FontRepository $repository) use ($kit): void {
|
||||
$repository->deleteByType('adobe-fonts');
|
||||
foreach ($kit['families'] as $family) {
|
||||
$repository->insert(['status' => 1, 'type' => 'adobe-fonts', 'title' => sanitize_text_field($family['name']), 'slug' => sanitize_key($family['id']), 'family' => sanitize_text_field($family['slug']), 'metadata' => FontCodec::encode($family), 'font_faces' => FontCodec::encode([])], ['%d', '%s', '%s', '%s', '%s', '%s', '%s']);
|
||||
}
|
||||
});
|
||||
} catch (\Throwable $throwable) {
|
||||
return new WP_REST_Response(['message' => __('Adobe Fonts could not be synchronized. The previous data was preserved.', 'jooosi-fon')], 500);
|
||||
}
|
||||
FontEvents::invalidate('a!jooosi/fon/api/setting/adobe-fonts:sync');
|
||||
return new WP_REST_Response([]);
|
||||
}
|
||||
public function destroy(WP_REST_Request $wprestRequest): WP_REST_Response
|
||||
{
|
||||
try {
|
||||
$this->delete_fonts();
|
||||
} catch (\Throwable $throwable) {
|
||||
return new WP_REST_Response(['message' => __('Adobe Fonts could not be disconnected.', 'jooosi-fon')], 500);
|
||||
}
|
||||
FontEvents::invalidate('a!jooosi/fon/api/setting/adobe-fonts:destroy');
|
||||
return new WP_REST_Response([]);
|
||||
}
|
||||
private function delete_fonts(): void
|
||||
{
|
||||
(new FontRepository())->deleteByType('adobe-fonts');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Jooosi Fon package.
|
||||
*
|
||||
* (c) Joshua Gugun Siagian <suabahasa@gmail.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
declare (strict_types=1);
|
||||
namespace JooosiFon\Api\Setting;
|
||||
|
||||
use JooosiFon\Api\AbstractApi;
|
||||
use JooosiFon\Api\ApiInterface;
|
||||
use JooosiFon\Api\Support\FontEvents;
|
||||
use JooosiFon\Core\Cache as CoreCache;
|
||||
use WP_REST_Request;
|
||||
use WP_REST_Response;
|
||||
use WP_REST_Server;
|
||||
class Cache extends AbstractApi implements ApiInterface
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
}
|
||||
public function get_prefix(): string
|
||||
{
|
||||
return 'setting/cache';
|
||||
}
|
||||
public function register_custom_endpoints(): void
|
||||
{
|
||||
register_rest_route(self::API_NAMESPACE, $this->get_prefix() . '/index', ['methods' => WP_REST_Server::READABLE, 'callback' => fn(\WP_REST_Request $wprestRequest): \WP_REST_Response => $this->index($wprestRequest), 'permission_callback' => fn(\WP_REST_Request $wprestRequest): bool => $this->permission_callback($wprestRequest)]);
|
||||
register_rest_route(self::API_NAMESPACE, $this->get_prefix() . '/generate', ['methods' => WP_REST_Server::CREATABLE, 'callback' => fn(\WP_REST_Request $wprestRequest): \WP_REST_Response => $this->generate($wprestRequest), 'permission_callback' => fn(\WP_REST_Request $wprestRequest): bool => $this->permission_callback($wprestRequest)]);
|
||||
}
|
||||
public function index(WP_REST_Request $wprestRequest): WP_REST_Response
|
||||
{
|
||||
$cache_path = CoreCache::get_cache_path(CoreCache::CSS_CACHE_FILE);
|
||||
$cache = ['last_generated' => '', 'pending_task' => \false, 'file_url' => '', 'state' => 'idle', 'error' => '', 'warnings' => []];
|
||||
$buildStatus = CoreCache::getBuildStatus();
|
||||
$cache['state'] = (string) ($buildStatus['state'] ?? 'idle');
|
||||
$cache['error'] = (string) ($buildStatus['error'] ?? '');
|
||||
$cache['warnings'] = is_array($buildStatus['warnings'] ?? null) ? array_values($buildStatus['warnings']) : [];
|
||||
$cache['hash'] = (string) ($buildStatus['hash'] ?? '');
|
||||
$cache['changed'] = (bool) ($buildStatus['changed'] ?? \false);
|
||||
if (file_exists($cache_path) && is_readable($cache_path)) {
|
||||
$cache['file_url'] = CoreCache::get_versioned_cache_url(CoreCache::CSS_CACHE_FILE);
|
||||
$cache['last_generated'] = filemtime($cache_path);
|
||||
}
|
||||
if (wp_next_scheduled('a!jooosi/fon/core/cache:build_cache') || $cache['state'] === 'running') {
|
||||
$cache['pending_task'] = \true;
|
||||
}
|
||||
return new WP_REST_Response(['cache' => $cache]);
|
||||
}
|
||||
public function generate(WP_REST_Request $wprestRequest): WP_REST_Response
|
||||
{
|
||||
wp_clear_scheduled_hook('a!jooosi/fon/core/cache:build_cache');
|
||||
FontEvents::invalidate('a!jooosi/fon/api/setting/cache:generate', null, \false);
|
||||
return $this->index($wprestRequest);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Jooosi Fon package.
|
||||
*
|
||||
* (c) Joshua Gugun Siagian <suabahasa@gmail.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
declare (strict_types=1);
|
||||
namespace JooosiFon\Api\Setting;
|
||||
|
||||
use JooosiFonDeps\JOOOSI_FON;
|
||||
use JooosiFon\Api\AbstractApi;
|
||||
use JooosiFon\Api\ApiInterface;
|
||||
use JooosiFon\Plugin;
|
||||
use WP_REST_Request;
|
||||
use WP_REST_Response;
|
||||
use WP_REST_Server;
|
||||
class License extends AbstractApi implements ApiInterface
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
}
|
||||
public function get_prefix(): string
|
||||
{
|
||||
return 'setting/license';
|
||||
}
|
||||
public function register_custom_endpoints(): void
|
||||
{
|
||||
register_rest_route(self::API_NAMESPACE, $this->get_prefix() . '/index', ['methods' => WP_REST_Server::READABLE, 'callback' => fn(\WP_REST_Request $wprestRequest): \WP_REST_Response => $this->index($wprestRequest), 'permission_callback' => fn(\WP_REST_Request $wprestRequest): bool => $this->permission_callback($wprestRequest)]);
|
||||
register_rest_route(self::API_NAMESPACE, $this->get_prefix() . '/store', ['methods' => WP_REST_Server::CREATABLE, 'callback' => fn(\WP_REST_Request $wprestRequest): \WP_REST_Response => $this->store($wprestRequest), 'permission_callback' => fn(\WP_REST_Request $wprestRequest): bool => $this->permission_callback($wprestRequest), 'args' => ['license' => ['required' => \true, 'sanitize_callback' => 'sanitize_text_field', 'validate_callback' => static fn($value): bool => is_string($value) && strlen($value) <= 255]]]);
|
||||
}
|
||||
public function index(WP_REST_Request $wprestRequest): WP_REST_Response
|
||||
{
|
||||
return new WP_REST_Response(['license' => $this->get_license()]);
|
||||
}
|
||||
private function store(WP_REST_Request $wprestRequest): WP_REST_Response
|
||||
{
|
||||
$new_license_key = trim((string) $wprestRequest->get_param('license'));
|
||||
$old_license = $this->get_license();
|
||||
$plugin_updater = Plugin::get_instance()->plugin_updater;
|
||||
$notice = [];
|
||||
if ($new_license_key !== $old_license['key']) {
|
||||
if (!$plugin_updater) {
|
||||
return new WP_REST_Response(['message' => __('License management is unavailable in this edition.', 'jooosi-fon'), 'license' => $this->get_license()], 404);
|
||||
}
|
||||
if ($new_license_key === '') {
|
||||
$response = $plugin_updater->deactivate();
|
||||
if (is_wp_error($response)) {
|
||||
$message = $response->get_error_message();
|
||||
$status = $response->get_error_code() === 'license_server_unavailable' ? 502 : 422;
|
||||
return new WP_REST_Response(['message' => $message, 'license' => $this->get_license(), 'notice' => ['error' => $message]], $status);
|
||||
}
|
||||
$notice['success'] = __('Plugin license key deactivated successfully.', 'jooosi-fon');
|
||||
} else {
|
||||
$response = $plugin_updater->activate($new_license_key);
|
||||
if (is_wp_error($response)) {
|
||||
$message = $response->get_error_message();
|
||||
$status = $response->get_error_code() === 'license_server_unavailable' ? 502 : 422;
|
||||
return new WP_REST_Response(['message' => $message, 'license' => $this->get_license(), 'notice' => ['error' => $message]], $status);
|
||||
}
|
||||
$notice['success'] = __('Plugin license key activated successfully.', 'jooosi-fon');
|
||||
}
|
||||
$newOption = ['key' => $new_license_key, 'opt_in_pre_release' => (bool) $old_license['opt_in_pre_release']];
|
||||
if (!update_option(JOOOSI_FON::WP_OPTION . '_license', $newOption) && get_option(JOOOSI_FON::WP_OPTION . '_license') !== $newOption) {
|
||||
return new WP_REST_Response(['message' => __('The license was accepted but could not be saved locally.', 'jooosi-fon'), 'license' => $this->get_license()], 500);
|
||||
}
|
||||
}
|
||||
return new WP_REST_Response(['license' => $this->get_license(), 'notice' => $notice]);
|
||||
}
|
||||
private function get_license(): array
|
||||
{
|
||||
$license = get_option(JOOOSI_FON::WP_OPTION . '_license', ['key' => '', 'opt_in_pre_release' => \false]);
|
||||
$license = wp_parse_args(is_array($license) ? $license : [], ['key' => '', 'opt_in_pre_release' => \false]);
|
||||
$plugin_updater = Plugin::get_instance()->plugin_updater;
|
||||
if ($plugin_updater) {
|
||||
$license['key'] = $plugin_updater->get_license_key();
|
||||
}
|
||||
try {
|
||||
$license['is_activated'] = $plugin_updater && $plugin_updater->is_activated();
|
||||
} catch (\Throwable $throwable) {
|
||||
$license['is_activated'] = \false;
|
||||
}
|
||||
return $license;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Jooosi Fon package.
|
||||
*
|
||||
* (c) Joshua Gugun Siagian <suabahasa@gmail.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
declare (strict_types=1);
|
||||
namespace JooosiFon\Api\Setting;
|
||||
|
||||
use JooosiFonDeps\JOOOSI_FON;
|
||||
use JooosiFon\Api\AbstractApi;
|
||||
use JooosiFon\Api\ApiInterface;
|
||||
use JooosiFon\Api\Support\RequestValidator;
|
||||
use JooosiFon\Database\FontTable;
|
||||
use JooosiFon\Upgrade\LegacyRebrandUpgrade;
|
||||
use WP_REST_Request;
|
||||
use WP_REST_Response;
|
||||
use WP_REST_Server;
|
||||
/**
|
||||
* @todo Remove all legacy Yabe Webfont filter shims completely in Jooosi Fon 3.0.0.
|
||||
*/
|
||||
class Option extends AbstractApi implements ApiInterface
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
}
|
||||
public function get_prefix(): string
|
||||
{
|
||||
return 'setting/option';
|
||||
}
|
||||
public function register_custom_endpoints(): void
|
||||
{
|
||||
register_rest_route(self::API_NAMESPACE, $this->get_prefix() . '/index', ['methods' => WP_REST_Server::READABLE, 'callback' => fn(\WP_REST_Request $wprestRequest): \WP_REST_Response => $this->index($wprestRequest), 'permission_callback' => fn(\WP_REST_Request $wprestRequest): bool => $this->permission_callback($wprestRequest)]);
|
||||
register_rest_route(self::API_NAMESPACE, $this->get_prefix() . '/store', ['methods' => WP_REST_Server::CREATABLE, 'callback' => fn(\WP_REST_Request $wprestRequest): \WP_REST_Response => $this->store($wprestRequest), 'permission_callback' => fn(\WP_REST_Request $wprestRequest): bool => $this->permission_callback($wprestRequest), 'args' => ['options' => ['required' => \true, 'validate_callback' => [RequestValidator::class, 'arrayValue']]]]);
|
||||
register_rest_route(self::API_NAMESPACE, $this->get_prefix() . '/migrate-legacy', ['methods' => WP_REST_Server::CREATABLE, 'callback' => fn(\WP_REST_Request $wprestRequest): \WP_REST_Response => $this->migrate_legacy($wprestRequest), 'permission_callback' => fn(\WP_REST_Request $wprestRequest): bool => $this->permission_callback($wprestRequest)]);
|
||||
}
|
||||
public function index(WP_REST_Request $wprestRequest): WP_REST_Response
|
||||
{
|
||||
try {
|
||||
$stored = get_option(JOOOSI_FON::WP_OPTION . '_options', '{}');
|
||||
$options = json_decode(is_string($stored) ? $stored : '{}', null, 512, \JSON_THROW_ON_ERROR);
|
||||
} catch (\JsonException $exception) {
|
||||
$options = new \stdClass();
|
||||
}
|
||||
$options = apply_filters('f!jooosi/fon/api/setting/option:index_options', $options);
|
||||
$options = apply_filters_deprecated('f!yabe/webfont/api/setting/option:index_options', [$options], '2.1.0', 'f!jooosi/fon/api/setting/option:index_options');
|
||||
return new WP_REST_Response(['options' => $options, 'legacy_migration' => (new LegacyRebrandUpgrade())->status()]);
|
||||
}
|
||||
public function migrate_legacy(WP_REST_Request $wprestRequest): WP_REST_Response
|
||||
{
|
||||
try {
|
||||
FontTable::migrateLegacy();
|
||||
$upgrade = new LegacyRebrandUpgrade();
|
||||
$upgrade->run();
|
||||
$status = $upgrade->status();
|
||||
if (!$status['complete']) {
|
||||
return new WP_REST_Response(['message' => __('The Yabe Webfont migration is incomplete. The original data was preserved; try again after resolving the reported file issue.', 'jooosi-fon'), 'legacy_migration' => $status], 500);
|
||||
}
|
||||
return new WP_REST_Response(['legacy_migration' => $status]);
|
||||
} catch (\Throwable $throwable) {
|
||||
return new WP_REST_Response(['message' => $throwable->getMessage(), 'legacy_migration' => (new LegacyRebrandUpgrade())->status()], 500);
|
||||
}
|
||||
}
|
||||
public function store(WP_REST_Request $wprestRequest): WP_REST_Response
|
||||
{
|
||||
$options = (array) $wprestRequest->get_param('options');
|
||||
if (empty($options)) {
|
||||
$options = (object) $options;
|
||||
}
|
||||
$options = apply_filters('f!jooosi/fon/api/setting/option:store_options', $options);
|
||||
$options = apply_filters_deprecated('f!yabe/webfont/api/setting/option:store_options', [$options], '2.1.0', 'f!jooosi/fon/api/setting/option:store_options');
|
||||
try {
|
||||
$encoded = json_encode($options, \JSON_THROW_ON_ERROR);
|
||||
} catch (\JsonException $exception) {
|
||||
return new WP_REST_Response(['message' => __('The settings payload could not be encoded.', 'jooosi-fon')], 400);
|
||||
}
|
||||
if (!update_option(JOOOSI_FON::WP_OPTION . '_options', $encoded) && get_option(JOOOSI_FON::WP_OPTION . '_options') !== $encoded) {
|
||||
return new WP_REST_Response(['message' => __('The settings could not be saved.', 'jooosi-fon')], 500);
|
||||
}
|
||||
if ($this->shouldDeleteLegacyData($options) && !(new LegacyRebrandUpgrade())->deleteLegacyData()) {
|
||||
return new WP_REST_Response(['message' => __('The legacy Yabe Webfont data cleanup was incomplete. Any remaining data was preserved.', 'jooosi-fon')], 500);
|
||||
}
|
||||
do_action('f!jooosi/fon/api/setting/option:after_store', $options);
|
||||
do_action_deprecated('f!yabe/webfont/api/setting/option:after_store', [$options], '2.1.0', 'f!jooosi/fon/api/setting/option:after_store');
|
||||
return $this->index($wprestRequest);
|
||||
}
|
||||
/**
|
||||
* @param mixed $options
|
||||
*/
|
||||
private function shouldDeleteLegacyData($options): bool
|
||||
{
|
||||
if (is_object($options)) {
|
||||
$options = get_object_vars($options);
|
||||
}
|
||||
if (!is_array($options) || !is_array($options['misc'] ?? null)) {
|
||||
return \false;
|
||||
}
|
||||
return !empty($options['misc']['delete_legacy_data']);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
<?php
|
||||
|
||||
declare (strict_types=1);
|
||||
namespace JooosiFon\Api\Support;
|
||||
|
||||
/**
|
||||
* Encodes font payloads and reads both the current compressed representation
|
||||
* and the legacy plain JSON representation.
|
||||
*/
|
||||
final class FontCodec
|
||||
{
|
||||
/**
|
||||
* @return array|object
|
||||
*/
|
||||
public static function decode(string $payload, bool $associative = \false)
|
||||
{
|
||||
try {
|
||||
return self::decodeJson($payload, $associative);
|
||||
} catch (\JsonException $exception) {
|
||||
$compressed = base64_decode($payload, \true);
|
||||
if ($compressed === \false) {
|
||||
throw new \UnexpectedValueException('The stored font payload is neither JSON nor valid base64.', 0, $exception);
|
||||
}
|
||||
$json = @gzuncompress($compressed);
|
||||
if (!is_string($json)) {
|
||||
throw new \UnexpectedValueException('The stored font payload could not be decompressed.', 0, $exception);
|
||||
}
|
||||
return self::decodeJson($json, $associative);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* @param array|object $payload
|
||||
*/
|
||||
public static function encode($payload, bool $compressed = \true): string
|
||||
{
|
||||
$json = json_encode($payload, \JSON_THROW_ON_ERROR);
|
||||
if (!$compressed) {
|
||||
return $json;
|
||||
}
|
||||
$encoded = gzcompress($json, 9);
|
||||
if ($encoded === \false) {
|
||||
throw new \RuntimeException('The font payload could not be compressed.');
|
||||
}
|
||||
return base64_encode($encoded);
|
||||
}
|
||||
/**
|
||||
* @return array|object
|
||||
*/
|
||||
private static function decodeJson(string $payload, bool $associative)
|
||||
{
|
||||
$decoded = json_decode($payload, $associative, 512, \JSON_THROW_ON_ERROR);
|
||||
if (!is_array($decoded) && !is_object($decoded)) {
|
||||
throw new \UnexpectedValueException('The font payload must decode to an object or array.');
|
||||
}
|
||||
return $decoded;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
<?php
|
||||
|
||||
declare (strict_types=1);
|
||||
namespace JooosiFon\Api\Support;
|
||||
|
||||
use JooosiFon\Utils\Font;
|
||||
/**
|
||||
* Emits the public font lifecycle hooks and exactly one cache invalidation
|
||||
* event for each successful mutation.
|
||||
*
|
||||
* @todo Remove all legacy Yabe Webfont hook shims completely in Jooosi Fon 3.0.0.
|
||||
*/
|
||||
final class FontEvents
|
||||
{
|
||||
/**
|
||||
* @param mixed $payload
|
||||
*/
|
||||
public static function dispatch(string $event, $payload = null, bool $async = \true): void
|
||||
{
|
||||
$hook = 'a!jooosi/fon/api/font:' . $event;
|
||||
$legacyHook = 'a!yabe/webfont/api/font:' . $event;
|
||||
Font::clear_cache();
|
||||
do_action($hook, $payload);
|
||||
do_action_deprecated($legacyHook, [$payload], '2.1.0', $hook);
|
||||
self::emitInvalidation($hook, $payload, $async);
|
||||
}
|
||||
/**
|
||||
* @param mixed $payload
|
||||
*/
|
||||
public static function invalidate(string $source, $payload = null, bool $async = \true): void
|
||||
{
|
||||
Font::clear_cache();
|
||||
self::emitInvalidation($source, $payload, $async);
|
||||
}
|
||||
/**
|
||||
* @param mixed $payload
|
||||
*/
|
||||
private static function emitInvalidation(string $source, $payload, bool $async): void
|
||||
{
|
||||
$hook = $async ? 'a!jooosi/fon/api/font:fonts_event_async' : 'a!jooosi/fon/api/font:fonts_event';
|
||||
$legacyHook = $async ? 'a!yabe/webfont/api/font:fonts_event_async' : 'a!yabe/webfont/api/font:fonts_event';
|
||||
do_action($hook, $source, $payload);
|
||||
do_action_deprecated($legacyHook, [str_replace('!jooosi/fon/', '!yabe/webfont/', $source), $payload], '2.1.0', $hook);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
<?php
|
||||
|
||||
declare (strict_types=1);
|
||||
namespace JooosiFon\Api\Support;
|
||||
|
||||
/**
|
||||
* Owns database writes for font records and turns silent wpdb failures into
|
||||
* exceptions that REST controllers can handle consistently.
|
||||
*/
|
||||
final class FontRepository
|
||||
{
|
||||
public function table(): string
|
||||
{
|
||||
global $wpdb;
|
||||
return $wpdb->prefix . 'jooosi_fon_fonts';
|
||||
}
|
||||
public function find(int $id)
|
||||
{
|
||||
global $wpdb;
|
||||
return $wpdb->get_row($wpdb->prepare("SELECT * FROM {$this->table()} WHERE id = %d", $id));
|
||||
}
|
||||
public function findOfType(int $id, string $type)
|
||||
{
|
||||
global $wpdb;
|
||||
return $wpdb->get_row($wpdb->prepare("SELECT * FROM {$this->table()} WHERE id = %d AND type = %s", $id, $type));
|
||||
}
|
||||
public function findBySlug(string $slug)
|
||||
{
|
||||
global $wpdb;
|
||||
return $wpdb->get_row($wpdb->prepare("SELECT * FROM {$this->table()} WHERE slug = %s LIMIT 1", $slug));
|
||||
}
|
||||
/**
|
||||
* @param array<string, mixed> $data
|
||||
* @param string[] $formats
|
||||
*/
|
||||
public function insert(array $data, array $formats): int
|
||||
{
|
||||
global $wpdb;
|
||||
if ($wpdb->insert($this->table(), $data, $formats) === \false || $wpdb->insert_id < 1) {
|
||||
throw new \RuntimeException($wpdb->last_error ?: 'Unable to create the font record.');
|
||||
}
|
||||
return (int) $wpdb->insert_id;
|
||||
}
|
||||
/**
|
||||
* @param array<string, mixed> $data
|
||||
* @param string[] $formats
|
||||
*/
|
||||
public function update(int $id, array $data, array $formats): void
|
||||
{
|
||||
global $wpdb;
|
||||
if ($wpdb->update($this->table(), $data, ['id' => $id], $formats, ['%d']) === \false) {
|
||||
throw new \RuntimeException($wpdb->last_error ?: 'Unable to update the font record.');
|
||||
}
|
||||
}
|
||||
public function delete(int $id): void
|
||||
{
|
||||
global $wpdb;
|
||||
if ($wpdb->delete($this->table(), ['id' => $id], ['%d']) === \false) {
|
||||
throw new \RuntimeException($wpdb->last_error ?: 'Unable to delete the font record.');
|
||||
}
|
||||
}
|
||||
public function deleteByType(string $type): void
|
||||
{
|
||||
global $wpdb;
|
||||
if ($wpdb->delete($this->table(), ['type' => $type], ['%s']) === \false) {
|
||||
throw new \RuntimeException($wpdb->last_error ?: 'Unable to delete the font records.');
|
||||
}
|
||||
}
|
||||
/**
|
||||
* @return mixed
|
||||
*/
|
||||
public function transaction(callable $callback)
|
||||
{
|
||||
global $wpdb;
|
||||
if ($wpdb->query('START TRANSACTION') === \false) {
|
||||
throw new \RuntimeException($wpdb->last_error ?: 'Unable to start the database transaction.');
|
||||
}
|
||||
try {
|
||||
$result = $callback($this);
|
||||
if ($wpdb->query('COMMIT') === \false) {
|
||||
throw new \RuntimeException($wpdb->last_error ?: 'Unable to commit the database transaction.');
|
||||
}
|
||||
return $result;
|
||||
} catch (\Throwable $throwable) {
|
||||
$wpdb->query('ROLLBACK');
|
||||
throw $throwable;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
<?php
|
||||
|
||||
declare (strict_types=1);
|
||||
namespace JooosiFon\Api\Support;
|
||||
|
||||
final class GoogleFontFileSelector
|
||||
{
|
||||
/**
|
||||
* @param array<int, array<string, mixed>> $files
|
||||
* @param array<string, mixed> $face
|
||||
* @param string[] $subsets
|
||||
* @param string[] $formats
|
||||
* @return array<int, array<string, mixed>>
|
||||
*/
|
||||
public static function variableFiles(array $files, array $face, array $subsets, array $formats): array
|
||||
{
|
||||
$selected = [];
|
||||
foreach ($subsets as $subset) {
|
||||
foreach ($files as $file) {
|
||||
if (self::matchesFace($file, $face, $formats) && in_array($subset, (array) ($file['subsets'] ?? []), \true)) {
|
||||
$selected[] = $file;
|
||||
}
|
||||
}
|
||||
}
|
||||
$usesNamedSubsets = array_reduce($subsets, static fn(bool $carry, string $subset): bool => $carry && preg_match('/\d/', $subset) !== 1, \true);
|
||||
if ($usesNamedSubsets) {
|
||||
foreach ($files as $file) {
|
||||
if (self::matchesFace($file, $face, $formats)) {
|
||||
$selected[] = $file;
|
||||
}
|
||||
}
|
||||
}
|
||||
return array_values(array_unique($selected, \SORT_REGULAR));
|
||||
}
|
||||
/**
|
||||
* @param array<string, mixed> $file
|
||||
* @param array<string, mixed> $face
|
||||
* @param string[] $formats
|
||||
*/
|
||||
private static function matchesFace(array $file, array $face, array $formats): bool
|
||||
{
|
||||
return ($file['weight'] ?? null) === ($face['weight'] ?? null) && ($file['style'] ?? null) === ($face['style'] ?? null) && in_array($file['format'] ?? null, $formats, \true);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
|
||||
declare (strict_types=1);
|
||||
namespace JooosiFon\Api\Support;
|
||||
|
||||
final class GoogleFontsClient
|
||||
{
|
||||
public function fetchCss(string $url, string $userAgent): string
|
||||
{
|
||||
$host = strtolower((string) wp_parse_url($url, \PHP_URL_HOST));
|
||||
if (wp_parse_url($url, \PHP_URL_SCHEME) !== 'https' || $host !== 'fonts.googleapis.com') {
|
||||
throw new \InvalidArgumentException('The Google Fonts stylesheet URL is invalid.');
|
||||
}
|
||||
$response = wp_safe_remote_get($url, ['headers' => ['User-Agent' => $userAgent], 'redirection' => 2, 'timeout' => 15, 'limit_response_size' => \MB_IN_BYTES]);
|
||||
if (is_wp_error($response)) {
|
||||
throw new \RuntimeException($response->get_error_message());
|
||||
}
|
||||
$status = wp_remote_retrieve_response_code($response);
|
||||
if ($status !== 200) {
|
||||
throw new \RuntimeException(sprintf('Google Fonts returned HTTP %d.', $status));
|
||||
}
|
||||
$body = wp_remote_retrieve_body($response);
|
||||
if (!is_string($body) || trim($body) === '') {
|
||||
throw new \RuntimeException('Google Fonts returned an empty stylesheet.');
|
||||
}
|
||||
return $body;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
<?php
|
||||
|
||||
declare (strict_types=1);
|
||||
namespace JooosiFon\Api\Support;
|
||||
|
||||
use JooosiFon\Utils\Common;
|
||||
use JooosiFon\Utils\Upload;
|
||||
/**
|
||||
* Creates font attachments as a unit and can compensate for a later database
|
||||
* failure by deleting attachments created during the current operation.
|
||||
*/
|
||||
final class MediaImportService
|
||||
{
|
||||
/**
|
||||
* @var int[]
|
||||
*/
|
||||
private array $createdAttachmentIds = [];
|
||||
/**
|
||||
* @param string[] $allowedHosts
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function remote(string $url, string $fileName, string $extension, array $allowedHosts = []): array
|
||||
{
|
||||
$this->assertRemoteUrl($url, $allowedHosts);
|
||||
$mime = self::mimeForExtension($extension);
|
||||
$attachmentId = Upload::remote_upload_media($url, $fileName, $mime);
|
||||
return $this->attachmentData($attachmentId, $fileName, $extension, $mime);
|
||||
}
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function binary(string $binary, string $fileName, string $extension): array
|
||||
{
|
||||
$mime = self::mimeForExtension($extension);
|
||||
$attachmentId = Upload::binary_upload_media($binary, $fileName, $mime);
|
||||
return $this->attachmentData($attachmentId, $fileName, $extension, $mime);
|
||||
}
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function local(string $path, string $fileName, string $extension): array
|
||||
{
|
||||
if (!is_file($path) || !is_readable($path)) {
|
||||
throw new \RuntimeException('The source font file is not readable.');
|
||||
}
|
||||
$binary = file_get_contents($path);
|
||||
if (!is_string($binary) || $binary === '') {
|
||||
throw new \RuntimeException('The source font file is empty.');
|
||||
}
|
||||
return $this->binary($binary, $fileName, $extension);
|
||||
}
|
||||
public function commit(): void
|
||||
{
|
||||
$this->createdAttachmentIds = [];
|
||||
}
|
||||
public function rollback(): void
|
||||
{
|
||||
foreach (array_unique($this->createdAttachmentIds) as $attachmentId) {
|
||||
wp_delete_attachment($attachmentId, \true);
|
||||
}
|
||||
$this->createdAttachmentIds = [];
|
||||
}
|
||||
/**
|
||||
* @param array|object $fontFaces
|
||||
* @return int[]
|
||||
*/
|
||||
public static function attachmentIds($fontFaces): array
|
||||
{
|
||||
$ids = [];
|
||||
foreach ((array) $fontFaces as $fontFace) {
|
||||
$files = is_array($fontFace) ? $fontFace['files'] ?? [] : $fontFace->files ?? [];
|
||||
foreach ((array) $files as $file) {
|
||||
$attachmentId = is_array($file) ? $file['attachment_id'] ?? 0 : $file->attachment_id ?? 0;
|
||||
if (is_numeric($attachmentId) && (int) $attachmentId > 0) {
|
||||
$ids[] = (int) $attachmentId;
|
||||
}
|
||||
}
|
||||
}
|
||||
return array_values(array_unique($ids));
|
||||
}
|
||||
/**
|
||||
* @param int[] $attachmentIds
|
||||
*/
|
||||
public static function deleteAttachments(array $attachmentIds): void
|
||||
{
|
||||
foreach (array_unique(array_map('intval', $attachmentIds)) as $attachmentId) {
|
||||
if ($attachmentId > 0) {
|
||||
wp_delete_attachment($attachmentId, \true);
|
||||
}
|
||||
}
|
||||
}
|
||||
public static function mimeForExtension(string $extension): string
|
||||
{
|
||||
$mimes = ['woff2' => 'font/woff2', 'woff' => 'font/woff', 'ttf' => 'font/ttf', 'otf' => 'font/otf', 'eot' => 'font/eot'];
|
||||
$extension = strtolower($extension);
|
||||
if (!isset($mimes[$extension])) {
|
||||
throw new \InvalidArgumentException('Unsupported font file extension.');
|
||||
}
|
||||
return $mimes[$extension];
|
||||
}
|
||||
/**
|
||||
* @param mixed $attachmentId
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function attachmentData($attachmentId, string $fileName, string $extension, string $mime): array
|
||||
{
|
||||
if (is_wp_error($attachmentId)) {
|
||||
throw new \RuntimeException($attachmentId->get_error_message());
|
||||
}
|
||||
if (!is_int($attachmentId) || $attachmentId < 1) {
|
||||
throw new \RuntimeException('The font attachment could not be created.');
|
||||
}
|
||||
$path = get_attached_file($attachmentId);
|
||||
if (!is_string($path) || !is_readable($path)) {
|
||||
wp_delete_attachment($attachmentId, \true);
|
||||
throw new \RuntimeException('The uploaded font attachment is not readable.');
|
||||
}
|
||||
$this->createdAttachmentIds[] = $attachmentId;
|
||||
return ['uid' => Common::random_slug(10), 'attachment_id' => $attachmentId, 'attachment_url' => wp_get_attachment_url($attachmentId), 'extension' => strtolower($extension), 'mime' => $mime, 'file_size' => (int) filesize($path), 'name' => pathinfo($fileName, \PATHINFO_FILENAME)];
|
||||
}
|
||||
/**
|
||||
* @param string[] $allowedHosts
|
||||
*/
|
||||
private function assertRemoteUrl(string $url, array $allowedHosts): void
|
||||
{
|
||||
if (!wp_http_validate_url($url)) {
|
||||
throw new \InvalidArgumentException('The remote font URL is not safe.');
|
||||
}
|
||||
if ($allowedHosts === []) {
|
||||
return;
|
||||
}
|
||||
$host = strtolower((string) wp_parse_url($url, \PHP_URL_HOST));
|
||||
$allowedHosts = array_map('strtolower', $allowedHosts);
|
||||
if (!in_array($host, $allowedHosts, \true)) {
|
||||
throw new \InvalidArgumentException('The remote font URL uses an unapproved host.');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
<?php
|
||||
|
||||
declare (strict_types=1);
|
||||
namespace JooosiFon\Api\Support;
|
||||
|
||||
final class RequestValidator
|
||||
{
|
||||
private const FONT_EXTENSION_ALIASES = ['font/woff2' => 'woff2', 'font/woff' => 'woff', 'font/ttf' => 'ttf', 'font/otf' => 'otf', 'font/eot' => 'eot', 'application/font-woff2' => 'woff2', 'application/font-woff' => 'woff', 'application/x-font-woff2' => 'woff2', 'application/x-font-woff' => 'woff', 'application/x-font-ttf' => 'ttf', 'application/x-font-truetype' => 'ttf', 'application/x-font-opentype' => 'otf', 'application/vnd.ms-opentype' => 'otf', 'application/vnd.ms-fontobject' => 'eot', 'x-font-woff2' => 'woff2', 'x-font-woff' => 'woff', 'x-font-ttf' => 'ttf', 'x-font-opentype' => 'otf', 'vnd.ms-opentype' => 'otf', 'vnd.ms-fontobject' => 'eot', 'truetype' => 'ttf', 'opentype' => 'otf', 'embedded-opentype' => 'eot'];
|
||||
public static function positiveInteger($value): bool
|
||||
{
|
||||
return filter_var($value, \FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]) !== \false;
|
||||
}
|
||||
public static function pageSize($value): bool
|
||||
{
|
||||
return filter_var($value, \FILTER_VALIDATE_INT, ['options' => ['min_range' => 1, 'max_range' => 100]]) !== \false;
|
||||
}
|
||||
public static function boolean($value): bool
|
||||
{
|
||||
return is_bool($value) || in_array($value, [0, 1, '0', '1', 'false', 'true'], \true);
|
||||
}
|
||||
public static function nonEmptyString($value): bool
|
||||
{
|
||||
return is_string($value) && trim($value) !== '';
|
||||
}
|
||||
public static function arrayValue($value): bool
|
||||
{
|
||||
if (!is_array($value)) {
|
||||
return \false;
|
||||
}
|
||||
$encoded = json_encode($value);
|
||||
return is_string($encoded) && strlen($encoded) <= 2 * 1024 * 1024;
|
||||
}
|
||||
public static function positiveIntegerList($value): bool
|
||||
{
|
||||
if (!is_array($value) || $value === [] || count($value) > 50) {
|
||||
return \false;
|
||||
}
|
||||
foreach ($value as $item) {
|
||||
if (!self::positiveInteger($item)) {
|
||||
return \false;
|
||||
}
|
||||
}
|
||||
return \true;
|
||||
}
|
||||
public static function fontType($value): bool
|
||||
{
|
||||
return is_string($value) && in_array($value, ['custom', 'google-fonts', 'adobe-fonts'], \true);
|
||||
}
|
||||
public static function projectId($value): bool
|
||||
{
|
||||
return is_string($value) && preg_match('/^[a-zA-Z0-9_-]{1,100}$/', $value) === 1;
|
||||
}
|
||||
public static function subsets($value): bool
|
||||
{
|
||||
return is_string($value) && ($value === '' || preg_match('/^[a-zA-Z0-9_-]+(?:,[a-zA-Z0-9_-]+)*$/', $value) === 1);
|
||||
}
|
||||
public static function importItem($value): bool
|
||||
{
|
||||
return is_array($value) && isset($value['type'], $value['title'], $value['family'], $value['font_faces'], $value['metadata']) && self::fontType($value['type']) && self::nonEmptyString($value['title']) && self::nonEmptyString($value['family']) && is_string($value['font_faces']) && is_string($value['metadata']) && strlen($value['font_faces']) <= 30 * 1024 * 1024 && strlen($value['metadata']) <= 5 * 1024 * 1024;
|
||||
}
|
||||
public static function googleMetadata($value): bool
|
||||
{
|
||||
if (!is_array($value) || !isset($value['google_fonts']) || !is_array($value['google_fonts'])) {
|
||||
return \false;
|
||||
}
|
||||
$google = $value['google_fonts'];
|
||||
if (!isset($google['font_data'], $google['font_faces'], $google['font_files'], $google['formats'], $google['subsets']) || !is_array($google['font_data']) || !is_array($google['font_faces']) || !is_array($google['font_files']) || !is_array($google['formats']) || !is_array($google['subsets']) || !isset($google['font_data']['family'], $google['font_data']['slug']) || !self::nonEmptyString($google['font_data']['family']) || !self::nonEmptyString($google['font_data']['slug']) || strlen($google['font_data']['family']) > 255 || strlen($google['font_data']['slug']) > 255 || count($google['font_faces']) > 100 || count($google['font_files']) > 500 || count($google['formats']) > 3 || count($google['subsets']) > 50 || $google['formats'] === [] || $google['subsets'] === [] || $google['font_files'] === [] || $google['font_faces'] === []) {
|
||||
return \false;
|
||||
}
|
||||
foreach ($google['formats'] as $format) {
|
||||
if (!in_array($format, ['woff2', 'woff', 'ttf'], \true)) {
|
||||
return \false;
|
||||
}
|
||||
}
|
||||
foreach ($google['subsets'] as $subset) {
|
||||
if (!is_string($subset) || preg_match('/^[a-zA-Z0-9_-]+$/', $subset) !== 1) {
|
||||
return \false;
|
||||
}
|
||||
}
|
||||
foreach ($google['font_files'] as $file) {
|
||||
if (!is_array($file) || !isset($file['uid'], $file['format'], $file['weight'], $file['style'], $file['subsets'], $file['url']) || !self::nonEmptyString($file['uid']) || strlen($file['uid']) > 255 || !in_array($file['format'], ['woff2', 'woff', 'ttf'], \true) || !is_numeric($file['weight']) || !is_string($file['style']) || !is_array($file['subsets']) || count($file['subsets']) > 50 || !filter_var($file['url'], \FILTER_VALIDATE_URL) || strtolower((string) parse_url($file['url'], \PHP_URL_SCHEME)) !== 'https' || strtolower((string) parse_url($file['url'], \PHP_URL_HOST)) !== 'fonts.gstatic.com') {
|
||||
return \false;
|
||||
}
|
||||
foreach ($file['subsets'] as $subset) {
|
||||
if (!is_string($subset) || preg_match('/^[a-zA-Z0-9_-]+$/', $subset) !== 1) {
|
||||
return \false;
|
||||
}
|
||||
}
|
||||
if (array_key_exists('file', $file) && !self::attachmentFile($file['file'])) {
|
||||
return \false;
|
||||
}
|
||||
}
|
||||
$hasEnabledFace = \false;
|
||||
foreach ($google['font_faces'] as $face) {
|
||||
if (!is_array($face) || !array_key_exists('weight', $face) || !array_key_exists('width', $face) || !array_key_exists('style', $face) || !array_key_exists('isEnabled', $face) || !array_key_exists('display', $face) || !array_key_exists('selector', $face) || !array_key_exists('comment', $face) || !array_key_exists('preload', $face) || !is_numeric($face['weight']) || !is_string($face['style']) || !self::boolean($face['isEnabled'])) {
|
||||
return \false;
|
||||
}
|
||||
$hasEnabledFace = $hasEnabledFace || filter_var($face['isEnabled'], \FILTER_VALIDATE_BOOLEAN) === \true;
|
||||
}
|
||||
if (!empty($google['variable']) && (!isset($google['font_data']['axes']) || !is_array($google['font_data']['axes']))) {
|
||||
return \false;
|
||||
}
|
||||
if (!empty($google['variable'])) {
|
||||
if ($google['font_data']['axes'] === [] || count($google['font_data']['axes']) > 20) {
|
||||
return \false;
|
||||
}
|
||||
foreach ($google['font_data']['axes'] as $axis) {
|
||||
if (!is_array($axis) || !isset($axis['tag'], $axis['min'], $axis['max']) || !is_string($axis['tag']) || preg_match('/^[a-zA-Z0-9]{1,10}$/', $axis['tag']) !== 1 || !is_numeric($axis['min']) || !is_numeric($axis['max']) || (float) $axis['min'] > (float) $axis['max']) {
|
||||
return \false;
|
||||
}
|
||||
}
|
||||
}
|
||||
return $hasEnabledFace;
|
||||
}
|
||||
public static function fontFaces($value): bool
|
||||
{
|
||||
if (!is_array($value) || $value === [] || count($value) > 100) {
|
||||
return \false;
|
||||
}
|
||||
foreach ($value as $face) {
|
||||
if (!is_array($face) || !isset($face['id'], $face['weight'], $face['style'], $face['files']) || !self::nonEmptyString($face['id']) || !self::fontWeight($face['weight']) || !is_string($face['style']) || array_key_exists('isEnabled', $face) && !self::boolean($face['isEnabled']) || !is_array($face['files']) || count($face['files']) > 10) {
|
||||
return \false;
|
||||
}
|
||||
foreach ($face['files'] as $file) {
|
||||
if (!self::attachmentFile($file)) {
|
||||
return \false;
|
||||
}
|
||||
}
|
||||
}
|
||||
return \true;
|
||||
}
|
||||
/**
|
||||
* Normalize font file extensions from WordPress MIME subtypes and legacy
|
||||
* payloads before they are persisted.
|
||||
*/
|
||||
public static function sanitizeFontFaces($value): array
|
||||
{
|
||||
if (!is_array($value)) {
|
||||
return (array) $value;
|
||||
}
|
||||
foreach ($value as &$face) {
|
||||
if (!is_array($face) || !isset($face['files']) || !is_array($face['files'])) {
|
||||
continue;
|
||||
}
|
||||
foreach ($face['files'] as &$file) {
|
||||
if (!is_array($file) || !isset($file['extension'])) {
|
||||
continue;
|
||||
}
|
||||
$extension = self::fontExtension($file['extension']);
|
||||
if ($extension !== null) {
|
||||
$file['extension'] = $extension;
|
||||
}
|
||||
}
|
||||
unset($file);
|
||||
}
|
||||
unset($face);
|
||||
return $value;
|
||||
}
|
||||
public static function attachmentFile($value): bool
|
||||
{
|
||||
return is_array($value) && isset($value['attachment_id'], $value['extension']) && self::positiveInteger($value['attachment_id']) && self::fontExtension($value['extension']) !== null;
|
||||
}
|
||||
private static function fontExtension($value): ?string
|
||||
{
|
||||
$extension = strtolower(trim((string) $value));
|
||||
if (in_array($extension, ['woff2', 'woff', 'ttf', 'otf', 'eot'], \true)) {
|
||||
return $extension;
|
||||
}
|
||||
return self::FONT_EXTENSION_ALIASES[$extension] ?? null;
|
||||
}
|
||||
public static function fontWeight($value): bool
|
||||
{
|
||||
if (is_int($value) || is_float($value)) {
|
||||
return $value >= 1 && $value <= 1000;
|
||||
}
|
||||
if (!is_string($value) || preg_match('/^(?:normal|bold|[1-9]\d{0,3})(?:\s+[1-9]\d{0,3})?$/', trim($value)) !== 1) {
|
||||
return \false;
|
||||
}
|
||||
$weights = preg_split('/\s+/', trim($value));
|
||||
if ($weights === \false) {
|
||||
return \false;
|
||||
}
|
||||
foreach ($weights as $weight) {
|
||||
if (is_numeric($weight) && ((int) $weight < 1 || (int) $weight > 1000)) {
|
||||
return \false;
|
||||
}
|
||||
}
|
||||
return \true;
|
||||
}
|
||||
public static function adobeKit($value): bool
|
||||
{
|
||||
if (!is_array($value) || !isset($value['families']) || !is_array($value['families'])) {
|
||||
return \false;
|
||||
}
|
||||
foreach ($value['families'] as $family) {
|
||||
if (!is_array($family) || !isset($family['id'], $family['name'], $family['slug']) || !self::nonEmptyString($family['id']) || !self::nonEmptyString($family['name']) || !self::nonEmptyString($family['slug'])) {
|
||||
return \false;
|
||||
}
|
||||
}
|
||||
return \true;
|
||||
}
|
||||
public static function confirmed($value): bool
|
||||
{
|
||||
return filter_var($value, \FILTER_VALIDATE_BOOLEAN) === \true;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user