first
53
wp-content/plugins/ewww-image-optimizer/.travis.yml
Normal file
@ -0,0 +1,53 @@
|
||||
os: linux
|
||||
|
||||
dist: bionic
|
||||
|
||||
language: php
|
||||
|
||||
notifications:
|
||||
email:
|
||||
on_success: never
|
||||
on_failure: change
|
||||
|
||||
branches:
|
||||
only:
|
||||
- master
|
||||
|
||||
php:
|
||||
- 7.3
|
||||
- 7.4
|
||||
- 8.0
|
||||
- 8.1
|
||||
- 8.2
|
||||
|
||||
services:
|
||||
- mysql
|
||||
|
||||
env:
|
||||
- WP_VERSION=latest WP_MULTISITE=0
|
||||
|
||||
jobs:
|
||||
include:
|
||||
- php: 7.3
|
||||
env: WP_VERSION=latest WP_MULTISITE=1 WPSNIFF=1
|
||||
- php: 8.2
|
||||
env: WP_VERSION=latest WP_MULTISITE=1 WPSNIFF=1
|
||||
- php: 8.0
|
||||
env: WP_VERSION=6.0 WP_MULTISITE=0
|
||||
|
||||
before_script:
|
||||
- export PATH="$HOME/.config/composer/vendor/bin:$PATH"
|
||||
- phpenv config-rm xdebug.ini
|
||||
- bash bin/install-wp-tests.sh wordpress_test root '' localhost $WP_VERSION
|
||||
- composer global require --dev yoast/phpunit-polyfills:"^1.0"
|
||||
- |
|
||||
if [[ "$WPSNIFF" == "1" ]]; then
|
||||
composer global config allow-plugins.dealerdirect/phpcodesniffer-composer-installer true
|
||||
composer global require --dev wp-coding-standards/wpcs phpcompatibility/phpcompatibility-wp
|
||||
phpcs -i
|
||||
fi
|
||||
- |
|
||||
|
||||
script:
|
||||
- if [[ "$WPSNIFF" == "1" ]]; then phpcs --standard=phpcs.ruleset.xml --extensions=php .; fi
|
||||
- phpunit
|
1811
wp-content/plugins/ewww-image-optimizer/aux-optimize.php
Normal file
127
wp-content/plugins/ewww-image-optimizer/bin/install-wp-tests.sh
Normal file
@ -0,0 +1,127 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
if [ $# -lt 3 ]; then
|
||||
echo "usage: $0 <db-name> <db-user> <db-pass> [db-host] [wp-version] [skip-database-creation]"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
DB_NAME=$1
|
||||
DB_USER=$2
|
||||
DB_PASS=$3
|
||||
DB_HOST=${4-localhost}
|
||||
WP_VERSION=${5-latest}
|
||||
SKIP_DB_CREATE=${6-false}
|
||||
|
||||
WP_TESTS_DIR=${WP_TESTS_DIR-/tmp/wordpress-tests-lib}
|
||||
WP_CORE_DIR=${WP_CORE_DIR-/tmp/wordpress/}
|
||||
|
||||
download() {
|
||||
if [ `which curl` ]; then
|
||||
curl -s "$1" > "$2";
|
||||
elif [ `which wget` ]; then
|
||||
wget -nv -O "$2" "$1"
|
||||
fi
|
||||
}
|
||||
|
||||
if [[ $WP_VERSION =~ [0-9]+\.[0-9]+(\.[0-9]+)? ]]; then
|
||||
WP_TESTS_TAG="tags/$WP_VERSION"
|
||||
elif [[ $WP_VERSION == 'nightly' || $WP_VERSION == 'trunk' ]]; then
|
||||
WP_TESTS_TAG="trunk"
|
||||
else
|
||||
# http serves a single offer, whereas https serves multiple. we only want one
|
||||
download http://api.wordpress.org/core/version-check/1.7/ /tmp/wp-latest.json
|
||||
grep '[0-9]+\.[0-9]+(\.[0-9]+)?' /tmp/wp-latest.json
|
||||
LATEST_VERSION=$(grep -o '"version":"[^"]*' /tmp/wp-latest.json | sed 's/"version":"//')
|
||||
if [[ -z "$LATEST_VERSION" ]]; then
|
||||
echo "Latest WordPress version could not be found"
|
||||
exit 1
|
||||
fi
|
||||
WP_TESTS_TAG="tags/$LATEST_VERSION"
|
||||
fi
|
||||
|
||||
set -ex
|
||||
|
||||
install_wp() {
|
||||
|
||||
if [ -d $WP_CORE_DIR ]; then
|
||||
return;
|
||||
fi
|
||||
|
||||
mkdir -p $WP_CORE_DIR
|
||||
|
||||
if [[ $WP_VERSION == 'nightly' || $WP_VERSION == 'trunk' ]]; then
|
||||
mkdir -p /tmp/wordpress-nightly
|
||||
download https://wordpress.org/nightly-builds/wordpress-latest.zip /tmp/wordpress-nightly/wordpress-nightly.zip
|
||||
unzip -q /tmp/wordpress-nightly/wordpress-nightly.zip -d /tmp/wordpress-nightly/
|
||||
mv /tmp/wordpress-nightly/wordpress/* $WP_CORE_DIR
|
||||
else
|
||||
if [ $WP_VERSION == 'latest' ]; then
|
||||
local ARCHIVE_NAME='latest'
|
||||
else
|
||||
local ARCHIVE_NAME="wordpress-$WP_VERSION"
|
||||
fi
|
||||
download https://wordpress.org/${ARCHIVE_NAME}.tar.gz /tmp/wordpress.tar.gz
|
||||
tar --strip-components=1 -zxmf /tmp/wordpress.tar.gz -C $WP_CORE_DIR
|
||||
fi
|
||||
|
||||
download https://raw.github.com/markoheijnen/wp-mysqli/master/db.php $WP_CORE_DIR/wp-content/db.php
|
||||
}
|
||||
|
||||
install_test_suite() {
|
||||
# portable in-place argument for both GNU sed and Mac OSX sed
|
||||
if [[ $(uname -s) == 'Darwin' ]]; then
|
||||
local ioption='-i .bak'
|
||||
else
|
||||
local ioption='-i'
|
||||
fi
|
||||
|
||||
# set up testing suite if it doesn't yet exist
|
||||
if [ ! -d $WP_TESTS_DIR ]; then
|
||||
# set up testing suite
|
||||
mkdir -p $WP_TESTS_DIR
|
||||
svn co --quiet https://develop.svn.wordpress.org/${WP_TESTS_TAG}/tests/phpunit/includes/ $WP_TESTS_DIR/includes
|
||||
svn co --quiet https://develop.svn.wordpress.org/${WP_TESTS_TAG}/tests/phpunit/data/ $WP_TESTS_DIR/data
|
||||
fi
|
||||
|
||||
if [ ! -f wp-tests-config.php ]; then
|
||||
download https://develop.svn.wordpress.org/${WP_TESTS_TAG}/wp-tests-config-sample.php "$WP_TESTS_DIR"/wp-tests-config.php
|
||||
# remove all forward slashes in the end
|
||||
WP_CORE_DIR=$(echo $WP_CORE_DIR | sed "s:/\+$::")
|
||||
sed $ioption "s:dirname( __FILE__ ) . '/src/':'$WP_CORE_DIR/':" "$WP_TESTS_DIR"/wp-tests-config.php
|
||||
sed $ioption "s/youremptytestdbnamehere/$DB_NAME/" "$WP_TESTS_DIR"/wp-tests-config.php
|
||||
sed $ioption "s/yourusernamehere/$DB_USER/" "$WP_TESTS_DIR"/wp-tests-config.php
|
||||
sed $ioption "s/yourpasswordhere/$DB_PASS/" "$WP_TESTS_DIR"/wp-tests-config.php
|
||||
sed $ioption "s|localhost|${DB_HOST}|" "$WP_TESTS_DIR"/wp-tests-config.php
|
||||
fi
|
||||
|
||||
}
|
||||
|
||||
install_db() {
|
||||
|
||||
if [ ${SKIP_DB_CREATE} = "true" ]; then
|
||||
return 0
|
||||
fi
|
||||
|
||||
# parse DB_HOST for port or socket references
|
||||
local PARTS=(${DB_HOST//\:/ })
|
||||
local DB_HOSTNAME=${PARTS[0]};
|
||||
local DB_SOCK_OR_PORT=${PARTS[1]};
|
||||
local EXTRA=""
|
||||
|
||||
if ! [ -z $DB_HOSTNAME ] ; then
|
||||
if [ $(echo $DB_SOCK_OR_PORT | grep -e '^[0-9]\{1,\}$') ]; then
|
||||
EXTRA=" --host=$DB_HOSTNAME --port=$DB_SOCK_OR_PORT --protocol=tcp"
|
||||
elif ! [ -z $DB_SOCK_OR_PORT ] ; then
|
||||
EXTRA=" --socket=$DB_SOCK_OR_PORT"
|
||||
elif ! [ -z $DB_HOSTNAME ] ; then
|
||||
EXTRA=" --host=$DB_HOSTNAME --protocol=tcp"
|
||||
fi
|
||||
fi
|
||||
|
||||
# create database
|
||||
mysqladmin create $DB_NAME --user="$DB_USER" --password="$DB_PASS"$EXTRA
|
||||
}
|
||||
|
||||
install_wp
|
||||
install_test_suite
|
||||
install_db
|
BIN
wp-content/plugins/ewww-image-optimizer/binaries/cwebp-fbsd
Normal file
BIN
wp-content/plugins/ewww-image-optimizer/binaries/cwebp-linux
Normal file
BIN
wp-content/plugins/ewww-image-optimizer/binaries/cwebp-mac15
Normal file
BIN
wp-content/plugins/ewww-image-optimizer/binaries/cwebp.exe
Normal file
BIN
wp-content/plugins/ewww-image-optimizer/binaries/gifsicle-fbsd
Normal file
BIN
wp-content/plugins/ewww-image-optimizer/binaries/gifsicle-linux
Normal file
BIN
wp-content/plugins/ewww-image-optimizer/binaries/gifsicle-mac
Normal file
BIN
wp-content/plugins/ewww-image-optimizer/binaries/gifsicle.exe
Normal file
BIN
wp-content/plugins/ewww-image-optimizer/binaries/jpegtran-fbsd
Normal file
BIN
wp-content/plugins/ewww-image-optimizer/binaries/jpegtran-linux
Normal file
BIN
wp-content/plugins/ewww-image-optimizer/binaries/jpegtran-mac
Normal file
BIN
wp-content/plugins/ewww-image-optimizer/binaries/jpegtran.exe
Normal file
BIN
wp-content/plugins/ewww-image-optimizer/binaries/optipng-fbsd
Normal file
BIN
wp-content/plugins/ewww-image-optimizer/binaries/optipng-linux
Normal file
BIN
wp-content/plugins/ewww-image-optimizer/binaries/optipng-mac
Normal file
BIN
wp-content/plugins/ewww-image-optimizer/binaries/optipng.exe
Normal file
BIN
wp-content/plugins/ewww-image-optimizer/binaries/pngquant-fbsd
Normal file
BIN
wp-content/plugins/ewww-image-optimizer/binaries/pngquant-linux
Normal file
BIN
wp-content/plugins/ewww-image-optimizer/binaries/pngquant-mac
Normal file
BIN
wp-content/plugins/ewww-image-optimizer/binaries/pngquant.exe
Normal file
2269
wp-content/plugins/ewww-image-optimizer/bulk.php
Normal file
2105
wp-content/plugins/ewww-image-optimizer/changelog.txt
Normal file
@ -0,0 +1,43 @@
|
||||
<?php
|
||||
/**
|
||||
* Class for Background of Media Library images.
|
||||
*
|
||||
* @link https://ewww.io
|
||||
* @package EWWW_Image_Optimizer
|
||||
*/
|
||||
|
||||
namespace EWWW;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles an async request for validating API keys.
|
||||
*
|
||||
* Allows periodic verification of an API key without slowing down normal operations.
|
||||
*
|
||||
* @see EWWW\Async_Request
|
||||
*/
|
||||
class Async_Key_Verify extends Async_Request {
|
||||
|
||||
/**
|
||||
* The action name used to trigger this class extension.
|
||||
*
|
||||
* @access protected
|
||||
* @var string $action
|
||||
*/
|
||||
protected $action = 'ewwwio_async_key_verify';
|
||||
|
||||
/**
|
||||
* Handles the async key verification request.
|
||||
*
|
||||
* Called via a POST request to verify an API key asynchronously.
|
||||
*/
|
||||
protected function handle() {
|
||||
session_write_close();
|
||||
ewwwio_debug_message( '<b>' . __METHOD__ . '()</b>' );
|
||||
check_ajax_referer( $this->identifier, 'nonce' );
|
||||
ewww_image_optimizer_cloud_verify( ewww_image_optimizer_get_option( 'ewww_image_optimizer_cloud_key' ), false );
|
||||
}
|
||||
}
|
@ -0,0 +1,90 @@
|
||||
<?php
|
||||
/**
|
||||
* Class for async optimization of Media Library images.
|
||||
*
|
||||
* @link https://ewww.io
|
||||
* @package EWWW_Image_Optimizer
|
||||
*/
|
||||
|
||||
namespace EWWW;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles an async request used to optimize a Media Library image.
|
||||
*
|
||||
* Used to optimize a single image, like a resize, retina, or the original upload for a
|
||||
* Media Library attachment. Done in parallel to increase processing capability.
|
||||
*
|
||||
* @see EWWW\Async_Request
|
||||
*/
|
||||
class Async_Media_Optimize extends Async_Request {
|
||||
|
||||
/**
|
||||
* The action name used to trigger this class extension.
|
||||
*
|
||||
* @access protected
|
||||
* @var string $action
|
||||
*/
|
||||
protected $action = 'ewwwio_async_media_optimize';
|
||||
|
||||
/**
|
||||
* Handles the async media image optimization request.
|
||||
*
|
||||
* Called via a POST to optimize an image from a Media Library attachment using parallel optimization.
|
||||
*
|
||||
* @global object $ewww_image Tracks attributes of the image currently being optimized.
|
||||
*/
|
||||
protected function handle() {
|
||||
session_write_close();
|
||||
ewwwio_debug_message( '<b>' . __METHOD__ . '()</b>' );
|
||||
check_ajax_referer( $this->identifier, 'nonce' );
|
||||
global $ewww_force;
|
||||
if ( empty( $_POST['ewwwio_size'] ) ) {
|
||||
$size = '';
|
||||
} else {
|
||||
$size = sanitize_key( $_POST['ewwwio_size'] );
|
||||
}
|
||||
if ( empty( $_POST['ewwwio_attachment_id'] ) ) {
|
||||
$id = 0;
|
||||
} else {
|
||||
$id = (int) $_POST['ewwwio_attachment_id'];
|
||||
}
|
||||
if ( empty( $_POST['ewwwio_id'] ) ) {
|
||||
return;
|
||||
}
|
||||
$ewww_force = ! empty( $_REQUEST['ewww_force'] ) ? true : false;
|
||||
$ewwwio_id = (int) $_POST['ewwwio_id'];
|
||||
global $ewww_image;
|
||||
$file_path = ewww_image_optimizer_find_file_by_id( $ewwwio_id );
|
||||
if ( $file_path && 'full' === $size ) {
|
||||
ewwwio_debug_message( "processing async optimization request for $file_path" );
|
||||
$ewww_image = new EWWW_Image( $id, 'media', $file_path );
|
||||
$ewww_image->resize = 'full';
|
||||
|
||||
list( $file, $msg, $conv, $original ) = ewww_image_optimizer( $file_path, 1, false, false, true );
|
||||
} elseif ( $file_path ) {
|
||||
ewwwio_debug_message( "processing async optimization request for $file_path" );
|
||||
$ewww_image = new EWWW_Image( $id, 'media', $file_path );
|
||||
$ewww_image->resize = ( empty( $size ) ? null : $size );
|
||||
|
||||
list( $file, $msg, $conv, $original ) = ewww_image_optimizer( $file_path );
|
||||
} else {
|
||||
if ( $ewwwio_id && ! $file_path ) {
|
||||
ewwwio_debug_message( "could not find file to process async optimization request for $ewwwio_id" );
|
||||
} else {
|
||||
ewwwio_debug_message( 'ignored async optimization request' );
|
||||
}
|
||||
return;
|
||||
}
|
||||
ewww_image_optimizer_hidpi_optimize( $file_path );
|
||||
ewwwio_debug_message( 'checking for: ' . $file_path . '.processing' );
|
||||
if ( ewwwio_is_file( $file_path . '.processing' ) ) {
|
||||
ewwwio_debug_message( 'removing ' . $file_path . '.processing' );
|
||||
$upload_path = wp_get_upload_dir();
|
||||
ewwwio_delete_file( $file_path . '.processing' );
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,168 @@
|
||||
<?php
|
||||
/**
|
||||
* EWWW Async Request
|
||||
*
|
||||
* @link https://ewww.io
|
||||
* @package EWWW_Image_Optimizer
|
||||
*/
|
||||
|
||||
namespace EWWW;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Abstract EWWW\Async_Request class.
|
||||
*
|
||||
* @abstract
|
||||
*/
|
||||
abstract class Async_Request {
|
||||
|
||||
/**
|
||||
* Prefix
|
||||
*
|
||||
* (default value: 'wp')
|
||||
*
|
||||
* @var string
|
||||
* @access protected
|
||||
*/
|
||||
protected $prefix = 'wp';
|
||||
|
||||
/**
|
||||
* Action
|
||||
*
|
||||
* (default value: 'async_request')
|
||||
*
|
||||
* @var string
|
||||
* @access protected
|
||||
*/
|
||||
protected $action = 'async_request';
|
||||
|
||||
/**
|
||||
* Identifier
|
||||
*
|
||||
* @var mixed
|
||||
* @access protected
|
||||
*/
|
||||
protected $identifier;
|
||||
|
||||
/**
|
||||
* Data
|
||||
*
|
||||
* (default value: array())
|
||||
*
|
||||
* @var array
|
||||
* @access protected
|
||||
*/
|
||||
protected $data = array();
|
||||
|
||||
/**
|
||||
* Initiate new async request
|
||||
*/
|
||||
public function __construct() {
|
||||
$this->identifier = $this->prefix . '_' . $this->action;
|
||||
|
||||
\add_action( 'wp_ajax_' . $this->identifier, array( $this, 'maybe_handle' ) );
|
||||
\add_action( 'wp_ajax_nopriv_' . $this->identifier, array( $this, 'maybe_handle' ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Set data used during the request
|
||||
*
|
||||
* @param array $data Data.
|
||||
*
|
||||
* @return $this
|
||||
*/
|
||||
public function data( $data ) {
|
||||
$this->data = $data;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Dispatch the async request
|
||||
*
|
||||
* @return array|WP_Error
|
||||
*/
|
||||
public function dispatch() {
|
||||
$url = \add_query_arg( $this->get_query_args(), $this->get_query_url() );
|
||||
$args = $this->get_post_args();
|
||||
|
||||
// Close up any loose sessions before we open another request.
|
||||
\session_write_close();
|
||||
return \wp_remote_post( \esc_url_raw( $url ), $args );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get query args
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
protected function get_query_args() {
|
||||
if ( \property_exists( $this, 'query_args' ) ) {
|
||||
return $this->query_args;
|
||||
}
|
||||
|
||||
return array(
|
||||
'action' => $this->identifier,
|
||||
'nonce' => \wp_create_nonce( $this->identifier ),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get query URL
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function get_query_url() {
|
||||
if ( \property_exists( $this, 'query_url' ) ) {
|
||||
return $this->query_url;
|
||||
}
|
||||
|
||||
return \admin_url( 'admin-ajax.php' );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get post args
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
protected function get_post_args() {
|
||||
if ( \property_exists( $this, 'post_args' ) ) {
|
||||
return $this->post_args;
|
||||
}
|
||||
|
||||
return array(
|
||||
'timeout' => 0.01,
|
||||
'blocking' => false,
|
||||
'body' => $this->data,
|
||||
'cookies' => $_COOKIE,
|
||||
'sslverify' => \apply_filters( 'https_local_ssl_verify', false ),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Maybe handle
|
||||
*
|
||||
* Check for correct nonce and pass to handler.
|
||||
*/
|
||||
public function maybe_handle() {
|
||||
// Don't lock up other requests while processing.
|
||||
\session_write_close();
|
||||
|
||||
\check_ajax_referer( $this->identifier, 'nonce' );
|
||||
|
||||
$this->handle();
|
||||
|
||||
die;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle
|
||||
*
|
||||
* Override this method to perform any actions required
|
||||
* during the async request.
|
||||
*/
|
||||
abstract protected function handle();
|
||||
}
|
@ -0,0 +1,41 @@
|
||||
<?php
|
||||
/**
|
||||
* Class for Background of Media Library images.
|
||||
*
|
||||
* @link https://ewww.io
|
||||
* @package EWWW_Image_Optimizer
|
||||
*/
|
||||
|
||||
namespace EWWW;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles an async request to scan for unoptimized images. Subsequent calls will resume from the previous request.
|
||||
*
|
||||
* @see EWWW\Async_Request
|
||||
*/
|
||||
class Async_Scan extends Async_Request {
|
||||
|
||||
/**
|
||||
* The action name used to trigger this class extension.
|
||||
*
|
||||
* @access protected
|
||||
* @var string $action
|
||||
*/
|
||||
protected $action = 'ewwwio_scan_async';
|
||||
|
||||
/**
|
||||
* Handles the async scan request.
|
||||
*/
|
||||
protected function handle() {
|
||||
session_write_close();
|
||||
ewwwio_debug_message( '<b>' . __METHOD__ . '()</b>' );
|
||||
check_ajax_referer( $this->identifier, 'nonce' );
|
||||
global $ewww_scan;
|
||||
$ewww_scan = empty( $_REQUEST['ewww_scan'] ) ? '' : sanitize_key( $_REQUEST['ewww_scan'] );
|
||||
ewww_image_optimizer_aux_images_script( 'ewww-image-optimizer-auto' );
|
||||
}
|
||||
}
|
@ -0,0 +1,43 @@
|
||||
<?php
|
||||
/**
|
||||
* Class for Background of Media Library images.
|
||||
*
|
||||
* @link https://ewww.io
|
||||
* @package EWWW_Image_Optimizer
|
||||
*/
|
||||
|
||||
namespace EWWW;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles a simulated async request used to test async requests for the debugger.
|
||||
*
|
||||
* @see EWWW\Async_Request
|
||||
*/
|
||||
class Async_Test_Optimize extends Async_Request {
|
||||
|
||||
/**
|
||||
* The action name used to trigger this class extension.
|
||||
*
|
||||
* @access protected
|
||||
* @var string $action
|
||||
*/
|
||||
protected $action = 'ewwwio_test_optimize';
|
||||
|
||||
/**
|
||||
* Handles the test async request.
|
||||
*
|
||||
* Called via a POST request to verify that nothing is blocking or altering requests from the server to itself.
|
||||
*/
|
||||
protected function handle() {
|
||||
session_write_close();
|
||||
ewwwio_debug_message( '<b>' . __METHOD__ . '()</b>' );
|
||||
check_ajax_referer( $this->identifier, 'nonce' );
|
||||
if ( empty( $_POST['ewwwio_test_verify'] ) ) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,64 @@
|
||||
<?php
|
||||
/**
|
||||
* Class for Background of Media Library images.
|
||||
*
|
||||
* @link https://ewww.io
|
||||
* @package EWWW_Image_Optimizer
|
||||
*/
|
||||
|
||||
namespace EWWW;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles an async request used to test the viability of using async requests
|
||||
* elsewhere.
|
||||
*
|
||||
* During a plugin update, an async request is sent with a specific string
|
||||
* value to validate that nothing is blocking admin-ajax.php requests from
|
||||
* the server to itself. Once verified, full background/parallel processing
|
||||
* can be used.
|
||||
*
|
||||
* @see EWWW\Async_Request
|
||||
*/
|
||||
class Async_Test_Request extends Async_Request {
|
||||
|
||||
/**
|
||||
* The action name used to trigger this class extension.
|
||||
*
|
||||
* @access protected
|
||||
* @var string $action
|
||||
*/
|
||||
protected $action = 'ewwwio_test_async';
|
||||
|
||||
/**
|
||||
* Handles the test async request.
|
||||
*
|
||||
* Called via a POST request to verify that nothing is blocking or altering requests from the server to itself.
|
||||
*/
|
||||
protected function handle() {
|
||||
session_write_close();
|
||||
ewwwio_debug_message( '<b>' . __METHOD__ . '()</b>' );
|
||||
check_ajax_referer( $this->identifier, 'nonce' );
|
||||
if ( empty( $_POST['ewwwio_test_verify'] ) ) {
|
||||
return;
|
||||
}
|
||||
$item = sanitize_key( $_POST['ewwwio_test_verify'] );
|
||||
ewwwio_debug_message( "testing async handling, received $item" );
|
||||
if ( ewww_image_optimizer_detect_wpsf_location_lock() ) {
|
||||
ewwwio_debug_message( 'detected location lock, not enabling background opt' );
|
||||
return;
|
||||
}
|
||||
if ( '949c34123cf2a4e4ce2f985135830df4a1b2adc24905f53d2fd3f5df5b162932' !== $item ) {
|
||||
ewwwio_debug_message( 'wrong item received, not enabling background opt' );
|
||||
return;
|
||||
}
|
||||
ewwwio_debug_message( 'setting background option to true' );
|
||||
$success = ewww_image_optimizer_set_option( 'ewww_image_optimizer_background_optimization', true );
|
||||
if ( $success ) {
|
||||
ewwwio_debug_message( 'hurrah, async enabled!' );
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,102 @@
|
||||
<?php
|
||||
/**
|
||||
* Class for Background processing of FlaGallery images.
|
||||
*
|
||||
* @link https://ewww.io
|
||||
* @package EWWW_Image_Optimizer
|
||||
*/
|
||||
|
||||
namespace EWWW;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Processes FlaGallery uploads in background/async mode.
|
||||
*
|
||||
* @see EWWW\Background_Process
|
||||
*/
|
||||
class Background_Process_Flag extends Background_Process {
|
||||
|
||||
/**
|
||||
* The action name used to trigger this class extension.
|
||||
*
|
||||
* @access protected
|
||||
* @var string $action
|
||||
*/
|
||||
protected $action = 'ewwwio_flag_optimize';
|
||||
|
||||
/**
|
||||
* The queue name for this class extension.
|
||||
*
|
||||
* @access protected
|
||||
* @var string $action
|
||||
*/
|
||||
protected $active_queue = 'flag-async';
|
||||
|
||||
/**
|
||||
* Runs task for an item from the FlaGallery queue.
|
||||
*
|
||||
* Makes sure an image upload has finished processing and has been stored in the database.
|
||||
* Then runs the usual flag optimization routine on the specified item.
|
||||
*
|
||||
* @access protected
|
||||
* @global bool $ewwwflag
|
||||
*
|
||||
* @param array $item The id of the upload, and how many attempts have been made so far.
|
||||
* @return bool|array If the item is not complete, return it. False indicates completion.
|
||||
*/
|
||||
protected function task( $item ) {
|
||||
session_write_close();
|
||||
if ( empty( $item['attempts'] ) ) {
|
||||
$item['attempts'] = 0;
|
||||
}
|
||||
$id = $item['id'];
|
||||
ewwwio_debug_message( "background processing flagallery: $id" );
|
||||
if ( ! class_exists( 'flagMeta' ) ) {
|
||||
if ( defined( 'FLAG_ABSPATH' ) && ewwwio_is_file( FLAG_ABSPATH . 'lib/meta.php' ) ) {
|
||||
require_once FLAG_ABSPATH . 'lib/meta.php';
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
// Retrieve the metadata for the image.
|
||||
$meta = new flagMeta( $id );
|
||||
if ( empty( $meta ) ) {
|
||||
++$item['attempts'];
|
||||
sleep( 4 );
|
||||
ewwwio_debug_message( "could not retrieve meta, requeueing {$item['attempts']}" );
|
||||
return $item;
|
||||
}
|
||||
global $ewwwflag;
|
||||
$ewwwflag->ewww_added_new_image( $id, $meta );
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs failure routine for an item from the queue.
|
||||
*
|
||||
* @access protected
|
||||
*
|
||||
* @param array $item The id of the attachment, how many attempts have been made to process
|
||||
* the item and whether it is a new upload.
|
||||
*/
|
||||
protected function failure( $item ) {
|
||||
if ( empty( $item['id'] ) ) {
|
||||
return;
|
||||
}
|
||||
if ( ! class_exists( 'flagMeta' ) ) {
|
||||
if ( defined( 'FLAG_ABSPATH' ) && ewwwio_is_file( FLAG_ABSPATH . 'lib/meta.php' ) ) {
|
||||
require_once FLAG_ABSPATH . 'lib/meta.php';
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
}
|
||||
// Retrieve the metadata for the image.
|
||||
$meta = new flagMeta( $item['id'] );
|
||||
if ( ! empty( $meta ) && isset( $meta->image->imagePath ) ) {
|
||||
ewww_image_optimizer_add_file_exclusion( $meta->image->imagePath );
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,96 @@
|
||||
<?php
|
||||
/**
|
||||
* Class for Background optimization of individual images, used by scheduled optimization.
|
||||
*
|
||||
* @link https://ewww.io
|
||||
* @package EWWW_Image_Optimizer
|
||||
*/
|
||||
|
||||
namespace EWWW;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Processes a single image in background/async mode.
|
||||
*
|
||||
* @see EWWW\Background_Process
|
||||
*/
|
||||
class Background_Process_Image extends Background_Process {
|
||||
|
||||
/**
|
||||
* The action name used to trigger this class extension.
|
||||
*
|
||||
* @access protected
|
||||
* @var string $action
|
||||
*/
|
||||
protected $action = 'ewwwio_image_optimize';
|
||||
|
||||
/**
|
||||
* The queue name for this class extension.
|
||||
*
|
||||
* @access protected
|
||||
* @var string $action
|
||||
*/
|
||||
protected $active_queue = 'single-async';
|
||||
|
||||
/**
|
||||
* Attempts limit, shorter for scheduled opt.
|
||||
*
|
||||
* @var int
|
||||
* @access protected
|
||||
*/
|
||||
protected $max_attempts = 5;
|
||||
|
||||
/**
|
||||
* Runs optimization for a file from the image queue.
|
||||
*
|
||||
* @access protected
|
||||
*
|
||||
* @param string $item The filename of the attachment.
|
||||
* @return bool False indicates completion.
|
||||
*/
|
||||
protected function task( $item ) {
|
||||
session_write_close();
|
||||
$id = (int) $item['id'];
|
||||
ewwwio_debug_message( "background processing $id" );
|
||||
$file_path = ewww_image_optimizer_find_file_by_id( $id );
|
||||
if ( $file_path ) {
|
||||
$attachment = array(
|
||||
'id' => $id,
|
||||
'path' => $file_path,
|
||||
);
|
||||
ewwwio_debug_message( "processing background optimization request for $file_path" );
|
||||
ewww_image_optimizer_aux_images_loop( $attachment, true );
|
||||
} else {
|
||||
ewwwio_debug_message( "could not find file to process background optimization request for $id" );
|
||||
return false;
|
||||
}
|
||||
$delay = (int) ewww_image_optimizer_get_option( 'ewww_image_optimizer_delay' );
|
||||
if ( $delay && ewww_image_optimizer_function_exists( 'sleep' ) ) {
|
||||
sleep( $delay );
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs failure routine for an item from the queue.
|
||||
*
|
||||
* @access protected
|
||||
*
|
||||
* @param array $item The id of the attachment, how many attempts have been made to process
|
||||
* the item and whether it is a new upload.
|
||||
*/
|
||||
protected function failure( $item ) {
|
||||
if ( empty( $item['id'] ) ) {
|
||||
return;
|
||||
}
|
||||
global $wpdb;
|
||||
$file_path = ewww_image_optimizer_find_file_by_id( $item['id'] );
|
||||
if ( $file_path ) {
|
||||
ewww_image_optimizer_add_file_exclusion( $file_path );
|
||||
}
|
||||
$wpdb->query( $wpdb->prepare( "DELETE from $wpdb->ewwwio_images WHERE id=%d pending=1 AND (image_size IS NULL OR image_size = 0)", $item['id'] ) );
|
||||
}
|
||||
}
|
@ -0,0 +1,125 @@
|
||||
<?php
|
||||
/**
|
||||
* Class for Background processing of Media Library images.
|
||||
*
|
||||
* @link https://ewww.io
|
||||
* @package EWWW_Image_Optimizer
|
||||
*/
|
||||
|
||||
namespace EWWW;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Processes media uploads in background/async mode.
|
||||
*
|
||||
* Uses a db queue system to track uploads to be optimized, handling them one at a time.
|
||||
*
|
||||
* @see EWWW\Background_Process
|
||||
*/
|
||||
class Background_Process_Media extends Background_Process {
|
||||
|
||||
/**
|
||||
* The action name used to trigger this class extension.
|
||||
*
|
||||
* @access protected
|
||||
* @var string $action
|
||||
*/
|
||||
protected $action = 'ewwwio_media_optimize';
|
||||
|
||||
/**
|
||||
* The queue name for this class extension.
|
||||
*
|
||||
* @access protected
|
||||
* @var string $action
|
||||
*/
|
||||
protected $active_queue = 'media-async';
|
||||
|
||||
/**
|
||||
* Runs task for an item from the Media Library queue.
|
||||
*
|
||||
* Makes sure an image upload has finished processing and has been stored in the database.
|
||||
* Then runs the usual media optimization routine on the specified item.
|
||||
*
|
||||
* @access protected
|
||||
* @global bool $ewww_defer True to defer optimization, false otherwise.
|
||||
*
|
||||
* @param array $item The id of the attachment, how many attempts have been made to process
|
||||
* the item, the type of attachment, and whether it is a new upload.
|
||||
* @return bool|array If the item is not complete, return it. False indicates completion.
|
||||
*/
|
||||
protected function task( $item ) {
|
||||
session_write_close();
|
||||
global $ewww_defer;
|
||||
$ewww_defer = false;
|
||||
$max_attempts = 15;
|
||||
$id = $item['id'];
|
||||
if ( empty( $item['attempts'] ) ) {
|
||||
ewwwio_debug_message( 'first attempt, going to sleep for a bit' );
|
||||
$item['attempts'] = 0;
|
||||
sleep( 1 ); // On the first attempt, hold off and wait for the db to catch up.
|
||||
}
|
||||
$type = get_post_mime_type( $id );
|
||||
if ( empty( $type ) ) {
|
||||
ewwwio_debug_message( "mime is missing, requeueing {$item['attempts']}" );
|
||||
sleep( 4 );
|
||||
return $item;
|
||||
}
|
||||
ewwwio_debug_message( "background processing $id, type: " . $type );
|
||||
$image_types = array(
|
||||
'image/jpeg',
|
||||
'image/png',
|
||||
'image/gif',
|
||||
);
|
||||
|
||||
if ( in_array( $type, $image_types, true ) && $item['new'] && class_exists( 'wpCloud\StatelessMedia\EWWW' ) ) {
|
||||
$meta = wp_get_attachment_metadata( $id );
|
||||
} else {
|
||||
// This is unfiltered for performance, because we don't often need filtered meta.
|
||||
$meta = wp_get_attachment_metadata( $id, true );
|
||||
}
|
||||
if ( in_array( $type, $image_types, true ) && empty( $meta ) ) {
|
||||
ewwwio_debug_message( "metadata is missing, requeueing {$item['attempts']}" );
|
||||
sleep( 4 );
|
||||
return $item;
|
||||
}
|
||||
$meta = ewww_image_optimizer_resize_from_meta_data( $meta, $id, true, $item['new'] );
|
||||
if ( ! empty( $meta['processing'] ) ) {
|
||||
ewwwio_debug_message( 'image not finished, try again' );
|
||||
return $item;
|
||||
}
|
||||
if ( class_exists( 'wpCloud\StatelessMedia\EWWW' ) ) {
|
||||
ewwwio_debug_message( 'async optimize complete, triggering wp_update_attachment_metadata filter with existing meta' );
|
||||
$meta = apply_filters( 'wp_update_attachment_metadata', wp_get_attachment_metadata( $image->attachment_id ), $image->attachment_id );
|
||||
} else {
|
||||
ewwwio_debug_message( 'async optimize complete, running wp_update_attachment_metadata()' );
|
||||
wp_update_attachment_metadata( $id, $meta );
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs failure routine for an item from the Media Library queue.
|
||||
*
|
||||
* @access protected
|
||||
*
|
||||
* @param array $item The id of the attachment, how many attempts have been made to process
|
||||
* the item and whether it is a new upload.
|
||||
*/
|
||||
protected function failure( $item ) {
|
||||
if ( empty( $item['id'] ) ) {
|
||||
return;
|
||||
}
|
||||
$file_path = false;
|
||||
$meta = wp_get_attachment_metadata( $item['id'] );
|
||||
if ( ! empty( $meta ) ) {
|
||||
list( $file_path, $upload_path ) = ewww_image_optimizer_attachment_path( $meta, $item['id'] );
|
||||
}
|
||||
|
||||
if ( $file_path ) {
|
||||
ewww_image_optimizer_add_file_exclusion( $file_path );
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,102 @@
|
||||
<?php
|
||||
/**
|
||||
* Class for Background processing of Nextcellent images.
|
||||
*
|
||||
* @link https://ewww.io
|
||||
* @package EWWW_Image_Optimizer
|
||||
*/
|
||||
|
||||
namespace EWWW;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Processes Nextcellent uploads in background/async mode.
|
||||
*
|
||||
* @see EWWW\Background_Process
|
||||
*/
|
||||
class Background_Process_Ngg extends Background_Process {
|
||||
|
||||
/**
|
||||
* The action name used to trigger this class extension.
|
||||
*
|
||||
* @access protected
|
||||
* @var string $action
|
||||
*/
|
||||
protected $action = 'ewwwio_ngg_optimize';
|
||||
|
||||
/**
|
||||
* The queue name for this class extension.
|
||||
*
|
||||
* @access protected
|
||||
* @var string $action
|
||||
*/
|
||||
protected $active_queue = 'nextc-async';
|
||||
|
||||
/**
|
||||
* Runs task for an item from the Nextcellent queue.
|
||||
*
|
||||
* Makes sure an image upload has finished processing and has been stored in the database.
|
||||
* Then runs the usual nextcellent optimization routine on the specified item.
|
||||
*
|
||||
* @access protected
|
||||
* @global bool $ewwwngg
|
||||
*
|
||||
* @param array $item The id of the upload, and how many attempts have been made so far.
|
||||
* @return bool|array If the item is not complete, return it. False indicates completion.
|
||||
*/
|
||||
protected function task( $item ) {
|
||||
session_write_close();
|
||||
if ( empty( $item['attempts'] ) ) {
|
||||
$item['attempts'] = 0;
|
||||
}
|
||||
$id = $item['id'];
|
||||
ewwwio_debug_message( "background processing nextcellent: $id" );
|
||||
if ( ! class_exists( 'nggMeta' ) ) {
|
||||
if ( defined( 'NGGALLERY_ABSPATH' ) && ewwwio_is_file( NGGALLERY_ABSPATH . 'lib/meta.php' ) ) {
|
||||
require_once NGGALLERY_ABSPATH . '/lib/meta.php';
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
// Retrieve the metadata for the image.
|
||||
$meta = new nggMeta( $id );
|
||||
if ( empty( $meta ) ) {
|
||||
++$item['attempts'];
|
||||
sleep( 4 );
|
||||
ewwwio_debug_message( "could not retrieve meta, requeueing {$item['attempts']}" );
|
||||
return $item;
|
||||
}
|
||||
global $ewwwngg;
|
||||
$ewwwngg->ewww_added_new_image( $id, $meta );
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs failure routine for an item from the queue.
|
||||
*
|
||||
* @access protected
|
||||
*
|
||||
* @param array $item The id of the attachment, how many attempts have been made to process
|
||||
* the item and whether it is a new upload.
|
||||
*/
|
||||
protected function failure( $item ) {
|
||||
if ( empty( $item['id'] ) ) {
|
||||
return;
|
||||
}
|
||||
if ( ! class_exists( 'nggMeta' ) ) {
|
||||
if ( defined( 'NGGALLERY_ABSPATH' ) && ewwwio_is_file( NGGALLERY_ABSPATH . 'lib/meta.php' ) ) {
|
||||
require_once NGGALLERY_ABSPATH . '/lib/meta.php';
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
}
|
||||
// Retrieve the metadata for the image.
|
||||
$meta = new nggMeta( $item['id'] );
|
||||
if ( ! empty( $meta ) && isset( $meta->image->imagePath ) ) {
|
||||
ewww_image_optimizer_add_file_exclusion( $meta->image->imagePath );
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,98 @@
|
||||
<?php
|
||||
/**
|
||||
* Class for Background processing of NextGEN Gallery images.
|
||||
*
|
||||
* @link https://ewww.io
|
||||
* @package EWWW_Image_Optimizer
|
||||
*/
|
||||
|
||||
namespace EWWW;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Processes NextGEN uploads in background/async mode.
|
||||
*
|
||||
* Uses a dual-queue system to track uploads to be optimized, handling them one at a time.
|
||||
*
|
||||
* @see EWWW\Background_Process
|
||||
*/
|
||||
class Background_Process_Ngg2 extends Background_Process {
|
||||
|
||||
/**
|
||||
* The action name used to trigger this class extension.
|
||||
*
|
||||
* @access protected
|
||||
* @var string $action
|
||||
*/
|
||||
protected $action = 'ewwwio_ngg2_optimize';
|
||||
|
||||
/**
|
||||
* The queue name for this class extension.
|
||||
*
|
||||
* @access protected
|
||||
* @var string $action
|
||||
*/
|
||||
protected $active_queue = 'nextg-async';
|
||||
|
||||
/**
|
||||
* Runs task for an item from the NextGEN queue.
|
||||
*
|
||||
* Makes sure an image upload has finished processing and has been stored in the database.
|
||||
* Then runs the usual nextgen optimization routine on the specified item.
|
||||
*
|
||||
* @access protected
|
||||
* @global bool $ewwwngg
|
||||
*
|
||||
* @param array $item The id of the upload, and how many attempts have been made so far.
|
||||
* @return bool|array If the item is not complete, return it. False indicates completion.
|
||||
*/
|
||||
protected function task( $item ) {
|
||||
session_write_close();
|
||||
if ( empty( $item['attempts'] ) ) {
|
||||
$item['attempts'] = 0;
|
||||
}
|
||||
$id = $item['id'];
|
||||
ewwwio_debug_message( "background processing nextgen2: $id" );
|
||||
if ( ! defined( 'NGG_PLUGIN_VERSION' ) ) {
|
||||
return false;
|
||||
}
|
||||
global $ewwwngg;
|
||||
// Get a NextGEN image object.
|
||||
$image = $ewwwngg->get_ngg_image( $id );
|
||||
if ( ! is_object( $image ) ) {
|
||||
++$item['attempts'];
|
||||
sleep( 4 );
|
||||
ewwwio_debug_message( "could not retrieve image, requeueing {$item['attempts']}" );
|
||||
return $item;
|
||||
}
|
||||
$ewwwngg->ewww_added_new_image( $image );
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs failure routine for an item from the queue.
|
||||
*
|
||||
* @access protected
|
||||
*
|
||||
* @param array $item The id of the attachment, how many attempts have been made to process
|
||||
* the item and whether it is a new upload.
|
||||
*/
|
||||
protected function failure( $item ) {
|
||||
if ( empty( $item['id'] ) ) {
|
||||
return;
|
||||
}
|
||||
if ( ! defined( 'NGG_PLUGIN_VERSION' ) ) {
|
||||
return false;
|
||||
}
|
||||
// Get a NextGEN image object.
|
||||
global $ewwwngg;
|
||||
$image = $ewwwngg->get_ngg_image( $item['id'] );
|
||||
$file_path = $ewwwngg->get_image_abspath( $image, 'full' );
|
||||
if ( ! empty( $file_path ) ) {
|
||||
ewww_image_optimizer_add_file_exclusion( $file_path );
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,509 @@
|
||||
<?php
|
||||
/**
|
||||
* EWWWIO Background Process
|
||||
*
|
||||
* @package EWWW_Image_Optimizer
|
||||
*/
|
||||
|
||||
namespace EWWW;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Abstract Background_Process class.
|
||||
*
|
||||
* @abstract
|
||||
* @extends EWWW\Async_Request
|
||||
*/
|
||||
abstract class Background_Process extends Async_Request {
|
||||
|
||||
/**
|
||||
* Action
|
||||
*
|
||||
* (default value: 'background_process')
|
||||
*
|
||||
* @var string
|
||||
* @access protected
|
||||
*/
|
||||
protected $action = 'background_process';
|
||||
|
||||
/**
|
||||
* Start time of current process.
|
||||
*
|
||||
* (default value: 0)
|
||||
*
|
||||
* @var int
|
||||
* @access protected
|
||||
*/
|
||||
protected $start_time = 0;
|
||||
|
||||
/**
|
||||
* Batch size limit.
|
||||
*
|
||||
* @var int
|
||||
* @access protected
|
||||
*/
|
||||
protected $limit = 50;
|
||||
|
||||
/**
|
||||
* Attempts limit.
|
||||
*
|
||||
* @var int
|
||||
* @access protected
|
||||
*/
|
||||
protected $max_attempts = 15;
|
||||
|
||||
/**
|
||||
* Cron_hook_identifier
|
||||
*
|
||||
* @var mixed
|
||||
* @access protected
|
||||
*/
|
||||
protected $cron_hook_identifier;
|
||||
|
||||
/**
|
||||
* Cron health check interval.
|
||||
*
|
||||
* @var int
|
||||
* @access protected
|
||||
*/
|
||||
protected $cron_interval = 5;
|
||||
|
||||
/**
|
||||
* Cron_interval_identifier
|
||||
*
|
||||
* @var mixed
|
||||
* @access protected
|
||||
*/
|
||||
protected $cron_interval_identifier;
|
||||
|
||||
/**
|
||||
* A unique identifier for each background class extension.
|
||||
*
|
||||
* @var string
|
||||
* @access protected
|
||||
*/
|
||||
protected $active_queue;
|
||||
|
||||
/**
|
||||
* Amount of time to set the "process lock" transient.
|
||||
*
|
||||
* @var int
|
||||
* @access protected
|
||||
*/
|
||||
protected $queue_lock_time = 180; // 3 minutes
|
||||
|
||||
/**
|
||||
* Initiate new background process
|
||||
*/
|
||||
public function __construct() {
|
||||
parent::__construct();
|
||||
|
||||
$this->cron_hook_identifier = $this->identifier . '_cron';
|
||||
$this->cron_interval_identifier = $this->identifier . '_cron_interval';
|
||||
|
||||
add_action( $this->cron_hook_identifier, array( $this, 'handle_cron_healthcheck' ) );
|
||||
add_filter( 'cron_schedules', array( $this, 'schedule_cron_healthcheck' ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Dispatch
|
||||
*
|
||||
* @access public
|
||||
* @return array The wp_remote_post response.
|
||||
*/
|
||||
public function dispatch() {
|
||||
// Schedule the cron healthcheck.
|
||||
$this->schedule_event();
|
||||
|
||||
// Perform remote post.
|
||||
return parent::dispatch();
|
||||
}
|
||||
|
||||
/**
|
||||
* Push to queue
|
||||
*
|
||||
* @param mixed $data Data.
|
||||
*/
|
||||
public function push_to_queue( $data ) {
|
||||
global $wpdb;
|
||||
|
||||
$id = (int) $data['id'];
|
||||
$new = ! empty( $data['new'] ) ? 1 : 0;
|
||||
if ( ! $id ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$exists = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->ewwwio_queue WHERE attachment_id = %d AND gallery = %s LIMIT 1", $id, $this->active_queue ) );
|
||||
if ( empty( $exists ) ) {
|
||||
$to_insert = array(
|
||||
'attachment_id' => $id,
|
||||
'gallery' => $this->active_queue,
|
||||
'new' => $new,
|
||||
);
|
||||
$wpdb->insert( $wpdb->ewwwio_queue, $to_insert );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update queue item
|
||||
*
|
||||
* @param int $id ID of queue item.
|
||||
* @param array $data Data related to queue item.
|
||||
*/
|
||||
public function update( $id, $data = array() ) {
|
||||
if ( ! empty( $id ) ) {
|
||||
global $wpdb;
|
||||
$wpdb->get_row( $wpdb->prepare( "UPDATE $wpdb->ewwwio_queue SET scanned=scanned+1 WHERE attachment_id = %d AND gallery = %s LIMIT 1", $id, $this->active_queue ) );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete queue item
|
||||
*
|
||||
* @param string $key Key.
|
||||
*/
|
||||
public function delete( $key ) {
|
||||
if ( ! $key ) {
|
||||
return;
|
||||
}
|
||||
$key = (int) $key;
|
||||
global $wpdb;
|
||||
$wpdb->delete(
|
||||
$wpdb->ewwwio_queue,
|
||||
array(
|
||||
'attachment_id' => $key,
|
||||
'gallery' => $this->active_queue,
|
||||
),
|
||||
array( '%d', '%s' )
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Maybe process queue
|
||||
*
|
||||
* Checks whether data exists within the queue and that
|
||||
* the process is not already running.
|
||||
*/
|
||||
public function maybe_handle() {
|
||||
session_write_close();
|
||||
|
||||
if ( $this->is_process_running() ) {
|
||||
// Background process already running.
|
||||
die;
|
||||
}
|
||||
|
||||
if ( $this->is_queue_empty() ) {
|
||||
// No data to process.
|
||||
die;
|
||||
}
|
||||
|
||||
\check_ajax_referer( $this->identifier, 'nonce' );
|
||||
|
||||
$this->handle();
|
||||
|
||||
die;
|
||||
}
|
||||
|
||||
/**
|
||||
* Count items in queue.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function count_queue() {
|
||||
global $wpdb;
|
||||
return (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->ewwwio_queue WHERE gallery = %s", $this->active_queue ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Is queue empty
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
protected function is_queue_empty() {
|
||||
return ! $this->count_queue();
|
||||
}
|
||||
|
||||
/**
|
||||
* Is process running
|
||||
*
|
||||
* Check whether the current process is already running
|
||||
* in a background process.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function is_process_running() {
|
||||
if ( \get_transient( $this->identifier . '_process_lock' ) ) {
|
||||
// Process already running.
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update (or initialize) process lock
|
||||
*
|
||||
* Update the process lock so that other instances do not spawn.
|
||||
*
|
||||
* @return $this
|
||||
*/
|
||||
protected function update_lock() {
|
||||
if ( empty( $this->active_queue ) ) {
|
||||
return;
|
||||
}
|
||||
$lock_duration = \apply_filters( $this->identifier . '_queue_lock_time', $this->queue_lock_time );
|
||||
\set_transient( $this->identifier . '_process_lock', $this->active_queue, $lock_duration );
|
||||
}
|
||||
|
||||
/**
|
||||
* Unlock process
|
||||
*
|
||||
* Unlock the process so that other instances can spawn.
|
||||
*
|
||||
* @return $this
|
||||
*/
|
||||
protected function unlock_process() {
|
||||
\delete_transient( $this->identifier . '_process_lock' );
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get batch
|
||||
*
|
||||
* @return array Return the first batch from the queue
|
||||
*/
|
||||
protected function get_batch() {
|
||||
global $wpdb;
|
||||
$batch = $wpdb->get_results( $wpdb->prepare( "SELECT attachment_id AS id, scanned AS attempts, new FROM $wpdb->ewwwio_queue WHERE gallery = %s LIMIT %d", $this->active_queue, $this->limit ), ARRAY_A );
|
||||
if ( empty( $batch ) ) {
|
||||
return array();
|
||||
}
|
||||
\ewwwio_debug_message( 'selected items: ' . count( $batch ) );
|
||||
|
||||
$this->update_lock();
|
||||
return $batch;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle
|
||||
*
|
||||
* Pass each queue item to the task handler, while remaining
|
||||
* within server memory and time limit constraints.
|
||||
*/
|
||||
protected function handle() {
|
||||
$this->start_time = time(); // Set start time of current process.
|
||||
|
||||
do {
|
||||
$batch = $this->get_batch();
|
||||
|
||||
foreach ( $batch as $key => $value ) {
|
||||
if ( $value['attempts'] > $this->max_attempts ) {
|
||||
$this->failure( $value );
|
||||
$this->delete( $value['id'] );
|
||||
continue;
|
||||
}
|
||||
$this->update( $value['id'], $value );
|
||||
$task = $this->task( $value );
|
||||
|
||||
if ( false !== $task ) {
|
||||
$batch[ $key ] = $task;
|
||||
} else {
|
||||
$this->delete( $value['id'] );
|
||||
}
|
||||
|
||||
if ( $this->time_exceeded() || $this->memory_exceeded() ) {
|
||||
// Batch limits reached.
|
||||
break;
|
||||
}
|
||||
}
|
||||
} while ( ! $this->time_exceeded() && ! $this->memory_exceeded() && ! $this->is_queue_empty() );
|
||||
|
||||
$this->unlock_process();
|
||||
|
||||
// Start next batch or complete process.
|
||||
if ( ! $this->is_queue_empty() ) {
|
||||
$this->dispatch();
|
||||
} else {
|
||||
$this->complete();
|
||||
}
|
||||
|
||||
die;
|
||||
}
|
||||
|
||||
/**
|
||||
* Memory exceeded
|
||||
*
|
||||
* Ensures the batch process never exceeds 90%
|
||||
* of the maximum WordPress memory.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
protected function memory_exceeded() {
|
||||
$memory_limit = $this->get_memory_limit() * 0.9; // 90% of max memory
|
||||
$current_memory = memory_get_usage( true );
|
||||
$return = false;
|
||||
|
||||
if ( $current_memory >= $memory_limit ) {
|
||||
$return = true;
|
||||
}
|
||||
|
||||
return \apply_filters( $this->identifier . '_memory_exceeded', $return );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get memory limit
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
protected function get_memory_limit() {
|
||||
if ( ! function_exists( 'wp_convert_hr_to_bytes' ) ) {
|
||||
return 128 * MB_IN_BYTES;
|
||||
}
|
||||
if ( function_exists( 'ini_get' ) ) {
|
||||
$memory_limit = ini_get( 'memory_limit' );
|
||||
} else {
|
||||
// Sensible default.
|
||||
$memory_limit = '128M';
|
||||
}
|
||||
if ( ! $memory_limit || -1 === (int) $memory_limit ) {
|
||||
// Unlimited, set to 32GB.
|
||||
$memory_limit = '32G';
|
||||
}
|
||||
|
||||
return \wp_convert_hr_to_bytes( $memory_limit );
|
||||
}
|
||||
|
||||
/**
|
||||
* Time exceeded.
|
||||
*
|
||||
* Ensures the batch never exceeds a sensible time limit.
|
||||
* A timeout limit of 30s is common on shared hosting.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
protected function time_exceeded() {
|
||||
$finish = $this->start_time + \apply_filters( $this->identifier . '_default_time_limit', 20 ); // 20 seconds
|
||||
$return = false;
|
||||
|
||||
if ( time() >= $finish ) {
|
||||
$return = true;
|
||||
}
|
||||
|
||||
return \apply_filters( $this->identifier . '_time_exceeded', $return );
|
||||
}
|
||||
|
||||
/**
|
||||
* Complete.
|
||||
*
|
||||
* Override if applicable, but ensure that the below actions are
|
||||
* performed, or, call parent::complete().
|
||||
*/
|
||||
protected function complete() {
|
||||
// Unschedule the cron healthcheck.
|
||||
$this->clear_scheduled_event();
|
||||
}
|
||||
|
||||
/**
|
||||
* Schedule cron healthcheck
|
||||
*
|
||||
* @access public
|
||||
* @param mixed $schedules Schedules.
|
||||
* @return mixed
|
||||
*/
|
||||
public function schedule_cron_healthcheck( $schedules ) {
|
||||
$interval = \apply_filters( $this->identifier . '_cron_interval', $this->cron_interval );
|
||||
|
||||
// Adds every X (default=5) minutes to the existing schedules.
|
||||
$schedules[ $this->identifier . '_cron_interval' ] = array(
|
||||
'interval' => MINUTE_IN_SECONDS * $interval,
|
||||
/* translators: %d: number of minutes */
|
||||
'display' => sprintf( __( 'Every %d Minutes' ), $interval ),
|
||||
);
|
||||
|
||||
return $schedules;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle cron healthcheck
|
||||
*
|
||||
* Restart the background process if not already running
|
||||
* and data exists in the queue.
|
||||
*/
|
||||
public function handle_cron_healthcheck() {
|
||||
if ( $this->is_process_running() ) {
|
||||
// Background process already running.
|
||||
exit;
|
||||
}
|
||||
|
||||
if ( $this->is_queue_empty() ) {
|
||||
// No data to process.
|
||||
$this->clear_scheduled_event();
|
||||
exit;
|
||||
}
|
||||
|
||||
$this->handle();
|
||||
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Schedule event
|
||||
*/
|
||||
protected function schedule_event() {
|
||||
if ( ! \wp_next_scheduled( $this->cron_hook_identifier ) ) {
|
||||
\wp_schedule_event( time(), $this->cron_interval_identifier, $this->cron_hook_identifier );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear scheduled event
|
||||
*/
|
||||
protected function clear_scheduled_event() {
|
||||
$timestamp = \wp_next_scheduled( $this->cron_hook_identifier );
|
||||
|
||||
if ( $timestamp ) {
|
||||
\wp_unschedule_event( $timestamp, $this->cron_hook_identifier );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Cancel Process
|
||||
*
|
||||
* Stop processing queue items, clear cronjob and delete batch.
|
||||
*/
|
||||
public function cancel_process() {
|
||||
global $wpdb;
|
||||
$wpdb->query( $wpdb->prepare( "DELETE from $wpdb->ewwwio_queue WHERE gallery = %s", $this->active_queue ) );
|
||||
\wp_clear_scheduled_hook( $this->cron_hook_identifier );
|
||||
$this->unlock_process();
|
||||
}
|
||||
|
||||
/**
|
||||
* Task
|
||||
*
|
||||
* Override this method to perform any actions required on each
|
||||
* queue item. Return the modified item for further processing
|
||||
* in the next pass through. Or, return false to remove the
|
||||
* item from the queue.
|
||||
*
|
||||
* @param mixed $item Queue item to iterate over.
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
abstract protected function task( $item );
|
||||
|
||||
/**
|
||||
* Failure
|
||||
*
|
||||
* Override this method to perform any actions required when a
|
||||
* queue item reaches the maximum retries. Will be removed
|
||||
* from the queue after this fires.
|
||||
*
|
||||
* @param mixed $item Queue item entering failure condition.
|
||||
*/
|
||||
abstract protected function failure( $item );
|
||||
}
|
458
wp-content/plugins/ewww-image-optimizer/classes/class-backup.php
Normal file
@ -0,0 +1,458 @@
|
||||
<?php
|
||||
/**
|
||||
* Implements backup/restore functions.
|
||||
*
|
||||
* @link https://ewww.io
|
||||
* @package EIO
|
||||
*/
|
||||
|
||||
namespace EWWW;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Backup & Restore images from both local and cloud locations.
|
||||
*/
|
||||
class Backup extends Base {
|
||||
|
||||
/**
|
||||
* An error from a restore operation.
|
||||
*
|
||||
* @access protected
|
||||
* @var string $error_message
|
||||
*/
|
||||
protected $error_message = '';
|
||||
|
||||
/**
|
||||
* A list of exclusions.
|
||||
*
|
||||
* @access protected
|
||||
* @var array $exclusions
|
||||
*/
|
||||
protected $exclusions = array();
|
||||
|
||||
/**
|
||||
* Backup mode (local/cloud).
|
||||
*
|
||||
* @var string $backup_mode
|
||||
*/
|
||||
protected $backup_mode = '';
|
||||
|
||||
/**
|
||||
* Backup location.
|
||||
*
|
||||
* @var string $backup_dir
|
||||
*/
|
||||
protected $backup_dir = '';
|
||||
|
||||
/**
|
||||
* Backup location for media uploads.
|
||||
*
|
||||
* @var string $backup_uploads_dir
|
||||
*/
|
||||
protected $backup_uploads_dir = '';
|
||||
|
||||
/**
|
||||
* Backup location for images outside the wp-content directory.
|
||||
*
|
||||
* @var string $backup_root_dir
|
||||
*/
|
||||
protected $backup_root_dir = '';
|
||||
|
||||
/**
|
||||
* Register (once) actions and filters for Backup and Restore.
|
||||
*/
|
||||
public function __construct() {
|
||||
global $eio_backup;
|
||||
if ( \is_object( $eio_backup ) ) {
|
||||
return $eio_backup;
|
||||
}
|
||||
parent::__construct();
|
||||
$this->debug_message( '<b>' . __METHOD__ . '()</b>' );
|
||||
if ( 'local' === $this->get_option( 'ewww_image_optimizer_backup_files' ) ) {
|
||||
$this->backup_mode = 'local';
|
||||
// Sub-folders of the content directory will be stored directly in the image-backup/ folder.
|
||||
$this->backup_dir = \trailingslashit( $this->content_dir ) . \trailingslashit( 'image-backup' );
|
||||
// Sub-folders of the content directory will be stored directly in the image-backup/ folder.
|
||||
$this->backup_uploads_dir = \trailingslashit( $this->backup_dir ) . \trailingslashit( 'uploads' );
|
||||
// Folders outside the content dir, and relative to ABSPATH will be stored in the root/ directory.
|
||||
$this->backup_root_dir = \trailingslashit( $this->backup_dir ) . \trailingslashit( 'root' );
|
||||
} elseif ( $this->get_option( 'ewww_image_optimizer_cloud_key' ) && $this->get_option( 'ewww_image_optimizer_backup_files' ) ) {
|
||||
$this->backup_mode = 'cloud';
|
||||
}
|
||||
|
||||
// AJAX action hook for manually restoring a single image from cloud/local backups.
|
||||
\add_action( 'wp_ajax_ewww_manual_image_restore_single', array( $this, 'restore_single_image_handler' ) );
|
||||
\add_action( 'ewww_image_optimizer_pre_optimization', array( $this, 'store_local_backup' ) );
|
||||
|
||||
$this->exclusions = array(
|
||||
$this->content_dir,
|
||||
'/wp-admin/',
|
||||
'/wp-includes/',
|
||||
'/cache/',
|
||||
'/dynamic/', // Nextgen dynamic images.
|
||||
);
|
||||
$this->exclusions = \apply_filters( 'ewww_image_optimizer_backup_exclusions', $this->exclusions );
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the error message from the most recent restore operation, if any.
|
||||
*
|
||||
* @return string An error message.
|
||||
*/
|
||||
public function get_error() {
|
||||
return (string) $this->error_message;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the error message for restore operations.
|
||||
*
|
||||
* @param string $error An error message.
|
||||
*/
|
||||
public function throw_error( $error ) {
|
||||
if ( \is_string( $error ) ) {
|
||||
$this->error_message = \sanitize_text_field( $error );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether a file is in the uploads dir, content dir, or within the ABSPATH/root.
|
||||
*
|
||||
* This helps to deal with cases where folks have upload and/or content dirs outside ABSPATH.
|
||||
*
|
||||
* @param string $file The filename to backup.
|
||||
* @return string The backup location for the file.
|
||||
*/
|
||||
public function get_backup_location( $file ) {
|
||||
$this->debug_message( '<b>' . __METHOD__ . '()</b>' );
|
||||
if ( \ewww_image_optimizer_stream_wrapped( $file ) || 'local' !== $this->backup_mode ) {
|
||||
return '';
|
||||
}
|
||||
$upload_dir = \wp_get_upload_dir();
|
||||
$upload_dir = \trailingslashit( \realpath( $upload_dir['basedir'] ) );
|
||||
if ( $upload_dir && \strpos( $file, $upload_dir ) === 0 ) {
|
||||
$this->debug_message( 'using ' . $this->backup_uploads_dir );
|
||||
return \str_replace( $upload_dir, $this->backup_uploads_dir, $file );
|
||||
}
|
||||
$content_dir = \trailingslashit( \realpath( WP_CONTENT_DIR ) );
|
||||
if ( $content_dir && \strpos( $file, $content_dir ) === 0 ) {
|
||||
$this->debug_message( 'using ' . $this->backup_dir );
|
||||
return \str_replace( $content_dir, $this->backup_dir, $file );
|
||||
}
|
||||
$wp_dir = \trailingslashit( \realpath( ABSPATH ) );
|
||||
if ( $wp_dir && \strpos( $file, $wp_dir ) === 0 ) {
|
||||
$this->debug_message( 'using ' . $this->backup_root_dir );
|
||||
return \str_replace( $wp_dir, $this->backup_root_dir, $file );
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks to see if a backup is available for a given file.
|
||||
*
|
||||
* @param string $file The image file to search for a backup.
|
||||
* @param array $record The database record for the file. Optional.
|
||||
* @return bool True if a backup is available, false otherwise.
|
||||
*/
|
||||
public function is_backup_available( $file, $record = false ) {
|
||||
$this->debug_message( '<b>' . __METHOD__ . '()</b>' );
|
||||
$file = \ewww_image_optimizer_absolutize_path( $file );
|
||||
if ( 'local' === $this->backup_mode ) {
|
||||
\clearstatcache();
|
||||
$backup_file = $this->get_backup_location( $file );
|
||||
return $this->is_file( $backup_file );
|
||||
} elseif ( 'cloud' === $this->backup_mode ) {
|
||||
if ( ! $record || ! isset( $record['backup'] ) || ! isset( $record['updated'] ) ) {
|
||||
$record = \ewww_image_optimizer_find_already_optimized( $file );
|
||||
}
|
||||
if ( $record && $this->is_iterable( $record ) && ! empty( $record['backup'] ) && ! empty( $record['updated'] ) ) {
|
||||
$updated_time = \strtotime( $record['updated'] );
|
||||
if ( DAY_IN_SECONDS * 30 + $updated_time > \time() ) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Backup a file to local or cloud storage.
|
||||
*
|
||||
* @param string $file Name of the file to backup.
|
||||
*/
|
||||
public function backup_file( $file ) {
|
||||
$this->debug_message( '<b>' . __METHOD__ . '()</b>' );
|
||||
$this->debug_message( "file: $file " );
|
||||
foreach ( $this->exclusions as $exclusion ) {
|
||||
if ( false !== \strpos( $file, $exclusion ) ) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
if ( 'local' === $this->backup_mode ) {
|
||||
$this->store_local_backup( $file );
|
||||
} elseif ( 'cloud' === $this->backup_mode ) {
|
||||
$this->store_cloud_backup( $file );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Copy a file to the backup location.
|
||||
*
|
||||
* @param string $file Name of the file to backup.
|
||||
*/
|
||||
public function store_local_backup( $file ) {
|
||||
$this->debug_message( '<b>' . __METHOD__ . '()</b>' );
|
||||
if ( 'local' !== $this->backup_mode ) {
|
||||
return;
|
||||
}
|
||||
if ( ! $this->is_file( $file ) || ! $this->is_readable( $file ) ) {
|
||||
return;
|
||||
}
|
||||
if ( apply_filters( 'ewww_image_optimizer_skip_local_backup', false, $file ) ) {
|
||||
return;
|
||||
}
|
||||
$backup_file = $this->get_backup_location( $file );
|
||||
if ( ! $backup_file || $backup_file === $file ) {
|
||||
return;
|
||||
}
|
||||
\clearstatcache();
|
||||
if ( $this->is_file( $backup_file ) ) {
|
||||
return;
|
||||
}
|
||||
\wp_mkdir_p( \dirname( $backup_file ) );
|
||||
\clearstatcache();
|
||||
if ( ! \is_writable( \dirname( $backup_file ) ) ) {
|
||||
return;
|
||||
}
|
||||
$this->debug_message( "backing up $file to $backup_file" );
|
||||
\copy( $file, $backup_file );
|
||||
if ( $this->filesize( $file ) !== $this->filesize( $backup_file ) ) {
|
||||
// In order to not store bogus files.
|
||||
$this->delete_file( $backup_file );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a file to the API for backup.
|
||||
*
|
||||
* @param string $file Name of the file to backup.
|
||||
*/
|
||||
protected function store_cloud_backup( $file ) {
|
||||
$this->debug_message( '<b>' . __METHOD__ . '()</b>' );
|
||||
\ewww_image_optimizer_cloud_backup( $file );
|
||||
}
|
||||
|
||||
/**
|
||||
* Restore an image from local or cloud storage.
|
||||
*
|
||||
* @global object $wpdb
|
||||
* @global object $ewwwdb A clone of $wpdb unless it is lacking utf8 connectivity.
|
||||
*
|
||||
* @param int|array $image The db record/ID of the image to restore.
|
||||
* @return bool True if the image was restored successfully.
|
||||
*/
|
||||
public function restore_file( $image ) {
|
||||
$this->debug_message( '<b>' . __METHOD__ . '()</b>' );
|
||||
global $wpdb;
|
||||
if ( \strpos( $wpdb->charset, 'utf8' ) === false ) {
|
||||
\ewww_image_optimizer_db_init();
|
||||
global $ewwwdb;
|
||||
} else {
|
||||
$ewwwdb = $wpdb;
|
||||
}
|
||||
$this->error_message = '';
|
||||
if ( ! \is_array( $image ) && ! empty( $image ) && \is_numeric( $image ) ) {
|
||||
$image = $ewwwdb->get_row( "SELECT id,path,backup FROM $ewwwdb->ewwwio_images WHERE id = $image", ARRAY_A );
|
||||
}
|
||||
if ( ! empty( $image['path'] ) ) {
|
||||
$image['path'] = \ewww_image_optimizer_absolutize_path( $image['path'] );
|
||||
}
|
||||
if ( empty( $image['path'] ) ) {
|
||||
return false;
|
||||
}
|
||||
if ( 'local' === $this->backup_mode ) {
|
||||
return $this->restore_from_local( $image );
|
||||
} elseif ( 'cloud' === $this->backup_mode ) {
|
||||
return $this->restore_from_cloud( $image );
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Restore a file from a local backup location.
|
||||
*
|
||||
* @param array $image The db record of the image to restore.
|
||||
*/
|
||||
protected function restore_from_local( $image ) {
|
||||
$this->debug_message( '<b>' . __METHOD__ . '()</b>' );
|
||||
if ( 'local' !== $this->backup_mode ) {
|
||||
return false;
|
||||
}
|
||||
$file = $image['path'];
|
||||
if ( ! \is_writable( \dirname( $file ) ) ) {
|
||||
$this->debug_message( "$file (or the parent dir) is not writable" );
|
||||
/* translators: %s: An image filename */
|
||||
$this->error_message = \sprintf( \__( '%s is not writable.', 'ewww-image-optimizer' ), $file );
|
||||
return false;
|
||||
}
|
||||
$backup_file = $this->get_backup_location( $file );
|
||||
if ( ! $backup_file || $backup_file === $file ) {
|
||||
$this->debug_message( "$backup_file is not a valid backup location for $file" );
|
||||
/* translators: %s: An image filename */
|
||||
$this->error_message = \sprintf( \__( 'Could not determine backup location for %s.', 'ewww-image-optimizer' ), $file );
|
||||
return false;
|
||||
}
|
||||
\clearstatcache();
|
||||
if ( ! $this->is_file( $backup_file ) ) {
|
||||
$this->debug_message( "$backup_file does not exist" );
|
||||
/* translators: %s: An image filename */
|
||||
$this->error_message = \sprintf( \__( 'No backup available for %s.', 'ewww-image-optimizer' ), $file );
|
||||
return false;
|
||||
}
|
||||
if ( \ewww_image_optimizer_mimetype( $file, 'i' ) !== \ewww_image_optimizer_mimetype( $backup_file, 'i' ) ) {
|
||||
$this->debug_message( "$backup_file is different type than $file " . \ewww_image_optimizer_mimetype( $backup_file, 'i' ) . ' vs. ' . \ewww_image_optimizer_mimetype( $file, 'i' ) );
|
||||
/* translators: %s: An image filename */
|
||||
$this->error_message = \sprintf( \__( 'Backup file for %s has the wrong mime type.', 'ewww-image-optimizer' ), $file );
|
||||
return false;
|
||||
}
|
||||
$filesize = $this->filesize( $file );
|
||||
$backsize = $this->filesize( $backup_file );
|
||||
if ( $filesize && $filesize === $backsize ) {
|
||||
// $this->delete_file( $backup_file );
|
||||
// return true; // Because restore not needed, already done!
|
||||
}
|
||||
$this->debug_message( "restoring $file from $backup_file" );
|
||||
copy( $backup_file, $file );
|
||||
if ( $this->filesize( $file ) === $this->filesize( $backup_file ) ) {
|
||||
if ( $this->is_file( $file . '.webp' ) && \is_writable( $file . '.webp' ) ) {
|
||||
$this->delete_file( $file . '.webp' );
|
||||
}
|
||||
/* $this->delete_file( $backup_file ); */
|
||||
global $wpdb;
|
||||
// Reset the image record.
|
||||
$wpdb->query( $wpdb->prepare( "UPDATE $wpdb->ewwwio_images SET results = '', image_size = 0, updates = 0, updated=updated, level = 0 WHERE id = %d", $image['id'] ) );
|
||||
return true;
|
||||
}
|
||||
/* translators: %s: An image filename */
|
||||
$this->error_message = \sprintf( \__( 'Restore attempted for %s, but could not be confirmed.', 'ewww-image-optimizer' ), $file );
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a file to the API for backup.
|
||||
*
|
||||
* @param int|array $image The db record/ID of the image to restore.
|
||||
* @return bool True if the image was restored successfully.
|
||||
*/
|
||||
protected function restore_from_cloud( $image ) {
|
||||
$this->debug_message( '<b>' . __METHOD__ . '()</b>' );
|
||||
return \ewww_image_optimizer_cloud_restore_single_image( $image );
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete the local backup file. Used when deleting an attachment.
|
||||
*
|
||||
* @param array $file The filename of the image for which we should remove the backup.
|
||||
*/
|
||||
public function delete_local_backup( $file ) {
|
||||
$this->debug_message( '<b>' . __METHOD__ . '()</b>' );
|
||||
if ( ! $file ) {
|
||||
return;
|
||||
}
|
||||
if ( 'local' !== $this->backup_mode ) {
|
||||
return;
|
||||
}
|
||||
$backup_file = $this->get_backup_location( $file );
|
||||
if ( ! $backup_file || $backup_file === $file ) {
|
||||
return;
|
||||
}
|
||||
\clearstatcache();
|
||||
if ( ! $this->is_file( $backup_file ) || ! \is_writable( $backup_file ) ) {
|
||||
return;
|
||||
}
|
||||
$this->delete_file( $backup_file );
|
||||
}
|
||||
|
||||
/**
|
||||
* Restore an attachment from the API or local backups.
|
||||
*
|
||||
* @global object $wpdb
|
||||
* @global object $ewwwdb A clone of $wpdb unless it is lacking utf8 connectivity.
|
||||
*
|
||||
* @param int $id The attachment id number.
|
||||
* @param string $gallery Optional. The gallery from whence we came. Default 'media'.
|
||||
* @param array $meta Optional. The image metadata from the postmeta table.
|
||||
* @return array The altered meta (if size differs), or the original value passed along.
|
||||
*/
|
||||
public function restore_backup_from_meta_data( $id, $gallery = 'media', $meta = array() ) {
|
||||
$this->debug_message( '<b>' . __METHOD__ . '()</b>' );
|
||||
global $wpdb;
|
||||
if ( \strpos( $wpdb->charset, 'utf8' ) === false ) {
|
||||
\ewww_image_optimizer_db_init();
|
||||
global $ewwwdb;
|
||||
} else {
|
||||
$ewwwdb = $wpdb;
|
||||
}
|
||||
$images = $ewwwdb->get_results( "SELECT id,path,resize,backup FROM $ewwwdb->ewwwio_images WHERE attachment_id = $id AND gallery = '$gallery'", ARRAY_A );
|
||||
foreach ( $images as $image ) {
|
||||
if ( ! empty( $image['path'] ) ) {
|
||||
$image['path'] = \ewww_image_optimizer_absolutize_path( $image['path'] );
|
||||
}
|
||||
$this->restore_file( $image );
|
||||
if ( 'media' === $gallery && 'full' === $image['resize'] && ! empty( $meta['width'] ) && ! empty( $meta['height'] ) ) {
|
||||
list( $width, $height ) = \wp_getimagesize( $image['path'] );
|
||||
if ( (int) $width !== (int) $meta['width'] || (int) $height !== (int) $meta['height'] ) {
|
||||
$meta['height'] = $height;
|
||||
$meta['width'] = $width;
|
||||
}
|
||||
}
|
||||
}
|
||||
if ( 'media' === $gallery ) {
|
||||
\remove_filter( 'wp_update_attachment_metadata', 'ewww_image_optimizer_update_filesize_metadata', 9 );
|
||||
$meta = \ewww_image_optimizer_update_filesize_metadata( $meta, $id );
|
||||
}
|
||||
if ( $this->s3_uploads_enabled() ) {
|
||||
\ewww_image_optimizer_remote_push( $meta, $id );
|
||||
$this->debug_message( 're-uploading to S3(_Uploads)' );
|
||||
}
|
||||
return $meta;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle the AJAX call for a single image restore.
|
||||
*/
|
||||
public function restore_single_image_handler() {
|
||||
$this->debug_message( '<b>' . __METHOD__ . '()</b>' );
|
||||
// Check permissions of current user.
|
||||
$permissions = \apply_filters( 'ewww_image_optimizer_manual_permissions', '' );
|
||||
if ( ! \current_user_can( $permissions ) ) {
|
||||
// Display error message if insufficient permissions.
|
||||
$this->ob_clean();
|
||||
\wp_die( \wp_json_encode( array( 'error' => \esc_html__( 'You do not have permission to optimize images.', 'ewww-image-optimizer' ) ) ) );
|
||||
}
|
||||
// Make sure we didn't accidentally get to this page without an attachment to work on.
|
||||
if ( empty( $_REQUEST['ewww_image_id'] ) ) {
|
||||
// Display an error message since we don't have anything to work on.
|
||||
$this->ob_clean();
|
||||
\wp_die( \wp_json_encode( array( 'error' => \esc_html__( 'No image ID was provided.', 'ewww-image-optimizer' ) ) ) );
|
||||
}
|
||||
if ( empty( $_REQUEST['ewww_wpnonce'] ) || ! \wp_verify_nonce( \sanitize_key( $_REQUEST['ewww_wpnonce'] ), 'ewww-image-optimizer-tools' ) ) {
|
||||
$this->ob_clean();
|
||||
\wp_die( \wp_json_encode( array( 'error' => \esc_html__( 'Access token has expired, please reload the page.', 'ewww-image-optimizer' ) ) ) );
|
||||
}
|
||||
\session_write_close();
|
||||
$image = (int) $_REQUEST['ewww_image_id'];
|
||||
$this->debug_message( "attempting restore for $image" );
|
||||
if ( $this->restore_file( $image ) ) {
|
||||
$this->ob_clean();
|
||||
\wp_die( \wp_json_encode( array( 'success' => 1 ) ) );
|
||||
}
|
||||
$this->ob_clean();
|
||||
\wp_die( \wp_json_encode( array( 'error' => \esc_html__( 'Unable to restore image.', 'ewww-image-optimizer' ) ) ) );
|
||||
}
|
||||
}
|
||||
|
||||
global $eio_backup;
|
||||
$eio_backup = new Backup();
|
1595
wp-content/plugins/ewww-image-optimizer/classes/class-base.php
Normal file
@ -0,0 +1,859 @@
|
||||
<?php
|
||||
/**
|
||||
* Class and methods to integrate EWWW IO and GRAND FlaGallery.
|
||||
*
|
||||
* @link https://ewww.io
|
||||
* @package EWWW_Image_Optimizer
|
||||
*/
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit;
|
||||
}
|
||||
|
||||
// TODO: may be able to make things more efficient by not getting a new flagMeta, but get a new flagImage instead, but still probably need it to migrate data to ewwwio_images.
|
||||
if ( ! class_exists( 'EWWW_Flag' ) ) {
|
||||
/**
|
||||
* Allows EWWW to integrate with the GRAND FlaGallery plugin.
|
||||
*
|
||||
* Adds automatic optimization on upload, a bulk optimizer, and compression details when
|
||||
* managing galleries.
|
||||
*/
|
||||
class EWWW_Flag {
|
||||
/**
|
||||
* Initializes the flagallery integration.
|
||||
*/
|
||||
public function __construct() {
|
||||
add_filter( 'flag_manage_images_columns', array( $this, 'ewww_manage_images_columns' ) );
|
||||
add_action( 'flag_manage_gallery_custom_column', array( $this, 'ewww_manage_image_custom_column' ), 10, 2 );
|
||||
add_action( 'admin_enqueue_scripts', array( $this, 'ewww_flag_manual_actions_script' ), 21 );
|
||||
if ( current_user_can( apply_filters( 'ewww_image_optimizer_bulk_permissions', '' ) ) ) {
|
||||
add_action( 'flag_manage_images_bulkaction', array( $this, 'ewww_manage_images_bulkaction' ) );
|
||||
add_action( 'flag_manage_galleries_bulkaction', array( $this, 'ewww_manage_galleries_bulkaction' ) );
|
||||
add_action( 'flag_manage_post_processor_images', array( $this, 'ewww_flag_bulk' ) );
|
||||
add_action( 'flag_manage_post_processor_galleries', array( $this, 'ewww_flag_bulk' ) );
|
||||
}
|
||||
if ( ewww_image_optimizer_test_background_opt() ) {
|
||||
add_action( 'flag_image_optimized', array( $this, 'queue_new_image' ) );
|
||||
add_action( 'flag_image_resized', array( $this, 'queue_new_image' ) );
|
||||
} else {
|
||||
add_action( 'flag_image_optimized', array( $this, 'ewww_added_new_image_slow' ) );
|
||||
add_action( 'flag_image_resized', array( $this, 'ewww_added_new_image_slow' ) );
|
||||
}
|
||||
// To prevent webview from being prematurely optimized.
|
||||
add_action( 'flag_thumbnail_created', array( $this, 'ewww_remove_image_editor' ) );
|
||||
add_action( 'wp_ajax_ewww_flag_manual', array( $this, 'ewww_flag_manual' ) );
|
||||
add_action( 'wp_ajax_ewww_flag_image_restore', array( $this, 'ewww_flag_image_restore' ) );
|
||||
add_action( 'admin_action_ewww_flag_manual', array( $this, 'ewww_flag_manual' ) );
|
||||
add_action( 'admin_menu', array( $this, 'ewww_flag_bulk_menu' ) );
|
||||
add_action( 'admin_enqueue_scripts', array( $this, 'ewww_flag_bulk_script' ), PHP_INT_MAX );
|
||||
add_action( 'wp_ajax_bulk_flag_init', array( $this, 'ewww_flag_bulk_init' ) );
|
||||
add_action( 'wp_ajax_bulk_flag_filename', array( $this, 'ewww_flag_bulk_filename' ) );
|
||||
add_action( 'wp_ajax_bulk_flag_loop', array( $this, 'ewww_flag_bulk_loop' ) );
|
||||
add_action( 'wp_ajax_bulk_flag_cleanup', array( $this, 'ewww_flag_bulk_cleanup' ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds the Bulk Optimize page to the menu.
|
||||
*/
|
||||
public function ewww_flag_bulk_menu() {
|
||||
add_submenu_page( 'flag-overview', esc_html__( 'Bulk Optimize', 'ewww-image-optimizer' ), esc_html__( 'Bulk Optimize', 'ewww-image-optimizer' ), 'FlAG Manage gallery', 'flag-bulk-optimize', array( &$this, 'ewww_flag_bulk' ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Add bulk optimize action to image management page.
|
||||
*/
|
||||
public function ewww_manage_images_bulkaction() {
|
||||
echo '<option value="bulk_optimize_images">' . esc_html__( 'Bulk Optimize', 'ewww-image-optimizer' ) . '</option>';
|
||||
}
|
||||
|
||||
/**
|
||||
* Add bulk optimize action to gallery management page.
|
||||
*/
|
||||
public function ewww_manage_galleries_bulkaction() {
|
||||
echo '<option value="bulk_optimize_galleries">' . esc_html__( 'Bulk Optimize', 'ewww-image-optimizer' ) . '</option>';
|
||||
}
|
||||
|
||||
/**
|
||||
* Displays the bulk optimiizer html output.
|
||||
*/
|
||||
public function ewww_flag_bulk() {
|
||||
ewwwio_debug_message( '<b>' . __METHOD__ . '()</b>' );
|
||||
// If there is POST data, make sure bulkaction and doaction are the values we want.
|
||||
if ( ! empty( $_POST ) && empty( $_REQUEST['ewww_reset'] ) ) {
|
||||
if (
|
||||
empty( $_REQUEST['_wpnonce'] ) ||
|
||||
(
|
||||
! wp_verify_nonce( sanitize_key( $_REQUEST['_wpnonce'] ), 'flag_bulkgallery' ) &&
|
||||
! wp_verify_nonce( sanitize_key( $_REQUEST['_wpnonce'] ), 'flag_updategallery' )
|
||||
)
|
||||
) {
|
||||
wp_die( esc_html__( 'Access denied.', 'ewww-image-optimizer' ) );
|
||||
}
|
||||
// If there is no requested bulk action, do nothing.
|
||||
if ( empty( $_REQUEST['bulkaction'] ) ) {
|
||||
return;
|
||||
}
|
||||
// If there is no media to optimize, do nothing.
|
||||
if ( empty( $_REQUEST['doaction'] ) || ! is_array( $_REQUEST['doaction'] ) ) {
|
||||
return;
|
||||
}
|
||||
if ( ! preg_match( '/^bulk_optimize/', sanitize_key( $_REQUEST['bulkaction'] ) ) ) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
list( $fullsize_count, $resize_count ) = ewww_image_optimizer_count_optimized( 'flag' );
|
||||
// Bail-out if there aren't any images to optimize.
|
||||
if ( $fullsize_count < 1 ) {
|
||||
echo '<p>' . esc_html__( 'You do not appear to have uploaded any images yet.', 'ewww-image-optimizer' ) . '</p>';
|
||||
return;
|
||||
}
|
||||
?>
|
||||
<div class="wrap"><h1>GRAND FlAGallery <?php esc_html_e( 'Bulk Optimize', 'ewww-image-optimizer' ); ?></h1>
|
||||
<?php
|
||||
if ( ewww_image_optimizer_get_option( 'ewww_image_optimizer_cloud_key' ) ) {
|
||||
ewww_image_optimizer_cloud_verify( ewww_image_optimizer_get_option( 'ewww_image_optimizer_cloud_key' ) );
|
||||
echo '<a id="ewww-bulk-credits-available" target="_blank" class="page-title-action" style="float:right;" href="https://ewww.io/my-account/">' . esc_html__( 'Image credits available:', 'ewww-image-optimizer' ) . ' ' . esc_html( ewww_image_optimizer_cloud_quota() ) . '</a>';
|
||||
}
|
||||
if ( ! ewww_image_optimizer_get_option( 'ewww_image_optimizer_backup_files' ) ) {
|
||||
echo '<div id="ewww-bulk-warning" class="ewww-bulk-info notice notice-warning"><p>' . esc_html__( 'Bulk Optimization will alter your original images and cannot be undone. Please be sure you have a backup of your images before proceeding.', 'ewww-image-optimizer' ) . '</p></div>';
|
||||
}
|
||||
// Retrieve the value of the 'bulk resume' option and set the button text for the form to use.
|
||||
$resume = get_option( 'ewww_image_optimizer_bulk_flag_resume' );
|
||||
if ( empty( $resume ) ) {
|
||||
$button_text = __( 'Start optimizing', 'ewww-image-optimizer' );
|
||||
} else {
|
||||
$button_text = __( 'Resume previous optimization', 'ewww-image-optimizer' );
|
||||
}
|
||||
$delay = ewww_image_optimizer_get_option( 'ewww_image_optimizer_delay' ) ? ewww_image_optimizer_get_option( 'ewww_image_optimizer_delay' ) : 0;
|
||||
/* translators: 1-4: number(s) of images */
|
||||
$selected_images_text = sprintf( __( '%1$d images have been selected, with %2$d resized versions.', 'ewww-image-optimizer' ), $fullsize_count, $resize_count );
|
||||
?>
|
||||
<div id="ewww-bulk-loading"></div>
|
||||
<div id="ewww-bulk-progressbar"></div>
|
||||
<div id="ewww-bulk-counter"></div>
|
||||
<form id="ewww-bulk-stop" style="display:none;" method="post" action="">
|
||||
<br /><input type="submit" class="button-secondary action" value="<?php esc_attr_e( 'Stop Optimizing', 'ewww-image-optimizer' ); ?>" />
|
||||
</form>
|
||||
<div id="ewww-bulk-widgets" class="metabox-holder" style="display:none">
|
||||
<div class="meta-box-sortables">
|
||||
<div id="ewww-bulk-last" class="postbox">
|
||||
<button type="button" class="ewww-handlediv button-link" aria-expanded="true">
|
||||
<span class="screen-reader-text"><?php esc_html_e( 'Click to toggle', 'ewww-image-optimizer' ); ?></span>
|
||||
<span class="toggle-indicator" aria-hidden="true"></span>
|
||||
</button>
|
||||
<h2 class="ewww-hndle"><span><?php esc_html_e( 'Last Image Optimized', 'ewww-image-optimizer' ); ?></span></h2>
|
||||
<div class="inside"></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="meta-box-sortables">
|
||||
<div id="ewww-bulk-status" class="postbox">
|
||||
<button type="button" class="ewww-handlediv button-link" aria-expanded="true">
|
||||
<span class="screen-reader-text"><?php esc_html_e( 'Click to toggle', 'ewww-image-optimizer' ); ?></span>
|
||||
<span class="toggle-indicator" aria-hidden="true"></span>
|
||||
</button>
|
||||
<h2 class="ewww-hndle"><span><?php esc_html_e( 'Optimization Log', 'ewww-image-optimizer' ); ?></span></h2>
|
||||
<div class="inside"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<form id="ewww-bulk-controls" class="ewww-bulk-form">
|
||||
<p><label for="ewww-force" style="font-weight: bold"><?php esc_html_e( 'Force re-optimize', 'ewww-image-optimizer' ); ?></label><?php ewwwio_help_link( 'https://docs.ewww.io/article/65-force-re-optimization', '5bb640a7042863158cc711cd' ); ?>
|
||||
 <input type="checkbox" idp="ewww-force" name="ewww-force">
|
||||
<?php esc_html_e( 'Previously optimized images will be skipped by default, check this box before scanning to override.', 'ewww-image-optimizer' ); ?>
|
||||
<a href="tools.php?page=ewww-image-optimizer-tools"><?php esc_html_e( 'View optimization history.', 'ewww-image-optimizer' ); ?></a>
|
||||
</p>
|
||||
<p>
|
||||
<label for="ewww-delay" style="font-weight: bold"><?php esc_html_e( 'Pause between images', 'ewww-image-optimizer' ); ?></label> <input type="text" id="ewww-delay" name="ewww-delay" value="<?php echo (int) $delay; ?>"> <?php esc_html_e( 'in seconds, 0 = disabled', 'ewww-image-optimizer' ); ?>
|
||||
</p>
|
||||
<div id="ewww-delay-slider"></div>
|
||||
</form>
|
||||
<div id="ewww-bulk-forms" style="float:none;">
|
||||
<p class="ewww-bulk-info"><?php echo esc_html( $selected_images_text ); ?></p>
|
||||
<form id="ewww-bulk-start" class="ewww-bulk-form" method="post" action="">
|
||||
<input type="submit" class="button-primary action" value="<?php echo esc_attr( $button_text ); ?>" />
|
||||
</form>
|
||||
<?php
|
||||
// If there was a previous operation, offer the option to reset the option in the db.
|
||||
if ( ! empty( $resume ) ) :
|
||||
?>
|
||||
<p class="ewww-bulk-info" style="margin-top:3em;"><?php esc_html_e( 'Would you like clear the queue and start over?', 'ewww-image-optimizer' ); ?></p>
|
||||
<form method="post" class="ewww-bulk-form" action="">
|
||||
<?php wp_nonce_field( 'ewww-image-optimizer-bulk', 'ewww_wpnonce' ); ?>
|
||||
<input type="hidden" name="ewww_reset" value="1">
|
||||
<button id="bulk-reset" type="submit" class="button-secondary action"><?php esc_html_e( 'Clear Queue', 'ewww-image-optimizer' ); ?></button>
|
||||
</form>
|
||||
<?php
|
||||
endif;
|
||||
echo '</div></div>';
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks the hook suffix to see if this is the individual gallery management page.
|
||||
*
|
||||
* @param string $hook The hook suffix of the page.
|
||||
* @returns boolean True for the gallery page, false anywhere else.
|
||||
*/
|
||||
public function is_gallery_page( $hook ) {
|
||||
if ( 'flagallery_page_flag-manage-gallery' === $hook ) {
|
||||
return true;
|
||||
}
|
||||
if ( false !== strpos( $hook, 'page_flag-manage-gallery' ) ) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks the hook suffix to see if this is the bulk optimize page.
|
||||
*
|
||||
* @param string $hook The hook suffix of the page.
|
||||
* @returns boolean True for the bulk page, false anywhere else.
|
||||
*/
|
||||
public function is_bulk_page( $hook ) {
|
||||
if ( 'flagallery_page_flag-bulk-optimize' === $hook ) {
|
||||
return true;
|
||||
}
|
||||
if ( false !== strpos( $hook, 'page_flag-bulk-optimize' ) ) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepares the bulk operation and includes the necessary javascript files.
|
||||
*
|
||||
* @global object $flagdb
|
||||
* @global object $wpdb
|
||||
*
|
||||
* @param string $hook The hook value for the current page.
|
||||
*/
|
||||
public function ewww_flag_bulk_script( $hook ) {
|
||||
ewwwio_debug_message( '<b>' . __METHOD__ . '()</b>' );
|
||||
// Make sure we are being hooked from a valid location.
|
||||
if ( ! $this->is_bulk_page( $hook ) && ! $this->is_gallery_page( $hook ) ) {
|
||||
return;
|
||||
}
|
||||
$nonce_verified = false;
|
||||
if ( ! empty( $_REQUEST['_wpnonce'] ) && wp_verify_nonce( sanitize_key( $_REQUEST['_wpnonce'] ), 'flag_bulkgallery' ) ) {
|
||||
$nonce_verified = true;
|
||||
}
|
||||
if ( ! empty( $_REQUEST['_wpnonce'] ) && wp_verify_nonce( sanitize_key( $_REQUEST['_wpnonce'] ), 'flag_updategallery' ) ) {
|
||||
$nonce_verified = true;
|
||||
}
|
||||
// If there is no requested bulk action, do nothing.
|
||||
if ( $this->is_gallery_page( $hook ) && ( empty( $_REQUEST['bulkaction'] ) || false === strpos( sanitize_key( $_REQUEST['bulkaction'] ), 'bulk_optimize' ) ) ) {
|
||||
return;
|
||||
}
|
||||
// If there is no media to optimize, do nothing.
|
||||
if ( $this->is_gallery_page( $hook ) && ( empty( $_REQUEST['doaction'] ) || ! is_array( $_REQUEST['doaction'] ) ) ) {
|
||||
return;
|
||||
}
|
||||
$ids = null;
|
||||
// Reset the resume flag if the user requested it.
|
||||
if ( ! empty( $_REQUEST['ewww_reset'] ) ) {
|
||||
update_option( 'ewww_image_optimizer_bulk_flag_resume', '' );
|
||||
}
|
||||
// Get the resume flag from the db.
|
||||
$resume = get_option( 'ewww_image_optimizer_bulk_flag_resume' );
|
||||
// Check if we are being asked to optimize galleries or images rather than a full bulk optimize.
|
||||
if ( ! empty( $_REQUEST['doaction'] ) ) {
|
||||
ewwwio_debug_message( 'possible batch image request' );
|
||||
// See if the bulk operation requested is from the manage images page.
|
||||
if ( ! empty( $_REQUEST['page'] ) ) {
|
||||
ewwwio_debug_message( sanitize_key( $_REQUEST['page'] ) );
|
||||
}
|
||||
if ( ! empty( $_REQUEST['page'] ) && 'flag-manage-gallery' === $_REQUEST['page'] && ! empty( $_REQUEST['bulkaction'] ) && 'bulk_optimize_images' === $_REQUEST['bulkaction'] ) {
|
||||
// Check the referring page and nonce.
|
||||
check_admin_referer( 'flag_updategallery' );
|
||||
// We don't allow previous operations to resume if the user is asking to optimize specific images.
|
||||
update_option( 'ewww_image_optimizer_bulk_flag_resume', '' );
|
||||
// Retrieve the image IDs from POST.
|
||||
$ids = array_map( 'intval', $_REQUEST['doaction'] );
|
||||
ewwwio_debug_message( 'batch image request from image list' );
|
||||
}
|
||||
// See if the bulk operation requested is from the manage galleries page.
|
||||
if ( ! empty( $_REQUEST['page'] ) && 'flag-manage-gallery' === $_REQUEST['page'] && ! empty( $_REQUEST['bulkaction'] ) && 'bulk_optimize_galleries' === $_REQUEST['bulkaction'] ) {
|
||||
// Check the referring page and nonce.
|
||||
check_admin_referer( 'flag_bulkgallery' );
|
||||
global $flagdb;
|
||||
// We don't allow previous operations to resume if the user is asking to optimize specific galleries.
|
||||
update_option( 'ewww_image_optimizer_bulk_flag_resume', '' );
|
||||
$ids = array();
|
||||
$gids = array_map( 'intval', $_REQUEST['doaction'] );
|
||||
// For each gallery ID, retrieve the image IDs within.
|
||||
foreach ( $gids as $gid ) {
|
||||
$gallery_list = $flagdb->get_gallery( $gid );
|
||||
// For each image ID found, put it onto the $ids array.
|
||||
foreach ( $gallery_list as $image ) {
|
||||
$ids[] = $image->pid;
|
||||
}
|
||||
}
|
||||
ewwwio_debug_message( 'batch image request from gallery list' );
|
||||
}
|
||||
} elseif ( ! empty( $resume ) ) {
|
||||
// If there is an operation to resume, get those IDs from the db.
|
||||
$ids = get_option( 'ewww_image_optimizer_bulk_flag_attachments' );
|
||||
} elseif ( $this->is_bulk_page( $hook ) ) {
|
||||
// Otherwise, if we are on the main bulk optimize page, just get all the IDs available.
|
||||
global $wpdb;
|
||||
$ids = $wpdb->get_col( "SELECT pid FROM $wpdb->flagpictures ORDER BY sortorder ASC" );
|
||||
} // End if().
|
||||
// Store the IDs to optimize in the options table of the db.
|
||||
update_option( 'ewww_image_optimizer_bulk_flag_attachments', $ids );
|
||||
// Add the EWWW IO javascript.
|
||||
wp_enqueue_script( 'ewwwbulkscript', plugins_url( '/includes/eio-bulk.js', EWWW_IMAGE_OPTIMIZER_PLUGIN_FILE ), array( 'jquery', 'jquery-ui-progressbar', 'jquery-ui-slider', 'postbox', 'dashboard' ), EWWW_IMAGE_OPTIMIZER_VERSION );
|
||||
// Add the styling for the progressbar.
|
||||
wp_enqueue_style( 'jquery-ui-progressbar', plugins_url( '/includes/jquery-ui-1.10.1.custom.css', EWWW_IMAGE_OPTIMIZER_PLUGIN_FILE ) );
|
||||
// Prepare a few variables to be used by the javascript code.
|
||||
wp_localize_script(
|
||||
'ewwwbulkscript',
|
||||
'ewww_vars',
|
||||
array(
|
||||
'_wpnonce' => wp_create_nonce( 'ewww-image-optimizer-bulk' ),
|
||||
'gallery' => 'flag',
|
||||
'attachments' => count( $ids ),
|
||||
'scan_fail' => esc_html__( 'Operation timed out, you may need to increase the max_execution_time for PHP', 'ewww-image-optimizer' ),
|
||||
'operation_stopped' => esc_html__( 'Optimization stopped, reload page to resume.', 'ewww-image-optimizer' ),
|
||||
'operation_interrupted' => esc_html__( 'Operation Interrupted', 'ewww-image-optimizer' ),
|
||||
'temporary_failure' => esc_html__( 'Temporary failure, seconds left to retry:', 'ewww-image-optimizer' ),
|
||||
'remove_failed' => esc_html__( 'Could not remove image from table.', 'ewww-image-optimizer' ),
|
||||
'optimized' => esc_html__( 'Optimized', 'ewww-image-optimizer' ),
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a newly uploaded image to the background queue.
|
||||
*
|
||||
* @param object $image A Flag_Image object for the new upload.
|
||||
*/
|
||||
public function queue_new_image( $image ) {
|
||||
ewwwio_debug_message( '<b>' . __METHOD__ . '()</b>' );
|
||||
$image_id = $image->pid;
|
||||
ewwwio_debug_message( "optimization (flagallery) queued for $image_id" );
|
||||
ewwwio()->background_flag->push_to_queue( array( 'id' => $image_id ) );
|
||||
ewwwio()->background_flag->dispatch();
|
||||
}
|
||||
|
||||
/**
|
||||
* Optimizes newly uploaded images from the queue.
|
||||
*
|
||||
* @param int $id The ID number for the new image.
|
||||
* @param object $image A Flag_Image object for the new upload.
|
||||
*/
|
||||
public function ewww_added_new_image( $id, $image ) {
|
||||
ewwwio_debug_message( '<b>' . __METHOD__ . '()</b>' );
|
||||
global $ewww_defer;
|
||||
global $ewww_image;
|
||||
// Make sure the image path is set.
|
||||
if ( ! isset( $image->image->imagePath ) ) {
|
||||
return;
|
||||
}
|
||||
$ewww_image = new EWWW_Image( $id, 'flag', $image->image->imagePath );
|
||||
$ewww_image->resize = 'full';
|
||||
// Optimize the full size.
|
||||
$res = ewww_image_optimizer( $image->image->imagePath, 3, false, false, true );
|
||||
$ewww_image = new EWWW_Image( $id, 'flag', $image->image->webimagePath );
|
||||
$ewww_image->resize = 'webview';
|
||||
// Optimize the web optimized version.
|
||||
$wres = ewww_image_optimizer( $image->image->webimagePath, 3, false, true );
|
||||
$ewww_image = new EWWW_Image( $id, 'flag', $image->image->thumbPath );
|
||||
$ewww_image->resize = 'thumbnail';
|
||||
// Optimize the thumbnail.
|
||||
$tres = ewww_image_optimizer( $image->image->thumbPath, 3, false, true );
|
||||
}
|
||||
|
||||
/**
|
||||
* Optimizes newly uploaded images immediately on upload (no background opt).
|
||||
*
|
||||
* @param object $image A Flag_Image object for the new upload.
|
||||
*/
|
||||
public function ewww_added_new_image_slow( $image ) {
|
||||
ewwwio_debug_message( '<b>' . __METHOD__ . '()</b>' );
|
||||
// Make sure the image path is set.
|
||||
if ( isset( $image->imagePath ) ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
|
||||
global $ewww_image;
|
||||
$ewww_image = new EWWW_Image( $image->pid, 'flag', $image->imagePath ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
|
||||
$ewww_image->resize = 'full';
|
||||
// Optimize the full size.
|
||||
$res = ewww_image_optimizer( $image->imagePath, 3, false, false, true ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
|
||||
$ewww_image = new EWWW_Image( $image->pid, 'flag', $image->webimagePath ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
|
||||
$ewww_image->resize = 'webview';
|
||||
// Optimize the web optimized version.
|
||||
$wres = ewww_image_optimizer( $image->webimagePath, 3, false, true ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
|
||||
$ewww_image = new EWWW_Image( $image->pid, 'flag', $image->thumbPath ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
|
||||
$ewww_image->resize = 'thumbnail';
|
||||
// Optimize the thumbnail.
|
||||
$tres = ewww_image_optimizer( $image->thumbPath, 3, false, true ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
|
||||
if ( ! class_exists( 'flagMeta' ) ) {
|
||||
require_once FLAG_ABSPATH . 'lib/meta.php';
|
||||
}
|
||||
// Retrieve the metadata for the image ID.
|
||||
$pid = $image->pid;
|
||||
$meta = new flagMeta( $pid );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove the image editor filter during upload, and add a new filter that will restore it later.
|
||||
*/
|
||||
public function ewww_remove_image_editor() {
|
||||
global $ewww_preempt_editor;
|
||||
$ewww_preempt_editor = true;
|
||||
/* remove_filter( 'wp_image_editors', 'ewww_image_optimizer_load_editor', 60 ); */
|
||||
add_action( 'flag_image_optimized', 'ewww_image_optimizer_restore_editor_hooks' );
|
||||
}
|
||||
|
||||
/**
|
||||
* Manually process an image from the gallery.
|
||||
*/
|
||||
public function ewww_flag_manual() {
|
||||
ewwwio_debug_message( '<b>' . __METHOD__ . '()</b>' );
|
||||
// Make sure the current user has appropriate permissions.
|
||||
$permissions = apply_filters( 'ewww_image_optimizer_manual_permissions', '' );
|
||||
if ( false === current_user_can( $permissions ) ) {
|
||||
if ( ! wp_doing_ajax() ) {
|
||||
wp_die( esc_html__( 'You do not have permission to optimize images.', 'ewww-image-optimizer' ) );
|
||||
}
|
||||
ewwwio_ob_clean();
|
||||
wp_die( wp_json_encode( array( 'error' => esc_html__( 'You do not have permission to optimize images.', 'ewww-image-optimizer' ) ) ) );
|
||||
}
|
||||
// Make sure we have an attachment ID.
|
||||
if ( empty( $_REQUEST['ewww_attachment_ID'] ) ) {
|
||||
if ( ! wp_doing_ajax() ) {
|
||||
wp_die( esc_html__( 'No attachment ID was provided.', 'ewww-image-optimizer' ) );
|
||||
}
|
||||
ewwwio_ob_clean();
|
||||
wp_die( wp_json_encode( array( 'error' => esc_html__( 'No attachment ID was provided.', 'ewww-image-optimizer' ) ) ) );
|
||||
}
|
||||
$id = intval( $_REQUEST['ewww_attachment_ID'] );
|
||||
if ( empty( $_REQUEST['ewww_manual_nonce'] ) || ! wp_verify_nonce( sanitize_key( $_REQUEST['ewww_manual_nonce'] ), "ewww-manual-$id" ) ) {
|
||||
if ( ! wp_doing_ajax() ) {
|
||||
wp_die( esc_html__( 'Access denied.', 'ewww-image-optimizer' ) );
|
||||
}
|
||||
ewwwio_ob_clean();
|
||||
wp_die( wp_json_encode( array( 'error' => esc_html__( 'Access denied.', 'ewww-image-optimizer' ) ) ) );
|
||||
}
|
||||
global $ewww_image;
|
||||
global $ewww_force;
|
||||
$ewww_force = ! empty( $_REQUEST['ewww_force'] ) ? true : false;
|
||||
if ( ! class_exists( 'flagMeta' ) ) {
|
||||
require_once FLAG_ABSPATH . 'lib/meta.php';
|
||||
}
|
||||
// Retrieve the metadata for the image ID.
|
||||
$meta = new flagMeta( $id );
|
||||
// Determine the path of the image.
|
||||
$file_path = $meta->image->imagePath;
|
||||
$ewww_image = new EWWW_Image( $id, 'flag', $file_path );
|
||||
$ewww_image->resize = 'full';
|
||||
// Optimize the full size.
|
||||
$res = ewww_image_optimizer( $file_path, 3, false, false, true );
|
||||
if ( ! empty( $meta->image->meta_data['webview'] ) ) {
|
||||
// Determine path of the webview.
|
||||
$web_path = $meta->image->webimagePath;
|
||||
$ewww_image = new EWWW_Image( $id, 'flag', $web_path );
|
||||
$ewww_image->resize = 'webview';
|
||||
$wres = ewww_image_optimizer( $web_path, 3, false, true );
|
||||
}
|
||||
// Determine the path of the thumbnail.
|
||||
$thumb_path = $meta->image->thumbPath;
|
||||
$ewww_image = new EWWW_Image( $id, 'flag', $thumb_path );
|
||||
$ewww_image->resize = 'thumbnail';
|
||||
// Optimize the thumbnail.
|
||||
$tres = ewww_image_optimizer( $thumb_path, 3, false, true );
|
||||
if ( ! wp_doing_ajax() ) {
|
||||
// Get the referring page...
|
||||
$sendback = wp_get_referer();
|
||||
// Send the user back where they came from.
|
||||
wp_safe_redirect( $sendback );
|
||||
die;
|
||||
}
|
||||
$success = $this->ewww_manage_image_custom_column_capture( $id );
|
||||
ewwwio_ob_clean();
|
||||
wp_die( wp_json_encode( array( 'success' => $success ) ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Restore an image from the API.
|
||||
*/
|
||||
public function ewww_flag_image_restore() {
|
||||
ewwwio_debug_message( '<b>' . __METHOD__ . '()</b>' );
|
||||
// Check permission of current user.
|
||||
$permissions = apply_filters( 'ewww_image_optimizer_manual_permissions', '' );
|
||||
if ( false === current_user_can( $permissions ) ) {
|
||||
if ( ! wp_doing_ajax() ) {
|
||||
wp_die( esc_html__( 'You do not have permission to optimize images.', 'ewww-image-optimizer' ) );
|
||||
}
|
||||
ewwwio_ob_clean();
|
||||
wp_die( wp_json_encode( array( 'error' => esc_html__( 'You do not have permission to optimize images.', 'ewww-image-optimizer' ) ) ) );
|
||||
}
|
||||
// Make sure function wasn't called without an attachment to work with.
|
||||
if ( false === isset( $_REQUEST['ewww_attachment_ID'] ) ) {
|
||||
if ( ! wp_doing_ajax() ) {
|
||||
wp_die( esc_html__( 'No attachment ID was provided.', 'ewww-image-optimizer' ) );
|
||||
}
|
||||
ewwwio_ob_clean();
|
||||
wp_die( wp_json_encode( array( 'error' => esc_html__( 'No attachment ID was provided.', 'ewww-image-optimizer' ) ) ) );
|
||||
}
|
||||
// Store the attachment $id.
|
||||
$id = intval( $_REQUEST['ewww_attachment_ID'] );
|
||||
if ( empty( $_REQUEST['ewww_manual_nonce'] ) || ! wp_verify_nonce( sanitize_key( $_REQUEST['ewww_manual_nonce'] ), "ewww-manual-$id" ) ) {
|
||||
if ( ! wp_doing_ajax() ) {
|
||||
wp_die( esc_html__( 'Access denied.', 'ewww-image-optimizer' ) );
|
||||
}
|
||||
ewwwio_ob_clean();
|
||||
wp_die( wp_json_encode( array( 'error' => esc_html__( 'Access denied.', 'ewww-image-optimizer' ) ) ) );
|
||||
}
|
||||
if ( ! class_exists( 'flagMeta' ) ) {
|
||||
require_once FLAG_ABSPATH . 'lib/meta.php';
|
||||
}
|
||||
global $eio_backup;
|
||||
$eio_backup->restore_backup_from_meta_data( $id, 'flag' );
|
||||
$success = $this->ewww_manage_image_custom_column_capture( $id );
|
||||
ewwwio_ob_clean();
|
||||
wp_die( wp_json_encode( array( 'success' => $success ) ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize the bulk operation.
|
||||
*/
|
||||
public function ewww_flag_bulk_init() {
|
||||
ewwwio_debug_message( '<b>' . __METHOD__ . '()</b>' );
|
||||
$permissions = apply_filters( 'ewww_image_optimizer_bulk_permissions', '' );
|
||||
if ( empty( $_REQUEST['ewww_wpnonce'] ) || ! wp_verify_nonce( sanitize_key( $_REQUEST['ewww_wpnonce'] ), 'ewww-image-optimizer-bulk' ) || ! current_user_can( $permissions ) ) {
|
||||
ewwwio_ob_clean();
|
||||
wp_die( esc_html__( 'Access denied.', 'ewww-image-optimizer' ) );
|
||||
}
|
||||
$output = array();
|
||||
// Set the resume flag to indicate the bulk operation is in progress.
|
||||
update_option( 'ewww_image_optimizer_bulk_flag_resume', 'true' );
|
||||
// Retrieve the list of attachments left to work on.
|
||||
$attachments = get_option( 'ewww_image_optimizer_bulk_flag_attachments' );
|
||||
if ( ! is_array( $attachments ) && ! empty( $attachments ) ) {
|
||||
$attachments = unserialize( $attachments );
|
||||
}
|
||||
if ( ! is_array( $attachments ) ) {
|
||||
$output['error'] = esc_html__( 'Error retrieving list of images' );
|
||||
ewwwio_ob_clean();
|
||||
wp_die( wp_json_encode( $output ) );
|
||||
}
|
||||
$id = array_shift( $attachments );
|
||||
$file_name = $this->ewww_flag_bulk_filename( $id );
|
||||
$loading_image = plugins_url( '/images/wpspin.gif', EWWW_IMAGE_OPTIMIZER_PLUGIN_FILE );
|
||||
// Output the initial message letting the user know we are starting.
|
||||
if ( empty( $file_name ) ) {
|
||||
$output['results'] = '<p>' . esc_html__( 'Optimizing', 'ewww-image-optimizer' ) . " <img src='$loading_image' alt='loading'/></p>";
|
||||
} else {
|
||||
$output['results'] = '<p>' . esc_html__( 'Optimizing', 'ewww-image-optimizer' ) . ' <b>' . $file_name . "</b> <img src='$loading_image' alt='loading'/></p>";
|
||||
}
|
||||
ewwwio_ob_clean();
|
||||
wp_die( wp_json_encode( $output ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the filename of the currently optimizing image.
|
||||
*
|
||||
* @param int $id The ID number for the image.
|
||||
* @return string|bool The name of the first image in the queue, or false.
|
||||
*/
|
||||
public function ewww_flag_bulk_filename( $id ) {
|
||||
ewwwio_debug_message( '<b>' . __METHOD__ . '()</b>' );
|
||||
// Need this file to work with flag meta.
|
||||
require_once FLAG_ABSPATH . 'lib/meta.php';
|
||||
// Retrieve the meta for the current ID.
|
||||
$meta = new flagMeta( $id );
|
||||
// Retrieve the filename for the current image ID.
|
||||
$file_name = esc_html( $meta->image->filename );
|
||||
if ( ! empty( $file_name ) ) {
|
||||
return $file_name;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Process each image during the bulk operation.
|
||||
*/
|
||||
public function ewww_flag_bulk_loop() {
|
||||
ewwwio_debug_message( '<b>' . __METHOD__ . '()</b>' );
|
||||
global $ewww_defer;
|
||||
$ewww_defer = false;
|
||||
$output = array();
|
||||
$permissions = apply_filters( 'ewww_image_optimizer_bulk_permissions', '' );
|
||||
if ( empty( $_REQUEST['ewww_wpnonce'] ) || ! wp_verify_nonce( sanitize_key( $_REQUEST['ewww_wpnonce'] ), 'ewww-image-optimizer-bulk' ) || ! current_user_can( $permissions ) ) {
|
||||
$output['error'] = esc_html__( 'Access token has expired, please reload the page.', 'ewww-image-optimizer' );
|
||||
ewwwio_ob_clean();
|
||||
wp_die( wp_json_encode( $output ) );
|
||||
}
|
||||
session_write_close();
|
||||
// Find out if our nonce is on it's last leg/tick.
|
||||
$tick = wp_verify_nonce( sanitize_key( $_REQUEST['ewww_wpnonce'] ), 'ewww-image-optimizer-bulk' );
|
||||
if ( 2 === $tick ) {
|
||||
$output['new_nonce'] = wp_create_nonce( 'ewww-image-optimizer-bulk' );
|
||||
} else {
|
||||
$output['new_nonce'] = '';
|
||||
}
|
||||
global $ewww_image;
|
||||
// Need this file to work with flag meta.
|
||||
require_once FLAG_ABSPATH . 'lib/meta.php';
|
||||
// Record the starting time for the current image (in microseconds).
|
||||
$started = microtime( true );
|
||||
// Retrieve the list of attachments left to work on.
|
||||
$attachments = get_option( 'ewww_image_optimizer_bulk_flag_attachments' );
|
||||
$id = array_shift( $attachments );
|
||||
// Get the image meta for the current ID.
|
||||
$meta = new flagMeta( $id );
|
||||
$file_path = $meta->image->imagePath;
|
||||
$ewww_image = new EWWW_Image( $id, 'flag', $file_path );
|
||||
$ewww_image->resize = 'full';
|
||||
// Optimize the full-size version.
|
||||
$fres = ewww_image_optimizer( $file_path, 3, false, false, true );
|
||||
if ( 'exceeded' === get_transient( 'ewww_image_optimizer_cloud_status' ) ) {
|
||||
$output['error'] = '<a href="https://ewww.io/buy-credits/" target="_blank">' . esc_html__( 'License Exceeded', 'ewww-image-optimizer' ) . '</a>';
|
||||
ewwwio_ob_clean();
|
||||
wp_die( wp_json_encode( $output ) );
|
||||
}
|
||||
if ( 'exceeded quota' === get_transient( 'ewww_image_optimizer_cloud_status' ) ) {
|
||||
$output['error'] = '<a href="https://docs.ewww.io/article/101-soft-quotas-on-unlimited-plans" target="_blank">' . esc_html__( 'Soft quota reached, contact us for more', 'ewww-image-optimizer' ) . '</a>';
|
||||
ewwwio_ob_clean();
|
||||
wp_die( wp_json_encode( $output ) );
|
||||
}
|
||||
// Let the user know what happened.
|
||||
$output['results'] = sprintf( '<p>' . esc_html__( 'Optimized image:', 'ewww-image-optimizer' ) . ' <strong>%s</strong><br>', esc_html( $meta->image->filename ) );
|
||||
/* Translators: %s: The compression results/savings */
|
||||
$output['results'] .= sprintf( esc_html__( 'Full size – %s', 'ewww-image-optimizer' ) . '<br>', esc_html( $fres[1] ) );
|
||||
if ( ! empty( $meta->image->meta_data['webview'] ) ) {
|
||||
// Determine path of the webview.
|
||||
$web_path = $meta->image->webimagePath;
|
||||
$ewww_image = new EWWW_Image( $id, 'flag', $web_path );
|
||||
$ewww_image->resize = 'webview';
|
||||
$wres = ewww_image_optimizer( $web_path, 3, false, true );
|
||||
/* Translators: %s: The compression results/savings */
|
||||
$output['results'] .= sprintf( esc_html__( 'Optimized size – %s', 'ewww-image-optimizer' ) . '<br>', esc_html( $wres[1] ) );
|
||||
}
|
||||
$thumb_path = $meta->image->thumbPath;
|
||||
$ewww_image = new EWWW_Image( $id, 'flag', $thumb_path );
|
||||
$ewww_image->resize = 'thumbnail';
|
||||
// Optimize the thumbnail.
|
||||
$tres = ewww_image_optimizer( $thumb_path, 3, false, true );
|
||||
// And let the user know the results.
|
||||
/* Translators: %s: The compression results/savings */
|
||||
$output['results'] .= sprintf( esc_html__( 'Thumbnail – %s', 'ewww-image-optimizer' ) . '<br>', esc_html( $tres[1] ) );
|
||||
// Determine how much time the image took to process.
|
||||
$elapsed = microtime( true ) - $started;
|
||||
// And output it to the user.
|
||||
/* Translators: %s: number of seconds, localized */
|
||||
$output['results'] .= sprintf( esc_html( _n( 'Elapsed: %s second', 'Elapsed: %s seconds', $elapsed, 'ewww-image-optimizer' ) ) . '</p>', number_format_i18n( $elapsed, 2 ) );
|
||||
$output['completed'] = 1;
|
||||
// Send the list back to the db.
|
||||
update_option( 'ewww_image_optimizer_bulk_flag_attachments', $attachments, false );
|
||||
if ( ! empty( $attachments ) ) {
|
||||
$next_attachment = array_shift( $attachments );
|
||||
$next_file = $this->ewww_flag_bulk_filename( $next_attachment );
|
||||
$loading_image = plugins_url( '/images/wpspin.gif', EWWW_IMAGE_OPTIMIZER_PLUGIN_FILE );
|
||||
if ( $next_file ) {
|
||||
$output['next_file'] = '<p>' . esc_html__( 'Optimizing', 'ewww-image-optimizer' ) . " <b>$next_file</b> <img src='$loading_image' alt='loading'/></p>";
|
||||
} else {
|
||||
$output['next_file'] = '<p>' . esc_html__( 'Optimizing', 'ewww-image-optimizer' ) . " <img src='$loading_image' alt='loading'/></p>";
|
||||
}
|
||||
} else {
|
||||
$output['done'] = 1;
|
||||
}
|
||||
ewwwio_ob_clean();
|
||||
wp_die( wp_json_encode( $output ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Finish the bulk operation, and clear out the bulk_flag options.
|
||||
*/
|
||||
public function ewww_flag_bulk_cleanup() {
|
||||
ewwwio_debug_message( '<b>' . __METHOD__ . '()</b>' );
|
||||
$permissions = apply_filters( 'ewww_image_optimizer_bulk_permissions', '' );
|
||||
if ( empty( $_REQUEST['ewww_wpnonce'] ) || ! wp_verify_nonce( sanitize_key( $_REQUEST['ewww_wpnonce'] ), 'ewww-image-optimizer-bulk' ) || ! current_user_can( $permissions ) ) {
|
||||
ewwwio_ob_clean();
|
||||
wp_die( esc_html__( 'Access token has expired, please reload the page.', 'ewww-image-optimizer' ) );
|
||||
}
|
||||
// Reset the bulk flags in the db.
|
||||
update_option( 'ewww_image_optimizer_bulk_flag_resume', '' );
|
||||
update_option( 'ewww_image_optimizer_bulk_flag_attachments', '', false );
|
||||
ewwwio_ob_clean();
|
||||
// And let the user know we are done.
|
||||
wp_die( '<p><b>' . esc_html__( 'Finished Optimization!', 'ewww-image-optimizer' ) . '</b></p>' );
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepare javascript for one-click actions on manage gallery page.
|
||||
*
|
||||
* @param string $hook The hook value for the current page.
|
||||
*/
|
||||
public function ewww_flag_manual_actions_script( $hook ) {
|
||||
ewwwio_debug_message( '<b>' . __METHOD__ . '()</b>' );
|
||||
if ( ! $this->is_gallery_page( $hook ) ) {
|
||||
return;
|
||||
}
|
||||
if ( ! current_user_can( apply_filters( 'ewww_image_optimizer_manual_permissions', '' ) ) ) {
|
||||
return;
|
||||
}
|
||||
add_thickbox();
|
||||
wp_enqueue_script( 'ewwwflagscript', plugins_url( '/includes/flag.js', EWWW_IMAGE_OPTIMIZER_PLUGIN_FILE ), array( 'jquery' ), EWWW_IMAGE_OPTIMIZER_VERSION );
|
||||
wp_enqueue_style( 'jquery-ui-tooltip-custom', plugins_url( '/includes/jquery-ui-1.10.1.custom.css', EWWW_IMAGE_OPTIMIZER_PLUGIN_FILE ), array(), EWWW_IMAGE_OPTIMIZER_VERSION );
|
||||
// Submit a couple variables needed for javascript functions.
|
||||
$loading_image = plugins_url( '/images/spinner.gif', EWWW_IMAGE_OPTIMIZER_PLUGIN_FILE );
|
||||
wp_localize_script(
|
||||
'ewwwflagscript',
|
||||
'ewww_vars',
|
||||
array(
|
||||
'optimizing' => '<p>' . esc_html__( 'Optimizing', 'ewww-image-optimizer' ) . " <img src='$loading_image' /></p>",
|
||||
'restoring' => '<p>' . esc_html__( 'Restoring', 'ewww-image-optimizer' ) . " <img src='$loading_image' /></p>",
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a column on the gallery display.
|
||||
*
|
||||
* @param array $columns A list of columns displayed on the manage gallery page.
|
||||
* @return array The list of columns, with EWWW's custom column added.
|
||||
*/
|
||||
public function ewww_manage_images_columns( $columns ) {
|
||||
$columns['ewww_image_optimizer'] = esc_html__( 'Image Optimizer', 'ewww-image-optimizer' );
|
||||
return $columns;
|
||||
}
|
||||
|
||||
/**
|
||||
* Output the EWWW IO information on the gallery display.
|
||||
*
|
||||
* @param string $column_name The name of the current column.
|
||||
* @param int $id The ID number of the image being displayed.
|
||||
*/
|
||||
public function ewww_manage_image_custom_column( $column_name, $id ) {
|
||||
if ( 'ewww_image_optimizer' !== $column_name ) {
|
||||
return;
|
||||
}
|
||||
ewwwio_debug_message( '<b>' . __METHOD__ . '()</b>' );
|
||||
echo '<div id="ewww-flag-status-' . (int) $id . '">';
|
||||
// Get the metadata.
|
||||
$meta = new flagMeta( $id );
|
||||
if ( ewww_image_optimizer_get_option( 'ewww_image_optimizer_debug' ) && ewww_image_optimizer_function_exists( 'print_r' ) ) {
|
||||
$print_meta = print_r( $meta->image->meta_data, true );
|
||||
echo '<button type="button" class="ewww-show-debug-meta button button-secondary" data-id="' . (int) $id . '">' .
|
||||
esc_html__( 'Show Metadata', 'ewww-image-optimizer' ) .
|
||||
'</button><div id="ewww-debug-meta-' . (int) $id .
|
||||
'" style="font-size: 10px;padding: 10px;margin:3px -10px 10px;line-height: 1.1em;display: none;">' .
|
||||
wp_kses_post( preg_replace( array( '/ /', '/\n+/' ), array( ' ', '<br />' ), $print_meta ) ) .
|
||||
'</div>';
|
||||
}
|
||||
// Get the image path from the meta.
|
||||
$file_path = $meta->image->imagePath;
|
||||
// Grab the image status from the meta.
|
||||
if ( empty( $meta->image->meta_data['ewww_image_optimizer'] ) ) {
|
||||
$status = '';
|
||||
} else {
|
||||
// Run db import here.
|
||||
if ( $file_path ) {
|
||||
ewww_image_optimizer_update_file_from_meta( $file_path, 'flag', $id, 'full' );
|
||||
}
|
||||
if ( $meta->image->webimagePath ) {
|
||||
ewww_image_optimizer_update_file_from_meta( $meta->image->webimagePath, 'flag', $id, 'webview' );
|
||||
}
|
||||
if ( $meta->image->thumbPath ) {
|
||||
ewww_image_optimizer_update_file_from_meta( $meta->image->thumbPath, 'flag', $id, 'thumbnail' );
|
||||
}
|
||||
}
|
||||
$msg = '';
|
||||
// Get the mimetype.
|
||||
$type = ewww_image_optimizer_mimetype( $file_path, 'i' );
|
||||
$valid = true;
|
||||
|
||||
if ( ! ewwwio()->tools_initialized && ! ewwwio()->local->os_supported() ) {
|
||||
ewwwio()->local->skip_tools();
|
||||
} elseif ( ! ewwwio()->tools_initialized ) {
|
||||
ewwwio()->tool_init();
|
||||
}
|
||||
$tools = ewwwio()->local->check_all_tools();
|
||||
// If we don't have a valid tool for the image type, output the appropriate message.
|
||||
switch ( $type ) {
|
||||
case 'image/jpeg':
|
||||
if ( $tools['jpegtran']['enabled'] && ! $tools['jpegtran']['path'] ) {
|
||||
/* translators: %s: name of a tool like jpegtran */
|
||||
echo '<div>' . sprintf( esc_html__( '%s is missing', 'ewww-image-optimizer' ), '<em>jpegtran</em>' ) . '</div></div>';
|
||||
return;
|
||||
}
|
||||
break;
|
||||
case 'image/png':
|
||||
if ( $tools['optipng']['enabled'] && ! $tools['optipng']['path'] ) {
|
||||
/* translators: %s: name of a tool like jpegtran */
|
||||
echo '<div>' . sprintf( esc_html__( '%s is missing', 'ewww-image-optimizer' ), '<em>optipng</em>' ) . '</div></div>';
|
||||
return;
|
||||
}
|
||||
if ( $tools['pngout']['enabled'] && ! $tools['pngout']['path'] ) {
|
||||
/* translators: %s: name of a tool like jpegtran */
|
||||
echo '<div>' . sprintf( esc_html__( '%s is missing', 'ewww-image-optimizer' ), '<em>pngout</em>' ) . '</div></div>';
|
||||
return;
|
||||
}
|
||||
break;
|
||||
case 'image/gif':
|
||||
if ( $tools['gifsicle']['enabled'] && ! $tools['gifsicle']['path'] ) {
|
||||
/* translators: %s: name of a tool like jpegtran */
|
||||
echo '<div>' . sprintf( esc_html__( '%s is missing', 'ewww-image-optimizer' ), '<em>gifsicle</em>' ) . '</div></div>';
|
||||
return;
|
||||
}
|
||||
break;
|
||||
default:
|
||||
echo '<div>' . esc_html__( 'Unsupported file type', 'ewww-image-optimizer' ) . '</div></div>';
|
||||
return;
|
||||
}
|
||||
$backup_available = false;
|
||||
global $wpdb;
|
||||
$optimized_images = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM $wpdb->ewwwio_images WHERE attachment_id = %d AND gallery = 'flag' AND image_size <> 0 ORDER BY orig_size DESC", $id ), ARRAY_A );
|
||||
$ewww_manual_nonce = wp_create_nonce( 'ewww-manual-' . $id );
|
||||
if ( ! empty( $optimized_images ) ) {
|
||||
list( $detail_output, $converted, $backup_available ) = ewww_image_optimizer_custom_column_results( $id, $optimized_images );
|
||||
echo wp_kses_post( $detail_output );
|
||||
if ( current_user_can( apply_filters( 'ewww_image_optimizer_manual_permissions', '' ) ) ) {
|
||||
printf(
|
||||
'<a class="ewww-manual-optimize" data-id="%1$d" data-nonce="%2$s" href="' . esc_url( admin_url( 'admin.php?action=ewww_flag_manual' ) ) . '&ewww_manual_nonce=%2$s&ewww_force=1&ewww_attachment_ID=%1$d">%3$s</a>',
|
||||
(int) $id,
|
||||
esc_attr( $ewww_manual_nonce ),
|
||||
esc_html__( 'Re-optimize', 'ewww-image-optimizer' )
|
||||
);
|
||||
if ( $backup_available ) {
|
||||
printf(
|
||||
'<br><a class="ewww-manual-image-restore" data-id="%1$d" data-nonce="%2$s" href="' . esc_url( admin_url( 'admin.php?action=ewww_flag_image_restore' ) ) . '&ewww_manual_nonce=%2$s&ewww_attachment_ID=%1$d">%3$s</a>',
|
||||
(int) $id,
|
||||
esc_attr( $ewww_manual_nonce ),
|
||||
esc_html__( 'Restore original', 'ewww-image-optimizer' )
|
||||
);
|
||||
}
|
||||
}
|
||||
} elseif ( ewww_image_optimizer_image_is_pending( $id, 'flag-async' ) ) {
|
||||
echo '<div>' . esc_html__( 'In Progress', 'ewww-image-optimizer' ) . '</div>';
|
||||
// Otherwise, tell the user that they can optimize the image now.
|
||||
} else {
|
||||
if ( current_user_can( apply_filters( 'ewww_image_optimizer_manual_permissions', '' ) ) ) {
|
||||
printf(
|
||||
'<div><a class="ewww-manual-optimize" data-id="%1$d" data-nonce="%2$s" href="' . esc_url( admin_url( 'admin.php?action=ewww_flag_manual' ) ) . '&ewww_manual_nonce=%2$s&ewww_attachment_ID=%1$d">%3$s</a></div>',
|
||||
(int) $id,
|
||||
esc_attr( $ewww_manual_nonce ),
|
||||
esc_html__( 'Optimize now!', 'ewww-image-optimizer' )
|
||||
);
|
||||
}
|
||||
}
|
||||
echo '</div>';
|
||||
}
|
||||
|
||||
/**
|
||||
* Wrapper around the custom column display to capture and return the output, usually for AJAX.
|
||||
*
|
||||
* @param int $id The ID number of the image to display.
|
||||
*/
|
||||
public function ewww_manage_image_custom_column_capture( $id ) {
|
||||
ob_start();
|
||||
$this->ewww_manage_image_custom_column( 'ewww_image_optimizer', $id );
|
||||
return ob_get_clean();
|
||||
}
|
||||
}
|
||||
|
||||
global $ewwwflag;
|
||||
$ewwwflag = new EWWW_Flag();
|
||||
} // End if().
|
1262
wp-content/plugins/ewww-image-optimizer/classes/class-ewww-image.php
Normal file
@ -0,0 +1,701 @@
|
||||
<?php
|
||||
/**
|
||||
* Class and methods to integrate EWWW IO and Nextcellent Gallery.
|
||||
*
|
||||
* @link https://ewww.io
|
||||
* @package EWWW_Image_Optimizer
|
||||
*/
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit;
|
||||
}
|
||||
if ( ! class_exists( 'EWWW_Nextcellent' ) ) {
|
||||
/**
|
||||
* Allows EWWW to integrate with the Nextcellent Gallery plugin.
|
||||
*
|
||||
* Adds automatic optimization on upload, a bulk optimizer, and compression details when
|
||||
* managing galleries.
|
||||
*/
|
||||
class EWWW_Nextcellent {
|
||||
/**
|
||||
* Initializes the nextcellent integration functions.
|
||||
*/
|
||||
public function __construct() {
|
||||
add_filter( 'ngg_manage_images_columns', array( $this, 'ewww_manage_images_columns' ) );
|
||||
add_action( 'ngg_manage_image_custom_column', array( $this, 'ewww_manage_image_custom_column' ), 10, 2 );
|
||||
if ( ewww_image_optimizer_get_option( 'ewww_image_optimizer_background_optimization' ) ) {
|
||||
add_action( 'ngg_after_new_images_added', array( $this, 'dispatch_new_images' ), 10, 2 );
|
||||
} else {
|
||||
add_action( 'ngg_added_new_image', array( $this, 'ewww_added_new_image_slow' ) );
|
||||
}
|
||||
add_action( 'admin_enqueue_scripts', array( $this, 'ewww_ngg_manual_actions_script' ) );
|
||||
add_action( 'wp_ajax_ewww_ngg_manual', array( $this, 'ewww_ngg_manual' ) );
|
||||
add_action( 'wp_ajax_ewww_ngg_cloud_restore', array( $this, 'ewww_ngg_cloud_restore' ) );
|
||||
add_action( 'admin_action_ewww_ngg_manual', array( $this, 'ewww_ngg_manual' ) );
|
||||
add_action( 'admin_menu', array( $this, 'ewww_ngg_bulk_menu' ) );
|
||||
add_action( 'admin_enqueue_scripts', array( $this, 'ewww_ngg_bulk_script' ), 9 );
|
||||
add_action( 'wp_ajax_bulk_ngg_preview', array( $this, 'ewww_ngg_bulk_preview' ) );
|
||||
add_action( 'wp_ajax_bulk_ngg_init', array( $this, 'ewww_ngg_bulk_init' ) );
|
||||
add_action( 'wp_ajax_bulk_ngg_filename', array( $this, 'ewww_ngg_bulk_filename' ) );
|
||||
add_action( 'wp_ajax_bulk_ngg_loop', array( $this, 'ewww_ngg_bulk_loop' ) );
|
||||
add_action( 'wp_ajax_bulk_ngg_cleanup', array( $this, 'ewww_ngg_bulk_cleanup' ) );
|
||||
add_action( 'ngg_ajax_image_save', array( $this, 'ewww_ngg_image_save' ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds the Bulk Optimize page to the tools menu.
|
||||
*/
|
||||
public function ewww_ngg_bulk_menu() {
|
||||
add_submenu_page( NGGFOLDER, esc_html__( 'Bulk Optimize', 'ewww-image-optimizer' ), esc_html__( 'Bulk Optimize', 'ewww-image-optimizer' ), 'NextGEN Manage gallery', 'ewww-ngg-bulk', array( &$this, 'ewww_ngg_bulk_preview' ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a newly uploaded image to the optimization queue.
|
||||
*
|
||||
* @param int $gallery The gallery ID number (I think).
|
||||
* @param array $images The list of new images.
|
||||
*/
|
||||
public function dispatch_new_images( $gallery, $images ) {
|
||||
foreach ( $images as $id ) {
|
||||
ewwwio()->background_ngg->push_to_queue( array( 'id' => $id ) );
|
||||
ewwwio_debug_message( "optimization (nextcellent) queued for $id" );
|
||||
}
|
||||
ewwwio()->background_ngg->dispatch();
|
||||
}
|
||||
|
||||
/**
|
||||
* Optimizes a new image from the queue.
|
||||
*
|
||||
* @global object $ewww_image Contains more information about the image currently being processed.
|
||||
*
|
||||
* @param int $id The ID number of the image.
|
||||
* @param array $meta The image metadata.
|
||||
*/
|
||||
public function ewww_added_new_image( $id, $meta ) {
|
||||
global $ewww_image;
|
||||
// Retrieve the image path.
|
||||
$file_path = $meta->image->imagePath;
|
||||
$ewww_image = new EWWW_Image( $id, 'nextcell', $file_path );
|
||||
$ewww_image->resize = 'full';
|
||||
// Run the optimizer on the current image.
|
||||
$fres = ewww_image_optimizer( $file_path, 2, false, false, true );
|
||||
}
|
||||
|
||||
/**
|
||||
* Optimizes a new image in foreground mode.
|
||||
*
|
||||
* @global bool $ewww_defer Set to false to avoid deferring image optimization.
|
||||
* @global object $wpdb
|
||||
* @global object $ewww_image Contains more information about the image currently being processed.
|
||||
*
|
||||
* @param array $image The new image and all the related data.
|
||||
*/
|
||||
public function ewww_added_new_image_slow( $image ) {
|
||||
// Query the filesystem path of the gallery from the database.
|
||||
global $ewww_defer;
|
||||
global $wpdb;
|
||||
global $ewww_image;
|
||||
$gallery_path = $wpdb->get_var( $wpdb->prepare( "SELECT path FROM {$wpdb->prefix}ngg_gallery WHERE gid = %d LIMIT 1", $image['galleryID'] ) );
|
||||
// If we have a path to work with.
|
||||
if ( $gallery_path ) {
|
||||
// Construct the absolute path of the current image.
|
||||
$file_path = trailingslashit( $gallery_path ) . $image['filename'];
|
||||
$ewww_image = new EWWW_Image( $image['id'], 'nextcell', $file_path );
|
||||
$ewww_image->resize = 'full';
|
||||
// Run the optimizer on the current image.
|
||||
$res = ewww_image_optimizer( ABSPATH . $file_path, 2, false, false, true );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Optimizes the thumbnail generated for a new upload.
|
||||
*
|
||||
* @global bool $ewww_defer Set to false to avoid deferring image optimization.
|
||||
* @global object $ewww_image Contains more information about the image currently being processed.
|
||||
*
|
||||
* @param string $filename The name of the file generated.
|
||||
*/
|
||||
public function ewww_ngg_image_save( $filename ) {
|
||||
ewwwio_debug_message( '<b>' . __METHOD__ . '()</b>' );
|
||||
global $ewww_defer;
|
||||
global $ewww_image;
|
||||
ewwwio_debug_message( 'nextcellent new image thumb' );
|
||||
if ( empty( $_REQUEST['_wpnonce'] ) || ! wp_verify_nonce( sanitize_key( $_REQUEST['_wpnonce'] ), 'ngg-ajax' ) ) {
|
||||
ewwwio_debug_message( 'failed verification' );
|
||||
return;
|
||||
}
|
||||
if ( ewww_image_optimizer_get_option( 'ewww_image_optimizer_debug' ) && ewww_image_optimizer_function_exists( 'print_r' ) ) {
|
||||
ewwwio_debug_message( print_r( $_REQUEST, true ) );
|
||||
}
|
||||
if ( file_exists( $filename ) ) {
|
||||
if ( ! empty( $_POST['id'] ) ) {
|
||||
$id = (int) $_POST['id'];
|
||||
} elseif ( ! empty( $_POST['image'] ) ) {
|
||||
$id = sanitize_key( $_POST['image'] );
|
||||
}
|
||||
$ewww_image = new EWWW_Image( $id, 'nextcell', $filename );
|
||||
$ewww_image->resize = 'thumbnail';
|
||||
ewww_image_optimizer( $filename );
|
||||
}
|
||||
ewwwio_memory( __METHOD__ );
|
||||
}
|
||||
|
||||
/**
|
||||
* Manually process an image from the NextGEN Gallery.
|
||||
*/
|
||||
public function ewww_ngg_manual() {
|
||||
// Check permission of current user.
|
||||
$permissions = apply_filters( 'ewww_image_optimizer_manual_permissions', '' );
|
||||
if ( false === current_user_can( $permissions ) ) {
|
||||
if ( ! wp_doing_ajax() ) {
|
||||
wp_die( esc_html__( 'You do not have permission to optimize images.', 'ewww-image-optimizer' ) );
|
||||
}
|
||||
ewwwio_ob_clean();
|
||||
wp_die( wp_json_encode( array( 'error' => esc_html__( 'You do not have permission to optimize images.', 'ewww-image-optimizer' ) ) ) );
|
||||
}
|
||||
// Make sure function wasn't called without an attachment to work with.
|
||||
if ( empty( $_REQUEST['ewww_attachment_ID'] ) ) {
|
||||
if ( ! wp_doing_ajax() ) {
|
||||
wp_die( esc_html__( 'No attachment ID was provided.', 'ewww-image-optimizer' ) );
|
||||
}
|
||||
ewwwio_ob_clean();
|
||||
wp_die( wp_json_encode( array( 'error' => esc_html__( 'No attachment ID was provided.', 'ewww-image-optimizer' ) ) ) );
|
||||
}
|
||||
// Store the attachment $id.
|
||||
$id = intval( $_REQUEST['ewww_attachment_ID'] );
|
||||
if ( empty( $_REQUEST['ewww_manual_nonce'] ) || ! wp_verify_nonce( sanitize_key( $_REQUEST['ewww_manual_nonce'] ), "ewww-manual-$id" ) ) {
|
||||
if ( ! wp_doing_ajax() ) {
|
||||
wp_die( esc_html__( 'Access denied.', 'ewww-image-optimizer' ) );
|
||||
}
|
||||
ewwwio_ob_clean();
|
||||
wp_die( wp_json_encode( array( 'error' => esc_html__( 'Access denied.', 'ewww-image-optimizer' ) ) ) );
|
||||
}
|
||||
global $ewww_force;
|
||||
$ewww_force = ! empty( $_REQUEST['ewww_force'] ) ? true : false;
|
||||
$this->ewww_ngg_optimize( $id );
|
||||
$success = $this->ewww_manage_image_custom_column( 'ewww_image_optimizer', $id, true );
|
||||
if ( ! wp_doing_ajax() ) {
|
||||
// Get the referring page, and send the user back there.
|
||||
wp_safe_redirect( wp_get_referer() );
|
||||
die;
|
||||
}
|
||||
ewwwio_ob_clean();
|
||||
wp_die( wp_json_encode( array( 'success' => $success ) ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Restore an image from the NextGEN Gallery.
|
||||
*/
|
||||
public function ewww_ngg_cloud_restore() {
|
||||
// Check permission of current user.
|
||||
$permissions = apply_filters( 'ewww_image_optimizer_manual_permissions', '' );
|
||||
if ( false === current_user_can( $permissions ) ) {
|
||||
if ( ! wp_doing_ajax() ) {
|
||||
wp_die( esc_html__( 'You do not have permission to optimize images.', 'ewww-image-optimizer' ) );
|
||||
}
|
||||
ewwwio_ob_clean();
|
||||
wp_die( wp_json_encode( array( 'error' => esc_html__( 'You do not have permission to optimize images.', 'ewww-image-optimizer' ) ) ) );
|
||||
}
|
||||
// Make sure function wasn't called without an attachment to work with.
|
||||
if ( ! isset( $_REQUEST['ewww_attachment_ID'] ) ) {
|
||||
if ( ! wp_doing_ajax() ) {
|
||||
wp_die( esc_html__( 'No attachment ID was provided.', 'ewww-image-optimizer' ) );
|
||||
}
|
||||
ewwwio_ob_clean();
|
||||
wp_die( wp_json_encode( array( 'error' => esc_html__( 'No attachment ID was provided.', 'ewww-image-optimizer' ) ) ) );
|
||||
}
|
||||
// Sanitize the attachment $id.
|
||||
$id = (int) $_REQUEST['ewww_attachment_ID'];
|
||||
if ( empty( $_REQUEST['ewww_manual_nonce'] ) || ! wp_verify_nonce( sanitize_key( $_REQUEST['ewww_manual_nonce'] ), "ewww-manual-$id" ) ) {
|
||||
if ( ! wp_doing_ajax() ) {
|
||||
wp_die( esc_html__( 'Access denied.', 'ewww-image-optimizer' ) );
|
||||
}
|
||||
ewwwio_ob_clean();
|
||||
wp_die( wp_json_encode( array( 'error' => esc_html__( 'Access denied.', 'ewww-image-optimizer' ) ) ) );
|
||||
}
|
||||
ewww_image_optimizer_cloud_restore_from_meta_data( $id, 'nextcell' );
|
||||
$success = $this->ewww_manage_image_custom_column( 'ewww_image_optimizer', $id, true );
|
||||
ewwwio_ob_clean();
|
||||
wp_die( wp_json_encode( array( 'success' => $success ) ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Optimize a nextcellent image by ID.
|
||||
*
|
||||
* @global object $ewww_image Contains more information about the image currently being processed.
|
||||
* @global object nggdb
|
||||
*
|
||||
* @param int $id The ID number of the image.
|
||||
* @return array {
|
||||
* The optimization results for the image.
|
||||
*
|
||||
* @type array $fres The optimization results for the full-size image.
|
||||
* @type array $tres The optimization results for the thumbnail.
|
||||
* }
|
||||
*/
|
||||
public function ewww_ngg_optimize( $id ) {
|
||||
global $ewww_image;
|
||||
// Need this file to work with metadata.
|
||||
require_once WP_CONTENT_DIR . '/plugins/nextcellent-gallery-nextgen-legacy/lib/meta.php';
|
||||
// Retrieve the metadata for the image.
|
||||
$meta = new nggMeta( $id );
|
||||
// Retrieve the image path.
|
||||
$file_path = $meta->image->imagePath;
|
||||
$ewww_image = new EWWW_Image( $id, 'nextcell', $file_path );
|
||||
$ewww_image->resize = 'full';
|
||||
// Run the optimizer on the current image.
|
||||
$fres = ewww_image_optimizer( $file_path, 2, false, false, true );
|
||||
// Get the filepath of the thumbnail image.
|
||||
$thumb_path = $meta->image->thumbPath;
|
||||
$ewww_image = new EWWW_Image( $id, 'nextcell', $thumb_path );
|
||||
$ewww_image->resize = 'thumbnail';
|
||||
// Run the optimization on the thumbnail.
|
||||
$tres = ewww_image_optimizer( $thumb_path, 2, false, true );
|
||||
return array( $fres, $tres );
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds the Image Optimizer column via the ngg_manage_images_columns hook.
|
||||
*
|
||||
* @param array $columns A list of columns to display in the images table.
|
||||
* @return array The updated list of columns.
|
||||
*/
|
||||
public function ewww_manage_images_columns( $columns ) {
|
||||
$columns['ewww_image_optimizer'] = esc_html__( 'Image Optimizer', 'ewww-image-optimizer' );
|
||||
return $columns;
|
||||
}
|
||||
|
||||
/**
|
||||
* Displays the Image Optimizer data via the ngg_manage_image_custom_column hook.
|
||||
*
|
||||
* @param string $column_name The name of the current column.
|
||||
* @param int $id The ID number of the current image.
|
||||
* @param bool $return_output Return the output instead of sending it straight to the screen.
|
||||
* @return string The output when $return is true.
|
||||
*/
|
||||
public function ewww_manage_image_custom_column( $column_name, $id, $return_output = false ) {
|
||||
// Once we've found our custom column.
|
||||
if ( 'ewww_image_optimizer' === $column_name ) {
|
||||
if ( $return_output ) {
|
||||
ob_start();
|
||||
}
|
||||
// Need this file to work with metadata.
|
||||
require_once WP_CONTENT_DIR . '/plugins/nextcellent-gallery-nextgen-legacy/lib/meta.php';
|
||||
// Get the metadata for the image.
|
||||
$meta = new nggMeta( $id );
|
||||
echo '<div id="ewww-nextcellent-status-' . (int) $id . '">';
|
||||
// Get the file path of the image.
|
||||
$file_path = $meta->image->imagePath;
|
||||
// Get the mimetype of the image.
|
||||
$type = ewww_image_optimizer_quick_mimetype( $file_path, 'i' );
|
||||
|
||||
// Check to see if we have a tool to handle the mimetype detected.
|
||||
if ( ! ewwwio()->tools_initialized && ! ewwwio()->local->os_supported() ) {
|
||||
ewwwio()->local->skip_tools();
|
||||
} elseif ( ! ewwwio()->tools_initialized ) {
|
||||
ewwwio()->tool_init();
|
||||
}
|
||||
$tools = ewwwio()->local->check_all_tools();
|
||||
switch ( $type ) {
|
||||
case 'image/jpeg':
|
||||
if ( $tools['jpegtran']['enabled'] && ! $tools['jpegtran']['path'] ) {
|
||||
/* translators: %s: name of a tool like jpegtran */
|
||||
echo '<div>' . sprintf( esc_html__( '%s is missing', 'ewww-image-optimizer' ), '<em>jpegtran</em>' ) . '</div></div>';
|
||||
if ( $return_output ) {
|
||||
return ob_get_clean();
|
||||
}
|
||||
return;
|
||||
}
|
||||
break;
|
||||
case 'image/png':
|
||||
// If the PNG tools are missing, tell the user.
|
||||
if ( $tools['optipng']['enabled'] && ! $tools['optipng']['path'] ) {
|
||||
/* translators: %s: name of a tool like jpegtran */
|
||||
echo '<div>' . sprintf( esc_html__( '%s is missing', 'ewww-image-optimizer' ), '<em>optipng</em>' ) . '</div></div>';
|
||||
if ( $return_output ) {
|
||||
return ob_get_clean();
|
||||
}
|
||||
return;
|
||||
}
|
||||
break;
|
||||
case 'image/gif':
|
||||
// If gifsicle is missing, tell the user.
|
||||
if ( $tools['gifsicle']['enabled'] && ! $tools['gifsicle']['path'] ) {
|
||||
/* translators: %s: name of a tool like jpegtran */
|
||||
echo '<div>' . sprintf( esc_html__( '%s is missing', 'ewww-image-optimizer' ), '<em>gifsicle</em>' ) . '</div></div>';
|
||||
if ( $return_output ) {
|
||||
return ob_get_clean();
|
||||
}
|
||||
return;
|
||||
}
|
||||
break;
|
||||
default:
|
||||
echo '<div>' . esc_html__( 'Unsupported file type', 'ewww-image-optimizer' ) . '</div></div>';
|
||||
if ( $return_output ) {
|
||||
return ob_get_clean();
|
||||
}
|
||||
return;
|
||||
}
|
||||
if ( ! empty( $meta->image->meta_data['ewww_image_optimizer'] ) ) {
|
||||
ewww_image_optimizer_update_file_from_meta( $file_path, 'nextcell', $id, 'full' );
|
||||
$thumb_path = $meta->image->thumbPath;
|
||||
ewww_image_optimizer_update_file_from_meta( $thumb_path, 'nextcell', $id, 'thumbnail' );
|
||||
}
|
||||
$backup_available = false;
|
||||
global $wpdb;
|
||||
$optimized_images = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM $wpdb->ewwwio_images WHERE attachment_id = %d AND gallery = 'nextcell' AND image_size <> 0 ORDER BY orig_size DESC", $id ), ARRAY_A );
|
||||
$ewww_manual_nonce = wp_create_nonce( 'ewww-manual-' . $id );
|
||||
// If we have a valid status, display it, the image size, and give a re-optimize link.
|
||||
if ( ! empty( $optimized_images ) ) {
|
||||
list( $detail_output, $converted, $backup_available ) = ewww_image_optimizer_custom_column_results( $id, $optimized_images );
|
||||
echo wp_kses_post( $detail_output );
|
||||
if ( current_user_can( apply_filters( 'ewww_image_optimizer_manual_permissions', '' ) ) ) {
|
||||
printf(
|
||||
'<a class="ewww-manual-optimize" data-id="%1$d" data-nonce="%2$s" href="' . esc_url( admin_url( 'admin.php?action=ewww_ngg_manual' ) ) . '&ewww_manual_nonce=%2$s&ewww_force=1&ewww_attachment_ID=%1$d">%3$s</a>',
|
||||
(int) $id,
|
||||
esc_attr( $ewww_manual_nonce ),
|
||||
esc_html__( 'Re-optimize', 'ewww-image-optimizer' )
|
||||
);
|
||||
if ( $backup_available ) {
|
||||
printf(
|
||||
'<br><a class="ewww-manual-cloud-restore" data-id="%1$d" data-nonce="%2$s" href="' . esc_url( admin_url( 'admin.php?action=ewww_ngg_cloud_restore' ) ) . '&ewww_manual_nonce=%2$s&ewww_attachment_ID=%1$d">%3$s</a>',
|
||||
(int) $id,
|
||||
esc_attr( $ewww_manual_nonce ),
|
||||
esc_html__( 'Restore original', 'ewww-image-optimizer' )
|
||||
);
|
||||
}
|
||||
}
|
||||
} elseif ( ewww_image_optimizer_image_is_pending( $id, 'nextc-async' ) ) {
|
||||
echo '<div>' . esc_html__( 'In Progress', 'ewww-image-optimizer' ) . '</div>';
|
||||
// Otherwise, give the image size, and a link to optimize right now.
|
||||
} else {
|
||||
if ( current_user_can( apply_filters( 'ewww_image_optimizer_manual_permissions', '' ) ) ) {
|
||||
printf(
|
||||
'<div><a class="ewww-manual-optimize" data-id="%1$d" data-nonce="%2$s" href="' . esc_url( admin_url( 'admin.php?action=ewww_ngg_manual' ) ) . '&ewww_manual_nonce=%2$s&ewww_attachment_ID=%1$d">%3$s</a></div>',
|
||||
(int) $id,
|
||||
esc_attr( $ewww_manual_nonce ),
|
||||
esc_html__( 'Optimize now!', 'ewww-image-optimizer' )
|
||||
);
|
||||
}
|
||||
}
|
||||
echo '</div>';
|
||||
if ( $return_output ) {
|
||||
return ob_get_clean();
|
||||
}
|
||||
} // End if().
|
||||
}
|
||||
|
||||
/**
|
||||
* Output the html for the bulk optimize page.
|
||||
*/
|
||||
public function ewww_ngg_bulk_preview() {
|
||||
// Retrieve the attachments array from the db.
|
||||
$attachments = get_option( 'ewww_image_optimizer_bulk_ngg_attachments' );
|
||||
// Make sure there are some attachments to process.
|
||||
if ( count( $attachments ) < 1 ) {
|
||||
echo '<p>' . esc_html__( 'You do not appear to have uploaded any images yet.', 'ewww-image-optimizer' ) . '</p>';
|
||||
return;
|
||||
}
|
||||
?>
|
||||
<div class="wrap">
|
||||
<h1><?php esc_html_e( 'Bulk Optimize', 'ewww-image-optimizer' ); ?></h1>
|
||||
<?php
|
||||
if ( ewww_image_optimizer_get_option( 'ewww_image_optimizer_cloud_key' ) ) {
|
||||
ewww_image_optimizer_cloud_verify( ewww_image_optimizer_get_option( 'ewww_image_optimizer_cloud_key' ) );
|
||||
echo '<a id="ewww-bulk-credits-available" target="_blank" class="page-title-action" style="float:right;" href="https://ewww.io/my-account/">' . esc_html__( 'Image credits available:', 'ewww-image-optimizer' ) . ' ' . esc_html( ewww_image_optimizer_cloud_quota() ) . '</a>';
|
||||
}
|
||||
// Retrieve the value of the 'bulk resume' option and set the button text for the form to use.
|
||||
$resume = get_option( 'ewww_image_optimizer_bulk_ngg_resume' );
|
||||
if ( empty( $resume ) ) {
|
||||
$button_text = __( 'Start optimizing', 'ewww-image-optimizer' );
|
||||
} else {
|
||||
$button_text = __( 'Resume previous bulk operation', 'ewww-image-optimizer' );
|
||||
}
|
||||
/* translators: %d: number of images */
|
||||
$selected_images_text = sprintf( _n( 'There is %d image ready to optimize.', 'There are %d images ready to optimize.', count( $attachments ), 'ewww-image-optimizer' ), count( $attachments ) );
|
||||
?>
|
||||
<div id="ewww-bulk-loading"></div>
|
||||
<div id="ewww-bulk-progressbar"></div>
|
||||
<div id="ewww-bulk-counter"></div>
|
||||
<form id="ewww-bulk-stop" style="display:none;" method="post" action="">
|
||||
<br /><input type="submit" class="button-secondary action" value="<?php esc_attr_e( 'Stop Optimizing', 'ewww-image-optimizer' ); ?>" />
|
||||
</form>
|
||||
<div id="ewww-bulk-widgets" class="metabox-holder" style="display:none">
|
||||
<div class="meta-box-sortables">
|
||||
<div id="ewww-bulk-last" class="postbox">
|
||||
<button type="button" class="ewww-handlediv button-link" aria-expanded="true">
|
||||
<span class="screen-reader-text"><?php esc_html_e( 'Click to toggle', 'ewww-image-optimizer' ); ?></span>
|
||||
<span class="toggle-indicator" aria-hidden="true"></span>
|
||||
</button>
|
||||
<h2 class="ewww-hndle"><span><?php esc_html_e( 'Last Image Optimized', 'ewww-image-optimizer' ); ?></span></h2>
|
||||
<div class="inside"></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="meta-box-sortables">
|
||||
<div id="ewww-bulk-status" class="postbox">
|
||||
<button type="button" class="ewww-handlediv button-link" aria-expanded="true">
|
||||
<span class="screen-reader-text"><?php esc_html_e( 'Click to toggle', 'ewww-image-optimizer' ); ?></span>
|
||||
<span class="toggle-indicator" aria-hidden="true"></span>
|
||||
</button>
|
||||
<h2 class="ewww-hndle"><span><?php esc_html_e( 'Optimization Log', 'ewww-image-optimizer' ); ?></span></h2>
|
||||
<div class="inside"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div id="ewww-bulk-forms">
|
||||
<p class="ewww-bulk-info"><?php echo esc_html( $selected_images_text ); ?><br />
|
||||
<?php esc_html_e( 'Previously optimized images will be skipped by default.', 'ewww-image-optimizer' ); ?></p>
|
||||
<form id="ewww-bulk-start" class="ewww-bulk-form" method="post" action="">
|
||||
<input type="hidden" id="ewww-delay" name="ewww-delay" value="0">
|
||||
<input type="submit" class="button-secondary action" value="<?php echo esc_attr( $button_text ); ?>" />
|
||||
</form>
|
||||
<?php
|
||||
// If there is a previous bulk operation to resume, give the user the option to reset the resume flag.
|
||||
if ( ! empty( $resume ) ) {
|
||||
?>
|
||||
<p class="ewww-bulk-info"><?php esc_html_e( 'If you would like to start over again, press the Reset Status button to reset the bulk operation status.', 'ewww-image-optimizer' ); ?></p>
|
||||
<form id="ewww-bulk-reset" class="ewww-bulk-form" method="post" action="">
|
||||
<?php wp_nonce_field( 'ewww-image-optimizer-bulk-reset', 'ewww_wpnonce' ); ?>
|
||||
<input type="hidden" name="ewww_reset" value="1">
|
||||
<input type="submit" class="button-secondary action" value="<?php esc_attr_e( 'Reset Status', 'ewww-image-optimizer' ); ?>" />
|
||||
</form>
|
||||
<?php
|
||||
}
|
||||
echo '</div></div>';
|
||||
return;
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepares the javascript for a bulk operation.
|
||||
*
|
||||
* @global object $nggdb
|
||||
*
|
||||
* @param string $hook The hook identifier for the current page.
|
||||
*/
|
||||
public function ewww_ngg_bulk_script( $hook ) {
|
||||
ewwwio_debug_message( $hook );
|
||||
if ( 'galleries_page_ewww-ngg-bulk' !== $hook ) {
|
||||
return;
|
||||
}
|
||||
ewwwio_debug_message( '<b>' . __METHOD__ . '()</b>' );
|
||||
$images = null;
|
||||
// See if the user wants to reset the previous bulk status.
|
||||
if ( ! empty( $_REQUEST['ewww_reset'] ) && ! empty( $_REQUEST['ewww_wpnonce'] ) && wp_verify_nonce( sanitize_key( $_REQUEST['ewww_wpnonce'] ), 'ewww-image-optimizer-bulk-reset' ) ) {
|
||||
update_option( 'ewww_image_optimizer_bulk_ngg_resume', '' );
|
||||
}
|
||||
// See if there is a previous operation to resume.
|
||||
$resume = get_option( 'ewww_image_optimizer_bulk_ngg_resume' );
|
||||
// If we've been given a bulk action to perform.
|
||||
if ( ! empty( $resume ) ) {
|
||||
// Otherwise, if we have an operation to resume.
|
||||
ewwwio_debug_message( 'resuming a previous operation (maybe)' );
|
||||
// Get the list of attachment IDs from the db.
|
||||
$images = get_option( 'ewww_image_optimizer_bulk_ngg_attachments' );
|
||||
// Otherwise, if we are on the standard bulk page, get all the images in the db.
|
||||
} else {
|
||||
ewwwio_debug_message( 'starting from scratch, grabbing all the images' );
|
||||
global $wpdb;
|
||||
$images = $wpdb->get_col( "SELECT pid FROM $wpdb->nggpictures ORDER BY sortorder ASC" );
|
||||
} // End if().
|
||||
|
||||
// Store the image IDs to process in the db.
|
||||
update_option( 'ewww_image_optimizer_bulk_ngg_attachments', $images, false );
|
||||
// Add the EWWW IO script.
|
||||
wp_enqueue_script( 'ewwwbulkscript', plugins_url( '/includes/eio-bulk.js', EWWW_IMAGE_OPTIMIZER_PLUGIN_FILE ), array( 'jquery', 'jquery-ui-progressbar', 'jquery-ui-slider', 'postbox', 'dashboard' ), EWWW_IMAGE_OPTIMIZER_VERSION );
|
||||
// Replacing the built-in nextgen styling rules for progressbar.
|
||||
wp_register_style( 'ngg-jqueryui', plugins_url( '/includes/jquery-ui-1.10.1.custom.css', EWWW_IMAGE_OPTIMIZER_PLUGIN_FILE ) );
|
||||
// Enqueue the progressbar styling.
|
||||
wp_enqueue_style( 'ngg-jqueryui' );
|
||||
wp_add_inline_style( 'ngg-jqueryui', '.ui-widget-header { background-color: ' . ewww_image_optimizer_admin_background() . '; }' );
|
||||
// Include all the vars we need for javascript.
|
||||
wp_localize_script(
|
||||
'ewwwbulkscript',
|
||||
'ewww_vars',
|
||||
array(
|
||||
'_wpnonce' => wp_create_nonce( 'ewww-image-optimizer-bulk' ),
|
||||
'gallery' => 'nextgen',
|
||||
'attachments' => count( $images ),
|
||||
'scan_fail' => esc_html__( 'Operation timed out, you may need to increase the max_execution_time for PHP', 'ewww-image-optimizer' ),
|
||||
'operation_stopped' => esc_html__( 'Optimization stopped, reload page to resume.', 'ewww-image-optimizer' ),
|
||||
'operation_interrupted' => esc_html__( 'Operation Interrupted', 'ewww-image-optimizer' ),
|
||||
'temporary_failure' => esc_html__( 'Temporary failure, seconds left to retry:', 'ewww-image-optimizer' ),
|
||||
'remove_failed' => esc_html__( 'Could not remove image from table.', 'ewww-image-optimizer' ),
|
||||
'optimized' => esc_html__( 'Optimized', 'ewww-image-optimizer' ),
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Start the bulk operation.
|
||||
*/
|
||||
public function ewww_ngg_bulk_init() {
|
||||
$permissions = apply_filters( 'ewww_image_optimizer_bulk_permissions', '' );
|
||||
$output = array();
|
||||
if ( empty( $_REQUEST['ewww_wpnonce'] ) || ! wp_verify_nonce( sanitize_key( $_REQUEST['ewww_wpnonce'] ), 'ewww-image-optimizer-bulk' ) || ! current_user_can( $permissions ) ) {
|
||||
$output['error'] = esc_html__( 'Access denied.', 'ewww-image-optimizer' );
|
||||
ewwwio_ob_clean();
|
||||
wp_die( wp_json_encode( $output ) );
|
||||
}
|
||||
// Toggle the resume flag to indicate an operation is in progress.
|
||||
update_option( 'ewww_image_optimizer_bulk_ngg_resume', 'true' );
|
||||
// Get the list of attachments remaining from the db.
|
||||
$attachments = get_option( 'ewww_image_optimizer_bulk_ngg_attachments' );
|
||||
if ( ! is_array( $attachments ) && ! empty( $attachments ) ) {
|
||||
$attachments = unserialize( $attachments );
|
||||
}
|
||||
if ( ! is_array( $attachments ) ) {
|
||||
$output['error'] = esc_html__( 'Error retrieving list of images' );
|
||||
ewwwio_ob_clean();
|
||||
wp_die( wp_json_encode( $output ) );
|
||||
}
|
||||
$id = array_shift( $attachments );
|
||||
$file_name = $this->ewww_ngg_bulk_filename( $id );
|
||||
// Let the user know we are starting.
|
||||
$loading_image = plugins_url( '/images/wpspin.gif', EWWW_IMAGE_OPTIMIZER_PLUGIN_FILE );
|
||||
if ( empty( $file_name ) ) {
|
||||
$output['results'] = '<p>' . esc_html__( 'Optimizing', 'ewww-image-optimizer' ) . " <img src='$loading_image' alt='loading'/></p>";
|
||||
} else {
|
||||
$output['results'] = '<p>' . esc_html__( 'Optimizing', 'ewww-image-optimizer' ) . ' <b>' . $file_name . "</b> <img src='$loading_image' alt='loading'/></p>";
|
||||
}
|
||||
ewwwio_ob_clean();
|
||||
wp_die( wp_json_encode( $output ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the filename of the image being optimized.
|
||||
*
|
||||
* @param int $id The ID number of the image.
|
||||
*/
|
||||
public function ewww_ngg_bulk_filename( $id ) {
|
||||
// Need this file to work with metadata.
|
||||
require_once WP_CONTENT_DIR . '/plugins/nextcellent-gallery-nextgen-legacy/lib/meta.php';
|
||||
// Get the meta for the image.
|
||||
$meta = new nggMeta( $id );
|
||||
// Get the filename for the image, and output our current status.
|
||||
$file_name = esc_html( $meta->image->filename );
|
||||
if ( $file_name ) {
|
||||
return $file_name;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Process each image in the bulk queue.
|
||||
*
|
||||
* @global bool $ewww_defer Set to false to avoid deferring image optimization.
|
||||
*/
|
||||
public function ewww_ngg_bulk_loop() {
|
||||
global $ewww_defer;
|
||||
$ewww_defer = false;
|
||||
$output = array();
|
||||
$permissions = apply_filters( 'ewww_image_optimizer_bulk_permissions', '' );
|
||||
if ( empty( $_REQUEST['ewww_wpnonce'] ) || ! wp_verify_nonce( sanitize_key( $_REQUEST['ewww_wpnonce'] ), 'ewww-image-optimizer-bulk' ) || ! current_user_can( $permissions ) ) {
|
||||
$outupt['error'] = esc_html__( 'Access token has expired, please reload the page.', 'ewww-image-optimizer' );
|
||||
ewwwio_ob_clean();
|
||||
wp_die( wp_json_encode( $output ) );
|
||||
}
|
||||
session_write_close();
|
||||
// Find out if our nonce is on it's last leg/tick.
|
||||
$tick = wp_verify_nonce( sanitize_key( $_REQUEST['ewww_wpnonce'] ), 'ewww-image-optimizer-bulk' );
|
||||
if ( 2 === $tick ) {
|
||||
$output['new_nonce'] = wp_create_nonce( 'ewww-image-optimizer-bulk' );
|
||||
} else {
|
||||
$output['new_nonce'] = '';
|
||||
}
|
||||
// Find out what time we started, in microseconds.
|
||||
$started = microtime( true );
|
||||
// Get the list of attachments remaining from the db.
|
||||
$attachments = get_option( 'ewww_image_optimizer_bulk_ngg_attachments' );
|
||||
$id = array_shift( $attachments );
|
||||
list( $fres, $tres ) = $this->ewww_ngg_optimize( $id );
|
||||
if ( 'exceeded' === get_transient( 'ewww_image_optimizer_cloud_status' ) ) {
|
||||
$output['error'] = '<a href="https://ewww.io/buy-credits/" target="_blank">' . esc_html__( 'License Exceeded', 'ewww-image-optimizer' ) . '</a>';
|
||||
ewwwio_ob_clean();
|
||||
wp_die( wp_json_encode( $output ) );
|
||||
}
|
||||
if ( 'exceeded quota' === get_transient( 'ewww_image_optimizer_cloud_status' ) ) {
|
||||
$output['error'] = '<a href="https://docs.ewww.io/article/101-soft-quotas-on-unlimited-plans" target="_blank">' . esc_html__( 'Soft quota reached, contact us for more', 'ewww-image-optimizer' ) . '</a>';
|
||||
ewwwio_ob_clean();
|
||||
wp_die( wp_json_encode( $output ) );
|
||||
}
|
||||
// Output the results of the optimization.
|
||||
if ( $fres[0] ) {
|
||||
$output['results'] = sprintf( '<p>' . esc_html__( 'Optimized image:', 'ewww-image-optimizer' ) . ' <strong>%s</strong><br>', esc_html( $fres[0] ) );
|
||||
}
|
||||
/* Translators: %s: The compression results/savings */
|
||||
$output['results'] .= sprintf( esc_html__( 'Full size - %s', 'ewww-image-optimizer' ) . '<br>', esc_html( $fres[1] ) );
|
||||
// Output the results of the thumb optimization.
|
||||
/* Translators: %s: The compression results/savings */
|
||||
$output['results'] .= sprintf( esc_html__( 'Thumbnail - %s', 'ewww-image-optimizer' ) . '<br>', esc_html( $tres[1] ) );
|
||||
// Output how much time we spent.
|
||||
$elapsed = microtime( true ) - $started;
|
||||
/* Translators: %s: localized number of seconds */
|
||||
$output['results'] .= sprintf( esc_html( _n( 'Elapsed: %s second', 'Elapsed: %s seconds', $elapsed, 'ewww-image-optimizer' ) ) . '</p>', number_format_i18n( $elapsed, 2 ) );
|
||||
$output['completed'] = 1;
|
||||
// Store the list back in the db.
|
||||
update_option( 'ewww_image_optimizer_bulk_ngg_attachments', $attachments, false );
|
||||
if ( ! empty( $attachments ) ) {
|
||||
$next_attachment = array_shift( $attachments );
|
||||
$next_file = $this->ewww_ngg_bulk_filename( $next_attachment );
|
||||
$loading_image = plugins_url( '/images/wpspin.gif', EWWW_IMAGE_OPTIMIZER_PLUGIN_FILE );
|
||||
if ( $next_file ) {
|
||||
$output['next_file'] = '<p>' . esc_html__( 'Optimizing', 'ewww-image-optimizer' ) . " <b>$next_file</b> <img src='$loading_image' alt='loading'/></p>";
|
||||
} else {
|
||||
$output['next_file'] = '<p>' . esc_html__( 'Optimizing', 'ewww-image-optimizer' ) . " <img src='$loading_image' alt='loading'/></p>";
|
||||
}
|
||||
} else {
|
||||
$output['done'] = 1;
|
||||
}
|
||||
ewwwio_ob_clean();
|
||||
wp_die( wp_json_encode( $output ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Finish the bulk operation.
|
||||
*/
|
||||
public function ewww_ngg_bulk_cleanup() {
|
||||
$permissions = apply_filters( 'ewww_image_optimizer_bulk_permissions', '' );
|
||||
if ( empty( $_REQUEST['ewww_wpnonce'] ) || ! wp_verify_nonce( sanitize_key( $_REQUEST['ewww_wpnonce'] ), 'ewww-image-optimizer-bulk' ) || ! current_user_can( $permissions ) ) {
|
||||
ewwwio_ob_clean();
|
||||
wp_die( esc_html__( 'Access token has expired, please reload the page.', 'ewww-image-optimizer' ) );
|
||||
}
|
||||
// Reset all the bulk options in the db...
|
||||
update_option( 'ewww_image_optimizer_bulk_ngg_resume', '' );
|
||||
update_option( 'ewww_image_optimizer_bulk_ngg_attachments', '', false );
|
||||
// and let the user know we are done.
|
||||
ewwwio_ob_clean();
|
||||
wp_die( '<p><b>' . esc_html__( 'Finished Optimization!', 'ewww-image-optimizer' ) . '</b></p>' );
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepare javascript for one-click actions on manage gallery page.
|
||||
*
|
||||
* @param string $hook The hook value for the current page.
|
||||
*/
|
||||
public function ewww_ngg_manual_actions_script( $hook ) {
|
||||
if ( 'galleries_page_nggallery-manage' !== $hook ) {
|
||||
return;
|
||||
}
|
||||
if ( ! current_user_can( apply_filters( 'ewww_image_optimizer_manual_permissions', '' ) ) ) {
|
||||
return;
|
||||
}
|
||||
add_thickbox();
|
||||
wp_enqueue_script( 'ewwwnextcellentscript', plugins_url( '/includes/nextcellent.js', EWWW_IMAGE_OPTIMIZER_PLUGIN_FILE ), array( 'jquery' ), EWWW_IMAGE_OPTIMIZER_VERSION );
|
||||
wp_enqueue_style( 'jquery-ui-tooltip-custom', plugins_url( '/includes/jquery-ui-1.10.1.custom.css', EWWW_IMAGE_OPTIMIZER_PLUGIN_FILE ), array(), EWWW_IMAGE_OPTIMIZER_VERSION );
|
||||
// Submit a couple variables needed for javascript functions.
|
||||
$loading_image = plugins_url( '/images/spinner.gif', EWWW_IMAGE_OPTIMIZER_PLUGIN_FILE );
|
||||
wp_localize_script(
|
||||
'ewwwnextcellentscript',
|
||||
'ewww_vars',
|
||||
array(
|
||||
'optimizing' => '<p>' . esc_html__( 'Optimizing', 'ewww-image-optimizer' ) . " <img src='$loading_image' /></p>",
|
||||
'restoring' => '<p>' . esc_html__( 'Restoring', 'ewww-image-optimizer' ) . " <img src='$loading_image' /></p>",
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
global $ewwwngg;
|
||||
$ewwwngg = new EWWW_Nextcellent();
|
||||
} // End if().
|
102
wp-content/plugins/ewww-image-optimizer/classes/class-ewwwdb.php
Normal file
@ -0,0 +1,102 @@
|
||||
<?php
|
||||
/**
|
||||
* Class file for EwwwDB
|
||||
*
|
||||
* EwwwDB contains methods for working with the ewwwio_images table.
|
||||
*
|
||||
* @link https://ewww.io
|
||||
* @package EWWW_Image_Optimizer
|
||||
*/
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* DB class extension to for working with the ewwwio_images table.
|
||||
*
|
||||
* Provides functions needed to ensure that all data in the table is in utf8 format.
|
||||
*
|
||||
* @see wpdb
|
||||
*/
|
||||
class EwwwDB extends wpdb {
|
||||
|
||||
/**
|
||||
* Ensures use of some variant of utf8 for interacting with the images table.
|
||||
*/
|
||||
public function init_charset() {
|
||||
parent::init_charset();
|
||||
if ( strpos( $this->charset, 'utf8' ) === false ) {
|
||||
$this->charset = 'utf8';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Inserts multiple records into the table at once.
|
||||
*
|
||||
* Takes an associative array and creates a database record for each array item, using a single
|
||||
* MySQL query. Column names are extracted from the key names of the first record.
|
||||
*
|
||||
* @param string $table Name of table to be used in INSERT statement.
|
||||
* @param array $data Records to be inserted into table. Default none. Accepts an array of arrays,
|
||||
* see example below.
|
||||
* @param array $format List of formats for values in each record. Each sub-array should have the
|
||||
* same number of items as $formats. Default '%s'. Accepts '%s', '%d', '%f'.
|
||||
* @return int|false Number of rows affected or false on error.
|
||||
*/
|
||||
public function insert_multiple( $table, $data, $format ) {
|
||||
if ( empty( $table ) || ! ewww_image_optimizer_iterable( $data ) || ! ewww_image_optimizer_iterable( $format ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
/*
|
||||
* Given a multi-dimensional array like so:
|
||||
* array(
|
||||
* [0] =>
|
||||
* 'path' => '/some/image/path/here.jpg'
|
||||
* 'gallery' => 'something'
|
||||
* 'orig_size => 5678
|
||||
* 'attachment_id => 2
|
||||
* 'resize' => 'thumb'
|
||||
* 'pending' => 1
|
||||
* [1] =>
|
||||
* 'path' => '/some/image/path/another.jpg'
|
||||
* 'gallery' => 'something'
|
||||
* 'orig_size => 1234
|
||||
* 'attachment_id => 3
|
||||
* 'resize' => 'full'
|
||||
* 'pending' => 1
|
||||
* )
|
||||
*/
|
||||
ewwwio_debug_message( 'we have records to store via ewwwdb' );
|
||||
$multi_formats = array();
|
||||
$values = array();
|
||||
foreach ( $data as $record ) {
|
||||
if ( ! ewww_image_optimizer_iterable( $record ) ) {
|
||||
continue;
|
||||
}
|
||||
$record = $this->process_fields( $table, $record, $format );
|
||||
if ( false === $record ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$formats = array();
|
||||
foreach ( $record as $value ) {
|
||||
if ( is_null( $value['value'] ) ) {
|
||||
$formats[] = 'NULL';
|
||||
continue;
|
||||
}
|
||||
|
||||
$formats[] = $value['format'];
|
||||
$values[] = $value['value'];
|
||||
}
|
||||
$multi_formats[] = '(' . implode( ',', $formats ) . ')';
|
||||
}
|
||||
$first = reset( $data );
|
||||
$fields = '`' . implode( '`, `', array_keys( $first ) ) . '`';
|
||||
$multi_formats = implode( ',', $multi_formats );
|
||||
$this->check_current_query = false;
|
||||
return $this->query( $this->prepare( "INSERT INTO `$table` ($fields) VALUES $multi_formats", $values ) );
|
||||
}
|
||||
}
|
@ -0,0 +1,869 @@
|
||||
<?php
|
||||
/**
|
||||
* Class file for EWWWIO_CLI
|
||||
*
|
||||
* EWWWIO_CLI contains an extension to the WP_CLI_Command class to enable bulk optimizing from the
|
||||
* command line using WP-CLI.
|
||||
*
|
||||
* @link https://ewww.io
|
||||
* @package EWWW_Image_Optimizer
|
||||
*/
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Run bulk EWWW IO tools via WP CLI.
|
||||
*/
|
||||
class EWWWIO_CLI extends WP_CLI_Command {
|
||||
/**
|
||||
* Optimizes images from the selected 'gallery'.
|
||||
*
|
||||
* ## OPTIONS
|
||||
*
|
||||
* <library>
|
||||
* : valid values are 'all' (default), 'media', 'nextgen', and 'flagallery'
|
||||
* : media: Media Library, theme, and configured folders
|
||||
* : nextgen: Nextcellent and NextGEN 2.x
|
||||
* : flagallery: Grand FlAGallery
|
||||
*
|
||||
* <delay>
|
||||
* : optional, number of seconds to pause between images
|
||||
*
|
||||
* <force>
|
||||
* : optional, should the plugin re-optimize images that have already been processed.
|
||||
*
|
||||
* <reset>
|
||||
* : optional, start the optimizer back at the beginning instead of resuming from last position
|
||||
*
|
||||
* <webp-only>
|
||||
* : optional, only do WebP Conversion, skip all other operations
|
||||
*
|
||||
* <noprompt>
|
||||
* : do not prompt, just start optimizing
|
||||
*
|
||||
* ## EXAMPLES
|
||||
*
|
||||
* wp-cli ewwwio optimize media 5 --force --reset --webp-only --noprompt
|
||||
*
|
||||
* @synopsis <library> [<delay>] [--force] [--reset] [--webp-only] [--noprompt]
|
||||
*
|
||||
* @global bool $ewww_defer Gets set to false to make sure optimization happens inline.
|
||||
*
|
||||
* @param array $args A numeric array of required arguments.
|
||||
* @param array $assoc_args An associative array of optional arguments.
|
||||
*/
|
||||
public function optimize( $args, $assoc_args ) {
|
||||
global $ewww_defer;
|
||||
$ewww_defer = false;
|
||||
global $ewww_webp_only;
|
||||
$ewww_webp_only = false;
|
||||
// because NextGEN hasn't flushed it's buffers...
|
||||
while ( @ob_end_flush() ) { // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
|
||||
}
|
||||
$library = $args[0];
|
||||
if ( empty( $args[1] ) ) {
|
||||
$delay = ewww_image_optimizer_get_option( 'ewww_image_optimizer_delay' );
|
||||
} else {
|
||||
$delay = $args[1];
|
||||
}
|
||||
$ewww_reset = false;
|
||||
if ( ! empty( $assoc_args['reset'] ) ) {
|
||||
$ewww_reset = true;
|
||||
} else {
|
||||
$media_resume = get_option( 'ewww_image_optimizer_bulk_resume' );
|
||||
if (
|
||||
( ! empty( $media_resume ) && 'scanning' !== $media_resume ) ||
|
||||
get_option( 'ewww_image_optimizer_bulk_ngg_resume', '' ) ||
|
||||
get_option( 'ewww_image_optimizer_bulk_flag_resume', '' )
|
||||
) {
|
||||
WP_CLI::line( __( 'Resuming previous operation.', 'ewww-image-optimizer' ) );
|
||||
}
|
||||
}
|
||||
|
||||
if ( ! empty( $assoc_args['force'] ) ) {
|
||||
WP_CLI::line( __( 'Forcing re-optimization of previously processed images.', 'ewww-image-optimizer' ) );
|
||||
$_REQUEST['ewww_force'] = true;
|
||||
global $ewww_force;
|
||||
$ewww_force = 1;
|
||||
}
|
||||
if ( ! empty( $assoc_args['webp-only'] ) ) {
|
||||
if ( empty( ewww_image_optimizer_get_option( 'ewww_image_optimizer_webp' ) ) ) {
|
||||
WP_CLI::error( __( 'WebP Conversion is not enabled.', 'ewww-image-optimizer' ) );
|
||||
}
|
||||
WP_CLI::line( __( 'Running WebP conversion only.', 'ewww-image-optimizer' ) );
|
||||
$ewww_webp_only = true;
|
||||
}
|
||||
/* translators: 1: type of images, like media, or nextgen 2: number of seconds */
|
||||
WP_CLI::line( sprintf( _x( 'Optimizing %1$s with a %2$d second pause between images.', 'string will be something like "media" or "nextgen"', 'ewww-image-optimizer' ), $library, $delay ) );
|
||||
// Let's get started, shall we?
|
||||
ewwwio()->admin_init();
|
||||
|
||||
// And what shall we do?
|
||||
switch ( $library ) {
|
||||
case 'all':
|
||||
if ( $ewww_reset ) {
|
||||
update_option( 'ewww_image_optimizer_bulk_resume', '' );
|
||||
update_option( 'ewww_image_optimizer_aux_resume', '' );
|
||||
update_option( 'ewww_image_optimizer_scanning_attachments', '', false );
|
||||
update_option( 'ewww_image_optimizer_bulk_attachments', '', false );
|
||||
update_option( 'ewww_image_optimizer_bulk_ngg_resume', '' );
|
||||
update_option( 'ewww_image_optimizer_bulk_flag_resume', '' );
|
||||
ewww_image_optimizer_delete_pending();
|
||||
WP_CLI::line( __( 'Bulk status has been reset, starting from the beginning.', 'ewww-image-optimizer' ) );
|
||||
}
|
||||
ewww_image_optimizer_bulk_script( 'media_page_ewww-image-optimizer-bulk' );
|
||||
$fullsize_count = ewww_image_optimizer_count_optimized( 'media' );
|
||||
|
||||
/* translators: %d: number of images */
|
||||
WP_CLI::line( sprintf( _n( '%1$d image in the Media Library has been selected.', '%1$d images in the Media Library have been selected.', $fullsize_count, 'ewww-image-optimizer' ), $fullsize_count ) );
|
||||
WP_CLI::line( __( 'The active theme, BuddyPress, WP Symposium, and folders that you have configured will also be scanned for unoptimized images.', 'ewww-image-optimizer' ) );
|
||||
WP_CLI::line( __( 'Scanning, this could take a while', 'ewww-image-optimizer' ) );
|
||||
// Do a filter to increase the timeout to 999 or something crazy.
|
||||
add_filter( 'ewww_image_optimizer_timeout', 'ewww_image_optimizer_cli_timeout', 200 );
|
||||
ewww_image_optimizer_media_scan( 'ewww-image-optimizer-cli' );
|
||||
$pending_count = ewww_image_optimizer_aux_images_script( 'ewww-image-optimizer-cli' );
|
||||
if ( class_exists( 'EWWW_Nextgen' ) ) {
|
||||
list( $fullsize_count, $resize_count ) = ewww_image_optimizer_count_optimized( 'ngg' );
|
||||
/* translators: 1-2: number of images */
|
||||
WP_CLI::line( 'Nextgen: ' . sprintf( __( '%1$d images have been selected, with %2$d resized versions.', 'ewww-image-optimizer' ), $fullsize_count, $resize_count ) );
|
||||
} elseif ( class_exists( 'EWWW_Nextcellent' ) ) {
|
||||
$attachments = $this->scan_nextcellent();
|
||||
/* translators: %d: number of images */
|
||||
WP_CLI::line( 'Nextgen: ' . sprintf( _n( 'There is %d image ready to optimize.', 'There are %d images ready to optimize.', count( $attachments ), 'ewww-image-optimizer' ), count( $attachments ) ) );
|
||||
}
|
||||
if ( class_exists( 'EWWW_Flag' ) ) {
|
||||
list( $fullsize_count, $resize_count ) = ewww_image_optimizer_count_optimized( 'flag' );
|
||||
/* translators: 1-2: number of images */
|
||||
WP_CLI::line( 'FlAGallery: ' . sprintf( __( '%1$d images have been selected, with %2$d resized versions.', 'ewww-image-optimizer' ), $fullsize_count, $resize_count ) );
|
||||
}
|
||||
if ( empty( $assoc_args['noprompt'] ) && $pending_count ) {
|
||||
/* translators: %d: number of images */
|
||||
WP_CLI::confirm( sprintf( _n( 'There is %d image ready to optimize.', 'There are %d images ready to optimize.', $pending_count, 'ewww-image-optimizer' ), $pending_count ) );
|
||||
}
|
||||
if ( $pending_count ) {
|
||||
// Update the 'bulk resume' option to show that an operation is in progress.
|
||||
update_option( 'ewww_image_optimizer_bulk_resume', 'true' );
|
||||
$_REQUEST['ewww_batch_limit'] = 1;
|
||||
$clicount = 1;
|
||||
/* translators: 1: current image being proccessed 2: total number of images*/
|
||||
WP_CLI::line( sprintf( __( 'Processing image %1$d of %2$d', 'ewww-image-optimizer' ), $clicount, $pending_count ) );
|
||||
while ( ewww_image_optimizer_bulk_loop( 'ewww-image-optimizer-cli', $delay ) ) {
|
||||
++$clicount;
|
||||
if ( $clicount <= $pending_count ) {
|
||||
/* translators: 1: current image being proccessed 2: total number of images*/
|
||||
WP_CLI::line( sprintf( __( 'Processing image %1$d of %2$d', 'ewww-image-optimizer' ), $clicount, $pending_count ) );
|
||||
}
|
||||
}
|
||||
} else {
|
||||
WP_CLI::line( __( 'No images to optimize', 'ewww-image-optimizer' ) );
|
||||
}
|
||||
$this->bulk_media_cleanup();
|
||||
if ( class_exists( 'EWWW_Nextgen' ) ) {
|
||||
$this->bulk_ngg( $delay );
|
||||
} elseif ( class_exists( 'EWWW_Nextcellent' ) ) {
|
||||
$attachments = $this->scan_nextcellent();
|
||||
$this->bulk_nextcellent( $delay, $attachments );
|
||||
}
|
||||
if ( class_exists( 'EWWW_Flag' ) ) {
|
||||
$this->bulk_flag( $delay );
|
||||
}
|
||||
break;
|
||||
case 'media':
|
||||
case 'other':
|
||||
if ( $ewww_reset ) {
|
||||
update_option( 'ewww_image_optimizer_bulk_resume', '' );
|
||||
update_option( 'ewww_image_optimizer_aux_resume', '' );
|
||||
update_option( 'ewww_image_optimizer_scanning_attachments', '', false );
|
||||
update_option( 'ewww_image_optimizer_bulk_attachments', '', false );
|
||||
ewww_image_optimizer_delete_pending();
|
||||
WP_CLI::line( __( 'Bulk status has been reset, starting from the beginning.', 'ewww-image-optimizer' ) );
|
||||
}
|
||||
ewww_image_optimizer_bulk_script( 'media_page_ewww-image-optimizer-bulk' );
|
||||
$fullsize_count = ewww_image_optimizer_count_optimized( 'media' );
|
||||
/* translators: %d: number of images */
|
||||
WP_CLI::line( sprintf( __( '%1$d images in the Media Library have been selected.', 'ewww-image-optimizer' ), $fullsize_count ) );
|
||||
WP_CLI::line( __( 'The active theme, BuddyPress, WP Symposium, and folders that you have configured will also be scanned for unoptimized images.', 'ewww-image-optimizer' ) );
|
||||
WP_CLI::line( __( 'Scanning, this could take a while', 'ewww-image-optimizer' ) );
|
||||
// Do a filter to increase the timeout to 999 or something crazy.
|
||||
add_filter( 'ewww_image_optimizer_timeout', 'ewww_image_optimizer_cli_timeout', 200 );
|
||||
ewww_image_optimizer_media_scan( 'ewww-image-optimizer-cli' );
|
||||
$pending_count = ewww_image_optimizer_aux_images_script( 'ewww-image-optimizer-cli' );
|
||||
if ( empty( $assoc_args['noprompt'] ) && $pending_count ) {
|
||||
/* translators: %d: number of images */
|
||||
WP_CLI::confirm( sprintf( _n( 'There is %d image ready to optimize.', 'There are %d images ready to optimize.', $pending_count, 'ewww-image-optimizer' ), $pending_count ) );
|
||||
}
|
||||
$_REQUEST['ewww_batch_limit'] = 1;
|
||||
if ( $pending_count ) {
|
||||
// Update the 'bulk resume' option to show that an operation is in progress.
|
||||
update_option( 'ewww_image_optimizer_bulk_resume', 'true' );
|
||||
$clicount = 1;
|
||||
/* translators: 1: current image being proccessed 2: total number of images*/
|
||||
WP_CLI::line( sprintf( __( 'Processing image %1$d of %2$d', 'ewww-image-optimizer' ), $clicount, $pending_count ) );
|
||||
while ( ewww_image_optimizer_bulk_loop( 'ewww-image-optimizer-cli', $delay ) ) {
|
||||
++$clicount;
|
||||
if ( $clicount <= $pending_count ) {
|
||||
/* translators: 1: current image being proccessed 2: total number of images*/
|
||||
WP_CLI::line( sprintf( __( 'Processing image %1$d of %2$d', 'ewww-image-optimizer' ), $clicount, $pending_count ) );
|
||||
}
|
||||
}
|
||||
} else {
|
||||
WP_CLI::line( __( 'No images to optimize', 'ewww-image-optimizer' ) );
|
||||
}
|
||||
$this->bulk_media_cleanup();
|
||||
break;
|
||||
case 'nextgen':
|
||||
if ( $ewww_reset ) {
|
||||
update_option( 'ewww_image_optimizer_bulk_ngg_resume', '' );
|
||||
WP_CLI::line( __( 'Bulk status has been reset, starting from the beginning.', 'ewww-image-optimizer' ) );
|
||||
}
|
||||
if ( class_exists( 'EWWW_Nextgen' ) ) {
|
||||
list( $fullsize_count, $resize_count ) = ewww_image_optimizer_count_optimized( 'ngg' );
|
||||
if ( empty( $assoc_args['noprompt'] ) ) {
|
||||
/* translators: 1-2: number of images */
|
||||
WP_CLI::confirm( sprintf( __( '%1$d images have been selected, with %2$d resized versions.', 'ewww-image-optimizer' ), $fullsize_count, $resize_count ) );
|
||||
}
|
||||
$this->bulk_ngg( $delay );
|
||||
} elseif ( class_exists( 'EWWW_Nextcellent' ) ) {
|
||||
$attachments = $this->scan_nextcellent();
|
||||
if ( empty( $assoc_args['noprompt'] ) ) {
|
||||
/* translators: %d: number of images */
|
||||
WP_CLI::confirm( sprintf( _n( 'There is %d image ready to optimize.', 'There are %d images ready to optimize.', count( $attachments ), 'ewww-image-optimizer' ), count( $attachments ) ) );
|
||||
}
|
||||
$this->bulk_nextcellent( $delay, $attachments );
|
||||
} else {
|
||||
WP_CLI::error( __( 'NextGEN/Nextcellent not installed.', 'ewww-image-optimizer' ) );
|
||||
}
|
||||
break;
|
||||
case 'flagallery':
|
||||
if ( $ewww_reset ) {
|
||||
update_option( 'ewww_image_optimizer_bulk_flag_resume', '' );
|
||||
WP_CLI::line( __( 'Bulk status has been reset, starting from the beginning.', 'ewww-image-optimizer' ) );
|
||||
}
|
||||
if ( class_exists( 'EWWW_Flag' ) ) {
|
||||
list( $fullsize_count, $resize_count ) = ewww_image_optimizer_count_optimized( 'flag' );
|
||||
if ( empty( $assoc_args['noprompt'] ) ) {
|
||||
/* translators: 1-2: number of images */
|
||||
WP_CLI::confirm( 'FlAGallery: ' . sprintf( __( '%1$d images have been selected, with %2$d resized versions.', 'ewww-image-optimizer' ), $fullsize_count, $resize_count ) );
|
||||
}
|
||||
$this->bulk_flag( $delay );
|
||||
} else {
|
||||
WP_CLI::error( __( 'Grand Flagallery not installed.', 'ewww-image-optimizer' ) );
|
||||
}
|
||||
break;
|
||||
default:
|
||||
if ( $ewww_reset ) {
|
||||
update_option( 'ewww_image_optimizer_bulk_resume', '' );
|
||||
update_option( 'ewww_image_optimizer_aux_resume', '' );
|
||||
update_option( 'ewww_image_optimizer_bulk_ngg_resume', '' );
|
||||
update_option( 'ewww_image_optimizer_bulk_flag_resume', '' );
|
||||
WP_CLI::success( __( 'Bulk status has been reset, the next bulk operation will start from the beginning.', 'ewww-image-optimizer' ) );
|
||||
} else {
|
||||
WP_CLI::line( __( 'Please specify a valid library option, see "wp-cli help ewwwio optimize" for more information.', 'ewww-image-optimizer' ) );
|
||||
}
|
||||
} // End switch().
|
||||
}
|
||||
|
||||
/**
|
||||
* Restore images from cloud/local backups.
|
||||
*
|
||||
* ## OPTIONS
|
||||
*
|
||||
* <reset>
|
||||
* : optional, start the process over instead of resuming from last position
|
||||
*
|
||||
* ## EXAMPLES
|
||||
*
|
||||
* wp-cli ewwwio restore --reset
|
||||
*
|
||||
* @synopsis [--reset]
|
||||
*
|
||||
* @param array $args A numeric array of required arguments.
|
||||
* @param array $assoc_args An associative array of optional arguments.
|
||||
*/
|
||||
public function restore( $args, $assoc_args ) {
|
||||
if ( ! empty( $assoc_args['reset'] ) ) {
|
||||
delete_option( 'ewww_image_optimizer_bulk_restore_position' );
|
||||
}
|
||||
global $eio_backup;
|
||||
global $wpdb;
|
||||
if ( strpos( $wpdb->charset, 'utf8' ) === false ) {
|
||||
ewww_image_optimizer_db_init();
|
||||
global $ewwwdb;
|
||||
} else {
|
||||
$ewwwdb = $wpdb;
|
||||
}
|
||||
|
||||
$completed = 0;
|
||||
$position = (int) get_option( 'ewww_image_optimizer_bulk_restore_position' );
|
||||
$per_page = 200;
|
||||
|
||||
ewwwio_debug_message( "searching for $per_page records starting at $position" );
|
||||
$optimized_images = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM $wpdb->ewwwio_images WHERE id > %d AND pending = 0 AND image_size > 0 AND updates > 0 ORDER BY id LIMIT %d", $position, $per_page ), ARRAY_A );
|
||||
|
||||
$restorable_images = (int) $wpdb->get_var( $wpdb->prepare( "SELECT count(id) FROM $wpdb->ewwwio_images WHERE id > %d AND pending = 0 AND image_size > 0 AND updates > 0", $position ) );
|
||||
|
||||
/* translators: %d: number of images */
|
||||
WP_CLI::line( sprintf( __( 'There are %d images that may be restored.', 'ewww-image-optimizer' ), $restorable_images ) );
|
||||
WP_CLI::confirm( __( 'You should take a site backup before performing a bulk action on your images. Do you wish to continue?', 'ewww-image-optimizer' ) );
|
||||
|
||||
// Because some plugins might have loose filters (looking at you WPML).
|
||||
remove_all_filters( 'wp_delete_file' );
|
||||
|
||||
while ( ewww_image_optimizer_iterable( $optimized_images ) ) {
|
||||
foreach ( $optimized_images as $optimized_image ) {
|
||||
++$completed;
|
||||
ewwwio_debug_message( "submitting {$optimized_image['id']} to be restored" );
|
||||
$optimized_image['path'] = \ewww_image_optimizer_absolutize_path( $optimized_image['path'] );
|
||||
$eio_backup->restore_file( $optimized_image );
|
||||
$error_message = $eio_backup->get_error();
|
||||
if ( $error_message ) {
|
||||
WP_CLI::warning( "$completed/$restorable_images: $error_message" );
|
||||
} else {
|
||||
WP_CLI::success( "$completed/$restorable_images: {$optimized_image['path']}" );
|
||||
}
|
||||
update_option( 'ewww_image_optimizer_bulk_restore_position', $optimized_image['id'], false );
|
||||
} // End foreach().
|
||||
$optimized_images = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM $wpdb->ewwwio_images WHERE id > %d AND pending = 0 AND image_size > 0 AND updates > 0 ORDER BY id LIMIT %d", $optimized_image['id'], $per_page ), ARRAY_A );
|
||||
}
|
||||
|
||||
delete_option( 'ewww_image_optimizer_bulk_restore_position' );
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove pre-scaled original size versions of image uploads.
|
||||
*
|
||||
* ## OPTIONS
|
||||
*
|
||||
* <reset>
|
||||
* : optional, start the process back at the beginning instead of resuming from last position
|
||||
*
|
||||
* ## EXAMPLES
|
||||
*
|
||||
* wp-cli ewwwio remove_originals --reset
|
||||
*
|
||||
* @synopsis [--reset]
|
||||
*
|
||||
* @param array $args A numeric array of required arguments.
|
||||
* @param array $assoc_args An associative array of optional arguments.
|
||||
*/
|
||||
public function remove_originals( $args, $assoc_args ) {
|
||||
if ( ! empty( $assoc_args['reset'] ) ) {
|
||||
delete_option( 'ewww_image_optimizer_delete_originals_resume' );
|
||||
}
|
||||
global $wpdb;
|
||||
|
||||
$per_page = 200;
|
||||
$position = (int) get_option( 'ewww_image_optimizer_delete_originals_resume' );
|
||||
|
||||
$cleanable_uploads = (int) $wpdb->get_var(
|
||||
$wpdb->prepare(
|
||||
"SELECT count(ID) FROM $wpdb->posts WHERE ID > %d AND (post_type = 'attachment' OR post_type = 'ims_image') AND post_mime_type LIKE %s",
|
||||
(int) $position,
|
||||
'%image%'
|
||||
)
|
||||
);
|
||||
|
||||
/* translators: %d: number of image uploads */
|
||||
WP_CLI::line( sprintf( __( 'This process removes the originals that WordPress preserves for thumbnail generation. %d media uploads will checked for originals to remove.', 'ewww-image-optimizer' ), $cleanable_uploads ) );
|
||||
WP_CLI::confirm( __( 'You should take a site backup before performing a bulk action on your images. Do you wish to continue?', 'ewww-image-optimizer' ) );
|
||||
|
||||
/**
|
||||
* Require the files that contain functions for the images table and bulk processing images outside the library.
|
||||
*/
|
||||
require_once EWWW_IMAGE_OPTIMIZER_PLUGIN_PATH . 'aux-optimize.php';
|
||||
|
||||
\ewwwio_debug_message( "searching for $per_page records starting at $position" );
|
||||
|
||||
$attachments = $wpdb->get_col(
|
||||
$wpdb->prepare(
|
||||
"SELECT ID FROM $wpdb->posts WHERE ID > %d AND (post_type = 'attachment' OR post_type = 'ims_image') AND post_mime_type LIKE %s ORDER BY ID LIMIT %d",
|
||||
(int) $position,
|
||||
'%image%',
|
||||
(int) $per_page
|
||||
)
|
||||
);
|
||||
|
||||
$progress = \WP_CLI\Utils\make_progress_bar( __( 'Deleting originals', 'ewww-image-optimizer' ), $cleanable_uploads );
|
||||
|
||||
// Because some plugins might have loose filters (looking at you WPML).
|
||||
\remove_all_filters( 'wp_delete_file' );
|
||||
|
||||
while ( \ewww_image_optimizer_iterable( $attachments ) ) {
|
||||
foreach ( $attachments as $id ) {
|
||||
$new_meta = \ewwwio_remove_original_image( $id );
|
||||
if ( \ewww_image_optimizer_iterable( $new_meta ) ) {
|
||||
\wp_update_attachment_metadata( $id, $new_meta );
|
||||
}
|
||||
\update_option( 'ewww_image_optimizer_delete_originals_resume', $id, false );
|
||||
$progress->tick();
|
||||
}
|
||||
$attachments = $wpdb->get_col(
|
||||
$wpdb->prepare(
|
||||
"SELECT ID FROM $wpdb->posts WHERE ID > %d AND (post_type = 'attachment' OR post_type = 'ims_image') AND post_mime_type LIKE %s ORDER BY ID LIMIT %d",
|
||||
(int) $id,
|
||||
'%image%',
|
||||
(int) $per_page
|
||||
)
|
||||
);
|
||||
}
|
||||
$progress->finish();
|
||||
|
||||
WP_CLI::success( __( 'Finished', 'ewww-image-optimizer' ) );
|
||||
|
||||
\delete_option( 'ewww_image_optimizer_delete_originals_resume' );
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove the original version of converted images.
|
||||
*
|
||||
* @param array $args A numeric array of required arguments.
|
||||
* @param array $assoc_args An associative array of optional arguments.
|
||||
*/
|
||||
public function remove_converted_originals( $args, $assoc_args ) {
|
||||
if ( ! empty( $assoc_args['reset'] ) ) {
|
||||
delete_option( 'ewww_image_optimizer_delete_originals_resume' );
|
||||
}
|
||||
global $wpdb;
|
||||
if ( strpos( $wpdb->charset, 'utf8' ) === false ) {
|
||||
ewww_image_optimizer_db_init();
|
||||
global $ewwwdb;
|
||||
} else {
|
||||
$ewwwdb = $wpdb;
|
||||
}
|
||||
|
||||
$per_page = 200;
|
||||
|
||||
$converted_count = (int) $wpdb->get_var( "SELECT count(id) FROM $wpdb->ewwwio_images WHERE converted != ''" );
|
||||
|
||||
/* translators: %d: number of converted images */
|
||||
WP_CLI::line( sprintf( __( 'This process will remove the originals after you have converted images (PNG to JPG and friends). %d images will checked for originals to remove.', 'ewww-image-optimizer' ), $converted_count ) );
|
||||
WP_CLI::confirm( __( 'You should take a site backup before performing a bulk action on your images. Do you wish to continue?', 'ewww-image-optimizer' ) );
|
||||
|
||||
$converted_images = $wpdb->get_results( $wpdb->prepare( "SELECT path,converted,id FROM $wpdb->ewwwio_images WHERE converted != '' ORDER BY id DESC LIMIT %d", $per_page ), ARRAY_A );
|
||||
|
||||
$progress = \WP_CLI\Utils\make_progress_bar( __( 'Deleting converted images', 'ewww-image-optimizer' ), $converted_count );
|
||||
|
||||
// Because some plugins might have loose filters (looking at you WPML).
|
||||
\remove_all_filters( 'wp_delete_file' );
|
||||
|
||||
while ( \ewww_image_optimizer_iterable( $converted_images ) ) {
|
||||
foreach ( $converted_images as $optimized_image ) {
|
||||
$file = \ewww_image_optimizer_absolutize_path( $optimized_image['converted'] );
|
||||
\ewwwio_debug_message( "$file was converted, checking if it still exists" );
|
||||
if ( ! \ewww_image_optimizer_stream_wrapped( $file ) && \ewwwio_is_file( $file ) ) {
|
||||
\ewwwio_debug_message( "removing original: $file" );
|
||||
if ( \ewwwio_delete_file( $file ) ) {
|
||||
\ewwwio_debug_message( "removed $file" );
|
||||
} else {
|
||||
/* translators: %s: file name */
|
||||
WP_CLI::warning( sprintf( __( 'Could not delete %s, please remove manually or fix permissions and try again.', 'ewww-image-optimizer' ), $file ) );
|
||||
}
|
||||
}
|
||||
$wpdb->update(
|
||||
$wpdb->ewwwio_images,
|
||||
array(
|
||||
'converted' => '',
|
||||
),
|
||||
array(
|
||||
'id' => $optimized_image['id'],
|
||||
)
|
||||
);
|
||||
$progress->tick();
|
||||
} // End foreach().
|
||||
$converted_images = $wpdb->get_results( $wpdb->prepare( "SELECT path,converted,id FROM $wpdb->ewwwio_images WHERE converted != '' ORDER BY id DESC LIMIT %d", $per_page ), ARRAY_A );
|
||||
}
|
||||
$progress->finish();
|
||||
|
||||
WP_CLI::success( __( 'Finished', 'ewww-image-optimizer' ) );
|
||||
|
||||
\delete_option( 'ewww_image_optimizer_delete_originals_resume' );
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove all WebP images.
|
||||
*
|
||||
* ## OPTIONS
|
||||
*
|
||||
* <reset>
|
||||
* : optional, start the process back at the beginning instead of resuming from last position
|
||||
*
|
||||
* ## EXAMPLES
|
||||
*
|
||||
* wp-cli ewwwio remove_webp --reset
|
||||
*
|
||||
* @synopsis [--reset]
|
||||
*
|
||||
* @param array $args A numeric array of required arguments.
|
||||
* @param array $assoc_args An associative array of optional arguments.
|
||||
*/
|
||||
public function remove_webp( $args, $assoc_args ) {
|
||||
if ( ! empty( $assoc_args['reset'] ) ) {
|
||||
delete_option( 'ewww_image_optimizer_webp_clean_position' );
|
||||
}
|
||||
global $wpdb;
|
||||
if ( strpos( $wpdb->charset, 'utf8' ) === false ) {
|
||||
ewww_image_optimizer_db_init();
|
||||
global $ewwwdb;
|
||||
} else {
|
||||
$ewwwdb = $wpdb;
|
||||
}
|
||||
|
||||
$completed = 0;
|
||||
$per_page = 200;
|
||||
|
||||
$resume = get_option( 'ewww_image_optimizer_webp_clean_position' );
|
||||
$position1 = is_array( $resume ) && ! empty( $resume['stage1'] ) ? (int) $resume['stage1'] : 0;
|
||||
$position2 = is_array( $resume ) && ! empty( $resume['stage2'] ) ? (int) $resume['stage2'] : 0;
|
||||
|
||||
$cleanable_uploads = (int) $wpdb->get_var(
|
||||
$wpdb->prepare(
|
||||
"SELECT count(ID) FROM $wpdb->posts WHERE ID > %d AND (post_type = 'attachment' OR post_type = 'ims_image') AND (post_mime_type LIKE %s OR post_mime_type LIKE %s)",
|
||||
(int) $position1,
|
||||
'%image%',
|
||||
'%pdf%'
|
||||
)
|
||||
);
|
||||
$cleanable_records = (int) $wpdb->get_var(
|
||||
$wpdb->prepare(
|
||||
"SELECT count(id) FROM $wpdb->ewwwio_images WHERE id > %d AND pending = 0 AND image_size > 0 AND updates > 0",
|
||||
$position2
|
||||
)
|
||||
);
|
||||
|
||||
/* translators: 1: number of image uploads, 2: number of database records */
|
||||
WP_CLI::line( sprintf( __( 'WebP copies of %1$d media uploads will be removed first, then %2$d records in the optimization history will be checked to remove any remaining WebP images.', 'ewww-image-optimizer' ), $cleanable_uploads, $cleanable_records ) );
|
||||
WP_CLI::confirm( __( 'You should take a site backup before performing a bulk action on your images. Do you wish to continue?', 'ewww-image-optimizer' ) );
|
||||
|
||||
/**
|
||||
* Require the files that contain functions for the images table and bulk processing images outside the library.
|
||||
*/
|
||||
require_once EWWW_IMAGE_OPTIMIZER_PLUGIN_PATH . 'aux-optimize.php';
|
||||
|
||||
ewwwio_debug_message( "searching for $per_page records starting at $position1" );
|
||||
|
||||
$attachment_ids = $wpdb->get_col(
|
||||
$wpdb->prepare(
|
||||
"SELECT ID FROM $wpdb->posts WHERE ID > %d AND (post_type = 'attachment' OR post_type = 'ims_image') AND (post_mime_type LIKE %s OR post_mime_type LIKE %s) ORDER BY ID LIMIT %d",
|
||||
(int) $position1,
|
||||
'%image%',
|
||||
'%pdf%',
|
||||
(int) $per_page
|
||||
)
|
||||
);
|
||||
|
||||
$progress1 = \WP_CLI\Utils\make_progress_bar( __( 'Stage 1:', 'ewww-image-optimizer' ), $cleanable_uploads );
|
||||
|
||||
// Because some plugins might have loose filters (looking at you WPML).
|
||||
\remove_all_filters( 'wp_delete_file' );
|
||||
|
||||
while ( \ewww_image_optimizer_iterable( $attachment_ids ) ) {
|
||||
foreach ( $attachment_ids as $id ) {
|
||||
\ewww_image_optimizer_delete_webp( $id );
|
||||
$resume['stage1'] = (int) $id;
|
||||
\update_option( 'ewww_image_optimizer_webp_clean_position', $resume, false );
|
||||
$progress1->tick();
|
||||
}
|
||||
$attachment_ids = $wpdb->get_col(
|
||||
$wpdb->prepare(
|
||||
"SELECT ID FROM $wpdb->posts WHERE ID > %d AND (post_type = 'attachment' OR post_type = 'ims_image') AND (post_mime_type LIKE %s OR post_mime_type LIKE %s) ORDER BY ID LIMIT %d",
|
||||
(int) $id,
|
||||
'%image%',
|
||||
'%pdf%',
|
||||
(int) $per_page
|
||||
)
|
||||
);
|
||||
}
|
||||
$progress1->finish();
|
||||
|
||||
\ewwwio_debug_message( "searching for $per_page records starting at $position2" );
|
||||
|
||||
$optimized_images = $wpdb->get_results(
|
||||
$wpdb->prepare(
|
||||
"SELECT * FROM $wpdb->ewwwio_images WHERE id > %d AND pending = 0 AND image_size > 0 AND updates > 0 ORDER BY id LIMIT %d",
|
||||
(int) $position2,
|
||||
(int) $per_page
|
||||
),
|
||||
ARRAY_A
|
||||
);
|
||||
|
||||
$progress2 = \WP_CLI\Utils\make_progress_bar( __( 'Stage 2:', 'ewww-image-optimizer' ), $cleanable_records );
|
||||
|
||||
while ( \ewww_image_optimizer_iterable( $optimized_images ) ) {
|
||||
foreach ( $optimized_images as $optimized_image ) {
|
||||
\ewww_image_optimizer_aux_images_webp_clean( $optimized_image );
|
||||
$resume['stage2'] = $optimized_image['id'];
|
||||
\update_option( 'ewww_image_optimizer_webp_clean_position', $resume, false );
|
||||
$progress2->tick();
|
||||
}
|
||||
$optimized_images = $wpdb->get_results(
|
||||
$wpdb->prepare(
|
||||
"SELECT * FROM $wpdb->ewwwio_images WHERE id > %d AND pending = 0 AND image_size > 0 AND updates > 0 ORDER BY id LIMIT %d",
|
||||
(int) $optimized_image['id'],
|
||||
(int) $per_page
|
||||
),
|
||||
ARRAY_A
|
||||
);
|
||||
}
|
||||
$progress2->finish();
|
||||
WP_CLI::success( __( 'Finished', 'ewww-image-optimizer' ) );
|
||||
|
||||
\delete_option( 'ewww_image_optimizer_webp_clean_position' );
|
||||
}
|
||||
|
||||
/**
|
||||
* Cleanup after ourselves after a bulk operation.
|
||||
*/
|
||||
private function bulk_media_cleanup() {
|
||||
// All done, so we can update the bulk options with empty values...
|
||||
update_option( 'ewww_image_optimizer_bulk_resume', '' );
|
||||
update_option( 'ewww_image_optimizer_aux_resume', '' );
|
||||
// and let the user know we are done.
|
||||
WP_CLI::success( __( 'Finished Optimization!', 'ewww-image-optimizer' ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Bulk Optimize all GRAND FlaGallery uploads from WP-CLI.
|
||||
*
|
||||
* @global object $wpdb
|
||||
*
|
||||
* @param int $delay Number of seconds to pause between images.
|
||||
*/
|
||||
private function bulk_flag( $delay = 0 ) {
|
||||
$ids = null;
|
||||
if ( get_option( 'ewww_image_optimizer_bulk_flag_resume' ) ) {
|
||||
// If there is an operation to resume, get those IDs from the db.
|
||||
$ids = get_option( 'ewww_image_optimizer_bulk_flag_attachments' );
|
||||
} else {
|
||||
// Otherwise, if we are on the main bulk optimize page, just get all the IDs available.
|
||||
global $wpdb;
|
||||
$ids = $wpdb->get_col( "SELECT pid FROM $wpdb->flagpictures ORDER BY sortorder ASC" );
|
||||
// Store the IDs to optimize in the options table of the db.
|
||||
update_option( 'ewww_image_optimizer_bulk_flag_attachments', $ids, false );
|
||||
}
|
||||
$attachments = $ids; // Use this separately to keep track of progress in the db.
|
||||
// Set the resume flag to indicate the bulk operation is in progress.
|
||||
update_option( 'ewww_image_optimizer_bulk_flag_resume', 'true' );
|
||||
// Need this file to work with flag meta.
|
||||
require_once WP_CONTENT_DIR . '/plugins/flash-album-gallery/lib/meta.php';
|
||||
if ( ! ewww_image_optimizer_iterable( $ids ) ) {
|
||||
WP_CLI::line( __( 'You do not appear to have uploaded any images yet.', 'ewww-image-optimizer' ) );
|
||||
return;
|
||||
}
|
||||
foreach ( $ids as $id ) {
|
||||
if ( ewww_image_optimizer_function_exists( 'sleep' ) ) {
|
||||
sleep( $delay );
|
||||
}
|
||||
// Record the starting time for the current image (in microseconds).
|
||||
$started = microtime( true );
|
||||
// Retrieve the meta for the current ID.
|
||||
$meta = new flagMeta( $id );
|
||||
$file_path = $meta->image->imagePath;
|
||||
$ewww_image = new EWWW_Image( $id, 'flag', $file_path );
|
||||
$ewww_image->resize = 'full';
|
||||
// Optimize the full-size version.
|
||||
$fres = ewww_image_optimizer( $file_path, 3, false, false, true );
|
||||
WP_CLI::line( __( 'Optimized image:', 'ewww-image-optimizer' ) . ' ' . esc_html( $meta->image->filename ) );
|
||||
/* translators: %s: compression results */
|
||||
WP_CLI::line( sprintf( __( 'Full size – %s', 'ewww-image-optimizer' ), html_entity_decode( $fres[1] ) ) );
|
||||
if ( ! empty( $meta->image->meta_data['webview'] ) ) {
|
||||
// Determine path of the webview.
|
||||
$web_path = $meta->image->webimagePath;
|
||||
$ewww_image = new EWWW_Image( $id, 'flag', $web_path );
|
||||
$ewww_image->resize = 'webview';
|
||||
$wres = ewww_image_optimizer( $web_path, 3, false, true );
|
||||
/* translators: %s: compression results */
|
||||
WP_CLI::line( sprintf( __( 'Optimized size – %s', 'ewww-image-optimizer' ), html_entity_decode( $wres[1] ) ) );
|
||||
}
|
||||
$thumb_path = $meta->image->thumbPath;
|
||||
$ewww_image = new EWWW_Image( $id, 'flag', $thumb_path );
|
||||
$ewww_image->resize = 'thumbnail';
|
||||
// Optimize the thumbnail.
|
||||
$tres = ewww_image_optimizer( $thumb_path, 3, false, true );
|
||||
/* translators: %s: compression results */
|
||||
WP_CLI::line( sprintf( __( 'Thumbnail – %s', 'ewww-image-optimizer' ), html_entity_decode( $tres[1] ) ) );
|
||||
// Determine how much time the image took to process...
|
||||
$elapsed = microtime( true ) - $started;
|
||||
// and output it to the user.
|
||||
/* translators: %s: localized number of seconds */
|
||||
WP_CLI::line( sprintf( _n( 'Elapsed: %s second', 'Elapsed: %s seconds', $elapsed, 'ewww-image-optimizer' ), number_format_i18n( $elapsed, 2 ) ) );
|
||||
// Take the first image off the list.
|
||||
if ( ! empty( $attachments ) ) {
|
||||
array_shift( $attachments );
|
||||
}
|
||||
// And send the list back to the db.
|
||||
update_option( 'ewww_image_optimizer_bulk_flag_attachments', $attachments, false );
|
||||
} // End foreach().
|
||||
// Reset the bulk flags in the db...
|
||||
update_option( 'ewww_image_optimizer_bulk_flag_resume', '' );
|
||||
update_option( 'ewww_image_optimizer_bulk_flag_attachments', '', false );
|
||||
// and let the user know we are done.
|
||||
WP_CLI::success( __( 'Finished Optimization!', 'ewww-image-optimizer' ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Bulk Optimize all NextGEN uploads from WP-CLI.
|
||||
*
|
||||
* @global object $wpdb
|
||||
* @global object $ewwwngg
|
||||
*
|
||||
* @param int $delay Number of seconds to pause between images.
|
||||
*/
|
||||
private function bulk_ngg( $delay = 0 ) {
|
||||
if ( get_option( 'ewww_image_optimizer_bulk_ngg_resume' ) ) {
|
||||
// Get the list of attachment IDs from the db.
|
||||
$images = get_option( 'ewww_image_optimizer_bulk_ngg_attachments' );
|
||||
} else {
|
||||
// Otherwise, get all the images in the db.
|
||||
global $wpdb;
|
||||
$images = $wpdb->get_col( "SELECT pid FROM $wpdb->nggpictures ORDER BY sortorder ASC" );
|
||||
// Store the image IDs to process in the db.
|
||||
update_option( 'ewww_image_optimizer_bulk_ngg_attachments', $images, false );
|
||||
// Toggle the resume flag to indicate an operation is in progress.
|
||||
update_option( 'ewww_image_optimizer_bulk_ngg_resume', 'true' );
|
||||
}
|
||||
if ( ! ewww_image_optimizer_iterable( $images ) ) {
|
||||
WP_CLI::line( __( 'You do not appear to have uploaded any images yet.', 'ewww-image-optimizer' ) );
|
||||
return;
|
||||
}
|
||||
$attachments = $images; // Kept separate to update status in db.
|
||||
global $ewwwngg;
|
||||
global $ewww_defer;
|
||||
$ewww_defer = false;
|
||||
$clicount = 0;
|
||||
$pending_count = count( $images );
|
||||
foreach ( $images as $id ) {
|
||||
if ( ewww_image_optimizer_function_exists( 'sleep' ) ) {
|
||||
sleep( $delay );
|
||||
}
|
||||
// Output which image in the queue is being worked on.
|
||||
++$clicount;
|
||||
/* translators: 1: current image being proccessed 2: total number of images*/
|
||||
WP_CLI::line( sprintf( __( 'Processing image %1$d of %2$d', 'ewww-image-optimizer' ), $clicount, $pending_count ) );
|
||||
// Find out what time we started, in microseconds.
|
||||
$started = microtime( true );
|
||||
// Get an image object.
|
||||
$image = $ewwwngg->get_ngg_image( $id );
|
||||
$image = $ewwwngg->ewww_added_new_image( $image );
|
||||
// Output the results of the optimization.
|
||||
WP_CLI::line( __( 'Optimized image:', 'ewww-image-optimizer' ) . ' ' . basename( $ewwwngg->get_image_abspath( $image, 'full' ) ) );
|
||||
if ( ewww_image_optimizer_iterable( $ewwwngg->bulk_sizes ) ) {
|
||||
// Output the results for each $size.
|
||||
foreach ( $ewwwngg->bulk_sizes as $size => $results_msg ) {
|
||||
if ( 'backup' === $size ) {
|
||||
continue;
|
||||
} elseif ( 'full' === $size ) {
|
||||
/* translators: %s: compression results */
|
||||
WP_CLI::line( sprintf( __( 'Full size - %s', 'ewww-image-optimizer' ), html_entity_decode( $results_msg ) ) );
|
||||
} elseif ( 'thumbnail' === $size ) {
|
||||
// Output the results of the thumb optimization.
|
||||
/* translators: %s: compression results */
|
||||
WP_CLI::line( sprintf( __( 'Thumbnail - %s', 'ewww-image-optimizer' ), html_entity_decode( $results_msg ) ) );
|
||||
} else {
|
||||
// Output savings for any other sizes, if they ever exist...
|
||||
WP_CLI::line( ucfirst( $size ) . ' - ' . html_entity_decode( $results_msg ) );
|
||||
}
|
||||
}
|
||||
$ewwwngg->bulk_sizes = array();
|
||||
}
|
||||
// Output how much time we spent.
|
||||
$elapsed = microtime( true ) - $started;
|
||||
/* translators: %s: number of seconds */
|
||||
WP_CLI::line( sprintf( _n( 'Elapsed: %s second', 'Elapsed: %s seconds', $elapsed, 'ewww-image-optimizer' ), number_format_i18n( $elapsed, 2 ) ) );
|
||||
// Remove the first item.
|
||||
if ( ! empty( $attachments ) ) {
|
||||
array_shift( $attachments );
|
||||
}
|
||||
// And store the list back in the db.
|
||||
update_option( 'ewww_image_optimizer_bulk_ngg_attachments', $attachments, false );
|
||||
} // End foreach().
|
||||
|
||||
// Reset all the bulk options in the db.
|
||||
update_option( 'ewww_image_optimizer_bulk_ngg_resume', '' );
|
||||
update_option( 'ewww_image_optimizer_bulk_ngg_attachments', '', false );
|
||||
WP_CLI::success( __( 'Finished Optimization!', 'ewww-image-optimizer' ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Search for all Nextcellent uploads using WP-CLI command.
|
||||
*
|
||||
* @global object $wpdb
|
||||
*/
|
||||
private function scan_nextcellent() {
|
||||
$images = null;
|
||||
if ( get_option( 'ewww_image_optimizer_bulk_ngg_resume' ) ) {
|
||||
// If we have an operation to resume...
|
||||
// get the list of attachment IDs from the queue.
|
||||
$images = get_option( 'ewww_image_optimizer_bulk_ngg_attachments' );
|
||||
} else {
|
||||
// Otherwise, get all the images in the db.
|
||||
global $wpdb;
|
||||
$images = $wpdb->get_col( "SELECT pid FROM $wpdb->nggpictures ORDER BY sortorder ASC" );
|
||||
}
|
||||
|
||||
// Store the image IDs to process in the queue.
|
||||
update_option( 'ewww_image_optimizer_bulk_ngg_attachments', $images, false );
|
||||
return $images;
|
||||
}
|
||||
|
||||
/**
|
||||
* Bulk Optimize all Nextcellent uploads from WP-CLI.
|
||||
*
|
||||
* @param int $delay Number of seconds to pause between images.
|
||||
* @param array $attachments A list of image IDs to optimize.
|
||||
*/
|
||||
private function bulk_nextcellent( $delay, $attachments ) {
|
||||
global $ewwwngg;
|
||||
global $ewww_defer;
|
||||
$ewww_defer = false;
|
||||
// Toggle the resume flag to indicate an operation is in progress.
|
||||
update_option( 'ewww_image_optimizer_bulk_ngg_resume', 'true' );
|
||||
// Need this file to work with metadata.
|
||||
require_once WP_CONTENT_DIR . '/plugins/nextcellent-gallery-nextgen-legacy/lib/meta.php';
|
||||
foreach ( $attachments as $id ) {
|
||||
if ( ewww_image_optimizer_function_exists( 'sleep' ) ) {
|
||||
sleep( $delay );
|
||||
}
|
||||
// Find out what time we started, in microseconds.
|
||||
$started = microtime( true );
|
||||
// Optimize by ID.
|
||||
list( $fres, $tres ) = $ewwwngg->ewww_ngg_optimize( $id );
|
||||
if ( $fres[0] ) {
|
||||
// Output the results of the optimization.
|
||||
WP_CLI::line( __( 'Optimized image:', 'ewww-image-optimizer' ) . $fres[0] );
|
||||
}
|
||||
/* translators: %s: compression results */
|
||||
WP_CLI::line( sprintf( __( 'Full size - %s', 'ewww-image-optimizer' ), html_entity_decode( $fres[1] ) ) );
|
||||
// Output the results of the thumb optimization.
|
||||
/* translators: %s: compression results */
|
||||
WP_CLI::line( sprintf( __( 'Thumbnail - %s', 'ewww-image-optimizer' ), html_entity_decode( $tres[1] ) ) );
|
||||
// Output how much time we spent.
|
||||
$elapsed = microtime( true ) - $started;
|
||||
/* translators: %s: number of seconds */
|
||||
WP_CLI::line( sprintf( _n( 'Elapsed: %s second', 'Elapsed: %s seconds', $elapsed, 'ewww-image-optimizer' ), number_format_i18n( $elapsed, 2 ) ) );
|
||||
// Remove the first item.
|
||||
if ( ! empty( $attachments ) ) {
|
||||
array_shift( $attachments );
|
||||
}
|
||||
// and store the list back in the db queue.
|
||||
update_option( 'ewww_image_optimizer_bulk_ngg_attachments', $attachments, false );
|
||||
} // End foreach().
|
||||
// Reset all the bulk options in the db.
|
||||
update_option( 'ewww_image_optimizer_bulk_ngg_resume', '' );
|
||||
update_option( 'ewww_image_optimizer_bulk_ngg_attachments', '', false );
|
||||
WP_CLI::success( __( 'Finished Optimization!', 'ewww-image-optimizer' ) );
|
||||
}
|
||||
}
|
||||
|
||||
WP_CLI::add_command( 'ewwwio', 'EWWWIO_CLI' );
|
||||
|
||||
/**
|
||||
* Increases the EWWW IO timeout for scanning images.
|
||||
*
|
||||
* @param int $time_limit The number of seconds before a timeout happens.
|
||||
* @return int The number of seconds to wait before a timeout from the CLI.
|
||||
*/
|
||||
function ewww_image_optimizer_cli_timeout( $time_limit ) {
|
||||
return 9999;
|
||||
}
|
@ -0,0 +1,454 @@
|
||||
<?php
|
||||
/**
|
||||
* Class and methods to integrate with the WP_Image_Editor_GD class and other extensions.
|
||||
*
|
||||
* @link https://ewww.io
|
||||
* @package EWWW_Image_Optimizer
|
||||
*/
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extension of the WP_Image_Editor_GD class to auto-compress edited images.
|
||||
*
|
||||
* @see WP_Image_Editor_GD
|
||||
*/
|
||||
class EWWWIO_GD_Editor extends WP_Image_Editor_GD {
|
||||
|
||||
/**
|
||||
* GD Resource.
|
||||
*
|
||||
* @access protected
|
||||
* @var resource|GdImage $ewww_image
|
||||
*/
|
||||
protected $ewww_image;
|
||||
|
||||
/**
|
||||
* Site (URL) for the plugin to use.
|
||||
*
|
||||
* @access protected
|
||||
* @var string $site_url
|
||||
*/
|
||||
protected $modified = false;
|
||||
|
||||
/**
|
||||
* Resizes current image.
|
||||
*
|
||||
* Requires width or height, crop is optional. Uses gifsicle to preserve GIF animations.
|
||||
* Also use API in future for better quality resizing.
|
||||
*
|
||||
* @since 4.4.0
|
||||
*
|
||||
* @param int|null $max_w Image width.
|
||||
* @param int|null $max_h Image height.
|
||||
* @param bool $crop Optional. Scale by default, crop if true.
|
||||
* @return bool|WP_Error
|
||||
*/
|
||||
protected function _resize( $max_w, $max_h, $crop = false ) {
|
||||
ewwwio_debug_message( '<b>' . __METHOD__ . '()</b>' );
|
||||
$dims = image_resize_dimensions( $this->size['width'], $this->size['height'], $max_w, $max_h, $crop );
|
||||
if ( ! $dims ) {
|
||||
return new WP_Error( 'error_getting_dimensions', __( 'Could not calculate resized image dimensions' ), $this->file );
|
||||
}
|
||||
list( $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h ) = $dims;
|
||||
ewwwio_debug_message( "dst_x $dst_x, dst_y $dst_y, src_x $src_x, src_y $src_y, dst_w $dst_w, dst_h $dst_h, src_w $src_w, src_h $src_h" );
|
||||
|
||||
if ( defined( 'EWWWIO_EDITOR_AGR' ) && ! EWWWIO_EDITOR_AGR ) {
|
||||
ewwwio_debug_message( 'AGR disabled' );
|
||||
return parent::_resize( $max_w, $max_h, $crop );
|
||||
}
|
||||
if ( defined( 'EWWWIO_EDITOR_BETTER_RESIZE' ) && ! EWWW_IO_EDITOR_BETTER_RESIZE ) {
|
||||
ewwwio_debug_message( 'API resize disabled' );
|
||||
return parent::_resize( $max_w, $max_h, $crop );
|
||||
}
|
||||
$ewww_status = get_transient( 'ewww_image_optimizer_cloud_status' );
|
||||
if ( 'image/gif' === $this->mime_type && ! ewww_image_optimizer_get_option( 'ewww_image_optimizer_cloud_key' ) ) {
|
||||
$gifsicle_path = ewwwio()->local->get_path( 'gifsicle' );
|
||||
}
|
||||
// If this is a GIF, and we have no gifsicle, and there's an API key, but the status isn't 'great',
|
||||
// double-check the key to see if the status has changed before bailing.
|
||||
if (
|
||||
'image/gif' === $this->mime_type &&
|
||||
empty( $gifsicle_path ) &&
|
||||
false === strpos( $ewww_status, 'great' ) &&
|
||||
ewww_image_optimizer_get_option( 'ewww_image_optimizer_cloud_key' ) &&
|
||||
! ewww_image_optimizer_cloud_verify( ewww_image_optimizer_get_option( 'ewww_image_optimizer_cloud_key' ) )
|
||||
) {
|
||||
ewwwio_debug_message( 'no gifsicle or API to resize an animated GIF' );
|
||||
return parent::_resize( $max_w, $max_h, $crop );
|
||||
}
|
||||
// If this is some other image, and there's an API key, but the status isn't 'great',
|
||||
// double-check the key to see if the status has changed before bailing.
|
||||
if (
|
||||
'image/gif' !== $this->mime_type &&
|
||||
false === strpos( $ewww_status, 'great' ) &&
|
||||
ewww_image_optimizer_get_option( 'ewww_image_optimizer_cloud_key' ) &&
|
||||
! ewww_image_optimizer_cloud_verify( ewww_image_optimizer_get_option( 'ewww_image_optimizer_cloud_key' ) )
|
||||
) {
|
||||
ewwwio_debug_message( 'no API to resize the image' );
|
||||
return parent::_resize( $max_w, $max_h, $crop );
|
||||
}
|
||||
// If this isn't a GIF, or if the GIF isn't animated, then bail--we don't yet support "better resizing" for non-GIFs.
|
||||
if ( 'image/gif' !== $this->mime_type || ! ewww_image_optimizer_is_animated( $this->file ) ) {
|
||||
ewwwio_debug_message( 'not an animated GIF' );
|
||||
return parent::_resize( $max_w, $max_h, $crop );
|
||||
}
|
||||
// TODO: Possibly handle crop, rotate, and flip down the road.
|
||||
if ( $this->modified ) {
|
||||
ewwwio_debug_message( 'GIF already altered! Too late, so leave it alone...' );
|
||||
return parent::_resize( $max_w, $max_h, $crop );
|
||||
}
|
||||
if (
|
||||
! $this->file ||
|
||||
ewww_image_optimizer_stream_wrapped( $this->file ) ||
|
||||
0 === strpos( $this->file, 'http' ) ||
|
||||
0 === strpos( $this->file, 'ftp' ) ||
|
||||
! ewwwio_is_file( $this->file )
|
||||
) {
|
||||
ewwwio_debug_message( 'could not load original file, or remote path detected' );
|
||||
return parent::_resize( $max_w, $max_h, $crop );
|
||||
}
|
||||
$resize_result = ewww_image_optimizer_better_resize( $this->file, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h );
|
||||
if ( is_wp_error( $resize_result ) ) {
|
||||
return $resize_result;
|
||||
}
|
||||
|
||||
$new_size = getimagesizefromstring( $resize_result );
|
||||
if ( empty( $new_size ) ) {
|
||||
return new WP_Error( 'image_resize_error', __( 'Image resize failed.' ) );
|
||||
}
|
||||
$this->update_size( $new_size[0], $new_size[1] );
|
||||
return $resize_result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resizes current image.
|
||||
* Wraps _resize, since _resize returns a GD Resource.
|
||||
*
|
||||
* At minimum, either a height or width must be provided.
|
||||
* If one of the two is set to null, the resize will
|
||||
* maintain aspect ratio according to the provided dimension.
|
||||
*
|
||||
* @since 4.4.0
|
||||
*
|
||||
* @param int|null $max_w Image width.
|
||||
* @param int|null $max_h Image height.
|
||||
* @param bool $crop Optional. Scale by default, crop if true.
|
||||
* @return true|WP_Error
|
||||
*/
|
||||
public function resize( $max_w, $max_h, $crop = false ) {
|
||||
ewwwio_debug_message( '<b>' . __METHOD__ . '()</b>' );
|
||||
if ( (int) $this->size['width'] === (int) $max_w && (int) $this->size['height'] === (int) $max_h ) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$resized = $this->_resize( $max_w, $max_h, $crop );
|
||||
|
||||
if ( is_resource( $resized ) || ( is_object( $resized ) && $resized instanceof GdImage ) ) {
|
||||
imagedestroy( $this->image );
|
||||
$this->image = $resized;
|
||||
return true;
|
||||
} elseif ( is_string( $resized ) ) {
|
||||
$this->ewww_image = $resized;
|
||||
imagedestroy( $this->image );
|
||||
$this->image = @imagecreatefromstring( $resized );
|
||||
return true;
|
||||
} elseif ( is_wp_error( $resized ) ) {
|
||||
return $resized;
|
||||
}
|
||||
return new WP_Error( 'image_resize_error', __( 'Image resize failed.' ), $this->file );
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an image sub-size and return the image meta data value for it.
|
||||
*
|
||||
* @since 5.3.0
|
||||
*
|
||||
* @param array $size_data {
|
||||
* Array of size data.
|
||||
*
|
||||
* @type int $width The maximum width in pixels.
|
||||
* @type int $height The maximum height in pixels.
|
||||
* @type bool $crop Whether to crop the image to exact dimensions.
|
||||
* }
|
||||
* @return array|WP_Error The image data array for inclusion in the `sizes` array in the image meta,
|
||||
* WP_Error object on error.
|
||||
*/
|
||||
public function make_subsize( $size_data ) {
|
||||
ewwwio_debug_message( '<b>' . __METHOD__ . '()</b>' );
|
||||
if ( ! isset( $size_data['width'] ) && ! isset( $size_data['height'] ) ) {
|
||||
return new WP_Error( 'image_subsize_create_error', __( 'Cannot resize the image. Both width and height are not set.' ) );
|
||||
}
|
||||
|
||||
$orig_size = $this->size;
|
||||
|
||||
if ( ! isset( $size_data['width'] ) ) {
|
||||
$size_data['width'] = null;
|
||||
}
|
||||
|
||||
if ( ! isset( $size_data['height'] ) ) {
|
||||
$size_data['height'] = null;
|
||||
}
|
||||
|
||||
if ( ! isset( $size_data['crop'] ) ) {
|
||||
$size_data['crop'] = false;
|
||||
}
|
||||
|
||||
$resized = $this->_resize( $size_data['width'], $size_data['height'], $size_data['crop'] );
|
||||
|
||||
if ( is_string( $resized ) ) {
|
||||
$this->ewww_image = $resized;
|
||||
}
|
||||
if ( is_wp_error( $resized ) ) {
|
||||
$saved = $resized;
|
||||
} else {
|
||||
$saved = $this->_save( $resized );
|
||||
}
|
||||
|
||||
$this->size = $orig_size;
|
||||
|
||||
if ( ! is_wp_error( $saved ) ) {
|
||||
unset( $saved['path'] );
|
||||
}
|
||||
|
||||
return $saved;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resize multiple images from a single source.
|
||||
*
|
||||
* @since 4.4.0
|
||||
*
|
||||
* @param array $sizes {
|
||||
* An array of image size arrays. Default sizes are 'small', 'medium', 'medium_large', 'large'.
|
||||
*
|
||||
* Either a height or width must be provided.
|
||||
* If one of the two is set to null, the resize will
|
||||
* maintain aspect ratio according to the provided dimension.
|
||||
* Likewise, if crop is false, aspect ratio will also be preserved.
|
||||
*
|
||||
* @type array $size {
|
||||
* Array of height, width values, and whether to crop.
|
||||
*
|
||||
* @type int $width Image width. Optional if `$height` is specified.
|
||||
* @type int $height Image height. Optional if `$width` is specified.
|
||||
* @type bool $crop Optional. Whether to crop the image. Default false.
|
||||
* }
|
||||
* }
|
||||
* @return array An array of resized images' metadata by size.
|
||||
*/
|
||||
public function multi_resize( $sizes ) {
|
||||
ewwwio_debug_message( '<b>' . __METHOD__ . '()</b>' );
|
||||
global $wp_version;
|
||||
if ( version_compare( $wp_version, '5.3' ) >= 0 ) {
|
||||
return parent::multi_resize( $sizes );
|
||||
}
|
||||
$metadata = array();
|
||||
$orig_size = $this->size;
|
||||
foreach ( $sizes as $size => $size_data ) {
|
||||
if ( ! isset( $size_data['width'] ) && ! isset( $size_data['height'] ) ) {
|
||||
continue;
|
||||
}
|
||||
if ( ! isset( $size_data['width'] ) ) {
|
||||
$size_data['width'] = null;
|
||||
}
|
||||
if ( ! isset( $size_data['height'] ) ) {
|
||||
$size_data['height'] = null;
|
||||
}
|
||||
if ( ! isset( $size_data['crop'] ) ) {
|
||||
$size_data['crop'] = false;
|
||||
}
|
||||
|
||||
$image = $this->_resize( $size_data['width'], $size_data['height'], $size_data['crop'] );
|
||||
$duplicate = ( (int) $orig_size['width'] === (int) $size_data['width'] && (int) $orig_size['height'] === (int) $size_data['height'] );
|
||||
|
||||
if ( ! is_wp_error( $image ) && ! $duplicate ) {
|
||||
if ( is_resource( $image ) || ( is_object( $image ) && $image instanceof GdImage ) ) {
|
||||
$resized = $this->_save( $image );
|
||||
imagedestroy( $image );
|
||||
} elseif ( is_string( $image ) ) {
|
||||
$resized = $this->_save_ewwwio_file( $image );
|
||||
unset( $image );
|
||||
}
|
||||
if ( ! is_wp_error( $resized ) && $resized ) {
|
||||
unset( $resized['path'] );
|
||||
$metadata[ $size ] = $resized;
|
||||
}
|
||||
}
|
||||
|
||||
$this->size = $orig_size;
|
||||
}
|
||||
return $metadata;
|
||||
}
|
||||
|
||||
/**
|
||||
* Crops Image.
|
||||
*
|
||||
* Currently does nothing more than call the parent and let us know the image is modified.
|
||||
*
|
||||
* @since 4.4.0
|
||||
*
|
||||
* @param int $src_x The start x position to crop from.
|
||||
* @param int $src_y The start y position to crop from.
|
||||
* @param int $src_w The width to crop.
|
||||
* @param int $src_h The height to crop.
|
||||
* @param int $dst_w Optional. The destination width.
|
||||
* @param int $dst_h Optional. The destination height.
|
||||
* @param bool $src_abs Optional. If the source crop points are absolute.
|
||||
* @return bool|WP_Error
|
||||
*/
|
||||
public function crop( $src_x, $src_y, $src_w, $src_h, $dst_w = null, $dst_h = null, $src_abs = false ) {
|
||||
$this->modified = 'crop';
|
||||
return parent::crop( $src_x, $src_y, $src_w, $src_h, $dst_w, $dst_h, $src_abs );
|
||||
}
|
||||
|
||||
/**
|
||||
* Rotates current image counter-clockwise by $angle.
|
||||
*
|
||||
* Currently does nothing more than call the parent and let us know the image is modified.
|
||||
*
|
||||
* @since 4.4.0
|
||||
*
|
||||
* @param float $angle The number of degrees for rotation.
|
||||
* @return true|WP_Error
|
||||
*/
|
||||
public function rotate( $angle ) {
|
||||
$this->modified = 'rotate';
|
||||
return parent::rotate( $angle );
|
||||
}
|
||||
|
||||
/**
|
||||
* Flips current image.
|
||||
*
|
||||
* Currently does nothing more than call the parent and let us know the image is modified.
|
||||
*
|
||||
* @since 4.4.0
|
||||
*
|
||||
* @param bool $horz Flip along Horizontal Axis.
|
||||
* @param bool $vert Flip along Vertical Axis.
|
||||
* @return true|WP_Error
|
||||
*/
|
||||
public function flip( $horz, $vert ) {
|
||||
$this->modified = 'flip';
|
||||
return parent::flip( $horz, $vert );
|
||||
}
|
||||
|
||||
/**
|
||||
* Saves a file from the EWWW IO API-enabled image editor.
|
||||
*
|
||||
* @since 4.4.0
|
||||
*
|
||||
* @param string $image A string containing the image contents.
|
||||
* @param string $filename Optional. The name of the file to be saved to.
|
||||
* @param string $mime_type Optional. The mimetype of the file.
|
||||
* @return WP_Error|array The full path, base filename, and mimetype.
|
||||
*/
|
||||
protected function _save_ewwwio_file( $image, $filename = null, $mime_type = null ) {
|
||||
ewwwio_debug_message( '<b>' . __METHOD__ . '()</b>' );
|
||||
list( $filename, $extension, $mime_type ) = $this->get_output_format( $filename, $mime_type );
|
||||
if ( ! $filename ) {
|
||||
$filename = $this->generate_filename( null, null, $extension );
|
||||
}
|
||||
if ( wp_is_stream( $filename ) ) {
|
||||
$image = @imagecreatefromstring( $image );
|
||||
unset( $this->ewww_image );
|
||||
return parent::_save( $image, $filename, $mime_type );
|
||||
}
|
||||
if ( ! is_string( $image ) ) {
|
||||
unset( $this->ewww_image );
|
||||
return parent::_save( $image, $filename, $mime_type );
|
||||
}
|
||||
global $ewww_preempt_editor;
|
||||
if ( ( ! defined( 'EWWWIO_EDITOR_OVERWRITE' ) || ! EWWWIO_EDITOR_OVERWRITE ) && ewwwio_is_file( $filename ) && empty( $ewww_preempt_editor ) ) {
|
||||
ewwwio_debug_message( "detected existing file: $filename" );
|
||||
$current_size = wp_getimagesize( $filename );
|
||||
if ( $current_size && (int) $this->size['width'] === (int) $current_size[0] && (int) $this->size['height'] === (int) $current_size[1] ) {
|
||||
ewwwio_debug_message( "existing file has same dimensions, not saving $filename" );
|
||||
return array(
|
||||
'path' => $filename,
|
||||
'file' => wp_basename( apply_filters( 'image_make_intermediate_size', $filename ) ),
|
||||
'width' => $this->size['width'],
|
||||
'height' => $this->size['height'],
|
||||
'mime-type' => $mime_type,
|
||||
);
|
||||
}
|
||||
}
|
||||
// Write out the image (substitute for $this->make_image()).
|
||||
wp_mkdir_p( dirname( $filename ) );
|
||||
$result = file_put_contents( $filename, $image );
|
||||
if ( $result ) {
|
||||
ewwwio_debug_message( "image editor (gd-api-enhanced) saved: $filename" );
|
||||
if ( is_writable( $filename ) ) {
|
||||
$stat = stat( dirname( $filename ) );
|
||||
$perms = $stat['mode'] & 0000666; // Same permissions as parent folder with executable bits stripped.
|
||||
ewwwio_chmod( $filename, $perms );
|
||||
}
|
||||
ewwwio_memory( __METHOD__ );
|
||||
return array(
|
||||
'path' => $filename,
|
||||
'file' => wp_basename( apply_filters( 'image_make_intermediate_size', $filename ) ),
|
||||
'width' => $this->size['width'],
|
||||
'height' => $this->size['height'],
|
||||
'mime-type' => $mime_type,
|
||||
);
|
||||
}
|
||||
ewwwio_memory( __METHOD__ );
|
||||
return new WP_Error( 'image_save_error', __( 'Image Editor Save Failed' ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Saves a file from the image editor.
|
||||
*
|
||||
* @since 1.7.0
|
||||
*
|
||||
* @param resource $image A GD image object.
|
||||
* @param string $filename Optional. The name of the file to be saved to.
|
||||
* @param string $mime_type Optional. The mimetype of the file.
|
||||
* @return WP_Error|array The full path, base filename, and mimetype.
|
||||
*/
|
||||
protected function _save( $image, $filename = null, $mime_type = null ) {
|
||||
ewwwio_debug_message( '<b>' . __METHOD__ . '()</b>' );
|
||||
global $ewww_defer;
|
||||
global $ewww_preempt_editor;
|
||||
if ( ! empty( $this->ewww_image ) && ! $this->modified ) {
|
||||
return $this->_save_ewwwio_file( $this->ewww_image, $filename, $mime_type );
|
||||
}
|
||||
if ( ! empty( $ewww_preempt_editor ) || ! defined( 'EWWW_IMAGE_OPTIMIZER_ENABLE_EDITOR' ) || ! EWWW_IMAGE_OPTIMIZER_ENABLE_EDITOR ) {
|
||||
return parent::_save( $image, $filename, $mime_type );
|
||||
}
|
||||
list( $filename, $extension, $mime_type ) = $this->get_output_format( $filename, $mime_type );
|
||||
if ( ! $filename ) {
|
||||
$filename = $this->generate_filename( null, null, $extension );
|
||||
}
|
||||
if ( ( ! defined( 'EWWWIO_EDITOR_OVERWRITE' ) || ! EWWWIO_EDITOR_OVERWRITE ) && ewwwio_is_file( $filename ) ) {
|
||||
ewwwio_debug_message( "detected existing file: $filename" );
|
||||
$current_size = wp_getimagesize( $filename );
|
||||
if ( $current_size && (int) $this->size['width'] === (int) $current_size[0] && (int) $this->size['height'] === (int) $current_size[1] ) {
|
||||
ewwwio_debug_message( "existing file has same dimensions, not saving $filename" );
|
||||
return array(
|
||||
'path' => $filename,
|
||||
'file' => wp_basename( apply_filters( 'image_make_intermediate_size', $filename ) ),
|
||||
'width' => $this->size['width'],
|
||||
'height' => $this->size['height'],
|
||||
'mime-type' => $mime_type,
|
||||
);
|
||||
}
|
||||
}
|
||||
$saved = parent::_save( $image, $filename, $mime_type );
|
||||
if ( ! is_wp_error( $saved ) ) {
|
||||
if ( ! $filename ) {
|
||||
$filename = $saved['path'];
|
||||
}
|
||||
if ( file_exists( $filename ) ) {
|
||||
ewww_image_optimizer( $filename );
|
||||
ewwwio_debug_message( "image editor (gd) saved: $filename" );
|
||||
$image_size = ewww_image_optimizer_filesize( $filename );
|
||||
ewwwio_debug_message( "image editor size: $image_size" );
|
||||
}
|
||||
}
|
||||
ewwwio_memory( __METHOD__ );
|
||||
return $saved;
|
||||
}
|
||||
}
|
@ -0,0 +1,68 @@
|
||||
<?php
|
||||
/**
|
||||
* Class and methods to integrate with the WP_Image_Editor_Gmagick class and other extensions.
|
||||
*
|
||||
* @link https://ewww.io
|
||||
* @package EWWW_Image_Optimizer
|
||||
*/
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit;
|
||||
}
|
||||
|
||||
if ( class_exists( 'WP_Image_Editor_Gmagick' ) ) {
|
||||
/**
|
||||
* Extension of the WP_Image_Editor_Gmagick class to auto-compress edited images.
|
||||
*
|
||||
* @see WP_Image_Editor_Gmagick
|
||||
*/
|
||||
class EWWWIO_Gmagick_Editor extends WP_Image_Editor_Gmagick {
|
||||
/**
|
||||
* Saves a file from the image editor.
|
||||
*
|
||||
* @param resource $image A Gmagick image object.
|
||||
* @param string $filename Optional. The name of the file to be saved to.
|
||||
* @param string $mime_type Optional. The mimetype of the file.
|
||||
* @return WP_Error| array The full path, base filename, width, height, and mimetype.
|
||||
*/
|
||||
protected function _save( $image, $filename = null, $mime_type = null ) {
|
||||
global $ewww_defer;
|
||||
global $ewww_preempt_editor;
|
||||
if ( ! empty( $ewww_preempt_editor ) || ! defined( 'EWWW_IMAGE_OPTIMIZER_ENABLE_EDITOR' ) || ! EWWW_IMAGE_OPTIMIZER_ENABLE_EDITOR ) {
|
||||
return parent::_save( $image, $filename, $mime_type );
|
||||
}
|
||||
list( $filename, $extension, $mime_type ) = $this->get_output_format( $filename, $mime_type );
|
||||
if ( ! $filename ) {
|
||||
$filename = $this->generate_filename( null, null, $extension );
|
||||
}
|
||||
if ( ( ! defined( 'EWWWIO_EDITOR_OVERWRITE' ) || ! EWWWIO_EDITOR_OVERWRITE ) && ewwwio_is_file( $filename ) ) {
|
||||
ewwwio_debug_message( "detected existing file: $filename" );
|
||||
$current_size = wp_getimagesize( $filename );
|
||||
if ( $current_size && (int) $this->size['width'] === (int) $current_size[0] && (int) $this->size['height'] === (int) $current_size[1] ) {
|
||||
ewwwio_debug_message( "existing file has same dimensions, not saving $filename" );
|
||||
return array(
|
||||
'path' => $filename,
|
||||
'file' => wp_basename( apply_filters( 'image_make_intermediate_size', $filename ) ),
|
||||
'width' => $this->size['width'],
|
||||
'height' => $this->size['height'],
|
||||
'mime-type' => $mime_type,
|
||||
);
|
||||
}
|
||||
}
|
||||
$saved = parent::_save( $image, $filename, $mime_type );
|
||||
if ( ! is_wp_error( $saved ) ) {
|
||||
if ( ! $filename ) {
|
||||
$filename = $saved['path'];
|
||||
}
|
||||
if ( file_exists( $filename ) ) {
|
||||
ewww_image_optimizer( $filename );
|
||||
ewwwio_debug_message( "image editor (gmagick) saved: $filename" );
|
||||
$image_size = ewww_image_optimizer_filesize( $filename );
|
||||
ewwwio_debug_message( "image editor size: $image_size" );
|
||||
}
|
||||
}
|
||||
ewwwio_memory( __FUNCTION__ );
|
||||
return $saved;
|
||||
}
|
||||
}
|
||||
} // End if().
|
@ -0,0 +1,591 @@
|
||||
<?php
|
||||
/**
|
||||
* Class and methods to integrate with the WP_Image_Editor_Imagick class and other extensions.
|
||||
*
|
||||
* @link https://ewww.io
|
||||
* @package EWWW_Image_Optimizer
|
||||
*/
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extension of the WP_Image_Editor_Imagick class to auto-compress edited images.
|
||||
*
|
||||
* @see WP_Image_Editor_Imagick
|
||||
*/
|
||||
class EWWWIO_Imagick_Editor extends WP_Image_Editor_Imagick {
|
||||
|
||||
/**
|
||||
* GD Resource.
|
||||
*
|
||||
* @access protected
|
||||
* @var resource|GdImage $ewww_image
|
||||
*/
|
||||
protected $ewww_image;
|
||||
|
||||
/**
|
||||
* Site (URL) for the plugin to use.
|
||||
*
|
||||
* @access protected
|
||||
* @var string $site_url
|
||||
*/
|
||||
protected $modified = false;
|
||||
|
||||
/**
|
||||
* Resizes current image.
|
||||
* Wraps _resize, since _resize returns a GD Resource.
|
||||
*
|
||||
* At minimum, either a height or width must be provided.
|
||||
* If one of the two is set to null, the resize will
|
||||
* maintain aspect ratio according to the provided dimension.
|
||||
*
|
||||
* @since 4.6.0
|
||||
*
|
||||
* @param int|null $max_w Image width.
|
||||
* @param int|null $max_h Image height.
|
||||
* @param bool $crop Optional. Scale by default, crop if true.
|
||||
* @return true|WP_Error
|
||||
*/
|
||||
public function resize( $max_w, $max_h, $crop = false ) {
|
||||
ewwwio_debug_message( '<b>wp_image_editor_imagick::' . __FUNCTION__ . '()</b>' );
|
||||
if ( (int) $this->size['width'] === (int) $max_w && (int) $this->size['height'] === (int) $max_h ) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$dims = image_resize_dimensions( $this->size['width'], $this->size['height'], $max_w, $max_h, $crop );
|
||||
if ( ! $dims ) {
|
||||
return new WP_Error( 'error_getting_dimensions', __( 'Could not calculate resized image dimensions' ) );
|
||||
}
|
||||
list( $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h ) = $dims;
|
||||
|
||||
$resized = $this->_resize( $dims, $crop );
|
||||
|
||||
if ( is_string( $resized ) ) {
|
||||
$this->ewww_image = $resized;
|
||||
return $resized;
|
||||
} elseif ( is_wp_error( $resized ) ) {
|
||||
return $resized;
|
||||
}
|
||||
return $this->update_size( $dst_w, $dst_h );
|
||||
}
|
||||
|
||||
/**
|
||||
* Resizes current image.
|
||||
*
|
||||
* Uses gifsicle to preserve GIF animations.
|
||||
*
|
||||
* @since 4.6.0
|
||||
*
|
||||
* @param array $dims {
|
||||
* All parameters necessary for resizing.
|
||||
*
|
||||
* @type int $dst_x X-coordinate of destination image (usually 0).
|
||||
* @type int $dst_y Y-coordinate of destination image (usually 0).
|
||||
* @type int $src_x X-coordinate of source image (usually 0 unless cropping).
|
||||
* @type int $src_y Y-coordinate of source image (usually 0 unless cropping).
|
||||
* @type int $dst_w Desired image width.
|
||||
* @type int $dst_h Desired image height.
|
||||
* @type int $src_w Source width.
|
||||
* @type int $src_h Source height.
|
||||
* }
|
||||
* @param bool $crop Should we crop or should we scale.
|
||||
* @return bool|WP_Error
|
||||
*/
|
||||
protected function _resize( $dims, $crop ) {
|
||||
ewwwio_debug_message( '<b>wp_image_editor_imagick::' . __FUNCTION__ . '()</b>' );
|
||||
list( $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h ) = $dims;
|
||||
if ( defined( 'EWWWIO_EDITOR_AGR' ) && ! EWWWIO_EDITOR_AGR ) {
|
||||
ewwwio_debug_message( 'AGR disabled' );
|
||||
if ( $crop ) {
|
||||
return $this->crop( $src_x, $src_y, $src_w, $src_h, $dst_w, $dst_h );
|
||||
}
|
||||
return $this->thumbnail_image( $dst_w, $dst_h );
|
||||
}
|
||||
if ( defined( 'EWWWIO_EDITOR_BETTER_RESIZE' ) && ! EWWW_IO_EDITOR_BETTER_RESIZE ) {
|
||||
ewwwio_debug_message( 'API resize disabled' );
|
||||
if ( $crop ) {
|
||||
return $this->crop( $src_x, $src_y, $src_w, $src_h, $dst_w, $dst_h );
|
||||
}
|
||||
return $this->thumbnail_image( $dst_w, $dst_h );
|
||||
}
|
||||
$return_parent = false; // An indicator for whether we should short-circuit and use the parent thumbnail_image method.
|
||||
$ewww_status = get_transient( 'ewww_image_optimizer_cloud_status' );
|
||||
if ( 'image/gif' === $this->mime_type && ! ewww_image_optimizer_get_option( 'ewww_image_optimizer_cloud_key' ) ) {
|
||||
$gifsicle_path = ewwwio()->local->get_path( 'gifsicle' );
|
||||
}
|
||||
// If this is a GIF, and we have no gifsicle, and there's an API key, but the status isn't 'great',
|
||||
// double-check the key to see if the status has changed before bailing.
|
||||
if (
|
||||
'image/gif' === $this->mime_type &&
|
||||
empty( $gifsicle_path ) &&
|
||||
false === strpos( $ewww_status, 'great' ) &&
|
||||
ewww_image_optimizer_get_option( 'ewww_image_optimizer_cloud_key' ) &&
|
||||
! ewww_image_optimizer_cloud_verify( ewww_image_optimizer_get_option( 'ewww_image_optimizer_cloud_key' ) )
|
||||
) {
|
||||
ewwwio_debug_message( 'no gifsicle or API to resize an animated GIF' );
|
||||
$return_parent = true;
|
||||
}
|
||||
// If this is some other image, and there's an API key, but the status isn't 'great',
|
||||
// double-check the key to see if the status has changed before bailing.
|
||||
if (
|
||||
'image/gif' !== $this->mime_type &&
|
||||
false === strpos( $ewww_status, 'great' ) &&
|
||||
ewww_image_optimizer_get_option( 'ewww_image_optimizer_cloud_key' ) &&
|
||||
! ewww_image_optimizer_cloud_verify( ewww_image_optimizer_get_option( 'ewww_image_optimizer_cloud_key' ) )
|
||||
) {
|
||||
ewwwio_debug_message( 'no API to resize the image' );
|
||||
$return_parent = true;
|
||||
}
|
||||
// If this isn't a GIF, or if the GIF isn't animated, then bail--we don't yet support "better resizing" for non-GIFs.
|
||||
if ( 'image/gif' !== $this->mime_type || ! ewww_image_optimizer_is_animated( $this->file ) ) {
|
||||
ewwwio_debug_message( 'not an animated GIF' );
|
||||
$return_parent = true;
|
||||
}
|
||||
// TODO: Possibly handle crop, rotate, and flip down the road.
|
||||
if ( $this->modified ) {
|
||||
ewwwio_debug_message( 'image already altered, leave it alone' );
|
||||
$return_parent = true;
|
||||
}
|
||||
if (
|
||||
! $this->file ||
|
||||
ewww_image_optimizer_stream_wrapped( $this->file ) ||
|
||||
0 === strpos( $this->file, 'http' ) ||
|
||||
0 === strpos( $this->file, 'ftp' ) ||
|
||||
! ewwwio_is_file( $this->file )
|
||||
) {
|
||||
ewwwio_debug_message( 'could not load original file, or remote path detected' );
|
||||
$return_parent = true;
|
||||
}
|
||||
if ( $return_parent ) {
|
||||
if ( $crop ) {
|
||||
return $this->crop( $src_x, $src_y, $src_w, $src_h, $dst_w, $dst_h );
|
||||
}
|
||||
return $this->thumbnail_image( $dst_w, $dst_h );
|
||||
}
|
||||
$resize_result = ewww_image_optimizer_better_resize( $this->file, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h );
|
||||
if ( is_wp_error( $resize_result ) ) {
|
||||
return $resize_result;
|
||||
}
|
||||
|
||||
$imagick = new Imagick();
|
||||
$new_size = array();
|
||||
try {
|
||||
$imagick->clear();
|
||||
$imagick->readImageBlob( $resize_result );
|
||||
if ( function_exists( 'getimagesizefromstring' ) ) {
|
||||
$gd_size_info = getimagesizefromstring( $resize_result );
|
||||
}
|
||||
if ( ! empty( $gd_size_info ) ) {
|
||||
$new_size['width'] = $gd_size_info[0];
|
||||
$new_size['height'] = $gd_size_info[1];
|
||||
} else {
|
||||
$new_size = $imagick->getImageGeometry();
|
||||
}
|
||||
ewwwio_debug_message( 'new size: ' . implode( 'x', $new_size ) );
|
||||
} catch ( Exception $e ) {
|
||||
return new WP_Error( 'image_resize_error', $e->getMessage(), $this->file );
|
||||
}
|
||||
$this->image = $imagick;
|
||||
if ( empty( $new_size ) ) {
|
||||
return new WP_Error( 'image_resize_error', __( 'Image resize failed.' ) );
|
||||
}
|
||||
$this->update_size( $new_size['width'], $new_size['height'] );
|
||||
return $resize_result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Efficiently resize the current image
|
||||
*
|
||||
* This is a WordPress specific implementation of Imagick::thumbnailImage(),
|
||||
* which resizes an image to given dimensions and removes any associated profiles.
|
||||
*
|
||||
* @since 4.5.0
|
||||
*
|
||||
* @param int $dst_w The destination width.
|
||||
* @param int $dst_h The destination height.
|
||||
* @param string $filter_name Optional. The Imagick filter to use when resizing. Default 'FILTER_TRIANGLE'.
|
||||
* @param bool $strip_meta Optional. Strip all profiles, excluding color profiles, from the image. Default true.
|
||||
* @return void|WP_Error
|
||||
*/
|
||||
protected function thumbnail_image( $dst_w, $dst_h, $filter_name = 'FILTER_TRIANGLE', $strip_meta = true ) {
|
||||
ewwwio_debug_message( '<b>wp_image_editor_imagick::' . __FUNCTION__ . '()</b>' );
|
||||
$allowed_filters = array(
|
||||
'FILTER_POINT',
|
||||
'FILTER_BOX',
|
||||
'FILTER_TRIANGLE',
|
||||
'FILTER_HERMITE',
|
||||
'FILTER_HANNING',
|
||||
'FILTER_HAMMING',
|
||||
'FILTER_BLACKMAN',
|
||||
'FILTER_GAUSSIAN',
|
||||
'FILTER_QUADRATIC',
|
||||
'FILTER_CUBIC',
|
||||
'FILTER_CATROM',
|
||||
'FILTER_MITCHELL',
|
||||
'FILTER_LANCZOS',
|
||||
'FILTER_BESSEL',
|
||||
'FILTER_SINC',
|
||||
);
|
||||
|
||||
$filter_name = apply_filters( 'eio_image_resize_filter', $filter_name, $dst_w, $dst_h );
|
||||
ewwwio_debug_message( "using resize filter $filter_name" );
|
||||
/**
|
||||
* Set the filter value if '$filter_name' name is in the allowed list and the related
|
||||
* Imagick constant is defined or fall back to the default filter.
|
||||
*/
|
||||
if ( in_array( $filter_name, $allowed_filters, true ) && defined( 'Imagick::' . $filter_name ) ) {
|
||||
$filter = constant( 'Imagick::' . $filter_name );
|
||||
} else {
|
||||
$filter = defined( 'Imagick::FILTER_TRIANGLE' ) ? Imagick::FILTER_TRIANGLE : false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Filters whether to strip metadata from images when they're resized.
|
||||
*
|
||||
* This filter only applies when resizing using the Imagick editor since GD
|
||||
* always strips profiles by default.
|
||||
*
|
||||
* @since 4.5.0
|
||||
*
|
||||
* @param bool $strip_meta Whether to strip image metadata during resizing. Default true.
|
||||
*/
|
||||
if ( apply_filters( 'image_strip_meta', $strip_meta ) ) {
|
||||
$this->strip_meta(); // Fail silently if not supported.
|
||||
}
|
||||
|
||||
try {
|
||||
/*
|
||||
* To be more efficient, resample large images to 5x the destination size before resizing
|
||||
* whenever the output size is less that 1/3 of the original image size (1/3^2 ~= .111),
|
||||
* unless we would be resampling to a scale smaller than 128x128.
|
||||
*/
|
||||
if ( is_callable( array( $this->image, 'sampleImage' ) ) ) {
|
||||
$resize_ratio = ( $dst_w / $this->size['width'] ) * ( $dst_h / $this->size['height'] );
|
||||
$sample_factor = 5;
|
||||
|
||||
if ( $resize_ratio < .111 && ( $dst_w * $sample_factor > 128 && $dst_h * $sample_factor > 128 ) ) {
|
||||
$this->image->sampleImage( $dst_w * $sample_factor, $dst_h * $sample_factor );
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* Use resizeImage() when it's available and a valid filter value is set.
|
||||
* Otherwise, fall back to the scaleImage() method for resizing, which
|
||||
* results in better image quality over resizeImage() with default filter
|
||||
* settings and retains backward compatibility with pre 4.5 functionality.
|
||||
*/
|
||||
if ( is_callable( array( $this->image, 'resizeImage' ) ) && $filter ) {
|
||||
$this->image->setOption( 'filter:support', '2.0' );
|
||||
$this->image->resizeImage( $dst_w, $dst_h, $filter, 1 );
|
||||
} else {
|
||||
$this->image->scaleImage( $dst_w, $dst_h );
|
||||
}
|
||||
|
||||
// Set appropriate quality settings after resizing.
|
||||
if ( 'image/jpeg' === $this->mime_type ) {
|
||||
if ( apply_filters( 'eio_use_adaptive_sharpen', false, $dst_w, $dst_h ) && is_callable( array( $this->image, 'adaptiveSharpenImage' ) ) ) {
|
||||
$radius = apply_filters( 'eio_adaptive_sharpen_radius', 0, $dst_w, $dst_h );
|
||||
$sigma = apply_filters( 'eio_adaptive_sharpen_sigma', 1, $dst_w, $dst_h );
|
||||
ewwwio_debug_message( "running adaptiveSharpenImage( $radius, $sigma )" );
|
||||
$this->image->adaptiveSharpenImage( $radius, $sigma );
|
||||
} elseif ( is_callable( array( $this->image, 'unsharpMaskImage' ) ) ) {
|
||||
$radius = apply_filters( 'eio_sharpen_radius', 0.25, $dst_w, $dst_h );
|
||||
$sigma = apply_filters( 'eio_sharpen_sigma', 0.25, $dst_w, $dst_h );
|
||||
$amount = apply_filters( 'eio_sharpen_amount', 8, $dst_w, $dst_h );
|
||||
$threshold = apply_filters( 'eio_sharpen_threshold', 0.065, $dst_w, $dst_h );
|
||||
ewwwio_debug_message( "running unsharpMaskImage( $radius, $sigma, $amount, $threshold )" );
|
||||
$this->image->unsharpMaskImage( $radius, $sigma, $amount, $threshold );
|
||||
// $this->image->unsharpMaskImage( 0.25, 0.25, 8, 0.065 ); // core WP defaults.
|
||||
// $this->image->unsharpMaskImage( 0, 0.4, 1.2, 0.01 ); // values from the Better Images plugin.
|
||||
}
|
||||
|
||||
$this->image->setOption( 'jpeg:fancy-upsampling', 'off' );
|
||||
}
|
||||
|
||||
if ( 'image/png' === $this->mime_type ) {
|
||||
$this->image->setOption( 'png:compression-filter', '5' );
|
||||
$this->image->setOption( 'png:compression-level', '9' );
|
||||
$this->image->setOption( 'png:compression-strategy', '1' );
|
||||
$this->image->setOption( 'png:exclude-chunk', 'all' );
|
||||
}
|
||||
|
||||
/*
|
||||
* If alpha channel is not defined, set it opaque.
|
||||
*
|
||||
* Note that Imagick::getImageAlphaChannel() is only available if Imagick
|
||||
* has been compiled against ImageMagick version 6.4.0 or newer.
|
||||
*/
|
||||
if ( is_callable( array( $this->image, 'getImageAlphaChannel' ) )
|
||||
&& is_callable( array( $this->image, 'setImageAlphaChannel' ) )
|
||||
&& defined( 'Imagick::ALPHACHANNEL_UNDEFINED' )
|
||||
&& defined( 'Imagick::ALPHACHANNEL_OPAQUE' )
|
||||
) {
|
||||
if ( $this->image->getImageAlphaChannel() === Imagick::ALPHACHANNEL_UNDEFINED ) {
|
||||
$this->image->setImageAlphaChannel( Imagick::ALPHACHANNEL_OPAQUE );
|
||||
}
|
||||
}
|
||||
|
||||
// Limit the bit depth of resized images to 8 bits per channel.
|
||||
if ( is_callable( array( $this->image, 'getImageDepth' ) ) && is_callable( array( $this->image, 'setImageDepth' ) ) ) {
|
||||
if ( 8 < $this->image->getImageDepth() ) {
|
||||
$this->image->setImageDepth( 8 );
|
||||
}
|
||||
}
|
||||
|
||||
if ( is_callable( array( $this->image, 'setInterlaceScheme' ) ) && defined( 'Imagick::INTERLACE_NO' ) ) {
|
||||
$this->image->setInterlaceScheme( Imagick::INTERLACE_NO );
|
||||
}
|
||||
} catch ( Exception $e ) {
|
||||
return new WP_Error( 'image_resize_error', $e->getMessage() );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resize multiple images from a single source.
|
||||
*
|
||||
* @since 4.6.0
|
||||
*
|
||||
* @param array $sizes {
|
||||
* An array of image size arrays. Default sizes are 'small', 'medium', 'medium_large', 'large'.
|
||||
*
|
||||
* Either a height or width must be provided.
|
||||
* If one of the two is set to null, the resize will
|
||||
* maintain aspect ratio according to the provided dimension.
|
||||
* Likewise, if crop is false, aspect ratio will also be preserved.
|
||||
*
|
||||
* @type array $size {
|
||||
* Array of height, width values, and whether to crop.
|
||||
*
|
||||
* @type int $width Image width. Optional if `$height` is specified.
|
||||
* @type int $height Image height. Optional if `$width` is specified.
|
||||
* @type bool $crop Optional. Whether to crop the image. Default false.
|
||||
* }
|
||||
* }
|
||||
* @return array An array of resized images' metadata by size.
|
||||
*/
|
||||
public function multi_resize( $sizes ) {
|
||||
ewwwio_debug_message( '<b>wp_image_editor_imagick::' . __FUNCTION__ . '()</b>' );
|
||||
$metadata = array();
|
||||
$orig_size = $this->size;
|
||||
$orig_image = $this->image->getImage();
|
||||
foreach ( $sizes as $size => $size_data ) {
|
||||
if ( ! $this->image ) {
|
||||
$this->image = $orig_image->getImage();
|
||||
}
|
||||
if ( ! isset( $size_data['width'] ) && ! isset( $size_data['height'] ) ) {
|
||||
continue;
|
||||
}
|
||||
if ( ! isset( $size_data['width'] ) ) {
|
||||
$size_data['width'] = null;
|
||||
}
|
||||
if ( ! isset( $size_data['height'] ) ) {
|
||||
$size_data['height'] = null;
|
||||
}
|
||||
if ( ! isset( $size_data['crop'] ) ) {
|
||||
$size_data['crop'] = false;
|
||||
}
|
||||
|
||||
$resize_result = $this->resize( $size_data['width'], $size_data['height'], $size_data['crop'] );
|
||||
$duplicate = ( (int) $orig_size['width'] === (int) $size_data['width'] && (int) $orig_size['height'] === (int) $size_data['height'] );
|
||||
|
||||
if ( ! is_wp_error( $resize_result ) && ! $duplicate ) {
|
||||
if ( is_string( $resize_result ) ) {
|
||||
$resized = $this->_save_ewwwio_file( $resize_result );
|
||||
unset( $resize_result );
|
||||
// Note sure this bit is necessary, but just to be safe.
|
||||
$this->image->clear();
|
||||
$this->image->destroy();
|
||||
$this->image = null;
|
||||
} else {
|
||||
$resized = $this->_save( $this->image );
|
||||
$this->image->clear();
|
||||
$this->image->destroy();
|
||||
$this->image = null;
|
||||
}
|
||||
if ( ! is_wp_error( $resized ) && $resized ) {
|
||||
unset( $resized['path'] );
|
||||
$metadata[ $size ] = $resized;
|
||||
}
|
||||
}
|
||||
$this->size = $orig_size;
|
||||
}
|
||||
$this->image = $orig_image;
|
||||
return $metadata;
|
||||
}
|
||||
|
||||
/**
|
||||
* Crops Image.
|
||||
*
|
||||
* Currently does nothing more than call the parent and let us know the image is modified.
|
||||
*
|
||||
* @since 4.6.0
|
||||
*
|
||||
* @param int $src_x The start x position to crop from.
|
||||
* @param int $src_y The start y position to crop from.
|
||||
* @param int $src_w The width to crop.
|
||||
* @param int $src_h The height to crop.
|
||||
* @param int $dst_w Optional. The destination width.
|
||||
* @param int $dst_h Optional. The destination height.
|
||||
* @param bool $src_abs Optional. If the source crop points are absolute.
|
||||
* @return bool|WP_Error
|
||||
*/
|
||||
public function crop( $src_x, $src_y, $src_w, $src_h, $dst_w = null, $dst_h = null, $src_abs = false ) {
|
||||
$this->modified = 'crop';
|
||||
return parent::crop( $src_x, $src_y, $src_w, $src_h, $dst_w, $dst_h, $src_abs );
|
||||
}
|
||||
|
||||
/**
|
||||
* Rotates current image counter-clockwise by $angle.
|
||||
*
|
||||
* Currently does nothing more than call the parent and let us know the image is modified.
|
||||
*
|
||||
* @since 4.6.0
|
||||
*
|
||||
* @param float $angle The number of degrees for rotation.
|
||||
* @return true|WP_Error
|
||||
*/
|
||||
public function rotate( $angle ) {
|
||||
$this->modified = 'rotate';
|
||||
return parent::rotate( $angle );
|
||||
}
|
||||
|
||||
/**
|
||||
* Flips current image.
|
||||
*
|
||||
* Currently does nothing more than call the parent and let us know the image is modified.
|
||||
*
|
||||
* @since 4.6.0
|
||||
*
|
||||
* @param bool $horz Flip along Horizontal Axis.
|
||||
* @param bool $vert Flip along Vertical Axis.
|
||||
* @return true|WP_Error
|
||||
*/
|
||||
public function flip( $horz, $vert ) {
|
||||
$this->modified = 'flip';
|
||||
return parent::flip( $horz, $vert );
|
||||
}
|
||||
|
||||
/**
|
||||
* Saves a file from the EWWW IO API-enabled image editor.
|
||||
*
|
||||
* @since 4.6.0
|
||||
*
|
||||
* @param string $image A string containing the image contents.
|
||||
* @param string $filename Optional. The name of the file to be saved to.
|
||||
* @param string $mime_type Optional. The mimetype of the file.
|
||||
* @return WP_Error|array The full path, base filename, and mimetype.
|
||||
*/
|
||||
protected function _save_ewwwio_file( $image, $filename = null, $mime_type = null ) {
|
||||
ewwwio_debug_message( '<b>wp_image_editor_imagick::' . __FUNCTION__ . '()</b>' );
|
||||
list( $filename, $extension, $mime_type ) = $this->get_output_format( $filename, $mime_type );
|
||||
if ( ! $filename ) {
|
||||
$filename = $this->generate_filename( null, null, $extension );
|
||||
}
|
||||
if ( wp_is_stream( $filename ) ) {
|
||||
$imagick = new Imagick();
|
||||
try {
|
||||
$imagick->readImageBlob( $image );
|
||||
} catch ( Exception $e ) {
|
||||
return new WP_Error( 'image_save_error', $e->getMessage(), $filename );
|
||||
}
|
||||
unset( $this->ewww_image );
|
||||
return parent::_save( $imagick, $filename, $mime_type );
|
||||
}
|
||||
if ( ! is_string( $image ) ) {
|
||||
unset( $this->ewww_image );
|
||||
return parent::_save( $image, $filename, $mime_type );
|
||||
}
|
||||
global $ewww_preempt_editor;
|
||||
if ( ( ! defined( 'EWWWIO_EDITOR_OVERWRITE' ) || ! EWWWIO_EDITOR_OVERWRITE ) && ewwwio_is_file( $filename ) && empty( $ewww_preempt_editor ) ) {
|
||||
ewwwio_debug_message( "detected existing file: $filename" );
|
||||
$current_size = wp_getimagesize( $filename );
|
||||
if ( $current_size && (int) $this->size['width'] === (int) $current_size[0] && (int) $this->size['height'] === (int) $current_size[1] ) {
|
||||
ewwwio_debug_message( "existing file has same dimensions, not saving $filename" );
|
||||
return array(
|
||||
'path' => $filename,
|
||||
'file' => wp_basename( apply_filters( 'image_make_intermediate_size', $filename ) ),
|
||||
'width' => $this->size['width'],
|
||||
'height' => $this->size['height'],
|
||||
'mime-type' => $mime_type,
|
||||
);
|
||||
}
|
||||
}
|
||||
// Write out the image (substitute for $this->make_image()).
|
||||
wp_mkdir_p( dirname( $filename ) );
|
||||
$result = file_put_contents( $filename, $image );
|
||||
if ( $result ) {
|
||||
ewwwio_debug_message( "image editor (imagick-api-enhanced) saved: $filename" );
|
||||
if ( is_writable( $filename ) ) {
|
||||
$stat = stat( dirname( $filename ) );
|
||||
$perms = $stat['mode'] & 0000666; // Same permissions as parent folder with executable bits stripped.
|
||||
ewwwio_chmod( $filename, $perms );
|
||||
}
|
||||
ewwwio_memory( __FUNCTION__ );
|
||||
return array(
|
||||
'path' => $filename,
|
||||
'file' => wp_basename( apply_filters( 'image_make_intermediate_size', $filename ) ),
|
||||
'width' => $this->size['width'],
|
||||
'height' => $this->size['height'],
|
||||
'mime-type' => $mime_type,
|
||||
);
|
||||
}
|
||||
ewwwio_memory( __FUNCTION__ );
|
||||
return new WP_Error( 'image_save_error', __( 'Image Editor Save Failed' ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Saves a file from the image editor.
|
||||
*
|
||||
* @since 1.7.0
|
||||
*
|
||||
* @param resource $image An Imagick image object.
|
||||
* @param string $filename Optional. The name of the file to be saved to.
|
||||
* @param string $mime_type Optional. The mimetype of the file.
|
||||
* @return WP_Error| array The full path, base filename, width, height, and mimetype.
|
||||
*/
|
||||
protected function _save( $image, $filename = null, $mime_type = null ) {
|
||||
ewwwio_debug_message( '<b>wp_image_editor_imagick::' . __FUNCTION__ . '()</b>' );
|
||||
global $ewww_defer;
|
||||
global $ewww_preempt_editor;
|
||||
if ( ! empty( $this->ewww_image ) && ! $this->modified ) {
|
||||
return $this->_save_ewwwio_file( $this->ewww_image, $filename, $mime_type );
|
||||
}
|
||||
if ( ! empty( $ewww_preempt_editor ) || ! defined( 'EWWW_IMAGE_OPTIMIZER_ENABLE_EDITOR' ) || ! EWWW_IMAGE_OPTIMIZER_ENABLE_EDITOR ) {
|
||||
return parent::_save( $image, $filename, $mime_type );
|
||||
}
|
||||
list( $filename, $extension, $mime_type ) = $this->get_output_format( $filename, $mime_type );
|
||||
if ( ! $filename ) {
|
||||
$filename = $this->generate_filename( null, null, $extension );
|
||||
}
|
||||
if ( ( ! defined( 'EWWWIO_EDITOR_OVERWRITE' ) || ! EWWWIO_EDITOR_OVERWRITE ) && ewwwio_is_file( $filename ) ) {
|
||||
ewwwio_debug_message( "detected existing file: $filename" );
|
||||
$current_size = wp_getimagesize( $filename );
|
||||
if ( $current_size && (int) $this->size['width'] === (int) $current_size[0] && (int) $this->size['height'] === (int) $current_size[1] ) {
|
||||
ewwwio_debug_message( "existing file has same dimensions, not saving $filename" );
|
||||
return array(
|
||||
'path' => $filename,
|
||||
'file' => wp_basename( apply_filters( 'image_make_intermediate_size', $filename ) ),
|
||||
'width' => $this->size['width'],
|
||||
'height' => $this->size['height'],
|
||||
'mime-type' => $mime_type,
|
||||
);
|
||||
}
|
||||
}
|
||||
$saved = parent::_save( $image, $filename, $mime_type );
|
||||
if ( ! is_wp_error( $saved ) ) {
|
||||
if ( ! $filename ) {
|
||||
$filename = $saved['path'];
|
||||
}
|
||||
if ( file_exists( $filename ) ) {
|
||||
ewww_image_optimizer( $filename );
|
||||
ewwwio_debug_message( "image editor (imagick) saved: $filename" );
|
||||
$image_size = ewww_image_optimizer_filesize( $filename );
|
||||
ewwwio_debug_message( "image editor size: $image_size" );
|
||||
}
|
||||
}
|
||||
ewwwio_memory( __FUNCTION__ );
|
||||
return $saved;
|
||||
}
|
||||
}
|
@ -0,0 +1,202 @@
|
||||
<?php
|
||||
/**
|
||||
* Class file for EWWWIO_Relative_Migration
|
||||
*
|
||||
* Performs the migration from storing absolute paths to using relative paths in the ewwwio_images table.
|
||||
*
|
||||
* @link https://ewww.io
|
||||
* @package EWWW_Image_Optimizer
|
||||
* @since 4.5.2
|
||||
*/
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Migrates absolute paths to relative paths (once).
|
||||
*/
|
||||
class EWWWIO_Relative_Migration {
|
||||
|
||||
/**
|
||||
* The offset/position in the database.
|
||||
*
|
||||
* @var int $id
|
||||
*/
|
||||
private $offset = 0;
|
||||
|
||||
/**
|
||||
* The time when we started processing.
|
||||
*
|
||||
* @var int $started
|
||||
*/
|
||||
private $started;
|
||||
|
||||
/**
|
||||
* Sets up the the migration.
|
||||
*/
|
||||
public function __construct() {
|
||||
if ( 'done' === get_option( 'ewww_image_optimizer_relative_migration_status' ) ) {
|
||||
return;
|
||||
}
|
||||
if ( ! $this->table_exists() ) {
|
||||
$this->unschedule();
|
||||
update_option( 'ewww_image_optimizer_relative_migration_status', 'done' );
|
||||
delete_option( 'ewww_image_optimizer_relative_migration_offset' );
|
||||
}
|
||||
if ( ! get_option( 'ewww_image_optimizer_relative_migration_status' ) ) {
|
||||
update_option( 'ewww_image_optimizer_relative_migration_status', 'started' );
|
||||
}
|
||||
$this->maybe_schedule();
|
||||
}
|
||||
|
||||
/**
|
||||
* Check to see if the ewwwio_images table actually exists.
|
||||
*
|
||||
* @return bool True if does, false if it don't.
|
||||
*/
|
||||
private function table_exists() {
|
||||
global $wpdb;
|
||||
return $wpdb->get_var( "SHOW TABLES LIKE '$wpdb->ewwwio_images'" ) === $wpdb->ewwwio_images;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves a batch of records based on the current offset.
|
||||
*/
|
||||
private function get_records() {
|
||||
ewwwio_debug_message( '<b>' . __METHOD__ . '()</b>' );
|
||||
global $wpdb;
|
||||
if ( strpos( $wpdb->charset, 'utf8' ) === false ) {
|
||||
ewww_image_optimizer_db_init();
|
||||
global $ewwwdb;
|
||||
} else {
|
||||
$ewwwdb = $wpdb;
|
||||
}
|
||||
$query = "SELECT id,path,updated FROM $ewwwdb->ewwwio_images WHERE pending=0 AND image_size > 0 ORDER BY id DESC LIMIT $this->offset,500";
|
||||
$records = $ewwwdb->get_results( $query, ARRAY_A );
|
||||
|
||||
$this->offset += 500;
|
||||
if ( is_array( $records ) ) {
|
||||
return $records;
|
||||
}
|
||||
return array();
|
||||
}
|
||||
|
||||
/**
|
||||
* Called via wp_cron to initiate the migration effort.
|
||||
*/
|
||||
public function migrate() {
|
||||
ewwwio_debug_message( '<b>' . __METHOD__ . '()</b>' );
|
||||
$this->started = time();
|
||||
$this->offset = (int) get_option( 'ewww_image_optimizer_relative_migration_offset' );
|
||||
$records = $this->get_records();
|
||||
ewwwio_debug_message( 'starting at ' . gmdate( 'Y-m-d H:i:s', $this->started ) . " with offset $this->offset" );
|
||||
while ( ! empty( $records ) ) {
|
||||
foreach ( $records as $record ) {
|
||||
if ( $this->already_migrated( $record['path'] ) ) {
|
||||
ewwwio_debug_message( 'already migrated' );
|
||||
continue;
|
||||
}
|
||||
// Relativize the path, and store it back in the db.
|
||||
$relative_path = ewww_image_optimizer_relativize_path( $record['path'] );
|
||||
if ( $record['path'] !== $relative_path ) {
|
||||
$record['path'] = $relative_path;
|
||||
$this->update_relative_record( $record );
|
||||
}
|
||||
}
|
||||
if ( time() - $this->started > 20 ) {
|
||||
update_option( 'ewww_image_optimizer_relative_migration_offset', $this->offset, false );
|
||||
return;
|
||||
}
|
||||
$records = $this->get_records();
|
||||
}
|
||||
$this->unschedule();
|
||||
update_option( 'ewww_image_optimizer_relative_migration_status', 'done' );
|
||||
delete_option( 'ewww_image_optimizer_relative_migration_offset' );
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks to see if the record already has been migrated.
|
||||
*
|
||||
* @param string $path Path of file as retrieved from database.
|
||||
*/
|
||||
private function already_migrated( $path ) {
|
||||
if ( strpos( $path, 'EWWW_IMAGE_OPTIMIZER_RELATIVE_FOLDER' ) === 0 ) {
|
||||
return true;
|
||||
}
|
||||
if ( strpos( $path, 'ABSPATH' ) === 0 ) {
|
||||
return true;
|
||||
}
|
||||
if ( strpos( $path, 'WP_CONTENT_DIR' ) === 0 ) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates the db record with the relativized path.
|
||||
*
|
||||
* @param array $record Includes a relative path, the ID, and the updated timestamp.
|
||||
*/
|
||||
private function update_relative_record( $record ) {
|
||||
ewwwio_debug_message( '<b>' . __METHOD__ . '()</b>' );
|
||||
global $wpdb;
|
||||
if ( strpos( $wpdb->charset, 'utf8' ) === false ) {
|
||||
ewww_image_optimizer_db_init();
|
||||
global $ewwwdb;
|
||||
} else {
|
||||
$ewwwdb = $wpdb;
|
||||
}
|
||||
$ewwwdb->update(
|
||||
$ewwwdb->ewwwio_images,
|
||||
array(
|
||||
'path' => $record['path'],
|
||||
'updated' => $record['updated'],
|
||||
),
|
||||
array(
|
||||
'id' => $record['id'],
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Schedule the migration.
|
||||
*/
|
||||
private function maybe_schedule() {
|
||||
ewwwio_debug_message( '<b>' . __METHOD__ . '()</b>' );
|
||||
// Create 5 minute wp_cron schedule.
|
||||
add_filter( 'cron_schedules', array( $this, 'add_migration_schedule' ) );
|
||||
add_action( 'ewww_image_optimizer_relative_migration', array( $this, 'migrate' ) );
|
||||
// Schedule migration function.
|
||||
if ( ! wp_next_scheduled( 'ewww_image_optimizer_relative_migration' ) ) {
|
||||
ewwwio_debug_message( 'scheduling migration' );
|
||||
wp_schedule_event( time(), 'ewwwio_relative_migration_interval', 'ewww_image_optimizer_relative_migration' );
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Clean up the scheduled event.
|
||||
*/
|
||||
private function unschedule() {
|
||||
ewwwio_debug_message( '<b>' . __METHOD__ . '()</b>' );
|
||||
$timestamp = wp_next_scheduled( 'ewww_image_optimizer_relative_migration' );
|
||||
if ( $timestamp ) {
|
||||
wp_unschedule_event( $timestamp, 'ewww_image_optimizer_relative_migration' );
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Adds a custom cron schedule: every 5 minutes.
|
||||
*
|
||||
* @param array $schedules An array of custom cron schedules.
|
||||
*/
|
||||
public function add_migration_schedule( $schedules ) {
|
||||
ewwwio_debug_message( '<b>' . __METHOD__ . '()</b>' );
|
||||
$schedules['ewwwio_relative_migration_interval'] = array(
|
||||
'interval' => MINUTE_IN_SECONDS * 5,
|
||||
'display' => 'Every 5 Minutes until complete',
|
||||
);
|
||||
return $schedules;
|
||||
}
|
||||
}
|
||||
new EWWWIO_Relative_Migration();
|
4154
wp-content/plugins/ewww-image-optimizer/classes/class-exactdn.php
Normal file
@ -0,0 +1,97 @@
|
||||
<?php
|
||||
/**
|
||||
* Help integration functions for embedding the HS Beacon for users that have opted in.
|
||||
*
|
||||
* @package EIO
|
||||
* @since 3.5.1
|
||||
*/
|
||||
|
||||
namespace EWWW;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Embed HS Beacon to give users more help when they need it.
|
||||
*
|
||||
* @since 3.5.1
|
||||
*/
|
||||
class HS_Beacon extends Base {
|
||||
|
||||
/**
|
||||
* Get things going
|
||||
*/
|
||||
public function __construct() {
|
||||
parent::__construct();
|
||||
\add_action( 'admin_action_eio_opt_into_hs_beacon', array( $this, 'check_for_optin' ) );
|
||||
\add_action( 'admin_action_eio_opt_out_of_hs_beacon', array( $this, 'check_for_optout' ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Check for a new opt-in via the admin notice
|
||||
*/
|
||||
public function check_for_optin() {
|
||||
$this->debug_message( '<b>' . __METHOD__ . '()</b>' );
|
||||
$this->set_option( $this->prefix . 'enable_help', 1 );
|
||||
$this->set_option( $this->prefix . 'enable_help_notice', 1 );
|
||||
\wp_safe_redirect( \remove_query_arg( 'action', \wp_get_referer() ) );
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check for a new opt-out via the admin notice
|
||||
*/
|
||||
public function check_for_optout() {
|
||||
$this->debug_message( '<b>' . __METHOD__ . '()</b>' );
|
||||
\delete_option( $this->prefix . 'enable_help' );
|
||||
\delete_network_option( null, $this->prefix . 'enable_help' );
|
||||
$this->set_option( $this->prefix . 'enable_help_notice', 1 );
|
||||
\wp_safe_redirect( \remove_query_arg( 'action', \wp_get_referer() ) );
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Display the admin notice to users that have not opted-in or out
|
||||
*
|
||||
* @access public
|
||||
* @param string $network_class A string that indicates where this is being displayed.
|
||||
* @return void
|
||||
*/
|
||||
public function admin_notice( $network_class = '' ) {
|
||||
$this->debug_message( '<b>' . __METHOD__ . '()</b>' );
|
||||
$hide_notice = $this->get_option( $this->prefix . 'enable_help_notice' );
|
||||
if ( 'network-multisite-over' === $network_class ) {
|
||||
return;
|
||||
}
|
||||
if ( 'network-singlesite' === $network_class ) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ( $hide_notice ) {
|
||||
return;
|
||||
}
|
||||
if ( $this->get_option( $this->prefix . 'enable_help' ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ( ! \current_user_can( 'manage_options' ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ( ! \function_exists( 'is_plugin_active_for_network' ) && \is_multisite() ) {
|
||||
// Need to include the plugin library for the is_plugin_active function.
|
||||
require_once ABSPATH . 'wp-admin/includes/plugin.php';
|
||||
}
|
||||
if (
|
||||
\is_multisite() &&
|
||||
\is_plugin_active_for_network( \constant( \strtoupper( $this->prefix ) . 'PLUGIN_FILE_REL' ) ) &&
|
||||
! \current_user_can( 'manage_network_options' )
|
||||
) {
|
||||
return;
|
||||
}
|
||||
if ( \strpos( __FILE__, 'plugins/easy' ) ) {
|
||||
\easyio_notice_beacon();
|
||||
}
|
||||
}
|
||||
}
|
1220
wp-content/plugins/ewww-image-optimizer/classes/class-js-webp.php
Normal file
1337
wp-content/plugins/ewww-image-optimizer/classes/class-lazy-load.php
Normal file
1112
wp-content/plugins/ewww-image-optimizer/classes/class-local.php
Normal file
@ -0,0 +1,466 @@
|
||||
<?php
|
||||
/**
|
||||
* Implements basic page parsing functions.
|
||||
*
|
||||
* @link https://ewww.io
|
||||
* @package EIO
|
||||
*/
|
||||
|
||||
namespace EWWW;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* HTML element and attribute parsing, replacing, etc.
|
||||
*/
|
||||
class Page_Parser extends Base {
|
||||
|
||||
/**
|
||||
* Allowed image extensions.
|
||||
*
|
||||
* @access protected
|
||||
* @var array $extensions
|
||||
*/
|
||||
protected $extensions = array(
|
||||
'gif',
|
||||
'jpg',
|
||||
'jpeg',
|
||||
'jpe',
|
||||
'png',
|
||||
'svg',
|
||||
'webp',
|
||||
);
|
||||
|
||||
/**
|
||||
* Indicates if we are filtering ExactDN urls.
|
||||
*
|
||||
* @access protected
|
||||
* @var bool $parsing_exactdn
|
||||
*/
|
||||
protected $parsing_exactdn = false;
|
||||
|
||||
/**
|
||||
* Match all images and any relevant <a> tags in a block of HTML.
|
||||
*
|
||||
* The hyperlinks param implies that the src attribute is required, but not the other way around.
|
||||
*
|
||||
* @param string $content Some HTML.
|
||||
* @param bool $hyperlinks Default true. Should we include encasing hyperlinks in our search.
|
||||
* @param bool $src_required Default true. Should we look only for images with src attributes.
|
||||
* @return array An array of $images matches, where $images[0] is
|
||||
* an array of full matches, and the link_url, img_tag,
|
||||
* and img_url keys are arrays of those matches.
|
||||
*/
|
||||
public function get_images_from_html( $content, $hyperlinks = true, $src_required = true ) {
|
||||
$this->debug_message( '<b>' . __METHOD__ . '()</b>' );
|
||||
$images = array();
|
||||
$unquoted_images = array();
|
||||
|
||||
$unquoted_pattern = '';
|
||||
$search_pattern = '#(?P<img_tag><img\s[^\\\\>]*?>)#is';
|
||||
if ( $hyperlinks ) {
|
||||
$this->debug_message( 'using div/figure+hyperlink(a) patterns with src required' );
|
||||
$search_pattern = '#(?:<div[^>]*?\s+?class\s*=\s*["\'](?P<div_class>[\w\s-]+?)["\'][^>]*?>\s*(?:<span[^>]*?></span>)?)?(?:<figure[^>]*?\s+?class\s*=\s*["\'](?P<figure_class>[\w\s-]+?)["\'][^>]*?>\s*)?(?:<a[^>]*?\s+?href\s*=\s*["\'](?P<link_url>[^\s]+?)["\'][^>]*?>\s*)?(?P<img_tag><img[^>]*?\s+?src\s*=\s*("|\')(?P<img_url>(?!\5)[^\\\\]+?)\5[^>]*?>){1}(?:\s*</a>)?#is';
|
||||
$unquoted_pattern = '#(?:<div[^>]*?\s+?class\s*=\s*(?P<div_class>[\w-]+?)[^>]*?>\s*(?:<span[^>]*?></span>)?)?(?:<figure[^>]*?\s+?class\s*=\s*(?P<figure_class>[\w-]+?)[^>]*?>\s*)?(?:<a[^>]*?\s+?href\s*=\s*(?P<link_url>[^"\'\\\\<>][^\s<>]+)[^>]*?>\s*)?(?P<img_tag><img[^>]*?\s+?src\s*=\s*(?P<img_url>[^"\'\\\\<>][^\s\\\\<>]+)(?:\s[^>]*?)?>){1}(?:\s*</a>)?#is';
|
||||
} elseif ( $src_required ) {
|
||||
$this->debug_message( 'using plain img pattern, src still required' );
|
||||
$search_pattern = '#(?P<img_tag><img[^>]*?\s+?src\s*=\s*("|\')(?P<img_url>(?!\2)[^\\\\]+?)\2[^>]*?>)#is';
|
||||
$unquoted_pattern = '#(?P<img_tag><img[^>]*?\s+?src\s*=\s*(?P<img_url>[^"\'\\\\<>][^\s\\\\<>]+)(?:\s[^>]*?)?>)#is';
|
||||
}
|
||||
if ( \preg_match_all( $search_pattern, $content, $images ) ) {
|
||||
$this->debug_message( 'found ' . \count( $images[0] ) . ' image elements with quoted pattern' );
|
||||
foreach ( $images as $key => $unused ) {
|
||||
// Simplify the output as much as possible.
|
||||
if ( \is_numeric( $key ) && $key > 0 ) {
|
||||
unset( $images[ $key ] );
|
||||
}
|
||||
}
|
||||
/* $this->debug_message( print_r( $images, true ) ); */
|
||||
}
|
||||
$images = \array_filter( $images );
|
||||
if ( $unquoted_pattern && \preg_match_all( $unquoted_pattern, $content, $unquoted_images ) ) {
|
||||
$this->debug_message( 'found ' . \count( $unquoted_images[0] ) . ' image elements with unquoted pattern' );
|
||||
foreach ( $unquoted_images as $key => $unused ) {
|
||||
// Simplify the output as much as possible.
|
||||
if ( \is_numeric( $key ) && $key > 0 ) {
|
||||
unset( $unquoted_images[ $key ] );
|
||||
}
|
||||
}
|
||||
/* $this->debug_message( print_r( $unquoted_images, true ) ); */
|
||||
}
|
||||
$unquoted_images = \array_filter( $unquoted_images );
|
||||
if ( ! empty( $images ) && ! empty( $unquoted_images ) ) {
|
||||
$this->debug_message( 'both patterns found results, merging' );
|
||||
/* $this->debug_message( print_r( $images, true ) ); */
|
||||
$images = \array_merge_recursive( $images, $unquoted_images );
|
||||
/* $this->debug_message( print_r( $images, true ) ); */
|
||||
if ( ! empty( $images[0] ) && ! empty( $images[1] ) ) {
|
||||
$images[0] = \array_merge( $images[0], $images[1] );
|
||||
unset( $images[1] );
|
||||
}
|
||||
} elseif ( empty( $images ) && ! empty( $unquoted_images ) ) {
|
||||
$this->debug_message( 'unquoted results only, subbing in' );
|
||||
$images = $unquoted_images;
|
||||
}
|
||||
/* $this->debug_message( print_r( $images, true ) ); */
|
||||
return $images;
|
||||
}
|
||||
|
||||
/**
|
||||
* Match all images wrapped in <noscript> tags in a block of HTML.
|
||||
*
|
||||
* @param string $content Some HTML.
|
||||
* @return array An array of $images matches, where $images[0] is
|
||||
* an array of full matches, and the noscript_tag, img_tag,
|
||||
* and img_url keys are arrays of those matches.
|
||||
*/
|
||||
public function get_noscript_images_from_html( $content ) {
|
||||
$this->debug_message( '<b>' . __METHOD__ . '()</b>' );
|
||||
$images = array();
|
||||
|
||||
if ( \preg_match_all( '#(?P<noscript_tag><noscript[^>]*?>\s*)(?P<img_tag><img[^>]*?\s+?src\s*=\s*["\'](?P<img_url>[^\s]+?)["\'][^>]*?>){1}(?:\s*</noscript>)?#is', $content, $images ) ) {
|
||||
foreach ( $images as $key => $unused ) {
|
||||
// Simplify the output as much as possible, mostly for confirming test results.
|
||||
if ( \is_numeric( $key ) && $key > 0 ) {
|
||||
unset( $images[ $key ] );
|
||||
}
|
||||
}
|
||||
return $images;
|
||||
}
|
||||
return array();
|
||||
}
|
||||
|
||||
/**
|
||||
* Match all sources wrapped in <picture> tags in a block of HTML.
|
||||
*
|
||||
* @param string $content Some HTML.
|
||||
* @return array An array of $pictures matches, containing full elements with ending tags.
|
||||
*/
|
||||
public function get_picture_tags_from_html( $content ) {
|
||||
$this->debug_message( '<b>' . __METHOD__ . '()</b>' );
|
||||
$pictures = array();
|
||||
if ( \preg_match_all( '#(?:<picture[^>]*?>\s*)(?:<source[^>]*?>)+(?:.*?</picture>)?#is', $content, $pictures ) ) {
|
||||
return $pictures[0];
|
||||
}
|
||||
return array();
|
||||
}
|
||||
|
||||
/**
|
||||
* Match all <style> tags in a block of HTML.
|
||||
*
|
||||
* @param string $content Some HTML.
|
||||
* @return array An array of $styles matches, containing full elements with ending tags.
|
||||
*/
|
||||
public function get_style_tags_from_html( $content ) {
|
||||
$this->debug_message( '<b>' . __METHOD__ . '()</b>' );
|
||||
$styles = array();
|
||||
if ( \preg_match_all( '#<style[^>]*?>.*?</style>#is', $content, $styles ) ) {
|
||||
return $styles[0];
|
||||
}
|
||||
return array();
|
||||
}
|
||||
|
||||
/**
|
||||
* Match all elements by tag name in a block of HTML. Does not retrieve contents or closing tags.
|
||||
*
|
||||
* @param string $content Some HTML.
|
||||
* @param string $tag_name The name of the elements to retrieve.
|
||||
* @return array An array of $elements.
|
||||
*/
|
||||
public function get_elements_from_html( $content, $tag_name ) {
|
||||
$this->debug_message( '<b>' . __METHOD__ . '()</b>' );
|
||||
if ( ! \ctype_alpha( $tag_name ) ) {
|
||||
return array();
|
||||
}
|
||||
if ( \preg_match_all( '#<' . $tag_name . '\s[^\\\\>]+?>#is', $content, $elements ) ) {
|
||||
return $elements[0];
|
||||
}
|
||||
return array();
|
||||
}
|
||||
|
||||
/**
|
||||
* Try to determine height and width from strings WP appends to resized image filenames.
|
||||
*
|
||||
* @param string $src The image URL.
|
||||
* @param bool $use_params Check ExactDN image parameters for additional size information. Default to false.
|
||||
* @return array An array consisting of width and height.
|
||||
*/
|
||||
public function get_dimensions_from_filename( $src, $use_params = false ) {
|
||||
$this->debug_message( '<b>' . __METHOD__ . '()</b>' );
|
||||
$width_height_string = array();
|
||||
$this->debug_message( "looking for dimensions in $src" );
|
||||
$width_param = false;
|
||||
$height_param = false;
|
||||
if ( $use_params && \strpos( $src, '?' ) ) {
|
||||
$url_params = \urldecode( $this->parse_url( $src, PHP_URL_QUERY ) );
|
||||
if ( $url_params && false !== \strpos( $url_params, 'resize=' ) ) {
|
||||
\preg_match( '/resize=(\d+),(\d+)/', $url_params, $resize_matches );
|
||||
if ( \is_array( $resize_matches ) && ! empty( $resize_matches[1] ) && ! empty( $resize_matches[2] ) ) {
|
||||
$width_param = (int) $resize_matches[1];
|
||||
$height_param = (int) $resize_matches[2];
|
||||
}
|
||||
} elseif ( false !== \strpos( $url_params, 'fit=' ) ) {
|
||||
\preg_match( '/fit=(\d+),(\d+)/', $url_params, $fit_matches );
|
||||
if ( \is_array( $fit_matches ) && ! empty( $fit_matches[1] ) && ! empty( $fit_matches[2] ) ) {
|
||||
$width_param = (int) $fit_matches[1];
|
||||
$height_param = (int) $fit_matches[2];
|
||||
}
|
||||
}
|
||||
}
|
||||
if ( \preg_match( '#-(\d+)x(\d+)(@2x)?\.(?:' . \implode( '|', $this->extensions ) . '){1}(?:\?.+)?$#i', $src, $width_height_string ) ) {
|
||||
$width = (int) $width_height_string[1];
|
||||
$height = (int) $width_height_string[2];
|
||||
|
||||
if ( \strpos( $src, '@2x' ) ) {
|
||||
$width = 2 * $width;
|
||||
$height = 2 * $height;
|
||||
}
|
||||
if ( $width && $height ) {
|
||||
if ( $width_param && $width_param < $width ) {
|
||||
$width = $width_param;
|
||||
}
|
||||
if ( $height_param && $height_param < $height ) {
|
||||
$height = $height_param;
|
||||
}
|
||||
$this->debug_message( "found w$width h$height" );
|
||||
return array( $width, $height );
|
||||
}
|
||||
}
|
||||
return array( $width_param, $height_param ); // These may be false, unless URL parameters were found.
|
||||
}
|
||||
|
||||
/**
|
||||
* Get dimensions of a file from the URL.
|
||||
*
|
||||
* @param string $url The URL of the image.
|
||||
* @return array The width and height, in pixels.
|
||||
*/
|
||||
public function get_image_dimensions_by_url( $url ) {
|
||||
$this->debug_message( '<b>' . __METHOD__ . '()</b>' );
|
||||
$this->debug_message( "getting dimensions for $url" );
|
||||
|
||||
list( $width, $height ) = $this->get_dimensions_from_filename( $url, ! empty( $this->parsing_exactdn ) );
|
||||
if ( empty( $width ) || empty( $height ) ) {
|
||||
// Couldn't get it from the URL directly, see if we can get the actual filename.
|
||||
$file = false;
|
||||
if ( $this->allowed_urls && $this->allowed_domains ) {
|
||||
$file = $this->cdn_to_local( $url );
|
||||
}
|
||||
if ( ! $file ) {
|
||||
$file = $this->url_to_path_exists( $url );
|
||||
}
|
||||
if ( $file && $this->is_file( $file ) ) {
|
||||
list( $width, $height ) = \wp_getimagesize( $file );
|
||||
}
|
||||
}
|
||||
$width = $width && \is_numeric( $width ) ? (int) $width : false;
|
||||
$height = $height && \is_numeric( $height ) ? (int) $height : false;
|
||||
|
||||
return array( $width, $height );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the width from an image element.
|
||||
*
|
||||
* @param string $img The full image element.
|
||||
* @return string The width found or an empty string.
|
||||
*/
|
||||
public function get_img_style_width( $img ) {
|
||||
// Check for an inline max-width directive.
|
||||
$style = $this->get_attribute( $img, 'style' );
|
||||
if ( $style && \preg_match( '#max-width:\s?(\d+)px#', $style, $max_width_string ) ) {
|
||||
if ( ! empty( $max_width_string[1] ) && \is_numeric( $max_width_string ) ) {
|
||||
return (int) $max_width_string[1];
|
||||
}
|
||||
} elseif ( $style && \preg_match( '#width:\s?(\d+)px#', $style, $width_string ) ) {
|
||||
if ( ! empty( $width_string[1] ) && \is_numeric( $width_string[1] ) ) {
|
||||
return (int) $width_string[1];
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the height from an image element.
|
||||
*
|
||||
* @param string $img The full image element.
|
||||
* @return string The height found or an empty string.
|
||||
*/
|
||||
public function get_img_style_height( $img ) {
|
||||
// Then check for an inline max-height directive.
|
||||
$style = $this->get_attribute( $img, 'style' );
|
||||
if ( $style && \preg_match( '#max-height:\s?(\d+)px#', $style, $max_height_string ) ) {
|
||||
if ( ! empty( $max_height_string[1] ) && \is_numeric( $max_height_string[1] ) ) {
|
||||
return (int) $max_height_string[1];
|
||||
}
|
||||
} elseif ( $style && \preg_match( '#height:\s?(\d+)px#', $style, $height_string ) ) {
|
||||
if ( ! empty( $height_string[1] ) && \is_numeric( $height_string[1] ) ) {
|
||||
return (int) $height_string[1];
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get an attribute from an HTML element.
|
||||
*
|
||||
* @param string $element The HTML element to parse.
|
||||
* @param string $name The name of the attribute to search for.
|
||||
* @return string The value of the attribute, or an empty string if not found.
|
||||
*/
|
||||
public function get_attribute( $element, $name ) {
|
||||
// Don't forget, back references cannot be used in character classes.
|
||||
if ( \preg_match( '#\s' . $name . '\s*=\s*("|\')((?!\1).+?)\1#is', $element, $attr_matches ) ) {
|
||||
if ( ! empty( $attr_matches[2] ) ) {
|
||||
return $attr_matches[2];
|
||||
}
|
||||
}
|
||||
// If there were not any matches with quotes, look for unquoted attributes, no spaces or quotes allowed.
|
||||
if ( \preg_match( '#\s' . $name . '\s*=\s*([^"\'][^\s>]+)#is', $element, $attr_matches ) ) {
|
||||
if ( ! empty( $attr_matches[1] ) ) {
|
||||
return $attr_matches[1];
|
||||
}
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Get CSS background-image URLs.
|
||||
*
|
||||
* @param string $attribute An element's style attribute. Do not pass a full HTML element.
|
||||
* @return array An array containing URL(s) from the background/background-image property.
|
||||
*/
|
||||
public function get_background_image_urls( $attribute ) {
|
||||
$urls = array();
|
||||
if ( ( false !== \strpos( $attribute, 'background:' ) || false !== \strpos( $attribute, 'background-image:' ) ) && false !== \strpos( $attribute, 'url(' ) ) {
|
||||
if ( \preg_match_all( '#url\((?P<bg_url>[^)]+)\)#', $attribute, $prop_matches ) ) {
|
||||
if ( $this->is_iterable( $prop_matches['bg_url'] ) ) {
|
||||
foreach ( $prop_matches['bg_url'] as $url ) {
|
||||
$urls[] = \trim( \html_entity_decode( $url, ENT_QUOTES | ENT_HTML401 ), "'\"\t\n\r " );
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return $urls;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a single CSS background-image URL. For backwords compat.
|
||||
*
|
||||
* @param string $attribute An element's style attribute. Do not pass a full HTML element.
|
||||
* @return array An array containing URL(s) from the background/background-image property.
|
||||
*/
|
||||
public function get_background_image_url( $attribute ) {
|
||||
if ( ( false !== \strpos( $attribute, 'background:' ) || false !== \strpos( $attribute, 'background-image:' ) ) && false !== \strpos( $attribute, 'url(' ) ) {
|
||||
$background_urls = $this->get_background_image_urls( $attribute );
|
||||
if ( ! empty( $background_urls[0] ) ) {
|
||||
return $background_urls[0];
|
||||
}
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Get CSS background-image rules from HTML.
|
||||
*
|
||||
* @param string $html The code containing potential background images.
|
||||
* @return array The URLs with background/background-image properties.
|
||||
*/
|
||||
public function get_background_images( $html ) {
|
||||
if ( ( false !== \strpos( $html, 'background:' ) || false !== \strpos( $html, 'background-image:' ) ) && false !== \strpos( $html, 'url(' ) ) {
|
||||
if ( \preg_match_all( '#background(-image)?:\s*?[^;}]*?url\([^)]+\)#', $html, $matches ) ) {
|
||||
return $matches[0];
|
||||
}
|
||||
}
|
||||
return array();
|
||||
}
|
||||
|
||||
/**
|
||||
* Set an attribute on an HTML element.
|
||||
*
|
||||
* @param string $element The HTML element to modify. Passed by reference.
|
||||
* @param string $name The name of the attribute to set.
|
||||
* @param string $value The value of the attribute to set.
|
||||
* @param bool $replace Default false. True to replace, false to append.
|
||||
*/
|
||||
public function set_attribute( &$element, $name, $value, $replace = false ) {
|
||||
if ( 'class' === $name ) {
|
||||
$element = \preg_replace( "#\s$name\s+([^=])#", ' $1', $element );
|
||||
}
|
||||
// Remove empty attributes first.
|
||||
$element = \preg_replace( "#\s$name=\"\"#", ' ', $element );
|
||||
// Remove/escape double-quotes with the encoded version, so that we can safely enclose the value in double-quotes.
|
||||
$value = \str_replace( '"', '"', $value );
|
||||
$value = \trim( $value );
|
||||
if ( $replace ) {
|
||||
// Don't forget, back references cannot be used in character classes.
|
||||
$new_element = \preg_replace( '#\s' . $name . '\s*=\s*("|\')(?!\1).*?\1#is', ' ' . $name . '="' . $value . '"', $element );
|
||||
if ( \strpos( $new_element, "$name=" ) && $new_element !== $element ) {
|
||||
$element = $new_element;
|
||||
return;
|
||||
}
|
||||
// Purge un-quoted attribute patterns, so the new value can be inserted further down.
|
||||
$new_element = \preg_replace( '#\s' . $name . '\s*=\s*[^"\'][^\s>]+#is', ' ', $element );
|
||||
// But if we couldn't purge the attribute, then bail out.
|
||||
if ( \preg_match( '#\s' . $name . '\s*=\s*#', $new_element ) && $new_element === $element ) {
|
||||
$this->debug_message( "$name replacement failed, still exists in $element" );
|
||||
return;
|
||||
}
|
||||
$element = $new_element;
|
||||
}
|
||||
$closing = ' />';
|
||||
if ( false === \strpos( $element, '/>' ) ) {
|
||||
$closing = '>';
|
||||
}
|
||||
if ( false === \strpos( $value, '"' ) ) { // This should always be true, since we escape double-quotes above.
|
||||
$element = \rtrim( $element, $closing ) . " $name=\"$value\"$closing";
|
||||
return;
|
||||
}
|
||||
// If we get here, something is kind of weird, since double-quotes were supposed to be escaped.
|
||||
$element = \rtrim( $element, $closing ) . " $name='$value'$closing";
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove an attribute from an HTML element.
|
||||
*
|
||||
* @param string $element The HTML element to modify. Passed by reference.
|
||||
* @param string $name The name of the attribute to remove.
|
||||
*/
|
||||
public function remove_attribute( &$element, $name ) {
|
||||
// Don't forget, back references cannot be used in character classes.
|
||||
$element = \preg_replace( '#\s' . $name . '\s*=\s*("|\')(?!\1).+?\1#is', ' ', $element );
|
||||
$element = \preg_replace( '#\s' . $name . '\s*=\s*[^"\'][^\s>]+#is', ' ', $element );
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove the background image URL from a style attribute.
|
||||
*
|
||||
* @param string $attribute The element's style attribute to modify.
|
||||
* @return string The style attribute with any image url removed.
|
||||
*/
|
||||
public function remove_background_image( $attribute ) {
|
||||
if ( false !== \strpos( $attribute, 'background:' ) && false !== \strpos( $attribute, 'url(' ) ) {
|
||||
$new_attribute = \preg_replace( '#\s?url\([^)]+\)#', '', $attribute );
|
||||
if ( $new_attribute !== $attribute ) {
|
||||
return $new_attribute;
|
||||
}
|
||||
}
|
||||
if ( false !== \strpos( $attribute, 'background-image:' ) && false !== \strpos( $attribute, 'url(' ) ) {
|
||||
$new_attribute = \preg_replace( '#background-image:\s*(,?\s*url\([^)]+\))+;?\s*#', '', $attribute );
|
||||
if ( $new_attribute !== $attribute ) {
|
||||
$new_attribute = \preg_replace( '#background-image:\s*;?\s*$#', '', $new_attribute );
|
||||
return $new_attribute;
|
||||
}
|
||||
}
|
||||
if ( false !== \strpos( $attribute, 'background-image:' ) && false !== \strpos( $attribute, 'url(' ) ) {
|
||||
$new_attribute = \preg_replace( '#,?\s*url\([^)]+\)#', '', $attribute );
|
||||
if ( $new_attribute !== $attribute ) {
|
||||
$new_attribute = \preg_replace( '#background-image:\s*;?\s*$#', '', $new_attribute );
|
||||
return $new_attribute;
|
||||
}
|
||||
}
|
||||
return $attribute;
|
||||
}
|
||||
}
|
@ -0,0 +1,595 @@
|
||||
<?php
|
||||
/**
|
||||
* Implements WebP rewriting using page parsing and <picture> tags.
|
||||
*
|
||||
* @link https://ewww.io
|
||||
* @package EIO
|
||||
*/
|
||||
|
||||
namespace EWWW;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Enables EWWW IO to filter the page content and replace img elements with WebP <picture> markup.
|
||||
*/
|
||||
class Picture_Webp extends Page_Parser {
|
||||
|
||||
/**
|
||||
* A list of user-defined exclusions, populated by validate_user_exclusions().
|
||||
*
|
||||
* @access protected
|
||||
* @var array $user_exclusions
|
||||
*/
|
||||
protected $user_exclusions = array();
|
||||
|
||||
/**
|
||||
* A list of user-defined (element-type) exclusions, populated by validate_user_exclusions().
|
||||
*
|
||||
* @access protected
|
||||
* @var array $user_exclusions
|
||||
*/
|
||||
protected $user_element_exclusions = array();
|
||||
|
||||
/**
|
||||
* A list of user-defined page/URL exclusions, populated by validate_user_exclusions().
|
||||
*
|
||||
* @access protected
|
||||
* @var array $user_page_exclusions
|
||||
*/
|
||||
protected $user_page_exclusions = array();
|
||||
|
||||
/**
|
||||
* Request URI.
|
||||
*
|
||||
* @var string $request_uri
|
||||
*/
|
||||
public $request_uri = '';
|
||||
|
||||
/**
|
||||
* Register (once) actions and filters for Picture WebP.
|
||||
*/
|
||||
public function __construct() {
|
||||
global $eio_picture_webp;
|
||||
if ( \is_object( $eio_picture_webp ) ) {
|
||||
return 'you are doing it wrong';
|
||||
}
|
||||
if ( \ewww_image_optimizer_ce_webp_enabled() ) {
|
||||
return false;
|
||||
}
|
||||
parent::__construct();
|
||||
$this->debug_message( '<b>' . __METHOD__ . '()</b>' );
|
||||
$this->content_url();
|
||||
|
||||
$this->request_uri = \add_query_arg( '', '' );
|
||||
if ( false === \strpos( $this->request_uri, 'page=ewww-image-optimizer-options' ) ) {
|
||||
$this->debug_message( "request uri is {$this->request_uri}" );
|
||||
} else {
|
||||
$this->debug_message( 'request uri is EWWW IO settings' );
|
||||
}
|
||||
|
||||
\add_filter( 'eio_do_picture_webp', array( $this, 'should_process_page' ), 10, 2 );
|
||||
|
||||
/**
|
||||
* Allow pre-empting <picture> WebP by page.
|
||||
*
|
||||
* @param bool Whether to parse the page for images to rewrite for WebP, default true.
|
||||
* @param string The URI/path of the page.
|
||||
*/
|
||||
if ( ! \apply_filters( 'eio_do_picture_webp', true, $this->request_uri ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Make sure gallery block images crop properly.
|
||||
\add_action( 'wp_head', array( $this, 'gallery_block_css' ) );
|
||||
// Hook onto the output buffer function.
|
||||
if ( \function_exists( '\swis' ) && \swis()->settings->get_option( 'lazy_load' ) ) {
|
||||
\add_filter( 'swis_filter_page_output', array( $this, 'filter_page_output' ) );
|
||||
} else {
|
||||
\add_filter( 'ewww_image_optimizer_filter_page_output', array( $this, 'filter_page_output' ), 10 );
|
||||
}
|
||||
// Filter for FacetWP JSON responses.
|
||||
\add_filter( 'facetwp_render_output', array( $this, 'filter_facetwp_json_output' ) );
|
||||
|
||||
$allowed_urls = $this->get_option( 'ewww_image_optimizer_webp_paths' );
|
||||
if ( $this->is_iterable( $allowed_urls ) ) {
|
||||
$this->allowed_urls = \array_merge( $this->allowed_urls, $allowed_urls );
|
||||
}
|
||||
|
||||
$this->get_allowed_domains();
|
||||
|
||||
$this->allowed_urls = \apply_filters( 'webp_allowed_urls', $this->allowed_urls );
|
||||
$this->allowed_domains = \apply_filters( 'webp_allowed_domains', $this->allowed_domains );
|
||||
$this->debug_message( 'checking any images matching these URLs/patterns for webp: ' . \implode( ',', $this->allowed_urls ) );
|
||||
$this->debug_message( 'rewriting any images matching these domains to webp: ' . \implode( ',', $this->allowed_domains ) );
|
||||
$this->validate_user_exclusions();
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if pages should be processed, especially for things like page builders.
|
||||
*
|
||||
* @since 6.2.2
|
||||
*
|
||||
* @param boolean $should_process Whether <picture> WebP should process the page.
|
||||
* @param string $uri The URI of the page (no domain or scheme included).
|
||||
* @return boolean True to process the page, false to skip.
|
||||
*/
|
||||
public function should_process_page( $should_process = true, $uri = '' ) {
|
||||
// Don't foul up the admin side of things, unless a plugin needs to.
|
||||
if ( \is_admin() &&
|
||||
/**
|
||||
* Provide plugins a way of running <picture> WebP for images in the WordPress Admin, usually for admin-ajax.php.
|
||||
*
|
||||
* @param bool false Allow <picture> WebP to run on the Dashboard. Defaults to false.
|
||||
*/
|
||||
false === \apply_filters( 'eio_allow_admin_picture_webp', false )
|
||||
) {
|
||||
$this->debug_message( 'is_admin' );
|
||||
return false;
|
||||
}
|
||||
if ( \ewww_image_optimizer_ce_webp_enabled() ) {
|
||||
return false;
|
||||
}
|
||||
if ( empty( $uri ) ) {
|
||||
$uri = $this->request_uri;
|
||||
}
|
||||
if ( $this->is_iterable( $this->user_page_exclusions ) ) {
|
||||
foreach ( $this->user_page_exclusions as $page_exclusion ) {
|
||||
if ( '/' === $page_exclusion && '/' === $uri ) {
|
||||
return false;
|
||||
} elseif ( '/' === $page_exclusion ) {
|
||||
continue;
|
||||
}
|
||||
if ( false !== \strpos( $uri, $page_exclusion ) ) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
if ( false !== \strpos( $uri, 'bricks=run' ) ) {
|
||||
return false;
|
||||
}
|
||||
if ( false !== \strpos( $uri, '?brizy-edit' ) ) {
|
||||
return false;
|
||||
}
|
||||
if ( false !== \strpos( $uri, '&builder=true' ) ) {
|
||||
return false;
|
||||
}
|
||||
if ( false !== \strpos( $uri, 'cornerstone=' ) || false !== \strpos( $uri, 'cornerstone-endpoint' ) || false !== \strpos( $uri, 'cornerstone/edit/' ) ) {
|
||||
return false;
|
||||
}
|
||||
if ( false !== \strpos( $uri, 'ct_builder=' ) ) {
|
||||
return false;
|
||||
}
|
||||
if ( false !== \strpos( $uri, 'ct_render_shortcode=' ) || false !== \strpos( $uri, 'action=oxy_render' ) ) {
|
||||
return false;
|
||||
}
|
||||
if ( \did_action( 'cornerstone_boot_app' ) || \did_action( 'cs_before_preview_frame' ) ) {
|
||||
return false;
|
||||
}
|
||||
if ( \did_action( 'cs_element_rendering' ) || \did_action( 'cornerstone_before_boot_app' ) || \apply_filters( 'cs_is_preview_render', false ) ) {
|
||||
return false;
|
||||
}
|
||||
if ( false !== \strpos( $uri, 'elementor-preview=' ) ) {
|
||||
return false;
|
||||
}
|
||||
if ( false !== \strpos( $uri, 'et_fb=' ) ) {
|
||||
return false;
|
||||
}
|
||||
if ( false !== \strpos( $uri, 'fb-edit=' ) ) {
|
||||
return false;
|
||||
}
|
||||
if ( false !== \strpos( $uri, '?fl_builder' ) ) {
|
||||
return false;
|
||||
}
|
||||
if ( false !== \strpos( $uri, 'is-editor-iframe=' ) ) {
|
||||
return false;
|
||||
}
|
||||
if ( '/print/' === \substr( $uri, -7 ) ) {
|
||||
return false;
|
||||
}
|
||||
if ( \defined( 'REST_REQUEST' ) && REST_REQUEST ) {
|
||||
return false;
|
||||
}
|
||||
if ( false !== \strpos( $uri, 'tatsu=' ) ) {
|
||||
return false;
|
||||
}
|
||||
if ( false !== \strpos( $uri, 'tve=true' ) ) {
|
||||
return false;
|
||||
}
|
||||
if ( ! empty( $_POST['action'] ) && 'tatsu_get_concepts' === \sanitize_text_field( \wp_unslash( $_POST['action'] ) ) ) { // phpcs:ignore WordPress.Security.NonceVerification
|
||||
return false;
|
||||
}
|
||||
if ( \is_customize_preview() ) {
|
||||
$this->debug_message( 'is_customize_preview' );
|
||||
return false;
|
||||
}
|
||||
global $wp_query;
|
||||
if ( ! isset( $wp_query ) || ! ( $wp_query instanceof \WP_Query ) ) {
|
||||
return $should_process;
|
||||
}
|
||||
if ( $this->is_amp() ) {
|
||||
return false;
|
||||
}
|
||||
if ( \is_feed() ) {
|
||||
$this->debug_message( 'is_feed' );
|
||||
return false;
|
||||
}
|
||||
if ( \is_preview() ) {
|
||||
$this->debug_message( 'is_preview' );
|
||||
return false;
|
||||
}
|
||||
if ( \wp_script_is( 'twentytwenty-twentytwenty', 'enqueued' ) ) {
|
||||
$this->debug_message( 'twentytwenty enqueued' );
|
||||
return false;
|
||||
}
|
||||
return $should_process;
|
||||
}
|
||||
|
||||
/**
|
||||
* Grant read-only access to allowed WebP domains.
|
||||
*
|
||||
* @return array A list of WebP domains.
|
||||
*/
|
||||
public function get_webp_domains() {
|
||||
return $this->allowed_domains;
|
||||
}
|
||||
|
||||
/**
|
||||
* Replaces images within a srcset attribute with their .webp derivatives.
|
||||
*
|
||||
* @param string $srcset A valid srcset attribute from an img element.
|
||||
* @return bool|string False if no changes were made, or the new srcset if any WebP images replaced the originals.
|
||||
*/
|
||||
public function srcset_replace( $srcset ) {
|
||||
$srcset_urls = \explode( ' ', $srcset );
|
||||
$found_webp = false;
|
||||
if ( $this->is_iterable( $srcset_urls ) && \count( $srcset_urls ) > 1 ) {
|
||||
$this->debug_message( 'parsing srcset urls' );
|
||||
foreach ( $srcset_urls as $srcurl ) {
|
||||
if ( \is_numeric( \substr( $srcurl, 0, 1 ) ) ) {
|
||||
continue;
|
||||
}
|
||||
$trailing = ' ';
|
||||
if ( ',' === \substr( $srcurl, -1 ) ) {
|
||||
$trailing = ',';
|
||||
$srcurl = \rtrim( $srcurl, ',' );
|
||||
}
|
||||
$this->debug_message( "looking for $srcurl from srcset" );
|
||||
if ( $this->validate_image_url( $srcurl ) ) {
|
||||
$srcset = \str_replace( $srcurl . $trailing, $this->generate_url( $srcurl ) . $trailing, $srcset );
|
||||
$this->debug_message( "replaced $srcurl in srcset" );
|
||||
$found_webp = true;
|
||||
}
|
||||
}
|
||||
} elseif ( $this->validate_image_url( $srcset ) ) {
|
||||
return $this->generate_url( $srcset );
|
||||
}
|
||||
if ( $found_webp ) {
|
||||
return $srcset;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Search for img elements and rewrite them with noscript elements for WebP replacement.
|
||||
*
|
||||
* Any img elements or elements that may be used in place of img elements by JS are checked to see
|
||||
* if WebP derivatives exist. The element is then wrapped within a noscript element for fallback,
|
||||
* and noscript element receives a copy of the attributes from the img along with webp replacement
|
||||
* values for those attributes.
|
||||
*
|
||||
* @param string $buffer The full HTML page generated since the output buffer was started.
|
||||
* @return string The altered buffer containing the full page with WebP images inserted.
|
||||
*/
|
||||
public function filter_page_output( $buffer ) {
|
||||
$this->debug_message( '<b>' . __METHOD__ . '()</b>' );
|
||||
if (
|
||||
empty( $buffer ) ||
|
||||
\preg_match( '/^<\?xml/', $buffer ) ||
|
||||
\strpos( $buffer, 'amp-boilerplate' )
|
||||
) {
|
||||
$this->debug_message( 'picture WebP disabled' );
|
||||
return $buffer;
|
||||
}
|
||||
if ( $this->is_json( $buffer ) ) {
|
||||
return $buffer;
|
||||
}
|
||||
if ( ! $this->should_process_page() ) {
|
||||
$this->debug_message( 'picture WebP should not process page' );
|
||||
return $buffer;
|
||||
}
|
||||
if ( ! \apply_filters( 'eio_do_picture_webp', true, $this->request_uri ) ) {
|
||||
return $buffer;
|
||||
}
|
||||
|
||||
$images = $this->get_images_from_html( \preg_replace( '/<(picture|noscript).*?\/\1>/s', '', $buffer ), false );
|
||||
if ( ! empty( $images[0] ) && $this->is_iterable( $images[0] ) ) {
|
||||
foreach ( $images[0] as $index => $image ) {
|
||||
if ( ! $this->validate_img_tag( $image ) ) {
|
||||
continue;
|
||||
}
|
||||
$file = $images['img_url'][ $index ];
|
||||
$this->debug_message( "parsing an image: $file" );
|
||||
if ( $this->validate_image_url( $file ) ) {
|
||||
// If a CDN path match was found, or .webp image existence is confirmed.
|
||||
$this->debug_message( 'found a webp image or forced path' );
|
||||
$srcset = $this->get_attribute( $image, 'srcset' );
|
||||
$srcset_webp = '';
|
||||
if ( $srcset ) {
|
||||
$srcset_webp = $this->srcset_replace( $srcset );
|
||||
}
|
||||
$sizes_attr = '';
|
||||
if ( empty( $srcset_webp ) ) {
|
||||
$srcset_webp = $this->generate_url( $file );
|
||||
} else {
|
||||
$sizes = $this->get_attribute( $image, 'sizes' );
|
||||
if ( $sizes ) {
|
||||
$sizes_attr = "sizes='$sizes'";
|
||||
}
|
||||
}
|
||||
if ( empty( $srcset_webp ) || $srcset_webp === $file ) {
|
||||
continue;
|
||||
}
|
||||
$pic_img = $image;
|
||||
$this->set_attribute( $pic_img, 'data-eio', 'p', true );
|
||||
$picture_tag = "<picture><source srcset=\"$srcset_webp\" $sizes_attr type=\"image/webp\">$pic_img</picture>";
|
||||
$this->debug_message( "going to swap\n$image\nwith\n$picture_tag" );
|
||||
$buffer = \str_replace( $image, $picture_tag, $buffer );
|
||||
}
|
||||
} // End foreach().
|
||||
} // End if().
|
||||
// Images listed as picture/source elements.
|
||||
$pictures = $this->get_picture_tags_from_html( $buffer );
|
||||
if ( $this->is_iterable( $pictures ) ) {
|
||||
foreach ( $pictures as $index => $picture ) {
|
||||
if ( \strpos( $picture, 'image/webp' ) ) {
|
||||
continue;
|
||||
}
|
||||
if ( ! $this->validate_tag( $picture ) ) {
|
||||
continue;
|
||||
}
|
||||
$sources = $this->get_elements_from_html( $picture, 'source' );
|
||||
if ( $this->is_iterable( $sources ) ) {
|
||||
foreach ( $sources as $source ) {
|
||||
$this->debug_message( "parsing a picture source: $source" );
|
||||
$srcset_attr_name = 'srcset';
|
||||
if ( false !== \strpos( $source, 'base64,R0lGOD' ) && false !== \strpos( $source, 'data-srcset=' ) ) {
|
||||
$srcset_attr_name = 'data-srcset';
|
||||
} elseif ( ! $this->get_attribute( $source, $srcset_attr_name ) && false !== strpos( $source, 'data-srcset=' ) ) {
|
||||
$srcset_attr_name = 'data-srcset';
|
||||
}
|
||||
$srcset = $this->get_attribute( $source, $srcset_attr_name );
|
||||
if ( $srcset ) {
|
||||
$srcset_webp = $this->srcset_replace( $srcset );
|
||||
if ( $srcset_webp ) {
|
||||
$source_webp = \str_replace( $srcset, $srcset_webp, $source );
|
||||
$this->set_attribute( $source_webp, 'type', 'image/webp' );
|
||||
$picture = \str_replace( $source, $source_webp . $source, $picture );
|
||||
}
|
||||
}
|
||||
}
|
||||
if ( $picture !== $pictures[ $index ] ) {
|
||||
$this->debug_message( 'found webp for picture element' );
|
||||
$buffer = \str_replace( $pictures[ $index ], $picture, $buffer );
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
$this->debug_message( 'all done parsing page for picture webp' );
|
||||
return $buffer;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse template data from FacetWP that will be included in JSON response.
|
||||
* https://facetwp.com/documentation/developers/output/facetwp_render_output/
|
||||
*
|
||||
* @param array $output The full array of FacetWP data.
|
||||
* @return array The FacetWP data with WebP images.
|
||||
*/
|
||||
public function filter_facetwp_json_output( $output ) {
|
||||
$this->debug_message( '<b>' . __METHOD__ . '()</b>' );
|
||||
if ( empty( $output['template'] ) || ! \is_string( $output['template'] ) ) {
|
||||
return $output;
|
||||
}
|
||||
|
||||
$template = $this->filter_page_output( $output['template'] );
|
||||
if ( $template ) {
|
||||
$this->debug_message( 'template data modified' );
|
||||
$output['template'] = $template;
|
||||
}
|
||||
|
||||
return $output;
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts a URL to a file-system path and checks if the resulting path exists.
|
||||
*
|
||||
* @param string $url The URL to mangle.
|
||||
* @param string $extension An optional extension to append during is_file().
|
||||
* @return bool True if a local file exists correlating to the URL, false otherwise.
|
||||
*/
|
||||
public function url_to_path_exists( $url, $extension = '' ) {
|
||||
return parent::url_to_path_exists( $url, '.webp' );
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate the user-defined exclusions.
|
||||
*/
|
||||
public function validate_user_exclusions() {
|
||||
$user_exclusions = $this->get_option( $this->prefix . 'webp_rewrite_exclude' );
|
||||
$this->debug_message( $this->prefix . 'webp_rewrite_exclude' );
|
||||
if ( ! empty( $user_exclusions ) ) {
|
||||
if ( \is_string( $user_exclusions ) ) {
|
||||
$user_exclusions = array( $user_exclusions );
|
||||
}
|
||||
if ( \is_array( $user_exclusions ) ) {
|
||||
foreach ( $user_exclusions as $exclusion ) {
|
||||
if ( ! \is_string( $exclusion ) ) {
|
||||
continue;
|
||||
}
|
||||
$exclusion = \trim( $exclusion );
|
||||
if ( 0 === \strpos( $exclusion, 'page:' ) ) {
|
||||
$this->user_page_exclusions[] = \str_replace( 'page:', '', $exclusion );
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
'a' === $exclusion ||
|
||||
'div' === $exclusion ||
|
||||
'li' === $exclusion ||
|
||||
'picture' === $exclusion ||
|
||||
'section' === $exclusion ||
|
||||
'span' === $exclusion ||
|
||||
'video' === $exclusion
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
$this->user_exclusions[] = $exclusion;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the tag is allowed to be rewritten.
|
||||
*
|
||||
* @param string $image The HTML tag: img, span, etc.
|
||||
* @return bool False if it flags a filter or exclusion, true otherwise.
|
||||
*/
|
||||
public function validate_tag( $image ) {
|
||||
$this->debug_message( '<b>' . __METHOD__ . '()</b>' );
|
||||
// For now, only picture tags are allowed anyway, so just roll with it!
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the img tag is allowed to be rewritten.
|
||||
*
|
||||
* @param string $image The img tag.
|
||||
* @return bool False if it flags a filter or exclusion, true otherwise.
|
||||
*/
|
||||
public function validate_img_tag( $image ) {
|
||||
$this->debug_message( '<b>' . __METHOD__ . '()</b>' );
|
||||
// Skip inline data URIs.
|
||||
if ( false !== \strpos( $image, 'data:image' ) ) {
|
||||
$this->debug_message( 'data:image pattern detected in src' );
|
||||
return false;
|
||||
}
|
||||
// Ignore 0-size Pinterest schema images.
|
||||
if ( \strpos( $image, 'data-pin-description=' ) && \strpos( $image, 'width="0" height="0"' ) ) {
|
||||
$this->debug_message( 'data-pin-description img skipped' );
|
||||
return false;
|
||||
}
|
||||
|
||||
$exclusions = \apply_filters(
|
||||
'ewwwio_picture_webp_exclusions',
|
||||
\array_merge(
|
||||
array(
|
||||
'lazyload',
|
||||
'class="ls-bg',
|
||||
'class="ls-l',
|
||||
'class="rev-slidebg',
|
||||
'data-bgposition=',
|
||||
'data-envira-src=',
|
||||
'data-lazy=',
|
||||
'data-lazy-original=',
|
||||
'data-lazy-src=',
|
||||
'data-lazy-srcset=',
|
||||
'data-lazyload=',
|
||||
'data-lazysrc=',
|
||||
'data-no-lazy=',
|
||||
'data-src=',
|
||||
'data-srcset=',
|
||||
'fullurl=',
|
||||
'gazette-featured-content-thumbnail',
|
||||
'jetpack-lazy-image',
|
||||
'lazy-slider-img=',
|
||||
'mgl-lazy',
|
||||
'skip-lazy',
|
||||
'timthumb.php?',
|
||||
'wpcf7_captcha/',
|
||||
),
|
||||
$this->user_exclusions
|
||||
),
|
||||
$image
|
||||
);
|
||||
foreach ( $exclusions as $exclusion ) {
|
||||
if ( false !== \strpos( $image, $exclusion ) ) {
|
||||
$this->debug_message( "img matched $exclusion" );
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the path is a valid WebP image, on-disk or forced.
|
||||
*
|
||||
* @param string $image The image URL.
|
||||
* @return bool True if the file exists or matches a forced path, false otherwise.
|
||||
*/
|
||||
public function validate_image_url( $image ) {
|
||||
$this->debug_message( __METHOD__ . "() webp validation for $image" );
|
||||
if ( $this->is_lazy_placeholder( $image ) ) {
|
||||
return false;
|
||||
}
|
||||
// Cleanup the image from encoded HTML characters.
|
||||
$image = \str_replace( '&', '&', $image );
|
||||
$image = \str_replace( '#038;', '&', $image );
|
||||
|
||||
$extension = '';
|
||||
$image_path = $this->parse_url( $image, PHP_URL_PATH );
|
||||
if ( ! \is_null( $image_path ) && $image_path ) {
|
||||
$extension = \strtolower( \pathinfo( $image_path, PATHINFO_EXTENSION ) );
|
||||
}
|
||||
if ( $extension && 'gif' === $extension && ! $this->get_option( 'ewww_image_optimizer_force_gif2webp' ) ) {
|
||||
return false;
|
||||
}
|
||||
if ( $extension && 'svg' === $extension ) {
|
||||
return false;
|
||||
}
|
||||
if ( $extension && 'webp' === $extension ) {
|
||||
return false;
|
||||
}
|
||||
if ( \apply_filters( 'ewww_image_optimizer_skip_webp_rewrite', false, $image ) ) {
|
||||
return false;
|
||||
}
|
||||
if ( $this->get_option( 'ewww_image_optimizer_webp_force' ) && $this->is_iterable( $this->allowed_urls ) ) {
|
||||
// Check the image for configured CDN paths.
|
||||
foreach ( $this->allowed_urls as $allowed_url ) {
|
||||
if ( \strpos( $image, $allowed_url ) !== false ) {
|
||||
$this->debug_message( 'forced cdn image' );
|
||||
return true;
|
||||
}
|
||||
}
|
||||
} elseif ( $this->allowed_urls && $this->allowed_domains ) {
|
||||
if ( $this->cdn_to_local( $image ) ) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return $this->url_to_path_exists( $image );
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a WebP URL by appending .webp to the filename.
|
||||
*
|
||||
* @param string $url The image url.
|
||||
* @return string The WebP version of the image url.
|
||||
*/
|
||||
public function generate_url( $url ) {
|
||||
$path_parts = \explode( '?', $url );
|
||||
return \apply_filters( 'ewwwio_generated_webp_image_url', $path_parts[0] . '.webp' . ( ! empty( $path_parts[1] ) && 'is-pending-load=1' !== $path_parts[1] ? '?' . $path_parts[1] : '' ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a small CSS block to make sure images in gallery blocks behave.
|
||||
*/
|
||||
public function gallery_block_css() {
|
||||
echo '<style>.wp-block-gallery.is-cropped .blocks-gallery-item picture{height:100%;width:100%;}</style>';
|
||||
}
|
||||
}
|
||||
|
||||
global $eio_picture_webp;
|
||||
$eio_picture_webp = new Picture_Webp();
|
924
wp-content/plugins/ewww-image-optimizer/classes/class-plugin.php
Normal file
@ -0,0 +1,924 @@
|
||||
<?php
|
||||
/**
|
||||
* Low-level plugin class.
|
||||
*
|
||||
* @link https://ewww.io
|
||||
* @package EWWW_Image_Optimizer
|
||||
*/
|
||||
|
||||
namespace EWWW;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* The kitchen sink, for everything that doesn't fit somewhere else.
|
||||
* Ideally, these are things like plugin initialization, setting defaults, and checking compatibility. We'll see how that plays out!
|
||||
*/
|
||||
final class Plugin extends Base {
|
||||
/* Singleton */
|
||||
|
||||
/**
|
||||
* The one and only true EWWW\Plugin
|
||||
*
|
||||
* @var object|EWWW\Plugin $instance
|
||||
*/
|
||||
private static $instance;
|
||||
|
||||
/**
|
||||
* Async Key Verify object.
|
||||
*
|
||||
* @var object|EWWW\Async_Key_Verify $async_key_verify
|
||||
*/
|
||||
public $async_key_verify;
|
||||
|
||||
/**
|
||||
* Async Scan object.
|
||||
*
|
||||
* @var object|EWWW\Async_Scan $async_scan
|
||||
*/
|
||||
public $async_scan;
|
||||
|
||||
/**
|
||||
* Async Test Optimize object.
|
||||
*
|
||||
* @var object|EWWW\Async_Test_Optimize $async_test_optimize
|
||||
*/
|
||||
public $async_test_optimize;
|
||||
|
||||
/**
|
||||
* Async Test Request object.
|
||||
*
|
||||
* @var object|EWWW\Async_Test_Request $async_test_request
|
||||
*/
|
||||
public $async_test_request;
|
||||
|
||||
/**
|
||||
* Background Process Flag object.
|
||||
*
|
||||
* @var object|EWWW\Background_Process_Flag $background_flag
|
||||
*/
|
||||
public $background_flag;
|
||||
|
||||
/**
|
||||
* Background Process Image object.
|
||||
*
|
||||
* @var object|EWWW\Background_Process_Image $background_image
|
||||
*/
|
||||
public $background_image;
|
||||
|
||||
/**
|
||||
* Background Process Media object.
|
||||
*
|
||||
* @var object|EWWW\Background_Process_Media $background_media
|
||||
*/
|
||||
public $background_media;
|
||||
|
||||
/**
|
||||
* Background Process Ngg object.
|
||||
*
|
||||
* @var object|EWWW\Background_Process_Ngg $background_ngg
|
||||
*/
|
||||
public $background_ngg;
|
||||
|
||||
/**
|
||||
* Background Process Ngg2 object.
|
||||
*
|
||||
* @var object|EWWW\Background_Process_Ngg2 $background_ngg2
|
||||
*/
|
||||
public $background_ngg2;
|
||||
|
||||
/**
|
||||
* Helpscout Beacon object.
|
||||
*
|
||||
* @var object|EWWW\HS_Beacon $hs_beacon
|
||||
*/
|
||||
public $hs_beacon;
|
||||
|
||||
/**
|
||||
* EWWW\Local object for handling local optimization tools/functions.
|
||||
*
|
||||
* @var object|EWWW\Local $local
|
||||
*/
|
||||
public $local;
|
||||
|
||||
/**
|
||||
* EWWW\Tracking object for anonymous usage tracking.
|
||||
*
|
||||
* @var object|EWWW\Tracking $tracking
|
||||
*/
|
||||
public $tracking;
|
||||
|
||||
/**
|
||||
* Whether the plugin is using the API or local tools.
|
||||
*
|
||||
* @var bool $cloud_mode
|
||||
*/
|
||||
public $cloud_mode = false;
|
||||
|
||||
/**
|
||||
* Did we already run tool_init()?
|
||||
*
|
||||
* @var bool $tools_initialized
|
||||
*/
|
||||
public $tools_initialized = false;
|
||||
|
||||
/**
|
||||
* Main EWWW\Plugin instance.
|
||||
*
|
||||
* Ensures that only one instance of EWWW_Plugin exists in memory at any given time.
|
||||
*
|
||||
* @static
|
||||
*/
|
||||
public static function instance() {
|
||||
if ( ! isset( self::$instance ) && ! ( self::$instance instanceof Plugin ) ) {
|
||||
// Setup custom $wpdb attribute for our image-tracking table.
|
||||
global $wpdb;
|
||||
if ( ! isset( $wpdb->ewwwio_images ) ) {
|
||||
$wpdb->ewwwio_images = $wpdb->prefix . 'ewwwio_images';
|
||||
}
|
||||
if ( ! isset( $wpdb->ewwwio_queue ) ) {
|
||||
$wpdb->ewwwio_queue = $wpdb->prefix . 'ewwwio_queue';
|
||||
}
|
||||
|
||||
self::$instance = new Plugin( true );
|
||||
self::$instance->debug_message( '<b>' . __METHOD__ . '()</b>' );
|
||||
// TODO: self::$instance->setup_constants()?
|
||||
|
||||
// For classes we need everywhere, front-end and back-end. Others are only included on admin_init (below).
|
||||
self::$instance->requires();
|
||||
self::$instance->load_children();
|
||||
// Initializes the plugin for admin interactions, like saving network settings and scheduling cron jobs.
|
||||
\add_action( 'admin_init', array( self::$instance, 'admin_init' ) );
|
||||
// We run this early, and then double-check after admin_init, once network settings have been saved/updated.
|
||||
self::$instance->cloud_init();
|
||||
|
||||
// AJAX action hook to dismiss the exec notice and other related notices.
|
||||
\add_action( 'wp_ajax_ewww_dismiss_exec_notice', array( self::$instance, 'dismiss_exec_notice' ) );
|
||||
|
||||
// TODO: check PHP and WP compat here.
|
||||
// TODO: setup anything that needs to run on init/plugins_loaded.
|
||||
// TODO: add any custom option/setting hooks here (actions that need to be taken when certain settings are saved/updated).
|
||||
\add_action( 'update_option_ewww_image_optimizer_cloud_key', array( self::$instance, 'updated_cloud_key' ), 10, 2 );
|
||||
}
|
||||
|
||||
return self::$instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Throw error on object clone.
|
||||
*
|
||||
* The whole idea of the singleton design pattern is that there is a single
|
||||
* object. Therefore, we don't want the object to be cloned.
|
||||
*/
|
||||
public function __clone() {
|
||||
// Cloning instances of the class is forbidden.
|
||||
\_doing_it_wrong( __METHOD__, \esc_html__( 'Cannot clone core object.', 'ewww-image-optimizer' ), \esc_html( EWWW_IMAGE_OPTIMIZER_VERSION ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Disable unserializing of the class.
|
||||
*/
|
||||
public function __wakeup() {
|
||||
// Unserializing instances of the class is forbidden.
|
||||
\_doing_it_wrong( __METHOD__, \esc_html__( 'Cannot unserialize (wakeup) the core object.', 'ewww-image-optimizer' ), \esc_html( EWWW_IMAGE_OPTIMIZER_VERSION ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Include required files.
|
||||
*
|
||||
* @access private
|
||||
*/
|
||||
private function requires() {
|
||||
// Fall-back and convenience functions.
|
||||
require_once EWWW_IMAGE_OPTIMIZER_PLUGIN_PATH . 'functions.php';
|
||||
// Require the various class extensions for background optimization.
|
||||
$this->async_requires();
|
||||
// EWWW_Image class for working with queued images and image records from the database.
|
||||
require_once EWWW_IMAGE_OPTIMIZER_PLUGIN_PATH . 'classes/class-ewww-image.php';
|
||||
// EWWW\Backup class for managing image backups.
|
||||
require_once EWWW_IMAGE_OPTIMIZER_PLUGIN_PATH . 'classes/class-backup.php';
|
||||
// EWWW\HS_Beacon class for integrated help/docs.
|
||||
require_once EWWW_IMAGE_OPTIMIZER_PLUGIN_PATH . 'classes/class-hs-beacon.php';
|
||||
// EWWW\Tracking class for reporting anonymous site data.
|
||||
require_once EWWW_IMAGE_OPTIMIZER_PLUGIN_PATH . 'classes/class-tracking.php';
|
||||
if ( 'done' !== get_option( 'ewww_image_optimizer_relative_migration_status' ) ) {
|
||||
require_once EWWW_IMAGE_OPTIMIZER_PLUGIN_PATH . 'classes/class-ewwwio-relative-migration.php';
|
||||
}
|
||||
// Used for manipulating exif info.
|
||||
if ( ! class_exists( '\lsolesen\pel\PelJpeg' ) ) {
|
||||
require_once EWWW_IMAGE_OPTIMIZER_PLUGIN_PATH . 'vendor/autoload.php';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Include required files for async/background processing.
|
||||
*
|
||||
* @access private
|
||||
*/
|
||||
private function async_requires() {
|
||||
/**
|
||||
* The (grand)parent EWWW\Async_Request class file.
|
||||
*/
|
||||
require_once EWWW_IMAGE_OPTIMIZER_PLUGIN_PATH . 'classes/class-async-request.php';
|
||||
|
||||
/**
|
||||
* The parent EWWW\Background_Process class file.
|
||||
*/
|
||||
require_once EWWW_IMAGE_OPTIMIZER_PLUGIN_PATH . 'classes/class-background-process.php';
|
||||
|
||||
// Async API Key verification.
|
||||
require_once EWWW_IMAGE_OPTIMIZER_PLUGIN_PATH . 'classes/class-async-key-verify.php';
|
||||
// Async image scanning for scheduled opt.
|
||||
require_once EWWW_IMAGE_OPTIMIZER_PLUGIN_PATH . 'classes/class-async-scan.php';
|
||||
// Async optimization test, used for debugging.
|
||||
require_once EWWW_IMAGE_OPTIMIZER_PLUGIN_PATH . 'classes/class-async-test-optimize.php';
|
||||
// Async test request, used to make sure async works properly.
|
||||
require_once EWWW_IMAGE_OPTIMIZER_PLUGIN_PATH . 'classes/class-async-test-request.php';
|
||||
// Background optimization for GRAND FlaGallery.
|
||||
require_once EWWW_IMAGE_OPTIMIZER_PLUGIN_PATH . 'classes/class-background-process-flag.php';
|
||||
// Background optimization for individual images.
|
||||
require_once EWWW_IMAGE_OPTIMIZER_PLUGIN_PATH . 'classes/class-background-process-image.php';
|
||||
// Background optimization for the Media Library.
|
||||
require_once EWWW_IMAGE_OPTIMIZER_PLUGIN_PATH . 'classes/class-background-process-media.php';
|
||||
// Background optimization for Nextcellent.
|
||||
require_once EWWW_IMAGE_OPTIMIZER_PLUGIN_PATH . 'classes/class-background-process-ngg.php';
|
||||
// Background optimization for NextGEN Gallery.
|
||||
require_once EWWW_IMAGE_OPTIMIZER_PLUGIN_PATH . 'classes/class-background-process-ngg2.php';
|
||||
}
|
||||
|
||||
/**
|
||||
* Setup mandatory child classes.
|
||||
*/
|
||||
public function load_children() {
|
||||
// Setup async/background classes first.
|
||||
self::$instance->async_key_verify = new Async_Key_Verify();
|
||||
self::$instance->async_scan = new Async_Scan();
|
||||
self::$instance->async_test_optimize = new Async_Test_Optimize();
|
||||
self::$instance->async_test_request = new Async_Test_Request();
|
||||
self::$instance->background_flag = new Background_Process_Flag();
|
||||
self::$instance->background_image = new Background_Process_Image();
|
||||
self::$instance->background_media = new Background_Process_Media();
|
||||
self::$instance->background_ngg = new Background_Process_Ngg();
|
||||
self::$instance->background_ngg2 = new Background_Process_Ngg2();
|
||||
|
||||
// Then, setup the rest of the classes we need.
|
||||
self::$instance->local = new Local();
|
||||
self::$instance->tracking = new Tracking();
|
||||
}
|
||||
|
||||
/**
|
||||
* Check to see if we are running in "cloud" mode. That is, using the API and no local tools.
|
||||
*/
|
||||
public function cloud_init() {
|
||||
$this->debug_message( '<b>' . __METHOD__ . '()</b>' );
|
||||
if (
|
||||
$this->get_option( 'ewww_image_optimizer_cloud_key' ) &&
|
||||
$this->get_option( 'ewww_image_optimizer_jpg_level' ) > 10 &&
|
||||
$this->get_option( 'ewww_image_optimizer_png_level' ) > 10
|
||||
) {
|
||||
$this->cloud_mode = true;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Initializes settings for the local tools, and runs the checks for tools on select pages.
|
||||
*/
|
||||
public function exec_init() {
|
||||
$this->debug_message( '<b>' . __METHOD__ . '()</b>' );
|
||||
global $exactdn;
|
||||
// If cloud is fully enabled, we're going to skip all the checks related to the bundled tools.
|
||||
if ( $this->cloud_mode ) {
|
||||
$this->debug_message( 'cloud options enabled, shutting off binaries' );
|
||||
$this->local->skip_tools();
|
||||
return;
|
||||
}
|
||||
if (
|
||||
\defined( 'WPCOMSH_VERSION' ) ||
|
||||
! empty( $_ENV['PANTHEON_ENVIRONMENT'] ) ||
|
||||
\defined( 'WPE_PLUGIN_VERSION' ) ||
|
||||
\defined( 'FLYWHEEL_CONFIG_DIR' ) ||
|
||||
\defined( 'KINSTAMU_VERSION' ) ||
|
||||
\defined( 'WPNET_INIT_PLUGIN_VERSION' )
|
||||
) {
|
||||
if (
|
||||
! $this->get_option( 'ewww_image_optimizer_cloud_key' ) &&
|
||||
! \ewww_image_optimizer_easy_active() &&
|
||||
$this->get_option( 'ewww_image_optimizer_wizard_complete' )
|
||||
) {
|
||||
\add_action( 'network_admin_notices', array( $this, 'notice_hosting_requires_api' ) );
|
||||
\add_action( 'admin_notices', array( $this, 'notice_hosting_requires_api' ) );
|
||||
}
|
||||
$this->debug_message( 'WPE/wp.com/pantheon/flywheel site, disabling tools' );
|
||||
return;
|
||||
}
|
||||
// If they haven't completed the wizard yet, only display stuff on the bulk page, and short-circuit the rest of the checks elsewhere.
|
||||
if ( ! ewww_image_optimizer_get_option( 'ewww_image_optimizer_wizard_complete' ) ) {
|
||||
// Check if this is a supported OS (Linux, Mac OS, FreeBSD, or Windows).
|
||||
if (
|
||||
! $this->get_option( 'ewww_image_optimizer_cloud_key' ) &&
|
||||
! \ewww_image_optimizer_easy_active() &&
|
||||
$this->local->os_supported()
|
||||
) {
|
||||
\add_action( 'load-media_page_ewww-image-optimizer-bulk', array( $this, 'tool_init' ) );
|
||||
}
|
||||
return;
|
||||
}
|
||||
if ( ! $this->local->os_supported() ) {
|
||||
// Register the function to display a notice.
|
||||
\add_action( 'network_admin_notices', array( $this, 'notice_os' ) );
|
||||
\add_action( 'admin_notices', array( $this, 'notice_os' ) );
|
||||
// Turn off all the tools.
|
||||
$this->debug_message( 'unsupported OS, disabling tools: ' . PHP_OS );
|
||||
$this->local->skip_tools();
|
||||
return;
|
||||
}
|
||||
\add_action( 'load-upload.php', array( $this, 'tool_init' ), 9 );
|
||||
\add_action( 'load-media-new.php', array( $this, 'tool_init' ) );
|
||||
\add_action( 'load-media_page_ewww-image-optimizer-bulk', array( $this, 'tool_init' ) );
|
||||
\add_action( 'load-settings_page_ewww-image-optimizer-options', array( $this, 'tool_init' ) );
|
||||
\add_action( 'load-plugins.php', array( $this, 'tool_init' ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Check for binary installation and availability.
|
||||
*/
|
||||
public function tool_init() {
|
||||
$this->debug_message( '<b>' . __METHOD__ . '()</b>' );
|
||||
$this->tools_initialized = true;
|
||||
// Make sure the bundled tools are installed.
|
||||
if ( ! $this->get_option( 'ewww_image_optimizer_skip_bundle' ) ) {
|
||||
$this->local->install_tools();
|
||||
}
|
||||
if ( $this->cloud_mode ) {
|
||||
$this->debug_message( 'cloud options enabled, shutting off binaries' );
|
||||
$this->local->skip_tools();
|
||||
return;
|
||||
}
|
||||
// Check for optimization utilities and display a notice if something is missing.
|
||||
\add_action( 'network_admin_notices', array( $this, 'notice_utils' ) );
|
||||
\add_action( 'admin_notices', array( $this, 'notice_utils' ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Setup plugin for wp-admin.
|
||||
*/
|
||||
public function admin_init() {
|
||||
$this->hs_beacon = new HS_Beacon();
|
||||
/**
|
||||
* Require the file that does the bulk processing.
|
||||
*/
|
||||
require_once EWWW_IMAGE_OPTIMIZER_PLUGIN_PATH . 'bulk.php';
|
||||
/**
|
||||
* Require the files that contain functions for the images table and bulk processing images outside the library.
|
||||
*/
|
||||
require_once EWWW_IMAGE_OPTIMIZER_PLUGIN_PATH . 'aux-optimize.php';
|
||||
/**
|
||||
* Require the files that migrate WebP images from extension replacement to extension appending.
|
||||
*/
|
||||
require_once EWWW_IMAGE_OPTIMIZER_PLUGIN_PATH . 'mwebp.php';
|
||||
\ewww_image_optimizer_upgrade();
|
||||
|
||||
// Do settings validation for multi-site.
|
||||
\ewww_image_optimizer_save_network_settings();
|
||||
|
||||
$this->register_settings();
|
||||
$this->cloud_init();
|
||||
$this->exec_init();
|
||||
\ewww_image_optimizer_cron_setup( 'ewww_image_optimizer_auto' );
|
||||
|
||||
// Adds scripts to ajaxify the one-click actions on the media library, and register tooltips for conversion links.
|
||||
\add_action( 'admin_enqueue_scripts', 'ewww_image_optimizer_media_scripts' );
|
||||
// Adds scripts for the EWWW IO settings page.
|
||||
\add_action( 'admin_enqueue_scripts', 'ewww_image_optimizer_settings_script' );
|
||||
// Queue the function that contains custom styling for our progressbars.
|
||||
\add_action( 'admin_enqueue_scripts', 'ewww_image_optimizer_progressbar_style' );
|
||||
|
||||
if ( false !== \strpos( \add_query_arg( '', '' ), 'site-new.php' ) ) {
|
||||
if ( \is_multisite() && \is_network_admin() && isset( $_GET['update'] ) && 'added' === $_GET['update'] && ! empty( $_GET['id'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification
|
||||
\add_action( 'network_admin_notices', 'ewww_image_optimizer_easyio_site_initialized' );
|
||||
\add_action( 'admin_notices', 'ewww_image_optimizer_easyio_site_initialized' );
|
||||
}
|
||||
}
|
||||
if ( \defined( 'EWWW_IMAGE_OPTIMIZER_CLOUD_KEY' ) && \get_option( 'ewww_image_optimizer_cloud_key_invalid' ) ) {
|
||||
\add_action( 'network_admin_notices', 'ewww_image_optimizer_notice_invalid_key' );
|
||||
\add_action( 'admin_notices', 'ewww_image_optimizer_notice_invalid_key' );
|
||||
}
|
||||
if ( $this->get_option( 'ewww_image_optimizer_webp_enabled' ) ) {
|
||||
\add_action( 'admin_notices', 'ewww_image_optimizer_notice_webp_bulk' );
|
||||
if ( \ewww_image_optimizer_cloud_based_media() ) {
|
||||
\ewww_image_optimizer_set_option( 'ewww_image_optimizer_webp_force', true );
|
||||
}
|
||||
}
|
||||
if ( $this->get_option( 'ewww_image_optimizer_auto' ) && ! \ewww_image_optimizer_background_mode_enabled() ) {
|
||||
\add_action( 'network_admin_notices', 'ewww_image_optimizer_notice_schedule_noasync' );
|
||||
\add_action( 'admin_notices', 'ewww_image_optimizer_notice_schedule_noasync' );
|
||||
}
|
||||
if ( $this->get_option( 'ewww_image_optimizer_webp_force' ) && $this->get_option( 'ewww_image_optimizer_force_gif2webp' ) && ! $this->get_option( 'ewww_image_optimizer_cloud_key' ) ) {
|
||||
$this->set_option( 'ewww_image_optimizer_force_gif2webp', false );
|
||||
}
|
||||
// Prevent ShortPixel AIO messiness.
|
||||
\remove_action( 'admin_notices', 'autoptimizeMain::notice_plug_imgopt' );
|
||||
if ( \class_exists( '\autoptimizeExtra' ) || \defined( 'AUTOPTIMIZE_PLUGIN_VERSION' ) ) {
|
||||
$ao_extra = \get_option( 'autoptimize_imgopt_settings' );
|
||||
if ( $this->get_option( 'ewww_image_optimizer_exactdn' ) && ! empty( $ao_extra['autoptimize_imgopt_checkbox_field_1'] ) ) {
|
||||
$this->debug_message( 'detected ExactDN + SP conflict' );
|
||||
$ao_extra['autoptimize_imgopt_checkbox_field_1'] = 0;
|
||||
\update_option( 'autoptimize_imgopt_settings', $ao_extra );
|
||||
\add_action( 'admin_notices', 'ewww_image_optimizer_notice_exactdn_sp_conflict' );
|
||||
}
|
||||
}
|
||||
if (
|
||||
! $this->get_option( 'ewww_image_optimizer_ludicrous_mode' ) &&
|
||||
! $this->get_option( 'ewww_image_optimizer_cloud_key' ) &&
|
||||
\ewww_image_optimizer_easy_active()
|
||||
) {
|
||||
// Suppress the custom column in the media library if local mode is disabled and easy mode is active.
|
||||
\remove_filter( 'manage_media_columns', 'ewww_image_optimizer_columns' );
|
||||
} else {
|
||||
\add_action( 'admin_notices', 'ewww_image_optimizer_notice_media_listmode' );
|
||||
}
|
||||
if ( \ewww_image_optimizer_easy_active() ) {
|
||||
$this->set_option( 'ewww_image_optimizer_webp', false );
|
||||
$this->set_option( 'ewww_image_optimizer_webp_force', false );
|
||||
}
|
||||
|
||||
// Alert user if multiple re-optimizations detected.
|
||||
if ( false && ! \defined( 'EWWWIO_DISABLE_REOPT_NOTICE' ) ) {
|
||||
\add_action( 'network_admin_notices', 'ewww_image_optimizer_notice_reoptimization' );
|
||||
\add_action( 'admin_notices', 'ewww_image_optimizer_notice_reoptimization' );
|
||||
}
|
||||
// Let the admin know a db upgrade is needed.
|
||||
if ( \is_super_admin() && \get_transient( 'ewww_image_optimizer_620_upgrade_needed' ) ) {
|
||||
\add_action( 'admin_notices', 'ewww_image_optimizer_620_upgrade_needed' );
|
||||
}
|
||||
if (
|
||||
\is_super_admin() &&
|
||||
$this->get_option( 'ewww_image_optimizer_review_time' ) &&
|
||||
$this->get_option( 'ewww_image_optimizer_review_time' ) < \time() &&
|
||||
! $this->get_option( 'ewww_image_optimizer_dismiss_review_notice' )
|
||||
) {
|
||||
\add_action( 'admin_notices', 'ewww_image_optimizer_notice_review' );
|
||||
\add_action( 'admin_footer', 'ewww_image_optimizer_notice_review_script' );
|
||||
}
|
||||
if ( ! empty( $_GET['page'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification
|
||||
if ( 'regenerate-thumbnails' === $_GET['page'] // phpcs:ignore WordPress.Security.NonceVerification
|
||||
|| 'force-regenerate-thumbnails' === $_GET['page'] // phpcs:ignore WordPress.Security.NonceVerification
|
||||
|| 'ajax-thumbnail-rebuild' === $_GET['page'] // phpcs:ignore WordPress.Security.NonceVerification
|
||||
|| 'regenerate_thumbnails_advanced' === $_GET['page'] // phpcs:ignore WordPress.Security.NonceVerification
|
||||
|| 'rta_generate_thumbnails' === $_GET['page'] // phpcs:ignore WordPress.Security.NonceVerification
|
||||
) {
|
||||
// Add a notice for thumb regeneration.
|
||||
\add_action( 'admin_notices', 'ewww_image_optimizer_thumbnail_regen_notice' );
|
||||
}
|
||||
}
|
||||
if ( ! empty( $_GET['ewww_pngout'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification
|
||||
\add_action( 'admin_notices', 'ewww_image_optimizer_pngout_installed' );
|
||||
\add_action( 'network_admin_notices', 'ewww_image_optimizer_pngout_installed' );
|
||||
}
|
||||
if ( ! empty( $_GET['ewww_svgcleaner'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification
|
||||
\add_action( 'admin_notices', 'ewww_image_optimizer_svgcleaner_installed' );
|
||||
\add_action( 'network_admin_notices', 'ewww_image_optimizer_svgcleaner_installed' );
|
||||
}
|
||||
if ( ! \defined( 'EIO_PHPUNIT' ) && ( ! \defined( 'WP_CLI' ) || ! WP_CLI ) ) {
|
||||
\ewww_image_optimizer_privacy_policy_content();
|
||||
\ewww_image_optimizer_ajax_compat_check();
|
||||
}
|
||||
if ( \class_exists( '\WooCommerce' ) && $this->get_option( 'ewww_image_optimizer_wc_regen' ) ) {
|
||||
\add_action( 'admin_notices', 'ewww_image_optimizer_notice_wc_regen' );
|
||||
\add_action( 'admin_footer', 'ewww_image_optimizer_wc_regen_script' );
|
||||
}
|
||||
if ( \class_exists( '\Meow_WPLR_Sync_Core' ) && $this->get_option( 'ewww_image_optimizer_lr_sync' ) ) {
|
||||
\add_action( 'admin_notices', 'ewww_image_optimizer_notice_lr_sync' );
|
||||
\add_action( 'admin_footer', 'ewww_image_optimizer_lr_sync_script' );
|
||||
}
|
||||
// Increase the version when the next bump is coming.
|
||||
if ( \defined( 'PHP_VERSION_ID' ) && PHP_VERSION_ID < 70200 ) {
|
||||
\add_action( 'network_admin_notices', 'ewww_image_optimizer_php72_warning' );
|
||||
\add_action( 'admin_notices', 'ewww_image_optimizer_php72_warning' );
|
||||
}
|
||||
if ( \get_option( 'ewww_image_optimizer_debug' ) ) {
|
||||
\add_action( 'admin_notices', 'ewww_image_optimizer_debug_enabled_notice' );
|
||||
} elseif ( \get_site_option( 'ewww_image_optimizer_debug' ) && \is_network_admin() ) {
|
||||
\add_action( 'network_admin_notices', 'ewww_image_optimizer_debug_enabled_notice' );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Register all our options and santiation functions.
|
||||
*/
|
||||
public function register_settings() {
|
||||
$this->debug_message( '<b>' . __METHOD__ . '()</b>' );
|
||||
// Register all the common EWWW IO settings and their sanitation functions.
|
||||
register_setting( 'ewww_image_optimizer_options', 'ewww_image_optimizer_debug', 'boolval' );
|
||||
register_setting( 'ewww_image_optimizer_options', 'ewww_image_optimizer_metadata_remove', 'boolval' );
|
||||
register_setting( 'ewww_image_optimizer_options', 'ewww_image_optimizer_jpg_level', 'intval' );
|
||||
register_setting( 'ewww_image_optimizer_options', 'ewww_image_optimizer_png_level', 'intval' );
|
||||
register_setting( 'ewww_image_optimizer_options', 'ewww_image_optimizer_gif_level', 'intval' );
|
||||
register_setting( 'ewww_image_optimizer_options', 'ewww_image_optimizer_pdf_level', 'intval' );
|
||||
register_setting( 'ewww_image_optimizer_options', 'ewww_image_optimizer_svg_level', 'intval' );
|
||||
register_setting( 'ewww_image_optimizer_options', 'ewww_image_optimizer_backup_files', 'sanitize_text_field' );
|
||||
register_setting( 'ewww_image_optimizer_options', 'ewww_image_optimizer_enable_cloudinary', 'boolval' );
|
||||
register_setting( 'ewww_image_optimizer_options', 'ewww_image_optimizer_sharpen', 'boolval' );
|
||||
register_setting( 'ewww_image_optimizer_options', 'ewww_image_optimizer_jpg_quality', 'ewww_image_optimizer_jpg_quality' );
|
||||
register_setting( 'ewww_image_optimizer_options', 'ewww_image_optimizer_webp_quality', 'ewww_image_optimizer_webp_quality' );
|
||||
register_setting( 'ewww_image_optimizer_options', 'ewww_image_optimizer_avif_quality', 'ewww_image_optimizer_avif_quality' );
|
||||
register_setting( 'ewww_image_optimizer_options', 'ewww_image_optimizer_auto', 'boolval' );
|
||||
register_setting( 'ewww_image_optimizer_options', 'ewww_image_optimizer_include_media_paths', 'boolval' );
|
||||
register_setting( 'ewww_image_optimizer_options', 'ewww_image_optimizer_include_originals', 'boolval' );
|
||||
register_setting( 'ewww_image_optimizer_options', 'ewww_image_optimizer_aux_paths', 'ewww_image_optimizer_aux_paths_sanitize' );
|
||||
register_setting( 'ewww_image_optimizer_options', 'ewww_image_optimizer_exclude_paths', array( $this, 'exclude_paths_sanitize' ) );
|
||||
register_setting( 'ewww_image_optimizer_options', 'ewww_image_optimizer_allow_tracking', array( $this->tracking, 'check_for_settings_optin' ) );
|
||||
register_setting( 'ewww_image_optimizer_options', 'ewww_image_optimizer_enable_help', 'boolval' );
|
||||
register_setting( 'ewww_image_optimizer_options', 'exactdn_all_the_things', 'boolval' );
|
||||
register_setting( 'ewww_image_optimizer_options', 'exactdn_lossy', 'boolval' );
|
||||
register_setting( 'ewww_image_optimizer_options', 'exactdn_exclude', array( $this, 'exclude_paths_sanitize' ) );
|
||||
register_setting( 'ewww_image_optimizer_options', 'ewww_image_optimizer_add_missing_dims', 'boolval' );
|
||||
register_setting( 'ewww_image_optimizer_options', 'ewww_image_optimizer_lazy_load', 'boolval' );
|
||||
register_setting( 'ewww_image_optimizer_options', 'ewww_image_optimizer_ll_autoscale', 'boolval' );
|
||||
register_setting( 'ewww_image_optimizer_options', 'ewww_image_optimizer_use_lqip', 'boolval' );
|
||||
// Using sanitize_text_field instead of textarea on purpose.
|
||||
register_setting( 'ewww_image_optimizer_options', 'ewww_image_optimizer_ll_all_things', 'sanitize_text_field' );
|
||||
register_setting( 'ewww_image_optimizer_options', 'ewww_image_optimizer_ll_exclude', array( $this, 'exclude_paths_sanitize' ) );
|
||||
register_setting( 'ewww_image_optimizer_options', 'ewww_image_optimizer_resize_detection', 'boolval' );
|
||||
register_setting( 'ewww_image_optimizer_options', 'ewww_image_optimizer_maxmediawidth', 'intval' );
|
||||
register_setting( 'ewww_image_optimizer_options', 'ewww_image_optimizer_maxmediaheight', 'intval' );
|
||||
register_setting( 'ewww_image_optimizer_options', 'ewww_image_optimizer_resize_existing', 'boolval' );
|
||||
register_setting( 'ewww_image_optimizer_options', 'ewww_image_optimizer_resize_other_existing', 'boolval' );
|
||||
register_setting( 'ewww_image_optimizer_options', 'ewww_image_optimizer_disable_resizes', 'ewww_image_optimizer_disable_resizes_sanitize' );
|
||||
register_setting( 'ewww_image_optimizer_options', 'ewww_image_optimizer_disable_resizes_opt', 'ewww_image_optimizer_disable_resizes_sanitize' );
|
||||
register_setting( 'ewww_image_optimizer_options', 'ewww_image_optimizer_disable_convert_links', 'boolval' );
|
||||
register_setting( 'ewww_image_optimizer_options', 'ewww_image_optimizer_delete_originals', 'boolval' );
|
||||
register_setting( 'ewww_image_optimizer_options', 'ewww_image_optimizer_jpg_to_png', 'boolval' );
|
||||
register_setting( 'ewww_image_optimizer_options', 'ewww_image_optimizer_png_to_jpg', 'boolval' );
|
||||
register_setting( 'ewww_image_optimizer_options', 'ewww_image_optimizer_gif_to_png', 'boolval' );
|
||||
register_setting( 'ewww_image_optimizer_options', 'ewww_image_optimizer_jpg_background', 'ewww_image_optimizer_jpg_background' );
|
||||
register_setting( 'ewww_image_optimizer_options', 'ewww_image_optimizer_webp', 'boolval' );
|
||||
register_setting( 'ewww_image_optimizer_options', 'ewww_image_optimizer_webp_force', 'boolval' );
|
||||
register_setting( 'ewww_image_optimizer_options', 'ewww_image_optimizer_webp_paths', 'ewww_image_optimizer_webp_paths_sanitize' );
|
||||
register_setting( 'ewww_image_optimizer_options', 'ewww_image_optimizer_webp_for_cdn', 'boolval' );
|
||||
register_setting( 'ewww_image_optimizer_options', 'ewww_image_optimizer_picture_webp', 'boolval' );
|
||||
register_setting( 'ewww_image_optimizer_options', 'ewww_image_optimizer_webp_rewrite_exclude', array( $this, 'exclude_paths_sanitize' ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Set some default option values.
|
||||
*/
|
||||
public function set_defaults() {
|
||||
$this->debug_message( '<b>' . __METHOD__ . '()</b>' );
|
||||
// Set defaults for all options that need to be autoloaded.
|
||||
\add_option( 'ewww_image_optimizer_background_optimization', false );
|
||||
\add_option( 'ewww_image_optimizer_noauto', false );
|
||||
\add_option( 'ewww_image_optimizer_disable_editor', false );
|
||||
\add_option( 'ewww_image_optimizer_debug', false );
|
||||
\add_option( 'ewww_image_optimizer_metadata_remove', true );
|
||||
\add_option( 'ewww_image_optimizer_jpg_level', '10' );
|
||||
\add_option( 'ewww_image_optimizer_png_level', '10' );
|
||||
\add_option( 'ewww_image_optimizer_gif_level', '10' );
|
||||
\add_option( 'ewww_image_optimizer_pdf_level', '0' );
|
||||
\add_option( 'ewww_image_optimizer_svg_level', '0' );
|
||||
\add_option( 'ewww_image_optimizer_jpg_quality', '' );
|
||||
\add_option( 'ewww_image_optimizer_webp_quality', '' );
|
||||
\add_option( 'ewww_image_optimizer_backup_files', '' );
|
||||
\add_option( 'ewww_image_optimizer_resize_existing', true );
|
||||
\add_option( 'ewww_image_optimizer_exactdn', false );
|
||||
\add_option( 'ewww_image_optimizer_exactdn_plan_id', 0 );
|
||||
\add_option( 'exactdn_all_the_things', true );
|
||||
\add_option( 'exactdn_lossy', true );
|
||||
\add_option( 'exactdn_exclude', '' );
|
||||
\add_option( 'exactdn_sub_folder', false );
|
||||
\add_option( 'exactdn_prevent_db_queries', true );
|
||||
\add_option( 'ewww_image_optimizer_lazy_load', false );
|
||||
\add_option( 'ewww_image_optimizer_use_siip', false );
|
||||
\add_option( 'ewww_image_optimizer_use_lqip', false );
|
||||
\add_option( 'ewww_image_optimizer_ll_exclude', '' );
|
||||
\add_option( 'ewww_image_optimizer_ll_all_things', '' );
|
||||
\add_option( 'ewww_image_optimizer_disable_pngout', true );
|
||||
\add_option( 'ewww_image_optimizer_disable_svgcleaner', true );
|
||||
\add_option( 'ewww_image_optimizer_optipng_level', 2 );
|
||||
\add_option( 'ewww_image_optimizer_pngout_level', 2 );
|
||||
\add_option( 'ewww_image_optimizer_webp_for_cdn', false );
|
||||
\add_option( 'ewww_image_optimizer_force_gif2webp', false );
|
||||
\add_option( 'ewww_image_optimizer_picture_webp', false );
|
||||
\add_option( 'ewww_image_optimizer_webp_rewrite_exclude', '' );
|
||||
|
||||
// Set network defaults.
|
||||
\add_site_option( 'ewww_image_optimizer_background_optimization', false );
|
||||
\add_site_option( 'ewww_image_optimizer_metadata_remove', true );
|
||||
\add_site_option( 'ewww_image_optimizer_jpg_level', '10' );
|
||||
\add_site_option( 'ewww_image_optimizer_png_level', '10' );
|
||||
\add_site_option( 'ewww_image_optimizer_gif_level', '10' );
|
||||
\add_site_option( 'ewww_image_optimizer_pdf_level', '0' );
|
||||
\add_site_option( 'ewww_image_optimizer_svg_level', '0' );
|
||||
\add_site_option( 'ewww_image_optimizer_jpg_quality', '' );
|
||||
\add_site_option( 'ewww_image_optimizer_webp_quality', '' );
|
||||
\add_site_option( 'ewww_image_optimizer_backup_files', '' );
|
||||
\add_site_option( 'ewww_image_optimizer_resize_existing', true );
|
||||
\add_site_option( 'ewww_image_optimizer_disable_pngout', true );
|
||||
\add_site_option( 'ewww_image_optimizer_disable_svgcleaner', true );
|
||||
\add_site_option( 'ewww_image_optimizer_optipng_level', 2 );
|
||||
\add_site_option( 'ewww_image_optimizer_pngout_level', 2 );
|
||||
\add_site_option( 'exactdn_all_the_things', true );
|
||||
\add_site_option( 'exactdn_lossy', true );
|
||||
\add_site_option( 'exactdn_sub_folder', false );
|
||||
\add_site_option( 'exactdn_prevent_db_queries', true );
|
||||
\add_site_option( 'ewww_image_optimizer_ll_autoscale', true );
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks for exec() and availability of local optimizers, then displays an error if needed.
|
||||
*
|
||||
* @param string $quiet Optional. Use 'quiet' to suppress output.
|
||||
*/
|
||||
public function notice_utils( $quiet = null ) {
|
||||
$this->debug_message( '<b>' . __METHOD__ . '()</b>' );
|
||||
// Check if exec is disabled.
|
||||
if ( ! $this->local->exec_check() ) {
|
||||
// Don't bother if we're in quiet mode, or they already dismissed the notice.
|
||||
if ( 'quiet' !== $quiet && ! $this->get_option( 'ewww_image_optimizer_dismiss_exec_notice' ) ) {
|
||||
\ob_start();
|
||||
// Display a warning if exec() is disabled, can't run local tools without it.
|
||||
if ( \ewww_image_optimizer_easy_active() ) {
|
||||
echo "<div id='ewww-image-optimizer-warning-exec' class='notice notice-info is-dismissible'><p>";
|
||||
\esc_html_e( 'Free compression of local images cannot be done on your site without an API key. Since Easy IO is already automatically optimizing your site, you may dismiss this notice unless you need to save storage space.', 'ewww-image-optimizer' );
|
||||
} else {
|
||||
echo "<div id='ewww-image-optimizer-warning-exec' class='notice notice-warning is-dismissible'><p>";
|
||||
\printf(
|
||||
/* translators: %s: link to 'start your premium trial' */
|
||||
\esc_html__( 'Your web server does not meet the requirements for free server-based compression with EWWW Image Optimizer. You may %s for 5x more compression, PNG/GIF/PDF compression, and more. Otherwise, continue with free cloud-based JPG compression.', 'ewww-image-optimizer' ),
|
||||
"<a href='https://ewww.io/plans/'>" . \esc_html__( 'start your premium trial', 'ewww-image-optimizer' ) . '</a>'
|
||||
);
|
||||
}
|
||||
\ewwwio_help_link( 'https://docs.ewww.io/article/29-what-is-exec-and-why-do-i-need-it', '592dd12d0428634b4a338c39' );
|
||||
echo '</p></div>';
|
||||
echo "<script>\n" .
|
||||
"jQuery(document).on('click', '#ewww-image-optimizer-warning-exec .notice-dismiss', function() {\n" .
|
||||
"\tvar ewww_dismiss_exec_data = {\n" .
|
||||
"\t\taction: 'ewww_dismiss_exec_notice',\n" .
|
||||
"\t};\n" .
|
||||
"\tjQuery.post(ajaxurl, ewww_dismiss_exec_data, function(response) {\n" .
|
||||
"\t\tif (response) {\n" .
|
||||
"\t\t\tconsole.log(response);\n" .
|
||||
"\t\t}\n" .
|
||||
"\t});\n" .
|
||||
"});\n" .
|
||||
"</script>\n";
|
||||
if (
|
||||
\ewww_image_optimizer_easy_active() &&
|
||||
! $this->get_option( 'ewww_image_optimizer_ludicrous_mode' )
|
||||
) {
|
||||
\ob_end_clean();
|
||||
} else {
|
||||
\ob_end_flush();
|
||||
}
|
||||
$this->debug_message( 'exec disabled, alerting user' );
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
$tools = ewwwio()->local->check_all_tools();
|
||||
$missing = array();
|
||||
// Go through each of the required tools.
|
||||
foreach ( $tools as $tool => $info ) {
|
||||
// If a tool is needed, but wasn't found, add it to the $missing so we can display that info to the user.
|
||||
if ( $info['enabled'] && empty( $info['path'] ) ) {
|
||||
if ( 'cwebp' === $tool && ( $this->imagick_supports_webp() || $this->gd_supports_webp() ) ) {
|
||||
continue;
|
||||
}
|
||||
$missing[] = $tool;
|
||||
}
|
||||
}
|
||||
// If there is a message, display the warning.
|
||||
if ( ! empty( $missing ) && 'quiet' !== $quiet ) {
|
||||
if ( ! \is_dir( $this->content_dir ) ) {
|
||||
$this->tool_folder_notice();
|
||||
} elseif ( ! \is_writable( $this->content_dir ) || ! is_readable( $this->content_dir ) ) {
|
||||
$this->tool_folder_permissions_notice();
|
||||
} elseif ( ! \is_executable( $this->content_dir ) && PHP_OS !== 'WINNT' ) {
|
||||
$this->tool_folder_permissions_notice();
|
||||
}
|
||||
if ( \in_array( 'pngout', $missing, true ) ) {
|
||||
// Display a separate notice for pngout with an install option, and then suppress it from the latter notice.
|
||||
$key = \array_search( 'pngout', $missing, true );
|
||||
if ( false !== $key ) {
|
||||
unset( $missing[ $key ] );
|
||||
}
|
||||
$pngout_install_url = \admin_url( 'admin.php?action=ewww_image_optimizer_install_pngout' );
|
||||
echo "<div id='ewww-image-optimizer-warning-opt-missing' class='notice notice-warning'><p>" .
|
||||
\sprintf(
|
||||
/* translators: 1: automatically (link) 2: manually (link) */
|
||||
\esc_html__( 'EWWW Image Optimizer is missing pngout. Install %1$s or %2$s.', 'ewww-image-optimizer' ),
|
||||
"<a href='" . \esc_url( $pngout_install_url ) . "'>" . \esc_html__( 'automatically', 'ewww-image-optimizer' ) . '</a>',
|
||||
'<a href="https://docs.ewww.io/article/13-installing-pngout" data-beacon-article="5854531bc697912ffd6c1afa">' . \esc_html__( 'manually', 'ewww-image-optimizer' ) . '</a>'
|
||||
) .
|
||||
'</p></div>';
|
||||
}
|
||||
if ( \in_array( 'svgcleaner', $missing, true ) ) {
|
||||
$key = array_search( 'svgcleaner', $missing, true );
|
||||
if ( false !== $key ) {
|
||||
unset( $missing[ $key ] );
|
||||
}
|
||||
$svgcleaner_install_url = \admin_url( 'admin.php?action=ewww_image_optimizer_install_svgcleaner' );
|
||||
echo "<div id='ewww-image-optimizer-warning-opt-missing' class='notice notice-warning'><p>" .
|
||||
\sprintf(
|
||||
/* translators: 1: automatically (link) 2: manually (link) */
|
||||
\esc_html__( 'EWWW Image Optimizer is missing svgleaner. Install %1$s or %2$s.', 'ewww-image-optimizer' ),
|
||||
"<a href='" . \esc_url( $svgcleaner_install_url ) . "'>" . \esc_html__( 'automatically', 'ewww-image-optimizer' ) . '</a>',
|
||||
'<a href="https://docs.ewww.io/article/95-installing-svgcleaner" data-beacon-article="5f7921c9cff47e001a58adbc">' . \esc_html__( 'manually', 'ewww-image-optimizer' ) . '</a>'
|
||||
) .
|
||||
'</p></div>';
|
||||
}
|
||||
if ( ! empty( $missing ) && ! $this->get_option( 'ewww_image_optimizer_dismiss_exec_notice' ) ) {
|
||||
$dismissible = false;
|
||||
// If all the tools are missing, make it dismissible.
|
||||
if (
|
||||
\in_array( 'jpegtran', $missing, true ) &&
|
||||
\in_array( 'optipng', $missing, true ) &&
|
||||
\in_array( 'gifsicle', $missing, true )
|
||||
) {
|
||||
$dismissible = true;
|
||||
}
|
||||
// If they are missing tools, but not jpegtran, make it dismissible, since they can effectively do locally what we would offer in free-cloud mode.
|
||||
if ( ! \in_array( 'jpegtran', $missing, true ) ) {
|
||||
$dismissible = true;
|
||||
}
|
||||
// Expand the missing utilities list for use in the error message.
|
||||
$msg = \implode( ', ', $missing );
|
||||
echo "<div id='ewww-image-optimizer-warning-opt-missing' class='notice notice-warning" . ( $dismissible ? ' is-dismissible' : '' ) . "'><p>" .
|
||||
\sprintf(
|
||||
/* translators: 1: comma-separated list of missing tools 2: Installation Instructions (link) */
|
||||
\esc_html__( 'EWWW Image Optimizer uses open-source tools to enable free mode, but your server is missing these: %1$s. Please install via the %2$s to continue in free mode.', 'ewww-image-optimizer' ),
|
||||
\esc_html( $msg ),
|
||||
"<a href='https://docs.ewww.io/article/6-the-plugin-says-i-m-missing-something' data-beacon-article='585371e3c697912ffd6c0ba1' target='_blank'>" . \esc_html__( 'Installation Instructions', 'ewww-image-optimizer' ) . '</a>'
|
||||
) .
|
||||
'</p></div>';
|
||||
?>
|
||||
<script>
|
||||
jQuery(document).on('click', '#ewww-image-optimizer-warning-opt-missing .notice-dismiss', function() {
|
||||
var ewww_dismiss_exec_data = {
|
||||
action: 'ewww_dismiss_exec_notice',
|
||||
};
|
||||
jQuery.post(ajaxurl, ewww_dismiss_exec_data, function(response) {
|
||||
if (response) {
|
||||
console.log(response);
|
||||
}
|
||||
});
|
||||
});
|
||||
</script>
|
||||
<?php
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Let the user know the plugin requires API/ExactDN to operate at their webhost.
|
||||
*/
|
||||
public function notice_hosting_requires_api() {
|
||||
if ( ! \function_exists( '\is_plugin_active_for_network' ) && \is_multisite() ) {
|
||||
// Need to include the plugin library for the is_plugin_active function.
|
||||
require_once ABSPATH . 'wp-admin/includes/plugin.php';
|
||||
}
|
||||
if ( \is_multisite() && \is_plugin_active_for_network( EWWW_IMAGE_OPTIMIZER_PLUGIN_FILE_REL ) ) {
|
||||
$settings_url = \network_admin_url( 'settings.php?page=ewww-image-optimizer-options' );
|
||||
} else {
|
||||
$settings_url = \admin_url( 'options-general.php?page=ewww-image-optimizer-options' );
|
||||
}
|
||||
if ( \defined( 'WPCOMSH_VERSION' ) ) {
|
||||
$webhost = 'WordPress.com';
|
||||
} elseif ( ! empty( $_ENV['PANTHEON_ENVIRONMENT'] ) ) {
|
||||
$webhost = 'Pantheon';
|
||||
} elseif ( \defined( 'WPE_PLUGIN_VERSION' ) ) {
|
||||
$webhost = 'WP Engine';
|
||||
} elseif ( \defined( 'FLYWHEEL_CONFIG_DIR' ) ) {
|
||||
$webhost = 'Flywheel';
|
||||
} elseif ( \defined( 'KINSTAMU_VERSION' ) ) {
|
||||
$webhost = 'Kinsta';
|
||||
} elseif ( \defined( 'WPNET_INIT_PLUGIN_VERSION' ) ) {
|
||||
$webhost = 'WP NET';
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
if ( $this->get_option( 'ewww_image_optimizer_dismiss_exec_notice' ) ) {
|
||||
return;
|
||||
}
|
||||
echo "<div id='ewww-image-optimizer-warning-exec' class='notice notice-warning is-dismissible'><p>" .
|
||||
/* translators: %s: Name of a web host, like WordPress.com or Pantheon. */
|
||||
\sprintf( \esc_html__( 'EWWW Image Optimizer cannot use server-based optimization on %s sites. Activate our premium service for 5x more compression, PNG/GIF/PDF compression, and image backups.', 'ewww-image-optimizer' ), \esc_html( $webhost ) ) .
|
||||
'<br><strong>' .
|
||||
/* translators: %s: link to 'start your free trial' */
|
||||
\sprintf( \esc_html__( 'Dismiss this notice to continue with free cloud-based JPG compression or %s.', 'ewww-image-optimizer' ), "<a href='https://ewww.io/plans/'>" . \esc_html__( 'start your premium trial', 'ewww-image-optimizer' ) . '</a>' );
|
||||
\ewwwio_help_link( 'https://docs.ewww.io/article/29-what-is-exec-and-why-do-i-need-it', '592dd12d0428634b4a338c39' );
|
||||
echo '</strong></p></div>';
|
||||
?>
|
||||
<script>
|
||||
jQuery(document).on('click', '#ewww-image-optimizer-warning-exec .notice-dismiss', function() {
|
||||
var ewww_dismiss_exec_data = {
|
||||
action: 'ewww_dismiss_exec_notice',
|
||||
};
|
||||
jQuery.post(ajaxurl, ewww_dismiss_exec_data, function(response) {
|
||||
if (response) {
|
||||
console.log(response);
|
||||
}
|
||||
});
|
||||
});
|
||||
</script>
|
||||
<?php
|
||||
}
|
||||
|
||||
/**
|
||||
* Tells the user they are on an unsupported operating system.
|
||||
*/
|
||||
public function notice_os() {
|
||||
$this->debug_message( '<b>' . __METHOD__ . '()</b>' );
|
||||
if ( $this->get_option( 'ewww_image_optimizer_dismiss_exec_notice' ) ) {
|
||||
return;
|
||||
}
|
||||
// If they are already using our services, or haven't gone through the wizard, exit now!
|
||||
if (
|
||||
$this->get_option( 'ewww_image_optimizer_cloud_key' ) ||
|
||||
\ewww_image_optimizer_easy_active() ||
|
||||
! $this->get_option( 'ewww_image_optimizer_wizard_complete' )
|
||||
) {
|
||||
return;
|
||||
}
|
||||
echo "<div id='ewww-image-optimizer-warning-exec' class='notice notice-warning is-dismissible'><p>" .
|
||||
\esc_html__( 'Free server-based compression with EWWW Image Optimizer is only supported on Linux, FreeBSD, Mac OSX, and Windows.', 'ewww-image-optimizer' ) .
|
||||
'<br><strong>' .
|
||||
/* translators: %s: link to 'start your free trial' */
|
||||
\sprintf( \esc_html__( 'Dismiss this notice to continue with free cloud-based JPG compression or %s.', 'ewww-image-optimizer' ), "<a href='https://ewww.io/plans/'>" . \esc_html__( 'start your premium trial', 'ewww-image-optimizer' ) . '</a>' );
|
||||
\ewwwio_help_link( 'https://docs.ewww.io/article/29-what-is-exec-and-why-do-i-need-it', '592dd12d0428634b4a338c39' );
|
||||
echo '</strong></p></div>';
|
||||
?>
|
||||
<script>
|
||||
jQuery(document).on('click', '#ewww-image-optimizer-warning-exec .notice-dismiss', function() {
|
||||
var ewww_dismiss_exec_data = {
|
||||
action: 'ewww_dismiss_exec_notice',
|
||||
};
|
||||
jQuery.post(ajaxurl, ewww_dismiss_exec_data, function(response) {
|
||||
if (response) {
|
||||
console.log(response);
|
||||
}
|
||||
});
|
||||
});
|
||||
</script>
|
||||
<?php
|
||||
}
|
||||
|
||||
/**
|
||||
* Alert the user when the tool folder could not be created.
|
||||
*/
|
||||
public function tool_folder_notice() {
|
||||
echo "<div id='ewww-image-optimizer-warning-tool-folder-create' class='notice notice-error'><p><strong>" . \esc_html__( 'EWWW Image Optimizer could not create the tool folder', 'ewww-image-optimizer' ) . ': ' . \esc_html( $this->content_dir ) . '.</strong> ' . \esc_html__( 'Please adjust permissions or create the folder', 'ewww-image-optimizer' ) . '.</p></div>';
|
||||
}
|
||||
|
||||
/**
|
||||
* Alert the user when permissions on the tool folder are insufficient.
|
||||
*/
|
||||
public function tool_folder_permissions_notice() {
|
||||
echo "<div id='ewww-image-optimizer-warning-tool-folder-permissions' class='notice notice-error'><p><strong>" .
|
||||
/* translators: %s: Folder location where executables should be installed */
|
||||
\sprintf( \esc_html__( 'EWWW Image Optimizer could not install tools in %s', 'ewww-image-optimizer' ), \esc_html( $this->content_dir ) ) . '.</strong> ' .
|
||||
\esc_html__( 'Please adjust permissions on the folder. If you have installed the tools elsewhere, use the override to skip the bundled tools.', 'ewww-image-optimizer' ) . ' ' .
|
||||
/* translators: s: Installation Instructions (link) */
|
||||
\sprintf( \esc_html__( 'For more details, see the %s.', 'ewww-image-optimizer' ), "<a href='https://docs.ewww.io/article/6-the-plugin-says-i-m-missing-something'>" . \esc_html__( 'Installation Instructions', 'ewww-image-optimizer' ) . '</a>' ) . '</p></div>';
|
||||
}
|
||||
|
||||
/**
|
||||
* Disables local compression when exec notice is dismissed.
|
||||
*/
|
||||
public function dismiss_exec_notice() {
|
||||
$this->ob_clean();
|
||||
$this->debug_message( '<b>' . __METHOD__ . '()</b>' );
|
||||
// Verify that the user is properly authorized.
|
||||
if ( ! \current_user_can( \apply_filters( 'ewww_image_optimizer_admin_permissions', '' ) ) ) {
|
||||
\wp_die( \esc_html__( 'Access denied.', 'ewww-image-optimizer' ) );
|
||||
}
|
||||
$this->enable_free_exec();
|
||||
die();
|
||||
}
|
||||
|
||||
/**
|
||||
* Sync the cloud_mode property with the cloud_key option.
|
||||
*
|
||||
* @param mixed $old_setting The old value.
|
||||
* @param mixed $new_setting The new value.
|
||||
*/
|
||||
public function updated_cloud_key( $old_setting, $new_setting ) {
|
||||
$this->cloud_mode = ! empty( $new_setting );
|
||||
}
|
||||
|
||||
/**
|
||||
* Put site in "free exec" mode with JPG-only API compression, and suppress the exec() notice.
|
||||
*/
|
||||
public function enable_free_exec() {
|
||||
$this->debug_message( '<b>' . __METHOD__ . '()</b>' );
|
||||
\update_option( 'ewww_image_optimizer_jpg_level', 10 );
|
||||
\update_option( 'ewww_image_optimizer_png_level', 0 );
|
||||
\update_option( 'ewww_image_optimizer_gif_level', 0 );
|
||||
\update_option( 'ewww_image_optimizer_pdf_level', 0 );
|
||||
\update_option( 'ewww_image_optimizer_svg_level', 0 );
|
||||
\update_option( 'ewww_image_optimizer_dismiss_exec_notice', 1 );
|
||||
\update_site_option( 'ewww_image_optimizer_dismiss_exec_notice', 1 );
|
||||
}
|
||||
}
|
@ -0,0 +1,396 @@
|
||||
<?php
|
||||
/**
|
||||
* Functions for reporting plugin usage to EWWW IO for users that have opted in.
|
||||
*
|
||||
* @package EWWW_Image_Optimizer
|
||||
* @copyright Copyright (c) 2017, Pippin Williamson and Shane Bishop
|
||||
* @license http://opensource.org/licenses/gpl-2.0.php GNU Public License
|
||||
* @since 3.3.2
|
||||
*/
|
||||
|
||||
namespace EWWW;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Usage tracking so we can make informed decisions.
|
||||
*
|
||||
* @since 3.3.2
|
||||
*/
|
||||
class Tracking {
|
||||
|
||||
/**
|
||||
* The data to send to the API
|
||||
*
|
||||
* @access private
|
||||
* @var array $data
|
||||
*/
|
||||
private $data;
|
||||
|
||||
/**
|
||||
* Get things going
|
||||
*/
|
||||
public function __construct() {
|
||||
\add_action( 'admin_init', array( $this, 'schedule_send' ) );
|
||||
\add_action( 'ewww_image_optimizer_site_report', array( $this, 'send_checkin' ) );
|
||||
\add_action( 'admin_action_ewww_opt_into_tracking', array( $this, 'check_for_optin' ) );
|
||||
\add_action( 'admin_action_ewww_opt_out_of_tracking', array( $this, 'check_for_optout' ) );
|
||||
\add_action( 'admin_notices', array( $this, 'admin_notice' ) );
|
||||
\add_action( 'network_admin_notices', array( $this, 'admin_notice' ) );
|
||||
\register_deactivation_hook( EWWW_IMAGE_OPTIMIZER_PLUGIN_FILE, array( $this, 'unschedule_send' ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the user has opted into tracking
|
||||
*
|
||||
* @access private
|
||||
* @return bool
|
||||
*/
|
||||
private function tracking_allowed() {
|
||||
return (bool) \ewww_image_optimizer_get_option( 'ewww_image_optimizer_allow_tracking' );
|
||||
}
|
||||
|
||||
/**
|
||||
* Setup the data that is going to be tracked
|
||||
*
|
||||
* @access private
|
||||
* @return void
|
||||
*/
|
||||
private function setup_data() {
|
||||
\ewwwio_debug_message( '<b>' . __METHOD__ . '()</b>' );
|
||||
$data = array();
|
||||
|
||||
// Retrieve current theme info.
|
||||
$theme_data = \wp_get_theme();
|
||||
$theme = $theme_data->Name . ' ' . $theme_data->Version; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
|
||||
$data['site_id'] = \md5( \home_url() );
|
||||
if (
|
||||
\strlen( \ewww_image_optimizer_get_option( 'ewww_image_optimizer_tracking_site_id' ) ) === 32 &&
|
||||
\ctype_alnum( \ewww_image_optimizer_get_option( 'ewww_image_optimizer_tracking_site_id' ) )
|
||||
) {
|
||||
\ewwwio_debug_message( 'using pre-existing site_id' );
|
||||
$data['site_id'] = \ewww_image_optimizer_get_option( 'ewww_image_optimizer_tracking_site_id' );
|
||||
} else {
|
||||
\ewww_image_optimizer_set_option( 'ewww_image_optimizer_tracking_site_id', $data['site_id'] );
|
||||
}
|
||||
$data['ewwwio_version'] = EWWW_IMAGE_OPTIMIZER_VERSION;
|
||||
$data['wp_version'] = \get_bloginfo( 'version' );
|
||||
$data['php_version'] = PHP_VERSION_ID;
|
||||
$data['server'] = isset( $_SERVER['SERVER_SOFTWARE'] ) ? \sanitize_text_field( \wp_unslash( $_SERVER['SERVER_SOFTWARE'] ) ) : '';
|
||||
$data['multisite'] = \is_multisite();
|
||||
$data['theme'] = $theme;
|
||||
|
||||
// Retrieve current plugin information.
|
||||
if ( ! \function_exists( '\get_plugins' ) ) {
|
||||
require_once ABSPATH . '/wp-admin/includes/plugin.php';
|
||||
}
|
||||
|
||||
$plugins = \array_keys( \get_plugins() );
|
||||
$active_plugins = \get_option( 'active_plugins', array() );
|
||||
|
||||
foreach ( $plugins as $key => $plugin ) {
|
||||
if ( \in_array( $plugin, $active_plugins, true ) ) {
|
||||
// Remove active plugins from list so we can show active and inactive separately.
|
||||
unset( $plugins[ $key ] );
|
||||
}
|
||||
}
|
||||
|
||||
$data['active_plugins'] = $active_plugins;
|
||||
$data['inactive_plugins'] = $plugins;
|
||||
$data['locale'] = ( $data['wp_version'] >= 4.7 ) ? \get_user_locale() : \get_locale();
|
||||
if ( ! \function_exists( '\ewww_image_optimizer_aux_images_table_count_pending' ) ) {
|
||||
require_once EWWW_IMAGE_OPTIMIZER_PLUGIN_PATH . 'aux-optimize.php';
|
||||
}
|
||||
if (
|
||||
\ewww_image_optimizer_get_option( 'ewww_image_optimizer_cloud_key' ) ||
|
||||
! \ewwwio()->local->os_supported() ||
|
||||
! \ewwwio()->local->exec_check()
|
||||
) {
|
||||
$total_images = 0;
|
||||
$total_savings = 0;
|
||||
} else {
|
||||
$total_images = \ewww_image_optimizer_aux_images_table_count();
|
||||
$total_sizes = \ewww_image_optimizer_savings();
|
||||
$total_savings = $total_sizes[1] - $total_sizes[0];
|
||||
}
|
||||
|
||||
$data['images_optimized'] = $total_images;
|
||||
$data['bytes_saved'] = $total_savings;
|
||||
|
||||
$data['nextgen'] = \class_exists( '\EWWW_Nextgen' ) ? true : false;
|
||||
$data['nextcellent'] = \class_exists( '\EWWW_Nextcellent' ) ? true : false;
|
||||
$data['flagallery'] = \class_exists( '\EWWW_Flag' ) ? true : false;
|
||||
$data['memory_limit'] = \ewwwio_memory_limit();
|
||||
$data['time_limit'] = (int) \ini_get( 'max_execution_time' );
|
||||
$data['operating_system'] = \ewwwio()->function_exists( '\php_uname' ) ? \php_uname( 's' ) : '';
|
||||
|
||||
$data['image_library'] = '';
|
||||
if ( \ewwwio()->gmagick_support() ) {
|
||||
$data['image_library'] = 'gmagick';
|
||||
} elseif ( \ewwwio()->imagick_support() ) {
|
||||
$data['image_library'] = 'imagick';
|
||||
} elseif ( \ewwwio()->gd_support() ) {
|
||||
$data['image_library'] = 'gd';
|
||||
}
|
||||
|
||||
$data['cloud_api'] = \ewww_image_optimizer_get_option( 'ewww_image_optimizer_cloud_key' ) ? true : false;
|
||||
$data['keep_metadata'] = \ewww_image_optimizer_get_option( 'ewww_image_optimizer_metadata_remove' ) ? false : true;
|
||||
$data['jpg_level'] = (int) \ewww_image_optimizer_get_option( 'ewww_image_optimizer_jpg_level' );
|
||||
$data['png_level'] = (int) \ewww_image_optimizer_get_option( 'ewww_image_optimizer_png_level' );
|
||||
$data['gif_level'] = (int) \ewww_image_optimizer_get_option( 'ewww_image_optimizer_gif_level' );
|
||||
$data['pdf_level'] = (int) \ewww_image_optimizer_get_option( 'ewww_image_optimizer_pdf_level' );
|
||||
$data['bulk_delay'] = (int) \ewww_image_optimizer_get_option( 'ewww_image_optimizer_delay' );
|
||||
$data['backups'] = (bool) \ewww_image_optimizer_get_option( 'ewww_image_optimizer_backup_files' );
|
||||
|
||||
if ( \ewww_image_optimizer_get_option( 'ewww_image_optimizer_exactdn' ) && \class_exists( __NAMESPACE__ . '\ExactDN' ) ) {
|
||||
global $exactdn;
|
||||
if ( $exactdn->get_exactdn_domain() ) {
|
||||
$data['exactdn_lossy'] = (int) \ewww_image_optimizer_get_option( 'exactdn_lossy' );
|
||||
$data['exactdn_all_the_things'] = (bool) \ewww_image_optimizer_get_option( 'exactdn_all_the_things' );
|
||||
$data['exactdn_resize_existing'] = (bool) \ewww_image_optimizer_get_option( 'exactdn_resize_existing' );
|
||||
$data['exactdn_prevent_db_queries'] = (bool) \ewww_image_optimizer_get_option( 'exactdn_prevent_db_queries' );
|
||||
$data['exactdn_prevent_srcset_fill'] = (bool) \ewww_image_optimizer_get_option( 'exactdn_prevent_srcset_fill' );
|
||||
}
|
||||
}
|
||||
|
||||
$data['lazyload'] = (bool) \ewww_image_optimizer_get_option( 'ewww_image_optimizer_lazy_load' );
|
||||
$data['optipng_level'] = \ewww_image_optimizer_get_option( 'ewww_image_optimizer_cloud_key' ) ? 0 : (int) \ewww_image_optimizer_get_option( 'ewww_image_optimizer_optipng_level' );
|
||||
$data['disable_pngout'] = (bool) \ewww_image_optimizer_get_option( 'ewww_image_optimizer_disable_pngout' );
|
||||
$data['pngout_level'] = \ewww_image_optimizer_get_option( 'ewww_image_optimizer_cloud_key' ) ? 9 : (int) \ewww_image_optimizer_get_option( 'ewww_image_optimizer_pngout_level' );
|
||||
$data['jpg_quality'] = (int) \apply_filters( 'jpeg_quality', 82 );
|
||||
$data['background_opt'] = (bool) \ewww_image_optimizer_get_option( 'ewww_image_optimizer_background_optimization' );
|
||||
$data['scheduled_opt'] = (bool) \ewww_image_optimizer_get_option( 'ewww_image_optimizer_auto' );
|
||||
$data['include_media_folders'] = (bool) \ewww_image_optimizer_get_option( 'ewww_image_optimizer_include_media_paths' );
|
||||
$data['include_originals'] = (bool) \ewww_image_optimizer_get_option( 'ewww_image_optimizer_include_originals' );
|
||||
$data['folders_to_opt'] = (bool) \ewww_image_optimizer_get_option( 'ewww_image_optimizer_aux_paths' );
|
||||
$data['folders_to_ignore'] = (bool) \ewww_image_optimizer_get_option( 'ewww_image_optimizer_exclude_paths' );
|
||||
$data['resize_media_width'] = (int) \ewww_image_optimizer_get_option( 'ewww_image_optimizer_maxmediawidth' );
|
||||
$data['resize_media_height'] = (int) \ewww_image_optimizer_get_option( 'ewww_image_optimizer_maxmediaheight' );
|
||||
$data['resize_indirect_width'] = (int) \ewww_image_optimizer_get_option( 'ewww_image_optimizer_maxotherwidth' );
|
||||
$data['resize_indirect_height'] = (int) \ewww_image_optimizer_get_option( 'ewww_image_optimizer_maxotherheight' );
|
||||
$data['resize_existing'] = (bool) \ewww_image_optimizer_get_option( 'ewww_image_optimizer_resize_existing' );
|
||||
$data['resize_other'] = (bool) \ewww_image_optimizer_get_option( 'ewww_image_optimizer_resize_other_existing' );
|
||||
$data['total_sizes'] = (int) \count( \ewww_image_optimizer_get_image_sizes() );
|
||||
$data['disabled_opt_sizes'] = \is_array( \get_option( 'ewww_image_optimizer_disable_resizes_opt' ) ) ? \count( \get_option( 'ewww_image_optimizer_disable_resizes_opt' ) ) : 0;
|
||||
$data['disabled_create_sizes'] = \is_array( \get_option( 'ewww_image_optimizer_disable_resizes' ) ) ? \count( \get_option( 'ewww_image_optimizer_disable_resizes' ) ) : 0;
|
||||
$data['skip_small_images'] = (int) \ewww_image_optimizer_get_option( 'ewww_image_optimizer_skip_size' );
|
||||
$data['skip_large_pngs'] = (int) \ewww_image_optimizer_get_option( 'ewww_image_optimizer_skip_png_size' );
|
||||
$data['exclude_full_lossy'] = (bool) \ewww_image_optimizer_get_option( 'ewww_image_optimizer_lossy_skip_full' );
|
||||
$data['exclude_full_meta'] = (bool) \ewww_image_optimizer_get_option( 'ewww_image_optimizer_metadata_skip_full' );
|
||||
$data['system_paths'] = (bool) \ewww_image_optimizer_get_option( 'ewww_image_optimizer_skip_bundle' );
|
||||
|
||||
$data['hide_conversion'] = (bool) \ewww_image_optimizer_get_option( 'ewww_image_optimizer_disable_convert_links' );
|
||||
$data['delete_originals'] = (bool) \ewww_image_optimizer_get_option( 'ewww_image_optimizer_delete_originals' );
|
||||
$data['jpg2png'] = (bool) \ewww_image_optimizer_get_option( 'ewww_image_optimizer_jpg_to_png' );
|
||||
$data['png2jpg'] = (bool) \ewww_image_optimizer_get_option( 'ewww_image_optimizer_png_to_jpg' );
|
||||
$data['gif2png'] = (bool) \ewww_image_optimizer_get_option( 'ewww_image_optimizer_gif_to_png' );
|
||||
$data['fill_color'] = \is_null( \ewww_image_optimizer_jpg_background() ) ? '' : \ewww_image_optimizer_jpg_background();
|
||||
|
||||
$data['webp_create'] = (bool) \ewww_image_optimizer_get_option( 'ewww_image_optimizer_webp' );
|
||||
$data['webp_force'] = (bool) \ewww_image_optimizer_get_option( 'ewww_image_optimizer_webp_force' );
|
||||
$data['webp_urls'] = (bool) \ewww_image_optimizer_get_option( 'ewww_image_optimizer_webp_paths' );
|
||||
$data['alt_webp'] = (bool) \ewww_image_optimizer_get_option( 'ewww_image_optimizer_webp_for_cdn' );
|
||||
|
||||
$this->data = $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Send the data to the EDD server
|
||||
*
|
||||
* @access private
|
||||
*
|
||||
* @param bool $override Optional. Force check-in regardless of stored option. Default false.
|
||||
* @param bool $ignore_last_checkin Optional. Force check-in regardless of last attempted time. Default false.
|
||||
*
|
||||
* @return bool Was data sent.
|
||||
*/
|
||||
public function send_checkin( $override = false, $ignore_last_checkin = false ) {
|
||||
if ( ! $this->tracking_allowed() && ! $override ) {
|
||||
return false;
|
||||
}
|
||||
\ewwwio_debug_message( '<b>' . __METHOD__ . '()</b>' );
|
||||
|
||||
// Send a maximum of once per week.
|
||||
$last_send = $this->get_last_send();
|
||||
if ( \is_numeric( $last_send ) && $last_send > \strtotime( '-1 week' ) && ! $ignore_last_checkin ) {
|
||||
\ewwwio_debug_message( 'has not been a week since we last reported' );
|
||||
return false;
|
||||
}
|
||||
|
||||
$this->setup_data();
|
||||
\ewwwio_debug_message( 'sending site data' );
|
||||
$request = \wp_remote_post(
|
||||
'https://optimize.exactlywww.com/stats/report.php',
|
||||
array(
|
||||
'timeout' => 5,
|
||||
'body' => $this->data,
|
||||
'user-agent' => 'EWWW/' . EWWW_IMAGE_OPTIMIZER_VERSION . '; ' . \get_bloginfo( 'url' ),
|
||||
)
|
||||
);
|
||||
|
||||
\ewwwio_debug_message( 'finished reporting' );
|
||||
if ( \is_wp_error( $request ) ) {
|
||||
$error_message = $request->get_error_message();
|
||||
\ewwwio_debug_message( "check-in failed: $error_message" );
|
||||
return $request;
|
||||
}
|
||||
|
||||
\ewwwio_debug_message( 'no error, recording time sent' );
|
||||
\ewww_image_optimizer_set_option( 'ewww_image_optimizer_tracking_last_send', \time() );
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check for a new opt-in on settings save
|
||||
*
|
||||
* @param bool $input The tracking setting.
|
||||
* @return bool The unaltered setting.
|
||||
*/
|
||||
public function check_for_settings_optin( $input ) {
|
||||
\ewwwio_debug_message( '<b>' . __METHOD__ . '()</b>' );
|
||||
// Send an intial check in on settings save.
|
||||
if ( $input ) {
|
||||
$this->send_checkin( true );
|
||||
\ewww_image_optimizer_set_option( 'ewww_image_optimizer_tracking_notice', 1 );
|
||||
}
|
||||
return (bool) $input;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check for a new opt-in via the admin notice
|
||||
*/
|
||||
public function check_for_optin() {
|
||||
\ewwwio_debug_message( '<b>' . __METHOD__ . '()</b>' );
|
||||
\ewww_image_optimizer_set_option( 'ewww_image_optimizer_allow_tracking', 1 );
|
||||
$this->send_checkin( true );
|
||||
\ewww_image_optimizer_set_option( 'ewww_image_optimizer_tracking_notice', 1 );
|
||||
\wp_safe_redirect( \remove_query_arg( 'action', \wp_get_referer() ) );
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check for a new opt-out via the admin notice
|
||||
*/
|
||||
public function check_for_optout() {
|
||||
\ewwwio_debug_message( '<b>' . __METHOD__ . '()</b>' );
|
||||
\delete_option( 'ewww_image_optimizer_allow_tracking' );
|
||||
\delete_network_option( null, 'ewww_image_optimizer_allow_tracking' );
|
||||
\ewww_image_optimizer_set_option( 'ewww_image_optimizer_tracking_notice', 1 );
|
||||
\wp_safe_redirect( \remove_query_arg( 'action', \wp_get_referer() ) );
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the last time a checkin was sent
|
||||
*
|
||||
* @access private
|
||||
* @return false|string
|
||||
*/
|
||||
private function get_last_send() {
|
||||
\ewwwio_debug_message( '<b>' . __METHOD__ . '()</b>' );
|
||||
return \ewww_image_optimizer_get_option( 'ewww_image_optimizer_tracking_last_send' );
|
||||
}
|
||||
|
||||
/**
|
||||
* Schedule a weekly checkin.
|
||||
*/
|
||||
public function schedule_send() {
|
||||
\ewwwio_debug_message( '<b>' . __METHOD__ . '()</b>' );
|
||||
if ( \is_multisite() ) {
|
||||
if ( ! \function_exists( '\is_plugin_active_for_network' ) ) {
|
||||
// Need to include the plugin library for the is_plugin_active function.
|
||||
require_once ABSPATH . 'wp-admin/includes/plugin.php';
|
||||
}
|
||||
if ( \is_plugin_active_for_network( EWWW_IMAGE_OPTIMIZER_PLUGIN_FILE_REL ) && \get_current_blog_id() > 1 ) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
// We send once a week (while tracking is allowed) to check in, which can be used to determine active sites.
|
||||
if ( \ewww_image_optimizer_get_option( 'ewww_image_optimizer_allow_tracking' ) && ! \wp_next_scheduled( 'ewww_image_optimizer_site_report' ) ) {
|
||||
\ewwwio_debug_message( 'scheduling checkin' );
|
||||
\wp_schedule_event( \time(), \apply_filters( 'ewww_image_optimizer_schedule', 'daily', 'ewww_image_optimizer_site_report' ), 'ewww_image_optimizer_site_report' );
|
||||
} elseif ( \ewww_image_optimizer_get_option( 'ewww_image_optimizer_allow_tracking' ) ) {
|
||||
\ewwwio_debug_message( 'checkin already scheduled: ' . \wp_next_scheduled( 'ewww_image_optimizer_site_report' ) );
|
||||
} elseif ( \wp_next_scheduled( 'ewww_image_optimizer_site_report' ) ) {
|
||||
\ewwwio_debug_message( 'un-scheduling checkin' );
|
||||
\wp_clear_scheduled_hook( 'ewww_image_optimizer_site_report' );
|
||||
if ( ! \function_exists( '\is_plugin_active_for_network' ) && \is_multisite() ) {
|
||||
// Need to include the plugin library for the is_plugin_active function.
|
||||
require_once ABSPATH . 'wp-admin/includes/plugin.php';
|
||||
}
|
||||
if ( \is_multisite() && get_current_blog_id() > 1 && \is_plugin_active_for_network( EWWW_IMAGE_OPTIMIZER_PLUGIN_FILE_REL ) ) {
|
||||
\switch_to_blog( 1 );
|
||||
\wp_clear_scheduled_hook( 'ewww_image_optimizer_site_report' );
|
||||
\restore_current_blog();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Un-schedule the weekly checkin.
|
||||
*/
|
||||
public function unschedule_send() {
|
||||
\wp_clear_scheduled_hook( 'ewww_image_optimizer_site_report' );
|
||||
}
|
||||
|
||||
/**
|
||||
* Display the admin notice to users that have not opted-in or out
|
||||
*
|
||||
* @access public
|
||||
* @return void
|
||||
*/
|
||||
public function admin_notice() {
|
||||
return;
|
||||
// If network-active and network notice is hidden, or single-active and single site notice has been hidden, don't show it again.
|
||||
$hide_notice = ewww_image_optimizer_get_option( 'ewww_image_optimizer_tracking_notice' );
|
||||
// But what if they allow overrides? Then the above was checking single-site settings, so we need to check the network admin.
|
||||
if ( is_multisite() && get_site_option( 'ewww_image_optimizer_allow_multisite_override' ) && get_site_option( 'ewww_image_optimizer_tracking_notice' ) ) {
|
||||
$hide_notice = true;
|
||||
}
|
||||
|
||||
if ( $hide_notice ) {
|
||||
return;
|
||||
}
|
||||
if ( ewww_image_optimizer_get_option( 'ewww_image_optimizer_allow_tracking' ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ( ! current_user_can( 'manage_options' ) ) {
|
||||
return;
|
||||
}
|
||||
ewwwio_debug_message( '<b>' . __METHOD__ . '()</b>' );
|
||||
|
||||
if ( ! function_exists( 'is_plugin_active_for_network' ) && is_multisite() ) {
|
||||
// Need to include the plugin library for the is_plugin_active function.
|
||||
require_once ABSPATH . 'wp-admin/includes/plugin.php';
|
||||
}
|
||||
if ( is_multisite() && is_plugin_active_for_network( EWWW_IMAGE_OPTIMIZER_PLUGIN_FILE_REL ) && ! current_user_can( 'manage_network_options' ) ) {
|
||||
return;
|
||||
}
|
||||
if ( is_multisite() && ! is_plugin_active_for_network( EWWW_IMAGE_OPTIMIZER_PLUGIN_FILE_REL ) && is_network_admin() ) {
|
||||
return;
|
||||
}
|
||||
if (
|
||||
stristr( network_site_url( '/' ), '.local' ) !== false ||
|
||||
stristr( network_site_url( '/' ), 'dev' ) !== false ||
|
||||
stristr( network_site_url( '/' ), 'localhost' ) !== false ||
|
||||
stristr( network_site_url( '/' ), ':8888' ) !== false // This is common with MAMP on OS X.
|
||||
) {
|
||||
ewww_image_optimizer_set_option( 'ewww_image_optimizer_tracking_notice', 1 );
|
||||
} else {
|
||||
$admin_email = '<strong>' . get_bloginfo( 'admin_email' ) . '</strong>';
|
||||
$optin_url = admin_url( 'admin.php?action=ewww_opt_into_tracking' );
|
||||
$optout_url = admin_url( 'admin.php?action=ewww_opt_out_of_tracking' );
|
||||
echo '<div class="updated"><p>';
|
||||
/* translators: %s: admin email as configured in settings */
|
||||
printf( esc_html__( 'Allow EWWW Image Optimizer to track plugin usage? Opt-in to tracking and receive 500 free image credits in your admin email: %s. No sensitive data is tracked.', 'ewww-image-optimizer' ), wp_kses_post( $admin_email ) );
|
||||
echo ' <a href="https://docs.ewww.io/article/23-usage-tracking" target="_blank" data-beacon-article="591f3a8e2c7d3a057f893d91">' . esc_html__( 'Learn more.', 'ewww-image-optimizer' ) . '</a>';
|
||||
echo '<a href="' . esc_url( $optin_url ) . '" class="button-secondary" style="margin-left:5px;">' . esc_html__( 'Allow', 'ewww-image-optimizer' ) . '</a>';
|
||||
echo '<a href="' . esc_url( $optout_url ) . '" class="button-secondary" style="margin-left:5px">' . esc_html__( 'Do not allow', 'ewww-image-optimizer' ) . '</a>';
|
||||
echo '</p></div>';
|
||||
}
|
||||
}
|
||||
}
|
14480
wp-content/plugins/ewww-image-optimizer/common.php
Normal file
5
wp-content/plugins/ewww-image-optimizer/composer.json
Normal file
@ -0,0 +1,5 @@
|
||||
{
|
||||
"require": {
|
||||
"lsolesen/pel": "0.9.12"
|
||||
}
|
||||
}
|
79
wp-content/plugins/ewww-image-optimizer/composer.lock
generated
Normal file
@ -0,0 +1,79 @@
|
||||
{
|
||||
"_readme": [
|
||||
"This file locks the dependencies of your project to a known state",
|
||||
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
|
||||
"This file is @generated automatically"
|
||||
],
|
||||
"content-hash": "3d1a26d43e65eba3a0bd49c016586678",
|
||||
"packages": [
|
||||
{
|
||||
"name": "lsolesen/pel",
|
||||
"version": "0.9.12",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/pel/pel.git",
|
||||
"reference": "b95fe29cdacf9d36330da277f10910a13648c84c"
|
||||
},
|
||||
"dist": {
|
||||
"type": "zip",
|
||||
"url": "https://api.github.com/repos/pel/pel/zipball/b95fe29cdacf9d36330da277f10910a13648c84c",
|
||||
"reference": "b95fe29cdacf9d36330da277f10910a13648c84c",
|
||||
"shasum": ""
|
||||
},
|
||||
"require": {
|
||||
"php": ">=7.1.0"
|
||||
},
|
||||
"require-dev": {
|
||||
"ext-exif": "*",
|
||||
"ext-gd": "*",
|
||||
"php-coveralls/php-coveralls": ">2.4",
|
||||
"squizlabs/php_codesniffer": ">3.5",
|
||||
"symfony/phpunit-bridge": "^4 || ^5"
|
||||
},
|
||||
"type": "library",
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
"lsolesen\\pel\\": "src/"
|
||||
}
|
||||
},
|
||||
"notification-url": "https://packagist.org/downloads/",
|
||||
"license": [
|
||||
"GPL-2.0"
|
||||
],
|
||||
"authors": [
|
||||
{
|
||||
"name": "Lars Olesen",
|
||||
"email": "lars@intraface.dk",
|
||||
"homepage": "http://intraface.dk",
|
||||
"role": "Developer"
|
||||
},
|
||||
{
|
||||
"name": "Martin Geisler",
|
||||
"email": "martin@geisler.net",
|
||||
"homepage": "http://geisler.net",
|
||||
"role": "Developer"
|
||||
}
|
||||
],
|
||||
"description": "PHP Exif Library. A library for reading and writing Exif headers in JPEG and TIFF images using PHP.",
|
||||
"homepage": "http://pel.github.com/pel/",
|
||||
"keywords": [
|
||||
"exif",
|
||||
"image"
|
||||
],
|
||||
"support": {
|
||||
"issues": "https://github.com/pel/pel/issues",
|
||||
"source": "https://github.com/pel/pel/tree/0.9.12"
|
||||
},
|
||||
"time": "2022-02-18T13:20:54+00:00"
|
||||
}
|
||||
],
|
||||
"packages-dev": [],
|
||||
"aliases": [],
|
||||
"minimum-stability": "stable",
|
||||
"stability-flags": [],
|
||||
"prefer-stable": false,
|
||||
"prefer-lowest": false,
|
||||
"platform": [],
|
||||
"platform-dev": [],
|
||||
"plugin-api-version": "2.1.0"
|
||||
}
|
27
wp-content/plugins/ewww-image-optimizer/docs/CONTRIBUTING.md
Normal file
@ -0,0 +1,27 @@
|
||||
# Contributing to EWWW IO
|
||||
|
||||
:+1::tada: First off, thanks for taking the time to contribute! :tada::+1:
|
||||
|
||||
## Code of Conduct
|
||||
|
||||
Someday, we'll have something more substantial. For now, let's keep it simple:
|
||||
|
||||
* Be nice, you'll catch more flies with honey (or something like that)
|
||||
* Do not file an issue to ask for support. Issues are for bugs and feature requests, but if you have a question, you can [contact us](https://ewww.io/contact-us/) directly.
|
||||
* Do not issue a pull request without submitting an Issue first.
|
||||
|
||||
## Coding Standards
|
||||
|
||||
All PHP code submitted must follow the [WordPress Coding Standards](https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards), specifically the Core ruleset. All commits are automatically tested for this, but it helps if you know what the [rules are](https://make.wordpress.org/core/handbook/best-practices/coding-standards/php/). JS and CSS code is honestly a bit unruly at this point.
|
||||
|
||||
## Reporting Issues
|
||||
|
||||
When you submit a bug:
|
||||
|
||||
* Include as much detail as possible. If you're not sure about something, include it anyway.
|
||||
* Include steps to reproduce the issue, in as much detail as possible, including other plugins/themes that are involved, and settings that may affect the bug.
|
||||
* Explain what behavior you expected to see, and point out exactly what you saw instead that was not expected.
|
||||
* If applicable, provide screenshots.
|
||||
* Provide images that you've used to reproduce the issue.
|
||||
* Enable EWWW IO's debugging option and provide as much of it as possible. You may wish to redact the user account and file system paths listed.
|
||||
* Check older versions to see if it is a regression. You can download them from the [Advanced section at wordpress.org](https://wordpress.org/plugins/ewww-image-optimizer/advanced/).
|
154
wp-content/plugins/ewww-image-optimizer/ewww-image-optimizer.php
Normal file
@ -0,0 +1,154 @@
|
||||
<?php
|
||||
/**
|
||||
* Loader for Standard EWWW IO plugin.
|
||||
*
|
||||
* This file bootstraps the rest of the EWWW IO plugin after some basic checks.
|
||||
*
|
||||
* @link https://ewww.io
|
||||
* @package EWWW_Image_Optimizer
|
||||
*/
|
||||
|
||||
/*
|
||||
Plugin Name: EWWW Image Optimizer
|
||||
Plugin URI: https://wordpress.org/plugins/ewww-image-optimizer/
|
||||
Description: Smaller Images, Faster Sites, Happier Visitors. Comprehensive image optimization that doesn't require a degree in rocket science.
|
||||
Author: Exactly WWW
|
||||
Version: 7.2.2
|
||||
Requires at least: 6.1
|
||||
Requires PHP: 7.3
|
||||
Author URI: https://ewww.io/
|
||||
License: GPLv3
|
||||
*/
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit;
|
||||
}
|
||||
|
||||
// Check the PHP version.
|
||||
if ( ! defined( 'PHP_VERSION_ID' ) || PHP_VERSION_ID < 70300 ) {
|
||||
add_action( 'network_admin_notices', 'ewww_image_optimizer_unsupported_php' );
|
||||
add_action( 'admin_notices', 'ewww_image_optimizer_unsupported_php' );
|
||||
} elseif ( defined( 'EWWW_IMAGE_OPTIMIZER_VERSION' ) ) {
|
||||
// Prevent loading more than one EWWW IO plugin.
|
||||
add_action( 'network_admin_notices', 'ewww_image_optimizer_dual_plugin' );
|
||||
add_action( 'admin_notices', 'ewww_image_optimizer_dual_plugin' );
|
||||
} elseif ( false === strpos( add_query_arg( '', '' ), 'ewwwio_disable=1' ) ) {
|
||||
|
||||
define( 'EWWW_IMAGE_OPTIMIZER_VERSION', 722 );
|
||||
// Initialize a global.
|
||||
$ewww_defer = true;
|
||||
|
||||
if ( WP_DEBUG && function_exists( 'memory_get_usage' ) ) {
|
||||
$ewww_memory = 'plugin load: ' . memory_get_usage( true ) . "\n";
|
||||
}
|
||||
|
||||
/**
|
||||
* Always use relative paths unless the user has already defined this constant.
|
||||
*
|
||||
* @var bool EWWW_IMAGE_OPTIMIZER_RELATIVE
|
||||
*/
|
||||
if ( ! defined( 'EWWW_IMAGE_OPTIMIZER_RELATIVE' ) ) {
|
||||
define( 'EWWW_IMAGE_OPTIMIZER_RELATIVE', true );
|
||||
}
|
||||
/**
|
||||
* The full path of the plugin file (this file).
|
||||
*
|
||||
* @var string EWWW_IMAGE_OPTIMIZER_PLUGIN_FILE
|
||||
*/
|
||||
define( 'EWWW_IMAGE_OPTIMIZER_PLUGIN_FILE', __FILE__ );
|
||||
/**
|
||||
* The path of the plugin file relative to the plugins/ folder.
|
||||
*
|
||||
* @var string EWWW_IMAGE_OPTIMIZER_PLUGIN_FILE_REL
|
||||
*/
|
||||
define( 'EWWW_IMAGE_OPTIMIZER_PLUGIN_FILE_REL', plugin_basename( __FILE__ ) );
|
||||
/**
|
||||
* This is the full system path to the plugin folder.
|
||||
*
|
||||
* @var string EWWW_IMAGE_OPTIMIZER_PLUGIN_PATH
|
||||
*/
|
||||
define( 'EWWW_IMAGE_OPTIMIZER_PLUGIN_PATH', plugin_dir_path( __FILE__ ) );
|
||||
/**
|
||||
* This is the full system path to the bundled binaries.
|
||||
*
|
||||
* @var string EWWW_IMAGE_OPTIMIZER_BINARY_PATH
|
||||
*/
|
||||
define( 'EWWW_IMAGE_OPTIMIZER_BINARY_PATH', plugin_dir_path( __FILE__ ) . 'binaries/' );
|
||||
/**
|
||||
* This is the full system path to the plugin images for testing.
|
||||
*
|
||||
* @var string EWWW_IMAGE_OPTIMIZER_IMAGES_PATH
|
||||
*/
|
||||
define( 'EWWW_IMAGE_OPTIMIZER_IMAGES_PATH', plugin_dir_path( __FILE__ ) . 'images/' );
|
||||
if ( ! defined( 'EWWW_IMAGE_OPTIMIZER_TOOL_PATH' ) ) {
|
||||
if ( ! defined( 'EWWWIO_CONTENT_DIR' ) ) {
|
||||
$ewwwio_content_dir = trailingslashit( realpath( WP_CONTENT_DIR ) ) . trailingslashit( 'ewww' );
|
||||
if ( ! is_writable( WP_CONTENT_DIR ) || ! empty( $_ENV['PANTHEON_ENVIRONMENT'] ) ) {
|
||||
$upload_dir = wp_get_upload_dir();
|
||||
if ( false === strpos( $upload_dir['basedir'], '://' ) && is_writable( $upload_dir['basedir'] ) ) {
|
||||
$ewwwio_content_dir = trailingslashit( realpath( $upload_dir['basedir'] ) ) . trailingslashit( 'ewww' );
|
||||
}
|
||||
}
|
||||
/**
|
||||
* The folder where we store debug logs (among other things) - MUST have a trailing slash.
|
||||
*
|
||||
* @var string EWWWIO_CONTENT_DIR
|
||||
*/
|
||||
define( 'EWWWIO_CONTENT_DIR', $ewwwio_content_dir );
|
||||
}
|
||||
/**
|
||||
* The folder where we install optimization tools - MUST have a trailing slash.
|
||||
*
|
||||
* @var string EWWW_IMAGE_OPTIMIZER_TOOL_PATH
|
||||
*/
|
||||
define( 'EWWW_IMAGE_OPTIMIZER_TOOL_PATH', EWWWIO_CONTENT_DIR );
|
||||
} elseif ( ! defined( 'EWWWIO_CONTENT_DIR' ) ) {
|
||||
define( 'EWWWIO_CONTENT_DIR', EWWW_IMAGE_OPTIMIZER_TOOL_PATH );
|
||||
}
|
||||
|
||||
/**
|
||||
* All the 'unique' functions for the core EWWW IO plugin (slowly being replaced with oop).
|
||||
*/
|
||||
require_once EWWW_IMAGE_OPTIMIZER_PLUGIN_PATH . 'unique.php';
|
||||
/**
|
||||
* All the 'common' functions for both EWWW IO plugins.
|
||||
*/
|
||||
require_once EWWW_IMAGE_OPTIMIZER_PLUGIN_PATH . 'common.php';
|
||||
/**
|
||||
* All the base functions for our plugins and classes to inherit.
|
||||
*/
|
||||
require_once EWWW_IMAGE_OPTIMIZER_PLUGIN_PATH . 'classes/class-base.php';
|
||||
/**
|
||||
* The setup functions for EWWW IO.
|
||||
*/
|
||||
require_once EWWW_IMAGE_OPTIMIZER_PLUGIN_PATH . 'classes/class-plugin.php';
|
||||
/**
|
||||
* Class for local optimization tool installation/valication.
|
||||
*/
|
||||
require_once EWWW_IMAGE_OPTIMIZER_PLUGIN_PATH . 'classes/class-local.php';
|
||||
/**
|
||||
* The main function to return a single EWWW\Plugin object to functions elsewhere.
|
||||
*
|
||||
* @return object object|EWWW\Plugin The one true EWWW\Plugin instance.
|
||||
*/
|
||||
function ewwwio() {
|
||||
return EWWW\Plugin::instance();
|
||||
}
|
||||
ewwwio();
|
||||
} // End if().
|
||||
|
||||
if ( ! function_exists( 'ewww_image_optimizer_unsupported_php' ) ) {
|
||||
/**
|
||||
* Display a notice that the PHP version is too old.
|
||||
*/
|
||||
function ewww_image_optimizer_unsupported_php() {
|
||||
echo '<div id="ewww-image-optimizer-warning-php" class="error"><p><a href="https://docs.ewww.io/article/55-upgrading-php" target="_blank" data-beacon-article="5ab2baa6042863478ea7c2ae">' . esc_html__( 'EWWW Image Optimizer requires PHP 7.4 or greater. Newer versions of PHP are significantly faster and much more secure. If you are unsure how to upgrade to a supported version, ask your webhost for instructions.', 'ewww-image-optimizer' ) . '</a></p></div>';
|
||||
}
|
||||
|
||||
/**
|
||||
* Display a notice when both the standard and cloud plugins are active.
|
||||
*/
|
||||
function ewww_image_optimizer_dual_plugin() {
|
||||
echo "<div id='ewww-image-optimizer-warning-double-plugin' class='error'><p><strong>" . esc_html__( 'Only one version of the EWWW Image Optimizer can be active at a time. Please deactivate other copies of the plugin.', 'ewww-image-optimizer' ) . '</strong></p></div>';
|
||||
}
|
||||
}
|
90
wp-content/plugins/ewww-image-optimizer/functions.php
Normal file
@ -0,0 +1,90 @@
|
||||
<?php
|
||||
/**
|
||||
* Wrapper functions for commonly used functions that haven't been fully migrated to oop OR failsafes for backwards compat.
|
||||
*
|
||||
* @link https://ewww.io
|
||||
* @package EWWW_Image_Optimizer
|
||||
*/
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check the mimetype of the given file with magic mime strings/patterns.
|
||||
*
|
||||
* @param string $path The absolute path to the file.
|
||||
* @param string $type The type of file we are checking. Accepts 'i' for
|
||||
* images/pdfs or 'b' for binary.
|
||||
* @return bool|string A valid mime-type or false.
|
||||
*/
|
||||
function ewww_image_optimizer_mimetype( $path, $type ) {
|
||||
return ewwwio()->mimetype( $path, $type );
|
||||
}
|
||||
|
||||
/**
|
||||
* Escape any spaces in the filename.
|
||||
*
|
||||
* @param string $path The path to a binary file.
|
||||
* @return string The path with spaces escaped.
|
||||
*/
|
||||
function ewww_image_optimizer_escapeshellcmd( $path ) {
|
||||
return ewwwio()->escapeshellcmd( $path );
|
||||
}
|
||||
|
||||
/**
|
||||
* Replacement for escapeshellarg() that won't kill non-ASCII characters.
|
||||
*
|
||||
* @param string $arg A value to sanitize/escape for commmand-line usage.
|
||||
* @return string The value after being escaped.
|
||||
*/
|
||||
function ewww_image_optimizer_escapeshellarg( $arg ) {
|
||||
return ewwwio()->escapeshellarg( $arg );
|
||||
}
|
||||
|
||||
/**
|
||||
* Sanitize the folders/patterns to exclude from optimization.
|
||||
*
|
||||
* @param string $input A list of filesystem paths, from a textarea.
|
||||
* @return array The sanitized list of paths/patterns to exclude.
|
||||
*/
|
||||
function ewww_image_optimizer_exclude_paths_sanitize( $input ) {
|
||||
return ewwwio()->exclude_paths_sanitize( $input );
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if a function is disabled or does not exist.
|
||||
*
|
||||
* @param string $function_name The name of a function to test.
|
||||
* @param bool $debug Whether to output debugging.
|
||||
* @return bool True if the function is available, False if not.
|
||||
*/
|
||||
function ewww_image_optimizer_function_exists( $function_name, $debug = false ) {
|
||||
return ewwwio()->function_exists( $function_name, $debug );
|
||||
}
|
||||
|
||||
/**
|
||||
* Make sure an array/object can be parsed by a foreach().
|
||||
*
|
||||
* @param mixed $value A variable to test for iteration ability.
|
||||
* @return bool True if the variable is iterable.
|
||||
*/
|
||||
function ewww_image_optimizer_iterable( $value ) {
|
||||
return ewwwio()->is_iterable( $value );
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds information to the in-memory debug log.
|
||||
*
|
||||
* @param string $message Debug information to add to the log.
|
||||
*/
|
||||
function ewwwio_debug_message( $message ) {
|
||||
ewwwio()->debug_message( $message );
|
||||
}
|
||||
|
||||
/**
|
||||
* Saves the in-memory debug log to a logfile in the plugin folder.
|
||||
*/
|
||||
function ewww_image_optimizer_debug_log() {
|
||||
ewwwio()->debug_log();
|
||||
}
|
BIN
wp-content/plugins/ewww-image-optimizer/images/ewwwio-logo.png
Normal file
After Width: | Height: | Size: 8.4 KiB |
After Width: | Height: | Size: 579 B |
BIN
wp-content/plugins/ewww-image-optimizer/images/sample.jpg
Normal file
After Width: | Height: | Size: 285 B |
BIN
wp-content/plugins/ewww-image-optimizer/images/spinner.gif
Normal file
After Width: | Height: | Size: 3.7 KiB |
BIN
wp-content/plugins/ewww-image-optimizer/images/test.png
Normal file
After Width: | Height: | Size: 866 B |
BIN
wp-content/plugins/ewww-image-optimizer/images/test.png.webp
Normal file
After Width: | Height: | Size: 720 B |
BIN
wp-content/plugins/ewww-image-optimizer/images/testorig.gif
Normal file
After Width: | Height: | Size: 12 KiB |
BIN
wp-content/plugins/ewww-image-optimizer/images/testorig.jpg
Normal file
After Width: | Height: | Size: 5.6 KiB |
BIN
wp-content/plugins/ewww-image-optimizer/images/testorig.png
Normal file
After Width: | Height: | Size: 114 B |
BIN
wp-content/plugins/ewww-image-optimizer/images/wpspin.gif
Normal file
After Width: | Height: | Size: 2.0 KiB |
@ -0,0 +1,26 @@
|
||||
var ewww_webp_supported = false;
|
||||
// webp detection adapted from https://developers.google.com/speed/webp/faq#how_can_i_detect_browser_support_using_javascript
|
||||
function check_webp_feature(feature, callback) {
|
||||
callback = (typeof callback !== 'undefined') ? callback : function(){};
|
||||
if (ewww_webp_supported) {
|
||||
callback(ewww_webp_supported);
|
||||
return;
|
||||
}
|
||||
var kTestImages = {
|
||||
alpha: "UklGRkoAAABXRUJQVlA4WAoAAAAQAAAAAAAAAAAAQUxQSAwAAAARBxAR/Q9ERP8DAABWUDggGAAAABQBAJ0BKgEAAQAAAP4AAA3AAP7mtQAAAA==",
|
||||
};
|
||||
var img = new Image();
|
||||
img.onload = function () {
|
||||
ewww_webp_supported = (img.width > 0) && (img.height > 0);
|
||||
if (callback) {
|
||||
callback(ewww_webp_supported);
|
||||
}
|
||||
};
|
||||
img.onerror = function () {
|
||||
if (callback) {
|
||||
callback(false);
|
||||
}
|
||||
};
|
||||
img.src = "data:image/webp;base64," + kTestImages[feature];
|
||||
}
|
||||
check_webp_feature('alpha');
|
1
wp-content/plugins/ewww-image-optimizer/includes/check-webp.min.js
vendored
Normal file
@ -0,0 +1 @@
|
||||
var ewww_webp_supported=!1;function check_webp_feature(A,e){var w;e=void 0!==e?e:function(){},ewww_webp_supported?e(ewww_webp_supported):((w=new Image).onload=function(){ewww_webp_supported=0<w.width&&0<w.height,e&&e(ewww_webp_supported)},w.onerror=function(){e&&e(!1)},w.src="data:image/webp;base64,"+{alpha:"UklGRkoAAABXRUJQVlA4WAoAAAAQAAAAAAAAAAAAQUxQSAwAAAARBxAR/Q9ERP8DAABWUDggGAAAABQBAJ0BKgEAAQAAAP4AAA3AAP7mtQAAAA=="}[A])}check_webp_feature("alpha");
|
@ -0,0 +1,64 @@
|
||||
jQuery(document).ready(function($) {
|
||||
$('#ewww-copy-debug').on( 'click', function() {
|
||||
selectText('ewww-debug-info');
|
||||
try {
|
||||
var successful = document.execCommand('copy');
|
||||
if ( successful ) {
|
||||
unselectText();
|
||||
}
|
||||
} catch(err) {
|
||||
console.log('browser cannot copy');
|
||||
console.log(err);
|
||||
}
|
||||
});
|
||||
function HSregister() {
|
||||
if (typeof(Beacon) !== 'undefined' ) {
|
||||
$('.ewww-overrides-nav').on( 'click', function() {
|
||||
Beacon('article', '59710ce4042863033a1b45a6', { type: 'modal' });
|
||||
return false;
|
||||
});
|
||||
$('.ewww-contact-root').on( 'click', function() {
|
||||
Beacon('navigate', '/ask/')
|
||||
Beacon('open');
|
||||
return false;
|
||||
});
|
||||
$('.ewww-docs-root').on( 'click', function() {
|
||||
Beacon('navigate', '/answers/')
|
||||
Beacon('open');
|
||||
return false;
|
||||
});
|
||||
$('.ewww-help-beacon-multi').on( 'click', function() {
|
||||
var hsids = $(this).attr('data-beacon-articles');
|
||||
hsids = hsids.split(',');
|
||||
Beacon('suggest', hsids);
|
||||
Beacon('navigate', '/answers/');
|
||||
Beacon('open');
|
||||
return false;
|
||||
});
|
||||
$('.ewww-help-beacon-single').on( 'click', function() {
|
||||
var hsid = $(this).attr('data-beacon-article');
|
||||
Beacon('article', hsid, { type: 'modal' });
|
||||
return false;
|
||||
});
|
||||
}
|
||||
}
|
||||
HSregister();
|
||||
});
|
||||
function selectText(containerid) {
|
||||
var debug_node = document.getElementById(containerid);
|
||||
if (document.selection) {
|
||||
var range = document.body.createTextRange();
|
||||
range.moveToElementText(debug_node);
|
||||
range.select();
|
||||
} else if (window.getSelection) {
|
||||
window.getSelection().selectAllChildren(debug_node);
|
||||
}
|
||||
}
|
||||
function unselectText() {
|
||||
var sel;
|
||||
if ( (sel = document.selection) && sel.empty) {
|
||||
sel.empty();
|
||||
} else if (window.getSelection) {
|
||||
window.getSelection().removeAllRanges();
|
||||
}
|
||||
}
|
445
wp-content/plugins/ewww-image-optimizer/includes/eio-bulk.js
Normal file
@ -0,0 +1,445 @@
|
||||
jQuery(document).ready(function($) {
|
||||
var ewww_error_counter = 30;
|
||||
$("#ewww-delay-slider").slider({
|
||||
min: 0,
|
||||
max: 30,
|
||||
value: $("#ewww-delay").val(),
|
||||
slide: function(event, ui) {
|
||||
$("#ewww-delay").val(ui.value);
|
||||
}
|
||||
});
|
||||
var ewwwdelayinput = document.getElementById("ewww-delay");
|
||||
if (ewwwdelayinput) {
|
||||
ewwwdelayinput.onblur = function() {
|
||||
if (isNaN(this.value)) {
|
||||
this.value = 0;
|
||||
} else {
|
||||
this.value = Math.ceil(this.value);
|
||||
}
|
||||
};
|
||||
}
|
||||
var ewww_attachments = ewww_vars.attachments;
|
||||
var ewww_i = 0;
|
||||
var ewww_k = 0;
|
||||
var ewww_import_total = 0;
|
||||
var ewww_force = 0;
|
||||
var ewww_force_smart = 0;
|
||||
var ewww_webp_only = 0;
|
||||
var ewww_delay = 0;
|
||||
var ewww_batch_limit = 0;
|
||||
var ewww_aux = false;
|
||||
var ewww_main = false;
|
||||
var ewww_quota_update = 0;
|
||||
var ewww_scan_failures = 0;
|
||||
var ewww_bulk_start_time = 0;
|
||||
var ewww_bulk_elapsed_time = 0;
|
||||
var ewww_time_per_image = 0;
|
||||
var ewww_time_remaining = 0;
|
||||
var ewww_days_remaining = 0;
|
||||
var ewww_hours_remaining = 0;
|
||||
var ewww_minutes_remaining = 0;
|
||||
var ewww_seconds_remaining = 0;
|
||||
var ewww_countdown = false;
|
||||
var ewww_tiny_skip = '';
|
||||
// initialize the ajax actions for the appropriate bulk page
|
||||
var ewww_quota_update_data = {
|
||||
action: 'bulk_quota_update',
|
||||
ewww_wpnonce: ewww_vars._wpnonce,
|
||||
};
|
||||
if (ewww_vars.gallery == 'flag') {
|
||||
var ewww_init_action = 'bulk_flag_init';
|
||||
var ewww_loop_action = 'bulk_flag_loop';
|
||||
var ewww_cleanup_action = 'bulk_flag_cleanup';
|
||||
} else if (ewww_vars.gallery == 'nextgen') {
|
||||
var ewww_preview_action = 'bulk_ngg_preview';
|
||||
var ewww_init_action = 'bulk_ngg_init';
|
||||
var ewww_loop_action = 'bulk_ngg_loop';
|
||||
var ewww_cleanup_action = 'bulk_ngg_cleanup';
|
||||
} else {
|
||||
var ewww_scan_action = 'bulk_scan';
|
||||
var ewww_init_action = 'bulk_init';
|
||||
var ewww_loop_action = 'bulk_loop';
|
||||
var ewww_cleanup_action = 'bulk_cleanup';
|
||||
ewww_main = true;
|
||||
}
|
||||
var ewww_init_data = {
|
||||
action: ewww_init_action,
|
||||
ewww_wpnonce: ewww_vars._wpnonce,
|
||||
};
|
||||
var ewww_table_action = 'bulk_aux_images_table';
|
||||
var ewww_table_count_action = 'bulk_aux_images_table_count';
|
||||
var ewww_import_init_action = 'bulk_import_init';
|
||||
var ewww_import_loop_action = 'bulk_import_loop';
|
||||
$(document).on('click', '.ewww-show-debug-meta', function() {
|
||||
var post_id = $(this).data('id');
|
||||
$('.ewww-debug-meta-' + post_id).toggle();
|
||||
});
|
||||
$('.ewww-hndle').click(function() {
|
||||
return;
|
||||
$(this).next('.inside').toggle();
|
||||
var button = $(this).prev('.button-link');
|
||||
if ('true' == button.attr('aria-expanded')) {
|
||||
button.attr('aria-expanded', 'false');
|
||||
button.closest('.postbox').addClass('closed');
|
||||
button.children('.toggle-indicator').attr('aria-hidden', 'true');
|
||||
} else {
|
||||
button.attr('aria-expanded', 'true');
|
||||
button.closest('.postbox').removeClass('closed');
|
||||
button.children('.toggle-indicator').attr('aria-hidden', 'false');
|
||||
}
|
||||
});
|
||||
$('.ewww-handlediv').click(function() {
|
||||
$(this).parent().children('.inside').toggle();
|
||||
if ('true' == $(this).attr('aria-expanded')) {
|
||||
$(this).attr('aria-expanded', 'false');
|
||||
$(this).closest('.postbox').addClass('closed');
|
||||
$(this).children('.toggle-indicator').attr('aria-hidden', 'true');
|
||||
} else {
|
||||
$(this).attr('aria-expanded', 'true');
|
||||
$(this).closest('.postbox').removeClass('closed');
|
||||
$(this).children('.toggle-indicator').attr('aria-hidden', 'false');
|
||||
}
|
||||
});
|
||||
$('#ewww-aux-start').submit(function() {
|
||||
ewww_aux = true;
|
||||
if ($('#ewww-force:checkbox:checked').val()) {
|
||||
ewww_force = 1;
|
||||
}
|
||||
if ($('#ewww-force-smart:checkbox:checked').val()) {
|
||||
ewww_force_smart = 1;
|
||||
}
|
||||
if ($('#ewww-webp-only:checkbox:checked').val()) {
|
||||
ewww_webp_only = 1;
|
||||
}
|
||||
$('#ewww-aux-start').hide();
|
||||
$('.ewww-bulk-info').hide();
|
||||
$('.ewww-aux-table').hide();
|
||||
$('#ewww-show-table').hide();
|
||||
$('#ewww-scanning').show();
|
||||
ewwwStartScan();
|
||||
return false;
|
||||
});
|
||||
function ewwwStartScan() {
|
||||
var ewww_scan_data = {
|
||||
action: ewww_scan_action,
|
||||
ewww_force: ewww_force,
|
||||
ewww_force_smart: ewww_force_smart,
|
||||
ewww_webp_only: ewww_webp_only,
|
||||
ewww_scan: true,
|
||||
ewww_wpnonce: ewww_vars._wpnonce,
|
||||
};
|
||||
$.post(ajaxurl, ewww_scan_data, function(response) {
|
||||
var is_json = true;
|
||||
try {
|
||||
var ewww_response = JSON.parse(response);
|
||||
} catch (err) {
|
||||
is_json = false;
|
||||
}
|
||||
if ( ! is_json ) {
|
||||
$('#ewww-scanning').html('<span class="ewww-bulk-error"><b>' + ewww_vars.invalid_response + '</b></span>');
|
||||
console.log( response );
|
||||
return false;
|
||||
}
|
||||
ewww_init_data = {
|
||||
action: ewww_init_action,
|
||||
ewww_wpnonce: ewww_vars._wpnonce,
|
||||
};
|
||||
if ( ewww_response.error ) {
|
||||
$('#ewww-scanning').html('<span class="ewww-bulk-error"><b>' + ewww_response.error + '</b></span>');
|
||||
} else if ( ewww_response.remaining ) {
|
||||
$('.ewww-aux-table').hide();
|
||||
$('#ewww-show-table').hide();
|
||||
//if ( ! ewww_response.notice ) {
|
||||
// ewww_response.notice = '';
|
||||
//}
|
||||
$('#ewww-scanning').html( ewww_response.remaining );
|
||||
if ( ewww_response.notice ) {
|
||||
$('#ewww-scanning').append( '<br>' + ewww_response.notice );
|
||||
}
|
||||
if ( ewww_response.tiny_skip ) {
|
||||
$('#ewww-scanning').append( '<br>' + ewww_response.tiny_skip );
|
||||
ewww_tiny_skip = ewww_response.tiny_skip;
|
||||
console.log( 'skipped some tiny images' );
|
||||
}
|
||||
if ( ewww_response.bad_attachment ) {
|
||||
$('#ewww-scanning').append( '<br>' + ewww_vars.bad_attachment + ' ' + ewww_response.bad_attachment );
|
||||
}
|
||||
ewww_scan_failures = 0;
|
||||
ewwwStartScan();
|
||||
} else if ( ewww_response.ready ) {
|
||||
ewww_attachments = ewww_response.ready;
|
||||
$('#ewww-scanning').html(ewww_response.message);
|
||||
if ( ewww_tiny_skip ) {
|
||||
$('#ewww-scanning').append( '<br><i>' + ewww_tiny_skip + '</i>' );
|
||||
console.log( 'done, skipped some tiny images' );
|
||||
}
|
||||
$('#ewww-bulk-first').val(ewww_response.start_button);
|
||||
$('#ewww-bulk-start').show();
|
||||
} else if ( ewww_response.ready === 0 ) {
|
||||
$('#ewww-scanning').hide();
|
||||
$('#ewww-nothing').show();
|
||||
if ( ewww_tiny_skip ) {
|
||||
$('#ewww-nothing').append( '<br><i>' + ewww_tiny_skip + '</i>' );
|
||||
console.log( 'done, skipped some tiny images' );
|
||||
}
|
||||
}
|
||||
})
|
||||
.fail(function() {
|
||||
ewww_scan_failures++;
|
||||
if (ewww_scan_failures > 10) {
|
||||
$('#ewww-scanning').html('<span class="ewww-bulk-error"><b>' + ewww_vars.scan_fail + ':</b> ' + ewww_vars.bulk_fail_more + '</span>');
|
||||
} else {
|
||||
$('#ewww-scanning').html('<span class="ewww-bulk-error"><b>' + ewww_vars.scan_incomplete + '</b></span>');
|
||||
setTimeout(function() {
|
||||
ewwwStartScan();
|
||||
}, 1000);
|
||||
}
|
||||
});
|
||||
}
|
||||
$('#ewww-bulk-start').submit(function() {
|
||||
ewwwStartOpt();
|
||||
return false;
|
||||
});
|
||||
function ewwwUpdateQuota() {
|
||||
if ($('#ewww-bulk-credits-available').length > 0) {
|
||||
ewww_quota_update_data.ewww_wpnonce = ewww_vars._wpnonce;
|
||||
$.post(ajaxurl, ewww_quota_update_data, function(response) {
|
||||
$('#ewww-bulk-credits-available').html(response);
|
||||
});
|
||||
}
|
||||
}
|
||||
function ewwwStartOpt () {
|
||||
ewww_k = 0;
|
||||
ewww_quota_update = setInterval( ewwwUpdateQuota, 60000 );
|
||||
$('#ewww-bulk-stop').submit(function() {
|
||||
ewww_k = 9;
|
||||
$('#ewww-bulk-stop').hide();
|
||||
return false;
|
||||
});
|
||||
if ( ! $('#ewww-delay').val().match( /^[1-9][0-9]*$/) ) {
|
||||
ewww_delay = 0;
|
||||
} else {
|
||||
ewww_delay = $('#ewww-delay').val();
|
||||
}
|
||||
if (ewww_delay) {
|
||||
ewww_batch_limit = 1;
|
||||
$('#ewww-bulk-last h2').html( ewww_vars.last_image_header );
|
||||
}
|
||||
$('.ewww-aux-table').hide();
|
||||
$('#ewww-bulk-stop').show();
|
||||
$('.ewww-bulk-form').hide();
|
||||
$('.ewww-bulk-info').hide();
|
||||
$('#ewww-bulk-forms').hide();
|
||||
$('h2').hide();
|
||||
$.post(ajaxurl, ewww_init_data, function(response) {
|
||||
var is_json = true;
|
||||
try {
|
||||
var ewww_init_response = JSON.parse(response);
|
||||
} catch (err) {
|
||||
is_json = false;
|
||||
}
|
||||
if ( ! is_json || ! response ) {
|
||||
$('#ewww-bulk-loading').append('<p class="ewww-bulk-error"><b>' + ewww_vars.invalid_response + '</b></p>');
|
||||
console.log( response );
|
||||
return false;
|
||||
}
|
||||
if ( ewww_init_response.error ) {
|
||||
$('#ewww-bulk-loading').append('<p class="ewww-bulk-error"><b>' + ewww_init_response.error + '</b></p>');
|
||||
if ( ewww_init_response.data ) {
|
||||
console.log( ewww_init_response.data );
|
||||
}
|
||||
} else {
|
||||
if ( ewww_init_response.start_time ) {
|
||||
ewww_bulk_start_time = ewww_init_response.start_time;
|
||||
}
|
||||
$('#ewww-bulk-loading').html(ewww_init_response.results);
|
||||
$('#ewww-bulk-progressbar').progressbar({ max: ewww_attachments });
|
||||
$('#ewww-bulk-counter').html( ewww_vars.optimized + ' 0/' + ewww_attachments);
|
||||
ewwwProcessImage();
|
||||
}
|
||||
});
|
||||
}
|
||||
function ewwwProcessImage() {
|
||||
if ($('#ewww-force:checkbox:checked').val()) {
|
||||
ewww_force = 1;
|
||||
}
|
||||
if ($('#ewww-force-smart:checkbox:checked').val()) {
|
||||
ewww_force_smart = 1;
|
||||
}
|
||||
if ($('#ewww-webp-only:checkbox:checked').val()) {
|
||||
ewww_webp_only = 1;
|
||||
}
|
||||
var ewww_loop_data = {
|
||||
action: ewww_loop_action,
|
||||
ewww_wpnonce: ewww_vars._wpnonce,
|
||||
ewww_force: ewww_force,
|
||||
ewww_force_smart: ewww_force_smart,
|
||||
ewww_webp_only: ewww_webp_only,
|
||||
ewww_batch_limit: ewww_batch_limit,
|
||||
ewww_error_counter: ewww_error_counter,
|
||||
};
|
||||
var ewww_jqxhr = $.post(ajaxurl, ewww_loop_data, function(response) {
|
||||
var is_json = true;
|
||||
try {
|
||||
var ewww_response = JSON.parse(response);
|
||||
} catch (err) {
|
||||
is_json = false;
|
||||
}
|
||||
if ( ! is_json || ! response ) {
|
||||
$('#ewww-bulk-loading').append('<p class="ewww-bulk-error"><b>' + ewww_vars.invalid_response + '</b></p>');
|
||||
clearInterval(ewww_quota_update);
|
||||
clearInterval(ewww_countdown);
|
||||
if ( ! response ) {
|
||||
console.log( 'empty response' );
|
||||
} else {
|
||||
console.log( response );
|
||||
}
|
||||
return false;
|
||||
}
|
||||
ewww_i += ewww_response.completed;
|
||||
$('#ewww-bulk-progressbar').progressbar( "option", "value", ewww_i );
|
||||
$('#ewww-bulk-counter').html(ewww_vars.optimized + ' ' + ewww_i + '/' + ewww_attachments);
|
||||
if ( ewww_response.update_meta ) {
|
||||
var ewww_updatemeta_data = {
|
||||
action: 'ewww_bulk_update_meta',
|
||||
attachment_id: ewww_response.update_meta,
|
||||
ewww_wpnonce: ewww_vars._wpnonce,
|
||||
};
|
||||
$.post(ajaxurl, ewww_updatemeta_data);
|
||||
}
|
||||
if ( ewww_response.error ) {
|
||||
$('#ewww-bulk-loading img').hide();
|
||||
$('#ewww-bulk-progressbar').hide();
|
||||
$('#ewww-bulk-timer').hide();
|
||||
$('#ewww-bulk-counter').hide();
|
||||
$('#ewww-bulk-stop').hide();
|
||||
$('#ewww-bulk-loading').append('<p class="ewww-bulk-error"><b>' + ewww_response.error + '</b></p>');
|
||||
clearInterval(ewww_quota_update);
|
||||
clearInterval(ewww_countdown);
|
||||
ewwwUpdateQuota();
|
||||
}
|
||||
else if (ewww_k == 9) {
|
||||
if ( ewww_response.results ) {
|
||||
$('#ewww-bulk-last .inside').html( ewww_response.results );
|
||||
$('#ewww-bulk-status .inside').append( ewww_response.results );
|
||||
}
|
||||
clearInterval(ewww_quota_update);
|
||||
clearInterval(ewww_countdown);
|
||||
$('#ewww-bulk-loading').html('<p class="ewww-bulk-error"><b>' + ewww_vars.operation_stopped + '</b></p>');
|
||||
}
|
||||
else if ( response == 0 ) {
|
||||
clearInterval(ewww_quota_update);
|
||||
clearInterval(ewww_countdown);
|
||||
$('#ewww-bulk-loading').html('<p class="ewww-bulk-error"><b>' + ewww_vars.operation_stopped + '</b></p>');
|
||||
}
|
||||
else if ( ewww_i < ewww_attachments && ! ewww_response.done ) {
|
||||
if ( ewww_bulk_start_time && ewww_response.current_time ) {
|
||||
ewww_bulk_elapsed_time = ewww_response.current_time - ewww_bulk_start_time;
|
||||
ewww_time_per_image = ewww_bulk_elapsed_time / ewww_i;
|
||||
ewww_time_remaining = Math.floor((ewww_attachments - ewww_i) * ewww_time_per_image);
|
||||
ewwwTimeIncrementsUpdate();
|
||||
if ( ! ewww_countdown) {
|
||||
$('#ewww-bulk-timer').html(ewww_days_remaining + ':' + ewww_hours_remaining + ':' + ewww_minutes_remaining + ':' + ewww_seconds_remaining + ' ' + ewww_vars.time_remaining);
|
||||
ewww_countdown = setInterval( ewwwCountDown, 1000 );
|
||||
}
|
||||
}
|
||||
$('#ewww-bulk-widgets').show();
|
||||
$('#ewww-bulk-status h2').show();
|
||||
$('#ewww-bulk-last h2').show();
|
||||
if ( ewww_response.results ) {
|
||||
$('#ewww-bulk-last .inside').html( ewww_response.results );
|
||||
$('#ewww-bulk-status .inside').append( ewww_response.results );
|
||||
}
|
||||
if ( ewww_response.next_file ) {
|
||||
$('#ewww-bulk-loading').html(ewww_response.next_file);
|
||||
}
|
||||
if ( ewww_response.new_nonce ) {
|
||||
ewww_vars._wpnonce = ewww_response.new_nonce;
|
||||
}
|
||||
ewww_error_counter = 30;
|
||||
setTimeout(ewwwProcessImage, ewww_delay * 1000);
|
||||
}
|
||||
else {
|
||||
if ( ewww_response.results ) {
|
||||
$('#ewww-bulk-widgets').show();
|
||||
$('#ewww-bulk-status h2').show();
|
||||
$('#ewww-bulk-status .inside').append( ewww_response.results );
|
||||
}
|
||||
var ewww_cleanup_data = {
|
||||
action: ewww_cleanup_action,
|
||||
ewww_wpnonce: ewww_vars._wpnonce,
|
||||
};
|
||||
$.post(ajaxurl, ewww_cleanup_data, function(response) {
|
||||
$('#ewww-bulk-loading').html(response);
|
||||
$('#ewww-bulk-stop').hide();
|
||||
$('#ewww-bulk-last').hide();
|
||||
ewwwAuxCleanup();
|
||||
});
|
||||
}
|
||||
})
|
||||
.fail(function() {
|
||||
if (ewww_error_counter == 0) {
|
||||
$('#ewww-bulk-loading').html('<p class="ewww-bulk-error"><b>' + ewww_vars.operation_interrupted + ':</b> ' + ewww_vars.bulk_fail_more + '</p>');
|
||||
} else {
|
||||
$('#ewww-bulk-loading').html('<p class="ewww-bulk-error"><b>' + ewww_vars.temporary_failure + ' ' + ewww_error_counter + ' (' + ewww_vars.bulk_fail_more + ')</b></p>');
|
||||
ewww_error_counter--;
|
||||
setTimeout(function() {
|
||||
ewwwProcessImage();
|
||||
}, 1000);
|
||||
}
|
||||
});
|
||||
}
|
||||
function ewwwAuxCleanup() {
|
||||
if (ewww_main == true) {
|
||||
clearInterval(ewww_quota_update);
|
||||
clearInterval(ewww_countdown);
|
||||
var ewww_table_count_data = {
|
||||
action: ewww_table_count_action,
|
||||
ewww_wpnonce: ewww_vars._wpnonce,
|
||||
ewww_inline: 1,
|
||||
};
|
||||
$.post(ajaxurl, ewww_table_count_data, function(response) {
|
||||
ewww_vars.image_count = response;
|
||||
});
|
||||
$('#ewww-show-table').show();
|
||||
$('#ewww-table-info').show();
|
||||
$('#ewww-bulk-timer').hide();
|
||||
if (ewww_aux == true) {
|
||||
$('#ewww-aux-first').hide();
|
||||
} else {
|
||||
$('#ewww-bulk-first').hide();
|
||||
}
|
||||
ewww_attachments = ewww_vars.attachments;
|
||||
ewww_init_action = 'bulk_init';
|
||||
ewww_filename_action = 'bulk_filename';
|
||||
ewww_loop_action = 'bulk_loop';
|
||||
ewww_cleanup_action = 'bulk_cleanup';
|
||||
ewww_init_data = {
|
||||
action: ewww_init_action,
|
||||
ewww_wpnonce: ewww_vars._wpnonce,
|
||||
};
|
||||
ewww_aux = false;
|
||||
ewww_i = 0;
|
||||
ewww_force = 0;
|
||||
ewww_force_smart = 0;
|
||||
ewww_webp_only = 0;
|
||||
}
|
||||
}
|
||||
function ewwwCountDown() {
|
||||
if (ewww_time_remaining > 1) {
|
||||
ewww_time_remaining--;
|
||||
}
|
||||
ewwwTimeIncrementsUpdate();
|
||||
$('#ewww-bulk-timer').html(ewww_days_remaining + ':' + ewww_hours_remaining + ':' + ewww_minutes_remaining + ':' + ewww_seconds_remaining + ' ' + ewww_vars.time_remaining);
|
||||
}
|
||||
function ewwwTimeIncrementsUpdate() {
|
||||
ewww_days_remaining = Math.floor(ewww_time_remaining / 86400);
|
||||
ewww_hours_remaining = Math.floor((ewww_time_remaining - (ewww_days_remaining * 86400)) / 3600);
|
||||
ewww_minutes_remaining = Math.floor((ewww_time_remaining - (ewww_days_remaining * 86400) - (ewww_hours_remaining * 3600)) / 60);
|
||||
ewww_seconds_remaining = ewww_time_remaining - (ewww_days_remaining * 86400) - (ewww_hours_remaining * 3600) - (ewww_minutes_remaining * 60);
|
||||
if (ewww_days_remaining < 10) { ewww_days_remaining = '0'+ewww_days_remaining; }
|
||||
if (ewww_hours_remaining < 10) { ewww_hours_remaining = '0'+ewww_hours_remaining; }
|
||||
if (ewww_minutes_remaining < 10) { ewww_minutes_remaining = '0'+ewww_minutes_remaining; }
|
||||
if (ewww_seconds_remaining < 10) { ewww_seconds_remaining = '0'+ewww_seconds_remaining; }
|
||||
}
|
||||
});
|
730
wp-content/plugins/ewww-image-optimizer/includes/eio-settings.js
Normal file
@ -0,0 +1,730 @@
|
||||
jQuery(document).ready(function($) {
|
||||
// Wizard bits:
|
||||
$('input:radio[name="ewww_image_optimizer_budget"]').on(
|
||||
'change',
|
||||
function() {
|
||||
if (this.checked && this.value === 'pay') {
|
||||
$('.ewwwio-premium-setup').show();
|
||||
} else {
|
||||
$('.ewwwio-premium-setup').hide();
|
||||
$('#ewww-image-optimizer-warning-opt-missing').show();
|
||||
$('#ewww-image-optimizer-warning-exec').show();
|
||||
}
|
||||
}
|
||||
);
|
||||
var ewww_wizard_required_checkboxes = $('#ewwwio-wizard-step-1 :checkbox[required]');
|
||||
ewww_wizard_required_checkboxes.on(
|
||||
'change',
|
||||
function() {
|
||||
if (ewww_wizard_required_checkboxes.is(':checked')) {
|
||||
ewww_wizard_required_checkboxes.removeAttr('required');
|
||||
} else {
|
||||
ewww_wizard_required_checkboxes.attr('required', 'required');
|
||||
}
|
||||
}
|
||||
);
|
||||
$('#ewwwio-wizard-step-1').on(
|
||||
'submit',
|
||||
function() {
|
||||
return;
|
||||
$(this).hide();
|
||||
$('#ewwwio-wizard-step-2').show();
|
||||
return false;
|
||||
}
|
||||
);
|
||||
$('.ewwwio-wizard-back').on(
|
||||
'click',
|
||||
function() {
|
||||
return;
|
||||
$('#ewwwio-wizard-step-2').hide();
|
||||
$('#ewwwio-wizard-step-1').show();
|
||||
return false;
|
||||
}
|
||||
);
|
||||
function removeQueryArg(url) {
|
||||
return url.split('?')[0];
|
||||
}
|
||||
$('.fade').fadeTo(5000,1).fadeOut(3000);
|
||||
var speed_bar_width = $('#ewww-speed-fill').data('score');
|
||||
$('#ewww-speed-fill').animate( {
|
||||
width: speed_bar_width + '%',
|
||||
}, 1000 );
|
||||
var ewww_save_bar_width = $('#ewww-savings-fill').data('score');
|
||||
$('#ewww-savings-fill').animate( {
|
||||
width: ewww_save_bar_width + '%',
|
||||
}, 1000 );
|
||||
var easy_save_bar_width = $('#easyio-savings-fill').data('score');
|
||||
$('#easyio-savings-fill').animate( {
|
||||
width: easy_save_bar_width + '%',
|
||||
}, 1000 );
|
||||
$('#ewww-show-recommendations a').on(
|
||||
'click',
|
||||
function() {
|
||||
$('.ewww-recommend').toggle();
|
||||
$('#ewww-show-recommendations a').toggle();
|
||||
return false;
|
||||
}
|
||||
);
|
||||
$('#ewww_image_optimizer_cloud_key').on('keydown', function(event){
|
||||
if (event.which === 13) {
|
||||
$('#ewwwio-api-activate').trigger('click');
|
||||
return false;
|
||||
}
|
||||
});
|
||||
$('#ewwwio-api-activate').on('click', function() {
|
||||
var ewww_post_action = 'ewww_cloud_key_verify';
|
||||
var ewww_post_data = {
|
||||
action: ewww_post_action,
|
||||
compress_api_key: $('#ewww_image_optimizer_cloud_key').val(),
|
||||
ewww_wpnonce: ewww_vars._wpnonce,
|
||||
};
|
||||
$('#ewwwio-api-activate').hide();
|
||||
$('#ewwwio-api-activation-processing').show();
|
||||
$('#ewwwio-api-activation-result').hide();
|
||||
$.post(ajaxurl, ewww_post_data, function(response) {
|
||||
try {
|
||||
var ewww_response = JSON.parse(response);
|
||||
} catch (err) {
|
||||
$('#ewwwio-api-activation-processing').hide();
|
||||
$('#ewwwio-api-activation-result').html(ewww_vars.invalid_response);
|
||||
$('#ewwwio-api-activation-result').addClass('error');
|
||||
$('#ewwwio-api-activation-result').show();
|
||||
console.log( response );
|
||||
return false;
|
||||
}
|
||||
if ( ewww_response.error ) {
|
||||
$('#ewwwio-api-activation-processing').hide();
|
||||
$('#ewwwio-api-activate').show();
|
||||
$('#ewwwio-api-activation-result').html(ewww_response.error);
|
||||
$('#ewwwio-api-activation-result').addClass('error');
|
||||
$('#ewwwio-api-activation-result').show();
|
||||
} else if ( ! ewww_response.success ) {
|
||||
$('#ewwwio-api-activation-processing').hide();
|
||||
$('#ewwwio-api-activation-result').html(ewww_vars.invalid_response);
|
||||
$('#ewwwio-api-activation-result').addClass('error');
|
||||
$('#ewwwio-api-activation-result').show();
|
||||
console.log( response );
|
||||
} else {
|
||||
$('#ewwwio-api-activation-processing').hide();
|
||||
$('#ewwwio-api-activate').html('<span class="dashicons dashicons-yes"></span>');
|
||||
$('#ewwwio-api-activate').show();
|
||||
$('#ewwwio-api-activation-result').html(ewww_response.success);
|
||||
$('#ewwwio-api-activation-result').removeClass('error');
|
||||
$('#ewwwio-api-activation-result').show();
|
||||
$('.easyio-manual-ui').hide();
|
||||
$('.easyio-cloud-key-ui').show();
|
||||
$('#ewww_image_optimizer_cloud_key').attr('type', 'password');
|
||||
ewww_vars.easy_autoreg = 1;
|
||||
ewwwCloudEnable();
|
||||
}
|
||||
});
|
||||
return false;
|
||||
});
|
||||
function ewwwCloudEnable() {
|
||||
if (
|
||||
$('#ewww_image_optimizer_jpg_level').val() < 20 &&
|
||||
$('#ewww_image_optimizer_png_level').val() < 20 &&
|
||||
$('#ewww_image_optimizer_gif_level').val() < 20 &&
|
||||
$('#ewww_image_optimizer_pdf_level').val() < 10
|
||||
) {
|
||||
$('#ewww_image_optimizer_jpg_level option').prop('disabled', false);
|
||||
$('#ewww_image_optimizer_png_level option').prop('disabled', false);
|
||||
$('#ewww_image_optimizer_pdf_level option').prop('disabled', false);
|
||||
$('#ewww_image_optimizer_svg_level option').prop('disabled', false);
|
||||
$('#ewww_image_optimizer_backup_files option').prop('disabled', false);
|
||||
$('#ewww_image_optimizer_jpg_level').val(30);
|
||||
$('#ewww_image_optimizer_png_level').val(20);
|
||||
$('#ewww_image_optimizer_gif_level').val(10);
|
||||
$('#ewww_image_optimizer_pdf_level').val(10);
|
||||
$('#ewww_image_optimizer_svg_level').val(10);
|
||||
}
|
||||
}
|
||||
var easyio_registration_error = '';
|
||||
$('#ewwwio-easy-activate').on( 'click', function() {
|
||||
$('#ewwwio-easy-activate').hide();
|
||||
$('#ewwwio-easy-deregister').hide();
|
||||
$('#ewwwio-easy-activation-result').hide();
|
||||
$('#ewwwio-easy-activation-processing').show();
|
||||
if (! ewww_vars.easyio_site_registered && ewww_vars.easy_autoreg) {
|
||||
var ewww_post_data = {
|
||||
action: 'ewww_exactdn_register_site',
|
||||
ewww_wpnonce: ewww_vars._wpnonce,
|
||||
blog_id: ewww_vars.blog_id,
|
||||
};
|
||||
$.post(ajaxurl, ewww_post_data, function(response) {
|
||||
try {
|
||||
var ewww_response = JSON.parse(response);
|
||||
} catch (err) {
|
||||
$('#ewwwio-easy-activation-processing').hide();
|
||||
$('#ewwwio-easy-activation-result').html(ewww_vars.invalid_response);
|
||||
$('#ewwwio-easy-activation-result').addClass('error');
|
||||
$('#ewwwio-easy-activation-result').show();
|
||||
console.log( 'registration response: ' + response );
|
||||
return false;
|
||||
}
|
||||
if ( ewww_response.error ) {
|
||||
easyio_registration_error = ewww_response.error;
|
||||
} else if ( ! ewww_response.status ) {
|
||||
$('#ewwwio-easy-activation-processing').hide();
|
||||
$('#ewwwio-easy-activation-result').html(ewww_vars.invalid_response);
|
||||
$('#ewwwio-easy-activation-result').addClass('error');
|
||||
$('#ewwwio-easy-activation-result').show();
|
||||
console.log( 'registration response: ' + response );
|
||||
return false;
|
||||
}
|
||||
setTimeout( activateExactDNSite, 5000 );
|
||||
return false;
|
||||
});
|
||||
} else {
|
||||
activateExactDNSite();
|
||||
return false;
|
||||
}
|
||||
return false;
|
||||
});
|
||||
function activateExactDNSite() {
|
||||
var ewww_post_action = 'ewww_exactdn_activate';
|
||||
var ewww_post_data = {
|
||||
action: ewww_post_action,
|
||||
ewww_wpnonce: ewww_vars._wpnonce,
|
||||
};
|
||||
$.post(ajaxurl, ewww_post_data, function(response) {
|
||||
try {
|
||||
var ewww_response = JSON.parse(response);
|
||||
} catch (err) {
|
||||
$('#ewwwio-easy-activation-processing').hide();
|
||||
$('#ewwwio-easy-activation-result').html(ewww_vars.invalid_response);
|
||||
$('#ewwwio-easy-activation-result').addClass('error');
|
||||
$('#ewwwio-easy-activation-result').show();
|
||||
console.log( response );
|
||||
return false;
|
||||
}
|
||||
if ( ewww_response.error ) {
|
||||
if ( easyio_registration_error ) {
|
||||
ewww_response.error = easyio_registration_error + '<br>' + ewww_response.error;
|
||||
}
|
||||
$('#ewwwio-easy-activation-processing').hide();
|
||||
$('#ewwwio-easy-activate').show();
|
||||
$('#ewwwio-easy-activation-result').html(ewww_response.error);
|
||||
$('#ewwwio-easy-activation-result').addClass('error');
|
||||
$('#ewwwio-easy-activation-result').show();
|
||||
} else if ( ! ewww_response.success ) {
|
||||
$('#ewwwio-easy-activation-processing').hide();
|
||||
$('#ewwwio-easy-activation-result').html(ewww_vars.invalid_response);
|
||||
$('#ewwwio-easy-activation-result').addClass('error');
|
||||
$('#ewwwio-easy-activation-result').show();
|
||||
console.log( response );
|
||||
} else {
|
||||
$('#ewwwio-easy-activation-processing').hide();
|
||||
$('#ewwwio-easy-activation-result').html(ewww_response.success);
|
||||
$('#ewwwio-easy-activation-result').removeClass('error');
|
||||
$('#ewwwio-easy-activation-result').show();
|
||||
$('.ewwwio-exactdn-options input').prop('disabled', false);
|
||||
$('.ewwwio-exactdn-options').show();
|
||||
$('.ewwwio-easy-setup-instructions').hide();
|
||||
$('#ewww_image_optimizer_webp_container').hide();
|
||||
$('.ewww_image_optimizer_webp_setting_container').hide();
|
||||
$('.ewww_image_optimizer_webp_rewrite_setting_container').hide();
|
||||
$('#ewww_image_optimizer_webp_easyio_container').show();
|
||||
}
|
||||
});
|
||||
return false;
|
||||
}
|
||||
var exactdn_blog_ids = [];
|
||||
var exactdn_blog_count = 0;
|
||||
var exactdn_cancelled = false;
|
||||
$('#ewwwio-easy-activate-network').on( 'click', function() {
|
||||
if (!confirm(ewww_vars.exactdn_network_warning)) {
|
||||
return false;
|
||||
}
|
||||
exactdn_blog_ids = Array.from(ewww_vars.network_blog_ids);
|
||||
exactdn_blog_count = exactdn_blog_ids.length;
|
||||
$('#ewww_image_optimizer_exactdn_container .button-secondary').hide();
|
||||
$('#ewwwio-easy-cancel-network-operation').show();
|
||||
$('#ewwwio-easy-activation-result').hide();
|
||||
$('#ewwwio-easy-activation-processing').show();
|
||||
$('#ewwwio-easy-activation-progressbar').progressbar({ max: exactdn_blog_count });
|
||||
$('#ewwwio-easy-activation-progressbar').show();
|
||||
activateExactDNMultiSite();
|
||||
return false;
|
||||
});
|
||||
function activateExactDNMultiSite() {
|
||||
var ewww_post_data = {
|
||||
action: 'ewww_exactdn_activate_site',
|
||||
ewww_wpnonce: ewww_vars._wpnonce,
|
||||
blog_id: exactdn_blog_ids.pop(),
|
||||
};
|
||||
$.post(ajaxurl, ewww_post_data, function(response) {
|
||||
try {
|
||||
var ewww_response = JSON.parse(response);
|
||||
} catch (err) {
|
||||
$('#ewwwio-easy-activation-processing').hide();
|
||||
$('#ewwwio-easy-activation-result').html(ewww_vars.invalid_response);
|
||||
$('#ewwwio-easy-activation-result').addClass('error');
|
||||
$('#ewwwio-easy-activation-result').show();
|
||||
$('#ewwwio-easy-cancel-network-operation').hide();
|
||||
console.log( response );
|
||||
return false;
|
||||
}
|
||||
var exactdn_blogs_done = exactdn_blog_count - exactdn_blog_ids.length;
|
||||
if ( ewww_response.error ) {
|
||||
$('#ewwwio-easy-activation-processing').hide();
|
||||
$('#ewwwio-easy-activation-errors').append('<p>' + ewww_response.error + '</p>');
|
||||
$('#ewwwio-easy-activation-errors').show();
|
||||
$('#ewwwio-easy-activation-progressbar').progressbar('option', 'value', exactdn_blogs_done);
|
||||
} else if ( ! ewww_response.success ) {
|
||||
$('#ewwwio-easy-activate-network').show();
|
||||
$('#ewwwio-easy-activation-processing').hide();
|
||||
$('#ewwwio-easy-activation-result').html(ewww_vars.invalid_response);
|
||||
$('#ewwwio-easy-activation-result').addClass('error');
|
||||
$('#ewwwio-easy-activation-result').show();
|
||||
$('#ewwwio-easy-cancel-network-operation').hide();
|
||||
console.log( response );
|
||||
return false;
|
||||
} else {
|
||||
$('#ewwwio-easy-activation-processing').hide();
|
||||
$('.ewwwio-easy-setup-instructions').hide();
|
||||
$('p.ewwwio-easy-description').hide();
|
||||
$('#ewwwio-easy-activation-progressbar').progressbar('option', 'value', exactdn_blogs_done);
|
||||
}
|
||||
if ( exactdn_blog_ids.length ) {
|
||||
activateExactDNMultiSite();
|
||||
} else {
|
||||
$('#ewwwio-easy-cancel-network-operation').hide();
|
||||
if (exactdn_cancelled) {
|
||||
$('#ewwwio-easy-activation-result').html(ewww_vars.operation_stopped);
|
||||
} else {
|
||||
$('#ewwwio-easy-activation-result').html(ewww_vars.exactdn_network_success);
|
||||
}
|
||||
$('#ewwwio-easy-activation-result').removeClass('error');
|
||||
$('#ewwwio-easy-activation-result').show();
|
||||
$('.ewwwio-exactdn-options input').prop('disabled', false);
|
||||
$('.ewwwio-exactdn-options').show();
|
||||
$('#ewwwio-easy-activation-progressbar').hide();
|
||||
$('#ewww_image_optimizer_webp_container').hide();
|
||||
$('.ewww_image_optimizer_webp_setting_container').hide();
|
||||
$('.ewww_image_optimizer_webp_rewrite_setting_container').hide();
|
||||
$('#ewww_image_optimizer_webp_easyio_container').show();
|
||||
}
|
||||
});
|
||||
return false;
|
||||
}
|
||||
$('#ewwwio-easy-register-network').on( 'click', function() {
|
||||
if (!confirm(ewww_vars.easyio_register_warning)) {
|
||||
return false;
|
||||
}
|
||||
exactdn_blog_ids = Array.from(ewww_vars.network_blog_ids);
|
||||
exactdn_blog_count = exactdn_blog_ids.length;
|
||||
$('#ewww_image_optimizer_exactdn_container .button-secondary').hide();
|
||||
$('#ewwwio-easy-cancel-network-operation').show();
|
||||
$('#ewwwio-easy-activation-result').hide();
|
||||
$('#ewwwio-easy-activation-processing').show();
|
||||
$('#ewwwio-easy-activation-progressbar').progressbar({ max: exactdn_blog_count });
|
||||
$('#ewwwio-easy-activation-progressbar').show();
|
||||
registerExactDNSite();
|
||||
return false;
|
||||
});
|
||||
function registerExactDNSite() {
|
||||
var ewww_post_data = {
|
||||
action: 'ewww_exactdn_register_site',
|
||||
ewww_wpnonce: ewww_vars._wpnonce,
|
||||
blog_id: exactdn_blog_ids.pop(),
|
||||
};
|
||||
$.post(ajaxurl, ewww_post_data, function(response) {
|
||||
try {
|
||||
var ewww_response = JSON.parse(response);
|
||||
} catch (err) {
|
||||
$('#ewwwio-easy-activation-processing').hide();
|
||||
$('#ewwwio-easy-activation-result').html(ewww_vars.invalid_response);
|
||||
$('#ewwwio-easy-activation-result').addClass('error');
|
||||
$('#ewwwio-easy-activation-result').show();
|
||||
$('#ewwwio-easy-cancel-network-operation').hide();
|
||||
console.log( response );
|
||||
return false;
|
||||
}
|
||||
var exactdn_blogs_done = exactdn_blog_count - exactdn_blog_ids.length;
|
||||
if ( ewww_response.error ) {
|
||||
$('#ewwwio-easy-activation-processing').hide();
|
||||
$('#ewwwio-easy-register-network').show();
|
||||
$('#ewwwio-easy-activation-result').html(ewww_response.error);
|
||||
$('#ewwwio-easy-activation-result').addClass('error');
|
||||
$('#ewwwio-easy-activation-result').show();
|
||||
$('#ewwwio-easy-cancel-network-operation').hide();
|
||||
return false;
|
||||
} else if ( ! ewww_response.status ) {
|
||||
$('#ewwwio-easy-activation-processing').hide();
|
||||
$('#ewwwio-easy-activation-result').html(ewww_vars.invalid_response);
|
||||
$('#ewwwio-easy-activation-result').addClass('error');
|
||||
$('#ewwwio-easy-activation-result').show();
|
||||
$('#ewwwio-easy-cancel-network-operation').hide();
|
||||
console.log( response );
|
||||
return false;
|
||||
} else {
|
||||
$('#ewwwio-easy-activation-processing').hide();
|
||||
$('.ewwwio-easy-setup-instructions').hide();
|
||||
$('p.ewwwio-easy-description').hide();
|
||||
$('#ewwwio-easy-activation-progressbar').progressbar('option', 'value', exactdn_blogs_done);
|
||||
}
|
||||
if ( exactdn_blog_ids.length ) {
|
||||
registerExactDNSite();
|
||||
} else {
|
||||
if (exactdn_cancelled) {
|
||||
$('#ewwwio-easy-activation-result').html(ewww_vars.operation_stopped);
|
||||
} else {
|
||||
$('#ewwwio-easy-activation-result').html(ewww_vars.easyio_register_success);
|
||||
}
|
||||
$('#ewwwio-easy-activation-result').removeClass('error');
|
||||
$('#ewwwio-easy-activation-result').show();
|
||||
$('#ewwwio-easy-cancel-network-operation').hide();
|
||||
$('#ewwwio-easy-activation-progressbar').hide();
|
||||
$('#ewwwio-easy-activate-network').show();
|
||||
}
|
||||
});
|
||||
return false;
|
||||
}
|
||||
$('#ewwwio-easy-cancel-network-operation').on('click', function() {
|
||||
exactdn_blog_ids = [];
|
||||
exactdn_cancelled = true;
|
||||
$('#ewwwio-easy-cancel-network-operation').hide();
|
||||
return false;
|
||||
});
|
||||
$('#ewwwio-easy-deregister').on( 'click', function() {
|
||||
if (!confirm(ewww_vars.easyio_deregister_warning)) {
|
||||
return false;
|
||||
}
|
||||
$('#ewwwio-easy-activate').hide();
|
||||
$('#ewwwio-easy-deregister').hide();
|
||||
$('#ewwwio-easy-activation-result').hide();
|
||||
$('#ewwwio-easy-activation-processing').show();
|
||||
if (ewww_vars.easyio_site_id) {
|
||||
deregisterExactDNSite();
|
||||
} else {
|
||||
$('#ewwwio-easy-activation-processing').hide();
|
||||
$('#ewwwio-easy-activation-result').html(ewww_vars.invalid_response);
|
||||
$('#ewwwio-easy-activation-result').addClass('error');
|
||||
$('#ewwwio-easy-activation-result').show();
|
||||
}
|
||||
return false;
|
||||
});
|
||||
function deregisterExactDNSite() {
|
||||
var ewww_post_data = {
|
||||
action: 'ewww_exactdn_deregister_site',
|
||||
ewww_wpnonce: ewww_vars._wpnonce,
|
||||
site_id: ewww_vars.easyio_site_id,
|
||||
};
|
||||
$.post(ajaxurl, ewww_post_data, function(response) {
|
||||
try {
|
||||
var ewww_response = JSON.parse(response);
|
||||
} catch (err) {
|
||||
$('#ewwwio-easy-activation-processing').hide();
|
||||
$('#ewwwio-easy-activation-result').html(ewww_vars.invalid_response);
|
||||
$('#ewwwio-easy-activation-result').addClass('error');
|
||||
$('#ewwwio-easy-activation-result').show();
|
||||
console.log( 'de-registration response: ' + response );
|
||||
return false;
|
||||
}
|
||||
if ( ewww_response.error ) {
|
||||
$('#ewwwio-easy-activation-processing').hide();
|
||||
$('#ewwwio-easy-activation-result').html(ewww_response.error);
|
||||
$('#ewwwio-easy-activation-result').addClass('error');
|
||||
$('#ewwwio-easy-activation-result').show();
|
||||
} else if ( ! ewww_response.success ) {
|
||||
$('#ewwwio-easy-activation-processing').hide();
|
||||
$('#ewwwio-easy-activation-result').html(ewww_vars.invalid_response);
|
||||
$('#ewwwio-easy-activation-result').addClass('error');
|
||||
$('#ewwwio-easy-activation-result').show();
|
||||
console.log( 'de-registration response: ' + response );
|
||||
} else {
|
||||
$('#ewwwio-easy-activation-processing').hide();
|
||||
$('#ewwwio-easy-activation-result').html(ewww_response.success);
|
||||
$('#ewwwio-easy-activation-result').removeClass('error');
|
||||
$('#ewwwio-easy-activation-result').show();
|
||||
}
|
||||
});
|
||||
return false;
|
||||
}
|
||||
$('#ewww_image_optimizer_webp').on(
|
||||
'click',
|
||||
function() {
|
||||
if ( $(this).prop('checked') && ewww_vars.save_space ) {
|
||||
$('#ewwwio-webp-storage-warning').fadeIn();
|
||||
return false;
|
||||
} else if ($(this).prop('checked')) {
|
||||
$('.ewww_image_optimizer_webp_setting_container').fadeIn();
|
||||
if ($('#ewww_image_optimizer_webp_for_cdn').prop('checked') || $('#ewww_image_optimizer_picture_webp').prop('checked')) {
|
||||
$('.ewww_image_optimizer_webp_rewrite_setting_container').fadeIn();
|
||||
}
|
||||
} else {
|
||||
$('.ewww_image_optimizer_webp_setting_container').fadeOut();
|
||||
$('.ewww_image_optimizer_webp_rewrite_setting_container').fadeOut();
|
||||
}
|
||||
}
|
||||
);
|
||||
$('#ewwwio-cancel-webp').on(
|
||||
'click',
|
||||
function() {
|
||||
$('#ewwwio-webp-storage-warning').fadeOut();
|
||||
return false;
|
||||
}
|
||||
);
|
||||
$('#ewwwio-easyio-webp-info').on(
|
||||
'click',
|
||||
function() {
|
||||
$('#ewwwio-webp-storage-warning').fadeOut();
|
||||
$('.ewwwio-premium-setup').show();
|
||||
}
|
||||
)
|
||||
$('#ewwwio-confirm-webp').on(
|
||||
'click',
|
||||
function() {
|
||||
$('#ewwwio-webp-storage-warning').fadeOut();
|
||||
$('#ewww_image_optimizer_webp').prop('checked', true);
|
||||
$('.ewww_image_optimizer_webp_setting_container').fadeIn();
|
||||
if ($('#ewww_image_optimizer_webp_for_cdn').prop('checked') || $('#ewww_image_optimizer_picture_webp').prop('checked')) {
|
||||
$('.ewww_image_optimizer_webp_rewrite_setting_container').fadeIn();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
);
|
||||
$('#ewww-webp-rewrite #ewww-webp-insert').on( 'click', function() {
|
||||
var ewww_webp_rewrite_action = 'ewww_webp_rewrite';
|
||||
var ewww_webp_rewrite_data = {
|
||||
action: ewww_webp_rewrite_action,
|
||||
ewww_wpnonce: ewww_vars._wpnonce,
|
||||
};
|
||||
$.post(ajaxurl, ewww_webp_rewrite_data, function(response) {
|
||||
$('#ewww-webp-rewrite-result').html(response);
|
||||
$('#ewww-webp-rewrite-result').show();
|
||||
$('#ewww-webp-rewrite-status').hide();
|
||||
$('#webp-rewrite-rules').hide();
|
||||
$('#ewww-webp-insert').hide();
|
||||
ewww_webp_image = document.getElementById('ewww-webp-image').src;
|
||||
document.getElementById('ewww-webp-image').src = removeQueryArg(ewww_webp_image) + '?m=' + new Date().getTime();
|
||||
});
|
||||
return false;
|
||||
});
|
||||
$('#ewww-webp-rewrite #ewww-webp-remove').on( 'click', function() {
|
||||
var ewww_webp_rewrite_action = 'ewww_webp_unwrite';
|
||||
var ewww_webp_rewrite_data = {
|
||||
action: ewww_webp_rewrite_action,
|
||||
ewww_wpnonce: ewww_vars._wpnonce,
|
||||
};
|
||||
$.post(ajaxurl, ewww_webp_rewrite_data, function(response) {
|
||||
$('#ewww-webp-rewrite-result').html(response);
|
||||
$('#ewww-webp-rewrite-result').show();
|
||||
$('#ewww-webp-rewrite-status').hide();
|
||||
$('#ewww-webp-remove').hide();
|
||||
ewww_webp_image = document.getElementById('ewww-webp-image').src;
|
||||
document.getElementById('ewww-webp-image').src = removeQueryArg(ewww_webp_image) + '?m' + new Date().getTime();
|
||||
});
|
||||
return false;
|
||||
});
|
||||
$('#exactdn_site_url').on( 'mouseenter',
|
||||
function() {
|
||||
$('#exactdn-site-url-copy').fadeIn();
|
||||
}
|
||||
);
|
||||
$('#exactdn_site_url').on( 'mouseleave',
|
||||
function() {
|
||||
$('#exactdn-site-url-copy').fadeOut();
|
||||
$('#exactdn-site-url-copied').fadeOut();
|
||||
}
|
||||
);
|
||||
$('#exactdn_site_url').on( 'click', function() {
|
||||
this.select();
|
||||
this.setSelectionRange(0,300); // For mobile.
|
||||
try {
|
||||
var successful = document.execCommand('copy');
|
||||
if ( successful ) {
|
||||
unselectText();
|
||||
$('#exactdn-site-url-copy').hide();
|
||||
$('#exactdn-site-url-copied').fadeIn();
|
||||
}
|
||||
} catch(err) {
|
||||
console.log('browser cannot copy');
|
||||
console.log(err);
|
||||
}
|
||||
});
|
||||
$('#ewww_image_optimizer_exactdn').on( 'click', function() {
|
||||
if($(this).prop('checked')) {
|
||||
$('.ewwwio-exactdn-options').show();
|
||||
} else {
|
||||
$('.ewwwio-exactdn-options').hide();
|
||||
}
|
||||
});
|
||||
$('#ewww_image_optimizer_lazy_load').on( 'click', function() {
|
||||
if($(this).prop('checked')) {
|
||||
$('#ewww_image_optimizer_ll_exclude_container').fadeIn();
|
||||
$('#ewww_image_optimizer_ll_autoscale_container').fadeIn();
|
||||
$('#ewww_image_optimizer_ll_all_things_container').fadeIn();
|
||||
$('#ewww_image_optimizer_siip_container').fadeIn();
|
||||
$('#ewww_image_optimizer_lqip_container').fadeIn();
|
||||
} else {
|
||||
$('#ewww_image_optimizer_ll_exclude_container').fadeOut();
|
||||
$('#ewww_image_optimizer_ll_autoscale_container').fadeOut();
|
||||
$('#ewww_image_optimizer_ll_all_things_container').fadeOut();
|
||||
$('#ewww_image_optimizer_siip_container').fadeOut();
|
||||
$('#ewww_image_optimizer_lqip_container').fadeOut();
|
||||
}
|
||||
});
|
||||
$('#ewww_image_optimizer_webp_for_cdn, #ewww_image_optimizer_picture_webp').on(
|
||||
'click',
|
||||
function() {
|
||||
if ( $(this).prop('checked') && ewww_vars.cloud_media ) {
|
||||
var webp_delivery_confirm = confirm(ewww_vars.webp_cloud_warning);
|
||||
if (! webp_delivery_confirm) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if ( ! $('#ewww_image_optimizer_webp_for_cdn').prop('checked') && ! $('#ewww_image_optimizer_picture_webp').prop('checked') ) {
|
||||
$('.ewww_image_optimizer_webp_rewrite_setting_container').fadeOut();
|
||||
} else {
|
||||
$('.ewww_image_optimizer_webp_rewrite_setting_container').fadeIn();
|
||||
}
|
||||
}
|
||||
);
|
||||
//$('#ewww-webp-settings').hide();
|
||||
//$('#ewww-exactdn-settings').hide();
|
||||
$('#ewww-general-settings').show();
|
||||
$('li.ewww-general-nav').addClass('ewww-selected');
|
||||
if($('#ewww_image_optimizer_debug').length){
|
||||
$('#ewww-resize-settings').hide();
|
||||
}
|
||||
// New tabs.
|
||||
$('#ewww-local-settings').hide();
|
||||
$('#ewww-advanced-settings').hide();
|
||||
|
||||
//$('#ewww-optimization-settings').hide();
|
||||
$('#ewww-conversion-settings').hide();
|
||||
$('#ewww-support-settings').hide();
|
||||
$('#ewww-contribute-settings').hide();
|
||||
$('.ewww-webp-nav').on('click', function() {
|
||||
$('.ewww-tab-nav li').removeClass('ewww-selected');
|
||||
$('li.ewww-webp-nav').addClass('ewww-selected');
|
||||
$('.ewww-tab a').trigger('blur');
|
||||
$('#ewww-webp-settings').show();
|
||||
$('#ewww-general-settings').hide();
|
||||
$('#ewww-local-settings').hide();
|
||||
$('#ewww-advanced-settings').hide();
|
||||
$('#ewww-resize-settings').hide();
|
||||
$('#ewww-conversion-settings').hide();
|
||||
$('#ewww-support-settings').hide();
|
||||
$('#ewww-contribute-settings').hide();
|
||||
});
|
||||
$('.ewww-general-nav').on('click', function() {
|
||||
$('.ewww-tab-nav li').removeClass('ewww-selected');
|
||||
$('li.ewww-general-nav').addClass('ewww-selected');
|
||||
$('.ewww-tab a').trigger('blur');
|
||||
$('#ewww-webp-settings').hide();
|
||||
$('#ewww-general-settings').show();
|
||||
$('#ewww-local-settings').hide();
|
||||
$('#ewww-advanced-settings').hide();
|
||||
$('#ewww-resize-settings').hide();
|
||||
$('#ewww-conversion-settings').hide();
|
||||
$('#ewww-support-settings').hide();
|
||||
$('#ewww-contribute-settings').hide();
|
||||
});
|
||||
$('.ewww-exactdn-nav').on('click', function() {
|
||||
$('.ewww-tab-nav li').removeClass('ewww-selected');
|
||||
$('li.ewww-exactdn-nav').addClass('ewww-selected');
|
||||
$('.ewww-tab a').trigger('blur');
|
||||
$('#ewww-webp-settings').hide();
|
||||
$('#ewww-general-settings').hide();
|
||||
$('#ewww-exactdn-settings').show();
|
||||
$('#ewww-optimization-settings').hide();
|
||||
$('#ewww-resize-settings').hide();
|
||||
$('#ewww-conversion-settings').hide();
|
||||
$('#ewww-support-settings').hide();
|
||||
$('#ewww-contribute-settings').hide();
|
||||
});
|
||||
$('.ewww-optimization-nav').on('click', function() {
|
||||
$('.ewww-tab-nav li').removeClass('ewww-selected');
|
||||
$('li.ewww-optimization-nav').addClass('ewww-selected');
|
||||
$('.ewww-tab a').trigger('blur');
|
||||
$('#ewww-webp-settings').hide();
|
||||
$('#ewww-general-settings').hide();
|
||||
$('#ewww-exactdn-settings').hide();
|
||||
$('#ewww-optimization-settings').show();
|
||||
$('#ewww-resize-settings').hide();
|
||||
$('#ewww-conversion-settings').hide();
|
||||
$('#ewww-support-settings').hide();
|
||||
$('#ewww-contribute-settings').hide();
|
||||
});
|
||||
$('.ewww-local-nav').on( 'click', function() {
|
||||
$('.ewww-tab-nav li').removeClass('ewww-selected');
|
||||
$('li.ewww-local-nav').addClass('ewww-selected');
|
||||
$('.ewww-tab a').trigger('blur');
|
||||
$('#ewww-webp-settings').hide();
|
||||
$('#ewww-general-settings').hide();
|
||||
$('#ewww-local-settings').show();
|
||||
$('#ewww-advanced-settings').hide();
|
||||
$('#ewww-resize-settings').hide();
|
||||
$('#ewww-conversion-settings').hide();
|
||||
$('#ewww-support-settings').hide();
|
||||
$('#ewww-contribute-settings').hide();
|
||||
});
|
||||
$('.ewww-advanced-nav').on( 'click', function() {
|
||||
$('.ewww-tab-nav li').removeClass('ewww-selected');
|
||||
$('li.ewww-advanced-nav').addClass('ewww-selected');
|
||||
$('.ewww-tab a').trigger('blur');
|
||||
$('#ewww-webp-settings').hide();
|
||||
$('#ewww-general-settings').hide();
|
||||
$('#ewww-local-settings').hide();
|
||||
$('#ewww-advanced-settings').show();
|
||||
$('#ewww-resize-settings').hide();
|
||||
$('#ewww-conversion-settings').hide();
|
||||
$('#ewww-support-settings').hide();
|
||||
$('#ewww-contribute-settings').hide();
|
||||
});
|
||||
$('.ewww-resize-nav').on( 'click', function() {
|
||||
$('.ewww-tab-nav li').removeClass('ewww-selected');
|
||||
$('li.ewww-resize-nav').addClass('ewww-selected');
|
||||
$('.ewww-tab a').trigger('blur');
|
||||
$('#ewww-webp-settings').hide();
|
||||
$('#ewww-general-settings').hide();
|
||||
$('#ewww-local-settings').hide();
|
||||
$('#ewww-advanced-settings').hide();
|
||||
$('#ewww-resize-settings').show();
|
||||
$('#ewww-conversion-settings').hide();
|
||||
$('#ewww-support-settings').hide();
|
||||
$('#ewww-contribute-settings').hide();
|
||||
});
|
||||
$('.ewww-conversion-nav').on( 'click', function() {
|
||||
$('.ewww-tab-nav li').removeClass('ewww-selected');
|
||||
$('li.ewww-conversion-nav').addClass('ewww-selected');
|
||||
$('.ewww-tab a').trigger('blur');
|
||||
$('#ewww-webp-settings').hide();
|
||||
$('#ewww-general-settings').hide();
|
||||
$('#ewww-local-settings').hide();
|
||||
$('#ewww-advanced-settings').hide();
|
||||
$('#ewww-resize-settings').hide();
|
||||
$('#ewww-conversion-settings').show();
|
||||
$('#ewww-support-settings').hide();
|
||||
$('#ewww-contribute-settings').hide();
|
||||
});
|
||||
$('.ewww-support-nav').on( 'click', function() {
|
||||
$('.ewww-tab-nav li').removeClass('ewww-selected');
|
||||
$('li.ewww-support-nav').addClass('ewww-selected');
|
||||
$('.ewww-tab a').trigger('blur');
|
||||
$('#ewww-webp-settings').hide();
|
||||
$('#ewww-general-settings').hide();
|
||||
$('#ewww-local-settings').hide();
|
||||
$('#ewww-advanced-settings').hide();
|
||||
$('#ewww-resize-settings').hide();
|
||||
$('#ewww-conversion-settings').hide();
|
||||
$('#ewww-support-settings').show();
|
||||
$('#ewww-contribute-settings').hide();
|
||||
});
|
||||
$('.ewww-contribute-nav').on( 'click', function() {
|
||||
$('.ewww-tab-nav li').removeClass('ewww-selected');
|
||||
$('li.ewww-contribute-nav').addClass('ewww-selected');
|
||||
$('.ewww-tab a').trigger('blur');
|
||||
$('#ewww-webp-settings').hide();
|
||||
$('#ewww-general-settings').hide();
|
||||
$('#ewww-local-settings').hide();
|
||||
$('#ewww-advanced-settings').hide();
|
||||
$('#ewww-resize-settings').hide();
|
||||
$('#ewww-conversion-settings').hide();
|
||||
$('#ewww-support-settings').hide();
|
||||
$('#ewww-contribute-settings').show();
|
||||
});
|
||||
});
|
712
wp-content/plugins/ewww-image-optimizer/includes/eio-tools.js
Normal file
@ -0,0 +1,712 @@
|
||||
jQuery(document).ready(function($) {
|
||||
var ewww_table_action = 'bulk_aux_images_table';
|
||||
var ewww_total_pages = 0;
|
||||
var ewww_pointer = 0;
|
||||
var ewww_search_total = 0;
|
||||
var ewww_clean_meta_total = 0;
|
||||
var ewww_table_debug = 0;
|
||||
$('#ewww-show-table').on('submit',function() {
|
||||
ewww_pointer = 0;
|
||||
ewww_total_pages = Math.ceil(ewww_vars.image_count / 50);
|
||||
$('.displaying-num').text(ewww_vars.count_string);
|
||||
$('#ewww-table-info').hide();
|
||||
$('#ewww-show-table').hide();
|
||||
$('#ewww-debug-table-info').hide();
|
||||
$('#ewww-show-debug-table').hide();
|
||||
var ewww_table_data = {
|
||||
action: ewww_table_action,
|
||||
ewww_wpnonce: ewww_vars._wpnonce,
|
||||
ewww_offset: ewww_pointer,
|
||||
ewww_debug: ewww_table_debug,
|
||||
ewww_total_pages: ewww_total_pages,
|
||||
};
|
||||
$.post(ajaxurl, ewww_table_data, function(response) {
|
||||
try {
|
||||
var ewww_response = JSON.parse(response);
|
||||
} catch (err) {
|
||||
$('#ewww-bulk-table').html('<span style="color: red"><b>' + ewww_vars.invalid_response + '</b></span>');
|
||||
console.log( response );
|
||||
return false;
|
||||
}
|
||||
if ( ewww_response.error ) {
|
||||
$('#ewww-bulk-table').html('<span style="color: red"><b>' + ewww_response.error + '</b></span>');
|
||||
return false;
|
||||
}
|
||||
$('#ewww-bulk-table').html(ewww_response.table);
|
||||
$('.ewww-aux-table').show();
|
||||
$('.ewww-search-count').text(ewww_response.search_result);
|
||||
$('.current-page').text(ewww_response.pagination);
|
||||
// from here
|
||||
if ( ewww_response.search_total > 0 ) {
|
||||
ewww_search_total = ewww_response.search_total;
|
||||
}
|
||||
if (ewww_response.search_count < 50) {
|
||||
$('.next-page').hide();
|
||||
$('.last-page').hide();
|
||||
}
|
||||
if (ewww_table_debug) {
|
||||
$('.displaying-num').hide();
|
||||
}
|
||||
// to here
|
||||
if (ewww_vars.image_count >= 50) {
|
||||
$('.tablenav').show();
|
||||
$('.next-page').show();
|
||||
$('.last-page').show();
|
||||
}
|
||||
});
|
||||
return false;
|
||||
});
|
||||
$('#ewww-show-debug-table').on( 'submit', function() {
|
||||
ewww_table_debug = 1;
|
||||
ewww_pointer = 0;
|
||||
$('#ewww-show-table').submit();
|
||||
document.body.scrollTop = 0; // For Safari.
|
||||
document.documentElement.scrollTop = 0; // For everyone else.
|
||||
return false;
|
||||
});
|
||||
$('.ewww-search-form').on( 'submit', function() {
|
||||
ewww_pointer = 0;
|
||||
var ewww_search = $('.ewww-search-input').val();
|
||||
var ewww_table_data = {
|
||||
action: ewww_table_action,
|
||||
ewww_wpnonce: ewww_vars._wpnonce,
|
||||
ewww_offset: ewww_pointer,
|
||||
ewww_debug: ewww_table_debug,
|
||||
ewww_total_pages: ewww_total_pages,
|
||||
ewww_search: ewww_search,
|
||||
};
|
||||
$.post(ajaxurl, ewww_table_data, function(response) {
|
||||
try {
|
||||
var ewww_response = JSON.parse(response);
|
||||
} catch (err) {
|
||||
$('#ewww-bulk-table').html('<span style="color: red"><b>' + ewww_vars.invalid_response + '</b></span>');
|
||||
console.log( response );
|
||||
return false;
|
||||
}
|
||||
if ( ewww_response.error ) {
|
||||
$('#ewww-bulk-table').html('<span style="color: red"><b>' + ewww_response.error + '</b></span>');
|
||||
return false;
|
||||
}
|
||||
$('#ewww-bulk-table').html(ewww_response.table);
|
||||
$('.ewww-search-count').text(ewww_response.search_result);
|
||||
ewww_search_total = ewww_response.search_total;
|
||||
if (ewww_response.search_count < 50) {
|
||||
$('.next-page').hide();
|
||||
$('.last-page').hide();
|
||||
}
|
||||
$('.current-page').text(ewww_response.pagination);
|
||||
});
|
||||
$('.prev-page').hide();
|
||||
$('.first-page').hide();
|
||||
$('.next-page').show();
|
||||
$('.last-page').show();
|
||||
return false;
|
||||
});
|
||||
$('.next-page').on( 'click', function() {
|
||||
var ewww_search = $('.ewww-search-input').val();
|
||||
ewww_pointer++;
|
||||
var ewww_table_data = {
|
||||
action: ewww_table_action,
|
||||
ewww_wpnonce: ewww_vars._wpnonce,
|
||||
ewww_offset: ewww_pointer,
|
||||
ewww_debug: ewww_table_debug,
|
||||
ewww_total_pages: ewww_total_pages,
|
||||
ewww_search: ewww_search,
|
||||
};
|
||||
$.post(ajaxurl, ewww_table_data, function(response) {
|
||||
try {
|
||||
var ewww_response = JSON.parse(response);
|
||||
} catch (err) {
|
||||
$('#ewww-bulk-table').html('<span style="color: red"><b>' + ewww_vars.invalid_response + '</b></span>');
|
||||
console.log( response );
|
||||
return false;
|
||||
}
|
||||
if ( ewww_response.error ) {
|
||||
$('#ewww-bulk-table').html('<span style="color: red"><b>' + ewww_response.error + '</b></span>');
|
||||
return false;
|
||||
}
|
||||
$('#ewww-bulk-table').html(ewww_response.table);
|
||||
$('.ewww-search-count').text(ewww_response.search_result);
|
||||
if (ewww_response.search_count < 50) {
|
||||
$('.next-page').hide();
|
||||
$('.last-page').hide();
|
||||
}
|
||||
$('.current-page').text(ewww_response.pagination);
|
||||
});
|
||||
if (ewww_vars.image_count <= ((ewww_pointer + 1) * 50)) {
|
||||
$('.next-page').hide();
|
||||
$('.last-page').hide();
|
||||
}
|
||||
$('.prev-page').show();
|
||||
$('.first-page').show();
|
||||
return false;
|
||||
});
|
||||
$('.prev-page').on( 'click', function() {
|
||||
var ewww_search = $('.ewww-search-input').val();
|
||||
ewww_pointer--;
|
||||
var ewww_table_data = {
|
||||
action: ewww_table_action,
|
||||
ewww_wpnonce: ewww_vars._wpnonce,
|
||||
ewww_offset: ewww_pointer,
|
||||
ewww_debug: ewww_table_debug,
|
||||
ewww_total_pages: ewww_total_pages,
|
||||
ewww_search: ewww_search,
|
||||
};
|
||||
$.post(ajaxurl, ewww_table_data, function(response) {
|
||||
try {
|
||||
var ewww_response = JSON.parse(response);
|
||||
} catch (err) {
|
||||
$('#ewww-bulk-table').html('<span style="color: red"><b>' + ewww_vars.invalid_response + '</b></span>');
|
||||
console.log( response );
|
||||
return false;
|
||||
}
|
||||
if ( ewww_response.error ) {
|
||||
$('#ewww-bulk-table').html('<span style="color: red"><b>' + ewww_response.error + '</b></span>');
|
||||
return false;
|
||||
}
|
||||
$('#ewww-bulk-table').html(ewww_response.table);
|
||||
$('.ewww-search-count').text(ewww_response.search_result);
|
||||
$('.current-page').text(ewww_response.pagination);
|
||||
});
|
||||
if (!ewww_pointer) {
|
||||
$('.prev-page').hide();
|
||||
$('.first-page').hide();
|
||||
}
|
||||
$('.next-page').show();
|
||||
$('.last-page').show();
|
||||
return false;
|
||||
});
|
||||
$('.last-page').on( 'click', function() {
|
||||
var ewww_search = $('.ewww-search-input').val();
|
||||
ewww_pointer = ewww_total_pages - 1;
|
||||
if (ewww_search || ewww_table_debug) {
|
||||
ewww_pointer = ewww_search_total - 1;
|
||||
}
|
||||
var ewww_table_data = {
|
||||
action: ewww_table_action,
|
||||
ewww_wpnonce: ewww_vars._wpnonce,
|
||||
ewww_offset: ewww_pointer,
|
||||
ewww_debug: ewww_table_debug,
|
||||
ewww_total_pages: ewww_total_pages,
|
||||
ewww_search: ewww_search,
|
||||
};
|
||||
$.post(ajaxurl, ewww_table_data, function(response) {
|
||||
try {
|
||||
var ewww_response = JSON.parse(response);
|
||||
} catch (err) {
|
||||
$('#ewww-bulk-table').html('<span style="color: red"><b>' + ewww_vars.invalid_response + '</b></span>');
|
||||
console.log( response );
|
||||
return false;
|
||||
}
|
||||
if ( ewww_response.error ) {
|
||||
$('#ewww-bulk-table').html('<span style="color: red"><b>' + ewww_response.error + '</b></span>');
|
||||
return false;
|
||||
}
|
||||
$('#ewww-bulk-table').html(ewww_response.table);
|
||||
$('.ewww-search-count').text(ewww_response.search_result);
|
||||
$('.current-page').text(ewww_response.pagination);
|
||||
});
|
||||
$('.next-page').hide();
|
||||
$('.last-page').hide();
|
||||
$('.prev-page').show();
|
||||
$('.first-page').show();
|
||||
return false;
|
||||
});
|
||||
$('.first-page').on( 'click', function() {
|
||||
ewww_pointer = 0;
|
||||
var ewww_search = $('.ewww-search-input').val();
|
||||
var ewww_table_data = {
|
||||
action: ewww_table_action,
|
||||
ewww_wpnonce: ewww_vars._wpnonce,
|
||||
ewww_offset: ewww_pointer,
|
||||
ewww_debug: ewww_table_debug,
|
||||
ewww_total_pages: ewww_total_pages,
|
||||
ewww_search: ewww_search,
|
||||
};
|
||||
$.post(ajaxurl, ewww_table_data, function(response) {
|
||||
try {
|
||||
var ewww_response = JSON.parse(response);
|
||||
} catch (err) {
|
||||
$('#ewww-bulk-table').html('<span style="color: red"><b>' + ewww_vars.invalid_response + '</b></span>');
|
||||
console.log( response );
|
||||
return false;
|
||||
}
|
||||
if ( ewww_response.error ) {
|
||||
$('#ewww-bulk-table').html('<span style="color: red"><b>' + ewww_response.error + '</b></span>');
|
||||
return false;
|
||||
}
|
||||
$('#ewww-bulk-table').html(ewww_response.table);
|
||||
$('.ewww-search-count').text(ewww_response.search_result);
|
||||
if (ewww_response.search_count < 50) {
|
||||
$('.next-page').hide();
|
||||
$('.last-page').hide();
|
||||
} else {
|
||||
$('.next-page').show();
|
||||
$('.last-page').show();
|
||||
}
|
||||
$('.prev-page').hide();
|
||||
$('.first-page').hide();
|
||||
$('.current-page').text(ewww_response.pagination);
|
||||
});
|
||||
return false;
|
||||
});
|
||||
$('#ewww-clear-table').on( 'submit', function() {
|
||||
var ewww_table_data = {
|
||||
action: 'bulk_aux_images_table_clear',
|
||||
ewww_wpnonce: ewww_vars._wpnonce,
|
||||
};
|
||||
if (confirm(ewww_vars.erase_warning)) {
|
||||
$.post(ajaxurl, ewww_table_data, function(response) {
|
||||
$('#ewww-table-info').hide();
|
||||
$('#ewww-show-table').hide();
|
||||
$('#ewww-clear-table').hide();
|
||||
$('#ewww-clear-table-info').html(response);
|
||||
});
|
||||
}
|
||||
return false;
|
||||
});
|
||||
var ewww_total_restored = 0;
|
||||
$('#ewww-restore-originals').on( 'submit', function() {
|
||||
if (!confirm(ewww_vars.tool_warning)) {
|
||||
return false;
|
||||
}
|
||||
var header_label = $(this).find('input[type="submit"]').val();
|
||||
if (header_label) {
|
||||
$('#ewwwio-tools-header').html(header_label);
|
||||
}
|
||||
$('.ewww-tool-info').hide();
|
||||
$('.ewww-tool-form').hide();
|
||||
$('.ewww-tool-divider').hide();
|
||||
$('#ewww-restore-originals-progressbar').progressbar({ max: ewww_vars.restorable_images });
|
||||
$('#ewww-restore-originals-progress').html('<p> 0/' + ewww_vars.restorable_images + '</p>');
|
||||
$('#ewww-restore-originals-progressbar').show();
|
||||
$('#ewww-restore-originals-progress').show();
|
||||
ewwwRestoreOriginals();
|
||||
return false;
|
||||
});
|
||||
function ewwwRestoreOriginals(){
|
||||
var ewww_originals_data = {
|
||||
action: 'bulk_aux_images_restore_original',
|
||||
ewww_wpnonce: ewww_vars._wpnonce,
|
||||
};
|
||||
$.post(ajaxurl, ewww_originals_data, function(response) {
|
||||
try {
|
||||
var ewww_response = JSON.parse(response);
|
||||
} catch (err) {
|
||||
$('#ewww-restore-originals-progressbar').hide();
|
||||
$('#ewww-restore-originals-progress').html('<span style="color: red"><b>' + ewww_vars.invalid_response + '</b></span>');
|
||||
console.log(err);
|
||||
console.log(response);
|
||||
return false;
|
||||
}
|
||||
if ( ewww_response.error ) {
|
||||
$('#ewww-restore-originals-progressbar').hide();
|
||||
$('#ewww-restore-originals-progress').html('<span style="color: red"><b>' + ewww_response.error + '</b></span>');
|
||||
return false;
|
||||
}
|
||||
if(ewww_response.finished) {
|
||||
$('#ewww-restore-originals-messages').append(ewww_vars.finished);
|
||||
$('#ewww-restore-originals-messages').show();
|
||||
return false;
|
||||
}
|
||||
if (ewww_response.messages) {
|
||||
$('#ewww-restore-originals-messages').append(ewww_response.messages);
|
||||
$('#ewww-restore-originals-messages').show();
|
||||
}
|
||||
ewww_total_restored += ewww_response.completed;
|
||||
$('#ewww-restore-originals-progressbar').progressbar("option", "value", ewww_total_restored);
|
||||
$('#ewww-restore-originals-progress').html('<p>' + ewww_total_restored + '/' + ewww_vars.restorable_images + '</p>');
|
||||
if ( ewww_total_restored > ewww_vars.restorable_images + 100 ) {
|
||||
$('#ewww-restore-originals-messages').append('<p><b>' + ewww_vars.too_far) + '</b></p>';
|
||||
}
|
||||
ewwwRestoreOriginals();
|
||||
});
|
||||
}
|
||||
var ewww_total_originals = 0;
|
||||
var ewww_original_attachments = false;
|
||||
$('#ewww-clean-originals').on( 'submit', function() {
|
||||
if (!confirm(ewww_vars.tool_warning)) {
|
||||
return false;
|
||||
}
|
||||
var header_label = $(this).find('input[type="submit"]').val();
|
||||
if (header_label) {
|
||||
$('#ewwwio-tools-header').html(header_label);
|
||||
}
|
||||
var ewww_originals_data = {
|
||||
action: 'ewwwio_get_all_attachments',
|
||||
ewww_wpnonce: ewww_vars._wpnonce,
|
||||
};
|
||||
$.post(ajaxurl, ewww_originals_data, function(response) {
|
||||
try {
|
||||
ewww_original_attachments = JSON.parse(response);
|
||||
} catch (err) {
|
||||
$('.ewww-tool-info').hide();
|
||||
$('.ewww-tool-form').hide();
|
||||
$('.ewww-tool-divider').hide();
|
||||
$('#ewww-clean-originals-progress').html('<span style="color: red"><b>' + ewww_vars.invalid_response + '</b></span>');
|
||||
$('#ewww-clean-originals-progress').show();
|
||||
console.log(err);
|
||||
console.log(response);
|
||||
return false;
|
||||
}
|
||||
if ( ewww_original_attachments.error ) {
|
||||
$('.ewww-tool-info').hide();
|
||||
$('.ewww-tool-form').hide();
|
||||
$('.ewww-tool-divider').hide();
|
||||
$('#ewww-clean-originals-progress').html(ewww_original_attachments.error);
|
||||
$('#ewww-clean-originals-progress').show();
|
||||
return false;
|
||||
}
|
||||
ewww_total_originals = ewww_original_attachments.length;
|
||||
$('.ewww-tool-info').hide();
|
||||
$('.ewww-tool-form').hide();
|
||||
$('.ewww-tool-divider').hide();
|
||||
$('#ewww-clean-originals-progressbar').progressbar({ max: ewww_total_originals });
|
||||
$('#ewww-clean-originals-progress').html('<p> 0/' + ewww_total_originals + '</p>');
|
||||
$('#ewww-clean-originals-progressbar').show();
|
||||
$('#ewww-clean-originals-progress').show();
|
||||
ewwwDeleteOriginalByID();
|
||||
});
|
||||
return false;
|
||||
});
|
||||
function ewwwDeleteOriginalByID(){
|
||||
var attachment_id = ewww_original_attachments.pop();
|
||||
var ewww_originals_data = {
|
||||
action: 'bulk_aux_images_delete_original',
|
||||
ewww_wpnonce: ewww_vars._wpnonce,
|
||||
attachment_id: attachment_id,
|
||||
};
|
||||
$.post(ajaxurl, ewww_originals_data, function(response) {
|
||||
try {
|
||||
var ewww_response = JSON.parse(response);
|
||||
} catch (err) {
|
||||
$('#ewww-clean-originals-progressbar').hide();
|
||||
$('#ewww-clean-originals-progress').html('<span style="color: red"><b>' + ewww_vars.invalid_response + '</b></span>');
|
||||
console.log(err);
|
||||
console.log(response);
|
||||
return false;
|
||||
}
|
||||
if ( ewww_response.error ) {
|
||||
$('#ewww-clean-originals-progressbar').hide();
|
||||
$('#ewww-clean-originals-progress').html('<span style="color: red"><b>' + ewww_response.error + '</b></span>');
|
||||
return false;
|
||||
}
|
||||
if(!ewww_original_attachments.length) {
|
||||
var ewww_originals_data = {
|
||||
action: 'bulk_aux_images_delete_original',
|
||||
ewww_wpnonce: ewww_vars._wpnonce,
|
||||
delete_originals_done: 1,
|
||||
};
|
||||
$.post(ajaxurl, ewww_originals_data);
|
||||
$('#ewww-clean-originals-progress').html(ewww_vars.finished);
|
||||
return false;
|
||||
}
|
||||
var completed = ewww_total_originals - ewww_original_attachments.length;
|
||||
$('#ewww-clean-originals-progressbar').progressbar("option", "value", completed);
|
||||
$('#ewww-clean-originals-progress').html('<p>' + completed + '/' + ewww_total_originals + '</p>');
|
||||
ewwwDeleteOriginalByID();
|
||||
});
|
||||
}
|
||||
var ewww_total_converted = 0;
|
||||
$('#ewww-clean-converted').on( 'submit', function() {
|
||||
var ewww_converted_data = {
|
||||
action: 'bulk_aux_images_count_converted',
|
||||
ewww_wpnonce: ewww_vars._wpnonce,
|
||||
};
|
||||
var header_label = $(this).find('input[type="submit"]').val();
|
||||
if (header_label) {
|
||||
$('#ewwwio-tools-header').html(header_label);
|
||||
}
|
||||
$.post(ajaxurl, ewww_converted_data, function(response) {
|
||||
try {
|
||||
var ewww_response = JSON.parse(response);
|
||||
} catch (err) {
|
||||
$('#ewww-clean-converted-progress').html('<span style="color: red"><b>' + ewww_vars.invalid_response + '</b></span>');
|
||||
console.log( response );
|
||||
return false;
|
||||
}
|
||||
ewww_total_converted = ewww_response.total_converted;
|
||||
$('.ewww-tool-info').hide();
|
||||
$('.ewww-tool-form').hide();
|
||||
$('.ewww-tool-divider').hide();
|
||||
$('#ewww-clean-converted-progressbar').progressbar({ max: ewww_total_converted });
|
||||
$('#ewww-clean-converted-progress').html('<p> 0/' + ewww_total_converted + '</p>');
|
||||
$('#ewww-clean-converted-progressbar').show();
|
||||
$('#ewww-clean-converted-progress').show();
|
||||
ewwwCleanConvertedOriginals(0);
|
||||
});
|
||||
return false;
|
||||
});
|
||||
function ewwwCleanConvertedOriginals(converted_offset){
|
||||
var ewww_converted_data = {
|
||||
action: 'bulk_aux_images_converted_clean',
|
||||
ewww_wpnonce: ewww_vars._wpnonce,
|
||||
};
|
||||
$.post(ajaxurl, ewww_converted_data, function(response) {
|
||||
try {
|
||||
var ewww_response = JSON.parse(response);
|
||||
} catch (err) {
|
||||
$('#ewww-clean-converted-progressbar').hide();
|
||||
$('#ewww-clean-converted-progress').html('<span style="color: red"><b>' + ewww_vars.invalid_response + '</b></span>');
|
||||
console.log(err);
|
||||
console.log(response);
|
||||
return false;
|
||||
}
|
||||
if ( ewww_response.error ) {
|
||||
$('#ewww-clean-converted-progressbar').hide();
|
||||
$('#ewww-clean-converted-progress').html('<span style="color: red"><b>' + ewww_response.error + '</b></span>');
|
||||
return false;
|
||||
}
|
||||
if(ewww_response.finished) {
|
||||
$('#ewww-clean-converted-progress').html(ewww_vars.finished);
|
||||
return false;
|
||||
}
|
||||
converted_offset += ewww_response.completed;
|
||||
$('#ewww-clean-converted-progressbar').progressbar("option", "value", converted_offset);
|
||||
$('#ewww-clean-converted-progress').html('<p>' + converted_offset + '/' + ewww_total_converted + '</p>');
|
||||
ewwwCleanConvertedOriginals(converted_offset);
|
||||
});
|
||||
}
|
||||
var ewww_total_webp = 0;
|
||||
var ewww_webp_cleaned = 0;
|
||||
$('#ewww-clean-webp').on( 'submit', function() {
|
||||
var ewww_webp_data = {
|
||||
action: 'ewwwio_webp_attachment_count',
|
||||
ewww_wpnonce: ewww_vars._wpnonce,
|
||||
};
|
||||
var header_label = $(this).find('input[type="submit"]').val();
|
||||
if (header_label) {
|
||||
$('#ewwwio-tools-header').html(header_label);
|
||||
}
|
||||
$.post(ajaxurl, ewww_webp_data, function(response) {
|
||||
try {
|
||||
ewww_webp_attachments = JSON.parse(response);
|
||||
} catch (err) {
|
||||
$('#ewww-clean-webp-progress').html('<span style="color: red"><b>' + ewww_vars.invalid_response + '</b></span>');
|
||||
console.log(err);
|
||||
console.log(response);
|
||||
return false;
|
||||
}
|
||||
ewww_total_webp = ewww_webp_attachments.total;
|
||||
$('.ewww-tool-info').hide();
|
||||
$('.ewww-tool-form').hide();
|
||||
$('.ewww-tool-divider').hide();
|
||||
$('#ewww-clean-webp-progressbar').progressbar({ max: ewww_total_webp });
|
||||
$('#ewww-clean-webp-progress').html('<p>' + ewww_vars.stage1 + ' 0/' + ewww_total_webp + '</p>');
|
||||
$('#ewww-clean-webp-progressbar').show();
|
||||
$('#ewww-clean-webp-progress').show();
|
||||
ewwwRemoveWebPByID();
|
||||
});
|
||||
return false;
|
||||
});
|
||||
function ewwwRemoveWebPByID(){
|
||||
var ewww_webp_data = {
|
||||
action: 'bulk_aux_images_delete_webp',
|
||||
ewww_wpnonce: ewww_vars._wpnonce,
|
||||
};
|
||||
$.post(ajaxurl, ewww_webp_data, function(response) {
|
||||
try {
|
||||
var ewww_response = JSON.parse(response);
|
||||
} catch (err) {
|
||||
$('#ewww-clean-webp-progressbar').hide();
|
||||
$('#ewww-clean-webp-progress').html('<span style="color: red"><b>' + ewww_vars.invalid_response + '</b></span>');
|
||||
console.log(err);
|
||||
console.log(response);
|
||||
return false;
|
||||
}
|
||||
if ( ewww_response.error ) {
|
||||
$('#ewww-clean-webp-progressbar').hide();
|
||||
$('#ewww-clean-webp-progress').html('<span style="color: red"><b>' + ewww_response.error + '</b></span>');
|
||||
return false;
|
||||
}
|
||||
if(ewww_response.finished) {
|
||||
ewww_total_webp = ewww_vars.webp_cleanable;
|
||||
ewww_webp_cleaned = 0;
|
||||
$('#ewww-clean-webp-progressbar').progressbar({ max: ewww_total_webp });
|
||||
$('#ewww-clean-webp-progressbar').progressbar("option", "value", 0);
|
||||
$('#ewww-clean-webp-progress').html('<p>' + ewww_vars.stage2 + ' 0/' + ewww_total_webp + '</p>');
|
||||
ewwwRemoveWebP();
|
||||
return false;
|
||||
}
|
||||
ewww_webp_cleaned++;
|
||||
$('#ewww-clean-webp-progressbar').progressbar("option", "value", ewww_webp_cleaned);
|
||||
$('#ewww-clean-webp-progress').html('<p>' + ewww_vars.stage1 + ' ' + ewww_webp_cleaned + '/' + ewww_total_webp + '</p>');
|
||||
ewwwRemoveWebPByID();
|
||||
});
|
||||
}
|
||||
function ewwwRemoveWebP(){
|
||||
var ewww_webp_data = {
|
||||
action: 'bulk_aux_images_webp_clean',
|
||||
ewww_wpnonce: ewww_vars._wpnonce,
|
||||
};
|
||||
$.post(ajaxurl, ewww_webp_data, function(response) {
|
||||
try {
|
||||
var ewww_response = JSON.parse(response);
|
||||
} catch (err) {
|
||||
$('#ewww-clean-webp-progressbar').hide();
|
||||
$('#ewww-clean-webp-progress').html('<span style="color: red"><b>' + ewww_vars.invalid_response + '</b></span>');
|
||||
console.log(err);
|
||||
console.log(response);
|
||||
return false;
|
||||
}
|
||||
if ( ewww_response.error ) {
|
||||
$('#ewww-clean-webp-progressbar').hide();
|
||||
$('#ewww-clean-webp-progress').html('<span style="color: red"><b>' + ewww_response.error + '</b></span>');
|
||||
return false;
|
||||
}
|
||||
if(ewww_response.finished) {
|
||||
$('#ewww-clean-webp-progress').html(ewww_vars.finished);
|
||||
return false;
|
||||
}
|
||||
ewww_webp_cleaned += ewww_response.completed;
|
||||
$('#ewww-clean-webp-progressbar').progressbar("option", "value", ewww_webp_cleaned);
|
||||
$('#ewww-clean-webp-progress').html('<p>' + ewww_vars.stage2 + ' ' + ewww_webp_cleaned + '/' + ewww_total_webp + '</p>');
|
||||
ewwwRemoveWebP();
|
||||
});
|
||||
}
|
||||
$('#ewww-clean-table').on( 'submit', function() {
|
||||
var header_label = $(this).find('input[type="submit"]').val();
|
||||
if (header_label) {
|
||||
$('#ewwwio-tools-header').html(header_label);
|
||||
}
|
||||
ewww_total_pages = Math.ceil(ewww_vars.image_count / 500);
|
||||
$('.ewww-tool-info').hide();
|
||||
$('.ewww-tool-form').hide();
|
||||
$('.ewww-tool-divider').hide();
|
||||
$('#ewww-clean-table-progressbar').progressbar({ max: ewww_total_pages });
|
||||
$('#ewww-clean-table-progress').html('<p>' + ewww_vars.batch + ' 0/' + ewww_total_pages + '</p>');
|
||||
$('#ewww-clean-table-progressbar').show();
|
||||
$('#ewww-clean-table-progress').show();
|
||||
var total_pages = ewww_total_pages;
|
||||
ewwwCleanup(total_pages);
|
||||
return false;
|
||||
});
|
||||
function ewwwCleanup(total_pages){
|
||||
total_pages--;
|
||||
var ewww_table_data = {
|
||||
action: 'bulk_aux_images_table_clean',
|
||||
ewww_wpnonce: ewww_vars._wpnonce,
|
||||
ewww_offset: total_pages,
|
||||
};
|
||||
$.post(ajaxurl, ewww_table_data, function(response) {
|
||||
try {
|
||||
var ewww_response = JSON.parse(response);
|
||||
} catch (err) {
|
||||
$('#ewww-clean-table-progressbar').hide();
|
||||
$('#ewww-clean-table-progress').html('<span style="color: red"><b>' + ewww_vars.invalid_response + '</b></span>');
|
||||
console.log( response );
|
||||
return false;
|
||||
}
|
||||
if ( ewww_response.error ) {
|
||||
$('#ewww-clean-table-progressbar').hide();
|
||||
$('#ewww-clean-table-progress').html('<span style="color: red"><b>' + ewww_response.error + '</b></span>');
|
||||
return false;
|
||||
}
|
||||
if(!total_pages>0) {
|
||||
$('#ewww-clean-table-progress').html(ewww_vars.finished);
|
||||
$('#ewww-clean-table-progressbar').progressbar("option", "value", ewww_total_pages);
|
||||
return;
|
||||
}
|
||||
$('#ewww-clean-table-progressbar').progressbar("option", "value", ewww_total_pages-total_pages);
|
||||
$('#ewww-clean-table-progress').html('<p>' + ewww_vars.batch + ' ' + (ewww_total_pages-total_pages) + '/' + ewww_total_pages + '</p>');
|
||||
ewwwCleanup(total_pages);
|
||||
});
|
||||
}
|
||||
$('#ewww-clean-meta').on( 'submit', function() {
|
||||
var header_label = $(this).find('input[type="submit"]').val();
|
||||
if (header_label) {
|
||||
$('#ewwwio-tools-header').html(header_label);
|
||||
}
|
||||
$('.ewww-tool-info').hide();
|
||||
$('.ewww-tool-form').hide();
|
||||
$('.ewww-tool-divider').hide();
|
||||
$('#ewww-clean-meta-progressbar').progressbar({ max: ewww_vars.attachment_count });
|
||||
console.log( $('#ewww-clean-meta-progressbar').progressbar("option","max"));
|
||||
$('#ewww-clean-meta-progress').html('<p>0/' + ewww_vars.attachment_string + '</p>');
|
||||
$('#ewww-clean-meta-progressbar').show();
|
||||
$('#ewww-clean-meta-progress').show();
|
||||
ewwwCleanupMeta();
|
||||
return false;
|
||||
});
|
||||
function ewwwCleanupMeta(){
|
||||
var ewww_cleanmeta_data = {
|
||||
action: 'bulk_aux_images_meta_clean',
|
||||
ewww_wpnonce: ewww_vars._wpnonce,
|
||||
ewww_offset: ewww_clean_meta_total,
|
||||
};
|
||||
$.post(ajaxurl, ewww_cleanmeta_data, function(response) {
|
||||
try {
|
||||
var ewww_response = JSON.parse(response);
|
||||
} catch (err) {
|
||||
$('#ewww-clean-meta-progressbar').hide();
|
||||
$('#ewww-clean-meta-progress').html('<span style="color: red"><b>' + ewww_vars.invalid_response + '</b></span>');
|
||||
console.log( response );
|
||||
return false;
|
||||
}
|
||||
if ( ewww_response.error ) {
|
||||
$('#ewww-clean-meta-progressbar').hide();
|
||||
$('#ewww-clean-meta-progress').html('<span style="color: red"><b>' + ewww_response.error + '</b></span>');
|
||||
return false;
|
||||
}
|
||||
if(ewww_response.done) {
|
||||
$('#ewww-clean-meta-progress').html(ewww_vars.finished);
|
||||
$('#ewww-clean-meta-progressbar').progressbar("value", parseInt(ewww_vars.attachment_count));
|
||||
return;
|
||||
}
|
||||
ewww_clean_meta_total += ewww_response.success;
|
||||
if (ewww_clean_meta_total > ewww_vars.attachment_count) {
|
||||
ewww_clean_meta_total = ewww_vars.attachment_count;
|
||||
}
|
||||
$('#ewww-clean-meta-progressbar').progressbar("value", ewww_clean_meta_total);
|
||||
$('#ewww-clean-meta-progress').html('<p>' + ewww_clean_meta_total + '/' + ewww_vars.attachment_string + '</p>');
|
||||
ewwwCleanupMeta();
|
||||
});
|
||||
}
|
||||
$('.ewww-aux-table').on( 'click', '.ewww-remove-image', function() {
|
||||
var imageID = $(this).data('id');
|
||||
var ewww_image_removal = {
|
||||
action: 'bulk_aux_images_remove',
|
||||
ewww_wpnonce: ewww_vars._wpnonce,
|
||||
ewww_image_id: imageID,
|
||||
};
|
||||
$.post(ajaxurl, ewww_image_removal, function(response) {
|
||||
if(response == '1') {
|
||||
$('#ewww-image-' + imageID).remove();
|
||||
var ewww_prev_count = ewww_vars.image_count;
|
||||
ewww_vars.image_count--;
|
||||
ewww_vars.count_string = ewww_vars.count_string.replace( ewww_prev_count, ewww_vars.image_count );
|
||||
$('.displaying-num').text(ewww_vars.count_string);
|
||||
} else {
|
||||
alert(ewww_vars.remove_failed);
|
||||
}
|
||||
});
|
||||
return false;
|
||||
});
|
||||
$('.ewww-aux-table').on( 'click', '.ewww-restore-image', function() {
|
||||
var imageID = $(this).data('id');
|
||||
var ewww_image_restore = {
|
||||
action: 'ewww_manual_image_restore_single',
|
||||
ewww_wpnonce: ewww_vars._wpnonce,
|
||||
ewww_image_id: imageID,
|
||||
};
|
||||
var original_html = $('#ewww-image-' + imageID + ' td:last-child').html();
|
||||
$('#ewww-image-' + imageID + ' td:last-child').html(ewww_vars.restoring);
|
||||
$.post(ajaxurl, ewww_image_restore, function(response) {
|
||||
var is_json = true;
|
||||
try {
|
||||
var ewww_response = JSON.parse(response);
|
||||
} catch (err) {
|
||||
alert( ewww_vars.invalid_response );
|
||||
console.log( response );
|
||||
return false;
|
||||
}
|
||||
if ( ewww_response.success == '1') {
|
||||
$('#ewww-image-' + imageID + ' td:last-child').html(ewww_vars.original_restored);
|
||||
} else if (ewww_response.error) {
|
||||
$('#ewww-image-' + imageID + ' td:last-child').html(original_html);
|
||||
alert(ewww_response.error);
|
||||
}
|
||||
});
|
||||
return false;
|
||||
});
|
||||
});
|
43
wp-content/plugins/ewww-image-optimizer/includes/flag.js
Normal file
@ -0,0 +1,43 @@
|
||||
jQuery(document).on( 'click', '.ewww-manual-optimize', function() {
|
||||
var post_id = jQuery(this).data('id');
|
||||
var ewww_nonce = jQuery(this).data('nonce');
|
||||
var ewww_manual_optimize_data = {
|
||||
action: 'ewww_flag_manual',
|
||||
ewww_manual_nonce: ewww_nonce,
|
||||
ewww_force: 1,
|
||||
ewww_attachment_ID: post_id,
|
||||
};
|
||||
jQuery('#ewww-flag-status-' + post_id ).html( ewww_vars.optimizing );
|
||||
jQuery.post(ajaxurl, ewww_manual_optimize_data, function(response) {
|
||||
var ewww_manual_response = JSON.parse(response);
|
||||
if (ewww_manual_response.error) {
|
||||
jQuery('#ewww-flag-status-' + post_id ).html( ewww_manual_response.error );
|
||||
} else if (ewww_manual_response.success) {
|
||||
jQuery('#ewww-flag-status-' + post_id ).html( ewww_manual_response.success );
|
||||
}
|
||||
});
|
||||
return false;
|
||||
});
|
||||
jQuery(document).on( 'click', '.ewww-manual-image-restore', function() {
|
||||
var post_id = jQuery(this).data('id');
|
||||
var ewww_nonce = jQuery(this).data('nonce');
|
||||
var ewww_manual_optimize_data = {
|
||||
action: 'ewww_flag_image_restore',
|
||||
ewww_manual_nonce: ewww_nonce,
|
||||
ewww_attachment_ID: post_id,
|
||||
};
|
||||
jQuery('#ewww-flag-status-' + post_id ).html( ewww_vars.restoring );
|
||||
jQuery.post(ajaxurl, ewww_manual_optimize_data, function(response) {
|
||||
var ewww_manual_response = JSON.parse(response);
|
||||
if (ewww_manual_response.error) {
|
||||
jQuery('#ewww-flag-status-' + post_id ).html( ewww_manual_response.error );
|
||||
} else if (ewww_manual_response.success) {
|
||||
jQuery('#ewww-flag-status-' + post_id ).html( ewww_manual_response.success );
|
||||
}
|
||||
});
|
||||
return false;
|
||||
});
|
||||
jQuery(document).on('click', '.ewww-show-debug-meta', function() {
|
||||
var post_id = jQuery(this).data('id');
|
||||
jQuery('#ewww-debug-meta-' + post_id).toggle();
|
||||
});
|
981
wp-content/plugins/ewww-image-optimizer/includes/jquery-ui-1.10.1.custom.css
vendored
Normal file
@ -0,0 +1,981 @@
|
||||
/*! jQuery UI - v1.10.1 - 2013-03-14
|
||||
* Copyright 2013 jQuery Foundation and other contributors Licensed MIT */
|
||||
/* includes styling for progressbar and tooltip elements */
|
||||
/* Layout helpers
|
||||
----------------------------------*/
|
||||
.ui-helper-hidden {
|
||||
display: none;
|
||||
}
|
||||
.ui-helper-hidden-accessible {
|
||||
border: 0;
|
||||
clip: rect(0 0 0 0);
|
||||
height: 1px;
|
||||
margin: -1px;
|
||||
overflow: hidden;
|
||||
padding: 0;
|
||||
position: absolute;
|
||||
width: 1px;
|
||||
}
|
||||
.ui-helper-reset {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
outline: 0;
|
||||
line-height: 1.3;
|
||||
text-decoration: none;
|
||||
font-size: 100%;
|
||||
list-style: none;
|
||||
}
|
||||
.ui-helper-clearfix:before,
|
||||
.ui-helper-clearfix:after {
|
||||
content: "";
|
||||
display: table;
|
||||
border-collapse: collapse;
|
||||
}
|
||||
.ui-helper-clearfix:after {
|
||||
clear: both;
|
||||
}
|
||||
.ui-helper-clearfix {
|
||||
min-height: 0; /* support: IE7 */
|
||||
}
|
||||
.ui-helper-zfix {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
top: 0;
|
||||
left: 0;
|
||||
position: absolute;
|
||||
opacity: 0;
|
||||
filter:Alpha(Opacity=0);
|
||||
}
|
||||
.ui-front {
|
||||
z-index: 100;
|
||||
}
|
||||
/* Interaction Cues
|
||||
----------------------------------*/
|
||||
.ui-state-disabled {
|
||||
cursor: default !important;
|
||||
}
|
||||
|
||||
/* Misc visuals
|
||||
----------------------------------*/
|
||||
/* Corner radius */
|
||||
.ui-corner-all,
|
||||
.ui-corner-top,
|
||||
.ui-corner-left,
|
||||
.ui-corner-tl {
|
||||
border-top-left-radius: 22px;
|
||||
}
|
||||
.ui-corner-all,
|
||||
.ui-corner-top,
|
||||
.ui-corner-right,
|
||||
.ui-corner-tr {
|
||||
border-top-right-radius: 22px;
|
||||
}
|
||||
.ui-corner-all,
|
||||
.ui-corner-bottom,
|
||||
.ui-corner-left,
|
||||
.ui-corner-bl {
|
||||
border-bottom-left-radius: 22px;
|
||||
}
|
||||
.ui-corner-all,
|
||||
.ui-corner-bottom,
|
||||
.ui-corner-right,
|
||||
.ui-corner-br {
|
||||
border-bottom-right-radius: 22px;
|
||||
}
|
||||
/* Overlays */
|
||||
.ui-widget-overlay {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
.ui-progressbar {
|
||||
height: 22px;
|
||||
text-align: left;
|
||||
overflow: hidden;
|
||||
}
|
||||
.ui-progressbar .ui-progressbar-value {
|
||||
margin: 0px;
|
||||
height: 100%;
|
||||
|
||||
}
|
||||
.ui-accordion .ui-accordion-header {
|
||||
display: block;
|
||||
cursor: pointer;
|
||||
position: relative;
|
||||
margin-top: 2px;
|
||||
padding: .5em .5em .5em .7em;
|
||||
min-height: 0; /* support: IE7 */
|
||||
}
|
||||
.ui-accordion .ui-accordion-icons {
|
||||
padding-left: 2.2em;
|
||||
}
|
||||
.ui-accordion .ui-accordion-noicons {
|
||||
padding-left: .7em;
|
||||
}
|
||||
.ui-accordion .ui-accordion-icons .ui-accordion-icons {
|
||||
padding-left: 2.2em;
|
||||
}
|
||||
.ui-accordion .ui-accordion-header .ui-accordion-header-icon {
|
||||
position: absolute;
|
||||
left: .5em;
|
||||
top: 50%;
|
||||
margin-top: -8px;
|
||||
}
|
||||
.ui-accordion .ui-accordion-content {
|
||||
padding: 1em 2.2em;
|
||||
border-top: 0;
|
||||
overflow: auto;
|
||||
border-top-left-radius: 0px;
|
||||
border-top-right-radius: 0px;
|
||||
}
|
||||
.ui-slider {
|
||||
position: relative;
|
||||
text-align: left;
|
||||
}
|
||||
.ui-slider .ui-slider-handle {
|
||||
position: absolute;
|
||||
z-index: 2;
|
||||
width: 1.2em;
|
||||
height: 1.2em;
|
||||
cursor: default;
|
||||
}
|
||||
.ui-slider .ui-slider-range {
|
||||
position: absolute;
|
||||
z-index: 1;
|
||||
font-size: .7em;
|
||||
display: block;
|
||||
border: 0;
|
||||
background-position: 0 0;
|
||||
}
|
||||
|
||||
/* For IE8 - See #6727 */
|
||||
.ui-slider.ui-state-disabled .ui-slider-handle,
|
||||
.ui-slider.ui-state-disabled .ui-slider-range {
|
||||
filter: inherit;
|
||||
}
|
||||
|
||||
.ui-slider-horizontal {
|
||||
height: .8em;
|
||||
}
|
||||
.ui-slider-horizontal .ui-slider-handle {
|
||||
top: -.3em;
|
||||
margin-left: -.6em;
|
||||
}
|
||||
.ui-slider-horizontal .ui-slider-range {
|
||||
top: 0;
|
||||
height: 100%;
|
||||
}
|
||||
.ui-slider-horizontal .ui-slider-range-min {
|
||||
left: 0;
|
||||
}
|
||||
.ui-slider-horizontal .ui-slider-range-max {
|
||||
right: 0;
|
||||
}
|
||||
|
||||
.ui-slider-vertical {
|
||||
width: .8em;
|
||||
height: 100px;
|
||||
}
|
||||
.ui-slider-vertical .ui-slider-handle {
|
||||
left: -.3em;
|
||||
margin-left: 0;
|
||||
margin-bottom: -.6em;
|
||||
}
|
||||
.ui-slider-vertical .ui-slider-range {
|
||||
left: 0;
|
||||
width: 100%;
|
||||
}
|
||||
.ui-slider-vertical .ui-slider-range-min {
|
||||
bottom: 0;
|
||||
}
|
||||
.ui-slider-vertical .ui-slider-range-max {
|
||||
top: 0;
|
||||
}
|
||||
/* Component containers
|
||||
----------------------------------*/
|
||||
.ui-widget-content {
|
||||
background: none repeat scroll 0% 0% #dddddd;
|
||||
-webkit-border-radius: 22px;
|
||||
border-radius: 22px;
|
||||
-webkit-box-shadow: inset 0 1px 2px rgba(0,0,0,0.1);
|
||||
box-shadow: inset 0 1px 2px rgba(0,0,0,0.1);
|
||||
}
|
||||
.ui-widget-content a {
|
||||
color: #222222;
|
||||
}
|
||||
.ui-widget-header {
|
||||
z-index: 9;
|
||||
background-color: #0074a2;
|
||||
-webkit-border-radius: 22px;
|
||||
border-radius: 22px;
|
||||
}
|
||||
.ui-widget-header a {
|
||||
color: #ffffff;
|
||||
}
|
||||
/* Interaction states
|
||||
----------------------------------*/
|
||||
.ui-state-default,
|
||||
.ui-widget-content .ui-state-default,
|
||||
.ui-widget-header .ui-state-default {
|
||||
border: 1px solid #d3d3d3;
|
||||
background: #e6e6e6 50% 50% repeat-x;
|
||||
font-weight: normal;
|
||||
color: #555555;
|
||||
}
|
||||
.ui-state-default a,
|
||||
.ui-state-default a:link,
|
||||
.ui-state-default a:visited {
|
||||
color: #555555;
|
||||
text-decoration: none;
|
||||
}
|
||||
.ui-state-hover,
|
||||
.ui-widget-content .ui-state-hover,
|
||||
.ui-widget-header .ui-state-hover,
|
||||
.ui-state-focus,
|
||||
.ui-widget-content .ui-state-focus,
|
||||
.ui-widget-header .ui-state-focus {
|
||||
border: 1px solid #999999;
|
||||
background: #dadada 50% 50% repeat-x;
|
||||
font-weight: normal;
|
||||
color: #212121;
|
||||
}
|
||||
.ui-state-hover a,
|
||||
.ui-state-hover a:hover,
|
||||
.ui-state-hover a:link,
|
||||
.ui-state-hover a:visited {
|
||||
color: #212121;
|
||||
text-decoration: none;
|
||||
}
|
||||
.ui-state-active,
|
||||
.ui-widget-content .ui-state-active,
|
||||
.ui-widget-header .ui-state-active {
|
||||
border: 1px solid #aaaaaa;
|
||||
background: #ffffff 50% 50% repeat-x;
|
||||
font-weight: normal;
|
||||
color: #212121;
|
||||
}
|
||||
.ui-state-active a,
|
||||
.ui-state-active a:link,
|
||||
.ui-state-active a:visited {
|
||||
color: #212121;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
/* Interaction Cues
|
||||
----------------------------------*/
|
||||
.ui-state-highlight,
|
||||
.ui-widget-content .ui-state-highlight,
|
||||
.ui-widget-header .ui-state-highlight {
|
||||
border: 1px solid #fcefa1;
|
||||
color: #363636;
|
||||
}
|
||||
.ui-state-highlight a,
|
||||
.ui-widget-content .ui-state-highlight a,
|
||||
.ui-widget-header .ui-state-highlight a {
|
||||
color: #363636;
|
||||
}
|
||||
.ui-state-error,
|
||||
.ui-widget-content .ui-state-error,
|
||||
.ui-widget-header .ui-state-error {
|
||||
border: 1px solid #cd0a0a;
|
||||
color: #cd0a0a;
|
||||
}
|
||||
.ui-state-error a,
|
||||
.ui-widget-content .ui-state-error a,
|
||||
.ui-widget-header .ui-state-error a {
|
||||
color: #cd0a0a;
|
||||
}
|
||||
.ui-state-error-text,
|
||||
.ui-widget-content .ui-state-error-text,
|
||||
.ui-widget-header .ui-state-error-text {
|
||||
color: #cd0a0a;
|
||||
}
|
||||
.ui-priority-primary,
|
||||
.ui-widget-content .ui-priority-primary,
|
||||
.ui-widget-header .ui-priority-primary {
|
||||
font-weight: bold;
|
||||
}
|
||||
.ui-priority-secondary,
|
||||
.ui-widget-content .ui-priority-secondary,
|
||||
.ui-widget-header .ui-priority-secondary {
|
||||
opacity: .7;
|
||||
filter:Alpha(Opacity=70);
|
||||
font-weight: normal;
|
||||
}
|
||||
.ui-state-disabled,
|
||||
.ui-widget-content .ui-state-disabled,
|
||||
.ui-widget-header .ui-state-disabled {
|
||||
opacity: .35;
|
||||
filter:Alpha(Opacity=35);
|
||||
background-image: none;
|
||||
}
|
||||
.ui-state-disabled .ui-icon {
|
||||
filter:Alpha(Opacity=35); /* For IE8 - See #6059 */
|
||||
}
|
||||
/* jQuery UI Tooltip 1.10.1 */
|
||||
.ui-tooltip {
|
||||
padding: 8px;
|
||||
position: absolute;
|
||||
z-index: 9999;
|
||||
max-width: 300px;
|
||||
min-width: 130px;
|
||||
border-radius: 8px;
|
||||
background: #fff;
|
||||
}
|
||||
body .ui-tooltip {
|
||||
border-width: 1px;
|
||||
}
|
||||
.ui-tooltip, .arrow:after {
|
||||
border: 1px solid #272727;
|
||||
}
|
||||
.ui-tooltip {
|
||||
padding: 5px 10px;
|
||||
}
|
||||
.arrow {
|
||||
width: 70px;
|
||||
height: 16px;
|
||||
overflow: hidden;
|
||||
position: absolute;
|
||||
left: 50%;
|
||||
margin-left: -35px;
|
||||
bottom: -16px;
|
||||
z-index: 99999;
|
||||
}
|
||||
.arrow.top {
|
||||
top: -16px;
|
||||
bottom: auto;
|
||||
}
|
||||
.arrow.left {
|
||||
left: 20%;
|
||||
}
|
||||
.arrow:after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
left: 20px;
|
||||
top: -20px;
|
||||
width: 25px;
|
||||
height: 25px;
|
||||
background-color: #FFF;
|
||||
-webkit-transform: rotate(45deg);
|
||||
-moz-transform: rotate(45deg);
|
||||
-ms-transform: rotate(45deg);
|
||||
-o-transform: rotate(45deg);
|
||||
tranform: rotate(45deg);
|
||||
}
|
||||
.arrow.top:after {
|
||||
bottom: -20px;
|
||||
top: auto;
|
||||
}
|
||||
/* media library actions and details */
|
||||
a.ewww-remove-image, a.ewww-restore-image {
|
||||
cursor: pointer;
|
||||
}
|
||||
.ewww-attachment-detail table td, .ewww-attachment-detail table th {
|
||||
padding: 8px 10px;
|
||||
}
|
||||
.ewww-attachment-detail table th {
|
||||
border-bottom: 1px solid #e5e5e5;
|
||||
}
|
||||
.ewww-attachment-detail table {
|
||||
width: 100%;
|
||||
border: 1px solid #e5e5e5;
|
||||
border-collapse: collapse;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
.ewww-attachment-detail {
|
||||
padding: 13px 0px 0px;
|
||||
}
|
||||
.ewww-variant-icon {
|
||||
color: white;
|
||||
background-color: #f1900e;
|
||||
border-radius: 50%;
|
||||
font-size: 10px;
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
line-height: 16px;
|
||||
text-align: center;
|
||||
display: inline-block;
|
||||
padding-bottom: 0px;
|
||||
}
|
||||
/* bulk and settings ui */
|
||||
#ewww-bulk-credits-available {
|
||||
margin-left: 20px;
|
||||
padding: 4px 8px;
|
||||
position: relative;
|
||||
top: -3px;
|
||||
border: 1px solid #2271b1;
|
||||
border-radius: 2px;
|
||||
text-shadow: none;
|
||||
font-weight: 600;
|
||||
font-size: 13px;
|
||||
line-height: normal;
|
||||
color: #2271b1;
|
||||
background: #f6f7f7;
|
||||
}
|
||||
h2.ewww-hndle {
|
||||
font-size: 14px;
|
||||
padding: 8px 12px;
|
||||
margin: 0;
|
||||
line-height: 1.4;
|
||||
user-select: none;
|
||||
border-bottom: 1px solid #eee;
|
||||
touch-action: none;
|
||||
cursor: pointer;
|
||||
}
|
||||
button.ewww-handlediv {
|
||||
color: #72777c;
|
||||
display: block;
|
||||
cursor: pointer;
|
||||
float: right;
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
}
|
||||
.js .postbox .ewww-handlediv .toggle-indicator:before {
|
||||
margin-top: 4px;
|
||||
width: 20px;
|
||||
border-radius: 50%;
|
||||
text-indent: -1px;
|
||||
}
|
||||
.js .postbox.closed .ewww-handlediv .toggle-indicator:before {
|
||||
content: "\f140";
|
||||
}
|
||||
.ewww-bulk-error, .ewww-ajax-error {
|
||||
color: red;
|
||||
}
|
||||
.ewww-bulk-error a, .ewww-bulk-error a:visited {
|
||||
color: red;
|
||||
}
|
||||
#ewww-bulk-controls {
|
||||
border: solid 1px #e5e5e5;
|
||||
background: #fff;
|
||||
padding: 10px;
|
||||
float: right;
|
||||
width: 24%;
|
||||
max-width: 360px;
|
||||
margin-left: 15px;
|
||||
}
|
||||
#ewww-bulk-forms {
|
||||
float: left;
|
||||
min-width: 50%;
|
||||
max-width: 65%;
|
||||
border: solid 1px #e5e5e5;
|
||||
background: #fff;
|
||||
padding: 0 10px 12px;
|
||||
}
|
||||
#ewww-delay-slider {
|
||||
margin: 0 0 15px 10px;
|
||||
max-width: 500px;
|
||||
}
|
||||
#ewww-delay {
|
||||
max-width: 50px;
|
||||
min-width: 30px;
|
||||
}
|
||||
.ngg-admin .ewww_bulk_wrap {
|
||||
margin-left: 20px;
|
||||
}
|
||||
.ngg-admin .wrap h2.wp-heading-inline {
|
||||
display: inline-block;
|
||||
margin-right: 5px;
|
||||
}
|
||||
@media screen and (max-width: 780px) {
|
||||
#ewww-bulk-controls {
|
||||
float: none;
|
||||
margin-left: 0px;
|
||||
max-width: none;
|
||||
width: auto;
|
||||
}
|
||||
#ewww-bulk-forms {
|
||||
margin: 10px 0;
|
||||
float: none;
|
||||
max-width: none;
|
||||
width: auto;
|
||||
}
|
||||
}
|
||||
/* settings tabs */
|
||||
.ewww-tab span { font-size: 14px; font-weight: 600; color: #555; text-decoration: none; line-height: 36px; padding: 0 10px; }
|
||||
.ewww-tab span:hover { color: #464646; }
|
||||
.ewww-tab { margin: 0 0 0 5px; padding: 0px; border-width: 1px 1px 1px; border-style: solid solid none; border-image: none; border-color: #ccc; display: inline-block; background-color: #e4e4e4; cursor: pointer }
|
||||
.ewww-tab:hover { background-color: #fff }
|
||||
.ewww-selected { background-color: #f1f1f1; margin-bottom: -1px; border-bottom: 1px solid #f1f1f1 }
|
||||
.ewww-selected span { color: #000; }
|
||||
.ewww-selected:hover { background-color: #f1f1f1; }
|
||||
.ewww-tab-nav { list-style: none; margin: 10px 0 0; padding-left: 5px; border-bottom: 1px solid #ccc; }
|
||||
/* optimization status section */
|
||||
#ewww-widgets {
|
||||
width: 100%;
|
||||
/* max-width: 1400px; */
|
||||
clear: right;
|
||||
}
|
||||
#ewww-status .inside {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
.ewww-blocks {
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
#ewww-status h2.ewww-hndle {
|
||||
border-bottom: 0;
|
||||
}
|
||||
.ewww-blocks div.ewww-status-detail {
|
||||
border-left: 1px solid #e2e2e2;
|
||||
margin: 0px;
|
||||
padding: 2em;
|
||||
}
|
||||
.ewww-blocks div.ewww-status-detail:first-child {
|
||||
border-left: 0;
|
||||
}
|
||||
.ewww-blocks div.ewww-status-detail {
|
||||
border-top: 1px solid #e2e2e2;
|
||||
/* display: block; */
|
||||
text-align: center;
|
||||
/* margin: 2em; */
|
||||
}
|
||||
.ewww-blocks #ewww-notices {
|
||||
text-align: left;
|
||||
}
|
||||
#ewww-notices p:first-child {
|
||||
margin-top: 0;
|
||||
}
|
||||
.ewww-guage {
|
||||
position: relative;
|
||||
margin: 0 auto 1rem;
|
||||
padding: 0;
|
||||
width: 120px;
|
||||
height: 120px;
|
||||
}
|
||||
.ewww-guage svg {
|
||||
-webkit-transform: rotate(-90deg);
|
||||
transform: rotate(-90deg);
|
||||
}
|
||||
.ewww-inactive,
|
||||
.ewww-active {
|
||||
fill: none;
|
||||
}
|
||||
.ewww-inactive {
|
||||
stroke: #e6e6e6;
|
||||
}
|
||||
#ewww-score-bars {
|
||||
flex:1 1 auto;
|
||||
}
|
||||
#ewww-compress, #ewww-savings, #easyio-savings {
|
||||
flex: 1 1 120px;
|
||||
}
|
||||
#ewww-savings p {
|
||||
margin: 0.5em 0;
|
||||
}
|
||||
#ewww-compress-guage .ewww-active {
|
||||
stroke-linecap: round;
|
||||
}
|
||||
#ewww-compress-guage .ewww-red {
|
||||
stroke: #dc3232;
|
||||
}
|
||||
#ewww-compress-guage .ewww-orange {
|
||||
stroke: #ffb900;
|
||||
}
|
||||
#ewww-compress-guage .ewww-green {
|
||||
stroke: #46b450;
|
||||
}
|
||||
#ewww-resize-guage .ewww-active {
|
||||
stroke: #1d3c71;
|
||||
stroke-linecap: round;
|
||||
}
|
||||
#ewww-savings-guage .ewww-active {
|
||||
stroke: #3eadc9;
|
||||
stroke-linecap: round;
|
||||
}
|
||||
#easyio-savings-guage .ewww-active {
|
||||
stroke: #3eadc9;
|
||||
stroke: #1d3c71;
|
||||
stroke-linecap: round;
|
||||
}
|
||||
#ewww-compress-guage .ewww-score {
|
||||
color: #444;
|
||||
}
|
||||
#ewww-resize-guage .ewww-score {
|
||||
color: #1d3c71;
|
||||
}
|
||||
.ewww-score {
|
||||
position: absolute;
|
||||
left: 50%;
|
||||
top: 50%;
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
transform: translate(-50%, -50%);
|
||||
font-size: 1.3rem;
|
||||
font-weight: bold;
|
||||
line-height: 1.5;
|
||||
}
|
||||
#ewww-savings-guage .ewww-score {
|
||||
font-size: 1rem;
|
||||
color: #3eadc9;
|
||||
white-space: nowrap;
|
||||
}
|
||||
#easyio-savings-guage .ewww-score {
|
||||
font-size: 1rem;
|
||||
color: #1d3c71;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.ewww-bar-container {
|
||||
background-color: #e6e6e6;
|
||||
/* border: 1px solid #ccd0d4; */
|
||||
border-radius: 6px;
|
||||
/* box-shadow: 0 1px 1px rgba(0, 0, 0, 0.04); */
|
||||
height: 12px;
|
||||
width: 100%;
|
||||
overflow: hidden;
|
||||
}
|
||||
.ewww-bar-fill {
|
||||
margin: 0;
|
||||
height: 100%;
|
||||
width: 0;
|
||||
}
|
||||
#ewww-speed-container .ewww-red {
|
||||
background-color: #dc3232;
|
||||
}
|
||||
#ewww-speed-container .ewww-orange {
|
||||
background-color: #ffb900;
|
||||
}
|
||||
#ewww-speed-container .ewww-green {
|
||||
background-color: #46b450;
|
||||
}
|
||||
#ewww-savings-container .ewww-bar-fill {
|
||||
background-color: #3eadc9;
|
||||
}
|
||||
#easyio-savings-container .ewww-bar-fill {
|
||||
background-color: #1d3c71;
|
||||
}
|
||||
.ewww-bar-caption {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
.ewww-bar-caption p {
|
||||
margin: 0.5em 0;
|
||||
flex: 1;
|
||||
text-align: center;
|
||||
}
|
||||
.ewww-bar-score {
|
||||
font-size: 1.0rem;
|
||||
font-weight: bold;
|
||||
line-height: 1.5;
|
||||
}
|
||||
#ewww-savings-flex .ewww-bar-score {
|
||||
color: #3eadc9;
|
||||
}
|
||||
#easyio-savings-flex .ewww-bar-score {
|
||||
color: #1d3c71;
|
||||
}
|
||||
.ewww-recommend {
|
||||
display: none;
|
||||
text-align: left;
|
||||
border-top: 1px solid #ccd0d4;
|
||||
border-bottom: 1px solid #ccd0d4;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
.ui-tooltip ul.ewww-tooltip/*, .ewww-recommend ul.ewww-tooltip*/ {
|
||||
list-style: disc outside none;
|
||||
}
|
||||
.ui-tooltip ul.ewww-tooltip li/*, .ewww-recommend ul.ewww-tooltip li*/ {
|
||||
margin-left: 1em;
|
||||
}
|
||||
/* other settings UI */
|
||||
#ewww-rescue-mode {
|
||||
margin: 10px 0;
|
||||
}
|
||||
p.debug-actions {
|
||||
clear: both;
|
||||
}
|
||||
#ewww-debug-info {
|
||||
border:1px solid #e5e5e5;
|
||||
background: #fff;
|
||||
overflow: auto;
|
||||
height: 300px;
|
||||
width: 800px;
|
||||
margin-top: 5px;
|
||||
}
|
||||
#ewww-webp-rewrite #webp-rewrite-rules {
|
||||
background-color: white;
|
||||
border: 1px solid #ccd0d4;
|
||||
clear: both;
|
||||
padding: 10px;
|
||||
box-shadow: 0 1px 1px rgba(0, 0, 0, 0.04);
|
||||
}
|
||||
#ewww-webp-rewrite button {
|
||||
margin-top: 1em;
|
||||
}
|
||||
#ewww-webp-image {
|
||||
float: right;
|
||||
padding: 0 0 10px 10px;
|
||||
/*padding: 0 1px 10px 10px;*/
|
||||
}
|
||||
div#ewww-webp-rewrite-status {
|
||||
font-weight: bold;
|
||||
}
|
||||
p#ewww-webp-rewrite-status {
|
||||
font-style: italic;
|
||||
}
|
||||
#ewwwio-easy-activate, #ewwwio-easy-deactivate, #ewwwio-easy-activate-network, #ewwwio-easy-register-network {
|
||||
margin-top: 10px;
|
||||
}
|
||||
#ewwwio-easy-deregister {
|
||||
vertical-align: bottom;
|
||||
padding-left: 20px;
|
||||
line-height: 2.15;
|
||||
}
|
||||
.ewwwio-notice {
|
||||
background-color: white;
|
||||
border: 1px solid #ccd0d4;
|
||||
border-left: 4px solid #3eadc9;
|
||||
margin: 10px 10px 15px 0;
|
||||
padding: 12px;
|
||||
}
|
||||
.ewwwio-notice.notice-warning {
|
||||
border-left-color: #ffb900;
|
||||
}
|
||||
.ewwwio-notice.notice-success {
|
||||
border-left-color: #46b450;
|
||||
}
|
||||
#ewwwio-easy-register-failed {
|
||||
display: none;
|
||||
}
|
||||
#ewwwio-api-activation-result, #ewwwio-easy-activation-result, #ewww-webp-rewrite-result {
|
||||
display: none;
|
||||
background-color: white;
|
||||
border: 1px solid #ccd0d4;
|
||||
border-left: 4px solid #3eadc9;
|
||||
margin: 10px 10px 15px 0;
|
||||
padding: 12px;
|
||||
font-weight: bold;
|
||||
}
|
||||
#ewww-webp-rewrite-result {
|
||||
margin-right: 110px;
|
||||
}
|
||||
#ewwwio-api-activation-result.error, #ewwwio-easy-activation-result.error, #ewww-webp-rewrite-result.error {
|
||||
border-left-color: #dc3232;
|
||||
}
|
||||
#ewwwio-easy-activation-progressbar {
|
||||
margin: 10px 0;
|
||||
}
|
||||
#ewww-webp-rewrite-result p {
|
||||
/* margin: 0.5em 0; */
|
||||
}
|
||||
#ewww_image_optimizer_cloud_key_container th, #ewww_image_optimizer_exactdn_container th, #swis_promo_container th {
|
||||
color: #3eadc9;
|
||||
}
|
||||
#ewww_image_optimizer_cloud_key_container td, #ewww_image_optimizer_exactdn_container td, #swis_promo_container td {
|
||||
background-color: white;
|
||||
border: 1px solid #ccd0d4;
|
||||
box-shadow: 0 1px 1px rgba(0, 0, 0, 0.04);
|
||||
}
|
||||
#ewww_image_optimizer_cloud_key_container .dashicons-yes {
|
||||
font-size: 30px;
|
||||
}
|
||||
#ewwwio-exactdn-anchor {
|
||||
display: block;
|
||||
position: relative;
|
||||
top: -40px;
|
||||
visibility: hidden;
|
||||
}
|
||||
#exactdn_site_url {
|
||||
cursor: pointer;
|
||||
}
|
||||
/* .top-bar is for the ewww.io iframe(s) */
|
||||
.ewww-attachment-detail-container, .top-bar, #exactdn-site-url-copied, #exactdn-site-url-copy, #ewwwio-api-activation-processing, #ewwwio-easy-activation-processing, #ewwwio-webp-storage-warning {
|
||||
display: none;
|
||||
}
|
||||
#ewwwio-rescue ul {
|
||||
list-style: disc;
|
||||
margin-left: 10px;
|
||||
}
|
||||
#ewwwio-wizard, #ewwwio-rescue {
|
||||
display: flex;
|
||||
max-width: 450px;
|
||||
flex-direction: column;
|
||||
margin: auto;
|
||||
padding: 5% 0;
|
||||
}
|
||||
#ewwwio-rescue .ewww-help-beacon-single {
|
||||
margin: 0px;
|
||||
}
|
||||
#ewwwio-wizard-header, #ewwwio-rescue-header {
|
||||
background-color: #3eadc9;
|
||||
}
|
||||
#ewwwio-wizard-header img, #ewwwio-rescue-header img {
|
||||
margin: 15px auto;
|
||||
display: block;
|
||||
}
|
||||
#ewwwio-wizard-body, #ewwwio-rescue-body {
|
||||
background-color: #fff;
|
||||
padding: 20px;
|
||||
}
|
||||
.ewwwio-intro-text {
|
||||
font-weight: bold;
|
||||
font-size: 1.3em;
|
||||
margin: 1em 0;
|
||||
}
|
||||
.ewwwio-wizard-form {
|
||||
margin: auto 0;
|
||||
}
|
||||
.ewwwio-wizard-form-group {
|
||||
margin-bottom: 2em;
|
||||
}
|
||||
.ewwwio-wizard-form .ewwwio-premium-setup {
|
||||
display: none;
|
||||
margin-left: 2em;
|
||||
}
|
||||
.ewwwio-wizard-form .ewwwio-premium-setup label {
|
||||
font-weight: bold;
|
||||
}
|
||||
.ewwwio-wizard-form .description {
|
||||
margin-bottom: 20px;
|
||||
color: #666;
|
||||
}
|
||||
.ewwwio-wizard-form #ewww_image_optimizer_cloud_key {
|
||||
width: 100%;
|
||||
max-width: 300px;
|
||||
}
|
||||
.ewwwio-flex-space-between {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
}
|
||||
#ewwwio-banner {
|
||||
display: flex;
|
||||
margin: 0px;
|
||||
padding: 15px;
|
||||
background-color: #3eadc9;
|
||||
}
|
||||
#ewwwio-banner div {
|
||||
width: 100%;
|
||||
}
|
||||
#ewwwio-banner img:first-child {
|
||||
margin: auto 10px auto 0;
|
||||
}
|
||||
#ewwwio-banner a.ewww-help-beacon-single img {
|
||||
padding: 0;
|
||||
}
|
||||
#ewwwio-banner p:first-of-type {
|
||||
/* margin-top: 0; */
|
||||
}
|
||||
#ewwwio-banner p {
|
||||
color: #fff;
|
||||
/* margin-bottom: 1.0em; */
|
||||
/* line-height: 1; */
|
||||
}
|
||||
#ewwwio-banner #ewww-review a:first-child {
|
||||
padding-left: 20px;
|
||||
}
|
||||
#ewwwio-banner #ewww-review {
|
||||
white-space: nowrap;
|
||||
}
|
||||
#ewwwio-banner a {
|
||||
color: #272727;
|
||||
}
|
||||
#ewwwio-banner a span.dashicons {
|
||||
color: #fff;
|
||||
text-decoration: none;
|
||||
font-size: 16px;
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
}
|
||||
#ewwwio-banner #ewww-news-button {
|
||||
margin-top: 0;
|
||||
}
|
||||
#ewww-settings-form a.ewww-orange-button {
|
||||
background: #f18f07;
|
||||
border-color: #f18f07;
|
||||
}
|
||||
#ewww-settings-form a.ewww-orange-button:hover {
|
||||
background: #f39c12;
|
||||
border-color: #f18f07;
|
||||
}
|
||||
#ewww-settings-form a.ewww-orange-button:focus {
|
||||
box-shadow: 0 0 0 1px #fff,0 0 0 3px #f18f07;
|
||||
}
|
||||
#ewww-general-settings a.ewww-upgrade {
|
||||
font-weight:bold;
|
||||
background-color: #3eadc9;
|
||||
border-color: #3eadc9;
|
||||
}
|
||||
#ewww-general-settings a.ewww-upgrade:hover {
|
||||
background-color: #40bad4;
|
||||
border-color: #3ca0be;
|
||||
}
|
||||
#ewww-general-settings a.ewww-upgrade:focus {
|
||||
box-shadow: 0 0 0 1px #fff,0 0 0 3px #3ca0be;
|
||||
}
|
||||
.ewww-help-beacon-multi, .ewww-help-beacon-single, .ewww-help-external {
|
||||
margin: 3px;
|
||||
}
|
||||
/* mobile rules */
|
||||
@media screen and (max-width: 868px) {
|
||||
.ewww-blocks {
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.ewww-blocks div.ewww-status-detail {
|
||||
padding: 1em 2em;
|
||||
}
|
||||
.ewww-status-detail p {
|
||||
margin: 0.5em 0;
|
||||
}
|
||||
.ewww-blocks #ewww-notices {
|
||||
width: 100%;
|
||||
border-left: 0;
|
||||
}
|
||||
.ewww-overrides-nav {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
@media screen and (max-width: 600px) {
|
||||
#ewwwio-banner img:first-child {
|
||||
width: 100px;
|
||||
height: auto;
|
||||
}
|
||||
.ewww-blocks div.ewww-status-detail {
|
||||
padding: 1em;
|
||||
}
|
||||
.ewww-tab-nav {
|
||||
border-style: none;
|
||||
}
|
||||
.ewww-tab {
|
||||
margin: 0 0 3px 3px;
|
||||
border-style: solid;
|
||||
}
|
||||
.ewww-selected {
|
||||
border-color: #ccc;
|
||||
}
|
||||
.ewww-tab span {
|
||||
font-size: 12px;
|
||||
padding: 2px 3px;
|
||||
|
||||
}
|
||||
}
|
||||
@media screen and (max-width: 782px) {
|
||||
#ewwwio-banner .ewwwio-flex-space-between {
|
||||
flex-direction: column-reverse;
|
||||
}
|
||||
#ewwwio-banner #ewww-review a:first-child {
|
||||
padding-left: 0;
|
||||
}
|
||||
p.debug-actions {
|
||||
margin-top: 30px;
|
||||
clear: none;
|
||||
}
|
||||
#ewww-debug-info {
|
||||
width: auto;
|
||||
}
|
||||
#ewww-settings-disable-resizes th, #ewww-settings-disable-resizes td {
|
||||
display: table-cell;
|
||||
}
|
||||
#ewwwio-wizard-form input[type="checkbox"], #ewwwio-wizard-form input[type="radio"] {
|
||||
margin-top: 5px;
|
||||
}
|
||||
#ewww_image_optimizer_cloud_key_container td, #ewww_image_optimizer_exactdn_container td, #swis_promo_container td {
|
||||
padding: 10px;
|
||||
}
|
||||
}
|
@ -0,0 +1,547 @@
|
||||
(function(window, factory) {
|
||||
var globalInstall = function(){
|
||||
factory(window.lazySizes);
|
||||
window.removeEventListener('lazyunveilread', globalInstall, true);
|
||||
};
|
||||
|
||||
factory = factory.bind(null, window, window.document);
|
||||
|
||||
if(typeof module == 'object' && module.exports){
|
||||
factory(require('lazysizes'));
|
||||
} else if (typeof define == 'function' && define.amd) {
|
||||
define(['lazysizes'], factory);
|
||||
} else if(window.lazySizes) {
|
||||
globalInstall();
|
||||
} else {
|
||||
window.addEventListener('lazyunveilread', globalInstall, true);
|
||||
}
|
||||
}(window, function(window, document, lazySizes) {
|
||||
/*jshint eqnull:true */
|
||||
'use strict';
|
||||
var regBgUrlEscape;
|
||||
var autosizedElems = [];
|
||||
|
||||
if(document.addEventListener){
|
||||
regBgUrlEscape = /\(|\)|\s|'/;
|
||||
|
||||
addEventListener('lazybeforeunveil', function(e){
|
||||
if(e.detail.instance != lazySizes){return;}
|
||||
|
||||
var bg, bgWebP;
|
||||
if(!e.defaultPrevented) {
|
||||
|
||||
if(e.target.preload == 'none'){
|
||||
e.target.preload = 'auto';
|
||||
}
|
||||
|
||||
// handle data-back (so as not to conflict with the stock data-bg)
|
||||
bg = e.target.getAttribute('data-back');
|
||||
if (bg) {
|
||||
if(ewww_webp_supported) {
|
||||
console.log('checking for data-back-webp');
|
||||
bgWebP = e.target.getAttribute('data-back-webp');
|
||||
if (bgWebP) {
|
||||
console.log('replacing data-back with data-back-webp');
|
||||
bg = bgWebP;
|
||||
}
|
||||
}
|
||||
var dPR = (window.devicePixelRatio || 1);
|
||||
var targetWidth = Math.round(e.target.offsetWidth * dPR);
|
||||
var targetHeight = Math.round(e.target.offsetHeight * dPR);
|
||||
if ( 0 === bg.search(/\[/) ) {
|
||||
} else if (!shouldAutoScale(e.target)||!shouldAutoScale(e.target.parentNode)){
|
||||
} else if (lazySizes.hC(e.target,'wp-block-cover')) {
|
||||
console.log('found wp-block-cover with data-back');
|
||||
if (lazySizes.hC(e.target,'has-parallax')) {
|
||||
console.log('also has-parallax with data-back');
|
||||
targetWidth = Math.round(window.screen.width * dPR);
|
||||
targetHeight = Math.round(window.screen.height * dPR);
|
||||
} else if (targetHeight<300) {
|
||||
targetHeight = 430;
|
||||
}
|
||||
bg = constrainSrc(bg,targetWidth,targetHeight,'bg-cover');
|
||||
} else if (lazySizes.hC(e.target,'cover-image')){
|
||||
console.log('found .cover-image with data-back');
|
||||
bg = constrainSrc(bg,targetWidth,targetHeight,'bg-cover');
|
||||
} else if (lazySizes.hC(e.target,'elementor-bg')){
|
||||
console.log('found elementor-bg with data-back');
|
||||
bg = constrainSrc(bg,targetWidth,targetHeight,'bg-cover');
|
||||
} else if (lazySizes.hC(e.target,'et_parallax_bg')){
|
||||
console.log('found et_parallax_bg with data-back');
|
||||
bg = constrainSrc(bg,targetWidth,targetHeight,'bg-cover');
|
||||
} else if (lazySizes.hC(e.target,'bg-image-crop')){
|
||||
console.log('found bg-image-crop with data-back');
|
||||
bg = constrainSrc(bg,targetWidth,targetHeight,'bg-cover');
|
||||
} else {
|
||||
console.log('found other data-back');
|
||||
bg = constrainSrc(bg,targetWidth,targetHeight,'bg');
|
||||
}
|
||||
if ( e.target.style.backgroundImage && -1 === e.target.style.backgroundImage.search(/^initial/) ) {
|
||||
// Convert JSON for multiple URLs.
|
||||
if ( 0 === bg.search(/\[/) ) {
|
||||
console.log('multiple URLs to append');
|
||||
bg = JSON.parse(bg);
|
||||
bg.forEach(
|
||||
function(bg_url){
|
||||
bg_url = (regBgUrlEscape.test(bg_url) ? JSON.stringify(bg_url) : bg_url );
|
||||
}
|
||||
);
|
||||
bg = 'url("' + bg.join('"), url("') + '"';
|
||||
var new_bg = e.target.style.backgroundImage + ', ' + bg;
|
||||
console.log('setting .backgroundImage: ' + new_bg );
|
||||
e.target.style.backgroundImage = new_bg;
|
||||
} else {
|
||||
console.log( 'appending bg url: ' + e.target.style.backgroundImage + ', url(' + (regBgUrlEscape.test(bg) ? JSON.stringify(bg) : bg ) + ')' );
|
||||
e.target.style.backgroundImage = e.target.style.backgroundImage + ', url("' + (regBgUrlEscape.test(bg) ? JSON.stringify(bg) : bg ) + '")';
|
||||
}
|
||||
} else {
|
||||
// Convert JSON for multiple URLs.
|
||||
if ( 0 === bg.search(/\[/) ) {
|
||||
console.log('multiple URLs to insert');
|
||||
bg = JSON.parse(bg);
|
||||
bg.forEach(
|
||||
function(bg_url){
|
||||
bg_url = (regBgUrlEscape.test(bg_url) ? JSON.stringify(bg_url) : bg_url );
|
||||
}
|
||||
);
|
||||
bg = 'url("' + bg.join('"), url("') + '"';
|
||||
console.log('setting .backgroundImage: ' + bg );
|
||||
e.target.style.backgroundImage = bg;
|
||||
} else {
|
||||
console.log('setting .backgroundImage: ' + 'url(' + (regBgUrlEscape.test(bg) ? JSON.stringify(bg) : bg ) + ')');
|
||||
e.target.style.backgroundImage = 'url(' + (regBgUrlEscape.test(bg) ? JSON.stringify(bg) : bg ) + ')';
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}, false);
|
||||
}
|
||||
|
||||
var shouldAutoScale = function(target){
|
||||
if (eio_lazy_vars.skip_autoscale == 1) {
|
||||
console.log('autoscale disabled globally');
|
||||
return false;
|
||||
}
|
||||
if (target.hasAttributes()) {
|
||||
var attrs = target.attributes
|
||||
var regNoScale = /skip-autoscale/;
|
||||
for (var i = attrs.length - 1; i >= 0; i--) {
|
||||
if (regNoScale.test(attrs[i].name)) {
|
||||
console.log('autoscale disabled by attr');
|
||||
return false;
|
||||
}
|
||||
if (regNoScale.test(attrs[i].value)) {
|
||||
console.log('autoscale disabled by attr value');
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
var constrainSrc = function(url,objectWidth,objectHeight,objectType,upScale = false){
|
||||
if (url===null){
|
||||
return url;
|
||||
}
|
||||
console.log('constrain ' + url + ' to ' + objectWidth + 'x' + objectHeight + ' with type ' + objectType);
|
||||
var regW = /w=(\d+)/;
|
||||
var regFit = /fit=(\d+),(\d+)/;
|
||||
var regResize = /resize=(\d+),(\d+)/;
|
||||
var regSVG = /\.svg(\?.+)?$/;
|
||||
var decUrl = decodeURIComponent(url);
|
||||
if (regSVG.exec(decUrl)){
|
||||
return url;
|
||||
}
|
||||
console.log('domain to test: ' + eio_lazy_vars.exactdn_domain);
|
||||
if (url.search('\\?') > 0 && url.search(eio_lazy_vars.exactdn_domain) > 0){
|
||||
console.log('domain matches URL with a ?');
|
||||
var resultResize = regResize.exec(decUrl);
|
||||
if(resultResize && (objectWidth < resultResize[1] || upScale)){
|
||||
if('img-w'===objectType){
|
||||
console.log('resize param found, replacing in ' + objectType);
|
||||
return decUrl.replace(regResize, 'w=' + objectWidth );
|
||||
}
|
||||
if('img-h'===objectType){
|
||||
console.log('resize param found, replacing in ' + objectType);
|
||||
return decUrl.replace(regResize, 'h=' + objectHeight );
|
||||
}
|
||||
console.log('resize param found, replacing');
|
||||
return decUrl.replace(regResize, 'resize=' + objectWidth + ',' + objectHeight);
|
||||
}
|
||||
var resultW = regW.exec(url);
|
||||
if(resultW && (objectWidth <= resultW[1] || upScale)){
|
||||
if('img-h'===objectType){
|
||||
console.log('w param found, replacing in ' + objectType);
|
||||
return decUrl.replace(regW, 'h=' + objectHeight );
|
||||
}
|
||||
if('bg-cover'===objectType || 'img-crop'===objectType){
|
||||
var diff = Math.abs(resultW[1] - objectWidth);
|
||||
if ( diff > 20 || objectHeight < 1080 ) {
|
||||
console.log('w param found, replacing in ' + objectType);
|
||||
return url.replace(regW, 'resize=' + objectWidth + ',' + objectHeight );
|
||||
}
|
||||
console.log('w param found, but only ' + diff + ' pixels off, ignoring');
|
||||
return url;
|
||||
}
|
||||
console.log('w param found, replacing');
|
||||
return url.replace(regW, 'w=' + objectWidth);
|
||||
}
|
||||
var resultFit = regFit.exec(decUrl);
|
||||
if(resultFit && (objectWidth < resultFit[1] || upScale)){
|
||||
if('bg-cover'===objectType || 'img-crop'===objectType){
|
||||
var wDiff = Math.abs(resultFit[1] - objectWidth);
|
||||
var hDiff = Math.abs(resultFit[2] - objectHeight);
|
||||
if ( wDiff > 20 || hDiff > 20 ) {
|
||||
console.log('fit param found, replacing in ' + objectType);
|
||||
return url.replace(regW, 'resize=' + objectWidth + ',' + objectHeight );
|
||||
}
|
||||
console.log('fit param found, but only w' + wDiff + '/h' + hDiff + ' pixels off, ignoring');
|
||||
return url;
|
||||
}
|
||||
if('img-w'===objectType){
|
||||
console.log('fit param found, replacing in ' + objectType);
|
||||
return decUrl.replace(regFit, 'w=' + objectWidth );
|
||||
}
|
||||
if('img-h'===objectType){
|
||||
console.log('fit param found, replacing in ' + objectType);
|
||||
return decUrl.replace(regFit, 'h=' + objectHeight );
|
||||
}
|
||||
console.log('fit param found, replacing');
|
||||
return decUrl.replace(regFit, 'fit=' + objectWidth + ',' + objectHeight);
|
||||
}
|
||||
if(!resultW && !resultFit && !resultResize){
|
||||
console.log('no param found, appending');
|
||||
if('img'===objectType){
|
||||
console.log('for ' + objectType);
|
||||
return url + '&fit=' + objectWidth + ',' + objectHeight;
|
||||
}
|
||||
if('bg-cover'===objectType || 'img-crop'===objectType){
|
||||
console.log('for ' + objectType);
|
||||
return url + '&resize=' + objectWidth + ',' + objectHeight;
|
||||
}
|
||||
if('img-h'===objectType || objectHeight>objectWidth){
|
||||
console.log('img-h or fallback height>width, using h param');
|
||||
return url + '&h=' + objectHeight;
|
||||
}
|
||||
console.log('fallback using w param');
|
||||
return url + '&w=' + objectWidth;
|
||||
}
|
||||
}
|
||||
if (url.search('\\?') == -1 && url.search(eio_lazy_vars.exactdn_domain) > 0){
|
||||
console.log('domain matches URL without a ?, appending query string');
|
||||
if('img'===objectType){
|
||||
console.log('for ' + objectType);
|
||||
return url + '?fit=' + objectWidth + ',' + objectHeight;
|
||||
}
|
||||
if('bg-cover'===objectType || 'img-crop'===objectType){
|
||||
console.log('for ' + objectType);
|
||||
return url + '?resize=' + objectWidth + ',' + objectHeight;
|
||||
}
|
||||
if('img-h'===objectType || objectHeight>objectWidth){
|
||||
console.log('img-h or fallback height>width, using h param');
|
||||
return url + '?h=' + objectHeight;
|
||||
}
|
||||
console.log('fallback using w param');
|
||||
return url + '?w=' + objectWidth;
|
||||
}
|
||||
console.log('boo, just using same url');
|
||||
return url;
|
||||
};
|
||||
|
||||
var getImgType = function(elem){
|
||||
if ( lazySizes.hC(elem,'et_pb_jt_filterable_grid_item_image') || lazySizes.hC(elem,'ss-foreground-image') || lazySizes.hC(elem,'img-crop') ) {
|
||||
console.log('img that needs a hard crop');
|
||||
return 'img-crop';
|
||||
} else if (
|
||||
lazySizes.hC(elem,'object-cover') &&
|
||||
( lazySizes.hC(elem,'object-top') || lazySizes.hC(elem,'object-bottom') )
|
||||
) {
|
||||
console.log('cover img that needs a width scale');
|
||||
return 'img-w';
|
||||
} else if (
|
||||
lazySizes.hC(elem,'object-cover') &&
|
||||
( lazySizes.hC(elem,'object-left') || lazySizes.hC(elem,'object-right') )
|
||||
) {
|
||||
console.log('cover img that needs a height scale');
|
||||
return 'img-h';
|
||||
} else if ( lazySizes.hC(elem,'ct-image') && lazySizes.hC(elem,'object-cover') ) {
|
||||
console.log('Oxygen cover img that needs a hard crop');
|
||||
return 'img-crop';
|
||||
} else if ( ! elem.getAttribute('data-srcset') && ! elem.srcset && elem.offsetHeight > elem.offsetWidth && getAspectRatio(elem) > 1 ) {
|
||||
console.log('non-srcset img with portrait display, landscape in real life');
|
||||
return 'img-crop';
|
||||
}
|
||||
console.log('plain old img, constraining');
|
||||
return 'img';
|
||||
};
|
||||
|
||||
var getDimensionsFromURL = function(url){
|
||||
var regDims = /-(\d+)x(\d+)\./;
|
||||
var resultDims = regDims.exec(url);
|
||||
if (resultDims && resultDims[1] > 1 && resultDims[2] > 1) {
|
||||
return {w:resultDims[1],h:resultDims[2]};
|
||||
}
|
||||
return {w:0,h:0};
|
||||
};
|
||||
|
||||
var getRealDimensionsFromImg = function(img){
|
||||
var realWidth = img.getAttribute('data-eio-rwidth');
|
||||
var realHeight = img.getAttribute('data-eio-rheight');
|
||||
if (realWidth > 1 && realHeight > 1) {
|
||||
return {w:realWidth,h:realHeight};
|
||||
}
|
||||
return {w:0,h:0};
|
||||
};
|
||||
|
||||
var getSrcsetDims = function(img) {
|
||||
var srcSet;
|
||||
if (img.srcset){
|
||||
srcSet = img.srcset.split(',');
|
||||
} else {
|
||||
var srcSetAttr = img.getAttribute('data-srcset');
|
||||
if (srcSetAttr){
|
||||
srcSet = srcSetAttr.split(',');
|
||||
}
|
||||
}
|
||||
if (srcSet){
|
||||
var i = 0;
|
||||
var len = srcSet.length;
|
||||
if (len){
|
||||
for (; i < len; i++){
|
||||
var src = srcSet[i].trim().split(' ');
|
||||
if (src[0].length) {
|
||||
var nextDims = getDimensionsFromURL(src[0]);
|
||||
if (nextDims.w && nextDims.h){
|
||||
var srcSetDims = nextDims;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (srcSetDims.w && srcSetDims.h){
|
||||
return srcSetDims;
|
||||
}
|
||||
}
|
||||
}
|
||||
return {w:0,h:0};
|
||||
}
|
||||
|
||||
var getAspectRatio = function(img){
|
||||
var width = img.getAttribute('width');
|
||||
var height = img.getAttribute('height');
|
||||
if (width > 1 && height > 1){
|
||||
console.log('found dims ' + width + 'x' + height + ', returning ' + width/height);
|
||||
return width / height;
|
||||
}
|
||||
var src = false;
|
||||
if (img.src && img.src.search('http') > -1) {
|
||||
src = img.src;
|
||||
}
|
||||
if (!src) {
|
||||
src = img.getAttribute('data-src');
|
||||
}
|
||||
if (src){
|
||||
var urlDims = getDimensionsFromURL(src);
|
||||
if (urlDims.w && urlDims.h) {
|
||||
console.log('found dims from URL: ' + urlDims.w + 'x' + urlDims.h);
|
||||
return urlDims.w / urlDims.h;
|
||||
}
|
||||
}
|
||||
var realDims = getRealDimensionsFromImg(img);
|
||||
if (realDims.w && realDims.h){
|
||||
console.log('found dims from eio-attrs: ' + realDims.w + 'x' + realDims.h);
|
||||
return realDims.w / realDims.h;
|
||||
}
|
||||
var srcSetDims = getSrcsetDims(img);
|
||||
if (srcSetDims.w && srcSetDims.h){
|
||||
console.log('largest found dims from srcset: ' + srcSetDims.w + 'x' + srcSetDims.h);
|
||||
return srcSetDims.w / srcSetDims.h;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
var updateImgElem = function(target,upScale=false){
|
||||
var dPR = (window.devicePixelRatio || 1);
|
||||
var targetWidth = Math.round(target.offsetWidth * dPR);
|
||||
var targetHeight = Math.round(target.offsetHeight * dPR);
|
||||
|
||||
var src = target.getAttribute('data-src');
|
||||
var webpsrc = target.getAttribute('data-src-webp');
|
||||
if(ewww_webp_supported && webpsrc && -1 == src.search('webp=1') && !upScale){
|
||||
console.log('using data-src-webp');
|
||||
src = webpsrc;
|
||||
}
|
||||
if (!shouldAutoScale(target)||!shouldAutoScale(target.parentNode)){
|
||||
return;
|
||||
}
|
||||
var imgType = getImgType(target);
|
||||
var newSrc = constrainSrc(src,targetWidth,targetHeight,imgType,upScale);
|
||||
if (newSrc && src != newSrc){
|
||||
console.log('new src: ' + newSrc);
|
||||
if (upScale){
|
||||
target.setAttribute('src', newSrc);
|
||||
}
|
||||
target.setAttribute('data-src', newSrc);
|
||||
}
|
||||
};
|
||||
|
||||
document.addEventListener('lazybeforesizes', function(e){
|
||||
var src = e.target.getAttribute('data-src');
|
||||
console.log('auto-sizing ' + src + ' to: ' + e.detail.width);
|
||||
var imgAspect = getAspectRatio(e.target);
|
||||
if (e.target.clientHeight > 1 && imgAspect) {
|
||||
var minimum_width = Math.ceil(imgAspect * e.target.clientHeight);
|
||||
console.log('minimum_width = ' + minimum_width);
|
||||
if (e.detail.width+2 < minimum_width) {
|
||||
e.detail.width = minimum_width;
|
||||
}
|
||||
}
|
||||
if (e.target._lazysizesWidth === undefined) {
|
||||
return;
|
||||
}
|
||||
console.log('previous width was ' + e.target._lazysizesWidth);
|
||||
if (e.detail.width < e.target._lazysizesWidth) {
|
||||
console.log('no way! ' + e.detail.width + ' is smaller than ' + e.target._lazysizesWidth);
|
||||
e.detail.width = e.target._lazysizesWidth;
|
||||
}
|
||||
});
|
||||
|
||||
document.addEventListener('lazybeforeunveil', function(e){
|
||||
var target = e.target;
|
||||
console.log('loading an image');
|
||||
console.log(target);
|
||||
var srcset = target.getAttribute('data-srcset');
|
||||
if (target.naturalWidth && ! srcset) {
|
||||
console.log('natural width of ' + target.getAttribute('src') + ' is ' + target.naturalWidth);
|
||||
console.log('we have an image with no srcset');
|
||||
if ((target.naturalWidth > 1) && (target.naturalHeight > 1)) {
|
||||
// For each image with a natural width which isn't
|
||||
// a 1x1 image, check its size.
|
||||
var dPR = (window.devicePixelRatio || 1);
|
||||
var physicalWidth = target.naturalWidth;
|
||||
var physicalHeight = target.naturalHeight;
|
||||
var realDims = getRealDimensionsFromImg(target);
|
||||
if (realDims.w && realDims.w > physicalWidth) {
|
||||
console.log( 'using ' + realDims.w + 'w instead of ' + physicalWidth + 'w and ' + realDims.h + 'h instead of ' + physicalHeight + 'h from data-eio-r*')
|
||||
physicalWidth = realDims.w;
|
||||
physicalHeight = realDims.h;
|
||||
}
|
||||
var wrongWidth = (target.clientWidth && (target.clientWidth * 1.25 * dPR < physicalWidth));
|
||||
var wrongHeight = (target.clientHeight && (target.clientHeight * 1.25 * dPR < physicalHeight));
|
||||
console.log('displayed at ' + Math.round(target.clientWidth * dPR) + 'w x ' + Math.round(target.clientHeight * dPR) + 'h, natural/physical is ' +
|
||||
physicalWidth + 'w x ' + physicalHeight + 'h!');
|
||||
console.log('the data-src: ' + target.getAttribute('data-src') );
|
||||
if (wrongWidth || wrongHeight) {
|
||||
updateImgElem(target);
|
||||
}
|
||||
}
|
||||
}
|
||||
if(ewww_webp_supported) {
|
||||
console.log('webp supported');
|
||||
//console.log(srcset);
|
||||
if (srcset) {
|
||||
console.log('srcset available');
|
||||
var webpsrcset = target.getAttribute('data-srcset-webp');
|
||||
if(webpsrcset){
|
||||
console.log('replacing data-srcset with data-srcset-webp');
|
||||
target.setAttribute('data-srcset', webpsrcset);
|
||||
}
|
||||
}
|
||||
var webpsrc = target.getAttribute('data-src-webp');
|
||||
if(!webpsrc){
|
||||
console.log('no data-src-webp attr');
|
||||
return;
|
||||
}
|
||||
console.log('replacing data-src with data-src-webp');
|
||||
target.setAttribute('data-src', webpsrc);
|
||||
}
|
||||
});
|
||||
|
||||
// Based on http://modernjavascript.blogspot.de/2013/08/building-better-debounce.html
|
||||
var debounce = function(func) {
|
||||
var timeout, timestamp;
|
||||
var wait = 99;
|
||||
var run = function(){
|
||||
timeout = null;
|
||||
func();
|
||||
};
|
||||
var later = function() {
|
||||
var last = Date.now() - timestamp;
|
||||
|
||||
if (last < wait) {
|
||||
setTimeout(later, wait - last);
|
||||
} else {
|
||||
(window.requestIdleCallback || run)(run);
|
||||
}
|
||||
};
|
||||
|
||||
return function() {
|
||||
timestamp = Date.now();
|
||||
|
||||
if (!timeout) {
|
||||
timeout = setTimeout(later, wait);
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
var recheckLazyElements = function(event = false) {
|
||||
console.log('rechecking elements:');
|
||||
if (event.type) {
|
||||
console.log(event.type);
|
||||
if ('load'===event.type) {
|
||||
lazySizes.autoSizer.checkElems();
|
||||
}
|
||||
}
|
||||
var dPR = (window.devicePixelRatio || 1);
|
||||
var autosizedElems = document.getElementsByClassName(lazySizes.cfg.loadedClass);
|
||||
var i;
|
||||
var len = autosizedElems.length;
|
||||
if(len){
|
||||
i = 0;
|
||||
|
||||
for(; i < len; i++){
|
||||
var autosizedElem = autosizedElems[i];
|
||||
if (autosizedElem.src && ! autosizedElem.srcset && autosizedElem.naturalWidth > 1 && autosizedElem.naturalHeight > 1 && autosizedElem.clientWidth > 1 && autosizedElem.clientHeight > 1){
|
||||
console.log(autosizedElem);
|
||||
console.log('natural width of ' + autosizedElem.src + ' is ' + autosizedElem.naturalWidth);
|
||||
// For each image with a natural width which isn't
|
||||
// a 1x1 image, check its size.
|
||||
var physicalWidth = autosizedElem.naturalWidth;
|
||||
var physicalHeight = autosizedElem.naturalHeight;
|
||||
var maxWidth = window.innerWidth;
|
||||
var maxHeight = window.innerHeight;
|
||||
var realDims = getRealDimensionsFromImg(autosizedElem);
|
||||
var urlDims = getDimensionsFromURL(autosizedElem.src);
|
||||
|
||||
if (realDims.w) {
|
||||
maxWidth = realDims.w;
|
||||
} else if (urlDims.w) {
|
||||
maxWidth = urlDims.w;
|
||||
}
|
||||
if (realDims.h) {
|
||||
maxHeight = realDims.h;
|
||||
} else if (urlDims.h) {
|
||||
maxHeight = urlDims.h;
|
||||
}
|
||||
console.log( 'max image size is ' + maxWidth + 'w, ' + maxHeight + 'h');
|
||||
|
||||
// For upscaling, the goal is to get to 1x dPR, we won't waste bandwidth on retina/2x images.
|
||||
var desiredWidth = autosizedElem.clientWidth;
|
||||
var desiredHeight = autosizedElem.clientHeight;
|
||||
var wrongWidth = (desiredWidth > physicalWidth * 1.1 && maxWidth >= desiredWidth);
|
||||
var wrongHeight = (desiredHeight > physicalHeight * 1.1 && maxHeight >= desiredHeight);
|
||||
console.log('displayed at ' + Math.round(desiredWidth) + 'w x ' + Math.round(desiredHeight) + 'h, natural/physical is ' +
|
||||
physicalWidth + 'w x ' + physicalHeight + 'h');
|
||||
if (wrongWidth || wrongHeight) {
|
||||
console.log('requesting upsize');
|
||||
updateImgElem(autosizedElem,true);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
var debouncedRecheckElements = debounce(recheckLazyElements);
|
||||
|
||||
addEventListener('load', recheckLazyElements);
|
||||
addEventListener('resize', debouncedRecheckElements);
|
||||
setTimeout(recheckLazyElements, 20000);
|
||||
}));
|
@ -0,0 +1,17 @@
|
||||
if (typeof ewww_webp_supported === 'undefined') {
|
||||
var ewww_webp_supported = false;
|
||||
}
|
||||
window.lazySizesConfig = window.lazySizesConfig || {};
|
||||
window.lazySizesConfig.expand = document.documentElement.clientHeight > 500 && document.documentElement.clientWidth > 500 ? 1000 : 740;
|
||||
if (typeof eio_lazy_vars === 'undefined'){
|
||||
console.log('setting failsafe lazy vars');
|
||||
eio_lazy_vars = {
|
||||
exactdn_domain: '.exactdn.com',
|
||||
threshold: 0,
|
||||
skip_autoscale: 0,
|
||||
};
|
||||
}
|
||||
if (eio_lazy_vars.threshold > 50) {
|
||||
window.lazySizesConfig.expand = eio_lazy_vars.threshold;
|
||||
}
|
||||
console.log( 'root margin: ' + window.lazySizesConfig.expand );
|
760
wp-content/plugins/ewww-image-optimizer/includes/lazysizes.js
Normal file
@ -0,0 +1,760 @@
|
||||
// version 5.3.0
|
||||
(function(window, factory) {
|
||||
var lazySizes = factory(window, window.document, Date);
|
||||
window.lazySizes = lazySizes;
|
||||
if(typeof module == 'object' && module.exports){
|
||||
module.exports = lazySizes;
|
||||
}
|
||||
}(typeof window != 'undefined' ?
|
||||
window : {}, function l(window, document, Date) { // Pass in the windoe Date function also for SSR because the Date class can be lost
|
||||
'use strict';
|
||||
/*jshint eqnull:true */
|
||||
|
||||
var lazysizes, lazySizesCfg;
|
||||
|
||||
(function(){
|
||||
var prop;
|
||||
|
||||
var lazySizesDefaults = {
|
||||
lazyClass: 'lazyload',
|
||||
loadedClass: 'lazyloaded',
|
||||
loadingClass: 'lazyloading',
|
||||
preloadClass: 'lazypreload',
|
||||
errorClass: 'lazyerror',
|
||||
//strictClass: 'lazystrict',
|
||||
autosizesClass: 'lazyautosizes',
|
||||
fastLoadedClass: 'ls-is-cached',
|
||||
iframeLoadMode: 0,
|
||||
srcAttr: 'data-src',
|
||||
srcsetAttr: 'data-srcset',
|
||||
sizesAttr: 'data-sizes',
|
||||
//preloadAfterLoad: false,
|
||||
minSize: 40,
|
||||
customMedia: {},
|
||||
init: true,
|
||||
expFactor: 1.5,
|
||||
hFac: 0.8,
|
||||
loadMode: 2,
|
||||
loadHidden: true,
|
||||
ricTimeout: 0,
|
||||
throttleDelay: 125,
|
||||
};
|
||||
|
||||
lazySizesCfg = window.lazySizesConfig || window.lazysizesConfig || {};
|
||||
|
||||
for(prop in lazySizesDefaults){
|
||||
if(!(prop in lazySizesCfg)){
|
||||
lazySizesCfg[prop] = lazySizesDefaults[prop];
|
||||
}
|
||||
}
|
||||
})();
|
||||
|
||||
if (!document || !document.getElementsByClassName) {
|
||||
return {
|
||||
init: function () {},
|
||||
cfg: lazySizesCfg,
|
||||
noSupport: true,
|
||||
};
|
||||
}
|
||||
|
||||
var docElem = document.documentElement;
|
||||
|
||||
var supportPicture = window.HTMLPictureElement;
|
||||
|
||||
var _addEventListener = 'addEventListener';
|
||||
|
||||
var _getAttribute = 'getAttribute';
|
||||
|
||||
/**
|
||||
* Update to bind to window because 'this' becomes null during SSR
|
||||
* builds.
|
||||
*/
|
||||
var addEventListener = window[_addEventListener].bind(window);
|
||||
|
||||
var setTimeout = window.setTimeout;
|
||||
|
||||
var requestAnimationFrame = window.requestAnimationFrame || setTimeout;
|
||||
|
||||
var requestIdleCallback = window.requestIdleCallback;
|
||||
|
||||
var regPicture = /^picture$/i;
|
||||
|
||||
var loadEvents = ['load', 'error', 'lazyincluded', '_lazyloaded'];
|
||||
|
||||
var regClassCache = {};
|
||||
|
||||
var forEach = Array.prototype.forEach;
|
||||
|
||||
var hasClass = function(ele, cls) {
|
||||
if(!regClassCache[cls]){
|
||||
regClassCache[cls] = new RegExp('(\\s|^)'+cls+'(\\s|$)');
|
||||
}
|
||||
return regClassCache[cls].test(ele[_getAttribute]('class') || '') && regClassCache[cls];
|
||||
};
|
||||
|
||||
var addClass = function(ele, cls) {
|
||||
if (!hasClass(ele, cls)){
|
||||
ele.setAttribute('class', (ele[_getAttribute]('class') || '').trim() + ' ' + cls);
|
||||
}
|
||||
};
|
||||
|
||||
var removeClass = function(ele, cls) {
|
||||
var reg;
|
||||
if ((reg = hasClass(ele,cls))) {
|
||||
ele.setAttribute('class', (ele[_getAttribute]('class') || '').replace(reg, ' '));
|
||||
}
|
||||
};
|
||||
|
||||
var addRemoveLoadEvents = function(dom, fn, add){
|
||||
var action = add ? _addEventListener : 'removeEventListener';
|
||||
if(add){
|
||||
addRemoveLoadEvents(dom, fn);
|
||||
}
|
||||
loadEvents.forEach(function(evt){
|
||||
dom[action](evt, fn);
|
||||
});
|
||||
};
|
||||
|
||||
var triggerEvent = function(elem, name, detail, noBubbles, noCancelable){
|
||||
var event = document.createEvent('Event');
|
||||
|
||||
if(!detail){
|
||||
detail = {};
|
||||
}
|
||||
|
||||
detail.instance = lazysizes;
|
||||
|
||||
event.initEvent(name, !noBubbles, !noCancelable);
|
||||
|
||||
event.detail = detail;
|
||||
|
||||
elem.dispatchEvent(event);
|
||||
return event;
|
||||
};
|
||||
|
||||
var updatePolyfill = function (el, full){
|
||||
var polyfill;
|
||||
if( !supportPicture && ( polyfill = (window.picturefill || lazySizesCfg.pf) ) ){
|
||||
if(full && full.src && !el[_getAttribute]('srcset')){
|
||||
el.setAttribute('srcset', full.src);
|
||||
}
|
||||
polyfill({reevaluate: true, elements: [el]});
|
||||
} else if(full && full.src){
|
||||
el.src = full.src;
|
||||
}
|
||||
};
|
||||
|
||||
var getCSS = function (elem, style){
|
||||
return (getComputedStyle(elem, null) || {})[style];
|
||||
};
|
||||
|
||||
var getWidth = function(elem, parent, width){
|
||||
width = width || elem.offsetWidth;
|
||||
|
||||
while(width < lazySizesCfg.minSize && parent && !elem._lazysizesWidth){
|
||||
width = parent.offsetWidth;
|
||||
parent = parent.parentNode;
|
||||
}
|
||||
|
||||
return width;
|
||||
};
|
||||
|
||||
var rAF = (function(){
|
||||
var running, waiting;
|
||||
var firstFns = [];
|
||||
var secondFns = [];
|
||||
var fns = firstFns;
|
||||
|
||||
var run = function(){
|
||||
var runFns = fns;
|
||||
|
||||
fns = firstFns.length ? secondFns : firstFns;
|
||||
|
||||
running = true;
|
||||
waiting = false;
|
||||
|
||||
while(runFns.length){
|
||||
runFns.shift()();
|
||||
}
|
||||
|
||||
running = false;
|
||||
};
|
||||
|
||||
var rafBatch = function(fn, queue){
|
||||
if(running && !queue){
|
||||
fn.apply(this, arguments);
|
||||
} else {
|
||||
fns.push(fn);
|
||||
|
||||
if(!waiting){
|
||||
waiting = true;
|
||||
(document.hidden ? setTimeout : requestAnimationFrame)(run);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
rafBatch._lsFlush = run;
|
||||
|
||||
return rafBatch;
|
||||
})();
|
||||
|
||||
var rAFIt = function(fn, simple){
|
||||
return simple ?
|
||||
function() {
|
||||
rAF(fn);
|
||||
} :
|
||||
function(){
|
||||
var that = this;
|
||||
var args = arguments;
|
||||
rAF(function(){
|
||||
fn.apply(that, args);
|
||||
});
|
||||
}
|
||||
;
|
||||
};
|
||||
|
||||
var throttle = function(fn){
|
||||
var running;
|
||||
var lastTime = 0;
|
||||
var gDelay = lazySizesCfg.throttleDelay;
|
||||
var rICTimeout = lazySizesCfg.ricTimeout;
|
||||
var run = function(){
|
||||
running = false;
|
||||
lastTime = Date.now();
|
||||
fn();
|
||||
};
|
||||
var idleCallback = requestIdleCallback && rICTimeout > 49 ?
|
||||
function(){
|
||||
requestIdleCallback(run, {timeout: rICTimeout});
|
||||
|
||||
if(rICTimeout !== lazySizesCfg.ricTimeout){
|
||||
rICTimeout = lazySizesCfg.ricTimeout;
|
||||
}
|
||||
} :
|
||||
rAFIt(function(){
|
||||
setTimeout(run);
|
||||
}, true)
|
||||
;
|
||||
|
||||
return function(isPriority){
|
||||
var delay;
|
||||
|
||||
if((isPriority = isPriority === true)){
|
||||
rICTimeout = 33;
|
||||
}
|
||||
|
||||
if(running){
|
||||
return;
|
||||
}
|
||||
|
||||
running = true;
|
||||
|
||||
delay = gDelay - (Date.now() - lastTime);
|
||||
|
||||
if(delay < 0){
|
||||
delay = 0;
|
||||
}
|
||||
|
||||
if(isPriority || delay < 9){
|
||||
idleCallback();
|
||||
} else {
|
||||
setTimeout(idleCallback, delay);
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
//based on http://modernjavascript.blogspot.de/2013/08/building-better-debounce.html
|
||||
var debounce = function(func) {
|
||||
var timeout, timestamp;
|
||||
var wait = 99;
|
||||
var run = function(){
|
||||
timeout = null;
|
||||
func();
|
||||
};
|
||||
var later = function() {
|
||||
var last = Date.now() - timestamp;
|
||||
|
||||
if (last < wait) {
|
||||
setTimeout(later, wait - last);
|
||||
} else {
|
||||
(requestIdleCallback || run)(run);
|
||||
}
|
||||
};
|
||||
|
||||
return function() {
|
||||
timestamp = Date.now();
|
||||
|
||||
if (!timeout) {
|
||||
timeout = setTimeout(later, wait);
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
var loader = (function(){
|
||||
var preloadElems, isCompleted, resetPreloadingTimer, loadMode, started;
|
||||
|
||||
var eLvW, elvH, eLtop, eLleft, eLright, eLbottom, isBodyHidden;
|
||||
|
||||
var regImg = /^img$/i;
|
||||
var regIframe = /^iframe$/i;
|
||||
|
||||
var supportScroll = ('onscroll' in window) && !(/(gle|ing)bot/.test(navigator.userAgent));
|
||||
|
||||
var shrinkExpand = 0;
|
||||
var currentExpand = 0;
|
||||
|
||||
var isLoading = 0;
|
||||
var lowRuns = -1;
|
||||
|
||||
var resetPreloading = function(e){
|
||||
isLoading--;
|
||||
if(!e || isLoading < 0 || !e.target){
|
||||
isLoading = 0;
|
||||
}
|
||||
};
|
||||
|
||||
var isVisible = function (elem) {
|
||||
if (isBodyHidden == null) {
|
||||
isBodyHidden = getCSS(document.body, 'visibility') == 'hidden';
|
||||
}
|
||||
|
||||
return isBodyHidden || !(getCSS(elem.parentNode, 'visibility') == 'hidden' && getCSS(elem, 'visibility') == 'hidden');
|
||||
};
|
||||
|
||||
var isNestedVisible = function(elem, elemExpand){
|
||||
var outerRect;
|
||||
var parent = elem;
|
||||
var visible = isVisible(elem);
|
||||
|
||||
eLtop -= elemExpand;
|
||||
eLbottom += elemExpand;
|
||||
eLleft -= elemExpand;
|
||||
eLright += elemExpand;
|
||||
|
||||
while(visible && (parent = parent.offsetParent) && parent != document.body && parent != docElem){
|
||||
visible = ((getCSS(parent, 'opacity') || 1) > 0);
|
||||
|
||||
if(visible && getCSS(parent, 'overflow') != 'visible'){
|
||||
outerRect = parent.getBoundingClientRect();
|
||||
visible = eLright > outerRect.left &&
|
||||
eLleft < outerRect.right &&
|
||||
eLbottom > outerRect.top - 1 &&
|
||||
eLtop < outerRect.bottom + 1
|
||||
;
|
||||
}
|
||||
}
|
||||
|
||||
return visible;
|
||||
};
|
||||
|
||||
var checkElements = function() {
|
||||
var eLlen, i, rect, autoLoadElem, loadedSomething, elemExpand, elemNegativeExpand, elemExpandVal,
|
||||
beforeExpandVal, defaultExpand, preloadExpand, hFac;
|
||||
var lazyloadElems = lazysizes.elements;
|
||||
|
||||
if((loadMode = lazySizesCfg.loadMode) && isLoading < 8 && (eLlen = lazyloadElems.length)){
|
||||
|
||||
i = 0;
|
||||
|
||||
lowRuns++;
|
||||
|
||||
for(; i < eLlen; i++){
|
||||
|
||||
if(!lazyloadElems[i] || lazyloadElems[i]._lazyRace){continue;}
|
||||
|
||||
if(!supportScroll || (lazysizes.prematureUnveil && lazysizes.prematureUnveil(lazyloadElems[i]))){unveilElement(lazyloadElems[i]);continue;}
|
||||
|
||||
if(!(elemExpandVal = lazyloadElems[i][_getAttribute]('data-expand')) || !(elemExpand = elemExpandVal * 1)){
|
||||
elemExpand = currentExpand;
|
||||
}
|
||||
|
||||
if (!defaultExpand) {
|
||||
defaultExpand = (!lazySizesCfg.expand || lazySizesCfg.expand < 1) ?
|
||||
docElem.clientHeight > 500 && docElem.clientWidth > 500 ? 500 : 370 :
|
||||
lazySizesCfg.expand;
|
||||
|
||||
lazysizes._defEx = defaultExpand;
|
||||
|
||||
preloadExpand = defaultExpand * lazySizesCfg.expFactor;
|
||||
hFac = lazySizesCfg.hFac;
|
||||
isBodyHidden = null;
|
||||
|
||||
if(currentExpand < preloadExpand && isLoading < 1 && lowRuns > 2 && loadMode > 2 && !document.hidden){
|
||||
currentExpand = preloadExpand;
|
||||
lowRuns = 0;
|
||||
} else if(loadMode > 1 && lowRuns > 1 && isLoading < 6){
|
||||
currentExpand = defaultExpand;
|
||||
} else {
|
||||
currentExpand = shrinkExpand;
|
||||
}
|
||||
}
|
||||
|
||||
if(beforeExpandVal !== elemExpand){
|
||||
eLvW = innerWidth + (elemExpand * hFac);
|
||||
elvH = innerHeight + elemExpand;
|
||||
elemNegativeExpand = elemExpand * -1;
|
||||
beforeExpandVal = elemExpand;
|
||||
}
|
||||
|
||||
rect = lazyloadElems[i].getBoundingClientRect();
|
||||
|
||||
if ((eLbottom = rect.bottom) >= elemNegativeExpand &&
|
||||
(eLtop = rect.top) <= elvH &&
|
||||
(eLright = rect.right) >= elemNegativeExpand * hFac &&
|
||||
(eLleft = rect.left) <= eLvW &&
|
||||
(eLbottom || eLright || eLleft || eLtop) &&
|
||||
(lazySizesCfg.loadHidden || isVisible(lazyloadElems[i])) &&
|
||||
((isCompleted && isLoading < 3 && !elemExpandVal && (loadMode < 3 || lowRuns < 4)) || isNestedVisible(lazyloadElems[i], elemExpand))){
|
||||
unveilElement(lazyloadElems[i]);
|
||||
loadedSomething = true;
|
||||
if(isLoading > 9){break;}
|
||||
} else if(!loadedSomething && isCompleted && !autoLoadElem &&
|
||||
isLoading < 4 && lowRuns < 4 && loadMode > 2 &&
|
||||
(preloadElems[0] || lazySizesCfg.preloadAfterLoad) &&
|
||||
(preloadElems[0] || (!elemExpandVal && ((eLbottom || eLright || eLleft || eLtop) || lazyloadElems[i][_getAttribute](lazySizesCfg.sizesAttr) != 'auto')))){
|
||||
autoLoadElem = preloadElems[0] || lazyloadElems[i];
|
||||
}
|
||||
}
|
||||
|
||||
if(autoLoadElem && !loadedSomething){
|
||||
unveilElement(autoLoadElem);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
var throttledCheckElements = throttle(checkElements);
|
||||
|
||||
var switchLoadingClass = function(e){
|
||||
var elem = e.target;
|
||||
|
||||
if (elem._lazyCache) {
|
||||
delete elem._lazyCache;
|
||||
return;
|
||||
}
|
||||
|
||||
resetPreloading(e);
|
||||
addClass(elem, lazySizesCfg.loadedClass);
|
||||
removeClass(elem, lazySizesCfg.loadingClass);
|
||||
addRemoveLoadEvents(elem, rafSwitchLoadingClass);
|
||||
triggerEvent(elem, 'lazyloaded');
|
||||
};
|
||||
var rafedSwitchLoadingClass = rAFIt(switchLoadingClass);
|
||||
var rafSwitchLoadingClass = function(e){
|
||||
rafedSwitchLoadingClass({target: e.target});
|
||||
};
|
||||
|
||||
var changeIframeSrc = function(elem, src){
|
||||
var loadMode = elem.getAttribute('data-load-mode') || lazySizesCfg.iframeLoadMode;
|
||||
|
||||
// loadMode can be also a string!
|
||||
if (loadMode == 0) {
|
||||
elem.contentWindow.location.replace(src);
|
||||
} else if (loadMode == 1) {
|
||||
elem.src = src;
|
||||
}
|
||||
};
|
||||
|
||||
var handleSources = function(source){
|
||||
var customMedia;
|
||||
|
||||
var sourceSrcset = source[_getAttribute](lazySizesCfg.srcsetAttr);
|
||||
|
||||
if( (customMedia = lazySizesCfg.customMedia[source[_getAttribute]('data-media') || source[_getAttribute]('media')]) ){
|
||||
source.setAttribute('media', customMedia);
|
||||
}
|
||||
|
||||
if(sourceSrcset){
|
||||
source.setAttribute('srcset', sourceSrcset);
|
||||
}
|
||||
};
|
||||
|
||||
var lazyUnveil = rAFIt(function (elem, detail, isAuto, sizes, isImg){
|
||||
var src, srcset, parent, isPicture, event, firesLoad;
|
||||
|
||||
if(!(event = triggerEvent(elem, 'lazybeforeunveil', detail)).defaultPrevented){
|
||||
|
||||
if(sizes){
|
||||
if(isAuto){
|
||||
addClass(elem, lazySizesCfg.autosizesClass);
|
||||
} else {
|
||||
elem.setAttribute('sizes', sizes);
|
||||
}
|
||||
}
|
||||
|
||||
srcset = elem[_getAttribute](lazySizesCfg.srcsetAttr);
|
||||
src = elem[_getAttribute](lazySizesCfg.srcAttr);
|
||||
|
||||
if(isImg) {
|
||||
parent = elem.parentNode;
|
||||
isPicture = parent && regPicture.test(parent.nodeName || '');
|
||||
}
|
||||
|
||||
firesLoad = detail.firesLoad || (('src' in elem) && (srcset || src || isPicture));
|
||||
|
||||
event = {target: elem};
|
||||
|
||||
addClass(elem, lazySizesCfg.loadingClass);
|
||||
|
||||
if(firesLoad){
|
||||
clearTimeout(resetPreloadingTimer);
|
||||
resetPreloadingTimer = setTimeout(resetPreloading, 2500);
|
||||
addRemoveLoadEvents(elem, rafSwitchLoadingClass, true);
|
||||
}
|
||||
|
||||
if(isPicture){
|
||||
forEach.call(parent.getElementsByTagName('source'), handleSources);
|
||||
}
|
||||
|
||||
if(srcset){
|
||||
elem.setAttribute('srcset', srcset);
|
||||
} else if(src && !isPicture){
|
||||
if(regIframe.test(elem.nodeName)){
|
||||
changeIframeSrc(elem, src);
|
||||
} else {
|
||||
elem.src = src;
|
||||
}
|
||||
}
|
||||
|
||||
if(isImg && (srcset || isPicture)){
|
||||
updatePolyfill(elem, {src: src});
|
||||
}
|
||||
}
|
||||
|
||||
if(elem._lazyRace){
|
||||
delete elem._lazyRace;
|
||||
}
|
||||
removeClass(elem, lazySizesCfg.lazyClass);
|
||||
|
||||
rAF(function(){
|
||||
// Part of this can be removed as soon as this fix is older: https://bugs.chromium.org/p/chromium/issues/detail?id=7731 (2015)
|
||||
var isLoaded = elem.complete && elem.naturalWidth > 1;
|
||||
|
||||
if( !firesLoad || isLoaded){
|
||||
if (isLoaded) {
|
||||
addClass(elem, lazySizesCfg.fastLoadedClass);
|
||||
}
|
||||
switchLoadingClass(event);
|
||||
elem._lazyCache = true;
|
||||
setTimeout(function(){
|
||||
if ('_lazyCache' in elem) {
|
||||
delete elem._lazyCache;
|
||||
}
|
||||
}, 9);
|
||||
}
|
||||
if (elem.loading == 'lazy') {
|
||||
isLoading--;
|
||||
}
|
||||
}, true);
|
||||
});
|
||||
|
||||
var unveilElement = function (elem){
|
||||
if (elem._lazyRace) {return;}
|
||||
var detail;
|
||||
|
||||
var isImg = regImg.test(elem.nodeName);
|
||||
|
||||
//allow using sizes="auto", but don't use. it's invalid. Use data-sizes="auto" or a valid value for sizes instead (i.e.: sizes="80vw")
|
||||
var sizes = isImg && (elem[_getAttribute](lazySizesCfg.sizesAttr) || elem[_getAttribute]('sizes'));
|
||||
var isAuto = sizes == 'auto';
|
||||
|
||||
if( (isAuto || !isCompleted) && isImg && (elem[_getAttribute]('src') || elem.srcset) && !elem.complete && !hasClass(elem, lazySizesCfg.errorClass) && hasClass(elem, lazySizesCfg.lazyClass)){return;}
|
||||
|
||||
detail = triggerEvent(elem, 'lazyunveilread').detail;
|
||||
|
||||
if(isAuto){
|
||||
autoSizer.updateElem(elem, true, elem.offsetWidth);
|
||||
}
|
||||
|
||||
elem._lazyRace = true;
|
||||
isLoading++;
|
||||
|
||||
lazyUnveil(elem, detail, isAuto, sizes, isImg);
|
||||
};
|
||||
|
||||
var afterScroll = debounce(function(){
|
||||
lazySizesCfg.loadMode = 3;
|
||||
throttledCheckElements();
|
||||
});
|
||||
|
||||
var altLoadmodeScrollListner = function(){
|
||||
if(lazySizesCfg.loadMode == 3){
|
||||
lazySizesCfg.loadMode = 2;
|
||||
}
|
||||
afterScroll();
|
||||
};
|
||||
|
||||
var onload = function(){
|
||||
if(isCompleted){return;}
|
||||
if(Date.now() - started < 999){
|
||||
setTimeout(onload, 999);
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
isCompleted = true;
|
||||
|
||||
lazySizesCfg.loadMode = 3;
|
||||
|
||||
throttledCheckElements();
|
||||
|
||||
addEventListener('scroll', altLoadmodeScrollListner, true);
|
||||
};
|
||||
|
||||
return {
|
||||
_: function(){
|
||||
started = Date.now();
|
||||
|
||||
lazysizes.elements = document.getElementsByClassName(lazySizesCfg.lazyClass);
|
||||
preloadElems = document.getElementsByClassName(lazySizesCfg.lazyClass + ' ' + lazySizesCfg.preloadClass);
|
||||
|
||||
addEventListener('scroll', throttledCheckElements, true);
|
||||
|
||||
addEventListener('resize', throttledCheckElements, true);
|
||||
|
||||
addEventListener('pageshow', function (e) {
|
||||
if (e.persisted) {
|
||||
var loadingElements = document.querySelectorAll('.' + lazySizesCfg.loadingClass);
|
||||
|
||||
if (loadingElements.length && loadingElements.forEach) {
|
||||
requestAnimationFrame(function () {
|
||||
loadingElements.forEach( function (img) {
|
||||
if (img.complete) {
|
||||
unveilElement(img);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if(window.MutationObserver){
|
||||
new MutationObserver( throttledCheckElements ).observe( docElem, {childList: true, subtree: true, attributes: true} );
|
||||
} else {
|
||||
docElem[_addEventListener]('DOMNodeInserted', throttledCheckElements, true);
|
||||
docElem[_addEventListener]('DOMAttrModified', throttledCheckElements, true);
|
||||
setInterval(throttledCheckElements, 999);
|
||||
}
|
||||
|
||||
addEventListener('hashchange', throttledCheckElements, true);
|
||||
|
||||
//, 'fullscreenchange'
|
||||
['focus', 'mouseover', 'click', 'load', 'transitionend', 'animationend'].forEach(function(name){
|
||||
document[_addEventListener](name, throttledCheckElements, true);
|
||||
});
|
||||
|
||||
if((/d$|^c/.test(document.readyState))){
|
||||
onload();
|
||||
} else {
|
||||
addEventListener('load', onload);
|
||||
document[_addEventListener]('DOMContentLoaded', throttledCheckElements);
|
||||
setTimeout(onload, 20000);
|
||||
}
|
||||
|
||||
if(lazysizes.elements.length){
|
||||
checkElements();
|
||||
rAF._lsFlush();
|
||||
} else {
|
||||
throttledCheckElements();
|
||||
}
|
||||
},
|
||||
checkElems: throttledCheckElements,
|
||||
unveil: unveilElement,
|
||||
_aLSL: altLoadmodeScrollListner,
|
||||
};
|
||||
})();
|
||||
|
||||
|
||||
var autoSizer = (function(){
|
||||
var autosizesElems;
|
||||
|
||||
var sizeElement = rAFIt(function(elem, parent, event, width){
|
||||
var sources, i, len;
|
||||
elem._lazysizesWidth = width;
|
||||
width += 'px';
|
||||
|
||||
elem.setAttribute('sizes', width);
|
||||
|
||||
if(regPicture.test(parent.nodeName || '')){
|
||||
sources = parent.getElementsByTagName('source');
|
||||
for(i = 0, len = sources.length; i < len; i++){
|
||||
sources[i].setAttribute('sizes', width);
|
||||
}
|
||||
}
|
||||
|
||||
if(!event.detail.dataAttr){
|
||||
updatePolyfill(elem, event.detail);
|
||||
}
|
||||
});
|
||||
var getSizeElement = function (elem, dataAttr, width){
|
||||
var event;
|
||||
var parent = elem.parentNode;
|
||||
|
||||
if(parent){
|
||||
width = getWidth(elem, parent, width);
|
||||
event = triggerEvent(elem, 'lazybeforesizes', {width: width, dataAttr: !!dataAttr});
|
||||
|
||||
if(!event.defaultPrevented){
|
||||
width = event.detail.width;
|
||||
|
||||
if(width && width !== elem._lazysizesWidth){
|
||||
sizeElement(elem, parent, event, width);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
var updateElementsSizes = function(){
|
||||
var i;
|
||||
var len = autosizesElems.length;
|
||||
if(len){
|
||||
i = 0;
|
||||
|
||||
for(; i < len; i++){
|
||||
getSizeElement(autosizesElems[i]);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
var debouncedUpdateElementsSizes = debounce(updateElementsSizes);
|
||||
|
||||
return {
|
||||
_: function(){
|
||||
autosizesElems = document.getElementsByClassName(lazySizesCfg.autosizesClass);
|
||||
addEventListener('resize', debouncedUpdateElementsSizes);
|
||||
},
|
||||
checkElems: debouncedUpdateElementsSizes,
|
||||
updateElem: getSizeElement
|
||||
};
|
||||
})();
|
||||
|
||||
var init = function(){
|
||||
if(!init.i && document.getElementsByClassName){
|
||||
init.i = true;
|
||||
autoSizer._();
|
||||
loader._();
|
||||
}
|
||||
};
|
||||
|
||||
setTimeout(function(){
|
||||
if(lazySizesCfg.init){
|
||||
init();
|
||||
}
|
||||
});
|
||||
|
||||
lazysizes = {
|
||||
cfg: lazySizesCfg,
|
||||
autoSizer: autoSizer,
|
||||
loader: loader,
|
||||
init: init,
|
||||
uP: updatePolyfill,
|
||||
aC: addClass,
|
||||
rC: removeClass,
|
||||
hC: hasClass,
|
||||
fire: triggerEvent,
|
||||
gW: getWidth,
|
||||
rAF: rAF,
|
||||
};
|
||||
|
||||
return lazysizes;
|
||||
}
|
||||
));
|
1
wp-content/plugins/ewww-image-optimizer/includes/lazysizes.min.js
vendored
Normal file
701
wp-content/plugins/ewww-image-optimizer/includes/load-webp.js
Normal file
@ -0,0 +1,701 @@
|
||||
/*globals jQuery,Window,HTMLElement,HTMLDocument,HTMLCollection,NodeList,MutationObserver */
|
||||
/*exported Arrive*/
|
||||
/*jshint latedef:false */
|
||||
|
||||
/*
|
||||
* arrive.js
|
||||
* v2.4.1
|
||||
* https://github.com/uzairfarooq/arrive
|
||||
* MIT licensed
|
||||
*
|
||||
* Copyright (c) 2014-2017 Uzair Farooq
|
||||
*/
|
||||
var Arrive = (function(window, $, undefined) {
|
||||
|
||||
"use strict";
|
||||
|
||||
if(!window.MutationObserver || typeof HTMLElement === 'undefined'){
|
||||
return; //for unsupported browsers
|
||||
}
|
||||
|
||||
var arriveUniqueId = 0;
|
||||
|
||||
var utils = (function() {
|
||||
var matches = HTMLElement.prototype.matches || HTMLElement.prototype.webkitMatchesSelector || HTMLElement.prototype.mozMatchesSelector
|
||||
|| HTMLElement.prototype.msMatchesSelector;
|
||||
|
||||
return {
|
||||
matchesSelector: function(elem, selector) {
|
||||
return elem instanceof HTMLElement && matches.call(elem, selector);
|
||||
},
|
||||
// to enable function overloading - By John Resig (MIT Licensed)
|
||||
addMethod: function (object, name, fn) {
|
||||
var old = object[ name ];
|
||||
object[ name ] = function(){
|
||||
if ( fn.length == arguments.length ) {
|
||||
return fn.apply( this, arguments );
|
||||
}
|
||||
else if ( typeof old == 'function' ) {
|
||||
return old.apply( this, arguments );
|
||||
}
|
||||
};
|
||||
},
|
||||
callCallbacks: function(callbacksToBeCalled, registrationData) {
|
||||
if (registrationData && registrationData.options.onceOnly && registrationData.firedElems.length == 1) {
|
||||
// as onlyOnce param is true, make sure we fire the event for only one item
|
||||
callbacksToBeCalled = [callbacksToBeCalled[0]];
|
||||
}
|
||||
|
||||
for (var i = 0, cb; (cb = callbacksToBeCalled[i]); i++) {
|
||||
if (cb && cb.callback) {
|
||||
cb.callback.call(cb.elem, cb.elem);
|
||||
}
|
||||
}
|
||||
|
||||
if (registrationData && registrationData.options.onceOnly && registrationData.firedElems.length == 1) {
|
||||
// unbind event after first callback as onceOnly is true.
|
||||
registrationData.me.unbindEventWithSelectorAndCallback.call(
|
||||
registrationData.target, registrationData.selector, registrationData.callback
|
||||
);
|
||||
}
|
||||
},
|
||||
// traverse through all descendants of a node to check if event should be fired for any descendant
|
||||
checkChildNodesRecursively: function(nodes, registrationData, matchFunc, callbacksToBeCalled) {
|
||||
// check each new node if it matches the selector
|
||||
for (var i=0, node; (node = nodes[i]); i++) {
|
||||
if (matchFunc(node, registrationData, callbacksToBeCalled)) {
|
||||
callbacksToBeCalled.push({ callback: registrationData.callback, elem: node });
|
||||
}
|
||||
|
||||
if (node.childNodes.length > 0) {
|
||||
utils.checkChildNodesRecursively(node.childNodes, registrationData, matchFunc, callbacksToBeCalled);
|
||||
}
|
||||
}
|
||||
},
|
||||
mergeArrays: function(firstArr, secondArr){
|
||||
// Overwrites default options with user-defined options.
|
||||
var options = {},
|
||||
attrName;
|
||||
for (attrName in firstArr) {
|
||||
if (firstArr.hasOwnProperty(attrName)) {
|
||||
options[attrName] = firstArr[attrName];
|
||||
}
|
||||
}
|
||||
for (attrName in secondArr) {
|
||||
if (secondArr.hasOwnProperty(attrName)) {
|
||||
options[attrName] = secondArr[attrName];
|
||||
}
|
||||
}
|
||||
return options;
|
||||
},
|
||||
toElementsArray: function (elements) {
|
||||
// check if object is an array (or array like object)
|
||||
// Note: window object has .length property but it's not array of elements so don't consider it an array
|
||||
if (typeof elements !== 'undefined' && (typeof elements.length !== 'number' || elements === window)) {
|
||||
elements = [elements];
|
||||
}
|
||||
return elements;
|
||||
}
|
||||
};
|
||||
})();
|
||||
|
||||
|
||||
// Class to maintain state of all registered events of a single type
|
||||
var EventsBucket = (function() {
|
||||
var EventsBucket = function() {
|
||||
// holds all the events
|
||||
|
||||
this._eventsBucket = [];
|
||||
// function to be called while adding an event, the function should do the event initialization/registration
|
||||
this._beforeAdding = null;
|
||||
// function to be called while removing an event, the function should do the event destruction
|
||||
this._beforeRemoving = null;
|
||||
};
|
||||
|
||||
EventsBucket.prototype.addEvent = function(target, selector, options, callback) {
|
||||
var newEvent = {
|
||||
target: target,
|
||||
selector: selector,
|
||||
options: options,
|
||||
callback: callback,
|
||||
firedElems: []
|
||||
};
|
||||
|
||||
if (this._beforeAdding) {
|
||||
this._beforeAdding(newEvent);
|
||||
}
|
||||
|
||||
this._eventsBucket.push(newEvent);
|
||||
return newEvent;
|
||||
};
|
||||
|
||||
EventsBucket.prototype.removeEvent = function(compareFunction) {
|
||||
for (var i=this._eventsBucket.length - 1, registeredEvent; (registeredEvent = this._eventsBucket[i]); i--) {
|
||||
if (compareFunction(registeredEvent)) {
|
||||
if (this._beforeRemoving) {
|
||||
this._beforeRemoving(registeredEvent);
|
||||
}
|
||||
|
||||
// mark callback as null so that even if an event mutation was already triggered it does not call callback
|
||||
var removedEvents = this._eventsBucket.splice(i, 1);
|
||||
if (removedEvents && removedEvents.length) {
|
||||
removedEvents[0].callback = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
EventsBucket.prototype.beforeAdding = function(beforeAdding) {
|
||||
this._beforeAdding = beforeAdding;
|
||||
};
|
||||
|
||||
EventsBucket.prototype.beforeRemoving = function(beforeRemoving) {
|
||||
this._beforeRemoving = beforeRemoving;
|
||||
};
|
||||
|
||||
return EventsBucket;
|
||||
})();
|
||||
|
||||
|
||||
/**
|
||||
* @constructor
|
||||
* General class for binding/unbinding arrive and leave events
|
||||
*/
|
||||
var MutationEvents = function(getObserverConfig, onMutation) {
|
||||
var eventsBucket = new EventsBucket(),
|
||||
me = this;
|
||||
|
||||
var defaultOptions = {
|
||||
fireOnAttributesModification: false
|
||||
};
|
||||
|
||||
// actual event registration before adding it to bucket
|
||||
eventsBucket.beforeAdding(function(registrationData) {
|
||||
var
|
||||
target = registrationData.target,
|
||||
observer;
|
||||
|
||||
// mutation observer does not work on window or document
|
||||
if (target === window.document || target === window) {
|
||||
target = document.getElementsByTagName("html")[0];
|
||||
}
|
||||
|
||||
// Create an observer instance
|
||||
observer = new MutationObserver(function(e) {
|
||||
onMutation.call(this, e, registrationData);
|
||||
});
|
||||
|
||||
var config = getObserverConfig(registrationData.options);
|
||||
|
||||
observer.observe(target, config);
|
||||
|
||||
registrationData.observer = observer;
|
||||
registrationData.me = me;
|
||||
});
|
||||
|
||||
// cleanup/unregister before removing an event
|
||||
eventsBucket.beforeRemoving(function (eventData) {
|
||||
eventData.observer.disconnect();
|
||||
});
|
||||
|
||||
this.bindEvent = function(selector, options, callback) {
|
||||
options = utils.mergeArrays(defaultOptions, options);
|
||||
|
||||
var elements = utils.toElementsArray(this);
|
||||
|
||||
for (var i = 0; i < elements.length; i++) {
|
||||
eventsBucket.addEvent(elements[i], selector, options, callback);
|
||||
}
|
||||
};
|
||||
|
||||
this.unbindEvent = function() {
|
||||
var elements = utils.toElementsArray(this);
|
||||
eventsBucket.removeEvent(function(eventObj) {
|
||||
for (var i = 0; i < elements.length; i++) {
|
||||
if (this === undefined || eventObj.target === elements[i]) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
});
|
||||
};
|
||||
|
||||
this.unbindEventWithSelectorOrCallback = function(selector) {
|
||||
var elements = utils.toElementsArray(this),
|
||||
callback = selector,
|
||||
compareFunction;
|
||||
|
||||
if (typeof selector === "function") {
|
||||
compareFunction = function(eventObj) {
|
||||
for (var i = 0; i < elements.length; i++) {
|
||||
if ((this === undefined || eventObj.target === elements[i]) && eventObj.callback === callback) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
};
|
||||
}
|
||||
else {
|
||||
compareFunction = function(eventObj) {
|
||||
for (var i = 0; i < elements.length; i++) {
|
||||
if ((this === undefined || eventObj.target === elements[i]) && eventObj.selector === selector) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
};
|
||||
}
|
||||
eventsBucket.removeEvent(compareFunction);
|
||||
};
|
||||
|
||||
this.unbindEventWithSelectorAndCallback = function(selector, callback) {
|
||||
var elements = utils.toElementsArray(this);
|
||||
eventsBucket.removeEvent(function(eventObj) {
|
||||
for (var i = 0; i < elements.length; i++) {
|
||||
if ((this === undefined || eventObj.target === elements[i]) && eventObj.selector === selector && eventObj.callback === callback) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
});
|
||||
};
|
||||
|
||||
return this;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @constructor
|
||||
* Processes 'arrive' events
|
||||
*/
|
||||
var ArriveEvents = function() {
|
||||
// Default options for 'arrive' event
|
||||
var arriveDefaultOptions = {
|
||||
fireOnAttributesModification: false,
|
||||
onceOnly: false,
|
||||
existing: false
|
||||
};
|
||||
|
||||
function getArriveObserverConfig(options) {
|
||||
var config = {
|
||||
attributes: false,
|
||||
childList: true,
|
||||
subtree: true
|
||||
};
|
||||
|
||||
if (options.fireOnAttributesModification) {
|
||||
config.attributes = true;
|
||||
}
|
||||
|
||||
return config;
|
||||
}
|
||||
|
||||
function onArriveMutation(mutations, registrationData) {
|
||||
mutations.forEach(function( mutation ) {
|
||||
var newNodes = mutation.addedNodes,
|
||||
targetNode = mutation.target,
|
||||
callbacksToBeCalled = [],
|
||||
node;
|
||||
|
||||
// If new nodes are added
|
||||
if( newNodes !== null && newNodes.length > 0 ) {
|
||||
utils.checkChildNodesRecursively(newNodes, registrationData, nodeMatchFunc, callbacksToBeCalled);
|
||||
}
|
||||
else if (mutation.type === "attributes") {
|
||||
if (nodeMatchFunc(targetNode, registrationData, callbacksToBeCalled)) {
|
||||
callbacksToBeCalled.push({ callback: registrationData.callback, elem: targetNode });
|
||||
}
|
||||
}
|
||||
|
||||
utils.callCallbacks(callbacksToBeCalled, registrationData);
|
||||
});
|
||||
}
|
||||
|
||||
function nodeMatchFunc(node, registrationData, callbacksToBeCalled) {
|
||||
// check a single node to see if it matches the selector
|
||||
if (utils.matchesSelector(node, registrationData.selector)) {
|
||||
if(node._id === undefined) {
|
||||
node._id = arriveUniqueId++;
|
||||
}
|
||||
// make sure the arrive event is not already fired for the element
|
||||
if (registrationData.firedElems.indexOf(node._id) == -1) {
|
||||
registrationData.firedElems.push(node._id);
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
arriveEvents = new MutationEvents(getArriveObserverConfig, onArriveMutation);
|
||||
|
||||
var mutationBindEvent = arriveEvents.bindEvent;
|
||||
|
||||
// override bindEvent function
|
||||
arriveEvents.bindEvent = function(selector, options, callback) {
|
||||
|
||||
if (typeof callback === "undefined") {
|
||||
callback = options;
|
||||
options = arriveDefaultOptions;
|
||||
} else {
|
||||
options = utils.mergeArrays(arriveDefaultOptions, options);
|
||||
}
|
||||
|
||||
var elements = utils.toElementsArray(this);
|
||||
|
||||
if (options.existing) {
|
||||
var existing = [];
|
||||
|
||||
for (var i = 0; i < elements.length; i++) {
|
||||
var nodes = elements[i].querySelectorAll(selector);
|
||||
for (var j = 0; j < nodes.length; j++) {
|
||||
existing.push({ callback: callback, elem: nodes[j] });
|
||||
}
|
||||
}
|
||||
|
||||
// no need to bind event if the callback has to be fired only once and we have already found the element
|
||||
if (options.onceOnly && existing.length) {
|
||||
return callback.call(existing[0].elem, existing[0].elem);
|
||||
}
|
||||
|
||||
setTimeout(utils.callCallbacks, 1, existing);
|
||||
}
|
||||
|
||||
mutationBindEvent.call(this, selector, options, callback);
|
||||
};
|
||||
|
||||
return arriveEvents;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @constructor
|
||||
* Processes 'leave' events
|
||||
*/
|
||||
var LeaveEvents = function() {
|
||||
// Default options for 'leave' event
|
||||
var leaveDefaultOptions = {};
|
||||
|
||||
function getLeaveObserverConfig() {
|
||||
var config = {
|
||||
childList: true,
|
||||
subtree: true
|
||||
};
|
||||
|
||||
return config;
|
||||
}
|
||||
|
||||
function onLeaveMutation(mutations, registrationData) {
|
||||
mutations.forEach(function( mutation ) {
|
||||
var removedNodes = mutation.removedNodes,
|
||||
callbacksToBeCalled = [];
|
||||
|
||||
if( removedNodes !== null && removedNodes.length > 0 ) {
|
||||
utils.checkChildNodesRecursively(removedNodes, registrationData, nodeMatchFunc, callbacksToBeCalled);
|
||||
}
|
||||
|
||||
utils.callCallbacks(callbacksToBeCalled, registrationData);
|
||||
});
|
||||
}
|
||||
|
||||
function nodeMatchFunc(node, registrationData) {
|
||||
return utils.matchesSelector(node, registrationData.selector);
|
||||
}
|
||||
|
||||
leaveEvents = new MutationEvents(getLeaveObserverConfig, onLeaveMutation);
|
||||
|
||||
var mutationBindEvent = leaveEvents.bindEvent;
|
||||
|
||||
// override bindEvent function
|
||||
leaveEvents.bindEvent = function(selector, options, callback) {
|
||||
|
||||
if (typeof callback === "undefined") {
|
||||
callback = options;
|
||||
options = leaveDefaultOptions;
|
||||
} else {
|
||||
options = utils.mergeArrays(leaveDefaultOptions, options);
|
||||
}
|
||||
|
||||
mutationBindEvent.call(this, selector, options, callback);
|
||||
};
|
||||
|
||||
return leaveEvents;
|
||||
};
|
||||
|
||||
|
||||
var arriveEvents = new ArriveEvents(),
|
||||
leaveEvents = new LeaveEvents();
|
||||
|
||||
function exposeUnbindApi(eventObj, exposeTo, funcName) {
|
||||
// expose unbind function with function overriding
|
||||
utils.addMethod(exposeTo, funcName, eventObj.unbindEvent);
|
||||
utils.addMethod(exposeTo, funcName, eventObj.unbindEventWithSelectorOrCallback);
|
||||
utils.addMethod(exposeTo, funcName, eventObj.unbindEventWithSelectorAndCallback);
|
||||
}
|
||||
|
||||
/*** expose APIs ***/
|
||||
function exposeApi(exposeTo) {
|
||||
exposeTo.arrive = arriveEvents.bindEvent;
|
||||
exposeUnbindApi(arriveEvents, exposeTo, "unbindArrive");
|
||||
|
||||
exposeTo.leave = leaveEvents.bindEvent;
|
||||
exposeUnbindApi(leaveEvents, exposeTo, "unbindLeave");
|
||||
}
|
||||
|
||||
exposeApi(HTMLElement.prototype);
|
||||
exposeApi(NodeList.prototype);
|
||||
exposeApi(HTMLCollection.prototype);
|
||||
exposeApi(HTMLDocument.prototype);
|
||||
exposeApi(Window.prototype);
|
||||
|
||||
var Arrive = {};
|
||||
// expose functions to unbind all arrive/leave events
|
||||
exposeUnbindApi(arriveEvents, Arrive, "unbindAllArrive");
|
||||
exposeUnbindApi(leaveEvents, Arrive, "unbindAllLeave");
|
||||
|
||||
return Arrive;
|
||||
|
||||
})(window, null, undefined);
|
||||
|
||||
var ewww_webp_supported = false;
|
||||
// webp detection adapted from https://developers.google.com/speed/webp/faq#how_can_i_detect_browser_support_using_javascript
|
||||
function check_webp_feature(feature, callback) {
|
||||
if (ewww_webp_supported) {
|
||||
callback(ewww_webp_supported);
|
||||
return;
|
||||
}
|
||||
var kTestImages = {
|
||||
alpha: "UklGRkoAAABXRUJQVlA4WAoAAAAQAAAAAAAAAAAAQUxQSAwAAAARBxAR/Q9ERP8DAABWUDggGAAAABQBAJ0BKgEAAQAAAP4AAA3AAP7mtQAAAA==",
|
||||
animation: "UklGRlIAAABXRUJQVlA4WAoAAAASAAAAAAAAAAAAQU5JTQYAAAD/////AABBTk1GJgAAAAAAAAAAAAAAAAAAAGQAAABWUDhMDQAAAC8AAAAQBxAREYiI/gcA"
|
||||
};
|
||||
var img = new Image();
|
||||
img.onload = function () {
|
||||
ewww_webp_supported = (img.width > 0) && (img.height > 0);
|
||||
callback(ewww_webp_supported);
|
||||
};
|
||||
img.onerror = function () {
|
||||
callback(false);
|
||||
};
|
||||
img.src = "data:image/webp;base64," + kTestImages[feature];
|
||||
}
|
||||
function ewwwLoadImages(ewww_webp_supported) {
|
||||
if (ewww_webp_supported) {
|
||||
var nggImages = document.querySelectorAll('.batch-image img, .image-wrapper a, .ngg-pro-masonry-item a, .ngg-galleria-offscreen-seo-wrapper a');
|
||||
for (var i = 0, len = nggImages.length; i < len; i++){
|
||||
ewwwAttr(nggImages[i], 'data-src', nggImages[i].getAttribute('data-webp'));
|
||||
ewwwAttr(nggImages[i], 'data-thumbnail', nggImages[i].getAttribute('data-webp-thumbnail'));
|
||||
}
|
||||
var revImages = document.querySelectorAll('.rev_slider ul li');
|
||||
for (var i = 0, len = revImages.length; i < len; i++){
|
||||
ewwwAttr(revImages[i], 'data-thumb', revImages[i].getAttribute('data-webp-thumb'));
|
||||
var param_num = 1;
|
||||
while ( param_num < 11 ) {
|
||||
ewwwAttr(revImages[i], 'data-param' + param_num, revImages[i].getAttribute('data-webp-param' + param_num));
|
||||
param_num++;
|
||||
}
|
||||
}
|
||||
var revImages = document.querySelectorAll('.rev_slider img');
|
||||
for (var i = 0, len = revImages.length; i < len; i++){
|
||||
ewwwAttr(revImages[i], 'data-lazyload', revImages[i].getAttribute('data-webp-lazyload'));
|
||||
}
|
||||
var wooImages = document.querySelectorAll('div.woocommerce-product-gallery__image');
|
||||
for (var i = 0, len = wooImages.length; i < len; i++){
|
||||
ewwwAttr(wooImages[i], 'data-thumb', wooImages[i].getAttribute('data-webp-thumb'));
|
||||
}
|
||||
}
|
||||
var videos = document.querySelectorAll('video');
|
||||
for (var i = 0, len = videos.length; i < len; i++){
|
||||
if (ewww_webp_supported) {
|
||||
ewwwAttr(videos[i], 'poster', videos[i].getAttribute('data-poster-webp'));
|
||||
} else {
|
||||
ewwwAttr(videos[i], 'poster', videos[i].getAttribute('data-poster-image'));
|
||||
}
|
||||
}
|
||||
var lazies = document.querySelectorAll('img.ewww_webp_lazy_load');
|
||||
for (var i = 0, len = lazies.length; i < len; i++){
|
||||
console.log('parsing an image: ' + lazies[i].getAttribute('data-src'));
|
||||
if (ewww_webp_supported) {
|
||||
console.log('webp good');
|
||||
ewwwAttr(lazies[i], 'data-lazy-srcset', lazies[i].getAttribute('data-lazy-srcset-webp'));
|
||||
ewwwAttr(lazies[i], 'data-srcset', lazies[i].getAttribute('data-srcset-webp'));
|
||||
ewwwAttr(lazies[i], 'data-lazy-src', lazies[i].getAttribute('data-lazy-src-webp'));
|
||||
ewwwAttr(lazies[i], 'data-src', lazies[i].getAttribute('data-src-webp'));
|
||||
ewwwAttr(lazies[i], 'data-orig-file', lazies[i].getAttribute('data-webp-orig-file'));
|
||||
ewwwAttr(lazies[i], 'data-medium-file', lazies[i].getAttribute('data-webp-medium-file'));
|
||||
ewwwAttr(lazies[i], 'data-large-file', lazies[i].getAttribute('data-webp-large-file'));
|
||||
var jpsrcset = lazies[i].getAttribute('srcset');
|
||||
if (jpsrcset != null && jpsrcset !== false && jpsrcset.includes('R0lGOD')) {
|
||||
ewwwAttr(lazies[i], 'src', lazies[i].getAttribute('data-lazy-src-webp'));
|
||||
}
|
||||
}
|
||||
lazies[i].className = lazies[i].className.replace(/\bewww_webp_lazy_load\b/, '');
|
||||
}
|
||||
var elems = document.querySelectorAll('.ewww_webp');
|
||||
for (var i = 0, len = elems.length; i < len; i++){
|
||||
console.log('parsing an image: ' + elems[i].getAttribute('data-src'));
|
||||
if (ewww_webp_supported) {
|
||||
ewwwAttr(elems[i], 'srcset', elems[i].getAttribute('data-srcset-webp'));
|
||||
ewwwAttr(elems[i], 'src', elems[i].getAttribute('data-src-webp'));
|
||||
ewwwAttr(elems[i], 'data-orig-file', elems[i].getAttribute('data-webp-orig-file'));
|
||||
ewwwAttr(elems[i], 'data-medium-file', elems[i].getAttribute('data-webp-medium-file'));
|
||||
ewwwAttr(elems[i], 'data-large-file', elems[i].getAttribute('data-webp-large-file'));
|
||||
ewwwAttr(elems[i], 'data-large_image', elems[i].getAttribute('data-webp-large_image'));
|
||||
ewwwAttr(elems[i], 'data-src', elems[i].getAttribute('data-webp-src'));
|
||||
} else {
|
||||
ewwwAttr(elems[i], 'srcset', elems[i].getAttribute('data-srcset-img'));
|
||||
ewwwAttr(elems[i], 'src', elems[i].getAttribute('data-src-img'));
|
||||
}
|
||||
elems[i].className = elems[i].className.replace(/\bewww_webp\b/, 'ewww_webp_loaded');
|
||||
}
|
||||
if (window.jQuery && jQuery.fn.isotope && jQuery.fn.imagesLoaded) {
|
||||
jQuery('.fusion-posts-container-infinite').imagesLoaded( function() {
|
||||
if ( jQuery( '.fusion-posts-container-infinite' ).hasClass( 'isotope' ) ) {
|
||||
jQuery( '.fusion-posts-container-infinite' ).isotope();
|
||||
}
|
||||
});
|
||||
jQuery('.fusion-portfolio:not(.fusion-recent-works) .fusion-portfolio-wrapper').imagesLoaded( function() {
|
||||
jQuery( '.fusion-portfolio:not(.fusion-recent-works) .fusion-portfolio-wrapper' ).isotope();
|
||||
});
|
||||
}
|
||||
}
|
||||
check_webp_feature('alpha', ewwwWebPInit);
|
||||
function ewwwWebPInit(ewww_webp_supported) {
|
||||
ewwwLoadImages(ewww_webp_supported);
|
||||
ewwwNggLoadGalleries(ewww_webp_supported);
|
||||
document.arrive('.ewww_webp', function() {
|
||||
ewwwLoadImages(ewww_webp_supported);
|
||||
});
|
||||
document.arrive('.ewww_webp_lazy_load', function() {
|
||||
ewwwLoadImages(ewww_webp_supported);
|
||||
});
|
||||
document.arrive('videos', function() {
|
||||
ewwwLoadImages(ewww_webp_supported);
|
||||
});
|
||||
if (document.readyState == 'loading') {
|
||||
console.log('deferring ewwwJSONParserInit until DOMContentLoaded')
|
||||
document.addEventListener('DOMContentLoaded', ewwwJSONParserInit);
|
||||
} else {
|
||||
console.log(document.readyState);
|
||||
console.log('running JSON parsers post haste')
|
||||
if ( typeof galleries !== 'undefined' ) {
|
||||
console.log('galleries found, parsing')
|
||||
ewwwNggParseGalleries(ewww_webp_supported);
|
||||
}
|
||||
ewwwWooParseVariations(ewww_webp_supported);
|
||||
}
|
||||
}
|
||||
function ewwwAttr(elem, attr, value) {
|
||||
if (value != null && value !== false) {
|
||||
elem.setAttribute(attr, value);
|
||||
}
|
||||
}
|
||||
function ewwwJSONParserInit() {
|
||||
if ( typeof galleries !== 'undefined' ) {
|
||||
check_webp_feature('alpha', ewwwNggParseGalleries);
|
||||
}
|
||||
check_webp_feature('alpha', ewwwWooParseVariations);
|
||||
}
|
||||
function ewwwWooParseVariations(ewww_webp_supported) {
|
||||
if (!ewww_webp_supported) {
|
||||
return;
|
||||
}
|
||||
var elems = document.querySelectorAll('form.variations_form');
|
||||
for (var i = 0, len = elems.length; i < len; i++){
|
||||
var variations = elems[i].getAttribute('data-product_variations');
|
||||
var variations_changed = false;
|
||||
try {
|
||||
variations = JSON.parse(variations);
|
||||
//console.log(variations);
|
||||
console.log('parsing WC variations');
|
||||
for ( var num in variations ) {
|
||||
if (variations[ num ] !== undefined && variations[ num ].image !== undefined) {
|
||||
console.log(variations[num].image);
|
||||
if (variations[num].image.src_webp !== undefined) {
|
||||
variations[num].image.src = variations[num].image.src_webp;
|
||||
variations_changed = true;
|
||||
}
|
||||
if (variations[num].image.srcset_webp !== undefined) {
|
||||
variations[num].image.srcset = variations[num].image.srcset_webp;
|
||||
variations_changed = true;
|
||||
}
|
||||
if (variations[num].image.full_src_webp !== undefined) {
|
||||
variations[num].image.full_src = variations[num].image.full_src_webp;
|
||||
variations_changed = true;
|
||||
}
|
||||
if (variations[num].image.gallery_thumbnail_src_webp !== undefined) {
|
||||
variations[num].image.gallery_thumbnail_src = variations[num].image.gallery_thumbnail_src_webp;
|
||||
variations_changed = true;
|
||||
}
|
||||
if (variations[num].image.thumb_src_webp !== undefined) {
|
||||
variations[num].image.thumb_src = variations[num].image.thumb_src_webp;
|
||||
variations_changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (variations_changed) {
|
||||
ewwwAttr(elems[i], 'data-product_variations', JSON.stringify(variations));
|
||||
}
|
||||
} catch (err) {
|
||||
console.log(err);
|
||||
console.log(response);
|
||||
}
|
||||
}
|
||||
}
|
||||
function ewwwNggParseGalleries(ewww_webp_supported) {
|
||||
if (ewww_webp_supported) {
|
||||
for(var galleryIndex in galleries) {
|
||||
var gallery = galleries[galleryIndex];
|
||||
galleries[galleryIndex].images_list = ewwwNggParseImageList(gallery.images_list);
|
||||
}
|
||||
}
|
||||
}
|
||||
function ewwwNggLoadGalleries(ewww_webp_supported) {
|
||||
if (ewww_webp_supported) {
|
||||
document.addEventListener('ngg.galleria.themeadded', function(event, themename){
|
||||
window.ngg_galleria._create_backup = window.ngg_galleria.create;
|
||||
window.ngg_galleria.create = function(gallery_parent, themename) {
|
||||
var gallery_id = $(gallery_parent).data('id');
|
||||
galleries['gallery_' + gallery_id].images_list = ewwwNggParseImageList(galleries['gallery_' + gallery_id].images_list);
|
||||
return window.ngg_galleria._create_backup(gallery_parent, themename);
|
||||
};
|
||||
});
|
||||
}
|
||||
}
|
||||
function ewwwNggParseImageList(images_list) {
|
||||
console.log('parsing gallery images');
|
||||
for(var nggIndex in images_list) {
|
||||
var nggImage = images_list[nggIndex];
|
||||
if (typeof nggImage['image-webp'] !== typeof undefined) {
|
||||
images_list[nggIndex]['image'] = nggImage['image-webp'];
|
||||
delete images_list[nggIndex]['image-webp'];
|
||||
}
|
||||
if (typeof nggImage['thumb-webp'] !== typeof undefined) {
|
||||
images_list[nggIndex]['thumb'] = nggImage['thumb-webp'];
|
||||
delete images_list[nggIndex]['thumb-webp'];
|
||||
}
|
||||
if (typeof nggImage['full_image_webp'] !== typeof undefined) {
|
||||
images_list[nggIndex]['full_image'] = nggImage['full_image_webp'];
|
||||
delete images_list[nggIndex]['full_image_webp'];
|
||||
}
|
||||
if (typeof nggImage['srcsets'] !== typeof undefined) {
|
||||
for(var nggSrcsetIndex in nggImage['srcsets']) {
|
||||
nggSrcset = nggImage['srcsets'][nggSrcsetIndex];
|
||||
if (typeof nggImage['srcsets'][nggSrcsetIndex + '-webp'] !== typeof undefined) {
|
||||
images_list[nggIndex]['srcsets'][nggSrcsetIndex] = nggImage['srcsets'][nggSrcsetIndex + '-webp'];
|
||||
delete images_list[nggIndex]['srcsets'][nggSrcsetIndex + '-webp'];
|
||||
}
|
||||
}
|
||||
}
|
||||
if (typeof nggImage['full_srcsets'] !== typeof undefined) {
|
||||
for(var nggFSrcsetIndex in nggImage['full_srcsets']) {
|
||||
nggFSrcset = nggImage['full_srcsets'][nggFSrcsetIndex];
|
||||
if (typeof nggImage['full_srcsets'][nggFSrcsetIndex + '-webp'] !== typeof undefined) {
|
||||
images_list[nggIndex]['full_srcsets'][nggFSrcsetIndex] = nggImage['full_srcsets'][nggFSrcsetIndex + '-webp'];
|
||||
delete images_list[nggIndex]['full_srcsets'][nggFSrcsetIndex + '-webp'];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return images_list;
|
||||
}
|
1
wp-content/plugins/ewww-image-optimizer/includes/load-webp.min.js
vendored
Normal file
51
wp-content/plugins/ewww-image-optimizer/includes/ls.print.js
Normal file
@ -0,0 +1,51 @@
|
||||
/*
|
||||
This lazySizes extension adds better support for print.
|
||||
In case the user starts to print lazysizes will load all images.
|
||||
*/
|
||||
(function(window, factory) {
|
||||
var globalInstall = function(){
|
||||
factory(window.lazySizes);
|
||||
window.removeEventListener('lazyunveilread', globalInstall, true);
|
||||
};
|
||||
|
||||
factory = factory.bind(null, window, window.document);
|
||||
|
||||
if(typeof module == 'object' && module.exports){
|
||||
factory(require('lazysizes'));
|
||||
} else if(window.lazySizes) {
|
||||
globalInstall();
|
||||
} else {
|
||||
window.addEventListener('lazyunveilread', globalInstall, true);
|
||||
}
|
||||
}(window, function(window, document, lazySizes) {
|
||||
/*jshint eqnull:true */
|
||||
'use strict';
|
||||
var config, elements, onprint, printMedia;
|
||||
// see also: http://tjvantoll.com/2012/06/15/detecting-print-requests-with-javascript/
|
||||
if(window.addEventListener){
|
||||
config = lazySizes && lazySizes.cfg;
|
||||
elements = config.lazyClass || 'lazyload';
|
||||
onprint = function(){
|
||||
var i, len;
|
||||
if(typeof elements == 'string'){
|
||||
elements = document.getElementsByClassName(elements);
|
||||
}
|
||||
|
||||
if(lazySizes){
|
||||
for(i = 0, len = elements.length; i < len; i++){
|
||||
lazySizes.loader.unveil(elements[i]);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
addEventListener('beforeprint', onprint, false);
|
||||
|
||||
if(!('onbeforeprint' in window) && window.matchMedia && (printMedia = matchMedia('print')) && printMedia.addListener){
|
||||
printMedia.addListener(function(){
|
||||
if(printMedia.matches){
|
||||
onprint();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}));
|
2
wp-content/plugins/ewww-image-optimizer/includes/ls.print.min.js
vendored
Normal file
@ -0,0 +1,2 @@
|
||||
/*! lazysizes - v5.1.0 */
|
||||
!function(a,b){var c=function(){b(a.lazySizes),a.removeEventListener("lazyunveilread",c,!0)};b=b.bind(null,a,a.document),"object"==typeof module&&module.exports?b(require("lazysizes")):a.lazySizes?c():a.addEventListener("lazyunveilread",c,!0)}(window,function(a,b,c){"use strict";var d,e,f,g;a.addEventListener&&(d=c&&c.cfg,e=d.lazyClass||"lazyload",f=function(){var a,d;if("string"==typeof e&&(e=b.getElementsByClassName(e)),c)for(a=0,d=e.length;a<d;a++)c.loader.unveil(e[a])},addEventListener("beforeprint",f,!1),!("onbeforeprint"in a)&&a.matchMedia&&(g=matchMedia("print"))&&g.addListener&&g.addListener(function(){g.matches&&f()}))});
|
@ -0,0 +1,118 @@
|
||||
(function(window, factory) {
|
||||
var globalInstall = function(){
|
||||
factory(window.lazySizes);
|
||||
window.removeEventListener('lazyunveilread', globalInstall, true);
|
||||
};
|
||||
|
||||
factory = factory.bind(null, window, window.document);
|
||||
|
||||
if(typeof module == 'object' && module.exports){
|
||||
factory(require('lazysizes'));
|
||||
} else if (typeof define == 'function' && define.amd) {
|
||||
define(['lazysizes'], factory);
|
||||
} else if(window.lazySizes) {
|
||||
globalInstall();
|
||||
} else {
|
||||
window.addEventListener('lazyunveilread', globalInstall, true);
|
||||
}
|
||||
}(window, function(window, document, lazySizes) {
|
||||
/*jshint eqnull:true */
|
||||
'use strict';
|
||||
var regBgUrlEscape;
|
||||
|
||||
if(document.addEventListener){
|
||||
regBgUrlEscape = /\(|\)|\s|'/;
|
||||
|
||||
addEventListener('lazybeforeunveil', function(e){
|
||||
if(e.detail.instance != lazySizes){return;}
|
||||
|
||||
var bg, bgWebP;
|
||||
if(!e.defaultPrevented) {
|
||||
|
||||
if(e.target.preload == 'none'){
|
||||
e.target.preload = 'auto';
|
||||
}
|
||||
|
||||
// handle data-back (so as not to conflict with the stock data-bg)
|
||||
bg = e.target.getAttribute('data-back');
|
||||
if (bg) {
|
||||
if(ewww_webp_supported) {
|
||||
console.log('checking for data-back-webp');
|
||||
bgWebP = e.target.getAttribute('data-back-webp');
|
||||
if (bgWebP) {
|
||||
console.log('replacing data-back with data-back-webp');
|
||||
bg = bgWebP;
|
||||
}
|
||||
}
|
||||
var dPR = (window.devicePixelRatio || 1);
|
||||
var targetWidth = Math.round(e.target.offsetWidth * dPR);
|
||||
var targetHeight = Math.round(e.target.offsetHeight * dPR);
|
||||
if ( 0 === bg.search(/\[/) ) {
|
||||
} else if (!shouldAutoScale(e.target)||!shouldAutoScale(e.target.parentNode)){
|
||||
} else if (window.lazySizes.hC(e.target,'wp-block-cover')) {
|
||||
console.log('found wp-block-cover with data-back');
|
||||
if (window.lazySizes.hC(e.target,'has-parallax')) {
|
||||
console.log('also has-parallax with data-back');
|
||||
targetWidth = Math.round(window.screen.width * dPR);
|
||||
targetHeight = Math.round(window.screen.height * dPR);
|
||||
} else if (targetHeight<300) {
|
||||
targetHeight = 430;
|
||||
}
|
||||
bg = constrainSrc(bg,targetWidth,targetHeight,'bg-cover');
|
||||
} else if (window.lazySizes.hC(e.target,'cover-image')){
|
||||
console.log('found .cover-image with data-back');
|
||||
bg = constrainSrc(bg,targetWidth,targetHeight,'bg-cover');
|
||||
} else if (window.lazySizes.hC(e.target,'elementor-bg')){
|
||||
console.log('found elementor-bg with data-back');
|
||||
bg = constrainSrc(bg,targetWidth,targetHeight,'bg-cover');
|
||||
} else if (window.lazySizes.hC(e.target,'et_parallax_bg')){
|
||||
console.log('found et_parallax_bg with data-back');
|
||||
bg = constrainSrc(bg,targetWidth,targetHeight,'bg-cover');
|
||||
} else if (window.lazySizes.hC(e.target,'bg-image-crop')){
|
||||
console.log('found bg-image-crop with data-back');
|
||||
bg = constrainSrc(bg,targetWidth,targetHeight,'bg-cover');
|
||||
} else {
|
||||
console.log('found other data-back');
|
||||
bg = constrainSrc(bg,targetWidth,targetHeight,'bg');
|
||||
}
|
||||
if ( e.target.style.backgroundImage && -1 === e.target.style.backgroundImage.search(/^initial/) ) {
|
||||
// Convert JSON for multiple URLs.
|
||||
if ( 0 === bg.search(/\[/) ) {
|
||||
console.log('multiple URLs to append');
|
||||
bg = JSON.parse(bg);
|
||||
bg.forEach(
|
||||
function(bg_url){
|
||||
bg_url = (regBgUrlEscape.test(bg_url) ? JSON.stringify(bg_url) : bg_url );
|
||||
}
|
||||
);
|
||||
bg = 'url("' + bg.join('"), url("') + '"';
|
||||
var new_bg = e.target.style.backgroundImage + ', ' + bg;
|
||||
console.log('setting .backgroundImage: ' + new_bg );
|
||||
e.target.style.backgroundImage = new_bg;
|
||||
} else {
|
||||
console.log( 'appending bg url: ' + e.target.style.backgroundImage + ', url(' + (regBgUrlEscape.test(bg) ? JSON.stringify(bg) : bg ) + ')' );
|
||||
e.target.style.backgroundImage = e.target.style.backgroundImage + ', url("' + (regBgUrlEscape.test(bg) ? JSON.stringify(bg) : bg ) + '")';
|
||||
}
|
||||
} else {
|
||||
// Convert JSON for multiple URLs.
|
||||
if ( 0 === bg.search(/\[/) ) {
|
||||
console.log('multiple URLs to insert');
|
||||
bg = JSON.parse(bg);
|
||||
bg.forEach(
|
||||
function(bg_url){
|
||||
bg_url = (regBgUrlEscape.test(bg_url) ? JSON.stringify(bg_url) : bg_url );
|
||||
}
|
||||
);
|
||||
bg = 'url("' + bg.join('"), url("') + '"';
|
||||
console.log('setting .backgroundImage: ' + bg );
|
||||
e.target.style.backgroundImage = bg;
|
||||
} else {
|
||||
console.log('setting .backgroundImage: ' + 'url(' + (regBgUrlEscape.test(bg) ? JSON.stringify(bg) : bg ) + ')');
|
||||
e.target.style.backgroundImage = 'url(' + (regBgUrlEscape.test(bg) ? JSON.stringify(bg) : bg ) + ')';
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}, false);
|
||||
}
|
||||
}));
|
@ -0,0 +1,184 @@
|
||||
/*
|
||||
This plugin extends lazySizes to lazyLoad:
|
||||
background images, videos/posters and scripts
|
||||
|
||||
Background-Image:
|
||||
For background images, use data-bg attribute:
|
||||
<div class="lazyload" data-bg="bg-img.jpg"></div>
|
||||
|
||||
Video:
|
||||
For video/audio use data-poster and preload="none":
|
||||
<video class="lazyload" preload="none" data-poster="poster.jpg" src="src.mp4">
|
||||
<!-- sources -->
|
||||
</video>
|
||||
|
||||
For video that plays automatically if in view:
|
||||
<video
|
||||
class="lazyload"
|
||||
preload="none"
|
||||
muted=""
|
||||
data-autoplay=""
|
||||
data-poster="poster.jpg"
|
||||
src="src.mp4">
|
||||
</video>
|
||||
|
||||
Scripts:
|
||||
For scripts use data-script:
|
||||
<div class="lazyload" data-script="module-name.js"></div>
|
||||
|
||||
|
||||
Script modules using require:
|
||||
For modules using require use data-require:
|
||||
<div class="lazyload" data-require="module-name"></div>
|
||||
*/
|
||||
|
||||
(function(window, factory) {
|
||||
var globalInstall = function(){
|
||||
factory(window.lazySizes);
|
||||
window.removeEventListener('lazyunveilread', globalInstall, true);
|
||||
};
|
||||
|
||||
factory = factory.bind(null, window, window.document);
|
||||
|
||||
if(typeof module == 'object' && module.exports){
|
||||
factory(require('lazysizes'));
|
||||
} else if (typeof define == 'function' && define.amd) {
|
||||
define(['lazysizes'], factory);
|
||||
} else if(window.lazySizes) {
|
||||
globalInstall();
|
||||
} else {
|
||||
window.addEventListener('lazyunveilread', globalInstall, true);
|
||||
}
|
||||
}(window, function(window, document, lazySizes) {
|
||||
/*jshint eqnull:true */
|
||||
'use strict';
|
||||
var bgLoad, regBgUrlEscape;
|
||||
var uniqueUrls = {};
|
||||
|
||||
if(document.addEventListener){
|
||||
regBgUrlEscape = /\(|\)|\s|'/;
|
||||
|
||||
bgLoad = function (url, cb){
|
||||
var img = document.createElement('img');
|
||||
img.onload = function(){
|
||||
img.onload = null;
|
||||
img.onerror = null;
|
||||
img = null;
|
||||
cb();
|
||||
};
|
||||
img.onerror = img.onload;
|
||||
|
||||
img.src = url;
|
||||
|
||||
if(img && img.complete && img.onload){
|
||||
img.onload();
|
||||
}
|
||||
};
|
||||
|
||||
addEventListener('lazybeforeunveil', function(e){
|
||||
if(e.detail.instance != lazySizes){return;}
|
||||
|
||||
var tmp, load, bg, poster;
|
||||
if(!e.defaultPrevented) {
|
||||
|
||||
var target = e.target;
|
||||
|
||||
if(target.preload == 'none'){
|
||||
target.preload = target.getAttribute('data-preload') || 'auto';
|
||||
}
|
||||
|
||||
if (target.getAttribute('data-autoplay') != null) {
|
||||
if (target.getAttribute('data-expand') && !target.autoplay) {
|
||||
try {
|
||||
target.play();
|
||||
} catch (er) {}
|
||||
} else {
|
||||
requestAnimationFrame(function () {
|
||||
target.setAttribute('data-expand', '-10');
|
||||
lazySizes.aC(target, lazySizes.cfg.lazyClass);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
tmp = target.getAttribute('data-link');
|
||||
if(tmp){
|
||||
addStyleScript(tmp, true);
|
||||
}
|
||||
|
||||
// handle data-script
|
||||
tmp = target.getAttribute('data-script');
|
||||
if(tmp){
|
||||
e.detail.firesLoad = true;
|
||||
load = function(){
|
||||
e.detail.firesLoad = false;
|
||||
lazySizes.fire(target, '_lazyloaded', {}, true, true);
|
||||
};
|
||||
addStyleScript(tmp, null, load);
|
||||
}
|
||||
|
||||
// handle data-require
|
||||
tmp = target.getAttribute('data-require');
|
||||
if(tmp){
|
||||
if(lazySizes.cfg.requireJs){
|
||||
lazySizes.cfg.requireJs([tmp]);
|
||||
} else {
|
||||
addStyleScript(tmp);
|
||||
}
|
||||
}
|
||||
|
||||
// handle data-bg
|
||||
bg = target.getAttribute('data-bg');
|
||||
if (bg) {
|
||||
e.detail.firesLoad = true;
|
||||
load = function(){
|
||||
target.style.backgroundImage = 'url(' + (regBgUrlEscape.test(bg) ? JSON.stringify(bg) : bg ) + ')';
|
||||
e.detail.firesLoad = false;
|
||||
lazySizes.fire(target, '_lazyloaded', {}, true, true);
|
||||
};
|
||||
|
||||
bgLoad(bg, load);
|
||||
}
|
||||
|
||||
// handle data-poster
|
||||
poster = target.getAttribute('data-poster');
|
||||
if(poster){
|
||||
e.detail.firesLoad = true;
|
||||
load = function(){
|
||||
target.poster = poster;
|
||||
e.detail.firesLoad = false;
|
||||
lazySizes.fire(target, '_lazyloaded', {}, true, true);
|
||||
};
|
||||
|
||||
bgLoad(poster, load);
|
||||
|
||||
}
|
||||
}
|
||||
}, false);
|
||||
|
||||
}
|
||||
|
||||
function addStyleScript(src, style, cb){
|
||||
if(uniqueUrls[src]){
|
||||
return;
|
||||
}
|
||||
var elem = document.createElement(style ? 'link' : 'script');
|
||||
var insertElem = document.getElementsByTagName('script')[0];
|
||||
|
||||
if(style){
|
||||
elem.rel = 'stylesheet';
|
||||
elem.href = src;
|
||||
} else {
|
||||
elem.onload = function(){
|
||||
elem.onerror = null;
|
||||
elem.onload = null;
|
||||
cb();
|
||||
};
|
||||
elem.onerror = elem.onload;
|
||||
|
||||
elem.src = src;
|
||||
}
|
||||
uniqueUrls[src] = true;
|
||||
uniqueUrls[elem.src || elem.href] = true;
|
||||
insertElem.parentNode.insertBefore(elem, insertElem);
|
||||
}
|
||||
}));
|
109
wp-content/plugins/ewww-image-optimizer/includes/media.js
Normal file
@ -0,0 +1,109 @@
|
||||
jQuery(document).on('click', '.ewww-manual-optimize', function() {
|
||||
var post_id = jQuery(this).data('id');
|
||||
var ewww_nonce = jQuery(this).data('nonce');
|
||||
var ewww_manual_optimize_data = {
|
||||
action: 'ewww_manual_optimize',
|
||||
ewww_manual_nonce: ewww_nonce,
|
||||
ewww_force: 1,
|
||||
ewww_attachment_ID: post_id,
|
||||
};
|
||||
post_id = jQuery(this).closest('.ewww-media-status').data('id');
|
||||
jQuery('#ewww-media-status-' + post_id ).html( ewww_vars.optimizing );
|
||||
jQuery.post(ajaxurl, ewww_manual_optimize_data, function(response) {
|
||||
var ewww_manual_response = JSON.parse(response);
|
||||
if (ewww_manual_response.error) {
|
||||
jQuery('#ewww-media-status-' + post_id ).html( ewww_manual_response.error );
|
||||
} else if (ewww_manual_response.success) {
|
||||
jQuery('#ewww-media-status-' + post_id ).html( ewww_manual_response.success );
|
||||
}
|
||||
if (ewww_manual_response.basename) {
|
||||
var attachment_span = jQuery('#post-' + post_id + ' .column-title .filename .screen-reader-text').html();
|
||||
jQuery('#post-' + post_id + ' .column-title .filename').html('<span class="screen-reader-text">' + attachment_span + '</span>' + ewww_manual_response.basename);
|
||||
}
|
||||
});
|
||||
return false;
|
||||
});
|
||||
jQuery(document).on('click', '.ewww-manual-convert', function() {
|
||||
var post_id = jQuery(this).data('id');
|
||||
var ewww_nonce = jQuery(this).data('nonce');
|
||||
var ewww_manual_optimize_data = {
|
||||
action: 'ewww_manual_optimize',
|
||||
ewww_manual_nonce: ewww_nonce,
|
||||
ewww_force: 1,
|
||||
ewww_convert: 1,
|
||||
ewww_attachment_ID: post_id,
|
||||
};
|
||||
post_id = jQuery(this).closest('.ewww-media-status').data('id');
|
||||
jQuery('#ewww-media-status-' + post_id ).html( ewww_vars.optimizing );
|
||||
jQuery.post(ajaxurl, ewww_manual_optimize_data, function(response) {
|
||||
var ewww_manual_response = JSON.parse(response);
|
||||
if (ewww_manual_response.error) {
|
||||
jQuery('#ewww-media-status-' + post_id ).html( ewww_manual_response.error );
|
||||
} else if (ewww_manual_response.success) {
|
||||
jQuery('#ewww-media-status-' + post_id ).html( ewww_manual_response.success );
|
||||
}
|
||||
if (ewww_manual_response.basename) {
|
||||
var attachment_span = jQuery('#post-' + post_id + ' .column-title .filename .screen-reader-text').html();
|
||||
jQuery('#post-' + post_id + ' .column-title .filename').html('<span class="screen-reader-text">' + attachment_span + '</span>' + ewww_manual_response.basename);
|
||||
}
|
||||
});
|
||||
return false;
|
||||
});
|
||||
jQuery(document).on('click', '.ewww-manual-restore', function() {
|
||||
var post_id = jQuery(this).data('id');
|
||||
var ewww_nonce = jQuery(this).data('nonce');
|
||||
var ewww_manual_optimize_data = {
|
||||
action: 'ewww_manual_restore',
|
||||
ewww_manual_nonce: ewww_nonce,
|
||||
ewww_attachment_ID: post_id,
|
||||
};
|
||||
post_id = jQuery(this).closest('.ewww-media-status').data('id');
|
||||
jQuery('#ewww-media-status-' + post_id ).html( ewww_vars.restoring );
|
||||
jQuery.post(ajaxurl, ewww_manual_optimize_data, function(response) {
|
||||
var ewww_manual_response = JSON.parse(response);
|
||||
if (ewww_manual_response.error) {
|
||||
jQuery('#ewww-media-status-' + post_id ).html( ewww_manual_response.error );
|
||||
} else if (ewww_manual_response.success) {
|
||||
jQuery('#ewww-media-status-' + post_id ).html( ewww_manual_response.success );
|
||||
}
|
||||
if (ewww_manual_response.basename) {
|
||||
var attachment_span = jQuery('#post-' + post_id + ' .column-title .filename .screen-reader-text').html();
|
||||
jQuery('#post-' + post_id + ' .column-title .filename').html('<span class="screen-reader-text">' + attachment_span + '</span>' + ewww_manual_response.basename);
|
||||
}
|
||||
});
|
||||
return false;
|
||||
});
|
||||
jQuery(document).on('click', '.ewww-manual-image-restore', function() {
|
||||
var post_id = jQuery(this).data('id');
|
||||
var ewww_nonce = jQuery(this).data('nonce');
|
||||
var ewww_manual_optimize_data = {
|
||||
action: 'ewww_manual_image_restore',
|
||||
ewww_manual_nonce: ewww_nonce,
|
||||
ewww_attachment_ID: post_id,
|
||||
};
|
||||
post_id = jQuery(this).closest('.ewww-media-status').data('id');
|
||||
jQuery('#ewww-media-status-' + post_id ).html( ewww_vars.restoring );
|
||||
jQuery.post(ajaxurl, ewww_manual_optimize_data, function(response) {
|
||||
var ewww_manual_response = JSON.parse(response);
|
||||
if (ewww_manual_response.error) {
|
||||
jQuery('#ewww-media-status-' + post_id ).html( ewww_manual_response.error );
|
||||
} else if (ewww_manual_response.success) {
|
||||
jQuery('#ewww-media-status-' + post_id ).html( ewww_manual_response.success );
|
||||
}
|
||||
});
|
||||
return false;
|
||||
});
|
||||
jQuery(document).on('click', '.ewww-show-debug-meta', function() {
|
||||
var post_id = jQuery(this).data('id');
|
||||
jQuery('#ewww-debug-meta-' + post_id).toggle();
|
||||
});
|
||||
jQuery(document).on('click', '#ewww-image-optimizer-media-listmode .notice-dismiss', function() {
|
||||
var ewww_dismiss_media_data = {
|
||||
action: 'ewww_dismiss_media_notice',
|
||||
};
|
||||
jQuery.post(ajaxurl, ewww_dismiss_media_data, function(response) {
|
||||
if (response) {
|
||||
console.log(response);
|
||||
}
|
||||
});
|
||||
});
|
@ -0,0 +1,39 @@
|
||||
jQuery(document).on( 'click', '.ewww-manual-optimize', function() {
|
||||
var post_id = jQuery(this).data('id');
|
||||
var ewww_nonce = jQuery(this).data('nonce');
|
||||
var ewww_manual_optimize_data = {
|
||||
action: 'ewww_ngg_manual',
|
||||
ewww_manual_nonce: ewww_nonce,
|
||||
ewww_force: 1,
|
||||
ewww_attachment_ID: post_id,
|
||||
};
|
||||
jQuery('#ewww-nextcellent-status-' + post_id ).html( ewww_vars.optimizing );
|
||||
jQuery.post(ajaxurl, ewww_manual_optimize_data, function(response) {
|
||||
var ewww_manual_response = JSON.parse(response);
|
||||
if (ewww_manual_response.error) {
|
||||
jQuery('#ewww-nextcellent-status-' + post_id ).html( ewww_manual_response.error );
|
||||
} else if (ewww_manual_response.success) {
|
||||
jQuery('#ewww-nextcellent-status-' + post_id ).html( ewww_manual_response.success );
|
||||
}
|
||||
});
|
||||
return false;
|
||||
});
|
||||
jQuery(document).on( 'click', '.ewww-manual-cloud-restore', function() {
|
||||
var post_id = jQuery(this).data('id');
|
||||
var ewww_nonce = jQuery(this).data('nonce');
|
||||
var ewww_manual_optimize_data = {
|
||||
action: 'ewww_ngg_cloud_restore',
|
||||
ewww_manual_nonce: ewww_nonce,
|
||||
ewww_attachment_ID: post_id,
|
||||
};
|
||||
jQuery('#ewww-nextcellent-status-' + post_id ).html( ewww_vars.restoring );
|
||||
jQuery.post(ajaxurl, ewww_manual_optimize_data, function(response) {
|
||||
var ewww_manual_response = JSON.parse(response);
|
||||
if (ewww_manual_response.error) {
|
||||
jQuery('#ewww-nextcellent-status-' + post_id ).html( ewww_manual_response.error );
|
||||
} else if (ewww_manual_response.success) {
|
||||
jQuery('#ewww-nextcellent-status-' + post_id ).html( ewww_manual_response.success );
|
||||
}
|
||||
});
|
||||
return false;
|
||||
});
|
43
wp-content/plugins/ewww-image-optimizer/includes/nextgen.js
Normal file
@ -0,0 +1,43 @@
|
||||
jQuery(document).on( 'click', '.ewww-manual-optimize', function() {
|
||||
var post_id = jQuery(this).data('id');
|
||||
var ewww_nonce = jQuery(this).data('nonce');
|
||||
var ewww_manual_optimize_data = {
|
||||
action: 'ewww_ngg_manual',
|
||||
ewww_manual_nonce: ewww_nonce,
|
||||
ewww_force: 1,
|
||||
ewww_attachment_ID: post_id,
|
||||
};
|
||||
jQuery('#ewww-nextgen-status-' + post_id ).html( ewww_vars.optimizing );
|
||||
jQuery.post(ajaxurl, ewww_manual_optimize_data, function(response) {
|
||||
var ewww_manual_response = JSON.parse(response);
|
||||
if (ewww_manual_response.error) {
|
||||
jQuery('#ewww-nextgen-status-' + post_id ).html( ewww_manual_response.error );
|
||||
} else if (ewww_manual_response.success) {
|
||||
jQuery('#ewww-nextgen-status-' + post_id ).html( ewww_manual_response.success );
|
||||
}
|
||||
});
|
||||
return false;
|
||||
});
|
||||
jQuery(document).on( 'click', '.ewww-manual-image-restore', function() {
|
||||
var post_id = jQuery(this).data('id');
|
||||
var ewww_nonce = jQuery(this).data('nonce');
|
||||
var ewww_manual_optimize_data = {
|
||||
action: 'ewww_ngg_image_restore',
|
||||
ewww_manual_nonce: ewww_nonce,
|
||||
ewww_attachment_ID: post_id,
|
||||
};
|
||||
jQuery('#ewww-nextgen-status-' + post_id ).html( ewww_vars.restoring );
|
||||
jQuery.post(ajaxurl, ewww_manual_optimize_data, function(response) {
|
||||
var ewww_manual_response = JSON.parse(response);
|
||||
if (ewww_manual_response.error) {
|
||||
jQuery('#ewww-nextgen-status-' + post_id ).html( ewww_manual_response.error );
|
||||
} else if (ewww_manual_response.success) {
|
||||
jQuery('#ewww-nextgen-status-' + post_id ).html( ewww_manual_response.success );
|
||||
}
|
||||
});
|
||||
return false;
|
||||
});
|
||||
jQuery(document).on('click', '.ewww-show-debug-meta', function() {
|
||||
var post_id = jQuery(this).data('id');
|
||||
jQuery('#ewww-debug-meta-' + post_id).toggle();
|
||||
});
|
@ -0,0 +1,66 @@
|
||||
window.onload = function() {
|
||||
checkImageSizes();
|
||||
var adminBarButton = document.getElementById('wp-admin-bar-resize-detection');
|
||||
if (adminBarButton) {
|
||||
adminBarButton.onclick = function() {
|
||||
adminBarButton.classList.toggle('ewww-fade');
|
||||
clearScaledImages();
|
||||
checkImageSizes();
|
||||
setTimeout(function() {
|
||||
adminBarButton.classList.toggle('ewww-fade');
|
||||
}, 500);
|
||||
};
|
||||
}
|
||||
}
|
||||
function checkImageSizes() {
|
||||
// Find images which have width or height greater than their natural
|
||||
// width or height, and give them a stark and ugly marker, as well
|
||||
// as a useful title.
|
||||
var imgs = document.getElementsByTagName("img");
|
||||
for (i = 0; i < imgs.length; i++) {
|
||||
imgs[i].classList.remove('scaled-image');
|
||||
checkImageScale(imgs[i]);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
function checkImageScale(img) {
|
||||
if (!img.src) {
|
||||
return;
|
||||
}
|
||||
if ('string' == typeof img.src && img.src.search(/\.svg/) > -1) {
|
||||
return;
|
||||
}
|
||||
if ('string' == typeof img.src && img.src.search(/data:image/) > -1) {
|
||||
return;
|
||||
}
|
||||
console.log('checking size of: ' + img.src);
|
||||
if (img.naturalWidth) {
|
||||
if (img.naturalWidth > 25 && img.naturalHeight > 25 && img.clientWidth > 25 && img.clientHeight > 25) {
|
||||
// For each image with a natural width which isn't
|
||||
// a 1x1 image, check its size.
|
||||
var dPR = (window.devicePixelRatio || 1);
|
||||
var wrongWidth = (img.clientWidth * 1.5 * dPR < img.naturalWidth);
|
||||
var wrongHeight = (img.clientHeight * 1.5 * dPR < img.naturalHeight);
|
||||
if (wrongWidth || wrongHeight) {
|
||||
img.classList.add('scaled-image');
|
||||
img.title = "Forced to wrong size: " +
|
||||
img.clientWidth + "x" + img.clientHeight + ", natural is " +
|
||||
img.naturalWidth + "x" + img.naturalHeight + "!";
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
function clearScaledImages() {
|
||||
var scaledImages = document.querySelectorAll('img.scaled-image');
|
||||
for (var i = 0, len = scaledImages.length; i < len; i++){
|
||||
scaledImages[i].classList.remove('scaled-image');
|
||||
}
|
||||
}
|
||||
document.addEventListener('lazyloaded', function(e){
|
||||
e.target.classList.remove('scaled-image');
|
||||
var current_title = e.target.title;
|
||||
if (0 === current_title.search('Forced to wrong size')) {
|
||||
e.target.title = '';
|
||||
}
|
||||
checkImageScale(e.target);
|
||||
});
|
1
wp-content/plugins/ewww-image-optimizer/includes/resize-detection.min.js
vendored
Normal file
@ -0,0 +1 @@
|
||||
function checkImageSizes(){var e=document.getElementsByTagName("img");for(i=0;i<e.length;i++)e[i].classList.remove("scaled-image"),checkImageScale(e[i]);return!1}function checkImageScale(e){var t,a;e.src&&("string"==typeof e.src&&-1<e.src.search(/\.svg/)||"string"==typeof e.src&&-1<e.src.search(/data:image/)||e.naturalWidth&&25<e.naturalWidth&&25<e.naturalHeight&&25<e.clientWidth&&25<e.clientHeight&&(a=window.devicePixelRatio||1,t=1.5*e.clientWidth*a<e.naturalWidth,a=1.5*e.clientHeight*a<e.naturalHeight,(t||a)&&(e.classList.add("scaled-image"),e.title="Forced to wrong size: "+e.clientWidth+"x"+e.clientHeight+", natural is "+e.naturalWidth+"x"+e.naturalHeight+"!")))}function clearScaledImages(){for(var e=document.querySelectorAll("img.scaled-image"),t=0,a=e.length;t<a;t++)e[t].classList.remove("scaled-image")}window.onload=function(){checkImageSizes();var e=document.getElementById("wp-admin-bar-resize-detection");e&&(e.onclick=function(){e.classList.toggle("ewww-fade"),clearScaledImages(),checkImageSizes(),setTimeout(function(){e.classList.toggle("ewww-fade")},500)})},document.addEventListener("lazyloaded",function(e){e.target.classList.remove("scaled-image"),0===e.target.title.search("Forced to wrong size")&&(e.target.title=""),checkImageScale(e.target)});
|
55
wp-content/plugins/ewww-image-optimizer/includes/webp.js
Normal file
@ -0,0 +1,55 @@
|
||||
jQuery(document).ready(function($) {
|
||||
var ewww_error_counter = 30;
|
||||
var sleep_action = 'ewww_sleep';
|
||||
var init_action = 'webp_init';
|
||||
var loop_action = 'webp_loop';
|
||||
var cleanup_action = 'webp_cleanup';
|
||||
var init_data = {
|
||||
action: init_action,
|
||||
ewww_wpnonce: ewww_vars.ewww_wpnonce,
|
||||
};
|
||||
$('#webp-start').submit(function() {
|
||||
startMigrate();
|
||||
return false;
|
||||
});
|
||||
function startMigrate () {
|
||||
$('.webp-form').hide();
|
||||
$.post(ajaxurl, init_data, function(response) {
|
||||
$('#webp-loading').html(response);
|
||||
processLoop();
|
||||
});
|
||||
}
|
||||
function processLoop () {
|
||||
var loop_data = {
|
||||
action: loop_action,
|
||||
ewww_wpnonce: ewww_vars.ewww_wpnonce,
|
||||
};
|
||||
var jqxhr = $.post(ajaxurl, loop_data, function(response) {
|
||||
if (response) {
|
||||
$('#webp-status').append( response );
|
||||
$('#webp-loading').hide();
|
||||
processLoop();
|
||||
} else {
|
||||
var cleanup_data = {
|
||||
action: cleanup_action,
|
||||
ewww_wpnonce: ewww_vars.ewww_wpnonce,
|
||||
};
|
||||
$.post(ajaxurl, cleanup_data, function(response) {
|
||||
$('#webp-loading').hide();
|
||||
$('#webp-status').append(response);
|
||||
});
|
||||
}
|
||||
})
|
||||
.fail(function() {
|
||||
if (ewww_error_counter == 0) {
|
||||
$('#webp-loading').html('<p style="color: red"><b>Operation Interrupted</b></p>');
|
||||
} else {
|
||||
$('#webp-loading').html('<p style="color: red"><b>Temporary failure, retrying for ' + ewww_error_counter + ' more seconds.</b></p>');
|
||||
ewww_error_counter--;
|
||||
setTimeout(function() {
|
||||
processLoop();
|
||||
}, 1000);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
782
wp-content/plugins/ewww-image-optimizer/license.txt
Normal file
@ -0,0 +1,782 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<http://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
|
||||
|
||||
Additional Copyrights
|
||||
|
||||
Portions of the software are derived from
|
||||
Licenses of included software:
|
||||
|
||||
arrive.js
|
||||
|
||||
Copyright (c) 2014-2017 Uzair Farooq
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
|
||||
optipng
|
||||
|
||||
Copyright (C) 2001-2017 Cosmin Truta and the Contributing Authors.
|
||||
For the purpose of copyright and licensing, the list of Contributing
|
||||
Authors is available in the accompanying AUTHORS file.
|
||||
|
||||
This software is provided 'as-is', without any express or implied
|
||||
warranty. In no event will the author(s) be held liable for any damages
|
||||
arising from the use of this software.
|
||||
|
||||
pngquant.c
|
||||
|
||||
© 1989, 1991 by Jef Poskanzer.
|
||||
|
||||
Permission to use, copy, modify, and distribute this software and its
|
||||
documentation for any purpose and without fee is hereby granted, provided
|
||||
that the above copyright notice appear in all copies and that both that
|
||||
copyright notice and this permission notice appear in supporting
|
||||
documentation. This software is provided "as is" without express or
|
||||
implied warranty.
|
||||
|
||||
pngquant.c and rwpng.c/h
|
||||
|
||||
© 1997-2002 by Greg Roelofs; based on an idea by Stefan Schneider.
|
||||
© 2009-2017 by Kornel Lesiński.
|
||||
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without modification,
|
||||
are permitted provided that the following conditions are met:
|
||||
|
||||
1. Redistributions of source code must retain the above copyright notice,
|
||||
this list of conditions and the following disclaimer.
|
||||
|
||||
2. Redistributions in binary form must reproduce the above copyright notice,
|
||||
this list of conditions and the following disclaimer in the documentation
|
||||
and/or other materials provided with the distribution.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
WebP
|
||||
|
||||
Copyright (c) 2010, Google Inc. All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are
|
||||
met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright
|
||||
notice, this list of conditions and the following disclaimer.
|
||||
|
||||
* Redistributions in binary form must reproduce the above copyright
|
||||
notice, this list of conditions and the following disclaimer in
|
||||
the documentation and/or other materials provided with the
|
||||
distribution.
|
||||
|
||||
* Neither the name of Google nor the names of its contributors may
|
||||
be used to endorse or promote products derived from this software
|
||||
without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
244
wp-content/plugins/ewww-image-optimizer/mwebp.php
Normal file
@ -0,0 +1,244 @@
|
||||
<?php
|
||||
/**
|
||||
* Functions to migrate WebP files from the extension replacement to extension appending.
|
||||
*
|
||||
* @link https://ewww.io
|
||||
* @package EWWW_Image_Optimizer
|
||||
*/
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit;
|
||||
}
|
||||
/**
|
||||
* Displays the bulk migration form.
|
||||
*/
|
||||
function ewww_image_optimizer_webp_migrate_preview() {
|
||||
ewwwio_debug_message( '<b>' . __FUNCTION__ . '()</b>' );
|
||||
?>
|
||||
<div class="wrap">
|
||||
<h1><?php esc_html_e( 'Migrate WebP Images', 'ewww-image-optimizer' ); ?></h1>
|
||||
<?php
|
||||
esc_html_e( 'The migration is split into two parts. First, the plugin needs to scan all folders for webp images. Once it has obtained the list of images to rename, it will proceed with the renaming' );
|
||||
$button_text = esc_attr__( 'Start Migration', 'ewww-image-optimizer' );
|
||||
$loading_image = plugins_url( '/images/wpspin.gif', __FILE__ );
|
||||
// Create the html for the migration form and status divs.
|
||||
?>
|
||||
<div id="webp-loading">
|
||||
</div>
|
||||
<div id="webp-progressbar"></div>
|
||||
<div id="webp-counter"></div>
|
||||
<div id="webp-status"></div>
|
||||
<div id="bulk-forms">
|
||||
<form id="webp-start" class="webp-form" method="post" action="">
|
||||
<input id="webp-first" type="submit" class="button-secondary action" value="<?php esc_attr_e( 'Start Migration', 'ewww-image-optimizer' ); ?>" />
|
||||
</form>
|
||||
</div>
|
||||
<?php
|
||||
}
|
||||
|
||||
/**
|
||||
* Scan a folder for webp images using the old naming scheme and return them as an array.
|
||||
*
|
||||
* @return array A list of images with the old naming scheme.
|
||||
*/
|
||||
function ewww_image_optimizer_webp_scan() {
|
||||
ewwwio_debug_message( '<b>' . __FUNCTION__ . '()</b>' );
|
||||
$list = array();
|
||||
$dir = get_home_path();
|
||||
$iterator = new RecursiveIteratorIterator( new RecursiveDirectoryIterator( $dir ), RecursiveIteratorIterator::CHILD_FIRST );
|
||||
$start = microtime( true );
|
||||
$file_counter = 0;
|
||||
foreach ( $iterator as $path ) {
|
||||
if ( ewww_image_optimizer_stl_check() ) {
|
||||
set_time_limit( 0 );
|
||||
}
|
||||
$skip_optimized = false;
|
||||
if ( $path->isDir() ) {
|
||||
continue;
|
||||
} else {
|
||||
++$file_counter;
|
||||
$path = $path->getPathname();
|
||||
$newwebpformat = preg_replace( '/\.webp/', '', $path );
|
||||
if ( file_exists( $newwebpformat ) ) {
|
||||
continue;
|
||||
}
|
||||
if ( preg_match( '/\.webp$/', $path ) ) {
|
||||
ewwwio_debug_message( "queued $path" );
|
||||
$list[] = $path;
|
||||
}
|
||||
}
|
||||
}
|
||||
$end = microtime( true ) - $start;
|
||||
ewwwio_debug_message( "query time for $file_counter files (seconds): $end" );
|
||||
return $list;
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepares the migration and includes the javascript functions.
|
||||
*
|
||||
* @param string $hook The hook identifier for the current page.
|
||||
*/
|
||||
function ewww_image_optimizer_webp_script( $hook ) {
|
||||
ewwwio_debug_message( '<b>' . __FUNCTION__ . '()</b>' );
|
||||
// Make sure we are being called from the migration page.
|
||||
if ( 'admin_page_ewww-image-optimizer-webp-migrate' !== $hook ) {
|
||||
return;
|
||||
}
|
||||
$images = ewww_image_optimizer_webp_scan();
|
||||
// Remove the images array from the db if it currently exists, and then store the new list in the database.
|
||||
if ( get_option( 'ewww_image_optimizer_webp_images' ) ) {
|
||||
delete_option( 'ewww_image_optimizer_webp_images' );
|
||||
}
|
||||
add_option( 'ewww_image_optimizer_webp_images', '', '', 'no' );
|
||||
update_option( 'ewww_image_optimizer_webp_images', $images );
|
||||
wp_enqueue_script( 'ewwwwebpscript', plugins_url( '/includes/webp.js', __FILE__ ), array( 'jquery' ), EWWW_IMAGE_OPTIMIZER_VERSION );
|
||||
$image_count = count( $images );
|
||||
// Submit a couple variables to the javascript to work with.
|
||||
wp_localize_script(
|
||||
'ewwwwebpscript',
|
||||
'ewww_vars',
|
||||
array( 'ewww_wpnonce' => wp_create_nonce( 'ewww-image-optimizer-webp' ) )
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Called by javascript to initialize some output.
|
||||
*/
|
||||
function ewww_image_optimizer_webp_initialize() {
|
||||
// Verify that an authorized user has started the migration.
|
||||
$permissions = apply_filters( 'ewww_image_optimizer_admin_permissions', '' );
|
||||
if ( empty( $_REQUEST['ewww_wpnonce'] ) || ! wp_verify_nonce( sanitize_key( $_REQUEST['ewww_wpnonce'] ), 'ewww-image-optimizer-webp' ) || ! current_user_can( $permissions ) ) {
|
||||
ewwwio_ob_clean();
|
||||
die( esc_html__( 'Access denied.', 'ewww-image-optimizer' ) );
|
||||
}
|
||||
if ( get_option( 'ewww_image_optimizer_webp_skipped' ) ) {
|
||||
delete_option( 'ewww_image_optimizer_webp_skipped' );
|
||||
}
|
||||
add_option( 'ewww_image_optimizer_webp_skipped', '', '', 'no' );
|
||||
// Generate the WP spinner image for display.
|
||||
$loading_image = plugins_url( '/images/wpspin.gif', __FILE__ );
|
||||
// Let the user know that we are beginning.
|
||||
ewwwio_ob_clean();
|
||||
die( '<p>' . esc_html__( 'Scanning', 'ewww-image-optimizer' ) . ' <img src="' . esc_url( $loading_image ) . '" /></p>' );
|
||||
}
|
||||
|
||||
/**
|
||||
* Called by javascript to process each image in the queue.
|
||||
*/
|
||||
function ewww_image_optimizer_webp_loop() {
|
||||
ewwwio_debug_message( '<b>' . __FUNCTION__ . '()</b>' );
|
||||
$permissions = apply_filters( 'ewww_image_optimizer_admin_permissions', '' );
|
||||
if ( empty( $_REQUEST['ewww_wpnonce'] ) || ! wp_verify_nonce( sanitize_key( $_REQUEST['ewww_wpnonce'] ), 'ewww-image-optimizer-webp' ) || ! current_user_can( $permissions ) ) {
|
||||
ewwwio_ob_clean();
|
||||
die( esc_html__( 'Access token has expired, please reload the page.', 'ewww-image-optimizer' ) );
|
||||
}
|
||||
// Retrieve the time when the migration starts.
|
||||
$started = microtime( true );
|
||||
if ( ewww_image_optimizer_stl_check() ) {
|
||||
set_time_limit( 0 );
|
||||
}
|
||||
$images = array();
|
||||
ewwwio_debug_message( 'renaming images now' );
|
||||
$images_processed = 0;
|
||||
$images_skipped = '';
|
||||
$images = get_option( 'ewww_image_optimizer_webp_images' );
|
||||
if ( $images ) {
|
||||
/* translators: %d: number of images */
|
||||
printf( esc_html__( '%d Webp images left to rename.', 'ewww-image-optimizer' ), count( $images ) );
|
||||
echo '<br>';
|
||||
}
|
||||
while ( $images ) {
|
||||
++$images_processed;
|
||||
ewwwio_debug_message( "processed $images_processed images so far" );
|
||||
if ( $images_processed > 1000 ) {
|
||||
ewwwio_debug_message( 'hit 1000, breaking loop' );
|
||||
break;
|
||||
}
|
||||
$image = array_pop( $images );
|
||||
$replace_base = '';
|
||||
$skip = true;
|
||||
$pngfile = preg_replace( '/webp$/', 'png', $image );
|
||||
$upngfile = preg_replace( '/webp$/', 'PNG', $image );
|
||||
$jpgfile = preg_replace( '/webp$/', 'jpg', $image );
|
||||
$jpegfile = preg_replace( '/webp$/', 'jpeg', $image );
|
||||
$ujpgfile = preg_replace( '/webp$/', 'JPG', $image );
|
||||
if ( file_exists( $pngfile ) ) {
|
||||
$replace_base = $pngfile;
|
||||
$skip = false;
|
||||
} if ( file_exists( $upngfile ) ) {
|
||||
if ( empty( $replace_base ) ) {
|
||||
$replace_base = $upngfile;
|
||||
$skip = false;
|
||||
} else {
|
||||
$skip = true;
|
||||
}
|
||||
} if ( file_exists( $jpgfile ) ) {
|
||||
if ( empty( $replace_base ) ) {
|
||||
$replace_base = $jpgfile;
|
||||
$skip = false;
|
||||
} else {
|
||||
$skip = true;
|
||||
}
|
||||
} if ( file_exists( $jpegfile ) ) {
|
||||
if ( empty( $replace_base ) ) {
|
||||
$replace_base = $jpegfile;
|
||||
$skip = false;
|
||||
} else {
|
||||
$skip = true;
|
||||
}
|
||||
} if ( file_exists( $ujpgfile ) ) {
|
||||
if ( empty( $replace_base ) ) {
|
||||
$replace_base = $ujpgfile;
|
||||
$skip = false;
|
||||
} else {
|
||||
$skip = true;
|
||||
}
|
||||
}
|
||||
if ( $skip ) {
|
||||
if ( $replace_base ) {
|
||||
ewwwio_debug_message( "multiple replacement options for $image, not renaming" );
|
||||
} else {
|
||||
ewwwio_debug_message( "no match found for $image, strange..." );
|
||||
}
|
||||
$images_skipped .= "$image<br>";
|
||||
} else {
|
||||
ewwwio_debug_message( "renaming $image with match of $replace_base" );
|
||||
rename( $image, $replace_base . '.webp' );
|
||||
}
|
||||
} // End while().
|
||||
if ( $images_skipped ) {
|
||||
update_option( 'ewww_image_optimizer_webp_skipped', get_option( 'ewww_image_optimizer_webp_skipped' ) . $images_skipped );
|
||||
}
|
||||
// Calculate how much time has elapsed since we started.
|
||||
$elapsed = microtime( true ) - $started;
|
||||
ewwwio_debug_message( "took $elapsed seconds this time around" );
|
||||
// Store the updated list of images back in the database.
|
||||
update_option( 'ewww_image_optimizer_webp_images', $images );
|
||||
die();
|
||||
}
|
||||
|
||||
/**
|
||||
* Called by javascript to cleanup after ourselves.
|
||||
*/
|
||||
function ewww_image_optimizer_webp_cleanup() {
|
||||
$permissions = apply_filters( 'ewww_image_optimizer_admin_permissions', '' );
|
||||
if ( empty( $_REQUEST['ewww_wpnonce'] ) || ! wp_verify_nonce( sanitize_key( $_REQUEST['ewww_wpnonce'] ), 'ewww-image-optimizer-webp' ) || ! current_user_can( $permissions ) ) {
|
||||
ewwwio_ob_clean();
|
||||
die( esc_html__( 'Access token has expired, please reload the page.', 'ewww-image-optimizer' ) );
|
||||
}
|
||||
$skipped = get_option( 'ewww_image_optimizer_webp_skipped' );
|
||||
// All done, so we can remove the webp options...
|
||||
delete_option( 'ewww_image_optimizer_webp_images' );
|
||||
delete_option( 'ewww_image_optimizer_webp_skipped', '' );
|
||||
ewwwio_ob_clean();
|
||||
if ( $skipped ) {
|
||||
echo '<p><b>' . esc_html__( 'Skipped:', 'ewww-image-optimizer' ) . '</b></p>';
|
||||
echo wp_kses_post( "<p>$skipped</p>" );
|
||||
}
|
||||
// and let the user know we are done.
|
||||
die( '<p><b>' . esc_html__( 'Finished', 'ewww-image-optimizer' ) . '</b></p>' );
|
||||
}
|
||||
add_action( 'admin_enqueue_scripts', 'ewww_image_optimizer_webp_script' );
|
||||
add_action( 'wp_ajax_webp_init', 'ewww_image_optimizer_webp_initialize' );
|
||||
add_action( 'wp_ajax_webp_loop', 'ewww_image_optimizer_webp_loop' );
|
||||
add_action( 'wp_ajax_webp_cleanup', 'ewww_image_optimizer_webp_cleanup' );
|