Initial commit xmarticaims

This commit is contained in:
2026-11-02 10:26:32 -06:00
commit e74236f5c1
9764 changed files with 2880647 additions and 0 deletions
@@ -0,0 +1,163 @@
<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
class CompressX_Addons_Display
{
public function __construct()
{
}
public function display()
{
?>
<div class="compressx-root">
<div class="compressx-v2-py-6 compressx-v2-w-full compressx-v2-max-w-[1200px] compressx-v2-mx-auto">
<?php
$this->output_header();
$this->output_addons();
$this->output_footer();
?>
</div>
</div>
<?php
}
public function output_header()
{
?>
<div class=" compressx-v2-pr-4 compressx-v2-flex compressx-v2-items-center compressx-v2-justify-between compressx-v2-mb-4">
<div>
<h1 class="compressx-v2-text-2xl compressx-v2-font-semibold compressx-v2-text-gray-900">
<?php echo esc_html(__('Addons', 'compressx')); ?>
</h1>
<p class="compressx-v2-text-sm compressx-v2-text-gray-600 compressx-v2-mt-2">
<?php echo esc_html(__('Extra utilities to simplify your workflow and manage images beyond compression.', 'compressx')); ?>
</p>
</div>
<div class="compressx-v2-mt-4">
<button onclick="window.open('https://compressx.io/pricing', '_blank')" class="compressx-v2-bg-blue-600 hover:compressx-v2-bg-blue-700 compressx-v2-text-white compressx-v2-rounded compressx-v2-px-4 compressx-v2-py-2 compressx-v2-text-sm">
<?php esc_html_e('Upgrade Now', 'compressx') ?>
</button>
</div>
</div>
<?php
}
public function output_addons()
{
?>
<section class="compressx-v2-bg-white compressx-v2-rounded compressx-v2-shadow-sm compressx-v2-border compressx-v2-p-6">
<div class="compressx-v2-grid sm:compressx-v2-grid-cols-2 lg:compressx-v2-grid-cols-3 compressx-v2-gap-6">
<div class="compressx-v2-bg-white compressx-v2-rounded compressx-v2-shadow-sm compressx-v2-border compressx-v2-p-5 compressx-v2-flex compressx-v2-flex-col compressx-v2-justify-between">
<div>
<h2 class="compressx-v2-text-lg compressx-v2-font-medium compressx-v2-flex compressx-v2-items-center compressx-v2-gap-2">
<?php esc_html_e('Advanced Compression Level Settings', 'compressx') ?>
</h2>
<p class="compressx-v2-text-sm compressx-v2-text-gray-500 compressx-v2-mt-2">
<?php esc_html_e('Maximize image optimization with smart algorithms that reduce file size while preserving visual quality. Ideal for users who want the best balance of speed and image clarity for their site', 'compressx') ?>
</p>
</div>
</div>
<div class="compressx-v2-bg-white compressx-v2-rounded compressx-v2-shadow-sm compressx-v2-border compressx-v2-p-5 compressx-v2-flex compressx-v2-flex-col compressx-v2-justify-between">
<div>
<h2 class="compressx-v2-text-lg compressx-v2-font-medium compressx-v2-flex compressx-v2-items-center compressx-v2-gap-2">
<?php esc_html_e('Remove JPG/PNG Thumbnails', 'compressx') ?>
</h2>
<p class="compressx-v2-text-sm compressx-v2-text-gray-500 compressx-v2-mt-2">
<?php esc_html_e('Automatically delete original JPG/PNG thumbnails after converting them to WebP or AVIF to free up disk space.', 'compressx') ?>
</p>
</div>
</div>
<div class="compressx-v2-bg-white compressx-v2-rounded compressx-v2-shadow-sm compressx-v2-border compressx-v2-p-5 compressx-v2-flex compressx-v2-flex-col compressx-v2-justify-between">
<div>
<h2 class="compressx-v2-text-lg compressx-v2-font-medium compressx-v2-flex compressx-v2-items-center compressx-v2-gap-2">
<?php esc_html_e('Cron Support', 'compressx') ?>
</h2>
<p class="compressx-v2-text-sm compressx-v2-text-gray-500 compressx-v2-mt-2">
<?php esc_html_e('Automates your image optimization workflows with a robust cron system, flexibly scheduling AVIF/WebP conversions for new, existing, and popular images.', 'compressx') ?>
</p>
</div>
</div>
<div class="compressx-v2-bg-white compressx-v2-rounded compressx-v2-shadow-sm compressx-v2-border compressx-v2-p-5 compressx-v2-flex compressx-v2-flex-col compressx-v2-justify-between">
<div>
<h2 class="compressx-v2-text-lg compressx-v2-font-medium compressx-v2-flex compressx-v2-items-center compressx-v2-gap-2">
<?php esc_html_e('Thumbnails Generation/reGeneration', 'compressx') ?>
</h2>
<p class="compressx-v2-text-sm compressx-v2-text-gray-500 compressx-v2-mt-2">
<?php esc_html_e('Regenerate thumbnails (WebP, AVIF, JPG, or PNG) for your website images based on your settings. Add custom thumbnail sizes. Remove unused and orphan thumbnails and their metadata.', 'compressx') ?>
</p>
</div>
</div>
<div class="compressx-v2-bg-white compressx-v2-rounded compressx-v2-shadow-sm compressx-v2-border compressx-v2-p-5 compressx-v2-flex compressx-v2-flex-col compressx-v2-justify-between">
<div>
<h2 class="compressx-v2-text-lg compressx-v2-font-medium compressx-v2-flex compressx-v2-items-center compressx-v2-gap-2">
<?php esc_html_e('WP-CLI', 'compressx') ?>
</h2>
<p class="compressx-v2-text-sm compressx-v2-text-gray-500 compressx-v2-mt-2">
<?php esc_html_e('Use WP-CLI to efficiently convert images in your WordPress media library. You can choose to convert all images, or a specific image, or convert the latest n images.', 'compressx') ?>
</p>
</div>
</div>
<div class="compressx-v2-bg-white compressx-v2-rounded compressx-v2-shadow-sm compressx-v2-border compressx-v2-p-5 compressx-v2-flex compressx-v2-flex-col compressx-v2-justify-between">
<div>
<h2 class="compressx-v2-text-lg compressx-v2-font-medium compressx-v2-flex compressx-v2-items-center compressx-v2-gap-2">
<?php esc_html_e('Watermark', 'compressx') ?>
</h2>
<p class="compressx-v2-text-sm compressx-v2-text-gray-500 compressx-v2-mt-2">
<?php esc_html_e('Add watermarks to your images during the process of uploading, bulk WebP/AVIF conversion, and thumbnail regeneration (WebP, AVIF, JPG, or PNG).', 'compressx') ?>
</p>
</div>
</div>
<div class="compressx-v2-bg-white compressx-v2-rounded compressx-v2-shadow-sm compressx-v2-border compressx-v2-p-5 compressx-v2-flex compressx-v2-flex-col compressx-v2-justify-between">
<div>
<h2 class="compressx-v2-text-lg compressx-v2-font-medium compressx-v2-flex compressx-v2-items-center compressx-v2-gap-2">
<?php esc_html_e('CDN Integration', 'compressx') ?>
</h2>
<p class="compressx-v2-text-sm compressx-v2-text-gray-500 compressx-v2-mt-2">
<?php esc_html_e('Integrate with Cloudflare Pro and and BunnyCDN to convert and serve your website images as WebP/AVIF formats. Enable \'Vary for images\' to dynamically serve correct variants.', 'compressx') ?>
</p>
</div>
</div>
<div class="compressx-v2-bg-white compressx-v2-rounded compressx-v2-shadow-sm compressx-v2-border compressx-v2-p-5 compressx-v2-flex compressx-v2-flex-col compressx-v2-justify-between">
<div>
<h2 class="compressx-v2-text-lg compressx-v2-font-medium compressx-v2-flex compressx-v2-items-center compressx-v2-gap-2">
<?php esc_html_e('Roles and Capabilities', 'compressx') ?>
</h2>
<p class="compressx-v2-text-sm compressx-v2-text-gray-500 compressx-v2-mt-2">
<?php esc_html_e('Control CompressX Pro settings and features by setting a super admin. The super admin can grant access for other user roles include admin.', 'compressx') ?>
</p>
</div>
</div>
<div class="compressx-v2-bg-white compressx-v2-rounded compressx-v2-shadow-sm compressx-v2-border compressx-v2-p-5 compressx-v2-flex compressx-v2-flex-col compressx-v2-justify-between">
<div>
<h2 class="compressx-v2-text-lg compressx-v2-font-medium compressx-v2-flex compressx-v2-items-center compressx-v2-gap-2">
<?php esc_html_e('Multisite Support', 'compressx') ?>
</h2>
<p class="compressx-v2-text-sm compressx-v2-text-gray-500 compressx-v2-mt-2">
<?php esc_html_e('Manage and optimize images across all sites in your WordPress Multisite network from a single dashboard.', 'compressx') ?>
</p>
</div>
</div>
</div>
</section>
<?php
}
public function output_footer()
{
do_action('compressx_output_footer');
}
}
@@ -0,0 +1,438 @@
<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
class CompressX_CDN_Display
{
public function __construct()
{
add_action('wp_ajax_compressx_save_cdn', array($this, 'save_cdn'));
add_action('wp_ajax_compressx_purge_cache', array($this, 'purge_cache'));
}
public function display()
{
?>
<div class="compressx-root">
<div class="compressx-v2-py-6 compressx-v2-w-full compressx-v2-max-w-[1200px] compressx-v2-mx-auto">
<?php
$this->output_header();
$this->output_cdn();
$this->output_save_section();
$this->output_footer();
?>
</div>
</div>
<?php
}
public function output_cdn()
{
$options = CompressX_Options::get_option('compressx_general_settings', array());
$zone_id = isset($options['cf_cdn']['zone_id']) ? $options['cf_cdn']['zone_id'] : '';
$email = isset($options['cf_cdn']['email']) ? $options['cf_cdn']['email'] : '';
$api_key = isset($options['cf_cdn']['api_key']) ? $options['cf_cdn']['api_key'] : '';
$auto_purge_cache = isset($options['cf_cdn']['auto_purge_cache']) ? $options['cf_cdn']['auto_purge_cache'] : true;
$auto_purge_cache_after_manual = isset($options['cf_cdn']['auto_purge_cache_after_manual']) ? $options['cf_cdn']['auto_purge_cache_after_manual'] : true;
$auto_purge_cache_checked = $auto_purge_cache ? 'checked' : '';
$auto_purge_cache_after_manual_checked = $auto_purge_cache_after_manual ? 'checked' : '';
?>
<section class="compressx-v2-bg-white compressx-v2-rounded compressx-v2-shadow-sm compressx-v2-border compressx-v2-mb-4 compressx-v2-p-6">
<div class="compressx-v2-bg-white compressx-v2-rounded compressx-v2-border compressx-v2-mb-4 compressx-v2-p-6">
<h2 class="compressx-v2-text-lg compressx-v2-font-medium"><?php esc_html_e('CDN Provider', 'compressx'); ?></h2>
<p class="compressx-v2-text-sm compressx-v2-text-gray-500"><?php esc_html_e('Select your CDN provider to configure integration details.', 'compressx'); ?></p>
<select id="compressx_cdn_provider" class="compressx-v2-mt-3 compressx-v2-w-64 compressx-v2-border compressx-v2-rounded compressx-v2-px-3 compressx-v2-py-2 compressx-v2-text-sm">
<option value="cloudflare"><?php esc_html_e('Cloudflare', 'compressx'); ?></option>
<option value="bunnycdn"><?php esc_html_e('BunnyCDN', 'compressx'); ?></option>
</select>
</div>
<div id="cloudflare_container">
<?php
$this->render_cloudflare_settings($zone_id, $email, $api_key);
$this->render_cloudflare_features($auto_purge_cache_checked, $auto_purge_cache_after_manual_checked);
?>
</div>
<?php $this->render_bunnycdn_placeholder(); ?>
</section>
<?php
}
public function render_cloudflare_settings($zone_id = '', $email = '', $api_key = '')
{
?>
<div id="cloudflare_settings" class="compressx-v2-bg-white compressx-v2-rounded compressx-v2-border compressx-v2-mb-4 compressx-v2-p-6">
<h2 class="compressx-v2-text-lg compressx-v2-font-medium"><?php esc_html_e('Cloudflare Integration', 'compressx'); ?></h2>
<p class="compressx-v2-text-sm compressx-v2-text-gray-500"><?php esc_html_e('Provide credentials to allow CompressX to connect with Cloudflare.', 'compressx'); ?></p>
<div class="compressx-v2-grid compressx-v2-grid-cols-2 compressx-v2-gap-4 compressx-v2-mt-4">
<div>
<label class="compressx-v2-text-sm">
<?php esc_html_e('Global API Key', 'compressx'); ?>
<?php
$this->output_tooltip(
'cf-api-key-tip',
__('A key for granting access to Cloudflare API to perform actions. You can find it in your Cloudflare dashboard > My Profile > API Tokens > Global API Key.', 'compressx'),
'small'
);
?>
</label>
<input type="password" autocomplete="new-password" option="cf_cdn" name="api_key" value="<?php echo esc_attr($api_key); ?>" class="compressx-v2-w-full compressx-v2-border compressx-v2-rounded compressx-v2-px-3 compressx-v2-py-2">
</div>
<div>
<label class="compressx-v2-text-sm">
<?php esc_html_e('Cloudflare Email', 'compressx'); ?>
<?php
$this->output_tooltip(
'cf-email-tip',
__('Email address associated to your Cloudflare account.', 'compressx'),
'small'
);
?>
</label>
<input type="text" option="cf_cdn" name="email" value="<?php echo esc_attr($email); ?>" class="compressx-v2-w-full compressx-v2-border compressx-v2-rounded compressx-v2-px-3 compressx-v2-py-2">
</div>
<div>
<label class="compressx-v2-text-sm">
<?php esc_html_e('Zone ID', 'compressx'); ?>
<?php
$this->output_tooltip(
'cf-zone-id-tip',
__('A zone ID is generated automatically when a domain is added to Cloudflare and is required for API operations. You can find it in your Cloudflare Dashboard > The website overview > API section.', 'compressx'),
'small'
);
?>
</label>
<input type="password" autocomplete="new-password" option="cf_cdn" name="zone_id" value="<?php echo esc_attr($zone_id); ?>" class="compressx-v2-w-full compressx-v2-border compressx-v2-rounded compressx-v2-px-3 compressx-v2-py-2">
</div>
</div>
</div>
<?php
}
public function render_cloudflare_features($auto_purge_cache_checked = '', $auto_purge_cache_after_manual_checked = '')
{
?>
<div class="compressx-v2-bg-white compressx-v2-rounded compressx-v2-border compressx-v2-p-6">
<h2 class="compressx-v2-text-lg compressx-v2-font-medium"><?php esc_html_e('Features', 'compressx'); ?></h2>
<div id="cloudflare_features" class="compressx-v2-mt-3 compressx-v2-space-y-3">
<label class="compressx-v2-flex compressx-v2-items-center compressx-v2-gap-2">
<input type="checkbox" option="cf_cdn" name="auto_purge_cache" <?php echo esc_attr($auto_purge_cache_checked); ?> class="compressx-v2-mt-1">
<span class="compressx-v2-text-sm"><?php esc_html_e('Purge cache automatically after bulk image optimization.', 'compressx'); ?></span>
</label>
<label class="compressx-v2-flex compressx-v2-items-center compressx-v2-gap-2">
<input type="checkbox" option="cf_cdn" name="auto_purge_cache_after_manual" <?php echo esc_attr($auto_purge_cache_after_manual_checked); ?> class="compressx-v2-mt-1">
<span class="compressx-v2-text-sm"><?php esc_html_e('Purge cache automatically after manual image conversions (5 min delay).', 'compressx'); ?></span>
</label>
<div class="compressx-v2-mt-4">
<button id="compressx_purge_cache" class="compressx-v2-border compressx-v2-text-sm compressx-v2-rounded compressx-v2-px-3 compressx-v2-py-2 hover:compressx-v2-bg-gray-100">
<?php esc_html_e('Purge All Cloudflare CDN Cache Manually', 'compressx'); ?>
</button>
<span id="compressx_purge_cache_progress" style="display: none" class="compressx-v2-text-sm compressx-v2-text-blue-600 compressx-v2-ml-2">
<?php esc_html_e('Processing...', 'compressx'); ?>
</span>
<span id="compressx_purge_cache_text" class="success hidden compressx-v2-text-sm compressx-v2-text-green-600 compressx-v2-ml-2" aria-hidden="true">
<?php esc_html_e('Done!', 'compressx'); ?>
</span>
</div>
</div>
</div>
<?php
}
public function render_bunnycdn_placeholder()
{
?>
<div id="bunnycdn_container" style="display:none">
<div id="bunnycdn_settings" class="compressx-v2-bg-white compressx-v2-rounded compressx-v2-border compressx-v2-mb-4 compressx-v2-p-6 compressx-v2-relative compressx-v2-opacity-60">
<div class="compressx-v2-absolute compressx-v2-inset-0 compressx-v2-bg-white compressx-v2-bg-opacity-50 compressx-v2-rounded compressx-v2-cursor-not-allowed" style="z-index: 1;"></div>
<h2 class="compressx-v2-text-lg compressx-v2-font-medium"><?php esc_html_e('BunnyCDN Integration', 'compressx'); ?>
</h2>
<p class="compressx-v2-text-sm compressx-v2-text-gray-500"><?php esc_html_e('Provide credentials to allow CompressX to connect with BunnyCDN.', 'compressx'); ?>
<a href="https://compressx.io/pricing" target="_blank" class="compressx-v2-text-blue-600"><?php esc_html_e('Pro only', 'compressx') ?></a></p>
<div class="compressx-v2-grid compressx-v2-grid-cols-2 compressx-v2-gap-4 compressx-v2-mt-4">
<div>
<label class="compressx-v2-text-sm"><?php esc_html_e('Access Key', 'compressx'); ?>
</label>
<input type="password" autocomplete="new-password" disabled placeholder="<?php esc_attr_e('Pro Feature', 'compressx'); ?>" class="compressx-v2-w-full compressx-v2-border compressx-v2-rounded compressx-v2-px-3 compressx-v2-py-2 compressx-v2-bg-gray-50">
</div>
<div>
<label class="compressx-v2-text-sm"><?php esc_html_e('Pull Zone ID', 'compressx'); ?>
</label>
<input type="text" disabled placeholder="<?php esc_attr_e('Pro Feature', 'compressx'); ?>" class="compressx-v2-w-full compressx-v2-border compressx-v2-rounded compressx-v2-px-3 compressx-v2-py-2 compressx-v2-bg-gray-50">
</div>
</div>
</div>
<!-- BunnyCDN Features (Disabled) -->
<div id="bunnycdn_features" class="compressx-v2-bg-white compressx-v2-rounded compressx-v2-border compressx-v2-p-6 compressx-v2-relative compressx-v2-opacity-60">
<div class="compressx-v2-absolute compressx-v2-inset-0 compressx-v2-bg-white compressx-v2-bg-opacity-50 compressx-v2-rounded compressx-v2-cursor-not-allowed" style="z-index: 1;"></div>
<h2 class="compressx-v2-text-lg compressx-v2-font-medium"><?php esc_html_e('Features', 'compressx'); ?></h2>
<div class="compressx-v2-mt-3 compressx-v2-space-y-3">
<label class="compressx-v2-flex compressx-v2-items-center compressx-v2-gap-2">
<input type="checkbox" disabled class="compressx-v2-mt-1">
<span class="compressx-v2-text-sm">
<?php esc_html_e('Enable', 'compressx'); ?> <strong><?php esc_html_e('Vary for Images', 'compressx'); ?></strong>
<?php esc_html_e('(ensures proper delivery of image variants across browsers).', 'compressx'); ?>
</span>
</label>
<label class="compressx-v2-flex compressx-v2-items-center compressx-v2-gap-2">
<input type="checkbox" disabled class="compressx-v2-mt-1">
<span class="compressx-v2-text-sm"><?php esc_html_e('Purge cache automatically after bulk image optimization.', 'compressx'); ?></span>
</label>
<label class="compressx-v2-flex compressx-v2-items-center compressx-v2-gap-2">
<input type="checkbox" disabled class="compressx-v2-mt-1">
<span class="compressx-v2-text-sm"><?php esc_html_e('Purge cache automatically after manual image conversions (5 min delay).', 'compressx'); ?></span>
</label>
<div class="compressx-v2-mt-4">
<button disabled class="compressx-v2-border compressx-v2-text-sm compressx-v2-rounded compressx-v2-px-3 compressx-v2-py-2 compressx-v2-bg-gray-50 compressx-v2-cursor-not-allowed">
<?php esc_html_e('Purge All BunnyCDN Cache Manually', 'compressx'); ?>
</button>
</div>
</div>
</div>
</div>
<?php
}
public function output_header()
{
?>
<div class=" compressx-v2-pr-4 compressx-v2-flex compressx-v2-items-center compressx-v2-justify-between compressx-v2-mb-4">
<div>
<h1 class="compressx-v2-text-2xl compressx-v2-font-semibold compressx-v2-text-gray-900">
<?php echo esc_html(__('CDN Support', 'compressx')); ?>
</h1>
<p class="compressx-v2-text-sm compressx-v2-text-gray-600 compressx-v2-mt-2">
<?php echo esc_html(__('Connect CompressX with your CDN to deliver optimized images worldwide, with automatic cache purging and faster performance.', 'compressx')); ?>
</p>
</div>
</div>
<?php
}
public function output_save_section()
{
?>
<section class="compressx-v2-sticky compressx-v2-bottom-0 compressx-v2-bg-white compressx-v2-border-t compressx-v2-border-gray-200 compressx-v2-p-4">
<div class="compressx-v2-max-w-[1200px] compressx-v2-mx-auto compressx-v2-flex compressx-v2-justify-end compressx-v2-gap-3">
<div class="compressx-v2-flex compressx-v2-items-center compressx-v2-gap-3">
<button id="compressx_save_cdn" class="compressx-v2-inline-flex compressx-v2-items-center compressx-v2-gap-1 compressx-v2-bg-blue-600 hover:compressx-v2-bg-blue-700 compressx-v2-text-white compressx-v2-text-sm compressx-v2-font-medium compressx-v2-px-4 compressx-v2-py-2 compressx-v2-rounded">
<?php esc_html_e('Save Changes', 'compressx'); ?>
</button>
<span id="compressx_save_cdn_progress" style="display: none" class="compressx-v2-text-sm compressx-v2-text-blue-600">
<?php esc_html_e('Saving...', 'compressx'); ?>
</span>
<span id="compressx_save_cdn_text" class="success hidden compressx-v2-text-sm compressx-v2-text-green-600" aria-hidden="true">
<?php esc_html_e('Saved!', 'compressx'); ?>
</span>
</div>
</div>
</section>
<?php
}
public function output_tooltip($id, $content, $button_size = 'medium')
{
if (empty($content)) {
return;
}
// Button size classes
$size_classes = array(
'small' => 'compressx-v2-h-4 compressx-v2-w-4',
'medium' => 'compressx-v2-h-5 compressx-v2-w-5',
'large' => 'compressx-v2-h-6 compressx-v2-w-6'
);
$button_class = isset($size_classes[$button_size]) ? $size_classes[$button_size] : $size_classes['medium'];
?>
<div class="compressx-v2-relative compressx-v2-inline-flex compressx-v2-items-center compressx-v2-group">
<button
type="button"
class="compressx-v2-inline-flex compressx-v2-items-center compressx-v2-justify-center <?php echo esc_attr($button_class) ?> compressx-v2-rounded compressx-v2-border compressx-v2-border-slate-300 compressx-v2-bg-white hover:compressx-v2-bg-slate-50 compressx-v2-text-slate-600 hover:compressx-v2-text-slate-800 compressx-v2-shadow-sm focus:compressx-v2-outline-none focus:compressx-v2-ring-2 focus:compressx-v2-ring-sky-400"
aria-describedby="<?php echo esc_attr($id) ?>"
data-tooltip-toggle>
<span class="compressx-v2-font-semibold compressx-v2-text-xs">i</span>
</button>
<div
id="<?php echo esc_attr($id) ?>"
role="tooltip"
class="compressx-v2-absolute compressx-v2-z-50 compressx-v2-bottom-full compressx-v2-left-1/2 -compressx-v2-translate-x-1/2 compressx-v2-mb-2
compressx-v2-hidden group-hover:compressx-v2-block group-focus-within:compressx-v2-block
compressx-v2-min-w-64 compressx-v2-max-w-96 compressx-v2-rounded compressx-v2-bg-slate-900/95 compressx-v2-text-white compressx-v2-text-xs compressx-v2-leading-5 compressx-v2-px-3 compressx-v2-py-3
compressx-v2-shadow-xl compressx-v2-ring-1 compressx-v2-ring-black/10">
<div class="compressx-v2-flex compressx-v2-gap-2 compressx-v2-items-start">
<span class="compressx-v2-mt-0.5 compressx-v2-inline-block compressx-v2-h-1.5 compressx-v2-w-1.5 compressx-v2-rounded compressx-v2-bg-emerald-400"></span>
<div>
<div class="compressx-v2-font-medium compressx-v2-text-[11px] compressx-v2-tracking-wide compressx-v2-text-emerald-300 compressx-v2-mb-0.5">
<?php esc_html_e('Tip', 'compressx') ?>
</div>
<div>
<?php echo wp_kses_post($content) ?>
</div>
</div>
</div>
<!-- Caret -->
<div class="compressx-v2-absolute compressx-v2-left-1/2 -compressx-v2-translate-x-1/2 compressx-v2-top-full compressx-v2-h-2 compressx-v2-w-2 compressx-v2-rotate-45 compressx-v2-bg-slate-900/95"></div>
</div>
</div>
<?php
}
public function output_footer()
{
do_action('compressx_output_footer');
}
public function save_cdn()
{
global $compressx;
$compressx->ajax_check_security('compressx-can-use-cdn');
if(isset($_POST['setting'])&&!empty($_POST['setting']))
{
$json_setting = sanitize_text_field($_POST['setting']);
$json_setting = stripslashes($json_setting);
$setting = json_decode($json_setting, true);
if (is_null($setting))
{
$ret['result']='failed';
$ret['error']='json decode failed';
echo wp_json_encode($ret);
die();
}
if($this->need_test($setting))
{
include_once COMPRESSX_DIR . '/includes/class-compressx-cloudflare-cdn.php';
$cdn=new CompressX_CloudFlare_CDN($setting);
$ret=$cdn->purge_cache();
if($ret['result']!='success')
{
echo wp_json_encode($ret);
die();
}
}
$options=CompressX_Options::get_option('compressx_general_settings',array());
if(isset($setting['zone_id'])) {
$options['cf_cdn']['zone_id']=$setting['zone_id'];
}
if(isset($setting['email'])) {
$options['cf_cdn']['email']=$setting['email'];
}
if(isset($setting['api_key'])) {
$options['cf_cdn']['api_key']=$setting['api_key'];
}
if(isset($setting['auto_purge_cache']))
{
$options['cf_cdn']['auto_purge_cache']=$setting['auto_purge_cache'];
}
else
{
$options['cf_cdn']['auto_purge_cache']=false;
}
if(isset($setting['auto_purge_cache_after_manual']))
{
$options['cf_cdn']['auto_purge_cache_after_manual']=$setting['auto_purge_cache_after_manual'];
}
else
{
$options['cf_cdn']['auto_purge_cache_after_manual']=false;
}
CompressX_Options::update_option('compressx_general_settings',$options);
$ret['result']='success';
echo wp_json_encode($ret);
die();
}
else
{
die();
}
}
public function need_test($setting)
{
if(isset($setting['auto_purge_cache'])&&$setting['auto_purge_cache'])
{
return true;
}
if(isset($setting['auto_purge_cache_after_manual'])&&$setting['auto_purge_cache_after_manual'])
{
return true;
}
return false;
}
public function purge_cache()
{
global $compressx;
$compressx->ajax_check_security('compressx-can-use-cdn');
if(isset($_POST['setting'])&&!empty($_POST['setting']))
{
$json_setting = sanitize_text_field($_POST['setting']);
$json_setting = stripslashes($json_setting);
$setting = json_decode($json_setting, true);
if (is_null($setting))
{
$ret['result']='failed';
$ret['error']='json decode failed';
echo wp_json_encode($ret);
die();
}
include_once COMPRESSX_DIR . '/includes/class-compressx-cloudflare-cdn.php';
$cdn=new CompressX_CloudFlare_CDN($setting);
$ret=$cdn->purge_cache();
echo wp_json_encode($ret);
die();
}
else
{
include_once COMPRESSX_DIR . '/includes/class-compressx-cloudflare-cdn.php';
$options=CompressX_Options::get_option('compressx_general_settings',array());
$setting=$options['cf_cdn'];
$cdn=new CompressX_CloudFlare_CDN($setting);
$ret=$cdn->purge_cache();
echo wp_json_encode($ret);
die();
}
}
}
@@ -0,0 +1,676 @@
<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
class CompressX_Custom_Bulk_Action_V2
{
public $support_extension;
public function __construct()
{
$this->support_extension=array();
$this->support_extension[]='jpg';
$this->support_extension[]='jpeg';
$this->support_extension[]='png';
$this->support_extension[]='webp';
add_action('wp_ajax_compressx_get_custom_tree_dir_ex', array($this, 'get_custom_tree_dir_ex'));
add_action('wp_ajax_compressx_add_include_folders', array($this, 'add_include_folders'));
add_action('wp_ajax_compressx_remove_include_folders', array($this, 'remove_include_folders'));
//
add_action('wp_ajax_compressx_start_scan_custom_images', array($this, 'start_scan_custom_images'));
add_action('wp_ajax_compressx_init_custom_bulk_optimization_task', array($this, 'init_custom_bulk_optimization_task'));
add_action('wp_ajax_compressx_run_custom_optimize', array($this, 'run_custom_optimize'));
add_action('wp_ajax_compressx_get_custom_opt_progress', array($this, 'get_custom_opt_progress'));
add_action('wp_ajax_compressx_get_dir_info', array($this, 'get_dir_info'));
//
add_action('cx_output_custom_bulk',array($this, 'output_custom_bulk'));
}
public function output_custom_bulk()
{
CompressX_Custom_Image_Meta::check_custom_table();
$includes=CompressX_Options::get_option('compressx_custom_includes',array());
$stats=$this->get_custom_stats($includes);
$found=$stats['files'];
$saved=$stats['saved'];
$processed=$stats['processed_files'];
?>
<header>
<div class="compressx-container compressx-header">
<div class="compressx-general-settings" style="padding-bottom: 0;">
<div class="compressx-general-settings-header">
<h5><?php esc_html_e('Custom Folders','compressx')?></h5>
</div>
<div class="compressing-converting-information" style="margin-top: 1rem;">
<?php esc_html_e('Select custom folders in the /wp-content folder and process images inside them.','compressx')?>
</div>
<div class="compressx-general-settings-body">
<?php
$this->output_custom_folders();
?>
<div class="cx-custom-overview">
<div>
<span id="cx_custom_overview">
<span><?php esc_html_e('Media Files Found: ','compressx')?></span><span id="cx_custom_founds"><?php echo esc_html($found);?></span><span> | </span>
<span><?php esc_html_e('Total Savings: ','compressx')?></span><span id="cx_custom_total_saving"><?php echo esc_html($saved);?></span><span>%</span><span> | </span>
<span><?php esc_html_e('Processed Media Files: ','compressx')?></span><span id="cx_custom_processed"><?php echo esc_html($processed);?></span>
</span>
</div>
<div style="padding-top:1rem;">
<input type="submit" id="compressx_start_custom_bulk_optimization" class="button-primary cx-button" value="<?php esc_attr_e('Bulk Process Now','compressx')?>">
<input class="button-primary cx-button" style="display: none" id="compressx_cancel_custom_bulk_optimization" type="submit" value="<?php esc_attr_e('Cancel Processing','compressx')?>">
<span id="cx_custom_bulk_progress_text" style="display: none"></span>
</div>
<div style="padding-top:1rem;">
<span><input id="cx_custom_force_optimization" type="checkbox"><?php esc_html_e('Force all images to be re-processed','compressx')?></span>
</div>
</div>
</div>
</div>
</div>
</header>
<?php
}
public function get_custom_stats($includes)
{
$stats=array();
$stats['files']=0;
$stats['saved']=0;
$stats['processed_files']=0;
$stats['total']=0;
$stats['processed']=0;
$convert_to_webp=CompressX_Image_Opt_Method::get_convert_to_webp();
$convert_to_avif=CompressX_Image_Opt_Method::get_convert_to_avif();
foreach ($includes as $include)
{
$this->get_folder_stats($include,$stats,$convert_to_webp,$convert_to_avif);
}
if($stats['total']>0)
{
$stats['saved'] = ( $stats['processed'] / $stats['total'] ) * 100;
$stats['saved'] = round( $stats['saved'], 1 );
}
return $stats;
}
public function get_folder_stats($path,&$stats,$convert_to_webp,$convert_to_avif)
{
try {
$count=0;
$rii = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path));
foreach ($rii as $file)
{
if ($file->isDir())
{
continue;
}
if($this->is_support_extension($file->getExtension()))
{
$filename=$path.'/'.$file->getFilename();
$filename=$this->transfer_path($filename);
$type=pathinfo($filename, PATHINFO_EXTENSION);
if($convert_to_webp&&$type!="webp")
{
if(CompressX_Custom_Image_Meta::is_convert_webp($filename))
{
$stats['processed_files']++;
$stats['processed']+=CompressX_Custom_Image_Meta::get_convert_webp_size($filename);
}
$count++;
$stats['files']++;
$stats['total']+=$file->getSize();
}
else if($convert_to_avif&&$type!="avif")
{
if(CompressX_Custom_Image_Meta::is_convert_avif($filename))
{
$stats['processed_files']++;
$stats['processed']+=CompressX_Custom_Image_Meta::get_convert_avif_size($filename);
}
$count++;
$stats['files']++;
$stats['total']+=$file->getSize();
}
}
}
return $count;
}
catch (Exception $exception)
{
return 0;
}
}
public function is_support_extension($extension)
{
if(in_array($extension,$this->support_extension))
{
return true;
}
else
{
return false;
}
}
public function output_custom_folders()
{
$includes=CompressX_Options::get_option('compressx_custom_includes',array());
$abs_path = trailingslashit(str_replace('\\', '/', realpath(ABSPATH)));
$convert_to_avif=CompressX_Options::get_option('compressx_output_format_avif',1);
if($convert_to_avif&&CompressX_Image_Opt_Method::is_support_avif())
{
$convert_to_avif=true;
}
else
{
$convert_to_avif=false;
}
?>
<div class="cx-mediafolder-rules">
<div class="cx-mediafolders">
<span>
<span class="dashicons dashicons-open-folder cx-icon-color-techblue"></span><span><?php esc_html_e( 'wp-content:', 'compressx' ); ?></span>
</span>
<div class="cx-upload-treeviewer" id="compressx_custom_include_js_tree">
</div>
</div>
<div class="cx-mediafolder-included">
<span>
<span class="dashicons dashicons-open-folder cx-icon-color-techblue"></span>
<span><strong><?php esc_html_e('Included Folders:','compressx')?></strong> <?php esc_html_e('Media files inside these folders will be processed','compressx')?></span>
</span>
<div class="cx-mediafolder-list" id="compressx_include_dir_node">
<ul>
<?php
foreach ($includes as $include)
{
$path=str_replace($abs_path,'',$include);
?>
<li>
<span class="dashicons dashicons-open-folder cx-icon-color-techblue"></span>
<span><?php echo esc_html($path.'('.$this->get_children_count($include,$convert_to_avif).')')?></span>
<span class="dashicons dashicons-remove cx-remove-rule cx-remove-custom-include-tree" data-id="<?php echo esc_attr($include)?>"></span>
</li>
<?php
}
?>
</ul>
</div>
</div>
</div>
<?php
}
public function get_custom_tree_dir_ex()
{
global $compressx;
$compressx->ajax_check_security('compressx-can-bulk-custom-convert');
try{
$node_array = array();
if ($_POST['tree_node']['node']['id'] == '#')
{
$path = ABSPATH;
if (!empty($_POST['tree_node']['path']))
{
$path = sanitize_text_field($_POST['tree_node']['path']);
}
} else {
$path = sanitize_text_field($_POST['tree_node']['node']['id']);
}
$path = trailingslashit(str_replace('\\', '/', realpath($path)));
if ($dh = opendir($path))
{
while (substr($path, -1) == '/')
{
$path = rtrim($path, '/');
}
$skip_paths = array(".", "..");
while (($value = readdir($dh)) !== false)
{
trailingslashit(str_replace('\\', '/', $value));
if (!in_array($value, $skip_paths))
{
if (is_dir($path . '/' . $value))
{
if(!$this->is_media_folder($path . '/' . $value))
{
$node['children'] = $this->has_children($path . '/' . $value);
$node['id'] = $path . '/' . $value;
$node['icon'] = 'dashicons dashicons-category cx-icon-color-techblue';
$node['text'] ='<span>'.$value.'</span>';
$node['text'] .='<span class="dashicons dashicons-insert cx-remove-rule cx-add-custom-include-tree" data-id="'.$node['id'].'"></span>';
$node_array[] = $node;
}
}
else{
continue;
}
}
}
}
$ret['nodes'] = $node_array;
echo wp_json_encode($ret);
}
catch (Exception $error) {
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
//error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
}
die();
}
public function has_children($path)
{
if ($dh = opendir($path))
{
while (substr($path, -1) == '/')
{
$path = rtrim($path, '/');
}
$skip_paths = array(".", "..");
while (($value = readdir($dh)) !== false)
{
trailingslashit(str_replace('\\', '/', $value));
if (!in_array($value, $skip_paths))
{
if (is_dir($path . '/' . $value))
{
return true;
}
}
}
}
return false;
}
public function is_media_folder($path)
{
$upload_dir = wp_upload_dir();
$base_dir = $upload_dir['basedir'];
$base_dir = trailingslashit(str_replace('\\', '/', realpath($base_dir)));
$path=str_replace( $base_dir, '', $path );
$path_arr = explode( '/', $path );
if ( count( $path_arr ) >= 1)
{
if(is_numeric( $path_arr[0] ) && $path_arr[0] > 1950 && $path_arr[0] < 2050)
{
return true;
}
}
$path=$this->transfer_path($path);
$upload_root=$this->transfer_path($upload_dir['basedir']);
$compressx1=$this->transfer_path(WP_CONTENT_DIR.'/compressx');
$compressx2=$this->transfer_path(WP_CONTENT_DIR.'/compressx-nextgen');
if($path==$compressx1)
{
return true;
}
else if($path==$compressx2)
{
return true;
}
else if($path==$upload_root)
{
return true;
}
return false;
}
public function get_children_count($path,$convert_to_avif)
{
try {
$rii = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path));
$files = 0;
/** @var SplFileInfo $file */
foreach ($rii as $file)
{
if ($file->isDir())
{
continue;
}
if($this->is_support_extension($file->getExtension()))
{
$filename=$path.'/'.$file->getFilename();
$type=pathinfo($filename, PATHINFO_EXTENSION);
if($type=='webp'&&$convert_to_avif)
{
$files++;
}
else
{
$files++;
}
}
}
return $files;
}
catch (Exception $e)
{
return 0;
}
}
public function add_include_folders()
{
global $compressx;
$compressx->ajax_check_security('compressx-can-bulk-custom-convert');
$includes=CompressX_Options::get_option('compressx_custom_includes',array());
$new_include = sanitize_text_field($_POST['id']);
$new_includes[$new_include]=$new_include;
$includes=array_merge($includes,$new_includes);
CompressX_Options::update_option('compressx_custom_includes',$includes);
$stats=array();
$stats['files']=0;
$stats['saved']=0;
$stats['processed_files']=0;
$stats['total']=0;
$stats['processed']=0;
$convert_to_webp=CompressX_Image_Opt_Method::get_convert_to_webp();
$convert_to_avif=CompressX_Image_Opt_Method::get_convert_to_avif();
$abs_path = trailingslashit(str_replace('\\', '/', realpath(ABSPATH)));
$html='<ul>';
foreach ($includes as $include)
{
$path=str_replace($abs_path,'',$include);
$html.= '<li><span class="dashicons dashicons-open-folder cx-icon-color-techblue"></span>'.
'<span>'.$path.'('.$this->get_folder_stats($include,$stats,$convert_to_webp,$convert_to_avif).')'.'</span>'.
'<span class="dashicons dashicons-remove cx-remove-rule cx-remove-custom-include-tree" data-id="'.$include.'"></span></li>';
}
$html.='<ul>';
if($stats['total']>0)
{
$stats['saved'] = ( $stats['processed'] / $stats['total'] ) * 100;
$stats['saved'] = round( $stats['saved'], 1 );
}
$ret['result']='success';
$ret['html']=$html;
$ret['found']=$stats['files'];
$ret['saved']=$stats['saved'];
$ret['processed']=$stats['processed_files'];
echo wp_json_encode($ret);
die();
}
public function get_dir_info()
{
global $compressx;
$compressx->ajax_check_security('compressx-can-bulk-custom-convert');
$includes=CompressX_Options::get_option('compressx_custom_includes',array());
$stats=array();
$stats['files']=0;
$stats['saved']=0;
$stats['processed_files']=0;
$stats['total']=0;
$stats['processed']=0;
$convert_to_webp=CompressX_Image_Opt_Method::get_convert_to_webp();
$convert_to_avif=CompressX_Image_Opt_Method::get_convert_to_avif();
foreach ($includes as $include)
{
$this->get_folder_stats($include,$stats,$convert_to_webp,$convert_to_avif);
}
if($stats['total']>0)
{
$stats['saved'] = ( $stats['processed'] / $stats['total'] ) * 100;
$stats['saved'] = round( $stats['saved'], 1 );
}
$ret['result']='success';
$ret['found']=$stats['files'];
$ret['saved']=$stats['saved'];
$ret['processed']=$stats['processed_files'];
echo wp_json_encode($ret);
die();
}
public function remove_include_folders()
{
global $compressx;
$compressx->ajax_check_security('compressx-can-bulk-custom-convert');
$includes=CompressX_Options::get_option('compressx_custom_includes',array());
$id = sanitize_text_field($_POST['id']);
unset($includes[$id]);
CompressX_Options::update_option('compressx_custom_includes',$includes);
$stats=array();
$stats['files']=0;
$stats['saved']=0;
$stats['processed_files']=0;
$stats['total']=0;
$stats['processed']=0;
$convert_to_webp=CompressX_Image_Opt_Method::get_convert_to_webp();
$convert_to_avif=CompressX_Image_Opt_Method::get_convert_to_avif();
foreach ($includes as $include)
{
$this->get_folder_stats($include,$stats,$convert_to_webp,$convert_to_avif);
}
if($stats['total']>0)
{
$stats['saved'] = ( $stats['processed'] / $stats['total'] ) * 100;
$stats['saved'] = round( $stats['saved'], 1 );
}
$ret['result']='success';
$ret['found']=$stats['files'];
$ret['saved']=$stats['saved'];
$ret['processed']=$stats['processed_files'];
echo wp_json_encode($ret);
die();
}
public function start_scan_custom_images()
{
global $compressx;
$compressx->ajax_check_security('compressx-can-bulk-custom-convert');
$includes=CompressX_Options::get_option('compressx_custom_includes',array());
if(empty($includes))
{
$ret['result']='failed';
$ret['error']='Please select at least one folder to process.';
echo wp_json_encode($ret);
die();
}
CompressX_Options::update_option("compressx_need_optimized_custom_images",array());
$images=array();
foreach ($includes as $include)
{
$this->get_folder_images($images,$include);
}
CompressX_Options::update_option("compressx_need_optimized_custom_images",$images);
$ret['result']='success';
$ret['progress']=sprintf(
'Scanning: %1$d Found | View Log',
sizeof($images));
$ret['finished']=true;
$ret['test']=$includes;
echo wp_json_encode($ret);
die();
}
public function get_folder_images(&$images,$path)
{
if(is_dir($path))
{
$handler = opendir($path);
if($handler!==false)
{
while (($filename = readdir($handler)) !== false)
{
if ($filename != "." && $filename != "..")
{
if (is_dir($path . DIRECTORY_SEPARATOR . $filename))
{
$this->get_folder_images($images, $path . DIRECTORY_SEPARATOR . $filename);
}
else
{
if($this->check_image($path . DIRECTORY_SEPARATOR . $filename))
{
$images[] = $path . DIRECTORY_SEPARATOR . $filename;
}
}
}
}
if($handler)
@closedir($handler);
}
}
}
public function check_image($file)
{
if ( ! file_exists( $file ))
{
return false;
}
$extension = array('jpg', 'jpeg', 'png','webp','avif');
$ext = strtolower( pathinfo( $file, PATHINFO_EXTENSION ) );
if ( !in_array( $ext, $extension, true ) )
{
return false;
}
return true;
}
public function init_custom_bulk_optimization_task()
{
global $compressx;
$compressx->ajax_check_security('compressx-can-bulk-custom-convert');
$force=isset($_POST['force'])?sanitize_key($_POST['force']):'0';
if($force=='1')
{
$force=true;
}
else
{
$force=false;
}
$task=new CompressX_Custom_ImgOptim_Task();
$ret=$task->init_task($force);
echo wp_json_encode($ret);
die();
}
public function run_custom_optimize()
{
global $compressx;
$compressx->ajax_check_security('compressx-can-bulk-custom-convert');
set_time_limit(180);
$task=new CompressX_Custom_ImgOptim_Task();
$ret=$task->get_task_status();
if($ret['result']=='success'&&$ret['status']=='completed')
{
$ret=$task->do_optimize_image();
echo wp_json_encode($ret);
}
else
{
echo wp_json_encode($ret);
}
die();
}
public function get_custom_opt_progress()
{
global $compressx;
$compressx->ajax_check_security('compressx-can-bulk-custom-convert');
$task=new CompressX_Custom_ImgOptim_Task();
$result=$task->get_task_progress();
echo wp_json_encode($result);
die();
}
private function transfer_path($path)
{
$path = str_replace('\\','/',$path);
$values = explode('/',$path);
return implode(DIRECTORY_SEPARATOR,$values);
}
}
@@ -0,0 +1,925 @@
<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
class CompressX_Media_Replace_Display
{
public $attachment_id;
public function __construct()
{
add_action('wp_ajax_compressx_save_media_replace_setting', array($this, 'save_settings'));
add_action('wp_ajax_compressx_replace_media', array($this, 'replace_media'));
add_filter('media_row_actions', array($this,'add_row_action'), 10, 2);
add_action('add_meta_boxes_attachment',array($this,'add_meta_boxes'), 10);
add_filter('attachment_fields_to_edit',array($this,'attachment_editor'), 10,2);
//
}
public function add_row_action($actions, $post)
{
if(!$this->is_supported_image($post))
{
return $actions;
}
$post_id = $post->ID;
$url = admin_url("upload.php");
$url = add_query_arg(array(
'page' => 'media-replace-compressx',
'attachment_id' => $post_id,
), $url);
$actions['compressx_media_replace']='<a href="' . esc_url( $url ) . '" aria-label="' . esc_attr__( 'Replace Media', 'compressx' ) . '" rel="permalink">' .
esc_html__( 'Replace Media', 'compressx' ) .
'</a>';
return $actions;
}
public function add_meta_boxes($post)
{
if (! $post || ! is_object($post)) {
return;
}
if (! current_user_can('upload_files')) {
return;
}
$mime = (string) get_post_mime_type($post);
if (strpos($mime, 'image/') !== 0) {
return;
}
add_meta_box(
'compressx-media-replace-box',
__('Replace Media', 'compressx'),
array($this,'render_media_replace_metabox'),
'attachment',
'side',
'low'
);
}
public function render_media_replace_metabox($post)
{
$attachment_id = (int) $post->ID;
$url = add_query_arg(
array(
'page' => 'media-replace-compressx',
'attachment_id' => $attachment_id,
),
admin_url('upload.php')
);
$url = wp_nonce_url($url, 'compressx_media_replace');
echo '<p><a class="button button-secondary" href="' . esc_url($url) . '">'
. esc_html__('Upload & Replace Media File', 'compressx')
. '</a></p>';
echo '<p class="description">'
. esc_html__('Replace this attachment and regenerate thumbnails according to your settings.', 'compressx')
. '</p>';
}
public function attachment_editor($form_fields, $post)
{
if (! current_user_can('upload_files')) {
return $form_fields;
}
$mime = (string) get_post_mime_type($post);
if (strpos($mime, 'image/') !== 0)
{
return $form_fields;
}
if (function_exists('get_current_screen'))
{
$screen = get_current_screen();
if ($screen && $screen->id === 'attachment') {
return $form_fields;
}
}
if (wp_doing_ajax())
{
$ref = wp_get_referer();
if (!$ref && !empty($_SERVER['HTTP_REFERER'])) {
$ref = $_SERVER['HTTP_REFERER'];
}
if (!$ref || strpos($ref, 'upload.php') === false) {
return $form_fields;
}
}
$url = add_query_arg(
array(
'page' => 'media-replace-compressx',
'attachment_id' => (int) $post->ID,
),
admin_url('upload.php')
);
$url = wp_nonce_url($url, 'compressx_media_replace');
$form_fields['compressx-media-replace'] = array(
'label' => __('Replace Media', 'compressx'),
'input' => 'html',
'html' => '<a class="button button-secondary" href="' . esc_url($url) . '">' .
esc_html__('Upload a new file', 'compressx') .
'</a>',
'helps' => __('Click to replace this file via CompressX.', 'compressx'),
);
return $form_fields;
}
public function is_supported_image($post)
{
if (! is_object($post))
{
return false;
}
$post_id = $post->ID;
$post_type = $post->post_type;
if ($post_type !== 'attachment')
{
return false;
}
$supported_mime_types = array(
"image/jpg",
"image/jpeg",
"image/png",
"image/webp",
"image/avif");
$mime_type=get_post_mime_type($post_id);
if(in_array($mime_type,$supported_mime_types))
{
return true;
}
else
{
return false;
}
}
public function display()
{
if (array_key_exists("attachment_id", $_GET) && intval($_GET["attachment_id"]) > 0)
{
$this->attachment_id= intval($_GET["attachment_id"]);
?>
<div class="compressx-root">
<div class="compressx-v2-py-6 compressx-v2-w-full compressx-v2-max-w-[1200px] compressx-v2-mx-auto">
<?php
$this->output_header();
$this->output_media_replace_v2();
$this->output_footer();
?>
</div>
</div>
<?php
}
}
public function output_header()
{
?>
<div class=" compressx-v2-pr-4 compressx-v2-flex compressx-v2-items-center compressx-v2-justify-between compressx-v2-mb-4">
<div>
<h1 class="compressx-v2-text-2xl compressx-v2-font-semibold compressx-v2-text-gray-900">
<?php echo esc_html(__('Replace Media', 'compressx')); ?>
</h1>
<p class="compressx-v2-text-sm compressx-v2-text-gray-600 compressx-v2-mt-2">
<?php echo esc_html(__(' Safely replace this media file without changing its URL.', 'compressx')); ?>
</p>
</div>
</div>
<?php
}
public function output_media_replace_v2()
{
?>
<div class="compressx-v2-bg-white">
<div class="compressx-v2-grid compressx-v2-grid-cols-1 md:compressx-v2-grid-cols-10 compressx-v2-p-4 compressx-v2-gap-6">
<!-- Left: Settings (30%) -->
<?php $this->output_media_replace_setting_v2()?>
<!-- Right: Manipulation (70%) -->
<?php $this->output_media_replace_manipulation()?>
</div>
<section class="compressx-v2-sticky compressx-v2-bottom-0 compressx-v2-bg-white compressx-v2-border-t compressx-v2-border-gray-200 compressx-v2-p-4">
<div class="compressx-v2-max-w-[1200px] compressx-v2-mx-auto compressx-v2-flex compressx-v2-justify-end compressx-v2-gap-3">
<!-- Save button -->
<div class="compressx-v2-flex compressx-v2-items-center compressx-v2-gap-2">
<button id="cx_replace_media" class="compressx-v2-inline-flex compressx-v2-items-center compressx-v2-gap-1 compressx-v2-bg-blue-600 hover:compressx-v2-bg-blue-700 compressx-v2-text-white compressx-v2-text-sm compressx-v2-font-medium compressx-v2-px-4 compressx-v2-py-2 compressx-v2-rounded">
<?php esc_html_e( 'Replace Media', 'compressx' ); ?>
</button>
<span id="cx_replace_media_progress" class="compressx-v2-flex compressx-v2-items-center compressx-v2-hidden">
<img src="<?php echo esc_url(is_network_admin() ? network_admin_url('images/loading.gif') : admin_url('images/loading.gif')); ?>" alt="<?php echo esc_attr__( 'Loading...', 'compressx' ); ?>" style="width: 16px; height: 16px;">
</span>
<span id="cx_replace_media_text" class="success compressx-v2-hidden compressx-v2-text-sm compressx-v2-font-medium" style="color:#007017"><?php esc_html_e('Success!', 'compressx') ?></span>
</div>
<input type="hidden" id="compressx_attachment_id" value="<?php echo esc_attr( $this->attachment_id ); ?>" style="display:none;"/>
</section>
</div>
<?php
}
public function output_media_replace_setting_v2()
{
$options=CompressX_Options::get_option('compressx_media_replace',array());
$auto_re_optimize=isset($options['auto_re_optimize'])?$options['auto_re_optimize']:true;
$thumbnail_generation=isset($options['thumbnail_generation'])?$options['thumbnail_generation']:'default_fill';
if($thumbnail_generation=="default_fill")
{
$default_fill=true;
$match_original=false;
}
else
{
$default_fill=false;
$match_original=true;
}
$backup_original=false;
?>
<div class="md:compressx-v2-col-span-3">
<div class="compressx-v2-bg-[#F2FBFA] compressx-v2-border compressx-v2-p-4 compressx-v2-mb-4 compressx-v2-rounded">
<h4 class="compressx-v2-text-xs compressx-v2-font-medium compressx-v2-text-gray-700 compressx-v2-mb-3">
<?php esc_html_e( 'Current Compression Settings', 'compressx' ); ?>
</h4>
<ul class="compressx-v2-text-xs compressx-v2-text-gray-600 compressx-v2-space-y-1.5">
<li>
<div class="compressx-v2-flex compressx-v2-items-center compressx-v2-gap-4 compressx-v2-text-gray-700">
<div class="compressx-v2-flex compressx-v2-items-center compressx-v2-gap-1.5">
<span class="dashicons dashicons-yes compressx-v2-text-green-600"></span>
<span class="compressx-v2-font-medium"><?php esc_html_e( 'General', 'compressx' ); ?></span>
</div>
<span class="compressx-v2-text-gray-300">|</span>
<div class="compressx-v2-flex compressx-v2-items-center compressx-v2-gap-1.5 compressx-v2-text-gray-400">
<span class="dashicons dashicons-star-filled"></span>
<span class="compressx-v2-font-medium"><?php esc_html_e( 'Smart', 'compressx' ); ?></span>
<span class="compressx-v2-text-[11px]"><a href="https://compressx.io/pricing/plans/"><?php esc_html_e( '(Pro)', 'compressx' ); ?></a></span>
</div>
</div>
</li>
<li>• <?php esc_html_e( 'Formats:', 'compressx' ); ?> <span class="compressx-v2-font-medium"><?php esc_html_e( 'WebP, AVIF', 'compressx' ); ?></span></li>
<li>• <?php esc_html_e( 'Thumbnails:', 'compressx' ); ?>: <span class="compressx-v2-font-medium"><?php esc_html_e( 'All Selected Thumbnail sizes', 'compressx' ); ?></span></li>
</ul>
</div>
<div class="compressx-v2-border compressx-v2-p-4">
<div class="compressx-v2-pb-4">
<div class="compressx-v2-grid compressx-v2-grid-cols-[auto,1fr] compressx-v2-gap-4 compressx-v2-border-b compressx-v2-mb-4 compressx-v2-items-start">
<!-- Checkbox -->
<div class="compressx-v2-pt-1">
<input id="cx_auto_re_optimize" type="checkbox" checked class="compressx-v2-h-4 compressx-v2-w-4" <?php echo esc_attr(checked($auto_re_optimize));?> >
</div>
<!-- Title + Description -->
<div>
<h3 class="compressx-v2-text-sm compressx-v2-font-medium compressx-v2-text-gray-800">
<?php esc_html_e( 'Auto re-optimize after replacement', 'compressx' ); ?><br>
<span id="auto_re_optimize-saved-indicator" class="compressx-v2-ml-2 compressx-v2-text-xs compressx-v2-text-green-600 hidden"><?php esc_html_e( '✓ Saved', 'compressx' ); ?></span>
</h3>
<p class="compressx-v2-text-xs compressx-v2-text-gray-500 compressx-v2-mt-1">
<?php esc_html_e( 'Replace all WordPress-generated thumbnails with new ones created from the replaced file, then re-optimize them automatically.', 'compressx' ); ?>
</p>
<div class="compressx-v2-mt-4 compressx-v2-mb-4">
<h3 class="compressx-v2-text-sm compressx-v2-font-medium compressx-v2-text-gray-900 compressx-v2-mb-3">
<?php esc_html_e( 'Thumbnail Generation Strategy', 'compressx' ); ?>
</h3>
<div class="compressx-v2-space-y-3">
<!-- Option 1 -->
<label class="compressx-v2-grid compressx-v2-grid-cols-[auto,1fr] compressx-v2-items-center compressx-v2-gap-3 compressx-v2-cursor-pointer">
<input type="radio" name="thumbnail_strategy" value="default_fill" <?php echo esc_attr(checked($default_fill));?>/>
<div>
<div class="compressx-v2-text-sm compressx-v2-text-gray-900">
<?php esc_html_e( 'Use current default sizes and fill missing ones (Recommended)', 'compressx' ); ?><br>
<span id="default_fill-saved-indicator" class="compressx-v2-ml-2 compressx-v2-text-xs compressx-v2-text-green-600 hidden"><?php esc_html_e( '✓ Saved', 'compressx' ); ?></span>
</div>
<div class="compressx-v2-text-xs compressx-v2-text-gray-500">
<?php esc_html_e( 'Generate thumbnails using the current default sizes and automatically create any missing sizes.', 'compressx' ); ?>
</div>
</div>
</label>
<!-- Option 2 -->
<label class="compressx-v2-grid compressx-v2-grid-cols-[auto,1fr] compressx-v2-items-center compressx-v2-gap-3 compressx-v2-cursor-pointer">
<input type="radio" name="thumbnail_strategy" value="match_original" class="compressx-v2-mt-1" <?php echo esc_attr(checked($match_original));?>/>
<div>
<div class="compressx-v2-text-sm compressx-v2-text-gray-900">
<?php esc_html_e( 'Match original thumbnail sizes', 'compressx' ); ?><br>
<span id="match_original-saved-indicator" class="compressx-v2-ml-2 compressx-v2-text-xs compressx-v2-text-green-600 hidden"><?php esc_html_e( '✓ Saved', 'compressx' ); ?></span>
</div>
<div class="compressx-v2-text-xs compressx-v2-text-gray-500">
<?php esc_html_e( 'Generate new thumbnails strictly based on the original image\'s existing thumbnail sizes.', 'compressx' ); ?>
</div>
</div>
</label>
</div>
</div>
</div>
</div>
<div class="compressx-v2-grid compressx-v2-grid-cols-[auto,1fr] compressx-v2-border-b compressx-v2-pb-4 compressx-v2-mb-4 compressx-v2-gap-4 compressx-v2-items-start">
<!-- Checkbox -->
<div class="compressx-v2-pt-1">
<input id="cx_backup_original" type="checkbox" class="compressx-v2-h-4 compressx-v2-w-4" disabled>
</div>
<!-- Title + Description -->
<div>
<h3 class="compressx-v2-text-sm compressx-v2-font-medium compressx-v2-text-gray-800">
<?php esc_html_e( 'Keep temporary versions after replacement', 'compressx' ); ?> <span class="compressx-v2-text-gray-400"><a href="https://compressx.io/pricing/plans/"><?php esc_html_e( '(Pro)', 'compressx' ); ?></a></span>
</h3>
<!-- Temporary Versions Retention -->
<div class="compressx-v2-space-y-3 compressx-v2-mt-3">
<!-- Versions count -->
<div class="compressx-v2-space-y-1">
<label class="compressx-v2-text-xs compressx-v2-text-gray-600">
<?php esc_html_e( 'Keep up to', 'compressx' ); ?>
</label>
<select class="compressx-v2-w-full
compressx-v2-border
compressx-v2-border-gray-300
compressx-v2-rounded
compressx-v2-h-8
compressx-v2-px-2
compressx-v2-text-sm">
<option>1</option>
<option>2</option>
<option>3</option>
</select>
<div class="compressx-v2-text-[11px] compressx-v2-text-gray-500">
<?php esc_html_e( 'versions', 'compressx' ); ?>
</div>
</div>
<!-- Retention time -->
<div class="compressx-v2-space-y-1">
<label class="compressx-v2-text-xs compressx-v2-text-gray-600">
<?php esc_html_e( 'Retention period', 'compressx' ); ?>
</label>
<select class="compressx-v2-w-full compressx-v2-border compressx-v2-border-gray-300 compressx-v2-rounded compressx-v2-h-8 compressx-v2-px-2 compressx-v2-text-sm">
<option value="1"><?php esc_html_e( '1 day', 'compressx' ); ?></option>
<option value="3"><?php esc_html_e( '3 days', 'compressx' ); ?></option>
<option value="7"><?php esc_html_e( '7 days', 'compressx' ); ?></option>
</select>
</div>
<!-- Helper text -->
<div class="compressx-v2-text-[11px] compressx-v2-text-gray-500">
<?php esc_html_e( 'Versions are removed automatically after expiration.', 'compressx' ); ?>
</div>
</div>
<p class="compressx-v2-text-[11px] compressx-v2-text-gray-400 compressx-v2-mt-1">
<?php esc_html_e( 'This is a short-term safety buffer, not a backup system.', 'compressx' ); ?>
</p>
</div>
</div>
</div>
</div>
</div>
<?php
}
public function output_media_replace_manipulation()
{
?>
<div class="md:compressx-v2-col-span-7">
<?php $this->output_current_media_v2()?>
<?php $this->output_upload_new_media_v2()?>
<!-- Replace Impact -->
<div class="compressx-v2-mb-4">
<h3 class="compressx-v2-text-sm compressx-v2-font-medium compressx-v2-mb-2">
<?php esc_html_e( 'After Replacement', 'compressx' ); ?>
</h3>
<ul class="compressx-v2-text-sm compressx-v2-text-gray-700 compressx-v2-space-y-1">
<li><?php esc_html_e( '✓ URL unchanged', 'compressx' ); ?></li>
<li><?php esc_html_e( '✓ Attachment ID unchanged', 'compressx' ); ?></li>
<li><?php esc_html_e( '✓ Thumbnails regenerated (PNG/JPG/WEBP/AVIF)', 'compressx' ); ?></li>
<li><?php esc_html_e( '✓ Formats re-optimized', 'compressx' ); ?></li>
<li><?php
printf(
/* translators: %d: number of days the previous version is retained. */
esc_html__( '✓ The previous version will be kept for %d day.', 'compressx' ),
1
);
?>
</li>
</ul>
</div>
</div>
<?php
}
public function output_current_media_v2()
{
$url='';
$medium = wp_get_attachment_image_src($this->attachment_id, 'medium');
if (is_array($medium) && !empty($medium[0]))
{
$url = $medium[0];
}
else
{
$full = wp_get_attachment_image_src($this->attachment_id, 'full');
$full_url = $full[0];
$full_w = (int) $full[1];
if ($full_w > 0 && $full_w < 300)
{
$url = $full_url;
}
else
{
$meta = wp_get_attachment_metadata($this->attachment_id);
if (!empty($meta['sizes']) && is_array($meta['sizes']))
{
$candidates = [];
foreach ($meta['sizes'] as $size_name => $info)
{
if (empty($info['width']) || empty($info['file'])) continue;
$w = (int) $info['width'];
if ($w >= 300)
{
$candidates[] = ['w' => $w,'s'=>$size_name];
}
}
if (!empty($candidates))
{
usort($candidates, function($a, $b) { return $a['w'] <=> $b['w']; });
$src=wp_get_attachment_image_src($this->attachment_id, $candidates[0]['s']);
$url=$src[0];
}
}
}
if(empty($url))
{
$url=$full_url;
}
}
$url.='?v='.time();
$width=0;
$height=0;
$size=0;
$meta = wp_get_attachment_metadata($this->attachment_id);
$file = get_attached_file($this->attachment_id);
if (is_array($meta))
{
if(!empty($meta['filesize']))
{
$size=(int)$meta['filesize'];
}
if (!empty($meta['width']))
$width = (int) $meta['width'];
if (!empty($meta['height']))
$height = (int) $meta['height'];
}
else
{
if ($file && file_exists($file))
{
$size = (int) @filesize($file);
$img = @getimagesize($file);
if (is_array($img) && !empty($img[0]) && !empty($img[1]))
{
$width = (int) $img[0];
$height = (int) $img[1];
}
}
}
$dimensions="Dimensions: $width × $height";
$size="File size: ".size_format($size,2);
if(CompressX_Image_Meta_V2::is_image_optimized($this->attachment_id))
{
$status="Status: Optimized";
}
else
{
$status="Status: Unoptimized";
}
if(!empty($meta['sizes']))
$thumbnail_counts = sprintf(
/* translators: %d: number of generated thumbnails. */
__( 'Thumbnails: %d', 'compressx' ),
count( $meta['sizes'] )
);
else
$thumbnail_counts = sprintf(
__( 'Thumbnails: 0', 'compressx' )
);
$mime_type=get_post_mime_type($this->attachment_id);
$ft = wp_check_filetype($file);
$ext = !empty($ft['ext']) ? $ft['ext'] : '';
$type = $ext ? strtoupper($ext) : '-';
?>
<div class="compressx-v2-mb-4">
<div class="compressx-v2-border-b compressx-v2-pb-4 compressx-v2-mb-4">
<h3 class="compressx-v2-text-sm compressx-v2-font-medium">
<span><?php esc_html_e( 'Current Media', 'compressx' ); ?></span>
</h3>
</div>
<div class="compressx-v2-grid compressx-v2-grid-cols-2 compressx-v2-gap-4 compressx-v2-items-start">
<div class="compressx-v2-bg-gray-100 compressx-v2-rounded compressx-v2-flex compressx-v2-items-center compressx-v2-justify-center">
<img src="<?php echo esc_url( $url ); ?>" alt="<?php echo esc_attr__( 'Replace preview', 'compressx' ); ?>"/>
</div>
<div class="compressx-v2-text-sm compressx-v2-text-gray-700">
<div id="og_image_dimensions" data-mime="<?php echo esc_attr( $mime_type ); ?>" data-width="<?php echo esc_attr( $width ); ?>" data-height="<?php echo esc_attr( $height ); ?>" ><?php echo esc_html( $dimensions ); ?></div>
<div><?php esc_html_e( 'Format:', 'compressx' ); ?> <span><?php echo esc_html( $type ); ?></span></div>
<div><?php echo esc_html( $size ); ?></div>
<div><?php echo esc_html( $status ); ?></div>
<div><?php echo esc_html( $thumbnail_counts ); ?></div>
<div class="compressx-v2-mt-2
compressx-v2-flex compressx-v2-items-start compressx-v2-gap-1.5
compressx-v2-text-[11px] compressx-v2-text-gray-400">
<p class="compressx-v2-leading-snug">
<span class="compressx-v2-font-medium compressx-v2-text-gray-500"><?php esc_html_e( 'Note:', 'compressx' ); ?></span>
<?php
printf(
wp_kses_post(
/* translators: %s: documentation URL. */
__( 'The image preview may still show a cached version due to browser or CDN caching. <a href="%s">Learn more...</a>', 'compressx' )
),
esc_url( 'https://compressx.io/docs/media-replace/' )
);
?>
</p>
</div>
</div>
</div>
</div>
<?php
}
public function output_upload_new_media_v2()
{
?>
<div class="compressx-v2-mb-4">
<div class="compressx-v2-bg-gray-50 compressx-v2-border compressx-v2-border-dashed compressx-v2-border-gray-300 compressx-v2-rounded compressx-v2-p-4 compressx-v2-mb-4">
<h3 class="compressx-v2-text-sm compressx-v2-font-semibold compressx-v2-text-gray-900 compressx-v2-mb-1">
<?php esc_html_e( 'New Media', 'compressx' ); ?>
</h3>
<div class="compressx-v2-text-xs compressx-v2-text-gray-500 compressx-v2-leading-relaxed">
<?php esc_html_e( 'For best visual consistency, upload an image with a similar width (or slightly wider) than the original.', 'compressx' ); ?>
<a href="https://compressx.io/docs/media-replace/" class="compressx-v2-text-blue-600 hover:compressx-v2-underline"><?php esc_html_e( 'Learn more...', 'compressx' ); ?></a>
</div>
</div>
<div id="cx-upload-notice" style="display: none" class="compressx-v2-bg-yellow-50 compressx-v2-border-l-4 compressx-v2-border-yellow-400 compressx-v2-rounded compressx-v2-p-4 compressx-v2-mb-4 compressx-v2-relative">
<!-- Close Button -->
<button id="cx-hide-upload-notice"
class="compressx-v2-absolute compressx-v2-top-2 compressx-v2-right-2 compressx-v2-text-yellow-700 hover:compressx-v2-text-yellow-900
compressx-v2-text-xs compressx-v2-font-medium compressx-v2-bg-transparent compressx-v2-border compressx-v2-border-yellow-300
hover:compressx-v2-bg-yellow-100 compressx-v2-rounded compressx-v2-px-2 compressx-v2-py-0.5 compressx-v2-transition"><?php esc_html_e( 'Dismiss', 'compressx' ); ?></button>
<div class="compressx-v2-flex compressx-v2-items-start compressx-v2-gap-3">
<!-- Warning Icon -->
<span class="dashicons dashicons-warning compressx-v2-text-yellow-500 compressx-v2-text-xl compressx-v2-mt-0.5"></span>
<div class="compressx-v2-flex-1">
<p class="compressx-v2-font-medium compressx-v2-text-yellow-800">
<?php esc_html_e( 'Warning:', 'compressx' ); ?> <span id="cx_notice_title" class="compressx-v2-font-semibold"></span>
</p>
<p id="cx_notice_content" class="compressx-v2-text-sm compressx-v2-text-yellow-700 compressx-v2-mt-0.5">
</p>
</div>
</div>
</div>
<!-- Upload Area -->
<div id="compressx-new-media-dropzone" role="button" tabindex="0" aria-label="<?php echo esc_attr__( 'Upload new media', 'compressx' ); ?>"
class="compressx-v2-border compressx-v2-border-dashed compressx-v2-border-gray-300 compressx-v2-rounded compressx-v2-bg-white compressx-v2-p-12 compressx-v2-text-center compressx-v2-transition hover:compressx-v2-border-gray-400">
<p class="compressx-v2-text-sm compressx-v2-text-gray-700 compressx-v2-mb-1">
<?php esc_html_e( 'Click to upload or drag and drop a file here', 'compressx' ); ?>
</p>
<p class="compressx-v2-text-xs compressx-v2-text-gray-400">
<?php esc_html_e( 'The file will replace the current media without changing the URL.', 'compressx' ); ?>
</p>
</div>
<div id="compressx-new-media-preview-layout" style="display:none;" class="compressx-v2-grid compressx-v2-grid-cols-2 compressx-v2-gap-4 compressx-v2-items-start">
<div class="compressx-v2-bg-gray-100 compressx-v2-rounded compressx-v2-flex compressx-v2-items-center compressx-v2-justify-center">
<img id="compressx-new-media-preview" alt="<?php echo esc_attr__( 'Replace preview', 'compressx' ); ?>"/>
</div>
<div class="compressx-v2-text-sm compressx-v2-text-gray-700">
<div><?php esc_html_e( 'Dimensions:', 'compressx' ); ?> <span id="compressx-new-media-dim">-</span></div>
<div><?php esc_html_e( 'Format:', 'compressx' ); ?> <span id="compressx-new-media-format">-</span></div>
<div><?php esc_html_e( 'File size:', 'compressx' ); ?> <span id="compressx-new-media-size">-</span></div>
<div>
<button id="compressx-remove-new-media-preview" type="button" class="compressx-v2-mt-2 compressx-v2-text-xs compressx-v2-font-medium compressx-v2-text-gray-600
hover:compressx-v2-text-gray-800 compressx-v2-border compressx-v2-border-gray-300 hover:compressx-v2-border-gray-400
compressx-v2-bg-white hover:compressx-v2-bg-gray-50 compressx-v2-rounded compressx-v2-px-2 compressx-v2-py-1 compressx-v2-transition">
<?php esc_html_e( 'Remove the uploaded file', 'compressx' ); ?>
</button>
</div>
</div>
</div>
<input type="file" id="compressx-new-media-file" name="compressx_new_media_file" accept="image/*" style="display:none;"/>
</div>
<?php
}
public function output_footer()
{
do_action('compressx_output_footer');
}
public function save_settings()
{
global $compressx;
$compressx->ajax_check_security();
if (isset($_POST['settings']) && !empty($_POST['settings']))
{
$settings=$_POST['settings'];
$options=CompressX_Options::get_option('compressx_media_replace',array());
if (isset($settings['auto_re_optimize']))
{
$auto_re_optimize=sanitize_text_field($settings['auto_re_optimize']);
if($auto_re_optimize=='1')
{
$auto_re_optimize=true;
}
else
{
$auto_re_optimize=false;
}
$options['auto_re_optimize']=$auto_re_optimize;
}
if (isset($settings['thumbnail_generation']))
{
$thumbnail_generation=sanitize_text_field($settings['thumbnail_generation']);
if($thumbnail_generation=='default_fill')
{
$thumbnail_generation='default_fill';
}
else
{
$thumbnail_generation='match_original';
}
$options['thumbnail_generation']=$thumbnail_generation;
}
CompressX_Options::update_option('compressx_media_replace',$options);
$ret['result']='success';
echo wp_json_encode($ret);
die();
}
else
{
die();
}
}
public function replace_media()
{
global $compressx;
$compressx->ajax_check_security();
if (empty($_FILES['image']) || !is_array($_FILES['image']))
{
wp_send_json( array(
'result' => 'failed',
'error' => __( 'No file uploaded.', 'compressx' ),
) );
}
if (empty($_POST['attachment_id']))
{
wp_send_json( array(
'result' => 'failed',
'error' => __( 'No attachment_id.', 'compressx' ),
) );
}
$file = $_FILES['image'];
$attachment_id = sanitize_text_field($_POST['attachment_id']);
$allowed_mimes = [
'jpg|jpeg|jpe' => 'image/jpeg',
'png' => 'image/png',
'gif' => 'image/gif',
'webp' => 'image/webp',
'avif' => 'image/avif',
];
if (!function_exists('wp_handle_upload'))
{
require_once ABSPATH . 'wp-admin/includes/file.php';
}
add_filter('upload_dir',array($this, 'get_compressx_tmp_folder'));
$overrides = [
'test_form' => false,
'mimes' => $allowed_mimes,
];
$uploaded = wp_handle_upload($file, $overrides);
remove_filter('upload_dir', array($this, 'get_compressx_tmp_folder'));
if (isset($uploaded['error']))
{
wp_send_json(['result' => 'failed', 'error' => $uploaded['error']]);
}
include_once COMPRESSX_DIR . '/includes/class-compressx-media-replace.php';
$media_replace=new CompressX_Media_Replace();
$options=CompressX_Options::get_option('compressx_media_replace',array());
if(CompressX_Image_Meta_V2::is_image_optimized($attachment_id))
{
$this->delete_converted_image($attachment_id);
}
$ret=$media_replace->replace($attachment_id,$uploaded['file'],$options);
if($ret['result']=='success')
{
$auto_re_optimize=isset($options['auto_re_optimize'])?$options['auto_re_optimize']:true;
if($auto_re_optimize)
{
$this->reconvert_image($attachment_id);
}
}
echo wp_json_encode($ret);
die();
}
public function reconvert_image($image_id)
{
$options=$this->init_option();
$this->delete_converted_image($image_id);
$image=new Compressx_Image($image_id,$options);
$file_path = get_attached_file( $image_id );
if(empty($file_path))
{
$error='Image:'.$image_id.' failed. Error: failed to get get_attached_file';
CompressX_Image_Meta_V2::update_image_failed($image_id,$error);
return;
}
CompressX_Image_Meta_V2::update_image_progressing($image_id);
//$image->resize();
if($image->convert())
{
CompressX_Image_Meta_V2::update_image_meta_status($image_id, 'optimized');
}
else
{
CompressX_Image_Meta_V2::update_image_meta_status($image_id,'failed');
}
CompressX_Image_Meta_V2::delete_image_progressing($image_id);
}
public function delete_converted_image($image_id)
{
$files=array();
$file_path = get_attached_file( $image_id );
$meta = wp_get_attachment_metadata( $image_id, true );
if ( ! empty( $meta['sizes'] ) )
{
foreach ( $meta['sizes'] as $size_key => $size_data )
{
$filename= path_join( dirname( $file_path ), $size_data['file'] );
$files[$size_key] =$filename;
}
if(!in_array($file_path,$files))
{
$files['og']=$file_path;
}
}
else
{
$files['og']=$file_path;
}
foreach ($files as $size_key=>$file)
{
$file=CompressX_Image_Method::get_output_path($file);
$webp_file =$file.'.webp';
$avif_file =$file.'.avif';
if(file_exists($webp_file))
@wp_delete_file($webp_file);
if(file_exists($avif_file))
@wp_delete_file($avif_file);
if(file_exists($file))
@wp_delete_file($file);
}
delete_post_meta($image_id,'compressx_image_meta_status');
delete_post_meta($image_id,'compressx_image_meta_webp_converted');
delete_post_meta($image_id,'compressx_image_meta_avif_converted');
delete_post_meta($image_id,'compressx_image_meta_compressed');
delete_post_meta($image_id,'compressx_image_meta_og_file_size');
delete_post_meta($image_id,'compressx_image_meta_webp_converted_size');
delete_post_meta($image_id,'compressx_image_meta_avif_converted_size');
delete_post_meta($image_id,'compressx_image_meta_compressed_size');
delete_post_meta($image_id,'compressx_image_meta');
delete_post_meta($image_id,'compressx_image_progressing');
CompressX_Image_Meta_V2::delete_image_meta($image_id);
}
public function init_option()
{
$general_options=CompressX_Options::get_general_settings();
$quality_options=CompressX_Options::get_quality_option();
return array_merge($general_options,$quality_options);
}
public function get_compressx_tmp_folder( $uploads ) {
$path = WP_CONTENT_DIR . '/compressx';
$url = content_url( '/compressx' );
// Ensure directory exists.
if ( ! is_dir( $path ) ) {
wp_mkdir_p( $path );
}
// Init WP_Filesystem.
global $wp_filesystem;
if ( empty( $wp_filesystem ) ) {
require_once ABSPATH . 'wp-admin/includes/file.php';
WP_Filesystem();
}
// If WP_Filesystem is not available, fallback to original uploads.
if ( empty( $wp_filesystem ) ) {
return $uploads;
}
// Create empty index.html (prevent directory listing).
$index_file = $path . '/index.html';
if ( ! $wp_filesystem->exists( $index_file ) ) {
$wp_filesystem->put_contents( $index_file, '', FS_CHMOD_FILE );
}
// .htaccess content (no heredoc).
$root_htaccess = "# CompressX - block public access by default\n\n"
. "<IfModule mod_authz_core.c>\n"
. " Require all denied\n"
. "</IfModule>\n"
. "<IfModule !mod_authz_core.c>\n"
. " Deny from all\n"
. "</IfModule>\n";
$root_ht_file = $path . '/.htaccess';
$current = '';
if ( $wp_filesystem->exists( $root_ht_file ) ) {
$current = $wp_filesystem->get_contents( $root_ht_file );
if ( false === $current ) {
$current = '';
}
}
// Write .htaccess only if changed.
if ( $current !== $root_htaccess ) {
$wp_filesystem->put_contents( $root_ht_file, $root_htaccess, FS_CHMOD_FILE );
}
// Override uploads paths.
$uploads['path'] = $path;
$uploads['url'] = $url;
$uploads['subdir'] = '';
$uploads['basedir'] = $path;
$uploads['baseurl'] = $url;
return $uploads;
}
}
@@ -0,0 +1,118 @@
:root {
--color-tech-blue: #018fd1;
--color-dark-yellow: orange;
--color-grey: #ddd;
--color-grey-black: #888;
--color-light-grey: #F8F9FA;
--color-light-blue: #175cff;
--color-light-blue-2: #104bd4;
--color-background: #fff;
--color-title: #0B163F;
}
.compressx-general-settings-body .cx-uploads-rules,
.compressx-general-settings-body .cx-mediafolder-rules {
display: grid;
grid-template-columns: 1fr 2fr;
gap: 1rem;
}
.compressx-general-settings-body .cx-mediafolder-rules .cx-icon-color-yellow {
color: var(--color-dark-yellow);
font-size: 1rem;
padding-top: 0.1rem;
}
.compressx-general-settings-body .cx-mediafolder-rules .cx-icon-color-techblue {
color: var(--color-tech-blue);
font-size: 1rem;
padding-top: 0.1rem;
}
.compressx-general-settings-body .cx-mediafolder-rules .cx-mediafolders,
.compressx-general-settings-body .cx-mediafolder-rules .cx-mediafolder-included {
position: relative;
padding: 1rem 0;
border-radius: 10px;
}
.compressx-general-settings-body .cx-mediafolder-rules .cx-mediafolders .cx-upload-treeviewer li,
.compressx-general-settings-body .cx-mediafolder-rules .cx-mediafolder-included .cx-mediafolder-list li {
position: relative;
}
.compressx-general-settings-body .cx-mediafolder-rules .cx-mediafolders .cx-upload-treeviewer .cx-remove-rule,
.compressx-general-settings-body .cx-mediafolder-rules .cx-mediafolder-included .cx-mediafolder-list .cx-remove-rule {
position: absolute;
right: 0;
cursor: pointer;
color: var(--color-grey-black);
font-size: 1rem;
padding-top: 0.1rem;
}
.compressx-general-settings-body .cx-mediafolder-rules .cx-mediafolders .cx-upload-treeviewer,
.compressx-general-settings-body .cx-mediafolder-rules .cx-mediafolder-included .cx-mediafolder-list {
margin-top: 1rem;
border: 1px solid var(--color-grey);
border-radius: 4px;
padding: 0 0.5rem;
height: 200px;
overflow-y: auto;
overflow-x: auto;
}
.compressx-general-settings-body .cx-mediafolder-rules .cx-mediafolder-included .cx-mediafolder-list ul {
padding: 0;
}
.compressx-general-settings-body .cx-mediafolder-rules .cx-mediafolder-included .cx-mediafolder-list li:nth-child(odd),
.compressx-general-settings-body .cx-mediafolder-rules .cx-mediafolders .cx-upload-treeviewer li:nth-child(odd) {
background-color: var(--color-light-grey);
}
.compressx-container .cx-button {
background-color: var(--color-light-blue);
border-color: var(--color-light-blue);
}
.compressx-container .cx-button:hover {
background-color: var(--color-light-blue-2);
border-color: var(--color-light-blue-2);
color: var(--color-background);
}
.compressx-container .cx-button:focus {
background-color: var(--color-light-blue-2);
border-color: var(--color-light-blue-2);
color: var(--color-background);
}
.compressx-container .cx-button-light {
background-color: var(--color-background);
border-color: var(--color-light-blue);
color: var(--color-light-blue);
}
.compressx-container .cx-button-light:hover {
background-color: var(--color-light-blue);
color: var(--color-background);
}
@media screen and (max-width: 768px) {
.compressx-general-settings-body .cx-uploads-rules,
.compressx-general-settings-body .cx-mediafolder-rules {
display: grid;
grid-template-columns: 1fr;
gap: 1rem;
}
}
@media screen and (max-width: 430px) {
.compressx-general-settings-body .cx-uploads-rules,
.compressx-general-settings-body .cx-mediafolder-rules {
display: grid;
grid-template-columns: 1fr;
gap: 1rem;
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,206 @@
.twentytwenty-horizontal .twentytwenty-handle:before, .twentytwenty-horizontal .twentytwenty-handle:after, .twentytwenty-vertical .twentytwenty-handle:before, .twentytwenty-vertical .twentytwenty-handle:after {
content: " ";
display: block;
background: white;
position: absolute;
z-index: 30;
-webkit-box-shadow: 0px 0px 12px rgba(51, 51, 51, 0.5);
-moz-box-shadow: 0px 0px 12px rgba(51, 51, 51, 0.5);
box-shadow: 0px 0px 12px rgba(51, 51, 51, 0.5); }
.twentytwenty-horizontal .twentytwenty-handle:before, .twentytwenty-horizontal .twentytwenty-handle:after {
width: 3px;
height: 9999px;
left: 50%;
margin-left: -1.5px; }
.twentytwenty-vertical .twentytwenty-handle:before, .twentytwenty-vertical .twentytwenty-handle:after {
width: 9999px;
height: 3px;
top: 50%;
margin-top: -1.5px; }
.twentytwenty-before-label, .twentytwenty-after-label, .twentytwenty-overlay {
position: absolute;
top: 0;
width: 100%;
height: 100%; }
.twentytwenty-before-label, .twentytwenty-after-label, .twentytwenty-overlay {
-webkit-transition-duration: 0.5s;
-moz-transition-duration: 0.5s;
transition-duration: 0.5s; }
.twentytwenty-before-label, .twentytwenty-after-label {
-webkit-transition-property: opacity;
-moz-transition-property: opacity;
transition-property: opacity; }
.twentytwenty-before-label:before, .twentytwenty-after-label:before {
color: white;
font-size: 13px;
letter-spacing: 0.1em; }
.twentytwenty-before-label:before, .twentytwenty-after-label:before {
position: absolute;
background: rgba(255, 255, 255, 0.2);
line-height: 38px;
padding: 0 20px;
-webkit-border-radius: 2px;
-moz-border-radius: 2px;
border-radius: 2px; }
.twentytwenty-horizontal .twentytwenty-before-label:before, .twentytwenty-horizontal .twentytwenty-after-label:before {
top: 50%;
margin-top: -19px; }
.twentytwenty-vertical .twentytwenty-before-label:before, .twentytwenty-vertical .twentytwenty-after-label:before {
left: 50%;
margin-left: -45px;
text-align: center;
width: 90px; }
.twentytwenty-left-arrow, .twentytwenty-right-arrow, .twentytwenty-up-arrow, .twentytwenty-down-arrow {
width: 0;
height: 0;
border: 6px inset transparent;
position: absolute; }
.twentytwenty-left-arrow, .twentytwenty-right-arrow {
top: 50%;
margin-top: -6px; }
.twentytwenty-up-arrow, .twentytwenty-down-arrow {
left: 50%;
margin-left: -6px; }
.twentytwenty-container {
-webkit-box-sizing: content-box;
-moz-box-sizing: content-box;
box-sizing: content-box;
z-index: 0;
overflow: hidden;
position: relative;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none; }
.twentytwenty-container img {
max-width: 100%;
position: absolute;
top: 0;
display: block; }
.twentytwenty-container.active .twentytwenty-overlay, .twentytwenty-container.active :hover.twentytwenty-overlay {
background: rgba(0, 0, 0, 0); }
.twentytwenty-container.active .twentytwenty-overlay .twentytwenty-before-label,
.twentytwenty-container.active .twentytwenty-overlay .twentytwenty-after-label, .twentytwenty-container.active :hover.twentytwenty-overlay .twentytwenty-before-label,
.twentytwenty-container.active :hover.twentytwenty-overlay .twentytwenty-after-label {
opacity: 0; }
.twentytwenty-container * {
-webkit-box-sizing: content-box;
-moz-box-sizing: content-box;
box-sizing: content-box; }
.twentytwenty-before-label {
opacity: 0; }
.twentytwenty-before-label:before {
content: attr(data-content); }
.twentytwenty-after-label {
opacity: 0; }
.twentytwenty-after-label:before {
content: attr(data-content); }
.twentytwenty-horizontal .twentytwenty-before-label:before {
left: 10px; }
.twentytwenty-horizontal .twentytwenty-after-label:before {
right: 10px; }
.twentytwenty-vertical .twentytwenty-before-label:before {
top: 10px; }
.twentytwenty-vertical .twentytwenty-after-label:before {
bottom: 10px; }
.twentytwenty-overlay {
-webkit-transition-property: background;
-moz-transition-property: background;
transition-property: background;
background: rgba(0, 0, 0, 0);
z-index: 25; }
.twentytwenty-overlay:hover {
background: rgba(0, 0, 0, 0.5); }
.twentytwenty-overlay:hover .twentytwenty-after-label {
opacity: 1; }
.twentytwenty-overlay:hover .twentytwenty-before-label {
opacity: 1; }
.twentytwenty-before {
z-index: 20; }
.twentytwenty-after {
z-index: 10; }
.twentytwenty-handle {
height: 38px;
width: 38px;
position: absolute;
left: 50%;
top: 50%;
margin-left: -22px;
margin-top: -22px;
border: 3px solid white;
-webkit-border-radius: 1000px;
-moz-border-radius: 1000px;
border-radius: 1000px;
-webkit-box-shadow: 0px 0px 12px rgba(51, 51, 51, 0.5);
-moz-box-shadow: 0px 0px 12px rgba(51, 51, 51, 0.5);
box-shadow: 0px 0px 12px rgba(51, 51, 51, 0.5);
z-index: 40;
cursor: pointer; }
.twentytwenty-horizontal .twentytwenty-handle:before {
bottom: 50%;
margin-bottom: 22px;
-webkit-box-shadow: 0 3px 0 white, 0px 0px 12px rgba(51, 51, 51, 0.5);
-moz-box-shadow: 0 3px 0 white, 0px 0px 12px rgba(51, 51, 51, 0.5);
box-shadow: 0 3px 0 white, 0px 0px 12px rgba(51, 51, 51, 0.5); }
.twentytwenty-horizontal .twentytwenty-handle:after {
top: 50%;
margin-top: 22px;
-webkit-box-shadow: 0 -3px 0 white, 0px 0px 12px rgba(51, 51, 51, 0.5);
-moz-box-shadow: 0 -3px 0 white, 0px 0px 12px rgba(51, 51, 51, 0.5);
box-shadow: 0 -3px 0 white, 0px 0px 12px rgba(51, 51, 51, 0.5); }
.twentytwenty-vertical .twentytwenty-handle:before {
left: 50%;
margin-left: 22px;
-webkit-box-shadow: 3px 0 0 white, 0px 0px 12px rgba(51, 51, 51, 0.5);
-moz-box-shadow: 3px 0 0 white, 0px 0px 12px rgba(51, 51, 51, 0.5);
box-shadow: 3px 0 0 white, 0px 0px 12px rgba(51, 51, 51, 0.5); }
.twentytwenty-vertical .twentytwenty-handle:after {
right: 50%;
margin-right: 22px;
-webkit-box-shadow: -3px 0 0 white, 0px 0px 12px rgba(51, 51, 51, 0.5);
-moz-box-shadow: -3px 0 0 white, 0px 0px 12px rgba(51, 51, 51, 0.5);
box-shadow: -3px 0 0 white, 0px 0px 12px rgba(51, 51, 51, 0.5); }
.twentytwenty-left-arrow {
border-right: 6px solid white;
left: 50%;
margin-left: -17px; }
.twentytwenty-right-arrow {
border-left: 6px solid white;
right: 50%;
margin-right: -17px; }
.twentytwenty-up-arrow {
border-bottom: 6px solid white;
top: 50%;
margin-top: -17px; }
.twentytwenty-down-arrow {
border-top: 6px solid white;
bottom: 50%;
margin-bottom: -17px; }
File diff suppressed because one or more lines are too long
@@ -0,0 +1,691 @@
var cx_cancel_bulk_optimization=false;
var cx_pause_bulk_optimization=false;
var cx_bulk_task_running = false;
jQuery('#cx-v2-start-now').on('click', function ()
{
compressx_start_bulk_optimization();
});
jQuery('#cx-v2-cancel-bulk').on('click', function ()
{
if(cx_bulk_task_running)
{
var descript = compressx_bulk_i18n.cancel_confirm;
var ret = confirm(descript);
if(ret === true)
{
cx_cancel_bulk_optimization=true;
jQuery('#cx-v2-cancel-bulk').css({'pointer-events': 'none', 'opacity': '0.4'});
}
}
else
{
jQuery('#cx-v2-bulk-ready').show();
jQuery('#cx-v2-bulk-progress').hide();
}
});
jQuery('#cx-v2-pause-bulk').on('click', function ()
{
var descript = compressx_bulk_i18n.pause_confirm;
var ret = confirm(descript);
if(ret === true)
{
cx_pause_bulk_optimization=true;
jQuery('#cx-v2-pause-bulk').css({'pointer-events': 'none', 'opacity': '0.4'});
}
});
//
jQuery('#cx_bulk_success_hide').on('click', function ()
{
jQuery('#cx_bulk_success').hide();
jQuery('#cx-v2-bulk-ready').show();
jQuery('#cx-v2-bulk-progress').hide();
});
jQuery('#cx_bulk_error_hide').on('click', function ()
{
jQuery('#cx_bulk_error').hide();
jQuery('#cx-v2-bulk-ready').show();
jQuery('#cx-v2-bulk-progress').hide();
});
jQuery('#cx-v2-log-copy').on('click', function() {
var logContent = jQuery('#cx-v2-live-log').text();
if (logContent)
{
// Check if Clipboard API is available
if (navigator.clipboard && navigator.clipboard.writeText)
{
navigator.clipboard.writeText(logContent).then(function()
{
alert('Log copied to clipboard!');
}).catch(function() {
// Fallback if clipboard API fails
});
}
else
{
// Use fallback for non-HTTPS or unsupported browsers
}
}
});
jQuery('#cx-v2-log-download').on('click', function()
{
location.href =ajaxurl+'?_wpnonce='+compressx_ajax_object.ajax_nonce+'&action=compressx_download_task_log';
});
var currentLogFilename='';
jQuery('.cx-log-details').on('click', function(e)
{
e.preventDefault();
var logFilename = jQuery(this).data('log');
compressx_open_log_details(logFilename);
});
function compressx_open_log_details(logFilename)
{
var ajax_data = {
action: 'compressx_open_log',
filename: logFilename
};
compressx_post_request(ajax_data, function(response)
{
try {
response = JSON.parse(response);
if (response.result === 'success')
{
currentLogFilename = logFilename;
jQuery('#cx-v2-log-content').val(response.data);
jQuery('#cx-v2-log-created-date').text(response.create || '--');
jQuery('#cx-v2-log-modal').show();
jQuery('html, body').animate({
scrollTop: jQuery('#cx-v2-log-modal').offset().top - 100
}, 500);
} else {
alert('Failed to open log: ' + (response.error || 'Unknown error'));
}
} catch(err) {
alert('An error occurred while opening log.');
}
}, function(XMLHttpRequest, textStatus, errorThrown) {
var error_message = compressx_output_ajaxerror('opening log', textStatus, errorThrown);
alert(error_message);
});
}
jQuery('.cx-log-download').on('click', function(e)
{
e.preventDefault();
var logFilename = jQuery(this).data('log');
var download_url = ajaxurl +
'?action=compressx_download_log&log=' +
logFilename +
'&nonce=' + compressx_ajax_object.ajax_nonce;
window.location.href = download_url;
});
jQuery('.cx-log-delete').on('click', function(e)
{
e.preventDefault();
var logFilename = jQuery(this).data('log');
var $element= jQuery(this);
if (!confirm(compressx_bulk_i18n.delete_log_confirm))
{
return;
}
var ajax_data = {
action: 'compressx_delete_log',
filename: logFilename
};
compressx_post_request(ajax_data, function(response) {
try {
response = JSON.parse(response);
if (response.result === 'success') {
$element.closest('tr').fadeOut(function() {
jQuery(this).remove();
});
} else {
alert('Failed to delete log: ' + (response.error || 'Unknown error'));
}
} catch(err) {
alert('An error occurred while deleting log.');
}
}, function(XMLHttpRequest, textStatus, errorThrown) {
var error_message = compressx_output_ajaxerror('deleting log', textStatus, errorThrown);
alert(error_message);
});
});
jQuery('#cx-v2-download-current-log').on('click', function()
{
//currentLogFilename
if (currentLogFilename === "")
{
return;
}
var download_url = ajaxurl +
'?action=compressx_download_log&log=' +
currentLogFilename +
'&nonce=' + compressx_ajax_object.ajax_nonce;
window.location.href = download_url;}
);
jQuery('#cx-v2-close-log').on('click', function(e)
{
jQuery('#cx-v2-log-modal').hide();
currentLogFilename = '';
});
function compressx_start_bulk_optimization()
{
var force="0";
if(jQuery('#cx-v2-force-reprocess').prop('checked'))
{
force = '1';
}
else {
force = '0';
}
var ajax_data = {
'action': 'compressx_start_scan_unoptimized_image',
'force':force
};
cx_cancel_bulk_optimization=false;
jQuery('#cx-v2-cancel-bulk').css({'pointer-events': 'auto', 'opacity': '1'});
cx_pause_bulk_optimization=false;
jQuery('#cx-v2-pause-bulk').css({'pointer-events': 'auto', 'opacity': '1'});
jQuery('#cx-v2-bulk-ready').hide();
jQuery('#cx-v2-bulk-progress').show();
compressx_reset_bulk_progress();
cx_bulk_task_running=true;
compressx_post_request(ajax_data, function (data)
{
if(cx_cancel_bulk_optimization)
{
compressx_bulk_optimization_canceled();
return;
}
if(cx_pause_bulk_optimization)
{
compressx_bulk_optimization_paused();
return;
}
var jsonarray = jQuery.parseJSON(data);
if (jsonarray.result === 'success')
{
if(jsonarray.finished==true)
{
compressx_update_bulk_scan_progress(jsonarray.progress_text,jsonarray.progress_percent);
compressx_init_bulk_optimization_task();
}
else
{
compressx_update_bulk_scan_progress(jsonarray.progress_text,jsonarray.progress_percent);
compressx_scanning_images(jsonarray.offset);
}
}
else
{
compressx_progress_error(jsonarray.error);
}
}, function (XMLHttpRequest, textStatus, errorThrown)
{
var error_message = compressx_output_ajaxerror('scanning images', textStatus, errorThrown);
compressx_progress_error(error_message);
});
}
function compressx_scanning_images(offset)
{
var force="0";
if(jQuery('#cx-v2-force-reprocess').prop('checked'))
{
force = '1';
}
else {
force = '0';
}
var ajax_data = {
'action': 'compressx_start_scan_unoptimized_image',
'force':force,
'offset':offset
};
cx_cancel_bulk_optimization=false;
compressx_post_request(ajax_data, function (data)
{
if(cx_cancel_bulk_optimization)
{
compressx_bulk_optimization_canceled();
return;
}
if(cx_pause_bulk_optimization)
{
compressx_bulk_optimization_paused();
return;
}
var jsonarray = jQuery.parseJSON(data);
if (jsonarray.result === 'success')
{
if(jsonarray.finished==true)
{
compressx_update_bulk_scan_progress(jsonarray.progress_text,jsonarray.progress_percent);
compressx_init_bulk_optimization_task();
}
else
{
compressx_update_bulk_scan_progress(jsonarray.progress_text,jsonarray.progress_percent);
compressx_scanning_images(jsonarray.offset);
}
}
else
{
compressx_progress_error(jsonarray.error);
}
}, function (XMLHttpRequest, textStatus, errorThrown)
{
var error_message = compressx_output_ajaxerror('scanning images', textStatus, errorThrown);
compressx_progress_error(error_message);
});
}
function compressx_init_bulk_optimization_task()
{
var force="0";
if(jQuery('#cx-v2-force-reprocess').prop('checked'))
{
force = '1';
}
else {
force = '0';
}
var ajax_data = {
'action': 'compressx_init_bulk_optimization_task',
'force':force
};
compressx_post_request(ajax_data, function (data)
{
if(cx_cancel_bulk_optimization)
{
compressx_bulk_optimization_canceled();
return;
}
if(cx_pause_bulk_optimization)
{
compressx_bulk_optimization_paused();
return;
}
var jsonarray = jQuery.parseJSON(data);
if (jsonarray.result === 'success')
{
compressx_get_task_log();
compressx_run_optimize();
}
else
{
if(jsonarray.no_unoptimized_images)
{
compressx_progress_finish(jsonarray.error,"Optimization Status:");
}
else
{
compressx_progress_error(jsonarray.error);
}
}
}, function (XMLHttpRequest, textStatus, errorThrown)
{
var error_message = compressx_output_ajaxerror('start bulk optimization', textStatus, errorThrown);
compressx_progress_error(error_message);
});
}
function compressx_run_optimize()
{
var ajax_data = {
'action': 'compressx_run_optimize',
};
compressx_post_request(ajax_data, function (data)
{
try
{
var jsonarray = jQuery.parseJSON(data);
if (jsonarray.result === 'success')
{
setTimeout(function ()
{
compressx_get_optimize_task_status();
}, 1000);
}
else
{
compressx_progress_error(jsonarray.error);
}
}
catch(err)
{
setTimeout(function ()
{
compressx_get_optimize_task_status();
}, 1000);
}
}, function (XMLHttpRequest, textStatus, errorThrown)
{
compressx_get_optimize_task_status();
});
}
function compressx_get_optimize_task_status()
{
var ajax_data = {
'action': 'compressx_get_opt_progress'
};
compressx_post_request(ajax_data, function(data)
{
try
{
var jsonarray = jQuery.parseJSON(data);
if (jsonarray.result === 'success')
{
//progress_text,progress_percent,sub_progress_text,sub_progress_percent,optimized,errors,remaining
compressx_update_bulk_progress(jsonarray.progress_text,jsonarray.progress_percent,jsonarray.sub_progress_text,jsonarray.sub_progress_percent,jsonarray.optimized,jsonarray.errors,jsonarray.remaining);
if(jsonarray.continue)
{
setTimeout(function ()
{
compressx_get_optimize_task_status();
}, 1000);
}
else if(jsonarray.finished)
{
jQuery(document).trigger('compressx:hasUpdateImageData');
compressx_progress_finish(jsonarray.message);
compressx_show_review_box(jsonarray);
}
else
{
if(cx_cancel_bulk_optimization)
{
compressx_bulk_optimization_canceled(jsonarray.message);
return;
}
if(cx_pause_bulk_optimization)
{
compressx_bulk_optimization_paused();
return;
}
jQuery(document).trigger('compressx:hasUpdateImageData');
compressx_run_optimize();
}
}
else if (jsonarray.result === 'failed')
{
if(jsonarray.timeout)
{
if(cx_cancel_bulk_optimization)
{
compressx_bulk_optimization_canceled(jsonarray.message);
return;
}
if(cx_pause_bulk_optimization)
{
compressx_bulk_optimization_paused();
return;
}
compressx_run_optimize();
}
else
{
compressx_progress_error(jsonarray.error);
}
}
}
catch(err)
{
setTimeout(function ()
{
compressx_get_optimize_task_status();
}, 1000);
}
}, function(XMLHttpRequest, textStatus, errorThrown)
{
setTimeout(function ()
{
compressx_get_optimize_task_status();
}, 1000);
});
}
function compressx_get_task_log(offset)
{
if(!cx_bulk_task_running)
return;
var ajax_data = {
'action': 'compressx_get_task_log',
'offset':offset
};
compressx_post_request(ajax_data, function(data)
{
try
{
var jsonarray = jQuery.parseJSON(data);
if (jsonarray.result === 'success')
{
var $logContainer = jQuery('#cx-v2-live-log');
$logContainer.append(jsonarray.content);
if (jQuery('#cx-v2-log-autoscroll').is(':checked'))
{
$logContainer.scrollTop($logContainer[0].scrollHeight);
}
compressx_limit_log_lines($logContainer, 5000);
setTimeout(function ()
{
compressx_get_task_log(jsonarray.offset);
}, 3000);
}
else
{
//
}
}
catch(err)
{
setTimeout(function ()
{
compressx_get_task_log(0);
}, 3000);
}
}, function(XMLHttpRequest, textStatus, errorThrown)
{
setTimeout(function ()
{
compressx_get_task_log(0);
}, 3000);
});
}
function compressx_limit_log_lines($container,maxLines)
{
var lines = $container.text().split('\n');
if (lines.length > maxLines)
{
var newLines = lines.slice(lines.length - maxLines);
$container.text(newLines.join('\n'));
}
}
function compressx_reset_bulk_progress()
{
jQuery('#cx-v2-progress-status').html("Ready");
jQuery('#cx-v2-scan-status').html("0 images scanned");
jQuery('#cx-v2-scan-progress-bar').width("0%");
jQuery('#cx-v2-overall-progress-text').html("0 images processed");
jQuery('#cx-v2-overall-progress-bar').width("0%");
jQuery('#cx-v2-job-current').html("None");
jQuery('#cx-v2-job-progress-bar').width("0%");
jQuery('#cx-v2-stat-optimized').html("0");
jQuery('#cx-v2-stat-errors').html("0");
jQuery('#cx-v2-stat-remaining').html("0");
jQuery('#cx_bulk_warning').show();
jQuery('#cx_bulk_success').hide();
jQuery('#cx_bulk_error').hide();
jQuery('#cx-v2-live-log').html("");
}
function compressx_bulk_optimization_canceled(message)
{
//jQuery('#cx-v2-bulk-ready').show();
//jQuery('#cx-v2-bulk-progress').hide();
jQuery('#cx-v2-cancel-bulk').css({'pointer-events': 'auto', 'opacity': '1'});
jQuery('#cx_bulk_warning').hide();
jQuery('#cx_bulk_success').show();
jQuery('#cx_bulk_success_title').html("The process has been canceled");
jQuery('#cx_bulk_success_message').html(message);
cx_bulk_task_running=false;
}
function compressx_bulk_optimization_paused()
{
cx_pause_bulk_optimization=false;
jQuery('#cx-v2-pause-bulk').css({'pointer-events': 'auto', 'opacity': '1'});
}
function compressx_update_bulk_scan_progress(progress_text,progress_percent)
{
jQuery('#cx-v2-progress-status').html("Scanning");
jQuery('#cx-v2-scan-status').html(progress_text);
jQuery('#cx-v2-scan-progress-bar').width(progress_percent+"%");
}
function compressx_update_bulk_progress(progress_text,progress_percent,sub_progress_text,sub_progress_percent,optimized,errors,remaining)
{
jQuery('#cx-v2-progress-status').html("Running");
jQuery('#cx-v2-overall-progress-text').html(progress_text);
jQuery('#cx-v2-overall-progress-bar').width(progress_percent+"%");
jQuery('#cx-v2-job-current').html(sub_progress_text);
jQuery('#cx-v2-job-progress-bar').width(sub_progress_percent+"%");
jQuery('#cx-v2-stat-optimized').html(optimized);
jQuery('#cx-v2-stat-errors').html(errors);
jQuery('#cx-v2-stat-remaining').html(remaining);
}
function compressx_progress_finish(message,title=compressx_bulk_i18n.optimization_success)
{
//jQuery('#cx-v2-bulk-ready').show();
//jQuery('#cx-v2-bulk-progress').hide();
jQuery('#cx_bulk_warning').hide();
jQuery('#cx_bulk_success').show();
jQuery('#cx_bulk_success_title').html(title);
jQuery('#cx_bulk_success_message').html(message);
cx_bulk_task_running=false;
}
function compressx_progress_error(message)
{
//jQuery('#cx-v2-bulk-ready').show();
//jQuery('#cx-v2-bulk-progress').hide();
jQuery('#cx_bulk_warning').hide();
jQuery('#cx_bulk_error').show();
jQuery('#cx_bulk_error_title').html("Error: Optimization Failed");
jQuery('#cx_bulk_error_message').html(message);
cx_bulk_task_running=false;
}
function compressx_show_review_box(jsonarray)
{
if(jsonarray.show_review)
{
jQuery('#cx_rating_box').show();
jQuery('#cx_size_of_opt_images').html(jsonarray.opt_size);
}
}
window.addEventListener('click', function(e)
{
if(cx_bulk_task_running && e.target.matches('a')){
if(!confirm(compressx_bulk_i18n.leave_page_confirm))
{
e.preventDefault();
}
}
});
window.addEventListener("beforeunload", function (e) {
if (cx_bulk_task_running)
{
e.preventDefault();
e.returnValue = "Leaving this page will interrupt the optimization task.";
return "Leaving this page will interrupt the optimization task.";
}
});
@@ -0,0 +1,115 @@
jQuery(document).ready(function($) {
$('#compressx_save_cdn').click(function() {
compressx_save_cdn_setting();
});
$('#compressx_purge_cache').click(function() {
compressx_purge_cache();
});
$('#compressx_cdn_provider').on('change', function() {
var provider = $(this).val();
if (provider === 'cloudflare') {
$('#cloudflare_container').show();
$('#bunnycdn_container').hide();
} else if (provider === 'bunnycdn') {
$('#cloudflare_container').hide();
$('#bunnycdn_container').show();
}
});
$(document).trigger('compressx_cdn_v2_js_ready');
});
function compressx_save_cdn_setting() {
var json = {};
var option_type = 'cf_cdn';
var action_name = 'compressx_save_cdn';
var save_override = jQuery(document).triggerHandler('compressx_cdn_v2_save_override');
if (save_override) {
return save_override;
}
var setting_data = compressx_ajax_data_transfer(option_type);
var json1 = JSON.parse(setting_data);
jQuery.extend(json1, json);
setting_data = JSON.stringify(json1);
var ajax_data = {
'action': action_name,
'setting': setting_data,
};
jQuery('#compressx_save_cdn').css({'pointer-events': 'none', 'opacity': '0.4'});
jQuery('#compressx_save_cdn_progress').show();
compressx_post_request(ajax_data, function (data) {
try {
var jsonarray = jQuery.parseJSON(data);
jQuery('#compressx_save_cdn').css({'pointer-events': 'auto', 'opacity': '1'});
jQuery('#compressx_save_cdn_progress').hide();
if (jsonarray.result === 'success') {
jQuery('#compressx_save_cdn_text').removeClass("hidden");
setTimeout(function () {
jQuery('#compressx_save_cdn_text').addClass('hidden');
}, 3000);
} else {
alert(jsonarray.error);
}
} catch (err) {
alert(err);
jQuery('#compressx_save_cdn').css({'pointer-events': 'auto', 'opacity': '1'});
jQuery('#compressx_save_cdn_progress').hide();
}
}, function (XMLHttpRequest, textStatus, errorThrown) {
jQuery('#compressx_save_cdn').css({'pointer-events': 'auto', 'opacity': '1'});
jQuery('#compressx_save_cdn_progress').hide();
var error_message = compressx_output_ajaxerror('changing settings', textStatus, errorThrown);
alert(error_message);
});
}
function compressx_purge_cache() {
var json = {};
var setting_data = compressx_ajax_data_transfer('cf_cdn');
var json1 = JSON.parse(setting_data);
jQuery.extend(json1, json);
setting_data = JSON.stringify(json1);
var ajax_data = {
'action': 'compressx_purge_cache',
'setting': setting_data,
};
jQuery('#compressx_purge_cache').css({'pointer-events': 'none', 'opacity': '0.4'});
jQuery('#compressx_purge_cache_progress').show();
compressx_post_request(ajax_data, function (data) {
jQuery('#compressx_purge_cache_progress').hide();
try {
var jsonarray = jQuery.parseJSON(data);
jQuery('#compressx_purge_cache').css({'pointer-events': 'auto', 'opacity': '1'});
if (jsonarray.result === 'success') {
jQuery('#compressx_purge_cache_text').removeClass("hidden");
setTimeout(function () {
jQuery('#compressx_purge_cache_text').addClass('hidden');
}, 3000);
} else {
alert(jsonarray.error);
}
} catch (err) {
alert(err);
jQuery('#compressx_purge_cache').css({'pointer-events': 'auto', 'opacity': '1'});
}
}, function (XMLHttpRequest, textStatus, errorThrown) {
jQuery('#compressx_purge_cache_progress').hide();
jQuery('#compressx_purge_cache').css({'pointer-events': 'auto', 'opacity': '1'});
var error_message = compressx_output_ajaxerror('changing settings', textStatus, errorThrown);
alert(error_message);
});
}
@@ -0,0 +1,337 @@
//
let isHoveringComparison = false;
let hasUpdateImageData=false;
let latestImageData = null;
let currentComparisonMode = 'webp';
jQuery('#cx-v2-bulk-comparison-container').on('mouseenter', function()
{
isHoveringComparison = true;
}).on('mouseleave', function() {
isHoveringComparison = false;
});
jQuery('#cx-v2-bulk-show-webp').on('click', function () {
switchComparisonMode('webp');
});
jQuery('#cx-v2-bulk-show-avif').on('click', function () {
switchComparisonMode('avif');
});
jQuery('#cx-v2-bulk-show-formats').on('click', function () {
switchComparisonMode('formats');
});
function resetComparison()
{
var $container = jQuery('#cx-v2-bulk-comparison-container');
// Use the dedicated destroy function
destroyComparison($container);
// Reset opacity and add placeholder
$container.css('opacity', '1');
$container.append('<div class="cx-comparison-placeholder"><span class="compressx-v2-text-gray-500 compressx-v2-text-sm">Comparison will appear here during optimization</span></div>');
jQuery('#cx-v2-bulk-format-toggle').hide();
// Reset comparison buttons to default state
updateComparisonButtons(currentComparisonMode);
jQuery('#cx-v2-original-size').text('--');
jQuery('#cx-v2-webp-size').text('--');
jQuery('#cx-v2-webp-savings').text('');
jQuery('#cx-v2-avif-size').text('--');
jQuery('#cx-v2-avif-savings').text('');
latestImageData = null;
}
function destroyComparison($container) {
if ($container.hasClass('twentytwenty-container')) {
$container.off('.twentytwenty');
$container.removeClass('twentytwenty-container');
}
$container.empty();
}
function switchComparisonMode(mode)
{
currentComparisonMode = mode;
updateComparisonButtons(mode);
if (latestImageData) {
renderComparison(latestImageData, mode);
}
}
function updateComparisonButtons(activeMode)
{
jQuery('#cx-v2-bulk-show-webp, #cx-v2-bulk-show-avif, #cx-v2-bulk-show-formats')
.removeClass('hover:compressx-v2-bg-gray-100 compressx-v2-bg-green-500 compressx-v2-text-white compressx-v2-border-green-500')
.addClass('compressx-v2-bg-gray-50 compressx-v2-text-gray-700 compressx-v2-border-gray-300');
var activeButton = null;
if (activeMode === 'webp') {
activeButton = '#cx-v2-bulk-show-webp';
} else if (activeMode === 'avif') {
activeButton = '#cx-v2-bulk-show-avif';
} else if (activeMode === 'formats') {
activeButton = '#cx-v2-bulk-show-formats';
}
if (activeButton)
{
jQuery(activeButton)
.removeClass('compressx-v2-bg-gray-50 compressx-v2-text-gray-700 compressx-v2-border-gray-300')
.addClass('compressx-v2-bg-green-500 compressx-v2-text-white compressx-v2-border-green-500');
}
}
function renderComparison(imageData, mode)
{
var $container = jQuery('#cx-v2-bulk-comparison-container');
$container.css({
'opacity': '0',
'transition': 'opacity 0.3s ease'
});
// Completely destroy and rebuild the comparison container
destroyComparison($container);
var beforeImg, afterImg, beforeLabel, afterLabel;
var hasWebP = imageData.webp_url && !imageData.webp_disabled;
var hasAVIF = imageData.avif_url && !imageData.avif_disabled;
// Determine which buttons to show and default mode
var showToggle = hasWebP && hasAVIF;
var availableModes = [];
if (hasWebP) availableModes.push('webp');
if (hasAVIF) availableModes.push('avif');
if (hasWebP && hasAVIF) availableModes.push('formats');
// Update button visibility
jQuery('#cx-v2-bulk-show-webp').toggle(hasWebP && hasAVIF);
jQuery('#cx-v2-bulk-show-avif').toggle(hasWebP && hasAVIF);
jQuery('#cx-v2-bulk-show-formats').toggle(hasWebP && hasAVIF);
// Show or hide the toggle container
if (showToggle) {
jQuery('#cx-v2-bulk-format-toggle').show();
} else {
jQuery('#cx-v2-bulk-format-toggle').hide();
}
// Auto-select appropriate mode if current mode is not available
if (!availableModes.includes(mode)) {
mode = availableModes[0] || 'webp';
currentComparisonMode = mode;
updateComparisonButtons(mode);
}
if (mode === 'webp' && hasWebP) {
beforeImg = imageData.original_url;
afterImg = imageData.webp_url;
beforeLabel = 'Original';
afterLabel = 'WebP';
} else if (mode === 'avif' && hasAVIF) {
beforeImg = imageData.original_url;
afterImg = imageData.avif_url;
beforeLabel = 'Original';
afterLabel = 'AVIF';
} else if (mode === 'formats' && hasWebP && hasAVIF) {
beforeImg = imageData.webp_url;
afterImg = imageData.avif_url;
beforeLabel = 'WebP';
afterLabel = 'AVIF';
} else {
$container.append('<div class="cx-comparison-placeholder"><span class="compressx-v2-text-gray-500 compressx-v2-text-sm">Comparison not available for this mode</span></div>');
$container.css('opacity', '1');
return;
}
$container.append('<img src="' + beforeImg + '" />');
$container.append('<img src="' + afterImg + '" />');
reinitializeTwentyTwenty($container, function() {
$container.css('opacity', '1');
}, beforeLabel, afterLabel);
}
function updateComparisonData(imageData) {
if (isHoveringComparison) {
return;
}
latestImageData = imageData;
if (imageData.original_size) {
jQuery('#cx-v2-original-size').text(imageData.original_size);
}
if (imageData.webp_url && !imageData.webp_disabled)
{
jQuery('#cx-v2-webp-size').text(imageData.webp_size || '--');
jQuery('#cx-v2-webp-savings').text(imageData.webp_savings || '');
}
else {
jQuery('#cx-v2-webp-size').text('--');
jQuery('#cx-v2-webp-savings').text('');
}
if (imageData.avif_url && !imageData.avif_disabled)
{
jQuery('#cx-v2-avif-size').text(imageData.avif_size || '--');
jQuery('#cx-v2-avif-savings').text(imageData.avif_savings || '');
}
else {
jQuery('#cx-v2-avif-size').text('--');
jQuery('#cx-v2-avif-savings').text('');
}
// Determine appropriate comparison mode based on available formats
var hasWebP = imageData.webp_url && !imageData.webp_disabled;
var hasAVIF = imageData.avif_url && !imageData.avif_disabled;
var targetMode = currentComparisonMode;
// Auto-switch to available format if current mode is not available
if (currentComparisonMode === 'webp' && !hasWebP && hasAVIF) {
targetMode = 'avif';
} else if (currentComparisonMode === 'avif' && !hasAVIF && hasWebP) {
targetMode = 'webp';
} else if (currentComparisonMode === 'formats' && !(hasWebP && hasAVIF)) {
targetMode = hasWebP ? 'webp' : 'avif';
} else if (!hasWebP && !hasAVIF) {
// No formats available
targetMode = 'webp'; // Fallback
} else if (hasWebP && currentComparisonMode !== 'avif' && currentComparisonMode !== 'formats') {
targetMode = 'webp';
} else if (hasAVIF && !hasWebP) {
targetMode = 'avif';
}
if (targetMode !== currentComparisonMode) {
currentComparisonMode = targetMode;
}
renderComparison(imageData, currentComparisonMode);
}
function reinitializeTwentyTwenty($container, callback, beforeLabel, afterLabel) {
var images = $container.find('img');
var loadedCount = 0;
var totalImages = images.length;
if (totalImages === 0) {
if (callback) callback();
return;
}
images.off('load.cxcmp').on('load.cxcmp', function () {
loadedCount++;
if (loadedCount !== totalImages) return;
setTimeout(function () {
if (typeof jQuery.fn.twentytwenty !== 'function') {
if (callback) callback();
return;
}
var options = {
default_offset_pct: 0.5,
move_slider_on_hover: false,
move_with_handle_only: true,
click_to_move: false,
no_overlay: false,
before_label: beforeLabel || 'Before',
after_label: afterLabel || 'After'
};
var $img = $container.find('img').first();
var naturalW = $img[0]?.naturalWidth || 0;
if (naturalW) {
$container.css({
maxWidth: naturalW + 'px',
marginLeft: 'auto',
marginRight: 'auto'
});
}
$container.twentytwenty(options);
$container.find('img').css({
'max-width': '100%',
'height': 'auto',
'width': '100%',
'display': 'block'
});
var raf = window.requestAnimationFrame || function (fn) { return setTimeout(fn, 0); };
raf(async function () {
jQuery(window).trigger('resize.twentytwenty');
callback && callback();
});
}, 0);
});
images.each(function () {
if (this.complete && this.naturalHeight !== 0) {
jQuery(this).trigger('load.cxcmp');
}
});
}
function init_latestImageData()
{
var ajax_data = {
action: 'compressx_get_latest_image_data',
};
compressx_post_request(ajax_data, function(data)
{
try
{
var jsonarray = JSON.parse(data);
if (jsonarray.result === 'success')
{
updateComparisonData(jsonarray.current_image);
}
else
{
resetComparison();
}
}
catch (err)
{
resetComparison();
}
}, function(XMLHttpRequest, textStatus, errorThrown) {
resetComparison();
});
}
function autoRefreshLatestImageData()
{
if(!isHoveringComparison&&hasUpdateImageData)
{
init_latestImageData();
hasUpdateImageData = false;
}
setTimeout(autoRefreshLatestImageData, 10000);
}
jQuery(document).on('compressx:hasUpdateImageData', function () {
hasUpdateImageData = true;
});
jQuery(document).ready(function ($)
{
init_latestImageData();
autoRefreshLatestImageData();
});
@@ -0,0 +1,455 @@
jQuery('#cx_hide_big_update').click(function()
{
jQuery('#cx_big_update').hide();
var ajax_data = {
'action': 'compressx_hide_big_update_v2',
};
compressx_post_request(ajax_data, function(data)
{
}, function(XMLHttpRequest, textStatus, errorThrown) {
});
});
jQuery('#cx_show_size_threshold_tip').on('click', function()
{
jQuery('#cx_size_threshold_tip').slideToggle(150);
});
jQuery('input:radio[name=compression_mode]').click(function(e)
{
if(jQuery(this).prop('checked'))
{
//var $saveButton = jQuery("#cx-v2-save-settings");
let value = jQuery(this).prop('value');
if(value==='smart')
{
//$saveButton.css({ 'pointer-events': 'none', 'opacity': '0.4' });
jQuery("#compressx_general_quality_setting").hide();
jQuery("#compressx_smart_quality_setting").show();
jQuery("#cx_compression_mode_smart").closest('label').addClass('compressx-v2-bg-white');
jQuery("#cx_compression_mode_general").closest('label').removeClass('compressx-v2-bg-white');
}
else if(value==='general')
{
//$saveButton.css({ 'pointer-events': 'auto', 'opacity': '1' });
jQuery("#compressx_general_quality_setting").show();
jQuery("#compressx_smart_quality_setting").hide();
jQuery("#cx_compression_mode_general").closest('label').addClass('compressx-v2-bg-white');
jQuery("#cx_compression_mode_smart").closest('label').removeClass('compressx-v2-bg-white');
}
}
});
jQuery('#cx_convert_to_webp').click(function()
{
var value = '0';
if(jQuery('#cx_convert_to_webp').prop('checked'))
{
value = '1';
var descript = compressx_image_optimization_i18n.enable_webp_confirm;
}
else {
value = '0';
var descript = compressx_image_optimization_i18n.disable_webp_confirm;
}
var ret = confirm(descript);
if(ret === false)
{
if(jQuery('#cx_convert_to_webp').prop('checked'))
{
jQuery('#cx_convert_to_webp').prop('checked', false);
}
else
{
jQuery('#cx_convert_to_webp').prop('checked', true);
}
}
else
{
if(jQuery('#cx_convert_to_webp').prop('checked'))
{
jQuery('#cx_convert_to_webp').parent('label').addClass('compressx-v2-bg-white');
}
else
{
jQuery('#cx_convert_to_webp').parent('label').removeClass('compressx-v2-bg-white');
}
}
});
jQuery('#cx_convert_to_avif').click(function()
{
var value = '0';
if(jQuery('#cx_convert_to_avif').prop('checked'))
{
if(jQuery('#cx_converter_method_imagick').prop('checked'))
{
if(compressx_alert.imagick_avif)
{
var descript = compressx_image_optimization_i18n.imagick6_avif_warning;
}
else
{
var descript = compressx_image_optimization_i18n.enable_avif_confirm;
}
}
else
{
var descript = compressx_image_optimization_i18n.enable_avif_confirm;
}
value = '1';
}
else {
value = '0';
var descript = compressx_image_optimization_i18n.disable_avif_confirm;
}
var ret = confirm(descript);
if(ret === false)
{
if(jQuery('#cx_convert_to_avif').prop('checked'))
{
jQuery('#cx_convert_to_avif').prop('checked', false);
}
else
{
jQuery('#cx_convert_to_avif').prop('checked', true);
}
}
else
{
if(jQuery('#cx_convert_to_avif').prop('checked'))
{
jQuery('#cx_convert_to_avif').parent('label').addClass('compressx-v2-bg-white');
}
else
{
jQuery('#cx_convert_to_avif').parent('label').removeClass('compressx-v2-bg-white');
}
}
});
jQuery('#cx_converter_method_gd').click(function()
{
if(jQuery('#cx_converter_method_gd').prop('checked'))
{
jQuery('#cx_converter_method_gd').parent('label').addClass('compressx-v2-bg-white');
}
else
{
jQuery('#cx_converter_method_gd').parent('label').removeClass('compressx-v2-bg-white');
}
if(compressx_alert.support_gd_webp)
{
jQuery('#cx_convert_to_webp').prop('disabled', false);
jQuery('#cx_webp_status').removeClass("compressx-v2-text-red-600");
jQuery('#cx_webp_status').addClass("compressx-v2-text-green-600");
jQuery('#cx_webp_status').html(compressx_image_optimization_i18n.supported);
}
else
{
jQuery('#cx_convert_to_webp').prop('disabled', true);
jQuery('#cx_webp_status').addClass("compressx-v2-text-red-600");
jQuery('#cx_webp_status').removeClass("compressx-v2-text-green-600");
jQuery('#cx_webp_status').html(compressx_image_optimization_i18n.unsupported);
}
if(compressx_alert.support_gd_avif)
{
jQuery('#cx_convert_to_avif').prop('disabled', false);
jQuery('#cx_avif_status').removeClass("compressx-v2-text-red-600");
jQuery('#cx_avif_status').addClass("compressx-v2-text-green-600");
jQuery('#cx_avif_status').html(compressx_image_optimization_i18n.supported);
}
else
{
jQuery('#cx_convert_to_avif').prop('disabled', true);
jQuery('#cx_avif_status').addClass("compressx-v2-text-red-600");
jQuery('#cx_avif_status').removeClass("compressx-v2-text-green-600");
jQuery('#cx_avif_status').html(compressx_image_optimization_i18n.unsupported);
}
});
jQuery('#cx_converter_method_imagick').click(function()
{
if(jQuery('#cx_converter_method_imagick').prop('checked'))
{
jQuery('#cx_converter_method_imagick').parent('label').addClass('compressx-v2-bg-white');
}
else
{
jQuery('#cx_converter_method_imagick').parent('label').removeClass('compressx-v2-bg-white');
}
if(compressx_alert.support_imagick_webp)
{
jQuery('#cx_convert_to_webp').prop('disabled', false);
jQuery('#cx_webp_status').removeClass("compressx-v2-text-red-600");
jQuery('#cx_webp_status').addClass("compressx-v2-text-green-600");
jQuery('#cx_webp_status').html(compressx_image_optimization_i18n.supported);
}
else
{
jQuery('#cx_convert_to_webp').prop('disabled', true);
jQuery('#cx_webp_status').addClass("compressx-v2-text-red-600");
jQuery('#cx_webp_status').removeClass("compressx-v2-text-green-600");
jQuery('#cx_webp_status').html(compressx_image_optimization_i18n.unsupported);
}
if(compressx_alert.support_imagick_avif)
{
jQuery('#cx_convert_to_avif').prop('disabled', false);
jQuery('#cx_avif_status').removeClass("compressx-v2-text-red-600");
jQuery('#cx_avif_status').addClass("compressx-v2-text-green-600");
jQuery('#cx_avif_status').html(compressx_image_optimization_i18n.supported);
}
else
{
jQuery('#cx_convert_to_avif').prop('disabled', true);
jQuery('#cx_avif_status').addClass("compressx-v2-text-red-600");
jQuery('#cx_avif_status').removeClass("compressx-v2-text-green-600");
jQuery('#cx_avif_status').html("Unsupported");
}
});
jQuery('#cx_start_bulk_optimization').click(function()
{
let params = new URLSearchParams(window.location.search);
params.set('view', 'bulk');
window.location.href = window.location.pathname + '?' + params.toString();
});
jQuery('#cx_start_bulk_optimization_2').click(function()
{
let params = new URLSearchParams(window.location.search);
params.set('view', 'bulk');
window.location.href = window.location.pathname + '?' + params.toString();
});
jQuery('#cx-v2-save-settings').click(function(e)
{
e.preventDefault();
var $saveButton = jQuery(this);
$saveButton.css({ 'pointer-events': 'none', 'opacity': '0.4' });
jQuery('#cx-v2-save-settings-progress').show();
var json = {};
if(jQuery('#cx_convert_to_webp').prop('checked'))
{
json['convert_to_webp'] ='1';
}
else
{
json['convert_to_webp'] ='0';
}
if(jQuery('#cx_convert_to_avif').prop('checked'))
{
json['convert_to_avif'] ='1';
}
else
{
json['convert_to_avif'] ='0';
}
if(jQuery('#cx_converter_method_gd').prop('checked'))
{
json['converter_method'] = 'gd';
}
else if(jQuery('#cx_converter_method_imagick').prop('checked'))
{
json['converter_method'] = 'imagick';
}
else
{
json['converter_method'] = '';
}
json['auto_optimize'] = jQuery('#cx_enable_auto_optimize').attr('data-checked');
json['interface_version']= jQuery('input[name="cx-v2-interface-version"]:checked').val();
json['image_load']= jQuery('input[name="cx-v2-browser"]:checked').val();
json['resize']=jQuery('#cx-v2-resize-enable').attr('data-checked') === '1';
json['resize_width']=jQuery('#cx-v2-resize-width').val();
json['resize_height']=jQuery('#cx-v2-resize-height').val();
json['remove_exif']=jQuery('input[name="cx-v2-exif"]:checked').val() === 'strip';
json['auto_remove_larger_format']=jQuery('#cx-v2-avoid-larger').attr('data-checked') === '1';
json['exclude_png']=jQuery('#cx-v2-exclude-png').is(':checked');
json['exclude_png_webp'] =jQuery('#cx-v2-exclude-png-webp').is(':checked');
json['converter_images_pre_request'] =jQuery('#cx-v2-throughput').val();
json['quality_webp']=jQuery('#cx-v2-webp-quality-input').val();
json['quality_avif']=jQuery('#cx-v2-avif-quality-input').val();
if (json['quality_webp'] < 1 || json['quality_webp'] > 100) {
alert('WebP Quality must be between 1 and 99.');
return;
}
if ( json['quality_avif'] < 1 || json['quality_avif'] > 100) {
alert('AVIF Quality must be between 1 and 99.');
return;
}
var ajax_data = {
'action': 'compressx_save_image_optimization_settings',
'settings': JSON.stringify(json),
};
compressx_post_request(ajax_data, function(data)
{
try
{
var jsonarray = JSON.parse(data);
if (jsonarray.result === 'success')
{
$saveButton.css({ 'pointer-events': 'auto', 'opacity': '1' });
jQuery('#cx-v2-save-settings-progress').hide();
jQuery('#cx-v2-save-settings-text').removeClass('compressx-v2-hidden');
setTimeout(function() {
jQuery('#cx-v2-save-settings-text').addClass('compressx-v2-hidden');
}, 3000);
if(jsonarray.interface_version_changed===true)
{
location.reload();
}
}
else
{
$saveButton.css({ 'pointer-events': 'auto', 'opacity': '1' });
jQuery('#cx-v2-save-settings-progress').hide();
alert(jsonarray.error || 'Failed to save settings.');
}
}
catch (err)
{
$saveButton.css({ 'pointer-events': 'auto', 'opacity': '1' });
jQuery('#cx-v2-save-settings-progress').hide();
alert('An error occurred while saving settings.');
}
}, function(XMLHttpRequest, textStatus, errorThrown) {
$saveButton.css({ 'pointer-events': 'auto', 'opacity': '1' });
jQuery('#cx-v2-save-settings-progress').hide();
var error_message = compressx_output_ajaxerror('saving settings', textStatus, errorThrown);
alert(error_message);
});
});
jQuery('#cx_enable_auto_optimize').on('click', function()
{
updateAutoOptimizeSwitch();
});
jQuery('#cx-v2-free-toggle-advanced').click(function(e)
{
e.preventDefault();
var advancedArrow = jQuery('#cx-v2-free-advanced-arrow');
var advancedSection = jQuery('#cx-v2-free-advanced-section');
var isHidden =advancedSection.css('display') === 'none';
if (isHidden)
{
advancedSection.slideDown(300);
advancedArrow.removeClass('dashicons-arrow-right').addClass('dashicons-arrow-down');
}
else
{
advancedSection.slideUp(300);
advancedArrow.removeClass('dashicons-arrow-down').addClass('dashicons-arrow-right');
}
});
jQuery('.cx-v2-tab-btn').click(function(e)
{
e.preventDefault();
var $btn = jQuery(this);
var tabName = $btn.data('tab');
jQuery('.cx-v2-tab-btn').removeClass('compressx-v2-border-b-2 compressx-v2-border-blue-600 compressx-v2-font-medium').addClass('compressx-v2-text-slate-600');
$btn.removeClass('compressx-v2-text-slate-600').addClass('compressx-v2-border-blue-600 compressx-v2-font-medium compressx-v2-border-b-2');
jQuery('[data-tab-panel]').addClass('compressx-v2-hidden');
jQuery('[data-tab-panel="' + tabName + '"]').removeClass('compressx-v2-hidden');
});
function updateAutoOptimizeSwitch()
{
var $switchBtn = jQuery('#cx_enable_auto_optimize');
var $knob = $switchBtn.find('span');
var currentState = $switchBtn.attr('data-checked');
var newState = currentState === '1' ? '0' : '1';
$switchBtn.attr('data-checked', newState);
update_switch($switchBtn,$knob);
}
jQuery('#cx-v2-avoid-larger').on('click', function()
{
var $switchBtn = jQuery('#cx-v2-avoid-larger');
var $knob = $switchBtn.find('span');
var currentState = $switchBtn.attr('data-checked');
var newState = currentState === '1' ? '0' : '1';
$switchBtn.attr('data-checked', newState);
update_switch($switchBtn,$knob);
});
jQuery('#cx-v2-resize-enable').on('click', function()
{
var $switchBtn = jQuery('#cx-v2-resize-enable');
var $knob = $switchBtn.find('span');
var currentState = $switchBtn.attr('data-checked');
var newState = currentState === '1' ? '0' : '1';
$switchBtn.attr('data-checked', newState);
update_switch($switchBtn,$knob);
});
function update_switch($switchBtn,$knob)
{
var isChecked = $switchBtn.attr('data-checked') === '1';
if (isChecked) {
$switchBtn.removeClass('compressx-v2-bg-gray-300');
$switchBtn.addClass('compressx-v2-bg-blue-600');
$switchBtn.removeClass('compressx-v2-border-gray-300');
$switchBtn.addClass('compressx-v2-border-blue-600');
$knob.css('transform', 'translateX(20px)');
$switchBtn.attr('aria-checked', 'true');
} else {
$switchBtn.addClass('compressx-v2-bg-gray-300');
$switchBtn.removeClass('compressx-v2-bg-blue-600');
$switchBtn.addClass('compressx-v2-border-gray-300');
$switchBtn.removeClass('compressx-v2-border-blue-600');
$knob.css('transform', 'translateX(0px)');
$switchBtn.attr('aria-checked', 'false');
}
}
jQuery(document).ready(function ($) {
var $switchBtn = jQuery('#cx_enable_auto_optimize');
var $knob = $switchBtn.find('span');
update_switch($switchBtn,$knob);
$switchBtn = jQuery('#cx-v2-avoid-larger');
$knob = $switchBtn.find('span');
update_switch($switchBtn,$knob);
$switchBtn = jQuery('#cx-v2-resize-enable');
$knob = $switchBtn.find('span');
update_switch($switchBtn,$knob);
});
@@ -0,0 +1,345 @@
jQuery('#cx_log_list').on("click",'#cx_log_search_by_date',function()
{
var start_date = jQuery('#cx_log_list').find('#cx_log_start_date').val();
var start_time = jQuery('#cx_log_list').find('#cx_log_start_time').val();
var end_date = jQuery('#cx_log_list').find('#cx_log_end_date').val();
var end_time = jQuery('#cx_log_list').find('#cx_log_end_time').val();
compressx_get_logs_list(start_date,start_time,end_date,end_time);
});
jQuery('#cx_log_list').on("click",'.first-page',function() {
var start_date = jQuery('#cx_log_list').find('#cx_log_start_date').val();
var start_time = jQuery('#cx_log_list').find('#cx_log_start_time').val();
var end_date = jQuery('#cx_log_list').find('#cx_log_end_date').val();
var end_time = jQuery('#cx_log_list').find('#cx_log_end_time').val();
compressx_get_logs_list(start_date,start_time,end_date,end_time,'first');
});
jQuery('#cx_log_list').on("click",'.prev-page',function() {
var start_date = jQuery('#cx_log_list').find('#cx_log_start_date').val();
var start_time = jQuery('#cx_log_list').find('#cx_log_start_time').val();
var end_date = jQuery('#cx_log_list').find('#cx_log_end_date').val();
var end_time = jQuery('#cx_log_list').find('#cx_log_end_time').val();
var page=parseInt(jQuery(this).attr('value'));
compressx_get_logs_list(start_date,start_time,end_date,end_time,page-1);
});
jQuery('#cx_log_list').on("click",'.next-page',function() {
var start_date = jQuery('#cx_log_list').find('#cx_log_start_date').val();
var start_time = jQuery('#cx_log_list').find('#cx_log_start_time').val();
var end_date = jQuery('#cx_log_list').find('#cx_log_end_date').val();
var end_time = jQuery('#cx_log_list').find('#cx_log_end_time').val();
var page=parseInt(jQuery(this).attr('value'));
compressx_get_logs_list(start_date,start_time,end_date,end_time,page+1);
});
jQuery('#cx_log_list').on("click",'.last-page',function() {
var start_date = jQuery('#cx_log_list').find('#cx_log_start_date').val();
var start_time = jQuery('#cx_log_list').find('#cx_log_start_time').val();
var end_date = jQuery('#cx_log_list').find('#cx_log_end_date').val();
var end_time = jQuery('#cx_log_list').find('#cx_log_end_time').val();
compressx_get_logs_list(start_date,start_time,end_date,end_time,'last');
});
jQuery('#cx_log_list').on("keypress", '.current-page', function() {
var start_date = jQuery('#cx_log_list').find('#cx_log_start_date').val();
var start_time = jQuery('#cx_log_list').find('#cx_log_start_time').val();
var end_date = jQuery('#cx_log_list').find('#cx_log_end_date').val();
var end_time = jQuery('#cx_log_list').find('#cx_log_end_time').val();
if(event.keyCode === 13){
var page = jQuery(this).val();
compressx_get_logs_list(start_date,start_time,end_date,end_time,page);
}
});
var currentLogFilename="";
function compressx_get_logs_list(start_date,start_time,end_date,end_time,page=0)
{
var ajax_data = {
'action':'compressx_get_logs_list',
'start_date':start_date,
'start_time':start_time,
'end_date':end_date,
'end_time':end_time,
'page':page
};
compressx_post_request(ajax_data, function(data)
{
try
{
var jsonarray = jQuery.parseJSON(data);
if (jsonarray.result === "success")
{
jQuery('#cx_log_list').html(jsonarray.html);
jQuery('#cx_log_list').find('#cx_log_start_date').val(start_date);
jQuery('#cx_log_list').find('#cx_log_start_time').val(start_time);
jQuery('#cx_log_list').find('#cx_log_end_date').val(end_date);
jQuery('#cx_log_list').find('#cx_log_end_time').val(end_time);
}
else
{
alert(jsonarray.error);
}
}
catch(err)
{
alert(err);
}
}, function(XMLHttpRequest, textStatus, errorThrown)
{
var error_message =compressx_output_ajaxerror('get logs list', textStatus, errorThrown);
alert(error_message);
});
}
jQuery('#cx_close_log').click(function()
{
jQuery('#cx_log_detail_section').hide();
});
jQuery('#cx_log_list').on("click",'.cs-log-detail',function()
{
var file_name = jQuery(this).closest('td').data('id');
compressx_open_log(file_name);
});
function compressx_open_log(file_name)
{
var ajax_data = {
'action':'compressx_open_log',
'filename':file_name
};
jQuery('#cx_log_name').html(file_name);
jQuery('#cx_read_optimize_log_content').html("");
jQuery('#cx_log_detail_section').show();
compressx_post_request(ajax_data, function(data)
{
try
{
var jsonarray = jQuery.parseJSON(data);
if (jsonarray.result === "success")
{
currentLogFilename = file_name;
jQuery('#cx_read_optimize_log_content').val(jsonarray.data);
jQuery('#cx_log_created_date').text(jsonarray.create || '--');
jQuery('#cx_log_detail_section').show();
jQuery('html, body').animate({
scrollTop: jQuery('#cx_log_detail_section').offset().top - 100
}, 500);
//jQuery('#cx_read_optimize_log_content').html(jsonarray.html);
//jQuery('html, body').animate({scrollTop: jQuery("#cx_log_scroll_test").offset().top}, 'slow');
}
else
{
jQuery('#cx_read_optimize_log_content').html(jsonarray.error);
}
}
catch(err)
{
alert(err);
var div = "Reading the log failed. Please try again.";
jQuery('#cx_read_optimize_log_content').html(div);
}
}, function(XMLHttpRequest, textStatus, errorThrown)
{
var error_message =compressx_output_ajaxerror('open log', textStatus, errorThrown);
alert(error_message);
});
}
jQuery('#cx_close_log').on('click', function() {
jQuery('#cx_log_detail_section').hide();
currentLogFilename = '';
});
jQuery('#cx_download_current_log').on('click', function() {
if (!currentLogFilename) {
alert('No log file is currently open');
return;
}
compressx_download_log(currentLogFilename)
});
function compressx_download_log(file_name)
{
location.href =ajaxurl+'?_wpnonce='+compressx_ajax_object.ajax_nonce+'&action=compressx_download_log&log='+file_name;
}
jQuery('#cx_log_list').on("click",'.cs-log-download',function()
{
var file_name = jQuery(this).closest('td').data('id');
compressx_download_log(file_name);
});
jQuery('#cx_log_list').on("click",'.cs-log-delete',function()
{
var file_name = jQuery(this).closest('td').data('id');
var descript = 'Are you sure to delete this log file?';
var ret = confirm(descript);
if(ret === true)
{
compressx_delete_log(file_name);
}
});
function compressx_delete_log(file_name)
{
var ajax_data = {
'action':'compressx_delete_log',
'filename':file_name
};
compressx_post_request(ajax_data, function(data)
{
try
{
var jsonarray = jQuery.parseJSON(data);
if (jsonarray.result === "success")
{
var start_date = jQuery('#cx_log_list').find('#cx_log_start_date').val();
var start_time = jQuery('#cx_log_list').find('#cx_log_start_time').val();
var end_date = jQuery('#cx_log_list').find('#cx_log_end_date').val();
var end_time = jQuery('#cx_log_list').find('#cx_log_end_time').val();
compressx_get_logs_list(start_date,start_time,end_date,end_time);
}
else
{
alert(jsonarray.error);
}
}
catch(err)
{
alert(err);
}
}, function(XMLHttpRequest, textStatus, errorThrown)
{
var error_message =compressx_output_ajaxerror('delete log', textStatus, errorThrown);
alert(error_message);
});
}
jQuery('#cx_empty_log').click(function()
{
var descript = 'Are you sure to delete All log file?';
var ret = confirm(descript);
if(ret === true)
{
compressx_delete_all_log();
}
});
function compressx_delete_all_log()
{
var ajax_data = {
'action':'compressx_delete_all_log',
};
compressx_post_request(ajax_data, function(data)
{
try
{
var jsonarray = jQuery.parseJSON(data);
if (jsonarray.result === "success")
{
var start_date = jQuery('#cx_log_list').find('#cx_log_start_date').val();
var start_time = jQuery('#cx_log_list').find('#cx_log_start_time').val();
var end_date = jQuery('#cx_log_list').find('#cx_log_end_date').val();
var end_time = jQuery('#cx_log_list').find('#cx_log_end_time').val();
compressx_get_logs_list(start_date,start_time,end_date,end_time);
}
else
{
alert(jsonarray.error);
}
}
catch(err)
{
alert(err);
}
}, function(XMLHttpRequest, textStatus, errorThrown)
{
var error_message =compressx_output_ajaxerror('delete log', textStatus, errorThrown);
alert(error_message);
});
}
jQuery(document).ready(function($) {
$('#compressx_show_debug_form').on('click', function() {
$('#compressx_debug_form_section').show();
$('html, body').animate({
scrollTop: $('#compressx_debug_form_section').offset().top - 100
}, 500);
});
$('#compressx_debug_submit').on('click', function() {
var user_mail = $('#compressx_user_mail').val().trim();
var comment = $('#compressx_debug_comment').val().trim();
if (!user_mail) {
alert("Please enter your email address.");
$('#compressx_user_mail').focus();
return;
}
var $button = $(this);
var originalText = $button.text();
$button.text("Sending...").prop('disabled', true);
var ajax_data = {
action: 'compressx_send_debug_info',
user_mail: user_mail,
comment: comment,
};
compressx_post_request(ajax_data, function(data) {
try {
var response = jQuery.parseJSON(data);
if (response && response.result === 'success') {
alert("Debug information sent successfully!");
$('#compressx_debug_form_section').hide();
$('#compressx_user_mail').val('');
$('#compressx_debug_comment').val('');
} else {
alert(response.error || "Failed to send debug information.");
}
} catch(err) {
alert("Failed to send debug information.");
}
$button.text(originalText).prop('disabled', false);
}, function(XMLHttpRequest, textStatus, errorThrown) {
alert("Failed to send debug information.");
$button.text(originalText).prop('disabled', false);
});
});
$('#compressx_download_debug_info').on('click', function()
{
cx_download_website_info();
});
function cx_download_website_info()
{
location.href =ajaxurl+'?_wpnonce='+compressx_ajax_object.ajax_nonce+'&action=compressx_create_debug_package';
}
});
@@ -0,0 +1,444 @@
jQuery('#cx_replace_media').click(function(e)
{
e.preventDefault();
var input = document.getElementById('compressx-new-media-file');
var file = input && input.files && input.files[0];
if (!file)
{
alert('Please select an image that you want to replace.');
return;
}
var $saveButton = jQuery(this);
$saveButton.css({ 'pointer-events': 'none', 'opacity': '0.4' });
jQuery('#cx_replace_media_progress').show();
let attachment_id=jQuery('#compressx_attachment_id').val();
var ajax_data = {
'action': 'compressx_replace_media',
'attachment_id': attachment_id,
};
compressx_file_upload_request(
ajax_data,
'compressx-new-media-file', //file input id
'image', //$_FILES['image']
function(data)
{
try
{
var jsonarray = JSON.parse(data);
if (jsonarray.result === 'success')
{
//$saveButton.css({ 'pointer-events': 'auto', 'opacity': '1' });
jQuery('#cx_replace_media_progress').hide();
jQuery('#cx_replace_media_text').removeClass('compressx-v2-hidden');
setTimeout(function() {
jQuery('#cx_replace_media_text').addClass('compressx-v2-hidden');
location.href=compressx_media_replace.redirect_url;
}, 3000);
}
else
{
$saveButton.css({ 'pointer-events': 'auto', 'opacity': '1' });
jQuery('#cx_replace_media_progress').hide();
alert(jsonarray.error || 'Failed to save settings.');
}
}
catch (err)
{
$saveButton.css({ 'pointer-events': 'auto', 'opacity': '1' });
jQuery('#cx_replace_media_progress').hide();
alert(err);
}
},
function(XMLHttpRequest, textStatus, errorThrown)
{
$saveButton.css({ 'pointer-events': 'auto', 'opacity': '1' });
jQuery('#cx_replace_media_progress').hide();
var error_message = compressx_output_ajaxerror('saving settings', textStatus, errorThrown);
alert(error_message);
},
30000
);
});
function compressx_file_upload_request(ajax_data, file_input_id, file_field_name, callback, error_callback, time_out)
{
if (typeof time_out === 'undefined') time_out = 30000;
if (typeof file_field_name === 'undefined' || !file_field_name) file_field_name = 'image';
var form_data = (ajax_data instanceof FormData) ? ajax_data : new FormData();
if (!(ajax_data instanceof FormData)) {
for (var key in ajax_data) {
if (!ajax_data.hasOwnProperty(key)) continue;
form_data.append(key, ajax_data[key]);
}
}
form_data.append('nonce', compressx_ajax_object.ajax_nonce);
var input = document.getElementById(file_input_id);
var file = input && input.files && input.files[0];
if (!file) {
if (typeof error_callback === 'function') {
error_callback(null, 'no_file', 'No file selected.');
}
return;
}
form_data.append(file_field_name, file);
jQuery.ajax({
type: "post",
url: compressx_ajax_object.ajax_url,
data: form_data,
processData: false,
contentType: false,
success: function (data) {
callback(data);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
error_callback(XMLHttpRequest, textStatus, errorThrown);
},
timeout: time_out
});
}
jQuery(function ($)
{
// ===== Helpers =====
function cx_getSettingsPayload()
{
const auto_re_optimize = $('#cx_auto_re_optimize').is(':checked') ? 1 : 0;
const thumbnail_generation = $('input[name="thumbnail_strategy"]:checked').val() || 'default_fill';
return {
auto_re_optimize,
thumbnail_generation,
};
}
let ajaxTimer = null;
function compressx_save_media_replace_setting(triggerEl,triggerNotice)
{
window.clearTimeout(ajaxTimer);
ajaxTimer = window.setTimeout(function ()
{
const payload = cx_getSettingsPayload();
var ajax_data = {
'action': 'compressx_save_media_replace_setting',
'settings': payload,
};
jQuery(triggerEl).css({'pointer-events': 'none', 'opacity': '0.4'});
compressx_post_request(ajax_data, function (data)
{
try
{
var jsonarray = jQuery.parseJSON(data);
jQuery(triggerEl).css({'pointer-events': 'auto', 'opacity': '1'});
if (jsonarray.result === 'success')
{
jQuery(triggerNotice).removeClass("hidden");
setTimeout(function ()
{
jQuery(triggerNotice).addClass( 'hidden' );
}, 3000);
}
}
catch (err)
{
alert(err);
jQuery(triggerEl).css({'pointer-events': 'auto', 'opacity': '1'});
}
}, function (XMLHttpRequest, textStatus, errorThrown)
{
jQuery('triggerEl').css({'pointer-events': 'auto', 'opacity': '1'});
var error_message = compressx_output_ajaxerror('changing settings', textStatus, errorThrown);
alert(error_message);
});
}, 200);
}
// ===== Bindings =====
// checkbox change
$(document).on('change', '#cx_auto_re_optimize', function ()
{
var notice= jQuery("#auto_re_optimize-saved-indicator");
compressx_save_media_replace_setting(this,notice);
});
$(document).on('change', '#cx_backup_original', function ()
{
var notice= jQuery("#cx_backup_original-saved-indicator");
compressx_save_media_replace_setting(this,notice);
});
// radio change
$(document).on('change', 'input[name="thumbnail_strategy"]', function ()
{
var thumbnail_generation = $('input[name="thumbnail_strategy"]:checked').val() || 'default_fill';
var notice=null;
if(thumbnail_generation==='default_fill')
{
notice= jQuery("#default_fill-saved-indicator");
}
else
{
notice= jQuery("#match_original-saved-indicator");
}
compressx_save_media_replace_setting(this,notice);
});
//cx_backup_keep_versions
$(document).on('change', '#cx_backup_keep_versions', function ()
{
var notice= jQuery("#cx_backup_keep_versions-saved-indicator");
compressx_save_media_replace_setting(this,notice);
});
$(document).on('change', '#cx_backup_keep_date', function ()
{
var notice= jQuery("#cx_backup_keep_date-saved-indicator");
compressx_save_media_replace_setting(this,notice);
});
});
jQuery(function ($)
{
var og_type= compressx_media_replace.type;
var $dz = $("#compressx-new-media-dropzone");
var $inp = $("#compressx-new-media-file");
var $lay = $("#compressx-new-media-preview-layout");
var $pclk = $("#compressx-new-media-preview-click");
var $pre = $("#compressx-new-media-preview");
var $remove = $("#compressx-remove-new-media-preview");
var $dim = $("#compressx-new-media-dim");
var $size = $("#compressx-new-media-size");
var $fmt = $("#compressx-new-media-format");
var lastUrl = null;
function humanSize(bytes) {
if (bytes === undefined || bytes === null) return "—";
var units = ["B", "KB", "MB", "GB"], i = 0, n = bytes;
while (n >= 1024 && i < units.length - 1) { n /= 1024; i++; }
var fixed = i === 0 ? 0 : (n >= 10 ? 0 : 1);
return n.toFixed(fixed) + " " + units[i];
}
function getFormat(file) {
if (file.type) {
var p = file.type.split("/");
return (p[1] || "—").toUpperCase();
}
var m = (file.name || "").match(/\.([a-z0-9]+)$/i);
return m ? m[1].toUpperCase() : "—";
}
function showEmpty() {
$lay.hide();
$dz.show();
}
function showFilled() {
$dz.hide();
$lay.show();
}
function setFile(file) {
if (!file) return;
if (!file.type || file.type.indexOf("image/") !== 0) {
alert("Please choose an image file.");
return;
}
try
{
var dt = new DataTransfer();
dt.items.add(file);
$inp[0].files = dt.files;
} catch (e) {}
$size.text(humanSize(file.size));
$fmt.text(getFormat(file));
var url = URL.createObjectURL(file);
var img = new Image();
img.onload = function ()
{
$dim.text(img.naturalWidth + " × " + img.naturalHeight);
if (lastUrl) URL.revokeObjectURL(lastUrl);
lastUrl = url;
$pre.attr("src", url);
cx_showNotice(img.naturalWidth,img.naturalHeight,file.type);
};
img.onerror = function ()
{
URL.revokeObjectURL(url);
alert("Failed to read the image.");
$inp.val("");
$dim.text("—"); $size.text("—"); $fmt.text("—");
$pre.attr("src", "");
showEmpty();
};
img.src = url;
}
function openDialog() {
$inp[0].click();
}
function removeImage()
{
$inp.val("");
$pre.attr("src", "");
$dim.text("—");
$size.text("—");
$fmt.text("—");
if (lastUrl) {
URL.revokeObjectURL(lastUrl);
lastUrl = null;
}
$lay.hide();
$dz.show();
}
$dz.on("click", openDialog);
$pclk.on("click", openDialog);
$remove.on("click", removeImage);
$inp.on("change", function () {
var file = this.files && this.files[0];
if (file) setFile(file);
});
$dz.on("dragenter dragover", function (e) {
e.preventDefault(); e.stopPropagation();
$dz.addClass("compressx-drop-active");
});
$dz.on("dragleave drop", function (e) {
e.preventDefault(); e.stopPropagation();
$dz.removeClass("compressx-drop-active");
});
$dz.on("drop", function (e) {
var files = e.originalEvent && e.originalEvent.dataTransfer && e.originalEvent.dataTransfer.files;
var file = files && files[0];
if (file) setFile(file);
});
showEmpty();
function cx_showNotice(width,height,mimetype)
{
let og_w=$("#og_image_dimensions").data("width");
let og_h=$("#og_image_dimensions").data("height");
let og_mime=$("#og_image_dimensions").data("mime");
if(mimetype!==og_mime)
{
$("#cx-upload-notice").show();
$("#cx_notice_title").html("File format must match");
$("#cx_notice_content").html("The replacement file must use the same format as the current media ("+og_mime+" → "+mimetype+" detected). Please upload a "+og_type+" file to avoid unexpected issues.");
removeImage();
return;
}
showFilled();
/*
if(og_w>width)
{
$("#cx-upload-notice").show();
$("#cx_notice_title").html("Smaller Image Detected");
$("#cx_notice_content").html("The replacement image is smaller than the original. Some larger thumbnail sizes may not be generated, which can affect pages that reference those sizes.");
}
else if(og_w<width)
{
$("#cx-upload-notice").show();
$("#cx_notice_title").html("Larger Image Detected");
$("#cx_notice_content").html("The replacement image is significantly larger than the original. This may generate larger thumbnails and increase disk usage.");
}*/
}
$("#cx-hide-upload-notice").on("click", function ()
{
$("#cx-upload-notice").hide();
});
});
jQuery(document).ready(function ($)
{
$(document).on('click', '.cx-restore-btn', function ()
{
var $btn = $(this);
var backup_id = $btn.data('backup-id');
var attachment_id = $btn.data('attachment-id');
var ajax_data = {
'action': 'compressx_restore_media_replace',
'backup_id': backup_id,
'attachment_id':attachment_id
};
jQuery(".cx-restore-btn").css({'pointer-events': 'none', 'opacity': '0.4'});
var $wrap = $btn.closest('.cx-restore-item');
let $progress = $wrap.find('.cx-restore-progress');
let $success = $wrap.find('.cx-restore-text');
$progress.show();
compressx_post_request(ajax_data, function (data)
{
jQuery(".cx-restore-btn").css({'pointer-events': 'auto', 'opacity': '1'});
$progress.hide();
try
{
var jsonarray = jQuery.parseJSON(data);
if (jsonarray.result === 'success')
{
$success.removeClass("hidden");
setTimeout(function ()
{
location.href=compressx_media_replace.redirect_url;
$success.addClass('hidden');
}, 3000);
}
}
catch (err)
{
alert(err);
}
}, function (XMLHttpRequest, textStatus, errorThrown)
{
jQuery(".cx-restore-btn").css({'pointer-events': 'auto', 'opacity': '1'});
var error_message = compressx_output_ajaxerror('replace media', textStatus, errorThrown);
alert(error_message);
});
});
});
@@ -0,0 +1,326 @@
function compressx_init_exclude_tree()
{
jQuery('#compressx_exclude_js_tree').on('activate_node.jstree', function (event, data) {
}).jstree({
"core": {
"check_callback": true,
"multiple": true,
"data": function (node_id, callback) {
var tree_node = {
'node': node_id,
'path': compressx_uploads_root.path
};
var ajax_data = {
'action': 'compressx_get_custom_tree_dir',
'tree_node': tree_node,
};
ajax_data.nonce=compressx_ajax_object.ajax_nonce;
jQuery.ajax({
type: "post",
url: compressx_ajax_object.ajax_url,
data: ajax_data,
success: function (data) {
var jsonarray = jQuery.parseJSON(data);
callback.call(this, jsonarray.nodes);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
//alert("error");
},
timeout: 30000
});
},
'themes': {
'stripes': true
}
},
"plugins": ["sort"],
"sort": function(a, b) {
a1 = this.get_node(a);
b1 = this.get_node(b);
if (a1.icon === b1.icon) {
return (a1.text.toLowerCase() > b1.text.toLowerCase()) ? 1 : -1;
} else {
return (a1.icon > b1.icon) ? 1 : -1;
}
},
});
}
jQuery(document).ready(function ()
{
compressx_init_exclude_tree();
jQuery('#cx-v2-show-more-size').click(function() {
jQuery('.cx-v2-thumbnail-size').show();
jQuery(this).hide();
});
jQuery('#cx-v2-save-settings').click(function(e)
{
e.preventDefault();
var $saveButton = jQuery(this);
var originalText = $saveButton.text();
$saveButton.css({ 'pointer-events': 'none', 'opacity': '0.4' });
jQuery('#cx-v2-save-settings-progress').show();
var settings = {
size_settings: {},
list_view_setting: {},
cache_control_setting: {},
scan_page_setting:{},
};
jQuery('input[option="size_setting"]').each(function() {
var name = jQuery(this).attr('name');
var checked = jQuery(this).is(':checked');
settings.size_settings[name] = checked;
});
jQuery('input[option="list_view_setting"]').each(function() {
var name = jQuery(this).attr('name');
var checked = jQuery(this).is(':checked');
settings.list_view_setting[name] = checked ? '1' : '0';
});
jQuery('input[option="cache_control_setting"]').each(function() {
var name = jQuery(this).attr('name');
var checked = jQuery(this).is(':checked');
settings.cache_control_setting[name] = checked ? '1' : '0';
});
jQuery('input[option="scan_page_setting"]').each(function() {
var name = jQuery(this).attr('name');
var value = parseInt(jQuery(this).val(), 10);
if (isNaN(value) || value <= 0) {
value = 500;
}
settings.scan_page_setting[name] = value;
});
var select_folders = jQuery('#compressx_exclude_dir_node').find('.cx-remove-custom-exclude-tree');
var json = {};
jQuery.each(select_folders, function ()
{
var value=jQuery(this).data("id");
//var value = select_item.data( 'id' );
json[value]=value;
});
var exclude_node=JSON.stringify(json);
//
var ajax_data = {
'action': 'compressx_v2_save_settings',
'settings': JSON.stringify(settings),
'excludes':exclude_node,
};
compressx_post_request(ajax_data, function(data)
{
try
{
var jsonarray = JSON.parse(data);
if (jsonarray.result === 'success')
{
$saveButton.css({ 'pointer-events': 'auto', 'opacity': '1' });
jQuery('#cx-v2-save-settings-progress').hide();
jQuery('#cx-v2-save-settings-text').removeClass('hidden');
setTimeout(function() {
jQuery('#cx-v2-save-settings-text').addClass('hidden');
}, 3000);
}
else
{
$saveButton.css({ 'pointer-events': 'auto', 'opacity': '1' });
jQuery('#cx-v2-save-settings-progress').hide();
alert(jsonarray.error || 'Failed to save settings.');
}
}
catch (err)
{
$saveButton.css({ 'pointer-events': 'auto', 'opacity': '1' });
jQuery('#cx-v2-save-settings-progress').hide();
alert('An error occurred while saving settings.');
}
}, function(XMLHttpRequest, textStatus, errorThrown) {
$saveButton.css({ 'pointer-events': 'auto', 'opacity': '1' });
jQuery('#cx-v2-save-settings-progress').hide();
var error_message = compressx_output_ajaxerror('saving settings', textStatus, errorThrown);
alert(error_message);
});
});
});
jQuery('#compressx_exclude_js_tree').on('click', '.cx-add-custom-exclude-tree', function()
{
var id=jQuery(this).data("id");
var node=jQuery(this).parent();
var select_folders = jQuery('#compressx_exclude_dir_node').find('.cx-remove-custom-exclude-tree');
var json = {};
var bfind=false;
jQuery.each(select_folders, function ()
{
var value=jQuery(this).data("id");
if(value==id)
{
bfind=true;
}
});
if(bfind)
return;
var ajax_data = {
'action': 'compressx_add_exclude_folder',
'id': id,
};
compressx_post_request(ajax_data, function (data)
{
try
{
var jsonarray = jQuery.parseJSON(data);
if (jsonarray.result === 'success')
{
jQuery('#compressx_exclude_dir_node').find('ul:first').append(jsonarray.html);
}
else {
alert(jsonarray.error);
}
}
catch (err)
{
alert(err);
jQuery('#compressx_add_exclude_folders').css({'pointer-events': 'auto', 'opacity': '1'});
}
}, function (XMLHttpRequest, textStatus, errorThrown)
{
jQuery('#compressx_add_exclude_folders').css({'pointer-events': 'auto', 'opacity': '1'});
var error_message = compressx_output_ajaxerror('changing settings', textStatus, errorThrown);
alert(error_message);
});
});
jQuery('#compressx_exclude_dir_node').on('click', '.cx-remove-custom-exclude-tree', function()
{
var id=jQuery(this).data("id");
var node=jQuery(this).parent();
node.remove();
});
function compressx_add_exclude_folders()
{
var select_folders = jQuery('#compressx_exclude_dir_node').find('.cx-remove-custom-exclude-tree');
var json = {};
jQuery.each(select_folders, function ()
{
var value=jQuery(this).data("id");
//var value = select_item.data( 'id' );
json[value]=value;
});
var exclude_node=JSON.stringify(json);
var ajax_data = {
'action': 'compressx_add_exclude_folders',
'excludes': exclude_node,
};
jQuery('#compressx_add_exclude_folders').css({'pointer-events': 'none', 'opacity': '0.4'});
jQuery('#compressx_save_exclude_progress').show();
compressx_post_request(ajax_data, function (data)
{
try
{
var jsonarray = jQuery.parseJSON(data);
jQuery('#compressx_save_exclude_progress').hide();
jQuery('#compressx_add_exclude_folders').css({'pointer-events': 'auto', 'opacity': '1'});
if (jsonarray.result === 'success')
{
jQuery('#compressx_save_exclude_text').removeClass("hidden");
setTimeout(function ()
{
jQuery('#compressx_save_exclude_text').addClass( 'hidden' );
}, 3000);
jQuery('#compressx_exclude_dir_node').html(jsonarray.html);
}
else {
alert(jsonarray.error);
}
}
catch (err)
{
alert(err);
jQuery('#compressx_add_exclude_folders').css({'pointer-events': 'auto', 'opacity': '1'});
jQuery('#compressx_save_exclude_progress').hide();
}
}, function (XMLHttpRequest, textStatus, errorThrown)
{
jQuery('#compressx_add_exclude_folders').css({'pointer-events': 'auto', 'opacity': '1'});
jQuery('#compressx_add_exclude_folders').hide();
var error_message = compressx_output_ajaxerror('changing settings', textStatus, errorThrown);
alert(error_message);
});
}
jQuery('#cx-v2-delete-file').click(function() {
var confirm_text = jQuery('#cx-v2-confirm-delete-file').val();
if (confirm_text !== 'DELETE') {
alert('Please type "DELETE" to confirm.');
return;
}
if (!confirm('Are you sure you want to delete all WebP and AVIF images? This action cannot be undone.')) {
return;
}
var $deleteButton = jQuery(this);
$deleteButton.css({ 'pointer-events': 'none', 'opacity': '0.4' });
jQuery('#cx-v2-delete-file-progress').show();
var ajax_data = {
'action': 'compressx_delete_files'
};
compressx_post_request(ajax_data, function(data)
{
try
{
var jsonarray = JSON.parse(data);
if (jsonarray.result === 'success')
{
$deleteButton.css({ 'pointer-events': 'auto', 'opacity': '1' });
jQuery('#cx-v2-delete-file-progress').hide();
jQuery('#cx-v2-delete-file-success').removeClass('hidden');
jQuery('#cx-v2-confirm-delete-file').val('');
setTimeout(function() {
jQuery('#cx-v2-delete-file-success').addClass('hidden');
}, 3000);
} else {
$deleteButton.css({ 'pointer-events': 'auto', 'opacity': '1' });
jQuery('#cx-v2-delete-file-progress').hide();
alert(jsonarray.error || 'Failed to delete files.');
}
} catch (err) {
$deleteButton.css({ 'pointer-events': 'auto', 'opacity': '1' });
jQuery('#cx-v2-delete-file-progress').hide();
alert('An error occurred while deleting files.');
}
}, function(XMLHttpRequest, textStatus, errorThrown) {
$deleteButton.css({ 'pointer-events': 'auto', 'opacity': '1' });
jQuery('#cx-v2-delete-file-progress').hide();
var error_message = compressx_output_ajaxerror('deleting files', textStatus, errorThrown);
alert(error_message);
});
});