Commit inicial powerservice

This commit is contained in:
Gabriel
2026-10-19 12:45:45 -06:00
commit ad85486fe2
10158 changed files with 2736804 additions and 0 deletions
@@ -0,0 +1,78 @@
<?php
/**
* @link https://compressx.io
* @since 0.9.1
*
* @wordpress-plugin
* Plugin Name: CompressX - AVIF & WebP Converter
* Description: Convert JPG and PNG images to WebP and AVIF, compress WebP and AVIF.
* Version: 0.9.40
* Author: WPvivid Team
* Author URI: https://compressx.io
* License: GPL-3.0+
* License URI: http://www.gnu.org/copyleft/gpl.html
* Text Domain: compressx
* Domain Path: /languages
**/
// If this file is called directly, abort.
if ( ! defined( 'WPINC' ) )
{
die;
}
define( 'COMPRESSX_VERSION', '0.9.40' );
define( 'COMPRESSX_SLUG', 'CompressX' );
define( 'COMPRESSX_NAME', plugin_basename( __FILE__ ) );
define( 'COMPRESSX_URL', plugins_url( '', __FILE__ ) );
define( 'COMPRESSX_DIR', dirname( __FILE__ ) );
if ( isset( $compressx ) && is_a( $compressx, 'CompressX' ) )
{
return;
}
function compressx_actvation_action()
{
include_once COMPRESSX_DIR . '/includes/class-compressx-default-folder.php';
$dir=new CompressX_default_folder();
$dir->create_uploads_dir();
$options=get_option('compressx_general_settings',array());
$image_load=isset($options['image_load'])?$options['image_load']:'htaccess';
if ($image_load == "htaccess")
{
include_once COMPRESSX_DIR . '/includes/class-compressx-webp-rewrite.php';
$rewrite=new CompressX_Webp_Rewrite();
$rewrite->create_rewrite_rules();
}
else if($image_load == "compat_htaccess")
{
include_once COMPRESSX_DIR . '/includes/class-compressx-webp-rewrite.php';
$rewrite=new CompressX_Webp_Rewrite();
$rewrite->create_rewrite_rules_ex();
}
}
function compressx_deactivation_action()
{
include_once COMPRESSX_DIR . '/includes/class-compressx-webp-rewrite.php';
$rewrite=new CompressX_Webp_Rewrite();
$rewrite->remove_rewrite_rule();
}
register_activation_hook(__FILE__, 'compressx_actvation_action');
register_deactivation_hook(__FILE__, 'compressx_deactivation_action');
require plugin_dir_path( __FILE__ ) . 'includes/class-compressx.php';
function compressx_run()
{
$compressx = new CompressX();
$GLOBALS['compressx'] = $compressx;
}
compressx_run();
Binary file not shown.

After

Width:  |  Height:  |  Size: 9.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.4 KiB

@@ -0,0 +1,188 @@
<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
class CompressX_Auto_Optimization
{
public $auto_opt_ids;
public $log=false;
public function __construct()
{
$this->auto_opt_ids=array();
add_action( 'add_attachment', array( $this, 'add_auto_opt_id' ), 1000 );
add_filter( 'wp_generate_attachment_metadata', array( $this, 'update_auto_opt_id_status' ), 1000, 2 );
add_filter( 'wp_update_attachment_metadata', array( $this, 'auto_optimize' ), 1000, 2 );
add_filter( 'compressx_allowed_image_auto_optimization', array( $this, 'allowed_image_auto_optimization' ), 10 );
}
public function allowed_image_auto_optimization()
{
$is_auto=CompressX_Options::get_option('compressx_auto_optimize',false);
if($is_auto)
{
return true;
}
else
{
return false;
}
}
public function add_auto_opt_id($attachment_id)
{
$is_auto=apply_filters('compressx_allowed_image_auto_optimization',false);
if($is_auto)
{
$this->auto_opt_ids[$attachment_id]=0;
}
}
public function update_auto_opt_id_status($metadata, $attachment_id)
{
if(isset( $this->auto_opt_ids[$attachment_id]))
{
if ( ! wp_attachment_is_image( $attachment_id ) )
{
unset($this->auto_opt_ids[$attachment_id]);
}
else
{
$this->WriteLog('Add attachment images id:'.$attachment_id,'notice');
$this->auto_opt_ids[$attachment_id]=1;
}
}
return $metadata;
}
public function auto_optimize($metadata, $attachment_id)
{
$is_auto=apply_filters('compressx_allowed_image_auto_optimization',false);
if($is_auto)
{
if(isset($this->auto_opt_ids[$attachment_id])&&$this->auto_opt_ids[$attachment_id])
{
$supported_mime_types = array(
"image/jpg",
"image/jpeg",
"image/png",
"image/webp",
"image/avif");
$mime_type=get_post_mime_type($attachment_id);
if(in_array($mime_type,$supported_mime_types))
{
if($this->is_excludes($attachment_id))
{
$this->WriteLog('Exclude attachment images id:'.$attachment_id,'notice');
return $metadata;
}
set_time_limit(300);
delete_transient('compressx_set_global_stats');
$ret=$this->do_optimize_image($attachment_id,$metadata);
if(isset($ret['meta']))
{
return $ret['meta'];
}
}
}
}
return $metadata;
}
public function is_excludes($attachment_id)
{
$exclude_regex_folder=CompressX_Options::get_excludes();
if(CompressX_Image_Opt_Method::exclude_path($attachment_id,$exclude_regex_folder))
{
return true;
}
else
{
return false;
}
}
public function WriteLog($log,$type)
{
if (is_a($this->log, 'CompressX_Log'))
{
$this->log->WriteLog($log,$type);
}
else
{
$this->log=new CompressX_Log();
$this->log->OpenLogFile();
$this->log->WriteLog($log,$type);
}
}
public function do_optimize_image($attachment_id,$metadata)
{
$general_options=CompressX_Options::get_general_settings();
$quality_options=CompressX_Options::get_quality_option();
$options=array_merge($general_options,$quality_options);
$this->log=new CompressX_Log();
$this->log->CreateLogFile();
$this->WriteLog('Start optimizing new media images id:'.$attachment_id,'notice');
$file_path = get_attached_file( $attachment_id );
if(empty($file_path))
{
CompressX_Image_Opt_Method::WriteLog($this->log,'Image:'.$attachment_id.' failed. Error: failed to get get_attached_file','notice');
$error='Image:'.$attachment_id.' failed. Error: failed to get get_attached_file';
CompressX_Image_Meta_V2::update_image_failed($attachment_id,$error);
$ret['result']='success';
$ret['meta']=$metadata;
return $ret;
}
if(!file_exists($file_path))
{
CompressX_Image_Opt_Method::WriteLog($this->log,'Image:'.$attachment_id.' failed. Error: file not exists '.$file_path,'notice');
$error='Image:'.$attachment_id.' failed. Error: file not exists '.$file_path;
CompressX_Image_Meta_V2::update_image_failed($attachment_id,$error);
$ret['result']='success';
$ret['meta']=$metadata;
return $ret;
}
CompressX_Image_Meta_V2::update_image_progressing($attachment_id);
$image=new Compressx_Image($attachment_id,$options);
$ret=$image->resize_ex($metadata);
if($ret['result']=='success')
{
$metadata=$ret['meta'];
}
if($image->convert())
{
CompressX_Image_Meta_V2::update_image_meta_status($attachment_id,'optimized');
do_action('compressx_uploading_add_watermark',$attachment_id);
do_action('compressx_after_optimize_image',$attachment_id);
}
else
{
CompressX_Image_Meta_V2::update_image_meta_status($attachment_id,'failed');
}
CompressX_Image_Meta_V2::delete_image_progressing($attachment_id);
$ret['result']='success';
$ret['meta']=$metadata;
return $ret;
}
}
@@ -0,0 +1,86 @@
<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
class CompressX_CloudFlare_CDN
{
private $options;
public function __construct($options)
{
$this->options=$options;
}
public function purge_cache()
{
if(empty($this->options['zone_id']))
{
$ret['result']='failed';
$ret['error']=__('Zone ID is required, please enter a valid Zone ID','compressx');
return $ret;
}
if(empty($this->options['email']))
{
$ret['result']='failed';
$ret['error']=__('Cloudflare email is required, please enter your Cloudflare email.','compressx');
return $ret;
}
if(empty($this->options['api_key']))
{
$ret['result']='failed';
$ret['error']=__('Global API key is required, please enter your Cloudflare global API key.','compressx');
return $ret;
}
$zone_id=$this->options['zone_id'];
$email = $this->options['email'];
$api_key = $this->options['api_key'];
$headers = array(
'Content-Type' => 'application/json'
);
$headers["X-Auth-Email"] = $email;
$headers["X-Auth-Key"] = $api_key;
$args['method'] = 'POST';
$args['body'] = wp_json_encode( array( 'purge_everything' => true ) );
$args['headers'] = $headers;
$response = wp_remote_post(
esc_url_raw( "https://api.cloudflare.com/client/v4/zones/{$zone_id}/purge_cache" ),
$args
);
if ( is_wp_error( $response ) )
{
$ret['result']='failed';
$ret['error']=__('Connecting to Cloudflare failed:','compressx').$response->get_error_message();
return $ret;
}
$response_body = wp_remote_retrieve_body($response);
$json = json_decode( $response_body, true);
if( $json['success'] == false )
{
$error = array();
foreach($json['errors'] as $single_error)
{
$error[] = "{$single_error['message']} (err code: {$single_error['code']})";
}
$error = implode(' - ', $error);
$ret['result']='failed';
$ret['error']=__('Connecting to Cloudflare failed:','compressx').$error;
return $ret;
}
$ret['result']='success';
return $ret;
}
}
@@ -0,0 +1,458 @@
<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
class CompressX_Custom_ImgOptim_Task
{
public $task;
public $log=false;
public function __construct()
{
$this->get_task();
CompressX_Custom_Image_Meta::check_custom_table();
}
public function update_task()
{
CompressX_Options::update_option('compressx_custom_image_opt_task',$this->task);
$this->get_task();
}
public function get_task()
{
$this->task=CompressX_Options::get_option('compressx_custom_image_opt_task',array());
}
public function init_task($force=false)
{
$this->task=array();
$this->task['log']=uniqid('cx-');
$this->log=new CompressX_Log();
$this->log->CreateLogFile();
$this->init_options();
$this->task['options']['force']=$force;
$this->task['images']=$this->get_need_optimize_images();
if(empty($this->task['images']))
{
$ret['result']='failed';
$ret['error']=__('No unoptimized images found.','compressx');
$this->update_task();
return $ret;
}
$this->task['status']='init';
$this->task['last_update_time']=time();
$this->task['retry']=0;
$this->task['opt_images']=0;
$this->task['failed_images']=0;
$this->task['error']='';
$this->update_task();
$ret['result']='success';
$ret["test"]=$this->task;
return $ret;
}
public function WriteLog($log,$type)
{
if (is_a($this->log, 'CompressX_Log'))
{
$this->log->WriteLog($log,$type);
}
else
{
$this->log=new CompressX_Log();
$this->log->OpenLogFile();
$this->log->WriteLog($log,$type);
}
}
public function init_options()
{
$general_options=CompressX_Options::get_general_settings();
$quality_options=CompressX_Options::get_quality_option();
$this->task['options']=array_merge($general_options,$quality_options);
}
public function get_need_optimize_images()
{
$images=CompressX_Options::get_option("compressx_need_optimized_custom_images",array());
$need_optimize_images=array();
$index=0;
foreach ($images as $path)
{
$image['id']=$index;
$image['finished']=1;
$image['path']=$path;
$image['force']=0;
$status=CompressX_Custom_Image_Meta::get_image_status($path);
if($this->task['options']['convert_to_webp'])
{
$image['convert_webp_status']=$status['convert_webp_status'];
$image['finished']=0;
}
if($this->task['options']['convert_to_avif'])
{
$image['convert_avif_status']=$status['convert_avif_status'];
$image['finished']=0;
}
if($image['finished']==0)
{
$need_optimize_images[$index]=$image;
$index++;
}
}
return $need_optimize_images;
}
public function get_task_status()
{
if(empty($this->task))
{
$ret['result']='failed';
$ret['error']=__('All image(s) optimized successfully.','compressx');
return $ret;
}
if($this->task['status']=='error')
{
$ret['result']='failed';
$ret['error']=$this->task['error'];
}
else if($this->task['status']=='completed')
{
$ret['result']='success';
$ret['status']='completed';
}
else if($this->task['status']=='finished')
{
$ret['result']='success';
$ret['status']='finished';
}
else if($this->task['status']=='timeout')
{
$ret['result']='success';
$ret['status']='completed';
}
else if($this->task['status']=='init')
{
$ret['result']='success';
$ret['status']='completed';
}
else
{
$ret['result']='success';
$ret['status']='running';
}
return $ret;
}
public function do_optimize_image()
{
$this->task['status']='running';
$this->task['last_update_time']=time();
$this->update_task();
if(empty($this->task)||!isset($this->task['images']))
{
$ret['result']='success';
return $ret;
}
$image_id=false;
$need_reset=false;
foreach ($this->task['images'] as $image)
{
if($image['finished']==0)
{
$image_id=$image['id'];
if($this->task['options']['force']&&$image['force']==0)
{
$need_reset=true;
}
break;
}
}
if($image_id===false)
{
$ret['result']='success';
$this->task['status']='finished';
$this->task['last_update_time']=time();
$this->update_task();
return $ret;
}
if($need_reset)
{
$ret=$this->reset_optimize_image($image_id);
if($ret['result']=='success')
{
$this->task['images'][$image_id]['force']=1;
$this->update_task();
}
}
$this->WriteLog('Start optimizing custom images id:'.$image_id,'notice');
$ret=$this->optimize_image($image_id);
if($ret['result']=='success')
{
$this->WriteLog('Optimizing custom image id:'.$image_id.' succeeded.','notice');
$this->task['images'][$image_id]['finished']=1;
$this->task['status']='completed';
$this->task['last_update_time']=time();
$this->task['retry']=0;
$this->update_task();
$ret['result']='success';
$ret['test']=$this->task;
return $ret;
}
else
{
$this->WriteLog('Optimizing images failed. Error:'.$ret['error'],'error');
$this->task['status']='error';
$this->task['error']=$ret['error'];
$this->task['last_update_time']=time();
$this->update_task();
return $ret;
}
}
public function reset_optimize_image($image_id)
{
$filename=$this->get_image_path($image_id);
CompressX_Custom_Image_Meta::generate_custom_image_meta($filename,$this->task['options']);
$ret['result']='success';
return $ret;
}
public function optimize_image($image_id)
{
if (is_a($this->log, 'CompressX_Log'))
{
//
}
else
{
$this->log=new CompressX_Log();
$this->log->OpenLogFile();
}
$has_error=false;
$filename=$this->get_image_path($image_id);
$this->get_custom_image_meta($filename);
if(CompressX_Image_Opt_Method::custom_convert_to_webp($filename,$this->task['options'],$this->log)===false)
{
$has_error=true;
}
if(CompressX_Image_Opt_Method::custom_convert_to_avif($filename,$this->task['options'],$this->log)===false)
{
$has_error=true;
}
if($has_error)
{
$this->task['failed_images']++;
$this->update_task(); }
else
{
$this->task['opt_images']++;
$this->update_task();
}
$ret['result']='success';
return $ret;
}
public function get_image_path($image_id)
{
$image=$this->task['images'][$image_id];
return CompressX_Image_Method::transfer_path($image['path']);
}
public function get_custom_image_meta($filename)
{
$filename=CompressX_Image_Method::transfer_path($filename);
$meta=CompressX_Custom_Image_Meta::get_custom_image_meta($filename);
if(empty($meta))
{
$meta=CompressX_Custom_Image_Meta::generate_custom_image_meta($filename,$this->task['options']);
}
return $meta;
}
public function get_task_progress()
{
$this->get_task();
if(empty($this->task))
{
$ret['result']='failed';
$ret['error']=__('All image(s) optimized successfully.','compressx');
$ret['percent']=0;
$ret['timeout']=0;
$ret['log']=__('All image(s) optimized successfully.','compressx');
return $ret;
}
if(isset($this->task['images']))
{
$ret['total_images']=sizeof($this->task['images']);
}
else
{
$ret['total_images']=0;
}
$ret['optimized_images']=0;
if(isset($this->task['images']))
{
foreach ($this->task['images'] as $image)
{
if($image['finished'])
{
$ret['optimized_images']++;
}
}
}
$percent= intval(($ret['optimized_images']/$ret['total_images'])*100);
$ret['log']=sprintf(
'%1$d images found | Processed:%2$d/%3$d (%4$d%%)',
$ret['total_images'],$ret['optimized_images'],$ret['total_images'],$percent);
if(isset($this->task['status']))
{
if($this->task['status']=='error')
{
$ret['result']='failed';
$ret['error']=$this->task['error'];
$ret['timeout']=0;
$ret['percent']= intval(($ret['optimized_images']/$ret['total_images'])*100);
$ret['log']=$this->task['error'];
}
else if($this->task['status']=='finished')
{
$ret['result']='success';
$ret['continue']=0;
$ret['finished']=1;
$ret['timeout']=0;
$ret['percent']= 100;
$ret['log']=__('Finish Optimizing images.','compressx');
$dismiss=CompressX_Options::get_option('compressx_rating_dismiss',false);
if($dismiss===false)
{
$ret['show_review']=1;
}
else if($dismiss==0)
{
$ret['show_review']=0;
}
else if($dismiss<time())
{
$ret['show_review']=1;
}
else
{
$ret['show_review']=0;
}
if($ret['show_review']==1)
{
if (CompressX_Options::get_option('compressx_show_review', false) === false)
{
CompressX_Options::update_option('compressx_show_review', time());
}
delete_transient('compressx_set_global_stats');
$size=CompressX_Image_Method::get_opt_folder_size();
$ret['opt_size']=size_format($size,2);
}
}
else if($this->task['status']=='completed')
{
$ret['result']='success';
$ret['continue']=0;
$ret['finished']=0;
$ret['timeout']=0;
$ret['percent']= intval(($ret['optimized_images']/$ret['total_images'])*100);
}
else
{
if(isset($this->task['last_update_time']))
{
if(time()-$this->task['last_update_time']>180)
{
$this->task['last_update_time']=time();
$this->task['retry']++;
$this->task['status']='timeout';
$this->update_task();
if($this->task['retry']<3)
{
$ret['timeout']=1;
}
else
{
$ret['timeout']=0;
$this->task=array();
$this->update_task();
}
$ret['result']='failed';
$ret['error']=__('Task timed out','compressx');
$ret['percent']=0;
$ret['retry']=$this->task['retry'];
$ret['log']='task time out';
}
else
{
$ret['continue']=1;
$ret['finished']=0;
$ret['timeout']=0;
$ret['running_time']=time()-$this->task['last_update_time'];
$ret['result']='success';
$ret['percent']= intval(($ret['optimized_images']/$ret['total_images'])*100);
}
}
else
{
$ret['result']='failed';
$ret['error']='Not start task';
$ret['timeout']=0;
$ret['percent']=0;
$ret['log']='Not start task';
}
}
}
else
{
$ret['result']='failed';
$ret['error']='Not start task';
$ret['timeout']=0;
$ret['percent']=0;
$ret['log']='Not start task';
}
return $ret;
}
}
@@ -0,0 +1,46 @@
<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
class CompressX_default_folder
{
public function __construct()
{
}
public function create_uploads_dir()
{
$root_path= WP_CONTENT_DIR."/compressx-nextgen";
if(!is_dir($root_path))
{
wp_mkdir_p($root_path);
}
$uploads_folder=WP_CONTENT_DIR."/compressx-nextgen/uploads";
if(!is_dir($uploads_folder))
{
wp_mkdir_p($uploads_folder);
}
$this->create_htaccess();
}
public function create_htaccess()
{
$htaccess_file= WP_CONTENT_DIR."/compressx-nextgen/.htaccess";
$line[]='<IfModule mod_mime.c>';
$line[]='AddType image/avif .avif';
$line[]='AddType image/webp .webp';
$line[]='</IfModule>';
$line[]='<IfModule mod_expires.c>';
$line[]='ExpiresActive On';
$line[]='ExpiresByType image/avif "access plus 1 year"';
$line[]='ExpiresByType image/webp "access plus 1 year"';
$line[]='</IfModule>';
$line[]='Options -Indexes';
insert_with_markers($htaccess_file,'CompressX Webp',$line);
}
}
@@ -0,0 +1,22 @@
<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
class CompressX_i18n
{
/**
* Load the plugin text domain for translation.
*
*
*/
public function load_plugin_textdomain() {
//load_plugin_textdomain() has been discouraged since WordPress version 4.6.
/*load_plugin_textdomain(
'compressx',
false,
dirname( dirname( plugin_basename( __FILE__ ) ) ) . '/languages/'
);
*/
}
}
@@ -0,0 +1,650 @@
<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
class CompressX_Image_Scanner
{
private static $has_sellvia = null;
public static function check_sellvia_environment()
{
if ( self::$has_sellvia === null )
{
if ( !function_exists('get_plugins') )
{
require_once ABSPATH . 'wp-admin/includes/plugin.php';
}
$plugin_path = 'sellvia-platform/sellvia-platform.php';
$installed_plugins = get_plugins();
$is_installed = isset( $installed_plugins[ $plugin_path ] );
if($is_installed)
{
self::$has_sellvia=true;
}
else
{
self::$has_sellvia=false;
}
}
return self::$has_sellvia;
}
//bulk
public static function scan_unoptimized_images($force,$start_row)
{
$convert_to_webp=CompressX_Image_Method::get_convert_to_webp();
$convert_to_avif=CompressX_Image_Method::get_convert_to_avif();
//$exclude_regex_folder=CompressX_Pro_Options::get_excludes();
$time_start=time();
$max_timeout_limit=21;
$finished=true;
$options = CompressX_Options::get_option(
'compressx_general_settings',
array()
);
$page = isset($options['scan_images_page'])
? $options['scan_images_page']
: 500;
$max_count = isset($options['scan_images_max_count'])
? intval($options['scan_images_max_count'])
: 10000;
if ($max_count <= 0)
{
$max_count = 10000;
}
$count = 0;
$last_id = (int) $start_row;
$processed = 0;
while (true)
{
$result = self::scan_unoptimized_image_by_cursor($page, $last_id, $convert_to_webp, $convert_to_avif, $force);
if (empty($result['last_id'])) {
$finished = true;
break;
}
$last_id = $result['last_id'];
$processed += $result['count'];
$time_spend = time() - $time_start;
if ($time_spend > $max_timeout_limit || $processed > $max_count) {
$finished = false;
break;
}
}
$need_optimize_images = self::get_need_optimize_images_count($force);
$ret['result'] = 'success';
$ret['finished'] = $finished;
$ret['offset'] = $last_id;
//$max_image_count=CompressX_Image_Method::get_max_image_count();
global $wpdb;
$max_image_id = (int) $wpdb->get_var("
SELECT MAX(ID) FROM {$wpdb->posts} WHERE post_type='attachment'
");
$progress = min(100, round(($last_id / $max_image_id) * 100, 2));
$ret['progress'] = sprintf('Scanning up to ID %1$d of %2$d, Found %3$d (%4$s%%)',
$last_id, $max_image_id, $need_optimize_images, $progress
);
return $ret;
}
//scan
public static function scan_unoptimized_images_v2($force, $start_row)
{
$convert_to_webp=CompressX_Image_Method::get_convert_to_webp();
$convert_to_avif=CompressX_Image_Method::get_convert_to_avif();
$time_start=time();
$max_timeout_limit=15;
$finished=true;
$options = CompressX_Options::get_option(
'compressx_general_settings',
array()
);
$page = isset($options['scan_images_page'])
? $options['scan_images_page']
: 500;
$max_count = isset($options['scan_images_max_count'])
? intval($options['scan_images_max_count'])
: 10000;
if ($max_count <= 0)
{
$max_count = 10000;
}
$count = 0;
$last_id = (int) $start_row;
$processed = 0;
while (true)
{
$result = self::scan_unoptimized_image_by_cursor_v2(
$page,
$last_id,
$convert_to_webp,
$convert_to_avif,
$force
);
if (empty($result['last_id'])) {
$finished = true;
break;
}
$last_id = $result['last_id'];
$processed += $result['count'];
$time_spend = time() - $time_start;
if ($time_spend > $max_timeout_limit || $processed > $max_count) {
$finished = false;
break;
}
}
// percent
global $wpdb;
$total_attachments = self::get_total_attachments_cached();
$scanned_attachments = self::get_scanned_attachments($last_id);
$percent = $total_attachments > 0
? min(100, round(($scanned_attachments / $total_attachments) * 100, 2))
: 100;
// need optimize images
$need_optimize_images = self::get_need_optimize_images_count($force);
$progress_text = sprintf(
'%1$d / %2$d scanned',
$scanned_attachments,
$total_attachments
);
$ret = [
'result' => 'success',
'finished' => $finished,
'offset' => $last_id,
'found' => $need_optimize_images,
'progress_text' => $progress_text,
'progress_percent' => $percent,
'last_id' => $last_id
];
return $ret;
}
private static function get_total_attachments_cached()
{
global $wpdb;
$mime_types = array(
'image/jpg',
'image/jpeg',
'image/png',
'image/webp',
'image/avif'
);
$placeholders = implode(',', array_fill(0, count($mime_types), '%s'));
$query = "
SELECT COUNT(1)
FROM {$wpdb->posts}
WHERE post_type='attachment'
AND post_mime_type IN ($placeholders)
";
$query = $wpdb->prepare($query, $mime_types);
return (int) $wpdb->get_var($query);
}
public static function scan_unoptimized_image_by_cursor($limit, $last_id, $convert_to_webp, $convert_to_avif, $force)
{
if (!$convert_to_webp && !$convert_to_avif)
{
return ['count' => 0, 'last_id' => 0];
}
global $wpdb;
$mime_types = ["image/jpg", "image/jpeg", "image/png", "image/webp", "image/avif"];
$placeholders = implode(',', array_fill(0, count($mime_types), '%s'));
$subquery = "
SELECT ID,post_mime_type
FROM {$wpdb->posts}
WHERE post_type = 'attachment'
AND post_mime_type IN ($placeholders)
AND ID > %d
ORDER BY ID ASC
LIMIT %d
";
$args = array_merge($mime_types, [$last_id, $limit]);
if ($force) {
$status_filter = "1=1";
} else {
$status_filter = "(pm.status IS NULL OR pm.status NOT IN ('pending', 'skip'))";
}
$meta_table=CompressX_Image_Meta_V2::table_name();
$outer_query = "
SELECT p.ID,p.post_mime_type,pm.attachment_id
FROM ($subquery) p
LEFT JOIN {$meta_table} pm
ON p.ID = pm.attachment_id
WHERE $status_filter
";
// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
$query = $wpdb->prepare($outer_query, $args);
// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
$result = $wpdb->get_results($query, OBJECT_K);
if (empty($result)) {
return ['count' => 0, 'last_id' => 0];
}
$processed = 0;
$max_id = 0;
$exclude = CompressX_Options::get_excludes();
foreach ($result as $image)
{
$image_id = (int) $image->ID;
$max_id = max($max_id, $image_id);
$processed++;
$meta=CompressX_Image_Meta_V2::get_image_meta($image_id);
if (self::should_skip($image_id))
{
CompressX_Image_Meta_V2::update_image_meta_status($image_id, 'skip');
continue;
}
if(isset($meta['status'])&&$meta['status']=='optimized')
{
continue;
}
$type=$image->post_mime_type;
$file_path = get_post_meta($image_id, '_wp_attached_file', true);
if (empty($file_path))
{
continue;
}
if (self::should_exclude_by_path($file_path, $exclude))
{
CompressX_Image_Meta_V2::update_image_meta_status(
$image_id,
'skip'
);
continue;
}
$need_opt = false;
if ($convert_to_webp)
{
if ($type != 'image/avif')
{
if( !isset($meta['webp_converted']) ||$meta['webp_converted']==0)
{
$need_opt = true;
}
}
}
if ($convert_to_avif)
{
if( !isset($meta['avif_converted']) ||$meta['avif_converted']==0)
{
$need_opt = true;
}
}
if ($need_opt)
{
CompressX_Image_Meta_V2::update_image_meta_status($image_id, 'pending');
}
}
return [
'count' => $processed,
'last_id' => $max_id,
];
}
public static function should_skip($image_id)
{
if ( ! self::check_sellvia_environment() )
{
return false;
}
$is_sellvia = get_post_meta($image_id, '_wp_sellvia_attached_file', true);
if ($is_sellvia === '1')
{
return true;
}
else
{
return false;
}
}
public static function get_need_optimize_images_count($force)
{
global $wpdb;
$meta_table = CompressX_Image_Meta_V2::table_name();
if ($force) {
$statuses = ['pending', 'optimized', 'failed'];
} else {
$statuses = ['pending', 'failed'];
}
$placeholders = implode(',', array_fill(0, count($statuses), '%s'));
return (int) $wpdb->get_var($wpdb->prepare("
SELECT COUNT(attachment_id)
FROM {$meta_table}
WHERE status IN ($placeholders)
", $statuses));
}
public static function get_need_optimize_images_by_cursor($last_id = 0, $limit = 200, $force = false)
{
global $wpdb;
$meta_table=CompressX_Image_Meta_V2::table_name();
if ($force)
{
return $wpdb->get_col($wpdb->prepare("
SELECT pm.attachment_id
FROM {$meta_table} pm
WHERE pm.status IN ('pending', 'optimized', 'failed')
AND pm.attachment_id > %d
ORDER BY pm.attachment_id ASC
LIMIT %d
", $last_id, $limit));
}
else
{
return $wpdb->get_col($wpdb->prepare("
SELECT pm.attachment_id
FROM {$meta_table} pm
WHERE pm.status IN ('pending', 'failed')
AND pm.attachment_id > %d
ORDER BY pm.attachment_id ASC
LIMIT %d
", $last_id, $limit));
}
}
private static function get_scanned_attachments($last_id)
{
global $wpdb;
$mime_types = array(
'image/jpg',
'image/jpeg',
'image/png',
'image/webp',
'image/avif'
);
$placeholders = implode(',', array_fill(0, count($mime_types), '%s'));
$query = "
SELECT COUNT(1)
FROM {$wpdb->posts}
WHERE post_type='attachment'
AND post_mime_type IN ($placeholders)
AND ID <= %d
";
$args = array_merge($mime_types, array($last_id));
$query = $wpdb->prepare($query, $args);
return (int) $wpdb->get_var($query);
}
public static function scan_unoptimized_image_by_cursor_v2($limit, $last_id, $convert_to_webp, $convert_to_avif, $force)
{
if (!$convert_to_webp && !$convert_to_avif)
{
return array(
'count' => 0,
'last_id' => 0
);
}
global $wpdb;
$limit = max(1, (int)$limit);
$last_id = max(0, (int)$last_id);
$mime_types = array(
'image/jpg',
'image/jpeg',
'image/png',
'image/webp',
'image/avif'
);
$placeholders = implode(',', array_fill(0, count($mime_types), '%s'));
if ($force)
{
$status_filter = "1=1";
}
else
{
$status_filter = "(pm.status IS NULL OR pm.status NOT IN ('pending', 'skip'))";
}
$meta_table = CompressX_Image_Meta_V2::table_name();
$sql = "
SELECT
p.ID,
p.post_mime_type,
pm.status,
pm.webp_converted,
pm.avif_converted,
af.meta_value AS attached_file
FROM {$wpdb->posts} p
LEFT JOIN {$meta_table} pm
ON p.ID = pm.attachment_id
LEFT JOIN {$wpdb->postmeta} af
ON af.post_id = p.ID
AND af.meta_key = '_wp_attached_file'
WHERE p.post_type = 'attachment'
AND p.post_mime_type IN ($placeholders)
AND p.ID > %d
AND {$status_filter}
ORDER BY p.ID ASC
LIMIT %d
";
$args = array_merge(
$mime_types,
array(
$last_id,
$limit
)
);
$query = $wpdb->prepare($sql, $args);
$result = $wpdb->get_results($query);
if (empty($result))
{
return array(
'count' => 0,
'last_id' => 0
);
}
$processed = 0;
$max_id = 0;
$exclude = CompressX_Options::get_excludes();
foreach ($result as $image)
{
$image_id = (int)$image->ID;
$max_id = max($max_id, $image_id);
$processed++;
$status = isset($image->status)
? (string)$image->status
: '';
$webp_converted = isset($image->webp_converted)
? (int)$image->webp_converted
: 0;
$avif_converted = isset($image->avif_converted)
? (int)$image->avif_converted
: 0;
if (self::should_skip($image_id))
{
CompressX_Image_Meta_V2::update_image_meta_status(
$image_id,
'skip'
);
continue;
}
if ($status === 'optimized')
{
continue;
}
$file_path = isset($image->attached_file)
? (string)$image->attached_file
: '';
if (empty($file_path))
{
continue;
}
if (self::should_exclude_by_path($file_path, $exclude))
{
CompressX_Image_Meta_V2::update_image_meta_status(
$image_id,
'skip'
);
continue;
}
$type = (string)$image->post_mime_type;
$need_opt = false;
if ($convert_to_webp && $type !== 'image/avif' && $webp_converted === 0)
{
$need_opt = true;
}
if ($convert_to_avif && $avif_converted === 0)
{
$need_opt = true;
}
if ($need_opt)
{
CompressX_Image_Meta_V2::update_image_meta_status(
$image_id,
'pending'
);
}
}
return array(
'count' => $processed,
'last_id' => $max_id,
);
}
public static function get_attached_file_by_meta_value($file)
{
if (empty($file))
{
return false;
}
if (
0 !== strpos($file, '/') &&
!preg_match('|^.:\\\\|', $file) &&
!preg_match('|^[a-zA-Z]:/|', $file)
)
{
$uploads = wp_get_upload_dir();
if (false === $uploads['error'])
{
$file = $uploads['basedir'] . '/' . ltrim($file, '/');
}
}
return $file;
}
public static function should_exclude_by_path($relative_file, $exclude)
{
if (empty($relative_file) || empty($exclude))
{
return false;
}
$file_path = self::get_attached_file_by_meta_value($relative_file);
if (empty($file_path))
{
return false;
}
return CompressX_Image_Method::exclude_path_ex(
$file_path,
$exclude
);
}
}
@@ -0,0 +1,406 @@
<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
class Compressx_Image
{
public $image_id;
public $options;
public $log;
public function __construct($image_id,$options=array())
{
$this->image_id=$image_id;
$this->options=$options;
$this->log = CompressX_Log_Ex::get_instance();
if(!CompressX_Image_Meta_V2::has_image_meta($this->image_id))
{
CompressX_Image_Meta_V2::generate_images_meta($this->image_id, $this->options);
}
}
public function resize()
{
if(CompressX_Image_Meta_V2::get_image_meta_value($this->image_id,'resize_status')==0)
{
if(CompressX_Image_Opt_Method::resize($this->image_id,$this->options,$this->log))
{
CompressX_Image_Meta_V2::update_images_meta_value($this->image_id,'resize_status',1);
}
}
}
public function resize_ex($metadata)
{
if(CompressX_Image_Meta_V2::get_image_meta_value($this->image_id,'resize_status')==0)
{
$ret=CompressX_Image_Opt_Method::resize_ex($this->image_id,$this->options,$metadata,$this->log);
if($ret['result']=='success')
{
CompressX_Image_Meta_V2::update_images_meta_value($this->image_id,'resize_status',1);
return $ret;
}
}
$ret['result']='success';
$ret['meta']=$metadata;
return $ret;
}
public function convert()
{
$has_error=false;
if($this->convert_to_webp()===false)
{
$has_error=true;
}
if($this->convert_to_avif()===false)
{
$has_error=true;
}
return !$has_error;
}
public function convert_to_webp()
{
if(CompressX_Image_Method::is_exclude_webp($this->image_id,$this->options))
{
return true;
}
if(!$this->need_convert_to_webp())
{
return true;
}
if(CompressX_Image_Meta_V2::get_image_meta_webp_converted($this->image_id)==1)
{
return true;
}
$success=true;
$has_convert=true;
$size =CompressX_Image_Meta_V2::get_image_meta_value($this->image_id,'size');
$uploads=wp_get_upload_dir();
$file_path = get_attached_file( $this->image_id );
$type=pathinfo($file_path, PATHINFO_EXTENSION);
foreach ($size as $size_key=>$size_meta)
{
if($size_meta['convert_webp_status']==1||$this->skip_size($size_key))
{
continue;
}
if($size_key=="og")
{
$filename= $file_path;
}
else if(CompressX_Image_Opt_Method::is_elementor_thumbs($size_key))
{
$filename = $uploads['basedir'].'/'.$size_meta['file'];
}
else
{
$filename= path_join( dirname( $file_path ), $size_meta['file'] );
}
CompressX_Image_Opt_Method::WriteLog($this->log,'Start WebP conversion '.basename($filename),'notice');
if(!file_exists($filename))
{
CompressX_Image_Opt_Method::WriteLog($this->log,'File '.basename($filename).' not exist,so skip convert.','notice');
$size_meta['convert_webp_status']=1;
$size_meta['status']='optimized';
CompressX_Image_Meta_V2::update_image_meta_size($this->image_id,$size_key,$size_meta);
continue;
}
$nextgen_path=CompressX_Image_Opt_Method::get_output_path($filename);
if($type=="webp")
{
$des_filename=$nextgen_path;
}
else
{
$des_filename=$nextgen_path.'.webp';
}
$ret=$this->_convert_webp($filename,$des_filename);
if($ret['result']=='success')
{
$webp_converted_size=filesize($des_filename);
$file_size=filesize($filename);
if($this->options['auto_remove_larger_format']&&$webp_converted_size>$file_size)
{
@wp_delete_file($des_filename);
CompressX_Image_Opt_Method::WriteLog($this->log,'WebP size larger than original size, deleting file '.basename($des_filename).'.','notice');
$size_meta['webp_converted_size']=$file_size;
}
else
{
$size_meta['webp_converted_size']=$webp_converted_size;
}
$size_meta['file_size']=$file_size;
$size_meta['convert_webp_status']=1;
$size_meta['status']='optimized';
CompressX_Image_Meta_V2::update_image_meta_size($this->image_id,$size_key,$size_meta);
}
else
{
$size_meta['convert_webp_status']=0;
$size_meta['status']='failed';
$size_meta['error']=$ret['error'];
CompressX_Image_Meta_V2::update_image_meta_size($this->image_id,$size_key,$size_meta);
$success=false;
$has_convert=false;
}
}
if($has_convert)
{
CompressX_Image_Meta_V2::update_webp_image_converted($this->image_id);
//CompressX_Image_Meta_V2::update_image_meta_webp_converted($this->image_id,1);
}
return $success;
}
public function convert_to_avif()
{
if(CompressX_Image_Method::is_exclude_avif($this->image_id,$this->options))
{
return true;
}
if(!$this->need_convert_to_avif())
{
return true;
}
if(CompressX_Image_Meta_V2::get_image_meta_avif_converted($this->image_id)==1)
{
return true;
}
$success=true;
$has_convert=true;
$size =CompressX_Image_Meta_V2::get_image_meta_value($this->image_id,'size');
$uploads=wp_get_upload_dir();
$file_path = get_attached_file( $this->image_id );
$type=pathinfo($file_path, PATHINFO_EXTENSION);
foreach ($size as $size_key=>$size_meta)
{
if($size_meta['convert_avif_status']==1||$this->skip_size($size_key))
{
continue;
}
if($size_key=="og")
{
$filename= $file_path;
}
else if(CompressX_Image_Opt_Method::is_elementor_thumbs($size_key))
{
$filename = $uploads['basedir'].'/'.$size_meta['file'];
}
else
{
$filename= path_join( dirname( $file_path ), $size_meta['file'] );
}
$nextgen_path=CompressX_Image_Opt_Method::get_output_path($filename);
if($type=="avif")
{
$des_filename=$nextgen_path;
}
else
{
$des_filename=$nextgen_path.'.avif';
}
CompressX_Image_Opt_Method::WriteLog($this->log,'Start AVIF conversion:'.basename($filename),'notice');
if(!file_exists($filename))
{
CompressX_Image_Opt_Method::WriteLog($this->log,'File '.basename($filename).' not exist,so skip convert.','notice');
$size_meta['convert_avif_status']=1;
$size_meta['status']='optimized';
CompressX_Image_Meta_V2::update_image_meta_size($this->image_id,$size_key,$size_meta);
continue;
}
$ret=$this->_convert_avif($filename,$des_filename);
if($ret['result']=='success')
{
$avif_converted_size=filesize($des_filename);
$file_size=filesize($filename);
if($this->options['auto_remove_larger_format']&&$avif_converted_size>$file_size)
{
@wp_delete_file($des_filename);
CompressX_Image_Opt_Method::WriteLog($this->log,'AVIF size larger than original size, deleting file '.basename($des_filename).'.','notice');
$size_meta['avif_converted_size']=$file_size;
}
else
{
$size_meta['avif_converted_size']=$avif_converted_size;
}
$size_meta['file_size']=$file_size;
$size_meta['convert_avif_status']=1;
$size_meta['status']='optimized';
CompressX_Image_Meta_V2::update_image_meta_size($this->image_id,$size_key,$size_meta);
}
else
{
$size_meta['convert_avif_status']=0;
$size_meta['status']='failed';
$size_meta['error']=$ret['error'];
CompressX_Image_Meta_V2::update_image_meta_size($this->image_id,$size_key,$size_meta);
$success=false;
$has_convert=false;
}
}
if($has_convert)
{
//CompressX_Image_Meta_V2::update_image_meta_avif_converted($this->image_id,1);
CompressX_Image_Meta_V2::update_avif_image_converted($this->image_id);
}
return $success;
}
public function _convert_webp($filename,$des_filename)
{
if($this->options['converter_method']=='gd')
{
$ret=CompressX_Image_Opt_Method::convert_webp_gd_ex($filename,$des_filename,$this->options);
}
else if($this->options['converter_method']=='imagick')
{
$ret=CompressX_Image_Opt_Method::convert_webp_imagick_ex($filename,$des_filename,$this->options);
}
else
{
$ret=CompressX_Image_Opt_Method::convert_webp_gd_ex($filename,$des_filename,$this->options);
}
if($ret['result']=='success')
{
CompressX_Image_Opt_Method::WriteLog($this->log,'Converting '.basename($filename).' to WebP succeeded.','notice');
}
else
{
CompressX_Image_Opt_Method::WriteLog($this->log,'Converting '.basename($filename).' to WebP failed. Error:'.$ret['error'],'notice');
}
return $ret;
}
public function _convert_avif($filename,$des_filename)
{
if($this->options['converter_method']=='gd')
{
$ret=CompressX_Image_Opt_Method::convert_avif_gd_ex($filename,$des_filename,$this->options);
}
else if($this->options['converter_method']=='imagick')
{
$ret=CompressX_Image_Opt_Method::convert_avif_imagick_ex($filename,$des_filename,$this->options);
}
else
{
$ret=CompressX_Image_Opt_Method::convert_avif_gd_ex($filename,$des_filename,$this->options);
}
if($ret['result']=='success')
{
CompressX_Image_Opt_Method::WriteLog($this->log,'Converting '.basename($filename).' to AVIF succeeded.','notice');
}
else
{
CompressX_Image_Opt_Method::WriteLog($this->log,'Converting '.basename($filename).' to AVIF failed. Error:'.$ret['error'],'notice');
}
return $ret;
}
public function need_compress()
{
$file_path = get_attached_file($this->image_id);
$type=pathinfo($file_path, PATHINFO_EXTENSION);
if($type=='webp')
{
return $this->options['compressed_webp'];
}
else if($type=='avif')
{
return $this->options['compressed_avif'];
}
return false;
}
public function skip_size($size_key)
{
if(isset($this->options['skip_size'])&&isset($this->options['skip_size'][$size_key]))
{
return $this->options['skip_size'][$size_key];
}
return false;
}
public function need_convert_to_webp_ex()
{
$file_path = get_attached_file($this->image_id);
$type=pathinfo($file_path, PATHINFO_EXTENSION);
if($type=='webp'||$type=='avif')
{
return false;
}
return $this->options['convert_to_webp'];
}
public function need_convert_to_avif_ex()
{
$file_path = get_attached_file($this->image_id);
$type=pathinfo($file_path, PATHINFO_EXTENSION);
if($type=='avif')
{
return false;
}
return $this->options['convert_to_avif'];
}
public function need_convert_to_webp()
{
$file_path = get_attached_file($this->image_id);
$type=pathinfo($file_path, PATHINFO_EXTENSION);
if($type=='avif')
{
return false;
}
return $this->options['convert_to_webp'];
}
public function need_convert_to_avif()
{
return $this->options['convert_to_avif'];
}
}
@@ -0,0 +1,771 @@
<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
class CompressX_ImgOptim_Task
{
public $task;
public $log=false;
public function __construct()
{
$this->get_task();
}
public function update_task()
{
CompressX_Options::update_option('compressx_image_opt_task',$this->task);
$this->get_task();
}
public function get_task()
{
$this->task=CompressX_Options::get_option('compressx_image_opt_task',array());
}
public function init_task($force=false)
{
$this->task=array();
$offset=get_option('gmt_offset');
$localtime = time() + $offset * 60 * 60;
$this->task['log']=uniqid('compressx_').'_'.gmdate('Ymd',$localtime).'_log.txt';
$this->log=CompressX_Log_Ex::get_instance();
$this->log->CreateLogFile($this->task['log']);
$this->init_options();
$this->task['options']['force']=$force;
$this->task['offset']=0;
if(!$this->get_need_optimize_images())
{
$ret['result']='failed';
$ret['no_unoptimized_images']=true;
$ret['error']=__('No unoptimized images found.','compressx');
$this->update_task();
return $ret;
}
$this->task['status']='init';
$this->task['last_update_time']=time();
$this->task['retry']=0;
$this->task['total_retry']=0;
//$this->task['total_images']=CompressX_Options::get_option("compressx_need_optimized_images",0);
$this->task['total_images']=CompressX_Image_Scanner::get_need_optimize_images_count($force);
$this->task['optimized_images']=0;
$this->task['skipped_images']=0;
$this->task['opt_images']=0;
$this->task['failed_images']=0;
$this->task['current_image']=0;
$this->task['current_file']='';
$this->task['error']='';
$this->task['update_error_list']=false;
$this->update_task();
$ret['result']='success';
$ret["test"]=$this->task;
return $ret;
}
public function init_options()
{
$general_options=CompressX_Options::get_general_settings();
$quality_options=CompressX_Options::get_quality_option();
$this->task['options']=array_merge($general_options,$quality_options);
$this->task['options']['exclude']=CompressX_Options::get_excludes();
}
public function OpenLog()
{
$this->log=CompressX_Log_Ex::get_instance();
$this->log->OpenLogFile($this->task['log']);
}
public function WriteLog($log,$type)
{
if (is_a($this->log, 'CompressX_Log_Ex'))
{
$this->log->WriteLog($log,$type);
}
else
{
$this->log=CompressX_Log_Ex::get_instance();
$this->log->OpenLogFile($this->task['log']);
$this->log->WriteLog($log,$type);
}
}
public function get_log_file()
{
if(isset($this->task['log']))
{
return $this->task['log'];
}
else
{
return "";
}
}
public function get_need_optimize_images()
{
$ret=$this->init_optimize_images();
if($ret['finished']&&empty($this->task['images']))
{
return false;
}
else
{
return true;
}
}
public function get_task_status()
{
if(empty($this->task))
{
$ret['result']='failed';
$ret['error']=__('All image(s) optimized successfully.','compressx');
return $ret;
}
if($this->task['status']=='error')
{
$ret['result']='failed';
$ret['error']=$this->task['error'];
}
else if($this->task['status']=='completed')
{
$ret['result']='success';
$ret['status']='completed';
}
else if($this->task['status']=='finished')
{
$ret['result']='success';
$ret['status']='finished';
}
else if($this->task['status']=='timeout')
{
$ret['result']='success';
$ret['status']='completed';
}
else if($this->task['status']=='init')
{
$ret['result']='success';
$ret['status']='completed';
}
else
{
$ret['result']='success';
$ret['status']='running';
}
return $ret;
}
public function init_optimize_images()
{
$this->task['images']=array();
$max_count=200;
$force=$this->task['options']['force'];
$start_row=$this->task['offset'];
$image_ids=CompressX_Image_Scanner::get_need_optimize_images_by_cursor($start_row,$max_count,$force);
if(!empty($image_ids))
{
$last_id=$this->task['offset'];
foreach ($image_ids as $image_id)
{
$image['id']=$image_id;
$image['finished']=0;
$this->task['images'][$image['id']]=$image;
$last_id = $image_id;
}
$this->task['offset'] = $last_id;
$this->update_task();
}
if (empty($image_ids)||count($image_ids) < $max_count)
{
$finished=true;
}
else
{
$finished=false;
}
$ret['result']='success';
$ret['finished']=$finished;
return $ret;
}
public function get_need_optimize_image()
{
if(!empty($this->task['images']))
{
foreach ($this->task['images'] as $image)
{
if($image['finished']==0)
{
$ret['result']='success';
$ret['finished']=false;
$ret['image_id']=$image['id'];
return $ret;
}
}
}
$this->task['images']=array();
$ret=$this->init_optimize_images();
if($ret['finished']&&empty($this->task['images']))
{
$ret['result']='success';
$ret['finished']=true;
$ret['image_id']=false;
return $ret;
}
else
{
if(empty($this->task['images']))
{
$ret['result']='success';
$ret['finished']=false;
$ret['image_id']=false;
return $ret;
}
else
{
foreach ($this->task['images'] as $image)
{
if($image['finished']==0)
{
$ret['result']='success';
$ret['finished']=false;
$ret['image_id']=$image['id'];
return $ret;
}
}
$ret['result']='success';
$ret['finished']=false;
$ret['image_id']=false;
return $ret;
}
}
}
public function do_optimize_image()
{
$this->OpenLog();
if($this->check_timeout())
{
$this->WriteLog('Optimizing image failed. Error:task timeout','error');
$this->task['status']='error';
$this->task['error']='task timeout';
$this->task['last_update_time']=time();
$this->update_task();
$ret['result']='failed';
$ret['error']='task timeout';
return $ret;
}
$this->task['status']='running';
$this->task['last_update_time']=time();
$this->update_task();
$converter_images_pre_request=$this->task['options']['converter_images_pre_request'];
$time_start=time();
$max_timeout_limit=90;
for ($i=0;$i<$converter_images_pre_request;$i++)
{
$ret=$this->get_need_optimize_image();
if($ret['finished']&&$ret['image_id']===false)
{
$ret['result']='success';
$this->task['status']='finished';
$this->task['last_update_time']=time();
delete_transient('compressx_set_global_stats');
$this->update_task();
do_action('compressx_purge_cache');
return $ret;
}
else if($ret['image_id']===false)
{
break;
}
else
{
$image_id=$ret['image_id'];
}
$this->task['status']='running';
$this->task['last_update_time']=time();
$this->update_task();
if(CompressX_Image_Method::exclude_path($image_id,$this->task['options']['exclude']))
{
CompressX_Image_Meta_V2::update_image_meta_status($image_id,'skip');
$this->WriteLog('Exclude images: id:'.$image_id,'notice');
$this->task['images'][$image_id]['finished']=1;
$this->task['last_update_time']=time();
$this->task['retry']=0;
$this->task['total_retry']=0;
$this->task['skipped_images']++;
$this->update_task();
}
else
{
if($this->task['options']['force'])
{
CompressX_Image_Meta_V2::generate_images_meta($image_id,$this->task['options']);
}
$this->WriteLog('Start optimizing images: id:'.$image_id,'notice');
$ret=$this->optimize_image($image_id);
if($ret['result']=='success')
{
$this->WriteLog('Optimizing image id:'.$image_id.' succeeded.','notice');
$this->task['images'][$image_id]['finished']=1;
$this->task['last_update_time']=time();
$this->task['retry']=0;
$this->task['total_retry']=0;
$this->task['optimized_images']++;
$this->update_task();
do_action('compressx_after_optimize_image',$image_id);
}
else
{
$this->WriteLog('Optimizing image failed. Error:'.$ret['error'],'error');
$this->task['status']='error';
$this->task['error']=$ret['error'];
$this->task['last_update_time']=time();
$this->update_task();
return $ret;
}
}
$time_spend=time()-$time_start;
if($time_spend>$max_timeout_limit)
{
break;
}
}
delete_transient('compressx_set_global_stats');
$time_spend=time()-$time_start;
$this->WriteLog('End request cost time:'.$time_spend.'.','notice');
$this->task['status']='completed';
$this->task['last_update_time']=time();
$this->update_task();
$ret['result']='success';
$ret['test']=$this->task;
return $ret;
}
public function skip_current_image()
{
$image_id=$this->task['current_image'];
if(isset($this->task['images'][$image_id]))
{
$this->task['images'][$image_id]['finished']=1;
$this->task['last_update_time']=time();
$this->task['failed_images']++;
CompressX_Image_Meta_V2::update_image_meta_status($image_id,'failed');
$this->update_task();
$this->WriteLog('skip current timout image:'.$image_id,'error');
return true;
}
else
{
return false;
}
}
public function optimize_image($image_id)
{
$this->task['current_image']=$image_id;
$file_path = get_attached_file( $image_id );
$abs_root=CompressX_Image_Method::transfer_path(ABSPATH);
$attachment_dir=CompressX_Image_Method::transfer_path($file_path);
$this->task['current_file']=str_replace($abs_root,'',$attachment_dir);
$this->update_task();
$image=new Compressx_Image($image_id,$this->task['options']);
if(empty($file_path))
{
$this->WriteLog('Image:'.$image_id.' failed. Error: failed to get get_attached_file','notice');
$this->task['failed_images']++;
$this->update_task();
$error='Image:'.$image_id.' failed. Error: failed to get get_attached_file';
CompressX_Image_Meta_V2::update_image_failed($image_id,$error);
$ret['result']='success';
return $ret;
}
if(!file_exists($file_path))
{
$this->WriteLog('Image:'.$image_id.' failed. Error: file not exists '.$file_path,'notice');
$this->task['failed_images']++;
$this->update_task();
$error='Image:'.$image_id.' failed. Error: file not exists '.$file_path;
CompressX_Image_Meta_V2::update_image_failed($image_id,$error);
$ret['result']='success';
return $ret;
}
if(!$this->check_file_mime_content_type($file_path))
{
$this->WriteLog('Image:'.$image_id.' failed. Error: mime content type not support','notice');
$error='Image:'.$image_id.' failed. Error: mime content type not support';
$this->task['failed_images']++;
$this->update_task();
CompressX_Image_Meta_V2::update_image_failed($image_id,$error);
$ret['result']='success';
return $ret;
}
CompressX_Image_Meta_V2::update_image_progressing($image_id);
$image->resize();
if($image->convert())
{
$this->task['opt_images']++;
$this->update_task();
CompressX_Image_Meta_V2::update_image_meta_status($image_id,'optimized');
}
else
{
$this->task['failed_images']++;
$this->update_task();
CompressX_Image_Meta_V2::update_image_meta_status($image_id,'failed');
}
CompressX_Image_Meta_V2::delete_image_progressing($image_id);
$ret['result']='success';
return $ret;
}
public function check_file_mime_content_type($file_path)
{
if(function_exists( 'mime_content_type' ))
{
$type=mime_content_type($file_path);
if($type=="text/html")
{
return false;
}
else
{
return true;
}
}
else
{
return true;
}
}
public function get_task_progress()
{
$this->get_task();
if(empty($this->task))
{
$ret['result']='failed';
$ret['error']=__('Finish optimizing images.','compressx');
$ret['percent']=0;
$ret['timeout']=0;
$ret['log']=__('All image(s) optimized successfully.','compressx');
return $ret;
}
if(isset($this->task['total_images']))
{
$ret['total_images']=$this->task['total_images'];
}
else
{
$ret['total_images']=0;
}
$ret['optimized_images']=0;
if(isset($this->task['optimized_images']))
{
$ret['optimized_images']=$this->task['optimized_images'];
}
if($ret['total_images']>0)
{
$percent= intval(($ret['optimized_images']/$ret['total_images'])*100);
}
else
{
$percent=0;
}
$ret['log']=sprintf(
'%1$d images found | Processed:%2$d/%3$d (%4$d%%)',
$ret['total_images'],$this->task['optimized_images'],$ret['total_images'],$percent);
$sub_total=sizeof($this->task['images']);
$sub_optimized_images=0;
foreach ($this->task['images'] as $image)
{
if($image['finished']==1)
{
$sub_optimized_images++;
}
}
if($sub_total>0)
{
$sub_percent= intval(($sub_optimized_images/$sub_total)*100);
}
else
{
$sub_percent=0;
}
if(!empty($this->task['current_file']))
{
$ret['sub_log']=sprintf(
'Current Subtask: %1$d/%2$d | Processing:%3$s',
$sub_optimized_images,$sub_total,basename($this->task['current_file']));
}
else
{
$ret['sub_log']=sprintf(
'Current Subtask: %1$d/%2$d ',
$sub_optimized_images,$sub_total);
}
$ret['sub_log_ex']=sprintf(
'%1$d / %2$d',
$sub_optimized_images,$sub_total);
$ret['percent']= $sub_percent;
//$ret['sub_log']='Current Subtask: '.$sub_optimized_images.'/'.$sub_total;
if(isset($this->task['status']))
{
if($this->task['status']=='error')
{
$ret['result']='failed';
$ret['error']=$this->task['error'];
$ret['timeout']=0;
$ret['log']=$this->task['error'];
}
else if($this->task['status']=='finished')
{
$ret['result']='success';
$ret['continue']=0;
$ret['finished']=1;
$ret['timeout']=0;
$ret['percent']= 100;
$ret['message']=sprintf(
'Total optimized images:%1$d Succeeded:%2$d Failed:%3$d',
$ret['total_images'],$this->task['opt_images'],$this->task['failed_images']);
//$ret['message']='Total optimized images:'.$ret['total_images'].' Succeeded:'.$this->task['opt_images'].' Failed:'.$this->task['failed_images'];
$dismiss=CompressX_Options::get_option('compressx_rating_dismiss',false);
if($dismiss===false)
{
$ret['show_review']=1;
}
else if($dismiss==0)
{
$ret['show_review']=0;
}
else if($dismiss<time())
{
$ret['show_review']=1;
}
else
{
$ret['show_review']=0;
}
if($ret['show_review']==1)
{
CompressX_Options::update_option('compressx_show_review', time());
delete_transient('compressx_set_global_stats');
$size=CompressX_Image_Method::get_opt_folder_size();
$ret['opt_size']=size_format($size,2);
}
}
else if($this->task['status']=='completed')
{
$ret['result']='success';
$ret['continue']=0;
$ret['finished']=0;
$ret['timeout']=0;
$ret['message']=sprintf(
'Total optimized images:%1$d Succeeded:%2$d Failed:%3$d',
$ret['total_images'],$this->task['opt_images'],$this->task['failed_images']);
}
else
{
if(isset($this->task['last_update_time']))
{
if(time()-$this->task['last_update_time']>120)
{
$this->task['last_update_time']=time();
$this->task['retry']++;
$this->task['total_retry']++;
$this->task['status']='timeout';
$this->update_task();
$ret['timeout']=1;
$ret['result']='failed';
$ret['error']='Task timeout';
$ret['percent']=0;
$ret['continue']=0;
$ret['finished']=0;
$ret['retry']=$this->task['retry'];
$ret['log']='task time out';
}
else
{
$ret['continue']=1;
$ret['finished']=0;
$ret['timeout']=0;
$ret['running_time']=time()-$this->task['last_update_time'];
$ret['result']='success';
}
}
else
{
$ret['result']='failed';
$ret['error']='not start task';
$ret['timeout']=0;
$ret['percent']=0;
$ret['log']='not start task';
}
}
}
else
{
$ret['result']='failed';
$ret['error']='not start task';
$ret['timeout']=0;
$ret['percent']=0;
$ret['log']='not start task';
}
$ret['test']=$this->task;
return $ret;
}
public function get_task_progress_ex()
{
$ret = $this->get_task_progress();
if ($ret['result'] !== 'success') {
return $ret;
}
$total = intval($ret['total_images']);
$optimized = intval($ret['optimized_images']);
$failed = intval($this->task['failed_images']);
$skipped = intval($this->task['skipped_images']);
$remaining = max(0, $total - $optimized - $failed - $skipped);
$ret["progress_text"] = sprintf(
'%1$d / %2$d images optimized',
$optimized,
$total
);
$ret["progress_percent"] =intval(
$total > 0 ? round(($optimized / $total) * 100, 2) : 0);
$ret["sub_progress_text"] = $ret["sub_log_ex"];
$ret["sub_progress_percent"] = intval($ret["percent"]);
$ret["optimized"] = $optimized;
$ret["errors"] = $failed;
$ret["remaining"] = $remaining;
return $ret;
}
public function check_timeout()
{
if(isset($this->task['status']))
{
if($this->task['status']=='timeout')
{
if($this->task['retry']>3&&$this->task['total_retry']<10)
{
if($this->skip_current_image())
{
return false;
}
else
{
return true;
}
}
else if($this->task['total_retry']>10)
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
else
{
return false;
}
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,286 @@
<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
class CompressX_Manual_Optimization
{
public $log;
public function __construct()
{
add_action('wp_ajax_compressx_opt_single_image', array($this, 'opt_single_image'));
//add_action('wp_ajax_compressx_opt_image', array($this, 'opt_image'));
add_action('wp_ajax_compressx_delete_single_image', array($this, 'delete_single_image'));
}
public function delete_single_image()
{
global $compressx;
$compressx->ajax_check_security('compressx-can-convert');
if(!isset($_POST['id']))
{
die();
}
$id=sanitize_key($_POST['id']);
if(isset($_POST['page'])&&is_string($_POST['page']))
{
$page=sanitize_text_field($_POST['page']);
}
else
{
$page='media';
}
try
{
CompressX_Image_Opt_Method::delete_image($id);
if($page=='edit')
{
$html='<h4>'.__('CompressX', 'compressx').'</h4>';
}
else
{
$html='';
}
if(!CompressX_Image_Meta_V2::is_image_optimized($id))
{
if($this->is_image_progressing($id))
{
$html.= "<a class='cx-media-progressing button' data-id='{$id}'>".__('Converting...', 'compressx')."</a>";
}
else
{
$html.= "<a class='cx-media button' data-id='{$id}'>".__('Convert','compressx')."</a>";
if($this->is_image_processing_failed($id))
{
$meta=CompressX_Image_Meta_V2::get_image_meta($id);
foreach ($meta['size'] as $size_key => $size_data)
{
if(!empty($size_data['error']))
{
$html.='<p style="border-bottom:1px solid #D2D3D6;margin-top: 12px;"></p>';
$html.="<span>".esc_html($size_data['error'])."</span>";
break;
}
}
}
}
}
else
{
$convert_size=CompressX_Image_Meta_V2::get_webp_converted_size($id);
$og_size=CompressX_Image_Meta_V2::get_og_size($id);
if($og_size>0)
{
if($convert_size>0)
{
$webp_percent = round(100 - ($convert_size / $og_size) * 100, 2);
}
else if(CompressX_Image_Meta_V2::is_avif_image($id))
{
$webp_percent=0;
}
else
{
$webp_percent=0;
}
}
else
{
$webp_percent=0;
}
$avif_size=CompressX_Image_Meta_V2::get_avif_converted_size($id);
if($og_size>0)
{
if($avif_size>0)
{
$avif_percent = round(100 - ($avif_size / $og_size) * 100, 2);
}
else
{
$avif_percent=0;
}
}
else
{
$avif_percent=0;
}
$meta=CompressX_Image_Meta_V2::get_image_meta($id);
$thumbnail_counts=count($meta['size']);
$html.='<ul>';
$html.= '<li><span>'.__('Original','compressx').' : </span><strong>'.size_format($og_size,2).'</strong></li>';
$html.= '<li><span>'.__('Webp','compressx').' : </span><strong>'.size_format($convert_size,2).'</strong><span> '.__('Saved','compressx').' : </span><strong>'.$webp_percent.'%</strong></li>';
$html.= '<li><span>'.__('AVIF','compressx').' : </span><strong>'.size_format($avif_size,2).'</strong><span> '.__('Saved','compressx').' : </span><strong>'.$avif_percent.'%</strong></li>';
$html.= '<li><span>'.__('Thumbnails generated','compressx').' : </span><strong>'.$thumbnail_counts.'</strong></li>';
$html.="<li><a class='cx-media-delete button' data-id='".esc_attr($id)."'>Delete</a>
<span class='compressx-dashicons-help compressx-tooltip'>
<a href='#'><span class='dashicons dashicons-editor-help' style='padding-top: 3px;'></span></a>
<div class='compressx-bottom'>
<!-- The content you need -->
<p>
<span>".__('Delete the WebP and AVIF images generated by CompressX.','compressx')."</span><br>
</p>
<i></i> <!-- do not delete this line -->
</div>
</span>
</li>";
$html.='</ul>';
}
$ret[$id]['html']=$html;
$ret['result']='success';
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 opt_single_image()
{
global $compressx;
$compressx->ajax_check_security('compressx-can-convert');
if(!isset($_POST['id']))
{
die();
}
$id=sanitize_key($_POST['id']);
delete_transient('compressx_set_global_stats');
set_time_limit(180);
$this->log=new CompressX_Log();
$this->log->CreateLogFile();
$this->do_optimize_image($id);
die();
}
public function do_optimize_image($attachment_id)
{
$this->WriteLog('Start optimizing image id:'.$attachment_id,'notice');
$general_options=CompressX_Options::get_general_settings();
$quality_options=CompressX_Options::get_quality_option();
$options=array_merge($general_options,$quality_options);
CompressX_Image_Meta_V2::update_image_progressing($attachment_id);
$image=new Compressx_Image($attachment_id,$options);
$file_path = get_attached_file( $attachment_id );
if(empty($file_path))
{
$this->WriteLog('Image:'.$attachment_id.' failed. Error: failed to get get_attached_file','notice');
$error='Image:'.$attachment_id.' failed. Error: failed to get get_attached_file';
CompressX_Image_Meta_V2::update_image_failed($attachment_id,$error);
CompressX_Image_Meta_V2::delete_image_progressing($attachment_id);
CompressX_Image_Meta_V2::update_image_meta_status($attachment_id,'failed');
$ret['result']='success';
return $ret;
}
if(!file_exists($file_path))
{
$this->WriteLog('Image:'.$attachment_id.' failed. Error: file not exists '.$file_path,'notice');
$error='Image:'.$attachment_id.' failed. Error: file not exists '.$file_path;
CompressX_Image_Meta_V2::update_image_failed($attachment_id,$error);
CompressX_Image_Meta_V2::delete_image_progressing($attachment_id);
CompressX_Image_Meta_V2::update_image_meta_status($attachment_id,'failed');
$ret['result']='success';
return $ret;
}
$image->resize();
if($image->convert())
{
CompressX_Image_Meta_V2::delete_image_progressing($attachment_id);
CompressX_Image_Meta_V2::update_image_meta_status($attachment_id,'optimized');
do_action('compressx_purge_cache');
do_action('compressx_after_optimize_image',$attachment_id);
}
else
{
CompressX_Image_Meta_V2::delete_image_progressing($attachment_id);
CompressX_Image_Meta_V2::update_image_meta_status($attachment_id,'failed');
}
$ret['result']='success';
return $ret;
}
public function WriteLog($log,$type)
{
if (is_a($this->log, 'CompressX_Log'))
{
$this->log->WriteLog($log,$type);
}
else
{
$this->log=new CompressX_Log();
$this->log->OpenLogFile();
$this->log->WriteLog($log,$type);
}
}
public function is_image_processing_failed($post_id)
{
$status=CompressX_Image_Meta_V2::get_image_meta_status($post_id);
if(empty($status))
{
return false;
}
else
{
if($status=='failed')
{
return true;
}
else
{
return false;
}
}
}
public function is_image_progressing($post_id)
{
$progressing=CompressX_Image_Meta_V2::get_image_progressing($post_id);
if(empty($progressing))
{
return false;
}
else
{
$current_time=time();
if(($current_time-$progressing)>180)
{
return false;
}
else
{
return true;
}
}
}
}
@@ -0,0 +1,427 @@
<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
class CompressX_Media_Replace
{
public $options;
public $sizes;
public $current_file_path;
public function replace($attachment_id,$replace_path,$options)
{
$this->init_options($options);
if (! wp_attachment_is_image($attachment_id))
{
$ret['result']="failed";
$ret['error']="Attachment is not an image";
return $ret;
}
$ret = [];
if (!file_exists($replace_path))
{
$ret['result']="failed";
$ret['error']="Replace image file not found";
return $ret;
}
$original_file_path = wp_get_original_image_path( $attachment_id );
if (!file_exists($original_file_path))
{
$ret['result']="failed";
$ret['error']="Original image file not found";
return $ret;
}
$old_attachment_meta = wp_get_attachment_metadata($attachment_id);
if (! is_array($old_attachment_meta))
{
$old_attachment_meta = [];
}
$ret = $this->replace_original_image($original_file_path, $replace_path);
if ($ret['result']=='failed')
{
return $ret;
}
$ret = $this->build_new_size_metadata($old_attachment_meta);
if ($ret['result']=='failed')
{
return $ret;
}
$new_size_meta=$ret['new_size_meta'];
$this->cleanup_old_derivatives($original_file_path,$old_attachment_meta);
$ret = $this->generate_and_update_metadata($attachment_id, $original_file_path ,$new_size_meta);
if ($ret['result']=='failed')
{
return $ret;
}
$new_attachment_meta = wp_get_attachment_metadata($attachment_id);
if ( !empty( $new_attachment_meta['original_image'] ) )
{
$pathinfo = pathinfo($original_file_path);
$scaled = $pathinfo['dirname'] . '/' . $pathinfo['filename'] . '-scaled.' . ($pathinfo['extension'] ?? '');
if (!empty($pathinfo['extension']) && file_exists($scaled))
{
update_attached_file($attachment_id, $scaled);
}
}
else
{
update_attached_file($attachment_id, $original_file_path);
}
wp_delete_file($replace_path);
$ret['result']='success';
return $ret;
}
public function init_options($options)
{
$this->options = wp_parse_args($options, [
'thumbnail_generation' => 'default_fill',
'backup' => false,
]);
}
protected function rename( $source, $destination )
{
if ( ! file_exists( $source ) ) {
return false;
}
global $wp_filesystem;
if ( empty( $wp_filesystem ) ) {
require_once ABSPATH . 'wp-admin/includes/file.php';
WP_Filesystem();
}
if ( empty( $wp_filesystem ) ) {
return false;
}
return $wp_filesystem->move( $source, $destination, true );
}
protected function is_writable( $dir ) {
global $wp_filesystem;
if ( empty( $wp_filesystem ) ) {
require_once ABSPATH . 'wp-admin/includes/file.php';
WP_Filesystem();
}
if ( empty( $wp_filesystem ) ) {
return false;
}
return $wp_filesystem->is_writable( $dir );
}
protected function replace_original_image($original_file_path, $replace_path)
{
$ret = ['result' => 'failed'];
$dir = dirname($original_file_path);
if (!is_dir($dir) || !$this->is_writable($dir))
{
$ret['error'] = 'Original directory not writable';
return $ret;
}
if (!file_exists($original_file_path)) {
$ret['error'] = 'Original image file not found before swap';
return $ret;
}
if (!file_exists($replace_path)) {
$ret['error'] = 'Replace image file not found';
return $ret;
}
// 1) move replace file into same directory first (atomic rename needs same FS)
$new_temp = trailingslashit($dir) . basename($original_file_path) . '.__new_' . wp_generate_password(6, false, false);
if (!$this->rename($replace_path, $new_temp))
{
if (!@copy($replace_path, $new_temp))
{
$ret['error'] = 'Failed to move replace file into target directory';
return $ret;
}
@wp_delete_file($replace_path);
}
// 2) old -> bak
$bak = trailingslashit($dir) . basename($original_file_path) . '.__bak_' . gmdate('Ymd_His');
if (!$this->rename($original_file_path, $bak))
{
@wp_delete_file($new_temp);
$ret['error'] = 'Failed to create bak file (rename old -> bak failed)';
return $ret;
}
// 3) new_temp -> old
if (!$this->rename($new_temp, $original_file_path))
{
// rollback immediately
$this->rename($bak, $original_file_path);
@wp_delete_file($new_temp);
$ret['error'] = 'Failed to replace original file (rename new -> old failed)';
return $ret;
}
@wp_delete_file($bak);
$ret['result'] = 'success';
return $ret;
}
protected function build_new_size_metadata($old_attachment_meta)
{
$ret = ['result' => 'failed'];
$thumbnail_generation = (string) $this->options['thumbnail_generation'];
// 1) Collect "current registered sizes"
$registered = function_exists('wp_get_registered_image_subsizes')
? wp_get_registered_image_subsizes()
: [];
$plan_new = [];
foreach ($registered as $name => $cfg)
{
$w = isset($cfg['width']) ? (int) $cfg['width'] : 0;
$h = isset($cfg['height']) ? (int) $cfg['height'] : 0;
// drop sizes with no constraint
if ($w <= 0 && $h <= 0)
{
continue;
}
$plan_new[$name] = [
'width' => max(0, $w),
'height' => max(0, $h),
'crop' => isset($cfg['crop']) ? (bool) $cfg['crop'] : false
];
}
// 2) Collect "old sizes" from attachment metadata
$plan_old = [];
if (isset($old_attachment_meta['sizes']) && is_array($old_attachment_meta['sizes']))
{
foreach ($old_attachment_meta['sizes'] as $name => $data)
{
if (!is_array($data))
{
continue;
}
$w = isset($data['width']) ? (int) $data['width'] : 0;
$h = isset($data['height']) ? (int) $data['height'] : 0;
if ($w <= 0 || $h <= 0)
{
continue;
}
// Old meta does not store crop; we'll decide later by strategy.
$plan_old[$name] = [
'width' => $w,
'height' => $h,
'crop' => true
];
}
}
// 3) Build final plan by mode
if ($thumbnail_generation === 'match_original')
{
$plan = $plan_old;
}
//elseif ($thumbnail_generation === 'force_old')
//{
// $plan = $plan_old;
//}
elseif ($thumbnail_generation === 'default_fill')
{
$plan = $plan_new;
foreach ($plan_old as $name => $cfg)
{
if (isset($plan[$name]))
{
$w = $plan[$name]['width'];
$h = $plan[$name]['height'];
if ($w != $cfg['width']||$h != $cfg['height'])
{
$plan[$name] = $cfg;
}
}
else
{
$plan[$name] = $cfg;
}
}
}
else
{
$ret['error'] = 'Invalid mode';
return $ret;
}
//Final validation
foreach ($plan as $name => $cfg)
{
$w = $cfg['width'];
$h = $cfg['height'];
if ($w == 0 || $h == 0)
{
$plan[$name]['crop']=false;
}
}
$ret['result'] = 'success';
$ret['new_size_meta'] = $plan;
return $ret;
}
protected function generate_and_update_metadata($attachment_id, $original_file_path, $new_size_meta)
{
$ret = ['result' => 'failed'];
if (!file_exists($original_file_path))
{
$ret['error'] = 'Original image file not found';
return $ret;
}
$this->sizes=$new_size_meta;
$this->current_file_path=$original_file_path;
add_filter( 'intermediate_image_sizes_advanced', array( $this, 'regen_thumbnails_sizes' ), 10, 2 );
if ( ! function_exists( 'wp_generate_attachment_metadata' ) )
{
include(ABSPATH . 'wp-admin/includes/image.php');
}
$new_metadata = wp_generate_attachment_metadata( $attachment_id, $original_file_path );
remove_filter( 'intermediate_image_sizes_advanced', array( $this, 'regen_thumbnails_sizes' ), 10 );
wp_update_attachment_metadata( $attachment_id, $new_metadata );
$ret['result']='success';
return $ret;
}
public function regen_thumbnails_sizes($sizes, $fullsize_metadata)
{
if (!is_array($this->sizes) || empty($this->sizes))
{
return $sizes;
}
$full_w = isset($fullsize_metadata['width']) ? (int)$fullsize_metadata['width'] : 0;
$full_h = isset($fullsize_metadata['height']) ? (int)$fullsize_metadata['height'] : 0;
if ($full_w <= 0 || $full_h <= 0)
{
// Can't reason; fallback to WP sizes
return $sizes;
}
$new_sizes = [];
foreach ( $this->sizes as $size => $size_data )
{
if (!is_array($size_data)) {
continue;
}
$tw = isset($size_data['width']) ? (int)$size_data['width'] : 0;
$th = isset($size_data['height']) ? (int)$size_data['height'] : 0;
$crop = !empty($size_data['crop']);
// invalid
if ($tw <= 0 && $th <= 0) {
continue;
}
// if any side is 0, force non-crop (consistent with your build step)
if ($tw === 0 || $th === 0) {
$crop = false;
}
// Use WP core helper to decide if thumbnail can be generated without upscaling / invalid dims
$dims = image_resize_dimensions(
$full_w,
$full_h,
($tw > 0 ? $tw : null),
($th > 0 ? $th : null),
$crop
);
if (!$dims)
{
// skip this size (missing)
continue;
}
$new_sizes[$size] = [
'width' => ($tw > 0 ? $tw : null),
'height' => ($th > 0 ? $th : null),
'crop' => $crop,
];
}
return $new_sizes;
}
protected function cleanup_old_derivatives($original_file_path,$old_attachment_meta)
{
$ret = ['result' => 'success'];
$dir = trailingslashit(dirname($original_file_path));
// 1) Delete sizes from old meta
if (isset($old_attachment_meta['sizes']) && is_array($old_attachment_meta['sizes']))
{
foreach ($old_attachment_meta['sizes'] as $size_name => $data)
{
if (!is_array($data) || empty($data['file']))
{
continue;
}
$file = $dir . wp_basename($data['file']);
if (file_exists($file))
{
@wp_delete_file($file);
}
}
}
if ( !empty( $old_attachment_meta['original_image'] ) )
{
$pathinfo = pathinfo($original_file_path);
$scaled = $pathinfo['dirname'] . '/' . $pathinfo['filename'] . '-scaled.' . ($pathinfo['extension'] ?? '');
if (!empty($pathinfo['extension']) && file_exists($scaled))
{
@wp_delete_file($scaled);
}
}
return $ret;
}
}
@@ -0,0 +1,374 @@
<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
class CompressX_Options
{
public static function get_option($option_name,$default_value=false)
{
if(is_multisite())
{
return get_blog_option(get_main_site_id(),$option_name,$default_value);
}
else
{
return get_option($option_name,$default_value);
}
}
public static function update_option($option_name,$option_value)
{
if(is_multisite())
{
return update_blog_option(get_main_site_id(),$option_name,$option_value);
}
else
{
return update_option($option_name,$option_value,false);
}
}
public static function delete_option($option_name)
{
if(is_multisite())
{
return delete_blog_option(get_main_site_id(),$option_name);
}
else
{
return delete_option($option_name);
}
}
public static function get_general_settings()
{
$options=self::get_option('compressx_general_settings',array());
$general_options=array();
$general_options['remove_exif']=isset($options['remove_exif'])?$options['remove_exif']:false;
$general_options['auto_remove_larger_format']=isset($options['auto_remove_larger_format'])?$options['auto_remove_larger_format']:true;
$general_options['converter_images_pre_request']=isset($options['converter_images_pre_request'])?$options['converter_images_pre_request']:5;
$general_options['convert_to_webp']=CompressX_Image_Method::get_convert_to_webp();
$general_options['convert_to_avif']=CompressX_Image_Method::get_convert_to_avif();
$general_options['compressed_webp']=CompressX_Image_Method::get_compress_to_webp();
$general_options['compressed_avif']=CompressX_Image_Method::get_compress_to_avif();
$general_options['converter_method']=CompressX_Image_Method::get_converter_method();
if(isset($options['resize']))
{
$general_options['resize_enable']= isset($options['resize']['enable'])?$options['resize']['enable']:true;
$general_options['resize_width']=isset( $options['resize']['width'])? $options['resize']['width']:2560;
$general_options['resize_height']=isset( $options['resize']['height'])? $options['resize']['height']:2560;
}
else
{
$general_options['resize_enable']= true;
$general_options['resize_width']=2560;
$general_options['resize_height']=2560;
}
$general_options['skip_size']=isset($options['skip_size'])?$options['skip_size']:array();
$general_options['exclude_png']=isset($options['exclude_png'])?$options['exclude_png']:false;
$general_options['exclude_png_webp']=isset($options['exclude_png_webp'])?$options['exclude_png_webp']:false;
$general_options['exclude_jpg_avif']=isset($options['exclude_jpg_avif'])?$options['exclude_jpg_avif']:false;
$general_options['exclude_jpg_webp']=isset($options['exclude_jpg_webp'])?$options['exclude_jpg_webp']:false;
return $general_options;
}
public static function get_quality_option()
{
$quality_options=self::get_option('compressx_quality',array());
$quality_options['quality']=isset($quality_options['quality'])?$quality_options['quality']:'lossy';
if($quality_options['quality']=="custom")
{
$quality_options['quality_webp']=isset($quality_options['quality_webp'])?$quality_options['quality_webp']: 80;
$quality_options['quality_avif']=isset($quality_options['quality_avif'])?$quality_options['quality_avif']: 60;
}
return $quality_options;
}
public static function set_default_compress_server()
{
if( function_exists( 'gd_info' ) )
{
self::update_option('compressx_converter_method','gd');
return 'gd';
}
else if ( extension_loaded( 'imagick' ) && class_exists( '\Imagick' ) )
{
self::update_option('compressx_converter_method','imagick');
return 'imagick';
}
else
{
return false;
}
}
public static function set_default_output_format_webp()
{
$converter_method=self::get_option('compressx_converter_method',false);
if(empty($converter_method))
{
$converter_method=self::set_default_compress_server();
}
if($converter_method=="gd")
{
if(CompressX_Image_Opt_Method::is_support_gd_webp())
{
self::update_option('compressx_output_format_webp',1);
return 1;
}
else
{
self::update_option('compressx_output_format_webp',0);
return 0;
}
}
else if($converter_method=="imagick")
{
if(CompressX_Image_Opt_Method::is_support_imagick_webp())
{
self::update_option('compressx_output_format_webp',1);
return 1;
}
else
{
self::update_option('compressx_output_format_webp',0);
return 0;
}
}
else
{
return false;
}
}
public static function set_default_output_format_avif()
{
$converter_method=self::get_option('compressx_converter_method',false);
if(empty($converter_method))
{
$converter_method=self::set_default_compress_server();
}
if($converter_method=="gd")
{
if(CompressX_Image_Opt_Method::is_support_gd_avif())
{
self::update_option('compressx_output_format_avif',1);
return 1;
}
else
{
self::update_option('compressx_output_format_avif',0);
return 0;
}
}
else if($converter_method=="imagick")
{
if(CompressX_Image_Opt_Method::is_support_imagick_avif())
{
if(CompressX_Image_Opt_Method::check_imagick_avif())
{
self::update_option('compressx_output_format_avif',1);
return 1;
}
else
{
self::update_option('compressx_output_format_avif',0);
return 0;
}
}
else
{
self::update_option('compressx_output_format_avif',0);
return 0;
}
}
else
{
return false;
}
}
public static function get_excludes()
{
$excludes=self::get_option('compressx_media_excludes',array());
$exclude_regex_folder=array();
if(!empty($excludes))
{
foreach ($excludes as $item)
{
$exclude_regex_folder[]='#'.preg_quote(CompressX_Image_Method::transfer_path($item), '/').'#';
}
}
return $exclude_regex_folder;
}
public static function get_compress_quality($type,$options)
{
if($options['quality']=="custom")
{
if($type=='webp')
{
$quality=isset($options['quality_webp'])?$options['quality_webp']: 80;
}
else
{
$quality=isset($options['quality_avif'])?$options['quality_avif']: 60;
}
}
else if($options['quality']=='lossless')
{
$quality=99;
}
else if($options['quality']=='lossy_minus')
{
$quality=90;
}
else if($options['quality']=='lossy')
{
$quality=80;
}
else if($options['quality']=='lossy_plus')
{
$quality=70;
}
else if($options['quality']=='lossy_super')
{
$quality=60;
}
else
{
$quality=80;
}
return $quality;
}
public static function get_webp_quality($options)
{
if(!isset($options['quality']))
{
return 80;
}
if($options['quality']=="custom")
{
$quality=isset($options['quality_webp'])?$options['quality_webp']: 80;
}
else if($options['quality']=='lossless')
{
$quality=99;
}
else if($options['quality']=='lossy_minus')
{
$quality=90;
}
else if($options['quality']=='lossy')
{
$quality=80;
}
else if($options['quality']=='lossy_plus')
{
$quality=70;
}
else if($options['quality']=='lossy_super')
{
$quality=60;
}
else
{
$quality=80;
}
return $quality;
}
public static function get_avif_quality($options)
{
if(!isset($options['quality']))
{
return 60;
}
if($options['quality']=="custom")
{
$quality=isset($options['quality_avif'])?$options['quality_avif']: 60;
}
else if($options['quality']=='lossless')
{
$quality=80;
}
else if($options['quality']=='lossy_minus')
{
$quality=75;
}
else if($options['quality']=='lossy')
{
$quality=60;
}
else if($options['quality']=='lossy_plus')
{
$quality=50;
}
else if($options['quality']=='lossy_super')
{
$quality=40;
}
else
{
$quality=60;
}
return $quality;
}
public static function get_default_advanced_woocommerce_quality_option()
{
$list= [
// WooCommerce
'wc_product_featured_images' => ['enable'=>false,'webp' => 90, 'avif' => 65],
'wc_product_gallery_images' => ['enable'=>false,'webp' => 80, 'avif' => 55],
'wc_variation_images' => ['enable'=>false,'webp' => 80, 'avif' => 55],
'wc_product_category_images' => ['enable'=>false,'webp' => 75, 'avif' => 50],
];
return $list;
}
public static function get_default_advanced_quality_option()
{
$list= [
// core
'site_logo' => ['enable'=>false,'webp' => 90, 'avif' => 80],
'header_background' => ['enable'=>false,'webp' => 85, 'avif' => 60],
'featured_post' => ['enable'=>false,'webp' => 88, 'avif' => 62],
'featured_page' => ['enable'=>false,'webp' => 88, 'avif' => 62],
'sidebar_widget' => ['enable'=>false,'webp' => 75, 'avif' => 50],
'acf_image_fields' => ['enable'=>false,'webp' => 80, 'avif' => 55],
];
return $list;
}
public static function get_interface_version()
{
return "v2";
/*
$options = self::get_option('compressx_general_settings', array());
if(empty($options))
{
return "v2";
}
return isset($options['interface_version']) ? $options['interface_version'] : 'v2';*/
}
}
@@ -0,0 +1,666 @@
<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
class CompressX_Picture_Load
{
public function __construct()
{
if ( is_multisite() )
{
return;
}
$options=CompressX_Options::get_option('compressx_general_settings',array());
$image_load=isset($options['image_load'])?$options['image_load']:'htaccess';
if ($image_load == "htaccess"||$image_load == "compat_htaccess")
{
return;
}
if ( is_admin() || is_customize_preview() )
{
return;
}
if ( defined( 'DOING_AJAX' ) && DOING_AJAX )
{
return;
}
if ( defined( 'DOING_CRON' ) && DOING_CRON )
{
return;
}
add_action( 'template_redirect', [ $this, 'start_content_process' ], 1000 );
add_action( 'wp_enqueue_scripts', array( $this, 'overrides_main_style' ), 9999 );
}
public function overrides_main_style()
{
$current_active_theme = get_stylesheet();
if($current_active_theme === 'Divi')
{
$style = '';
$logo_height = esc_attr( et_get_option( 'logo_height', '54' ) );
$style .= "
picture#logo {
display: inherit;
}
picture#logo source, picture#logo img {
width: auto;
max-height: {$logo_height}%;
vertical-align: middle;
}
@media (min-width: 981px) {
.et_vertical_nav #main-header picture#logo source,
.et_vertical_nav #main-header picture#logo img {
margin-bottom: 28px;
}
}
";
if ( ! empty( $style ) ) {
wp_add_inline_style( 'divi-style', $style );
}
}
}
public function start_content_process()
{
ob_start( [ $this, 'replace_picture_tag' ] );
}
public function replace_picture_tag($content)
{
$images = $this->get_images( $content );
if ( empty( $images ) )
{
return $content;
}
foreach ( $images as $image )
{
$tag = $this->build_picture_tag( $image );
$content = str_replace( $image['tag'], $tag, $content );
}
return $content;
}
protected function get_images( $content )
{
if ( preg_match( '/(?=<body).*<\/body>/is', $content, $body ) )
{
$content = $body[0];
}
$content = preg_replace( '/<!--(.*)-->/Uis', '', $content );
$content = preg_replace('#<noscript(.*?)>(.*?)</noscript>#is', '', $content);
if ( ! preg_match_all( '/<img\s.*>/isU', $content, $matches ) )
{
return array();
}
$images = array_map(array($this, 'process_image'), $matches[0] );
$images = array_filter( $images );
if ( ! $images || ! is_array( $images ) )
{
return array();
}
return $images;
}
public function process_image($image)
{
$attributes=$this->get_attribute($image);
$src=$this->get_src($attributes);
$srcset=$this->get_srcset($attributes);
$style=$this->get_style($attributes);
if ( empty($src)&&empty($srcset) )
{
return false;
}
$data=array(
'tag' => $image,
'attributes' => $attributes,
'src' => $src,
'srcset' => $srcset,
'style' => $style,
);
return $data;
}
protected function build_picture_tag( $image )
{
$to_remove = array(
'alt' => '',
'height' => '',
'width' => '',
'data-lazy-src' => '',
'data-src' => '',
'src' => '',
'data-lazy-srcset' => '',
'data-srcset' => '',
'srcset' => '',
'data-lazy-sizes' => '',
'data-sizes' => '',
'sizes' => '',
'style' => '',
);
$attributes = array_diff_key( $image['attributes'], $to_remove );
$output = '<picture' . $this->picture_build_attributes( $attributes ) . ">";
$output .= $this->build_source_tag_ex( $image );
$output .= $this->build_img_tag( $image );
$output .= "</picture>";
return $output;
}
protected function picture_build_attributes( $attributes )
{
if ( ! $attributes || ! is_array( $attributes ) )
{
return '';
}
$out = '';
foreach ( $attributes as $attribute => $value )
{
$out .= ' ' . $attribute . '="' . esc_attr( $value ) . '"';
}
return $out;
}
protected function build_attributes( $attributes )
{
if ( ! $attributes || ! is_array( $attributes ) )
{
return '';
}
$out = '';
foreach ( $attributes as $attribute => $value )
{
$out .= ' ' . $attribute . '="' . esc_attr( $value ) . '"';
}
return $out;
}
protected function build_source_attributes( $image, $image_type )
{
$mime_type = '';
$url = '';
switch ( $image_type ) {
case 'webp':
$mime_type = 'image/webp';
$url = 'webp_url';
break;
case 'avif':
$mime_type = 'image/avif';
$url = 'avif_url';
break;
}
$srcset_source = ! empty( $image['srcset']['srcset_attr'] ) ? $image['srcset']['srcset_attr'] : $image['src']['src_attr'] . 'set';
$attributes = [
'type' => $mime_type,
$srcset_source => array(),
];
/*
if ( ! empty( $image['srcset'] ) )
{
foreach ( $image['srcset'] as $srcset )
{
if ( empty( $srcset[ $url ] ) )
{
continue;
}
$attributes[ $srcset_source ][] = $srcset[ $url ] . ' ' . $srcset['descriptor'];
}
}*/
if ( ! empty( $image['srcset']['srcs'] ) )
{
foreach ( $image['srcset']['srcs'] as $srcset )
{
if (! empty( $srcset[$url] ) )
{
$attributes[ $srcset_source ][] = $srcset[$url] . ' ' . $srcset['descriptor'];
}
}
}
else if ( ! empty( $image['srcset'] ) )
{
foreach ( $image['srcset'] as $srcset )
{
if ( empty( $srcset[ $url ] ) )
{
continue;
}
$attributes[ $srcset_source ][] = $srcset[ $url ] . ' ' . $srcset['descriptor'];
}
}
if ( empty( $attributes[ $srcset_source ] ) && empty( $image['src'][ $url ] ) ) {
return [];
}
if ( empty( $attributes[ $srcset_source ] ) ) {
$attributes[ $srcset_source ][] = $image['src'][ $url ];
}
$attributes[ $srcset_source ] = implode( ', ', $attributes[ $srcset_source ] );
foreach ( [ 'data-lazy-srcset', 'data-srcset', 'srcset' ] as $srcset_attr ) {
if ( ! empty( $image['attributes'][ $srcset_attr ] ) && $srcset_attr !== $srcset_source ) {
$attributes[ $srcset_attr ] = $image['attributes'][ $srcset_attr ];
}
}
if ( 'srcset' !== $srcset_source && empty( $attributes['srcset'] ) && ! empty( $image['attributes']['src'] ) ) {
// Lazyload: the "src" attr should contain a placeholder (a data image or a blank.gif ).
$attributes['srcset'] = $image['attributes']['src'];
}
foreach ( [ 'data-lazy-sizes', 'data-sizes', 'sizes' ] as $sizes_attr ) {
if ( ! empty( $image['attributes'][ $sizes_attr ] ) ) {
$attributes[ $sizes_attr ] = $image['attributes'][ $sizes_attr ];
}
}
return $attributes;
}
protected function build_source_tag_ex( $image )
{
$source = '';
foreach ( [ 'avif', 'webp' ] as $image_type )
{
$attributes = $this->build_source_attributes( $image, $image_type );
if ( empty( $attributes ) ) {
continue;
}
$source .= '<source' . $this->build_attributes( $attributes ) . "/>";
}
return $source;
}
protected function build_img_tag( $image )
{
/*$to_remove = array(
'class' => '',
'id' => '',
'style' => '',
'title' => '',
);*/
$to_remove = array(
'id' => '',
'title' => '',
);
$attributes = array_diff_key( $image['attributes'], $to_remove );
return '<img' . $this->build_attributes( $attributes ) . "/>";
}
public function get_attribute($image)
{
if (function_exists("mb_convert_encoding"))
{
$image = mb_encode_numericentity($image, [0x80, 0x10FFFF, 0, ~0], 'UTF-8');
//$image = mb_convert_encoding($image, 'HTML-ENTITIES', 'UTF-8');
}
if (class_exists('DOMDocument'))
{
$dom = new \DOMDocument();
@$dom->loadHTML($image);
$image = $dom->getElementsByTagName('img')->item(0);
$attributes = array();
/* This can happen with mismatches, or extremely malformed HTML.
In customer case, a javascript that did for (i<imgDefer) --- </script> */
if (! is_object($image))
return false;
foreach ($image->attributes as $attr)
{
$attributes[$attr->nodeName] = $attr->nodeValue;
}
return $attributes;
}
else
{
$atts_pattern = '/(?<name>[^\s"\']+)\s*=\s*(["\'])\s*(?<value>.*?)\s*\2/s';
if ( ! preg_match_all( $atts_pattern, $image, $tmp_attributes, PREG_SET_ORDER ) )
{
return false;
}
$attributes = array();
foreach ( $tmp_attributes as $attribute )
{
$attributes[ $attribute['name'] ] = $attribute['value'];
}
return $attributes;
}
}
public function get_src($attributes)
{
$src_source = false;
$data_tag=array( 'data-lazy-src','data-src', 'src');
foreach ( $data_tag as $src_attr )
{
if ( ! empty( $attributes[ $src_attr ] ) )
{
$src_source = $src_attr;
break;
}
}
if ( ! $src_source )
{
// No src attribute.
return false;
}
$extensions = array(
'jpg|jpeg|jpe' => 'image/jpeg',
'png' => 'image/png',
'webp' => 'image/webp',
'avif' => 'image/avif',
);
$extensions = array_keys( $extensions );
$extensions = implode( '|', $extensions );
if ( ! preg_match( '@^(?<src>(?:(?:https?:)?//|/).+\.(?<extension>' . $extensions . '))(?<query>\?.*)?$@i', $attributes[ $src_source ], $src ) )
{
// Not a supported image format.
return false;
}
$url = $src['src'];
$path_exist=false;
$exist_ret=$this->webp_exist($url);
if($exist_ret['result']=='success')
{
$path_exist=true;
$ret['webp_exist']=true;
$ret['webp_path']=$exist_ret['path'];
$exist_ret['url'] .= ! empty( $src['query'] ) ? $src['query'] : '';
$ret['webp_url']=$exist_ret['url'];
}
$exist_ret=$this->avif_exist($url);
if($exist_ret['result']=='success')
{
$path_exist=true;
$ret['avif_exist']=true;
$ret['avif_path']=$exist_ret['path'];
$exist_ret['url'] .= ! empty( $src['query'] ) ? $src['query'] : '';
$ret['avif_url']=$exist_ret['url'];
}
if(!$path_exist)
{
return false;
}
$ret['src']=$attributes[ $src_source ];
$ret['src_attr']=$src_source;
return $ret;
}
public function webp_exist($url)
{
$upload=wp_upload_dir();
if ( stripos( $url, $upload['baseurl'] ) === 0 )
{
$path = str_replace($upload['baseurl'],$upload['basedir'],$url);
$upload_root=CompressX_Image_Method::transfer_path($upload['basedir']);
$attachment_dir=$path;
$attachment_dir=CompressX_Image_Method::transfer_path($attachment_dir);
$sub_dir=str_replace($upload_root,'',$attachment_dir);
$sub_dir=untrailingslashit($sub_dir);
$compressx_path=WP_CONTENT_DIR."/compressx-nextgen/uploads".$sub_dir.'.webp';
$path = str_replace($upload['baseurl'],'',$url);
$url = content_url().'/compressx-nextgen/uploads'.$path.'.webp';;
}
else
{
$compressx_path='';
$url='';
}
if(file_exists($compressx_path))
{
$ret['result']='success';
$ret['url']=$url;
$ret['path']=$compressx_path;
return $ret;
}
else
{
$ret['result']='failed';
return $ret;
}
}
public function avif_exist($url)
{
$upload=wp_upload_dir();
if ( stripos( $url, $upload['baseurl'] ) === 0 )
{
$path = str_replace($upload['baseurl'],$upload['basedir'],$url);
$upload_root=CompressX_Image_Method::transfer_path($upload['basedir']);
$attachment_dir=$path;
$attachment_dir=CompressX_Image_Method::transfer_path($attachment_dir);
$sub_dir=str_replace($upload_root,'',$attachment_dir);
$sub_dir=untrailingslashit($sub_dir);
$compressx_path=WP_CONTENT_DIR."/compressx-nextgen/uploads".$sub_dir.'.avif';
$path = str_replace($upload['baseurl'],'',$url);
$url = content_url().'/compressx-nextgen/uploads'.$path.'.avif';
}
else
{
$compressx_path='';
$url='';
}
if(file_exists($compressx_path))
{
$ret['result']='success';
$ret['url']=$url;
$ret['path']=$compressx_path;
return $ret;
}
else
{
$ret['result']='failed';
return $ret;
}
}
public function get_srcset($attributes)
{
$srcset_source = false;
$upload=wp_upload_dir();
$data_tag=array('data-lazy-srcset', 'data-srcset', 'srcset');
$extensions = array(
'jpg|jpeg|jpe' => 'image/jpeg',
'png' => 'image/png',
//'gif' => 'image/gif',
);
$extensions = array_keys( $extensions );
$extensions = implode( '|', $extensions );
foreach ( $data_tag as $srcset_attr )
{
if ( ! empty( $attributes[ $srcset_attr ] ) )
{
$srcset_source = $srcset_attr;
break;
}
}
$ret['srcset_attr']=$srcset_source;
$ret['srcs']=array();
if ( $srcset_source )
{
$srcset = explode( ',', $attributes[ $srcset_source ] );
foreach ( $srcset as $srcs )
{
$srcs = preg_split( '/\s+/', trim( $srcs ) );
if ( count( $srcs ) > 2 )
{
$descriptor = array_pop( $srcs );
$srcs = array(implode( ' ', $srcs ), $descriptor);
}
if ( empty( $srcs[1] ) )
{
$srcs[1] = '1x';
}
if ( ! preg_match( '@^(?<src>(?:https?:)?//.+\.(?<extension>' . $extensions . '))(?<query>\?.*)?$@i', $srcs[0], $src ) )
{
continue;
}
$url = $src['src'];
$path_exist=false;
$exist_ret=$this->webp_exist($url);
if($exist_ret['result']=='success')
{
$path_exist=true;
$ret['webp_exist']=true;
$ret['webp_path']=$exist_ret['path'];
$exist_ret['url'] .= ! empty( $src['query'] ) ? $src['query'] : '';
$ret['webp_url']=$exist_ret['url'];
$tmp_srcset=array(
'url' => $srcs[0],
'descriptor' => $srcs[1],
'webp_exists'=>$path_exist
);
$tmp_srcset['webp_path']=$ret['webp_path'];
$tmp_srcset['webp_url']=$ret['webp_url'];
$ret['srcs'][]=$tmp_srcset;
}
$exist_ret=$this->avif_exist($url);
if($exist_ret['result']=='success')
{
$path_exist=true;
$ret['avif_exist']=true;
$ret['avif_path']=$exist_ret['path'];
$exist_ret['url'] .= ! empty( $src['query'] ) ? $src['query'] : '';
$ret['avif_url']=$exist_ret['url'];
$tmp_srcset=array(
'url' => $srcs[0],
'descriptor' => $srcs[1],
'webp_exists'=>$path_exist
);
$tmp_srcset['avif_path']=$ret['avif_path'];
$tmp_srcset['avif_url']=$ret['avif_url'];
$ret['srcs'][]=$tmp_srcset;
}
/*
if($path_exist)
{
$tmp_srcset=array(
'url' => $srcs[0],
'descriptor' => $srcs[1],
'webp_exists'=>$path_exist
);
$tmp_srcset['webp_path']=$ret['webp_path'];
$tmp_srcset['webp_url']=$ret['webp_url'];
$ret['srcs'][]=$tmp_srcset;
}
else
{
//$path_exist=false;
continue;
}*/
}
}
else
{
return false;
}
if(empty($ret['srcs']))
return false;
return $ret;
}
public function get_style($attributes)
{
$style_attr='style';
if ( empty( $attributes[ $style_attr ] ) )
{
// No style.
return false;
}
return $attributes[ $style_attr ];
}
}
@@ -0,0 +1,261 @@
<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
class CompressX_Rewrite_Checker
{
public $og_test_file;
public $og_test_webp_file;
public $test_file;
public $test_webp_file;
public function __construct()
{
$this->og_test_file='/includes/assets/compressx_test.png';
$this->og_test_webp_file='/includes/assets/compressx_test.png.webp';
$this->test_file='compressx_test.png';
$this->test_webp_file='compressx_test.png.webp';
}
public function test()
{
$upload_dir = wp_upload_dir();
$path = $upload_dir['basedir'] . '/' . $this->test_file;
if (!file_exists($path)) {
$og_path = COMPRESSX_DIR . $this->og_test_file;
copy($og_path, $path);
}
$path2 = WP_CONTENT_DIR . '/compressx-nextgen/uploads/' . $this->test_webp_file;
if (!file_exists($path2)) {
$og_path = COMPRESSX_DIR . $this->og_test_webp_file;
copy($og_path, $path2);
}
$og_size = filesize($path);
$test_size = $this->get_test_size();
if ($test_size === false)
{
return false;
}
else if($test_size===401)
{
return true;
}
if ($og_size > $test_size)
{
return true;
}
else
{
if($this->is_cf_cached())
{
return true;
}
return false;
}
}
public function is_cf_cached()
{
$upload_dir = wp_upload_dir();
$url=$upload_dir['baseurl'].'/'. $this->test_file;
$headers['Accept']='image/webp,image/*';
foreach ( wp_get_nocache_headers() as $header_key => $header_value )
{
$headers[$header_key] =$header_value;
}
$args['headers']= $headers;
$response=wp_remote_request($url,$args);
if(!is_wp_error($response))
{
if(isset($response['headers']['cf-cache-status']))
{
if($response['headers']['cf-cache-status']=='HIT')
{
return true;
}
}
return false;
}
else
{
return false;
}
}
public function test_ex()
{
$upload_dir = wp_upload_dir();
$path = $upload_dir['basedir'] . '/' . $this->test_file;
if (!file_exists($path)) {
$og_path = COMPRESSX_DIR . $this->og_test_file;
copy($og_path, $path);
}
$path2 = WP_CONTENT_DIR . '/compressx-nextgen/uploads/' . $this->test_webp_file;
if (!file_exists($path2)) {
$og_path = COMPRESSX_DIR . $this->og_test_webp_file;
copy($og_path, $path2);
}
$og_size = filesize($path);
$ret = $this->get_test_size_ex();
if ($ret['result'] === 'success')
{
$test_size=$ret['size'];
if ($og_size > $test_size)
{
$ret['result']='success';
return $ret;
}
else
{
if($this->is_cf_cached())
{
$ret['result']='failed';
$ret['error']='image cached by cloudflare';
return $ret;
}
else
{
$ret['result']='failed';
$ret['error']='htaccess rewrite not work';
return $ret;
}
}
}
else
{
return $ret;
}
}
public function get_test_size()
{
$upload_dir = wp_upload_dir();
$url=$upload_dir['baseurl'].'/'. $this->test_file;
return $this->get_remote_url($url);
}
public function get_test_size_ex()
{
$upload_dir = wp_upload_dir();
$url=$upload_dir['baseurl'].'/'. $this->test_file;
$headers['Accept']='image/webp,image/*';
foreach ( wp_get_nocache_headers() as $header_key => $header_value )
{
$headers[$header_key] =$header_value;
}
$args['headers']= $headers;
$response=wp_remote_request($url,$args);
if(!is_wp_error($response))
{
if($response['response']['code']==200)
{
$ret['result']='success';
$ret['size']=strlen($response['body']);
return $ret;
}
else
{
$ret['result']='failed';
$ret['error']=$response['response']['message'];
return $ret;
}
}
else
{
$ret['result']='failed';
$ret['error'] =$response->get_error_message() ;
return $ret;
}
}
public function get_remote_url($url)
{
$headers['Accept']='image/webp,image/*';
foreach ( wp_get_nocache_headers() as $header_key => $header_value )
{
$headers[$header_key] =$header_value;
}
$args['headers']= $headers;
$response=wp_remote_request($url,$args);
if(!is_wp_error($response))
{
if($response['response']['code']==200)
{
return strlen($response['body']);
}
else if($response['response']['code']==401)
{
return 401;
}
}
else
{
return false;
}
return false;
}
public function is_apache()
{
$server = strtolower( sanitize_text_field($_SERVER['SERVER_SOFTWARE']));
if ( strpos( $server, 'apache' ) !== false )
{
return true;
}
else
{
return false;
}
}
public function is_nginx()
{
$server = strtolower( sanitize_text_field($_SERVER['SERVER_SOFTWARE']));
if ( strpos( $server, 'nginx' ) !== false )
{
return true;
}
else
{
return false;
}
}
public function is_litespeed()
{
$server = strtolower( sanitize_text_field($_SERVER['SERVER_SOFTWARE']));
if ( strpos( $server, 'litespeed' ) !== false )
{
return true;
}
else
{
return false;
}
}
public function is_active_cache()
{
$current = get_option( 'active_plugins', array() );
$cache='wp-cloudflare-page-cache/wp-cloudflare-super-page-cache.php';
if (($key = array_search($cache, $current)) !== false)
{
return true;
}
else
{
return false;
}
}
}
@@ -0,0 +1,337 @@
<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
class CompressX_Stats_Manager
{
const META_KEY = 'compressx_image_meta';
const OPTION_KEY = 'compressx_global_stats';
const PROGRESS_KEY = 'compressx_stats_progress';
const TRANSIENT_KEY = 'compressx_set_global_stats';
const BATCH_SIZE = 1000;
const MAX_DURATION = 25; // seconds
public static function init()
{
add_action('wp_ajax_compressx_start_stats', [__CLASS__, 'ajax_start']);
add_action('wp_ajax_compressx_get_stats', [__CLASS__, 'ajax_get']);
add_action('wp_ajax_compressx_continue_stats', [__CLASS__, 'ajax_continue']);
}
public static function ajax_start()
{
global $compressx;
$compressx->ajax_check_security('compressx-can-convert');
$cached = get_transient(self::TRANSIENT_KEY);
if ($cached)
{
$data=get_option(self::OPTION_KEY);
wp_send_json_success([
'message' => 'Cached data available',
'status' => 'cached',
'cached' => $data,
]);
}
delete_option(self::OPTION_KEY);
delete_option(self::PROGRESS_KEY);
delete_transient(self::TRANSIENT_KEY);
update_option(self::PROGRESS_KEY, [
'offset' => 0,
'_legacy_offset'=>0,
'accumulated' => [],
'state' => 'wait',
]);
wp_send_json_success(['status' => 'started']);
}
public static function ajax_continue()
{
global $compressx;
$compressx->ajax_check_security('compressx-can-convert');
$progress = get_option(self::PROGRESS_KEY);
if (!$progress || $progress['state'] !== 'wait') {
wp_send_json_error('Task not ready or already running.');
}
$progress['state'] = 'running';
update_option(self::PROGRESS_KEY, $progress);
//self::process_batch(self::BATCH_SIZE, $progress['offset'], $progress['accumulated']);
self::process_batch(self::BATCH_SIZE, $progress['offset'], $progress['_legacy_offset'],$progress['accumulated']);
wp_send_json_success(['status' => 'processing']);
}
public static function ajax_get()
{
global $compressx;
$compressx->ajax_check_security('compressx-can-convert');
$progress = get_option(self::PROGRESS_KEY);
if ($progress) {
if ($progress['state'] === 'running') {
wp_send_json_success(['status' => 'executing']);
}
if ($progress['state'] === 'wait') {
wp_send_json_success(['status' => 'in_progress']);
}
}
$final = get_option(self::OPTION_KEY);
if ($final) wp_send_json_success(array_merge(['status' => 'done'], $final));
wp_send_json_success(['status' => 'not_started']);
}
public static function process_batch($batch_size, $offset,$legacy_offset, $accumulated)
{
global $wpdb;
$start_time = time();
$data = wp_parse_args($accumulated, [
'converted_webp' => 0,
'converted_avif' => 0,
'total_count' => 0,
'original_total_webp' => 0,
'original_total_avif' => 0,
'webp_total' => 0,
'avif_total' => 0,
]);
CompressX_Image_Meta_V2::ensure_table();
$meta_table = CompressX_Image_Meta_V2::table_name();
while (true)
{
$results = $wpdb->get_results($wpdb->prepare("
SELECT m.attachment_id,
m.status,
m.og_file_size,
m.webp_converted,
m.avif_converted,
m.webp_converted_size,
m.avif_converted_size
FROM {$meta_table} m
INNER JOIN {$wpdb->posts} p
ON m.attachment_id = p.ID
WHERE p.post_type = 'attachment'
ORDER BY m.id ASC
LIMIT %d OFFSET %d
", $batch_size, $offset), ARRAY_A);
$count_this_batch = count($results);
if ($count_this_batch === 0) break;
foreach ($results as $row)
{
$status = $row['status'] ?? '';
if ($status === 'skip')
{
continue;
}
$original = (int)($row['og_file_size'] ?? 0);
if (!empty($row['webp_converted']))
{
$webp = (int)($row['webp_converted_size'] ?? 0);
$data['converted_webp']++;
if ($original > 0 && $webp > 0 && $webp <= $original)
{
$data['original_total_webp'] += $original;
$data['webp_total'] += $webp;
}
}
if (!empty($row['avif_converted']))
{
$avif = (int)($row['avif_converted_size'] ?? 0);
$data['converted_avif']++;
if ($original > 0 && $avif > 0 && $avif <= $original)
{
$data['original_total_avif'] += $original;
$data['avif_total'] += $avif;
}
}
$data['total_count']++;
}
$offset += $batch_size;
if ((time() - $start_time) >= self::MAX_DURATION)
{
update_option(self::PROGRESS_KEY, [
'offset' => $offset,
'_legacy_offset'=> $legacy_offset,
'accumulated' => $data,
'state' => 'wait',
]);
return;
}
}
while (true)
{
$legacy_results = $wpdb->get_results($wpdb->prepare("
SELECT pm.post_id, pm.meta_value
FROM {$wpdb->postmeta} pm
INNER JOIN {$wpdb->posts} p
ON pm.post_id = p.ID
LEFT JOIN {$meta_table} m
ON m.attachment_id = pm.post_id
WHERE pm.meta_key = %s
AND p.post_type = 'attachment'
AND m.attachment_id IS NULL
ORDER BY pm.post_id ASC
LIMIT %d OFFSET %d
", self::META_KEY, $batch_size, $legacy_offset), ARRAY_A);
$count_this_batch = count($legacy_results);
if ($count_this_batch === 0) {
break;
}
foreach ($legacy_results as $row)
{
$image_id = (int)$row['post_id'];
$meta = maybe_unserialize($row['meta_value']);
if (!is_array($meta)) {
continue;
}
CompressX_Image_Meta_V2::upgrade_image_meta($image_id);
$status = $meta['status'] ?? '';
if ($status === 'skip')
{
continue;
}
$original = isset($meta['og_file_size']) ? (int)$meta['og_file_size'] : 0;
if (!empty($meta['webp_converted']) && (int)$meta['webp_converted'] === 1)
{
$webp = isset($meta['webp_converted_size']) ? (int)$meta['webp_converted_size'] : 0;
$data['converted_webp']++;
if ($original > 0 && $webp > 0 && $webp <= $original)
{
$data['original_total_webp'] += $original;
$data['webp_total'] += $webp;
}
}
if (!empty($meta['avif_converted']) && (int)$meta['avif_converted'] === 1)
{
$avif = isset($meta['avif_converted_size']) ? (int)$meta['avif_converted_size'] : 0;
$data['converted_avif']++;
if ($original > 0 && $avif > 0 && $avif <= $original)
{
$data['original_total_avif'] += $original;
$data['avif_total'] += $avif;
}
}
$data['total_count']++;
}
$legacy_offset += $batch_size;
if ((time() - $start_time) >= self::MAX_DURATION)
{
update_option(self::PROGRESS_KEY, [
'offset' => $offset,
'_legacy_offset' =>$legacy_offset,
'accumulated' => $data,
'state' => 'wait',
'phase' => 'legacy',
]);
return;
}
}
CompressX_Options::delete_option(self::PROGRESS_KEY);
$webp_saved = $data['original_total_webp'] - $data['webp_total'];
$avif_saved = $data['original_total_avif'] - $data['avif_total'];
$percent_webp = $data['original_total_webp'] > 0 ? ($webp_saved / $data['original_total_webp']) * 100 : 0;
$percent_avif = $data['original_total_avif'] > 0 ? ($avif_saved / $data['original_total_avif']) * 100 : 0;
$max_webp_count=self::get_max_webp_image_count();
$max_avif_count=self::get_max_avif_image_count();
$conversion_webp = $max_webp_count > 0 ? ($data['converted_webp'] / $max_webp_count) * 100 : 0;
$conversion_avif = $max_avif_count > 0 ? ($data['converted_avif'] / $max_avif_count) * 100 : 0;
$final = [
'conversion_webp_percent' => round($conversion_webp, 2),
'conversion_avif_percent' => round($conversion_avif, 2),
'space_saved_webp_percent' => round($percent_webp, 2),
'space_saved_avif_percent' => round($percent_avif, 2),
'converted_webp' => $data['converted_webp'],
'converted_avif' => $data['converted_avif'],
'total_count' => $data['total_count'],
'saved_webp_size' => $webp_saved,
'saved_avif_size' => $avif_saved,
'webp_total' => $data['webp_total'],
'avif_total' => $data['avif_total'],
'webp_total_fomat' => size_format($data['webp_total'],2),
'avif_total_fomat' => size_format($data['avif_total'],2),
'original_total_webp' => $data['original_total_webp'],
'original_total_avif' => $data['original_total_avif'],
'calculated_at' => time(),
];
set_transient(self::TRANSIENT_KEY, $final, MINUTE_IN_SECONDS * 10);
}
public static function get_max_webp_image_count()
{
global $wpdb;
$supported_mime_types = array(
"image/jpg",
"image/jpeg",
"image/png",
"image/webp",);
//$supported_mime_types=apply_filters('compressx_supported_mime_types',$supported_mime_types);
$result=$wpdb->get_results( $wpdb->prepare("SELECT COUNT(*) FROM $wpdb->posts WHERE post_type = 'attachment' AND post_mime_type IN (%s,%s,%s,%s) ",$supported_mime_types),ARRAY_N);
if($result && sizeof($result)>0)
{
return $result[0][0];
}
else
{
return 0;
}
}
public static function get_max_avif_image_count()
{
global $wpdb;
$supported_mime_types = array(
"image/jpg",
"image/jpeg",
"image/png",
"image/webp",
"image/avif");
//$supported_mime_types=apply_filters('compressx_supported_mime_types',$supported_mime_types);
$result=$wpdb->get_results($wpdb->prepare("SELECT COUNT(*) FROM $wpdb->posts WHERE post_type = 'attachment' AND post_mime_type IN (%s,%s,%s,%s,%s) ",$supported_mime_types),ARRAY_N);
if($result && sizeof($result)>0)
{
return $result[0][0];
}
else
{
return 0;
}
}
}
@@ -0,0 +1,623 @@
<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
class CompressX_Webp_Rewrite
{
public function __construct()
{
}
public function create_rewrite_rules()
{
$this->create_wp_content_rules();
$this->create_uploads_rules();
}
public function create_rewrite_rules_ex()
{
$this->create_wp_content_rules_ex();
$this->create_uploads_rules_ex();
}
public function transfer_path($path)
{
return preg_replace( '/(\/|\\\\)/', '/', rtrim( $path, '\/' ) );
}
public function get_wordpress_root()
{
if( defined('WP_CONTENT_DIR'))
{
$path=dirname(WP_CONTENT_DIR);
}
else
{
$path=ABSPATH;
}
return $this->transfer_path($path);
}
public function create_wp_content_rules()
{
$document_root=$this->transfer_path($_SERVER['DOCUMENT_ROOT']);
$document_root_real=$this->transfer_path(realpath( $_SERVER['DOCUMENT_ROOT'] ));
$wordpress_root=$this->get_wordpress_root();
$root_path = trim( str_replace( $document_root_real ?: '', '', $wordpress_root ?: '' ), '\/' );
$root_suffix = str_replace( '//', '/', sprintf( '/%s/', $root_path ) );
//$document_root2='%{DOCUMENT_ROOT}'.str_replace($document_root,'',$wordpress_root);
$document_root2=( $document_root !== $document_root_real ) ? ( $wordpress_root . '/' ) : ( '%{DOCUMENT_ROOT}' . $root_suffix );
$document_root3=str_replace($document_root,'',$wordpress_root);
$upload_root = wp_parse_url( content_url() );
$upload_root = $upload_root['path'].'/compressx-nextgen';
$upload_root2=str_replace($document_root3,'',$upload_root);
$path=WP_CONTENT_DIR;
$htaccess_file=$path . '/.htaccess';
$line[]='<IfModule mod_rewrite.c>';
$line[]='RewriteEngine On';
$line[]='RewriteOptions Inherit';
$line[]='RewriteCond %{QUERY_STRING} original$';
$line[]='RewriteRule . - [L]';
$line[]='RewriteCond %{HTTP_ACCEPT} image/avif';
if($document_root2=='%{DOCUMENT_ROOT}')
{
$line[]='RewriteCond %{DOCUMENT_ROOT}'.$upload_root.'/$1.avif -f';
$line[]='RewriteRule (.+)\.avif '.$upload_root.'/$1.avif [NC,T=image/avif,L]';
}
elseif ( strpos( $document_root, '%{DOCUMENT_ROOT}' ) !== false )
{
$line[]='RewriteCond %{DOCUMENT_ROOT}'.$upload_root.'/$1.avif -f [OR]';
$line[]='RewriteCond %{DOCUMENT_ROOT}'.$upload_root2.'/$1.avif -f';
$line[]='RewriteRule (.+)\.avif '.$upload_root.'/$1.avif [NC,T=image/avif,L]';
}
else
{
$line[]='RewriteCond '.untrailingslashit($document_root2).$upload_root2.'/$1.avif -f [OR]';
$line[]='RewriteCond %{DOCUMENT_ROOT}'.$upload_root2.'/$1.avif -f';
$line[]='RewriteRule (.+)\.avif '.$upload_root.'/$1.avif [NC,T=image/avif,L]';
}
$line[]='RewriteCond %{HTTP_ACCEPT} image/avif';
if($document_root2=='%{DOCUMENT_ROOT}')
{
$line[]='RewriteCond %{DOCUMENT_ROOT}'.$upload_root.'/$1.webp.avif -f';
$line[]='RewriteRule (.+)\.webp '.$upload_root.'/$1.webp.avif [NC,T=image/avif,L]';
}
elseif ( strpos( $document_root, '%{DOCUMENT_ROOT}' ) !== false )
{
$line[]='RewriteCond %{DOCUMENT_ROOT}'.$upload_root.'/$1.webp.avif -f [OR]';
$line[]='RewriteCond %{DOCUMENT_ROOT}'.$upload_root2.'/$1.webp.avif -f';
$line[]='RewriteRule (.+)\.webp '.$upload_root.'/$1.webp.avif [NC,T=image/avif,L]';
}
else
{
$line[]='RewriteCond '.untrailingslashit($document_root2).$upload_root2.'/$1.webp.avif -f [OR]';
$line[]='RewriteCond %{DOCUMENT_ROOT}'.$upload_root2.'/$1.webp.avif -f';
$line[]='RewriteRule (.+)\.webp '.$upload_root.'/$1.webp.avif [NC,T=image/avif,L]';
}
$line[]='RewriteCond %{HTTP_ACCEPT} image/avif';
if($document_root2=='%{DOCUMENT_ROOT}')
{
$line[]='RewriteCond %{DOCUMENT_ROOT}'.$upload_root.'/$1.jpg.avif -f';
$line[]='RewriteRule (.+)\.jpg$ '.$upload_root.'/$1.jpg.avif [NC,T=image/avif,L]';
}
elseif ( strpos( $document_root, '%{DOCUMENT_ROOT}' ) !== false )
{
$line[]='RewriteCond %{DOCUMENT_ROOT}'.$upload_root.'/$1.jpg.avif -f [OR]';
$line[]='RewriteCond %{DOCUMENT_ROOT}'.$upload_root2.'/$1.jpg.avif -f';
$line[]='RewriteRule (.+)\.jpg$ '.$upload_root.'/$1.jpg.avif [NC,T=image/avif,L]';
}
else
{
$line[]='RewriteCond '.untrailingslashit($document_root2).$upload_root2.'/$1.jpg.avif -f [OR]';
$line[]='RewriteCond %{DOCUMENT_ROOT}'.$upload_root2.'/$1.jpg.avif -f';
$line[]='RewriteRule (.+)\.jpg$ '.$upload_root.'/$1.jpg.avif [NC,T=image/avif,L]';
}
$line[]='RewriteCond %{HTTP_ACCEPT} image/avif';
if($document_root2=='%{DOCUMENT_ROOT}')
{
$line[]='RewriteCond %{DOCUMENT_ROOT}'.$upload_root.'/$1.png.avif -f';
$line[]='RewriteRule (.+)\.png$ '.$upload_root.'/$1.png.avif [NC,T=image/avif,L]';
}
elseif ( strpos( $document_root, '%{DOCUMENT_ROOT}' ) !== false )
{
$line[]='RewriteCond %{DOCUMENT_ROOT}'.$upload_root.'/$1.png.avif -f [OR]';
$line[]='RewriteCond %{DOCUMENT_ROOT}'.$upload_root2.'/$1.png.avif -f';
$line[]='RewriteRule (.+)\.png$ '.$upload_root.'/$1.png.avif [NC,T=image/avif,L]';
}
else
{
$line[]='RewriteCond '.untrailingslashit($document_root2).$upload_root2.'/$1.png.avif -f [OR]';
$line[]='RewriteCond %{DOCUMENT_ROOT}'.$upload_root2.'/$1.png.avif -f';
$line[]='RewriteRule (.+)\.png$ '.$upload_root.'/$1.png.avif [NC,T=image/avif,L]';
}
$line[]='RewriteCond %{HTTP_ACCEPT} image/avif';
if($document_root2=='%{DOCUMENT_ROOT}')
{
$line[]='RewriteCond %{DOCUMENT_ROOT}'.$upload_root.'/$1.jpeg.avif -f';
$line[]='RewriteRule (.+)\.jpeg$ '.$upload_root.'/$1.jpeg.avif [NC,T=image/avif,L]';
}
elseif ( strpos( $document_root, '%{DOCUMENT_ROOT}' ) !== false )
{
$line[]='RewriteCond %{DOCUMENT_ROOT}'.$upload_root.'/$1.jpeg.avif -f [OR]';
$line[]='RewriteCond %{DOCUMENT_ROOT}'.$upload_root2.'/$1.jpeg.avif -f';
$line[]='RewriteRule (.+)\.jpeg$ '.$upload_root.'/$1.jpeg.avif [NC,T=image/avif,L]';
}
else
{
$line[]='RewriteCond '.untrailingslashit($document_root2).$upload_root2.'/$1.jpeg.avif -f [OR]';
$line[]='RewriteCond %{DOCUMENT_ROOT}'.$upload_root2.'/$1.jpeg.avif -f';
$line[]='RewriteRule (.+)\.jpeg$ '.$upload_root.'/$1.jpeg.avif [NC,T=image/avif,L]';
}
$line[]='RewriteCond %{HTTP_ACCEPT} image/webp';
if($document_root2=='%{DOCUMENT_ROOT}')
{
$line[]='RewriteCond %{DOCUMENT_ROOT}'.$upload_root.'/$1.webp -f';
$line[]='RewriteRule (.+)\.webp '.$upload_root.'/$1.webp [NC,T=image/webp,L]';
}
elseif ( strpos( $document_root, '%{DOCUMENT_ROOT}' ) !== false )
{
$line[]='RewriteCond %{DOCUMENT_ROOT}'.$upload_root.'/$1.webp -f [OR]';
$line[]='RewriteCond %{DOCUMENT_ROOT}'.$upload_root2.'/$1.webp -f';
$line[]='RewriteRule (.+)\.webp '.$upload_root.'/$1.webp [NC,T=image/webp,L]';
}
else
{
$line[]='RewriteCond '.untrailingslashit($document_root2).$upload_root2.'/$1.webp -f [OR]';
$line[]='RewriteCond %{DOCUMENT_ROOT}'.$upload_root2.'/$1.webp -f';
$line[]='RewriteRule (.+)\.webp '.$upload_root.'/$1.webp [NC,T=image/webp,L]';
}
$line[]='RewriteCond %{HTTP_ACCEPT} image/webp';
if($document_root2=='%{DOCUMENT_ROOT}')
{
$line[]='RewriteCond %{DOCUMENT_ROOT}'.$upload_root.'/$1.jpg.webp -f';
$line[]='RewriteRule (.+)\.jpg$ '.$upload_root.'/$1.jpg.webp [NC,T=image/webp,L]';
}
elseif ( strpos( $document_root, '%{DOCUMENT_ROOT}' ) !== false )
{
$line[]='RewriteCond %{DOCUMENT_ROOT}'.$upload_root.'/$1.jpg.webp -f [OR]';
$line[]='RewriteCond %{DOCUMENT_ROOT}'.$upload_root2.'/$1.jpg.webp -f';
$line[]='RewriteRule (.+)\.jpg$ '.$upload_root.'/$1.jpg.webp [NC,T=image/webp,L]';
}
else
{
$line[]='RewriteCond '.untrailingslashit($document_root2).$upload_root2.'/$1.jpg.webp -f [OR]';
$line[]='RewriteCond %{DOCUMENT_ROOT}'.$upload_root2.'/$1.jpg.webp -f';
$line[]='RewriteRule (.+)\.jpg$ '.$upload_root.'/$1.jpg.webp [NC,T=image/webp,L]';
}
$line[]='RewriteCond %{HTTP_ACCEPT} image/webp';
if($document_root2=='%{DOCUMENT_ROOT}')
{
$line[]='RewriteCond %{DOCUMENT_ROOT}'.$upload_root.'/$1.png.webp -f';
$line[]='RewriteRule (.+)\.png$ '.$upload_root.'/$1.png.webp [NC,T=image/webp,L]';
}
elseif ( strpos( $document_root, '%{DOCUMENT_ROOT}' ) !== false )
{
$line[]='RewriteCond %{DOCUMENT_ROOT}'.$upload_root.'/$1.png.webp -f [OR]';
$line[]='RewriteCond %{DOCUMENT_ROOT}'.$upload_root2.'/$1.png.webp -f';
$line[]='RewriteRule (.+)\.png$ '.$upload_root.'/$1.png.webp [NC,T=image/webp,L]';
}
else
{
$line[]='RewriteCond '.untrailingslashit($document_root2).$upload_root2.'/$1.png.webp -f [OR]';
$line[]='RewriteCond %{DOCUMENT_ROOT}'.$upload_root2.'/$1.png.webp -f';
$line[]='RewriteRule (.+)\.png$ '.$upload_root.'/$1.png.webp [NC,T=image/webp,L]';
}
$line[]='RewriteCond %{HTTP_ACCEPT} image/webp';
if($document_root2=='%{DOCUMENT_ROOT}')
{
$line[]='RewriteCond %{DOCUMENT_ROOT}'.$upload_root.'/$1.jpeg.webp -f';
$line[]='RewriteRule (.+)\.jpeg$ '.$upload_root.'/$1.jpeg.webp [NC,T=image/webp,L]';
}
elseif ( strpos( $document_root, '%{DOCUMENT_ROOT}' ) !== false )
{
$line[]='RewriteCond %{DOCUMENT_ROOT}'.$upload_root.'/$1.jpeg.webp -f [OR]';
$line[]='RewriteCond %{DOCUMENT_ROOT}'.$upload_root2.'/$1.jpeg.webp -f';
$line[]='RewriteRule (.+)\.jpeg$ '.$upload_root.'/$1.jpeg.webp [NC,T=image/webp,L]';
}
else
{
$line[]='RewriteCond '.untrailingslashit($document_root2).$upload_root2.'/$1.jpeg.webp -f [OR]';
$line[]='RewriteCond %{DOCUMENT_ROOT}'.$upload_root2.'/$1.jpeg.webp -f';
$line[]='RewriteRule (.+)\.jpeg$ '.$upload_root.'/$1.jpeg.webp [NC,T=image/webp,L]';
}
$options=CompressX_Options::get_option('compressx_general_settings',array());
$disable_cache_control=isset($options['disable_cache_control'])?$options['disable_cache_control']:false;
if(!$disable_cache_control)
{
$line[]='</IfModule>';
$line[]='<IfModule mod_headers.c>';
$line[]='<FilesMatch "(?i)\.(jpg|png|webp|jpeg)(\.(webp|avif))?$">';
$line[]='Header always set Cache-Control "private"';
$line[]='Header append Vary "Accept"';
$line[]='</FilesMatch>';
$line[]='</IfModule>';
}
insert_with_markers($htaccess_file,'CompressX',$line);
}
public function create_uploads_rules()
{
$document_root=$this->transfer_path($_SERVER['DOCUMENT_ROOT']);
$document_root_real=$this->transfer_path(realpath( $_SERVER['DOCUMENT_ROOT'] ));
$wordpress_root=$this->get_wordpress_root();
$root_path = trim( str_replace( $document_root_real ?: '', '', $wordpress_root ?: '' ), '\/' );
$root_suffix = str_replace( '//', '/', sprintf( '/%s/', $root_path ) );
//$document_root2='%{DOCUMENT_ROOT}'.str_replace($document_root,'',$wordpress_root);
$document_root2=( $document_root !== $document_root_real ) ? ( $wordpress_root . '/' ) : ( '%{DOCUMENT_ROOT}' . $root_suffix );
$document_root3=str_replace($document_root,'',$wordpress_root);
$upload_dir = wp_upload_dir();
$path=$upload_dir['basedir'];
$upload_root = wp_parse_url( content_url() );
$upload_root = $upload_root['path'].'/compressx-nextgen/uploads';
$upload_root2=str_replace($document_root3,'',$upload_root);
$htaccess_file=$path . '/.htaccess';
$line[]='<IfModule mod_rewrite.c>';
$line[]='RewriteEngine On';
$line[]='RewriteOptions Inherit';
$line[]='RewriteCond %{QUERY_STRING} original$';
$line[]='RewriteRule . - [L]';
$line[]='RewriteCond %{HTTP_ACCEPT} image/avif';
if($document_root2=='%{DOCUMENT_ROOT}')
{
$line[]='RewriteCond %{DOCUMENT_ROOT}'.$upload_root.'/$1.avif -f';
$line[]='RewriteRule (.+)\.avif '.$upload_root.'/$1.avif [NC,T=image/avif,L]';
}
elseif ( strpos( $document_root, '%{DOCUMENT_ROOT}' ) !== false )
{
$line[]='RewriteCond %{DOCUMENT_ROOT}'.$upload_root.'/$1.avif -f [OR]';
$line[]='RewriteCond %{DOCUMENT_ROOT}'.$upload_root2.'/$1.avif -f';
$line[]='RewriteRule (.+)\.avif '.$upload_root.'/$1.avif [NC,T=image/avif,L]';
}
else
{
$line[]='RewriteCond '.untrailingslashit($document_root2).$upload_root2.'/$1.avif -f [OR]';
$line[]='RewriteCond %{DOCUMENT_ROOT}'.$upload_root2.'/$1.avif -f';
$line[]='RewriteRule (.+)\.avif '.$upload_root.'/$1.avif [NC,T=image/avif,L]';
}
$line[]='RewriteCond %{HTTP_ACCEPT} image/avif';
if($document_root2=='%{DOCUMENT_ROOT}')
{
$line[]='RewriteCond %{DOCUMENT_ROOT}'.$upload_root.'/$1.webp.avif -f';
$line[]='RewriteRule (.+)\.webp '.$upload_root.'/$1.webp.avif [NC,T=image/avif,L]';
}
elseif ( strpos( $document_root, '%{DOCUMENT_ROOT}' ) !== false )
{
$line[]='RewriteCond %{DOCUMENT_ROOT}'.$upload_root.'/$1.webp.avif -f [OR]';
$line[]='RewriteCond %{DOCUMENT_ROOT}'.$upload_root2.'/$1.webp.avif -f';
$line[]='RewriteRule (.+)\.webp '.$upload_root.'/$1.webp.avif [NC,T=image/avif,L]';
}
else
{
$line[]='RewriteCond '.untrailingslashit($document_root2).$upload_root2.'/$1.webp.avif -f [OR]';
$line[]='RewriteCond %{DOCUMENT_ROOT}'.$upload_root2.'/$1.webp.avif -f';
$line[]='RewriteRule (.+)\.webp '.$upload_root.'/$1.webp.avif [NC,T=image/avif,L]';
}
$line[]='RewriteCond %{HTTP_ACCEPT} image/avif';
if($document_root2=='%{DOCUMENT_ROOT}')
{
$line[]='RewriteCond %{DOCUMENT_ROOT}'.$upload_root.'/$1.jpg.avif -f';
$line[]='RewriteRule (.+)\.jpg$ '.$upload_root.'/$1.jpg.avif [NC,T=image/avif,L]';
}
elseif ( strpos( $document_root, '%{DOCUMENT_ROOT}' ) !== false )
{
$line[]='RewriteCond %{DOCUMENT_ROOT}'.$upload_root.'/$1.jpg.avif -f [OR]';
$line[]='RewriteCond %{DOCUMENT_ROOT}'.$upload_root2.'/$1.jpg.avif -f';
$line[]='RewriteRule (.+)\.jpg$ '.$upload_root.'/$1.jpg.avif [NC,T=image/avif,L]';
}
else
{
$line[]='RewriteCond '.untrailingslashit($document_root2).$upload_root2.'/$1.jpg.avif -f [OR]';
$line[]='RewriteCond %{DOCUMENT_ROOT}'.$upload_root2.'/$1.jpg.avif -f';
$line[]='RewriteRule (.+)\.jpg$ '.$upload_root.'/$1.jpg.avif [NC,T=image/avif,L]';
}
$line[]='RewriteCond %{HTTP_ACCEPT} image/avif';
if($document_root2=='%{DOCUMENT_ROOT}')
{
$line[]='RewriteCond %{DOCUMENT_ROOT}'.$upload_root.'/$1.png.avif -f';
$line[]='RewriteRule (.+)\.png$ '.$upload_root.'/$1.png.avif [NC,T=image/avif,L]';
}
elseif ( strpos( $document_root, '%{DOCUMENT_ROOT}' ) !== false )
{
$line[]='RewriteCond %{DOCUMENT_ROOT}'.$upload_root.'/$1.png.avif -f [OR]';
$line[]='RewriteCond %{DOCUMENT_ROOT}'.$upload_root2.'/$1.png.avif -f';
$line[]='RewriteRule (.+)\.png$ '.$upload_root.'/$1.png.avif [NC,T=image/avif,L]';
}
else
{
$line[]='RewriteCond '.untrailingslashit($document_root2).$upload_root2.'/$1.png.avif -f [OR]';
$line[]='RewriteCond %{DOCUMENT_ROOT}'.$upload_root2.'/$1.png.avif -f';
$line[]='RewriteRule (.+)\.png$ '.$upload_root.'/$1.png.avif [NC,T=image/avif,L]';
}
$line[]='RewriteCond %{HTTP_ACCEPT} image/avif';
if($document_root2=='%{DOCUMENT_ROOT}')
{
$line[]='RewriteCond %{DOCUMENT_ROOT}'.$upload_root.'/$1.jpeg.avif -f';
$line[]='RewriteRule (.+)\.jpeg$ '.$upload_root.'/$1.jpeg.avif [NC,T=image/avif,L]';
}
elseif ( strpos( $document_root, '%{DOCUMENT_ROOT}' ) !== false )
{
$line[]='RewriteCond %{DOCUMENT_ROOT}'.$upload_root.'/$1.jpeg.avif -f [OR]';
$line[]='RewriteCond %{DOCUMENT_ROOT}'.$upload_root2.'/$1.jpeg.avif -f';
$line[]='RewriteRule (.+)\.jpeg$ '.$upload_root.'/$1.jpeg.avif [NC,T=image/avif,L]';
}
else
{
$line[]='RewriteCond '.untrailingslashit($document_root2).$upload_root2.'/$1.jpeg.avif -f [OR]';
$line[]='RewriteCond %{DOCUMENT_ROOT}'.$upload_root2.'/$1.jpeg.avif -f';
$line[]='RewriteRule (.+)\.jpeg$ '.$upload_root.'/$1.jpeg.avif [NC,T=image/avif,L]';
}
$line[]='RewriteCond %{HTTP_ACCEPT} image/webp';
if($document_root2=='%{DOCUMENT_ROOT}')
{
$line[]='RewriteCond %{DOCUMENT_ROOT}'.$upload_root.'/$1.webp -f';
$line[]='RewriteRule (.+)\.webp '.$upload_root.'/$1.webp [NC,T=image/webp,L]';
}
elseif ( strpos( $document_root, '%{DOCUMENT_ROOT}' ) !== false )
{
$line[]='RewriteCond %{DOCUMENT_ROOT}'.$upload_root.'/$1.webp -f [OR]';
$line[]='RewriteCond %{DOCUMENT_ROOT}'.$upload_root2.'/$1.webp -f';
$line[]='RewriteRule (.+)\.webp '.$upload_root.'/$1.webp [NC,T=image/webp,L]';
}
else
{
$line[]='RewriteCond '.untrailingslashit($document_root2).$upload_root2.'/$1.webp -f [OR]';
$line[]='RewriteCond %{DOCUMENT_ROOT}'.$upload_root2.'/$1.webp -f';
$line[]='RewriteRule (.+)\.webp '.$upload_root.'/$1.webp [NC,T=image/webp,L]';
}
$line[]='RewriteCond %{HTTP_ACCEPT} image/webp';
if($document_root2=='%{DOCUMENT_ROOT}')
{
$line[]='RewriteCond %{DOCUMENT_ROOT}'.$upload_root.'/$1.jpg.webp -f';
$line[]='RewriteRule (.+)\.jpg$ '.$upload_root.'/$1.jpg.webp [NC,T=image/webp,L]';
}
elseif ( strpos( $document_root, '%{DOCUMENT_ROOT}' ) !== false )
{
$line[]='RewriteCond %{DOCUMENT_ROOT}'.$upload_root.'/$1.jpg.webp -f [OR]';
$line[]='RewriteCond %{DOCUMENT_ROOT}'.$upload_root2.'/$1.jpg.webp -f';
$line[]='RewriteRule (.+)\.jpg$ '.$upload_root.'/$1.jpg.webp [NC,T=image/webp,L]';
}
else
{
$line[]='RewriteCond '.untrailingslashit($document_root2).$upload_root2.'/$1.jpg.webp -f [OR]';
$line[]='RewriteCond %{DOCUMENT_ROOT}'.$upload_root2.'/$1.jpg.webp -f';
$line[]='RewriteRule (.+)\.jpg$ '.$upload_root.'/$1.jpg.webp [NC,T=image/webp,L]';
}
$line[]='RewriteCond %{HTTP_ACCEPT} image/webp';
if($document_root2=='%{DOCUMENT_ROOT}')
{
$line[]='RewriteCond %{DOCUMENT_ROOT}'.$upload_root.'/$1.png.webp -f';
$line[]='RewriteRule (.+)\.png$ '.$upload_root.'/$1.png.webp [NC,T=image/webp,L]';
}
elseif ( strpos( $document_root, '%{DOCUMENT_ROOT}' ) !== false )
{
$line[]='RewriteCond %{DOCUMENT_ROOT}'.$upload_root.'/$1.png.webp -f [OR]';
$line[]='RewriteCond %{DOCUMENT_ROOT}'.$upload_root2.'/$1.png.webp -f';
$line[]='RewriteRule (.+)\.png$ '.$upload_root.'/$1.png.webp [NC,T=image/webp,L]';
}
else
{
$line[]='RewriteCond '.untrailingslashit($document_root2).$upload_root2.'/$1.png.webp -f [OR]';
$line[]='RewriteCond %{DOCUMENT_ROOT}'.$upload_root2.'/$1.png.webp -f';
$line[]='RewriteRule (.+)\.png$ '.$upload_root.'/$1.png.webp [NC,T=image/webp,L]';
}
$line[]='RewriteCond %{HTTP_ACCEPT} image/webp';
if($document_root2=='%{DOCUMENT_ROOT}')
{
$line[]='RewriteCond %{DOCUMENT_ROOT}'.$upload_root.'/$1.jpeg.webp -f';
$line[]='RewriteRule (.+)\.jpeg$ '.$upload_root.'/$1.jpeg.webp [NC,T=image/webp,L]';
}
elseif ( strpos( $document_root, '%{DOCUMENT_ROOT}' ) !== false )
{
$line[]='RewriteCond %{DOCUMENT_ROOT}'.$upload_root.'/$1.jpeg.webp -f [OR]';
$line[]='RewriteCond %{DOCUMENT_ROOT}'.$upload_root2.'/$1.jpeg.webp -f';
$line[]='RewriteRule (.+)\.jpeg$ '.$upload_root.'/$1.jpeg.webp [NC,T=image/webp,L]';
}
else
{
$line[]='RewriteCond '.untrailingslashit($document_root2).$upload_root2.'/$1.jpeg.webp -f [OR]';
$line[]='RewriteCond %{DOCUMENT_ROOT}'.$upload_root2.'/$1.jpeg.webp -f';
$line[]='RewriteRule (.+)\.jpeg$ '.$upload_root.'/$1.jpeg.webp [NC,T=image/webp,L]';
}
$line[]='</IfModule>';
insert_with_markers($htaccess_file,'CompressX',$line);
}
public function remove_rewrite_rule()
{
$path=WP_CONTENT_DIR;
$htaccess_file=$path . '/.htaccess';
insert_with_markers($htaccess_file,'CompressX','');
$upload_dir = wp_upload_dir();
$path=$upload_dir['basedir'];
$htaccess_file=$path . '/.htaccess';
insert_with_markers($htaccess_file,'CompressX','');
}
public function create_wp_content_rules_ex()
{
$doc_root = rtrim(str_replace('\\', '/', $_SERVER['DOCUMENT_ROOT']), '/');
$abs_path = rtrim(str_replace('\\', '/', ABSPATH), '/');
$prefix = '';
if (strpos($abs_path, $doc_root) === 0) {
$subdir = substr($abs_path, strlen($doc_root));
$prefix = rtrim($subdir, '/');
}
$prefix = $prefix ? '/' . ltrim($prefix, '/') : '';
$disable_cache_control = isset($options['disable_cache_control']) ? $options['disable_cache_control'] : false;
$lines = [];
$lines[] = '<IfModule mod_rewrite.c>';
$lines[] = 'RewriteEngine On';
$lines[] = 'RewriteCond %{QUERY_STRING} original$';
$lines[] = 'RewriteRule . - [L]';
$lines[] = '';
// AVIF
$lines[] = '# AVIF';
$lines[] = 'RewriteCond %{DOCUMENT_ROOT}' . $prefix . '/wp-content/compressx-nextgen/$1.$2 -f';
$lines[] = 'RewriteRule ^(?:.*wp-content/)?(.+)\.(avif)$ ' . $prefix . '/wp-content/compressx-nextgen/$1.$2 [T=image/avif,L]';
$lines[] = '';
// WebP
$lines[] = '# WebP';
$lines[] = 'RewriteCond %{DOCUMENT_ROOT}' . $prefix . '/wp-content/compressx-nextgen/$1.$2 -f';
$lines[] = 'RewriteRule ^(?:.*wp-content/)?(.+)\.(webp)$ ' . $prefix . '/wp-content/compressx-nextgen/$1.$2 [T=image/webp,L]';
$lines[] = '';
// JPG/PNG → AVIF
$lines[] = '# JPG/PNG → AVIF';
$lines[] = 'RewriteCond %{HTTP_ACCEPT} image/avif';
$lines[] = 'RewriteCond %{DOCUMENT_ROOT}' . $prefix . '/wp-content/compressx-nextgen/$1.$2.avif -f';
$lines[] = 'RewriteRule ^(?:.*wp-content/)?(.+)\.(jpe?g|png)$ ' . $prefix . '/wp-content/compressx-nextgen/$1.$2.avif [T=image/avif,L]';
$lines[] = '';
// JPG/PNG → WebP
$lines[] = '# JPG/PNG → WebP';
$lines[] = 'RewriteCond %{HTTP_ACCEPT} image/webp';
$lines[] = 'RewriteCond %{DOCUMENT_ROOT}' . $prefix . '/wp-content/compressx-nextgen/$1.$2.webp -f';
$lines[] = 'RewriteRule ^(?:.*wp-content/)?(.+)\.(jpe?g|png)$ ' . $prefix . '/wp-content/compressx-nextgen/$1.$2.webp [T=image/webp,L]';
$lines[] = '';
$lines[] = '</IfModule>';
if (!$disable_cache_control) {
$lines[] = '<IfModule mod_headers.c>';
$lines[] = '<FilesMatch "(?i)\.(jpg|png|webp|jpeg)(\.(webp|avif))?$">';
$lines[] = 'Header always set Cache-Control "private"';
$lines[] = 'Header append Vary "Accept"';
$lines[] = '</FilesMatch>';
$lines[] = '</IfModule>';
}
$target_path = WP_CONTENT_DIR . '/.htaccess';
insert_with_markers($target_path, 'CompressX', $lines);
}
public function create_uploads_rules_ex()
{
$doc_root = rtrim(str_replace(['\\', '/'], '/', $_SERVER['DOCUMENT_ROOT']), '/');
$abs_path = rtrim(str_replace(['\\', '/'], '/', ABSPATH), '/');
$prefix = '';
if (strpos($abs_path, $doc_root) === 0) {
$subdir = substr($abs_path, strlen($doc_root));
$prefix = rtrim($subdir, '/');
}
$prefix = $prefix ? '/' . ltrim($prefix, '/') : '';
$upload_dir = wp_get_upload_dir();
$upload_basedir = rtrim(str_replace(['\\', '/'], '/', $upload_dir['basedir']), '/');
$wp_content_dir = rtrim(str_replace(['\\', '/'], '/', WP_CONTENT_DIR), '/');
$upload_relative_path = ltrim(str_replace($wp_content_dir, '', $upload_basedir), '/');
$upload_prefix = $prefix . '/wp-content/compressx-nextgen/' . $upload_relative_path;
$upload_folder = trim(str_replace($abs_path, '', $upload_basedir), '/');
$filename_match = '(.+)';
$upload_rule_base = '^(?:.*' . preg_quote($upload_folder, '/') . '/)?' . $filename_match . '\.(%s)$';
$lines = [];
$lines[] = '<IfModule mod_rewrite.c>';
$lines[] = 'RewriteEngine On';
$lines[] = 'RewriteCond %{QUERY_STRING} original$';
$lines[] = 'RewriteRule . - [L]';
$lines[] = '';
//
$lines[] = '# AVIF';
$lines[] = 'RewriteCond %{DOCUMENT_ROOT}' . $prefix . '/wp-content/compressx-nextgen/' . $upload_relative_path . '/$1.$2 -f';
$lines[] = 'RewriteRule ' . sprintf($upload_rule_base, 'avif') . ' ' . $upload_prefix . '/$1.avif [T=image/avif,L]';
$lines[] = '';
//
$lines[] = '# WebP';
$lines[] = 'RewriteCond %{DOCUMENT_ROOT}' . $prefix . '/wp-content/compressx-nextgen/' . $upload_relative_path . '/$1.$2 -f';
$lines[] = 'RewriteRule ' . sprintf($upload_rule_base, 'webp') . ' ' . $upload_prefix . '/$1.webp [T=image/webp,L]';
$lines[] = '';
// JPG/PNG → AVIF
$lines[] = '# JPG/PNG → AVIF';
$lines[] = 'RewriteCond %{HTTP_ACCEPT} image/avif';
$lines[] = 'RewriteCond %{DOCUMENT_ROOT}' . $prefix . '/wp-content/compressx-nextgen/' . $upload_relative_path . '/$1.$2.avif -f';
$lines[] = 'RewriteRule ' . sprintf($upload_rule_base, 'jpe?g|png') . ' ' . $upload_prefix . '/$1.$2.avif [T=image/avif,L]';
$lines[] = '';
// JPG/PNG → WebP
$lines[] = '# JPG/PNG → WebP';
$lines[] = 'RewriteCond %{HTTP_ACCEPT} image/webp';
$lines[] = 'RewriteCond %{DOCUMENT_ROOT}' . $prefix . '/wp-content/compressx-nextgen/' . $upload_relative_path . '/$1.$2.webp -f';
$lines[] = 'RewriteRule ' . sprintf($upload_rule_base, 'jpe?g|png') . ' ' . $upload_prefix . '/$1.$2.webp [T=image/webp,L]';
$lines[] = '';
$lines[] = '</IfModule>';
$target_path = $upload_basedir . '/.htaccess';
insert_with_markers($target_path, 'CompressX', $lines);
}
}
@@ -0,0 +1,303 @@
<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
class CompressX
{
public function __construct()
{
$this->load_method();
$this->load_meta();
$this->load_dependencies();
$this->load_admin();
$this->load_hooks();
}
public function load_method()
{
include_once COMPRESSX_DIR . '/includes/method/class-compressx-image-method.php';
include_once COMPRESSX_DIR . '/includes/method/class-compressx-image-opt-method.php';
//include_once COMPRESSX_DIR . '/deprecated/class-compressx-image-opt-method-deprecated.php';
}
public function load_meta()
{
//include_once COMPRESSX_DIR . '/includes/meta/class-compressx-image-meta.php';
include_once COMPRESSX_DIR . '/includes/meta/class-compressx-image-meta-v2.php';
include_once COMPRESSX_DIR . '/includes/meta/class-compressx-custom-image-meta.php';
}
public function load_dependencies()
{
include_once COMPRESSX_DIR . '/includes/class-compressx-image.php';
include_once COMPRESSX_DIR . '/includes/class-compressx-options.php';
include_once COMPRESSX_DIR . '/includes/class-compressx-imgoptim-task.php';
include_once COMPRESSX_DIR . '/includes/class-compressx-image-scanner.php';
include_once COMPRESSX_DIR . '/includes/class-compressx-custom-imgoptim-task.php';
include_once COMPRESSX_DIR. '/includes/class-compressx-log.php';
include_once COMPRESSX_DIR . '/includes/class-compressx-auto-optimization.php';
new CompressX_Auto_Optimization();
include_once COMPRESSX_DIR . '/includes/class-compressx-picture-load.php';
new CompressX_Picture_Load();
include_once COMPRESSX_DIR . '/includes/class-compressx-stats-manager.php';
CompressX_Stats_Manager::init();
// Load Task Manager V2 System
//$this->load_task_system_v2();
}
public function load_hooks()
{
add_action( 'delete_attachment', array( $this, 'delete_images' ), 20 );
$plugin_basename = plugin_basename( plugin_dir_path( __DIR__ ) . 'compressx.php' );
add_filter('plugin_action_links_' . $plugin_basename, array( $this,'add_action_links'));
add_action( 'wp_ajax_compressx_dissmiss_conflict_notice', array( $this, 'dissmiss_conflict_notice' ), 20 );
add_action('compressx_purge_cache_event',array( $this,'purge_cache_event'));
add_action('compressx_purge_cache',array( $this,'purge_cache'));
add_action('compressx_after_optimize_image', array($this, 'update_latest_image'),10,2);
}
public function load_admin()
{
if(is_admin())
{
include_once COMPRESSX_DIR . '/includes/display/class-compressx-display.php';
new CompressX_Display();
include_once COMPRESSX_DIR . '/includes/display/class-compressx-custom-media-lib.php';
new CompressX_Custom_Media_Lib();
include_once COMPRESSX_DIR . '/includes/class-compressx-manual-optimization.php';
new CompressX_Manual_Optimization();
add_action( 'admin_notices', array( $this, 'optimizer_conflicts' ) );
add_action('in_admin_header',array( $this,'hide_notices'), 99);
$this->set_locale();
}
}
public function ajax_check_security($role='manage_options')
{
check_ajax_referer( 'compressx_ajax', 'nonce' );
$check=is_admin()&&current_user_can('manage_options');
$check=apply_filters('compressx_ajax_check_security',$check,$role);
if(!$check)
{
die();
}
}
public function hide_notices()
{
if(is_multisite())
{
$screen_ids[]='toplevel_page_CompressX-network';
}
else
{
$screen_ids[]='toplevel_page_'.COMPRESSX_SLUG;
$screen_ids[]='compressx_page_settings-compressx';
$screen_ids[]='compressx_page_info-compressx';
$screen_ids[]='compressx_page_logs-compressx';
$screen_ids[]='compressx_page_cdn-compressx';
$screen_ids[]='compressx_page_addons-compressx';
}
$screen_ids=apply_filters('compressx_get_screen_ids',$screen_ids);
if(in_array(get_current_screen()->id,$screen_ids))
{
remove_all_actions('admin_notices');
add_action( 'admin_notices', array( $this, 'optimizer_conflicts' ) );
}
}
private function set_locale()
{
require_once COMPRESSX_DIR . '/includes/class-compressx-i18n.php';
$plugin_i18n = new CompressX_i18n();
add_action('init',array( $plugin_i18n,'load_plugin_textdomain'));
}
public function dissmiss_conflict_notice()
{
update_option('compressx_dissmiss_conflict_notice', true,false);
wp_send_json_success();
}
public function optimizer_conflicts()
{
if ( ( defined( 'DOING_AJAX' ) && DOING_AJAX ) )
{
return;
}
if ( is_network_admin() )
{
return;
}
if ( ! current_user_can( 'manage_options' ) )
{
return;
}
$dissmiss=CompressX_Options::get_option('compressx_dissmiss_conflict_notice');
if($dissmiss)
{
return;
}
include_once ABSPATH . 'wp-admin/includes/plugin.php';
$plugins=array();
$plugins["wp-smush"]="wp-smushit/wp-smush.php";
$plugins["wp-smush-pro"]="wp-smush-pro/wp-smush.php";
$plugins["kraken"]="kraken-image-optimizer/kraken.php";
$plugins["tinypng"]="tiny-compress-images/tiny-compress-images.php";
$plugins["shortpixel"]="shortpixel-image-optimiser/wp-shortpixel.php";
$plugins["ewww"]="ewww-image-optimizer/ewww-image-optimizer.php";
$plugins["ewww-cloud"]="ewww-image-optimizer-cloud/ewww-image-optimizer-cloud.php";
$plugins["imagerecycle"]="imagerecycle-pdf-image-compression/wp-image-recycle.php";
$plugins["imagify"]="imagify/imagify.php";
$plugins["webp-converter-for-media"]="webp-converter-for-media/webp-converter-for-media.php";
$plugins["optimole-wp"]="optimole-wp/optimole-wp.php";
$plugins["wp-optimize"]="wp-optimize/wp-optimize.php";
$plugins["wpvivid-imgoptim"]="wpvivid-imgoptim/wpvivid-imgoptim.php";
$plugins = array_filter( $plugins, 'is_plugin_active' );
if(empty($plugins))
{
return;
}
$plugins_names=array();
foreach ( $plugins as $plugin )
{
$plugin_data = get_plugin_data( WP_PLUGIN_DIR . DIRECTORY_SEPARATOR . $plugin,false,false );
$plugins_names[] = $plugin_data['Name'];
}
$plugins_names = implode( ', ', $plugins_names );
?>
<div class="notice notice-warning is-dismissible" id="compressx_conflict_notice">
<p class="notice-title">
<strong>Multiple image optimization plugins detected</strong>
</p>
<p class="description">
<strong>
<?php
echo wp_kses_post(sprintf(
/* translators: %1$s: plugins name */
esc_html__('It seems that multiple image optimization plugins are installed on the website. This may cause conflicts while optimizing your images. In order to optimize your images properly and effectively, you may consider disabling other image optimization plugins: %1$s.','compressx'),
$plugins_names
));
?>
</strong>
</p>
<p>
<a href="<?php echo esc_url( admin_url( 'plugins.php' ) ); ?>"
class="button button-primary button-hero">Go to Plugins page
</a>
<a href="#" style="margin-left: 15px" id="compressx_dissmiss_conflict_notice">Dismiss</a>
</p>
</div>
<script>
jQuery(document).on('click', '#compressx_dissmiss_conflict_notice', function()
{
jQuery('#compressx_conflict_notice').hide();
var ajax_data = {
'action': 'compressx_dissmiss_conflict_notice'
};
var time_out = 30000;
jQuery.ajax({
type: "post",
url: '<?php echo esc_url(admin_url('admin-ajax.php'));?>',
data: ajax_data,
success: function (data) {
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
},
timeout: time_out
});
});
</script>
<?php
}
public function add_action_links( $links )
{
if(!is_multisite())
{
$settings_link = array(
'<a href="' . admin_url( 'admin.php?page=' .COMPRESSX_SLUG ) . '">Settings</a>',
);
}
else
{
$settings_link = array(
'<a href="' . network_admin_url( 'admin.php?page=' . COMPRESSX_SLUG ) . '">Settings</a>',
);
}
return array_merge( $settings_link, $links );
}
public function delete_images( $image_id )
{
if ( empty( $image_id ) )
{
return;
}
CompressX_Image_Method::delete_image($image_id);
}
public function purge_cache_event()
{
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);
$cdn->purge_cache();
die();
}
public function purge_cache()
{
$options=CompressX_Options::get_option('compressx_general_settings',array());
if(isset($options['cf_cdn']['auto_purge_cache_after_manual'])&&$options['cf_cdn']['auto_purge_cache_after_manual'])
{
$timestamp =wp_next_scheduled('compressx_purge_cache_event');
if($timestamp===false)
{
wp_schedule_single_event(time()+300,'compressx_purge_cache_event');
}
return;
}
if(isset($options['cf_cdn']['auto_purge_cache'])&&$options['cf_cdn']['auto_purge_cache'])
{
include_once COMPRESSX_DIR . '/includes/class-compressx-cloudflare-cdn.php';
$setting=$options['cf_cdn'];
$cdn=new CompressX_CloudFlare_CDN($setting);
$cdn->purge_cache();
}
}
public function update_latest_image($image_id)
{
CompressX_Options::update_option('compressx_latest_bulk_image',$image_id);
}
}
@@ -0,0 +1,142 @@
<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
class CompressX_Addons
{
public function __construct()
{
}
public function display()
{
?>
<div id="compressx-root">
<div id="compressx-wrap">
<?php
$this->output_nav();
$this->output_header();
$this->output_addons();
$this->output_footer();
?>
</div>
</div>
<?php
}
public function output_nav()
{
do_action('compressx_output_nav');
}
public function output_header()
{
do_action('compressx_output_header');
}
public function output_addons()
{
?>
<header>
<div class="compressx-container compressx-header">
<div class="compressx-header-dashboard">
<h5>Addons <a href="https://compressx.io">(Pro Only)</a></h5>
</div>
<div class="compressx-addons-grid">
<div class="cx-addons" style="position: relative;">
<div class="cx-addons-icon-block">
<span class="dashicons dashicons-admin-generic compressx-icon-style" style="color:green"></span>
</div>
<div>
<h5>Advanced Compression Level Settings</h5>
<span>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</span>
</div>
</div>
<div class="cx-addons" style="position: relative;">
<div class="cx-addons-icon-block">
<span class="dashicons dashicons-admin-appearance compressx-icon-style"></span>
</div>
<div>
<h5>Remove JPG/PNG Thumbnails</h5>
<span>Automatically delete original JPG/PNG thumbnails after converting them to WebP or AVIF to free up disk space.</span>
</div>
</div>
<div class="cx-addons" style="position: relative;">
<div class="cx-addons-icon-block">
<span class="dashicons dashicons-calendar-alt compressx-icon-style"></span>
</div>
<div>
<h5>Cron Support</h5>
<span>Automates your image optimization workflows with a robust cron system, flexibly scheduling AVIF/WebP conversions for new, existing, and popular images.</span>
</div>
</div>
<div class="cx-addons" style="position: relative;">
<div class="cx-addons-icon-block">
<span class="dashicons dashicons-format-gallery compressx-icon-style" style="color:#f25767"></span>
</div>
<div>
<h5>Thumbnails Generation/reGeneration</h5>
<span>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.</span>
</div>
</div>
<div class="cx-addons" style="position: relative;">
<div class="cx-addons-icon-block">
<span class="dashicons dashicons-shortcode compressx-icon-style" style="color:#071c4d"></span>
</div>
<div>
<h5>WP-CLI</h5>
<span>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(coming soon).</span>
</div>
</div>
<div class="cx-addons" style="position: relative;">
<div class="cx-addons-icon-block">
<span class="dashicons dashicons-cover-image compressx-icon-style"></span>
</div>
<div>
<h5>Watermark</h5>
<span>Add watermarks to your images during the process of uploading, bulk WebP/AVIF conversion, and thumbnail regeneration (WebP, AVIF, JPG, or PNG).</span>
</div>
</div>
<div class="cx-addons" style="position: relative;">
<div class="cx-addons-icon-block">
<span class="dashicons dashicons-cloud compressx-icon-style"></span>
</div>
<div>
<h5>CDN Integration</h5>
<span>Integrate with Cloudflare pro to convert and serve your website images as WebP/AVIF formats. Enable ‘Vary for images’ to dynamically serve correct variants.</span>
</div>
</div>
<div class="cx-addons" style="position: relative;">
<div class="cx-addons-icon-block">
<span class="dashicons dashicons-groups compressx-icon-style" style="color:#f25767"></span>
</div>
<div>
<h5>Roles and Capabilities</h5>
<span>Control CompressX Pro settings and features by setting a super admin. The super admin can grant access for other user roles include admin.</span>
</div>
</div>
<div class="cx-addons" style="position: relative;">
<div class="cx-addons-icon-block">
<span class="dashicons dashicons-wordpress compressx-icon-style" style="color:#ffb116"></span>
</div>
<div>
<h5>Multisite Support</h5>
<span>Coming soon..</span>
</div>
</div>
</div>
</div>
</header>
<?php
}
public function output_footer()
{
do_action('compressx_output_footer');
}
}
@@ -0,0 +1,409 @@
<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
class CompressX_Advanced_Compression_Level_Display
{
public function __construct()
{
//add_action('wp_ajax_compressx_save_compression', array($this, 'save_compression'));
}
public function display()
{
?>
<div id="compressx-root">
<div id="compressx-wrap">
<?php
$this->output_nav();
$this->output_header();
$this->output_advanced_custom_compression_level();
$this->output_footer();
?>
</div>
</div>
<?php
}
public function output_nav()
{
do_action('compressx_output_nav');
}
public function output_header()
{
do_action('compressx_output_header');
}
public function output_footer()
{
do_action('compressx_output_footer');
}
public function output_advanced_custom_compression_level()
{
$options=CompressX_Options::get_option('compressx_quality',array());
$quality=isset($options['quality'])?$options['quality']:'lossy';
$quality_webp=isset($options['quality_webp'])?$options['quality_webp']: 80;
$quality_avif=isset($options['quality_avif'])?$options['quality_avif']: 60;
?>
<section>
<div class="compressx-container compressx-section ">
<div class="compressx-general-settings">
<div class="compressx-general-settings-header" style="position: relative;">
<h5><span>Advanced Custom Compression Level Settings</span></h5>
</div>
<div class="compressx-general-settings-body">
<div class="compressx-general-settings-body-grid">
<div>
<span>
<span class="dashicons dashicons-admin-site"></span><strong>Global compression level</strong>
</span>
<p style="padding-left: 2rem;">
<span>Webp<input id="cx_quality_webp" type="text" style="width: 2.5rem;" value="<?php echo esc_attr($quality_webp); ?>"></span><span style="padding: 0 0.5rem;"></span>
<span>AVIF<input id="cx_quality_avif" type="text" style="width: 2.5rem;" value="<?php echo esc_attr($quality_avif); ?>"></span>
</p>
</div>
<div>
<div class="compressing-converting-information">
<span><strong>Compression Levels by Categories</strong> have <strong>higher</strong> priority than the <strong>global compression level.</strong>
This means that images assigned to specific categories will use their category's compression level to be processed, while all other images will fall back to the global compression setting.</span><br>
<span>You can choose which image categories should receive special compression treatment.</span>
</div>
</div>
</div>
</div>
<div>
<p>
<strong><span class="dashicons dashicons-wordpress" style="color:#00749C"></span><span>Compression Levels by Category (WordPress Standard Image Types)</span></strong>
<span><a href="https://compressx.io">(Pro only)</a></span>
</p>
<div class="compressx-table" style="padding-bottom: 2rem;">
<div class="compressx-table-3-cols-header">
<div><strong><input type="checkbox" title="Check all" class="cx-table-all-check" disabled>Image Usage Type</strong></div>
<div><strong>Webp/AVIF</strong></div>
<div><strong>Recommended Compression Level</strong></div>
</div>
<?php
$list=$this->get_advanced_custom_compression_list();
foreach ($list as $item)
{
if($item['enable'])
{
$quality_enbale="checked";
}
else
{
$quality_enbale="";
}
?>
<div class="compressx-table-3-cols-body">
<div>
<input class="cx-table-check" type="checkbox" <?php echo esc_attr($quality_enbale); ?> option="cx_advanced_quality_enable" name="<?php echo esc_attr($item['type']); ?>" disabled>
<span><strong><?php echo esc_html($item['display']); ?></strong></span>
</div>
<div>
<input type="text" style="width: 2.5rem;" option="cx_advanced_webp_quality" name="<?php echo esc_attr($item['type']); ?>" value="<?php echo esc_attr($item['webp']); ?>" disabled>
<input type="text" style="width: 2.5rem;" option="cx_advanced_avif_quality" name="<?php echo esc_attr($item['type']); ?>" value="<?php echo esc_attr($item['avif']); ?>" disabled>
</div>
<div>
<span class="compressx-compression-level-items">
<?php echo esc_html($item['description']); ?>
</span>
</div>
</div>
<?php
}
?>
<div class="compressx-table-3-cols-footer">
<div><strong><input type="checkbox" title="Check all" class="cx-table-all-check" disabled>Image Usage Type</strong></div>
<div><strong>Webp/AVIF</strong></div>
<div><strong>Recommended Compression Level</strong></div>
</div>
</div>
<p>
<strong><span class="dashicons dashicons-cart" style="color:#96588a"></span>Compression Levels by Category (WooCommerce Image Type)</strong>
<span><a href="https://compressx.io">(Pro only)</a></span>
</p>
<div class="compressx-table">
<div class="compressx-table-3-cols-header">
<div><strong><input type="checkbox" title="Check all" class="cx-woo-table-all-check" disabled>Image Usage Type</strong></div>
<div><strong>Webp/AVIF</strong></div>
<div><strong>Recommended Compression Level</strong></div>
</div>
<?php
$list=$this->get_advanced_custom_woocommerce_compression_list();
foreach ($list as $item)
{
if($item['enable'])
{
$quality_enbale="checked";
}
else
{
$quality_enbale="";
}
?>
<div class="compressx-table-3-cols-body">
<div>
<input class="cx-woo-table-check" type="checkbox" <?php echo esc_attr($quality_enbale); ?> option="cx_advanced_quality_enable" name="<?php echo esc_attr($item['type']); ?>" disabled>
<span><strong><?php echo esc_html($item['display']); ?></strong></span>
</div>
<div>
<input type="text" style="width: 2.5rem;" option="cx_advanced_webp_quality" name="<?php echo esc_attr($item['type']); ?>" value="<?php echo esc_attr($item['webp']); ?>" disabled>
<input type="text" style="width: 2.5rem;" option="cx_advanced_avif_quality" name="<?php echo esc_attr($item['type']); ?>" value="<?php echo esc_attr($item['avif']); ?>" disabled>
</div>
<div>
<span class="compressx-compression-level-items">
<?php echo esc_html($item['description']); ?>
</span>
</div>
</div>
<?php
}
?>
<div class="compressx-table-3-cols-footer">
<div><strong><input type="checkbox" title="Check all" class="cx-woo-table-all-check" disabled>Image Usage Type</strong></div>
<div><strong>Webp</strong></div>
<div><strong>AVIF</strong></div>
</div>
<div class="compressx-compression-level">
<div class="compressx-compression-level-items"><span class="compressx-compression-level-item-high" style="background-color:#4caf50"></span><span><strong>High Quality</strong></span></div>
<div class="compressx-compression-level-items"><span class="compressx-compression-level-item-high" style="background-color:#ffeb3b"></span><span><strong>Balanced Quality</strong></span></div>
<div class="compressx-compression-level-items"><span class="compressx-compression-level-item-high" style="background-color:#ff9800"></span><span><strong>Medium Quality</strong></span></div>
<div class="compressx-compression-level-items"><span class="compressx-compression-level-item-high" style="background-color:#f44336"></span><span><strong>Aggressive Quality</strong></span></div>
</div>
</div>
<div class="compressx-general-settings-footer">
<input class="button-primary cx-button" id="compressx_save_advance_compression" type="submit" value="Save Changes">
<span style="padding:0 0.2rem;"></span>
<span id="compressx_save_advance_progress" style="display: none">
<img src="../wp-admin/images/loading.gif" alt="">
</span>
<span id="compressx_save_advance_text" class="success hidden" aria-hidden="true" style="color:#007017"><?php esc_html_e('Saved!','compressx')?></span>
</div>
</div>
</div>
</div>
</section>
<script>
//
jQuery('.cx-table-all-check').click(function()
{
var check=true;
if(jQuery(this).prop('checked'))
{
check = true;
}
else {
check = false;
}
jQuery('input[type="checkbox"].cx-table-check').each(function()
{
jQuery(this).prop('checked',check);
});
});
jQuery('.cx-woo-table-all-check').click(function()
{
var check=true;
if(jQuery(this).prop('checked'))
{
check = true;
}
else {
check = false;
}
jQuery('input[type="checkbox"].cx-woo-table-check').each(function()
{
jQuery(this).prop('checked',check);
});
});
jQuery('#compressx_save_advance_compression').click(function()
{
compressx_save_advance_compression();
});
function compressx_save_advance_compression()
{
var webp_quality = jQuery('#cx_quality_webp').val();
var avif_quality = jQuery('#cx_quality_avif').val();
var ajax_data = {
'action': 'compressx_save_compression',
'webp_quality': webp_quality,
'avif_quality': avif_quality
};
jQuery('#compressx_save_advance_compression').css({'pointer-events': 'none', 'opacity': '0.4'});
jQuery('#compressx_save_advance_progress').show();
compressx_post_request(ajax_data, function (data)
{
try
{
var jsonarray = jQuery.parseJSON(data);
jQuery('#compressx_save_advance_compression').css({'pointer-events': 'auto', 'opacity': '1'});
jQuery('#compressx_save_advance_progress').hide();
if (jsonarray.result === 'success')
{
jQuery('#compressx_save_advance_text').removeClass("hidden");
setTimeout(function ()
{
jQuery('#compressx_save_advance_text').addClass( 'hidden' );
}, 3000);
}
}
catch (err)
{
alert(err);
jQuery('#compressx_save_advance_compression').css({'pointer-events': 'auto', 'opacity': '1'});
jQuery('#compressx_save_advance_progress').hide();
}
}, function (XMLHttpRequest, textStatus, errorThrown)
{
jQuery('#compressx_save_advance_compression').css({'pointer-events': 'auto', 'opacity': '1'});
jQuery('#compressx_save_advance_progress').hide();
var error_message = compressx_output_ajaxerror('changing settings', textStatus, errorThrown);
alert(error_message);
});
}
</script>
<?php
}
public function get_advanced_custom_compression_list()
{
$advanced_quality_list=CompressX_Options::get_default_advanced_quality_option();
$display_list=array();
foreach ($advanced_quality_list as $type=>$item)
{
$item['type']=$type;
$item['display']=$this->get_advanced_quality_display_name($type);
$item['description']=$this->get_advanced_quality_description($type);
$display_list[]=$item;
}
return $display_list;
}
public function get_advanced_custom_woocommerce_compression_list()
{
$advanced_quality_list=CompressX_Options::get_default_advanced_woocommerce_quality_option();
$display_list=array();
foreach ($advanced_quality_list as $type=>$item)
{
$item['type']=$type;
$item['display']=$this->get_advanced_quality_display_name($type);
$item['description']=$this->get_advanced_quality_description($type);
$display_list[]=$item;
}
return $display_list;
}
public function get_advanced_quality_display_name($type)
{
$list= [
// core
'site_logo' => ['display' => 'Site logo'],
'header_background' => ['display' => 'Header background image'],
'featured_post' => ['display' => 'Featured image (Post)'],
'featured_page' => ['display' => 'Featured image (Page)'],
'sidebar_widget' => ['display' => 'Image in sidebar'],
'acf_image_fields' => ['display' => 'Image field used via ACF(Advanced Custom Fields)'],
// WooCommerce
'wc_product_featured_images' => ['display' => 'Product featured image'],
'wc_product_gallery_images' => ['display' => 'Product gallery image'],
'wc_variation_images' => ['display' => 'Variation-specific image'],
'wc_product_category_images' => ['display' => 'Category image (taxonomy thumbnail)'],
];
return isset($list[$type]['display'])?$list[$type]['display']:'';
}
public function get_advanced_quality_description($type)
{
$list= [
// core
'site_logo' => ['level' => 'high','text'=>'Webp (90+), AVIF (90+)---branding clarity is essential'],
'header_background' => ['level' => 'mid','text'=>'Webp (75-85), AVIF (75-85)---may span full width, retain clarity'],
'featured_post' => ['level' => 'high','text'=>'Webp (85-90), AVIF (85-90)---visually impactful, often shared'],
'featured_page' => ['level' => 'high','text'=>'Webp (85-90), AVIF (85-90)---visually impactful, often shared'],
'sidebar_widget' => ['level' => 'aggressive','text'=>'Webp (60-75), AVIF (60-75)---small visual element'],
'acf_image_fields' => ['level' => 'balanced','text'=>'Webp (70-80), AVIF (70-80)---depends on context, often supportive'],
// WooCommerce
'wc_product_featured_images' => ['level' => 'high','text'=>'Webp (85-90), AVIF (85-90)---brand/visual integrity important'],
'wc_product_gallery_images' => ['level' => 'mid','text'=>'Webp (75-85), AVIF (75-85)---visual but secondary to main image'],
'wc_variation_images' => ['level' => 'mid','text'=>'Webp (75-85), AVIF (75-85)---often similar to gallery use'],
'wc_product_category_images' => ['level' => 'balanced','text'=>'Webp (70-80), AVIF (70-80)---smaller, not full focus'],
];
if(isset($list[$type]))
{
$html='';
if($list[$type]['level']=='high')
{
$html.='<span class="compressx-compression-level-item-high" style="background-color:#4caf50"></span>';
$html.='<span><strong>High</strong>';
}
else if($list[$type]['level']=='mid')
{
$html.='<span class="compressx-compression-level-item-high" style="background-color:#ff9800"></span>';
$html.='<span><strong>Medium</strong>';
}
else if($list[$type]['level']=='aggressive')
{
$html.='<span class="compressx-compression-level-item-high" style="background-color:#f44336"></span>';
$html.='<span><strong>Aggressive</strong>';
}
else if($list[$type]['level']=='balanced')
{
$html.='<span class="compressx-compression-level-item-high" style="background-color:#ffeb3b"></span>';
$html.='<span><strong>Balanced</strong>';
}
$html.='<span>: '.$list[$type]['text'].'</span></span>';
return $html;
}
else
{
return '';
}
}
public function save_compression()
{
global $compressx;
$compressx->ajax_check_security('compressx-can-use-general-settings');
if(!isset($_POST['webp_quality']))
{
die();
}
if(!isset($_POST['avif_quality']))
{
die();
}
$webp_quality = sanitize_text_field($_POST['webp_quality']);
$avif_quality = sanitize_text_field($_POST['avif_quality']);
$options=CompressX_Options::get_option('compressx_quality',array());
$options['quality_webp']=intval($webp_quality);
$options['quality_avif']=intval($avif_quality);
CompressX_Options::update_option('compressx_quality',$options);
$ret['result']='success';
echo wp_json_encode($ret);
die();
}
}
@@ -0,0 +1,123 @@
<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
class CompressX_Bulk_Action
{
public $end_shutdown_function;
public function __construct()
{
add_action('wp_ajax_compressx_start_scan_unoptimized_image', array($this, 'start_scan_unoptimized_image'));
add_action('wp_ajax_compressx_init_bulk_optimization_task', array($this, 'init_bulk_optimization_task'));
add_action('wp_ajax_compressx_run_optimize', array($this, 'run_optimize'));
add_action('wp_ajax_compressx_get_opt_progress', array($this, 'get_opt_progress'));
}
public function start_scan_unoptimized_image()
{
global $compressx;
$compressx->ajax_check_security('compressx-can-convert');
$force=isset($_POST['force'])?sanitize_key($_POST['force']):'0';
if($force=='1')
{
$force=true;
}
else
{
$force=false;
}
$start_row=isset($_POST['offset'])?sanitize_key($_POST['offset']):0;
$ret=CompressX_Image_Scanner::scan_unoptimized_images($force,$start_row);
echo wp_json_encode($ret);
die();
}
public function init_bulk_optimization_task()
{
global $compressx;
$compressx->ajax_check_security('compressx-can-convert');
$force=isset($_POST['force'])?sanitize_key($_POST['force']):'0';
if($force=='1')
{
$force=true;
}
else
{
$force=false;
}
$task=new CompressX_ImgOptim_Task();
$ret=$task->init_task($force);
echo wp_json_encode($ret);
die();
}
public function run_optimize()
{
global $compressx;
$compressx->ajax_check_security('compressx-can-convert');
set_time_limit(120);
$task=new CompressX_ImgOptim_Task();
$ret=$task->get_task_status();
if($ret['result']=='success'&&$ret['status']=='completed')
{
$this->flush($ret);
$task->do_optimize_image();
//echo wp_json_encode($ret);
}
else
{
echo wp_json_encode($ret);
}
die();
}
private function flush($ret)
{
$json=wp_json_encode($ret);
if(!headers_sent())
{
header('Content-Length: '.strlen($json));
header('Connection: close');
header('Content-Encoding: none');
}
if (session_id())
session_write_close();
echo wp_json_encode($ret);
if(function_exists('fastcgi_finish_request'))
{
fastcgi_finish_request();
}
else
{
ob_flush();
flush();
}
}
public function get_opt_progress()
{
global $compressx;
$compressx->ajax_check_security('compressx-can-convert');
$task=new CompressX_ImgOptim_Task();
$result=$task->get_task_progress();
echo wp_json_encode($result);
die();
}
}
@@ -0,0 +1,387 @@
<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
class CompressX_CDN
{
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 id="compressx-root">
<div id="compressx-wrap">
<?php
$this->output_nav();
$this->output_header();
$this->output_cdn();
$this->output_footer();
?>
</div>
</div>
<?php
}
public function output_nav()
{
do_action('compressx_output_nav');
}
public function output_header()
{
do_action('compressx_output_header');
}
public function output_footer()
{
do_action('compressx_output_footer');
}
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;
if($auto_purge_cache)
{
$auto_purge_cache='checked';
}
else
{
$auto_purge_cache='';
}
$auto_purge_cache_after_manual=isset($options['cf_cdn']['auto_purge_cache_after_manual'])?$options['cf_cdn']['auto_purge_cache_after_manual']:true;
if($auto_purge_cache_after_manual)
{
$auto_purge_cache_after_manual='checked';
}
else
{
$auto_purge_cache_after_manual='';
}
?>
<section>
<div class="compressx-container compressx-section ">
<div class="compressx-general-settings">
<div class="compressx-general-settings-header">
<h5><?php esc_html_e('Cloudflare Integration','compressx')?></h5>
</div>
<div class="compressx-general-settings-body">
<div class="compressx-general-settings-body-grid">
<div class="compressing-converting" style="margin-top: 0;">
<span class="cx-title">
<strong><?php esc_html_e('Cloudflare E-mail: ','compressx')?></strong>
</span>
<p>
<input style="width: 100%;" type="text" option="cf_cdn" name="email" value="<?php echo esc_attr($email); ?>" >
</p>
<span class="cx-title">
<strong><?php esc_html_e('Global API Key: ','compressx')?></strong>
</span>
<p>
<input style="width: 100%;" type="password" autocomplete="new-password" option="cf_cdn" name="api_key" value="<?php echo esc_attr($api_key); ?>" >
</p>
<span class="cx-title">
<strong><?php esc_html_e('Zone ID: ','compressx')?></strong>
</span>
<p>
<input style="width: 100%;" type="password" autocomplete="new-password" option="cf_cdn" name="zone_id" value="<?php echo esc_attr($zone_id); ?>" >
</p>
<span class="cx-title">
<strong><?php esc_html_e('Purge Cache Automatically: ','compressx')?></strong>
</span>
<p>
<input id="compressx_auto_purge_cache" type="checkbox" option="cf_cdn" name="auto_purge_cache" <?php echo esc_attr($auto_purge_cache); ?>>
<?php esc_html_e('Purge all cache automatically after successfully converting images in bulk.','compressx')?>
</p>
<p>
<input id="compressx_auto_purge_cache_after_manual" type="checkbox" option="cf_cdn" name="auto_purge_cache_after_manual" <?php echo esc_attr($auto_purge_cache_after_manual); ?>>
<?php esc_html_e('Purge all cache automatically after 5 minutes of manually converting images on media library.','compressx')?>
</p>
</div>
<div class="compressing-converting">
<div class="compressing-converting-information">
<span><strong><?php esc_html_e('Cloudflare Email:','compressx')?></strong> <?php esc_html_e('Email address associated to your Cloudflare account','compressx')?></span>
<p><span><strong><?php esc_html_e('Global API Key:','compressx')?></strong> <?php esc_html_e('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')?></span></p>
<span><strong><?php esc_html_e('Zone ID:','compressx')?></strong> <?php esc_html_e('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')?></span>
<br>
</div>
<div>
<p>
<input id="compressx_purge_cache" class="button" type="submit" value="<?php esc_attr_e('Purge All Cloudflare CDN Cache Manually','compressx')?>">
<span style="padding:0 0.2rem;"></span>
<span id="compressx_purge_cache_progress" style="display: none">
<img src="../wp-admin/images/loading.gif" alt="">
</span>
<span id="compressx_purge_cache_text" class="success hidden" aria-hidden="true" style="color:#007017"><?php esc_html_e('Done!','compressx')?></span>
</p>
</div>
</div>
</div>
</div>
<div class="compressx-general-settings-footer">
<input class="button-primary cx-button" id="compressx_save_cdn" type="submit" value="<?php esc_attr_e('Save Changes','compressx')?>">
<span style="padding:0 0.2rem;"></span>
<span id="compressx_save_cdn_progress" style="display: none">
<img src="../wp-admin/images/loading.gif" alt="">
</span>
<span id="compressx_save_cdn_text" class="success hidden" aria-hidden="true" style="color:#007017"><?php esc_html_e('Saved!','compressx')?></span>
</div>
</div>
</div>
</section>
<script>
jQuery('#compressx_save_cdn').click(function()
{
compressx_save_cdn_setting();
});
jQuery('#compressx_purge_cache').click(function()
{
compressx_purge_cache();
});
//
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);
});
}
function compressx_save_cdn_setting()
{
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_save_cdn',
'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);
});
}
</script>
<?php
}
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());
$options['cf_cdn']['zone_id']=$setting['zone_id'];
$options['cf_cdn']['email']=$setting['email'];
$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
{
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>wp-content:</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,324 @@
<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
class CompressX_Custom_Media_Lib
{
public function __construct()
{
if(is_multisite())
return;
add_filter( 'manage_media_columns', array($this,'optimize_columns'));
add_action( 'manage_media_custom_column', array($this, 'optimize_column_display'),10,2);
add_action( 'attachment_submitbox_misc_actions', array( $this,'submitbox') );
add_filter( 'wp_prepare_attachment_for_js', array($this,'attachment_fields_to_edit'), 10, 2 );
add_action('wp_ajax_compressx_get_opt_single_image_progress', array($this, 'get_opt_single_image_progress'));
//wp_prepare_attachment_for_js
//add_action( 'restrict_manage_posts', array($this,'add_dropdown') );
//add_action( 'pre_get_posts', array( $this, 'filter_posts' ) );
}
public function optimize_columns($defaults)
{
$defaults['compressx'] = 'CompressX';
return $defaults;
}
public function optimize_column_display($column_name, $id )
{
if ( 'compressx' === $column_name )
{
echo $this->optimize_action_columns( $id );
}
}
public function optimize_action_columns($id)
{
$allowed_mime_types = CompressX_Image_Opt_Method::supported_mime_types_ex();
if ( ! wp_attachment_is_image( $id ) || ! in_array( get_post_mime_type( $id ),$allowed_mime_types ) )
{
return __('Not support','compressx');
}
$html=$this->output_item($id);
return $html;
}
public function submitbox()
{
global $post;
$id=$post->ID;
$allowed_mime_types = CompressX_Image_Method::supported_mime_types_ex();
if ( ! wp_attachment_is_image( $post->ID ) || ! in_array( get_post_mime_type( $post->ID ),$allowed_mime_types ) )
{
echo esc_html__('Not support','compressx');
return;
}
if($this->is_skipped($id))
{
echo esc_html__('Skipped','compressx');
return;
}
$html=$this->output_item_edit($id);
echo $html;
}
public function attachment_fields_to_edit(array $response, \WP_Post $attachment)
{
$source_post_id = (string) isset( $_REQUEST['post_id'])?$_REQUEST['post_id']:'';
if ( $source_post_id !== '0' )
{
return $response;
}
$allowed_mime_types = CompressX_Image_Method::supported_mime_types_ex();
if ( ! wp_attachment_is_image( $attachment->ID ) || ! in_array( get_post_mime_type( $attachment->ID ),$allowed_mime_types ) )
{
return $response;
}
$html=$this->output_item_attachment($attachment->ID);
$response['compat']['meta'] .=$html;
return $response;
}
public function output_item($id)
{
if($this->is_skipped($id))
{
return __('Skipped','compressx');
}
$html='<div class="cx-media-item" data-id="'.esc_attr($id).'">';
$html.='<ul>';
$html.=$this->output_item_detail($id);
$html.=$this->output_item_action($id);
$html.='</ul>';
$html.='</div>';
return $html;
}
public function output_item_edit($id)
{
if($this->is_skipped($id))
{
return __('Skipped','compressx');
}
$html='<div class="misc-pub-section misc-pub-cx" data-id="'.esc_attr($id).'"><h4>' . esc_html__('CompressX','compressx') . '</h4>';
$html.='<ul>';
$html.=$this->output_item_detail($id);
$html.=$this->output_item_action($id);
$html.='</ul>';
$html.='</div>';
return $html;
}
public function output_item_attachment($id)
{
$html='<div class="cx-media-attachment" data-id="'.esc_attr($id).'"><h4>' . esc_html__('CompressX','compressx') . '</h4>';
$html.='<ul>';
$html.=$this->output_item_detail($id);
$html.=$this->output_item_action($id);
$html.='</ul>';
$html.='</div>';
return $html;
}
public function output_item_detail($id)
{
$html='';
$og_size=CompressX_Image_Meta_V2::get_og_size($id);
if(empty($og_size))
{
$file_path = get_attached_file( $id );
if(file_exists($file_path))
$og_size=filesize($file_path);
else
$og_size=0;
}
$html.='<li><span>Original : </span><strong>'.esc_html(size_format($og_size,2)).'</strong></li>';
$webp_size=CompressX_Image_Meta_V2::get_webp_converted_size($id);
if($webp_size>0&&$og_size>$webp_size)
{
$webp_percent = round(100 - ($webp_size / $og_size) * 100, 2);
}
else
{
$webp_percent=0;
}
$html.='<li><span>Webp : <strong>'.esc_html(size_format($webp_size,2)).'</strong> Saved : <strong>'.esc_html($webp_percent).'%</strong></span></li>';
$avif_size=CompressX_Image_Meta_V2::get_avif_converted_size($id);
if($avif_size>0&&$og_size>$avif_size)
{
$avif_percent = round(100 - ($avif_size / $og_size) * 100, 2);
}
else
{
$avif_percent=0;
}
$html.='<li><span>AVIF : <strong>'.esc_html(size_format($avif_size,2)).'</strong> Saved : <strong>'.esc_html($avif_percent).'%</strong></span></li>';
$meta=CompressX_Image_Meta_V2::get_image_meta($id);
if(isset($meta['size'])&&!empty($meta['size']))
{
$thumbnail_counts=count($meta['size']);
}
else
{
$thumbnail_counts=0;
}
$html.='<li><span>Thumbnails generated : </span><strong>'.esc_html($thumbnail_counts).'</strong></li>';
return $html;
}
public function output_item_action($id)
{
$html='<li>';
$html.='<select class="cx-media-selected">';
$html.='<option value="">Select Action</option>';
if(CompressX_Image_Meta_V2::is_image_optimized($id))
{
$html.='<option value="delete">Delete</option>';
}
else
{
$html.='<option value="convert">Convert</option>';
if(CompressX_Image_Meta_V2::has_optimized_file($id))
{
$html.='<option value="delete">Delete</option>';
}
}
$html.='</select>';
if($this->is_image_progressing($id))
{
$html.='<a class="cx-media button-disabled button" data-id="'.esc_attr($id).'">Progressing</a>';
}
else
{
$html.='<a class="cx-media button" data-id="'.esc_attr($id).'">Apply</a>';
}
$html.='</li>';
return $html;
}
public function is_skipped($image_id)
{
if(CompressX_Image_Meta_V2::get_image_meta_status($image_id)==='skip')
{
return true;
}
else
{
return false;
}
}
public function is_image_progressing($post_id)
{
$progressing=CompressX_Image_Meta_V2::get_image_progressing($post_id);
if(empty($progressing))
{
return false;
}
else
{
$current_time=time();
if(($current_time-$progressing)>180)
{
return false;
}
else
{
return true;
}
}
}
public function get_opt_single_image_progress()
{
global $compressx;
$compressx->ajax_check_security('compressx-can-convert');
if(!isset($_POST['ids'])||!is_string($_POST['ids']))
{
die();
}
$ids=sanitize_text_field($_POST['ids']);
$ids=json_decode($ids,true);
$running=false;
if(isset($_POST['page']))
{
$page=sanitize_text_field($_POST['page']);
}
else
{
$page='media';
}
foreach ($ids as $id)
{
if(!CompressX_Image_Meta_V2::is_image_optimized($id))
{
if($this->is_image_progressing($id))
{
$running=true;
break;
}
}
}
$ret['result']='success';
if($running)
{
$ret['continue']=1;
$ret['finished']=0;
}
else
{
$ret['continue']=0;
$ret['finished']=1;
}
foreach ($ids as $id)
{
if($page=='edit')
{
$html=$this->output_item_edit($id);
}
else
{
$html=$this->output_item($id);
}
$ret[$id]['html']=$html;
}
echo wp_json_encode($ret);
die();
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,891 @@
<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
class CompressX_Display
{
public $dashboard;
public $bulk_action;
public $custom_bulk_action;
public $log;
public $system_info;
public $cdn;
public $compression;
public $addons;
public $image_optimization;
public $settings;
public $media_replace;
public function __construct()
{
$this->load_v2();
/*
$interface_version = CompressX_Options::get_interface_version();
if($interface_version === 'v2')
{
$this->load_v2();
}
else
{
$this->load();
}*/
}
/*
public function load()
{
include_once COMPRESSX_DIR . '/includes/display/class-compressx-dashboard.php';
include_once COMPRESSX_DIR . '/includes/display/class-compressx-bulk-action.php';
include_once COMPRESSX_DIR . '/includes/display/class-compressx-custom-bulk-action.php';
include_once COMPRESSX_DIR . '/includes/display/class-compressx-cdn.php';
include_once COMPRESSX_DIR . '/includes/display/class-compressx-logs.php';
include_once COMPRESSX_DIR . '/includes/display/class-compressx-system-info.php';
include_once COMPRESSX_DIR . '/includes/display/class-compressx-addons.php';
$this->dashboard=new CompressX_Dashboard();
$this->bulk_action=new CompressX_Bulk_Action();
$this->custom_bulk_action=new CompressX_Custom_Bulk_Action();
$this->cdn=new CompressX_CDN();
$this->log=new CompressX_Logs();
$this->system_info=new CompressX_System_Info();
$this->addons=new CompressX_Addons();
add_action('admin_enqueue_scripts',array( $this,'enqueue_styles'));
add_action('admin_enqueue_scripts',array( $this,'enqueue_scripts'));
add_action('compressx_output_nav',array( $this,'output_nav'));
add_action('compressx_output_header',array( $this,'output_header'));
add_action('compressx_output_footer',array( $this,'output_footer'));
if(is_multisite())
{
add_action('network_admin_menu',array( $this,'add_plugin_network_admin_menu'));
}
else
{
add_action('admin_menu',array( $this,'add_plugin_admin_menu'));
}
}
*/
public function load_v2()
{
include_once COMPRESSX_DIR . '/includes/display_v2/class-compressx-image-optimization-display.php';
include_once COMPRESSX_DIR . '/includes/display_v2/class-compressx-bulk-optimization-display.php';
$this->image_optimization=new CompressX_Image_Optimization_Display();
include_once COMPRESSX_DIR . '/includes/display_v2/class-compressx-settings-display.php';
$this->settings=new CompressX_Settings_Display();
include_once COMPRESSX_DIR . '/includes/display_v2/class-compressx-cdn-display.php';
$this->cdn=new CompressX_CDN_Display();
include_once COMPRESSX_DIR . '/includes/display_v2/class-compressx-system-info-display.php';
$this->system_info=new CompressX_System_Info_Display();
include_once COMPRESSX_DIR . '/includes/display_v2/class-compressx-addons-display.php';
$this->addons=new CompressX_Addons_Display();
include_once COMPRESSX_DIR . '/includes/display_v2/class-compressx-custom-bulk-action-v2.php';
$this->custom_bulk_action=new CompressX_Custom_Bulk_Action_V2();
//
include_once COMPRESSX_DIR . '/includes/display_v2/class-compressx-media-replace-display.php';
$this->media_replace=new CompressX_Media_Replace_Display();
add_action('admin_enqueue_scripts',array( $this,'enqueue_styles_v2'));
add_action('admin_enqueue_scripts',array( $this,'enqueue_scripts_v2'));
add_action('compressx_output_nav',array( $this,'output_nav'));
add_action('compressx_output_header',array( $this,'output_header'));
add_action('compressx_output_footer',array( $this,'output_footer_v2'));
if(is_multisite())
{
add_action('network_admin_menu',array( $this,'add_plugin_network_admin_menu'));
}
else
{
add_action('admin_menu',array( $this,'add_plugin_admin_menu_v2'));
add_action('admin_menu',array( $this,'add_media_replace_menu'));
add_action('submenu_file', array($this, 'hide_media_replace_menu'));
}
}
public function enqueue_styles()
{
if(is_multisite())
{
$screen_ids[]='toplevel_page_CompressX-network';
}
else
{
$screen_ids[]='toplevel_page_'.COMPRESSX_SLUG;
$screen_ids[]='compressx_page_info-compressx';
$screen_ids[]='compressx_page_logs-compressx';
$screen_ids[]='compressx_page_cdn-compressx';
$screen_ids[]='compressx_page_addons-compressx';
$screen_ids[]='compressx_page_compression-level-compressx';
}
$screen_ids=apply_filters('compressx_get_screen_ids',$screen_ids);
if(in_array(get_current_screen()->id,$screen_ids))
{
wp_enqueue_style(COMPRESSX_SLUG.'jstree', COMPRESSX_URL . '/includes/display/js/jstree/dist/themes/default/style.min.css', array(), COMPRESSX_VERSION, 'all');
wp_enqueue_style(COMPRESSX_SLUG, COMPRESSX_URL . '/includes/display/css/compressx-style.css', array(), COMPRESSX_VERSION, 'all');
wp_enqueue_style(COMPRESSX_SLUG.'-percentage-circle-style', COMPRESSX_URL . '/includes/display/css/compressx-percentage-circle-style.css', array(), COMPRESSX_VERSION, 'all');
}
else if(get_current_screen()->id=='upload'||get_current_screen()->id=='attachment')
{
wp_enqueue_style(COMPRESSX_SLUG, COMPRESSX_URL . '/includes/display/css/compressx-media.css', array(), COMPRESSX_VERSION, 'all');
}
}
public function enqueue_scripts()
{
$screen_ids[]='toplevel_page_'.COMPRESSX_SLUG;
$screen_ids[]='compressx_page_info-compressx';
$screen_ids[]='compressx_page_logs-compressx';
$screen_ids[]='compressx_page_cdn-compressx';
$screen_ids[]='compressx_page_compression-level-compressx';
$screen_ids=apply_filters('compressx_get_screen_ids',$screen_ids);
if(in_array(get_current_screen()->id,$screen_ids))
{
wp_enqueue_script(COMPRESSX_SLUG, COMPRESSX_URL . '/includes/display/js/compressx.js', array('jquery'), COMPRESSX_VERSION, false);
wp_enqueue_script(COMPRESSX_SLUG.'jstree', COMPRESSX_URL . '/includes/display/js/jstree/dist/jstree.min.js', array('jquery'), COMPRESSX_VERSION, false);
wp_localize_script(COMPRESSX_SLUG, 'compressx_ajax_object', array('ajax_url' => admin_url('admin-ajax.php'),'ajax_nonce'=>wp_create_nonce('compressx_ajax')));
wp_enqueue_script('plupload-all');
}
else if(get_current_screen()->id=='upload'||get_current_screen()->id=='attachment')
{
wp_enqueue_script(COMPRESSX_SLUG, COMPRESSX_URL . '/includes/display/js/compressx.js', array('jquery'), COMPRESSX_VERSION, false);
wp_enqueue_script(COMPRESSX_SLUG.'_media', COMPRESSX_URL . '/includes/display/js/optimize.js', array('jquery'), COMPRESSX_VERSION, true);
wp_localize_script(COMPRESSX_SLUG, 'compressx_ajax_object', array('ajax_url' => admin_url('admin-ajax.php'),'ajax_nonce'=>wp_create_nonce('compressx_ajax')));
}
$toplevel_screen_id='toplevel_page_'.COMPRESSX_SLUG;
$toplevel_screen_id=apply_filters('compressx_get_screen_id',$toplevel_screen_id);
if(get_current_screen()->id==$toplevel_screen_id)
{
$arg=array();
$arg['in_footer']=true;
$upload_dir = wp_upload_dir();
$path = $upload_dir['basedir'];
$path = str_replace('\\','/',$path);
$uploads_path = $path.'/';
$path = WP_CONTENT_DIR;
$path = str_replace('\\','/',$path);
$custom_root_path = $path.'/';
if(CompressX_Image_Opt_Method::check_imagick_avif())
{
wp_localize_script(COMPRESSX_SLUG, 'compressx_alert', array('imagick_avif' => false));
}
else
{
wp_localize_script(COMPRESSX_SLUG, 'compressx_alert', array('imagick_avif' => true));
}
wp_localize_script(COMPRESSX_SLUG, 'compressx_uploads_root', array('path' => $uploads_path,'custom_path'=>$custom_root_path));
wp_enqueue_script(COMPRESSX_SLUG.'_setting', COMPRESSX_URL . '/includes/display/js/compressx_setting.js', array('jquery'), COMPRESSX_VERSION, $arg);
wp_enqueue_script(COMPRESSX_SLUG.'_custom_bulk', COMPRESSX_URL . '/includes/display/js/compressx_custom_bulk.js', array('jquery'), COMPRESSX_VERSION, $arg);
}
$cdn_screen_id='compressx_page_cdn-compressx';
$cdn_screen_id=apply_filters('compressx_get_screen_id',$cdn_screen_id);
if(get_current_screen()->id=='compressx_page_cdn-compressx')
{
$arg=array();
$arg['in_footer']=true;
wp_enqueue_script(COMPRESSX_SLUG.'_setting', COMPRESSX_URL . '/includes/display/js/compressx_setting.js', array('jquery'), COMPRESSX_VERSION, $arg);
}
$logs_screen_id='compressx_page_logs-compressx';
$logs_screen_id=apply_filters('compressx_get_screen_id',$logs_screen_id);
if(get_current_screen()->id==$logs_screen_id)
{
$arg=array();
$arg['in_footer']=true;
wp_enqueue_script(COMPRESSX_SLUG.'_logs', COMPRESSX_URL . '/includes/display/js/compressx_log.js', array('jquery'), COMPRESSX_VERSION, $arg);
}
$info_screen_id='compressx_page_info-compressx';
$info_screen_id=apply_filters('compressx_get_screen_id',$info_screen_id);
if(get_current_screen()->id==$info_screen_id)
{
$arg=array();
$arg['in_footer']=true;
wp_enqueue_script(COMPRESSX_SLUG.'_systeminfo', COMPRESSX_URL . '/includes/display/js/compressx_system_info.js', array('jquery'), COMPRESSX_VERSION, $arg);
}
}
public function enqueue_styles_v2()
{
if(is_multisite())
{
$screen_ids[]='toplevel_page_CompressX-network';
}
else
{
$screen_ids[]='toplevel_page_'.COMPRESSX_SLUG;
$screen_ids[]='compressx_page_image-optimization-compressx';
$screen_ids[]='compressx_page_settings-compressx';
$screen_ids[]='compressx_page_cdn-compressx';
$screen_ids[]='compressx_page_info-compressx';
$screen_ids[]='compressx_page_addons-compressx';
//Replace Media
$screen_ids[]='media_page_media-replace-compressx';
}
$screen_ids=apply_filters('compressx_get_screen_ids',$screen_ids);
if(in_array(get_current_screen()->id,$screen_ids))
{
wp_enqueue_style(COMPRESSX_SLUG.'jstree', COMPRESSX_URL . '/includes/display/js/jstree/dist/themes/default/style.min.css', array(), COMPRESSX_VERSION, 'all');
wp_enqueue_style(COMPRESSX_SLUG.'_v2', COMPRESSX_URL . '/includes/display_v2/css/compressx-style-v2.css', array(), COMPRESSX_VERSION, 'all');
wp_enqueue_style(COMPRESSX_SLUG.'-percentage-circle-style', COMPRESSX_URL . '/includes/display/css/compressx-percentage-circle-style.css', array(), COMPRESSX_VERSION, 'all');
wp_enqueue_style(COMPRESSX_SLUG.'-twentytwenty', COMPRESSX_URL . '/includes/display_v2/css/twentytwenty/twentytwenty.css', array(), COMPRESSX_VERSION);
wp_enqueue_style(COMPRESSX_SLUG.'-folder-tree', COMPRESSX_URL . '/includes/display_v2/css/compressx-folder-tree.css', array(), COMPRESSX_VERSION, 'all');
}
else if(get_current_screen()->id=='upload'||get_current_screen()->id=='attachment')
{
wp_enqueue_style(COMPRESSX_SLUG, COMPRESSX_URL . '/includes/display/css/compressx-media.css', array(), COMPRESSX_VERSION, 'all');
}
}
public function enqueue_scripts_v2()
{
$screen_ids[]='toplevel_page_'.COMPRESSX_SLUG;
$screen_ids[]='compressx_page_image-optimization-compressx';
$screen_ids[]='compressx_page_settings-compressx';
$screen_ids[]='compressx_page_cdn-compressx';
$screen_ids[]='compressx_page_info-compressx';
$screen_ids[]='compressx_page_addons-compressx';
$screen_ids[]='media_page_media-replace-compressx';
$screen_ids=apply_filters('compressx_get_screen_ids',$screen_ids);
if(in_array(get_current_screen()->id,$screen_ids))
{
wp_enqueue_script(COMPRESSX_SLUG, COMPRESSX_URL . '/includes/display/js/compressx.js', array('jquery'), COMPRESSX_VERSION, false);
wp_enqueue_script(COMPRESSX_SLUG.'jstree', COMPRESSX_URL . '/includes/display/js/jstree/dist/jstree.min.js', array('jquery'), COMPRESSX_VERSION, false);
wp_localize_script(COMPRESSX_SLUG, 'compressx_ajax_object', array('ajax_url' => admin_url('admin-ajax.php'),'ajax_nonce'=>wp_create_nonce('compressx_ajax')));
wp_enqueue_script('plupload-all');
}
else if(get_current_screen()->id=='upload'||get_current_screen()->id=='attachment')
{
wp_enqueue_script(COMPRESSX_SLUG, COMPRESSX_URL . '/includes/display/js/compressx.js', array('jquery'), COMPRESSX_VERSION, false);
wp_enqueue_script(COMPRESSX_SLUG.'_media', COMPRESSX_URL . '/includes/display/js/optimize.js', array('jquery'), COMPRESSX_VERSION, true);
wp_localize_script(COMPRESSX_SLUG, 'compressx_ajax_object', array('ajax_url' => admin_url('admin-ajax.php'),'ajax_nonce'=>wp_create_nonce('compressx_ajax')));
}
$toplevel_screen_id='toplevel_page_'.COMPRESSX_SLUG;
$toplevel_screen_id=apply_filters('compressx_get_screen_id',$toplevel_screen_id);
if(get_current_screen()->id==$toplevel_screen_id)
{
$arg=array();
$arg['in_footer']=true;
if(CompressX_Image_Opt_Method::check_imagick_avif())
{
$imagick_avif=false;
}
else
{
$imagick_avif=true;
}
if(CompressX_Image_Method::is_support_gd_webp())
{
$support_gd_webp=true;
}
else
{
$support_gd_webp=false;
}
if(CompressX_Image_Method::is_support_imagick_webp())
{
$support_imagick_webp=true;
}
else
{
$support_imagick_webp=false;
}
if(CompressX_Image_Method::is_support_gd_avif())
{
$support_gd_avif=true;
}
else
{
$support_gd_avif=false;
}
if(CompressX_Image_Method::is_support_imagick_avif())
{
$support_imagick_avif=true;
}
else
{
$support_imagick_avif=false;
}
wp_localize_script(COMPRESSX_SLUG, 'compressx_alert',
array('imagick_avif' => $imagick_avif,
'support_gd_webp'=>$support_gd_webp,
'support_imagick_webp'=>$support_imagick_webp,
'support_gd_avif'=>$support_gd_avif,
'support_imagick_avif'=>$support_imagick_avif,
)
);
wp_enqueue_script('compressx-jquery-event-move', COMPRESSX_URL . '/includes/display/js/twentytwenty/jquery.event.move.js', array('jquery'), COMPRESSX_VERSION, $arg);
wp_enqueue_script('compressx-twentytwenty', COMPRESSX_URL . '/includes/display/js/twentytwenty/jquery.twentytwenty.js', array('jquery', 'compressx-jquery-event-move'), COMPRESSX_VERSION, $arg);
wp_enqueue_script(COMPRESSX_SLUG.'_image_optimization', COMPRESSX_URL . '/includes/display_v2/js/compressx_image_optimization.js', array('jquery'), COMPRESSX_VERSION, $arg);
wp_localize_script(
COMPRESSX_SLUG . '_image_optimization',
'compressx_image_optimization_i18n',
array(
'enable_webp_confirm' => __( 'Are you sure to enable WebP as output format? This will convert your images to WebP format.', 'compressx' ),
'disable_webp_confirm' => __( 'Are you sure to disable WebP as output format?', 'compressx' ),
'imagick6_avif_warning' => __( 'We detect that you use ImageMagick 6.x, this version has a known bug that can cause AVIF conversion timeout. Enabling AVIF conversion with this version is not recommended. Are you sure you wish to proceed?', 'compressx' ),
'enable_avif_confirm' => __( 'Are you sure to enable AVIF as output format? This will convert your images to AVIF format.', 'compressx' ),
'disable_avif_confirm' => __( 'Are you sure to disable AVIF as output format?', 'compressx' ),
'supported' => __( 'Supported', 'compressx' ),
'unsupported' => __( 'Unsupported', 'compressx' ),
'failed_save' => __( 'Failed to save settings.', 'compressx' ),
'save_error' => __( 'An error occurred while saving settings.', 'compressx' ),
)
);
wp_enqueue_script(COMPRESSX_SLUG.'_comparison', COMPRESSX_URL . '/includes/display_v2/js/compressx_image_comparison.js', array('jquery'), COMPRESSX_VERSION, $arg);
wp_enqueue_script(COMPRESSX_SLUG.'_bulk', COMPRESSX_URL . '/includes/display_v2/js/compressx_bulk.js', array('jquery'), COMPRESSX_VERSION, $arg);
wp_localize_script(
COMPRESSX_SLUG . '_bulk',
'compressx_bulk_i18n',
array(
'cancel_confirm' => __( 'Are you sure to cancel this progressing?', 'compressx' ),
'pause_confirm' => __( 'Are you sure to pause this progressing?', 'compressx' ),
'delete_log_confirm' => __( 'Are you sure you want to delete this log file?', 'compressx' ),
'leave_page_confirm' => __( 'Are you sure you want to leave this page?', 'compressx' ),
'optimization_success' => __( 'Optimization Success', 'compressx' ),
)
);
wp_enqueue_script('compressx-chart', COMPRESSX_URL . '/includes/display_v2/js/chart.umd.min.js', array('jquery'), COMPRESSX_VERSION, $arg);
}
$settings_screen_id='compressx_page_settings-compressx';
$settings_screen_id=apply_filters('compressx_get_screen_id',$settings_screen_id);
if(get_current_screen()->id==$settings_screen_id)
{
$arg=array();
$arg['in_footer']=true;
$upload_dir = wp_upload_dir();
$path = $upload_dir['basedir'];
$path = str_replace('\\','/',$path);
$uploads_path = $path.'/';
$path = WP_CONTENT_DIR;
$path = str_replace('\\','/',$path);
$custom_root_path = $path.'/';
wp_localize_script(COMPRESSX_SLUG, 'compressx_uploads_root', array('path' => $uploads_path,'custom_path'=>$custom_root_path));
wp_enqueue_script(COMPRESSX_SLUG.'_setting', COMPRESSX_URL . '/includes/display_v2/js/compressx_setting.js', array('jquery'), COMPRESSX_VERSION, $arg);
wp_enqueue_script(COMPRESSX_SLUG.'_custom_bulk', COMPRESSX_URL . '/includes/display/js/compressx_custom_bulk.js', array('jquery'), COMPRESSX_VERSION, $arg);
}
$cdn_screen_id='compressx_page_cdn-compressx';
$cdn_screen_id=apply_filters('compressx_get_screen_id',$cdn_screen_id);
if(get_current_screen()->id==$cdn_screen_id)
{
$arg=array();
$arg['in_footer']=true;
wp_enqueue_script(COMPRESSX_SLUG.'_cdn', COMPRESSX_URL . '/includes/display_v2/js/compressx_cdn.js', array('jquery'), COMPRESSX_VERSION, $arg);
}
$logs_screen_id='compressx_page_info-compressx';
$logs_screen_id=apply_filters('compressx_get_screen_id',$logs_screen_id);
if(get_current_screen()->id==$logs_screen_id)
{
$arg=array();
$arg['in_footer']=true;
wp_enqueue_script(COMPRESSX_SLUG.'_logs', COMPRESSX_URL . '/includes/display_v2/js/compressx_log.js', array('jquery'), COMPRESSX_VERSION, $arg);
}
$media_replace_id='media_page_media-replace-compressx';
if(get_current_screen()->id==$media_replace_id)
{
if (array_key_exists("attachment_id", $_GET) && intval($_GET["attachment_id"]) > 0)
{
$attachment_id = intval($_GET["attachment_id"]);
}
else
{
$attachment_id=0;
}
$mime_type=get_post_mime_type($attachment_id);
$file = get_attached_file($attachment_id);
$ft = wp_check_filetype($file);
$ext = !empty($ft['ext']) ? $ft['ext'] : '';
$type = $ext ? strtoupper($ext) : '-';
$url=admin_url("post.php?post=$attachment_id&action=edit");
wp_localize_script('CompressX', 'compressx_media_replace', array('redirect_url' => $url,'type'=>$type));
$arg=array();
$arg['in_footer']=true;
wp_enqueue_script('CompressX_media_replace', COMPRESSX_URL . '/includes/display_v2/js/compressx_media-replace.js', array('jquery'), COMPRESSX_VERSION, $arg);
return;
}
/*
$info_screen_id='compressx_page_info-compressx';
$info_screen_id=apply_filters('compressx_get_screen_id',$info_screen_id);
if(get_current_screen()->id==$info_screen_id)
{
$arg=array();
$arg['in_footer']=true;
wp_enqueue_script(COMPRESSX_SLUG.'_systeminfo', COMPRESSX_URL . '/includes/display/js/compressx_system_info.js', array('jquery'), COMPRESSX_VERSION, $arg);
}*/
}
public function add_plugin_network_admin_menu()
{
if(apply_filters('compressx_support_mu',false))
{
return;
}
$menu['page_title']= 'CompressX';
$menu['menu_title']= 'CompressX';
$menu['capability']='manage_options';
$menu['menu_slug']=COMPRESSX_SLUG;
$menu['function']=array($this, 'mu_display');
$menu['icon_url']='dashicons-images-alt2';
$menu['position']=100;
add_menu_page( $menu['page_title'],$menu['menu_title'], $menu['capability'], $menu['menu_slug'], $menu['function'], $menu['icon_url'], $menu['position']);
}
public function add_plugin_admin_menu()
{
$menu['page_title']= 'CompressX';
$menu['menu_title']= 'CompressX';
$menu['capability']='manage_options';
$menu['menu_slug']=COMPRESSX_SLUG;
$menu['function']=array($this->dashboard, 'display');
$menu['icon_url']='dashicons-images-alt2';
$menu['position']=100;
$menu = apply_filters('compressx_get_main_admin_menus', $menu);
add_menu_page( $menu['page_title'],$menu['menu_title'], $menu['capability'], $menu['menu_slug'], $menu['function'], $menu['icon_url'], $menu['position']);
$submenu['parent_slug']=COMPRESSX_SLUG;
$submenu['page_title']="Settings";
$submenu['menu_title']="Settings";
$submenu['capability']="manage_options";
$submenu['index']=1;
$submenu['menu_slug']=COMPRESSX_SLUG;
$submenu['function']=array($this->dashboard, 'display');
$submenus[ $submenu['menu_slug']]=$submenu;
if(apply_filters('compressx_current_user_can',true,'compressx-can-use-cdn'))
{
$submenu['parent_slug']=COMPRESSX_SLUG;
$submenu['page_title']="CDN Integration";
$submenu['menu_title']="CDN Integration";
$submenu['capability']="manage_options";
$submenu['menu_slug']="cdn-compressx";
$submenu['index']=3;
$submenu['function']=array($this->cdn, 'display');
$submenus[$submenu['menu_slug']]=$submenu;
}
if(apply_filters('compressx_current_user_can',true,'compressx-can-use-logs'))
{
$submenu['parent_slug']=COMPRESSX_SLUG;
$submenu['page_title']="Logs";
$submenu['menu_title']="Logs";
if(apply_filters('compressx_current_user_has',false,'compressx-can-use-logs'))
{
$submenu['capability']="compressx-can-use-logs";
}
else
{
$submenu['capability']="manage_options";
}
$submenu['menu_slug']="logs-compressx";
$submenu['index']=19;
$submenu['function']=array($this->log, 'display');
$submenus[$submenu['menu_slug']]=$submenu;
}
if(apply_filters('compressx_current_user_can',true,'compressx-can-use-system-info'))
{
$submenu['parent_slug']=COMPRESSX_SLUG;
$submenu['page_title']="System Information";
$submenu['menu_title']="System Information";
if(apply_filters('compressx_current_user_has',false,'compressx-can-use-system-info'))
{
$submenu['capability']="compressx-can-use-system-info";
}
else
{
$submenu['capability']="manage_options";
}
$submenu['menu_slug']="info-compressx";
$submenu['index']=20;
$submenu['function']=array($this->system_info, 'display');
$submenus[$submenu['menu_slug']]=$submenu;
}
$submenu['parent_slug']=COMPRESSX_SLUG;
$submenu['page_title']="Addons";
$submenu['menu_title']="Addons";
$submenu['capability']="manage_options";
$submenu['menu_slug']="addons-compressx";
$submenu['index']=21;
$submenu['function']=array($this->addons, 'display');
$submenus[$submenu['menu_slug']]=$submenu;
$submenus = apply_filters('compressx_get_admin_menus', $submenus);
usort($submenus, function ($a, $b)
{
if ($a['index'] == $b['index'])
return 0;
if ($a['index'] > $b['index'])
return 1;
else
return -1;
});
foreach ($submenus as $submenu)
{
add_submenu_page(
$submenu['parent_slug'],
$submenu['page_title'],
$submenu['menu_title'],
$submenu['capability'],
$submenu['menu_slug'],
$submenu['function']);
}
}
public function add_plugin_admin_menu_v2()
{
$menu['page_title']= 'CompressX';
$menu['menu_title']= 'CompressX';
$menu['capability']='manage_options';
$menu['menu_slug']=COMPRESSX_SLUG;
$menu['function']=array($this->image_optimization, 'display');
$menu['icon_url']='dashicons-images-alt2';
$menu['position']=100;
$menu = apply_filters('compressx_get_main_admin_menus', $menu);
add_menu_page( $menu['page_title'],$menu['menu_title'], $menu['capability'], $menu['menu_slug'], $menu['function'], $menu['icon_url'], $menu['position']);
if (apply_filters('compressx_current_user_can', true, 'compressx-can-convert'))
{
$submenu['parent_slug'] = COMPRESSX_SLUG;
$submenu['page_title'] = "Image Optimization";
$submenu['menu_title'] = "Image Optimization";
if (apply_filters('compressx_current_user_has', false, 'compressx-can-convert'))
{
$submenu['capability'] = "compressx-can-convert";
} else {
$submenu['capability'] = "manage_options";
}
$submenu['index'] = 1;
$submenu['menu_slug'] = COMPRESSX_SLUG;
$submenu['function'] = array($this->image_optimization, 'display');
$submenus[$submenu['menu_slug']] = $submenu;
}
if (apply_filters('compressx_current_user_can', true, 'compressx-can-use-general-settings') || apply_filters('compressx_current_user_can', true, 'compressx-can-use-thumbnail-settings')) {
$submenu['parent_slug'] = COMPRESSX_SLUG;
$submenu['page_title'] = "Global Settings";
$submenu['menu_title'] = "Settings";
$submenu['capability'] = "manage_options";
$submenu['menu_slug'] = "settings-compressx";
$submenu['index'] = 2;
$submenu['function'] = array($this->settings, 'display');
$submenus[$submenu['menu_slug']] = $submenu;
}
if (apply_filters('compressx_current_user_can', true, 'compressx-can-use-cdn')) {
$submenu['parent_slug'] = COMPRESSX_SLUG;
$submenu['page_title'] = "CDN Support";
$submenu['menu_title'] = "CDN Support";
if (apply_filters('compressx_current_user_has', false, 'compressx-can-use-cdn')) {
$submenu['capability'] = "compressx-can-use-cdn";
} else {
$submenu['capability'] = "manage_options";
}
$submenu['menu_slug'] = "cdn-compressx";
$submenu['index'] = 3;
$submenu['function'] = array($this->cdn, 'display');
$submenus[$submenu['menu_slug']] = $submenu;
}
if (apply_filters('compressx_current_user_can', true, 'compressx-can-use-system-info')) {
$submenu['parent_slug'] = COMPRESSX_SLUG;
$submenu['page_title'] = "Logs & System Information";
$submenu['menu_title'] = "Logs & System Info";
if (apply_filters('compressx_current_user_has', false, 'compressx-can-use-system-info')) {
$submenu['capability'] = "compressx-can-use-system-info";
} else {
$submenu['capability'] = "manage_options";
}
$submenu['menu_slug'] = "info-compressx";
$submenu['index'] = 19;
$submenu['function'] = array($this->system_info, 'display');
$submenus[$submenu['menu_slug']] = $submenu;
}
$submenu['parent_slug']=COMPRESSX_SLUG;
$submenu['page_title']="Addons";
$submenu['menu_title']="Addons";
$submenu['capability']="manage_options";
$submenu['menu_slug']="addons-compressx";
$submenu['index']=21;
$submenu['function']=array($this->addons, 'display');
$submenus[$submenu['menu_slug']] = $submenu;
$submenus = apply_filters('compressx_get_admin_menus', $submenus);
usort($submenus, function ($a, $b)
{
if ($a['index'] == $b['index'])
return 0;
if ($a['index'] > $b['index'])
return 1;
else
return -1;
});
foreach ($submenus as $submenu)
{
add_submenu_page(
$submenu['parent_slug'],
$submenu['page_title'],
$submenu['menu_title'],
$submenu['capability'],
$submenu['menu_slug'],
$submenu['function']);
}
}
public function add_media_replace_menu()
{
$has=false;
if(apply_filters('compressx_pro_media_replace',$has))
{
return;
}
$submenu['parent_slug']='upload.php';
$submenu['page_title']="Replace Media";
$submenu['menu_title']="Replace Media";
$submenu['capability']="upload_files";
$submenu['menu_slug']="media-replace-compressx";
$submenu['function']=array($this->media_replace, 'display');
add_submenu_page( $submenu['parent_slug'],$submenu['page_title'], $submenu['menu_title'], $submenu['capability'], $submenu['menu_slug'], $submenu['function']);
}
public function hide_media_replace_menu($submenu_file)
{
$has=false;
if(apply_filters('compressx_pro_media_replace',$has))
{
return $submenu_file;
}
global $plugin_page;
// Select another submenu item to highlight (optional).
if ( $plugin_page && $plugin_page == 'media-replace-compressx' )
{
$submenu_file = 'upload.php';
}
// Hide the submenu.
remove_submenu_page( 'upload.php', 'media-replace-compressx' );
return $submenu_file;
}
public function mu_display()
{
?>
<div id="compressx-root">
<div id="compressx-wrap">
<?php
$this->output_nav();
$this->output_header();
?>
<section style="display:block;">
<div class="compressx-container compressx-section">
<div class="compressx-notification">
<p><span class="dashicons dashicons-warning" style="color:#FF3951;"></span>
<span>Currently, AVIF, WebP Converter Plugin (CompressX.io) does not support WordPress Multisite.</span>
</p>
</div>
</div>
</section>
</div>
</div>
<?php
}
public function output_nav()
{
?>
<nav>
<div class="compressx-container compressx-menu">
<h2>Compress<span style="color:#175cff;">X</span><span style="font-size:1.2rem;">.io</span>
<span class="compressx-pro-version" style="font-size:0.7rem;">
<span><?php echo esc_html(COMPRESSX_VERSION);?></span><span> FREE</span>
<?php
if($this->check_update())
{
$url=get_admin_url().'plugins.php?s=compressx&plugin_status=all';
?><span style="padding:0 0.2rem"></span><a href="<?php echo esc_url($url)?>">(Latest Version: <?php echo esc_html( $this->latest_version());?>)</a><?php
}
?>
</span>
</h2>
<ul class="cx-menu-ul-large">
<li><a href="https://compressx.io/docs/compressx-overview/"><strong><?php esc_html_e('Documentation','compressx')?></strong></a></li>
<li><a href="https://compressx.io/docs/troubleshooting/"><strong><?php esc_html_e('Troubleshooting','compressx')?></strong></a></li>
<li><a href="https://wordpress.org/support/plugin/compressx/"><strong><?php esc_html_e('Support','compressx')?></strong></a></li>
</ul>
<ul class="cx-menu-ul-mini">
<li><a href="">Documentation</a></li>
</ul>
</div>
</nav>
<?php
}
public function check_update()
{
$update_data = wp_get_update_data();
if (isset($update_data['counts']['plugins']))
{
$plugins = get_site_transient('update_plugins');
if (isset($plugins->response[COMPRESSX_NAME]))
{
$plugin_data = $plugins->response[COMPRESSX_NAME];
$latest_version = $plugin_data->new_version;
if(version_compare($latest_version,COMPRESSX_VERSION,'>'))
{
return true;
}
}
}
return false;
}
public function latest_version()
{
$plugins = get_site_transient('update_plugins');
if (isset($plugins->response[COMPRESSX_NAME]))
{
$plugin_data = $plugins->response[COMPRESSX_NAME];
return $plugin_data->new_version;
}
else
{
return '';
}
}
public function output_header()
{
?>
<header>
<div class="compressx-container compressx-header">
</div>
</header>
<?php
}
public function output_footer()
{
?>
<footer>
<div class="compressx-container compressx-menu">
<div style="margin: auto;"><strong><span>If you like our plugin, a <a href="https://wordpress.org/support/plugin/compressx/reviews"><span class="dashicons dashicons-star-filled" style="color:#ffb900;"></span>
<span class="dashicons dashicons-star-filled" style="color:#ffb900;"></span>
<span class="dashicons dashicons-star-filled" style="color:#ffb900;"></span>
<span class="dashicons dashicons-star-filled" style="color:#ffb900;"></span>
<span class="dashicons dashicons-star-filled" style="color:#ffb900;"></span></a>
<span>will help us a lot, thanks in advance!</span></strong>
</div>
</div>
</footer>
<?php
}
public function output_footer_v2()
{
$defaults = array(
'show_review_link' => true,
'review_url' => 'https://wordpress.org/support/plugin/compressx/reviews',
'review_text' => __('Enjoying CompressX? Please', 'compressx') .
'<a href="%s" target="_blank">' .
__('leave us a', 'compressx') . ' ' .
'<span class="compressx-v2-text-yellow-500">★★★★★</span> ' .
__('review', 'compressx') .
'</a> — ' .
__('it helps a lot!', 'compressx'),
'container_class' => 'compressx-v2-border-t compressx-v2-pt-4 compressx-v2-text-center',
'text_class' => 'compressx-v2-text-sm compressx-v2-text-gray-600'
);
$args=$defaults;
if (!$args['show_review_link'])
{
return;
}
?>
<!-- Footer -->
<div class="<?php echo esc_attr($args['container_class']) ?>">
<p class="<?php echo esc_attr($args['text_class']) ?>">
<?php echo wp_kses_post(sprintf($args['review_text'], esc_url($args['review_url']))); ?>
</p>
</div>
<?php
}
}
@@ -0,0 +1,642 @@
<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
class CompressX_Logs
{
public function __construct()
{
//add_action('wp_ajax_compressx_open_log',array( $this,'open_log'));
//add_action('wp_ajax_compressx_download_log', array($this, 'download_log'));
//add_action('wp_ajax_compressx_delete_log', array($this, 'delete_log'));
//add_action('wp_ajax_compressx_delete_all_log', array($this, 'delete_all_log'));
//
//add_action('wp_ajax_compressx_get_logs_list', array($this, 'get_logs_list'));
}
public function display()
{
?>
<div id="compressx-root">
<div id="compressx-wrap">
<?php
$this->output_nav();
$this->output_header();
$this->output_logs();
$this->output_footer();
?>
</div>
</div>
<?php
}
public function output_nav()
{
do_action('compressx_output_nav');
}
public function output_header()
{
do_action('compressx_output_header');
}
public function output_footer()
{
do_action('compressx_output_footer');
}
public function output_logs()
{
?>
<section>
<div class="compressx-container compressx-header">
<div class="compressx-logs">
<article>
<div class="cx-title"><span><?php esc_html_e('Logs: ','compressx')?></span>
<span class="cx-bulk-opt-results">
<span><a style="cursor: pointer" id="cx_empty_log"><?php esc_html_e('Empty Logs','compressx')?></a></span>
</div>
<div id="cx_log_list" class="cx-table-overflow">
<?php
//$list=$this->get_log_list();
//$log_list=new CompressX_Log_List();
//$log_list->set_log_list($list);
//$log_list->prepare_items();
//$log_list->display();
?>
</div>
</article>
<div id="cx_log_scroll_test"></div>
</div>
</div>
</section>
<section id="cx_log_detail_section" style="display: none">
<div class="compressx-container compressx-section">
<div class="compressx-bulk-log">
<article>
<div class="cx-title">
<span>Log: </span><span id="cx_log_name"></span>
</div>
<div class="cx-logs-table">
<textarea id="cx_read_optimize_log_content" style="width:100%; height:300px; overflow-x:auto;">
</textarea>
</div>
<div class="compressx-general-settings-footer">
<input class="button-primary cx-button" id="cx_close_log" type="submit" value="Close">
</div>
</article>
</div>
</div>
</section>
<?php
}
/* not use anymore
public function get_log_list()
{
$log_list=array();
$log=new CompressX_Log();
$dir=$log->GetSaveLogFolder();
$files=array();
$handler=opendir($dir);
$regex='#^compressx.*_log.txt#';
if($handler!==false)
{
while(($filename=readdir($handler))!==false)
{
if($filename != "." && $filename != "..")
{
if(is_dir($dir.$filename))
{
continue;
}else{
if(preg_match($regex,$filename))
{
$files[$filename] = $dir.$filename;
}
}
}
}
if($handler)
@closedir($handler);
}
foreach ($files as $file)
{
$handle = @fopen($file, "r");
if ($handle)
{
$log_file['file_name']=basename($file);
if(preg_match('/compressx-(.*?)_/', basename($file), $matches))
{
$id= $matches[0];
$id=substr($id,0,strlen($id)-1);
$log_file['id']=$id;
}
$log_file['path']=$file;
$log_file['size']=filesize($file);
$log_file['name']=basename($file);
$log_file['time']=filemtime($file);
$offset=get_option('gmt_offset');
$localtime = $log_file['time'] + $offset * 60 * 60;
$log_file['date']=gmdate('M-d-y H:i',$localtime);
$line = fgets($handle);
if($line!==false)
{
$pos=strpos($line,'Log created: ');
if($pos!==false)
{
$log_file['time']=substr ($line,$pos+strlen('Log created: '));
}
}
fclose($handle);
$log_list[basename($file)]=$log_file;
}
}
$log_list =$this->sort_list($log_list);
return $log_list;
}
public function get_log_list_ex($start_date,$start_time,$end_date,$end_time)
{
if(empty($start_date))
{
$start=0;
}
else if(empty($start_time))
{
$start=strtotime($start_date);
}
else
{
$start=strtotime($start_date.' '.$start_time);
}
if($start>0)
{
$offset=get_option('gmt_offset');
$start = $start - $offset * 60 * 60;
}
if(empty($end_date))
{
$end=0;
}
else if(empty($end_time))
{
$end=strtotime($end_date);
}
else
{
$end=strtotime($end_date.' '.$end_time);
}
if($end>0)
{
$offset=get_option('gmt_offset');
$end = $end - $offset * 60 * 60;
}
$log_list=array();
$log=new CompressX_Log();
$dir=$log->GetSaveLogFolder();
$files=array();
$handler=opendir($dir);
$regex='#^compressx.*_log.txt#';
if($handler!==false)
{
while(($filename=readdir($handler))!==false)
{
if($filename != "." && $filename != "..")
{
if(is_dir($dir.$filename))
{
continue;
}else{
if(preg_match($regex,$filename))
{
$files[$filename] = $dir.$filename;
}
}
}
}
if($handler)
@closedir($handler);
}
foreach ($files as $file)
{
$handle = @fopen($file, "r");
if ($handle)
{
$log_file['file_name']=basename($file);
if(preg_match('/compressx-(.*?)_/', basename($file), $matches))
{
$id= $matches[0];
$id=substr($id,0,strlen($id)-1);
$log_file['id']=$id;
}
$log_file['path']=$file;
$log_file['size']=filesize($file);
$log_file['name']=basename($file);
$log_file['time']=preg_replace('/[^0-9]/', '', basename($file));
$offset=get_option('gmt_offset');
$localtime = strtotime($log_file['time']) + $offset * 60 * 60;
$log_file['date']=gmdate('M-d-y H:i',$localtime);
$line = fgets($handle);
if($line!==false)
{
$pos=strpos($line,'Log created: ');
if($pos!==false)
{
$log_file['time']=substr ($line,$pos+strlen('Log created: '));
}
}
fclose($handle);
if($start>0&&$end>0)
{
if($localtime>=$start&&$localtime<=$end)
{
$log_list[basename($file)]=$log_file;
}
}
else if($start>0)
{
if($localtime>=$start)
{
$log_list[basename($file)]=$log_file;
}
}
else if($end>0)
{
if($localtime<=$end)
{
$log_list[basename($file)]=$log_file;
}
}
else
{
$log_list[basename($file)]=$log_file;
}
}
}
$log_list =$this->sort_list($log_list);
return $log_list;
}
public function sort_list($list)
{
uasort ($list,function($a, $b)
{
if($a['time']>$b['time'])
{
return -1;
}
else if($a['time']===$b['time'])
{
return 0;
}
else
{
return 1;
}
});
return $list;
}
public function get_logs_list()
{
global $compressx;
$compressx->ajax_check_security('compressx-can-use-logs');
if(isset($_POST['start_date']))
{
$start_date=sanitize_key($_POST['start_date']);
}
else
{
$start_date='';
}
if(isset($_POST['start_time']))
{
$start_time=sanitize_key($_POST['start_time']);
}
else
{
$start_time='';
}
if(isset($_POST['end_date']))
{
$end_date=sanitize_key($_POST['end_date']);
}
else
{
$end_date='';
}
if(isset($_POST['end_time']))
{
$end_time=sanitize_key($_POST['end_time']);
}
else
{
$end_time='';
}
if(isset($_POST['page']))
{
$page=sanitize_key($_POST['page']);
}
else
{
$page=0;
}
$list=$this->get_log_list_ex($start_date,$start_time,$end_date,$end_time);
$log_list=new CompressX_Log_List();
$log_list->set_log_list($list,$page);
$log_list->prepare_items();
ob_start();
$log_list->display();
$json['result'] = 'success';
$json['html'] = ob_get_clean();
echo wp_json_encode($json);
die();
}
public function open_log()
{
global $compressx;
$compressx->ajax_check_security('compressx-can-use-logs');
try
{
if(!isset($_POST['filename']))
{
die();
}
$file_name=sanitize_text_field($_POST['filename']);
$loglist=$this->get_log_list();
if(!empty($loglist))
{
if(isset($loglist[$file_name]))
{
$log=$loglist[$file_name];
}
else
{
$json['result'] = 'failed';
$json['error'] =__('The log not found ','compressx').$file_name;
echo wp_json_encode($json);
die();
}
$path=$log['path'];
if (!file_exists($path))
{
$json['result'] = 'failed';
$json['error'] = __('The log not found ','compressx').$file_name;
echo wp_json_encode($json);
die();
}
$file = fopen($path, 'r');
if (!$file) {
$json['result'] = 'failed';
$json['error'] = __('Unable to open the log file.','compressx');
echo wp_json_encode($json);
die();
}
$offset=get_option('gmt_offset');
$localtime = strtotime($log['time']) + $offset * 60 * 60;
$buffer = 'Open log file created:'.gmdate('Y-m-d',$localtime).' '.PHP_EOL;
while (!feof($file)) {
$buffer .= fread($file, 1024);
}
fclose($file);
$json['result'] = 'success';
$json['html'] = $buffer;
echo wp_json_encode($json);
die();
}
else
{
$json['result'] = 'failed';
$json['error'] = 'The log not found.';
echo wp_json_encode($json);
die();
}
}
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 download_log()
{
global $compressx;
$compressx->ajax_check_security('compressx-can-use-logs');
$admin_url = admin_url();
try
{
if (isset($_REQUEST['log']))
{
$log = sanitize_text_field($_REQUEST['log']);
$log = basename($log);
$loglist=$this->get_log_list();
if(isset($loglist[$log]))
{
$log=$loglist[$log];
}
else
{
$message= 'Log does not exist. It might have been deleted or lost during a website migration.';
echo esc_html($message);
die();
}
$path=$log['path'];
if (!file_exists($path))
{
$message= 'Log does not exist. It might have been deleted or lost during a website migration.';
echo esc_html($message);
die();
}
if (file_exists($path))
{
if (session_id())
session_write_close();
$size = filesize($path);
if (!headers_sent())
{
header('Content-Description: File Transfer');
header('Content-Type: text');
header('Content-Disposition: attachment; filename="' . basename($path) . '"');
header('Cache-Control: must-revalidate');
header('Content-Length: ' . $size);
header('Content-Transfer-Encoding: binary');
}
ob_end_clean();
readfile($path);
exit;
}
else
{
echo esc_html(' file not found.');
die();
}
} else {
$message = 'Reading the log failed. Please try again.';
echo esc_html($message);
die();
}
}
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 esc_html($message);
die();
}
}
public function delete_log()
{
global $compressx;
$compressx->ajax_check_security('compressx-can-use-logs');
try
{
if(!isset($_POST['filename']))
{
die();
}
$file_name=sanitize_text_field($_POST['filename']);
$loglist=$this->get_log_list();
if(!empty($loglist))
{
if(isset($loglist[$file_name]))
{
$log=$loglist[$file_name];
}
else
{
$json['result'] = 'failed';
$json['error'] = __('The log not found ','compressx').$file_name;
echo wp_json_encode($json);
die();
}
$path=$log['path'];
@wp_delete_file($path);
$list=$this->get_log_list();
$log_list=new CompressX_Log_List();
$log_list->set_log_list($list);
$log_list->prepare_items();
ob_start();
$log_list->display();
$json['result'] = 'success';
$json['html'] = ob_get_clean();
echo wp_json_encode($json);
die();
}
else
{
$json['result'] = 'failed';
$json['error'] = __('The log not found ','compressx');
echo wp_json_encode($json);
die();
}
}
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 delete_all_log()
{
global $compressx;
$compressx->ajax_check_security('compressx-can-use-logs');
try
{
$loglist=$this->get_log_list();
if(!empty($loglist))
{
foreach ($loglist as $log)
{
$path=$log['path'];
@wp_delete_file($path);
}
$list=$this->get_log_list();
$log_list=new CompressX_Log_List();
$log_list->set_log_list($list);
$log_list->prepare_items();
ob_start();
$log_list->display();
$json['result'] = 'success';
$json['html'] = ob_get_clean();
echo wp_json_encode($json);
die();
}
else
{
$json['result'] = 'failed';
$json['error'] = __('The log not found ','compressx');
echo wp_json_encode($json);
die();
}
}
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();
}
*/
}
@@ -0,0 +1,616 @@
<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
class CompressX_System_Info
{
public function __construct()
{
//add_action('wp_ajax_compressx_create_debug_package',array( $this,'create_debug_package'));
//add_action('wp_ajax_compressx_send_debug_info',array( $this,'send_debug_info'));
//
}
public function display()
{
?>
<div id="compressx-root">
<div id="compressx-wrap">
<?php
$this->output_nav();
$this->output_header();
$this->output_debug();
$this->output_footer();
?>
</div>
</div>
<?php
}
public function output_nav()
{
do_action('compressx_output_nav');
}
public function output_header()
{
do_action('compressx_output_header');
}
public function output_debug()
{
?>
<section>
<div class="compressx-container compressx-section ">
<div class="compressx-bulk-log">
<article>
<div style="padding: 0 0 20px 10px;">
<?php esc_html_e('There are two ways available to send us the debug information. The first one is recommended.', 'compressx'); ?>
</div>
<div style="padding-left: 10px;">
<strong><?php esc_html_e('Method 1.', 'compressx'); ?></strong> <?php esc_html_e('If you have configured SMTP on your site, enter your email address and click the button below to send us the relevant information (website info and errors logs) when you are encountering errors. This will help us figure out what happened. Once the issue is resolved, we will inform you by your email address.', 'compressx'); ?>
</div>
<div style="padding:10px 10px 0">
<span>
<?php esc_html_e('CompressX support email:', 'compressx'); ?>
</span><input type="text" id="compressx_support_mail" value="support@compressx.io" readonly />
<span>
<?php esc_html_e('Your email:', 'compressx'); ?>
</span>
<input type="text" id="compressx_user_mail" />
</div>
<div style="padding:10px 10px;">
<textarea id="compressx_debug_comment" class="wp-editor-area" style="width:100%; height: 200px;" autocomplete="off" cols="60" placeholder="<?php esc_attr_e('Please describe your problem here.', 'compressx'); ?>" ></textarea>
</div>
<div style="padding:10px 10px;">
<input id="compressx_debug_submit" class="button-primary" type="submit" value="<?php esc_attr_e( 'Send Debug Information to Us', 'compressx' ); ?>" />
<span style="padding:0 0.2rem;"></span>
<span id="compressx_send_success_text" class="success hidden" aria-hidden="true" style="color:#007017"><?php esc_html_e('Send succeeded.','compressx')?></span>
</div>
<div style="clear:both;"></div>
<div style="padding-left: 10px;">
<strong><?php esc_html_e('Method 2.', 'compressx'); ?></strong> <?php esc_html_e('If you didn’t configure SMTP on your site, click the button below to download the relevant information (website info and error logs) to your PC when you are encountering some errors. Sending the files to us will help us diagnose what happened.', 'compressx'); ?>
</div>
<div style="padding: 10px 10px;">
<input class="button-primary" id="compressx_download_debug_info" type="submit" value="<?php esc_attr_e( 'Download', 'compressx' ); ?>" />
</div>
</article>
</div>
</div>
</section>
<section>
<div class="compressx-container compressx-section ">
<div class="compressx-bulk-log" style="padding-bottom: 0;">
<?php
//$this->output_debug_info();
?>
</div>
</div>
</section>
<?php
}
/*not ues any more
public function output_debug_info()
{
?>
<article>
<div class="cx-title">
<span><?php esc_html_e('Debug Information', 'compressx'); ?>: </span>
</div>
<div class="cx-table-overflow">
<table class="wp-list-table widefat striped">
<thead class="website-info-head">
<tr>
<th class="row-title" style="min-width: 260px;" colspan="3"><?php esc_html_e('Debug Information', 'compressx'); ?></th>
</tr>
</thead>
<tbody>
<?php
$debug_info=$this->get_debug_info();
if(!empty($debug_info))
{
foreach ($debug_info as $key=>$value)
{
if($key=='setting')
continue;
$website_value='';
if (is_array($value))
{
foreach ($value as $arr_value)
{
if (empty($website_value))
{
$website_value = $website_value . $arr_value;
} else {
$website_value = $website_value . ', ' . $arr_value;
}
}
}
else
{
if($value === true || $value === false)
{
if($value === true) {
$website_value = 'true';
}
else{
$website_value = 'false';
}
}
else {
$website_value = $value;
}
}
?>
<tr>
<td class="row-title tablelistcolumn"><label for="tablecell"><?php echo esc_html($key); ?></label></td>
<td class="tablelistcolumn"><?php echo esc_html($website_value); ?></td>
</tr>
<?php
}
}
?>
</tbody>
</table>
</div>
</article>
<?php
}
public function get_debug_info()
{
global $wp_version;
$debug_info=array();
$debug_info['home']=$this->get_domain();
$debug_info['Server name']=$_SERVER['SERVER_NAME'];
$debug_info['Web Server'] = sanitize_text_field($_SERVER["SERVER_SOFTWARE"]);
$debug_info['CompressX version'] = COMPRESSX_VERSION;
$debug_info['Wordpress version'] = $wp_version;
$debug_info['PHP version'] = phpversion();
if( !function_exists( 'gd_info' ))
{
$debug_info['GD extension']=__("GD extension is not installed or enabled.",'compressx');
}
else
{
$debug_info['GD extension']=__("The GD extension has been properly installed.",'compressx');
$info=gd_info();
$debug_info['GD Version']=isset($info['GD Version'])?$info['GD Version']:'';
$debug_info['GD WebP Support']=isset($info['WebP Support'])?$info['WebP Support']:false;
$debug_info['GD AVIF Support']=isset($info['AVIF Support'])?$info['AVIF Support']:false;
}
if ( extension_loaded( 'imagick' ) && class_exists( '\Imagick' ) )
{
$debug_info['Imagick extension']=__("The imagick extension has been properly installed.",'compressx');
$debug_info['Imagick Version']=\Imagick::getVersion();
if( \Imagick::queryformats( 'WEBP' ))
{
$debug_info['Imagick WebP Support']=true;
}
else
{
$debug_info['Imagick WebP Support']=false;
}
if( \Imagick::queryformats( 'AVIF' ))
{
$debug_info['Imagick AVIF Support']=true;
}
else
{
$debug_info['Imagick AVIF Support']=false;
}
}
else
{
$debug_info['Imagick extension']=__("Imagick extension is not installed or enabled.",'compressx');
}
$debug_info['active_plugins'] = get_option('active_plugins');
$debug_info['active_theme'] = wp_get_theme()->get_template();
$debug_info['memory_current'] = size_format(memory_get_usage(),2);
$debug_info['memory_peak'] = size_format(memory_get_peak_usage(),2);
$debug_info['memory_limit'] = ini_get('memory_limit');
include_once COMPRESSX_DIR . '/includes/class-compressx-rewrite-checker.php';
$test=new CompressX_Rewrite_Checker();
$result=$test->test_ex();
if($result['result']=='success')
{
$debug_info['Rewrite rules test'] = 'success';
}
else
{
$debug_info['Rewrite rules test'] = $result['error'];
}
$options=get_option('compressx_general_settings',array());
$debug_info['setting']=$options;
$quality_options=get_option('compressx_quality',array());
$converter_method=get_option('compressx_converter_method',false);
$output_format_webp=get_option('compressx_output_format_webp',1);
$output_format_avif=get_option('compressx_output_format_avif',1);
$debug_info['setting']['quality']=$quality_options;
$debug_info['setting']['output_format_webp']=$output_format_webp;
$debug_info['setting']['output_format_avif']=$output_format_avif;
$debug_info['setting']['converter_method']=$converter_method;
$debug_info['setting']=wp_json_encode($debug_info['setting']);
return $debug_info;
}
public function get_domain()
{
global $wpdb;
$home_url = home_url();
$db_home_url = home_url();
$home_url_sql = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM $wpdb->options WHERE option_name = %s", 'home' ) );
foreach ( $home_url_sql as $home )
{
$db_home_url = untrailingslashit($home->option_value);
}
if($home_url === $db_home_url)
{
$domain = $home_url;
}
else
{
$domain = $db_home_url;
}
return strtolower($domain);
}
public function output_footer()
{
do_action('compressx_output_footer');
}
public function get_website_info()
{
try
{
$version = COMPRESSX_VERSION;
$ret['result'] = 'success';
$ret['data']['version'] = $version;
$ret['data']['home_url'] = get_home_url();
$ret['data']['abspath'] = ABSPATH;
$ret['data']['wp_content_path'] = WP_CONTENT_DIR;
$ret['data']['wp_plugin_path'] = WP_PLUGIN_DIR;
$ret['data']['active_plugins'] = get_option('active_plugins');
global $wp_version;
$ret['wp_version'] = $wp_version;
if (is_multisite()) {
$ret['data']['multisite'] = 'enable';
} else {
$ret['data']['multisite'] = 'disable';
}
$ret['data']['web_server'] = sanitize_text_field($_SERVER["SERVER_SOFTWARE"]);
$ret['data']['php_version'] = phpversion();
global $wpdb;
$ret['data']['mysql_version'] = $wpdb->db_version();
if (defined('WP_DEBUG')) {
$ret['data']['wp_debug'] = WP_DEBUG;
} else {
$ret['wp_debug'] = false;
}
$ret['data']['language'] = get_bloginfo('language');
$ret['data']['upload_max_filesize'] = ini_get("upload_max_filesize");
$current_offset = get_option( 'gmt_offset' );
$timezone = get_option( 'timezone_string' );
if ( false !== strpos( $timezone, 'Etc/GMT' ) ) {
$timezone = '';
}
if ( empty( $timezone ) ) {
if ( 0 == $current_offset ) {
$timezone = 'UTC+0';
} elseif ( $current_offset < 0 ) {
$timezone = 'UTC' . $current_offset;
} else {
$timezone = 'UTC+' . $current_offset;
}
}
$ret['data']['max_execution_time'] = ini_get("max_execution_time");
$ret['data']['max_input_vars'] = ini_get("max_input_vars");
$ret['data']['max_input_vars'] = ini_get("max_input_vars");
$ret['data']['timezone'] = $timezone;//date_default_timezone_get();
if(function_exists('php_uname'))
{
$ret['data']['OS'] = php_uname();
}
$ret['data']['memory_current'] = size_format(memory_get_usage(),2);
$ret['data']['memory_peak'] = size_format(memory_get_peak_usage(),2);
$ret['data']['memory_limit'] = ini_get('memory_limit');
$ret['data']['post_max_size'] = ini_get('post_max_size');
$ret['data']['allow_url_fopen'] = ini_get('allow_url_fopen');
$ret['data']['safe_mode'] = ini_get('safe_mode');
$ret['data']['pcre.backtrack_limit'] = ini_get('pcre.backtrack_limit');
$extensions = get_loaded_extensions();
if (array_search('exif', $extensions)) {
$ret['data']['exif'] = 'support';
} else {
$ret['data']['exif'] = 'not support';
}
if (array_search('xml', $extensions)) {
$ret['data']['xml'] = 'support';
} else {
$ret['data']['xml'] = 'not support';
}
if (array_search('suhosin', $extensions)) {
$ret['data']['suhosin'] = 'support';
} else {
$ret['data']['suhosin'] = 'not support';
}
if (array_search('gd', $extensions)) {
$ret['data']['IPTC'] = 'support';
} else {
$ret['data']['IPTC'] = 'not support';
}
$ret['data']['extensions'] = $extensions;
if (function_exists('apache_get_modules')) {
$ret['data']['apache_modules'] = apache_get_modules();
} else {
$ret['data']['apache_modules'] = array();
}
if (array_search('pdo_mysql', $extensions))
{
$ret['data']['pdo_mysql'] = 'support';
} else {
$ret['data']['pdo_mysql'] = 'not support';
}
$ret['data']['mysql_mode'] = '';
global $wpdb;
$result = $wpdb->get_results('SELECT @@SESSION.sql_mode', ARRAY_A);
foreach ($result as $row)
{
$ret['data']['mysql_mode'] = $row["@@SESSION.sql_mode"];
}
if (!class_exists('PclZip')) include_once(ABSPATH . '/wp-admin/includes/class-pclzip.php');
if (!class_exists('PclZip'))
{
$ret['data']['PclZip'] = 'not support';
} else {
$ret['data']['PclZip'] = 'support';
}
if (is_multisite() && !defined('MULTISITE')) {
$prefix = $wpdb->base_prefix;
} else {
$prefix = $wpdb->get_blog_prefix(0);
}
$ret['data']['wp_prefix'] = $prefix;
$sapi_type = php_sapi_name();
if ($sapi_type == 'cgi-fcgi' || $sapi_type == ' fpm-fcgi') {
$ret['data']['fast_cgi'] = 'On';
} else {
$ret['data']['fast_cgi'] = 'Off';
}
}
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);
return array('result'=>'failed','error'=>$message);
}
return $ret;
}
public function create_debug_package()
{
global $compressx;
$compressx->ajax_check_security('compressx-can-use-system-info');
try
{
if (!class_exists('PclZip'))
include_once(ABSPATH . '/wp-admin/includes/class-pclzip.php');
$backup_path="compressx";
$path = WP_CONTENT_DIR . DIRECTORY_SEPARATOR . $backup_path . DIRECTORY_SEPARATOR . 'compressx_debug.zip';
if(!is_dir(WP_CONTENT_DIR.DIRECTORY_SEPARATOR.$backup_path))
{
wp_mkdir_p(WP_CONTENT_DIR.DIRECTORY_SEPARATOR.$backup_path);
@fopen(WP_CONTENT_DIR.DIRECTORY_SEPARATOR.$backup_path.DIRECTORY_SEPARATOR.'index.html', 'x');
$tempfile=@fopen(WP_CONTENT_DIR.DIRECTORY_SEPARATOR.$backup_path.DIRECTORY_SEPARATOR.'.htaccess', 'x');
if($tempfile)
{
$text="deny from all";
fwrite($tempfile,$text );
fclose($tempfile);
}
}
if (file_exists($path)) {
@wp_delete_file($path);
}
$archive = new PclZip($path);
$server_info = wp_json_encode($this->get_debug_info());
$server_file_path = WP_CONTENT_DIR . DIRECTORY_SEPARATOR . $backup_path . DIRECTORY_SEPARATOR . 'compressx_server_info.json';
if (file_exists($server_file_path)) {
@wp_delete_file($server_file_path);
}
$server_file = fopen($server_file_path, 'x');
fclose($server_file);
file_put_contents($server_file_path, $server_info);
if (!$archive->add($server_file_path, PCLZIP_OPT_REMOVE_ALL_PATH))
{
exit;
}
@wp_delete_file($server_file_path);
$log=new CompressX_Log();
$files=$log->get_logs();
if(!empty($files))
{
if(!$archive->add($files,PCLZIP_OPT_REMOVE_ALL_PATH))
{
exit;
}
}
if (session_id())
session_write_close();
$size = filesize($path);
if (!headers_sent()) {
header('Content-Description: File Transfer');
header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename="' . basename($path) . '"');
header('Cache-Control: must-revalidate');
header('Content-Length: ' . $size);
header('Content-Transfer-Encoding: binary');
}
ob_end_clean();
readfile($path);
@wp_delete_file($path);
}
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();
}
exit;
}
public function send_debug_info()
{
global $compressx;
$compressx->ajax_check_security('compressx-can-use-system-info');
try
{
if (!isset($_POST['user_mail']) || empty($_POST['user_mail']))
{
$ret['result'] = 'failed';
$ret['error'] = __('User\'s email address is required.', 'compressx');
}
else
{
$pattern = '/^[a-z0-9]+([._-][a-z0-9]+)*@([0-9a-z]+\.[a-z]{2,14}(\.[a-z]{2})?)$/i';
if (!preg_match($pattern, $_POST['user_mail']))
{
$ret['result'] = 'failed';
$ret['error'] = __('Please enter a valid email address.', 'compressx');
}
else
{
$user_mail=sanitize_email($_POST['user_mail']);
$comment=sanitize_text_field($_POST['comment']);
$ret =$this->_send_debug_info($user_mail,$comment);
}
}
echo wp_json_encode($ret);
die();
}
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 _send_debug_info($user_email,$comment)
{
$send_to = 'support@compressx.io';
$subject = 'Debug Information';
$body = '<div>User\'s email: '.$user_email.'.</div>';
$body .= '<div>Comment: '.$comment.'.</div>';
$headers = array('Content-Type: text/html; charset=UTF-8');
if (!class_exists('PclZip'))
include_once(ABSPATH . '/wp-admin/includes/class-pclzip.php');
$backup_path="compressx";
$path = WP_CONTENT_DIR . DIRECTORY_SEPARATOR . $backup_path . DIRECTORY_SEPARATOR . 'compressx_debug.zip';
if(!is_dir(WP_CONTENT_DIR.DIRECTORY_SEPARATOR.$backup_path))
{
wp_mkdir_p(WP_CONTENT_DIR.DIRECTORY_SEPARATOR.$backup_path);
@fopen(WP_CONTENT_DIR.DIRECTORY_SEPARATOR.$backup_path.DIRECTORY_SEPARATOR.'index.html', 'x');
$tempfile=@fopen(WP_CONTENT_DIR.DIRECTORY_SEPARATOR.$backup_path.DIRECTORY_SEPARATOR.'.htaccess', 'x');
if($tempfile)
{
$text="deny from all";
fwrite($tempfile,$text );
fclose($tempfile);
}
}
if (file_exists($path)) {
@wp_delete_file($path);
}
$archive = new PclZip($path);
$server_info = wp_json_encode($this->get_debug_info());
$server_file_path = WP_CONTENT_DIR . DIRECTORY_SEPARATOR . $backup_path . DIRECTORY_SEPARATOR . 'compressx_server_info.json';
if (file_exists($server_file_path))
{
@wp_delete_file($server_file_path);
}
$server_file = fopen($server_file_path, 'x');
fclose($server_file);
file_put_contents($server_file_path, $server_info);
$archive->add($server_file_path, PCLZIP_OPT_REMOVE_ALL_PATH);
@wp_delete_file($server_file_path);
$log=new CompressX_Log();
$files=$log->get_logs();
if(!empty($files))
{
$archive->add($files,PCLZIP_OPT_REMOVE_ALL_PATH);
}
$attachments[] = $path;
if(wp_mail( $send_to, $subject, $body,$headers,$attachments)===false)
{
$ret['result']='failed';
$ret['error']=__('Unable to send email. Please check the configuration of email server.', 'compressx');
}
else
{
$ret['result']='success';
}
@wp_delete_file($path);
return $ret;
}
*/
}
@@ -0,0 +1,56 @@
.compressx-tooltip {
display:inline-block;
position:relative;
text-align:left;
}
/* tooltip - bottom */
.compressx-bottom {
min-width:300px;
top:40px;
left:50%;
transform:translate(-50%, 0);
padding:10px 20px;
color:#444444;
background-color:#fff;
font-weight:normal;
font-size:13px;
border-radius:8px;
position:absolute;
z-index:99999999;
box-sizing:border-box;
box-shadow:0 1px 8px rgba(0,0,0,0.2);
visibility:hidden; opacity:0; transition:opacity 0.4s;
}
.compressx-dashicons-help a{
color: #888;
}
.compressx-dashicons-help a:hover{
color: #575757;
}
.compressx-dashicons-help:hover .compressx-bottom {
visibility:visible; opacity:1;
}
.compressx-dashicons-white:hover .compressx-bottom{
visibility:visible; opacity:1;
}
.compressx-tooltip .compressx-bottom i {
position:absolute;
bottom:100%;
left:50%;
margin-left:-12px;
width:24px;
height:12px;
overflow:hidden;
}
.compressx-tooltip .compressx-bottom i::after {
content:'';
position:absolute;
width:12px;
height:12px;
left:50%;
transform:translate(-50%,50%) rotate(45deg);
background-color:#fff;
box-shadow:0 1px 8px rgba(0,0,0,0.5);
}
/* tooltip - left */
@@ -0,0 +1,879 @@
/****************************************************************
*
* CSS Percentage Circle
* Author: Andre Firchow
*
*****************************************************************/
.rect-auto, .c100.p51 .slice, .c100.p52 .slice, .c100.p53 .slice, .c100.p54 .slice, .c100.p55 .slice, .c100.p56 .slice, .c100.p57 .slice, .c100.p58 .slice, .c100.p59 .slice, .c100.p60 .slice, .c100.p61 .slice, .c100.p62 .slice, .c100.p63 .slice, .c100.p64 .slice, .c100.p65 .slice, .c100.p66 .slice, .c100.p67 .slice, .c100.p68 .slice, .c100.p69 .slice, .c100.p70 .slice, .c100.p71 .slice, .c100.p72 .slice, .c100.p73 .slice, .c100.p74 .slice, .c100.p75 .slice, .c100.p76 .slice, .c100.p77 .slice, .c100.p78 .slice, .c100.p79 .slice, .c100.p80 .slice, .c100.p81 .slice, .c100.p82 .slice, .c100.p83 .slice, .c100.p84 .slice, .c100.p85 .slice, .c100.p86 .slice, .c100.p87 .slice, .c100.p88 .slice, .c100.p89 .slice, .c100.p90 .slice, .c100.p91 .slice, .c100.p92 .slice, .c100.p93 .slice, .c100.p94 .slice, .c100.p95 .slice, .c100.p96 .slice, .c100.p97 .slice, .c100.p98 .slice, .c100.p99 .slice, .c100.p100 .slice {
clip: rect(auto, auto, auto, auto);
}
.pie, .c100 .bar, .c100.p51 .fill, .c100.p52 .fill, .c100.p53 .fill, .c100.p54 .fill, .c100.p55 .fill, .c100.p56 .fill, .c100.p57 .fill, .c100.p58 .fill, .c100.p59 .fill, .c100.p60 .fill, .c100.p61 .fill, .c100.p62 .fill, .c100.p63 .fill, .c100.p64 .fill, .c100.p65 .fill, .c100.p66 .fill, .c100.p67 .fill, .c100.p68 .fill, .c100.p69 .fill, .c100.p70 .fill, .c100.p71 .fill, .c100.p72 .fill, .c100.p73 .fill, .c100.p74 .fill, .c100.p75 .fill, .c100.p76 .fill, .c100.p77 .fill, .c100.p78 .fill, .c100.p79 .fill, .c100.p80 .fill, .c100.p81 .fill, .c100.p82 .fill, .c100.p83 .fill, .c100.p84 .fill, .c100.p85 .fill, .c100.p86 .fill, .c100.p87 .fill, .c100.p88 .fill, .c100.p89 .fill, .c100.p90 .fill, .c100.p91 .fill, .c100.p92 .fill, .c100.p93 .fill, .c100.p94 .fill, .c100.p95 .fill, .c100.p96 .fill, .c100.p97 .fill, .c100.p98 .fill, .c100.p99 .fill, .c100.p100 .fill {
position: absolute;
border: 0.08em solid #175cff;
width: 0.84em;
height: 0.84em;
clip: rect(0em, 0.5em, 1em, 0em);
-webkit-border-radius: 50%;
-moz-border-radius: 50%;
-ms-border-radius: 50%;
-o-border-radius: 50%;
border-radius: 50%;
-webkit-transform: rotate(0deg);
-moz-transform: rotate(0deg);
-ms-transform: rotate(0deg);
-o-transform: rotate(0deg);
transform: rotate(0deg);
}
.pie-fill, .c100.p51 .bar:after, .c100.p51 .fill, .c100.p52 .bar:after, .c100.p52 .fill, .c100.p53 .bar:after, .c100.p53 .fill, .c100.p54 .bar:after, .c100.p54 .fill, .c100.p55 .bar:after, .c100.p55 .fill, .c100.p56 .bar:after, .c100.p56 .fill, .c100.p57 .bar:after, .c100.p57 .fill, .c100.p58 .bar:after, .c100.p58 .fill, .c100.p59 .bar:after, .c100.p59 .fill, .c100.p60 .bar:after, .c100.p60 .fill, .c100.p61 .bar:after, .c100.p61 .fill, .c100.p62 .bar:after, .c100.p62 .fill, .c100.p63 .bar:after, .c100.p63 .fill, .c100.p64 .bar:after, .c100.p64 .fill, .c100.p65 .bar:after, .c100.p65 .fill, .c100.p66 .bar:after, .c100.p66 .fill, .c100.p67 .bar:after, .c100.p67 .fill, .c100.p68 .bar:after, .c100.p68 .fill, .c100.p69 .bar:after, .c100.p69 .fill, .c100.p70 .bar:after, .c100.p70 .fill, .c100.p71 .bar:after, .c100.p71 .fill, .c100.p72 .bar:after, .c100.p72 .fill, .c100.p73 .bar:after, .c100.p73 .fill, .c100.p74 .bar:after, .c100.p74 .fill, .c100.p75 .bar:after, .c100.p75 .fill, .c100.p76 .bar:after, .c100.p76 .fill, .c100.p77 .bar:after, .c100.p77 .fill, .c100.p78 .bar:after, .c100.p78 .fill, .c100.p79 .bar:after, .c100.p79 .fill, .c100.p80 .bar:after, .c100.p80 .fill, .c100.p81 .bar:after, .c100.p81 .fill, .c100.p82 .bar:after, .c100.p82 .fill, .c100.p83 .bar:after, .c100.p83 .fill, .c100.p84 .bar:after, .c100.p84 .fill, .c100.p85 .bar:after, .c100.p85 .fill, .c100.p86 .bar:after, .c100.p86 .fill, .c100.p87 .bar:after, .c100.p87 .fill, .c100.p88 .bar:after, .c100.p88 .fill, .c100.p89 .bar:after, .c100.p89 .fill, .c100.p90 .bar:after, .c100.p90 .fill, .c100.p91 .bar:after, .c100.p91 .fill, .c100.p92 .bar:after, .c100.p92 .fill, .c100.p93 .bar:after, .c100.p93 .fill, .c100.p94 .bar:after, .c100.p94 .fill, .c100.p95 .bar:after, .c100.p95 .fill, .c100.p96 .bar:after, .c100.p96 .fill, .c100.p97 .bar:after, .c100.p97 .fill, .c100.p98 .bar:after, .c100.p98 .fill, .c100.p99 .bar:after, .c100.p99 .fill, .c100.p100 .bar:after, .c100.p100 .fill {
-webkit-transform: rotate(180deg);
-moz-transform: rotate(180deg);
-ms-transform: rotate(180deg);
-o-transform: rotate(180deg);
transform: rotate(180deg);
}
.c100 {
position: relative;
font-size: 120px;
width: 1em;
height: 1em;
-webkit-border-radius: 50%;
-moz-border-radius: 50%;
-ms-border-radius: 50%;
-o-border-radius: 50%;
border-radius: 50%;
float: left;
margin: 0 0.1em 0.1em 0;
background-color: #cccccc;
}
.c100 *, .c100 *:before, .c100 *:after {
-webkit-box-sizing: content-box;
-moz-box-sizing: content-box;
box-sizing: content-box;
}
.c100.center {
float: none;
margin: 0 auto;
}
.c100.big {
font-size: 240px;
}
.c100.small {
font-size: 80px;
}
.c100 > span {
position: absolute;
width: 100%;
z-index: 1;
left: 0;
top: 0;
width: 5em;
line-height: 5em;
font-size: 0.2em;
color: #cccccc;
display: block;
text-align: center;
white-space: nowrap;
-webkit-transition-property: all;
-moz-transition-property: all;
-o-transition-property: all;
transition-property: all;
-webkit-transition-duration: 0.2s;
-moz-transition-duration: 0.2s;
-o-transition-duration: 0.2s;
transition-duration: 0.2s;
-webkit-transition-timing-function: ease-out;
-moz-transition-timing-function: ease-out;
-o-transition-timing-function: ease-out;
transition-timing-function: ease-out;
}
.c100:after {
position: absolute;
top: 0.08em;
left: 0.08em;
display: block;
content: " ";
-webkit-border-radius: 50%;
-moz-border-radius: 50%;
-ms-border-radius: 50%;
-o-border-radius: 50%;
border-radius: 50%;
background-color: whitesmoke;
width: 0.84em;
height: 0.84em;
-webkit-transition-property: all;
-moz-transition-property: all;
-o-transition-property: all;
transition-property: all;
-webkit-transition-duration: 0.2s;
-moz-transition-duration: 0.2s;
-o-transition-duration: 0.2s;
transition-duration: 0.2s;
-webkit-transition-timing-function: ease-in;
-moz-transition-timing-function: ease-in;
-o-transition-timing-function: ease-in;
transition-timing-function: ease-in;
}
.c100 .slice {
position: absolute;
width: 1em;
height: 1em;
clip: rect(0em, 1em, 1em, 0.5em);
}
.c100.p1 .bar {
-webkit-transform: rotate(3.6deg);
-moz-transform: rotate(3.6deg);
-ms-transform: rotate(3.6deg);
-o-transform: rotate(3.6deg);
transform: rotate(3.6deg);
}
.c100.p2 .bar {
-webkit-transform: rotate(7.2deg);
-moz-transform: rotate(7.2deg);
-ms-transform: rotate(7.2deg);
-o-transform: rotate(7.2deg);
transform: rotate(7.2deg);
}
.c100.p3 .bar {
-webkit-transform: rotate(10.8deg);
-moz-transform: rotate(10.8deg);
-ms-transform: rotate(10.8deg);
-o-transform: rotate(10.8deg);
transform: rotate(10.8deg);
}
.c100.p4 .bar {
-webkit-transform: rotate(14.4deg);
-moz-transform: rotate(14.4deg);
-ms-transform: rotate(14.4deg);
-o-transform: rotate(14.4deg);
transform: rotate(14.4deg);
}
.c100.p5 .bar {
-webkit-transform: rotate(18deg);
-moz-transform: rotate(18deg);
-ms-transform: rotate(18deg);
-o-transform: rotate(18deg);
transform: rotate(18deg);
}
.c100.p6 .bar {
-webkit-transform: rotate(21.6deg);
-moz-transform: rotate(21.6deg);
-ms-transform: rotate(21.6deg);
-o-transform: rotate(21.6deg);
transform: rotate(21.6deg);
}
.c100.p7 .bar {
-webkit-transform: rotate(25.2deg);
-moz-transform: rotate(25.2deg);
-ms-transform: rotate(25.2deg);
-o-transform: rotate(25.2deg);
transform: rotate(25.2deg);
}
.c100.p8 .bar {
-webkit-transform: rotate(28.8deg);
-moz-transform: rotate(28.8deg);
-ms-transform: rotate(28.8deg);
-o-transform: rotate(28.8deg);
transform: rotate(28.8deg);
}
.c100.p9 .bar {
-webkit-transform: rotate(32.4deg);
-moz-transform: rotate(32.4deg);
-ms-transform: rotate(32.4deg);
-o-transform: rotate(32.4deg);
transform: rotate(32.4deg);
}
.c100.p10 .bar {
-webkit-transform: rotate(36deg);
-moz-transform: rotate(36deg);
-ms-transform: rotate(36deg);
-o-transform: rotate(36deg);
transform: rotate(36deg);
}
.c100.p11 .bar {
-webkit-transform: rotate(39.6deg);
-moz-transform: rotate(39.6deg);
-ms-transform: rotate(39.6deg);
-o-transform: rotate(39.6deg);
transform: rotate(39.6deg);
}
.c100.p12 .bar {
-webkit-transform: rotate(43.2deg);
-moz-transform: rotate(43.2deg);
-ms-transform: rotate(43.2deg);
-o-transform: rotate(43.2deg);
transform: rotate(43.2deg);
}
.c100.p13 .bar {
-webkit-transform: rotate(46.8deg);
-moz-transform: rotate(46.8deg);
-ms-transform: rotate(46.8deg);
-o-transform: rotate(46.8deg);
transform: rotate(46.8deg);
}
.c100.p14 .bar {
-webkit-transform: rotate(50.4deg);
-moz-transform: rotate(50.4deg);
-ms-transform: rotate(50.4deg);
-o-transform: rotate(50.4deg);
transform: rotate(50.4deg);
}
.c100.p15 .bar {
-webkit-transform: rotate(54deg);
-moz-transform: rotate(54deg);
-ms-transform: rotate(54deg);
-o-transform: rotate(54deg);
transform: rotate(54deg);
}
.c100.p16 .bar {
-webkit-transform: rotate(57.6deg);
-moz-transform: rotate(57.6deg);
-ms-transform: rotate(57.6deg);
-o-transform: rotate(57.6deg);
transform: rotate(57.6deg);
}
.c100.p17 .bar {
-webkit-transform: rotate(61.2deg);
-moz-transform: rotate(61.2deg);
-ms-transform: rotate(61.2deg);
-o-transform: rotate(61.2deg);
transform: rotate(61.2deg);
}
.c100.p18 .bar {
-webkit-transform: rotate(64.8deg);
-moz-transform: rotate(64.8deg);
-ms-transform: rotate(64.8deg);
-o-transform: rotate(64.8deg);
transform: rotate(64.8deg);
}
.c100.p19 .bar {
-webkit-transform: rotate(68.4deg);
-moz-transform: rotate(68.4deg);
-ms-transform: rotate(68.4deg);
-o-transform: rotate(68.4deg);
transform: rotate(68.4deg);
}
.c100.p20 .bar {
-webkit-transform: rotate(72deg);
-moz-transform: rotate(72deg);
-ms-transform: rotate(72deg);
-o-transform: rotate(72deg);
transform: rotate(72deg);
}
.c100.p21 .bar {
-webkit-transform: rotate(75.6deg);
-moz-transform: rotate(75.6deg);
-ms-transform: rotate(75.6deg);
-o-transform: rotate(75.6deg);
transform: rotate(75.6deg);
}
.c100.p22 .bar {
-webkit-transform: rotate(79.2deg);
-moz-transform: rotate(79.2deg);
-ms-transform: rotate(79.2deg);
-o-transform: rotate(79.2deg);
transform: rotate(79.2deg);
}
.c100.p23 .bar {
-webkit-transform: rotate(82.8deg);
-moz-transform: rotate(82.8deg);
-ms-transform: rotate(82.8deg);
-o-transform: rotate(82.8deg);
transform: rotate(82.8deg);
}
.c100.p24 .bar {
-webkit-transform: rotate(86.4deg);
-moz-transform: rotate(86.4deg);
-ms-transform: rotate(86.4deg);
-o-transform: rotate(86.4deg);
transform: rotate(86.4deg);
}
.c100.p25 .bar {
-webkit-transform: rotate(90deg);
-moz-transform: rotate(90deg);
-ms-transform: rotate(90deg);
-o-transform: rotate(90deg);
transform: rotate(90deg);
}
.c100.p26 .bar {
-webkit-transform: rotate(93.6deg);
-moz-transform: rotate(93.6deg);
-ms-transform: rotate(93.6deg);
-o-transform: rotate(93.6deg);
transform: rotate(93.6deg);
}
.c100.p27 .bar {
-webkit-transform: rotate(97.2deg);
-moz-transform: rotate(97.2deg);
-ms-transform: rotate(97.2deg);
-o-transform: rotate(97.2deg);
transform: rotate(97.2deg);
}
.c100.p28 .bar {
-webkit-transform: rotate(100.8deg);
-moz-transform: rotate(100.8deg);
-ms-transform: rotate(100.8deg);
-o-transform: rotate(100.8deg);
transform: rotate(100.8deg);
}
.c100.p29 .bar {
-webkit-transform: rotate(104.4deg);
-moz-transform: rotate(104.4deg);
-ms-transform: rotate(104.4deg);
-o-transform: rotate(104.4deg);
transform: rotate(104.4deg);
}
.c100.p30 .bar {
-webkit-transform: rotate(108deg);
-moz-transform: rotate(108deg);
-ms-transform: rotate(108deg);
-o-transform: rotate(108deg);
transform: rotate(108deg);
}
.c100.p31 .bar {
-webkit-transform: rotate(111.6deg);
-moz-transform: rotate(111.6deg);
-ms-transform: rotate(111.6deg);
-o-transform: rotate(111.6deg);
transform: rotate(111.6deg);
}
.c100.p32 .bar {
-webkit-transform: rotate(115.2deg);
-moz-transform: rotate(115.2deg);
-ms-transform: rotate(115.2deg);
-o-transform: rotate(115.2deg);
transform: rotate(115.2deg);
}
.c100.p33 .bar {
-webkit-transform: rotate(118.8deg);
-moz-transform: rotate(118.8deg);
-ms-transform: rotate(118.8deg);
-o-transform: rotate(118.8deg);
transform: rotate(118.8deg);
}
.c100.p34 .bar {
-webkit-transform: rotate(122.4deg);
-moz-transform: rotate(122.4deg);
-ms-transform: rotate(122.4deg);
-o-transform: rotate(122.4deg);
transform: rotate(122.4deg);
}
.c100.p35 .bar {
-webkit-transform: rotate(126deg);
-moz-transform: rotate(126deg);
-ms-transform: rotate(126deg);
-o-transform: rotate(126deg);
transform: rotate(126deg);
}
.c100.p36 .bar {
-webkit-transform: rotate(129.6deg);
-moz-transform: rotate(129.6deg);
-ms-transform: rotate(129.6deg);
-o-transform: rotate(129.6deg);
transform: rotate(129.6deg);
}
.c100.p37 .bar {
-webkit-transform: rotate(133.2deg);
-moz-transform: rotate(133.2deg);
-ms-transform: rotate(133.2deg);
-o-transform: rotate(133.2deg);
transform: rotate(133.2deg);
}
.c100.p38 .bar {
-webkit-transform: rotate(136.8deg);
-moz-transform: rotate(136.8deg);
-ms-transform: rotate(136.8deg);
-o-transform: rotate(136.8deg);
transform: rotate(136.8deg);
}
.c100.p39 .bar {
-webkit-transform: rotate(140.4deg);
-moz-transform: rotate(140.4deg);
-ms-transform: rotate(140.4deg);
-o-transform: rotate(140.4deg);
transform: rotate(140.4deg);
}
.c100.p40 .bar {
-webkit-transform: rotate(144deg);
-moz-transform: rotate(144deg);
-ms-transform: rotate(144deg);
-o-transform: rotate(144deg);
transform: rotate(144deg);
}
.c100.p41 .bar {
-webkit-transform: rotate(147.6deg);
-moz-transform: rotate(147.6deg);
-ms-transform: rotate(147.6deg);
-o-transform: rotate(147.6deg);
transform: rotate(147.6deg);
}
.c100.p42 .bar {
-webkit-transform: rotate(151.2deg);
-moz-transform: rotate(151.2deg);
-ms-transform: rotate(151.2deg);
-o-transform: rotate(151.2deg);
transform: rotate(151.2deg);
}
.c100.p43 .bar {
-webkit-transform: rotate(154.8deg);
-moz-transform: rotate(154.8deg);
-ms-transform: rotate(154.8deg);
-o-transform: rotate(154.8deg);
transform: rotate(154.8deg);
}
.c100.p44 .bar {
-webkit-transform: rotate(158.4deg);
-moz-transform: rotate(158.4deg);
-ms-transform: rotate(158.4deg);
-o-transform: rotate(158.4deg);
transform: rotate(158.4deg);
}
.c100.p45 .bar {
-webkit-transform: rotate(162deg);
-moz-transform: rotate(162deg);
-ms-transform: rotate(162deg);
-o-transform: rotate(162deg);
transform: rotate(162deg);
}
.c100.p46 .bar {
-webkit-transform: rotate(165.6deg);
-moz-transform: rotate(165.6deg);
-ms-transform: rotate(165.6deg);
-o-transform: rotate(165.6deg);
transform: rotate(165.6deg);
}
.c100.p47 .bar {
-webkit-transform: rotate(169.2deg);
-moz-transform: rotate(169.2deg);
-ms-transform: rotate(169.2deg);
-o-transform: rotate(169.2deg);
transform: rotate(169.2deg);
}
.c100.p48 .bar {
-webkit-transform: rotate(172.8deg);
-moz-transform: rotate(172.8deg);
-ms-transform: rotate(172.8deg);
-o-transform: rotate(172.8deg);
transform: rotate(172.8deg);
}
.c100.p49 .bar {
-webkit-transform: rotate(176.4deg);
-moz-transform: rotate(176.4deg);
-ms-transform: rotate(176.4deg);
-o-transform: rotate(176.4deg);
transform: rotate(176.4deg);
}
.c100.p50 .bar {
-webkit-transform: rotate(180deg);
-moz-transform: rotate(180deg);
-ms-transform: rotate(180deg);
-o-transform: rotate(180deg);
transform: rotate(180deg);
}
.c100.p51 .bar {
-webkit-transform: rotate(183.6deg);
-moz-transform: rotate(183.6deg);
-ms-transform: rotate(183.6deg);
-o-transform: rotate(183.6deg);
transform: rotate(183.6deg);
}
.c100.p52 .bar {
-webkit-transform: rotate(187.2deg);
-moz-transform: rotate(187.2deg);
-ms-transform: rotate(187.2deg);
-o-transform: rotate(187.2deg);
transform: rotate(187.2deg);
}
.c100.p53 .bar {
-webkit-transform: rotate(190.8deg);
-moz-transform: rotate(190.8deg);
-ms-transform: rotate(190.8deg);
-o-transform: rotate(190.8deg);
transform: rotate(190.8deg);
}
.c100.p54 .bar {
-webkit-transform: rotate(194.4deg);
-moz-transform: rotate(194.4deg);
-ms-transform: rotate(194.4deg);
-o-transform: rotate(194.4deg);
transform: rotate(194.4deg);
}
.c100.p55 .bar {
-webkit-transform: rotate(198deg);
-moz-transform: rotate(198deg);
-ms-transform: rotate(198deg);
-o-transform: rotate(198deg);
transform: rotate(198deg);
}
.c100.p56 .bar {
-webkit-transform: rotate(201.6deg);
-moz-transform: rotate(201.6deg);
-ms-transform: rotate(201.6deg);
-o-transform: rotate(201.6deg);
transform: rotate(201.6deg);
}
.c100.p57 .bar {
-webkit-transform: rotate(205.2deg);
-moz-transform: rotate(205.2deg);
-ms-transform: rotate(205.2deg);
-o-transform: rotate(205.2deg);
transform: rotate(205.2deg);
}
.c100.p58 .bar {
-webkit-transform: rotate(208.8deg);
-moz-transform: rotate(208.8deg);
-ms-transform: rotate(208.8deg);
-o-transform: rotate(208.8deg);
transform: rotate(208.8deg);
}
.c100.p59 .bar {
-webkit-transform: rotate(212.4deg);
-moz-transform: rotate(212.4deg);
-ms-transform: rotate(212.4deg);
-o-transform: rotate(212.4deg);
transform: rotate(212.4deg);
}
.c100.p60 .bar {
-webkit-transform: rotate(216deg);
-moz-transform: rotate(216deg);
-ms-transform: rotate(216deg);
-o-transform: rotate(216deg);
transform: rotate(216deg);
}
.c100.p61 .bar {
-webkit-transform: rotate(219.6deg);
-moz-transform: rotate(219.6deg);
-ms-transform: rotate(219.6deg);
-o-transform: rotate(219.6deg);
transform: rotate(219.6deg);
}
.c100.p62 .bar {
-webkit-transform: rotate(223.2deg);
-moz-transform: rotate(223.2deg);
-ms-transform: rotate(223.2deg);
-o-transform: rotate(223.2deg);
transform: rotate(223.2deg);
}
.c100.p63 .bar {
-webkit-transform: rotate(226.8deg);
-moz-transform: rotate(226.8deg);
-ms-transform: rotate(226.8deg);
-o-transform: rotate(226.8deg);
transform: rotate(226.8deg);
}
.c100.p64 .bar {
-webkit-transform: rotate(230.4deg);
-moz-transform: rotate(230.4deg);
-ms-transform: rotate(230.4deg);
-o-transform: rotate(230.4deg);
transform: rotate(230.4deg);
}
.c100.p65 .bar {
-webkit-transform: rotate(234deg);
-moz-transform: rotate(234deg);
-ms-transform: rotate(234deg);
-o-transform: rotate(234deg);
transform: rotate(234deg);
}
.c100.p66 .bar {
-webkit-transform: rotate(237.6deg);
-moz-transform: rotate(237.6deg);
-ms-transform: rotate(237.6deg);
-o-transform: rotate(237.6deg);
transform: rotate(237.6deg);
}
.c100.p67 .bar {
-webkit-transform: rotate(241.2deg);
-moz-transform: rotate(241.2deg);
-ms-transform: rotate(241.2deg);
-o-transform: rotate(241.2deg);
transform: rotate(241.2deg);
}
.c100.p68 .bar {
-webkit-transform: rotate(244.8deg);
-moz-transform: rotate(244.8deg);
-ms-transform: rotate(244.8deg);
-o-transform: rotate(244.8deg);
transform: rotate(244.8deg);
}
.c100.p69 .bar {
-webkit-transform: rotate(248.4deg);
-moz-transform: rotate(248.4deg);
-ms-transform: rotate(248.4deg);
-o-transform: rotate(248.4deg);
transform: rotate(248.4deg);
}
.c100.p70 .bar {
-webkit-transform: rotate(252deg);
-moz-transform: rotate(252deg);
-ms-transform: rotate(252deg);
-o-transform: rotate(252deg);
transform: rotate(252deg);
}
.c100.p71 .bar {
-webkit-transform: rotate(255.6deg);
-moz-transform: rotate(255.6deg);
-ms-transform: rotate(255.6deg);
-o-transform: rotate(255.6deg);
transform: rotate(255.6deg);
}
.c100.p72 .bar {
-webkit-transform: rotate(259.2deg);
-moz-transform: rotate(259.2deg);
-ms-transform: rotate(259.2deg);
-o-transform: rotate(259.2deg);
transform: rotate(259.2deg);
}
.c100.p73 .bar {
-webkit-transform: rotate(262.8deg);
-moz-transform: rotate(262.8deg);
-ms-transform: rotate(262.8deg);
-o-transform: rotate(262.8deg);
transform: rotate(262.8deg);
}
.c100.p74 .bar {
-webkit-transform: rotate(266.4deg);
-moz-transform: rotate(266.4deg);
-ms-transform: rotate(266.4deg);
-o-transform: rotate(266.4deg);
transform: rotate(266.4deg);
}
.c100.p75 .bar {
-webkit-transform: rotate(270deg);
-moz-transform: rotate(270deg);
-ms-transform: rotate(270deg);
-o-transform: rotate(270deg);
transform: rotate(270deg);
}
.c100.p76 .bar {
-webkit-transform: rotate(273.6deg);
-moz-transform: rotate(273.6deg);
-ms-transform: rotate(273.6deg);
-o-transform: rotate(273.6deg);
transform: rotate(273.6deg);
}
.c100.p77 .bar {
-webkit-transform: rotate(277.2deg);
-moz-transform: rotate(277.2deg);
-ms-transform: rotate(277.2deg);
-o-transform: rotate(277.2deg);
transform: rotate(277.2deg);
}
.c100.p78 .bar {
-webkit-transform: rotate(280.8deg);
-moz-transform: rotate(280.8deg);
-ms-transform: rotate(280.8deg);
-o-transform: rotate(280.8deg);
transform: rotate(280.8deg);
}
.c100.p79 .bar {
-webkit-transform: rotate(284.4deg);
-moz-transform: rotate(284.4deg);
-ms-transform: rotate(284.4deg);
-o-transform: rotate(284.4deg);
transform: rotate(284.4deg);
}
.c100.p80 .bar {
-webkit-transform: rotate(288deg);
-moz-transform: rotate(288deg);
-ms-transform: rotate(288deg);
-o-transform: rotate(288deg);
transform: rotate(288deg);
}
.c100.p81 .bar {
-webkit-transform: rotate(291.6deg);
-moz-transform: rotate(291.6deg);
-ms-transform: rotate(291.6deg);
-o-transform: rotate(291.6deg);
transform: rotate(291.6deg);
}
.c100.p82 .bar {
-webkit-transform: rotate(295.2deg);
-moz-transform: rotate(295.2deg);
-ms-transform: rotate(295.2deg);
-o-transform: rotate(295.2deg);
transform: rotate(295.2deg);
}
.c100.p83 .bar {
-webkit-transform: rotate(298.8deg);
-moz-transform: rotate(298.8deg);
-ms-transform: rotate(298.8deg);
-o-transform: rotate(298.8deg);
transform: rotate(298.8deg);
}
.c100.p84 .bar {
-webkit-transform: rotate(302.4deg);
-moz-transform: rotate(302.4deg);
-ms-transform: rotate(302.4deg);
-o-transform: rotate(302.4deg);
transform: rotate(302.4deg);
}
.c100.p85 .bar {
-webkit-transform: rotate(306deg);
-moz-transform: rotate(306deg);
-ms-transform: rotate(306deg);
-o-transform: rotate(306deg);
transform: rotate(306deg);
}
.c100.p86 .bar {
-webkit-transform: rotate(309.6deg);
-moz-transform: rotate(309.6deg);
-ms-transform: rotate(309.6deg);
-o-transform: rotate(309.6deg);
transform: rotate(309.6deg);
}
.c100.p87 .bar {
-webkit-transform: rotate(313.2deg);
-moz-transform: rotate(313.2deg);
-ms-transform: rotate(313.2deg);
-o-transform: rotate(313.2deg);
transform: rotate(313.2deg);
}
.c100.p88 .bar {
-webkit-transform: rotate(316.8deg);
-moz-transform: rotate(316.8deg);
-ms-transform: rotate(316.8deg);
-o-transform: rotate(316.8deg);
transform: rotate(316.8deg);
}
.c100.p89 .bar {
-webkit-transform: rotate(320.4deg);
-moz-transform: rotate(320.4deg);
-ms-transform: rotate(320.4deg);
-o-transform: rotate(320.4deg);
transform: rotate(320.4deg);
}
.c100.p90 .bar {
-webkit-transform: rotate(324deg);
-moz-transform: rotate(324deg);
-ms-transform: rotate(324deg);
-o-transform: rotate(324deg);
transform: rotate(324deg);
}
.c100.p91 .bar {
-webkit-transform: rotate(327.6deg);
-moz-transform: rotate(327.6deg);
-ms-transform: rotate(327.6deg);
-o-transform: rotate(327.6deg);
transform: rotate(327.6deg);
}
.c100.p92 .bar {
-webkit-transform: rotate(331.2deg);
-moz-transform: rotate(331.2deg);
-ms-transform: rotate(331.2deg);
-o-transform: rotate(331.2deg);
transform: rotate(331.2deg);
}
.c100.p93 .bar {
-webkit-transform: rotate(334.8deg);
-moz-transform: rotate(334.8deg);
-ms-transform: rotate(334.8deg);
-o-transform: rotate(334.8deg);
transform: rotate(334.8deg);
}
.c100.p94 .bar {
-webkit-transform: rotate(338.4deg);
-moz-transform: rotate(338.4deg);
-ms-transform: rotate(338.4deg);
-o-transform: rotate(338.4deg);
transform: rotate(338.4deg);
}
.c100.p95 .bar {
-webkit-transform: rotate(342deg);
-moz-transform: rotate(342deg);
-ms-transform: rotate(342deg);
-o-transform: rotate(342deg);
transform: rotate(342deg);
}
.c100.p96 .bar {
-webkit-transform: rotate(345.6deg);
-moz-transform: rotate(345.6deg);
-ms-transform: rotate(345.6deg);
-o-transform: rotate(345.6deg);
transform: rotate(345.6deg);
}
.c100.p97 .bar {
-webkit-transform: rotate(349.2deg);
-moz-transform: rotate(349.2deg);
-ms-transform: rotate(349.2deg);
-o-transform: rotate(349.2deg);
transform: rotate(349.2deg);
}
.c100.p98 .bar {
-webkit-transform: rotate(352.8deg);
-moz-transform: rotate(352.8deg);
-ms-transform: rotate(352.8deg);
-o-transform: rotate(352.8deg);
transform: rotate(352.8deg);
}
.c100.p99 .bar {
-webkit-transform: rotate(356.4deg);
-moz-transform: rotate(356.4deg);
-ms-transform: rotate(356.4deg);
-o-transform: rotate(356.4deg);
transform: rotate(356.4deg);
}
.c100.p100 .bar {
-webkit-transform: rotate(360deg);
-moz-transform: rotate(360deg);
-ms-transform: rotate(360deg);
-o-transform: rotate(360deg);
transform: rotate(360deg);
}
.c100:hover {
cursor: default;
}
.c100:hover > span {
width: 3.33em;
line-height: 3.33em;
font-size: 0.3em;
color: #307bbb;
}
.c100:hover:after {
top: 0.04em;
left: 0.04em;
width: 0.92em;
height: 0.92em;
}
.c100.dark {
background-color: #777777;
}
.c100.dark .bar,
.c100.dark .fill {
border-color: #c6ff00 !important;
}
.c100.dark > span {
color: #777777;
}
.c100.dark:after {
background-color: #666666;
}
.c100.dark:hover > span {
color: #c6ff00;
}
.c100.green .bar, .c100.green .fill {
border-color: #4db53c !important;
}
.c100.green:hover > span {
color: #4db53c;
}
.c100.green.dark .bar, .c100.green.dark .fill {
border-color: #5fd400 !important;
}
.c100.green.dark:hover > span {
color: #5fd400;
}
.c100.orange .bar, .c100.orange .fill {
border-color: #dd9d22 !important;
}
.c100.orange:hover > span {
color: #dd9d22;
}
.c100.orange.dark .bar, .c100.orange.dark .fill {
border-color: #e08833 !important;
}
.c100.orange.dark:hover > span {
color: #e08833;
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,102 @@
/* Custom styles for TwentyTwenty integration with CompressX */
/* Ensure TwentyTwenty container fits properly */
.twentytwenty-container {
position: relative !important;
width: 100% !important;
height: 100% !important;
min-height: 280px;
background: #ffffff !important;
border-radius: 6px;
overflow: hidden;
}
/* Ensure images maintain aspect ratio */
.twentytwenty-container img {
max-width: 100% !important;
height: auto !important;
display: block;
}
/* Override any conflicting flex styles */
.twentytwenty-container.compressx-v2-flex {
display: block !important;
}
/* Ensure proper overlay positioning */
.twentytwenty-overlay {
background: rgba(0, 0, 0, 0) !important;
}
/* Custom handle styling to match CompressX theme */
.twentytwenty-handle {
border: 3px solid #3b82f6 !important;
background: #ffffff !important;
}
.twentytwenty-handle:before,
.twentytwenty-handle:after {
background: #3b82f6 !important;
}
/* Enhanced visibility */
.twentytwenty-container::before {
content: '';
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: #ffffff;
z-index: -1;
}
/* Improved image visibility */
.twentytwenty-container img {
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
/* Better overlay contrast */
.twentytwenty-overlay {
background: rgba(0, 0, 0, 0) !important;
color: #ffffff !important;
font-weight: 600 !important;
}
/* Responsive adjustments */
@media (max-width: 768px) {
.twentytwenty-container {
min-height: 200px;
}
.twentytwenty-overlay {
font-size: 11px !important;
}
}
/* Prevent FOUC (Flash of Unstyled Content) */
.cx-comparison-placeholder {
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
}
/* Loading state */
.twentytwenty-container.loading {
opacity: 0.7;
}
.twentytwenty-container.loading::after {
content: "Loading...";
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: rgba(255, 255, 255, 0.9);
padding: 10px 20px;
border-radius: 4px;
font-size: 14px;
color: #666;
}
@@ -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; }
@@ -0,0 +1,74 @@
function compressx_post_request(ajax_data, callback, error_callback, time_out)
{
if(typeof time_out === 'undefined') time_out = 30000;
ajax_data.nonce=compressx_ajax_object.ajax_nonce;
jQuery.ajax({
type: "post",
url: compressx_ajax_object.ajax_url,
data: ajax_data,
success: function (data) {
callback(data);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
error_callback(XMLHttpRequest, textStatus, errorThrown);
},
timeout: time_out
});
}
function compressx_output_ajaxerror(action, textStatus, errorThrown){
//action = 'trying to establish communication with your server';
var error_msg = "compressx_request: "+ textStatus + "(" + errorThrown + "): an error occurred when " + action + ". " +
"It could be because the request did not reach or the server did not respond. Please try again later.";
return error_msg;
}
function compressx_ajax_data_transfer(data_type)
{
var json = {};
jQuery('input:checkbox[option='+data_type+']').each(function() {
var value = '0';
var key = jQuery(this).prop('name');
if(jQuery(this).prop('checked')) {
value = '1';
}
else {
value = '0';
}
json[key]=value;
});
jQuery('input:radio[option='+data_type+']').each(function() {
if(jQuery(this).prop('checked'))
{
var key = jQuery(this).prop('name');
var value = jQuery(this).prop('value');
json[key]=value;
}
});
jQuery('input:text[option='+data_type+']').each(function(){
var obj = {};
var key = jQuery(this).prop('name');
var value = jQuery(this).val();
json[key]=value;
});
jQuery('textarea[option='+data_type+']').each(function(){
var obj = {};
var key = jQuery(this).prop('name');
var value = jQuery(this).val();
json[key]=value;
});
jQuery('input:password[option='+data_type+']').each(function(){
var obj = {};
var key = jQuery(this).prop('name');
var value = jQuery(this).val();
json[key]=value;
});
jQuery('select[option='+data_type+']').each(function(){
var obj = {};
var key = jQuery(this).prop('name');
var value = jQuery(this).val();
json[key]=value;
});
return JSON.stringify(json);
}
@@ -0,0 +1,426 @@
var cx_cancel_custom_bulk_optimization=false;
jQuery('#compressx_start_custom_bulk_optimization').click(function()
{
compressx_start_custom_bulk_optimization();
});
jQuery('#compressx_cancel_custom_bulk_optimization').click(function()
{
var descript = 'Are you sure to cancel this progressing?';
var ret = confirm(descript);
if(ret === true)
{
cx_cancel_custom_bulk_optimization=true;
jQuery('#compressx_cancel_custom_bulk_optimization').css({'pointer-events': 'none', 'opacity': '0.4'});
}
});
function compressx_custom_bulk_optimization_canceled()
{
jQuery('#cx_custom_bulk_progress_text').hide();
jQuery('#compressx_cancel_custom_bulk_optimization').hide();
jQuery('#compressx_start_custom_bulk_optimization').show();
jQuery('#compressx_start_custom_bulk_optimization').css({'pointer-events': 'auto', 'opacity': '1'});
jQuery('#compressx_cancel_custom_bulk_optimization').css({'pointer-events': 'auto', 'opacity': '1'});
compressx_get_dir_info();
}
function compressx_start_custom_bulk_optimization()
{
var ajax_data = {
'action': 'compressx_start_scan_custom_images',
};
jQuery('#compressx_start_custom_bulk_optimization').css({'pointer-events': 'none', 'opacity': '0.4'});
jQuery('#cx_custom_bulk_progress_text').show();
jQuery('#cx_custom_bulk_progress_text').html("Processing...");
jQuery('#cx_custom_overview').hide();
jQuery('#compressx_cancel_custom_bulk_optimization').show();
jQuery('#compressx_start_custom_bulk_optimization').hide();
cx_cancel_custom_bulk_optimization=false;
compressx_post_request(ajax_data, function (data)
{
if(cx_cancel_custom_bulk_optimization)
{
compressx_custom_bulk_optimization_canceled();
alert("The process has been canceled");
return;
}
var jsonarray = jQuery.parseJSON(data);
if (jsonarray.result === 'success')
{
if(jsonarray.finished==true)
{
jQuery('#cx_custom_bulk_progress_text').html(jsonarray.progress);
compressx_init_custom_bulk_optimization_task();
}
}
else
{
jQuery('#compressx_cancel_custom_bulk_optimization').hide();
jQuery('#compressx_start_custom_bulk_optimization').show();
jQuery('#cx_custom_bulk_progress_text').hide();
jQuery('#cx_custom_overview').show();
jQuery('#compressx_start_custom_bulk_optimization').css({'pointer-events': 'auto', 'opacity': '1'});
alert(jsonarray.error);
}
}, function (XMLHttpRequest, textStatus, errorThrown)
{
jQuery('#compressx_cancel_custom_bulk_optimization').hide();
jQuery('#compressx_start_custom_bulk_optimization').show();
jQuery('#cx_custom_bulk_progress_text').hide();
jQuery('#cx_custom_overview').show();
jQuery('#compressx_start_custom_bulk_optimization').css({'pointer-events': 'auto', 'opacity': '1'});
var error_message = compressx_output_ajaxerror('scan images', textStatus, errorThrown);
alert(error_message);
});
}
function compressx_init_custom_bulk_optimization_task()
{
var force="0";
if(jQuery('#cx_custom_force_optimization').prop('checked'))
{
force = '1';
}
else {
force = '0';
}
var ajax_data = {
'action': 'compressx_init_custom_bulk_optimization_task',
'force':force
};
jQuery('#compressx_bulk_progress_step2').addClass("cx-active");
compressx_post_request(ajax_data, function (data)
{
if(cx_cancel_custom_bulk_optimization)
{
compressx_custom_bulk_optimization_canceled();
alert("The process has been canceled");
return;
}
var jsonarray = jQuery.parseJSON(data);
if (jsonarray.result === 'success')
{
compressx_run_custom_optimize();
}
else
{
jQuery('#compressx_cancel_custom_bulk_optimization').hide();
jQuery('#compressx_start_custom_bulk_optimization').show();
jQuery('#cx_custom_bulk_progress_text').hide();
jQuery('#cx_custom_overview').show();
jQuery('#compressx_start_custom_bulk_optimization').css({'pointer-events': 'auto', 'opacity': '1'});
alert(jsonarray.error);
}
}, function (XMLHttpRequest, textStatus, errorThrown)
{
jQuery('#compressx_cancel_custom_bulk_optimization').hide();
jQuery('#compressx_start_custom_bulk_optimization').show();
jQuery('#cx_custom_bulk_progress_text').hide();
jQuery('#cx_custom_overview').show();
jQuery('#compressx_start_custom_bulk_optimization').css({'pointer-events': 'auto', 'opacity': '1'});
var error_message = compressx_output_ajaxerror('start bulk optimization', textStatus, errorThrown);
alert(error_message);
});
}
function compressx_run_custom_optimize()
{
var ajax_data = {
'action': 'compressx_run_custom_optimize',
};
compressx_post_request(ajax_data, function (data)
{
var jsonarray = jQuery.parseJSON(data);
if (jsonarray.result === 'success')
{
compressx_get_custom_optimize_task_status();
}
else
{
jQuery('#compressx_cancel_custom_bulk_optimization').hide();
jQuery('#compressx_start_custom_bulk_optimization').show();
jQuery('#cx_custom_bulk_progress_text').hide();
jQuery('#cx_custom_overview').show();
jQuery('#compressx_start_custom_bulk_optimization').css({'pointer-events': 'auto', 'opacity': '1'});
alert(jsonarray.error);
}
}, function (XMLHttpRequest, textStatus, errorThrown)
{
compressx_get_custom_optimize_task_status();
});
}
function compressx_get_custom_optimize_task_status()
{
var ajax_data = {
'action': 'compressx_get_custom_opt_progress'
};
compressx_post_request(ajax_data, function(data)
{
try
{
var jsonarray = jQuery.parseJSON(data);
if (jsonarray.result === 'success')
{
jQuery('#cx_custom_bulk_progress_text').html(jsonarray.log);
if(jsonarray.continue)
{
setTimeout(function ()
{
compressx_get_custom_optimize_task_status();
}, 1000);
}
else if(jsonarray.finished)
{
compressx_get_dir_info();
jQuery('#compressx_start_custom_bulk_optimization').css({'pointer-events': 'auto', 'opacity': '1'});
jQuery('#cx_custom_bulk_progress_text').hide();
jQuery('#cx_custom_overview').show();
jQuery('#compressx_cancel_custom_bulk_optimization').hide();
jQuery('#compressx_start_custom_bulk_optimization').show();
compressx_custom_show_review_box(jsonarray);
}
else
{
if(cx_cancel_custom_bulk_optimization)
{
compressx_custom_bulk_optimization_canceled();
alert("The process has been canceled");
return;
}
compressx_run_custom_optimize();
}
}
else if (jsonarray.result === 'failed')
{
if(jsonarray.timeout)
{
if(cx_cancel_custom_bulk_optimization)
{
compressx_custom_bulk_optimization_canceled();
alert("The process has been canceled");
return;
}
compressx_run_custom_optimize();
}
else
{
alert(jsonarray.error);
jQuery('#compressx_start_custom_bulk_optimization').css({'pointer-events': 'auto', 'opacity': '1'});
jQuery('#cx_custom_bulk_progress_text').hide();
jQuery('#compressx_cancel_custom_bulk_optimization').hide();
jQuery('#compressx_start_custom_bulk_optimization').show();
jQuery('#cx_custom_overview').show();
}
}
}
catch(err)
{
alert(err);
jQuery('#compressx_start_custom_bulk_optimization').css({'pointer-events': 'auto', 'opacity': '1'});
jQuery('#cx_custom_bulk_progress_text').hide();
jQuery('#compressx_cancel_custom_bulk_optimization').hide();
jQuery('#compressx_start_custom_bulk_optimization').show();
jQuery('#cx_custom_overview').show();
}
}, function(XMLHttpRequest, textStatus, errorThrown)
{
setTimeout(function ()
{
compressx_get_custom_optimize_task_status();
}, 1000);
});
}
function compressx_custom_show_review_box(jsonarray)
{
if(jsonarray.show_review)
{
jQuery('#cx_rating_box').show();
jQuery('#cx_size_of_opt_images').html(jsonarray.opt_size);
}
}
function compressx_get_dir_info()
{
var ajax_data = {
'action': 'compressx_get_dir_info',
};
compressx_post_request(ajax_data, function (data)
{
try
{
var jsonarray = jQuery.parseJSON(data);
if (jsonarray.result === 'success')
{
jQuery('#cx_custom_founds').html(jsonarray.found);
jQuery('#cx_custom_total_saving').html(jsonarray.saved);
jQuery('#cx_custom_processed').html(jsonarray.processed);
}
}
catch (err)
{
//alert(err);
}
}, function (XMLHttpRequest, textStatus, errorThrown)
{
});
}
function compressx_init_custom_exclude_tree()
{
jQuery('#compressx_custom_include_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.custom_path
};
var ajax_data = {
'action': 'compressx_get_custom_tree_dir_ex',
'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_custom_exclude_tree();
});
jQuery('#compressx_custom_include_js_tree').on('click', '.cx-add-custom-include-tree', function()
{
var id=jQuery(this).data("id");
var ajax_data = {
'action': 'compressx_add_include_folders',
'id': id,
};
compressx_post_request(ajax_data, function (data)
{
try
{
var jsonarray = jQuery.parseJSON(data);
if (jsonarray.result === 'success')
{
jQuery('#cx_custom_founds').html(jsonarray.found);
jQuery('#cx_custom_total_saving').html(jsonarray.saved);
jQuery('#cx_custom_processed').html(jsonarray.processed);
jQuery('#compressx_include_dir_node').html(jsonarray.html);
}
else {
alert(jsonarray.error);
}
}
catch (err)
{
alert(err);
}
}, function (XMLHttpRequest, textStatus, errorThrown)
{
var error_message = compressx_output_ajaxerror('changing settings', textStatus, errorThrown);
alert(error_message);
});
});
jQuery('#compressx_include_dir_node').on('click', '.cx-remove-custom-include-tree', function()
{
var id=jQuery(this).data("id");
var node=jQuery(this).parent();
var ajax_data = {
'action': 'compressx_remove_include_folders',
'id': id,
};
compressx_post_request(ajax_data, function (data)
{
try
{
var jsonarray = jQuery.parseJSON(data);
if (jsonarray.result === 'success')
{
jQuery('#cx_custom_founds').html(jsonarray.found);
jQuery('#cx_custom_total_saving').html(jsonarray.saved);
jQuery('#cx_custom_processed').html(jsonarray.processed);
node.remove();
}
else {
alert(jsonarray.error);
}
}
catch (err)
{
alert(err);
}
}, function (XMLHttpRequest, textStatus, errorThrown)
{
var error_message = compressx_output_ajaxerror('changing settings', textStatus, errorThrown);
alert(error_message);
});
});
@@ -0,0 +1,297 @@
jQuery('#cx_edit_apiserver').click(function()
{
jQuery('#cx_apiserver').hide();
jQuery('#cx_apiserver_edit').show();
});
jQuery('#cx_apiserver_edit_btn').click(function()
{
jQuery('#cx_apiserver_edit_progress').show();
var api_server=jQuery('#cx_apiserver_select').val();
var ajax_data = {
'action': 'compressx_set_api_server',
'api_server': api_server,
};
jQuery('#cx_apiserver_edit_btn').css({'pointer-events': 'none', 'opacity': '0.4'});
compressx_post_request(ajax_data, function (data)
{
jQuery('#cx_apiserver_edit_progress').hide();
try
{
var jsonarray = jQuery.parseJSON(data);
jQuery('#cx_apiserver_edit_btn').css({'pointer-events': 'auto', 'opacity': '1'});
if (jsonarray.result === 'success')
{
//
jQuery('#cx_apiserver_text').html(jsonarray.html);
jQuery('#cx_apiserver').show();
jQuery('#cx_apiserver_edit').hide();
}
else {
alert(jsonarray.error);
}
}
catch (err)
{
alert(err);
jQuery('#cx_apiserver_edit_btn').css({'pointer-events': 'auto', 'opacity': '1'});
}
}, function (XMLHttpRequest, textStatus, errorThrown)
{
jQuery('#cx_apiserver_edit_progress').hide();
jQuery('#cx_apiserver_edit_btn').css({'pointer-events': 'auto', 'opacity': '1'});
var error_message = compressx_output_ajaxerror('set api server', textStatus, errorThrown);
alert(error_message);
});
});
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);
}
});
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")
{
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_log_list').on("click",'.cs-log-download',function()
{
var file_name = jQuery(this).closest('td').data('id');
compressx_download_log(file_name);
});
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-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")
{
jQuery('#cx_log_list').html(jsonarray.html);
}
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")
{
jQuery('#cx_log_list').html(jsonarray.html);
}
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);
});
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,51 @@
jQuery('#compressx_download_debug_info').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';
}
jQuery('#compressx_debug_submit').click(function()
{
cx_debug_submit();
});
function cx_debug_submit()
{
var user_mail = jQuery('#compressx_user_mail').val();
var comment = jQuery('#compressx_debug_comment').val();
var ajax_data = {
'action': 'compressx_send_debug_info',
'user_mail': user_mail,
'comment':comment
};
compressx_post_request(ajax_data, function (data) {
try {
var jsonarray = jQuery.parseJSON(data);
if (jsonarray.result === "success")
{
jQuery('#compressx_debug_comment').html("");
jQuery('#compressx_send_success_text').removeClass("hidden");
setTimeout(function ()
{
jQuery('#compressx_send_success_text').addClass( 'hidden' );
}, 3000);
}
else {
alert(jsonarray.error);
}
}
catch (err) {
alert(err);
}
}, function (XMLHttpRequest, textStatus, errorThrown) {
var error_message = compressx_output_ajaxerror('sending debug information', textStatus, errorThrown);
alert(error_message);
});
}
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.4 KiB

File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

@@ -0,0 +1,273 @@
window.compressx = window.compressx || {};
(function($, w, undefined)
{
w.compressx.media={
progress_queue:[],
lock:false,
init:function()
{
$( document ).on( 'click', '.cx-media-item a.cx-media', this.handle_action_button);
$( document ).on( 'click', '.misc-pub-cx a.cx-media', this.handle_action_button_edit);
$( document ).on( 'click', '.cx-media-attachment a.cx-media', this.handle_action_button_attachment);
w.compressx.media.get_progress();
},
handle_action_button:function ()
{
if(w.compressx.media.islockbtn())
{
return ;
}
var $row = $(this).closest('.cx-media-item');
var $select = $row.find('.cx-media-selected');
var action = $select.val();
if(action==="")
{
return;
}
var id=$( this ).data( 'id' );
$( this ).html("Progressing...");
$( this ).removeClass('cx-media');
w.compressx.media.lockbtn(true);
var ajax_action=w.compressx.media.get_ajax_action(action);
var ajax_data = {
'action': ajax_action,
'id':id
};
compressx_post_request(ajax_data, function(data)
{
w.compressx.media.get_progress();
}, function(XMLHttpRequest, textStatus, errorThrown)
{
w.compressx.media.get_progress();
});
},
handle_action_button_edit:function()
{
if(w.compressx.media.islockbtn())
{
return ;
}
var $row = $(this).closest('.misc-pub-cx');
var $select = $row.find('.cx-media-selected');
var action = $select.val();
if(action==="")
{
return;
}
var id=$( this ).data( 'id' );
$( this ).html("Converting...");
$( this ).removeClass('cx-media');
w.compressx.media.lockbtn(true);
var ajax_action=w.compressx.media.get_ajax_action(action);
var ajax_data = {
'action': ajax_action,
'id':id
};
compressx_post_request(ajax_data, function(data)
{
w.compressx.media.get_progress('edit');
}, function(XMLHttpRequest, textStatus, errorThrown)
{
w.compressx.media.get_progress('edit');
});
},
handle_action_button_attachment:function()
{
if(w.compressx.media.islockbtn())
{
return ;
}
var $row = $(this).closest('.cx-media-attachment');
var $select = $row.find('.cx-media-selected');
var action = $select.val();
if(action==="")
{
return;
}
var id=$( this ).data( 'id' );
$( this ).html("Converting...");
$( this ).removeClass('cx-media');
w.compressx.media.lockbtn(true);
var ajax_action=w.compressx.media.get_ajax_action(action);
var ajax_data = {
'action': ajax_action,
'id':id
};
compressx_post_request(ajax_data, function(data)
{
w.compressx.media.get_progress('attachment');
}, function(XMLHttpRequest, textStatus, errorThrown)
{
w.compressx.media.get_progress('attachment');
});
},
get_ajax_action: function(action) {
switch (action) {
case 'convert': return 'compressx_opt_single_image';
case 'delete': return 'compressx_delete_single_image';
default: return '';
}
},
get_progress:function(page='media')
{
var ids=[];
if(page=='media')
{
var media=$('.cx-media-item');
if ( media.length>0 )
{
media.each( function()
{
ids.push( $( this ).data( 'id' ) );
} );
}
}
else if(page=='attachment')
{
var id=$('.cx-media-attachment').data( 'id' );
ids.push(id );
}
else
{
var id=$('.misc-pub-cx').data( 'id' );
ids.push(id );
}
if(ids.length<1)
{
return;
}
var ids_json=JSON.stringify(ids);
var ajax_data = {
'action': 'compressx_get_opt_single_image_progress',
ids:ids_json,
page:page
};
compressx_post_request(ajax_data, function(data)
{
try
{
if(typeof data !== 'undefined' && data !== '')
{
var jsonarray = jQuery.parseJSON(data);
w.compressx.media.update(jsonarray,page);
if (jsonarray.result === 'success')
{
if(jsonarray.continue)
{
setTimeout(function ()
{
w.compressx.media.get_progress(page);
}, 1000);
}
else if(jsonarray.finished)
{
w.compressx.media.lockbtn(false);
}
else
{
//w.compressx.media.optimize_timeout_image(page);
w.compressx.media.lockbtn(false);
}
}
else
{
if(jsonarray.timeout)
{
//w.compressx.media.optimize_timeout_image(page);
w.compressx.media.lockbtn(false);
}
else
{
w.compressx.media.lockbtn(false);
}
}
}
}
catch(err)
{
alert(err);
w.compressx.media.lockbtn(false);
}
}, function(XMLHttpRequest, textStatus, errorThrown)
{
setTimeout(function ()
{
w.compressx.media.get_progress(page);
}, 1000);
});
},
update:function (jsonarray,page='media')
{
if(page=='edit')
{
var id=$('.misc-pub-cx').data( 'id' );
if(jsonarray.hasOwnProperty(id))
{
$( '.misc-pub-cx' ).html(jsonarray[id]['html']);
}
}
else if(page=='attachment')
{
var media=$('.cx-media-attachment');
if ( media.length>0 )
{
media.each( function()
{
var id=$( this ).data( 'id' );
if(jsonarray.hasOwnProperty(id))
{
$( this ).html(jsonarray[id]['html']);
}
} );
}
}
else
{
var media=$('.cx-media-item');
if ( media.length>0 )
{
media.each( function()
{
var id=$( this ).data( 'id' );
if(jsonarray.hasOwnProperty(id))
{
$( this ).html(jsonarray[id]['html']);
}
} );
}
}
},
lockbtn:function (status)
{
w.compressx.media.lock=status;
},
islockbtn:function ()
{
return w.compressx.media.lock;
}
};
w.compressx.media.init();
})(jQuery, window);
@@ -0,0 +1,599 @@
// DOM.event.move
//
// 2.0.0
//
// Stephen Band
//
// Triggers 'movestart', 'move' and 'moveend' events after
// mousemoves following a mousedown cross a distance threshold,
// similar to the native 'dragstart', 'drag' and 'dragend' events.
// Move events are throttled to animation frames. Move event objects
// have the properties:
//
// pageX:
// pageY: Page coordinates of pointer.
// startX:
// startY: Page coordinates of pointer at movestart.
// distX:
// distY: Distance the pointer has moved since movestart.
// deltaX:
// deltaY: Distance the finger has moved since last event.
// velocityX:
// velocityY: Average velocity over last few events.
(function(fn) {
if (typeof define === 'function' && define.amd) {
define([], fn);
} else if ((typeof module !== "undefined" && module !== null) && module.exports) {
module.exports = fn;
} else {
fn();
}
})(function(){
var assign = Object.assign || window.jQuery && jQuery.extend;
// Number of pixels a pressed pointer travels before movestart
// event is fired.
var threshold = 8;
// Shim for requestAnimationFrame, falling back to timer. See:
// see http://paulirish.com/2011/requestanimationframe-for-smart-animating/
var requestFrame = (function(){
return (
window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(fn, element){
return window.setTimeout(function(){
fn();
}, 25);
}
);
})();
// Shim for customEvent
// see https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent/CustomEvent#Polyfill
(function () {
if ( typeof window.CustomEvent === "function" ) return false;
function CustomEvent ( event, params ) {
params = params || { bubbles: false, cancelable: false, detail: undefined };
var evt = document.createEvent( 'CustomEvent' );
evt.initCustomEvent( event, params.bubbles, params.cancelable, params.detail );
return evt;
}
CustomEvent.prototype = window.Event.prototype;
window.CustomEvent = CustomEvent;
})();
var ignoreTags = {
textarea: true,
input: true,
select: true,
button: true
};
var mouseevents = {
move: 'mousemove',
cancel: 'mouseup dragstart',
end: 'mouseup'
};
var touchevents = {
move: 'touchmove',
cancel: 'touchend',
end: 'touchend'
};
var rspaces = /\s+/;
// DOM Events
var eventOptions = { bubbles: true, cancelable: true };
var eventsSymbol = typeof Symbol === "function" ? Symbol('events') : {};
function createEvent(type) {
return new CustomEvent(type, eventOptions);
}
function getEvents(node) {
return node[eventsSymbol] || (node[eventsSymbol] = {});
}
function on(node, types, fn, data, selector) {
types = types.split(rspaces);
var events = getEvents(node);
var i = types.length;
var handlers, type;
function handler(e) { fn(e, data); }
while (i--) {
type = types[i];
handlers = events[type] || (events[type] = []);
handlers.push([fn, handler]);
node.addEventListener(type, handler);
}
}
function off(node, types, fn, selector) {
types = types.split(rspaces);
var events = getEvents(node);
var i = types.length;
var type, handlers, k;
if (!events) { return; }
while (i--) {
type = types[i];
handlers = events[type];
if (!handlers) { continue; }
k = handlers.length;
while (k--) {
if (handlers[k][0] === fn) {
node.removeEventListener(type, handlers[k][1]);
handlers.splice(k, 1);
}
}
}
}
function trigger(node, type, properties) {
// Don't cache events. It prevents you from triggering an event of a
// given type from inside the handler of another event of that type.
var event = createEvent(type);
if (properties) { assign(event, properties); }
node.dispatchEvent(event);
}
// Constructors
function Timer(fn){
var callback = fn,
active = false,
running = false;
function trigger(time) {
if (active){
callback();
requestFrame(trigger);
running = true;
active = false;
}
else {
running = false;
}
}
this.kick = function(fn) {
active = true;
if (!running) { trigger(); }
};
this.end = function(fn) {
var cb = callback;
if (!fn) { return; }
// If the timer is not running, simply call the end callback.
if (!running) {
fn();
}
// If the timer is running, and has been kicked lately, then
// queue up the current callback and the end callback, otherwise
// just the end callback.
else {
callback = active ?
function(){ cb(); fn(); } :
fn ;
active = true;
}
};
}
// Functions
function noop() {}
function preventDefault(e) {
e.preventDefault();
}
function isIgnoreTag(e) {
return !!ignoreTags[e.target.tagName.toLowerCase()];
}
function isPrimaryButton(e) {
// Ignore mousedowns on any button other than the left (or primary)
// mouse button, or when a modifier key is pressed.
return (e.which === 1 && !e.ctrlKey && !e.altKey);
}
function identifiedTouch(touchList, id) {
var i, l;
if (touchList.identifiedTouch) {
return touchList.identifiedTouch(id);
}
// touchList.identifiedTouch() does not exist in
// webkit yet… we must do the search ourselves...
i = -1;
l = touchList.length;
while (++i < l) {
if (touchList[i].identifier === id) {
return touchList[i];
}
}
}
function changedTouch(e, data) {
var touch = identifiedTouch(e.changedTouches, data.identifier);
// This isn't the touch you're looking for.
if (!touch) { return; }
// Chrome Android (at least) includes touches that have not
// changed in e.changedTouches. That's a bit annoying. Check
// that this touch has changed.
if (touch.pageX === data.pageX && touch.pageY === data.pageY) { return; }
return touch;
}
// Handlers that decide when the first movestart is triggered
function mousedown(e){
// Ignore non-primary buttons
if (!isPrimaryButton(e)) { return; }
// Ignore form and interactive elements
if (isIgnoreTag(e)) { return; }
on(document, mouseevents.move, mousemove, e);
on(document, mouseevents.cancel, mouseend, e);
}
function mousemove(e, data){
checkThreshold(e, data, e, removeMouse);
}
function mouseend(e, data) {
removeMouse();
}
function removeMouse() {
off(document, mouseevents.move, mousemove);
off(document, mouseevents.cancel, mouseend);
}
function touchstart(e) {
// Don't get in the way of interaction with form elements
if (ignoreTags[e.target.tagName.toLowerCase()]) { return; }
var touch = e.changedTouches[0];
// iOS live updates the touch objects whereas Android gives us copies.
// That means we can't trust the touchstart object to stay the same,
// so we must copy the data. This object acts as a template for
// movestart, move and moveend event objects.
var data = {
target: touch.target,
pageX: touch.pageX,
pageY: touch.pageY,
identifier: touch.identifier,
// The only way to make handlers individually unbindable is by
// making them unique.
touchmove: function(e, data) { touchmove(e, data); },
touchend: function(e, data) { touchend(e, data); }
};
on(document, touchevents.move, data.touchmove, data);
on(document, touchevents.cancel, data.touchend, data);
}
function touchmove(e, data) {
var touch = changedTouch(e, data);
if (!touch) { return; }
checkThreshold(e, data, touch, removeTouch);
}
function touchend(e, data) {
var touch = identifiedTouch(e.changedTouches, data.identifier);
if (!touch) { return; }
removeTouch(data);
}
function removeTouch(data) {
off(document, touchevents.move, data.touchmove);
off(document, touchevents.cancel, data.touchend);
}
function checkThreshold(e, data, touch, fn) {
var distX = touch.pageX - data.pageX;
var distY = touch.pageY - data.pageY;
// Do nothing if the threshold has not been crossed.
if ((distX * distX) + (distY * distY) < (threshold * threshold)) { return; }
triggerStart(e, data, touch, distX, distY, fn);
}
function triggerStart(e, data, touch, distX, distY, fn) {
var touches = e.targetTouches;
var time = e.timeStamp - data.timeStamp;
// Create a movestart object with some special properties that
// are passed only to the movestart handlers.
var template = {
altKey: e.altKey,
ctrlKey: e.ctrlKey,
shiftKey: e.shiftKey,
startX: data.pageX,
startY: data.pageY,
distX: distX,
distY: distY,
deltaX: distX,
deltaY: distY,
pageX: touch.pageX,
pageY: touch.pageY,
velocityX: distX / time,
velocityY: distY / time,
identifier: data.identifier,
targetTouches: touches,
finger: touches ? touches.length : 1,
enableMove: function() {
this.moveEnabled = true;
this.enableMove = noop;
e.preventDefault();
}
};
// Trigger the movestart event.
trigger(data.target, 'movestart', template);
// Unbind handlers that tracked the touch or mouse up till now.
fn(data);
}
// Handlers that control what happens following a movestart
function activeMousemove(e, data) {
var timer = data.timer;
data.touch = e;
data.timeStamp = e.timeStamp;
timer.kick();
}
function activeMouseend(e, data) {
var target = data.target;
var event = data.event;
var timer = data.timer;
removeActiveMouse();
endEvent(target, event, timer, function() {
// Unbind the click suppressor, waiting until after mouseup
// has been handled.
setTimeout(function(){
off(target, 'click', preventDefault);
}, 0);
});
}
function removeActiveMouse() {
off(document, mouseevents.move, activeMousemove);
off(document, mouseevents.end, activeMouseend);
}
function activeTouchmove(e, data) {
var event = data.event;
var timer = data.timer;
var touch = changedTouch(e, event);
if (!touch) { return; }
// Stop the interface from gesturing
e.preventDefault();
event.targetTouches = e.targetTouches;
data.touch = touch;
data.timeStamp = e.timeStamp;
timer.kick();
}
function activeTouchend(e, data) {
var target = data.target;
var event = data.event;
var timer = data.timer;
var touch = identifiedTouch(e.changedTouches, event.identifier);
// This isn't the touch you're looking for.
if (!touch) { return; }
removeActiveTouch(data);
endEvent(target, event, timer);
}
function removeActiveTouch(data) {
off(document, touchevents.move, data.activeTouchmove);
off(document, touchevents.end, data.activeTouchend);
}
// Logic for triggering move and moveend events
function updateEvent(event, touch, timeStamp) {
var time = timeStamp - event.timeStamp;
event.distX = touch.pageX - event.startX;
event.distY = touch.pageY - event.startY;
event.deltaX = touch.pageX - event.pageX;
event.deltaY = touch.pageY - event.pageY;
// Average the velocity of the last few events using a decay
// curve to even out spurious jumps in values.
event.velocityX = 0.3 * event.velocityX + 0.7 * event.deltaX / time;
event.velocityY = 0.3 * event.velocityY + 0.7 * event.deltaY / time;
event.pageX = touch.pageX;
event.pageY = touch.pageY;
}
function endEvent(target, event, timer, fn) {
timer.end(function(){
trigger(target, 'moveend', event);
return fn && fn();
});
}
// Set up the DOM
function movestart(e) {
if (e.defaultPrevented) { return; }
if (!e.moveEnabled) { return; }
var event = {
startX: e.startX,
startY: e.startY,
pageX: e.pageX,
pageY: e.pageY,
distX: e.distX,
distY: e.distY,
deltaX: e.deltaX,
deltaY: e.deltaY,
velocityX: e.velocityX,
velocityY: e.velocityY,
identifier: e.identifier,
targetTouches: e.targetTouches,
finger: e.finger
};
var data = {
target: e.target,
event: event,
timer: new Timer(update),
touch: undefined,
timeStamp: e.timeStamp
};
function update(time) {
updateEvent(event, data.touch, data.timeStamp);
trigger(data.target, 'move', event);
}
if (e.identifier === undefined) {
// We're dealing with a mouse event.
// Stop clicks from propagating during a move
on(e.target, 'click', preventDefault);
on(document, mouseevents.move, activeMousemove, data);
on(document, mouseevents.end, activeMouseend, data);
}
else {
// In order to unbind correct handlers they have to be unique
data.activeTouchmove = function(e, data) { activeTouchmove(e, data); };
data.activeTouchend = function(e, data) { activeTouchend(e, data); };
// We're dealing with a touch.
on(document, touchevents.move, data.activeTouchmove, data);
on(document, touchevents.end, data.activeTouchend, data);
}
}
on(document, 'mousedown', mousedown);
on(document, 'touchstart', touchstart);
on(document, 'movestart', movestart);
// jQuery special events
//
// jQuery event objects are copies of DOM event objects. They need
// a little help copying the move properties across.
if (!window.jQuery) { return; }
var properties = ("startX startY pageX pageY distX distY deltaX deltaY velocityX velocityY").split(' ');
function enableMove1(e) { e.enableMove(); }
function enableMove2(e) { e.enableMove(); }
function enableMove3(e) { e.enableMove(); }
function add(handleObj) {
var handler = handleObj.handler;
handleObj.handler = function(e) {
// Copy move properties across from originalEvent
var i = properties.length;
var property;
while(i--) {
property = properties[i];
e[property] = e.originalEvent[property];
}
handler.apply(this, arguments);
};
}
jQuery.event.special.movestart = {
setup: function() {
// Movestart must be enabled to allow other move events
on(this, 'movestart', enableMove1);
// Do listen to DOM events
return false;
},
teardown: function() {
off(this, 'movestart', enableMove1);
return false;
},
add: add
};
jQuery.event.special.move = {
setup: function() {
on(this, 'movestart', enableMove2);
return false;
},
teardown: function() {
off(this, 'movestart', enableMove2);
return false;
},
add: add
};
jQuery.event.special.moveend = {
setup: function() {
on(this, 'movestart', enableMove3);
return false;
},
teardown: function() {
off(this, 'movestart', enableMove3);
return false;
},
add: add
};
});
@@ -0,0 +1,151 @@
(function($){
$.fn.twentytwenty = function(options) {
var options = $.extend({
default_offset_pct: 0.5,
orientation: 'horizontal',
before_label: 'Before',
after_label: 'After',
no_overlay: false,
move_slider_on_hover: false,
move_with_handle_only: true,
click_to_move: false
}, options);
return this.each(function() {
var sliderPct = options.default_offset_pct;
var container = $(this);
var sliderOrientation = options.orientation;
var beforeDirection = (sliderOrientation === 'vertical') ? 'down' : 'left';
var afterDirection = (sliderOrientation === 'vertical') ? 'up' : 'right';
container.wrap("<div class='twentytwenty-wrapper twentytwenty-" + sliderOrientation + "'></div>");
if(!options.no_overlay) {
container.append("<div class='twentytwenty-overlay'></div>");
var overlay = container.find(".twentytwenty-overlay");
overlay.append("<div class='twentytwenty-before-label' data-content='"+options.before_label+"'></div>");
overlay.append("<div class='twentytwenty-after-label' data-content='"+options.after_label+"'></div>");
}
var beforeImg = container.find("img:first");
var afterImg = container.find("img:last");
container.append("<div class='twentytwenty-handle'></div>");
var slider = container.find(".twentytwenty-handle");
slider.append("<span class='twentytwenty-" + beforeDirection + "-arrow'></span>");
slider.append("<span class='twentytwenty-" + afterDirection + "-arrow'></span>");
container.addClass("twentytwenty-container");
beforeImg.addClass("twentytwenty-before");
afterImg.addClass("twentytwenty-after");
var calcOffset = function(dimensionPct) {
var w = beforeImg.width();
var h = beforeImg.height();
return {
w: w+"px",
h: h+"px",
cw: (dimensionPct*w)+"px",
ch: (dimensionPct*h)+"px"
};
};
var adjustContainer = function(offset) {
if (sliderOrientation === 'vertical') {
beforeImg.css("clip", "rect(0,"+offset.w+","+offset.ch+",0)");
afterImg.css("clip", "rect("+offset.ch+","+offset.w+","+offset.h+",0)");
}
else {
beforeImg.css("clip", "rect(0,"+offset.cw+","+offset.h+",0)");
afterImg.css("clip", "rect(0,"+offset.w+","+offset.h+","+offset.cw+")");
}
container.css("height", offset.h);
};
var adjustSlider = function(pct) {
var offset = calcOffset(pct);
slider.css((sliderOrientation==="vertical") ? "top" : "left", (sliderOrientation==="vertical") ? offset.ch : offset.cw);
adjustContainer(offset);
};
// Return the number specified or the min/max number if it outside the range given.
var minMaxNumber = function(num, min, max) {
return Math.max(min, Math.min(max, num));
};
// Calculate the slider percentage based on the position.
var getSliderPercentage = function(positionX, positionY) {
var sliderPercentage = (sliderOrientation === 'vertical') ?
(positionY-offsetY)/imgHeight :
(positionX-offsetX)/imgWidth;
return minMaxNumber(sliderPercentage, 0, 1);
};
$(window).on("resize.twentytwenty", function(e) {
adjustSlider(sliderPct);
});
var offsetX = 0;
var offsetY = 0;
var imgWidth = 0;
var imgHeight = 0;
var onMoveStart = function(e) {
if (((e.distX > e.distY && e.distX < -e.distY) || (e.distX < e.distY && e.distX > -e.distY)) && sliderOrientation !== 'vertical') {
e.preventDefault();
}
else if (((e.distX < e.distY && e.distX < -e.distY) || (e.distX > e.distY && e.distX > -e.distY)) && sliderOrientation === 'vertical') {
e.preventDefault();
}
container.addClass("active");
offsetX = container.offset().left;
offsetY = container.offset().top;
imgWidth = beforeImg.width();
imgHeight = beforeImg.height();
};
var onMove = function(e) {
if (container.hasClass("active")) {
sliderPct = getSliderPercentage(e.pageX, e.pageY);
adjustSlider(sliderPct);
}
};
var onMoveEnd = function() {
container.removeClass("active");
};
var moveTarget = options.move_with_handle_only ? slider : container;
moveTarget.on("movestart",onMoveStart);
moveTarget.on("move",onMove);
moveTarget.on("moveend",onMoveEnd);
if (options.move_slider_on_hover) {
container.on("mouseenter", onMoveStart);
container.on("mousemove", onMove);
container.on("mouseleave", onMoveEnd);
}
slider.on("touchmove", function(e) {
e.preventDefault();
});
container.find("img").on("mousedown", function(event) {
event.preventDefault();
});
if (options.click_to_move) {
container.on('click', function(e) {
offsetX = container.offset().left;
offsetY = container.offset().top;
imgWidth = beforeImg.width();
imgHeight = beforeImg.height();
sliderPct = getSliderPercentage(e.pageX, e.pageY);
adjustSlider(sliderPct);
});
}
$(window).trigger("resize.twentytwenty");
});
};
})(jQuery);
@@ -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);
});
});
@@ -0,0 +1,175 @@
<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
class CompressX_Custom_Image_Meta
{
public static function check_custom_table()
{
global $wpdb;
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
$table_name = $wpdb->prefix . "compressx_files_opt_meta";
if($wpdb->get_var("SHOW TABLES LIKE '$table_name'") != $table_name)
{
$sql = "CREATE TABLE $table_name (
id int NOT NULL AUTO_INCREMENT,
path text NOT NULL,
type text NOT NULL,
path_hash CHAR(32),
convert_webp_status int,
convert_avif_status int,
error text,
quality text NOT NULL,
og_size int(10) unsigned,
convert_webp_size int(10) unsigned,
convert_avif_size int(10) unsigned,
meta text,
PRIMARY KEY (id),
UNIQUE KEY path_hash (path_hash)
);";
//reference to upgrade.php file
dbDelta( $sql );
}
}
public static function get_custom_image_meta($filename)
{
global $wpdb;
$table_name = $wpdb->prefix . "compressx_files_opt_meta";
$path_hash= md5( $filename );
$results = $wpdb->get_results( $wpdb->prepare("SELECT * FROM $table_name WHERE path_hash=%s",$path_hash), ARRAY_A );
if(empty($results))
{
return false;
}
else
{
return $results[0];
}
}
public static function generate_custom_image_meta($filename,$options)
{
$image_optimize_meta['convert_webp_status']=0;
$image_optimize_meta['convert_avif_status']=0;
$image_optimize_meta['error']="";
$image_optimize_meta['quality']=$options['quality'];
$image_optimize_meta['og_size']=filesize($filename);
$image_optimize_meta['convert_webp_size']=0;
$image_optimize_meta['convert_avif_size']=0;
$image_optimize_meta['path'] = $filename;
$type=pathinfo($filename, PATHINFO_EXTENSION);
$image_optimize_meta['type'] =$type;
$image_optimize_meta['path_hash'] = md5( $filename );
$image_optimize_meta['meta']='';
global $wpdb;
$path_hash= md5( $filename );
$results = $wpdb->get_results($wpdb->prepare("SELECT * FROM {$wpdb->prefix}compressx_files_opt_meta WHERE path_hash =%s",$path_hash),ARRAY_A);
if (empty($results))
{
$wpdb->insert($wpdb->prefix.'compressx_files_opt_meta',$image_optimize_meta);
}
else
{
$where['path']=$filename;
$wpdb->update($wpdb->prefix.'compressx_files_opt_meta',$image_optimize_meta,$where);
}
return $image_optimize_meta;
}
public static function update_custom_image_meta($filename,$image_optimize_meta)
{
global $wpdb;
$path_hash= md5( $filename );
$results = $wpdb->get_results($wpdb->prepare("SELECT * FROM {$wpdb->prefix}compressx_files_opt_meta WHERE path_hash =%s",$path_hash),ARRAY_A);
unset($image_optimize_meta['id']);
unset($image_optimize_meta['path_hash']);
if (empty($results))
{
$wpdb->insert($wpdb->prefix.'compressx_files_opt_meta',$image_optimize_meta);
}
else
{
$where['path_hash']=$path_hash;
$wpdb->update($wpdb->prefix.'compressx_files_opt_meta',$image_optimize_meta,$where);
}
}
public static function get_image_status($path)
{
$status['convert_webp_status']=CompressX_Custom_Image_Meta::is_convert_webp($path);
$status['convert_avif_status']=CompressX_Custom_Image_Meta::is_convert_avif($path);
return $status;
}
public static function is_convert_webp($path)
{
global $wpdb;
$table=$wpdb->prefix.'compressx_files_opt_meta';
$path_hash= md5( $path );
$result=$wpdb->get_results($wpdb->prepare("SELECT * FROM $table WHERE `path_hash`=%s AND `convert_webp_status`=1",$path_hash),ARRAY_N);
if(!empty($result) && sizeof($result)>0)
{
return true;
}
else
{
return false;
}
}
public static function is_convert_avif($path)
{
global $wpdb;
$table=$wpdb->prefix.'compressx_files_opt_meta';
$path_hash= md5( $path );
$result=$wpdb->get_results($wpdb->prepare("SELECT * FROM $table WHERE `path_hash`=%s AND `convert_avif_status`=1",$path_hash),ARRAY_N);
if(!empty($result) && sizeof($result)>0)
{
return true;
}
else
{
return false;
}
}
public static function get_convert_webp_size($path)
{
global $wpdb;
$table=$wpdb->prefix.'compressx_files_opt_meta';
$path_hash= md5( $path );
$result=$wpdb->get_results($wpdb->prepare("SELECT `convert_webp_size` FROM $table WHERE `path_hash`=%s",$path_hash),ARRAY_N);
if(!empty($result) && sizeof($result)>0)
{
return $result[0][0];
}
else
{
return 0;
}
}
public static function get_convert_avif_size($path)
{
global $wpdb;
$table=$wpdb->prefix.'compressx_files_opt_meta';
$path_hash= md5( $path );
$result=$wpdb->get_results( $wpdb->prepare("SELECT `convert_avif_size` FROM $table WHERE `path_hash`=%s",$path_hash),ARRAY_N);
if(!empty($result) && sizeof($result)>0)
{
return $result[0][0];
}
else
{
return 0;
}
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,621 @@
<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
class CompressX_Image_Meta
{
public static function has_image_meta($image_id)
{
if(empty(get_post_meta( $image_id, 'compressx_image_meta', true )))
{
return false;
}
else
{
return true;
}
}
public static function get_image_meta($image_id)
{
return get_post_meta( $image_id, 'compressx_image_meta', true );
}
public static function get_image_meta_value($image_id,$key)
{
$meta=get_post_meta( $image_id, 'compressx_image_meta', true );
if(empty($meta))
{
return false;
}
else
{
if(isset($meta[$key]))
{
return $meta[$key];
}
else
{
return false;
}
}
}
public static function update_images_meta_value($image_id,$key,$value)
{
$image_optimize_meta =self::get_image_meta($image_id);
$image_optimize_meta[$key]=$value;
self::update_images_meta($image_id,$image_optimize_meta);
}
public static function update_image_meta_size($image_id,$size_key,$size_meta)
{
$image_optimize_meta =self::get_image_meta($image_id);
$image_optimize_meta['size'][$size_key]=$size_meta;
self::update_images_meta($image_id,$image_optimize_meta);
}
public static function update_images_meta($image_id,$meta)
{
update_post_meta($image_id,'compressx_image_meta',$meta);
}
public static function generate_images_meta($image_id,$options)
{
$file_path = get_attached_file( $image_id );
$image_optimize_meta=array();
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');
update_post_meta($image_id,'compressx_image_meta_status','pending');
//update_post_meta($image_id,'compressx_image_meta_webp_converted',0);
//update_post_meta($image_id,'compressx_image_meta_avif_converted',0);
//update_post_meta($image_id,'compressx_image_meta_compressed',0);
$image_optimize_meta['status']='pending';
$image_optimize_meta['webp_converted']=0;
$image_optimize_meta['avif_converted']=0;
$image_optimize_meta['compressed']=0;
$image_optimize_meta['resize_status']=0;
$image_optimize_meta['compress_status']=0;
$image_optimize_meta['quality']=$options['quality'];
$image_optimize_meta['og_file_size']=filesize($file_path);
$image_optimize_meta['webp_converted_size']=0;
$image_optimize_meta['avif_converted_size']=0;
$image_optimize_meta['compressed_size']=0;
$meta = wp_get_attachment_metadata( $image_id, true );
if(empty($meta['sizes']))
{
$image_optimize_meta['size']['og']['compress_status']=0;
$image_optimize_meta['size']['og']['convert_webp_status']=0;
$image_optimize_meta['size']['og']['convert_avif_status']=0;
$image_optimize_meta['size']['og']['status']="pending";
$image_optimize_meta['size']['og']['error']="";
$image_optimize_meta['size']['og']['file'] = get_post_meta( $image_id, '_wp_attached_file', true );
}
else
{
$image_optimize_meta['size']['og']['compress_status']=0;
$image_optimize_meta['size']['og']['convert_webp_status']=0;
$image_optimize_meta['size']['og']['convert_avif_status']=0;
$image_optimize_meta['size']['og']['status']="pending";
$image_optimize_meta['size']['og']['error']="";
$image_optimize_meta['size']['og']['file']= get_post_meta( $image_id, '_wp_attached_file', true );
foreach ( $meta['sizes'] as $size_key => $size_data )
{
$image_optimize_meta['size'][$size_key]['compress_status']=0;
$image_optimize_meta['size'][$size_key]['convert_webp_status']=0;
$image_optimize_meta['size'][$size_key]['convert_avif_status']=0;
$image_optimize_meta['size'][$size_key]['status']="pending";
$image_optimize_meta['size'][$size_key]['error']="";
$image_optimize_meta['size'][$size_key]['file']=$size_data['file'];
}
}
//update_post_meta($image_id,'compressx_image_meta_og_file_size',$og_size);
//update_post_meta($image_id,'compressx_image_meta_webp_converted_size',0);
//update_post_meta($image_id,'compressx_image_meta_avif_converted_size',0);
//update_post_meta($image_id,'compressx_image_meta_compressed_size',0);
update_post_meta($image_id,'compressx_image_meta',$image_optimize_meta);
return $image_optimize_meta;
}
public static function delete_image_mete($image_id)
{
delete_post_meta($image_id,'compressx_image_meta');
delete_post_meta($image_id,'compressx_image_progressing');
delete_post_meta($image_id,'compressx_image_meta_status');
//old
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_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');
}
public static function get_image_progressing($image_id)
{
return get_post_meta( $image_id, 'compressx_image_progressing', true );
}
public static function update_image_progressing($image_id)
{
update_post_meta($image_id,'compressx_image_progressing',time());
}
public static function delete_image_progressing($image_id)
{
delete_post_meta($image_id,'compressx_image_progressing');
}
public static function get_image_meta_status($image_id)
{
return get_post_meta( $image_id, 'compressx_image_meta_status', true );
}
public static function update_image_meta_status($image_id,$status)
{
if(self::has_image_meta($image_id))
{
$meta=get_post_meta( $image_id, 'compressx_image_meta', true );
$meta['status']=$status;
update_post_meta($image_id,'compressx_image_meta',$meta);
}
update_post_meta($image_id,'compressx_image_meta_status',$status);
}
public static function get_image_meta_webp_converted($image_id)
{
$meta=get_post_meta( $image_id, 'compressx_image_meta', true );
if(isset($meta['webp_converted']))
{
return $meta['webp_converted'];
}
else
{
$converted=get_post_meta( $image_id, 'compressx_image_meta_webp_converted', true );
if(empty($converted))
{
return 0;
}
else
{
$meta['webp_converted']=$converted;
update_post_meta($image_id,'compressx_image_meta',$meta);
delete_post_meta($image_id,'compressx_image_meta_webp_converted');
return $converted;
}
}
}
public static function get_image_meta_avif_converted($image_id)
{
$meta=get_post_meta( $image_id, 'compressx_image_meta', true );
if(isset($meta['avif_converted']))
{
return $meta['avif_converted'];
}
else
{
$converted=get_post_meta( $image_id, 'compressx_image_meta_avif_converted', true );
if(empty($converted))
{
return 0;
}
else
{
$meta['avif_converted']=$converted;
update_post_meta($image_id,'compressx_image_meta',$meta);
delete_post_meta($image_id,'compressx_image_meta_avif_converted');
return $converted;
}
}
}
public static function get_image_meta_compressed($image_id)
{
$meta=get_post_meta( $image_id, 'compressx_image_meta', true );
if(isset($meta['compressed']))
{
return $meta['compressed'];
}
else
{
$compressed=get_post_meta( $image_id, 'compressx_image_meta_compressed', true );
if(empty($compressed))
{
return 0;
}
else
{
$meta['compressed']=$compressed;
update_post_meta($image_id,'compressx_image_meta',$meta);
delete_post_meta($image_id,'compressx_image_meta_compressed');
return $compressed;
}
}
}
public static function update_image_meta_webp_converted($image_id,$converted)
{
$meta=get_post_meta( $image_id, 'compressx_image_meta', true );
$meta['webp_converted']=$converted;
update_post_meta($image_id,'compressx_image_meta',$meta);
}
public static function update_image_meta_avif_converted($image_id,$converted)
{
$meta=get_post_meta( $image_id, 'compressx_image_meta', true );
$meta['avif_converted']=$converted;
update_post_meta($image_id,'compressx_image_meta',$meta);
}
public static function update_image_meta_compressed($image_id,$compressed)
{
$meta=get_post_meta( $image_id, 'compressx_image_meta', true );
$meta['compressed']=$compressed;
update_post_meta($image_id,'compressx_image_meta',$meta);
}
public static function update_webp_converted_size($image_id,$convert_size)
{
$meta=get_post_meta( $image_id, 'compressx_image_meta', true );
$meta['webp_converted_size']=$convert_size;
update_post_meta($image_id,'compressx_image_meta',$meta);
}
public static function update_avif_converted_size($image_id,$convert_size)
{
$meta=get_post_meta( $image_id, 'compressx_image_meta', true );
$meta['avif_converted_size']=$convert_size;
update_post_meta($image_id,'compressx_image_meta',$meta);
}
public static function update_compressed_size($image_id,$compressed_size)
{
$meta=get_post_meta( $image_id, 'compressx_image_meta', true );
$meta['compressed_size']=$compressed_size;
update_post_meta($image_id,'compressx_image_meta',$meta);
}
public static function update_og_size($image_id,$size)
{
$meta=get_post_meta( $image_id, 'compressx_image_meta', true );
$meta['og_file_size']=$size;
update_post_meta($image_id,'compressx_image_meta',$meta);
}
public static function get_og_size($image_id)
{
$meta=get_post_meta( $image_id, 'compressx_image_meta', true );
if(isset($meta['og_file_size']))
{
return $meta['og_file_size'];
}
else
{
$og_size=get_post_meta( $image_id, 'compressx_image_meta_og_file_size', true );
if(empty($og_size))
{
return 0;
}
else
{
$meta['og_file_size']=$og_size;
update_post_meta($image_id,'compressx_image_meta',$meta);
delete_post_meta($image_id,'compressx_image_meta_og_file_size');
return $og_size;
}
}
}
public static function get_webp_converted_size($image_id)
{
$meta=get_post_meta( $image_id, 'compressx_image_meta', true );
if(isset($meta['webp_converted_size']))
{
return $meta['webp_converted_size'];
}
else
{
$convert_size=get_post_meta( $image_id, 'compressx_image_meta_webp_converted_size', true );
if(empty($convert_size))
{
return 0;
}
else
{
$meta['webp_converted_size']=$convert_size;
update_post_meta($image_id,'compressx_image_meta',$meta);
delete_post_meta($image_id,'compressx_image_meta_webp_converted_size');
return $convert_size;
}
}
}
public static function get_avif_converted_size($image_id)
{
$meta=get_post_meta( $image_id, 'compressx_image_meta', true );
if(isset($meta['avif_converted_size']))
{
return $meta['avif_converted_size'];
}
else
{
$convert_size=get_post_meta( $image_id, 'compressx_image_meta_avif_converted_size', true );
if(empty($convert_size))
{
return 0;
}
else
{
$meta['avif_converted_size']=$convert_size;
update_post_meta($image_id,'compressx_image_meta',$meta);
delete_post_meta($image_id,'compressx_image_meta_avif_converted_size');
return $convert_size;
}
}
}
public static function get_compressed_size($image_id)
{
$meta=get_post_meta( $image_id, 'compressx_image_meta', true );
if(isset($meta['compressed_size']))
{
return $meta['compressed_size'];
}
else
{
$convert_size=get_post_meta( $image_id, 'compressx_image_meta_compressed_size', true );
if(empty($convert_size))
{
return 0;
}
else
{
$meta['compressed_size']=$convert_size;
update_post_meta($image_id,'compressx_image_meta',$meta);
delete_post_meta($image_id,'compressx_image_meta_compressed_size');
return $convert_size;
}
}
}
public static function get_global_stats()
{
$update=get_transient( 'compressx_set_global_stats' );
$stats=CompressX_Options::get_option('compressx_global_stats',array());
if(empty($stats)||empty($update)||!isset($stat['webp_converted_percent']))
{
$stats=array();
$stats['webp_converted_percent']=0;
$stats['avif_converted_percent']=0;
$webp_images_count=CompressX_Image_Method::get_max_webp_image_count();
$avif_images_count=CompressX_Image_Method::get_max_avif_image_count();
$stats['avif_converted']=0;
$stats['webp_converted']=0;
$stats['webp_total']=0;
$stats['avif_total']=0;
$stats['webp_saved']=0;
$stats['avif_saved']=0;
global $wpdb;
$result=$wpdb->get_results( "SELECT DISTINCT `post_id` FROM $wpdb->postmeta WHERE `meta_key`=\"compressx_image_meta_status\" AND `meta_value`=\"optimized\" ",ARRAY_N);
if($result && sizeof($result)>0)
{
foreach ($result as $item)
{
$image_id=$item[0];
wp_cache_delete( $image_id, 'post_meta' );
$og_size=self::get_og_size($image_id);
if($og_size>0)
{
if(self::get_image_meta_webp_converted($image_id))
{
$stats['webp_converted']++;
$webp_size=self::get_webp_converted_size($image_id);
$stats['webp_total']+=$og_size;
$stats['webp_saved']+=$webp_size;
}
if(self::get_image_meta_avif_converted($image_id))
{
$stats['avif_converted']++;
$avif_size=self::get_avif_converted_size($image_id);
$stats['avif_total']+=$og_size;
$stats['avif_saved']+=$avif_size;
}
}
}
}
//
if($webp_images_count>0)
{
$stats['webp_converted_percent'] = ( $stats['webp_converted'] / $webp_images_count ) * 100;
$stats['webp_converted_percent'] = round( $stats['webp_converted_percent'], 2 );
}
else
{
$stats['webp_converted_percent']=0;
}
if($avif_images_count>0)
{
$stats['avif_converted_percent'] = ( $stats['avif_converted'] / $avif_images_count ) * 100;
$stats['avif_converted_percent'] = round( $stats['avif_converted_percent'], 2);
}
if($stats['webp_total']>$stats['webp_saved'])
{
$saved=$stats['webp_total']-$stats['webp_saved'];
$stats['webp_saved_percent'] = ( $saved / $stats['webp_total'] ) * 100;
$stats['webp_saved_percent'] = round( $stats['webp_saved_percent'], 2 );
}
else
{
$stats['webp_saved_percent']=0;
}
if($stats['avif_total']>$stats['avif_saved'])
{
$saved=$stats['avif_total']-$stats['avif_saved'];
$stats['avif_saved_percent'] = ($saved / $stats['avif_total'] ) * 100;
$stats['avif_saved_percent'] = round( $stats['avif_saved_percent'], 2 );
}
else
{
$stats['avif_saved_percent'] = 0;
}
delete_transient('compressx_set_global_stats');
CompressX_Options::update_option('compressx_global_stats',$stats);
return $stats;
}
else
{
return $stats;
}
}
public static function get_global_stats_ex()
{
$update=get_transient( 'compressx_set_global_stats' );
$stats=CompressX_Options::get_option('compressx_global_stats_ex',array());
if(empty($stats)||empty($update)||!isset($stat['converted_percent']))
{
$stats=array();
$stats['converted_percent']=0;
//$webp_images_count=CompressX_Image_Method::get_max_webp_image_count();
$images_count=CompressX_Image_Method::get_max_image_count();
global $wpdb;
$result=$wpdb->get_results( "SELECT DISTINCT `post_id` FROM $wpdb->postmeta WHERE `meta_key`=\"compressx_image_meta_status\" AND `meta_value`=\"optimized\" ",ARRAY_N);
if($result && sizeof($result)>0)
{
$converted_images=sizeof($result);
}
else
{
$converted_images=0;
}
//
if($images_count>0)
{
$stats['converted_percent'] = ($converted_images / $images_count ) * 100;
$stats['converted_percent'] = round( $stats['converted_percent'], 2 );
}
else
{
$stats['converted_percent']=0;
}
delete_transient('compressx_set_global_stats');
CompressX_Options::update_option('compressx_global_stats_ex',$stats);
return $stats;
}
else
{
return $stats;
}
}
public static function get_failed_images_count()
{
global $wpdb;
$result=$wpdb->get_results( "SELECT COUNT(*) FROM $wpdb->postmeta WHERE meta_key='compressx_image_meta_status' AND meta_value = 'failed'",ARRAY_N);
if($result && sizeof($result)>0)
{
$count = $result[0][0];
if(is_null($count))
{
return 0;
}
else
{
return $count;
}
}
return 0;
}
public static function is_image_optimized($image_id)
{
if(self::get_image_meta_status($image_id)==='optimized')
{
return true;
}
else
{
return false;
}
}
public static function is_webp_image($image_id)
{
$file_path = get_attached_file($image_id);
$type=pathinfo($file_path, PATHINFO_EXTENSION);
if($type=='webp')
{
return true;
}
else
{
return false;
}
}
public static function is_avif_image($image_id)
{
$file_path = get_attached_file($image_id);
$type=pathinfo($file_path, PATHINFO_EXTENSION);
if($type=='avif')
{
return true;
}
else
{
return false;
}
}
public static function update_image_failed($image_id,$error)
{
$image_optimize_meta=get_post_meta( $image_id, 'compressx_image_meta', true );
$image_optimize_meta['status']='failed';
$image_optimize_meta['size']['og']['status']='failed';
$image_optimize_meta['size']['og']['error']=$error;
self::update_image_meta_status($image_id,'failed');
self::update_images_meta($image_id,$image_optimize_meta);
}
}
@@ -0,0 +1,605 @@
<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
class CompressX_Image_Method
{
public static function get_max_image_count()
{
global $wpdb;
$supported_mime_types = array(
"image/jpg",
"image/jpeg",
"image/png",
"image/webp",
"image/avif");
$args = $supported_mime_types;
$result=$wpdb->get_results($wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->posts WHERE post_type = 'attachment' AND post_mime_type IN (%s,%s,%s,%s,%s)", $args ),ARRAY_N);
if($result && sizeof($result)>0)
{
return $result[0][0];
}
else
{
return 0;
}
}
public static function get_convert_to_webp()
{
$converter_method=CompressX_Options::get_option('compressx_converter_method',false);
if(empty($converter_method))
{
$converter_method=CompressX_Options::set_default_compress_server();
}
$convert_to_webp=CompressX_Options::get_option('compressx_output_format_webp','not init');
if($convert_to_webp=='not init')
{
$convert_to_webp=CompressX_Options::set_default_output_format_webp();
}
if($converter_method=='gd')
{
if($convert_to_webp&&self::is_support_gd_webp())
{
return true;
}
else
{
return false;
}
}
else
{
if($convert_to_webp&&self::is_support_imagick_webp())
{
return true;
}
else
{
return false;
}
}
}
public static function get_convert_to_avif()
{
$converter_method=CompressX_Options::get_option('compressx_converter_method',false);
if(empty($converter_method))
{
$converter_method=CompressX_Options::set_default_compress_server();
}
$convert_to_avif=CompressX_Options::get_option('compressx_output_format_avif','not init');
if($convert_to_avif=='not init')
{
$convert_to_avif=CompressX_Options::set_default_output_format_avif();
}
if($converter_method=='gd')
{
if($convert_to_avif&&self::is_support_gd_avif())
{
return true;
}
else
{
return false;
}
}
else
{
if($convert_to_avif&&self::is_support_imagick_avif())
{
return true;
}
else
{
return false;
}
}
}
public static function get_compress_to_webp()
{
$converter_method=CompressX_Options::get_option('compressx_converter_method',false);
if(empty($converter_method))
{
$converter_method=CompressX_Options::set_default_compress_server();
}
$convert_to_webp=CompressX_Options::get_option('compressx_output_format_webp','not init');
if($convert_to_webp=='not init')
{
$convert_to_webp=CompressX_Options::set_default_output_format_webp();
}
if($converter_method=='gd')
{
if($convert_to_webp&&self::is_support_gd_webp())
{
return true;
}
else
{
return false;
}
}
else
{
if($convert_to_webp&&self::is_support_imagick_webp())
{
return true;
}
else
{
return false;
}
}
}
public static function get_compress_to_avif()
{
$converter_method=CompressX_Options::get_option('compressx_converter_method',false);
if(empty($converter_method))
{
$converter_method=CompressX_Options::set_default_compress_server();
}
$convert_to_avif=CompressX_Options::get_option('compressx_output_format_avif','not init');
if($convert_to_avif=='not init')
{
$convert_to_avif=CompressX_Options::set_default_output_format_avif();
}
if($converter_method=='gd')
{
if($convert_to_avif&&self::is_support_gd_avif())
{
return true;
}
else
{
return false;
}
}
else
{
if($convert_to_avif&&self::is_support_imagick_avif())
{
return true;
}
else
{
return false;
}
}
}
public static function get_converter_method()
{
$converter_method=CompressX_Options::get_option('compressx_converter_method',false);
if(empty($converter_method))
{
$converter_method=CompressX_Options::set_default_compress_server();
}
return $converter_method;
}
public static function get_max_webp_image_count()
{
global $wpdb;
$supported_mime_types = array(
"image/jpg",
"image/jpeg",
"image/png");
//$supported_mime_types=apply_filters('compressx_supported_mime_types',$supported_mime_types);
$result=$wpdb->get_results( $wpdb->prepare("SELECT COUNT(*) FROM $wpdb->posts WHERE post_type = 'attachment' AND post_mime_type IN (%s,%s,%s) ",$supported_mime_types),ARRAY_N);
if($result && sizeof($result)>0)
{
return $result[0][0];
}
else
{
return 0;
}
}
public static function get_max_avif_image_count()
{
global $wpdb;
$supported_mime_types = array(
"image/jpg",
"image/jpeg",
"image/png",
"image/webp");
//$supported_mime_types=apply_filters('compressx_supported_mime_types',$supported_mime_types);
$result=$wpdb->get_results($wpdb->prepare("SELECT COUNT(*) FROM $wpdb->posts WHERE post_type = 'attachment' AND post_mime_type IN (%s,%s,%s,%s) ",$supported_mime_types),ARRAY_N);
if($result && sizeof($result)>0)
{
return $result[0][0];
}
else
{
return 0;
}
}
public static function is_support_webp()
{
if( function_exists( 'gd_info' ) && function_exists( 'imagewebp' ) )
{
return true;
}
if ( extension_loaded( 'imagick' ) && class_exists( '\Imagick' ) )
{
if( \Imagick::queryformats( 'WEBP' ))
{
return true;
}
}
return false;
}
public static function is_support_avif()
{
if( function_exists( 'gd_info' ) )
{
$info=gd_info();
if(isset($info["AVIF Support"])&&$info["AVIF Support"])
{
return true;
}
}
if ( extension_loaded( 'imagick' ) && class_exists( '\Imagick' ) )
{
if( \Imagick::queryformats( 'AVIF' ))
{
return true;
}
}
return false;
}
public static function is_support_gd()
{
if( function_exists( 'gd_info' ) )
{
return true;
}
else
{
return false;
}
}
public static function is_support_gd_webp()
{
if( function_exists( 'gd_info' ) && function_exists( 'imagewebp' ) )
{
return true;
}
else
{
return false;
}
}
public static function is_support_gd_avif()
{
if( function_exists( 'gd_info' ) && function_exists( 'imageavif' ))
{
$info=gd_info();
if(isset($info["AVIF Support"])&&$info["AVIF Support"])
{
return true;
}
}
return false;
}
public static function is_support_imagick()
{
if ( extension_loaded( 'imagick' ) && class_exists( '\Imagick' ) )
{
if( \Imagick::queryformats( 'WEBP' ))
{
return true;
}
}
return false;
}
public static function is_support_imagick_webp()
{
if ( extension_loaded( 'imagick' ) && class_exists( '\Imagick' ) )
{
if( \Imagick::queryformats( 'WEBP' ))
{
return true;
}
}
return false;
}
public static function is_support_imagick_avif()
{
if ( extension_loaded( 'imagick' ) && class_exists( '\Imagick' ) )
{
if( \Imagick::queryformats( 'AVIF' ))
{
return true;
}
}
return false;
}
public static function is_exclude_avif($image_id,$options)
{
$file_path = get_attached_file( $image_id );
$type=pathinfo($file_path, PATHINFO_EXTENSION);
if($options['exclude_png']&&$type== 'png')
{
return true;
}
else if($options['exclude_jpg_avif']&&$type== 'jpg')
{
return true;
}
else
{
return false;
}
}
public static function is_exclude_webp($image_id,$options)
{
$file_path = get_attached_file( $image_id );
$type=pathinfo($file_path, PATHINFO_EXTENSION);
if($options['exclude_png_webp']&&$type== 'png')
{
return true;
}
else if($options['exclude_jpg_webp']&&$type== 'jpg')
{
return true;
}
else
{
return false;
}
}
public static function transfer_path($path)
{
$path = str_replace('\\','/',$path);
$values = explode('/',$path);
return implode(DIRECTORY_SEPARATOR,$values);
}
public static function need_convert_to_webp($post_id,$exclude_regex_folder)
{
if(!CompressX_Image_Meta_V2::get_image_meta_webp_converted($post_id))
{
if(!CompressX_Image_Method::exclude_path($post_id,$exclude_regex_folder))
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
public static function need_convert_to_avif($post_id,$exclude_regex_folder)
{
if(!CompressX_Image_Meta_V2::get_image_meta_avif_converted($post_id))
{
if(!CompressX_Image_Method::exclude_path($post_id,$exclude_regex_folder))
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
public static function exclude_path($post_id,$exclude_regex_folder)
{
if(empty($exclude_regex_folder))
{
return false;
}
$file_path = get_attached_file( $post_id );
$file_path = CompressX_Image_Method::transfer_path($file_path);
if (CompressX_Image_Method::regex_match($exclude_regex_folder, $file_path))
{
return true;
}
else
{
return false;
}
}
public static function regex_match($regex_array,$string)
{
if(empty($regex_array))
{
return false;
}
foreach ($regex_array as $regex)
{
if(preg_match($regex,$string))
{
return true;
}
}
return false;
}
public static function get_opt_folder_size()
{
try
{
$compressx_path=WP_CONTENT_DIR."/compressx-nextgen/uploads";
$bytestotal = 0;
$path = realpath($compressx_path);
if($path!==false && $path!='' && file_exists($path))
{
foreach(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS)) as $object){
$bytestotal += $object->getSize();
}
}
return $bytestotal;
}
catch (Exception $e)
{
return 0;
}
}
public static function supported_mime_types_ex()
{
$supported_mime_types = array(
"image/jpg",
"image/jpeg",
"image/png",
"image/webp",
"image/avif");
$supported_mime_types=apply_filters('compressx_supported_mime_types',$supported_mime_types);
return $supported_mime_types;
}
public static function delete_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=self::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_transient('compressx_set_global_stats');
CompressX_Image_Meta_V2::delete_image_meta($image_id);
}
public static function get_output_path($og_path)
{
$compressx_path=WP_CONTENT_DIR."/compressx-nextgen/uploads";
if(is_multisite())
{
$tmp_id=get_current_blog_id();
$main_site_id = get_main_site_id();
switch_to_blog($main_site_id);
$upload_dir = wp_get_upload_dir();
switch_to_blog($tmp_id);
}
else
{
$upload_dir = wp_get_upload_dir();
}
$upload_root=self::transfer_path($upload_dir['basedir']);
$attachment_dir=dirname($og_path);
$attachment_dir=self::transfer_path($attachment_dir);
$sub_dir=str_replace($upload_root,'',$attachment_dir);
$sub_dir=untrailingslashit($sub_dir);
$sub_dir=ltrim( $sub_dir, '/\\' );
$real_path=$compressx_path.'/'.$sub_dir;
if(!file_exists($real_path))
{
wp_mkdir_p($real_path);
}
return $real_path.'/'.basename($og_path);
}
//exclude_path_ex
public static function exclude_path_ex($file_path,$exclude_regex_folder)
{
if(empty($exclude_regex_folder))
{
return false;
}
$file_path = CompressX_Image_Method::transfer_path($file_path);
if (CompressX_Image_Method::regex_match($exclude_regex_folder, $file_path))
{
return true;
}
else
{
return false;
}
}
}
File diff suppressed because it is too large Load Diff
+219
View File
@@ -0,0 +1,219 @@
=== CompressX — AVIF & WebP Converter, Media Replacement ===
Contributors: compressxio
Tags: convert WebP, convert AVIF, WebP, AVIF, optimization
Requires at least: 5.8
Tested up to: 7.1.3
Requires PHP: 7.0
Stable tag: 0.9.40
License: GPLv3 or later
License URI: https://www.gnu.org/licenses/gpl-3.0.en.html
AVIF & WebP converter with built-in media replacement for local image optimization.
== Description ==
CompressX is a free, lightweight WebP & AVIF conversion and media replacement plugin for WordPress. It allows you to easily convert JPG and PNG images to WebP and AVIF formats, compress WebP and AVIF images, and replace media files without changing their URLs or attachment IDs. All AVIF and WebP conversions are performed locally on your web server.
== Core Features ==
= 1. Convert AVIF & Compress AVIF =
Convert jpg, png, and WebP images on your WordPress website to AVIF format, and compress AVIF images according to the compression level you set.
If the original image is already in AVIF format which is supported since WordPress 6.5, the original AVIF image will only be compressed.
= 2. Convert WebP & Compress WebP =
Convert jpg, png images on your WordPress website to WebP format, and compress WebP images according to the compression level you set.
If the original image is already in WebP format which is supported since WordPress 5.8, the original WebP image will only be compressed.
= 3. Media Replacement & Auto Re-Optimization =
Safely replace an existing media file without changing its URL or attachment ID. When a new image is uploaded as a replacement, the system automatically regenerates thumbnails, applies your configured format conversion and compression rules, resizes where needed, and re-optimizes the file.
= 4. Exclude Folders =
Select specific folders in your media library and prevent images inside them from being processed.
= 5. Custom Folders =
Select folders that are in the wp-content folder but outside the Uploads (media library) and process images inside them.
= 6. Auto-Process New Images =
Automatically convert new images uploaded to a WordPress website to WebP/AVIF format and compress WebP/AVIF images upon upload.
= 7. Auto-Remove Large Images =
Automatically remove converted AVIF/WebP images when they are larger than original images.
= 8. Restore Original Images =
Your images will be reverted to their original state and all AVIF/WebP images and data in the database generated by CompressX will be removed when CompressX is uninstalled.
== Minimum Requirements to use CompressX ==
* Character Encoding UTF-8
* PHP version 7.0
* MySQL version 4.1
* WordPress 5.8
== Screenshots ==
1. Converting PNG/JPG images to WebP
2. Converting PNG/JPG images to AVIF
3. Compressing WebP images
4. Compressing AVIF images
== Installation ==
= Install CompressX =
1.Go to your sites admin dashboard.
2.Navigate to Plugins Menu and search for CompressX.
3.Find CompressX and click Install Now.
4. Click Activate.
== External Services ==
This plugin optionally connects to the [Cloudflare API](https://api.cloudflare.com/) to purge your CDN cache. It sends the Cloudflare Zone ID, account email, and Global API Key whenever the "Purge Cloudflare Cache" button is clicked or automatically upon optimization completion (if enabled in settings). This service is provided by Cloudflare, Inc: [Terms of Service](https://www.cloudflare.com/terms/), [Privacy Policy](https://www.cloudflare.com/privacypolicy/).
== Frequently Asked Questions ==
= What does CompressX do? =
CompressX converts JPG/PNG images on your WordPress website to WebP and AVIF formats, compress WebP and AVIF images locally, and replace existing medias for free!
= Does CompressX convert AVIF? Is it a free feature? =
Yes, CompressX supports AVIF conversion and compression, the AVIF conversion and compression feature is completely free.
= Does CompressX convert WebP? Is it a free feature? =
Yes, CompressX supports WebP conversion and compression, the WebP conversion and compression feature is completely free.
= Do you provide support for CompressX? Where? =
Yes, absolutely. Whenever you need help, start a thread on the support forum or [contact us](https://compressx.io/contact-us/).
= Do you have any get-started guides/docs? =
Yes, we do. Here is a [tutorial](https://compressx.io/docs/compressx-overview/) for you to quickly get started with CompressX.
== Changelog ==
= 0.9.40 =
- Added the 'Maximum images per scan request' option to improve scanning performance.
= 0.9.39 =
- Added an option to control the number of images processed in each scan batch.
- Improved scan efficiency for websites with a large number of images.
= 0.9.38 =
- Successfully tested with WordPress 7.0.
= 0.9.37 =
- Improved localization support to align with the updated plugin interface.
= 0.9.36 =
- Fixed some bugs in the plugin code.
- Optimized the plugin code.
- Refined the plugin readme file.
= 0.9.35 =
- Added a feature of replacing an image in your media library by uploading a new image.
- Fixed some bugs in the plugin code.
- Optimized plugin UI.
= 0.9.34 =
- Added a custom database table for saving CompressX image data.
- Fixed some bugs in the plugin code.
- Optimized plugin UI and core code.
= 0.9.33 =
- Major update to the plugin user interface.
- Fixed some bugs in the plugin code.
- Successfully tested with PHP 8.5.
- Successfully tested with WordPress 6.9.
= 0.9.32 =
- Fixed: Manual image conversions from media library would fail.
= 0.9.31 =
- Fixed some bugs in the plugin code.
= 0.9.30 =
- Fixed: Custom compression level settings could not be saved.
= 0.9.29 =
- Added a compatible rewrite rule option for broader server compatibility.
- Optimized the efficiency of batch scanning, especially for sites with many images.
= 0.9.28 =
- Fixed: Incorrect image statistics calculation.
- Added support for image rotation during WebP/AVIF conversion.
- Fixed: Image resizing data could not be updated in the database.
= 0.9.27 =
- Refactored the plugin code and optimized the code structure.
- Optimized and reduced CompressX entries in postmeta table.
- Fixed some UI bugs.
= 0.9.26 =
- Expanded compatibility to support a wider range of server configurations.
- Added a clear warning about potential AVIF conversion timeouts when using ImageMagick 6.x.
- Enhanced compatibility of .htaccess rewrite rules to accommodate diverse server settings.
- Optimized bulk image processing to skip stuck images.
- Optimized the plugin code.
= 0.9.25 =
- Fixed a UI bug.
- Optimized the plugin code.
= 0.9.24 =
- Fixed: CDN integration settings could not be saved correctly.
- Optimized the plugin code and UI.
= 0.9.23 =
- Added support for conversion of Elementor custom thumbnails size.
- Added support for conversion in media library grid view and image edit page.
= 0.9.22 =
- Fixed: Picture tag did not take all sizes in srcset.
- Fixed: Conversion would fail if image's MIME type did not match the MIME type saved in posts.
- Optimized the plugin UI.
= 0.9.21 =
- Added an option of 'Do not convert PNG to WebP'.
- Added an option to automatically purge cache after manual conversion from media library.
- Optimized the plugin UI.
- Canceled support for grid view of media library. Only list view is supported.
= 0.9.20 =
- Optimized process of scanning a large number of images.
- Successfully tested with WordPress 6.7.
= 0.9.19 =
- Optimized image scanning method in the bulk processing workflow.
= 0.9.18 =
- Fixed: Default compression level for bulk processing was wrongly set to lossless.
= 0.9.17 =
- Added an option of 'picture tag' to load WebP and AVIF images.
- Optimized the plugin UI.
- Optimized the plugin code.
= 0.9.16 =
- Fixed a UI bug that would appear when folders that do not exist were added to exclusion rules.
- Optimized the plugin code.
= 0.9.15 =
- Fixed some bugs in the plugin code.
- Optimized the plugin code.
= 0.9.14 =
- Added support for multilanguage translation.
- Added an option to exclude PNG images from conversion.
- Added an option to delete cache control settings from .htaccess file.
- Fixed: WebP images could not be displayed as AVIF after conversion.
- Optimized the plugin UI.
- Optimized the plugin code.
= 0.9.13 =
- Added support for Cloudflare CDN.
- Fixed: Settings of 'auto-resizing large images' could not take effect.
- Optimized the plugin code.
= 0.9.12 =
- Fixed a UI bug where WebP option could not be selected in some cases.
- Fixed: Images would be repeatedly processed when EXIF removal option was enabled.
- Optimized the plugin code.
= 0.9.11 =
- Added an option to delete converted images.
- Optimized the plugin UI.
- Fixed some bugs in the plugin code.
- Optimized the plugin code.
= 0.9.10 =
- Fixed: Image quality would not be changed after AVIF conversion with Imagick.
- Fixed: Incorrect compression quality with Imagick and Lossless compression level.
- Fixed: Custom compression level would not take effect.
- Optimized the plugin code.
= 0.9.9 =
- Added an option to set how many images to process per ajax request.
- Fixed some bugs in the plugin code.
- Optimized the plugin code.
= 0.9.8 =
- Added a Debug section.
- Fixed some bugs in the plugin code.
- Optimized the plugin code.
= 0.9.7 =
- Fixed the path error of rewrite rules that appeared in some environments.
- Fixed: Some settings could not take effect.
- Fixed some bugs in the plugin code.
- Optimized the plugin code.
= 0.9.6 =
- Fixed a bug where AVIF output format could not be enabled.
- Fixed some bugs in the plugin code.
- Optimized the plugin code.
= 0.9.5 =
- Fixed a bug in the plugin code.
- Optimized the plugin code.
= 0.9.4 =
- Fixed a critical bug in the plugin code.
- Optimized the plugin code.
= 0.9.3 =
- Fixed a critical bug in the plugin code.
- Optimized the plugin code.
= 0.9.2 =
- Added a check for the case where multiple image optimization plugins are activated.
- Fixed some bugs in the plugin code.
- Optimized the plugin code.
- Successfully tested with WordPress 6.6.
= 0.9.1 =
- Initial release. Hello world!
== Upgrade Notice ==
Latest version 0.9.40:
= 0.9.40 =
- Added the 'Maximum images per scan request' option to improve scanning performance.
@@ -0,0 +1,26 @@
<?php
// If uninstall not called from WordPress, then exit.
if ( ! defined( 'WP_UNINSTALL_PLUGIN' ) ) {
exit;
}
delete_option("compressx_general_settings");
delete_option("compressx_auto_optimize");
delete_option("compressx_output_format_webp");
delete_option("compressx_output_format_avif");
delete_option("compressx_converter_method");
delete_option("compressx_quality");
delete_option("compressx_custom_includes");
delete_option("compressx_custom_image_opt_task");
delete_option("compressx_need_optimized_custom_images");
delete_option("compressx_image_opt_task");
delete_option("compressx_global_stats");
delete_option("compressx_media_excludes");
delete_option("compressx_hide_notice");
delete_option("compressx_need_optimized_images");
delete_option("compressx_dissmiss_conflict_notice");
delete_option('compressx_rating_dismiss');
delete_option('compressx_show_review');
delete_option('compressx_hide_big_update');
delete_option('compressx_media_replace');