Cleaning repo & changes on readME
This commit is contained in:
@@ -0,0 +1 @@
|
||||
<?php return array('dependencies' => array('react', 'wp-api-fetch', 'wp-components', 'wp-date', 'wp-element', 'wp-i18n', 'wp-url'), 'version' => '5f9e291d28b2047611cd');
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
|
||||
<?php return array('dependencies' => array('wp-a11y', 'wp-api-fetch', 'wp-escape-html', 'wp-i18n', 'wp-url'), 'version' => 'fba0bb7fdd8056185279');
|
||||
@@ -0,0 +1 @@
|
||||
.image-optimization-control--list-view{align-items:center;display:flex;justify-content:flex-start;min-height:105px}.image-optimization-control--list-view.image-optimization-control--error{align-items:flex-start;justify-content:center}.image-optimization-control__buttons-wrapper{margin-block-start:8px}.image-optimization-control__buttons-wrapper :not(:last-of-type){margin-inline-end:8px}.image-optimization-control--error{flex-direction:column}.image-optimization-control--optimized{align-items:flex-start;flex-direction:column}.image-optimization-control__error-message{display:flex;flex-direction:column;font-family:Roboto,sans-serif;font-size:14px;font-weight:600;line-height:24px;margin-block-end:15px;max-width:200px}.image-optimization-control__error-title{margin-block-end:10px}.image-optimization-control__error-subtitle{color:#dc2626}.image-optimization-control__button{border-radius:4px;font-family:Roboto,sans-serif;font-weight:500}.image-optimization-control__button--optimize>.spinner{float:left;margin-block-end:0;margin-block-start:4px;margin-left:0;padding:0}.image-optimization-control--error .image-optimization-control__button--try-again,.image-optimization-control--error .image-optimization-control__button--try-again:hover{background:transparent;border-color:#dc2626;color:#dc2626}.image-optimization-control__property{margin:9px 0}.image-optimization-control__details-button{background-color:transparent;border:none;color:#135e96;cursor:pointer;padding:0}.image-optimization-control .image-optimization-setting,.image-optimization-control__property:last-of-type{margin-block-end:0}.image-optimization-control--details-view .setting .image-optimization-control__property-value,.image-optimization-control__property-value{font-size:13px;font-weight:600;line-height:24px}.image-optimization-control--details-view .setting .image-optimization-control__property-value{margin:6px 3px 3px;text-align:start}.image-optimization-control--details-view .setting .image-optimization-control__property-value--button{font-weight:400;margin:0 0 0 3px}.image-optimization-control--details-view .setting .image-optimization-control__property-value--spinner{display:flex;justify-content:center;margin:25px 0 0 3px}.image-optimization-control__action-button-wrapper{display:flex;justify-content:flex-end;margin-block-start:37px;width:100%}.image-optimization-control__action-button-wrapper .button-link:not(:last-of-type){margin-inline-end:24px}.image-optimization-control--details-view .image-optimization-control__property-value--button .button-link,.image-optimization-control__action-button-wrapper .button-link{text-decoration:none}.image-optimization-control--details-view .image-optimization-control__property-value--button .button-link:hover,.image-optimization-control__action-button-wrapper .button-link:hover{background-color:transparent}.image-optimization-control__action-spinner-wrapper{align-items:center;display:flex;height:75px;justify-content:center}div .components-tooltip{max-width:165px;text-align:start}#image-optimization-optimization-details-modal{padding:20px 0}.image-optimization-details-table__property{display:block}.image-optimization-details-table__error{color:#dc2626;font-size:18px;font-weight:700}.image-optimization-details-table__property--error{color:#dc2626}body.dialog-container #TB_overlay{z-index:999999}body.dialog-container #TB_window{z-index:9999999}
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
|
||||
<?php return array('dependencies' => array(), 'version' => 'c72da904506127a4f056');
|
||||
@@ -0,0 +1 @@
|
||||
!function(){"use strict";var t,e={415:function(){function t(e){return t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},t(e)}function e(e,i){for(var n=0;n<i.length;n++){var o=i[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,(void 0,a=function(e,i){if("object"!==t(e)||null===e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var o=n.call(e,"string");if("object"!==t(o))return o;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(o.key),"symbol"===t(a)?a:String(a)),o)}var a}var i={unclear_how_to_use:["io_text_field_unclear","io_unclear_details"],switched_solution:["io_text_field_switched","io_switched_details"],other:["io_text_field_other","io_other_details"]},n=function(){function t(){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.deactivationLink=document.querySelector('[id*="deactivate-image-optimizer"], [id*="deactivate-image-optimization"]'),this.deactivationLink&&(this.originalDeactivationLink=this.deactivationLink.getAttribute("href"),this.init())}var n,o;return n=t,(o=[{key:"modal",value:function(t,e,i){var n,o;null===(n=(o=window).tb_show)||void 0===n||n.call(o,t,e),setTimeout((function(){var t;return null===(t=document.getElementById("TB_window"))||void 0===t?void 0:t.classList.add(i)}),5)}},{key:"hideFields",value:function(){document.querySelectorAll(".image-optimization-feedback-text-field").forEach((function(t){return t.classList.add("text-field-hidden")}))}},{key:"toggleField",value:function(t){var e;this.hideFields();var n=null===(e=i[t])||void 0===e?void 0:e[0];n&&document.getElementById(n).classList.remove("text-field-hidden")}},{key:"sendRequest",value:function(t,e){var i;fetch((null===(i=window)||void 0===i||null===(i=i.imageOptimizationDeactivationFeedback)||void 0===i?void 0:i.ajaxurl)||"",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t)}).finally(e)}},{key:"handleSubmit",value:function(){var t,e,n,o,a=this,r=null===(t=document.querySelector('input[name="image_optimization_deactivation_reason"]:checked'))||void 0===t?void 0:t.value,d=null===(e=i[r])||void 0===e?void 0:e[1],l=d&&(null===(n=document.getElementById(d))||void 0===n?void 0:n.value)||"";r?this.sendRequest({action:"image_optimization_deactivation_feedback",reason:r,additional_data:l,nonce:(null===(o=window)||void 0===o||null===(o=o.imageOptimizationDeactivationFeedback)||void 0===o?void 0:o.nonce)||""},(function(){return a.deactivate()})):this.deactivate()}},{key:"deactivate",value:function(){var t,e;null===(t=(e=window).tb_remove)||void 0===t||t.call(e),window.location.href=this.originalDeactivationLink}},{key:"init",value:function(){var t=this;this.deactivationLink.addEventListener("click",(function(e){e.preventDefault(),t.hideFields(),t.modal("QUICK FEEDBACK","#TB_inline?width=550&height=auto&inlineId=image-optimization-deactivation-modal","image-optimization-feedback-thickbox")})),document.addEventListener("change",(function(e){var i;"image_optimization_deactivation_reason"===(null===(i=e.target)||void 0===i?void 0:i.name)&&t.toggleField(e.target.value)})),document.addEventListener("click",(function(e){var i,n;"image-optimization-submit-deactivate"===(null===(i=e.target)||void 0===i?void 0:i.id)&&(e.preventDefault(),t.handleSubmit()),"image-optimization-skip-deactivate"===(null===(n=e.target)||void 0===n?void 0:n.id)&&(e.preventDefault(),t.deactivate())}))}}])&&e(n.prototype,o),Object.defineProperty(n,"prototype",{writable:!1}),t}();document.addEventListener("DOMContentLoaded",(function(){return new n}))}},i={};function n(t){var o=i[t];if(void 0!==o)return o.exports;var a=i[t]={exports:{}};return e[t](a,a.exports,n),a.exports}n.m=e,t=[],n.O=function(e,i,o,a){if(!i){var r=1/0;for(c=0;c<t.length;c++){i=t[c][0],o=t[c][1],a=t[c][2];for(var d=!0,l=0;l<i.length;l++)(!1&a||r>=a)&&Object.keys(n.O).every((function(t){return n.O[t](i[l])}))?i.splice(l--,1):(d=!1,a<r&&(r=a));if(d){t.splice(c--,1);var u=o();void 0!==u&&(e=u)}}return e}a=a||0;for(var c=t.length;c>0&&t[c-1][2]>a;c--)t[c]=t[c-1];t[c]=[i,o,a]},n.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},function(){var t={742:0,130:0};n.O.j=function(e){return 0===t[e]};var e=function(e,i){var o,a,r=i[0],d=i[1],l=i[2],u=0;if(r.some((function(e){return 0!==t[e]}))){for(o in d)n.o(d,o)&&(n.m[o]=d[o]);if(l)var c=l(n)}for(e&&e(i);u<r.length;u++)a=r[u],n.o(t,a)&&t[a]&&t[a][0](),t[a]=0;return n.O(c)},i=self.webpackChunkimage_optimization=self.webpackChunkimage_optimization||[];i.forEach(e.bind(null,0)),i.push=e.bind(null,i.push.bind(i))}();var o=n.O(void 0,[130],(function(){return n(415)}));o=n.O(o)}();
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 33 KiB |
@@ -0,0 +1 @@
|
||||
<?php return array('dependencies' => array('react', 'wp-api-fetch', 'wp-components', 'wp-core-data', 'wp-data', 'wp-date', 'wp-dom-ready', 'wp-element', 'wp-escape-html', 'wp-i18n', 'wp-url'), 'version' => '188a73aec01fb8e44dfa');
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
|
||||
.image-optimization-deactivation-modal{display:none}.image-optimization-deactivation-content{padding:20px}#TB_window.image-optimization-feedback-thickbox{border-radius:8px;box-shadow:0 10px 30px rgba(0,0,0,.3);height:auto!important;left:50%!important;margin:0!important;max-height:90vh;overflow:auto;top:50%!important;transform:translate(-50%,-50%)!important;width:600px!important}.image-optimization-feedback-thickbox #TB_ajaxContent{overflow:visible;padding:0}.image-optimization-feedback-thickbox #TB_title{display:flex;flex-direction:row;padding:5px}.image-optimization-feedback-thickbox #TB_closeWindowButton .tb-close-icon{box-shadow:none!important}.image-optimization-feedback-thickbox #TB_ajaxWindowTitle{font-size:14px;letter-spacing:1px}.image-optimization-deactivation-content h3{color:#23282d;font-size:18px;font-weight:600;margin-top:0}.image-optimization-deactivation-content p{color:#666;margin-bottom:20px}.image-optimization-feedback-options{margin-bottom:20px}.image-optimization-feedback-option{margin-bottom:15px}.image-optimization-feedback-option>label{align-items:center;color:#23282d;cursor:pointer;display:flex;margin-bottom:8px}.image-optimization-feedback-option input[type=radio]{margin-right:8px}.image-optimization-feedback-text-field{margin-left:24px;margin-top:8px}.text-field-hidden{display:none}.image-optimization-feedback-text-field label{color:#666;display:block;font-size:12px;margin-bottom:4px}.image-optimization-feedback-text-field input,.image-optimization-feedback-text-field textarea{border:1px solid #ddd;border-radius:3px;font-size:13px;padding:6px 8px;resize:vertical;width:100%}.image-optimization-feedback-text-field input:focus,.image-optimization-feedback-text-field textarea:focus{border-color:#0073aa;box-shadow:0 0 0 1px #0073aa;outline:none}.image-optimization-deactivation-buttons{border-top:1px solid #e1e1e1;display:flex;flex-direction:row-reverse;gap:10px;justify-content:space-between;padding-top:20px}.image-optimization-btn{background:none;border:none;border-radius:3px;color:silver;cursor:pointer;font-size:13px;font-weight:600;padding:8px 16px;text-decoration:none;transition:all .3s ease}.image-optimization-btn:hover{background:none;color:#000}.image-optimization-btn-primary{background:#f0abfc;border-color:#f0abfc;color:#000;font-weight:600;transition:all .3s ease}.image-optimization-btn-primary:hover{background:#e881fa;border-color:#e881fa;color:#000}.image-optimization-btn:focus{box-shadow:0 0 0 1px #5b9dd9,0 0 2px 1px rgba(30,140,190,.8);outline:none}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 31 KiB |
@@ -0,0 +1,13 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="30" height="30" fill="none">
|
||||
<g fill="#BABFC5" clip-path="url(#a)">
|
||||
<path d="m15.755 11.335-2.08-2.08a3.75 3.75 0 0 0-5.304 5.302l2.652 2.652a3.75 3.75 0 0 0 6.036-1.034l-.733-.734a1.235 1.235 0 0 0-.249-.193 2.5 2.5 0 0 1-4.17 1.077l-2.652-2.651a2.5 2.5 0 1 1 3.535-3.536l1.357 1.357a5.02 5.02 0 0 1 1.609-.16h-.001Z"/>
|
||||
<path d="m15.233 12.581.209.209c.322.322.538.71.647 1.12.424.114.81.337 1.12.648l.21.208a3.756 3.756 0 0 0-.36-1.826 3.75 3.75 0 0 0-1.826-.359Z"/>
|
||||
<path d="M18.093 13.674a3.75 3.75 0 0 0-6.037 1.034l.971.97a2.5 2.5 0 0 1 4.183-1.12l2.651 2.651a2.5 2.5 0 1 1-3.535 3.536l-1.357-1.357a5.025 5.025 0 0 1-1.609.159l2.082 2.081a3.75 3.75 0 0 0 5.303-5.303l-2.652-2.651Z"/>
|
||||
<path d="M12.056 17.943c.57.27 1.198.394 1.827.359l-.209-.209a2.487 2.487 0 0 1-.647-1.12 2.487 2.487 0 0 1-1.12-.648l-.21-.208a3.762 3.762 0 0 0 .36 1.826Z"/>
|
||||
</g>
|
||||
<defs>
|
||||
<clipPath id="a">
|
||||
<path fill="#fff" d="M15 .857 29.142 15 15 29.142.858 15z"/>
|
||||
</clipPath>
|
||||
</defs>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.1 KiB |
@@ -0,0 +1,3 @@
|
||||
<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path fill-rule="evenodd" clip-rule="evenodd" d="M10 1.875C8.93301 1.875 7.87647 2.08516 6.8907 2.49348C5.90493 2.9018 5.00923 3.50028 4.25476 4.25476C3.50028 5.00923 2.9018 5.90493 2.49348 6.8907C2.08516 7.87647 1.875 8.93301 1.875 10C1.875 11.067 2.08516 12.1235 2.49348 13.1093C2.9018 14.0951 3.50028 14.9908 4.25476 15.7452C5.00923 16.4997 5.90493 17.0982 6.8907 17.5065C7.87647 17.9148 8.93301 18.125 10 18.125C11.067 18.125 12.1235 17.9148 13.1093 17.5065C14.0951 17.0982 14.9908 16.4997 15.7452 15.7452C16.4997 14.9908 17.0982 14.0951 17.5065 13.1093C17.9148 12.1235 18.125 11.067 18.125 10C18.125 8.93301 17.9148 7.87647 17.5065 6.8907C17.0982 5.90493 16.4997 5.00923 15.7452 4.25476C14.9908 3.50028 14.0951 2.9018 13.1093 2.49348C12.1235 2.08516 11.067 1.875 10 1.875ZM13.5346 8.38024C13.7787 8.13616 13.7787 7.74043 13.5346 7.49635C13.2905 7.25228 12.8948 7.25228 12.6507 7.49635L8.96925 11.1778L7.34949 9.55805C7.10542 9.31398 6.70969 9.31398 6.46561 9.55805C6.22153 9.80213 6.22153 10.1979 6.46561 10.4419L8.52731 12.5036C8.64452 12.6208 8.80349 12.6867 8.96925 12.6867C9.13501 12.6867 9.29398 12.6208 9.41119 12.5036L13.5346 8.38024Z" fill="#F0ABFC"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.2 KiB |
+23
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Classes\Async_Operation;
|
||||
|
||||
use ImageOptimization\Classes\Basic_Enum;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
final class Async_Operation_Hook extends Basic_Enum {
|
||||
public const OPTIMIZE_SINGLE = 'image-optimization/optimize/single';
|
||||
public const OPTIMIZE_ON_UPLOAD = 'image-optimization/optimize/upload';
|
||||
public const OPTIMIZE_BULK = 'image-optimization/optimize/bulk';
|
||||
public const REOPTIMIZE_SINGLE = 'image-optimization/reoptimize/single';
|
||||
public const REOPTIMIZE_BULK = 'image-optimization/reoptimize/bulk';
|
||||
public const REMOVE_MANY_BACKUPS = 'image-optimization/backup/remove-many';
|
||||
public const RESTORE_SINGLE_IMAGE = 'image-optimization/restore/single';
|
||||
public const RESTORE_MANY_IMAGES = 'image-optimization/restore/restore-many';
|
||||
public const CALCULATE_OPTIMIZATION_STATS = 'image-optimization/optimization-stats/calculate';
|
||||
public const DB_MIGRATION = 'image-optimization/database/migration';
|
||||
public const STUCK_OPERATION_CLEANUP = 'image-optimization/cleanup/stuck-operation';
|
||||
}
|
||||
+82
@@ -0,0 +1,82 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Classes\Async_Operation;
|
||||
|
||||
use DateTime;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
class Async_Operation_Item {
|
||||
private int $id;
|
||||
private string $hook;
|
||||
private string $status;
|
||||
private array $args;
|
||||
private string $queue;
|
||||
private DateTime $date;
|
||||
private array $logs;
|
||||
|
||||
public function get_id(): int {
|
||||
return $this->id;
|
||||
}
|
||||
|
||||
public function set_id( int $id ): Async_Operation_Item {
|
||||
$this->id = $id;
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function get_hook(): string {
|
||||
return $this->hook;
|
||||
}
|
||||
|
||||
public function set_hook( string $hook ): Async_Operation_Item {
|
||||
$this->hook = $hook;
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function get_status(): string {
|
||||
return $this->status;
|
||||
}
|
||||
|
||||
public function set_status( string $status ): Async_Operation_Item {
|
||||
$this->status = $status;
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function get_args(): array {
|
||||
return $this->args;
|
||||
}
|
||||
|
||||
public function set_args( array $args ): Async_Operation_Item {
|
||||
$this->args = $args;
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function get_date(): DateTime {
|
||||
return $this->date;
|
||||
}
|
||||
|
||||
public function set_date( DateTime $date ): Async_Operation_Item {
|
||||
$this->date = $date;
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function get_queue(): string {
|
||||
return $this->queue;
|
||||
}
|
||||
|
||||
public function set_queue( string $queue ): Async_Operation_Item {
|
||||
$this->queue = $queue;
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function get_logs(): array {
|
||||
return $this->logs;
|
||||
}
|
||||
|
||||
public function set_logs( array $logs ): Async_Operation_Item {
|
||||
$this->logs = $logs;
|
||||
return $this;
|
||||
}
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Classes\Async_Operation;
|
||||
|
||||
use ImageOptimization\Classes\Basic_Enum;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
final class Async_Operation_Queue extends Basic_Enum {
|
||||
public const OPTIMIZE = 'image-optimization/optimize';
|
||||
public const BACKUP = 'image-optimization/backup';
|
||||
public const RESTORE = 'image-optimization/restore';
|
||||
public const STATS = 'image-optimization/stats';
|
||||
public const MIGRATION = 'image-optimization/migration';
|
||||
public const CLEANUP = 'image-optimization/cleanup';
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Classes\Async_Operation;
|
||||
|
||||
use ActionScheduler;
|
||||
use ImageOptimization\Classes\Async_Operation\{
|
||||
Exceptions\Async_Operation_Exception,
|
||||
Interfaces\Operation_Query_Interface
|
||||
};
|
||||
use ImageOptimization\Classes\Logger;
|
||||
use Throwable;
|
||||
use TypeError;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
class Async_Operation {
|
||||
public const OPERATION_STATUS_NOT_STARTED = 'not-started';
|
||||
public const OPERATION_STATUS_COMPLETE = 'complete';
|
||||
public const OPERATION_STATUS_PENDING = 'pending';
|
||||
public const OPERATION_STATUS_RUNNING = 'in-progress';
|
||||
public const OPERATION_STATUS_FAILED = 'failed';
|
||||
public const OPERATION_STATUS_CANCELED = 'canceled';
|
||||
|
||||
/**
|
||||
* @throws Async_Operation_Exception
|
||||
*/
|
||||
public static function create( string $hook, array $args, string $queue, int $priority = 10, $unique = false ): int {
|
||||
self::check_library_is_registered();
|
||||
|
||||
if ( ! in_array( $hook, Async_Operation_Hook::get_values(), true ) ) {
|
||||
Logger::log( Logger::LEVEL_ERROR, "Hook $hook is not a part of Async_Operation_Hook values" );
|
||||
|
||||
throw new TypeError( "Hook $hook is not a part of Async_Operation_Hook values" );
|
||||
}
|
||||
|
||||
if ( ! in_array( $queue, Async_Operation_Queue::get_values(), true ) ) {
|
||||
Logger::log( Logger::LEVEL_ERROR, "Queue $queue is not a part of Async_Operation_Queue values" );
|
||||
|
||||
throw new TypeError( "Queue $queue is not a part of Async_Operation_Queue values" );
|
||||
}
|
||||
|
||||
return as_enqueue_async_action(
|
||||
$hook,
|
||||
$args,
|
||||
$queue,
|
||||
$unique,
|
||||
$priority
|
||||
);
|
||||
}
|
||||
|
||||
public static function create_recurring( int $timestamp, int $interval_in_seconds, string $hook, array $args, string $queue, int $priority = 10, $unique = false ): int {
|
||||
self::check_library_is_registered();
|
||||
|
||||
if ( ! in_array( $hook, Async_Operation_Hook::get_values(), true ) ) {
|
||||
Logger::log( Logger::LEVEL_ERROR, "Hook $hook is not a part of Async_Operation_Hook values" );
|
||||
|
||||
throw new TypeError( "Hook $hook is not a part of Async_Operation_Hook values" );
|
||||
}
|
||||
|
||||
if ( ! in_array( $queue, Async_Operation_Queue::get_values(), true ) ) {
|
||||
Logger::log( Logger::LEVEL_ERROR, "Queue $queue is not a part of Async_Operation_Queue values" );
|
||||
|
||||
throw new TypeError( "Queue $queue is not a part of Async_Operation_Queue values" );
|
||||
}
|
||||
|
||||
return as_schedule_recurring_action(
|
||||
$timestamp,
|
||||
$interval_in_seconds,
|
||||
$hook,
|
||||
$args,
|
||||
$queue,
|
||||
$unique,
|
||||
$priority
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Operation_Query_Interface $query
|
||||
*
|
||||
* @return Async_Operation_Item[]|int[]
|
||||
* @throws Async_Operation_Exception
|
||||
*/
|
||||
public static function get( Operation_Query_Interface $query ): array {
|
||||
self::check_library_is_registered();
|
||||
|
||||
$actions = [];
|
||||
|
||||
$store = ActionScheduler::store();
|
||||
$logger = ActionScheduler::logger();
|
||||
|
||||
$action_ids = $store->query_actions( $query->get_query() );
|
||||
|
||||
if ( 'ids' === $query->get_return_type() ) {
|
||||
return $action_ids ?? [];
|
||||
}
|
||||
|
||||
foreach ( $action_ids as $action_id ) {
|
||||
try {
|
||||
$action = $store->fetch_action( $action_id );
|
||||
} catch ( Throwable $t ) {
|
||||
Logger::log(
|
||||
Logger::LEVEL_ERROR,
|
||||
"Unable to fetch an action `$action_id`. Reason: " . $t->getMessage()
|
||||
);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ( is_a( $action, 'ActionScheduler_NullAction' ) ) {
|
||||
Logger::log(
|
||||
Logger::LEVEL_WARN,
|
||||
'ActionScheduler_NullAction found'
|
||||
);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$item = new Async_Operation_Item();
|
||||
|
||||
$actions[] = $item->set_id( $action_id )
|
||||
->set_hook( $action->get_hook() )
|
||||
->set_status( $store->get_status( $action_id ) )
|
||||
->set_args( $action->get_args() )
|
||||
->set_queue( $action->get_group() )
|
||||
->set_date( $store->get_date( $action_id ) )
|
||||
->set_logs( $logger->get_logs( $action_id ) );
|
||||
}
|
||||
|
||||
return $actions;
|
||||
}
|
||||
|
||||
public static function get_by_id( int $action_id ): ?Async_Operation_Item {
|
||||
self::check_library_is_registered();
|
||||
|
||||
$store = ActionScheduler::store();
|
||||
$logger = ActionScheduler::logger();
|
||||
|
||||
try {
|
||||
$action = $store->fetch_action( $action_id );
|
||||
} catch ( Throwable $t ) {
|
||||
Logger::log(
|
||||
Logger::LEVEL_ERROR,
|
||||
"Unable to fetch an action `$action_id`. Reason: " . $t->getMessage()
|
||||
);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
if ( is_a( $action, 'ActionScheduler_NullAction' ) ) {
|
||||
Logger::log(
|
||||
Logger::LEVEL_WARN,
|
||||
'ActionScheduler_NullAction found'
|
||||
);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
return ( new Async_Operation_Item() )
|
||||
->set_id( $action_id )
|
||||
->set_hook( $action->get_hook() )
|
||||
->set_status( $store->get_status( $action_id ) )
|
||||
->set_args( $action->get_args() )
|
||||
->set_queue( $action->get_group() )
|
||||
->set_date( $store->get_date( $action_id ) )
|
||||
->set_logs( $logger->get_logs( $action_id ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws Async_Operation_Exception
|
||||
*/
|
||||
public static function cancel( int $operation_id ): void {
|
||||
self::check_library_is_registered();
|
||||
|
||||
$store = ActionScheduler::store();
|
||||
|
||||
$store->cancel_action( $operation_id );
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws Async_Operation_Exception
|
||||
*/
|
||||
public static function remove( array $operation_ids ): void {
|
||||
self::check_library_is_registered();
|
||||
|
||||
$store = ActionScheduler::store();
|
||||
|
||||
foreach ( $operation_ids as $operation_id ) {
|
||||
$store->delete_action( $operation_id );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws Async_Operation_Exception
|
||||
*/
|
||||
private static function check_library_is_registered(): void {
|
||||
if ( ! ActionScheduler::is_initialized() ) {
|
||||
Logger::log(
|
||||
Logger::LEVEL_ERROR,
|
||||
'ActionScheduler is not initialised though its method was called'
|
||||
);
|
||||
|
||||
throw new Async_Operation_Exception();
|
||||
}
|
||||
}
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Classes\Async_Operation\Exceptions;
|
||||
|
||||
use Exception;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
class Async_Operation_Exception extends Exception {
|
||||
protected $message = 'Async operation library is not loaded';
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Classes\Async_Operation\Interfaces;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
interface Operation_Query_Interface {
|
||||
public function get_query(): array;
|
||||
public function get_return_type(): string;
|
||||
}
|
||||
+89
@@ -0,0 +1,89 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Classes\Async_Operation\Queries;
|
||||
|
||||
use ImageOptimization\Classes\Async_Operation\{
|
||||
Async_Operation_Hook,
|
||||
Async_Operation_Queue,
|
||||
Interfaces\Operation_Query_Interface,
|
||||
};
|
||||
use TypeError;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
class Image_Optimization_Operation_Query implements Operation_Query_Interface {
|
||||
private array $query;
|
||||
|
||||
public function set_hook( string $hook ): self {
|
||||
if ( ! in_array( $hook, Async_Operation_Hook::get_values(), true ) ) {
|
||||
throw new TypeError( "Hook $hook is not a part of Async_Operation_Hook values" );
|
||||
}
|
||||
|
||||
$this->query['hook'] = $hook;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string|array $status
|
||||
* @return $this
|
||||
*/
|
||||
public function set_status( $status ): self {
|
||||
$this->query['status'] = $status;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function set_image_id( int $image_id ): self {
|
||||
if ( empty( $this->query['args'] ) ) {
|
||||
$this->query['args'] = [];
|
||||
}
|
||||
|
||||
$this->query['args']['attachment_id'] = $image_id;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function set_bulk_operation_id( string $operation_id ): self {
|
||||
if ( empty( $this->query['args'] ) ) {
|
||||
$this->query['args'] = [];
|
||||
}
|
||||
|
||||
$this->query['args']['operation_id'] = $operation_id;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function set_limit( int $limit ): self {
|
||||
$this->query['per_page'] = $limit;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function get_return_type(): string {
|
||||
return $this->query['_return_type'];
|
||||
}
|
||||
|
||||
public function return_ids(): self {
|
||||
$this->query['_return_type'] = 'ids';
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function get_query(): array {
|
||||
return $this->query;
|
||||
}
|
||||
|
||||
public function __construct() {
|
||||
$this->query = [
|
||||
'group' => Async_Operation_Queue::OPTIMIZE,
|
||||
'per_page' => 10,
|
||||
'orderby' => 'date',
|
||||
'order' => 'DESC',
|
||||
'partial_args_matching' => 'json',
|
||||
'_return_type' => 'object',
|
||||
];
|
||||
}
|
||||
}
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Classes\Async_Operation\Queries;
|
||||
|
||||
use ImageOptimization\Classes\Async_Operation\Async_Operation_Hook;
|
||||
use ImageOptimization\Classes\Async_Operation\Async_Operation_Queue;
|
||||
use ImageOptimization\Classes\Async_Operation\Interfaces\Operation_Query_Interface;
|
||||
use TypeError;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
class Operation_Query implements Operation_Query_Interface {
|
||||
private array $query;
|
||||
|
||||
public function set_hook( string $hook ): self {
|
||||
if ( ! in_array( $hook, Async_Operation_Hook::get_values(), true ) ) {
|
||||
throw new TypeError( "Hook $hook is not a part of Async_Operation_Hook values" );
|
||||
}
|
||||
|
||||
$this->query['hook'] = $hook;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function set_queue( string $queue ): self {
|
||||
if ( ! in_array( $queue, Async_Operation_Queue::get_values(), true ) ) {
|
||||
throw new TypeError( "Queue $queue is not a part of Async_Operation_Queue values" );
|
||||
}
|
||||
|
||||
$this->query['group'] = $queue;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string|array $status
|
||||
* @return $this
|
||||
*/
|
||||
public function set_status( $status ): self {
|
||||
$this->query['status'] = $status;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function set_image_id( int $image_id ): self {
|
||||
$this->query['args']['attachment_id'] = $image_id;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function set_limit( int $limit ): self {
|
||||
$this->query['per_page'] = $limit;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function get_return_type(): string {
|
||||
return $this->query['_return_type'];
|
||||
}
|
||||
|
||||
public function return_ids(): self {
|
||||
$this->query['_return_type'] = 'ids';
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function get_query(): array {
|
||||
$clone = $this->query;
|
||||
|
||||
if ( empty( $clone['args'] ) ) {
|
||||
unset( $clone['args'] );
|
||||
}
|
||||
|
||||
return $clone;
|
||||
}
|
||||
|
||||
public function __construct() {
|
||||
$this->query = [
|
||||
'args' => [],
|
||||
'per_page' => 10,
|
||||
'orderby' => 'date',
|
||||
'order' => 'DESC',
|
||||
'_return_type' => 'object',
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Classes;
|
||||
|
||||
use ReflectionClass;
|
||||
use ReflectionException;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
abstract class Basic_Enum {
|
||||
private static array $entries = [];
|
||||
|
||||
/**
|
||||
* @throws ReflectionException
|
||||
*/
|
||||
public static function get_values(): array {
|
||||
return array_values( self::get_entries() );
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws ReflectionException
|
||||
*/
|
||||
protected static function get_entries(): array {
|
||||
$caller = get_called_class();
|
||||
|
||||
if ( ! array_key_exists( $caller, self::$entries ) ) {
|
||||
$reflect = new ReflectionClass( $caller );
|
||||
self::$entries[ $caller ] = $reflect->getConstants();
|
||||
}
|
||||
|
||||
return self::$entries[ $caller ];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Classes\Client;
|
||||
|
||||
use Exception;
|
||||
use ImageOptimization\Classes\Exceptions\Quota_Exceeded_Error;
|
||||
use ImageOptimization\Modules\Optimization\Classes\Exceptions\Bulk_Token_Expired_Error;
|
||||
use ImageOptimization\Modules\Optimization\Classes\Exceptions\Image_Already_Optimized_Error;
|
||||
use Throwable;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
class Client_Response {
|
||||
private array $known_errors;
|
||||
/**
|
||||
* @var mixed
|
||||
*/
|
||||
private $response;
|
||||
|
||||
/**
|
||||
* @throws Throwable|Quota_Exceeded_Error|Bulk_Token_Expired_Error|Image_Already_Optimized_Error
|
||||
*/
|
||||
public function handle() {
|
||||
if ( ! is_wp_error( $this->response ) ) {
|
||||
return $this->response;
|
||||
}
|
||||
|
||||
$message = $this->response->get_error_message();
|
||||
|
||||
if ( isset( $this->known_errors[ $message ] ) ) {
|
||||
throw $this->known_errors[ $message ];
|
||||
}
|
||||
|
||||
throw new Exception( $message );
|
||||
}
|
||||
|
||||
public function __construct( $response ) {
|
||||
$this->known_errors = [
|
||||
'user reached limit' => new Quota_Exceeded_Error( esc_html__( 'Plan quota reached', 'image-optimization' ) ),
|
||||
'Bulk token expired' => new Bulk_Token_Expired_Error( esc_html__( 'Bulk token expired', 'image-optimization' ) ),
|
||||
'Image already optimized' => new Image_Already_Optimized_Error( esc_html__( 'Image already optimized', 'image-optimization' ) ),
|
||||
];
|
||||
$this->response = $response;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,320 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Classes\Client;
|
||||
|
||||
use ImageOptimization\Classes\Exceptions\Client_Exception;
|
||||
use ImageOptimization\Classes\File_Utils;
|
||||
use ImageOptimization\Classes\Image\Image;
|
||||
use ImageOptimization\Classes\Logger;
|
||||
use ImageOptimization\Modules\Stats\Classes\Optimization_Stats;
|
||||
use Throwable;
|
||||
use WP_Error;
|
||||
|
||||
use ImageOptimization\Plugin;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
/**
|
||||
* Class Client
|
||||
*/
|
||||
class Client {
|
||||
const BASE_URL = 'https://my.elementor.com/api/v2/image-optimizer/';
|
||||
const BASE_URL_FEEDBACK = 'https://feedback-api.prod.apps.elementor.red/apps/api/v1/';
|
||||
const STATUS_CHECK = 'status/check';
|
||||
const SITE_INFO = 'site/info';
|
||||
const SITE_INFO_TRANSIENT = 'image_optimizer_site_info_transient';
|
||||
|
||||
|
||||
private bool $refreshed = false;
|
||||
|
||||
public static ?Client $instance = null;
|
||||
|
||||
/**
|
||||
* get_instance
|
||||
* @return Client|null
|
||||
*/
|
||||
public static function get_instance(): ?Client {
|
||||
if ( ! self::$instance ) {
|
||||
self::$instance = new self();
|
||||
}
|
||||
return self::$instance;
|
||||
}
|
||||
|
||||
public static function get_site_info( $endpoint = null ): array {
|
||||
$data = [
|
||||
// Which API version is used.
|
||||
'app_version' => IMAGE_OPTIMIZATION_VERSION,
|
||||
// Which language to return.
|
||||
'site_lang' => get_bloginfo( 'language' ),
|
||||
// site to connect
|
||||
'site_url' => trailingslashit( home_url() ),
|
||||
// current user
|
||||
'local_id' => get_current_user_id(),
|
||||
|
||||
];
|
||||
|
||||
if ( $endpoint !== self::STATUS_CHECK ) {
|
||||
// Media library stats
|
||||
$data['media_data'] = base64_encode( wp_json_encode( self::get_request_stats() ) ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get site info
|
||||
* @return mixed|WP_Error|null
|
||||
*/
|
||||
public static function get_subscription_info() {
|
||||
$info = get_transient( self::SITE_INFO_TRANSIENT );
|
||||
if ( ! $info ) {
|
||||
try {
|
||||
$info = self::get_instance()->make_request( 'POST', self::SITE_INFO );
|
||||
} catch ( Throwable $t ) {
|
||||
Logger::log( Logger::LEVEL_ERROR, 'Cannot get site info response from service: ' . $t->getMessage() );
|
||||
return null;
|
||||
}
|
||||
|
||||
set_transient( self::SITE_INFO_TRANSIENT, $info, ( 24 * 60 * 60 ) );
|
||||
}
|
||||
return $info;
|
||||
}
|
||||
|
||||
private static function get_request_stats(): array {
|
||||
$optimization_stats = Optimization_Stats::get_image_stats();
|
||||
$image_sizes = [];
|
||||
|
||||
foreach ( wp_get_registered_image_subsizes() as $image_size_key => $image_size_data ) {
|
||||
$image_sizes[] = [
|
||||
'label' => $image_size_key,
|
||||
'size' => "{$image_size_data['width']}x{$image_size_data['height']}",
|
||||
];
|
||||
}
|
||||
|
||||
return [
|
||||
'not_optimized_images' => $optimization_stats['total_image_count'] - $optimization_stats['optimized_image_count'],
|
||||
'optimized_images' => $optimization_stats['optimized_image_count'],
|
||||
'images_sizes' => $image_sizes,
|
||||
];
|
||||
}
|
||||
|
||||
public function make_request( $method, $endpoint, $body = [], array $headers = [], $file = false, $file_name = '' ) {
|
||||
$headers = array_replace_recursive([
|
||||
'x-elementor-image-optimizer' => IMAGE_OPTIMIZATION_VERSION,
|
||||
], $headers);
|
||||
|
||||
$headers = array_replace_recursive(
|
||||
$headers,
|
||||
$this->is_connected() ? $this->generate_authentication_headers( $endpoint ) : []
|
||||
);
|
||||
|
||||
$body = array_replace_recursive( $body, $this->get_site_info( $endpoint ) );
|
||||
|
||||
try {
|
||||
if ( $file ) {
|
||||
$boundary = wp_generate_password( 24, false );
|
||||
$body = $this->get_upload_request_body( $body, $file, $boundary, $file_name );
|
||||
// add content type header
|
||||
$headers['Content-Type'] = 'multipart/form-data; boundary=' . $boundary;
|
||||
}
|
||||
} catch ( Client_Exception $ce ) {
|
||||
return new WP_Error( 500, $ce->getMessage() );
|
||||
}
|
||||
|
||||
$response = $this->request(
|
||||
$method,
|
||||
$endpoint,
|
||||
[
|
||||
'timeout' => 100,
|
||||
'headers' => $headers,
|
||||
'body' => $body,
|
||||
]
|
||||
);
|
||||
|
||||
return ( new Client_Response( $response ) )->handle();
|
||||
}
|
||||
|
||||
public static function get_feedback_base_url() {
|
||||
return apply_filters( 'image_optimizer_feedback_base_url', self::BASE_URL_FEEDBACK );
|
||||
}
|
||||
|
||||
private static function get_remote_url( $endpoint ): string {
|
||||
$base_url = apply_filters( 'image_optimizer_client_get_base_url', self::BASE_URL );
|
||||
|
||||
if ( strpos( $endpoint, 'feedback/' ) !== false ) {
|
||||
return self::get_feedback_base_url() . $endpoint;
|
||||
}
|
||||
|
||||
return $base_url . $endpoint;
|
||||
}
|
||||
|
||||
protected function is_connected(): bool {
|
||||
return Plugin::instance()->modules_manager->get_modules( 'connect-manager' )->connect_instance->is_connected();
|
||||
}
|
||||
|
||||
protected function generate_authentication_headers( $endpoint ): array {
|
||||
|
||||
$connect_instance = Plugin::instance()->modules_manager->get_modules( 'connect-manager' )->connect_instance;
|
||||
|
||||
if ( ! $connect_instance->get_is_connect_on_fly() ) {
|
||||
$headers = [
|
||||
'data' => base64_encode( // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
|
||||
wp_json_encode( [ 'app' => 'library' ] )
|
||||
),
|
||||
'access_token' => $connect_instance->get_access_token() ?? '',
|
||||
'client_id' => $connect_instance->get_client_id() ?? '',
|
||||
];
|
||||
|
||||
if ( $connect_instance->is_activated() ) {
|
||||
$headers['key'] = $connect_instance->get_activation_state() ?? '';
|
||||
}
|
||||
} else {
|
||||
$headers = $this->add_bearer_token([
|
||||
'x-elementor-apps-connect' => true,
|
||||
]);
|
||||
}
|
||||
|
||||
$headers['endpoint'] = $endpoint;
|
||||
$headers['x-elementor-apps'] = 'image-optimizer';
|
||||
|
||||
return $headers;
|
||||
}
|
||||
|
||||
protected function request( $method, $endpoint, $args = [] ) {
|
||||
$args['method'] = $method;
|
||||
|
||||
$response = wp_remote_request(
|
||||
self::get_remote_url( $endpoint ),
|
||||
$args
|
||||
);
|
||||
|
||||
if ( is_wp_error( $response ) ) {
|
||||
$message = $response->get_error_message();
|
||||
|
||||
return new WP_Error(
|
||||
$response->get_error_code(),
|
||||
is_array( $message ) ? join( ', ', $message ) : $message
|
||||
);
|
||||
}
|
||||
|
||||
$body = wp_remote_retrieve_body( $response );
|
||||
$response_code = (int) wp_remote_retrieve_response_code( $response );
|
||||
|
||||
if ( ! $response_code ) {
|
||||
return new WP_Error( 500, 'No Response' );
|
||||
}
|
||||
|
||||
// Server sent a success message without content.
|
||||
if ( 'null' === $body ) {
|
||||
$body = true;
|
||||
}
|
||||
|
||||
$body = json_decode( $body );
|
||||
|
||||
if ( false === $body ) {
|
||||
return new WP_Error( 422, 'Wrong Server Response' );
|
||||
}
|
||||
|
||||
if ( Plugin::instance()->modules_manager->get_modules( 'connect-manager' )->connect_instance->get_is_connect_on_fly() ) {
|
||||
// If the token is invalid, refresh it and try again once only.
|
||||
if ( ! $this->refreshed && ! empty( $body->message ) && ( false !== strpos( $body->message, 'Invalid Token' ) ) ) {
|
||||
Plugin::instance()->modules_manager->get_modules( 'connect-manager' )->connect_instance->refresh_token();
|
||||
$this->refreshed = true;
|
||||
$args['headers'] = $this->add_bearer_token( $args['headers'] );
|
||||
return $this->request( $method, $endpoint, $args );
|
||||
}
|
||||
}
|
||||
|
||||
if ( ! in_array( $response_code, [ 200, 201 ], true ) ) {
|
||||
// In case $as_array = true.
|
||||
$message = $body->message ?? wp_remote_retrieve_response_message( $response );
|
||||
$message = is_array( $message ) ? join( ', ', $message ) : $message;
|
||||
$code = isset( $body->code ) ? (int) $body->code : $response_code;
|
||||
|
||||
return new WP_Error( $code, $message );
|
||||
}
|
||||
|
||||
return $body;
|
||||
}
|
||||
|
||||
public function add_bearer_token( $headers ) {
|
||||
if ( $this->is_connected() ) {
|
||||
$headers['Authorization'] = 'Bearer ' . Plugin::instance()->modules_manager->get_modules( 'connect-manager' )->connect_instance->get_access_token();
|
||||
}
|
||||
return $headers;
|
||||
}
|
||||
|
||||
/**
|
||||
* get_upload_request_body
|
||||
*
|
||||
* @param array $body
|
||||
* @param $file
|
||||
* @param string $boundary
|
||||
* @param string $file_name
|
||||
*
|
||||
* @return string
|
||||
* @throws Client_Exception
|
||||
*/
|
||||
private function get_upload_request_body( array $body, $file, string $boundary, string $file_name = '' ): string {
|
||||
$payload = '';
|
||||
// add all body fields as standard POST fields:
|
||||
foreach ( $body as $name => $value ) {
|
||||
$payload .= '--' . $boundary;
|
||||
$payload .= "\r\n";
|
||||
$payload .= 'Content-Disposition: form-data; name="' . esc_attr( $name ) . '"' . "\r\n\r\n";
|
||||
$payload .= $value;
|
||||
$payload .= "\r\n";
|
||||
}
|
||||
|
||||
if ( is_array( $file ) ) {
|
||||
foreach ( $file as $key => $file_data ) {
|
||||
$payload .= $this->get_file_payload( $file_data['name'], $file_data['type'], $file_data['path'], $boundary );
|
||||
}
|
||||
} else {
|
||||
$image_mime = image_type_to_mime_type( exif_imagetype( $file ) );
|
||||
|
||||
if (
|
||||
! in_array( $image_mime, Image::get_supported_mime_types(), true ) &&
|
||||
( 'application/octet-stream' === $image_mime && 'avif' !== File_Utils::get_extension( $file ) )
|
||||
) {
|
||||
throw new Client_Exception( "Unsupported mime type `$image_mime`" );
|
||||
}
|
||||
|
||||
if ( empty( $file_name ) ) {
|
||||
$file_name = basename( $file );
|
||||
}
|
||||
|
||||
$payload .= $this->get_file_payload( $file_name, $image_mime, $file, $boundary );
|
||||
}
|
||||
|
||||
$payload .= '--' . $boundary . '--';
|
||||
|
||||
return $payload;
|
||||
}
|
||||
|
||||
/**
|
||||
* get_file_payload
|
||||
* @param string $filename
|
||||
* @param string $file_type
|
||||
* @param string $file_path
|
||||
* @param string $boundary
|
||||
* @return string
|
||||
*/
|
||||
private function get_file_payload( string $filename, string $file_type, string $file_path, string $boundary ): string {
|
||||
$name = $filename ?? basename( $file_path );
|
||||
$mine_type = 'image' === $file_type ? image_type_to_mime_type( exif_imagetype( $file_path ) ) : $file_type;
|
||||
$payload = '';
|
||||
// Upload the file
|
||||
$payload .= '--' . $boundary;
|
||||
$payload .= "\r\n";
|
||||
$payload .= 'Content-Disposition: form-data; name="' . esc_attr( $name ) . '"; filename="' . esc_attr( $name ) . '"' . "\r\n";
|
||||
$payload .= 'Content-Type: ' . $mine_type . "\r\n";
|
||||
$payload .= "\r\n";
|
||||
$payload .= file_get_contents( $file_path );
|
||||
$payload .= "\r\n";
|
||||
|
||||
return $payload;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Classes\Exceptions;
|
||||
|
||||
use Exception;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
class Client_Exception extends Exception {
|
||||
protected $message = 'Unknown client error';
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Classes\Exceptions;
|
||||
|
||||
use Exception;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
class File_Operation_Error extends Exception {
|
||||
protected $message = 'File operation error';
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Classes\Exceptions;
|
||||
|
||||
use Exception;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
class Quota_Exceeded_Error extends Exception {
|
||||
protected $message = 'Quota exceeded';
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Classes\File_System\Exceptions;
|
||||
|
||||
use Exception;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
class File_System_Operation_Error extends Exception {
|
||||
protected $message = 'File system operation error';
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Classes\File_System;
|
||||
|
||||
use ImageOptimization\Classes\File_System\Exceptions\File_System_Operation_Error;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
require_once ABSPATH . 'wp-admin/includes/file.php';
|
||||
WP_Filesystem();
|
||||
|
||||
/**
|
||||
* A wrapper class under WP_Filesystem that throws clear exceptions in case if something went wrong.
|
||||
*/
|
||||
class File_System {
|
||||
/**
|
||||
* Writes a string to a file.
|
||||
*
|
||||
* @param string $file Remote path to the file where to write the data.
|
||||
* @param string $contents The data to write.
|
||||
* @param int|false $mode The file permissions as octal number, usually 0644.
|
||||
*
|
||||
* @return true
|
||||
*
|
||||
* @throws File_System_Operation_Error
|
||||
*/
|
||||
public static function put_contents( string $file, string $contents, $mode = false ): bool {
|
||||
global $wp_filesystem;
|
||||
|
||||
$result = $wp_filesystem->put_contents( $file, $contents, $mode );
|
||||
|
||||
if ( ! $result ) {
|
||||
throw new File_System_Operation_Error( 'Error while writing ' . $file );
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes a file or directory.
|
||||
*
|
||||
* @param string $file Path to the file or directory.
|
||||
* @param bool $recursive If set to true, deletes files and folders recursively.
|
||||
* @param string|false $type Type of resource. 'f' for file, 'd' for directory.
|
||||
*
|
||||
* @return true
|
||||
*
|
||||
* @throws File_System_Operation_Error
|
||||
*/
|
||||
public static function delete( string $file, bool $recursive = false, $type = false ): bool {
|
||||
global $wp_filesystem;
|
||||
|
||||
$result = $wp_filesystem->delete( $file, $recursive, $type );
|
||||
|
||||
if ( ! $result ) {
|
||||
throw new File_System_Operation_Error( 'Error while deleting ' . $file );
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $source Path to the source file.
|
||||
* @param string $destination Path to the destination file.
|
||||
* @param bool $overwrite Whether to overwrite the destination file if it exists.
|
||||
*
|
||||
* @return true
|
||||
*
|
||||
* @throws File_System_Operation_Error
|
||||
*/
|
||||
public static function move( string $source, string $destination, bool $overwrite = false ): bool {
|
||||
global $wp_filesystem;
|
||||
|
||||
$result = $wp_filesystem->move( $source, $destination, $overwrite );
|
||||
|
||||
if ( ! $result ) {
|
||||
throw new File_System_Operation_Error( "Error while moving {$source} to {$destination}" );
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Copies a file.
|
||||
*
|
||||
* @param string $source Path to the source file.
|
||||
* @param string $destination Path to the destination file.
|
||||
* @param bool $overwrite Whether to overwrite the destination file if it exists.
|
||||
* @param int|false $mode The permissions as octal number, usually 0644 for files, 0755 for dirs.
|
||||
*
|
||||
* @return bool
|
||||
*
|
||||
* @throws File_System_Operation_Error
|
||||
*/
|
||||
public static function copy( string $source, string $destination, bool $overwrite = false, $mode = false ): bool {
|
||||
global $wp_filesystem;
|
||||
|
||||
$result = $wp_filesystem->copy( $source, $destination, $overwrite, $mode );
|
||||
|
||||
if ( ! $result ) {
|
||||
throw new File_System_Operation_Error( "Error while copying {$source} to {$destination}" );
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if a file or directory exists.
|
||||
*
|
||||
* @param string $path Path to file or directory.
|
||||
*
|
||||
* @return bool Whether $path exists or not.
|
||||
*/
|
||||
public static function exists( string $path ): bool {
|
||||
global $wp_filesystem;
|
||||
|
||||
return $wp_filesystem->exists( $path );
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the file size (in bytes).
|
||||
*
|
||||
* @param ?string $path Path to file.
|
||||
*
|
||||
* @return int Size of the file in bytes on success, false on failure.
|
||||
*
|
||||
* @throws File_System_Operation_Error
|
||||
*/
|
||||
public static function size( ?string $path ): int {
|
||||
global $wp_filesystem;
|
||||
|
||||
if ( is_null( $path ) ) {
|
||||
throw new File_System_Operation_Error( 'Null file path provided' );
|
||||
}
|
||||
|
||||
$size = $wp_filesystem->size( $path );
|
||||
|
||||
if ( ! $size ) {
|
||||
throw new File_System_Operation_Error( "Unable to calculate file size for $path" );
|
||||
}
|
||||
|
||||
return $size;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Classes;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
class File_Utils {
|
||||
public static function get_extension( string $path ): string {
|
||||
$locale = new Locale();
|
||||
$locale->set_utf_locale();
|
||||
|
||||
$extension = pathinfo( $path, PATHINFO_EXTENSION );
|
||||
|
||||
$locale->reset_to_original();
|
||||
|
||||
return $extension;
|
||||
}
|
||||
|
||||
public static function get_basename( string $path ): string {
|
||||
$locale = new Locale();
|
||||
$locale->set_utf_locale();
|
||||
|
||||
$basename = pathinfo( $path, PATHINFO_BASENAME );
|
||||
|
||||
$locale->reset_to_original();
|
||||
|
||||
return $basename;
|
||||
}
|
||||
|
||||
public static function replace_extension( string $path, string $new_extension, bool $unique_filename = false ): string {
|
||||
$locale = new Locale();
|
||||
$locale->set_utf_locale();
|
||||
|
||||
$path = pathinfo( $path );
|
||||
$basename = sprintf( '%s.%s', $path['filename'], $new_extension );
|
||||
|
||||
if ( $unique_filename ) {
|
||||
$basename = wp_unique_filename( $path['dirname'], $basename );
|
||||
}
|
||||
|
||||
$locale->reset_to_original();
|
||||
|
||||
return sprintf( '%s/%s', $path['dirname'], $basename );
|
||||
}
|
||||
|
||||
public static function get_unique_path( string $path ): string {
|
||||
$locale = new Locale();
|
||||
$locale->set_utf_locale();
|
||||
|
||||
$path = pathinfo( $path );
|
||||
$basename = sprintf( '%s.%s', $path['filename'], $path['extension'] );
|
||||
|
||||
$locale->reset_to_original();
|
||||
|
||||
return sprintf( '%s/%s', $path['dirname'], wp_unique_filename( $path['dirname'], $basename ) );
|
||||
}
|
||||
|
||||
public static function get_relative_upload_path( string $path ): string {
|
||||
$locale = new Locale();
|
||||
$locale->set_utf_locale();
|
||||
|
||||
$path = _wp_relative_upload_path( $path );
|
||||
|
||||
$locale->reset_to_original();
|
||||
|
||||
return $path;
|
||||
}
|
||||
|
||||
public static function get_url_from_path( string $full_path ): string {
|
||||
$locale = new Locale();
|
||||
$locale->set_utf_locale();
|
||||
|
||||
$upload_info = wp_upload_dir();
|
||||
$url_base = $upload_info['baseurl'];
|
||||
|
||||
$parts = preg_split(
|
||||
'/\/wp-content\/uploads/',
|
||||
$full_path
|
||||
);
|
||||
|
||||
$locale->reset_to_original();
|
||||
|
||||
return $url_base . $parts[1];
|
||||
}
|
||||
|
||||
public static function format_file_size( int $file_size_in_bytes, $decimals = 2 ): string {
|
||||
$sizes = [
|
||||
__( '%s Bytes', 'image-optimization' ),
|
||||
__( '%s Kb', 'image-optimization' ),
|
||||
__( '%s Mb', 'image-optimization' ),
|
||||
__( '%s Gb', 'image-optimization' ),
|
||||
];
|
||||
|
||||
if ( ! $file_size_in_bytes ) {
|
||||
return sprintf( $sizes[0], 0 );
|
||||
}
|
||||
|
||||
$current_scale = floor( log( $file_size_in_bytes ) / log( 1024 ) );
|
||||
$formatted_value = number_format( $file_size_in_bytes / pow( 1024, $current_scale ), $decimals );
|
||||
|
||||
return sprintf( $sizes[ $current_scale ], $formatted_value );
|
||||
}
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Classes\Image\Exceptions;
|
||||
|
||||
use Exception;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
class Image_Backup_Creation_Error extends Exception {
|
||||
protected $message = 'Backup creation error';
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Classes\Image\Exceptions;
|
||||
|
||||
use Exception;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
class Image_Restoring_Exception extends Exception {
|
||||
protected $message = 'Image cannot be restored';
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Classes\Image\Exceptions;
|
||||
|
||||
use Exception;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
class Invalid_Image_Exception extends Exception {
|
||||
protected $message = 'Invalid image';
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Classes\Image;
|
||||
|
||||
use ImageOptimization\Classes\File_System\Exceptions\File_System_Operation_Error;
|
||||
use ImageOptimization\Classes\File_System\File_System;
|
||||
use ImageOptimization\Classes\File_Utils;
|
||||
use ImageOptimization\Classes\Image\Exceptions\Image_Backup_Creation_Error;
|
||||
use ImageOptimization\Classes\Logger;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
/**
|
||||
* We're saving backup paths in meta even though the backup path could be dynamically generated.
|
||||
* The next reasons affected this decision:
|
||||
*
|
||||
* 1. Possible path conflicts with other plugins and/or custom user logic. We can't guarantee that the image
|
||||
* we find using the dynamically created path will be the same image we saved.
|
||||
* 2. If a backup doesn't exist, but stored in our meta -- we can be almost sure it's not because of us.
|
||||
* Probably, some other plugin removed it or even user manually did it, but it's not our fault. Makes this logic
|
||||
* easier to debug.
|
||||
* 3. We can change backup file name using `wp_unique_filename()` if needed and easily point a backup path to an
|
||||
* image.
|
||||
*/
|
||||
class Image_Backup {
|
||||
/**
|
||||
* Creates a backup of a file by copying it to a new file with the backup extension.
|
||||
* Also, attaches a newly created backup to image's meta.
|
||||
*
|
||||
* @param int $image_id Attachment id.
|
||||
* @param string $image_size Image size (e.g. 'full', 'thumbnail', etc.).
|
||||
* @param string $image_path Path to an image we plan to back up.
|
||||
*
|
||||
* @return string Backup path if successfully created, false otherwise.
|
||||
*
|
||||
* @throws Image_Backup_Creation_Error
|
||||
*/
|
||||
public static function create( int $image_id, string $image_size, string $image_path ): string {
|
||||
$extension = File_Utils::get_extension( $image_path );
|
||||
$backup_path = File_Utils::replace_extension( $image_path, "backup.$extension" );
|
||||
|
||||
try {
|
||||
File_System::copy( $image_path, $backup_path, true );
|
||||
} catch ( File_System_Operation_Error $e ) {
|
||||
Logger::log(
|
||||
Logger::LEVEL_ERROR,
|
||||
"Error while creating a backup for image {$image_id} and size {$image_size}"
|
||||
);
|
||||
|
||||
throw new Image_Backup_Creation_Error(
|
||||
"Error while creating a backup for image {$image_id} and size {$image_size}"
|
||||
);
|
||||
}
|
||||
|
||||
$meta = new Image_Meta( $image_id );
|
||||
|
||||
$meta->set_image_backup_path( $image_size, $backup_path );
|
||||
$meta->save();
|
||||
|
||||
return $backup_path;
|
||||
}
|
||||
|
||||
/**
|
||||
* Looks for registered backups and remove all files found.
|
||||
* Also, wipes removed files from image meta.
|
||||
*
|
||||
* @param int[] $image_ids Array of attachment ids.
|
||||
* @return void
|
||||
*/
|
||||
public static function remove_many( array $image_ids ): void {
|
||||
foreach ( $image_ids as $image_id ) {
|
||||
self::remove( $image_id );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes one or all backups for a specific image.
|
||||
* Also, wipes removed files from image meta.
|
||||
*
|
||||
* @param int $image_id Attachment id.
|
||||
* @param string|null $image_size Image size (e.g. 'full', 'thumbnail', etc.). All backups will be removed if no size provided.
|
||||
*
|
||||
* @return bool Returns true if backups were removed successfully, false otherwise.
|
||||
*/
|
||||
public static function remove( int $image_id, ?string $image_size = null ): bool {
|
||||
$meta = new Image_Meta( $image_id );
|
||||
$backups = $meta->get_image_backup_paths();
|
||||
|
||||
if ( empty( $backups ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ( $image_size ) {
|
||||
if ( ! key_exists( $image_size, $backups ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
File_System::delete( $backups[ $image_size ], false, 'f' );
|
||||
} catch ( File_System_Operation_Error $e ) {
|
||||
Logger::log(
|
||||
Logger::LEVEL_ERROR,
|
||||
"Error while removing a backup for image {$image_id} and size {$image_size}"
|
||||
);
|
||||
}
|
||||
|
||||
$meta->remove_image_backup_path( $image_size );
|
||||
$meta->save();
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
foreach ( $backups as $image_size => $backup_path ) {
|
||||
try {
|
||||
File_System::delete( $backup_path, false, 'f' );
|
||||
} catch ( File_System_Operation_Error $e ) {
|
||||
Logger::log( Logger::LEVEL_ERROR, "Error while removing backups {$image_id}" );
|
||||
}
|
||||
|
||||
$meta->remove_image_backup_path( $image_size );
|
||||
}
|
||||
|
||||
$meta->save();
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Classes\Image;
|
||||
|
||||
use ImageOptimization\Classes\Basic_Enum;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
final class Image_Conversion_Option extends Basic_Enum {
|
||||
public const ORIGINAL = 'original';
|
||||
public const WEBP = 'webp';
|
||||
public const AVIF = 'avif';
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Classes\Image;
|
||||
|
||||
use ImageOptimization\Modules\Settings\Classes\Settings;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
class Image_Conversion {
|
||||
protected ?string $convert_to_format;
|
||||
protected array $options;
|
||||
|
||||
public function is_enabled(): bool {
|
||||
return Image_Conversion_Option::ORIGINAL !== $this->convert_to_format;
|
||||
}
|
||||
|
||||
public function get_current_conversion_option(): string {
|
||||
return $this->convert_to_format;
|
||||
}
|
||||
|
||||
public function get_current_file_extension(): ?string {
|
||||
if ( ! $this->is_enabled() ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $this->options[ $this->convert_to_format ]['extension'];
|
||||
}
|
||||
|
||||
public function get_current_mime_type(): ?string {
|
||||
if ( ! $this->is_enabled() ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $this->options[ $this->convert_to_format ]['mime_type'];
|
||||
}
|
||||
|
||||
public function __construct() {
|
||||
$this->convert_to_format = Settings::get( Settings::CONVERT_TO_FORMAT_OPTION_NAME );
|
||||
|
||||
$this->options = [
|
||||
Image_Conversion_Option::WEBP => [
|
||||
'extension' => 'webp',
|
||||
'mime_type' => 'image/webp',
|
||||
],
|
||||
Image_Conversion_Option::AVIF => [
|
||||
'extension' => 'avif',
|
||||
'mime_type' => 'image/avif',
|
||||
],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Classes\Image;
|
||||
|
||||
use WP_Query;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
class Image_DB_Update {
|
||||
public static function update_posts_table_urls( string $old_url, string $new_url ) {
|
||||
$query = new WP_Query( [
|
||||
'post_type' => 'any',
|
||||
'post_status' => 'any',
|
||||
's' => $old_url,
|
||||
'search_columns' => [ 'post_content' ],
|
||||
] );
|
||||
|
||||
if ( ! $query->post_count ) {
|
||||
return;
|
||||
}
|
||||
|
||||
foreach ( $query->posts as $post ) {
|
||||
$new_content = str_replace( $old_url, $new_url, $post->post_content );
|
||||
|
||||
wp_update_post([
|
||||
'ID' => $post->ID,
|
||||
'post_content' => $new_content,
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Classes\Image;
|
||||
|
||||
use ImageOptimization\Classes\Logger;
|
||||
|
||||
use Imagick;
|
||||
use stdClass;
|
||||
use Throwable;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
class Image_Dimensions {
|
||||
/**
|
||||
* @param string $file_path
|
||||
*
|
||||
* @return stdClass{width: int, height: int}
|
||||
*/
|
||||
public static function get_by_path( string $file_path ): stdClass {
|
||||
$dimensions = wp_getimagesize( $file_path );
|
||||
$output = new stdClass();
|
||||
|
||||
$output->width = 0;
|
||||
$output->height = 0;
|
||||
|
||||
if ( $dimensions ) {
|
||||
$output->width = $dimensions[0];
|
||||
$output->height = $dimensions[1];
|
||||
|
||||
return $output;
|
||||
}
|
||||
|
||||
if ( class_exists( 'Imagick' ) ) {
|
||||
try {
|
||||
$im = new Imagick( $file_path );
|
||||
$image_geometry = $im->getImageGeometry();
|
||||
$im->clear();
|
||||
|
||||
$output->width = $image_geometry['width'];
|
||||
$output->height = $image_geometry['height'];
|
||||
} catch ( Throwable $t ) {
|
||||
Logger::log(
|
||||
Logger::LEVEL_ERROR,
|
||||
'AVIF image dimensions calculation error: ' . $t->getMessage()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return $output;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Classes\Image;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
class Image_Meta {
|
||||
public const IMAGE_OPTIMIZER_METADATA_KEY = 'image_optimizer_metadata';
|
||||
private const INITIAL_META_VALUE = [
|
||||
'status' => Image_Status::NOT_OPTIMIZED,
|
||||
'error_type' => null,
|
||||
'compression_level' => null,
|
||||
'retry_count' => null,
|
||||
'sizes_optimized' => [],
|
||||
'backups' => [],
|
||||
'original_data' => [
|
||||
'sizes' => [],
|
||||
],
|
||||
];
|
||||
|
||||
private int $image_id;
|
||||
private array $image_meta;
|
||||
|
||||
public function get_status(): string {
|
||||
return $this->image_meta['status'];
|
||||
}
|
||||
|
||||
public function set_status( string $status ): Image_Meta {
|
||||
$this->image_meta['status'] = $status;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function get_error_type(): ?string {
|
||||
return $this->image_meta['error_type'];
|
||||
}
|
||||
|
||||
public function set_error_type( ?string $type ): Image_Meta {
|
||||
$this->image_meta['error_type'] = $type;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function get_compression_level(): ?string {
|
||||
return $this->image_meta['compression_level'];
|
||||
}
|
||||
|
||||
public function set_compression_level( string $compression_level ): Image_Meta {
|
||||
$this->image_meta['compression_level'] = $compression_level;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function get_retry_count(): ?int {
|
||||
return $this->image_meta['retry_count'];
|
||||
}
|
||||
|
||||
public function set_retry_count( ?int $retry_count ): Image_Meta {
|
||||
$this->image_meta['retry_count'] = $retry_count;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function get_optimized_sizes(): array {
|
||||
return $this->image_meta['sizes_optimized'];
|
||||
}
|
||||
|
||||
public function add_optimized_size( string $optimized_size ): Image_Meta {
|
||||
if ( ! in_array( $optimized_size, $this->image_meta['sizes_optimized'], true ) ) {
|
||||
$this->image_meta['sizes_optimized'][] = $optimized_size;
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function clear_optimized_sizes(): Image_Meta {
|
||||
$this->image_meta['sizes_optimized'] = [];
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function set_optimized_size( array $optimized_size ): Image_Meta {
|
||||
$this->image_meta['sizes_optimized'] = $optimized_size;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function clear_backups(): Image_Meta {
|
||||
$this->image_meta['backups'] = [];
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function get_image_backup_paths(): array {
|
||||
return $this->image_meta['backups'];
|
||||
}
|
||||
|
||||
public function get_image_backup_path( string $image_size ): ?string {
|
||||
return $this->image_meta['backups'][ $image_size ] ?? null;
|
||||
}
|
||||
|
||||
public function set_image_backup_path( string $image_size, string $backup_path ): Image_Meta {
|
||||
$this->image_meta['backups'][ $image_size ] = $backup_path;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function remove_image_backup_path( string $image_size ): Image_Meta {
|
||||
unset( $this->image_meta['backups'][ $image_size ] );
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function get_original_file_size( string $image_size ): ?int {
|
||||
if ( ! isset( $this->image_meta['original_data']['sizes'][ $image_size ]['filesize'] ) ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $this->image_meta['original_data']['sizes'][ $image_size ]['filesize'];
|
||||
}
|
||||
|
||||
public function get_original_mime_type( string $image_size ): ?string {
|
||||
if ( ! isset( $this->image_meta['original_data']['sizes'][ $image_size ] ) ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $this->image_meta['original_data']['sizes'][ $image_size ]['mime-type'];
|
||||
}
|
||||
|
||||
public function get_original_width( string $image_size ): ?string {
|
||||
if ( ! isset( $this->image_meta['original_data']['sizes'][ $image_size ] ) ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $this->image_meta['original_data']['sizes'][ $image_size ]['width'];
|
||||
}
|
||||
|
||||
public function get_original_height( string $image_size ): ?string {
|
||||
if ( ! isset( $this->image_meta['original_data']['sizes'][ $image_size ] ) ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $this->image_meta['original_data']['sizes'][ $image_size ]['height'];
|
||||
}
|
||||
|
||||
public function add_original_data( string $size, array $data ): Image_Meta {
|
||||
$this->image_meta['original_data']['sizes'][ $size ] = $data;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function clear_original_data(): Image_Meta {
|
||||
$this->image_meta['original_data'] = [ 'sizes' => [] ];
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function delete(): bool {
|
||||
return delete_post_meta( $this->image_id, self::IMAGE_OPTIMIZER_METADATA_KEY );
|
||||
}
|
||||
|
||||
public function save(): Image_Meta {
|
||||
update_post_meta( $this->image_id, self::IMAGE_OPTIMIZER_METADATA_KEY, $this->image_meta );
|
||||
|
||||
$this->query_meta();
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
private function query_meta(): void {
|
||||
$meta = get_post_meta( $this->image_id, self::IMAGE_OPTIMIZER_METADATA_KEY, true );
|
||||
$this->image_meta = $meta ? array_replace_recursive( self::INITIAL_META_VALUE, $meta ) : self::INITIAL_META_VALUE;
|
||||
}
|
||||
|
||||
public function __construct( int $image_id ) {
|
||||
$this->image_id = $image_id;
|
||||
|
||||
$this->query_meta();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Classes\Image;
|
||||
|
||||
use ImageOptimization\Classes\Basic_Enum;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
final class Image_Optimization_Error_Type extends Basic_Enum {
|
||||
public const QUOTA_EXCEEDED = 'quota-exceeded';
|
||||
public const FILE_ALREADY_EXISTS = 'file-already-exists';
|
||||
public const PLUGIN_DEACTIVATION = 'plugin-deactivation';
|
||||
public const GENERIC = 'generic';
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Classes\Image;
|
||||
|
||||
use WP_Query;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
class Image_Query_Builder {
|
||||
private array $query;
|
||||
|
||||
public function return_images_only_with_backups(): self {
|
||||
$this->query['meta_query'][] = [
|
||||
'compare' => 'NOT LIKE',
|
||||
'value' => '"backups";a:0', // Serialized empty array of backups
|
||||
'key' => Image_Meta::IMAGE_OPTIMIZER_METADATA_KEY,
|
||||
];
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function return_not_optimized_images(): self {
|
||||
$this->query['meta_query'][] = [
|
||||
'relation' => 'OR',
|
||||
[
|
||||
'key' => Image_Meta::IMAGE_OPTIMIZER_METADATA_KEY,
|
||||
'compare' => 'NOT EXISTS',
|
||||
],
|
||||
[
|
||||
'compare' => 'LIKE',
|
||||
'value' => '-failed";',
|
||||
'key' => Image_Meta::IMAGE_OPTIMIZER_METADATA_KEY,
|
||||
],
|
||||
[
|
||||
'compare' => 'LIKE',
|
||||
'value' => ':"not-optimized";',
|
||||
'key' => Image_Meta::IMAGE_OPTIMIZER_METADATA_KEY,
|
||||
],
|
||||
];
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function return_optimization_in_progress_images(): self {
|
||||
$this->query['meta_query'][] = [
|
||||
'relation' => 'AND',
|
||||
[
|
||||
'key' => '_wp_attachment_metadata',
|
||||
'compare' => 'EXISTS',
|
||||
],
|
||||
[
|
||||
'relation' => 'OR',
|
||||
[
|
||||
'compare' => 'LIKE',
|
||||
'value' => 'optimization-in-progress";',
|
||||
'key' => 'image_optimizer_metadata',
|
||||
],
|
||||
[
|
||||
'compare' => 'LIKE',
|
||||
'value' => 'reoptimizing-in-progress";',
|
||||
'key' => 'image_optimizer_metadata',
|
||||
],
|
||||
],
|
||||
];
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function return_optimized_images(): self {
|
||||
$this->query['meta_query'][] = [
|
||||
'compare' => 'LIKE',
|
||||
'value' => '"status";s:9:"optimized"',
|
||||
'key' => Image_Meta::IMAGE_OPTIMIZER_METADATA_KEY,
|
||||
];
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function return_images_with_non_empty_meta(): self {
|
||||
$this->query['meta_query'][] = [
|
||||
'key' => Image_Meta::IMAGE_OPTIMIZER_METADATA_KEY,
|
||||
'compare' => 'EXISTS',
|
||||
];
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function set_paging_size( int $paging_size ): self {
|
||||
$this->query['posts_per_page'] = $paging_size;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function set_current_page( int $current_page ): self {
|
||||
$this->query['paged'] = $current_page;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function set_image_ids( array $image_ids ): self {
|
||||
// Passing an empty array to post__in will return the last posts instead of an empty result.
|
||||
$this->query['post__in'] = count( $image_ids ) ? $image_ids : [ 0 ];
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function set_mime_types( array $mime_types ): self {
|
||||
$this->query['post_mime_type'] = $mime_types;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function execute(): WP_Query {
|
||||
return new WP_Query( $this->query );
|
||||
}
|
||||
|
||||
public function __construct() {
|
||||
$basic_query = [
|
||||
'post_type' => 'attachment',
|
||||
'post_mime_type' => Image::get_supported_mime_types(),
|
||||
'post_status' => 'any',
|
||||
'fields' => 'ids',
|
||||
'posts_per_page' => -1,
|
||||
'meta_query' => [
|
||||
'relation' => 'AND',
|
||||
[
|
||||
'key' => '_wp_attachment_metadata', // Images without this field considered invalid
|
||||
'compare' => 'EXISTS',
|
||||
],
|
||||
],
|
||||
];
|
||||
|
||||
$this->query = $basic_query;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Classes\Image;
|
||||
|
||||
use ImageOptimization\Classes\File_System\{
|
||||
Exceptions\File_System_Operation_Error,
|
||||
File_System,
|
||||
};
|
||||
use ImageOptimization\Classes\File_Utils;
|
||||
use ImageOptimization\Classes\Image\Exceptions\{
|
||||
Image_Restoring_Exception,
|
||||
Invalid_Image_Exception,
|
||||
};
|
||||
use ImageOptimization\Classes\Logger;
|
||||
use Throwable;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
class Image_Restore {
|
||||
public static function restore_many( array $image_ids, bool $keep_image_meta = false ): void {
|
||||
foreach ( $image_ids as $image_id ) {
|
||||
try {
|
||||
self::restore( $image_id, $keep_image_meta );
|
||||
} catch ( Throwable $t ) {
|
||||
Logger::log( Logger::LEVEL_ERROR, 'Bulk images restoring error: ' . $t->getMessage() );
|
||||
|
||||
( new Image_Meta( $image_id ) )
|
||||
->set_status( Image_Status::RESTORING_FAILED )
|
||||
->save();
|
||||
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws Invalid_Image_Exception|Image_Restoring_Exception|File_System_Operation_Error
|
||||
*/
|
||||
public static function restore( int $image_id, bool $keep_image_meta = false ): void {
|
||||
$image = new Image( $image_id );
|
||||
|
||||
if ( ! $image->can_be_restored() ) {
|
||||
throw new Image_Restoring_Exception( "Image $image_id cannot be restored" );
|
||||
}
|
||||
|
||||
$meta = new Image_Meta( $image_id );
|
||||
$wp_meta = new WP_Image_Meta( $image_id );
|
||||
|
||||
foreach ( $meta->get_optimized_sizes() as $image_size ) {
|
||||
$backup_path = $meta->get_image_backup_path( $image_size );
|
||||
$current_path = $image->get_file_path( $image_size );
|
||||
|
||||
if ( $backup_path && $current_path ) {
|
||||
$original_path = self::get_path_from_backup_path( $backup_path );
|
||||
|
||||
if ( $original_path === $backup_path ) {
|
||||
File_System::delete( $current_path, false, 'f' );
|
||||
|
||||
self::update_posts( $current_path, $original_path );
|
||||
} else {
|
||||
File_System::move( $backup_path, $original_path, $original_path === $current_path );
|
||||
|
||||
if ( $original_path !== $current_path ) {
|
||||
File_System::delete( $current_path, false, 'f' );
|
||||
|
||||
self::update_posts( $current_path, $original_path );
|
||||
}
|
||||
}
|
||||
|
||||
$file_size = $meta->get_original_file_size( $image_size ) ?? File_System::size( $original_path );
|
||||
|
||||
$wp_meta
|
||||
->set_file_path( $image_size, $original_path )
|
||||
->set_mime_type( $image_size, $meta->get_original_mime_type( $image_size ) )
|
||||
->set_width( $image_size, $meta->get_original_width( $image_size ) )
|
||||
->set_height( $image_size, $meta->get_original_height( $image_size ) )
|
||||
->set_file_size( $image_size, $file_size );
|
||||
|
||||
if ( Image::SIZE_FULL === $image_size ) {
|
||||
self::update_image_post(
|
||||
$image,
|
||||
$original_path,
|
||||
$meta->get_original_mime_type( Image::SIZE_FULL )
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$wp_meta->save();
|
||||
|
||||
if ( $keep_image_meta ) {
|
||||
$meta
|
||||
->clear_optimized_sizes()
|
||||
->clear_backups()
|
||||
->clear_original_data()
|
||||
->save();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$meta->delete();
|
||||
}
|
||||
|
||||
private static function get_path_from_backup_path( string $backup_path ): string {
|
||||
$extension = File_Utils::get_extension( $backup_path );
|
||||
return str_replace( ".backup.$extension", ".$extension", $backup_path );
|
||||
}
|
||||
|
||||
private static function update_image_post( Image $image, string $image_path, string $mime_type ): void {
|
||||
$post_update_query = [
|
||||
'post_modified' => current_time( 'mysql' ),
|
||||
'post_modified_gmt' => current_time( 'mysql', true ),
|
||||
'post_mime_type' => $mime_type,
|
||||
'guid' => File_Utils::get_url_from_path( $image_path ),
|
||||
];
|
||||
|
||||
$image->update_attachment( $post_update_query );
|
||||
|
||||
update_attached_file( $image->get_id(), $image_path );
|
||||
}
|
||||
|
||||
/**
|
||||
* If we change an image extension, we should walk through the wp_posts table and update all the
|
||||
* hardcoded image links to prevent 404s.
|
||||
*
|
||||
* @param string $old_path Previous image path
|
||||
* @param string $new_path Current image path
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private static function update_posts( string $old_path, string $new_path ) {
|
||||
Image_DB_Update::update_posts_table_urls(
|
||||
File_Utils::get_url_from_path( $old_path ),
|
||||
File_Utils::get_url_from_path( $new_path )
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Classes\Image;
|
||||
|
||||
use ImageOptimization\Classes\Basic_Enum;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
final class Image_Status extends Basic_Enum {
|
||||
public const NOT_OPTIMIZED = 'not-optimized';
|
||||
public const OPTIMIZED = 'optimized';
|
||||
public const OPTIMIZATION_IN_PROGRESS = 'optimization-in-progress';
|
||||
public const OPTIMIZATION_FAILED = 'optimization-failed';
|
||||
public const RESTORING_IN_PROGRESS = 'restoring-in-progress';
|
||||
public const RESTORING_FAILED = 'restoring-failed';
|
||||
public const REOPTIMIZING_IN_PROGRESS = 'reoptimizing-in-progress';
|
||||
public const REOPTIMIZING_FAILED = 'reoptimizing-failed';
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Classes\Image;
|
||||
|
||||
use ImageOptimization\Classes\Image\Exceptions\Invalid_Image_Exception;
|
||||
use WP_Post;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
class Image {
|
||||
public const SIZE_FULL = 'full';
|
||||
private const SUPPORTED_MIME_TYPES = [ 'image/jpeg', 'image/png', 'image/webp', 'image/gif', 'image/avif' ];
|
||||
|
||||
// Used for error messages
|
||||
private const SUPPORTED_FORMATS = [ 'jpeg', 'png', 'webp', 'gif', 'avif' ];
|
||||
private const MIME_TYPES_CANNOT_BE_OPTIMIZED = [ 'image/avif' ];
|
||||
private const FORMATS_CANNOT_BE_OPTIMIZED = [ 'avif' ];
|
||||
|
||||
protected int $image_id;
|
||||
protected $attachment_object;
|
||||
|
||||
/**
|
||||
* Returns attachment post id.
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public function get_id(): int {
|
||||
return $this->image_id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns file URL for a specific image size.
|
||||
*
|
||||
* @param string $image_size Image size (e. g. 'full', 'thumbnail', etc)
|
||||
* @return string|null
|
||||
*/
|
||||
public function get_url( string $image_size ): ?string {
|
||||
$image_data = wp_get_attachment_image_src( $this->image_id, $image_size );
|
||||
|
||||
if ( empty( $image_data ) ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $image_data[0];
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns absolute file path for a specific image size.
|
||||
*
|
||||
* @param string $image_size Image size (e. g. 'full', 'thumbnail', etc)
|
||||
* @return string|null
|
||||
*/
|
||||
public function get_file_path( string $image_size ): ?string {
|
||||
if ( 'full' === $image_size ) {
|
||||
$path = get_attached_file( $this->image_id );
|
||||
return $path ?? null;
|
||||
}
|
||||
|
||||
$path_data = image_get_intermediate_size( $this->image_id, $image_size );
|
||||
|
||||
if ( empty( $path_data ) ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return sprintf(
|
||||
'%s/%s',
|
||||
wp_get_upload_dir()['basedir'],
|
||||
$path_data['path']
|
||||
);
|
||||
}
|
||||
|
||||
public function file_exists( string $image_size ): bool {
|
||||
$path = $this->get_file_path( $image_size );
|
||||
|
||||
if ( ! $path ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return file_exists( $path );
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if an image marked as optimized.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function is_optimized(): bool {
|
||||
$meta = new Image_Meta( $this->image_id );
|
||||
|
||||
return $meta->get_status() === Image_Status::OPTIMIZED;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if an image can be restored from the backups.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function can_be_restored(): bool {
|
||||
$meta = new Image_Meta( $this->image_id );
|
||||
|
||||
return (bool) count( $meta->get_image_backup_paths() );
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns image's mime type.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function get_mime_type(): string {
|
||||
return $this->attachment_object->post_mime_type;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an original attachment WP_Post object.
|
||||
*
|
||||
* @return WP_Post
|
||||
*/
|
||||
public function get_attachment_object(): WP_Post {
|
||||
return $this->attachment_object;
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates WP_Post fields of the attachment.
|
||||
*
|
||||
* @return bool True if the post was updated successfully, false otherwise.
|
||||
*/
|
||||
public function update_attachment( array $update_query ): bool {
|
||||
global $wpdb;
|
||||
|
||||
// Must use $wpdb here as `wp_update_post()` doesn't allow to rewrite guid.
|
||||
$result = $wpdb->update(
|
||||
$wpdb->posts,
|
||||
$update_query,
|
||||
[ 'ID' => $this->image_id ]
|
||||
);
|
||||
|
||||
if ( 0 !== $result ) {
|
||||
$this->attachment_object = get_post( $this->image_id );
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the list of mime types supported by the plugin.
|
||||
*
|
||||
* @return string[]
|
||||
*/
|
||||
public static function get_supported_mime_types(): array {
|
||||
return self::SUPPORTED_MIME_TYPES;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the list of formats types supported by the plugin.
|
||||
*
|
||||
* @return string[]
|
||||
*/
|
||||
public static function get_supported_formats(): array {
|
||||
return self::SUPPORTED_FORMATS;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the list of mime types that are supported by the plugin, but cannot be optimized
|
||||
*
|
||||
* @return string[]
|
||||
*/
|
||||
public static function get_mime_types_cannot_be_optimized(): array {
|
||||
return self::MIME_TYPES_CANNOT_BE_OPTIMIZED;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the list of formats that are supported by the plugin, but cannot be optimized
|
||||
*
|
||||
* @return string[]
|
||||
*/
|
||||
public static function get_formats_cannot_be_optimized(): array {
|
||||
return self::FORMATS_CANNOT_BE_OPTIMIZED;
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws Invalid_Image_Exception
|
||||
*/
|
||||
public function __construct( int $image_id ) {
|
||||
$this->image_id = $image_id;
|
||||
$this->attachment_object = get_post( $image_id );
|
||||
|
||||
if ( ! $this->attachment_object ) {
|
||||
throw new Invalid_Image_Exception( "There is no entity with id '$image_id'" );
|
||||
}
|
||||
|
||||
if ( ! wp_attachment_is_image( $this->attachment_object ) ) {
|
||||
throw new Invalid_Image_Exception( "Post '$image_id' is not an image" );
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,290 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Classes\Image;
|
||||
|
||||
use ImageOptimization\Classes\File_Utils;
|
||||
use ImageOptimization\Classes\Image\Exceptions\Invalid_Image_Exception;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
/**
|
||||
* Class WP_Image_Meta
|
||||
*
|
||||
* This class is used to manage the metadata of an image in WordPress.
|
||||
*/
|
||||
class WP_Image_Meta {
|
||||
private int $image_id;
|
||||
private array $image_meta;
|
||||
private Image $image;
|
||||
|
||||
/**
|
||||
* Get the size data of the image.
|
||||
*
|
||||
* @param string $image_size The size of the image.
|
||||
* @return array|null The size data of the image or null if the size does not exist.
|
||||
*/
|
||||
public function get_size_data( string $image_size ): ?array {
|
||||
if ( Image::SIZE_FULL === $image_size ) {
|
||||
$output = [];
|
||||
|
||||
$output['file'] = $this->image_meta['file'];
|
||||
$output['filesize'] = $this->image_meta['filesize'];
|
||||
$output['width'] = $this->image_meta['width'];
|
||||
$output['height'] = $this->image_meta['height'];
|
||||
$output['mime-type'] = $this->image->get_attachment_object()->post_mime_type;
|
||||
|
||||
return $output;
|
||||
}
|
||||
|
||||
if ( ! isset( $this->image_meta['sizes'][ $image_size ] ) ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $this->image_meta['sizes'][ $image_size ];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the keys of the image sizes.
|
||||
*
|
||||
* @return array The keys of the image sizes.
|
||||
*/
|
||||
public function get_size_keys(): array {
|
||||
return [ Image::SIZE_FULL, ...array_keys( $this->image_meta['sizes'] ) ];
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns keys of sizes that have the same dimensions as the one provided.
|
||||
*
|
||||
* @param string $image_size The size of the image.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function get_size_duplicates( string $image_size ): array {
|
||||
$duplicates = [];
|
||||
|
||||
$width = $this->get_width( $image_size );
|
||||
$height = $this->get_height( $image_size );
|
||||
|
||||
foreach ( $this->image_meta['sizes'] as $size_key => $size_data ) {
|
||||
if ( $size_data['width'] === $width && $size_data['height'] === $height && $image_size !== $size_key ) {
|
||||
$duplicates[] = $size_key;
|
||||
}
|
||||
}
|
||||
|
||||
return array_unique( $duplicates );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the file size of the image.
|
||||
*
|
||||
* @param string $image_size The size of the image.
|
||||
* @return int|null The file size of the image or null if the size does not exist.
|
||||
*/
|
||||
public function get_file_size( string $image_size ): ?int {
|
||||
if ( Image::SIZE_FULL === $image_size ) {
|
||||
return $this->image_meta['filesize'] ?? null;
|
||||
}
|
||||
|
||||
if ( ! isset( $this->image_meta['sizes'][ $image_size ]['filesize'] ) ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $this->image_meta['sizes'][ $image_size ]['filesize'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the file size of the image.
|
||||
*
|
||||
* @param string $image_size The size of the image.
|
||||
* @param int $file_size The file size to set.
|
||||
* @return WP_Image_Meta The current instance.
|
||||
*/
|
||||
public function set_file_size( string $image_size, int $file_size ): WP_Image_Meta {
|
||||
if ( Image::SIZE_FULL === $image_size ) {
|
||||
$this->image_meta['filesize'] = $file_size;
|
||||
return $this;
|
||||
}
|
||||
|
||||
$this->maybe_add_new_size( $image_size );
|
||||
|
||||
$this->image_meta['sizes'][ $image_size ]['filesize'] = $file_size;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the file path of the image.
|
||||
*
|
||||
* @param string $image_size The size of the image.
|
||||
* @param string $full_path The full path to set.
|
||||
* @return WP_Image_Meta The current instance.
|
||||
*/
|
||||
public function set_file_path( string $image_size, string $full_path ): WP_Image_Meta {
|
||||
if ( Image::SIZE_FULL === $image_size ) {
|
||||
$this->image_meta['file'] = File_Utils::get_relative_upload_path( $full_path );
|
||||
return $this;
|
||||
}
|
||||
|
||||
$this->maybe_add_new_size( $image_size );
|
||||
|
||||
$this->image_meta['sizes'][ $image_size ]['file'] = File_Utils::get_basename( $full_path );
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the width of the image.
|
||||
*
|
||||
* @param string $image_size The size of the image.
|
||||
*
|
||||
* @return int|null
|
||||
*/
|
||||
public function get_width( string $image_size ): ?int {
|
||||
if ( Image::SIZE_FULL === $image_size ) {
|
||||
return $this->image_meta['width'];
|
||||
}
|
||||
|
||||
if ( ! isset( $this->image_meta['sizes'][ $image_size ]['width'] ) ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $this->image_meta['sizes'][ $image_size ]['width'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the width of the image.
|
||||
*
|
||||
* @param string $image_size The size of the image.
|
||||
* @param int $width The width to set.
|
||||
* @return WP_Image_Meta The current instance.
|
||||
*/
|
||||
public function set_width( string $image_size, int $width ): WP_Image_Meta {
|
||||
if ( Image::SIZE_FULL === $image_size ) {
|
||||
$this->image_meta['width'] = $width;
|
||||
return $this;
|
||||
}
|
||||
|
||||
$this->maybe_add_new_size( $image_size );
|
||||
|
||||
$this->image_meta['sizes'][ $image_size ]['width'] = $width;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the height of the image.
|
||||
*
|
||||
* @param string $image_size The size of the image.
|
||||
*
|
||||
* @return int|null
|
||||
*/
|
||||
public function get_height( string $image_size ): ?int {
|
||||
if ( Image::SIZE_FULL === $image_size ) {
|
||||
return $this->image_meta['height'];
|
||||
}
|
||||
|
||||
if ( ! isset( $this->image_meta['sizes'][ $image_size ]['height'] ) ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $this->image_meta['sizes'][ $image_size ]['height'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the height of the image.
|
||||
*
|
||||
* @param string $image_size The size of the image.
|
||||
* @param int $height The height to set.
|
||||
* @return WP_Image_Meta The current instance.
|
||||
*/
|
||||
public function set_height( string $image_size, int $height ): WP_Image_Meta {
|
||||
if ( Image::SIZE_FULL === $image_size ) {
|
||||
$this->image_meta['height'] = $height;
|
||||
return $this;
|
||||
}
|
||||
|
||||
$this->maybe_add_new_size( $image_size );
|
||||
|
||||
$this->image_meta['sizes'][ $image_size ]['height'] = $height;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the mime type of the image.
|
||||
*
|
||||
* @param string $image_size The size of the image.
|
||||
* @param string $mime_type The mime type to set.
|
||||
* @return WP_Image_Meta The current instance.
|
||||
*/
|
||||
public function set_mime_type( string $image_size, string $mime_type ): WP_Image_Meta {
|
||||
if ( Image::SIZE_FULL === $image_size ) {
|
||||
// WP doesn't store it in meta for the original image
|
||||
return $this;
|
||||
}
|
||||
|
||||
$this->maybe_add_new_size( $image_size );
|
||||
|
||||
$this->image_meta['sizes'][ $image_size ]['mime-type'] = $mime_type;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a new size to the image if it does not exist.
|
||||
*
|
||||
* @param string $image_size The size of the image.
|
||||
*/
|
||||
private function maybe_add_new_size( $image_size ): void {
|
||||
if ( ! isset( $this->image_meta['sizes'][ $image_size ] ) ) {
|
||||
$this->image_meta['sizes'][ $image_size ] = [];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Save the image metadata.
|
||||
*
|
||||
* @return WP_Image_Meta The current instance.
|
||||
*/
|
||||
public function save(): WP_Image_Meta {
|
||||
wp_update_attachment_metadata( $this->image_id, $this->image_meta );
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Query the image metadata.
|
||||
*
|
||||
* @throws Invalid_Image_Exception
|
||||
*/
|
||||
private function query_meta(): void {
|
||||
$meta = wp_get_attachment_metadata( $this->image_id );
|
||||
|
||||
if ( ! $meta ) {
|
||||
throw new Invalid_Image_Exception( 'Invalid WP image meta' );
|
||||
}
|
||||
|
||||
// Handle unsupported formats that WP doesn't create thumbnails for
|
||||
if ( ! isset( $meta['sizes'] ) ) {
|
||||
$meta['sizes'] = [];
|
||||
}
|
||||
|
||||
$this->image_meta = $meta;
|
||||
}
|
||||
|
||||
/**
|
||||
* WP_Image_Meta constructor.
|
||||
*
|
||||
* @param int $image_id The ID of the image.
|
||||
* @param Image|null $image The image object.
|
||||
* @throws Invalid_Image_Exception If the image metadata is invalid.
|
||||
*/
|
||||
public function __construct( int $image_id, ?Image $image = null ) {
|
||||
$this->image_id = $image_id;
|
||||
$this->image = $image ?? new Image( $image_id );
|
||||
|
||||
$this->query_meta();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Classes;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
class Locale {
|
||||
private $original_locale;
|
||||
|
||||
public function set_utf_locale( int $category = LC_CTYPE ) {
|
||||
setlocale( $category, 'en_US.UTF-8' );
|
||||
}
|
||||
|
||||
public function get_locale( int $category = LC_CTYPE ) {
|
||||
return setlocale( $category, 0 );
|
||||
}
|
||||
|
||||
public function reset_to_original( int $category = LC_CTYPE ) {
|
||||
return setlocale( $category, $this->original_locale );
|
||||
}
|
||||
|
||||
public function __construct() {
|
||||
$this->original_locale = $this->get_locale();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Classes;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
class Logger {
|
||||
public const LEVEL_ERROR = 'error';
|
||||
public const LEVEL_WARN = 'warn';
|
||||
public const LEVEL_INFO = 'info';
|
||||
public const LEVEL_DEBUG = 'debug';
|
||||
|
||||
public const LOG_LEVEL_PRIORITY = [
|
||||
'debug' => 1,
|
||||
'info' => 2,
|
||||
'warn' => 3,
|
||||
'error' => 4,
|
||||
];
|
||||
|
||||
public static function log( string $log_level, $message ): void {
|
||||
if (
|
||||
defined( 'IMAGE_OPTIMIZATION_MINIMUM_LOG_LEVEL' ) &&
|
||||
self::LOG_LEVEL_PRIORITY[ $log_level ] < (int) IMAGE_OPTIMIZATION_MINIMUM_LOG_LEVEL
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
$backtrace = debug_backtrace(); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_debug_backtrace
|
||||
|
||||
$class = $backtrace[1]['class'] ?? null;
|
||||
$type = $backtrace[1]['type'] ?? null;
|
||||
$function = $backtrace[1]['function'];
|
||||
|
||||
if ( $class ) {
|
||||
$message = '[Image Optimizer]: ' . $log_level . ' in ' . "$class$type$function()" . ': ' . $message;
|
||||
} else {
|
||||
$message = '[Image Optimizer]: ' . $log_level . ' in ' . "$function()" . ': ' . $message;
|
||||
}
|
||||
|
||||
error_log( $message ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
|
||||
}
|
||||
|
||||
public static function debug( $message ): void {
|
||||
self::log( self::LEVEL_DEBUG, $message );
|
||||
}
|
||||
|
||||
public static function info( $message ): void {
|
||||
self::log( self::LEVEL_INFO, $message );
|
||||
}
|
||||
|
||||
public static function warn( $message ): void {
|
||||
self::log( self::LEVEL_WARN, $message );
|
||||
}
|
||||
|
||||
public static function error( $message ): void {
|
||||
self::log( self::LEVEL_ERROR, $message );
|
||||
}
|
||||
}
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Classes\Migration\Handlers;
|
||||
|
||||
use ImageOptimization\Classes\Image\{
|
||||
Image,
|
||||
Image_Dimensions,
|
||||
Image_Query_Builder,
|
||||
WP_Image_Meta,
|
||||
};
|
||||
|
||||
use ImageOptimization\Classes\Migration\Migration;
|
||||
use Throwable;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
class Fix_Avif_With_Zero_Dimensions extends Migration {
|
||||
public static function get_name(): string {
|
||||
return 'fix_avif_with_zero_dimensions';
|
||||
}
|
||||
|
||||
public static function run(): bool {
|
||||
$query = ( new Image_Query_Builder() )
|
||||
->set_mime_types( [ 'image/avif', 'application/octet-stream' ] )
|
||||
->return_images_with_non_empty_meta()
|
||||
->execute();
|
||||
|
||||
if ( ! $query->post_count ) {
|
||||
return true;
|
||||
}
|
||||
|
||||
foreach ( $query->posts as $attachment_id ) {
|
||||
try {
|
||||
$wp_meta = new WP_Image_Meta( $attachment_id );
|
||||
$image = new Image( $attachment_id );
|
||||
|
||||
foreach ( $wp_meta->get_size_keys() as $size_key ) {
|
||||
if ( 0 === $wp_meta->get_width( $size_key ) || 0 === $wp_meta->get_height( $size_key ) ) {
|
||||
$dimensions = Image_Dimensions::get_by_path( $image->get_file_path( $size_key ) );
|
||||
|
||||
$wp_meta
|
||||
->set_width( $size_key, $dimensions->width )
|
||||
->set_height( $size_key, $dimensions->height )
|
||||
->save();
|
||||
}
|
||||
}
|
||||
} catch ( Throwable $t ) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Classes\Migration\Handlers;
|
||||
|
||||
use ImageOptimization\Classes\Image\{
|
||||
Image,
|
||||
Image_Meta,
|
||||
Image_Query_Builder,
|
||||
WP_Image_Meta
|
||||
};
|
||||
|
||||
use ImageOptimization\Classes\Migration\Migration;
|
||||
use ImageOptimization\Modules\Stats\Classes\Optimization_Stats;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
class Fix_Mime_Type extends Migration {
|
||||
public static function get_name(): string {
|
||||
return 'fix_mime_type';
|
||||
}
|
||||
|
||||
public static function run(): bool {
|
||||
$query = ( new Image_Query_Builder() )
|
||||
->return_optimized_images()
|
||||
->execute();
|
||||
|
||||
if ( ! $query->post_count ) {
|
||||
return true;
|
||||
}
|
||||
|
||||
foreach ( $query->posts as $attachment_id ) {
|
||||
$stats = Optimization_Stats::get_image_stats( $attachment_id );
|
||||
$fully_optimized = ( $stats['initial_image_size'] - $stats['current_image_size'] ) <= 0;
|
||||
|
||||
if ( $fully_optimized ) {
|
||||
$io_meta = new Image_Meta( $attachment_id );
|
||||
$wp_meta = new WP_Image_Meta( $attachment_id );
|
||||
$size_data = $wp_meta->get_size_data( Image::SIZE_FULL );
|
||||
|
||||
if (
|
||||
! str_contains( $size_data['file'], '.webp' ) && 'image/webp' === $size_data['mime-type'] ||
|
||||
! str_contains( $size_data['file'], '.avif' ) && 'image/avif' === $size_data['mime-type'] ||
|
||||
! str_contains( $size_data['file'], '.avif' ) && 'application/octet-stream' === $size_data['mime-type']
|
||||
) {
|
||||
$original_mime_type = $io_meta->get_original_mime_type( Image::SIZE_FULL );
|
||||
|
||||
foreach ( $wp_meta->get_size_keys() as $size ) {
|
||||
$wp_meta
|
||||
->set_mime_type( $size, $original_mime_type )
|
||||
->save();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Classes\Migration\Handlers;
|
||||
|
||||
use ImageOptimization\Classes\Image\{
|
||||
Image_Meta,
|
||||
Image_Query_Builder,
|
||||
};
|
||||
|
||||
use ImageOptimization\Classes\Migration\Migration;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
class Fix_Optimized_Size_Keys extends Migration {
|
||||
public static function get_name(): string {
|
||||
return 'fix_optimized_size_keys';
|
||||
}
|
||||
|
||||
public static function run(): bool {
|
||||
$query = ( new Image_Query_Builder() )
|
||||
->return_optimized_images()
|
||||
->execute();
|
||||
|
||||
if ( ! $query->post_count ) {
|
||||
return true;
|
||||
}
|
||||
|
||||
foreach ( $query->posts as $attachment_id ) {
|
||||
$meta = new Image_Meta( $attachment_id );
|
||||
$size_keys = array_unique( $meta->get_optimized_sizes() );
|
||||
|
||||
$meta
|
||||
->set_optimized_size( $size_keys )
|
||||
->save();
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Classes\Migration;
|
||||
|
||||
use ImageOptimization\Classes\Async_Operation\{
|
||||
Async_Operation,
|
||||
Async_Operation_Hook,
|
||||
Async_Operation_Queue,
|
||||
Exceptions\Async_Operation_Exception,
|
||||
};
|
||||
|
||||
use ImageOptimization\Classes\Logger;
|
||||
use ImageOptimization\Classes\Migration\Handlers\{
|
||||
Fix_Avif_With_Zero_Dimensions,
|
||||
Fix_Mime_Type,
|
||||
Fix_Optimized_Size_Keys,
|
||||
};
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
class Migration_Manager {
|
||||
public static function get_migrations(): array {
|
||||
return [
|
||||
Fix_Optimized_Size_Keys::class,
|
||||
Fix_Mime_Type::class,
|
||||
Fix_Avif_With_Zero_Dimensions::class,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $migration_name
|
||||
*
|
||||
* @return \class-string|null
|
||||
*/
|
||||
public static function get_migration( $migration_name ): ?string {
|
||||
foreach ( self::get_migrations() as $migration ) {
|
||||
if ( $migration::get_name() === $migration_name ) {
|
||||
return $migration;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public static function init() {
|
||||
$migrations_passed = ( new Migration_Meta() )->get_migrations_passed();
|
||||
|
||||
foreach ( self::get_migrations() as $migration ) {
|
||||
if ( in_array( $migration::get_name(), $migrations_passed, true ) ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
Async_Operation::create(
|
||||
Async_Operation_Hook::DB_MIGRATION,
|
||||
[ 'name' => $migration::get_name() ],
|
||||
Async_Operation_Queue::MIGRATION,
|
||||
0,
|
||||
true
|
||||
);
|
||||
} catch ( Async_Operation_Exception $aoe ) {
|
||||
$name = $migration::get_name();
|
||||
|
||||
Logger::log(
|
||||
Logger::LEVEL_ERROR,
|
||||
"Error while running migration `$name`: " . $aoe->getMessage()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Classes\Migration;
|
||||
|
||||
use DateTime;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
class Migration_Meta {
|
||||
public const IMAGE_OPTIMIZER_MIGRATION_KEY = 'image_optimizer_migrations';
|
||||
private const INITIAL_META_VALUE = [
|
||||
'last_run' => null,
|
||||
'last_wp_version_run' => null,
|
||||
'migrations_passed' => [],
|
||||
];
|
||||
private array $migration_meta;
|
||||
|
||||
public function get_last_run(): ?string {
|
||||
return $this->migration_meta['last_run'];
|
||||
}
|
||||
|
||||
public function set_last_run( DateTime $date ): Migration_Meta {
|
||||
$this->migration_meta['last_run'] = $date;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function get_last_wp_version(): string {
|
||||
return $this->migration_meta['last_wp_version_run'];
|
||||
}
|
||||
|
||||
public function set_last_wp_version( ?string $version ): Migration_Meta {
|
||||
if ( ! $version ) {
|
||||
$this->migration_meta['last_wp_version_run'] = get_bloginfo( 'version' );
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
$this->migration_meta['last_wp_version_run'] = $version;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function get_migrations_passed(): array {
|
||||
return $this->migration_meta['migrations_passed'];
|
||||
}
|
||||
|
||||
public function add_migration_passed( string $migration ): Migration_Meta {
|
||||
$this->migration_meta['migrations_passed'][] = $migration;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function delete(): bool {
|
||||
return delete_option( self::IMAGE_OPTIMIZER_MIGRATION_KEY );
|
||||
}
|
||||
|
||||
public function save(): Migration_Meta {
|
||||
update_option( self::IMAGE_OPTIMIZER_MIGRATION_KEY, $this->migration_meta, false );
|
||||
|
||||
$this->query_meta();
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
private function query_meta(): void {
|
||||
$meta = get_option( self::IMAGE_OPTIMIZER_MIGRATION_KEY, [] );
|
||||
$this->migration_meta = $meta ? array_replace_recursive( self::INITIAL_META_VALUE, $meta ) : self::INITIAL_META_VALUE;
|
||||
}
|
||||
|
||||
public function __construct() {
|
||||
$this->query_meta();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Classes\Migration;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
abstract class Migration {
|
||||
abstract public static function run(): bool;
|
||||
abstract public static function get_name(): string;
|
||||
}
|
||||
@@ -0,0 +1,335 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Classes;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
/**
|
||||
* Module Base.
|
||||
*
|
||||
* An abstract class providing the properties and methods needed to
|
||||
* manage and handle modules in inheriting classes.
|
||||
*
|
||||
* @abstract
|
||||
*/
|
||||
abstract class Module_Base {
|
||||
|
||||
/**
|
||||
* Module class reflection.
|
||||
*
|
||||
* Holds the information about a class.
|
||||
* @access private
|
||||
*
|
||||
* @var \ReflectionClass
|
||||
*/
|
||||
private $reflection = null;
|
||||
|
||||
/**
|
||||
* Module routes.
|
||||
*
|
||||
* Holds the module registered routes.
|
||||
* @access public
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public $routes = [];
|
||||
|
||||
/**
|
||||
* Module components.
|
||||
*
|
||||
* Holds the module components.
|
||||
* @access private
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
private $components = [];
|
||||
|
||||
/**
|
||||
* Module instance.
|
||||
*
|
||||
* Holds the module instance.
|
||||
* @access protected
|
||||
*
|
||||
* @var Module_Base[]
|
||||
*/
|
||||
protected static $_instances = [];
|
||||
|
||||
/**
|
||||
* Get module name.
|
||||
*
|
||||
* Retrieve the module name.
|
||||
* @access public
|
||||
* @abstract
|
||||
*
|
||||
* @return string Module name.
|
||||
*/
|
||||
abstract public function get_name();
|
||||
|
||||
/**
|
||||
* Instance.
|
||||
*
|
||||
* Ensures only one instance of the module class is loaded or can be loaded.
|
||||
* @access public
|
||||
* @static
|
||||
*
|
||||
* @return Module_Base An instance of the class.
|
||||
*/
|
||||
public static function instance() {
|
||||
$class_name = static::class_name();
|
||||
|
||||
if ( empty( static::$_instances[ $class_name ] ) ) {
|
||||
static::$_instances[ $class_name ] = new static(); // @codeCoverageIgnore
|
||||
}
|
||||
|
||||
return static::$_instances[ $class_name ];
|
||||
}
|
||||
|
||||
/**
|
||||
* is_active
|
||||
* @access public
|
||||
* @static
|
||||
* @return bool
|
||||
*/
|
||||
public static function is_active() {
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Class name.
|
||||
*
|
||||
* Retrieve the name of the class.
|
||||
* @access public
|
||||
* @static
|
||||
*/
|
||||
public static function class_name() {
|
||||
return get_called_class();
|
||||
}
|
||||
|
||||
/**
|
||||
* Clone.
|
||||
*
|
||||
* Disable class cloning and throw an 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.
|
||||
*
|
||||
* @access public
|
||||
*/
|
||||
public function __clone() {
|
||||
// Cloning instances of the class is forbidden
|
||||
_doing_it_wrong( __FUNCTION__, esc_html__( 'Something went wrong.', 'image-optimization' ), '1.0.0' ); // @codeCoverageIgnore
|
||||
}
|
||||
|
||||
/**
|
||||
* Wakeup.
|
||||
*
|
||||
* Disable unserializing of the class.
|
||||
* @access public
|
||||
*/
|
||||
public function __wakeup() {
|
||||
// Unserializing instances of the class is forbidden
|
||||
_doing_it_wrong( __FUNCTION__, esc_html__( 'Something went wrong.', 'image-optimization' ), '1.0.0' ); // @codeCoverageIgnore
|
||||
}
|
||||
|
||||
/**
|
||||
* @access public
|
||||
*/
|
||||
public function get_reflection() {
|
||||
if ( null === $this->reflection ) {
|
||||
try {
|
||||
$this->reflection = new \ReflectionClass( $this );
|
||||
} catch ( \ReflectionException $e ) {
|
||||
if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
|
||||
error_log( $e->getMessage() );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $this->reflection;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add module component.
|
||||
*
|
||||
* Add new component to the current module.
|
||||
* @access public
|
||||
*
|
||||
* @param string $id Component ID.
|
||||
* @param mixed $instance An instance of the component.
|
||||
*/
|
||||
public function add_component( string $id, $instance ) {
|
||||
$this->components[ $id ] = $instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add module route.
|
||||
*
|
||||
* Add new route to the current module.
|
||||
* @access public
|
||||
*
|
||||
* @param string $id Route ID.
|
||||
* @param mixed $instance An instance of the route.
|
||||
*/
|
||||
public function add_route( string $id, $instance ) {
|
||||
$this->routes[ $id ] = $instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* @access public
|
||||
* @return string[]
|
||||
*/
|
||||
public function get_components(): array {
|
||||
return $this->components;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get module component.
|
||||
*
|
||||
* Retrieve the module component.
|
||||
* @access public
|
||||
*
|
||||
* @param string $id Component ID.
|
||||
*
|
||||
* @return mixed An instance of the component, or `false` if the component
|
||||
* doesn't exist.
|
||||
* @codeCoverageIgnore
|
||||
*/
|
||||
public function get_component( string $id ) {
|
||||
if ( isset( $this->components[ $id ] ) ) {
|
||||
return $this->components[ $id ];
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the namespace of the class
|
||||
*
|
||||
* @access public
|
||||
* @static
|
||||
*/
|
||||
public static function namespace_name() {
|
||||
$class_name = static::class_name();
|
||||
return substr( $class_name, 0, strrpos( $class_name, '\\' ) );
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Get assets url.
|
||||
*
|
||||
* @param string $file_name
|
||||
* @param string $file_extension
|
||||
* @param string $relative_url Optional. Default is null.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
final protected function get_assets_url( $file_name, $file_extension, $relative_url = null ): string {
|
||||
static $is_test_mode = null;
|
||||
|
||||
if ( null === $is_test_mode ) {
|
||||
$is_test_mode = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG;
|
||||
}
|
||||
|
||||
if ( ! $relative_url ) {
|
||||
$relative_url = $this->get_assets_relative_url();
|
||||
}
|
||||
|
||||
$url = $this->get_assets_base_url() . $relative_url . $file_name;
|
||||
|
||||
return $url . '.' . $file_extension;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get js assets url
|
||||
*
|
||||
* @param string $file_name
|
||||
* @param string $relative_url Optional. Default is null.
|
||||
* @param string $add_min_suffix Optional. Default is 'default'.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
final protected function get_js_assets_url( $file_name, $relative_url = null, $add_min_suffix = 'default' ): string {
|
||||
return $this->get_assets_url( $file_name, 'js', $relative_url, $add_min_suffix );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get css assets url
|
||||
*
|
||||
* @param string $file_name
|
||||
* @param string $relative_url Optional. Default is null.
|
||||
* @param string $add_min_suffix Optional. Default is 'default'.
|
||||
* @param bool $add_direction_suffix Optional. Default is `false`
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
final protected function get_css_assets_url( $file_name, $relative_url = null, $add_min_suffix = 'default', $add_direction_suffix = false ): string {
|
||||
static $direction_suffix = null;
|
||||
|
||||
if ( ! $direction_suffix ) {
|
||||
$direction_suffix = is_rtl() ? '-rtl' : '';
|
||||
}
|
||||
|
||||
if ( $add_direction_suffix ) {
|
||||
$file_name .= $direction_suffix;
|
||||
}
|
||||
|
||||
return $this->get_assets_url( $file_name, 'css', $relative_url, $add_min_suffix );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get assets base url
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function get_assets_base_url(): string {
|
||||
return IMAGE_OPTIMIZATION_URL;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get assets relative url
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function get_assets_relative_url(): string {
|
||||
return 'assets/build/';
|
||||
}
|
||||
|
||||
public static function routes_list() : array {
|
||||
return [];
|
||||
}
|
||||
|
||||
public static function component_list() : array {
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds an array of components.
|
||||
* Assumes namespace structure contains `\Components\`
|
||||
*/
|
||||
public function register_components() {
|
||||
$namespace = static::namespace_name();
|
||||
$components_ids = static::component_list();
|
||||
|
||||
foreach ( $components_ids as $component_id ) {
|
||||
$class_name = $namespace . '\\Components\\' . $component_id;
|
||||
$this->add_component( $component_id, new $class_name() );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds an array of routes.
|
||||
* Assumes namespace structure contains `\Rest\`
|
||||
*/
|
||||
public function register_routes() {
|
||||
$namespace = static::namespace_name();
|
||||
$routes_ids = static::routes_list();
|
||||
|
||||
foreach ( $routes_ids as $route_id ) {
|
||||
$class_name = $namespace . '\\Rest\\' . $route_id;
|
||||
$this->add_route( $route_id, new $class_name() );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,427 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Classes\Rest;
|
||||
|
||||
use ReflectionClass;
|
||||
use WP_Error;
|
||||
use WP_REST_Request;
|
||||
use WP_REST_Response;
|
||||
use WP_User;
|
||||
|
||||
abstract class Route {
|
||||
|
||||
/**
|
||||
* Should the endpoint be validated for user authentication?
|
||||
* If set to TRUE, the default permission callback will make sure the user is logged in and has a valid user id
|
||||
* @var bool
|
||||
*/
|
||||
protected $auth = true;
|
||||
|
||||
/**
|
||||
* holds current authenticated user id
|
||||
* @var int
|
||||
*/
|
||||
protected $current_user_id;
|
||||
|
||||
|
||||
/**
|
||||
* Should the endpoint override an existing one?
|
||||
* @var bool
|
||||
*/
|
||||
protected bool $override = false;
|
||||
|
||||
/**
|
||||
* Rest Endpoint namespace
|
||||
* @var string
|
||||
*/
|
||||
protected string $namespace = 'image-optimizer/v1';
|
||||
|
||||
/**
|
||||
* @var array The valid HTTP methods. The list represents the general REST methods. Do not modify.
|
||||
*/
|
||||
private array $valid_http_methods = [
|
||||
'GET',
|
||||
'PATCH',
|
||||
'POST',
|
||||
'PUT',
|
||||
'DELETE',
|
||||
'HEAD',
|
||||
];
|
||||
|
||||
/**
|
||||
* Route_Base constructor.
|
||||
*/
|
||||
public function __construct() {
|
||||
add_action( 'rest_api_init', [ $this, 'rest_api_init' ] );
|
||||
}
|
||||
|
||||
/**
|
||||
* rest_api_init
|
||||
*
|
||||
* Registers REST endpoints.
|
||||
* Loops through the REST methods for this route, creates an endpoint configuration for
|
||||
* each of them and registers all the endpoints with the WordPress system.
|
||||
*/
|
||||
public function rest_api_init(): void {
|
||||
$methods = $this->get_methods();
|
||||
if ( empty( $methods ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$callbacks = false;
|
||||
foreach ( (array) $methods as $method ) {
|
||||
if ( ! in_array( $method, $this->valid_http_methods ) ) {
|
||||
continue;
|
||||
}
|
||||
if ( $method && ! $callbacks ) {
|
||||
$callbacks = [];
|
||||
}
|
||||
$callbacks[] = $this->build_endpoint_method_config( $method );
|
||||
}
|
||||
|
||||
$arguments = $this->get_arguments();
|
||||
|
||||
if ( ! $callbacks && empty( $arguments ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$arguments = array_merge( $arguments, (array) $callbacks );
|
||||
register_rest_route( $this->namespace, '/' . $this->get_endpoint() . '/', $arguments, $this->override );
|
||||
}
|
||||
|
||||
/**
|
||||
* get_methods
|
||||
* Rest Endpoint methods
|
||||
*
|
||||
* Returns an array of the supported REST methods for this route
|
||||
* @return array<string> REST methods being configured for this route.
|
||||
*/
|
||||
abstract public function get_methods(): array;
|
||||
|
||||
/**
|
||||
* get_callback
|
||||
*
|
||||
* Returns a reference to the callback function to handle the REST method specified by the /method/ parameter.
|
||||
* @param string $method The REST method name
|
||||
*
|
||||
* @return callable A reference to a member function with the same name as the REST method being passed as a parameter,
|
||||
* or a reference to the default function /callback/.
|
||||
*/
|
||||
public function get_callback_method( string $method ): callable {
|
||||
$method_name = strtolower( $method );
|
||||
$callback = $this->method_exists_in_current_class( $method_name ) ? $method_name : 'callback';
|
||||
return [ $this, $callback ];
|
||||
}
|
||||
|
||||
/**
|
||||
* get_permission_callback_method
|
||||
*
|
||||
* Returns a reference to the permission callback for the method if exists or the default one if it doesn't.
|
||||
* @param string $method The REST method name
|
||||
*
|
||||
* @return callable If a method called (rest-method)_permission_callback exists, returns a reference to it, otherwise
|
||||
* returns a reference to the default member method /permission_callback/.
|
||||
*/
|
||||
public function get_permission_callback_method( string $method ): callable {
|
||||
$method_name = strtolower( $method );
|
||||
$permission_callback_method = $method_name . '_permission_callback';
|
||||
$permission_callback = $this->method_exists_in_current_class( $permission_callback_method ) ? $permission_callback_method : 'permission_callback';
|
||||
return [ $this, $permission_callback ];
|
||||
}
|
||||
|
||||
/**
|
||||
* maybe_add_args_to_config
|
||||
*
|
||||
* Checks if the class has a method call (rest-method)_args.
|
||||
* If it does, the function calls it and adds its response to the config object passed to the function, under the /args/ key.
|
||||
* if the function (rest-method)_consumes exists, it will add the response to the config object under the /consumes/ key.
|
||||
* if the function (rest-method)_produces exists, it will add the response to the config object under the /produces/ key.
|
||||
* if the function (rest-method)_summary exists, it will add the response to the config object under the /summary/ key.
|
||||
* if the function (rest-method)_description exists, it will add the response to the config object under the /description/ key.
|
||||
* @param string $method The REST method name being configured
|
||||
* @param array $config The configuration object for the method
|
||||
*
|
||||
* @return array The configuration object for the method, possibly after being amended
|
||||
*/
|
||||
public function maybe_add_args_to_config( string $method, array $config ): array {
|
||||
$method_name = strtolower( $method );
|
||||
$method_args = $method_name . '_args';
|
||||
if ( $this->method_exists_in_current_class( $method_args ) ) {
|
||||
$config['args'] = $this->{$method_args}();
|
||||
}
|
||||
$config['consumes'] = [ 'application/json' ];
|
||||
if ( $this->method_exists_in_current_class( $method . '_consumes' ) ) {
|
||||
$config['consumes'] = $this->{$method . '_consumes'}();
|
||||
}
|
||||
$config['produces'] = [ 'application/json' ];
|
||||
if ( $this->method_exists_in_current_class( $method . '_produces' ) ) {
|
||||
$config['produces'] = $this->{$method . '_produces'}();
|
||||
}
|
||||
if ( $this->method_exists_in_current_class( $method . '_summary' ) ) {
|
||||
$config['summary'] = $this->{$method . '_summary'}();
|
||||
}
|
||||
if ( $this->method_exists_in_current_class( $method . '_description' ) ) {
|
||||
$config['description'] = $this->{$method . '_description'}();
|
||||
}
|
||||
return $config;
|
||||
}
|
||||
|
||||
/**
|
||||
* maybe_add_response_to_swagger
|
||||
*
|
||||
* If the function method /(rest-method)_response_callback/ exists, adds the filter
|
||||
* /swagger_api_response_(namespace with slashes replaced with underscores)_(endpoint with slashes replaced with underscores)/
|
||||
* with the aforementioned function method.
|
||||
* This filter is used with the WP API Swagger UI plugin to create documentation for the API.
|
||||
* The value being passed is an array: [
|
||||
'200' => ['description' => 'OK'],
|
||||
'404' => ['description' => 'Not Found'],
|
||||
'400' => ['description' => 'Bad Request']
|
||||
]
|
||||
* @param string $method REST method name
|
||||
*/
|
||||
public function maybe_add_response_to_swagger( string $method ): void {
|
||||
$method_name = strtolower( $method );
|
||||
$method_response_callback = $method_name . '_response_callback';
|
||||
if ( $this->method_exists_in_current_class( $method_response_callback ) ) {
|
||||
$response_filter = $method_name . '_' . str_replace(
|
||||
'/',
|
||||
'_',
|
||||
$this->namespace . '/' . $this->get_endpoint()
|
||||
);
|
||||
add_filter( 'swagger_api_responses_' . $response_filter, [ $this, $method_response_callback ] );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* build_endpoint_method_config
|
||||
*
|
||||
* Builds a configuration array for the endpoint based on the presence of the callback, permission, additional parameters,
|
||||
* and response to Swagger member functions.
|
||||
* @param string $method The REST method for the endpoint
|
||||
*
|
||||
* @return array The endpoint configuration for the method specified by the parameter
|
||||
*/
|
||||
private function build_endpoint_method_config( string $method ): array {
|
||||
$config = [
|
||||
'methods' => $method,
|
||||
'callback' => $this->get_callback_method( $method ),
|
||||
'permission_callback' => $this->get_permission_callback_method( $method ),
|
||||
];
|
||||
$this->maybe_add_response_to_swagger( $method );
|
||||
return $this->maybe_add_args_to_config( $method, $config );
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* method_exists_in_current_class
|
||||
*
|
||||
* Uses reflection to check if this class has the /method/ method.
|
||||
* @param string $method The name of the method being checked.
|
||||
*
|
||||
* @return bool TRUE if the class has the /method/ method, FALSE otherwise.
|
||||
*/
|
||||
private function method_exists_in_current_class( string $method ): bool {
|
||||
$class_name = get_class( $this );
|
||||
try {
|
||||
$reflection = new ReflectionClass( $class_name );
|
||||
} catch ( \ReflectionException $e ) {
|
||||
return false;
|
||||
}
|
||||
if ( ! $reflection->hasMethod( $method ) ) {
|
||||
return false;
|
||||
}
|
||||
$method_ref = $reflection->getMethod( $method );
|
||||
|
||||
return ( $method_ref && $class_name === $method_ref->class );
|
||||
}
|
||||
|
||||
/**
|
||||
* permission_callback
|
||||
* Permissions callback fallback for the endpoint
|
||||
* Gets the current user ID and sets the /current_user_id/ property.
|
||||
* If the /auth/ property is set to /true/ will make sure that the user is logged in (has an id greater than 0)
|
||||
*
|
||||
* @param WP_REST_Request $request unused
|
||||
*
|
||||
* @return bool TRUE, if permission granted, FALSE otherwise
|
||||
*/
|
||||
public function permission_callback( WP_REST_Request $request ): bool {
|
||||
// try to get current user
|
||||
$this->current_user_id = get_current_user_id();
|
||||
if ( $this->auth ) {
|
||||
return $this->current_user_id > 0;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* callback
|
||||
* Fallback callback function, returns a response consisting of the string /ok/.
|
||||
*
|
||||
* @param WP_REST_Request $request unused
|
||||
*
|
||||
* @return WP_REST_Response Default Response of the string 'ok'.
|
||||
*/
|
||||
public function callback( WP_REST_Request $request ): WP_REST_Response {
|
||||
return rest_ensure_response( [ 'OK' ] );
|
||||
}
|
||||
|
||||
/**
|
||||
* respond_wrong_method
|
||||
*
|
||||
* Creates a WordPress error object with the /rest_no_route/ code and the message and code supplied or the defaults.
|
||||
* @param null $message The error message for the wrong method.
|
||||
* Optional.
|
||||
* Defaults to null, which makes sets the message to /No route was found matching the URL and request method/
|
||||
* @param int $code The HTTP status code.
|
||||
* Optional.
|
||||
* Defaults to 404 (Not found).
|
||||
*
|
||||
* @return WP_Error The WordPress error object with the error message and status code supplied
|
||||
*/
|
||||
public function respond_wrong_method( $message = null, int $code = 404 ): WP_Error {
|
||||
if ( null === $message ) {
|
||||
$message = __( 'No route was found matching the URL and request method', 'cloud-backup' );
|
||||
}
|
||||
|
||||
return new WP_Error( 'rest_no_route', $message, [ 'status' => $code ] );
|
||||
}
|
||||
|
||||
/**
|
||||
* respond_with_code
|
||||
* Create a new /WP_REST_Response/ object with the specified data and HTTP response code.
|
||||
*
|
||||
* @param array|null $data The data to return in this response
|
||||
* @param int $code The HTTP response code.
|
||||
* Optional.
|
||||
* Defaults to 200 (OK).
|
||||
*
|
||||
* @return WP_REST_Response The WordPress response object loaded with the data and the response code.
|
||||
*/
|
||||
public function respond_with_code( ?array $data = null, int $code = 200 ): WP_REST_Response {
|
||||
return new WP_REST_Response( $data, $code );
|
||||
}
|
||||
|
||||
/**
|
||||
* get_user_from_request
|
||||
*
|
||||
* Returns the current user object.
|
||||
* Depends on the property /current_user_id/ to be set.
|
||||
* @return WP_User|false The user object or false if not found or on error.
|
||||
*/
|
||||
public function get_user_from_request() {
|
||||
return get_user_by( 'id', $this->current_user_id );
|
||||
}
|
||||
|
||||
/**
|
||||
* get_arguments
|
||||
* Rest Endpoint extra arguments
|
||||
* @return array Additional arguments for the route configuration
|
||||
*/
|
||||
public function get_arguments(): array {
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* get_endpoint
|
||||
* Rest route Endpoint
|
||||
* @return string Endpoint uri component (comes after the route namespace)
|
||||
*/
|
||||
abstract public function get_endpoint(): string;
|
||||
|
||||
/**
|
||||
* get_name
|
||||
* @return string The name of the route
|
||||
*/
|
||||
abstract public function get_name(): string;
|
||||
|
||||
/**
|
||||
* get_self_url
|
||||
*
|
||||
* @param string $endpoint
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function get_self_url( string $endpoint = '' ): string {
|
||||
return rest_url( $this->namespace . '/' . $endpoint );
|
||||
}
|
||||
|
||||
public function respond_success_json( $data = [] ): WP_REST_Response {
|
||||
return new WP_REST_Response([
|
||||
'success' => true,
|
||||
'data' => $data,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{message: string, code: string} $data
|
||||
*
|
||||
* @return WP_Error
|
||||
*/
|
||||
public function respond_error_json( array $data ): WP_Error {
|
||||
if ( ! isset( $data['message'] ) || ! isset( $data['code'] ) ) {
|
||||
_doing_it_wrong(
|
||||
__FUNCTION__,
|
||||
esc_html__( 'Both `message` and `code` keys must be provided', 'image-optimization' ),
|
||||
'1.0.0'
|
||||
); // @codeCoverageIgnore
|
||||
}
|
||||
|
||||
return new WP_Error(
|
||||
$data['code'] ?? 'internal_server_error',
|
||||
$data['message'] ?? esc_html__( 'Internal server error', 'image-optimization' ),
|
||||
);
|
||||
}
|
||||
|
||||
public function verify_nonce( $nonce = '', $name = '' ) {
|
||||
if ( ! wp_verify_nonce( sanitize_text_field( wp_unslash( $nonce ) ), $name ) ) {
|
||||
return $this->respond_error_json([
|
||||
'message' => esc_html__( 'Invalid nonce', 'image-optimization' ),
|
||||
'code' => 'bad_request',
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
public function verify_capability( $capability = 'manage_options' ) {
|
||||
if ( ! current_user_can( $capability ) ) {
|
||||
return $this->respond_error_json([
|
||||
'message' => esc_html__( 'You do not have sufficient permissions to access this data.', 'image-optimization' ),
|
||||
'code' => 'bad_request',
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
public function verify_nonce_and_capability( $nonce = '', $name = '', $capability = 'manage_options' ) {
|
||||
$valid = $this->verify_nonce( $nonce, $name );
|
||||
|
||||
if ( is_wp_error( $valid ) ) {
|
||||
return $valid;
|
||||
}
|
||||
|
||||
if ( ! current_user_can( $capability ) ) {
|
||||
return $this->respond_error_json([
|
||||
'message' => esc_html__( 'You do not have sufficient permissions to access this data.', 'image-optimization' ),
|
||||
'code' => 'bad_request',
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
public function trigger_internal( $method, $endpoint, $args = [] ): array {
|
||||
$request = new WP_REST_Request( $method, $this->get_self_url( $endpoint ) );
|
||||
if ( ! empty( $args['body'] ) ) {
|
||||
$request->set_body_params( $args['body'] );
|
||||
}
|
||||
if ( ! empty( $args['headers'] ) ) {
|
||||
$request->set_headers( $args['headers'] );
|
||||
}
|
||||
if ( ! empty( $args['params'] ) ) {
|
||||
$request->set_query_params( $args['params'] );
|
||||
}
|
||||
|
||||
$response = rest_do_request( $request );
|
||||
$server = rest_get_server();
|
||||
return $server->response_to_data( $response, false );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,369 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Classes;
|
||||
|
||||
use ReflectionClass;
|
||||
use WP_Error;
|
||||
use WP_REST_Request;
|
||||
use WP_REST_Response;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
abstract class Route {
|
||||
|
||||
/**
|
||||
* Should the endpoint be validated for user authentication?
|
||||
* If set to TRUE, the default permission callback will make sure the user is logged in and has a valid user id
|
||||
* @var bool
|
||||
*/
|
||||
protected $auth = true;
|
||||
|
||||
/**
|
||||
* holds current authenticated user id
|
||||
* @var int
|
||||
*/
|
||||
protected $current_user_id;
|
||||
|
||||
protected $override = false;
|
||||
|
||||
/**
|
||||
* Rest Endpoint namespace
|
||||
* @var string
|
||||
*/
|
||||
protected $namespace = 'image-optimizer/v1';
|
||||
|
||||
/**
|
||||
* @var array The valid HTTP methods. The list represents the general REST methods. Do not modify.
|
||||
*/
|
||||
private $valid_http_methods = [
|
||||
'GET',
|
||||
'PATCH',
|
||||
'POST',
|
||||
'PUT',
|
||||
'DELETE',
|
||||
];
|
||||
|
||||
/**
|
||||
* Route_Base constructor.
|
||||
*/
|
||||
public function __construct() {
|
||||
add_action( 'rest_api_init', [ $this, 'rest_api_init' ] );
|
||||
}
|
||||
|
||||
/**
|
||||
* rest_api_init
|
||||
*
|
||||
* Registers REST endpoints.
|
||||
* Loops through the REST methods for this route, creates an endpoint configuration for
|
||||
* each of them and registers all the endpoints with the WordPress system.
|
||||
*/
|
||||
public function rest_api_init(): void {
|
||||
$methods = $this->get_methods();
|
||||
|
||||
if ( empty( $methods ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$callbacks = [];
|
||||
|
||||
foreach ( $methods as $method ) {
|
||||
if ( ! in_array( $method, $this->valid_http_methods, true ) ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$callbacks[] = $this->build_endpoint_method_config( $method );
|
||||
}
|
||||
|
||||
$arguments = $this->get_arguments();
|
||||
|
||||
if ( ! $callbacks && empty( $arguments ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$arguments = array_merge( $arguments, $callbacks );
|
||||
|
||||
register_rest_route( $this->namespace, '/' . $this->get_endpoint() . '/', $arguments, $this->override );
|
||||
}
|
||||
|
||||
/**
|
||||
* get_methods
|
||||
* Rest Endpoint methods
|
||||
*
|
||||
* Returns an array of the supported REST methods for this route
|
||||
* @return array<string> REST methods being configured for this route.
|
||||
*/
|
||||
abstract public function get_methods(): array;
|
||||
|
||||
/**
|
||||
* get_callback
|
||||
*
|
||||
* Returns a reference to the callback function to handle the REST method specified by the /method/ parameter.
|
||||
* @param string $method The REST method name
|
||||
*
|
||||
* @return callable A reference to a member function with the same name as the REST method being passed as a parameter,
|
||||
* or a reference to the default function /callback/.
|
||||
*/
|
||||
public function get_callback_method( string $method ): callable {
|
||||
$method_name = strtolower( $method );
|
||||
$callback = $this->method_exists_in_current_class( $method_name ) ? $method_name : 'callback';
|
||||
return [ $this, $callback ];
|
||||
}
|
||||
|
||||
/**
|
||||
* get_permission_callback_method
|
||||
*
|
||||
* Returns a reference to the permission callback for the method if exists or the default one if it doesn't.
|
||||
* @param string $method The REST method name
|
||||
*
|
||||
* @return callable If a method called (rest-method)_permission_callback exists, returns a reference to it, otherwise
|
||||
* returns a reference to the default member method /permission_callback/.
|
||||
*/
|
||||
public function get_permission_callback_method( string $method ): callable {
|
||||
$method_name = strtolower( $method );
|
||||
$permission_callback_method = $method_name . '_permission_callback';
|
||||
$permission_callback = $this->method_exists_in_current_class( $permission_callback_method ) ? $permission_callback_method : 'permission_callback';
|
||||
return [ $this, $permission_callback ];
|
||||
}
|
||||
|
||||
/**
|
||||
* maybe_add_args_to_config
|
||||
*
|
||||
* Checks if the class has a method call (rest-method)_args.
|
||||
* If it does, the function calls it and adds its response to the config object passed to the function, under the /args/ key.
|
||||
* @param string $method The REST method name being configured
|
||||
* @param array $config The configuration object for the method
|
||||
*
|
||||
* @return array The configuration object for the method, possibly after being amended
|
||||
*/
|
||||
public function maybe_add_args_to_config( string $method, array $config ): array {
|
||||
$method_name = strtolower( $method );
|
||||
$method_args = $method_name . '_args';
|
||||
if ( $this->method_exists_in_current_class( $method_args ) ) {
|
||||
$config['args'] = $this->{$method_args}();
|
||||
}
|
||||
return $config;
|
||||
}
|
||||
|
||||
/**
|
||||
* maybe_add_response_to_swagger
|
||||
*
|
||||
* If the function method /(rest-method)_response_callback/ exists, adds the filter
|
||||
* /swagger_api_response_(namespace with slashes replaced with underscores)_(endpoint with slashes replaced with underscores)/
|
||||
* with the aforementioned function method.
|
||||
* This filter is used with the WP API Swagger UI plugin to create documentation for the API.
|
||||
* The value being passed is an array: [
|
||||
'200' => ['description' => 'OK'],
|
||||
'404' => ['description' => 'Not Found'],
|
||||
'400' => ['description' => 'Bad Request']
|
||||
]
|
||||
* @param string $method REST method name
|
||||
*/
|
||||
public function maybe_add_response_to_swagger( string $method ): void {
|
||||
$method_name = strtolower( $method );
|
||||
$method_response_callback = $method_name . '_response_callback';
|
||||
if ( $this->method_exists_in_current_class( $method_response_callback ) ) {
|
||||
$response_filter = $method_name . '_' . str_replace(
|
||||
'/',
|
||||
'_',
|
||||
$this->namespace . '/' . $this->get_endpoint()
|
||||
);
|
||||
add_filter( 'swagger_api_responses_' . $response_filter, [ $this, $method_response_callback ] );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* build_endpoint_method_config
|
||||
*
|
||||
* Builds a configuration array for the endpoint based on the presence of the callback, permission, additional parameters,
|
||||
* and response to Swagger member functions.
|
||||
* @param string $method The REST method for the endpoint
|
||||
*
|
||||
* @return array The endpoint configuration for the method specified by the parameter
|
||||
*/
|
||||
private function build_endpoint_method_config( string $method ): array {
|
||||
$config = [
|
||||
'methods' => $method,
|
||||
'callback' => $this->get_callback_method( $method ),
|
||||
'permission_callback' => $this->get_permission_callback_method( $method ),
|
||||
];
|
||||
$config = $this->maybe_add_args_to_config( $method, $config );
|
||||
return $config;
|
||||
}
|
||||
|
||||
/**
|
||||
* method_exists_in_current_class
|
||||
*
|
||||
* Uses reflection to check if this class has the /method/ method.
|
||||
* @param string $method The name of the method being checked.
|
||||
*
|
||||
* @return bool TRUE if the class has the /method/ method, FALSE otherwise.
|
||||
*/
|
||||
private function method_exists_in_current_class( string $method ): bool {
|
||||
$class_name = get_class( $this );
|
||||
try {
|
||||
$reflection = new ReflectionClass( $class_name );
|
||||
} catch ( \ReflectionException $e ) {
|
||||
return false;
|
||||
}
|
||||
if ( ! $reflection->hasMethod( $method ) ) {
|
||||
return false;
|
||||
}
|
||||
$method_ref = $reflection->getMethod( $method );
|
||||
|
||||
return ( $method_ref && $class_name === $method_ref->class );
|
||||
}
|
||||
|
||||
/**
|
||||
* permission_callback
|
||||
* Permissions callback fallback for the endpoint
|
||||
* Gets the current user ID and sets the /current_user_id/ property.
|
||||
* If the /auth/ property is set to /true/ will make sure that the user is logged in (has an id greater than 0)
|
||||
*
|
||||
* @param WP_REST_Request $request unused
|
||||
*
|
||||
* @return bool TRUE, if permission granted, FALSE otherwise
|
||||
*/
|
||||
public function permission_callback( WP_REST_Request $request ): bool {
|
||||
// try to get current user
|
||||
$this->current_user_id = get_current_user_id();
|
||||
if ( $this->auth ) {
|
||||
return $this->current_user_id > 0;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* callback
|
||||
* Fallback callback function, returns a response consisting of the string /ok/.
|
||||
*
|
||||
* @param WP_REST_Request $request unused
|
||||
*
|
||||
* @return WP_REST_Response Default Response of the string 'ok'.
|
||||
*/
|
||||
public function callback( WP_REST_Request $request ): WP_REST_Response {
|
||||
return rest_ensure_response( [ 'OK' ] );
|
||||
}
|
||||
|
||||
/**
|
||||
* respond_wrong_method
|
||||
*
|
||||
* Creates a WordPress error object with the /rest_no_route/ code and the message and code supplied or the defaults.
|
||||
* @param null $message The error message for the wrong method.
|
||||
* Optional.
|
||||
* Defaults to null, which makes sets the message to /No route was found matching the URL and request method/
|
||||
* @param int $code The HTTP status code.
|
||||
* Optional.
|
||||
* Defaults to 404 (Not found).
|
||||
*
|
||||
* @return WP_Error The WordPress error object with the error message and status code supplied
|
||||
*/
|
||||
public function respond_wrong_method( $message = null, int $code = 404 ): WP_Error {
|
||||
if ( null === $message ) {
|
||||
$message = 'No route was found matching the URL and request method';
|
||||
}
|
||||
|
||||
return new WP_Error( 'rest_no_route', $message, [ 'status' => $code ] );
|
||||
}
|
||||
|
||||
/**
|
||||
* respond_with_code
|
||||
* Create a new /WP_REST_Response/ object with the specified data and HTTP response code.
|
||||
*
|
||||
* @param array|null $data The data to return in this response
|
||||
* @param int $code The HTTP response code.
|
||||
* Optional.
|
||||
* Defaults to 200 (OK).
|
||||
*
|
||||
* @return WP_REST_Response The WordPress response object loaded with the data and the response code.
|
||||
*/
|
||||
public function respond_with_code( ?array $data = null, int $code = 200 ): WP_REST_Response {
|
||||
return new WP_REST_Response( $data, $code );
|
||||
}
|
||||
|
||||
/**
|
||||
* get_user_from_request
|
||||
*
|
||||
* Returns the current user object.
|
||||
* Depends on the property /current_user_id/ to be set.
|
||||
* @return WP_User|false The user object or false if not found or on error.
|
||||
*/
|
||||
public function get_user_from_request() {
|
||||
return get_user_by( 'id', $this->current_user_id );
|
||||
}
|
||||
|
||||
/**
|
||||
* get_arguments
|
||||
* Rest Endpoint extra arguments
|
||||
* @return array Additional arguments for the route configuration
|
||||
*/
|
||||
public function get_arguments(): array {
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* get_endpoint
|
||||
* Rest route Endpoint
|
||||
* @return string Endpoint uri component (comes after the route namespace)
|
||||
*/
|
||||
abstract public function get_endpoint(): string;
|
||||
|
||||
/**
|
||||
* get_name
|
||||
* @return string The name of the route
|
||||
*/
|
||||
abstract public function get_name(): string;
|
||||
|
||||
public function get_self_url( $endpoint = '' ): string {
|
||||
return rest_url( $this->namespace . '/' . $endpoint );
|
||||
}
|
||||
|
||||
public function respond_success_json( $data = [] ): WP_REST_Response {
|
||||
return new WP_REST_Response([
|
||||
'success' => true,
|
||||
'data' => $data,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{message: string, code: string} $data
|
||||
*
|
||||
* @return WP_Error
|
||||
*/
|
||||
public function respond_error_json( array $data ): WP_Error {
|
||||
if ( ! isset( $data['message'] ) || ! isset( $data['code'] ) ) {
|
||||
_doing_it_wrong(
|
||||
__FUNCTION__,
|
||||
esc_html__( 'Both `message` and `code` keys must be provided', 'image-optimization' ),
|
||||
'1.0.0'
|
||||
); // @codeCoverageIgnore
|
||||
}
|
||||
|
||||
return new WP_Error(
|
||||
$data['code'] ?? 'internal_server_error',
|
||||
$data['message'] ?? esc_html__( 'Internal server error', 'image-optimization' ),
|
||||
);
|
||||
}
|
||||
|
||||
public function verify_nonce( $nonce = '', $name = '' ) {
|
||||
if ( ! wp_verify_nonce( sanitize_text_field( wp_unslash( $nonce ) ), $name ) ) {
|
||||
return $this->respond_error_json([
|
||||
'message' => esc_html__( 'Invalid nonce', 'image-optimization' ),
|
||||
'code' => 'bad_request',
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
public function verify_nonce_and_capability( $nonce = '', $name = '', $capability = 'manage_options' ) {
|
||||
$this->verify_nonce( $nonce, $name );
|
||||
|
||||
if ( ! current_user_can( $capability ) ) {
|
||||
return $this->respond_error_json([
|
||||
'message' => esc_html__( 'You do not have sufficient permissions to access this data.', 'image-optimization' ),
|
||||
'code' => 'bad_request',
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Classes;
|
||||
|
||||
use ImageOptimization\Classes\Client\Client;
|
||||
use ImageOptimization\Plugin;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
class Utils {
|
||||
/**
|
||||
* get_elementor
|
||||
* @param $instance
|
||||
*
|
||||
* @return \Elementor\Plugin|false|mixed|null
|
||||
*/
|
||||
public static function get_elementor( $instance = false ) {
|
||||
static $_instance = null;
|
||||
if ( false !== $instance ) {
|
||||
$_instance = $instance;
|
||||
|
||||
return $instance;
|
||||
}
|
||||
if ( null !== $_instance ) {
|
||||
return $_instance;
|
||||
}
|
||||
if ( class_exists( 'Elementor\Plugin' ) ) {
|
||||
return \Elementor\Plugin::instance(); // @codeCoverageIgnore
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public static function get_api_client(): ?Client {
|
||||
return Client::get_instance();
|
||||
}
|
||||
|
||||
public static function get_module( $module_name = '' ) {
|
||||
return Plugin::instance()->modules_manager->get_modules( $module_name );
|
||||
}
|
||||
|
||||
public static function get_module_component( $module_name, $component ) {
|
||||
$module = self::get_module( $module_name );
|
||||
if ( $module ) {
|
||||
return $module->get_component( $component );
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* is_elementor_installed
|
||||
* @return bool
|
||||
*/
|
||||
public static function is_elementor_installed(): bool {
|
||||
$plugins = get_plugins();
|
||||
return isset( $plugins['elementor/elementor.php'] );
|
||||
}
|
||||
|
||||
/**
|
||||
* is_elementor_installed_and_active
|
||||
* should be used only after `plugins_loaded` action
|
||||
* @return bool
|
||||
*/
|
||||
public static function is_elementor_installed_and_active(): bool {
|
||||
return did_action( 'elementor/loaded' );
|
||||
}
|
||||
|
||||
public static function is_media_page(): bool {
|
||||
$current_screen = get_current_screen();
|
||||
|
||||
if ( ! $current_screen ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return 'upload' === $current_screen->id && 'attachment' === $current_screen->post_type;
|
||||
}
|
||||
|
||||
public static function is_media_upload_page(): bool {
|
||||
$current_screen = get_current_screen();
|
||||
|
||||
if ( ! $current_screen ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return 'media' === $current_screen->id && 'add' === $current_screen->action;
|
||||
}
|
||||
|
||||
public static function is_single_attachment_page(): bool {
|
||||
$current_screen = get_current_screen();
|
||||
|
||||
if ( ! $current_screen ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return 'attachment' === $current_screen->id && 'post' === $current_screen->base;
|
||||
}
|
||||
|
||||
public static function is_plugin_page(): bool {
|
||||
$current_screen = get_current_screen();
|
||||
|
||||
return str_contains( $current_screen->id, 'image-optimization-' );
|
||||
}
|
||||
|
||||
public static function is_plugin_settings_page(): bool {
|
||||
$current_screen = get_current_screen();
|
||||
|
||||
return str_contains( $current_screen->id, 'image-optimization-settings' );
|
||||
}
|
||||
|
||||
public static function is_bulk_optimization_page(): bool {
|
||||
$current_screen = get_current_screen();
|
||||
|
||||
return str_contains( $current_screen->id, 'image-optimization-bulk-optimization' );
|
||||
}
|
||||
|
||||
public static function user_is_admin(): bool {
|
||||
return current_user_can( 'manage_options' );
|
||||
}
|
||||
|
||||
public static function is_wp_dashboard_page(): bool {
|
||||
$current_screen = get_current_screen();
|
||||
|
||||
return str_contains( $current_screen->id, 'dashboard' );
|
||||
}
|
||||
|
||||
public static function is_wp_updates_page(): bool {
|
||||
$current_screen = get_current_screen();
|
||||
|
||||
return str_contains( $current_screen->id, 'update' );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
<?php
|
||||
/**
|
||||
* Plugin Name: Image Optimizer - Compress, Resize and Optimize Images
|
||||
* Description: Automatically resize, optimize, and convert images to WebP and AVIF. Compress images in bulk or on upload to boost your WordPress site performance.
|
||||
* Plugin URI: https://go.elementor.com/wp-repo-description-tab-io-product-page/
|
||||
* Version: 1.6.9
|
||||
* Author: Elementor.com
|
||||
* Author URI: https://go.elementor.com/author-uri-io/
|
||||
* Text Domain: image-optimization
|
||||
* License: GPL-3
|
||||
* License URI: https://www.gnu.org/licenses/gpl-3.0.en.html
|
||||
*/
|
||||
|
||||
use ImageOptimization\Modules\Core\Module as CoreModule;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
define( 'IMAGE_OPTIMIZATION_VERSION', '1.6.9' );
|
||||
define( 'IMAGE_OPTIMIZATION_FILE', __FILE__ );
|
||||
define( 'IMAGE_OPTIMIZATION_PATH', plugin_dir_path( IMAGE_OPTIMIZATION_FILE ) );
|
||||
define( 'IMAGE_OPTIMIZATION_URL', plugins_url( '/', IMAGE_OPTIMIZATION_FILE ) );
|
||||
define( 'IMAGE_OPTIMIZATION_ASSETS_PATH', IMAGE_OPTIMIZATION_PATH . 'assets/' );
|
||||
define( 'IMAGE_OPTIMIZATION_ASSETS_URL', IMAGE_OPTIMIZATION_URL . 'assets/' );
|
||||
define( 'IMAGE_OPTIMIZATION_PLUGIN_FILE', plugin_basename( IMAGE_OPTIMIZATION_FILE ) );
|
||||
|
||||
if ( ! defined( 'IMAGE_OPTIMIZATION_MINIMUM_LOG_LEVEL' ) ) {
|
||||
define( 'IMAGE_OPTIMIZATION_MINIMUM_LOG_LEVEL', 3 );
|
||||
}
|
||||
|
||||
register_deactivation_hook(
|
||||
__FILE__,
|
||||
[ CoreModule::class, 'on_deactivation' ]
|
||||
);
|
||||
|
||||
/**
|
||||
* ImageOptimization Class
|
||||
*/
|
||||
final class ImageOptimization {
|
||||
private $requirements_errors = [];
|
||||
const REQUIRED_EXTENSIONS = [
|
||||
'exif',
|
||||
'fileinfo',
|
||||
'gd',
|
||||
];
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*
|
||||
* @access public
|
||||
*/
|
||||
public function __construct() {
|
||||
// Init Plugin
|
||||
add_action( 'plugins_loaded', [ $this, 'init' ], -11 );
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if all requirements met to safely start the plugin and renders admin notices
|
||||
* if something is not right.
|
||||
*
|
||||
* @access public
|
||||
* @return bool
|
||||
*/
|
||||
public function plugin_can_start(): bool {
|
||||
$can_start = true;
|
||||
|
||||
if ( ! version_compare( PHP_VERSION, '7.4', '>=' ) ) {
|
||||
$this->requirements_errors[] = sprintf(
|
||||
'%1$s <a href="https://go.elementor.com/wp-dash-update-php/" target="_blank">%2$s</a>',
|
||||
sprintf(
|
||||
/* translators: %s: PHP version. */
|
||||
esc_html__( 'Update to PHP version %s and get back to optimizing!', 'image-optimization' ),
|
||||
'7.4',
|
||||
),
|
||||
esc_html__( 'Show me how', 'image-optimization' )
|
||||
);
|
||||
|
||||
$can_start = false;
|
||||
}
|
||||
|
||||
if ( count( $this->get_missing_extensions_list() ) ) {
|
||||
$missed_extensions = $this->get_missing_extensions_list();
|
||||
|
||||
$this->requirements_errors[] = sprintf(
|
||||
esc_html__( 'The following required PHP extensions are missing: %s', 'image-optimization' ),
|
||||
implode( ', ', $missed_extensions )
|
||||
);
|
||||
|
||||
$can_start = false;
|
||||
}
|
||||
|
||||
if ( ! $this->is_db_json_supported() ) {
|
||||
$this->requirements_errors[] = sprintf(
|
||||
/* translators: 1: MySQL minimum version. 2: MariaDB minimum version. */
|
||||
esc_html__(
|
||||
'The database server version is outdated. Update to MySQL version %1$s or MariaDB version %2$s.',
|
||||
'image-optimization'
|
||||
),
|
||||
'5.7',
|
||||
'10.2'
|
||||
);
|
||||
|
||||
$can_start = false;
|
||||
}
|
||||
|
||||
$upload_dir = wp_upload_dir();
|
||||
|
||||
if ( ! wp_is_writable( $upload_dir['basedir'] ) ) {
|
||||
$this->requirements_errors[] = esc_html__(
|
||||
'Your site doesn’t have the necessary read/write permissions for your file system to use this plugin. Please contact your hosting provider to resolve this matter.',
|
||||
'image-optimization',
|
||||
);
|
||||
|
||||
$can_start = false;
|
||||
}
|
||||
|
||||
return $can_start;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve an array of missing extensions mentioned in self::REQUIRED_EXTENSIONS.
|
||||
*
|
||||
* @access private
|
||||
* @return array Missing extensions.
|
||||
*/
|
||||
private function get_missing_extensions_list(): array {
|
||||
$output = [];
|
||||
|
||||
foreach ( self::REQUIRED_EXTENSIONS as $extension ) {
|
||||
if ( ! extension_loaded( $extension ) ) {
|
||||
$output[] = $extension;
|
||||
}
|
||||
}
|
||||
|
||||
return $output;
|
||||
}
|
||||
|
||||
/**
|
||||
* The check is strictly based on the action scheduler requirements that needs JSON partial matching to work
|
||||
* with action queries.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function is_db_json_supported(): bool {
|
||||
global $wpdb;
|
||||
|
||||
$db_server_info = is_callable( array( $wpdb, 'db_server_info' ) ) ? $wpdb->db_server_info() : $wpdb->db_version();
|
||||
|
||||
if ( false !== strpos( $db_server_info, 'MariaDB' ) ) {
|
||||
$supports_json = version_compare(
|
||||
PHP_VERSION_ID >= 80016 ? $wpdb->db_version() : preg_replace( '/[^0-9.].*/', '', str_replace( '5.5.5-', '', $db_server_info ) ),
|
||||
'10.2',
|
||||
'>='
|
||||
);
|
||||
} else {
|
||||
$supports_json = version_compare( $wpdb->db_version(), '5.7', '>=' );
|
||||
}
|
||||
|
||||
return (bool) $supports_json;
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders an admin notice if the setup did not meet requirements.
|
||||
*
|
||||
* Fired by `admin_notices` action hook.
|
||||
*
|
||||
* @access public
|
||||
* @return void
|
||||
*/
|
||||
public function add_requirements_error() {
|
||||
$message = sprintf(
|
||||
'<h3>%s</h3>',
|
||||
esc_html__( 'Image Optimizer isn’t running because:', 'image-optimization' )
|
||||
);
|
||||
|
||||
$message .= '<ul>';
|
||||
|
||||
foreach ( $this->requirements_errors as $error ) {
|
||||
$message .= sprintf(
|
||||
'%s%s%s',
|
||||
'<li>',
|
||||
$error,
|
||||
'</li>'
|
||||
);
|
||||
}
|
||||
|
||||
$message .= '</ul>';
|
||||
|
||||
$html_message = sprintf( '<div class="error">%s</div>', wpautop( $message ) );
|
||||
|
||||
echo wp_kses_post( $html_message );
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize the plugin.
|
||||
*
|
||||
* Validates that PHP version is sufficient. Checks for basic plugin requirements,
|
||||
* if one check fail don't continue, if all check have passed include the plugin class.
|
||||
*
|
||||
* Fired by `plugins_loaded` action hook.
|
||||
*
|
||||
* @access public
|
||||
*/
|
||||
public function init() {
|
||||
if ( ! $this->plugin_can_start() ) {
|
||||
add_action( 'admin_notices', [ $this, 'add_requirements_error' ] );
|
||||
} else {
|
||||
// Once we get here, We have passed all validation checks, so we can safely include our plugin
|
||||
require_once 'plugin.php';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Instantiate ImageOptimization.
|
||||
new ImageOptimization();
|
||||
@@ -0,0 +1,74 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization;
|
||||
|
||||
use ImageOptimization\Classes\Module_Base;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
final class Manager {
|
||||
/**
|
||||
* @var Module_Base[]
|
||||
*/
|
||||
private array $modules = [];
|
||||
|
||||
public static function get_module_list(): array {
|
||||
return [
|
||||
'core',
|
||||
'connect',
|
||||
'Oauth',
|
||||
'connect-manager',
|
||||
'settings',
|
||||
'stats',
|
||||
'optimization',
|
||||
'backups',
|
||||
'whats-new',
|
||||
'Deactivation',
|
||||
'reviews',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @codeCoverageIgnore
|
||||
*/
|
||||
public function __construct() {
|
||||
$modules = self::get_module_list();
|
||||
|
||||
foreach ( $modules as $module_name ) {
|
||||
$class_name = str_replace( '-', ' ', $module_name );
|
||||
$class_name = str_replace( ' ', '', ucwords( $class_name ) );
|
||||
$class_name = __NAMESPACE__ . '\\Modules\\' . $class_name . '\Module';
|
||||
|
||||
/** @var Module_Base $class_name */
|
||||
if ( $class_name::is_active() ) {
|
||||
$this->modules[ $module_name ] = $class_name::instance();
|
||||
}
|
||||
}
|
||||
|
||||
// Action Scheduler needs to be registered before `plugins_loaded` hook priority 0
|
||||
add_action( 'plugins_loaded', [ $this, 'include_external_libraries' ], -10 );
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $module_name
|
||||
*
|
||||
* @return Module_Base|Module_Base[]
|
||||
*/
|
||||
public function get_modules( $module_name ) {
|
||||
if ( $module_name ) {
|
||||
if ( isset( $this->modules[ $module_name ] ) ) {
|
||||
return $this->modules[ $module_name ];
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
return $this->modules;
|
||||
}
|
||||
|
||||
public function include_external_libraries() {
|
||||
require_once IMAGE_OPTIMIZATION_PATH . 'vendor/woocommerce/action-scheduler/action-scheduler.php';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
<?php
|
||||
// Silence is golden.
|
||||
@@ -0,0 +1,35 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Modules\Backups\Classes;
|
||||
|
||||
use ImageOptimization\Classes\Async_Operation\{
|
||||
Async_Operation,
|
||||
Async_Operation_Hook,
|
||||
Async_Operation_Queue,
|
||||
};
|
||||
use ImageOptimization\Classes\Image\Image_Query_Builder;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
class Remove_All_Backups {
|
||||
private const CHUNK_SIZE = 100;
|
||||
|
||||
public static function find_and_schedule_removing(): void {
|
||||
$query = ( new Image_Query_Builder() )
|
||||
->return_images_only_with_backups()
|
||||
->execute();
|
||||
|
||||
$attachment_ids = $query->posts;
|
||||
$chunks = array_chunk( $attachment_ids, self::CHUNK_SIZE );
|
||||
|
||||
foreach ( $chunks as $chunk ) {
|
||||
Async_Operation::create(
|
||||
Async_Operation_Hook::REMOVE_MANY_BACKUPS,
|
||||
[ 'attachment_ids' => $chunk ],
|
||||
Async_Operation_Queue::BACKUP
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Modules\Backups\Classes;
|
||||
|
||||
use ImageOptimization\Classes\Async_Operation\{
|
||||
Async_Operation,
|
||||
Async_Operation_Hook,
|
||||
Async_Operation_Queue,
|
||||
};
|
||||
use ImageOptimization\Classes\Image\{
|
||||
Image_Meta,
|
||||
Image_Query_Builder,
|
||||
Image_Status
|
||||
};
|
||||
use Throwable;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
class Restore_Images {
|
||||
private const CHUNK_SIZE = 100;
|
||||
|
||||
/**
|
||||
* Schedules a single restoring operation.
|
||||
*
|
||||
* @param int $image_id
|
||||
* @return void
|
||||
* @throws Throwable
|
||||
* @throws \ImageOptimization\Classes\Async_Operation\Exceptions\Async_Operation_Exception
|
||||
*/
|
||||
public static function schedule_single_restoring( int $image_id ): void {
|
||||
$meta = new Image_Meta( $image_id );
|
||||
|
||||
try {
|
||||
$meta
|
||||
->set_status( Image_Status::RESTORING_IN_PROGRESS )
|
||||
->save();
|
||||
|
||||
Async_Operation::create(
|
||||
Async_Operation_Hook::RESTORE_SINGLE_IMAGE,
|
||||
[ 'attachment_id' => $image_id ],
|
||||
Async_Operation_Queue::RESTORE
|
||||
);
|
||||
} catch ( Throwable $t ) {
|
||||
$meta
|
||||
->set_status( Image_Status::RESTORING_FAILED )
|
||||
->save();
|
||||
|
||||
throw $t;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Schedules restoring operations for all valid images with backups created.
|
||||
*
|
||||
* @param array $image_ids
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public static function find_and_schedule_restoring( array $image_ids = [] ): void {
|
||||
$query = ( new Image_Query_Builder() )
|
||||
->return_images_only_with_backups();
|
||||
|
||||
if ( ! empty( $image_ids ) ) {
|
||||
$query->set_image_ids( $image_ids );
|
||||
}
|
||||
|
||||
$query = $query->execute();
|
||||
$attachment_ids = $query->posts;
|
||||
$chunks = array_chunk( $attachment_ids, self::CHUNK_SIZE );
|
||||
|
||||
foreach ( $chunks as $chunk ) {
|
||||
try {
|
||||
Async_Operation::create(
|
||||
Async_Operation_Hook::RESTORE_MANY_IMAGES,
|
||||
[ 'attachment_ids' => $chunk ],
|
||||
Async_Operation_Queue::RESTORE
|
||||
);
|
||||
|
||||
self::mark_chunk_as_in_progress( $chunk );
|
||||
} catch ( Throwable $t ) {
|
||||
self::fail_restoring_for_chunk( $chunk );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates chunk images optimization status to in-progress.
|
||||
*
|
||||
* @param int[] $chunk
|
||||
* @return void
|
||||
*/
|
||||
private static function mark_chunk_as_in_progress( array $chunk ) {
|
||||
foreach ( $chunk as $image_id ) {
|
||||
( new Image_Meta( $image_id ) )
|
||||
->set_status( Image_Status::RESTORING_IN_PROGRESS )
|
||||
->save();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates chunk images optimization status to failed.
|
||||
*
|
||||
* @param int[] $chunk
|
||||
* @return void
|
||||
*/
|
||||
private static function fail_restoring_for_chunk( array $chunk ) {
|
||||
foreach ( $chunk as $image_id ) {
|
||||
( new Image_Meta( $image_id ) )
|
||||
->set_status( Image_Status::RESTORING_FAILED )
|
||||
->save();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Modules\Backups\Classes;
|
||||
|
||||
use ImageOptimization\Classes\Route;
|
||||
use WP_REST_Request;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
class Route_Base extends Route {
|
||||
protected $auth = true;
|
||||
protected string $path = '';
|
||||
|
||||
public function get_methods(): array {
|
||||
return [];
|
||||
}
|
||||
|
||||
public function get_endpoint(): string {
|
||||
return 'backups/' . $this->get_path();
|
||||
}
|
||||
|
||||
public function get_path(): string {
|
||||
return $this->path;
|
||||
}
|
||||
|
||||
public function get_name(): string {
|
||||
return '';
|
||||
}
|
||||
|
||||
public function get_permission_callback( WP_REST_Request $request ): bool {
|
||||
$valid = $this->permission_callback( $request );
|
||||
|
||||
return $valid && user_can( $this->current_user_id, 'manage_options' );
|
||||
}
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Modules\Backups\Components;
|
||||
|
||||
use ImageOptimization\Classes\Async_Operation\Async_Operation_Hook;
|
||||
use ImageOptimization\Classes\Image\Image_Backup;
|
||||
use WP_Post;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
class Handle_Backups_Removing {
|
||||
public function remove_backups_on_attachment_removing( int $attachment_id, WP_Post $attachment_post ) {
|
||||
if ( ! wp_attachment_is_image( $attachment_post ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
Image_Backup::remove( $attachment_id );
|
||||
}
|
||||
|
||||
/** @async */
|
||||
public function remove_many_backups( array $attachment_ids ) {
|
||||
Image_Backup::remove_many( $attachment_ids );
|
||||
}
|
||||
|
||||
public function __construct() {
|
||||
add_action( 'delete_attachment', [ $this, 'remove_backups_on_attachment_removing' ], 10, 2 );
|
||||
add_action( Async_Operation_Hook::REMOVE_MANY_BACKUPS, [ $this, 'remove_many_backups' ] );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Modules\Backups\Components;
|
||||
|
||||
use ImageOptimization\Classes\Async_Operation\Async_Operation_Hook;
|
||||
use ImageOptimization\Classes\Image\{
|
||||
Image_Meta,
|
||||
Image_Restore,
|
||||
Image_Status,
|
||||
};
|
||||
|
||||
use ImageOptimization\Classes\Logger;
|
||||
use Throwable;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
class Restore_Images {
|
||||
/** @async */
|
||||
public function restore_image( int $image_id ) {
|
||||
try {
|
||||
Image_Restore::restore( $image_id );
|
||||
} catch ( Throwable $t ) {
|
||||
Logger::log( Logger::LEVEL_ERROR, 'Image restoring error: ' . $t->getMessage() );
|
||||
|
||||
( new Image_Meta( $image_id ) )
|
||||
->set_status( Image_Status::RESTORING_FAILED )
|
||||
->save();
|
||||
|
||||
throw $t;
|
||||
}
|
||||
}
|
||||
|
||||
/** @async */
|
||||
public function restore_many_images( array $attachment_ids ) {
|
||||
Image_Restore::restore_many( $attachment_ids );
|
||||
}
|
||||
|
||||
public function __construct() {
|
||||
add_action( Async_Operation_Hook::RESTORE_SINGLE_IMAGE, [ $this, 'restore_image' ] );
|
||||
add_action( Async_Operation_Hook::RESTORE_MANY_IMAGES, [ $this, 'restore_many_images' ] );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Modules\Backups;
|
||||
|
||||
use ImageOptimization\Classes\Module_Base;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
class Module extends Module_Base {
|
||||
public function get_name(): string {
|
||||
return 'backups';
|
||||
}
|
||||
|
||||
public static function routes_list() : array {
|
||||
return [
|
||||
'Remove_Backups',
|
||||
'Restore_Single',
|
||||
'Restore_All',
|
||||
];
|
||||
}
|
||||
|
||||
public static function component_list() : array {
|
||||
return [
|
||||
'Handle_Backups_Removing',
|
||||
'Restore_Images',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Module constructor.
|
||||
*/
|
||||
public function __construct() {
|
||||
$this->register_components();
|
||||
$this->register_routes();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Modules\Backups\Rest;
|
||||
|
||||
use ImageOptimization\Modules\Backups\Classes\{
|
||||
Route_Base,
|
||||
Remove_All_Backups,
|
||||
};
|
||||
use Throwable;
|
||||
use WP_REST_Request;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
class Remove_Backups extends Route_Base {
|
||||
const NONCE_NAME = 'image-optimization-remove-backups';
|
||||
|
||||
protected string $path = '';
|
||||
|
||||
public function get_name(): string {
|
||||
return 'remove-backups';
|
||||
}
|
||||
|
||||
public function get_methods(): array {
|
||||
return [ 'DELETE' ];
|
||||
}
|
||||
|
||||
public function DELETE( WP_REST_Request $request ) {
|
||||
$this->verify_nonce_and_capability(
|
||||
$request->get_param( self::NONCE_NAME ),
|
||||
self::NONCE_NAME
|
||||
);
|
||||
|
||||
try {
|
||||
Remove_All_Backups::find_and_schedule_removing();
|
||||
|
||||
return $this->respond_success_json();
|
||||
} catch ( Throwable $t ) {
|
||||
return $this->respond_error_json([
|
||||
'message' => $t->getMessage(),
|
||||
'code' => 'internal_server_error',
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Modules\Backups\Rest;
|
||||
|
||||
use ImageOptimization\Modules\Backups\Classes\{
|
||||
Restore_Images,
|
||||
Route_Base,
|
||||
};
|
||||
use Throwable;
|
||||
use WP_REST_Request;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
class Restore_All extends Route_Base {
|
||||
const NONCE_NAME = 'image-optimization-restore-all';
|
||||
|
||||
protected string $path = 'restore';
|
||||
|
||||
public function get_name(): string {
|
||||
return 'restore-all';
|
||||
}
|
||||
|
||||
public function get_methods(): array {
|
||||
return [ 'POST' ];
|
||||
}
|
||||
|
||||
public function POST( WP_REST_Request $request ) {
|
||||
$this->verify_nonce_and_capability(
|
||||
$request->get_param( self::NONCE_NAME ),
|
||||
self::NONCE_NAME
|
||||
);
|
||||
|
||||
try {
|
||||
Restore_Images::find_and_schedule_restoring();
|
||||
|
||||
return $this->respond_success_json();
|
||||
} catch ( Throwable $t ) {
|
||||
return $this->respond_error_json([
|
||||
'message' => $t->getMessage(),
|
||||
'code' => 'internal_server_error',
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Modules\Backups\Rest;
|
||||
|
||||
use ImageOptimization\Modules\Optimization\Classes\Validate_Image;
|
||||
use ImageOptimization\Modules\Backups\Classes\{
|
||||
Restore_Images,
|
||||
Route_Base,
|
||||
};
|
||||
use Throwable;
|
||||
use WP_REST_Request;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
class Restore_Single extends Route_Base {
|
||||
const NONCE_NAME = 'image-optimization-restore-single';
|
||||
|
||||
protected string $path = 'restore/(?P<image_id>\d+)';
|
||||
|
||||
public function get_name(): string {
|
||||
return 'restore-single';
|
||||
}
|
||||
|
||||
public function get_methods(): array {
|
||||
return [ 'POST' ];
|
||||
}
|
||||
|
||||
public function POST( WP_REST_Request $request ) {
|
||||
$this->verify_nonce_and_capability(
|
||||
$request->get_param( self::NONCE_NAME ),
|
||||
self::NONCE_NAME
|
||||
);
|
||||
|
||||
$image_id = (int) $request->get_param( 'image_id' );
|
||||
|
||||
if ( empty( $image_id ) ) {
|
||||
return $this->respond_error_json( [
|
||||
'message' => esc_html__( 'Invalid image id', 'image-optimization' ),
|
||||
'code' => 'internal_server_error',
|
||||
] );
|
||||
}
|
||||
|
||||
try {
|
||||
Validate_Image::is_valid( $image_id );
|
||||
|
||||
Restore_Images::schedule_single_restoring( $image_id );
|
||||
|
||||
return $this->respond_success_json();
|
||||
} catch ( Throwable $t ) {
|
||||
return $this->respond_error_json([
|
||||
'message' => $t->getMessage(),
|
||||
'code' => 'internal_server_error',
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
+98
@@ -0,0 +1,98 @@
|
||||
<?php
|
||||
namespace ImageOptimization\Modules\ConnectManager\Classes;
|
||||
|
||||
use ImageOptimization\Modules\ConnectManager\Components\Connect_Interface;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // exit if accessed directly
|
||||
}
|
||||
|
||||
class Connect_Runner {
|
||||
public $connect;
|
||||
|
||||
public function __construct( Connect_Interface $connect ) {
|
||||
$this->connect = $connect;
|
||||
}
|
||||
|
||||
public function is_connected() {
|
||||
return $this->connect->is_connected();
|
||||
}
|
||||
|
||||
public function is_activated() : bool {
|
||||
return $this->connect->is_activated();
|
||||
}
|
||||
|
||||
public function is_valid_home_url() : bool {
|
||||
return $this->connect->is_valid_home_url();
|
||||
}
|
||||
|
||||
public function get_connect_status() {
|
||||
return $this->connect->get_connect_status();
|
||||
}
|
||||
|
||||
public function get_connect_data( bool $force = false ): array {
|
||||
return $this->connect->get_connect_data( $force );
|
||||
}
|
||||
|
||||
public function update_usage_data( $new_usage_data ): void {
|
||||
$this->connect->update_usage_data( $new_usage_data );
|
||||
}
|
||||
|
||||
public function get_activation_state() : string {
|
||||
return $this->connect->get_activation_state();
|
||||
}
|
||||
|
||||
public function get_access_token() {
|
||||
return $this->connect->get_access_token();
|
||||
}
|
||||
|
||||
public function get_client_id(): string {
|
||||
return $this->connect->get_client_id();
|
||||
}
|
||||
|
||||
public function get_client_secret(): string {
|
||||
return $this->connect->get_client_secret();
|
||||
}
|
||||
|
||||
public function images_left(): int {
|
||||
return $this->connect->images_left();
|
||||
}
|
||||
|
||||
public function user_is_subscription_owner(): bool {
|
||||
return $this->connect->user_is_subscription_owner();
|
||||
}
|
||||
|
||||
// Legacy Nonces.
|
||||
|
||||
public function connect_init_nonce(): string {
|
||||
return $this->connect->connect_init_nonce();
|
||||
}
|
||||
|
||||
public function disconnect_nonce(): string {
|
||||
return $this->connect->disconnect_nonce();
|
||||
}
|
||||
|
||||
public function deactivate_nonce(): string {
|
||||
return $this->connect->deactivate_nonce();
|
||||
}
|
||||
|
||||
public function get_subscriptions_nonce(): string {
|
||||
return $this->connect->get_subscriptions_nonce();
|
||||
}
|
||||
|
||||
public function activate_nonce(): string {
|
||||
return $this->connect->activate_nonce();
|
||||
}
|
||||
|
||||
public function version_nonce(): string {
|
||||
return $this->connect->version_nonce();
|
||||
}
|
||||
|
||||
public function get_is_connect_on_fly(): bool {
|
||||
return $this->connect->get_is_connect_on_fly();
|
||||
}
|
||||
|
||||
public function refresh_token(): void {
|
||||
$this->connect->refresh_token();
|
||||
}
|
||||
}
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
<?php
|
||||
namespace ImageOptimization\Modules\ConnectManager\Components;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // exit if accessed directly
|
||||
}
|
||||
|
||||
interface Connect_Interface {
|
||||
|
||||
// Connect.
|
||||
public function is_connected(): bool;
|
||||
|
||||
public function is_activated() : bool;
|
||||
public function is_valid_home_url() : bool;
|
||||
|
||||
public function get_connect_status();
|
||||
|
||||
public function get_connect_data( bool $force = false ): array;
|
||||
|
||||
public function update_usage_data( $new_usage_data ): void;
|
||||
|
||||
public function get_activation_state() : string;
|
||||
|
||||
public function get_access_token();
|
||||
|
||||
public function get_client_id(): string;
|
||||
|
||||
public function get_client_secret(): string;
|
||||
|
||||
public function images_left(): int;
|
||||
|
||||
public function user_is_subscription_owner(): bool;
|
||||
|
||||
// Nonces.
|
||||
|
||||
public function connect_init_nonce(): string;
|
||||
|
||||
public function disconnect_nonce(): string;
|
||||
|
||||
public function deactivate_nonce(): string;
|
||||
|
||||
public function get_subscriptions_nonce(): string;
|
||||
|
||||
public function activate_nonce(): string;
|
||||
|
||||
public function version_nonce(): string;
|
||||
|
||||
public function get_is_connect_on_fly(): bool;
|
||||
|
||||
public function refresh_token(): void;
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
<?php
|
||||
namespace ImageOptimization\Modules\ConnectManager\Components;
|
||||
|
||||
use ImageOptimization\Modules\Connect\{
|
||||
Module as ConnectModule,
|
||||
Classes\Data,
|
||||
Classes\Service,
|
||||
Classes\Utils as ConnectUtils,
|
||||
Rest\Authorize,
|
||||
Rest\Version
|
||||
};
|
||||
|
||||
use ImageOptimization\Classes\Logger;
|
||||
use ImageOptimization\Classes\Utils;
|
||||
use Throwable;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // exit if accessed directly
|
||||
}
|
||||
|
||||
class Connect implements Connect_Interface {
|
||||
|
||||
const STATUS_CHECK_TRANSIENT = 'image_optimizer_status_check';
|
||||
|
||||
public function is_connected() : bool {
|
||||
return ConnectModule::is_connected();
|
||||
}
|
||||
|
||||
public function is_activated() : bool {
|
||||
return ConnectModule::is_connected();
|
||||
}
|
||||
|
||||
public function is_valid_home_url() : bool {
|
||||
return ConnectUtils::is_valid_home_url();
|
||||
}
|
||||
|
||||
public function get_connect_status() {
|
||||
if ( ! $this->is_connected() ) {
|
||||
Logger::log( Logger::LEVEL_INFO, 'Status check error. Reason: User is not connected' );
|
||||
return null;
|
||||
}
|
||||
|
||||
$cached_status = get_transient( self::STATUS_CHECK_TRANSIENT );
|
||||
|
||||
if ( $cached_status ) {
|
||||
return $cached_status;
|
||||
}
|
||||
|
||||
try {
|
||||
$response = Utils::get_api_client()->make_request(
|
||||
'POST',
|
||||
'status/check'
|
||||
);
|
||||
} catch ( Throwable $t ) {
|
||||
Logger::log(
|
||||
Logger::LEVEL_ERROR,
|
||||
'Status check error. Reason: ' . $t->getMessage()
|
||||
);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
if ( ! isset( $response->status ) ) {
|
||||
Logger::log( Logger::LEVEL_ERROR, 'Invalid response from server' );
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
if ( ! empty( $response->site_url ) && Data::get_home_url() !== $response->site_url ) {
|
||||
Data::set_home_url( $response->site_url );
|
||||
}
|
||||
|
||||
set_transient( self::STATUS_CHECK_TRANSIENT, $response, MINUTE_IN_SECONDS * 5 );
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
public function get_connect_data( bool $force = false ): array {
|
||||
$data = get_transient( self::STATUS_CHECK_TRANSIENT );
|
||||
|
||||
$user = [];
|
||||
|
||||
// Return empty array if transient does not exist or is expired.
|
||||
if ( ! $data ) {
|
||||
return $user;
|
||||
}
|
||||
|
||||
// Return if user property does not exist in the data object.
|
||||
if ( ! property_exists( $data, 'user' ) ) {
|
||||
return $user;
|
||||
}
|
||||
|
||||
if ( $data->user->email ) {
|
||||
$user = [
|
||||
'user' => [
|
||||
'email' => $data->user->email,
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
return $user;
|
||||
}
|
||||
|
||||
public function update_usage_data( $new_usage_data ): void {
|
||||
$connect_status = $this->get_connect_status();
|
||||
|
||||
if ( ! isset( $new_usage_data->allowed ) || ! isset( $new_usage_data->used ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ( 0 === $new_usage_data->allowed - $new_usage_data->used ) {
|
||||
$connect_status->status = 'expired';
|
||||
}
|
||||
|
||||
$connect_status->quota = $new_usage_data->allowed;
|
||||
$connect_status->used_quota = $new_usage_data->used;
|
||||
|
||||
set_transient( self::STATUS_CHECK_TRANSIENT, $connect_status, MINUTE_IN_SECONDS * 5 );
|
||||
}
|
||||
|
||||
public function get_activation_state() : string {
|
||||
/**
|
||||
* Returning true because the license key is
|
||||
* not used for deactivation in connect.
|
||||
*/
|
||||
return true;
|
||||
}
|
||||
|
||||
public function get_access_token() {
|
||||
return Data::get_access_token();
|
||||
|
||||
}
|
||||
|
||||
public function get_client_id(): string {
|
||||
return Data::get_client_id();
|
||||
}
|
||||
|
||||
public function get_client_secret(): string {
|
||||
return Data::get_client_secret();
|
||||
}
|
||||
|
||||
public function images_left(): int {
|
||||
$plan_data = $this->get_connect_status();
|
||||
|
||||
if ( empty( $plan_data ) ) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
$quota = $plan_data->quota;
|
||||
$used_quota = $plan_data->used_quota;
|
||||
|
||||
return max( $quota - $used_quota, 0 );
|
||||
}
|
||||
|
||||
public function user_is_subscription_owner(): bool {
|
||||
return Data::user_is_subscription_owner();
|
||||
}
|
||||
|
||||
// Nonces.
|
||||
public function connect_init_nonce(): string {
|
||||
return Authorize::NONCE_NAME;
|
||||
}
|
||||
|
||||
public function disconnect_nonce(): string {
|
||||
return Authorize::NONCE_NAME;
|
||||
}
|
||||
|
||||
public function deactivate_nonce(): string {
|
||||
return Authorize::NONCE_NAME;
|
||||
}
|
||||
|
||||
public function get_subscriptions_nonce(): string {
|
||||
return Authorize::NONCE_NAME;
|
||||
}
|
||||
|
||||
public function activate_nonce(): string {
|
||||
return Authorize::NONCE_NAME;
|
||||
}
|
||||
|
||||
public function version_nonce(): string {
|
||||
return Version::NONCE_NAME;
|
||||
}
|
||||
|
||||
public function get_is_connect_on_fly(): bool {
|
||||
return true;
|
||||
}
|
||||
|
||||
public function refresh_token(): void {
|
||||
Service::refresh_token();
|
||||
}
|
||||
}
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
<?php
|
||||
namespace ImageOptimization\Modules\ConnectManager\Components;
|
||||
|
||||
use ImageOptimization\Modules\Oauth\{
|
||||
Components\Connect,
|
||||
Classes\Data,
|
||||
Rest\Activate,
|
||||
Rest\Connect_Init,
|
||||
Rest\Deactivate,
|
||||
Rest\Disconnect,
|
||||
Rest\Get_Subscriptions,
|
||||
Rest\Version,
|
||||
};
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // exit if accessed directly
|
||||
}
|
||||
|
||||
class Legacy_Connect implements Connect_Interface {
|
||||
|
||||
public function is_connected() : bool {
|
||||
return Connect::is_connected();
|
||||
}
|
||||
|
||||
public function is_activated() : bool {
|
||||
return Connect::is_activated();
|
||||
}
|
||||
|
||||
public function is_valid_home_url() : bool {
|
||||
return true;
|
||||
}
|
||||
|
||||
public function get_connect_status() {
|
||||
return Connect::get_connect_status();
|
||||
}
|
||||
|
||||
public function get_connect_data( bool $force = false ): array {
|
||||
return Data::get_connect_data( $force );
|
||||
}
|
||||
|
||||
public function update_usage_data( $new_usage_data ): void {
|
||||
Connect::update_usage_data( $new_usage_data );
|
||||
}
|
||||
|
||||
public function get_activation_state() : string {
|
||||
return Data::get_activation_state();
|
||||
}
|
||||
|
||||
public function get_access_token() {
|
||||
return Data::get_access_token();
|
||||
}
|
||||
|
||||
public function get_client_id(): string {
|
||||
return Data::get_client_id();
|
||||
}
|
||||
|
||||
public function get_client_secret(): string {
|
||||
return Data::get_client_secret();
|
||||
}
|
||||
|
||||
public function images_left(): int {
|
||||
return Data::images_left();
|
||||
}
|
||||
|
||||
public function user_is_subscription_owner(): bool {
|
||||
return Data::user_is_subscription_owner();
|
||||
}
|
||||
|
||||
// Legacy Nonces.
|
||||
|
||||
public function connect_init_nonce(): string {
|
||||
return Connect_Init::NONCE_NAME;
|
||||
}
|
||||
|
||||
public function disconnect_nonce(): string {
|
||||
return Disconnect::NONCE_NAME;
|
||||
}
|
||||
|
||||
public function deactivate_nonce(): string {
|
||||
return Deactivate::NONCE_NAME;
|
||||
}
|
||||
|
||||
public function get_subscriptions_nonce(): string {
|
||||
return Get_Subscriptions::NONCE_NAME;
|
||||
}
|
||||
|
||||
public function activate_nonce(): string {
|
||||
return Activate::NONCE_NAME;
|
||||
}
|
||||
|
||||
public function version_nonce(): string {
|
||||
return Version::NONCE_NAME;
|
||||
}
|
||||
|
||||
public function get_is_connect_on_fly(): bool {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Placeholder function for legacy connect.
|
||||
public function refresh_token(): void {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Modules\ConnectManager;
|
||||
|
||||
use ImageOptimization;
|
||||
use ImageOptimization\Classes\{
|
||||
Module_Base,
|
||||
};
|
||||
|
||||
use ImageOptimization\Modules\ConnectManager\Classes\Connect_Runner;
|
||||
|
||||
use ImageOptimization\Modules\ConnectManager\Components\Legacy_Connect;
|
||||
use ImageOptimization\Modules\ConnectManager\Components\Connect;
|
||||
|
||||
use ImageOptimization\Plugin;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly
|
||||
}
|
||||
|
||||
/**
|
||||
* Class Module
|
||||
*/
|
||||
class Module extends Module_Base {
|
||||
|
||||
/**
|
||||
* Connect instance
|
||||
*
|
||||
* @var connect_instance
|
||||
*/
|
||||
public $connect_instance;
|
||||
|
||||
/**
|
||||
* Get module name.
|
||||
* Retrieve the module name.
|
||||
* @access public
|
||||
* @return string Module name.
|
||||
*/
|
||||
public function get_name() {
|
||||
return 'connect-manager';
|
||||
}
|
||||
|
||||
/**
|
||||
* component_list
|
||||
* @return string[]
|
||||
*/
|
||||
public static function component_list() : array {
|
||||
return [
|
||||
'Legacy_Connect',
|
||||
'Connect',
|
||||
];
|
||||
}
|
||||
|
||||
public function __construct() {
|
||||
// Register components.
|
||||
$this->register_components();
|
||||
// Load Connect Manager.
|
||||
add_action( 'plugins_loaded', [ $this, 'load_connect_manager' ] );
|
||||
}
|
||||
|
||||
/**
|
||||
* Load Connect Manager
|
||||
*
|
||||
* Load the correct version of Connect Manager based on whether
|
||||
* the user is already connected using legacy version or not.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function load_connect_manager() {
|
||||
|
||||
if ( ImageOptimization\Modules\Connect\Module::is_active() ) {
|
||||
$this->connect_instance = new Connect_Runner( new Connect() );
|
||||
} else {
|
||||
$this->connect_instance = new Connect_Runner( new Legacy_Connect() );
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Modules\Connect\Classes;
|
||||
|
||||
use ReflectionClass;
|
||||
use ReflectionException;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
abstract class Basic_Enum {
|
||||
private static array $entries = [];
|
||||
|
||||
/**
|
||||
* @throws ReflectionException
|
||||
*/
|
||||
public static function get_values(): array {
|
||||
return array_values( self::get_entries() );
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws ReflectionException
|
||||
*/
|
||||
protected static function get_entries(): array {
|
||||
$caller = get_called_class();
|
||||
|
||||
if ( ! array_key_exists( $caller, self::$entries ) ) {
|
||||
$reflect = new ReflectionClass( $caller );
|
||||
self::$entries[ $caller ] = $reflect->getConstants();
|
||||
}
|
||||
|
||||
return self::$entries[ $caller ];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Modules\Connect\Classes;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly
|
||||
}
|
||||
|
||||
/**
|
||||
* Class Config
|
||||
*/
|
||||
class Config {
|
||||
const APP_NAME = 'image-optimizer';
|
||||
const APP_PREFIX = 'image_optimizer';
|
||||
const APP_REST_NAMESPACE = 'image_optimizer';
|
||||
const BASE_URL = 'https://my.elementor.com/connect';
|
||||
const ADMIN_PAGE = 'upload.php?page=image-optimization-settings';
|
||||
const APP_TYPE = 'app_io';
|
||||
const SCOPES = 'openid offline_access';
|
||||
const STATE_NONCE = 'image_optimizer_auth_nonce';
|
||||
/**
|
||||
* Connect mode
|
||||
* accepts 'site' or 'user'
|
||||
*/
|
||||
const CONNECT_MODE = 'site';
|
||||
}
|
||||
@@ -0,0 +1,351 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Modules\Connect\Classes;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly
|
||||
}
|
||||
|
||||
/**
|
||||
* Class Data
|
||||
*/
|
||||
class Data {
|
||||
const CLIENT_ID = '_client_id';
|
||||
const CLIENT_SECRET = '_client_secret';
|
||||
const ACCESS_TOKEN = '_access_token';
|
||||
const REFRESH_TOKEN = '_refresh_token';
|
||||
const TOKEN_ID = '_token_id';
|
||||
const SUBSCRIPTION_ID = '_subscription_id';
|
||||
const OPTION_OWNER_USER_ID = '_owner_user_id';
|
||||
const HOME_URL = '_home_url';
|
||||
|
||||
/**
|
||||
* get_option
|
||||
* @param $option_name
|
||||
* @param $default
|
||||
*
|
||||
* @return false|mixed|null
|
||||
*/
|
||||
public static function get_option( $option_name, $default ) {
|
||||
return get_option( Config::APP_PREFIX . $option_name, $default );
|
||||
}
|
||||
|
||||
/**
|
||||
* set_option
|
||||
* @param $option_name
|
||||
* @param $option_value
|
||||
* @param $auto_load
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public static function set_option( $option_name, $option_value, $auto_load = false ): bool {
|
||||
return update_option( Config::APP_PREFIX . $option_name, $option_value, $auto_load );
|
||||
}
|
||||
|
||||
/**
|
||||
* delete_option
|
||||
* @param $option_name
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public static function delete_option( $option_name ) : bool {
|
||||
return delete_option( Config::APP_PREFIX . $option_name );
|
||||
}
|
||||
|
||||
/**
|
||||
* get_user_data
|
||||
* @param $user_id
|
||||
* @param $data_name
|
||||
* @param mixed|bool $default
|
||||
*
|
||||
* @return false|mixed
|
||||
*/
|
||||
public static function get_user_data( $user_id, $data_name, $default = false ) {
|
||||
$data = get_user_meta( $user_id, Config::APP_PREFIX . $data_name, true );
|
||||
|
||||
return empty( $data ) ? $default : $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* set_user_data
|
||||
* @param $user_id
|
||||
* @param $data_name
|
||||
* @param $value
|
||||
*
|
||||
* @return bool|int
|
||||
*/
|
||||
public static function set_user_data( $user_id, $data_name, $value ) {
|
||||
return update_user_meta( $user_id, Config::APP_PREFIX . $data_name, $value );
|
||||
}
|
||||
|
||||
/**
|
||||
* delete_user_data
|
||||
* @param $user_id
|
||||
* @param $data_name
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public static function delete_user_data( $user_id, $data_name ): bool {
|
||||
return delete_user_meta( $user_id, Config::APP_PREFIX . $data_name );
|
||||
}
|
||||
|
||||
/**
|
||||
* get_connect_mode_data
|
||||
* @param ...$data
|
||||
*
|
||||
* @return false|mixed|null|string
|
||||
*/
|
||||
public static function get_connect_mode_data( ...$data ) {
|
||||
if ( Config::CONNECT_MODE === 'site' ) {
|
||||
return self::get_option( ...$data );
|
||||
}
|
||||
$user_id = get_current_user_id();
|
||||
return self::get_user_data( ...( [ $user_id, ...$data ] ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* set_connect_mode_data
|
||||
* @param ...$data
|
||||
*
|
||||
* @return bool|int
|
||||
*/
|
||||
public static function set_connect_mode_data( ...$data ) {
|
||||
if ( Config::CONNECT_MODE === 'site' ) {
|
||||
return self::set_option( ...$data );
|
||||
}
|
||||
$user_id = get_current_user_id();
|
||||
return self::set_user_data( ...( [ $user_id, ...$data ] ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* get_client_id
|
||||
*
|
||||
* @return string|bool|mixed
|
||||
*/
|
||||
public static function get_client_id() {
|
||||
return self::get_connect_mode_data( self::CLIENT_ID, false );
|
||||
}
|
||||
|
||||
/**
|
||||
* get_client_secret
|
||||
* @return false|mixed|string|null
|
||||
*/
|
||||
public static function get_client_secret() {
|
||||
return self::get_connect_mode_data( self::CLIENT_SECRET, false );
|
||||
}
|
||||
|
||||
/**
|
||||
* set_client_id
|
||||
* @param $value
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public static function set_client_id( $value ): bool {
|
||||
return self::set_connect_mode_data( self::CLIENT_ID, $value );
|
||||
}
|
||||
|
||||
public static function get_subscription_id() {
|
||||
return self::get_connect_mode_data( self::SUBSCRIPTION_ID, false );
|
||||
}
|
||||
|
||||
public static function set_subscription_id( $value ): bool {
|
||||
return self::set_connect_mode_data( self::SUBSCRIPTION_ID, $value );
|
||||
}
|
||||
|
||||
/**
|
||||
* set_client_secret
|
||||
* @param $value
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public static function set_client_secret( $value ): bool {
|
||||
return self::set_connect_mode_data( self::CLIENT_SECRET, $value );
|
||||
}
|
||||
|
||||
/**
|
||||
* get_access_token
|
||||
* @return false|mixed|string|null
|
||||
*/
|
||||
public static function get_access_token() {
|
||||
return self::get_connect_mode_data( self::ACCESS_TOKEN, false );
|
||||
}
|
||||
|
||||
public static function get_token_id() {
|
||||
return self::get_connect_mode_data( self::TOKEN_ID, false );
|
||||
}
|
||||
|
||||
/**
|
||||
* get_refresh_token
|
||||
* @return false|mixed|string|null
|
||||
*/
|
||||
public static function get_refresh_token() {
|
||||
return self::get_connect_mode_data( self::REFRESH_TOKEN, false );
|
||||
}
|
||||
|
||||
public static function get_home_url() {
|
||||
$raw = self::get_connect_mode_data( self::HOME_URL, false );
|
||||
$is_base64 = base64_encode( base64_decode( $raw, true ) ) === $raw;
|
||||
return $is_base64 ? base64_decode( $raw ) : $raw;
|
||||
}
|
||||
|
||||
/**
|
||||
* set_home_url
|
||||
*
|
||||
* Stores home URL as a base64 string to avoid migration/stg tools from overriding value
|
||||
*/
|
||||
public static function set_home_url( ?string $home_url = null ): bool {
|
||||
$home_url = $home_url ?? home_url();
|
||||
return self::set_connect_mode_data( self::HOME_URL, base64_encode( $home_url ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* set_user_is_owner_option
|
||||
*/
|
||||
public static function set_user_is_owner_option( $value ) {
|
||||
return self::set_connect_mode_data( self::OPTION_OWNER_USER_ID, $value );
|
||||
}
|
||||
|
||||
/**
|
||||
* get_user_is_owner_option
|
||||
*/
|
||||
public static function get_user_is_owner_option() {
|
||||
return self::get_connect_mode_data( self::OPTION_OWNER_USER_ID, false );
|
||||
}
|
||||
|
||||
/**
|
||||
* fetch_option
|
||||
* direct query to avoid cache and race condition issues
|
||||
*
|
||||
* @param $option_name
|
||||
* @param $default
|
||||
*
|
||||
* @return mixed|null
|
||||
*/
|
||||
public static function fetch_option( $option_name, $default = null ) {
|
||||
global $wpdb;
|
||||
$cache_buster = wp_generate_uuid4();
|
||||
$option = $wpdb->get_col(
|
||||
$wpdb->prepare(
|
||||
"SELECT option_value
|
||||
FROM $wpdb->options
|
||||
WHERE option_name = %s
|
||||
AND %s = %s
|
||||
LIMIT 1",
|
||||
$option_name,
|
||||
$cache_buster,
|
||||
$cache_buster
|
||||
)
|
||||
);
|
||||
if ( ! empty( $option ) ) {
|
||||
return $option[0];
|
||||
}
|
||||
return $default;
|
||||
}
|
||||
|
||||
/**
|
||||
* insert_option_uniquely
|
||||
* used to insert option if not there already
|
||||
* direct query to avoid cache and race condition issues
|
||||
* @param $option_name
|
||||
* @param $option_value
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public static function insert_option_uniquely( $option_name, $option_value ): bool {
|
||||
global $wpdb;
|
||||
$cache_buster = wp_generate_uuid4();
|
||||
$result = $wpdb->query(
|
||||
$wpdb->prepare(
|
||||
"INSERT INTO $wpdb->options (option_name, option_value, autoload)
|
||||
SELECT * FROM (SELECT %s, %s, 'no') AS tmp
|
||||
WHERE NOT EXISTS (
|
||||
SELECT option_name
|
||||
FROM $wpdb->options
|
||||
WHERE option_name = %s
|
||||
AND option_value = %s
|
||||
AND %s = %s
|
||||
) LIMIT 1",
|
||||
$option_name,
|
||||
$option_value,
|
||||
$option_name,
|
||||
$option_value,
|
||||
$cache_buster,
|
||||
$cache_buster
|
||||
)
|
||||
);
|
||||
|
||||
if ( false === $result || 0 === $result ) {
|
||||
// false means query failed, 0 means no row inserted because it exists
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* User is subscription owner.
|
||||
*
|
||||
* Check if current user is subscription owner.
|
||||
*
|
||||
* @return boolean
|
||||
*/
|
||||
public static function user_is_subscription_owner(): bool {
|
||||
$owner_id = (int) self::get_connect_mode_data( self::OPTION_OWNER_USER_ID, false );
|
||||
|
||||
return get_current_user_id() === $owner_id;
|
||||
}
|
||||
|
||||
public static function ensure_reset_connect() {
|
||||
if ( Config::CONNECT_MODE === 'site' ) {
|
||||
self::delete_option( self::ACCESS_TOKEN );
|
||||
self::delete_option( self::REFRESH_TOKEN );
|
||||
self::delete_option( self::TOKEN_ID );
|
||||
self::delete_option( self::SUBSCRIPTION_ID );
|
||||
self::delete_option( self::OPTION_OWNER_USER_ID );
|
||||
self::delete_option( self::HOME_URL );
|
||||
|
||||
delete_transient( 'image_optimizer_status_check' );
|
||||
} else {
|
||||
$user_id = get_current_user_id();
|
||||
self::delete_user_data( $user_id, self::ACCESS_TOKEN );
|
||||
self::delete_user_data( $user_id, self::REFRESH_TOKEN );
|
||||
self::delete_user_data( $user_id, self::TOKEN_ID );
|
||||
self::delete_user_data( $user_id, self::SUBSCRIPTION_ID );
|
||||
self::delete_user_data( $user_id, self::OPTION_OWNER_USER_ID );
|
||||
self::delete_user_data( $user_id, self::HOME_URL );
|
||||
|
||||
delete_transient( 'image_optimizer_status_check' );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* clear_session
|
||||
*/
|
||||
public static function clear_session() {
|
||||
if ( Config::CONNECT_MODE === 'site' ) {
|
||||
self::delete_option( self::CLIENT_ID );
|
||||
self::delete_option( self::CLIENT_SECRET );
|
||||
self::delete_option( self::ACCESS_TOKEN );
|
||||
self::delete_option( self::REFRESH_TOKEN );
|
||||
self::delete_option( self::TOKEN_ID );
|
||||
self::delete_option( self::SUBSCRIPTION_ID );
|
||||
self::delete_option( self::OPTION_OWNER_USER_ID );
|
||||
self::delete_option( self::HOME_URL );
|
||||
|
||||
delete_transient( 'image_optimizer_status_check' );
|
||||
} else {
|
||||
$user_id = get_current_user_id();
|
||||
|
||||
self::delete_user_data( $user_id, self::CLIENT_ID );
|
||||
self::delete_user_data( $user_id, self::CLIENT_SECRET );
|
||||
self::delete_user_data( $user_id, self::ACCESS_TOKEN );
|
||||
self::delete_user_data( $user_id, self::REFRESH_TOKEN );
|
||||
self::delete_user_data( $user_id, self::TOKEN_ID );
|
||||
self::delete_user_data( $user_id, self::SUBSCRIPTION_ID );
|
||||
self::delete_user_data( $user_id, self::OPTION_OWNER_USER_ID );
|
||||
self::delete_user_data( $user_id, self::HOME_URL );
|
||||
|
||||
delete_transient( 'image_optimizer_status_check' );
|
||||
}
|
||||
}
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Modules\Connect\Classes\Exceptions;
|
||||
|
||||
use Exception;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
class Service_Exception extends Exception {
|
||||
protected $message = 'Service Exception';
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Modules\Connect\Classes;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly
|
||||
}
|
||||
|
||||
/**
|
||||
* Class GrantTypes
|
||||
*/
|
||||
class GrantTypes extends Basic_Enum {
|
||||
const CLIENT_CREDENTIALS = 'client_credentials';
|
||||
const AUTHORIZATION_CODE = 'authorization_code';
|
||||
const REFRESH_TOKEN = 'refresh_token';
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Modules\Connect\Classes;
|
||||
|
||||
use ImageOptimization\Classes\Rest\Route;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly
|
||||
}
|
||||
|
||||
/**
|
||||
* Class Route_Base
|
||||
*/
|
||||
class Route_Base extends Route {
|
||||
protected bool $override = false;
|
||||
protected $auth = true;
|
||||
protected string $path = '';
|
||||
public function get_methods(): array {
|
||||
return [];
|
||||
}
|
||||
|
||||
public function get_endpoint(): string {
|
||||
return 'connect/' . $this->get_path();
|
||||
}
|
||||
|
||||
public function get_path(): string {
|
||||
return $this->path;
|
||||
}
|
||||
|
||||
public function get_name(): string {
|
||||
return '';
|
||||
}
|
||||
|
||||
public function post_permission_callback( \WP_REST_Request $request ): bool {
|
||||
return $this->get_permission_callback( $request );
|
||||
}
|
||||
|
||||
public function get_permission_callback( \WP_REST_Request $request ): bool {
|
||||
$valid = $this->permission_callback( $request );
|
||||
|
||||
return $valid && user_can( $this->current_user_id, 'manage_options' );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,301 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Modules\Connect\Classes;
|
||||
|
||||
use ImageOptimization\Modules\Connect\Classes\Exceptions\Service_Exception;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly
|
||||
}
|
||||
|
||||
/**
|
||||
* Class Service
|
||||
*/
|
||||
class Service {
|
||||
const REFRESH_TOKEN_LOCK = '_connect_refresh_token';
|
||||
const APP_TYPE = 'APP_IO';
|
||||
|
||||
/**
|
||||
* Registers new client and returns client ID
|
||||
*
|
||||
* @return string
|
||||
* @throws Service_Exception
|
||||
*/
|
||||
public static function register_client(): string {
|
||||
$clients_url = Utils::get_clients_url();
|
||||
|
||||
if ( ! $clients_url ) {
|
||||
throw new Service_Exception( 'Missing client registration URL' );
|
||||
}
|
||||
|
||||
$client_data = self::request( $clients_url, [
|
||||
'method' => 'POST',
|
||||
'headers' => [
|
||||
'Content-Type' => 'application/json',
|
||||
],
|
||||
'body' => wp_json_encode( [
|
||||
'redirect_uri' => Utils::get_redirect_uri(),
|
||||
'app_type' => Config::APP_TYPE,
|
||||
] ),
|
||||
], 201 );
|
||||
|
||||
$client_id = $client_data['client_id'] ?? null;
|
||||
$client_secret = $client_data['client_secret'] ?? null;
|
||||
|
||||
Data::set_client_id( $client_id );
|
||||
Data::set_client_secret( $client_secret );
|
||||
Data::set_home_url();
|
||||
|
||||
return $client_id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Deactivate license
|
||||
*
|
||||
* @return void
|
||||
* @throws Service_Exception
|
||||
*/
|
||||
public static function deactivate_license(): void {
|
||||
$client_id = Data::get_client_id();
|
||||
|
||||
if ( ! $client_id ) {
|
||||
throw new Service_Exception( 'Missing client ID' );
|
||||
}
|
||||
|
||||
$deactivation_url = Utils::get_deactivation_url( $client_id );
|
||||
|
||||
if ( ! $deactivation_url ) {
|
||||
throw new Service_Exception( 'Missing deactivation URL' );
|
||||
}
|
||||
|
||||
$access_token = Data::get_access_token();
|
||||
|
||||
if ( ! $access_token ) {
|
||||
throw new Service_Exception( 'Missing access token' );
|
||||
}
|
||||
|
||||
$refresh_token = Data::get_refresh_token();
|
||||
|
||||
if ( ! $refresh_token ) {
|
||||
throw new Service_Exception( 'Missing refresh token' );
|
||||
}
|
||||
|
||||
self::request( $deactivation_url, [
|
||||
'method' => 'DELETE',
|
||||
'headers' => [
|
||||
'Authorization' => "Bearer {$access_token}",
|
||||
],
|
||||
], 204 );
|
||||
|
||||
self::get_token( 'refresh_token', $refresh_token );
|
||||
}
|
||||
|
||||
/**
|
||||
* disconnect
|
||||
*
|
||||
* @return void
|
||||
* @throws Service_Exception
|
||||
*/
|
||||
public static function disconnect(): void {
|
||||
$sessions_url = Utils::get_sessions_url();
|
||||
|
||||
if ( ! $sessions_url ) {
|
||||
throw new Service_Exception( 'Missing sessions URL' );
|
||||
}
|
||||
|
||||
$access_token = Data::get_access_token();
|
||||
|
||||
if ( ! $access_token ) {
|
||||
throw new Service_Exception( 'Missing access token' );
|
||||
}
|
||||
|
||||
self::request( $sessions_url, [
|
||||
'method' => 'DELETE',
|
||||
'headers' => [
|
||||
'Content-Type' => 'application/json',
|
||||
'Authorization' => "Bearer {$access_token}",
|
||||
],
|
||||
], 204 );
|
||||
|
||||
Data::clear_session();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get token & optionally save to user
|
||||
*
|
||||
* @param string $grant_type
|
||||
*
|
||||
* @param string|null $credential
|
||||
*
|
||||
* @return array
|
||||
* @throws Service_Exception
|
||||
*/
|
||||
public static function get_token( string $grant_type, ?string $credential = null, ?bool $update = true ): array {
|
||||
$token_url = Utils::get_token_url();
|
||||
|
||||
if ( ! $token_url ) {
|
||||
throw new Service_Exception( 'Missing token URL' );
|
||||
}
|
||||
|
||||
$client_id = Data::get_client_id();
|
||||
$client_secret = Data::get_client_secret();
|
||||
|
||||
if ( empty( $client_id ) || empty( $client_secret ) ) {
|
||||
throw new Service_Exception( 'Missing client ID or secret' );
|
||||
}
|
||||
|
||||
$body = [
|
||||
'grant_type' => $grant_type,
|
||||
'redirect_uri' => Utils::get_redirect_uri(),
|
||||
];
|
||||
|
||||
switch ( $grant_type ) {
|
||||
case GrantTypes::AUTHORIZATION_CODE:
|
||||
$body['code'] = $credential;
|
||||
break;
|
||||
case GrantTypes::REFRESH_TOKEN:
|
||||
$body[ GrantTypes::REFRESH_TOKEN ] = $credential;
|
||||
break;
|
||||
case GrantTypes::CLIENT_CREDENTIALS:
|
||||
$body['redirect_uri'] = Utils::get_redirect_uri( Data::get_home_url() );
|
||||
|
||||
break;
|
||||
default:
|
||||
throw new Service_Exception( 'Invalid grant type' );
|
||||
}
|
||||
|
||||
$data = self::request( $token_url, [
|
||||
'method' => 'POST',
|
||||
'headers' => [
|
||||
'x-elementor-apps' => Config::APP_NAME,
|
||||
'Authorization' => 'Basic ' . base64_encode( "{$client_id}:{$client_secret}" ),
|
||||
],
|
||||
'body' => $body,
|
||||
] );
|
||||
|
||||
if ( $update ) {
|
||||
Data::set_connect_mode_data( Data::TOKEN_ID, $data['id_token'] ?? null );
|
||||
Data::set_connect_mode_data( Data::ACCESS_TOKEN, $data['access_token'] ?? null );
|
||||
Data::set_connect_mode_data( Data::REFRESH_TOKEN, $data['refresh_token'] ?? null );
|
||||
Data::set_connect_mode_data( Data::OPTION_OWNER_USER_ID, get_current_user_id() );
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
public static function jwt_decode( $payload ): string {
|
||||
static $jwks = null;
|
||||
|
||||
$jwks_url = Utils::get_jwks_url();
|
||||
if ( ! $jwks_url ) {
|
||||
return __( 'Missing JWKS URL' );
|
||||
}
|
||||
|
||||
if ( ! $jwks ) {
|
||||
$jwks = self::request( $jwks_url, [
|
||||
'method' => 'GET',
|
||||
] );
|
||||
}
|
||||
if ( ! class_exists( 'JWT' ) ) {
|
||||
require_once IMAGE_OPTIMIZATION_PATH . 'vendor/autoload.php';
|
||||
}
|
||||
|
||||
try {
|
||||
$decoded = \Firebase\JWT\JWT::decode( $payload, \Firebase\JWT\JWK::parseKeySet( $jwks ) );
|
||||
return json_encode( $decoded, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES );
|
||||
} catch ( \Throwable $th ) {
|
||||
if ( $th instanceof \Firebase\JWT\ExpiredException ) {
|
||||
self::get_token( GrantTypes::REFRESH_TOKEN, Data::get_refresh_token() );
|
||||
return self::jwt_decode( $payload );
|
||||
}
|
||||
return $th->getMessage();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $url
|
||||
* @param array $args
|
||||
* @param int $valid_response_code
|
||||
*
|
||||
* @return array|null
|
||||
* @throws Service_Exception
|
||||
*/
|
||||
public static function request( string $url, array $args, int $valid_response_code = 200 ): ?array {
|
||||
$args['timeout'] = 30;
|
||||
$args['headers'] = array_replace_recursive( [
|
||||
'x-elementor-app-type' => self::APP_TYPE,
|
||||
], $args['headers'] ?? [] );
|
||||
|
||||
$response = wp_remote_request( $url, $args );
|
||||
|
||||
if ( is_wp_error( $response ) ) {
|
||||
error_log( '[Connect Service]: ' . $response->get_error_message() );
|
||||
throw new Service_Exception( $response->get_error_message() );
|
||||
}
|
||||
|
||||
if ( $valid_response_code !== wp_remote_retrieve_response_code( $response ) ) {
|
||||
error_log( '[Connect Service]: invalid status code' . wp_remote_retrieve_response_code( $response ) );
|
||||
throw new Service_Exception( wp_remote_retrieve_body( $response ) );
|
||||
}
|
||||
|
||||
return json_decode( wp_remote_retrieve_body( $response ), true );
|
||||
}
|
||||
|
||||
public static function refresh_token() {
|
||||
$lock_key = Config::APP_NAME . self::REFRESH_TOKEN_LOCK;
|
||||
$last_token = Data::fetch_option( $lock_key, '' );
|
||||
|
||||
$current_refresh_token = Data::get_refresh_token();
|
||||
|
||||
if ( ! empty( $last_token ) && $last_token === $current_refresh_token ) {
|
||||
sleep( 1 );
|
||||
delete_option( $lock_key );
|
||||
return;
|
||||
}
|
||||
|
||||
delete_option( $lock_key );
|
||||
$locked = Data::insert_option_uniquely( $lock_key, $current_refresh_token );
|
||||
if ( ! $locked ) {
|
||||
sleep( 1 );
|
||||
delete_option( $lock_key );
|
||||
return;
|
||||
}
|
||||
|
||||
self::get_token( GrantTypes::REFRESH_TOKEN, $current_refresh_token );
|
||||
delete_option( $lock_key );
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws Service_Exception
|
||||
*/
|
||||
public static function update_redirect_uri(): void {
|
||||
$client_id = Data::get_client_id();
|
||||
|
||||
if ( ! $client_id ) {
|
||||
throw new Service_Exception( 'Missing client ID' );
|
||||
}
|
||||
|
||||
$client_patch_url = Utils::get_clients_patch_url( $client_id );
|
||||
|
||||
[ 'access_token' => $access_token ] = self::get_token(
|
||||
GrantTypes::CLIENT_CREDENTIALS,
|
||||
null,
|
||||
false
|
||||
);
|
||||
|
||||
self::request( $client_patch_url, [
|
||||
'method' => 'PATCH',
|
||||
'headers' => [
|
||||
'Content-Type' => 'application/json',
|
||||
'Authorization' => "Bearer {$access_token}",
|
||||
],
|
||||
'body' => json_encode( [
|
||||
'redirect_uri' => Utils::get_redirect_uri(),
|
||||
] ),
|
||||
] );
|
||||
|
||||
self::refresh_token();
|
||||
|
||||
Data::set_home_url();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Modules\Connect\Classes;
|
||||
|
||||
use ImageOptimization\Modules\Connect\Classes\Exceptions\Service_Exception;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly
|
||||
}
|
||||
|
||||
/**
|
||||
* Class Utils
|
||||
*/
|
||||
class Utils {
|
||||
/**
|
||||
* get_clients_url
|
||||
* @return string
|
||||
*/
|
||||
public static function get_clients_url(): string {
|
||||
return self::get_base_url() . '/api/v1/clients';
|
||||
}
|
||||
|
||||
/**
|
||||
* get_redirect_uri
|
||||
* @return string
|
||||
*/
|
||||
public static function get_redirect_uri( string $domain = '' ): string {
|
||||
if ( false !== strpos( Config::ADMIN_PAGE, '?page=' ) ) {
|
||||
$admin_url = admin_url( Config::ADMIN_PAGE );
|
||||
} else {
|
||||
$admin_url = admin_url( 'options-general.php?page=' . Config::ADMIN_PAGE );
|
||||
}
|
||||
|
||||
if ( $domain ) {
|
||||
$parsed_url = parse_url( $admin_url );
|
||||
$path = $parsed_url['path'] . ( isset( $parsed_url['query'] ) ? '?' . $parsed_url['query'] : '' );
|
||||
|
||||
return rtrim( $domain, '/' ) . $path;
|
||||
}
|
||||
|
||||
return $admin_url;
|
||||
}
|
||||
|
||||
public static function get_auth_url(): string {
|
||||
return self::get_base_url() . '/v1/oauth2/auth';
|
||||
}
|
||||
|
||||
/**
|
||||
* Get full authorization URL with all required parameters
|
||||
*
|
||||
* @param string $client_id
|
||||
*
|
||||
* @return string
|
||||
* @throws Service_Exception
|
||||
*/
|
||||
public static function get_authorize_url( string $client_id ): string {
|
||||
return add_query_arg( [
|
||||
'client_id' => $client_id,
|
||||
'redirect_uri' => rawurlencode( self::get_redirect_uri() ),
|
||||
'response_type' => 'code',
|
||||
'scope' => Config::SCOPES,
|
||||
'state' => wp_create_nonce( Config::STATE_NONCE ),
|
||||
], self::get_auth_url() );
|
||||
}
|
||||
|
||||
/**
|
||||
* get_deactivation_url
|
||||
* @param string $client_id
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public static function get_deactivation_url( string $client_id ): string {
|
||||
return self::get_base_url() . "/api/v1/clients/{$client_id}/activation";
|
||||
}
|
||||
|
||||
public static function get_jwks_url(): string {
|
||||
return self::get_base_url() . '/v1/.well-known/jwks.json';
|
||||
}
|
||||
|
||||
/**
|
||||
* get_sessions_url
|
||||
* @return string
|
||||
*/
|
||||
public static function get_sessions_url(): string {
|
||||
return self::get_base_url() . '/api/v1/session';
|
||||
}
|
||||
|
||||
public static function get_token_url(): string {
|
||||
return self::get_base_url() . '/api/v1/oauth2/token';
|
||||
}
|
||||
|
||||
/**
|
||||
* Get clients URL
|
||||
*
|
||||
* @param string $client_id
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public static function get_clients_patch_url( string $client_id ): string {
|
||||
return self::get_base_url() . "/api/v1/clients/{$client_id}";
|
||||
}
|
||||
|
||||
/**
|
||||
* get_base_url
|
||||
* @return string
|
||||
*/
|
||||
public static function get_base_url(): string {
|
||||
return apply_filters( 'image_optimizer_connect_get_base_url', Config::BASE_URL );
|
||||
}
|
||||
|
||||
/**
|
||||
* is_valid_home_url
|
||||
* @return bool
|
||||
*/
|
||||
public static function is_valid_home_url(): bool {
|
||||
static $valid = null;
|
||||
|
||||
if ( null === $valid ) {
|
||||
if ( empty( Data::get_home_url() ) ) {
|
||||
$valid = true;
|
||||
} else {
|
||||
$valid = Data::get_home_url() === home_url();
|
||||
}
|
||||
}
|
||||
|
||||
return $valid;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Modules\Connect\Components;
|
||||
|
||||
use ImageOptimization\Modules\Connect\Classes\{
|
||||
Config,
|
||||
Data,
|
||||
GrantTypes,
|
||||
Service,
|
||||
Utils,
|
||||
};
|
||||
use ImageOptimization\Classes\Services\Client;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly
|
||||
}
|
||||
|
||||
/**
|
||||
* Class Handler
|
||||
*/
|
||||
class Handler {
|
||||
private function should_handle_auth_code(): bool {
|
||||
global $plugin_page;
|
||||
|
||||
$page_slug = explode( 'page=', Config::ADMIN_PAGE );
|
||||
|
||||
$is_connect_admin_page = false;
|
||||
|
||||
if ( ! empty( $page_slug[1] ) && $page_slug[1] === $plugin_page ) {
|
||||
$is_connect_admin_page = true;
|
||||
}
|
||||
|
||||
if ( ! $is_connect_admin_page && Config::ADMIN_PAGE === $plugin_page ) {
|
||||
$is_connect_admin_page = true;
|
||||
}
|
||||
|
||||
if ( ! $is_connect_admin_page ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$code = $_GET['code'] ?? null;
|
||||
$state = $_GET['state'] ?? null;
|
||||
|
||||
if ( empty( $code ) || empty( $state ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private function validate_nonce( $state ) {
|
||||
if ( ! wp_verify_nonce( $state, Config::STATE_NONCE ) ) {
|
||||
wp_die( 'Invalid state' );
|
||||
}
|
||||
}
|
||||
|
||||
public function handle_auth_code() {
|
||||
if ( ! $this->should_handle_auth_code() ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$code = sanitize_text_field( $_GET['code'] );
|
||||
$state = sanitize_text_field( $_GET['state'] );
|
||||
|
||||
// Check if the state is valid
|
||||
$this->validate_nonce( $state );
|
||||
|
||||
// Exchange the code for an access token and store it
|
||||
Service::get_token( GrantTypes::AUTHORIZATION_CODE, $code );
|
||||
|
||||
// Makes sure we won't stick in the mismatch limbo
|
||||
Data::set_home_url();
|
||||
|
||||
// Redirect to the redirect URI
|
||||
wp_redirect( Utils::get_redirect_uri() );
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handler constructor.
|
||||
*/
|
||||
public function __construct() {
|
||||
add_action( 'admin_init', [ $this, 'handle_auth_code' ] );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Modules\Connect;
|
||||
|
||||
use ImageOptimization\Classes\Module_Base;
|
||||
use ImageOptimization\Modules\Connect\Classes\{
|
||||
Data,
|
||||
Utils,
|
||||
};
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly
|
||||
}
|
||||
|
||||
/**
|
||||
* Class Module
|
||||
*/
|
||||
class Module extends Module_Base {
|
||||
|
||||
/**
|
||||
* Get module name.
|
||||
* Retrieve the module name.
|
||||
* @access public
|
||||
* @return string Module name.
|
||||
*/
|
||||
public function get_name() {
|
||||
return 'connect';
|
||||
}
|
||||
|
||||
/**
|
||||
* component_list
|
||||
* @return string[]
|
||||
*/
|
||||
public static function component_list() : array {
|
||||
return [
|
||||
'Handler',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* routes_list
|
||||
* @return string[]
|
||||
*/
|
||||
public static function routes_list() : array {
|
||||
return [
|
||||
'Authorize',
|
||||
'Disconnect',
|
||||
'Deactivate',
|
||||
'Deactivate_And_Disconnect',
|
||||
'Version',
|
||||
'Switch_Domain',
|
||||
];
|
||||
}
|
||||
|
||||
public static function is_connected() : bool {
|
||||
return ! ! Data::get_access_token() && Utils::is_valid_home_url();
|
||||
}
|
||||
|
||||
public static function is_active() : bool {
|
||||
// TODO: Add login to check if the function should be active or not.
|
||||
return empty( get_option( 'image_optimizer_client_data' ) );
|
||||
}
|
||||
|
||||
public function __construct() {
|
||||
$this->register_components();
|
||||
$this->register_routes();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Modules\Connect\Rest;
|
||||
|
||||
use ImageOptimization\Modules\Connect\Classes\{
|
||||
Data,
|
||||
Route_Base,
|
||||
Service,
|
||||
Utils
|
||||
};
|
||||
|
||||
use ImageOptimization\Modules\Connect\Module as Connect;
|
||||
use Throwable;
|
||||
use WP_REST_Request;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly
|
||||
}
|
||||
|
||||
/**
|
||||
* Class Authorize
|
||||
*/
|
||||
class Authorize extends Route_Base {
|
||||
public string $path = 'authorize';
|
||||
public const NONCE_NAME = 'wp_rest';
|
||||
|
||||
public function get_methods(): array {
|
||||
return [ 'POST' ];
|
||||
}
|
||||
|
||||
public function get_name(): string {
|
||||
return 'authorize';
|
||||
}
|
||||
|
||||
public function POST( WP_REST_Request $request ) {
|
||||
$valid = $this->verify_nonce_and_capability(
|
||||
$request->get_param( self::NONCE_NAME ),
|
||||
self::NONCE_NAME
|
||||
);
|
||||
|
||||
if ( is_wp_error( $valid ) ) {
|
||||
return $this->respond_error_json( [
|
||||
'message' => $valid->get_error_message(),
|
||||
'code' => 'forbidden',
|
||||
] );
|
||||
}
|
||||
|
||||
if ( Connect::is_connected() && Utils::is_valid_home_url() ) {
|
||||
return $this->respond_error_json( [
|
||||
'message' => esc_html__( 'You are already connected', 'image-optimization' ),
|
||||
'code' => 'forbidden',
|
||||
] );
|
||||
}
|
||||
|
||||
try {
|
||||
$client_id = Data::get_client_id();
|
||||
|
||||
if ( ! $client_id ) {
|
||||
$client_id = Service::register_client();
|
||||
}
|
||||
|
||||
if ( ! Utils::is_valid_home_url() ) {
|
||||
if ( $request->get_param( 'update_redirect_uri' ) ) {
|
||||
Service::update_redirect_uri();
|
||||
} else {
|
||||
return $this->respond_error_json( [
|
||||
'message' => esc_html__( 'Connected domain mismatch', 'image-optimization' ),
|
||||
'code' => 'forbidden',
|
||||
] );
|
||||
}
|
||||
}
|
||||
|
||||
$authorize_url = Utils::get_authorize_url( $client_id );
|
||||
|
||||
$additional_source_campaign = [];
|
||||
|
||||
$image_optimization_campaign = get_transient( 'elementor_image_optimization_campaign' );
|
||||
|
||||
if ( ! empty( $image_optimization_campaign['source'] ) ) {
|
||||
$additional_source_campaign['utm_source'] = $image_optimization_campaign['source'];
|
||||
}
|
||||
|
||||
if ( ! empty( $image_optimization_campaign['medium'] ) ) {
|
||||
$additional_source_campaign['utm_medium'] = $image_optimization_campaign['medium'];
|
||||
}
|
||||
|
||||
if ( ! empty( $image_optimization_campaign['campaign'] ) ) {
|
||||
$additional_source_campaign['utm_campaign'] = $image_optimization_campaign['campaign'];
|
||||
}
|
||||
|
||||
if ( ! empty( $additional_source_campaign ) ) {
|
||||
$authorize_url = add_query_arg( $additional_source_campaign, $authorize_url );
|
||||
}
|
||||
|
||||
return $this->respond_success_json( $authorize_url );
|
||||
} catch ( Throwable $t ) {
|
||||
return $this->respond_error_json( [
|
||||
'message' => $t->getMessage(),
|
||||
'code' => 'internal_server_error',
|
||||
] );
|
||||
}
|
||||
}
|
||||
}
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Modules\Connect\Rest;
|
||||
|
||||
use ImageOptimization\Modules\Connect\Classes\{
|
||||
Data,
|
||||
Route_Base,
|
||||
Service
|
||||
};
|
||||
use Throwable;
|
||||
use WP_REST_Request;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly
|
||||
}
|
||||
|
||||
/**
|
||||
* Class Disconnect
|
||||
*/
|
||||
class Deactivate_And_Disconnect extends Route_Base {
|
||||
public string $path = 'deactivate_and_disconnect';
|
||||
public const NONCE_NAME = 'wp_rest';
|
||||
|
||||
public function get_methods(): array {
|
||||
return [ 'POST' ];
|
||||
}
|
||||
|
||||
public function get_name(): string {
|
||||
return 'deactivate_and_disconnect';
|
||||
}
|
||||
|
||||
public function POST( WP_REST_Request $request ) {
|
||||
$valid = $this->verify_nonce_and_capability(
|
||||
$request->get_param( self::NONCE_NAME ),
|
||||
self::NONCE_NAME
|
||||
);
|
||||
|
||||
if ( is_wp_error( $valid ) ) {
|
||||
return $this->respond_error_json( [
|
||||
'message' => $valid->get_error_message(),
|
||||
'code' => 'forbidden',
|
||||
] );
|
||||
}
|
||||
|
||||
try {
|
||||
if ( $request->get_param( 'clear_session' ) ) {
|
||||
Data::clear_session();
|
||||
return $this->respond_success_json();
|
||||
}
|
||||
|
||||
Service::deactivate_license();
|
||||
Service::disconnect();
|
||||
|
||||
return $this->respond_success_json();
|
||||
} catch ( Throwable $t ) {
|
||||
Data::ensure_reset_connect();
|
||||
return $this->respond_error_json( [
|
||||
'message' => $t->getMessage(),
|
||||
'code' => 'internal_server_error',
|
||||
] );
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Modules\Connect\Rest;
|
||||
|
||||
use ImageOptimization\Modules\Connect\Classes\{
|
||||
Data,
|
||||
Route_Base,
|
||||
Service
|
||||
};
|
||||
use Throwable;
|
||||
use WP_REST_Request;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly
|
||||
}
|
||||
|
||||
/**
|
||||
* Class Deactivate
|
||||
*/
|
||||
class Deactivate extends Route_Base {
|
||||
public string $path = 'deactivate';
|
||||
public const NONCE_NAME = 'wp_rest';
|
||||
|
||||
public function get_methods(): array {
|
||||
return [ 'POST' ];
|
||||
}
|
||||
|
||||
public function get_name(): string {
|
||||
return 'deactivate';
|
||||
}
|
||||
|
||||
public function POST( WP_REST_Request $request ) {
|
||||
$valid = $this->verify_nonce_and_capability(
|
||||
$request->get_param( self::NONCE_NAME ),
|
||||
self::NONCE_NAME
|
||||
);
|
||||
|
||||
if ( is_wp_error( $valid ) ) {
|
||||
return $this->respond_error_json( [
|
||||
'message' => $valid->get_error_message(),
|
||||
'code' => 'forbidden',
|
||||
] );
|
||||
}
|
||||
|
||||
try {
|
||||
Service::deactivate_license();
|
||||
|
||||
return $this->respond_success_json();
|
||||
} catch ( Throwable $t ) {
|
||||
Data::ensure_reset_connect();
|
||||
return $this->respond_error_json( [
|
||||
'message' => $t->getMessage(),
|
||||
'code' => 'internal_server_error',
|
||||
] );
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Modules\Connect\Rest;
|
||||
|
||||
use ImageOptimization\Modules\Connect\Classes\{
|
||||
Data,
|
||||
Route_Base,
|
||||
Service
|
||||
};
|
||||
use Throwable;
|
||||
use WP_REST_Request;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly
|
||||
}
|
||||
|
||||
/**
|
||||
* Class Disconnect
|
||||
*/
|
||||
class Disconnect extends Route_Base {
|
||||
public string $path = 'disconnect';
|
||||
public const NONCE_NAME = 'wp_rest';
|
||||
|
||||
public function get_methods(): array {
|
||||
return [ 'POST' ];
|
||||
}
|
||||
|
||||
public function get_name(): string {
|
||||
return 'disconnect';
|
||||
}
|
||||
|
||||
public function POST( WP_REST_Request $request ) {
|
||||
$valid = $this->verify_nonce_and_capability(
|
||||
$request->get_param( self::NONCE_NAME ),
|
||||
self::NONCE_NAME
|
||||
);
|
||||
|
||||
if ( is_wp_error( $valid ) ) {
|
||||
return $this->respond_error_json( [
|
||||
'message' => $valid->get_error_message(),
|
||||
'code' => 'forbidden',
|
||||
] );
|
||||
}
|
||||
|
||||
try {
|
||||
Service::disconnect();
|
||||
|
||||
return $this->respond_success_json();
|
||||
} catch ( Throwable $t ) {
|
||||
Data::ensure_reset_connect();
|
||||
return $this->respond_error_json( [
|
||||
'message' => $t->getMessage(),
|
||||
'code' => 'internal_server_error',
|
||||
] );
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Modules\Connect\Rest;
|
||||
|
||||
use ImageOptimization\Modules\Connect\Classes\{
|
||||
Data,
|
||||
Route_Base,
|
||||
Service,
|
||||
};
|
||||
|
||||
use Throwable;
|
||||
use WP_REST_Request;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly
|
||||
}
|
||||
|
||||
/**
|
||||
* Class Switch_Domain
|
||||
*/
|
||||
class Switch_Domain extends Route_Base {
|
||||
public string $path = 'switch_domain';
|
||||
public const NONCE_NAME = 'wp_rest';
|
||||
|
||||
public function get_methods(): array {
|
||||
return [ 'POST' ];
|
||||
}
|
||||
|
||||
public function get_name(): string {
|
||||
return 'switch_domain';
|
||||
}
|
||||
|
||||
public function POST( WP_REST_Request $request ) {
|
||||
$valid = $this->verify_nonce_and_capability(
|
||||
$request->get_param( self::NONCE_NAME ),
|
||||
self::NONCE_NAME
|
||||
);
|
||||
|
||||
if ( is_wp_error( $valid ) ) {
|
||||
return $this->respond_error_json( [
|
||||
'message' => $valid->get_error_message(),
|
||||
'code' => 'forbidden',
|
||||
] );
|
||||
}
|
||||
|
||||
try {
|
||||
$client_id = Data::get_client_id();
|
||||
|
||||
if ( ! $client_id ) {
|
||||
return $this->respond_error_json( [
|
||||
'message' => esc_html__( 'Client ID not found', 'image-optimization' ),
|
||||
'code' => 'bad_request',
|
||||
] );
|
||||
}
|
||||
|
||||
Service::update_redirect_uri();
|
||||
|
||||
return $this->respond_success_json( [
|
||||
'message' => esc_html__( 'Domain updated!', 'image-optimization' ),
|
||||
] );
|
||||
} catch ( Throwable $t ) {
|
||||
return $this->respond_error_json( [
|
||||
'message' => $t->getMessage(),
|
||||
'code' => 'internal_server_error',
|
||||
] );
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Modules\Connect\Rest;
|
||||
|
||||
use ImageOptimization\Modules\Connect\Classes\{
|
||||
Data,
|
||||
Route_Base,
|
||||
Service,
|
||||
Utils
|
||||
};
|
||||
|
||||
use ImageOptimization\Modules\Connect\Module as Connect;
|
||||
use Throwable;
|
||||
use WP_REST_Request;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly
|
||||
}
|
||||
|
||||
/**
|
||||
* Class Version
|
||||
*/
|
||||
class Version extends Route_Base {
|
||||
public string $path = 'version';
|
||||
public const NONCE_NAME = 'wp_rest';
|
||||
|
||||
public function get_methods(): array {
|
||||
return [ 'GET' ];
|
||||
}
|
||||
|
||||
public function get_name(): string {
|
||||
return 'version';
|
||||
}
|
||||
|
||||
public function GET( WP_REST_Request $request ) {
|
||||
$valid = $this->verify_nonce_and_capability(
|
||||
$request->get_param( self::NONCE_NAME ),
|
||||
self::NONCE_NAME
|
||||
);
|
||||
|
||||
if ( is_wp_error( $valid ) ) {
|
||||
return $this->respond_error_json( [
|
||||
'message' => $valid->get_error_message(),
|
||||
'code' => 'forbidden',
|
||||
] );
|
||||
}
|
||||
|
||||
try {
|
||||
return $this->respond_success_json([
|
||||
'version' => 2,
|
||||
]);
|
||||
} catch ( Throwable $t ) {
|
||||
return $this->respond_error_json( [
|
||||
'message' => $t->getMessage(),
|
||||
'code' => 'internal_server_error',
|
||||
] );
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Modules\Core\Components;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
class Conflicts {
|
||||
private array $conflicting_plugins;
|
||||
|
||||
private const CONFLICTING_PLUGINS = [
|
||||
'imagify/imagify.php' => 'Imagify',
|
||||
'optimole-wp/optimole-wp.php' => 'Image optimization service by Optimole',
|
||||
'ewww-image-optimizer/ewww-image-optimizer.php' => 'EWWW Image Optimizer',
|
||||
'ewww-image-optimizer-cloud/ewww-image-optimizer-cloud.php' => 'EWWW Image Optimizer Cloud',
|
||||
'kraken-image-optimizer/kraken.php' => 'Kraken Image Optimizer',
|
||||
'shortpixel-image-optimiser/wp-shortpixel.php' => 'ShortPixel Image Optimizer',
|
||||
'wp-smushit/wp-smush.php' => 'Smush',
|
||||
'wp-smush-pro/wp-smush.php' => 'Smush PRO',
|
||||
'tiny-compress-images/tiny-compress-images.php' => 'TinyPNG - JPEG, PNG & WebP image compression',
|
||||
];
|
||||
|
||||
public function render_notice(): void {
|
||||
$conflicting_plugins_names = $this->conflicting_plugins;
|
||||
|
||||
?>
|
||||
<div class="notice notice-warning image-optimizer__notice image-optimizer__notice--warning">
|
||||
<p>
|
||||
<b>
|
||||
<?php esc_html_e(
|
||||
'Image optimizer has detected multiple active image optimization plugins.',
|
||||
'image-optimization'
|
||||
); ?>
|
||||
</b>
|
||||
|
||||
<span>
|
||||
<?php esc_html_e(
|
||||
'Having more than one may result in unexpected results.',
|
||||
'image-optimization'
|
||||
); ?>
|
||||
</span>
|
||||
</p>
|
||||
|
||||
<form action="<?php echo esc_url( admin_url( 'plugins.php' ) ); ?>" method="post" style="margin:0.5em 0;padding:2px">
|
||||
<span style="margin-inline-end: 8px;"><?php echo esc_html( join( ', ', $conflicting_plugins_names ) ); ?></span>
|
||||
|
||||
<input type="hidden" name="action" value="deactivate-selected">
|
||||
|
||||
<?php foreach ( array_keys( $this->conflicting_plugins ) as $plugin ) { ?>
|
||||
<input type="hidden" name="checked[]" value="<?php echo esc_attr( $plugin ); ?>">
|
||||
<?php } ?>
|
||||
|
||||
<input type="hidden" name="_wpnonce" value="<?php echo esc_attr( wp_create_nonce( 'bulk-plugins' ) ); ?>">
|
||||
|
||||
<input type="submit"
|
||||
style="border:none;background-color:transparent;text-decoration:underline;cursor:pointer;font-size:13px;color:#135e96;"
|
||||
value="<?php esc_html_e( 'Deactivate All', 'image-optimization' ); ?>">
|
||||
</form>
|
||||
</div>
|
||||
<?php
|
||||
}
|
||||
|
||||
public function get_conflicting_plugins(): array {
|
||||
$plugins = get_option( 'active_plugins' );
|
||||
$conflicting_plugins_file_names = array_keys( self::CONFLICTING_PLUGINS );
|
||||
$output = [];
|
||||
|
||||
foreach ( $plugins as $plugin_file_name ) {
|
||||
if ( in_array( $plugin_file_name, $conflicting_plugins_file_names, true ) ) {
|
||||
$output[ $plugin_file_name ] = self::CONFLICTING_PLUGINS[ $plugin_file_name ];
|
||||
}
|
||||
}
|
||||
|
||||
return $output;
|
||||
}
|
||||
|
||||
public function __construct() {
|
||||
$this->conflicting_plugins = $this->get_conflicting_plugins();
|
||||
|
||||
if ( ! empty( $this->conflicting_plugins ) ) {
|
||||
add_action( 'admin_notices', [ $this, 'render_notice' ] );
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Modules\Core\Components;
|
||||
|
||||
use ImageOptimization\Classes\Async_Operation\Async_Operation_Hook;
|
||||
use ImageOptimization\Classes\Logger;
|
||||
use ImageOptimization\Classes\Migration\{
|
||||
Migration_Manager,
|
||||
Migration_Meta,
|
||||
};
|
||||
|
||||
use Throwable;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
class Migrations {
|
||||
/**
|
||||
* @async
|
||||
* @param string $migration_name
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function run_migration( string $migration_name ): bool {
|
||||
$migration_class = Migration_Manager::get_migration( $migration_name );
|
||||
|
||||
if ( ! $migration_class ) {
|
||||
Logger::log(
|
||||
Logger::LEVEL_ERROR,
|
||||
"Migration class for `$migration_name` does not exist."
|
||||
);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
if ( ! method_exists( $migration_class, 'run' ) || ! is_callable( [ $migration_class, 'run' ] ) ) {
|
||||
Logger::log(
|
||||
Logger::LEVEL_ERROR,
|
||||
"The run method does not exist or is not static in the class `$migration_class`."
|
||||
);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
$migration_class::run();
|
||||
|
||||
( new Migration_Meta() )
|
||||
->add_migration_passed( $migration_name )
|
||||
->save();
|
||||
|
||||
Logger::log(
|
||||
Logger::LEVEL_INFO,
|
||||
"The migration `$migration_name` successfully executed."
|
||||
);
|
||||
} catch ( Throwable $t ) {
|
||||
Logger::log(
|
||||
Logger::LEVEL_ERROR,
|
||||
"Error while running the migration `$migration_name`: " . $t->getMessage()
|
||||
);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public function __construct() {
|
||||
add_action( Async_Operation_Hook::DB_MIGRATION, [ $this, 'run_migration' ] );
|
||||
}
|
||||
}
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Modules\Core\Components;
|
||||
|
||||
use ImageOptimization\Classes\Utils;
|
||||
use ImageOptimization\Modules\Settings\Module;
|
||||
use ImageOptimization\Plugin;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
class Not_Connected_Modal {
|
||||
const NOT_CONNECTED_MODAL_SLUG = 'image-optimizer-not-connected-modal';
|
||||
|
||||
public function render_not_connected_modal() {
|
||||
add_thickbox(); ?>
|
||||
|
||||
<div
|
||||
id="<?php echo esc_html( self::NOT_CONNECTED_MODAL_SLUG ); ?>"
|
||||
style="display:none;"
|
||||
>
|
||||
<div class="image-optimizer__modal image-optimizer__modal--not-connected" data-modal-slug="<?php echo esc_attr( self::NOT_CONNECTED_MODAL_SLUG ); ?>">
|
||||
<button class="image-optimizer__modal--not-connected-close">
|
||||
<svg viewBox="0 0 24 24" width="24" height="24">
|
||||
<path fill-rule="evenodd" clip-rule="evenodd" d="M18.5303 5.46967C18.8232 5.76256 18.8232 6.23744 18.5303 6.53033L6.53033 18.5303C6.23744 18.8232 5.76256 18.8232 5.46967 18.5303C5.17678 18.2374 5.17678 17.7626 5.46967 17.4697L17.4697 5.46967C17.7626 5.17678 18.2374 5.17678 18.5303 5.46967Z"></path><path fill-rule="evenodd" clip-rule="evenodd" d="M5.46967 5.46967C5.76256 5.17678 6.23744 5.17678 6.53033 5.46967L18.5303 17.4697C18.8232 17.7626 18.8232 18.2374 18.5303 18.5303C18.2374 18.8232 17.7626 18.8232 17.4697 18.5303L5.46967 6.53033C5.17678 6.23744 5.17678 5.76256 5.46967 5.46967Z"></path>
|
||||
</svg>
|
||||
</button>
|
||||
<img src="<?php echo esc_url( plugins_url( 'assets/static/connect.jpg', dirname( __FILE__, 3 ) ) ); ?>" alt="<?php esc_html_e( 'Connect now', 'image-optimization' ); ?>">
|
||||
<h2><?php esc_html_e( 'Let\'s start optimizing your images!', 'image-optimization' ); ?></h2>
|
||||
<p><?php esc_html_e( 'Connect the Image Optimizer plugin to speed up your site. We\'ll handle the rest.', 'image-optimization' ); ?></p>
|
||||
<ul>
|
||||
<li><?php esc_html_e( 'Boost site speed and compress images', 'image-optimization' ); ?></li>
|
||||
<li><?php esc_html_e( 'Bulk optimization for faster processing', 'image-optimization' ); ?></li>
|
||||
<li><?php esc_html_e( 'Convert to AVIF and WebP formats', 'image-optimization' ); ?></li>
|
||||
<li><?php esc_html_e( 'Works across unlimited websites', 'image-optimization' ); ?></li>
|
||||
</ul>
|
||||
<a href="<?php echo admin_url( 'admin.php?page=' . Module::SETTING_BASE_SLUG . '&action=connect' ); ?>" class="image-optimizer__modal--not-connected-connect">
|
||||
<?php esc_html_e( 'Connect to start', 'image-optimization' ); ?>
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
<script>
|
||||
jQuery( document ).ready( function( $ ) {
|
||||
setTimeout(() => {
|
||||
const TB_WIDTH = 630;
|
||||
const TB_HEIGHT = 620;
|
||||
const msInOneDay = 24 * 60 * 60 * 1000;
|
||||
const time_dismissed = localStorage.getItem('<?php echo self::NOT_CONNECTED_MODAL_SLUG; ?>');
|
||||
const show_notice = !time_dismissed || Date.now() - time_dismissed >= msInOneDay;
|
||||
const $modal = $( '[data-modal-slug="<?php echo esc_js( self::NOT_CONNECTED_MODAL_SLUG ); ?>"]' );
|
||||
|
||||
if (show_notice) {
|
||||
tb_show( '', `/?TB_inline&inlineId=<?php echo esc_js( self::NOT_CONNECTED_MODAL_SLUG ); ?>&height=${TB_HEIGHT - 40}&width=${TB_WIDTH - 30}&modal=true` );
|
||||
$modal.parents('#TB_window')
|
||||
.width(TB_WIDTH)
|
||||
.height(TB_HEIGHT)
|
||||
.css('margin-left', - TB_WIDTH / 2)
|
||||
.css('margin-top', - TB_HEIGHT / 2)
|
||||
.css('top', '50%');
|
||||
|
||||
const hideModal = (e) => {
|
||||
e.preventDefault();
|
||||
localStorage.setItem('<?php echo esc_js( self::NOT_CONNECTED_MODAL_SLUG ); ?>', Date.now().toString());
|
||||
tb_remove();
|
||||
}
|
||||
const $connectButton = $modal.find( '.image-optimizer__modal--not-connected-connect' );
|
||||
const $closeButton = $modal.find( '.image-optimizer__modal--not-connected-close' );
|
||||
|
||||
$connectButton.on( 'click', function (e) {
|
||||
hideModal(e);
|
||||
window.open( $( this ).attr( 'href' ), '_blank' ).focus();
|
||||
} );
|
||||
$closeButton.on( 'click', function (e) {
|
||||
hideModal(e);
|
||||
} );
|
||||
} else {
|
||||
$modal.remove();
|
||||
}
|
||||
}, 0);
|
||||
} );
|
||||
</script>
|
||||
<?php
|
||||
}
|
||||
|
||||
|
||||
|
||||
public function __construct() {
|
||||
add_action('current_screen', function () {
|
||||
// @var ImageOptimizer/Modules/ConnectManager/Module
|
||||
$module = Plugin::instance()->modules_manager->get_modules( 'connect-manager' );
|
||||
|
||||
if ( $module->connect_instance->is_connected() || ! Utils::user_is_admin() ) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
Utils::is_plugin_settings_page() ||
|
||||
Utils::is_bulk_optimization_page()
|
||||
) {
|
||||
add_action( 'admin_notices', [ $this, 'render_not_connected_modal' ] );
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Modules\Core\Components;
|
||||
|
||||
use ImageOptimization\Classes\Image\Image_Query_Builder;
|
||||
use ImageOptimization\Classes\Utils;
|
||||
use ImageOptimization\Plugin;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
class Not_Connected {
|
||||
const NOT_CONNECTED_NOTICE_SLUG = 'image-optimizer-not-connected';
|
||||
|
||||
public function render_not_connected_notice() {
|
||||
if ( Pointers::is_dismissed( self::NOT_CONNECTED_NOTICE_SLUG ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
?>
|
||||
<div class="notice notice-info notice is-dismissible image-optimizer__notice image-optimizer__notice--pink"
|
||||
data-notice-slug="<?php echo esc_attr( self::NOT_CONNECTED_NOTICE_SLUG ); ?>">
|
||||
<div class="image-optimizer__icon-block">
|
||||
<svg width="32" height="32" fill="none" role="presentation">
|
||||
<rect width="32" height="32" fill="#FF7BE5" rx="16"/>
|
||||
<path fill="#fff" d="M10.508 4.135a.125.125 0 0 0-.236 0l-1.183 3.42a.125.125 0 0 1-.078.078L5.553 8.8a.125.125 0 0 0 0 .237l3.458 1.166a.125.125 0 0 1 .078.078l1.183 3.42a.125.125 0 0 0 .236 0l1.182-3.42a.125.125 0 0 1 .078-.078l3.458-1.166a.125.125 0 0 0 0-.237l-3.458-1.167a.125.125 0 0 1-.078-.077l-1.182-3.421ZM17.425 12.738v3.683l-4.073 4.582L26.495 9.598a.125.125 0 0 1 .207.094v14.851a.125.125 0 0 1-.125.125H5.874a.125.125 0 0 1-.09-.212l11.427-11.805a.125.125 0 0 1 .214.087Z"/>
|
||||
</svg>
|
||||
</div>
|
||||
|
||||
<p>
|
||||
<b>
|
||||
<?php esc_html_e(
|
||||
'Image Optimizer is not connected right now. To start optimizing your images, please connect your account.',
|
||||
'image-optimization'
|
||||
); ?>
|
||||
</b>
|
||||
|
||||
<span>
|
||||
<a href="<?php echo admin_url( 'admin.php?page=' . \ImageOptimization\Modules\Settings\Module::SETTING_BASE_SLUG . '&action=connect' ); ?>">
|
||||
<?php esc_html_e(
|
||||
'Connect now',
|
||||
'image-optimization'
|
||||
); ?>
|
||||
</a>
|
||||
</span>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
const onNotConnectedNoticeClose = () => {
|
||||
const pointer = '<?php echo esc_js( self::NOT_CONNECTED_NOTICE_SLUG ); ?>';
|
||||
|
||||
return wp.ajax.post( 'image_optimizer_pointer_dismissed', {
|
||||
data: {
|
||||
pointer,
|
||||
},
|
||||
nonce: '<?php echo esc_js( wp_create_nonce( 'image-optimization-pointer-dismissed' ) ); ?>',
|
||||
} );
|
||||
}
|
||||
|
||||
jQuery( document ).ready( function( $ ) {
|
||||
setTimeout(() => {
|
||||
const $closeButton = $( '[data-notice-slug="<?php echo esc_js( self::NOT_CONNECTED_NOTICE_SLUG ); ?>"] .notice-dismiss' )
|
||||
|
||||
$closeButton
|
||||
.first()
|
||||
.on( 'click', onNotConnectedNoticeClose )
|
||||
|
||||
$( '[data-notice-slug="<?php echo esc_js( self::NOT_CONNECTED_NOTICE_SLUG ); ?>"] a' )
|
||||
.first()
|
||||
.on( 'click', function ( e ) {
|
||||
e.preventDefault();
|
||||
|
||||
onNotConnectedNoticeClose().promise().done(() => {
|
||||
window.open( $( this ).attr( 'href' ), '_blank' ).focus();
|
||||
|
||||
$closeButton.click();
|
||||
});
|
||||
})
|
||||
}, 0);
|
||||
} );
|
||||
</script>
|
||||
<?php
|
||||
}
|
||||
|
||||
public function add_media_menu_badge( $parent_file ) {
|
||||
global $menu;
|
||||
|
||||
foreach ( $menu as &$item ) {
|
||||
if ( 'upload.php' === $item[2] ) {
|
||||
$item[0] .= ' <span class="update-plugins count-1"><span class="plugin-count">1</span></span>';
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return $parent_file;
|
||||
}
|
||||
|
||||
|
||||
public function __construct() {
|
||||
add_action('current_screen', function () {
|
||||
if ( ! Utils::user_is_admin() ) {
|
||||
return;
|
||||
}
|
||||
|
||||
// @var ImageOptimizer/Modules/ConnectManager/Module
|
||||
$module = Plugin::instance()->modules_manager->get_modules( 'connect-manager' );
|
||||
|
||||
if ( $module->connect_instance->is_connected() || ! $module->connect_instance->is_valid_home_url() ) {
|
||||
return;
|
||||
}
|
||||
|
||||
add_filter( 'parent_file', [ $this, 'add_media_menu_badge' ] );
|
||||
|
||||
if (
|
||||
Utils::is_media_page() ||
|
||||
Utils::is_plugin_page() ||
|
||||
Utils::is_single_attachment_page() ||
|
||||
Utils::is_media_upload_page() ||
|
||||
Utils::is_wp_dashboard_page() ||
|
||||
Utils::is_wp_updates_page()
|
||||
) {
|
||||
add_action( 'admin_notices', [ $this, 'render_not_connected_notice' ] );
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Modules\Core\Components;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
class Pointers {
|
||||
const DISMISSED_POINTERS_META_KEY = 'image_optimizer_dismissed_pointers';
|
||||
|
||||
public function dismiss_pointers() {
|
||||
if ( empty( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'image-optimization-pointer-dismissed' ) ) {
|
||||
wp_send_json_error( [ 'message' => 'Invalid nonce' ] );
|
||||
}
|
||||
|
||||
$pointer = sanitize_text_field( $_POST['data']['pointer'] ) ?? null;
|
||||
|
||||
if ( empty( $pointer ) ) {
|
||||
wp_send_json_error( [ 'message' => 'The pointer id must be provided' ] );
|
||||
}
|
||||
|
||||
$pointer = explode( ',', $pointer );
|
||||
|
||||
$user_dismissed_meta = get_user_meta( get_current_user_id(), self::DISMISSED_POINTERS_META_KEY, true );
|
||||
|
||||
if ( ! $user_dismissed_meta ) {
|
||||
$user_dismissed_meta = [];
|
||||
}
|
||||
|
||||
foreach ( $pointer as $item ) {
|
||||
$user_dismissed_meta[ $item ] = true;
|
||||
}
|
||||
|
||||
update_user_meta( get_current_user_id(), self::DISMISSED_POINTERS_META_KEY, $user_dismissed_meta );
|
||||
|
||||
wp_send_json_success( [] );
|
||||
}
|
||||
|
||||
public static function is_dismissed( string $slug ): bool {
|
||||
$meta = (array) get_user_meta( get_current_user_id(), self::DISMISSED_POINTERS_META_KEY, true );
|
||||
|
||||
return key_exists( $slug, $meta );
|
||||
}
|
||||
|
||||
public function __construct() {
|
||||
add_action( 'wp_ajax_image_optimizer_pointer_dismissed', [ $this, 'dismiss_pointers' ] );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Modules\Core\Components;
|
||||
|
||||
use DateTime;
|
||||
use ImageOptimization\Classes\Client\Client;
|
||||
use ImageOptimization\Classes\Utils;
|
||||
use ImageOptimization\Plugin;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
class Renewal_Notice {
|
||||
const RENEWAL_NOTICE_SLUG = 'image-optimizer-renewal-notice';
|
||||
|
||||
public ?int $days_diff = null;
|
||||
|
||||
public function date_diff_from_current( $date ) {
|
||||
$current_date = new DateTime(); // Current date
|
||||
$given_date = new DateTime( $date );
|
||||
|
||||
$interval = $current_date->diff( $given_date );
|
||||
|
||||
$this->days_diff = $interval->invert ? -$interval->days : $interval->days;
|
||||
|
||||
return $this->days_diff;
|
||||
}
|
||||
|
||||
public function get_renewal_text(): array {
|
||||
if ( $this->days_diff <= 30 && $this->days_diff > 0 ) {
|
||||
return [
|
||||
'title' => esc_html__( 'Image Optimizer Expires Soon!', 'image-optimization' ),
|
||||
'description' => esc_html__( 'Renew your subscription to maintain optimized images, faster website load times, and high performance.', 'image-optimization' ),
|
||||
'btn' => esc_html__( 'Turn Auto Renew On', 'image-optimization' ),
|
||||
'link' => esc_url( 'https://go.elementor.com/io-renew-30/' ),
|
||||
];
|
||||
}
|
||||
if ( $this->days_diff <= 0 && $this->days_diff > -7 ) {
|
||||
return [
|
||||
'title' => esc_html__( 'Image Optimizer Has Expired!', 'image-optimization' ),
|
||||
'description' => esc_html__( 'Renew your license today to continue enjoying premium image optimization and fast load times.', 'image-optimization' ),
|
||||
'btn' => esc_html__( 'Renew Now', 'image-optimization' ),
|
||||
'link' => esc_url( 'https://go.elementor.com/io-renew-expire/' ),
|
||||
];
|
||||
}
|
||||
return [
|
||||
'title' => esc_html__( 'It’s Not Too Late! Renew Image Optimizer', 'image-optimization' ),
|
||||
'description' => esc_html__( 'Reactivate your license to get back to top image performance.', 'image-optimization' ),
|
||||
'btn' => esc_html__( 'Renew and Optimize', 'image-optimization' ),
|
||||
'link' => esc_url( 'https://go.elementor.com/io-renew-post-expire/' ),
|
||||
];
|
||||
}
|
||||
|
||||
public function render_renewal_notice() {
|
||||
$text = $this->get_renewal_text();
|
||||
?>
|
||||
<div class="notice notice-info is-dismissible image-optimizer__notice image-optimizer__notice--error image-optimizer__renewal-notice"
|
||||
data-notice-slug="<?php echo esc_attr( self::RENEWAL_NOTICE_SLUG ); ?>" style="display:none;">
|
||||
<div class="image-optimizer__content-block">
|
||||
<svg width="32" height="32" fill="none" role="presentation">
|
||||
<rect width="32" height="32" fill="#232629" rx="16"/>
|
||||
<path fill="#fff" d="M10.508 4.135a.125.125 0 0 0-.236 0l-1.183 3.42a.125.125 0 0 1-.078.078L5.553 8.8a.125.125 0 0 0 0 .237l3.458 1.166a.125.125 0 0 1 .078.078l1.183 3.42a.125.125 0 0 0 .236 0l1.182-3.42a.125.125 0 0 1 .078-.078l3.458-1.166a.125.125 0 0 0 0-.237l-3.458-1.167a.125.125 0 0 1-.078-.077l-1.182-3.421ZM17.425 12.738v3.683l-4.073 4.582L26.495 9.598a.125.125 0 0 1 .207.094v14.851a.125.125 0 0 1-.125.125H5.874a.125.125 0 0 1-.09-.212l11.427-11.805a.125.125 0 0 1 .214.087Z"/>
|
||||
</svg>
|
||||
<p>
|
||||
<b>
|
||||
<?php echo $text['title']; ?>
|
||||
</b>
|
||||
<span>
|
||||
<?php echo $text['description']; ?>
|
||||
</span>
|
||||
</p>
|
||||
</div>
|
||||
<a href="<?php echo $text['link']; ?>" target="_blank" rel="noopener noreferrer">
|
||||
<?php echo $text['btn']; ?>
|
||||
</a>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
jQuery( document ).ready( function( $ ) {
|
||||
setTimeout(() => {
|
||||
const $msInOneDay = 24 * 60 * 60 * 1000;
|
||||
const $time_dismissed = localStorage.getItem('<?php echo self::RENEWAL_NOTICE_SLUG; ?>');
|
||||
const $show_notice = !$time_dismissed || Date.now() - $time_dismissed >= $msInOneDay;
|
||||
|
||||
const $notice = $( '[data-notice-slug="<?php echo esc_js( self::RENEWAL_NOTICE_SLUG ); ?>"]' );
|
||||
const $closeButton = $( '[data-notice-slug="<?php echo esc_js( self::RENEWAL_NOTICE_SLUG ); ?>"] .notice-dismiss' );
|
||||
|
||||
if ($show_notice) {
|
||||
$notice.css('display', 'flex');
|
||||
$closeButton.on( 'click', function () {
|
||||
localStorage.setItem('<?php echo esc_js( self::RENEWAL_NOTICE_SLUG ); ?>', Date.now().toString());
|
||||
} );
|
||||
} else {
|
||||
$notice.remove();
|
||||
}
|
||||
}, 0);
|
||||
} );
|
||||
</script>
|
||||
<?php
|
||||
}
|
||||
|
||||
public function add_media_menu_badge( $parent_file ) {
|
||||
global $menu;
|
||||
|
||||
foreach ( $menu as &$item ) {
|
||||
if ( 'upload.php' === $item[2] ) {
|
||||
$item[0] .= ' <span class="update-plugins count-1"><span class="plugin-count">1</span></span>';
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return $parent_file;
|
||||
}
|
||||
|
||||
|
||||
public function __construct() {
|
||||
add_action('current_screen', function () {
|
||||
// @var ImageOptimizer/Modules/ConnectManager/Module
|
||||
$module = Plugin::instance()->modules_manager->get_modules( 'connect-manager' );
|
||||
|
||||
if ( ! $module->connect_instance->is_connected() || ! Utils::user_is_admin() ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$info = Client::get_subscription_info();
|
||||
|
||||
if ( empty( $info ) || $info->auto_renew || $this->date_diff_from_current( ( $info->date_next_payment ?? $info->date_end ) ) > 30 ) {
|
||||
return;
|
||||
}
|
||||
|
||||
add_filter( 'parent_file', [ $this, 'add_media_menu_badge' ] );
|
||||
|
||||
if (
|
||||
Utils::is_media_page() ||
|
||||
Utils::is_plugin_page() ||
|
||||
Utils::is_single_attachment_page() ||
|
||||
Utils::is_media_upload_page() ||
|
||||
Utils::is_wp_dashboard_page() ||
|
||||
Utils::is_wp_updates_page()
|
||||
) {
|
||||
add_action( 'admin_notices', [ $this, 'render_renewal_notice' ] );
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,264 @@
|
||||
<?php
|
||||
|
||||
namespace ImageOptimization\Modules\Core\Components;
|
||||
|
||||
use ImageOptimization\Classes\Image\Image_Query_Builder;
|
||||
use ImageOptimization\Classes\Utils;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
class User_Feedback {
|
||||
public const NOTICE_FEEDBACK_LINK = 'https://go.elementor.com/io-wp-dash-notice-review';
|
||||
public const FOOTER_FEEDBACK_LINK = 'https://go.elementor.com/io-wp-dash-footer-review';
|
||||
private const FIRST_IMAGE_OPTIMIZED_FEEDBACK_SLUG = 'image-optimizer-first-image-optimized-feedback';
|
||||
private const THIRD_OF_IMAGES_OPTIMIZED_FEEDBACK_SLUG = 'image-optimizer-third-images-optimized-feedback';
|
||||
|
||||
/**
|
||||
* Checks if the notice after the first optimization should be rendered.
|
||||
*
|
||||
* @param bool $check_location
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function should_render_first_optimized_notice( bool $check_location = true ): bool {
|
||||
if ( Pointers::is_dismissed( self::FIRST_IMAGE_OPTIMIZED_FEEDBACK_SLUG ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$is_wrong_page = ( ! Utils::is_media_page() && ! Utils::is_plugin_page() && ! Utils::is_single_attachment_page() ) ||
|
||||
Utils::is_plugin_settings_page();
|
||||
|
||||
if ( $check_location && $is_wrong_page ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$optimized_image_query = ( new Image_Query_Builder() )
|
||||
->return_optimized_images()
|
||||
->set_paging_size( 1 )
|
||||
->execute();
|
||||
|
||||
if ( ! $optimized_image_query->post_count ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the notice should be rendered after the one third of images were optimized.
|
||||
*
|
||||
* @param bool $check_location
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function should_render_third_optimized_notice( bool $check_location = true ): bool {
|
||||
if ( Pointers::is_dismissed( self::THIRD_OF_IMAGES_OPTIMIZED_FEEDBACK_SLUG ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ( $check_location && ! Utils::is_plugin_settings_page() ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$images_query = ( new Image_Query_Builder() )
|
||||
->execute();
|
||||
|
||||
$optimized_images_query = ( new Image_Query_Builder() )
|
||||
->return_optimized_images()
|
||||
->execute();
|
||||
|
||||
if ( ! $optimized_images_query->post_count ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$optimized_percentage = round( $optimized_images_query->post_count / $images_query->post_count * 100 );
|
||||
|
||||
if ( $optimized_percentage < 33.33 ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders the notice after the first optimization.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function render_first_optimized_notice() {
|
||||
?>
|
||||
<div class="notice is-dismissible notice-success notice image-optimizer__notice image-optimizer__notice--success image-optimizer__notice--feedback"
|
||||
data-notice-slug="<?php echo esc_attr( self::FIRST_IMAGE_OPTIMIZED_FEEDBACK_SLUG ); ?>">
|
||||
<p>
|
||||
<b>
|
||||
<?php esc_html_e(
|
||||
'Your image has been optimized!',
|
||||
'image-optimization'
|
||||
); ?>
|
||||
</b>
|
||||
|
||||
<span>
|
||||
<?php printf(
|
||||
__(
|
||||
'If you enjoyed using Image Optimizer, consider leaving a <a href="%1$s" aria-label="%2$s" target="_blank"
|
||||
rel="noopener noreferrer">★★★★★</a> review to spread the word.',
|
||||
'image-optimization'
|
||||
),
|
||||
esc_url( self::NOTICE_FEEDBACK_LINK ),
|
||||
esc_attr__( 'Five stars', 'image-optimization' )
|
||||
); ?>
|
||||
</span>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
const onClose = () => {
|
||||
const pointer = '<?php
|
||||
echo $this->should_render_third_optimized_notice( false ) ?
|
||||
esc_js( join( ',', [ static::FIRST_IMAGE_OPTIMIZED_FEEDBACK_SLUG, static::THIRD_OF_IMAGES_OPTIMIZED_FEEDBACK_SLUG ] ) ) :
|
||||
esc_js( static::FIRST_IMAGE_OPTIMIZED_FEEDBACK_SLUG )
|
||||
?>';
|
||||
|
||||
return wp.ajax.post( 'image_optimizer_pointer_dismissed', {
|
||||
data: {
|
||||
pointer,
|
||||
},
|
||||
nonce: '<?php echo esc_js( wp_create_nonce( 'image-optimization-pointer-dismissed' ) ); ?>',
|
||||
} );
|
||||
}
|
||||
|
||||
jQuery( document ).ready( function( $ ) {
|
||||
setTimeout(() => {
|
||||
const $closeButton = $( '[data-notice-slug="<?php echo esc_js( self::FIRST_IMAGE_OPTIMIZED_FEEDBACK_SLUG ); ?>"] .notice-dismiss' )
|
||||
|
||||
$closeButton
|
||||
.first()
|
||||
.on( 'click', onClose )
|
||||
|
||||
$( '[data-notice-slug="<?php echo esc_js( self::FIRST_IMAGE_OPTIMIZED_FEEDBACK_SLUG ); ?>"] a' )
|
||||
.first()
|
||||
.on( 'click', function ( e ) {
|
||||
e.preventDefault();
|
||||
|
||||
onClose().promise().done(() => {
|
||||
window.open( $( this ).attr( 'href' ), '_blank' ).focus();
|
||||
|
||||
$closeButton.click();
|
||||
});
|
||||
})
|
||||
}, 0);
|
||||
} );
|
||||
</script>
|
||||
<?php
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders the notice after the one third of images were optimized.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function render_third_optimized_notice() {
|
||||
?>
|
||||
<div class="notice is-dismissible notice-success notice image-optimizer__notice image-optimizer__notice--success image-optimizer__notice--feedback"
|
||||
data-notice-slug="<?php echo esc_attr( self::THIRD_OF_IMAGES_OPTIMIZED_FEEDBACK_SLUG ); ?>">
|
||||
<p>
|
||||
<b>
|
||||
<?php esc_html_e(
|
||||
'Thanks for using Image Optimizer!',
|
||||
'image-optimization'
|
||||
); ?>
|
||||
</b>
|
||||
|
||||
<span>
|
||||
<?php printf(
|
||||
__(
|
||||
'If you\'ve enjoyed it, consider leaving a <a href="%1$s" aria-label="%2$s" target="_blank"
|
||||
rel="noopener noreferrer">★★★★★</a> review to spread the word.',
|
||||
'image-optimization'
|
||||
),
|
||||
esc_url( self::NOTICE_FEEDBACK_LINK ),
|
||||
esc_attr__( 'Five stars', 'image-optimization' )
|
||||
); ?>
|
||||
</span>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
const onClose = () => {
|
||||
const pointer = '<?php
|
||||
echo $this->should_render_first_optimized_notice( false ) ?
|
||||
esc_js( join( ',', [ static::FIRST_IMAGE_OPTIMIZED_FEEDBACK_SLUG, static::THIRD_OF_IMAGES_OPTIMIZED_FEEDBACK_SLUG ] ) ) :
|
||||
esc_js( static::THIRD_OF_IMAGES_OPTIMIZED_FEEDBACK_SLUG )
|
||||
?>';
|
||||
|
||||
return wp.ajax.post( 'image_optimizer_pointer_dismissed', {
|
||||
data: {
|
||||
pointer,
|
||||
},
|
||||
nonce: '<?php echo esc_js( wp_create_nonce( 'image-optimization-pointer-dismissed' ) ); ?>',
|
||||
} );
|
||||
}
|
||||
|
||||
jQuery( document ).ready( function( $ ) {
|
||||
setTimeout(() => {
|
||||
const $closeButton = $( '[data-notice-slug="<?php echo esc_js( self::THIRD_OF_IMAGES_OPTIMIZED_FEEDBACK_SLUG ); ?>"] .notice-dismiss' );
|
||||
|
||||
$closeButton
|
||||
.first()
|
||||
.on( 'click', onClose)
|
||||
|
||||
$( '[data-notice-slug="<?php echo esc_js( self::THIRD_OF_IMAGES_OPTIMIZED_FEEDBACK_SLUG ); ?>"] a' )
|
||||
.first()
|
||||
.on( 'click', function ( e ) {
|
||||
e.preventDefault();
|
||||
|
||||
onClose().promise().done(() => {
|
||||
window.open( $( this ).attr( 'href' ), '_blank' ).focus();
|
||||
|
||||
$closeButton.click();
|
||||
});
|
||||
})
|
||||
}, 0);
|
||||
} );
|
||||
</script>
|
||||
<?php
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders the admin footer feedback notice.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function add_leave_feedback_footer_text(): void {
|
||||
printf(
|
||||
__( '<b>Found Image Optimizer helpful?</b> Leave us a <a href="%1$s" aria-label="%2$s" target="_blank"
|
||||
rel="noopener noreferrer">★★★★★</a> rating!',
|
||||
'image-optimization'
|
||||
),
|
||||
esc_url( self::FOOTER_FEEDBACK_LINK ),
|
||||
esc_attr__( 'Five stars', 'image-optimization' )
|
||||
);
|
||||
}
|
||||
|
||||
public function __construct() {
|
||||
add_action('current_screen', function () {
|
||||
if ( ! Utils::user_is_admin() ) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ( $this->should_render_first_optimized_notice() ) {
|
||||
add_action( 'admin_notices', [ $this, 'render_first_optimized_notice' ] );
|
||||
}
|
||||
|
||||
if ( $this->should_render_third_optimized_notice() ) {
|
||||
add_action( 'admin_notices', [ $this, 'render_third_optimized_notice' ] );
|
||||
}
|
||||
|
||||
if ( Utils::is_media_page() || Utils::is_plugin_page() || Utils::is_single_attachment_page() ) {
|
||||
add_filter( 'admin_footer_text', [ $this, 'add_leave_feedback_footer_text' ] );
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user