Skip to content

Commit 55cb752

Browse files
authored
Release version 4.1.1 (#95)
Merge pull request #95 from short-pixel-optimizer/updates
2 parents 770e4f9 + 8dbc25d commit 55cb752

File tree

13 files changed

+147
-38
lines changed

13 files changed

+147
-38
lines changed

build/shortpixel/filesystem/src/Model/File/FileModel.php

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -228,9 +228,15 @@ public function getFileDir()
228228

229229
public function getFileSize()
230230
{
231-
if ($this->exists())
231+
if ($this->exists() && false === $this->is_virtual() )
232+
{
232233
return filesize($this->fullpath);
233-
else
234+
}
235+
elseif (true === $this->is_virtual())
236+
{
237+
return -1;
238+
}
239+
else
234240
return 0;
235241
}
236242

build/shortpixel/replacer/src/Replacer.php

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -190,7 +190,8 @@ public function replace($args = array())
190190
Log::addDebug('Running additional replace for : '. $component, $run);
191191
$updated += $this->doReplaceQuery($run['base_url'], $run['search_urls'], $run['replace_urls']);
192192
}
193-
//do_action('')
193+
194+
do_action('shortpixel/replacer/after_replacing', $base_url, $search_urls, $replace_urls);
194195

195196
Log::addDebug("Updated Records : " . $updated);
196197
return $updated;
@@ -378,7 +379,7 @@ private function change_key($arr, $set) {
378379
}
379380
return $arr;
380381
}
381-
382+
382383
private function getRelativeURLS()
383384
{
384385
$dataArray = array(

classes/Controller/ReplaceController.php

Lines changed: 46 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ class ReplaceController
4040
protected $tmpUploadPath;
4141

4242
protected $lastError;
43+
protected $lastErrorData; // optional extra data for last error.
4344

4445
public function __construct($post_id)
4546
{
@@ -91,6 +92,15 @@ public function returnLastError()
9192
return $this->lastError;
9293
}
9394

95+
public function returnLastErrorData()
96+
{
97+
if (! is_null($this->lastErrorData))
98+
return $this->lastErrorData;
99+
else {
100+
return array();
101+
}
102+
}
103+
94104
public function run()
95105
{
96106
do_action('wp_handle_replace', array('post_id' => $this->post_id));
@@ -104,6 +114,7 @@ public function run()
104114
$targetFileObj = $this->fs()->getFile($this->targetFile);
105115

106116
$directoryObj = $targetFileObj->getFileDir();
117+
107118
$result = $directoryObj->check();
108119

109120
if ($result === false)
@@ -182,9 +193,9 @@ public function run()
182193
do_action('emr/converter/prevent-offload', $this->post_id);
183194
$target_metadata = wp_generate_attachment_metadata( $this->post_id, $this->targetFile->getFullPath() );
184195
do_action('emr/converter/prevent-offload-off', $this->post_id);
185-
186196
wp_update_attachment_metadata( $this->post_id, $target_metadata );
187197

198+
188199
$Replacer->setTargetMeta($target_metadata);
189200
//$this->target_metadata = $metadata;
190201

@@ -235,6 +246,7 @@ public function run()
235246
$args = array(
236247
'thumbnails_only' => ($this->replaceType == self::MODE_SEARCHREPLACE) ? false : true,
237248
);
249+
238250
$Replacer->replace($args);
239251

240252
// Here Updatedata and a ffew others.
@@ -258,42 +270,64 @@ public function run()
258270
protected function setupSource()
259271
{
260272
$source_file = false;
273+
274+
// The main image as registered in attached_file metadata. This can be regular or -scaled.
275+
$source_file_main = trim(get_attached_file($this->post_id, apply_filters( 'emr_unfiltered_get_attached_file', true )));
276+
277+
// If available it -needs- to use the main image when replacing since treating a -scaled images as main will create a resursion in the filename when not replacing that one . Ie image-scaled-scaled.jpg or image-scaled-100x100.jpg .
261278
if (function_exists('wp_get_original_image_path')) // WP 5.3+
262279
{
263280
$source_file = wp_get_original_image_path($this->post_id, apply_filters( 'emr_unfiltered_get_attached_file', true ));
264-
// For offload et al to change path if wrong.
281+
// For offload et al to change path if wrong. Somehow this happens?
265282
$source_file = apply_filters('emr/replace/original_image_path', $source_file, $this->post_id);
283+
266284
}
267285

268-
if (false === $source_file)
286+
if (false === $source_file) // If not scaled, use the main one.
269287
{
270-
$source_file = trim(get_attached_file($this->post_id, apply_filters( 'emr_unfiltered_get_attached_file', true )));
288+
$source_file = $source_file_main;
271289
}
272290

291+
273292
$sourceFileObj = $this->fs()->getFile($source_file);
293+
$isVirtual = false;
274294
if ($sourceFileObj->is_virtual())
275295
{
296+
$isVirtual = true;
297+
298+
/***
299+
*** Either here the table should check scaled - non-scaled ** or ** the original_path should be updated.
300+
***
301+
302+
*/
303+
276304
$this->sourceFileUntranslated = $this->fs()->getFile($source_file);
277-
$sourcePath = apply_filters('emr/file/virtual/translate', $sourceFileObj->getFullPath(), $sourceFileObj);
305+
$sourcePath = apply_filters('emr/file/virtual/translate', $sourceFileObj->getFullPath(), $sourceFileObj, $this->post_id);
278306

279-
if ($sourceFileObj->getFullPath() !== $sourcePath)
307+
if (false !== $sourcePath && $sourceFileObj->getFullPath() !== $sourcePath)
280308
{
281309
$sourceFileObj = $this->fs()->getFile($sourcePath);
282310
$source_file = $sourcePath;
283311
}
312+
284313
}
314+
315+
285316
/* It happens that the SourceFile returns relative / incomplete when something messes up get_upload_dir with an error something.
286317
This case shoudl be detected here and create a non-relative path anyhow..
287318
*/
288-
289-
if (! file_exists($source_file) && $source_file && 0 !== strpos( $source_file, '/' ) && ! preg_match( '|^.:\\\|', $source_file ) )
319+
if (
320+
false === $isVirtual &&
321+
false === file_exists($source_file) &&
322+
$source_file && 0 !== strpos( $source_file, '/' )
323+
&& ! preg_match( '|^.:\\\|', $source_file ) )
290324
{
291325
$file = get_post_meta( $this->post_id, '_wp_attached_file', true );
292326
$uploads = wp_get_upload_dir();
293327
$source_file = $uploads['basedir'] . "/$source_file";
294328
}
295329

296-
Log::addDebug('SourceFile ' . $source_file);
330+
Log::addDebug('SetupSource SourceFile Path ' . $source_file);
297331
$this->sourceFile = $this->fs()->getFile($source_file);
298332
}
299333

@@ -505,11 +539,13 @@ protected function getNewTargetLocation()
505539
$newPath = trailingslashit($uploadDir['basedir']) . $new_rel_location;
506540

507541
$realPath = realpath($newPath);
542+
$basedir = realpath($uploadDir['basedir']); // both need to go to realpath, otherwise some servers will have issues with it.
508543

509544
// Detect traversal by making sure the canonical path starts with uploads' basedir.
510-
if ( strpos($realPath, $uploadDir['basedir']) !== 0)
545+
if ( strpos($realPath, $basedir) !== 0)
511546
{
512547
$this->lastError = self::ERROR_DIRECTORY_SECURITY;
548+
$this->lastErrorData = array('path' => $realPath, 'basedir' => $basedir);
513549
return false;
514550
}
515551

classes/ViewController.php

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@ protected function loadView($template = null, $unique = true)
7474
}
7575
}
7676

77-
protected function viewError($errorCode)
77+
protected function viewError($errorCode, $errorData = array())
7878
{
7979
$message = $description = false;
8080
switch($errorCode)
@@ -114,6 +114,13 @@ protected function viewError($errorCode)
114114
break;
115115
case self::ERROR_DIRECTORY_SECURITY:
116116
$message = __('Specificed directory is outside the upload directory. This is not allowed for security reasons', 'enable-media-replace');
117+
$path = isset($errorData['path']) ? $errorData['path'] : false;
118+
$basedir = isset($errorData['basedir']) ? $errorData['basedir'] : false;
119+
120+
if ($path !== false && $basedir !== false)
121+
{
122+
$description = sprintf(__('Path: %s is not within basedir reported as: %s', 'shortpixel-image-optimiser'), $path, $basedir);
123+
}
117124
break;
118125
case self::ERROR_DIRECTORY_NOTEXIST:
119126
$message = __('Specificed new directory does not exist. Path must be a relative path from the upload directory and exist', 'enable-media-replace');
@@ -137,6 +144,7 @@ protected function viewError($errorCode)
137144
if( false !== $message)
138145
$this->view->errorMessage = $message;
139146

147+
140148
if (false !== $description)
141149
{
142150
$this->view->errorDescription = $description;

classes/ViewController/UploadViewController.php

Lines changed: 2 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,8 @@ public function load()
8080
if (false === $check)
8181
{
8282
$error = $replaceController->returnLastError();
83-
$this->viewError($error);
83+
$data = $replaceController->returnLastErrorData();
84+
$this->viewError($error, $data);
8485
}
8586

8687
$result = $replaceController->run();
@@ -120,15 +121,7 @@ protected function getPost()
120121
Log::addDebug('Custom Date - ' . $custom_date . ' ' . $custom_hour . ':' . $custom_minute);
121122
$custom_date = \DateTime::createFromFormat('Y-m-d G:i', $custom_date . ' ' . $custom_hour . ':' . $custom_minute);
122123
if ($custom_date === false) {
123-
/*wp_safe_redirect($redirect_error);
124-
$errors = \DateTime::getLastErrors();
125-
$error = '';
126-
if (isset($errors['errors'])) {
127-
$error = implode(',', $errors['errors']);
128-
} */
129-
//Notices::addError(sprintf(__('Invalid Custom Date. Please check the custom date values: (%s)', 'enable-media-replace'), $error));
130124
$this->viewError(self::ERROR_TIME);
131-
//exit();
132125
}
133126
$datetime = $custom_date->format("Y-m-d H:i:s");
134127
$is_custom_date = true;
@@ -201,7 +194,6 @@ protected function getUpload()
201194
}
202195

203196
if ($filedata["ext"] == false && ! current_user_can('unfiltered_upload')) {
204-
// Log::addWarn('Uploaded File type does not meet security guidelines, aborting');
205197
$this->viewError(self::ERROR_SECURITY);
206198
}
207199

classes/emr-plugin.php

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -332,6 +332,10 @@ public function admin_scripts()
332332
wp_localize_script('emr_admin', 'emr_options', $emr_options);
333333

334334
wp_register_script('emr_success', plugins_url('js/emr_success.js', EMR_ROOT_FILE), array(), EMR_VERSION, true);
335+
336+
wp_localize_script('emr_success', 'emr_success_options', array(
337+
'timeout' => apply_filters('emr/success/timeout', 10),
338+
));
335339
}
336340

337341
/** Utility function for the Jquery UI Datepicker */

classes/external/wp-offload.php

Lines changed: 54 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -18,12 +18,12 @@ class WPOffload
1818

1919
private static $offloadPrevented = array();
2020

21+
private $post_id; // source_id. The plugin has this, so why so tricky checks.
22+
2123

2224
public function __construct()
2325
{
2426
add_action('as3cf_init', array($this, 'init'));
25-
add_filter('shortpixel/image/urltopath', array($this, 'checkIfOffloaded'), 10,2);
26-
2727

2828
add_action('emr/converter/prevent-offload', array($this, 'preventOffload'), 10);
2929
add_action('emr/converter/prevent-offload-off', array($this, 'preventOffloadOff'), 10);
@@ -60,11 +60,15 @@ public function init($as3cf)
6060
return false;
6161
}
6262

63+
add_filter('shortpixel/image/urltopath', array($this, 'checkIfOffloaded'), 10,2);
64+
6365
add_action('emr_after_remove_current', array($this, 'removeRemote'), 10, 5);
64-
add_filter('emr/file/virtual/translate', array($this, 'getLocalPathByURL'));
66+
add_filter('emr/file/virtual/translate', array($this, 'getLocalPath'), 10, 3);
6567
add_filter('emr/replace/file_is_movable', array($this, 'isFileMovable'), 10, 2);
6668

6769
add_filter('emr/replace/original_image_path', array($this, 'checkScaledUrl'), 10,2);
70+
71+
add_action('enable-media-replace-upload-done', array($this, 'updateOriginalPath'), 10, 3);
6872
}
6973

