Commit inicial powerservice

This commit is contained in:
Gabriel
2026-10-19 12:45:45 -06:00
commit ad85486fe2
10158 changed files with 2736804 additions and 0 deletions
@@ -0,0 +1,131 @@
<?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\Admin;
use JooosiFonDeps\JOOOSI_FON;
use JooosiFon\Plugin;
use JooosiFon\Utils\Common;
use JooosiFon\Utils\Config;
use JooosiFon\Utils\Upload;
use JooosiFonDeps\Nabasa\VitePlus\Assets;
use WP_Query;
class AdminPage
{
public function __construct()
{
add_action('admin_init', fn() => $this->redirect_legacy_page());
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), 1000001);
add_filter('upload_dir', fn($uploads) => $this->upload_dir($uploads), 1000001);
add_action('admin_menu', fn() => $this->add_admin_menu());
if (Config::get('misc.hide_media_library', \false)) {
add_filter('ajax_query_attachments_args', fn(array $query) => $this->ajax_query_attachments_args($query), 1000001);
add_action('load-upload.php', function () {
add_action('pre_get_posts', fn(WP_Query $wpQuery) => $this->load_upload_pre_get_posts($wpQuery), 1000001);
});
}
}
public static function get_page_url(): string
{
return add_query_arg(['page' => JOOOSI_FON::WP_OPTION], admin_url('admin.php'));
}
public static function redirect_to_page(): void
{
Common::redirect(self::get_page_url());
}
public static function add_redirect_submenu_page($root_slug)
{
add_submenu_page($root_slug, __('Jooosi Fon', 'jooosi-fon'), __('Jooosi Fon', 'jooosi-fon'), 'manage_options', 'jooosi-fon-builder-redirect', static fn() => self::redirect_to_page());
}
public function add_admin_menu()
{
$hook = add_menu_page(__('Jooosi Fon', 'jooosi-fon'), __('Jooosi Fon', 'jooosi-fon'), 'manage_options', JOOOSI_FON::WP_OPTION, fn() => $this->render(), 'data:image/svg+xml;base64,' . base64_encode(file_get_contents(dirname(JOOOSI_FON::FILE) . '/jooosi-fon.svg')), 100);
add_action('load-' . $hook, fn() => $this->init_hooks());
}
private function render()
{
add_filter('admin_footer_text', static fn($text) => 'Thank you for using <b>Jooosi Fon</b>! Join us on the <a href="https://www.facebook.com/groups/1142662969627943" target="_blank" rel="noopener noreferrer">Facebook Group</a>.', 1000001);
add_filter('update_footer', static fn($text) => $text . ' | Jooosi Fon ' . JOOOSI_FON::VERSION, 1000001);
echo '<div id="jooosi-fon-app" class=""></div>';
}
/**
* Keep old bookmarks and integration links working during the 2.x rebrand.
*
* @todo Remove this legacy admin-page redirect completely in Jooosi Fon 3.0.0.
*/
private function redirect_legacy_page(): void
{
if (!current_user_can('manage_options') || !isset($_GET['page']) || wp_unslash($_GET['page']) !== JOOOSI_FON::LEGACY_WP_OPTION) {
return;
}
Common::redirect(self::get_page_url(), \true);
}
private function init_hooks()
{
add_action('admin_head', static fn() => remove_action('admin_notices', 'update_nag', 3), 1);
add_action('admin_enqueue_scripts', fn() => $this->enqueue_scripts());
add_action('wp_print_styles', fn() => $this->dequeue_wpml_styles(), \PHP_INT_MAX);
}
/**
* Keep WPML admin styles from leaking into the Jooosi Fon application.
* The application has no WPML-specific UI, and those global styles can
* collide with its utility classes.
*/
private function dequeue_wpml_styles(): void
{
$styles = wp_styles();
foreach ($styles->queue as $handle) {
$style = $styles->registered[$handle] ?? null;
if (!$style) {
continue;
}
$identity = $handle . ' ' . (string) $style->src;
if (preg_match('~sitepress-multilingual-cms|(?:^|[^a-z0-9])(?:wpml|icl)(?:[^a-z0-9]|$)~i', $identity) === 1) {
wp_dequeue_style($handle);
}
}
}
private function enqueue_scripts()
{
wp_enqueue_media();
$handle = JOOOSI_FON::WP_OPTION . ':app';
$assets = new Assets(dirname(JOOOSI_FON::FILE) . '/assets/dist', 'jooosi-fon');
$assets->enqueue('resources/main.tsx', ['handle' => $handle, 'dependencies' => ['wp-i18n'], 'in_footer' => \true]);
wp_set_script_translations($handle, 'jooosi-fon');
wp_localize_script($handle, 'jooosiFon', ['_version' => JOOOSI_FON::VERSION, '_wpnonce' => wp_create_nonce(JOOOSI_FON::WP_OPTION), 'option_namespace' => JOOOSI_FON::WP_OPTION, 'text_domain' => 'jooosi-fon', 'web_history' => self::get_page_url(), 'rest_api' => ['nonce' => wp_create_nonce('wp_rest'), 'root' => esc_url_raw(rest_url()), 'namespace' => JOOOSI_FON::REST_NAMESPACE, 'url' => esc_url_raw(rest_url(JOOOSI_FON::REST_NAMESPACE))], 'assets' => ['url' => $assets->url()], 'lite_edition' => !Plugin::is_pro_edition()]);
}
private function ajax_query_attachments_args(array $query): array
{
if ($query['post_type'] !== 'attachment') {
return $query;
}
if (!isset($_SERVER['HTTP_REFERER']) || strpos($_SERVER['HTTP_REFERER'], 'page=' . JOOOSI_FON::WP_OPTION) === \false) {
$all_mimes = get_allowed_mime_types();
$query['post_mime_type'] = $all_mimes;
}
return $query;
}
private function load_upload_pre_get_posts(WP_Query $wpQuery): void
{
if (!isset($_SERVER['HTTP_REFERER']) || strpos($_SERVER['HTTP_REFERER'], 'page=' . JOOOSI_FON::WP_OPTION) === \false) {
$all_mimes = get_allowed_mime_types();
$wpQuery->set('post_mime_type', $all_mimes);
}
}
private function upload_dir($uploads)
{
if (!isset($_POST['jooosi_fon_font_upload'])) {
return $uploads;
}
return Upload::font_upload_dir($uploads);
}
}
@@ -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;
}
}
@@ -0,0 +1,20 @@
<?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\Builder;
interface BuilderInterface
{
/**
* Get the Builder integration name.
*/
public function get_name(): string;
}
@@ -0,0 +1,67 @@
<?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\Builder\Builderius;
use JooosiFon\Admin\AdminPage;
use JooosiFon\Builder\BuilderInterface;
use JooosiFon\Utils\Font;
/**
* @author Joshua Gugun Siagian <suabahasa@gmail.com>
*
* @todo Built-in Google Fonts are not disabled.
*/
class Main implements BuilderInterface
{
public function __construct()
{
add_action('admin_menu', static fn() => AdminPage::add_redirect_submenu_page('builderius'), 1000001);
add_action('wp_enqueue_scripts', fn() => $this->enqueue_scripts(), 1000001);
}
public function get_name(): string
{
return 'builderius';
}
public function enqueue_scripts()
{
if (!wp_script_is('builderius-builder', 'registered')) {
return;
}
$fonts = Font::get_fonts();
$inline_script_content = <<<JS
const moduleTypography = builderiusBackend.settingsList?.module?.advanced?.typography?.find((item) => item.name === 'font');
if (moduleTypography) {
moduleTypography.options.fontType.values.push('Jooosi Fon');
moduleTypography.options.genericFamily.values['Jooosi Fon'] = ['Jooosi Fon'];
moduleTypography.options.fontFamily.values['Jooosi Fon.Jooosi Fon'] = jooosiFonBuilderiusFonts;
}
const GlobalTypography = builderiusBackend.settingsList?.global?.advanced?.typography?.find((item) => item.name === 'font');
if (GlobalTypography) {
GlobalTypography.options.fontType.values.push('Jooosi Fon');
GlobalTypography.options.genericFamily.values['Jooosi Fon'] = ['Jooosi Fon'];
GlobalTypography.options.fontFamily.values['Jooosi Fon.Jooosi Fon'] = jooosiFonBuilderiusFonts;
}
const templateTypography = builderiusBackend.settingsList?.template?.advanced?.typography?.find((item) => item.name === 'font');
if (templateTypography) {
templateTypography.options.fontType.values.push('Jooosi Fon');
templateTypography.options.genericFamily.values['Jooosi Fon'] = ['Jooosi Fon'];
templateTypography.options.fontFamily.values['Jooosi Fon.Jooosi Fon'] = jooosiFonBuilderiusFonts;
}
JS;
wp_add_inline_script('builderius-builder', 'const jooosiFonBuilderiusFonts = ' . json_encode(array_column($fonts, 'family'), \JSON_THROW_ON_ERROR), 'before');
wp_add_inline_script('builderius-builder', $inline_script_content, 'before');
}
}
@@ -0,0 +1,58 @@
<?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\Builder\ClassicEditor;
use JooosiFon\Builder\BuilderInterface;
use JooosiFon\Core\Cache;
use JooosiFon\Utils\Font;
/**
* Classic Editor integration.
*
* @author Joshua Gugun Siagian <suabahasa@gmail.com>
*/
class Main implements BuilderInterface
{
public function __construct()
{
add_filter('mce_buttons_2', fn($buttons) => $this->filter_mce_buttons($buttons), 1000001);
add_filter('tiny_mce_before_init', fn($mceInit, $editor_id) => $this->filter_tiny_mce($mceInit, $editor_id), 1000001, 2);
add_filter('mce_css', fn($stylesheets) => $this->filter_mce_css($stylesheets), 1000001);
}
public function get_name(): string
{
return 'classic-editor';
}
public function filter_tiny_mce($mceInit, $editor_id)
{
$theme_advanced_fonts = '';
$fonts = Font::get_fonts();
foreach ($fonts as $font) {
$theme_advanced_fonts .= sprintf('[Jooosi Fon] %s=%s;', $font['title'], $font['family']);
}
$mceInit['font_formats'] = $theme_advanced_fonts . 'Andale Mono=andale mono,times; Arial=arial,helvetica,sans-serif; Arial Black=arial black,avant garde; Book Antiqua=book antiqua,palatino; Comic Sans MS=comic sans ms,sans-serif; Courier New=courier new,courier; Georgia=georgia,palatino; Helvetica=helvetica; Impact=impact,chicago; Symbol=symbol; Tahoma=tahoma,arial,helvetica,sans-serif; Terminal=terminal,monaco; Times New Roman=times new roman,times; Trebuchet MS=trebuchet ms,geneva; Verdana=verdana,geneva; Webdings=webdings; Wingdings=wingdings,zapf dingbats';
return $mceInit;
}
public function filter_mce_buttons($buttons)
{
return array_merge($buttons, ['fontsizeselect', 'fontselect']);
}
public function filter_mce_css($stylesheets)
{
$css_url = Cache::get_versioned_cache_url(Cache::CSS_CACHE_FILE);
if (is_array($stylesheets)) {
$stylesheets[] = $css_url;
} else {
$stylesheets .= ',' . $css_url;
}
return $stylesheets;
}
}
@@ -0,0 +1,62 @@
<?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\Builder\Elementor;
use JooosiFon\Admin\AdminPage;
use JooosiFon\Builder\BuilderInterface;
use JooosiFon\Utils\Config;
use JooosiFon\Utils\Font;
/**
* Elementor integration.
*
* @author Joshua Gugun Siagian <suabahasa@gmail.com>
*/
class Main implements BuilderInterface
{
public function __construct()
{
/**
* Disable Elementor's built-in Google Fonts.
*/
if (Config::get('builder_integrations.disable_google_fonts.elementor', \true)) {
add_filter('pre_option_elementor_google_font', static fn($pre_option, $option, $default) => '0', 1000001, 3);
add_filter('pre_update_option_elementor_google_font', static fn($value, $old_value, $option) => '0', 1000001, 3);
}
/**
* Register fonts with 'custom' category for Atomic Widgets compatibility.
* Atomic Widgets (Elementor v4) only supports: system, custom, googlefonts
*/
add_filter('elementor/fonts/additional_fonts', fn($fonts) => $this->filter_elementor_fonts($fonts), 1000001);
add_action('admin_menu', static fn() => AdminPage::add_redirect_submenu_page('elementor'), 1000001);
}
public function get_name(): string
{
return 'elementor';
}
/**
* Register fonts with Elementor.
* Uses 'custom' category for compatibility with both Classic Editor and Atomic Widgets.
*
* @param array $elementor_fonts Existing Elementor fonts.
* @return array Modified fonts array.
*/
public function filter_elementor_fonts($elementor_fonts)
{
$fonts = Font::get_fonts();
foreach ($fonts as $font) {
// Use 'custom' category for Atomic Widgets v4 compatibility
// Atomic Widgets only recognizes: system, custom, googlefonts
$elementor_fonts[$font['family']] = 'custom';
}
return $elementor_fonts;
}
}
@@ -0,0 +1,110 @@
<?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\Builder\GeneratePress;
use JooosiFon\Builder\BuilderInterface;
use JooosiFon\Utils\Font;
/**
* GeneratePress and GenerateBlocks integration.
*
* @author Joshua Gugun Siagian <suabahasa@gmail.com>
*/
class Main implements BuilderInterface
{
public function __construct()
{
/**
* Disable GeneratePress's built-in Google Fonts.
*/
add_filter('generate_font_manager_show_google_fonts', static fn() => \false, 1000001, 0);
/**
* Disable GenerateBlocks's built-in Google Fonts.
*/
add_filter('generateblocks_option_defaults', fn($value) => $this->filter_generateblocks_option_defaults($value), 1000001, 1);
add_filter('option_generateblocks', fn($value, $option) => $this->filter_option_generateblocks($value), 1000001, 2);
/**
* Add custom font to GeneratePress.
* Append the data on the pre_option, and rewrite the data on the option and pre_update_option.
*/
add_filter('generate_option_defaults', fn($opt) => $this->filter_generate_option_defaults($opt), 1000001);
/**
* @deprecated version 2.0.11
* @see https://github.com/tomusborne/generatepress/blob/e7fbf5693bfe4325a41cae988e3eda16550d4025/inc/defaults.php#L412
*/
// add_filter('generate_typography_default_fonts', static fn ($fonts) => array_merge($fonts, array_column(Font::get_fonts(), 'family')), 1_000_001);
/**
* @deprecated version 2.0.46
*/
// add_filter('pre_option_generate_settings', fn ($value, $option) => $this->generate_settings($value), 1_000_001, 2);
// add_filter('option_generate_settings', fn ($value, $option) => $this->generate_settings($value), 1_000_001, 2);
// add_filter('pre_update_option_generate_settings', fn ($value, $old_value, $option) => $this->generate_settings($value), 1_000_001, 3);
/**
* Add custom font to GenerateBlocks.
*
* @see https://github.com/tomusborne/generateblocks/issues/937
*/
add_filter('generateblocks_typography_font_family_list', fn($fonts) => $this->generateblocks_typography_font_family_list($fonts), 1000001);
}
public function get_name(): string
{
return 'generate-press';
}
public function generate_settings($opt)
{
$fonts = Font::get_fonts();
if (!is_array($opt)) {
$opt = [];
}
if (!array_key_exists('font_manager', $opt) || !is_array($opt['font_manager'])) {
$opt['font_manager'] = [];
}
foreach ($fonts as $font) {
if (!in_array($font['family'], array_column($opt['font_manager'], 'fontFamily'), \true)) {
$opt['font_manager'][] = ['fontFamily' => $font['family'], 'googleFont' => \false, 'googleFontApi' => 0];
}
}
return $opt;
}
public function filter_generateblocks_option_defaults($opt)
{
if (is_array($opt)) {
$opt['disable_google_fonts'] = \true;
}
return $opt;
}
public function filter_option_generateblocks($opt)
{
if (is_array($opt)) {
$opt['disable_google_fonts'] = \true;
}
return $opt;
}
public function generateblocks_typography_font_family_list($gb_fonts)
{
$fonts = Font::get_fonts();
$jooosi_fonts = array_map(static fn($f) => ['label' => $f['title'], 'value' => $f['family']], $fonts);
return array_merge([['label' => 'Jooosi Fon', 'options' => $jooosi_fonts]], is_array($gb_fonts) ? $gb_fonts : iterator_to_array($gb_fonts));
}
public function filter_generate_option_defaults($opt)
{
$fonts = Font::get_fonts();
if (!array_key_exists('font_manager', $opt) || !is_array($opt['font_manager'])) {
$opt['font_manager'] = [];
}
foreach ($fonts as $font) {
if (!in_array($font['family'], array_column($opt['font_manager'], 'fontFamily'), \true)) {
$opt['font_manager'][] = ['fontFamily' => $font['family'], 'googleFont' => \false, 'googleFontApi' => 0];
}
}
return $opt;
}
}
@@ -0,0 +1,141 @@
<?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\Builder\Gutenberg;
use JooosiFonDeps\JOOOSI_FON;
use JooosiFon\Builder\BuilderInterface;
use JooosiFon\Core\Cache;
use JooosiFon\Core\Frontpage;
use JooosiFon\Utils\Config;
use JooosiFon\Utils\Font;
use WP_Theme_JSON;
use WP_Theme_JSON_Data;
/**
* Gutenberg integration.
*
* @see https://developer.wordpress.org/block-editor/how-to-guides/themes/theme-json/
* @see https://developer.wordpress.org/block-editor/reference-guides/theme-json-reference/theme-json-living/
* @see https://developer.wordpress.org/themes/advanced-topics/theme-json/
* @see https://make.wordpress.org/core/2022/10/10/filters-for-theme-json-data/
* @see https://make.wordpress.org/core/2021/09/28/implementing-a-webfonts-api-in-wordpress-core/
*
* @author Joshua Gugun Siagian <suabahasa@gmail.com>
*/
class Main implements BuilderInterface
{
public function __construct()
{
add_filter('wp_theme_json_data_theme', fn($theme_json) => $this->filter_theme_json_data_theme($theme_json), 1000001);
add_filter('f!jooosi/fon/core/cache:build_css.append_content', fn($css, $rows) => $this->filter_append_build_css_content($css, $rows), 1000001, 2);
add_filter('f!jooosi/fon/core/cache:build_css.append_content', fn($css, $rows) => $this->filter_ensure_block_editor($css, $rows), 1000001, 2);
// add_action('enqueue_block_editor_assets', fn () => $this->enqueue_block_editor_assets(), 1_000_001);
// add_action('after_setup_theme', fn () => $this->after_setup_theme(), 1_000_001);
add_action('enqueue_block_assets', fn() => $this->enqueue_block_assets(), 1000001);
}
public function get_name(): string
{
return 'gutenberg';
}
/**
* @see https://make.wordpress.org/core/2022/10/10/filters-for-theme-json-data/
* @param WP_Theme_JSON_Data $theme_json
* @return WP_Theme_JSON_Data
*/
public function filter_theme_json_data_theme($theme_json)
{
$theme_json_data = $theme_json->get_data();
$theme_json_font_families = $theme_json_data['settings']['typography']['fontFamilies']['theme'] ?? [];
$font_family_presets = [];
foreach (Font::get_fonts() as $font) {
/**
* @see https://www.w3.org/TR/CSS22/syndata.html#value-def-identifier
*/
$font_family_presets[] = ['name' => $font['title'], 'slug' => Font::slugify($font['family']), 'fontFamily' => Font::css_variable($font['family'])];
}
$new_data = ['version' => WP_Theme_JSON::LATEST_SCHEMA, 'settings' => ['typography' => ['fontFamilies' => self::merge_font_family_presets($theme_json_font_families, $font_family_presets)]]];
return $theme_json->update_with($new_data);
}
public function enqueue_block_editor_assets()
{
$screen = get_current_screen();
if (is_admin() && $screen->is_block_editor()) {
add_action('admin_head', static function () {
add_filter('f!jooosi/fon/api/setting/option:index_options', static function ($options) {
Config::propertyAccessor()->setValue($options, 'cache.inline_print', \false);
return $options;
}, 1000001);
Frontpage::enqueue_css_cache();
}, 1000001);
}
}
public function after_setup_theme()
{
// Add support for editor styles.
add_theme_support('editor-styles');
add_editor_style(Cache::get_versioned_cache_url(Cache::CSS_CACHE_FILE));
}
public function enqueue_block_assets()
{
if (is_admin() && file_exists(Cache::get_cache_path(Cache::CSS_CACHE_FILE))) {
$handle = JOOOSI_FON::WP_OPTION . '-cache';
$version = Cache::get_cache_version(Cache::CSS_CACHE_FILE) ?? JOOOSI_FON::VERSION;
wp_enqueue_style($handle, Cache::get_cache_url(Cache::CSS_CACHE_FILE), [], $version);
}
}
/**
* ensure the css file is loaded to the block editor, template editor, or site editor
*/
public function filter_ensure_block_editor($css, $rows): string
{
return $css . ".wp-block, .editor-styles-wrapper { } \n\n";
}
/**
* Support for a non block-based theme.
*/
public function filter_append_build_css_content($css, $rows)
{
if (function_exists('wp_is_block_theme') && wp_is_block_theme()) {
return $css;
}
return $css . self::non_block_based_theme_support_classes();
}
public static function non_block_based_theme_support_classes(): string
{
$inline_css = '';
$fonts = Font::get_fonts();
foreach ($fonts as $font) {
$inline_css .= sprintf(".has-%s-font-family {\n", Font::slugify($font['family']));
$inline_css .= sprintf("\tfont-family: %s !important;\n", Font::css_variable($font['family']));
$inline_css .= "}\n\n";
}
return $inline_css;
}
private static function merge_font_family_presets(array $existing, array $incoming): array
{
$merged = [];
$positions = [];
foreach (array_merge($existing, $incoming) as $preset) {
$slug = is_array($preset) && isset($preset['slug']) && is_string($preset['slug']) ? $preset['slug'] : '';
if ($slug === '') {
$merged[] = $preset;
continue;
}
if (isset($positions[$slug])) {
$merged[$positions[$slug]] = $preset;
continue;
}
$positions[$slug] = count($merged);
$merged[] = $preset;
}
return array_values($merged);
}
}
@@ -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\Builder;
use JooosiFonDeps\JOOOSI_FON;
use ReflectionClass;
use JooosiFonDeps\Symfony\Component\Finder\Finder;
/**
* @todo Remove all legacy Yabe Webfont hook shims completely in Jooosi Fon 3.0.0.
*/
class Integration
{
private static int $registered_count = 0;
/**
* List of Builders services.
*
* @var BuilderInterface[]
*/
private array $builders = [];
public function __construct()
{
$this->scan_builders();
$this->register_builders();
}
public function scan_builders()
{
// Get cached Builders
$transient_name = 'jooosi_fon_scanned_builders_' . JOOOSI_FON::VERSION;
/** @var BuilderInterface[]|false $cached */
$cached = get_transient($transient_name);
if ($cached !== \false) {
$this->builders = $cached;
return;
}
$finder = new Finder();
$finder->files()->in(__DIR__)->name('*.php');
/**
* Add additional places to scan for Builders integration.
*
* @param Finder $finder The Finder instance.
*/
do_action('a!jooosi/fon/builder/integration:before_scan', $finder);
do_action_deprecated('a!yabe/webfont/builder/integration:before_scan', [$finder], '2.1.0', 'a!jooosi/fon/builder/integration:before_scan');
foreach ($finder as $file) {
$builder_file = $file->getPathname();
if (!is_readable($builder_file)) {
continue;
}
require_once $builder_file;
}
// Find any Builders integration that extends BuilderInterface class
$declared_classes = get_declared_classes();
foreach ($declared_classes as $declared_class) {
if (!class_exists($declared_class)) {
continue;
}
$reflector = new ReflectionClass($declared_class);
if (!$reflector->isSubclassOf(\JooosiFon\Builder\BuilderInterface::class)) {
continue;
}
// Get Builders integration detail and push to Integration::$builders to be register later
/** @var BuilderInterface $builder */
$builder = $reflector->newInstanceWithoutConstructor();
$this->builders[$builder->get_name()] = ['name' => $builder->get_name(), 'file_path' => $reflector->getFileName(), 'class_name' => $reflector->getName()];
}
// Cache the Builders
set_transient($transient_name, $this->builders, \DAY_IN_SECONDS);
}
/**
* Register Builders.
*/
public function register_builders(): void
{
/**
* Filter the Builders before register.
*
* @param BuilderInterface[] $builders
* @return BuilderInterface[]
*/
/** @var BuilderInterface[] $builders */
$builders = apply_filters('f!jooosi/fon/builder/integration:register_builders', $this->builders);
$builders = apply_filters_deprecated('f!yabe/webfont/builder/integration:register_builders', [$builders], '2.1.0', 'f!jooosi/fon/builder/integration:register_builders');
self::$registered_count = count($builders);
foreach ($builders as $builder) {
// Create new instance of Builder class
/** @var BuilderInterface $builderInstance */
$builderInstance = new $builder['class_name']();
$this->builders[$builder['name']]['instance'] = $builderInstance;
}
}
public static function get_registered_count(): int
{
return self::$registered_count;
}
}
@@ -0,0 +1,79 @@
<?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\Builder\Kadence;
use JooosiFonDeps\JOOOSI_FON;
use JooosiFon\Builder\BuilderInterface;
use JooosiFon\Utils\Font;
/**
* Kadence integration.
*
* @author Joshua Gugun Siagian <suabahasa@gmail.com>
*/
class Main implements BuilderInterface
{
public function __construct()
{
add_filter('kadence_theme_custom_fonts', fn($fonts) => $this->theme_custom_fonts($fonts), 1000001);
add_action('enqueue_block_editor_assets', fn() => $this->register_block_editor_assets(), 1000001);
/**
* Disable Kadence's built-in Google Fonts.
*/
add_action('customize_controls_enqueue_scripts', fn() => $this->action_theme_customizer_google_fonts(), 1000001);
add_action('customize_preview_init', fn() => $this->action_theme_customizer_preview(), 1000001);
add_action('enqueue_block_editor_assets', fn() => $this->block_editor_remove_google_fonts(), 1000001);
}
public function get_name(): string
{
return 'kadence';
}
public function action_theme_customizer_google_fonts()
{
if (wp_script_is('kadence-customizer-controls', 'registered')) {
wp_add_inline_script('kadence-customizer-controls', 'kadenceCustomizerControlsData.gfontvars = [];', 'before');
}
}
public function action_theme_customizer_preview()
{
if (wp_script_is('kadence-webfont-js', 'registered')) {
wp_dequeue_script('kadence-webfont-js');
}
}
public function block_editor_remove_google_fonts()
{
if (wp_script_is('kadence-blocks-js', 'registered')) {
wp_add_inline_script('kadence-blocks-js', 'kadence_blocks_params.g_fonts = [];', 'before');
wp_add_inline_script('kadence-blocks-js', 'kadence_blocks_params.g_font_names = [];', 'before');
}
}
public function register_block_editor_assets()
{
if (wp_script_is('kadence-blocks-js', 'registered')) {
$jooosi_fonts = [];
$fonts = Font::get_fonts();
foreach ($fonts as $font) {
$jooosi_fonts[] = ['label' => $font['title'], 'value' => $font['family'], 'google' => \false, 'weights' => [['value' => '100', 'label' => 'Thin 100'], ['value' => '200', 'label' => 'Extra-Light 200'], ['value' => '300', 'label' => 'Light 300'], ['value' => '400', 'label' => 'Regular'], ['value' => '500', 'label' => 'Medium 500'], ['value' => '600', 'label' => 'Semi-Bold 600'], ['value' => '700', 'label' => 'Bold 700'], ['value' => '800', 'label' => 'Extra-Bold 800'], ['value' => '900', 'label' => 'Ultra-Bold 900']], 'styles' => [['value' => 'normal', 'label' => 'Normal'], ['value' => 'italic', 'label' => 'Italic']]];
}
wp_enqueue_script('jooosi-fon-for-kadence-blocks', plugin_dir_url(__FILE__) . 'assets/script/kadence-blocks.js', ['kadence-blocks-js'], JOOOSI_FON::VERSION, \true);
wp_localize_script('jooosi-fon-for-kadence-blocks', 'jooosiFonKadenceBlocks', ['fonts' => $jooosi_fonts]);
}
}
public function theme_custom_fonts($kadence_fonts)
{
$fonts = Font::get_fonts();
$v = ['100', '100italic', '200', '200italic', '300', '300italic', 'regular', 'italic', '500', '500italic', '600', '600italic', '700', '700italic', '800', '800italic', '900', '900italic'];
foreach ($fonts as $font) {
$kadence_fonts[$font['family']] = ['v' => $v];
}
return $kadence_fonts;
}
}
@@ -0,0 +1,15 @@
function jooosi_fon_add_fonts(options) {
const { __ } = wp.i18n;
const jooosi_fonts = [
{
type: 'group',
label: __('Jooosi Fon', 'jooosi-fon'),
options: jooosiFonKadenceBlocks.fonts,
},
];
options = jooosi_fonts.concat(options);
return options;
}
wp.hooks.addFilter('kadence.typography_options', 'jooosi/fon/add_fonts', jooosi_fon_add_fonts);
@@ -0,0 +1,44 @@
<?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\Builder\Pinegrow;
use JooosiFonDeps\JOOOSI_FON;
use JooosiFon\Admin\AdminPage;
use JooosiFon\Builder\BuilderInterface;
use JooosiFon\Core\Cache;
use JooosiFon\Utils\Font;
/**
* Pinegrow integration.
*
* @author Joshua Gugun Siagian <suabahasa@gmail.com>
*/
class Main implements BuilderInterface
{
public function __construct()
{
add_action('admin_menu', static fn() => AdminPage::add_redirect_submenu_page('pinegrow-projects'), 1000001);
add_action('load-toplevel_page_pinegrow-projects', fn() => $this->init_hooks());
}
public function get_name(): string
{
return 'pinegrow';
}
public function init_hooks(): void
{
add_action('admin_enqueue_scripts', fn() => $this->enqueue_scripts(), 1000001);
}
public function enqueue_scripts()
{
wp_enqueue_script('jooosi-fon-for-pinegrow', plugin_dir_url(__FILE__) . 'assets/script/pinegrow.js', [], JOOOSI_FON::VERSION, \true);
wp_localize_script('jooosi-fon-for-pinegrow', 'jooosiFonPinegrow', ['stylesheet_url' => Cache::get_versioned_cache_url(Cache::CSS_CACHE_FILE), 'font_families' => array_map(static fn($f) => ['name' => $f['title'], 'key' => $f['css']['variable'], 'family' => $f['family']], Font::get_fonts())]);
}
}
@@ -0,0 +1,81 @@
document.addEventListener('DOMContentLoaded', async function () {
await new Promise(resolve => {
let waitingForEditor = setInterval(() => {
if (
window.frames[0].pinegrow?.getSelectedPage() !== null
&& window.frames[0].pinegrow?.getSelectedPage() !== undefined
) {
clearInterval(waitingForEditor);
resolve();
}
}, 3000);
});
// add stylesheet
window.frames[0].pinegrow.getSelectedPage().addStylesheet(window.jooosiFonPinegrow.stylesheet_url);
// style tab
await new Promise(resolve => {
let waitingForFontFamily = setInterval(() => {
try {
if (
window.frames[0].$.fn.crsa.defaults.rulesDefinition.sections.text.fields['font-family'] !== null
&& window.frames[0].$.fn.crsa.defaults.rulesDefinition.sections.text.fields['font-family'] !== undefined
) {
clearInterval(waitingForFontFamily);
resolve();
}
} catch (err) { }
}, 100);
});
window.frames[0].$.fn.crsa.defaults.rulesDefinition.sections.text.fields['font-family'].options = function () {
return window.jooosiFonPinegrow.font_families || [];
};
// design tab
await new Promise(resolve => {
let waitingForFontLibrary = setInterval(() => {
try {
if (
window.frames[0].pinegrow.fontLibrary !== null
&& window.frames[0].pinegrow.fontLibrary !== undefined
) {
clearInterval(waitingForFontLibrary);
resolve();
}
} catch (err) { }
}, 100);
});
const preservedSystemFonts = [];
window.frames[0].pinegrow.fontLibrary.forEachFont(font => {
if (font.type === 'system') {
preservedSystemFonts.push(font);
}
});
const fontSystemClass = window.frames[0].pinegrow.fontLibrary.getFontClassForType('system');
window.frames[0].pinegrow.fontLibrary.removeAll();
window.jooosiFonPinegrow.font_families.forEach(font => {
const pfs = new fontSystemClass({
type: 'system',
family: font.family,
usage: 'all',
category: 'sans-serif',
w: '100, 200, 300, 400, 500, 600, 700, 800, 900'.split(/,\s?/)
});
window.frames[0].pinegrow.fontLibrary.addFont(pfs);
});
preservedSystemFonts.forEach(font => {
window.frames[0].pinegrow.fontLibrary.addFont(font);
});
window.frames[0].pinegrow.fontLibrary.save();
});
@@ -0,0 +1,419 @@
<?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\Core;
use JooosiFonDeps\JOOOSI_FON;
use JooosiFon\Core\Cache\FontCacheSnapshotBuilder;
use JooosiFon\Core\Cache\FontCssRenderer;
use JooosiFon\Core\Cache\FontPreloadRenderer;
use JooosiFon\Upgrade\LegacyRebrandUpgrade;
use JooosiFon\Utils\Common;
use JooosiFon\Utils\Config;
use JooosiFon\Utils\Notice;
/**
* Manage the cache of fonts for the frontpage.
*
* @author Joshua Gugun Siagian <suabahasa@gmail.com>
* @todo Remove all legacy Yabe Webfont hook shims completely in Jooosi Fon 3.0.0.
*/
class Cache
{
/**
* @var string
*/
public const CSS_CACHE_FILE = 'fonts.css';
/**
* @var string
*/
public const PRELOAD_HTML_FILE = 'preload.html';
/**
* @var string
*/
public const CACHE_DIR = '/jooosi-fon/cache/';
/**
* @var string
*/
public static $typekit_embed = 'css';
public function __construct()
{
$this->migrate_legacy_scheduled_cache();
add_action('a!jooosi/fon/core/cache:build_cache', fn() => $this->build_cache());
// listen to fonts event for cache build (async/scheduled)
add_action('a!jooosi/fon/api/font:fonts_event_async', fn() => $this->schedule_cache(), 10, 1);
// listen to fonts event for cache build (sync)
add_action('a!jooosi/fon/api/font:fonts_event', fn() => $this->build_cache(), 10, 1);
// listen to theme switch for cache build (async/scheduled)
add_action('switch_theme', fn() => $this->schedule_cache(), 1000001);
// listen to Config change for cache build (async/scheduled)
add_action('f!jooosi/fon/api/setting/option:after_store', fn() => $this->schedule_cache(), 10, 1);
// listen to plugin upgrade for cache build (async/scheduled)
add_action('a!jooosi/fon/plugins:upgrade_plugin_end', fn() => $this->schedule_cache(), 10, 1);
$this->maybeRebuildAfterLegacyUpgrade();
}
public function schedule_cache(): void
{
self::updateBuildStatus(['state' => 'pending', 'requested_at' => time(), 'changed' => \false, 'warnings' => [], 'error' => '']);
if (!wp_next_scheduled('a!jooosi/fon/core/cache:build_cache')) {
$scheduled = wp_schedule_single_event(time() + 10, 'a!jooosi/fon/core/cache:build_cache');
if ($scheduled === \false) {
self::updateBuildStatus(['state' => 'failed', 'error' => 'The cache build could not be scheduled.', 'completed_at' => time()]);
}
}
}
public static function get_cache_path(string $file_path = ''): string
{
return wp_upload_dir()['basedir'] . self::CACHE_DIR . $file_path;
}
public static function get_cache_url(string $file_path = ''): string
{
return wp_upload_dir()['baseurl'] . self::CACHE_DIR . $file_path;
}
public static function get_versioned_cache_url(string $filePath): string
{
$url = self::get_cache_url($filePath);
$version = self::get_cache_version($filePath);
return $version !== null ? add_query_arg('ver', $version, $url) : $url;
}
public static function get_cache_version(string $filePath): ?string
{
$path = self::get_cache_path($filePath);
if (!is_readable($path)) {
return null;
}
$hash = hash_file('sha256', $path);
return is_string($hash) ? substr($hash, 0, 16) : null;
}
public function build_cache(): void
{
try {
$lock = $this->acquireBuildLock();
} catch (\Throwable $throwable) {
$message = sprintf('Failed to start the font cache build: %s', $throwable->getMessage());
self::updateBuildStatus(['state' => 'failed', 'completed_at' => time(), 'changed' => \false, 'warnings' => [], 'error' => $message]);
Notice::error($message, 'jooosi-fon-cache-build', \true);
return;
}
if ($lock === \false) {
return;
}
self::updateBuildStatus(['state' => 'running', 'started_at' => time(), 'changed' => \false, 'warnings' => [], 'error' => '']);
try {
$artifacts = self::buildArtifacts();
$payload = sprintf("/*\n! %s v%s | %s\n*/\n\n%s", Common::plugin_data('Name'), JOOOSI_FON::VERSION, date('Y-m-d H:i:s', time()), $artifacts['css']);
$cssPath = self::get_cache_path(self::CSS_CACHE_FILE);
$preloadPath = self::get_cache_path(self::PRELOAD_HTML_FILE);
self::publishArtifacts($payload, $artifacts['preload'], $cssPath, $preloadPath);
$this->purge_cache_plugin();
self::updateBuildStatus(['state' => 'succeeded', 'completed_at' => time(), 'hash' => hash('sha256', $payload . "\x00" . $artifacts['preload']), 'changed' => \true, 'warnings' => $artifacts['warnings'], 'error' => '']);
do_action('a!jooosi/fon/core/cache:build_succeeded', \true, $artifacts['warnings']);
} catch (\Throwable $throwable) {
$message = sprintf('Failed to build the font cache: %s', $throwable->getMessage());
self::updateBuildStatus(['state' => 'failed', 'completed_at' => time(), 'changed' => \false, 'warnings' => [], 'error' => $message]);
Notice::error($message, 'jooosi-fon-cache-build', \true);
do_action('a!jooosi/fon/core/cache:build_failed', $throwable);
} finally {
flock($lock, \LOCK_UN);
fclose($lock);
}
}
public static function build_css(): string
{
return self::buildArtifacts()['css'];
}
public static function build_preload(): string
{
return self::buildArtifacts()['preload'];
}
public static function get_kit_css($kit_id, ?array &$warnings = null): string
{
$kitId = trim((string) $kit_id);
if (preg_match('/^[a-zA-Z0-9_-]{1,100}$/', $kitId) !== 1) {
self::adobeWarning($warnings, 'Adobe Fonts CSS was skipped because the project ID is invalid.');
return '';
}
$cachePath = self::get_cache_path('adobe/' . hash('sha256', $kitId) . '.css');
$cachedCss = is_readable($cachePath) ? file_get_contents($cachePath) : \false;
$cachedCss = is_string($cachedCss) ? $cachedCss : '';
if (!self::isSafeStylesheet($cachedCss)) {
$cachedCss = '';
}
$ttl = max(300, (int) apply_filters('f!jooosi/fon/core/cache:adobe_css_ttl', 12 * \HOUR_IN_SECONDS));
if ($cachedCss !== '' && filemtime($cachePath) > time() - $ttl) {
return $cachedCss;
}
$response = wp_safe_remote_get(sprintf('https://use.typekit.net/%s.css', rawurlencode($kitId)), ['timeout' => 15, 'redirection' => 2, 'limit_response_size' => 2 * \MB_IN_BYTES]);
if (is_wp_error($response)) {
return self::adobeFallback($cachedCss, $warnings, 'Adobe Fonts could not be refreshed.');
}
$status = wp_remote_retrieve_response_code($response);
if ($status === 412) {
self::$typekit_embed = 'js';
return '';
}
if ($status !== 200) {
return self::adobeFallback($cachedCss, $warnings, sprintf('Adobe Fonts returned HTTP %d.', $status));
}
$body = wp_remote_retrieve_body($response);
if (!is_string($body) || !self::isSafeStylesheet($body)) {
return self::adobeFallback($cachedCss, $warnings, 'Adobe Fonts returned an invalid stylesheet.');
}
try {
self::publishArtifact($body, $cachePath);
} catch (\Throwable $throwable) {
self::adobeWarning($warnings, 'Adobe Fonts CSS was refreshed but could not be cached separately.');
}
return $body;
}
public static function get_kit_js($kit_id): string
{
$kitId = trim((string) $kit_id);
if (preg_match('/^[a-zA-Z0-9_-]{1,100}$/', $kitId) !== 1) {
return '';
}
$response = wp_safe_remote_get(sprintf('https://use.typekit.net/%s.js', rawurlencode($kitId)), ['timeout' => 15, 'redirection' => 2, 'limit_response_size' => 2 * \MB_IN_BYTES]);
if (is_wp_error($response) || wp_remote_retrieve_response_code($response) !== 200) {
return '';
}
$body = wp_remote_retrieve_body($response);
if (!is_string($body) || trim($body) === '') {
return '';
}
$js = '<script type="text/javascript">';
$js .= $body;
$js .= "\n\n";
$js .= sprintf('try{Typekit.load({kitId:%s,scriptTimeout:3E3,async:true});}catch(e){}', wp_json_encode($kitId));
$js .= '</script>';
return "\n\n" . $js . "\n\n";
}
/**
* @return array<string, mixed>
*/
public static function getBuildStatus(): array
{
$status = get_option(JOOOSI_FON::WP_OPTION . '_cache_build_status', []);
return is_array($status) ? $status : [];
}
/**
* @return array{css: string, preload: string, warnings: string[]}
*/
private static function buildArtifacts(): array
{
self::$typekit_embed = 'css';
$snapshot = (new FontCacheSnapshotBuilder())->build();
$warnings = $snapshot['warnings'];
$adobeCss = '';
$projectId = trim((string) Config::get('adobe_fonts.project_id', ''));
$hasAdobeFonts = in_array('adobe-fonts', array_column($snapshot['fonts'], 'type'), \true);
if ($projectId !== '' && $hasAdobeFonts) {
$adobeCss = self::get_kit_css($projectId, $warnings);
}
$css = (new FontCssRenderer())->render($snapshot['fonts'], $adobeCss);
/**
* @param string $css The CSS content
* @param array $rows The active database rows
* @return string The CSS content
*/
$css = apply_filters('f!jooosi/fon/core/cache:build_css.append_content', $css, $snapshot['rows']);
$css = apply_filters_deprecated('f!yabe/webfont/core/cache:build_css.append_content', [$css, $snapshot['rows']], '2.1.0', 'f!jooosi/fon/core/cache:build_css.append_content');
if (!is_string($css)) {
throw new \UnexpectedValueException('The font CSS filter must return a string.');
}
$preloadLimit = (int) apply_filters('f!jooosi/fon/core/cache:preload_limit', 6);
$preload = (new FontPreloadRenderer())->render($snapshot['fonts'], $preloadLimit);
if (self::$typekit_embed === 'js' && $projectId !== '' && $hasAdobeFonts) {
$preload .= self::get_kit_js($projectId);
}
foreach ($warnings as $warning) {
do_action('a!jooosi/fon/core/cache:build_warning', $warning);
}
return ['css' => $css, 'preload' => $preload, 'warnings' => array_values(array_unique($warnings))];
}
/**
* @return resource|false
*/
private function acquireBuildLock()
{
$directory = self::get_cache_path();
if (!is_dir($directory) && !wp_mkdir_p($directory)) {
throw new \RuntimeException('The font cache directory could not be created.');
}
$lock = fopen($directory . '.build.lock', 'c');
if ($lock === \false) {
throw new \RuntimeException('The font cache build lock could not be opened.');
}
if (!flock($lock, \LOCK_EX | \LOCK_NB)) {
fclose($lock);
return \false;
}
return $lock;
}
private static function publishArtifacts(string $css, string $preload, string $cssPath, string $preloadPath): void
{
$cssTemp = self::stageArtifact($css, $cssPath);
$preloadTemp = null;
try {
$preloadTemp = self::stageArtifact($preload, $preloadPath);
if (!rename($preloadTemp, $preloadPath)) {
throw new \RuntimeException('The font preload cache could not be published.');
}
$preloadTemp = null;
if (!rename($cssTemp, $cssPath)) {
throw new \RuntimeException('The font CSS cache could not be published.');
}
$cssTemp = null;
} finally {
if (is_string($cssTemp) && file_exists($cssTemp)) {
unlink($cssTemp);
}
if (is_string($preloadTemp) && file_exists($preloadTemp)) {
unlink($preloadTemp);
}
}
}
private static function publishArtifact(string $contents, string $path): void
{
$temporaryPath = self::stageArtifact($contents, $path);
try {
if (!rename($temporaryPath, $path)) {
throw new \RuntimeException('The cache artifact could not be published.');
}
$temporaryPath = null;
} finally {
if (is_string($temporaryPath) && file_exists($temporaryPath)) {
unlink($temporaryPath);
}
}
}
private static function stageArtifact(string $contents, string $path): string
{
$directory = dirname($path);
if (!is_dir($directory) && !wp_mkdir_p($directory)) {
throw new \RuntimeException('The cache artifact directory could not be created.');
}
$temporaryPath = tempnam($directory, '.jooosi-fon-');
if (!is_string($temporaryPath)) {
throw new \RuntimeException('A temporary cache artifact could not be created.');
}
$written = file_put_contents($temporaryPath, $contents, \LOCK_EX);
if ($written === \false || $written !== strlen($contents)) {
unlink($temporaryPath);
throw new \RuntimeException('A cache artifact could not be written completely.');
}
$permissions = defined('FS_CHMOD_FILE') ? \FS_CHMOD_FILE : 0644;
chmod($temporaryPath, $permissions);
return $temporaryPath;
}
/**
* @param array<string, mixed> $status
*/
private static function updateBuildStatus(array $status): void
{
update_option(JOOOSI_FON::WP_OPTION . '_cache_build_status', array_merge(self::getBuildStatus(), $status), \false);
}
private static function adobeWarning(?array &$warnings, string $message): void
{
if ($warnings !== null && count($warnings) < 100) {
$warnings[] = $message;
}
}
private static function adobeFallback(string $cachedCss, ?array &$warnings, string $message): string
{
if ($cachedCss === '') {
throw new \RuntimeException($message . ' No cached stylesheet is available.');
}
self::adobeWarning($warnings, $message . ' The last-known-good stylesheet was retained.');
return $cachedCss;
}
private static function isSafeStylesheet(string $css): bool
{
return trim($css) !== '' && stripos($css, '</style') === \false;
}
/**
* @todo Remove this legacy cron migration completely in Jooosi Fon 3.0.0.
*/
private function migrate_legacy_scheduled_cache(): void
{
$legacyHook = 'a!yabe/webfont/core/cache:build_cache';
$hook = 'a!jooosi/fon/core/cache:build_cache';
$legacyTimestamp = wp_next_scheduled($legacyHook);
if ($legacyTimestamp === \false) {
return;
}
if (!wp_next_scheduled($hook)) {
wp_schedule_single_event(max(time() + 1, $legacyTimestamp), $hook);
}
wp_clear_scheduled_hook($legacyHook);
}
/**
* Rebuild generated files immediately after upload paths have moved so a
* frontend request never prints cache content containing legacy URLs.
*
* @todo Remove this legacy cache rebuild completely in Jooosi Fon 3.0.0.
*/
private function maybeRebuildAfterLegacyUpgrade(): void
{
if (get_option(LegacyRebrandUpgrade::CACHE_REBUILD_OPTION, \false) === \false) {
return;
}
self::updateBuildStatus(['state' => 'pending', 'requested_at' => time(), 'changed' => \false, 'warnings' => [], 'error' => '']);
$this->build_cache();
if ((self::getBuildStatus()['state'] ?? null) === 'succeeded') {
delete_option(LegacyRebrandUpgrade::CACHE_REBUILD_OPTION);
}
}
/**
* Clear the cache from various cache plugins.
*/
private function purge_cache_plugin()
{
/**
* Only invalidate this plugin's font catalog. Flushing the complete
* WordPress object cache can create a site-wide performance spike.
* @see https://developer.wordpress.org/reference/classes/wp_object_cache/
*/
\wp_cache_delete('get_fonts', JOOOSI_FON::WP_OPTION);
do_action('a!jooosi/fon/core/cache:before_page_cache_purge');
/**
* WP Rocket
* @see https://docs.wp-rocket.me/article/92-rocketcleandomain
*/
if (function_exists('rocket_clean_domain')) {
\rocket_clean_domain();
}
/**
* WP Super Cache
* @see https://github.com/Automattic/wp-super-cache/blob/a0872032b1b3fc6847f490eadfabf74c12ad0135/wp-cache-phase2.php#L3013
*/
if (function_exists('wp_cache_clear_cache')) {
\wp_cache_clear_cache();
}
/**
* W3 Total Cache
* @see https://github.com/BoldGrid/w3-total-cache/blob/3a094493064ea60d727b3389dee813639860ef49/w3-total-cache-api.php#L259
*/
if (function_exists('w3tc_flush_all')) {
\w3tc_flush_all();
}
/**
* WP Fastest Cache
* @see https://www.wpfastestcache.com/tutorial/delete-the-cache-by-calling-the-function/
*/
if (function_exists('wpfc_clear_all_cache')) {
\wpfc_clear_all_cache(\true);
}
/**
* LiteSpeed Cache
* @see https://docs.litespeedtech.com/lscache/lscwp/api/#purge-all-existing-caches
*/
do_action('litespeed_purge_all');
}
}
@@ -0,0 +1,204 @@
<?php
declare (strict_types=1);
namespace JooosiFon\Core\Cache;
use JooosiFon\Api\Support\FontCodec;
use JooosiFon\Database\FontTable;
use JooosiFon\Utils\Font;
/**
* Reads active font records once and converts them into a safe, predictable
* representation shared by the stylesheet and preload renderers.
*/
final class FontCacheSnapshotBuilder
{
/**
* @return array{fonts: array<int, array<string, mixed>>, rows: array<int, object>, warnings: string[]}
*/
public function build(): array
{
global $wpdb;
// Cache generation may be the first request after a failed update.
// Ensure the table exists even when migration history is stale.
FontTable::ensure();
$rows = $wpdb->get_results("\n SELECT id, type, family, metadata, font_faces\n FROM {$wpdb->prefix}jooosi_fon_fonts\n WHERE status = 1\n AND deleted_at IS NULL\n ORDER BY type ASC, family ASC, id ASC\n ");
if ($wpdb->last_error) {
throw new \RuntimeException($wpdb->last_error);
}
if (!is_array($rows)) {
throw new \RuntimeException('The active font records could not be loaded.');
}
$fonts = [];
$warnings = [];
foreach ($rows as $row) {
try {
$metadata = FontCodec::decode((string) $row->metadata, \true);
$fontFaces = FontCodec::decode((string) $row->font_faces, \true);
} catch (\Throwable $throwable) {
$this->warn($warnings, sprintf('Font #%d was skipped because its stored payload is invalid.', (int) $row->id));
continue;
}
if (!is_array($metadata) || !is_array($fontFaces)) {
$this->warn($warnings, sprintf('Font #%d was skipped because its stored payload has an invalid shape.', (int) $row->id));
continue;
}
$family = trim((string) $row->family);
if ($family === '' || preg_match('//u', $family) !== 1) {
$this->warn($warnings, sprintf('Font #%d was skipped because its family name is missing or invalid.', (int) $row->id));
continue;
}
[$selector, $fallback] = $this->fontSelector((string) ($metadata['selector'] ?? ''));
$faces = [];
foreach ($fontFaces as $faceIndex => $fontFace) {
if (!is_array($fontFace)) {
$this->warn($warnings, sprintf('Font #%d face #%d was skipped because it is invalid.', (int) $row->id, (int) $faceIndex + 1));
continue;
}
if (array_key_exists('isEnabled', $fontFace) && filter_var($fontFace['isEnabled'], \FILTER_VALIDATE_BOOLEAN) !== \true) {
continue;
}
$normalizedFace = $this->normalizeFace($fontFace, (int) $row->id, (int) $faceIndex, $warnings);
if ($normalizedFace !== null) {
$faces[] = $normalizedFace;
}
}
if ($faces === [] && $row->type !== 'adobe-fonts') {
$this->warn($warnings, sprintf('Font #%d was skipped because it has no usable font files.', (int) $row->id));
continue;
}
$fonts[] = ['id' => (int) $row->id, 'type' => (string) $row->type, 'family' => $family, 'custom_property' => Font::css_custom_property($family), 'legacy_custom_property' => Font::legacy_css_custom_property($family), 'display' => $this->display((string) ($metadata['display'] ?? 'auto'), 'auto'), 'preload' => filter_var($metadata['preload'] ?? \false, \FILTER_VALIDATE_BOOLEAN), 'selector' => $selector, 'fallback' => $fallback, 'faces' => $faces];
}
return ['fonts' => $fonts, 'rows' => $rows, 'warnings' => $warnings];
}
/**
* @param array<string, mixed> $face
* @param string[] $warnings
* @return array<string, mixed>|null
*/
private function normalizeFace(array $face, int $fontId, int $faceIndex, array &$warnings): ?array
{
$files = [];
$seenExtensions = [];
foreach ((array) ($face['files'] ?? []) as $file) {
if (!is_array($file)) {
continue;
}
$extension = strtolower((string) ($file['extension'] ?? ''));
$attachmentId = (int) ($file['attachment_id'] ?? 0);
$mime = $this->mime($extension);
if ($attachmentId < 1 || $mime === null || isset($seenExtensions[$extension])) {
continue;
}
$url = wp_get_attachment_url($attachmentId);
if (!is_string($url) || $url === '') {
$this->warn($warnings, sprintf('Font #%d face #%d references a missing attachment.', $fontId, $faceIndex + 1));
continue;
}
$seenExtensions[$extension] = \true;
$files[] = ['attachment_id' => $attachmentId, 'url' => $url, 'extension' => $extension, 'mime' => $mime, 'format' => $this->format($extension)];
}
if ($files === []) {
$this->warn($warnings, sprintf('Font #%d face #%d was skipped because it has no usable files.', $fontId, $faceIndex + 1));
return null;
}
usort($files, static function (array $left, array $right): int {
$precedence = ['woff2' => 1, 'woff' => 2, 'ttf' => 3, 'otf' => 4, 'eot' => 5];
return $precedence[$left['extension']] <=> $precedence[$right['extension']];
});
return ['weight' => $this->weight($face['weight'] ?? 400), 'width' => $this->width($face['width'] ?? '100%'), 'style' => $this->style((string) ($face['style'] ?? 'normal')), 'display' => $this->display((string) ($face['display'] ?? ''), ''), 'selector' => $this->selector((string) ($face['selector'] ?? '')), 'comment' => $this->comment((string) ($face['comment'] ?? '')), 'unicode_range' => $this->unicodeRange((string) ($face['unicodeRange'] ?? '')), 'preload' => filter_var($face['preload'] ?? \false, \FILTER_VALIDATE_BOOLEAN), 'files' => $files];
}
/**
* @return array{0: string, 1: string}
*/
private function fontSelector(string $value): array
{
$parts = array_map('trim', explode('|', $value, 2));
$selector = $this->selector($parts[0] ?? '');
$fallback = trim($parts[1] ?? '');
if ($fallback !== '' && (strlen($fallback) > 500 || preg_match('/[^a-zA-Z0-9\s,_\'"-]/', $fallback) !== 0 || substr_count($fallback, "'") % 2 !== 0 || substr_count($fallback, '"') % 2 !== 0)) {
$fallback = '';
}
return [$selector, $fallback];
}
private function selector(string $value): string
{
$value = trim($value);
if ($value === '' || strlen($value) > 1000 || preg_match('/[<{};@]|\/\*|\*\/|[\x00-\x08\x0B\x0C\x0E-\x1F]/', $value) !== 0) {
return '';
}
return $value;
}
private function comment(string $value): string
{
$value = trim(str_replace(['/*', '*/', '<'], ['', '* /', '\3C '], $value));
return strlen($value) <= 500 ? $value : substr($value, 0, 500);
}
private function style(string $value): string
{
$value = trim(strtolower($value));
return preg_match('/^(?:normal|italic|oblique(?:\s+-?\d+(?:\.\d+)?deg(?:\s+-?\d+(?:\.\d+)?deg)?)?)$/', $value) ? $value : 'normal';
}
/**
* @param mixed $value
*/
private function weight($value): string
{
$value = trim((string) $value);
if (in_array($value, ['normal', 'bold'], \true)) {
return $value;
}
if (preg_match('/^[1-9]\d{0,3}(?:\s+[1-9]\d{0,3})?$/', $value) !== 1) {
return '400';
}
foreach (preg_split('/\s+/', $value) ?: [] as $weight) {
if ((int) $weight < 1 || (int) $weight > 1000) {
return '400';
}
}
return $value;
}
/**
* @param mixed $value
*/
private function width($value): string
{
$value = trim((string) $value);
$keywords = ['normal', 'ultra-condensed', 'extra-condensed', 'condensed', 'semi-condensed', 'semi-expanded', 'expanded', 'extra-expanded', 'ultra-expanded'];
if (in_array($value, $keywords, \true) || preg_match('/^\d+(?:\.\d+)?%(?:\s+\d+(?:\.\d+)?%)?$/', $value) === 1) {
return $value;
}
return '100%';
}
private function display(string $value, string $fallback): string
{
$value = strtolower(trim($value));
return in_array($value, ['auto', 'block', 'swap', 'fallback', 'optional'], \true) ? $value : $fallback;
}
private function unicodeRange(string $value): string
{
$value = trim($value);
if ($value === '') {
return '';
}
return preg_match('/^U\+[0-9A-F?]{1,6}(?:-[0-9A-F]{1,6})?(?:\s*,\s*U\+[0-9A-F?]{1,6}(?:-[0-9A-F]{1,6})?)*$/i', $value) ? $value : '';
}
private function mime(string $extension): ?string
{
$mimes = ['woff2' => 'font/woff2', 'woff' => 'font/woff', 'ttf' => 'font/ttf', 'otf' => 'font/otf', 'eot' => 'font/eot'];
return $mimes[$extension] ?? null;
}
private function format(string $extension): string
{
$formats = ['ttf' => 'truetype', 'otf' => 'opentype', 'eot' => 'embedded-opentype'];
return $formats[$extension] ?? $extension;
}
/**
* @param string[] $warnings
*/
private function warn(array &$warnings, string $message): void
{
if (count($warnings) < 100) {
$warnings[] = $message;
}
}
}
@@ -0,0 +1,82 @@
<?php
declare (strict_types=1);
namespace JooosiFon\Core\Cache;
/**
* Pure renderer for an already validated font-cache snapshot.
*
* @phpstan-type CacheFile array{attachment_id: int, url: string, extension: string, mime: string, format: string}
* @phpstan-type CacheFace array{weight: string, width: string, style: string, display: string, selector: string, comment: string, unicode_range: string, preload: bool, files: array<int, CacheFile>}
* @phpstan-type CacheFont array{id: int, type: string, family: string, custom_property: string, legacy_custom_property: string, display: string, preload: bool, selector: string, fallback: string, faces: array<int, CacheFace>}
*/
final class FontCssRenderer
{
/**
* @param array<int, CacheFont> $fonts
*/
public function render(array $fonts, string $adobeCss = ''): string
{
$css = trim($adobeCss);
$css = $css !== '' ? $css . "\n\n" : '';
foreach ($fonts as $font) {
foreach ($font['faces'] as $face) {
if ($face['files'] === []) {
continue;
}
if ($face['comment'] !== '') {
$css .= sprintf("/* %s */\n", $face['comment']);
}
$sources = array_map(function (array $file): string {
return sprintf("url('%s') format('%s')", $this->escapeString($file['url']), $this->escapeString($file['format']));
}, $face['files']);
$display = $face['display'] !== '' ? $face['display'] : $font['display'];
$css .= "@font-face {\n";
$css .= sprintf("\tfont-family: '%s';\n", $this->escapeString($font['family']));
$css .= sprintf("\tfont-style: %s;\n", $face['style']);
$css .= sprintf("\tfont-weight: %s;\n", $face['weight']);
$css .= sprintf("\tfont-stretch: %s;\n", $face['width']);
$css .= sprintf("\tfont-display: %s;\n", $display);
$css .= sprintf("\tsrc: %s;\n", implode(",\n\t\t", $sources));
if ($face['unicode_range'] !== '') {
$css .= sprintf("\tunicode-range: %s;\n", $face['unicode_range']);
}
$css .= "}\n\n";
}
}
$variables = [];
foreach ($fonts as $font) {
$fallback = $font['fallback'] !== '' ? ', ' . $font['fallback'] : '';
$variables[$font['custom_property']] = ['legacy_property' => $font['legacy_custom_property'], 'value' => sprintf("'%s'%s", $this->escapeString($font['family']), $fallback)];
}
if ($variables !== []) {
$css .= ":root {\n";
foreach ($variables as $property => $variable) {
$css .= sprintf("\t%s: %s;\n", $property, $variable['value']);
// TODO: Remove this legacy CSS property alias completely in Jooosi Fon 3.0.0.
$css .= sprintf("\t%s: var(%s);\n", $variable['legacy_property'], $property);
}
$css .= "}\n\n";
}
foreach ($fonts as $font) {
if ($font['selector'] !== '') {
$css .= sprintf("%s {\n\tfont-family: var(%s);\n}\n\n", $font['selector'], $font['custom_property']);
}
foreach ($font['faces'] as $face) {
if ($face['selector'] === '') {
continue;
}
$css .= sprintf("%s {\n", $face['selector']);
$css .= sprintf("\tfont-family: var(%s);\n", $font['custom_property']);
$css .= sprintf("\tfont-style: %s;\n", $face['style']);
$css .= sprintf("\tfont-weight: %s;\n", $face['weight']);
$css .= "}\n\n";
}
}
return $css;
}
private function escapeString(string $value): string
{
return str_replace(['\\', "'", '<', "\r", "\n", "\f"], ['\\\\', "\\'", '\3C ', '\D ', '\A ', '\C '], $value);
}
}
@@ -0,0 +1,47 @@
<?php
declare (strict_types=1);
namespace JooosiFon\Core\Cache;
/**
* Pure renderer for the bounded set of critical WOFF2 preload resources.
*
* @phpstan-type CacheFile array{attachment_id: int, url: string, extension: string, mime: string, format: string}
* @phpstan-type CacheFace array{weight: string, width: string, style: string, display: string, selector: string, comment: string, unicode_range: string, preload: bool, files: array<int, CacheFile>}
* @phpstan-type CacheFont array{id: int, type: string, family: string, custom_property: string, legacy_custom_property: string, display: string, preload: bool, selector: string, fallback: string, faces: array<int, CacheFace>}
*/
final class FontPreloadRenderer
{
/**
* @param array<int, CacheFont> $fonts
*/
public function render(array $fonts, int $limit = 6): string
{
$limit = max(0, min(50, $limit));
if ($limit === 0) {
return '';
}
$resources = [];
foreach ($fonts as $font) {
foreach ($font['faces'] as $face) {
if (!$font['preload'] && !$face['preload']) {
continue;
}
foreach ($face['files'] as $file) {
if ($file['mime'] !== 'font/woff2') {
continue;
}
$resources[$file['url']] = $file['mime'];
if (count($resources) >= $limit) {
break 3;
}
}
}
}
$html = '';
foreach ($resources as $url => $mime) {
$html .= sprintf('<link rel="preload" href="%s" as="font" type="%s" crossorigin>' . \PHP_EOL, htmlspecialchars($url, \ENT_QUOTES | \ENT_SUBSTITUTE, 'UTF-8'), htmlspecialchars($mime, \ENT_QUOTES | \ENT_SUBSTITUTE, 'UTF-8'));
}
return $html;
}
}
@@ -0,0 +1,161 @@
<?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\Core;
use JooosiFonDeps\JOOOSI_FON;
use JooosiFon\Utils\Config;
use JooosiFon\Utils\Debug;
/**
* Serve the font on the frontpage.
*
* @author Joshua Gugun Siagian <suabahasa@gmail.com>
* @todo Remove the legacy Yabe Webfont hook shim completely in Jooosi Fon 3.0.0.
*/
final class Frontpage
{
/**
* @var string[]
*/
private array $preload_script_handles = [];
/**
* @var array<int, array<string, string>>
*/
private array $preload_resources = [];
private bool $print_preload_resources = \false;
public function __construct()
{
/**
* @see wp-includes\default-filters.php for the priority.
*/
add_action('wp_head', fn() => $this->append_header(), 1000001);
add_filter('wp_preload_resources', fn($resources) => $this->preload($resources));
add_action('wp_enqueue_scripts', fn() => $this->disable_user_google_fonts(), 1000001);
}
public static function enqueue_css_cache()
{
if (defined('JooosiFonDeps\JOOOSI_FON_CSS_CACHE_WAS_LOADED')) {
return;
}
Debug::stopwatch()->start(sprintf('%s::%s', self::class, __FUNCTION__));
if (file_exists(\JooosiFon\Core\Cache::get_cache_path(\JooosiFon\Core\Cache::CSS_CACHE_FILE))) {
$handle = JOOOSI_FON::WP_OPTION . '-cache';
$version = \JooosiFon\Core\Cache::get_cache_version(\JooosiFon\Core\Cache::CSS_CACHE_FILE) ?? JOOOSI_FON::VERSION;
if (Config::get('cache.inline_print', \false)) {
$css = file_get_contents(\JooosiFon\Core\Cache::get_cache_path(\JooosiFon\Core\Cache::CSS_CACHE_FILE));
if ($css !== \false) {
wp_register_style($handle, \false, [], null);
wp_add_inline_style($handle, $css);
}
} else {
wp_register_style($handle, \JooosiFon\Core\Cache::get_cache_url(\JooosiFon\Core\Cache::CSS_CACHE_FILE), [], $version);
}
do_action('a!jooosi/fon/core/frontpage:before_print_style');
do_action_deprecated('a!yabe/webfont/core/frontpage:before_print_style', [], '2.1.0', 'a!jooosi/fon/core/frontpage:before_print_style');
wp_enqueue_style($handle);
wp_print_styles($handle);
}
define('JooosiFonDeps\JOOOSI_FON_CSS_CACHE_WAS_LOADED', \true);
Debug::stopwatch()->stop(sprintf('%s::%s', self::class, __FUNCTION__));
}
/**
* Append the header to the frontpage.
*/
private function append_header()
{
if (function_exists('wp_preload_resources')) {
$this->print_preload_resources = \true;
wp_preload_resources();
$this->print_preload_resources = \false;
} else {
$this->preload([]);
}
self::enqueue_css_cache();
if ($this->preload_script_handles !== []) {
wp_print_scripts($this->preload_script_handles);
}
}
/**
* Preload the fonts file on the frontpage.
*/
private function preload($resources)
{
if (defined('JooosiFonDeps\JOOOSI_FON_PRELOAD_HTML_WAS_LOADED') && !$this->print_preload_resources) {
return $resources;
}
if (!defined('JooosiFonDeps\JOOOSI_FON_PRELOAD_HTML_WAS_LOADED')) {
Debug::stopwatch()->start(sprintf('%s::%s', self::class, __FUNCTION__));
if (file_exists(\JooosiFon\Core\Cache::get_cache_path(\JooosiFon\Core\Cache::PRELOAD_HTML_FILE))) {
$preload_html = file_get_contents(\JooosiFon\Core\Cache::get_cache_path(\JooosiFon\Core\Cache::PRELOAD_HTML_FILE));
if ($preload_html !== \false) {
preg_match_all('/<link\b[^>]*>/i', $preload_html, $link_tags);
foreach ($link_tags[0] as $link_tag) {
$rel = $this->get_attribute($link_tag, 'rel');
$href = $this->get_attribute($link_tag, 'href');
if (strtolower((string) $rel) !== 'preload' || $href === null) {
continue;
}
$resource = ['href' => $href];
foreach (['as', 'type', 'media', 'fetchpriority'] as $attribute) {
$value = $this->get_attribute($link_tag, $attribute);
if ($value !== null) {
$resource[$attribute] = $value;
}
}
if (stripos($link_tag, ' crossorigin') !== \false) {
$resource['crossorigin'] = '';
}
$this->preload_resources[] = $resource;
}
preg_match_all('/<script\b[^>]*>(.*?)<\/script>/is', $preload_html, $script_tags);
foreach ($script_tags[1] as $script) {
$script = trim($script);
if ($script === '') {
continue;
}
$handle = sprintf('%s-preload-%s', JOOOSI_FON::WP_OPTION, md5($script));
wp_register_script($handle, \false, [], null, \false);
wp_add_inline_script($handle, $script);
$this->preload_script_handles[] = $handle;
}
}
}
define('JooosiFonDeps\JOOOSI_FON_PRELOAD_HTML_WAS_LOADED', \true);
Debug::stopwatch()->stop(sprintf('%s::%s', self::class, __FUNCTION__));
}
return $this->print_preload_resources ? $this->preload_resources : $resources;
}
private function get_attribute(string $tag, string $attribute): ?string
{
$pattern = sprintf('/\b%s\s*=\s*([\'\"])(.*?)\1/is', preg_quote($attribute, '/'));
if (preg_match($pattern, $tag, $matches)) {
return html_entity_decode($matches[2], \ENT_QUOTES, 'UTF-8');
}
return null;
}
/**
* Scan and disable Google Fonts API that loaded manually by the theme or plugin through `wp_enqueue_style` function.
*/
private function disable_user_google_fonts()
{
$is_disable = Config::get('misc.disable_user_google_fonts', \false);
if (!$is_disable) {
return;
}
global $wp_styles;
foreach ($wp_styles->queue as $q) {
if ($wp_styles->registered[$q]->src && strpos($wp_styles->registered[$q]->src, 'fonts.googleapis.com') !== \false) {
wp_dequeue_style($q);
wp_deregister_style($q);
}
}
}
}
@@ -0,0 +1,23 @@
<?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\Core;
/**
* @author Joshua Gugun Siagian <suabahasa@gmail.com>
*/
class Runtime
{
public function __construct()
{
new \JooosiFon\Core\Frontpage();
}
}
@@ -0,0 +1,100 @@
<?php
declare (strict_types=1);
namespace JooosiFon\Database;
use RuntimeException;
/**
* Keeps the font library table available while the plugin is being rebranded.
*
* The migration history can survive an incomplete update, so table presence
* must not be inferred from a recorded migration version alone.
*/
final class FontTable
{
public static function migrateLegacy(): void
{
global $wpdb;
$legacyTable = self::legacyTable();
$table = self::table();
if (!self::exists($table)) {
if (self::exists($legacyTable)) {
self::rename($legacyTable, $table);
} else {
self::createTable($table);
}
} elseif (self::exists($legacyTable)) {
$columns = '`id`, `type`, `status`, `title`, `slug`, `family`, `metadata`, `font_faces`, `created_at`, `updated_at`, `deleted_at`';
if ($wpdb->query("INSERT IGNORE INTO `{$table}` ({$columns}) SELECT {$columns} FROM `{$legacyTable}`") === \false) {
throw new RuntimeException($wpdb->last_error ?: 'Unable to merge the legacy Jooosi Fon fonts table.');
}
}
self::assertExists($table);
}
/**
* Ensure the current table exists without merging a legacy table that has
* already been handled by the rebrand migration.
*/
public static function ensure(): void
{
$table = self::table();
if (self::exists($table)) {
return;
}
$legacyTable = self::legacyTable();
if (self::exists($legacyTable)) {
self::rename($legacyTable, $table);
} else {
self::createTable($table);
}
self::assertExists($table);
}
public static function create(): void
{
self::createTable(self::table());
}
public static function exists(?string $table = null): bool
{
global $wpdb;
$table = $table ?? self::table();
$foundTable = $wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $wpdb->esc_like($table)));
return is_string($foundTable) && $foundTable === $table;
}
private static function rename(string $legacyTable, string $table): void
{
global $wpdb;
if ($wpdb->query("RENAME TABLE `{$legacyTable}` TO `{$table}`") === \false) {
throw new RuntimeException($wpdb->last_error ?: 'Unable to rename the Jooosi Fon fonts table.');
}
}
private static function createTable(string $table): void
{
global $wpdb;
if (!function_exists('dbDelta') && defined('ABSPATH')) {
require_once \ABSPATH . 'wp-admin/includes/upgrade.php';
}
if (!function_exists('dbDelta')) {
throw new RuntimeException('The WordPress database upgrade API is unavailable.');
}
$collation = $wpdb->has_cap('collation') ? $wpdb->get_charset_collate() : '';
$sql = "CREATE TABLE `{$table}` (\n `id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,\n `type` VARCHAR(50) NOT NULL DEFAULT 'custom',\n `status` INT(1) NOT NULL DEFAULT 0,\n `title` VARCHAR(255) NOT NULL,\n `slug` VARCHAR(255) NOT NULL,\n `family` VARCHAR(255),\n `metadata` TEXT,\n `font_faces` TEXT,\n `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,\n `updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,\n `deleted_at` DATETIME DEFAULT NULL,\n PRIMARY KEY (`id`)\n ) {$collation};";
dbDelta($sql);
}
private static function assertExists(string $table): void
{
global $wpdb;
if (!self::exists($table)) {
throw new RuntimeException($wpdb->last_error ?: 'Unable to create the Jooosi Fon fonts table.');
}
}
private static function table(): string
{
global $wpdb;
return $wpdb->prefix . 'jooosi_fon_fonts';
}
private static function legacyTable(): string
{
global $wpdb;
return $wpdb->prefix . 'yabe_webfont_fonts';
}
}
@@ -0,0 +1,54 @@
<?php
declare (strict_types=1);
namespace JooosiFon\Database\Migration;
use JooosiFon\Database\Migration\Exception\AbortMigration;
use JooosiFon\Database\Migration\Exception\SkipMigration;
/**
* Base class for Jooosi Fon schema migrations.
*/
abstract class AbstractMigration
{
public function getDescription(): string
{
return '';
}
public function abortIf(bool $condition, string $message = 'Unknown reason'): void
{
if ($condition) {
throw new AbortMigration($message);
}
}
public function skipIf(bool $condition, string $message = 'Unknown reason'): void
{
if ($condition) {
throw new SkipMigration($message);
}
}
public function preUp(): void
{
}
public function postUp(): void
{
}
public function preDown(): void
{
}
public function postDown(): void
{
}
abstract public function up(): void;
public function down(): void
{
$this->abortIf(\true, sprintf('No down() migration implemented for "%s".', static::class));
}
protected function collation(): string
{
global $wpdb;
if (!$wpdb->has_cap('collation')) {
return '';
}
return $wpdb->get_charset_collate();
}
}
@@ -0,0 +1,8 @@
<?php
declare (strict_types=1);
namespace JooosiFon\Database\Migration\Exception;
final class AbortMigration extends \JooosiFon\Database\Migration\Exception\MigrationException
{
}
@@ -0,0 +1,9 @@
<?php
declare (strict_types=1);
namespace JooosiFon\Database\Migration\Exception;
use RuntimeException;
class MigrationException extends RuntimeException
{
}
@@ -0,0 +1,8 @@
<?php
declare (strict_types=1);
namespace JooosiFon\Database\Migration\Exception;
final class SkipMigration extends \JooosiFon\Database\Migration\Exception\MigrationException
{
}
@@ -0,0 +1,63 @@
<?php
declare (strict_types=1);
namespace JooosiFon\Database\Migration;
use WP_CLI_Command;
use function WP_CLI\Utils\format_items;
/**
* WP-CLI commands for Jooosi Fon migrations.
*/
final class MigrationCommand extends WP_CLI_Command
{
private \JooosiFon\Database\Migration\MigrationManager $manager;
public function __construct(\JooosiFon\Database\Migration\MigrationManager $manager)
{
$this->manager = $manager;
}
/**
* Generate a migration stub.
*
* ## OPTIONS
*
* [--table-name=<table-name>]
* : Optionally prefill a create/drop table migration.
*
* @when wp_loaded
*
* @param array<int, string> $args
* @param array<string, mixed> $assocArgs
*/
public function generate(array $args, array $assocArgs): void
{
$tableName = isset($assocArgs['table-name']) ? sanitize_key((string) $assocArgs['table-name']) : null;
$path = $this->manager->generate($tableName);
\WP_CLI::success(sprintf('Generated migration: %s', $path));
}
/**
* List discovered migrations and their execution state.
*
* @param array<int, string> $args
* @param array<string, mixed> $assocArgs
*/
public function list(array $args, array $assocArgs): void
{
format_items('table', $this->manager->list(), ['version', 'executed_at', 'execution_time', 'executed']);
}
/**
* Run all pending migrations.
*
* @param array<int, string> $args
* @param array<string, mixed> $assocArgs
*/
public function run(array $args, array $assocArgs): void
{
$executed = $this->manager->execute();
if ($executed === []) {
\WP_CLI::success('No pending migrations.');
return;
}
format_items('table', $executed, ['version', 'executed_at', 'execution_time']);
\WP_CLI::success(sprintf('%d migration(s) executed.', count($executed)));
}
}
@@ -0,0 +1,52 @@
<?php
declare (strict_types=1);
namespace JooosiFon\Database\Migration;
/**
* Immutable configuration for the plugin's migration subsystem.
*/
final class MigrationConfiguration
{
private string $tableName;
private string $namespace;
private string $directory;
private string $basePath;
private string $commandNamespace;
/**
* @param array<string, string> $configuration
*/
public function __construct(array $configuration = [])
{
$configuration = array_merge(['tableName' => 'jooosi_fon_migrations', 'namespace' => 'JooosiFon\Migrations', 'directory' => 'migrations', 'basePath' => dirname(__DIR__, 3), 'commandNamespace' => 'jooosi-fon migrations'], $configuration);
$this->tableName = $configuration['tableName'];
$this->namespace = trim($configuration['namespace'], '\\');
$this->directory = trim($configuration['directory'], \DIRECTORY_SEPARATOR);
$this->basePath = rtrim($configuration['basePath'], \DIRECTORY_SEPARATOR);
$this->commandNamespace = $configuration['commandNamespace'];
}
public function tableName(): string
{
return $this->tableName;
}
public function namespace(): string
{
return $this->namespace;
}
public function directory(): string
{
return $this->directory;
}
public function basePath(): string
{
return $this->basePath;
}
public function migrationsPath(): string
{
return $this->basePath . \DIRECTORY_SEPARATOR . $this->directory;
}
public function commandNamespace(): string
{
return $this->commandNamespace;
}
}
@@ -0,0 +1,21 @@
<?php
declare (strict_types=1);
namespace JooosiFon\Database\Migration;
/**
* Metadata for a discovered migration.
*/
final class MigrationDefinition
{
public string $version;
public string $className;
public string $description;
public function __construct(string $className, string $description)
{
// Existing installations store the fully-qualified class name as the version.
$this->version = $className;
$this->className = $className;
$this->description = $description;
}
}
@@ -0,0 +1,91 @@
<?php
declare (strict_types=1);
namespace JooosiFon\Database\Migration;
use DateTimeImmutable;
use DateTimeZone;
use RuntimeException;
/**
* Generates migration stubs for WP-CLI.
*/
final class MigrationGenerator
{
private \JooosiFon\Database\Migration\MigrationConfiguration $configuration;
public function __construct(\JooosiFon\Database\Migration\MigrationConfiguration $configuration)
{
$this->configuration = $configuration;
}
public function generate(?string $tableName = null): string
{
$className = 'Version' . (new DateTimeImmutable('now', new DateTimeZone('UTC')))->format('YmdHis');
$directory = $this->configuration->migrationsPath();
$path = $directory . \DIRECTORY_SEPARATOR . $className . '.php';
if (!is_dir($directory) && !wp_mkdir_p($directory)) {
throw new RuntimeException(sprintf('Unable to create migrations directory "%s".', $directory));
}
if (file_exists($path)) {
throw new RuntimeException(sprintf('Migration file "%s" already exists.', $path));
}
$code = $this->stub($className, $tableName);
if (file_put_contents($path, $code, \LOCK_EX) === \false) {
throw new RuntimeException(sprintf('Unable to write migration file "%s".', $path));
}
return $path;
}
private function stub(string $className, ?string $tableName): string
{
$up = '';
$down = '';
if ($tableName !== null && $tableName !== '') {
$up = sprintf(<<<'PHP'
$sql = "CREATE TABLE `{$wpdb->prefix}%s` (
`id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`id`)
) {$this->collation()};";
dbDelta($sql);
PHP
, $tableName);
$down = sprintf(<<<'PHP'
$wpdb->query("DROP TABLE IF EXISTS `{$wpdb->prefix}%s`");
PHP
, $tableName);
}
return sprintf(<<<'PHP'
<?php
declare(strict_types=1);
namespace %s;
use JooosiFon\Database\Migration\AbstractMigration;
/**
* Auto-generated migration. Update the description and implementation.
*/
final class %s extends AbstractMigration
{
public function getDescription(): string
{
return '';
}
public function up(): void
{
global $wpdb;
%s
}
public function down(): void
{
global $wpdb;
%s
}
}
PHP
, $this->configuration->namespace(), $className, $up, $down);
}
}
@@ -0,0 +1,80 @@
<?php
declare (strict_types=1);
namespace JooosiFon\Database\Migration;
use RuntimeException;
/**
* Moves legacy migration history to the current table and namespace.
*
* @todo Remove this legacy rebrand upgrader completely in Jooosi Fon 3.0.0.
*/
final class MigrationHistoryUpgrader
{
public function upgrade(string $legacyTableName, string $tableName, string $legacyNamespace, string $namespace): void
{
global $wpdb;
$legacyTable = $wpdb->prefix . $legacyTableName;
$table = $wpdb->prefix . $tableName;
$legacyTableExists = $this->tableExists($legacyTable);
$tableExists = $this->tableExists($table);
if ($legacyTableExists && !$tableExists) {
$this->renameTable($legacyTable, $table);
$tableExists = \true;
} elseif ($legacyTableExists) {
$this->mergeTables($legacyTable, $table);
$this->dropTable($legacyTable);
}
if ($tableExists) {
$this->migrateNamespace($table, $legacyNamespace, $namespace);
}
}
private function renameTable(string $legacyTable, string $table): void
{
global $wpdb;
if ($wpdb->query("RENAME TABLE `{$legacyTable}` TO `{$table}`") === \false) {
throw new RuntimeException($wpdb->last_error ?: 'Unable to rename the Jooosi Fon migrations table.');
}
}
private function mergeTables(string $legacyTable, string $table): void
{
global $wpdb;
$merged = $wpdb->query("INSERT IGNORE INTO `{$table}` (`version`, `executed_at`, `execution_time`)\n SELECT `version`, `executed_at`, `execution_time` FROM `{$legacyTable}`");
if ($merged === \false) {
throw new RuntimeException($wpdb->last_error ?: 'Unable to merge the legacy Jooosi Fon migration history.');
}
}
private function dropTable(string $legacyTable): void
{
global $wpdb;
if ($wpdb->query("DROP TABLE `{$legacyTable}`") === \false) {
throw new RuntimeException($wpdb->last_error ?: 'Unable to remove the legacy Jooosi Fon migrations table.');
}
}
private function migrateNamespace(string $table, string $legacyNamespace, string $namespace): void
{
global $wpdb;
$like = $wpdb->esc_like($legacyNamespace) . '%';
$legacyVersion = $wpdb->get_var($wpdb->prepare("SELECT `version` FROM `{$table}` WHERE `version` LIKE %s LIMIT 1", $like));
if (!is_string($legacyVersion)) {
return;
}
$inserted = $wpdb->query($wpdb->prepare("INSERT IGNORE INTO `{$table}` (`version`, `executed_at`, `execution_time`)\n SELECT REPLACE(`version`, %s, %s), `executed_at`, `execution_time`\n FROM `{$table}` WHERE `version` LIKE %s", $legacyNamespace, $namespace, $like));
if ($inserted === \false) {
throw new RuntimeException($wpdb->last_error ?: 'Unable to migrate the Jooosi Fon migration namespace.');
}
$deleted = $wpdb->query($wpdb->prepare("DELETE FROM `{$table}` WHERE `version` LIKE %s", $like));
if ($deleted === \false) {
throw new RuntimeException($wpdb->last_error ?: 'Unable to clean up the legacy Jooosi Fon migration namespace.');
}
}
/**
* @phpstan-impure
*/
private function tableExists(string $table): bool
{
global $wpdb;
$foundTable = $wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $wpdb->esc_like($table)));
return is_string($foundTable) && $foundTable === $table;
}
}
@@ -0,0 +1,77 @@
<?php
declare (strict_types=1);
namespace JooosiFon\Database\Migration;
/**
* Coordinates migration discovery, persistence, execution, and CLI access.
*/
final class MigrationManager
{
private \JooosiFon\Database\Migration\MigrationConfiguration $configuration;
private \JooosiFon\Database\Migration\MigrationRegistry $registry;
private \JooosiFon\Database\Migration\MigrationRepository $repository;
private \JooosiFon\Database\Migration\MigrationGenerator $generator;
/**
* @param array<string, string> $configuration
*/
public function __construct(array $configuration = [])
{
$this->configuration = new \JooosiFon\Database\Migration\MigrationConfiguration($configuration);
$this->registry = new \JooosiFon\Database\Migration\MigrationRegistry($this->configuration);
$this->repository = new \JooosiFon\Database\Migration\MigrationRepository($this->configuration, $this->registry);
$this->generator = new \JooosiFon\Database\Migration\MigrationGenerator($this->configuration);
}
public function boot(): void
{
if (!function_exists('dbDelta')) {
require_once \ABSPATH . 'wp-admin/includes/upgrade.php';
}
if (class_exists('WP_CLI')) {
\WP_CLI::add_command($this->configuration->commandNamespace(), new \JooosiFon\Database\Migration\MigrationCommand($this));
}
}
public function install(): void
{
$this->repository->install();
}
public function generate(?string $tableName = null): string
{
return $this->generator->generate($tableName);
}
/**
* @return array<string, array{version: string, executed: bool, executed_at: ?string, execution_time: ?int}>
*/
public function list(): array
{
return $this->repository->versions();
}
/**
* @return list<array{version: string, executed_at: string, execution_time: int}>
*/
public function execute(): array
{
$this->install();
$versions = $this->list();
$definitions = [];
foreach ($this->registry->all() as $definition) {
$definitions[$definition->version] = $definition;
}
$executed = [];
foreach ($versions as $version) {
if ($version['executed'] || !isset($definitions[$version['version']])) {
continue;
}
$definition = $definitions[$version['version']];
$migration = $this->registry->create($definition->className);
$startedAt = microtime(\true);
$migration->preUp();
$migration->up();
$migration->postUp();
$executionTime = (int) round((microtime(\true) - $startedAt) * 1000);
$this->repository->recordExecution($definition, $executionTime);
$executed[] = ['version' => $definition->version, 'executed_at' => function_exists('current_time') ? current_time('mysql') : gmdate('Y-m-d H:i:s'), 'execution_time' => $executionTime];
}
return $executed;
}
}
@@ -0,0 +1,56 @@
<?php
declare (strict_types=1);
namespace JooosiFon\Database\Migration;
use RuntimeException;
/**
* Discovers migrations from the configured directory.
*/
final class MigrationRegistry
{
private \JooosiFon\Database\Migration\MigrationConfiguration $configuration;
public function __construct(\JooosiFon\Database\Migration\MigrationConfiguration $configuration)
{
$this->configuration = $configuration;
}
/**
* @return list<MigrationDefinition>
*/
public function all(): array
{
$files = glob($this->configuration->migrationsPath() . \DIRECTORY_SEPARATOR . 'Version*.php');
if (!is_array($files)) {
return [];
}
sort($files, \SORT_STRING);
$definitions = [];
foreach ($files as $file) {
require_once $file;
$className = $this->configuration->namespace() . '\\' . pathinfo($file, \PATHINFO_FILENAME);
if (!class_exists($className)) {
throw new RuntimeException(sprintf('Migration class "%s" could not be loaded from "%s".', $className, $file));
}
$migration = new $className();
if (!$migration instanceof \JooosiFon\Database\Migration\AbstractMigration) {
throw new RuntimeException(sprintf('Migration class "%s" must extend %s.', $className, \JooosiFon\Database\Migration\AbstractMigration::class));
}
$definitions[] = new \JooosiFon\Database\Migration\MigrationDefinition($className, $migration->getDescription());
}
return $definitions;
}
public function create(string $className): \JooosiFon\Database\Migration\AbstractMigration
{
if (!class_exists($className)) {
$this->all();
}
if (!class_exists($className)) {
throw new RuntimeException(sprintf('Migration class "%s" could not be loaded.', $className));
}
$migration = new $className();
if (!$migration instanceof \JooosiFon\Database\Migration\AbstractMigration) {
throw new RuntimeException(sprintf('Migration class "%s" must extend %s.', $className, \JooosiFon\Database\Migration\AbstractMigration::class));
}
return $migration;
}
}
@@ -0,0 +1,95 @@
<?php
declare (strict_types=1);
namespace JooosiFon\Database\Migration;
use RuntimeException;
/**
* Persists and reads migration execution history.
*/
final class MigrationRepository
{
private \JooosiFon\Database\Migration\MigrationConfiguration $configuration;
private \JooosiFon\Database\Migration\MigrationRegistry $registry;
public function __construct(\JooosiFon\Database\Migration\MigrationConfiguration $configuration, \JooosiFon\Database\Migration\MigrationRegistry $registry)
{
$this->configuration = $configuration;
$this->registry = $registry;
}
public function install(): void
{
if ($this->tableExists()) {
return;
}
global $wpdb;
$collation = $wpdb->has_cap('collation') ? $wpdb->get_charset_collate() : '';
$tableName = $this->tableName();
$sql = "CREATE TABLE `{$tableName}` (\n `version` VARCHAR(191) NOT NULL,\n `executed_at` DATETIME DEFAULT NULL,\n `execution_time` INT DEFAULT NULL,\n PRIMARY KEY (`version`)\n ) {$collation};";
dbDelta($sql);
if (!$this->tableExists()) {
throw new RuntimeException($wpdb->last_error ?: 'Unable to create the Jooosi Fon migrations table.');
}
}
/**
* @return list<array<string, mixed>>
*/
public function metadata(): array
{
if (!$this->tableExists()) {
return [];
}
global $wpdb;
$results = $wpdb->get_results(sprintf('SELECT * FROM `%s`', $this->tableName()), \ARRAY_A);
if (!is_array($results)) {
return [];
}
$prefix = $this->configuration->namespace() . '\\';
return array_values(array_filter($results, static function (array $result) use ($prefix): bool {
$version = isset($result['version']) ? (string) $result['version'] : '';
return strncmp($version, $prefix, strlen($prefix)) === 0;
}));
}
/**
* @return array<string, array{version: string, executed: bool, executed_at: ?string, execution_time: ?int}>
*/
public function versions(): array
{
$versions = [];
foreach ($this->registry->all() as $definition) {
$versions[$definition->version] = ['version' => $definition->version, 'executed' => \false, 'executed_at' => null, 'execution_time' => null];
}
foreach ($this->metadata() as $metadata) {
$version = (string) $metadata['version'];
$versions[$version] = ['version' => $version, 'executed' => \true, 'executed_at' => isset($metadata['executed_at']) ? (string) $metadata['executed_at'] : null, 'execution_time' => isset($metadata['execution_time']) ? (int) $metadata['execution_time'] : null];
}
ksort($versions, \SORT_STRING);
return $versions;
}
public function recordExecution(\JooosiFon\Database\Migration\MigrationDefinition $definition, int $executionTime): void
{
global $wpdb;
$inserted = $wpdb->insert($this->tableName(), ['version' => $definition->version, 'executed_at' => $this->timestamp(), 'execution_time' => max(0, $executionTime)], ['%s', '%s', '%d']);
if ($inserted === \false) {
throw new RuntimeException($wpdb->last_error ?: sprintf('Unable to record migration "%s".', $definition->version));
}
}
public function tableName(): string
{
global $wpdb;
return $wpdb->prefix . $this->configuration->tableName();
}
/**
* @phpstan-impure
*/
private function tableExists(): bool
{
global $wpdb;
$tableName = $this->tableName();
$foundTable = $wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $wpdb->esc_like($tableName)));
return is_string($foundTable) && $foundTable === $tableName;
}
private function timestamp(): string
{
return function_exists('current_time') ? current_time('mysql') : gmdate('Y-m-d H:i:s');
}
}
@@ -0,0 +1,207 @@
<?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\Licensing;
use EasyDigitalDownloads\Updater\Licensing\License;
use EasyDigitalDownloads\Updater\Messenger;
use EasyDigitalDownloads\Updater\Requests\API;
use EasyDigitalDownloads\Updater\Updaters\Plugin as PluginUpdater;
use JooosiFonDeps\JOOOSI_FON;
use WP_Error;
/**
* Bridges the plugin's existing license UI to the official EDD Software
* Licensing SDK and initializes its WordPress plugin updater.
*/
final class Manager
{
public const INTEGRATION_ID = 'jooosi-fon';
public const OPTION_NAME = 'jooosi_fon_license_key';
private const MIGRATION_OPTION = 'jooosi_fon_edd_sl_sdk_migrated';
private License $license;
public function __construct()
{
$this->license = new License(self::INTEGRATION_ID, self::get_integration_args(), new Messenger());
$this->migrate_legacy_license();
}
/**
* Arguments shared by the SDK registry and the compatibility bridge.
*
* @return array<string, mixed>
*/
public static function get_integration_args(): array
{
return ['id' => self::INTEGRATION_ID, 'url' => JOOOSI_FON::EDD_STORE['store_url'], 'item_id' => JOOOSI_FON::EDD_STORE['item_id'], 'version' => JOOOSI_FON::VERSION, 'file' => JOOOSI_FON::FILE, 'option_name' => self::OPTION_NAME, 'weekly_check' => \true];
}
/**
* Initialize the official updater with the existing WordPress.org override
* and pre-release behavior preserved.
*/
public function boot_updater(): void
{
if (!current_user_can('manage_options') && !wp_doing_cron()) {
return;
}
$license_key = $this->get_license_key();
if ($license_key === '') {
return;
}
new PluginUpdater(JOOOSI_FON::EDD_STORE['store_url'], ['file' => JOOOSI_FON::FILE, 'item_id' => JOOOSI_FON::EDD_STORE['item_id'], 'version' => JOOOSI_FON::VERSION, 'license' => $license_key, 'beta' => $this->is_pre_release_enabled(), 'allow_tracking' => $this->license->get_allow_tracking(), 'wp_override' => \true], new Messenger());
}
public function get_license_key(): string
{
return trim((string) $this->license->get_license_key());
}
public function is_activated(): bool
{
if ($this->get_license_key() === '') {
return \false;
}
$status = get_option($this->license->get_status_option_name());
return is_object($status) && ($status->success ?? \true) !== \false && in_array($status->license ?? '', ['active', 'valid'], \true);
}
/**
* Activate and persist a license using the official SDK request client.
*
* @return object|WP_Error
*/
public function activate(string $license_key)
{
$license_key = trim($license_key);
if ($license_key === '') {
return new WP_Error('missing', __('Enter a license key.', 'jooosi-fon'));
}
$old_license_key = $this->get_license_key();
$license_data = $this->request('activate_license', $license_key);
if (is_wp_error($license_data)) {
return $license_data;
}
update_option(self::OPTION_NAME, $license_key);
$this->license->save($license_data);
$this->clear_cache([$old_license_key, $license_key]);
return $license_data;
}
/**
* Deactivate and remove the currently stored license.
*
* @return object|WP_Error
*/
public function deactivate()
{
$license_key = $this->get_license_key();
if ($license_key === '') {
delete_option($this->license->get_status_option_name());
return (object) ['success' => \true, 'license' => 'inactive'];
}
$license_data = $this->request('deactivate_license', $license_key);
if (is_wp_error($license_data)) {
return $license_data;
}
delete_option(self::OPTION_NAME);
delete_option($this->license->get_status_option_name());
$this->clear_cache([$license_key]);
return $license_data;
}
/**
* Clear update data after activation, deactivation, or plugin activation.
*
* @param array<int, string>|null $license_keys
*/
public function clear_cache(?array $license_keys = null): void
{
$license_keys = $license_keys ?? [$this->get_license_key()];
$slug = basename(dirname(JOOOSI_FON::FILE));
foreach (array_unique($license_keys) as $license_key) {
$cache_key = md5(wp_json_encode([$slug, $license_key, (int) $this->is_pre_release_enabled()]));
delete_option('edd_sl_' . $cache_key);
}
delete_transient(JOOOSI_FON::WP_OPTION . '_license_seed');
delete_transient(JOOOSI_FON::LEGACY_WP_OPTION . '_license_seed');
delete_site_transient('update_plugins');
}
public function error_message(string $code): string
{
switch ($code) {
case 'expired':
return __('Your license key has expired.', 'jooosi-fon');
case 'disabled':
case 'revoked':
return __('Your license key has been disabled.', 'jooosi-fon');
case 'inactive':
case 'site_inactive':
return __('Your license is not active for this website.', 'jooosi-fon');
case 'no_activations_left':
return __('Your license key has reached its activation limit.', 'jooosi-fon');
case 'missing_url':
return __('The license does not exist or the website URL was not provided.', 'jooosi-fon');
case 'key_mismatch':
case 'missing':
case 'invalid':
case 'invalid_item_id':
case 'item_name_mismatch':
return __('Invalid license key.', 'jooosi-fon');
default:
return __('The license server rejected the request.', 'jooosi-fon');
}
}
/**
* @return object|WP_Error
*/
private function request(string $action, string $license_key)
{
$api = new API(JOOOSI_FON::EDD_STORE['store_url']);
$license_data = $api->make_request(['edd_action' => $action, 'license' => $license_key, 'item_id' => JOOOSI_FON::EDD_STORE['item_id']]);
if (!is_object($license_data)) {
return new WP_Error('license_server_unavailable', __('The license server could not be reached.', 'jooosi-fon'));
}
if (empty($license_data->success)) {
$code = (string) ($license_data->error ?? $license_data->license ?? 'invalid');
return new WP_Error($code, $this->error_message($code));
}
return $license_data;
}
private function is_pre_release_enabled(): bool
{
$legacy_license = get_option(JOOOSI_FON::WP_OPTION . '_license', []);
return is_array($legacy_license) && !empty($legacy_license['opt_in_pre_release']);
}
/**
* Copy license data from the Rosua updater options without changing or
* deleting them, so upgraded installations keep their activation state.
*
* @todo Remove this legacy license migration completely in Jooosi Fon 3.0.0.
*/
private function migrate_legacy_license(): void
{
if (get_option(self::MIGRATION_OPTION, \false)) {
return;
}
$missing = new \stdClass();
$license_key = get_option(self::OPTION_NAME, $missing);
if ($license_key === $missing || trim((string) $license_key) === '') {
$legacy_license = get_option(JOOOSI_FON::WP_OPTION . '_license', []);
$legacy_key = is_array($legacy_license) ? trim((string) ($legacy_license['key'] ?? '')) : '';
if ($legacy_key !== '') {
update_option(self::OPTION_NAME, $legacy_key);
}
}
if (get_option($this->license->get_status_option_name(), $missing) === $missing) {
foreach ([JOOOSI_FON::WP_OPTION, JOOOSI_FON::LEGACY_WP_OPTION] as $option_prefix) {
$legacy_status = get_transient($option_prefix . '_license_seed');
if (is_object($legacy_status) && !empty($legacy_status->license)) {
$this->license->save($legacy_status);
break;
}
}
}
update_option(self::MIGRATION_OPTION, \true);
}
}
@@ -0,0 +1,74 @@
<?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;
use JooosiFonDeps\JOOOSI_FON;
use JooosiFon\Database\Migration\MigrationHistoryUpgrader;
use JooosiFon\Database\Migration\MigrationManager;
/**
* Manage the plugin custom database tables.
*
* @author Joshua Gugun Siagian <suabahasa@gmail.com>
*/
final class Migration
{
/**
* @todo Remove the legacy table/namespace upgrade constants in Jooosi Fon 3.0.0.
*/
private const LEGACY_MIGRATION_TABLE = 'yabe_webfont_migrations';
private const LEGACY_MIGRATION_UPGRADE_OPTION = 'jooosi_fon_legacy_migration_history_upgraded';
private const MIGRATION_TABLE = 'jooosi_fon_migrations';
private MigrationManager $migrationManager;
public function __construct()
{
$this->upgradeLegacyMigrationHistory();
$this->migrationManager = new MigrationManager(['tableName' => self::MIGRATION_TABLE, 'namespace' => 'JooosiFon\Migrations', 'directory' => 'migrations', 'basePath' => dirname(JOOOSI_FON::FILE), 'commandNamespace' => 'jooosi-fon migrations']);
add_action('a!jooosi/fon/plugins:activate_plugin_start', fn() => $this->install());
add_action('a!jooosi/fon/plugins:upgrade_plugin_start', fn() => $this->upgrade());
$this->migrationManager->boot();
$this->maybe_upgrade();
}
public function install(): void
{
$this->migrationManager->install();
$this->migrationManager->execute();
}
public function upgrade(): void
{
$this->migrationManager->install();
$this->migrationManager->execute();
}
/**
* @todo Remove this legacy migration-history upgrade completely in Jooosi Fon 3.0.0.
*/
private function upgradeLegacyMigrationHistory(): void
{
if (get_option(self::LEGACY_MIGRATION_UPGRADE_OPTION, \false) !== \false) {
return;
}
(new MigrationHistoryUpgrader())->upgrade(self::LEGACY_MIGRATION_TABLE, self::MIGRATION_TABLE, 'Yabe\Webfont\Migrations\\', 'JooosiFon\Migrations\\');
update_option(self::LEGACY_MIGRATION_UPGRADE_OPTION, JOOOSI_FON::VERSION, \false);
}
/**
* Run pending migrations before services query renamed tables. Activation
* still owns first-time installation; this path handles normal code updates.
*/
private function maybe_upgrade(): void
{
$installedVersion = get_option(JOOOSI_FON::WP_OPTION . '_version', \false);
if (is_string($installedVersion) && version_compare($installedVersion, JOOOSI_FON::VERSION, '>=')) {
return;
}
$this->upgrade();
update_option(JOOOSI_FON::WP_OPTION . '_version', JOOOSI_FON::VERSION);
}
}
@@ -0,0 +1,353 @@
<?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;
use EasyDigitalDownloads\Updater\Registry;
use Exception;
use JooosiFonDeps\JOOOSI_FON;
use JooosiFon\Admin\AdminPage;
use JooosiFon\Api\Router as ApiRouter;
use JooosiFon\Builder\Integration as BuilderIntegration;
use JooosiFon\Core\Cache;
use JooosiFon\Core\Runtime;
use JooosiFon\Licensing\Manager as LicenseManager;
use JooosiFon\Upgrade\LegacyRebrandUpgrade;
use JooosiFon\Utils\Common;
use JooosiFon\Utils\Debug;
use JooosiFon\Utils\Notice;
/**
* Manage the plugin lifecycle and provides a single point of entry to the plugin.
*
* @author Joshua Gugun Siagian <suabahasa@gmail.com>
* @todo Remove all legacy Yabe Webfont hook shims completely in Jooosi Fon 3.0.0.
*/
final class Plugin
{
/**
* Easy Digital Downloads Software Licensing integration manager.
* Pro version only.
*
* @var LicenseManager|null
*/
public $plugin_updater = null;
/**
* Stores the instance, implementing a Singleton pattern.
*/
private static self $instance;
/**
* The Singleton's constructor should always be private to prevent direct
* construction calls with the `new` operator.
*/
private function __construct()
{
}
/**
* Singletons should not be cloneable.
*/
private function __clone()
{
}
/**
* Singletons should not be restorable from strings.
*
* @throws Exception Cannot unserialize a singleton.
*/
public function __wakeup()
{
throw new Exception('Cannot unserialize a singleton.');
}
/**
* This is the static method that controls the access to the singleton
* instance. On the first run, it creates a singleton object and places it
* into the static property. On subsequent runs, it returns the client existing
* object stored in the static property.
*/
public static function get_instance(): self
{
if (!isset(self::$instance)) {
self::$instance = new self();
}
return self::$instance;
}
public function boot_debug()
{
if (\WP_DEBUG === \false) {
return;
}
// if (class_exists(\Sentry\SentrySdk::class)) {
// }
// when php exits, call the shutdown function.
register_shutdown_function(static fn() => Debug::shutdown());
}
public function boot_migration()
{
do_action('a!jooosi/fon/plugin:boot_migration.start');
do_action_deprecated('a!yabe/webfont/plugin:boot_migration.start', [], '2.1.0', 'a!jooosi/fon/plugin:boot_migration.start');
/** @var wpdb $wpdb */
global $wpdb;
$wpdb->jooosi_fon_prefix = JOOOSI_FON::DB_TABLE_PREFIX;
new \JooosiFon\Migration();
do_action('a!jooosi/fon/plugin:boot_migration.end');
do_action_deprecated('a!yabe/webfont/plugin:boot_migration.end', [], '2.1.0', 'a!jooosi/fon/plugin:boot_migration.end');
}
/**
* Boot to the Plugin.
*/
public function boot(): void
{
$this->migrate_legacy_options();
$this->boot_license_sdk();
do_action('a!jooosi/fon/plugins:boot_start');
do_action_deprecated('a!yabe/webfont/plugins:boot_start', [], '2.1.0', 'a!jooosi/fon/plugins:boot_start');
$this->boot_debug();
$this->boot_migration();
(new LegacyRebrandUpgrade())->run();
// (de)activation hooks.
register_activation_hook(JOOOSI_FON::FILE, function (): void {
$this->activate_plugin();
});
register_deactivation_hook(JOOOSI_FON::FILE, function (): void {
$this->deactivate_plugin();
});
// upgrade hooks.
add_action('upgrader_process_complete', function ($upgrader, $options): void {
if ($options['action'] === 'update' && $options['type'] === 'plugin') {
foreach ($options['plugins'] as $plugin) {
if ($plugin === plugin_basename(JOOOSI_FON::FILE)) {
$this->upgrade_plugin();
}
}
}
}, 10, 2);
new Cache();
new Runtime();
new BuilderIntegration();
new ApiRouter();
$this->maybe_update_plugin();
// admin hooks.
if (is_admin()) {
add_filter('plugin_action_links_' . plugin_basename(JOOOSI_FON::FILE), fn($links) => $this->plugin_action_links($links));
add_action('plugins_loaded', function (): void {
$this->plugins_loaded_admin();
}, 100);
new AdminPage();
do_action('a!jooosi/fon/plugins:boot_admin');
do_action_deprecated('a!yabe/webfont/plugins:boot_admin', [], '2.1.0', 'a!jooosi/fon/plugins:boot_admin');
}
do_action('a!jooosi/fon/plugins:boot_end');
do_action_deprecated('a!yabe/webfont/plugins:boot_end', [], '2.1.0', 'a!jooosi/fon/plugins:boot_end');
}
/**
* Handle the plugin's activation
*/
public function activate_plugin(): void
{
do_action('a!jooosi/fon/plugins:activate_plugin_start');
do_action_deprecated('a!yabe/webfont/plugins:activate_plugin_start', [], '2.1.0', 'a!jooosi/fon/plugins:activate_plugin_start');
update_option(JOOOSI_FON::WP_OPTION . '_version', JOOOSI_FON::VERSION);
if ($this->plugin_updater instanceof LicenseManager) {
$this->maybe_embedded_license();
$this->plugin_updater->clear_cache();
}
delete_transient('jooosi_fon_scanned_apis_' . JOOOSI_FON::VERSION);
do_action('a!jooosi/fon/plugins:activate_plugin_end');
do_action_deprecated('a!yabe/webfont/plugins:activate_plugin_end', [], '2.1.0', 'a!jooosi/fon/plugins:activate_plugin_end');
}
/**
* Handle plugin's deactivation by (maybe) cleaning up after ourselves.
*/
public function deactivate_plugin(): void
{
do_action('a!jooosi/fon/plugins:deactivate_plugin_start');
do_action_deprecated('a!yabe/webfont/plugins:deactivate_plugin_start', [], '2.1.0', 'a!jooosi/fon/plugins:deactivate_plugin_start');
// TODO: Add deactivation logic here.
do_action('a!jooosi/fon/plugins:deactivate_plugin_end');
do_action_deprecated('a!yabe/webfont/plugins:deactivate_plugin_end', [], '2.1.0', 'a!jooosi/fon/plugins:deactivate_plugin_end');
}
/**
* Handle the plugin's upgrade
*/
public function upgrade_plugin(): void
{
do_action('a!jooosi/fon/plugins:upgrade_plugin_start');
do_action_deprecated('a!yabe/webfont/plugins:upgrade_plugin_start', [], '2.1.0', 'a!jooosi/fon/plugins:upgrade_plugin_start');
update_option(JOOOSI_FON::WP_OPTION . '_version', JOOOSI_FON::VERSION);
do_action('a!jooosi/fon/plugins:upgrade_plugin_end');
do_action_deprecated('a!yabe/webfont/plugins:upgrade_plugin_end', [], '2.1.0', 'a!jooosi/fon/plugins:upgrade_plugin_end');
}
/**
* Warm up the plugin for admin.
*/
public function plugins_loaded_admin(): void
{
add_action('admin_notices', static function () {
$messages = Notice::get_lists();
if ($messages && is_array($messages)) {
foreach ($messages as $message) {
echo sprintf('<div class="notice notice-%s is-dismissible %s">%s</div>', esc_attr($message['status']), JOOOSI_FON::WP_OPTION, esc_html($message['message']));
}
}
}, 100);
}
/**
* Add plugin action links.
*
* @param array<string> $links
* @return array<string>
*/
public function plugin_action_links(array $links): array
{
$base_url = AdminPage::get_page_url();
array_unshift($links, sprintf('<a href="%s">%s</a>', esc_url(sprintf('%s#/settings', $base_url)), esc_html__('Settings', 'jooosi-fon')));
array_unshift($links, sprintf('<a href="%s">%s</a>', esc_url(sprintf('%s#/fonts/index', $base_url)), esc_html__('Fonts', 'jooosi-fon')));
if (!self::is_pro_edition()) {
array_unshift($links, sprintf('<a href="%s" style="color:#067b34;font-weight:600;" target="_blank">%s</a>', esc_url(Common::plugin_data('PluginURI') . '?utm_source=WordPress&utm_campaign=liteplugin&utm_medium=plugin-action-links&utm_content=Upgrade#pricing'), esc_html__('Upgrade to Pro', 'jooosi-fon')));
}
return $links;
}
/**
* Get the initialized license manager.
* Pro version only.
*
* @return LicenseManager|null
*/
public function maybe_update_plugin()
{
return $this->plugin_updater;
}
public static function is_pro_edition(): bool
{
return is_file(self::get_license_sdk_path());
}
/**
* Register the plugin with EDD's official Software Licensing SDK.
*/
private function boot_license_sdk(): void
{
$sdk_path = self::get_license_sdk_path();
if (!is_file($sdk_path)) {
return;
}
$this->plugin_updater = new LicenseManager();
add_action('init', [$this->plugin_updater, 'boot_updater']);
add_action('edd_sl_sdk_registry', function ($registry): void {
$this->register_license_integration($registry);
});
require_once $sdk_path;
// Plugin activation can happen after the SDK initialization hooks ran.
if (did_action('after_setup_theme') && class_exists(Registry::class)) {
$this->register_license_integration(Registry::instance());
}
}
/**
* @param mixed $registry
*/
private function register_license_integration($registry): void
{
if (!$registry instanceof Registry) {
return;
}
if (!$registry->offsetExists(LicenseManager::INTEGRATION_ID)) {
$registry->register(LicenseManager::get_integration_args());
}
$handler = $registry->offsetGet(LicenseManager::INTEGRATION_ID);
if (is_object($handler) && method_exists($handler, 'auto_updater')) {
// The SDK registry does not pass wp_override or beta through in
// version 1.0.3, so Manager boots the official updater directly.
remove_action('init', [$handler, 'auto_updater']);
}
}
private static function get_license_sdk_path(): string
{
return dirname(JOOOSI_FON::FILE) . '/vendor/easy-digital-downloads/edd-sl-sdk/edd-sl-sdk.php';
}
/**
* Check if the plugin distributed with an embedded license and activate the license.
* Pro version only.
*/
private function maybe_embedded_license(): void
{
$license_file = dirname(JOOOSI_FON::FILE) . '/license-data.php';
if (!file_exists($license_file)) {
return;
}
require_once $license_file;
$const_names = [
'JOOOSI_FON_EMBEDDED_LICENSE_KEY_' . JOOOSI_FON::EDD_STORE['item_id'],
// TODO: Remove this legacy embedded-license constant in Jooosi Fon 3.0.0.
'ROSUA_EMBEDDED_LICENSE_KEY_' . JOOOSI_FON::EDD_STORE['item_id'],
];
$const_name = null;
foreach ($const_names as $candidate) {
if (defined($candidate)) {
$const_name = $candidate;
break;
}
}
if ($const_name === null) {
return;
}
$license_key = constant($const_name);
update_option(JOOOSI_FON::WP_OPTION . '_license', ['key' => $license_key, 'opt_in_pre_release' => \false]);
unlink($license_file);
// activate the license.
$this->plugin_updater->activate((string) $license_key);
}
/**
* Copy persisted values to the rebranded option keys, then keep both names
* synchronized on upgraded installations. Fresh installs only use the new
* keys because no legacy option exists to activate this compatibility path.
*
* @todo Remove this legacy option migration completely in Jooosi Fon 3.0.0.
*/
private function migrate_legacy_options(): void
{
$missing = new \stdClass();
$optionMap = [];
$hasLegacyOptions = \false;
foreach (['_version', '_options', '_license', '_notices'] as $suffix) {
$option = JOOOSI_FON::WP_OPTION . $suffix;
$legacyOption = JOOOSI_FON::LEGACY_WP_OPTION . $suffix;
$optionMap[$option] = $legacyOption;
$legacyValue = get_option($legacyOption, $missing);
if ($legacyValue === $missing) {
continue;
}
$hasLegacyOptions = \true;
if (get_option($option, $missing) === $missing) {
add_option($option, $legacyValue);
}
}
if (!$hasLegacyOptions) {
return;
}
$legacyOptionMap = array_flip($optionMap);
$syncing = \false;
$syncOption = static function (string $option, $value) use ($optionMap, $legacyOptionMap, &$syncing): void {
if ($syncing) {
return;
}
$target = $optionMap[$option] ?? $legacyOptionMap[$option] ?? null;
if ($target === null) {
return;
}
$syncing = \true;
try {
update_option($target, $value);
} finally {
$syncing = \false;
}
};
add_action('updated_option', static fn($option, $oldValue, $value) => $syncOption($option, $value), 10, 3);
add_action('added_option', static fn($option, $value) => $syncOption($option, $value), 10, 2);
}
}
@@ -0,0 +1,309 @@
<?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\Upgrade;
use JooosiFonDeps\JOOOSI_FON;
use JooosiFon\Database\FontTable;
/**
* One-time filesystem and attachment migration for the Jooosi Fon rebrand.
*
* @todo Remove this class and its call site completely in Jooosi Fon 3.0.0.
*/
final class LegacyRebrandUpgrade
{
public const CACHE_REBUILD_OPTION = 'jooosi_fon_legacy_cache_rebuild_required';
public const DELETE_LEGACY_DATA_OPTION = 'misc.delete_legacy_data';
private const COMPLETION_OPTION = 'jooosi_fon_legacy_rebrand_upgraded';
private const CLEANUP_OPTION = 'jooosi_fon_legacy_data_cleaned';
private const LEGACY_UPLOAD_DIRECTORY = 'yabe-webfont';
private const UPLOAD_DIRECTORY = 'jooosi-fon';
private const FONT_DIRECTORY = 'fonts';
private const CACHE_DIRECTORY = 'cache';
/**
* @return array{complete: bool, filesystem_complete: bool, font_table_available: bool, legacy_data_available: bool, current_data_available: bool, cleanup_requested: bool, cleanup_complete: bool}
*/
public function status(): array
{
$uploads = wp_upload_dir();
$baseDirectory = is_array($uploads) ? rtrim((string) ($uploads['basedir'] ?? ''), '/\\') : '';
$legacyRoot = $baseDirectory !== '' ? $baseDirectory . '/' . self::LEGACY_UPLOAD_DIRECTORY : '';
$root = $baseDirectory !== '' ? $baseDirectory . '/' . self::UPLOAD_DIRECTORY : '';
$filesystemComplete = get_option(self::COMPLETION_OPTION, \false) !== \false;
$fontTableAvailable = FontTable::exists();
$cleanupComplete = get_option(self::CLEANUP_OPTION, \false) !== \false;
return ['complete' => $filesystemComplete && $fontTableAvailable, 'filesystem_complete' => $filesystemComplete, 'font_table_available' => $fontTableAvailable, 'legacy_data_available' => $legacyRoot !== '' && (is_dir($legacyRoot) || is_file($legacyRoot) || is_link($legacyRoot)), 'current_data_available' => $root !== '' && (is_dir($root) || is_file($root) || is_link($root)), 'cleanup_requested' => $this->shouldDeleteLegacyData(), 'cleanup_complete' => $cleanupComplete];
}
public function run(): void
{
if (get_option(self::COMPLETION_OPTION, \false) !== \false) {
if ($this->shouldDeleteLegacyData()) {
$this->deleteLegacyData();
}
return;
}
$uploads = wp_upload_dir();
$baseDirectory = is_array($uploads) ? rtrim((string) ($uploads['basedir'] ?? ''), '/\\') : '';
if ($baseDirectory === '' || !is_dir($baseDirectory)) {
return;
}
$legacyRoot = $baseDirectory . '/' . self::LEGACY_UPLOAD_DIRECTORY;
$root = $baseDirectory . '/' . self::UPLOAD_DIRECTORY;
$fontChanged = \false;
$cacheChanged = \false;
$otherChanged = \false;
$attachmentsComplete = $this->migrateAttachmentPaths($baseDirectory, $fontChanged);
$fontsComplete = $attachmentsComplete && $this->migrateDirectory($legacyRoot . '/' . self::FONT_DIRECTORY, $root . '/' . self::FONT_DIRECTORY, \false, $fontChanged);
$cacheComplete = $this->migrateDirectory($legacyRoot . '/' . self::CACHE_DIRECTORY, $root . '/' . self::CACHE_DIRECTORY, \true, $cacheChanged);
$rootComplete = $attachmentsComplete && $fontsComplete && $cacheComplete && $this->migrateDirectory($legacyRoot, $root, \false, $otherChanged, [self::FONT_DIRECTORY, self::CACHE_DIRECTORY]);
if ($fontChanged || $cacheChanged) {
update_option(self::CACHE_REBUILD_OPTION, \true, \false);
}
if ($attachmentsComplete && $fontsComplete && $cacheComplete && $rootComplete) {
update_option(self::COMPLETION_OPTION, JOOOSI_FON::VERSION, \false);
if ($this->shouldDeleteLegacyData()) {
$this->deleteLegacyData();
}
}
}
private function migrateAttachmentPaths(string $baseDirectory, bool &$changed): bool
{
global $wpdb;
$legacyPrefix = self::LEGACY_UPLOAD_DIRECTORY . '/' . self::FONT_DIRECTORY . '/';
$prefix = self::UPLOAD_DIRECTORY . '/' . self::FONT_DIRECTORY . '/';
$like = $wpdb->esc_like($legacyPrefix) . '%';
$rows = $wpdb->get_results($wpdb->prepare("SELECT `post_id`, `meta_value` FROM `{$wpdb->postmeta}` WHERE `meta_key` = %s AND `meta_value` LIKE %s", '_wp_attached_file', $like));
if (!is_array($rows)) {
return \false;
}
$complete = \true;
foreach ($rows as $row) {
$attachmentId = (int) (is_object($row) ? $row->post_id ?? 0 : $row['post_id'] ?? 0);
$legacyRelativePath = (string) (is_object($row) ? $row->meta_value ?? '' : $row['meta_value'] ?? '');
$legacyRelativePath = ltrim(str_replace('\\', '/', $legacyRelativePath), '/');
if ($attachmentId < 1 || strpos($legacyRelativePath, $legacyPrefix) !== 0) {
continue;
}
$relativePath = $prefix . substr($legacyRelativePath, strlen($legacyPrefix));
$legacyPath = $baseDirectory . '/' . $legacyRelativePath;
$path = $baseDirectory . '/' . $relativePath;
if (!$this->prepareAttachmentFile($legacyPath, $path)) {
$complete = \false;
continue;
}
$metadata = wp_get_attachment_metadata($attachmentId);
if (is_array($metadata) && ($metadata['file'] ?? null) === $legacyRelativePath) {
$metadata['file'] = $relativePath;
if (wp_update_attachment_metadata($attachmentId, $metadata) === \false) {
$complete = \false;
continue;
}
}
$updated = update_post_meta($attachmentId, '_wp_attached_file', $relativePath, $legacyRelativePath);
if ($updated === \false && get_post_meta($attachmentId, '_wp_attached_file', \true) !== $relativePath) {
$complete = \false;
continue;
}
$changed = \true;
}
return $complete;
}
/**
* Copy first so the stored legacy path remains valid until every metadata
* update has succeeded. The legacy file is intentionally retained until
* the administrator explicitly requests cleanup.
*/
private function prepareAttachmentFile(string $legacyPath, string $path): bool
{
if (is_file($path)) {
return !is_file($legacyPath) || $this->filesMatch($legacyPath, $path);
}
if (!is_file($legacyPath) || is_link($legacyPath)) {
return \false;
}
$directory = dirname($path);
if (!is_dir($directory) && !wp_mkdir_p($directory)) {
return \false;
}
if (copy($legacyPath, $path) && $this->filesMatch($legacyPath, $path)) {
return \true;
}
if (file_exists($path)) {
wp_delete_file($path);
}
return \false;
}
private function migrateDirectory(string $legacyDirectory, string $directory, bool $discardLegacyConflicts, bool &$changed, array $ignoredEntries = []): bool
{
if (!is_dir($legacyDirectory)) {
return \true;
}
if (!is_dir($directory) && !wp_mkdir_p($directory)) {
return \false;
}
$entries = scandir($legacyDirectory);
if (!is_array($entries)) {
return \false;
}
$complete = \true;
foreach ($entries as $entry) {
if ($entry === '.' || $entry === '..') {
continue;
}
if (in_array($entry, $ignoredEntries, \true)) {
continue;
}
$legacyPath = $legacyDirectory . '/' . $entry;
$path = $directory . '/' . $entry;
if (is_link($legacyPath)) {
$complete = \false;
continue;
}
if (is_dir($legacyPath)) {
if (!$this->migrateDirectory($legacyPath, $path, $discardLegacyConflicts, $changed)) {
$complete = \false;
}
continue;
}
if (!is_file($legacyPath) || !$this->migrateFile($legacyPath, $path, $discardLegacyConflicts, $changed)) {
$complete = \false;
}
}
return $complete;
}
private function migrateFile(string $legacyPath, string $path, bool $discardLegacyConflict, bool &$changed): bool
{
if (is_file($path)) {
if (!is_file($legacyPath)) {
return \true;
}
if ($discardLegacyConflict || $this->filesMatch($legacyPath, $path)) {
return \true;
}
return \false;
}
if (!is_file($legacyPath) || is_link($legacyPath)) {
return \false;
}
$directory = dirname($path);
if (!is_dir($directory) && !wp_mkdir_p($directory)) {
return \false;
}
if (!copy($legacyPath, $path) || !$this->filesMatch($legacyPath, $path)) {
if (file_exists($path)) {
wp_delete_file($path);
}
return \false;
}
$changed = \true;
return \true;
}
/**
* Delete the old Yabe Webfont upload directory after the rebrand migration
* has completed and the administrator has explicitly requested cleanup.
*/
public function deleteLegacyData(): bool
{
if (get_option(self::COMPLETION_OPTION, \false) === \false) {
return \false;
}
if (get_option(self::CLEANUP_OPTION, \false) !== \false) {
return \true;
}
$uploads = wp_upload_dir();
$baseDirectory = is_array($uploads) ? rtrim((string) ($uploads['basedir'] ?? ''), '/\\') : '';
if ($baseDirectory === '' || !is_dir($baseDirectory)) {
return \false;
}
$legacyRoot = $baseDirectory . '/' . self::LEGACY_UPLOAD_DIRECTORY;
if (is_link($legacyRoot)) {
return \false;
}
if (!is_dir($legacyRoot)) {
update_option(self::CLEANUP_OPTION, JOOOSI_FON::VERSION, \false);
return \true;
}
if (!$this->deleteDirectory($legacyRoot)) {
return \false;
}
update_option(self::CLEANUP_OPTION, JOOOSI_FON::VERSION, \false);
return \true;
}
private function deleteDirectory(string $directory): bool
{
if (!is_dir($directory)) {
return !file_exists($directory);
}
$entries = scandir($directory);
if (!is_array($entries)) {
return \false;
}
$complete = \true;
foreach ($entries as $entry) {
if ($entry === '.' || $entry === '..') {
continue;
}
$path = $directory . '/' . $entry;
if (is_link($path)) {
wp_delete_file($path);
if (file_exists($path) || is_link($path)) {
$complete = \false;
}
continue;
}
if (is_dir($path)) {
if (!$this->deleteDirectory($path)) {
$complete = \false;
}
continue;
}
if (is_file($path)) {
wp_delete_file($path);
if (file_exists($path)) {
$complete = \false;
}
continue;
}
$complete = \false;
}
if (!$complete) {
return \false;
}
if (!rmdir($directory)) {
return !is_dir($directory);
}
return \true;
}
private function shouldDeleteLegacyData(): bool
{
$stored = get_option(JOOOSI_FON::WP_OPTION . '_options', '{}');
if (!is_string($stored)) {
return \false;
}
try {
$options = json_decode($stored, \true, 512, \JSON_THROW_ON_ERROR);
} catch (\JsonException $exception) {
return \false;
}
return is_array($options) && is_array($options['misc'] ?? null) && !empty($options['misc']['delete_legacy_data']);
}
private function filesMatch(string $legacyPath, string $path): bool
{
$legacySize = filesize($legacyPath);
$size = filesize($path);
if (!is_int($legacySize) || !is_int($size) || $legacySize !== $size) {
return \false;
}
$legacyHash = hash_file('sha256', $legacyPath);
$hash = hash_file('sha256', $path);
return is_string($legacyHash) && is_string($hash) && hash_equals($legacyHash, $hash);
}
}
@@ -0,0 +1,116 @@
<?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\Utils;
use Exception;
use JooosiFonDeps\JOOOSI_FON;
/**
* Common utility functions for the plugin.
*
* @author Joshua Gugun Siagian <suabahasa@gmail.com>
*/
class Common
{
/**
* Check the type of the current request.
*
* @param string $type The type of the request. Available values: `admin`, `ajax`, `frontend`, `rest`, `cron`.
*/
public static function is_request(string $type): bool
{
switch ($type) {
case 'admin':
return is_admin();
case 'ajax':
return wp_doing_ajax();
case 'rest':
return defined('REST_REQUEST') && \REST_REQUEST;
case 'cron':
return wp_doing_cron();
case 'json':
return wp_is_json_request();
case 'xmlrpc':
return defined('XMLRPC_REQUEST') && \XMLRPC_REQUEST;
case 'xml':
return wp_is_xml_request();
case 'frontend':
return (!is_admin() || wp_doing_ajax()) && !wp_doing_cron();
default:
return \false;
}
}
/**
* Save the worker result into the file.
*
* @param string $content The content of the file.
* @param string $file_path The file path.
* @param int $flags The flags to pass to the file_put_contents() function.
* @throws Exception
*/
public static function save_file($content, $file_path, $flags = 0): void
{
if (!file_exists($file_path)) {
wp_mkdir_p(dirname($file_path));
}
$result = file_put_contents($file_path, $content, $flags);
if ($result === \false) {
throw new Exception('Failed to save to file.', 500);
}
// if write is successful continue
$saved_content = file_get_contents($file_path);
// if read is successful continue
if ($saved_content === \false) {
throw new Exception('The saved file is not readable.', 500);
}
}
/**
* Get the plugin's data.
*
* @param string $key The key to retrieve.
* @return mixed
*/
public static function plugin_data(?string $key = null)
{
if (!function_exists('get_plugin_data')) {
require_once \ABSPATH . 'wp-admin/includes/plugin.php';
}
$plugin_data = wp_cache_get('plugin_data', JOOOSI_FON::WP_OPTION);
if (!$plugin_data) {
$plugin_data = get_plugin_data(JOOOSI_FON::FILE);
wp_cache_set('plugin_data', $plugin_data, JOOOSI_FON::WP_OPTION);
}
return $key ? $plugin_data[$key] : $plugin_data;
}
public static function random_slug(int $length = 21): string
{
return (new \JooosiFonDeps\Hidehalo\Nanoid\Client())->generateId($length, \JooosiFonDeps\Hidehalo\Nanoid\Client::MODE_DYNAMIC);
}
/**
* Redirect to the given location. If headers are already sent, use a meta refresh.
*
* @param string $location The location to redirect to.
* @param bool $safe Whether to use wp_safe_redirect() or not.
*/
public static function redirect(string $location, bool $safe = \false)
{
if (!headers_sent()) {
if ($safe) {
wp_safe_redirect($location);
} else {
wp_redirect($location);
}
} else {
echo '<meta http-equiv="refresh" content="0;url=' . esc_url($location) . '">';
}
exit;
}
}
@@ -0,0 +1,76 @@
<?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\Utils;
use Exception;
use JooosiFonDeps\JOOOSI_FON;
use JooosiFonDeps\Symfony\Component\PropertyAccess\Exception\AccessException;
use JooosiFonDeps\Symfony\Component\PropertyAccess\Exception\InvalidArgumentException;
use JooosiFonDeps\Symfony\Component\PropertyAccess\Exception\UnexpectedTypeException;
use JooosiFonDeps\Symfony\Component\PropertyAccess\PropertyAccess;
/**
* Accessor for the plugin config.
*
* @author Joshua Gugun Siagian <suabahasa@gmail.com>
* @todo Remove all legacy Yabe Webfont filter shims completely in Jooosi Fon 3.0.0.
*/
class Config
{
/**
* Stores the instance of PropertyAccessor, implementing a Singleton pattern.
*/
private static ?\JooosiFonDeps\Symfony\Component\PropertyAccess\PropertyAccessorInterface $propertyAccessor = null;
public static function propertyAccessor()
{
if (!isset(self::$propertyAccessor)) {
self::$propertyAccessor = PropertyAccess::createPropertyAccessorBuilder()->enableExceptionOnInvalidIndex()->getPropertyAccessor();
}
return self::$propertyAccessor;
}
/**
* Gets a value at the end of the property path of the config.
*
* @param string $path The property path to read
* @param mixed $defaultValue The value to return if the property path does not exist
*
* @return mixed The value at the end of the property path
*/
public static function get($path, $defaultValue = null)
{
$options = json_decode(get_option(JOOOSI_FON::WP_OPTION . '_options', '{}'), null, 512, \JSON_THROW_ON_ERROR);
$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');
try {
return self::propertyAccessor()->getValue($options, $path);
} catch (Exception $exception) {
return $defaultValue;
}
}
/**
* Sets a value at the end of the property path of the config.
*
* @param string $path The property path to modify
* @param mixed $value The value to set at the end of the property path
*
* @throws InvalidArgumentException If the property path is invalid
* @throws AccessException If a property/index does not exist or is not public
* @throws UnexpectedTypeException If a value within the path is neither object nor array
*/
public static function set($path, $value)
{
$options = json_decode(get_option(JOOOSI_FON::WP_OPTION . '_options', '{}'), null, 512, \JSON_THROW_ON_ERROR);
$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');
self::propertyAccessor()->setValue($options, $path, $value);
update_option(JOOOSI_FON::WP_OPTION . '_options', json_encode($options, \JSON_THROW_ON_ERROR));
}
}
@@ -0,0 +1,55 @@
<?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\Utils;
use JooosiFonDeps\Symfony\Component\Stopwatch\Stopwatch;
/**
* Debug tools for the plugin.
*
* @author Joshua Gugun Siagian <suabahasa@gmail.com>
*/
class Debug
{
/**
* The stopwatch instance.
*/
private static Stopwatch $stopwatch_instance;
/**
* Get the stopwatch instance.
*/
public static function stopwatch(): Stopwatch
{
if (!isset(self::$stopwatch_instance)) {
self::$stopwatch_instance = new Stopwatch(\true);
}
return self::$stopwatch_instance;
}
public static function shutdown()
{
if (isset(self::$stopwatch_instance)) {
self::shutdown_stopwatch();
}
}
public static function shutdown_stopwatch()
{
$log = '=== ' . date('Y-m-d H:i:s', time()) . ' ===' . \PHP_EOL;
foreach (self::stopwatch()->getSectionEvents('__root__') as $stopwatchEvent) {
$log .= (string) $stopwatchEvent . \PHP_EOL;
}
$log .= \PHP_EOL;
$path = wp_upload_dir()['basedir'] . '/jooosi-fon/debug/stopwatch.log';
try {
\JooosiFon\Utils\Common::save_file($log, $path, \FILE_APPEND);
} catch (\Throwable $throwable) {
}
}
}
@@ -0,0 +1,100 @@
<?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\Utils;
use JooosiFonDeps\JOOOSI_FON;
use JooosiFon\Api\Support\FontCodec;
/**
* Font utility functions for the plugin.
*
* @author Joshua Gugun Siagian <suabahasa@gmail.com>
*/
class Font
{
private const CACHE_KEY = 'get_fonts';
public static function get_fonts(): array
{
$fonts = wp_cache_get(self::CACHE_KEY, JOOOSI_FON::WP_OPTION);
if ($fonts === \false) {
/** @var wpdb $wpdb */
global $wpdb;
$fonts = [];
$sql = "\n SELECT * FROM {$wpdb->prefix}jooosi_fon_fonts\n WHERE status = 1\n AND deleted_at IS NULL\n ORDER BY title ASC\n ";
$result = $wpdb->get_results($sql);
foreach ($result as $row) {
$f = ['title' => $row->title, 'family' => $row->family, 'type' => $row->type, 'slug' => $row->slug, 'css' => ['slug' => self::slugify($row->family), 'custom_property' => self::css_custom_property($row->family), 'legacy_custom_property' => self::legacy_css_custom_property($row->family), 'variable' => self::css_variable($row->family)], 'variants' => [], 'fallback_family' => null];
$font_faces = FontCodec::decode((string) $row->font_faces);
foreach ($font_faces as $font_face) {
if (property_exists($font_face, 'isEnabled') && filter_var($font_face->isEnabled, \FILTER_VALIDATE_BOOLEAN) !== \true) {
continue;
}
$f['variants'][] = ['weight' => $font_face->weight, 'style' => $font_face->style];
}
$selectorParts = [];
$metadata = FontCodec::decode((string) $row->metadata);
// if property selector is exists
if (property_exists($metadata, 'selector') && $metadata->selector) {
$selectorParts = explode('|', $metadata->selector);
$selectorParts = array_map('trim', $selectorParts);
$selectorParts = array_filter($selectorParts);
$f['fallback_family'] = $selectorParts[1] ?? null;
}
$fonts[] = $f;
}
wp_cache_set(self::CACHE_KEY, $fonts, JOOOSI_FON::WP_OPTION);
}
return $fonts;
}
/**
* Invalidate font data consumed by integrations and WordPress theme.json.
*/
public static function clear_cache(): void
{
wp_cache_delete(self::CACHE_KEY, JOOOSI_FON::WP_OPTION);
if (method_exists(\WP_Theme_JSON_Resolver::class, 'clean_cached_data')) {
\WP_Theme_JSON_Resolver::clean_cached_data();
}
}
/**
* @param string $value font family name
* @return string css custom property wrapped with variable function. e.g. `var(--jf--family-open-sans)` for `Open Sans`
*/
public static function css_variable(string $value): string
{
return sprintf('var(%s)', self::css_custom_property($value));
}
/**
* @param string $value font family name
* @return string css custom property. e.g. `--jf--family-open-sans` for `Open Sans`
*/
public static function css_custom_property(string $value): string
{
return sprintf('--jf--family-%s', self::slugify($value));
}
/**
* Return the pre-rebrand property name retained as a generated CSS alias.
*
* @todo Remove this legacy CSS property alias completely in Jooosi Fon 3.0.0.
*/
public static function legacy_css_custom_property(string $value): string
{
return sprintf('--ywf--family-%s', self::slugify($value));
}
/**
* @param string $value font family name
* @return string slugified string. e.g. `open-sans` for `Open Sans`
*/
public static function slugify(string $value): string
{
return preg_replace('#[^a-zA-Z0-9\-_]+#', '-', strtolower($value));
}
}
@@ -0,0 +1,106 @@
<?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\Utils;
use JooosiFonDeps\JOOOSI_FON;
/**
* Manage the plugin's notices for the wp-admin page.
*
* @author Joshua Gugun Siagian <suabahasa@gmail.com>
*/
class Notice
{
/**
* @var string
*/
public const ERROR = 'error';
/**
* @var string
*/
public const SUCCESS = 'success';
/**
* @var string
*/
public const WARNING = 'warning';
/**
* @var string
*/
public const INFO = 'info';
/**
* @var string
*/
public const OPTION_NAME = JOOOSI_FON::WP_OPTION . '_notices';
/**
* Get lists of notices.
*/
public static function get_lists(?bool $purge = \true): array
{
$notices = get_option(self::OPTION_NAME, []);
if ($purge) {
update_option(self::OPTION_NAME, []);
}
return $notices;
}
public static function add(string $status, string $message, ?string $key = null, bool $unique = \false): void
{
$notices = get_option(self::OPTION_NAME, []);
$payload = ['status' => $status, 'message' => $message];
if ($unique) {
if ($key && isset($notices[$key])) {
return;
}
if (in_array(['status' => $status, 'message' => $message], $notices, \true)) {
return;
}
}
if ($key) {
$notices[$key] = $payload;
} else {
$notices[] = $payload;
}
update_option(self::OPTION_NAME, $notices);
}
/**
* Add bulk notices.
*
* @param string|array $messages a message or an array of messages to add.
*/
public static function adds(string $status, $messages): void
{
if (!is_array($messages)) {
$messages = [$messages];
}
foreach ($messages as $message) {
if (!is_array($message)) {
self::add($status, $message);
} else {
self::add($status, ...$message);
}
}
}
public static function success(string $message, ?string $key = null, bool $unique = \false): void
{
self::add(self::SUCCESS, ...func_get_args());
}
public static function warning(string $message, ?string $key = null, bool $unique = \false): void
{
self::add(self::WARNING, ...func_get_args());
}
public static function info(string $message, ?string $key = null, bool $unique = \false): void
{
self::add(self::INFO, ...func_get_args());
}
public static function error(string $message, ?string $key = null, bool $unique = \false): void
{
self::add(self::ERROR, ...func_get_args());
}
}
@@ -0,0 +1,230 @@
<?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\Utils;
use Exception;
use WP_Error;
/**
* Upload utility functions for the plugin.
*
* @author Joshua Gugun Siagian <suabahasa@gmail.com>
* @todo Remove the legacy Yabe Webfont filter shim completely in Jooosi Fon 3.0.0.
*/
class Upload
{
public const UPLOAD_DIRECTORY = 'jooosi-fon/fonts';
/**
* Add the font mime types to the allowed upload mimes.
*
* @see https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face#description
* @see https://developer.wordpress.org/reference/hooks/upload_mimes/
*/
public static function upload_mimes(array $mimes, bool $manual_upload = \false): array
{
if (!$manual_upload && (!current_user_can('manage_options') || !isset($_POST['jooosi_fon_font_upload']))) {
return $mimes;
}
$exts = ['woff2' => 'font/woff2', 'woff' => 'font/woff', 'ttf' => 'font/ttf', 'otf' => 'font/otf', 'eot' => 'font/eot'];
foreach ($exts as $ext => $ext_mime) {
if (!isset($mimes[$ext])) {
$mimes[$ext] = $ext_mime;
}
}
return $mimes;
}
/**
* Disable real MIME check (introduced in WordPress 4.7.1)
*
* @see https://wordpress.stackexchange.com/a/252296/44794
* @see https://developer.wordpress.org/reference/hooks/wp_check_filetype_and_ext/
*/
public static function disable_real_mime_check(array $data, string $file, string $filename, $mimes)
{
$filetype = wp_check_filetype($filename, $mimes);
return ['ext' => $filetype['ext'], 'type' => $filetype['type'], 'proper_filename' => $data['proper_filename']];
}
/**
* Remote upload file to WordPress media library.
* The implementation is based on the https://rudrastyh.com/wordpress/how-to-add-images-to-media-library-from-uploaded-files-programmatically.html#upload-image-from-url
*
* @param string $file_url URL of the remote file
* @param string $file_name Name of the remote file to be stored in the media library
* @param string $mime_type Mime type of the remote file
* @return int|WP_Error|false Attachment ID on success, WP_Error or false on failure
* @throws Exception
*/
public static function remote_upload_media(string $file_url, string $file_name, string $mime_type)
{
require_once \ABSPATH . 'wp-admin/includes/file.php';
$file_url = apply_filters('f!jooosi/fon/utils/upload:remote_upload_media.file_url', $file_url);
$file_url = apply_filters_deprecated('f!yabe/webfont/utils/upload:remote_upload_media.file_url', [$file_url], '2.1.0', 'f!jooosi/fon/utils/upload:remote_upload_media.file_url');
$temp_file = download_url($file_url, 30);
if (is_wp_error($temp_file)) {
return $temp_file;
}
$sideload_path = null;
add_filter('upload_dir', [self::class, 'font_upload_dir']);
try {
$size = filesize($temp_file);
$max_size = (int) apply_filters('f!jooosi/fon/utils/upload:max_file_size', 20 * \MB_IN_BYTES);
if (!is_int($size) || $size < 1 || $size > $max_size) {
return new WP_Error('jooosi_fon_invalid_file_size', 'The font file is empty or exceeds the upload limit.');
}
$file = ['name' => $file_name, 'type' => $mime_type, 'tmp_name' => $temp_file, 'size' => $size];
$sideload = wp_handle_sideload($file, ['test_form' => \false, 'test_size' => \true]);
if (!empty($sideload['error'])) {
return new WP_Error('jooosi_fon_sideload_failed', (string) $sideload['error']);
}
$sideload_path = $sideload['file'];
$attachment_id = wp_insert_attachment(['guid' => $sideload['url'], 'post_mime_type' => $sideload['type'], 'post_title' => basename($sideload['file']), 'post_content' => '', 'post_status' => 'inherit'], $sideload['file']);
if (is_wp_error($attachment_id)) {
wp_delete_file($sideload_path);
return $attachment_id;
}
if (!is_int($attachment_id) || $attachment_id < 1) {
wp_delete_file($sideload_path);
return new WP_Error('jooosi_fon_attachment_failed', 'The font attachment could not be created.');
}
return $attachment_id;
} finally {
remove_filter('upload_dir', [self::class, 'font_upload_dir']);
if (file_exists($temp_file)) {
unlink($temp_file);
}
}
}
/**
* Remote upload file to WordPress media library.
* The implementation is based on the https://rudrastyh.com/wordpress/how-to-add-images-to-media-library-from-uploaded-files-programmatically.html#upload-image-from-url
*
* @param string $binary binary-safe string containing the file
* @param string $file_name Name of the remote file to be stored in the media library
* @param string $mime_type Mime type of the remote file
* @return int|WP_Error|false Attachment ID on success, WP_Error or false on failure
* @throws Exception
*/
public static function binary_upload_media(string $binary, string $file_name, string $mime_type)
{
require_once \ABSPATH . 'wp-admin/includes/file.php';
$max_size = (int) apply_filters('f!jooosi/fon/utils/upload:max_file_size', 20 * \MB_IN_BYTES);
if ($binary === '' || strlen($binary) > $max_size) {
return new WP_Error('jooosi_fon_invalid_file_size', 'The font file is empty or exceeds the upload limit.');
}
$temp_file = wp_tempnam($file_name);
if (!$temp_file) {
return \false;
}
$sideload_path = null;
add_filter('upload_dir', [self::class, 'font_upload_dir']);
try {
$written = file_put_contents($temp_file, $binary);
if ($written === \false || $written !== strlen($binary)) {
return new WP_Error('jooosi_fon_temp_write_failed', 'The temporary font file could not be written.');
}
$file = ['name' => $file_name, 'type' => $mime_type, 'tmp_name' => $temp_file, 'size' => $written];
$sideload = wp_handle_sideload($file, ['test_form' => \false, 'test_size' => \true]);
if (!empty($sideload['error'])) {
return new WP_Error('jooosi_fon_sideload_failed', (string) $sideload['error']);
}
$sideload_path = $sideload['file'];
$attachment_id = wp_insert_attachment(['guid' => $sideload['url'], 'post_mime_type' => $sideload['type'], 'post_title' => basename($sideload['file']), 'post_content' => '', 'post_status' => 'inherit'], $sideload['file']);
if (is_wp_error($attachment_id)) {
wp_delete_file($sideload_path);
return $attachment_id;
}
if (!is_int($attachment_id) || $attachment_id < 1) {
wp_delete_file($sideload_path);
return new WP_Error('jooosi_fon_attachment_failed', 'The font attachment could not be created.');
}
return $attachment_id;
} finally {
remove_filter('upload_dir', [self::class, 'font_upload_dir']);
if (file_exists($temp_file)) {
unlink($temp_file);
}
}
}
/**
* @see https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/src#font_formats
* @param string $mime file extension or mime type
*/
public static function mime_keyword(string $mime): string
{
switch ($mime) {
case 'woff2':
case 'font/woff2':
return 'woff2';
case 'woff':
case 'font/woff':
return 'woff';
case 'ttf':
case 'font/ttf':
return 'truetype';
case 'otf':
case 'font/otf':
return 'opentype';
case 'eot':
case 'font/eot':
return 'embedded-opentype';
default:
return 'woff2';
}
}
/**
* Get the new attachment url of a font face.
*/
public static function refresh_font_faces_attachment_url(array $font_faces): array
{
foreach ($font_faces as $i => $font_face) {
foreach ($font_face->files as $j => $file) {
$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'];
}
}
}
return $font_faces;
}
/**
* Get the new attachment url of a Google Fonts.
*/
public static function refresh_google_fonts_attachment_url(array $font_files): array
{
foreach ($font_files as $i => $font_file) {
if (property_exists($font_file, 'file')) {
$attachment_url = wp_get_attachment_url($font_file->file->attachment_id);
if ($attachment_url) {
$parsed = parse_url($attachment_url);
$font_files[$i]->file->attachment_url = $parsed['path'];
}
}
}
return $font_files;
}
public static function font_upload_dir(array $dir_data): array
{
$dir_data['path'] = $dir_data['basedir'] . '/' . self::UPLOAD_DIRECTORY;
$dir_data['subdir'] = '/' . self::UPLOAD_DIRECTORY;
$dir_data['url'] = $dir_data['baseurl'] . '/' . self::UPLOAD_DIRECTORY;
return $dir_data;
}
/**
* @deprecated 2.1.0 Use font_upload_dir() instead.
* @todo Remove this legacy method alias completely in Jooosi Fon 3.0.0.
*/
public static function wpse_custom_upload_dir($dir_data): array
{
_deprecated_function(__METHOD__, '2.1.0', __CLASS__ . '::font_upload_dir');
return self::font_upload_dir((array) $dir_data);
}
}