JFIF $ d d 7 * Z qn )ZP 0 !1 A "#a$2Qr D8 a Ri [f \m I ykI w0 c u F c Rı?lO7 к _f˓ [C $殷WF< _W ԣ s Kc ëI zyQy /_LK ℂ ;C",p F A : /] =H ~ , l s / 9 ć: [=/#f ; ) x { ٛE Q )~ = 𘙲r*2~ a _V = ' ku m F D } KYYC )( { * g& f `툪 r y ` = ^ c J. I ]( * `wq 1dđ #̩ ͑ 0 ; H ] u 搂 @:~ ו K L N s h } O I R* 8 :2 ! lD JV o ( 3 = M ( z Ȱ+i *N A r6K n S l ) ! J J Ӂ* % ݉?|D } d5: eP0 R; {$X' x F @ .ÊB {,WJ uQ ɲRI ;9 Q E琯 6 2fT .DU J ;*c P A\IL Nj! J ۱+ O\ ͔ ] ޒ S J ȧ c%A N ol ՎprU L Zԛe r E2= X D Xg VQeӓ k y P7 U* o m Q I s ,K `) 6\G3t?pgjr m ۛجw luGt f h 9uyP 0D;Uڽ"OXl i f $ ) &|ML 0 Z rm1 [ H XP l P R0 'G=i 2N +0 e 2 ]] 9 VT P O 7 h(F * 癈 ' = Q VZD F,d ߬ ~ T X G[ `le 69C R(!S2! P < 0 x < !1AQ "Raq 02Br #S CTb ? Ζ "]mH5WR 7 k.ۛ ! } Q~ + yԏ z |@ T20 S~ K e k *zF f^2X *( @ 8 r ? C I uI|֓>^Ex LgNU Y+{.R Ѫ τV YT D I 6 2 '8Y2 7'\T P.6 d &˦ @V q i |8 -O Ε ] ʔ U= T L 8= ;6c | !qfF3 a ů& ~$ l} 'NW U s$U k^S V : U#6w + +s &r+n ڐ { @ 29gL u " T Ù M=6 (^ "7 r}=6Yݾ lC u hquymp Ǧ G jhs ǜNl ɻ} o 7 #S6 a w 4 ! OS r D 5 7 % | ?x> L | / nD 6?/8 w # [ ) L 7 +6〼T A T g ! %5 Mm Z /c -{1_Je "| ^$ 'O & ޱմ < H vNqϡQ$ < 6 &Nݛ ֨tǻN (9 n ru~'όN sMG& ,uH Kw *Ī 5@ u6 BԒ i YN * f 0 _ GhKW u lT <nj- 0{ M L~ | /a v\ E = ?1 \ɟuq Ђ Y O a K ޡP q $ H8o Q˼EV ~ k 0 h' L Pp M -M" m^ !6l nմ 쮝C U T . ! :vMǨb h ډ Vc r @~p # !1QAa q ? AL0L x LU 4 d ; x " 16ad0 7.\ߋ 0 = P l v/ " c A Ay A|2pO8"d MV #1] = \ " ˡ ] k v I9 d ۓ & q ) ǐq E ꞅ v "P )q X &Q З non]я u ג./ ; gZ$ M QР 2M ]h ni 0 P $ێ 3CɏGjώy : m c # S_ l@ '_ \m|C 2`K _ 1 cIvGc $? PCQ S+D ? K aײ k Fr b 8 ύ NEدg ĝ U 3 6 #Ik+ v { v i ( ވ ? a e) X xy/*@Q Ǽ Ծ ) $ IWO l c G; !i k{ gOŀ L ('x T rb $ w) R $ & N1E td U3Uȉ1p M"N* (DNy d96.(jQ) X 5 c QɎMy W ? Q *!R > 6=7)Xj 5`J ] e 8%t ! + ' ! 1Q 5 !1 AQaq ё #2 "0BRb ? G t^ ## .l lQ T $ v , ,m 㵜5u bV =sY+ @d { N ! dn O < .- B; _w J t 6;Q Jd. Q c%p{ 1 ,sND dF H I0 Гo X ш e黅X ۢ F :)[ F G X ƹ / w _c MeD ,ʡc c . W D tA $ j@ : ) - #u c1< @ۗ9F ) KJ- hpP] _ x [ q B lb p ʖ w q " LFGd ƶ * s +ډ_Zc " ? % t[I P 6 J ]# =ɺ V v v CGs Gh1 > )6 |e y ? L ӣ m,4 G W Ui ` ] uJVo VDG< SB 6ϏQ @ TiU l y O U 0 kfV ~ ~}S Z @ *WU Ui ## ; s /[ = ! 7}" W N ] ' (L ! ~ y5 g9T̅J kbM' +s :S +B) v @ M j e C f j E 0 Y\Qn z G 1 д~ W o{T 9?` Rm yhsy3 !HAD ] m c1 ~ 2 L S u7x T ;j$ `} 4-> L# vzŏ I L S ֭ T { r jGK C ; b pU= - ` Bs K. S F w4 M q] Z dH S 0 ) tLg
<?php
namespace EnableMediaReplace\Externals;
if (! defined('ABSPATH')) {
exit; // Exit if accessed directly.
}
use EnableMediaReplace\ShortPixelLogger\ShortPixelLogger as Log;
use EnableMediaReplace\Notices\NoticeController as Notices;
class WPOffload
{
private static $instance;
private $as3cf;
private $sources; // cache for url > source_id lookup, to prevent duplicate queries.
private static $offloadPrevented = array();
private $post_id; // source_id. The plugin has this, so why so tricky checks.
public function __construct()
{
add_action('as3cf_init', array($this, 'init'));
add_action('emr/converter/prevent-offload', array($this, 'preventOffload'), 10);
add_action('emr/converter/prevent-offload-off', array($this, 'preventOffloadOff'), 10);
add_filter('as3cf_pre_update_attachment_metadata', array($this, 'preventUpdateMetaData'), 10,4);
}
public static function getInstance()
{
if (is_null(self::$instance))
{
self::$instance = new WPOffload();
}
return self::$instance;
}
public function init($as3cf)
{
if (! class_exists('\DeliciousBrains\WP_Offload_Media\Items\Media_Library_Item'))
{
Notices::addWarning(__('Your S3-Offload plugin version doesn\'t seem to be compatible. Please upgrade the S3-Offload plugin', 'enable-media-replace'), true);
return false;
}
$this->as3cf = $as3cf;
if (method_exists($as3cf, 'get_item_handler'))
{
}
else {
Notices::addWarning(__('Your S3-Offload plugin version doesn\'t seem to be compatible. Please upgrade the S3-Offload plugin', 'enable-media-replace'), true);
return false;
}
// @todo This all is begging for the creating of an enviroment model / controller.
if( !function_exists('is_plugin_active') ) {
include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
}
$spio_active = \is_plugin_active('shortpixel-image-optimiser/wp-shortpixel.php');
// Let spio handle this.
if (false === $spio_active)
{
add_filter('shortpixel/image/urltopath', array($this, 'checkIfOffloaded'), 10,2);
}
add_action('emr_after_remove_current', array($this, 'removeRemote'), 10, 5);
add_filter('emr/file/virtual/translate', array($this, 'getLocalPath'), 10, 3);
add_filter('emr/replace/file_is_movable', array($this, 'isFileMovable'), 10, 2);
add_filter('emr/replace/original_image_path', array($this, 'checkScaledUrl'), 10,2);
add_action('enable-media-replace-upload-done', array($this, 'updateOriginalPath'), 10, 3);
}
/*
* @param $post_id int The post ID
* @param $meta array Old Metadata before remove
* @param $backup_sizes array WP Backup sizes
* @param $sourceFile Object Source File
* @param $targetFile Object Target File
*/
public function removeRemote($post_id, $meta, $backup_sizes, $sourceFile, $targetFile )
{
// Always remove because also thumbnails can be different.
$a3cfItem = $this->getItemById($post_id); // MediaItem is AS3CF Object
if ($a3cfItem === false)
{
Log::addDebug('S3-Offload MediaItem not remote - ' . $post_id);
return false;
}
$remove = \DeliciousBrains\WP_Offload_Media\Items\Remove_Provider_Handler::get_item_handler_key_name();
$itemHandler = $this->as3cf->get_item_handler($remove);
$result = $itemHandler->handle($a3cfItem, array( 'verify_exists_on_local' => false)); //handle it then.
}
// @param s3 based URL that which is needed for finding local path
// @return String Filepath. Translated file path
public function getLocalPath($url, $sourceFileObj, $source_id)
{
$item = $this->getItemById($source_id);
if ($item === false)
{
$source_id = $this->getSourceIDByURL($url);
if (false !== $source_id)
$item = $this->getItemById($source_id);
}
if ($source_id == false)
{
Log::addError('Get Local Path: No source id for URL (Offload) ' . $url);
return false;
}
$original_path = $item->original_source_path(); // $values['original_source_path'];
if (wp_basename($url) !== wp_basename($original_path)) // thumbnails translate to main file.
{
$original_path = str_replace(wp_basename($original_path), wp_basename($url), $original_path);
}
$fs = emr()->filesystem();
$base = $fs->getWPUploadBase();
$file = $base . $original_path;
return $file;
}
public function isFileMovable($bool, $attach_id)
{
$item = $this->getItemById($attach_id);
if ($item === false)
{
return $bool;
}
// Can't move offloaded items.
if (is_object($item))
{
return false;
}
}
public function checkIfOffloaded($bool, $url)
{
$source_id = $this->sourceCache($url);
if (false === $source_id)
{
$extension = substr($url, strrpos($url, '.') + 1);
// If these filetypes are not in the cache, they cannot be found via geSourceyIDByUrl method ( not in path DB ), so it's pointless to try. If they are offloaded, at some point the extra-info might load.
if ($extension == 'webp' || $extension == 'avif')
{
return false;
}
$source_id = $this->getSourceIDByURL($url);
}
if ($source_id !== false)
{
return true;
}
else
{
return false;
}
}
// This is used in the converted. Might be deployed elsewhere for better control.
public function preventOffload($attach_id)
{
self::$offloadPrevented[$attach_id] = true;
}
public function preventOffloadOff($attach_id)
{
unset(self::$offloadPrevented[$attach_id]);
}
public function updateOriginalPath($source_url, $target_url, $post_id)
{
$item = $this->getItemById($post_id);
// If no item comes back, probably it's not offloaded
if (false === $item)
{
return;
}
$original_path = $item->original_path(); // Original path (non-scaled-)
$original_source_path = $item->original_source_path();
$path = $item->path();
$source_path = $item->source_path();
$wp_original = wp_get_original_image_path($post_id, apply_filters( 'emr_unfiltered_get_attached_file', true ));
$wp_original = apply_filters('emr/replace/original_image_path', $wp_original, $post_id);
$wp_source = trim(get_attached_file($post_id, apply_filters( 'emr_unfiltered_get_attached_file', true )));
$updated = false;
// If image is replaced with another name, the original soruce path will not match. This could also happen when an image is with -scaled as main is replaced by an image that doesn't have it. In all cases update the table to reflect proper changes.
if (wp_basename($wp_original) !== wp_basename($original_path))
{
$newpath = str_replace( wp_basename( $original_path ), wp_basename($wp_original), $original_path );
$item->set_original_path($newpath);
$newpath = str_replace( wp_basename( $original_source_path ), wp_basename($wp_original), $original_source_path );
$updated = true;
$item->set_original_source_path($newpath);
$item->save();
}
}
// When Offload is not offloaded but is created during the process of generate metadata in WP, wp_create_image_subsizes fires an update metadata after just moving the upload, before making any thumbnails. If this is the case and the file has an -scaled / original image setup, the original_source_path becomes the same as the source_path which creates issue later on when dealing with optimizing it, if the file is deleted on local server. Prevent this, and lean on later update metadata.
public function preventUpdateMetaData($bool, $data, $post_id, $old_provider_object)
{
if (isset(self::$offloadPrevented[$post_id]))
{
return true ; // return true to cancel.
}
return $bool;
}
// WP Offload -for some reason - returns the same result of get_attached_file and wp_get_original_image_path , which are different files (one scaled) which then causes a wrong copy action after optimizing the image ( wrong destination download of the remote file ). This happens if offload with delete is on. Attempt to fix the URL to reflect the differences between -scaled and not.
public function checkScaledUrl($filepath, $id)
{
// Original filepath can never have a scaled in there.
// @todo This should probably check -scaled.<extension> as string end preventing issues.
if (strpos($filepath, '-scaled') !== false)
{
$filepath = str_replace('-scaled', '', $filepath);
}
return $filepath;
}
/** @return Returns S3Ofload MediaItem, or false when this does not exist */
protected function getItemById($id, $create = false)
{
$class = $this->getMediaClass();
$mediaItem = $class::get_by_source_id($id);
if (true === $create && $mediaItem === false)
{
$mediaItem = $class::create_from_source_id($id);
}
return $mediaItem;
}
protected function getSourceIDByURL($url)
{
$source_id = $this->sourceCache($url); // check cache first.
if (false === $source_id) // check on the raw url.
{
$class = $this->getMediaClass();
$parsedUrl = parse_url($url);
if (! isset($parsedUrl['scheme']) || ! in_array($parsedUrl['scheme'], array('http','https')))
{
$url = 'http://' . $url; //str_replace($parsedUrl['scheme'], 'https', $url);
}
$source = $class::get_item_source_by_remote_url($url);
$source_id = isset($source['id']) ? intval($source['id']) : false;
}
if (false === $source_id) // check now via the thumbnail hocus.
{
$pattern = '/(.*)-\d+[xX]\d+(\.\w+)/m';
$url = preg_replace($pattern, '$1$2', $url);
$source_id = $this->sourceCache($url); // check cache first.
if (false === $source_id)
{
$source = $class::get_item_source_by_remote_url($url);
$source_id = isset($source['id']) ? intval($source['id']) : false;
}
}
// Check issue with double extensions. If say double webp/avif is on, the double extension causes the URL not to be found (ie .jpg)
if (false === $source_id)
{
if (substr_count($parsedUrl['path'], '.') > 1)
{
// Get extension
$ext = substr(strrchr($url, '.'), 1);
// Remove all extensions from the URL
$checkurl = substr($url, 0, strpos($url,'.')) ;
// Add back the last one.
$checkurl .= '.' . $ext;
// Retry
$source_id = $this->sourceCache($checkurl); // check cache first.
if (false === $source_id)
{
$source = $class::get_item_source_by_remote_url($url);
$source_id = isset($source['id']) ? intval($source['id']) : false;
}
}
}
if ($source_id !== false)
{
$this->sourceCache($url, $source_id); // cache it.
// get item
$item = $this->getItemById($source_id);
if (is_object($item) && method_exists($item, 'extra_info'))
{
$baseUrl = str_replace(basename($url),'', $url);
$extra_info = $item->extra_info();
if (isset($extra_info['objects']))
{
foreach($extra_info['objects'] as $extraItem)
{
if (is_array($extraItem) && isset($extraItem['source_file']))
{
// Add source stuff into cache.
$this->sourceCache($baseUrl . $extraItem['source_file'], $source_id);
}
}
}
}
return $source_id;
}
return false;
}
private function sourceCache($url, $source_id = null)
{
if ($source_id === null && isset($this->sources[$url]))
{
$source_id = $this->sources[$url];
return $source_id;
}
elseif ($source_id !== null)
{
if (! isset($this->sources[$url]))
{
$this->sources[$url] = $source_id;
}
return $source_id;
}
return false;
}
private function getMediaClass()
{
$class = $this->as3cf->get_source_type_class('media-library');
return $class;
}
}