7074
/*
@@ -93,15 +97,22 @@ public function removeRemote($post_id, $meta, $backup_sizes, $sourceFile, $targe
9397

9498
// @param s3 based URL that which is needed for finding local path
9599
// @return String Filepath. Translated file path
96-
public function getLocalPathByURL($url)
100+
public function getLocalPath($url, $sourceFileObj, $source_id)
97101
{
98-
$source_id = $this->getSourceIDByURL($url);
102+
$item = $this->getItemById($source_id);
103+
104+
if ($item === false)
105+
{
106+
$source_id = $this->getSourceIDByURL($url);
107+
if (false !== $source_id)
108+
$item = $this->getItemById($source_id);
109+
}
99110

100111
if ($source_id == false)
101112
{
113+
Log::addError('Get Local Path: No source id for URL (Offload) ' . $url);
102114
return false;
103115
}
104-
$item = $this->getItemById($source_id);
105116

106117
$original_path = $item->original_source_path(); // $values['original_source_path'];
107118

@@ -117,6 +128,8 @@ public function getLocalPathByURL($url)
117128
return $file;
118129
}
119130

131+
132+
120133
public function isFileMovable($bool, $attach_id)
121134
{
122135
$item = $this->getItemById($attach_id);
@@ -138,7 +151,6 @@ public function checkIfOffloaded($bool, $url)
138151

139152
$source_id = $this->sourceCache($url);
140153

141-
142154
if (false === $source_id)
143155
{
144156
$extension = substr($url, strrpos($url, '.') + 1);
@@ -172,6 +184,38 @@ public function preventOffloadOff($attach_id)
172184
unset(self::$offloadPrevented[$attach_id]);
173185
}
174186

187+
public function updateOriginalPath($source_url, $target_url, $post_id)
188+
{
189+
$item = $this->getItemById($post_id);
190+
191+
$original_path = $item->original_path(); // Original path (non-scaled-)
192+
$original_source_path = $item->original_source_path();
193+
$path = $item->path();
194+
$source_path = $item->source_path();
195+
196+
$wp_original = wp_get_original_image_path($post_id, apply_filters( 'emr_unfiltered_get_attached_file', true ));
197+
$wp_original = apply_filters('emr/replace/original_image_path', $wp_original, $post_id);
198+
$wp_source = trim(get_attached_file($post_id, apply_filters( 'emr_unfiltered_get_attached_file', true )));
199+
200+
$updated = false;
201+
202+
// 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.
203+
if (wp_basename($wp_original) !== wp_basename($original_path))
204+
{
205+
206+
$newpath = str_replace( wp_basename( $original_path ), wp_basename($wp_original), $original_path );
207+
208+
$item->set_original_path($newpath);
209+
210+
$newpath = str_replace( wp_basename( $original_source_path ), wp_basename($wp_original), $original_source_path );
211+
$updated = true;
212+
213+
$item->set_original_source_path($newpath);
214+
215+
$item->save();
216+
}
217+
}
218+
175219
// 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.
176220
public function preventUpdateMetaData($bool, $data, $post_id, $old_provider_object)
177221
{
@@ -184,6 +228,8 @@ public function preventUpdateMetaData($bool, $data, $post_id, $old_provider_obje
184228

185229
}
186230

231+
232+
187233
// 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.
188234
public function checkScaledUrl($filepath, $id)
189235
{
@@ -226,6 +272,7 @@ protected function getSourceIDByURL($url)
226272
}
227273

228274
$source = $class::get_item_source_by_remote_url($url);
275+
229276
$source_id = isset($source['id']) ? intval($source['id']) : false;
230277
}
231278

classes/uihelper.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -417,7 +417,7 @@ public function getPlaceHolder($args)
417417
$output = "<div class='image_placeholder $placeholder_class' $filetype style='width:" . $w . "px; height:". $h ."px'> ";
418418
if (true === $args['is_upload'])
419419
{
420-
$output .= "<span class='upload-title'>" . __('New', 'enable-media-replacer') . "</span>";
420+
$output .= "<span class='upload-title'>" . __('New', 'enable-media-replace') . "</span>";
421421
$output .= '<input type="file" name="userfile" id="upload-file" />';
422422
$output .= '<div class="drag-and-drop-title">
423423
<span>' . __('Click here to upload or drop file in area', 'enable-media-replace') . '</span>

0 commit comments

Comments
 (0)