ShortPixel Image Optimizer - Version 2.0.5

Version Description

  • small improvement to make the optimization of newly added images faster.
  • fixed condition when the PDF files weren't processed
  • different improvements
Download this release

Release Info

Developer ShortPixel
Plugin Icon 128x128 ShortPixel Image Optimizer
Version 2.0.5
Comparing to
See all releases

Code changes from version 2.0.4 to 2.0.5

Files changed (3) hide show
  1. readme.txt +7 -1
  2. shortpixel_api.php +118 -81
  3. wp-shortpixel.php +55 -23
readme.txt CHANGED
@@ -4,7 +4,7 @@ Contributors: AlexSP
4
  Tags: picture, optimization, image editor, pngout, upload speed, shortpixel, compression, jpegmini, webp, lossless, cwebp, media, tinypng, jpegtran,image, image optimisation, shrink, picture, photo, optimize photos, compress, performance, tinypng, crunch, pngquant, attachment, optimize, pictures,fast, images, image files, image quality, lossy, upload, kraken, resize, seo, smushit, optipng, kraken image optimizer, ewww, photo optimization, gifsicle, image optimizer, images, krakenio, png, gmagick, image optimize, pdf, pdf optimisation, optimise pdf, shrink pdf, jpg, jpeg, jpg optimisation, optimise jpg, shrink jpg, gif, animated gif, optimise gif
5
  Requires at least: 3.0.0 or higher
6
  Tested up to: 4.1.1
7
- Stable tag: 2.0.4
8
  License: GPLv2 or later
9
  License URI: http://www.gnu.org/licenses/gpl-2.0.html
10
 
@@ -107,6 +107,12 @@ The ShortPixel team is here to help. <a href="https://shortpixel.com/contact">Co
107
 
108
  == Changelog ==
109
 
 
 
 
 
 
 
110
  = 2.0.4 =
111
 
112
  * fixed recursive backup directory size counter
4
  Tags: picture, optimization, image editor, pngout, upload speed, shortpixel, compression, jpegmini, webp, lossless, cwebp, media, tinypng, jpegtran,image, image optimisation, shrink, picture, photo, optimize photos, compress, performance, tinypng, crunch, pngquant, attachment, optimize, pictures,fast, images, image files, image quality, lossy, upload, kraken, resize, seo, smushit, optipng, kraken image optimizer, ewww, photo optimization, gifsicle, image optimizer, images, krakenio, png, gmagick, image optimize, pdf, pdf optimisation, optimise pdf, shrink pdf, jpg, jpeg, jpg optimisation, optimise jpg, shrink jpg, gif, animated gif, optimise gif
5
  Requires at least: 3.0.0 or higher
6
  Tested up to: 4.1.1
7
+ Stable tag: 2.0.5
8
  License: GPLv2 or later
9
  License URI: http://www.gnu.org/licenses/gpl-2.0.html
10
 
107
 
108
  == Changelog ==
109
 
110
+ = 2.0.5 =
111
+
112
+ * small improvement to make the optimization of newly added images faster.
113
+ * fixed condition when the PDF files weren't processed
114
+ * different improvements
115
+
116
  = 2.0.4 =
117
 
118
  * fixed recursive backup directory size counter
shortpixel_api.php CHANGED
@@ -37,8 +37,12 @@ class shortpixel_api {
37
  $this->processImage($url, $filePath, $ID, $time);
38
  }
39
 
40
- public function doRequests($url, $filePath, $ID = null) {
41
- $response = $this->doBulkRequest(array($url), true);
 
 
 
 
42
 
43
  if(is_object($response) && get_class($response) == 'WP_Error') {
44
  return false;
@@ -55,7 +59,7 @@ class shortpixel_api {
55
  'lossy' => $this->_compressionType,
56
  'urllist' => $imageList
57
  );
58
-
59
  $response = wp_remote_post($this->_apiEndPoint, array(
60
  'method' => 'POST',
61
  'timeout' => 45,
@@ -68,7 +72,6 @@ class shortpixel_api {
68
  ));
69
 
70
  return $response;
71
-
72
  }
73
 
74
  public function parseResponse($response) {
@@ -80,8 +83,9 @@ class shortpixel_api {
80
 
81
  //handles the processing of the image using the ShortPixel API
82
  public function processImage($url, $filePath, $ID = null, $startTime = 0) {
83
- if($startTime == 0) { $startTime = time(); }
84
- if(time() - $startTime > MAX_EXECUTION_TIME) {
 
85
  $meta = wp_get_attachment_metadata($ID);
86
  $meta['ShortPixelImprovement'] = 'Could not determine compression';
87
  unset($meta['ShortPixel']['WaitingProcessing']);
@@ -89,24 +93,24 @@ class shortpixel_api {
89
  return 'Could not determine compression';
90
  }
91
 
92
- $response = $this->doRequests($url, $filePath, $ID);
93
-
94
  if(!$response) return $response;
95
 
96
- if($response['response']['code'] != 200) {
97
- printf('Web service did not respond. Please try again later.');
98
  return false;
99
  }
100
 
101
- $data = $this->parseResponse($response);
102
- $data = $data[0];
103
-
104
- if(!is_object($data) || !isset($data->Status->Code)) {
105
  printf('Web service returned an error. Please try again later.');
106
  return false;
107
  }
108
-
109
- switch($data->Status->Code) {
 
 
110
  case 1:
111
  //handle image has been scheduled
112
  sleep(1);
@@ -133,41 +137,53 @@ class shortpixel_api {
133
 
134
  public function handleSuccess($callData, $url, $filePath, $ID) {
135
 
136
- if($this->_compressionType) {
137
- //lossy
138
- $correctFileSize = $callData->LossySize;
139
- $tempFile = download_url(urldecode($callData->LossyURL));
140
- if(is_wp_error( $tempFile )) {
141
- $tempFile = download_url(str_replace('https://', 'http://', urldecode($callData->LossyURL)));
142
- }
143
- } else {
144
- //lossless
145
- $correctFileSize = $callData->LoselessSize;
146
- $tempFile = download_url(urldecode($callData->LosslessURL));
147
- if(is_wp_error( $tempFile )) {
148
- $tempFile = download_url(str_replace('https://', 'http://', urldecode($callData->LosslessURL)));
149
  }
150
- }
151
-
152
- if ( is_wp_error( $tempFile ) ) {
153
- @unlink($tempFile);
154
- return sprintf("Error downloading file (%s)", $tempFile->get_error_message());
155
- die;
156
- }
157
 
158
- //check response so that download is OK
159
- if(filesize($tempFile) != $correctFileSize) {
160
- return sprintf("Error downloading file - incorrect file size");
161
- die;
162
- }
163
 
164
- if (!file_exists($tempFile)) {
165
- return sprintf("Unable to locate downloaded file (%s)", $tempFile);
166
- die;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
167
  }
168
 
169
  //if backup is enabled
170
- if(get_option('wp-short-backup_images')) {
 
171
 
172
  $imageIndex = 0;
173
  $uploadDir = wp_upload_dir();
@@ -205,46 +221,67 @@ class shortpixel_api {
205
  } else {
206
  return sprintf("Backup folder exists but is not writable");
207
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
208
  }
209
-
210
-
211
-
212
- /////////////////////////
213
-
214
-
215
- @unlink( $filePath );
216
- $success = @rename( $tempFile, $filePath );
217
-
218
- if (!$success) {
219
- $copySuccess = copy($tempFile, $filePath);
220
- unlink($tempFile);
221
- }
222
-
223
- if($success || $copySuccess) {
224
- //update statistics
225
- if(isset($callData->LossySize)) {
226
- $savedSpace = $callData->OriginalSize - $callData->LossySize;
227
- } else {
228
- $savedSpace = $callData->OriginalSize - $callData->LoselessSize;
229
  }
230
-
231
- update_option(
232
- 'wp-short-pixel-savedSpace',
233
- get_option('wp-short-pixel-savedSpace') + $savedSpace
234
- );
235
- $averageCompression = get_option('wp-short-pixel-averageCompression') * get_option('wp-short-pixel-fileCount');
236
- $averageCompression += $callData->PercentImprovement;
237
- $averageCompression = $averageCompression / (get_option('wp-short-pixel-fileCount') + 1);
238
- update_option('wp-short-pixel-averageCompression', $averageCompression);
239
- update_option('wp-short-pixel-fileCount', get_option('wp-short-pixel-fileCount')+1);
240
-
241
- //update metadata
242
- if(isset($ID)) {
243
- $meta = wp_get_attachment_metadata($ID);
244
- $meta['ShortPixelImprovement'] = $callData->PercentImprovement;
245
- wp_update_attachment_metadata($ID, $meta);
 
246
  }
 
 
 
 
 
 
 
 
247
  }
 
 
248
  }
249
 
250
  public function parseJSON($data) {
37
  $this->processImage($url, $filePath, $ID, $time);
38
  }
39
 
40
+ public function doRequests($urls, $filePath, $ID = null) {
41
+
42
+ if ( !is_array($urls) )
43
+ $response = $this->doBulkRequest(array($urls), true);
44
+ else
45
+ $response = $this->doBulkRequest($urls, true);
46
 
47
  if(is_object($response) && get_class($response) == 'WP_Error') {
48
  return false;
59
  'lossy' => $this->_compressionType,
60
  'urllist' => $imageList
61
  );
62
+
63
  $response = wp_remote_post($this->_apiEndPoint, array(
64
  'method' => 'POST',
65
  'timeout' => 45,
72
  ));
73
 
74
  return $response;
 
75
  }
76
 
77
  public function parseResponse($response) {
83
 
84
  //handles the processing of the image using the ShortPixel API
85
  public function processImage($url, $filePath, $ID = null, $startTime = 0) {
86
+
87
+ if($startTime == 0) { $startTime = time(); }
88
+ if(time() - $startTime > MAX_EXECUTION_TIME) {//keeps track of time
89
  $meta = wp_get_attachment_metadata($ID);
90
  $meta['ShortPixelImprovement'] = 'Could not determine compression';
91
  unset($meta['ShortPixel']['WaitingProcessing']);
93
  return 'Could not determine compression';
94
  }
95
 
96
+ $response = $this->doRequests($url, $filePath, $ID);//send requests to API
 
97
  if(!$response) return $response;
98
 
99
+ if($response['response']['code'] != 200) {//response <> 200 -> there was an error apparently?
100
+ printf('ShortPixel API service accesibility error. Please try again later.');
101
  return false;
102
  }
103
 
104
+ $data = $this->parseResponse($response);//get the actual response from API
105
+
106
+ if( !is_array($data) ) {// the answer from API isn't good
 
107
  printf('Web service returned an error. Please try again later.');
108
  return false;
109
  }
110
+
111
+ $firstImage = $data[0];//extract as object first image
112
+
113
+ switch($firstImage->Status->Code) {
114
  case 1:
115
  //handle image has been scheduled
116
  sleep(1);
137
 
138
  public function handleSuccess($callData, $url, $filePath, $ID) {
139
 
140
+ $counter = 0;
141
+ if($this->_compressionType)
142
+ {
143
+ $fileType = "LossyURL";
144
+ $fileSize = "LossySize";
145
+ }
146
+ else
147
+ {
148
+ $fileType = "LosslessURL";
149
+ $fileSize = "LoselessSize";
 
 
 
150
  }
 
 
 
 
 
 
 
151
 
152
+ foreach ( $callData as $fileData )//download each file from array and process it
153
+ {
154
+
155
+ if ( $counter == 0 )//save percent improvement for main file
156
+ $percentImprovement = $fileData->PercentImprovement;
157
 
158
+ $correctFileSize = $fileData->$fileSize;
159
+ $tempFiles[$counter] = download_url(urldecode($fileData->$fileType));
160
+
161
+ if(is_wp_error( $tempFiles[$counter] )) //also tries with http instead of https
162
+ $tempFiles[$counter] = download_url(str_replace('https://', 'http://', urldecode($fileData->$fileType)));
163
+
164
+ if ( is_wp_error( $tempFiles[$counter] ) ) {
165
+ @unlink($tempFiles[$counter]);
166
+ return sprintf("Error downloading file (%s)", $tempFiles[$counter]->get_error_message());
167
+ die;
168
+ }
169
+
170
+ //check response so that download is OK
171
+ if( filesize($tempFiles[$counter]) != $correctFileSize) {
172
+ return sprintf("Error downloading file - incorrect file size");
173
+ die;
174
+ }
175
+
176
+ if (!file_exists($tempFiles[$counter])) {
177
+ return sprintf("Unable to locate downloaded file (%s)", $tempFiles[$counter]);
178
+ die;
179
+ }
180
+
181
+ $counter++;
182
  }
183
 
184
  //if backup is enabled
185
+ if(get_option('wp-short-backup_images'))
186
+ {
187
 
188
  $imageIndex = 0;
189
  $uploadDir = wp_upload_dir();
221
  } else {
222
  return sprintf("Backup folder exists but is not writable");
223
  }
224
+ }//end backup section
225
+
226
+
227
+ $counter = 0;
228
+ $meta = wp_get_attachment_metadata($ID);//we'll need the metadata for subdir
229
+ $SubDir = trim(substr($meta['file'],0,strrpos($meta['file'],"/")+1));
230
+ if ( strlen($SubDir) == 0 )//it is likely a PDF file so we treat this differently
231
+ {
232
+ global $wpdb;
233
+ $qry = "SELECT * FROM " . $wpdb->prefix . "postmeta
234
+ WHERE (
235
+ post_id = $ID AND
236
+ meta_key = '_wp_attached_file'
237
+ )";
238
+ $idList = $wpdb->get_results($qry);
239
+ $metaPDF = $idList[0];
240
+ $SubDir = trim(substr($metaPDF->meta_value,0,strrpos($metaPDF->meta_value,"/")+1));
241
  }
242
+
243
+ foreach ( $tempFiles as $tempFile )
244
+ {
245
+
246
+ $sourceFile = $tempFile;
247
+ $destinationFile = WP_CONTENT_DIR . DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR . $SubDir . basename($url[$counter]);
248
+
249
+ @unlink( $destinationFile );
250
+ $success = @rename( $sourceFile, $destinationFile );
251
+
252
+ if (!$success) {
253
+ $copySuccess = copy($sourceFile, $destinationFile);
254
+ unlink($sourceFile);
 
 
 
 
 
 
 
255
  }
256
+
257
+ //save data to counters
258
+ if($success || $copySuccess) {
259
+ //update statistics
260
+ $fileData = $callData[$counter];
261
+ $savedSpace = $fileData->OriginalSize - $fileData->LossySize;
262
+
263
+ update_option(
264
+ 'wp-short-pixel-savedSpace',
265
+ get_option('wp-short-pixel-savedSpace') + $savedSpace
266
+ );
267
+ $averageCompression = get_option('wp-short-pixel-averageCompression') * get_option('wp-short-pixel-fileCount');
268
+ $averageCompression += $fileData->PercentImprovement;
269
+ $averageCompression = $averageCompression / (get_option('wp-short-pixel-fileCount') + 1);
270
+ update_option('wp-short-pixel-averageCompression', $averageCompression);
271
+ update_option('wp-short-pixel-fileCount', get_option('wp-short-pixel-fileCount')+1);
272
+
273
  }
274
+ $counter++;
275
+ }
276
+
277
+ //update metadata
278
+ if(isset($ID)) {
279
+ $meta = wp_get_attachment_metadata($ID);
280
+ $meta['ShortPixelImprovement'] = $percentImprovement;
281
+ wp_update_attachment_metadata($ID, $meta);
282
  }
283
+
284
+
285
  }
286
 
287
  public function parseJSON($data) {
wp-shortpixel.php CHANGED
@@ -3,7 +3,7 @@
3
  * Plugin Name: ShortPixel Image Optimiser
4
  * Plugin URI: https://shortpixel.com/
5
  * Description: ShortPixel is an image compression tool that helps improve your website performance. The plugin optimises images automatically using both lossy and lossless compression. Resulting, smaller, images are no different in quality from the original. To install: 1) Click the "Activate" link to the left of this description. 2) <a href="https://shortpixel.com/wp-apikey" target="_blank">Free Sign up</a> for your unique API Key . 3) Check your email for your API key. 4) Use your API key to activate ShortPixel plugin in the 'Plugins' menu in WordPress. 5) Done!
6
- * Version: 2.0.4
7
  * Author: ShortPixel
8
  * Author URI: https://shortpixel.com
9
  */
@@ -193,17 +193,59 @@ class WPShortPixel {
193
  $imagePath = get_attached_file($ID);
194
  $meta = wp_get_attachment_metadata($ID);
195
 
196
- //check if the image file exists on disk, if not set the right params
197
- if(!file_exists($imagePath)) {
198
- if(isset($meta['ShortPixel']['BulkProcessing'])) { unset($meta['ShortPixel']['BulkProcessing']); }
199
- if(isset($meta['ShortPixel']['WaitingProcessing'])) { unset($meta['ShortPixel']['WaitingProcessing']); }
200
- $meta['ShortPixel']['NoFileOnDisk'] = true;
201
- wp_update_attachment_metadata($ID, $meta);
202
- die;
203
- }
 
 
 
 
 
 
 
 
 
 
 
 
204
 
205
- $result = $this->_apiInterface->processImage($imageURL, $imagePath, $ID);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
206
 
 
207
 
208
  if(is_string($result)) {
209
  if(isset($meta['ShortPixel']['BulkProcessing'])) { unset($meta['ShortPixel']['BulkProcessing']); }
@@ -214,16 +256,8 @@ class WPShortPixel {
214
  die;
215
  }
216
 
217
- $processThumbnails = get_option('wp-short-process_thumbnails');
218
 
219
- //handle the rest of the thumbnails generated by WP
220
- if($processThumbnails && $result && !empty($meta['sizes'])) {
221
- foreach($meta['sizes'] as $thumbnailInfo) {
222
- $thumbURL = str_replace(basename($imagePath), $thumbnailInfo['file'], $imageURL);
223
- $thumbPath = str_replace(basename($imagePath), $thumbnailInfo['file'], $imagePath);
224
- $this->_apiInterface->processImage($thumbURL, $thumbPath);
225
- }
226
- }
227
 
228
  unset($meta['ShortPixel']['WaitingProcessing']);
229
 
@@ -231,10 +265,8 @@ class WPShortPixel {
231
  unset($meta['ShortPixel']['BulkProcessing']);
232
  }
233
 
234
- $meta['ShortPixelImprovement'] = $result->PercentImprovement;
235
-
236
  wp_update_attachment_metadata($ID, $meta);
237
-
238
  echo "Processing done succesfully for image #{$ID}";
239
  }
240
 
@@ -799,7 +831,7 @@ HTML;
799
  }
800
 
801
  print $data['ShortPixelImprovement'];
802
- if( is_numeric($data['ShortPixelImprovement']) && !$data['ShortPixel']['NoBackup'] ) {
803
  print '%';
804
  print " | <a href=\"admin.php?action=shortpixel_restore_backup&amp;attachment_ID={$id}\">Restore backup</a>";
805
  return;
3
  * Plugin Name: ShortPixel Image Optimiser
4
  * Plugin URI: https://shortpixel.com/
5
  * Description: ShortPixel is an image compression tool that helps improve your website performance. The plugin optimises images automatically using both lossy and lossless compression. Resulting, smaller, images are no different in quality from the original. To install: 1) Click the "Activate" link to the left of this description. 2) <a href="https://shortpixel.com/wp-apikey" target="_blank">Free Sign up</a> for your unique API Key . 3) Check your email for your API key. 4) Use your API key to activate ShortPixel plugin in the 'Plugins' menu in WordPress. 5) Done!
6
+ * Version: 2.0.5
7
  * Author: ShortPixel
8
  * Author URI: https://shortpixel.com
9
  */
193
  $imagePath = get_attached_file($ID);
194
  $meta = wp_get_attachment_metadata($ID);
195
 
196
+ if ( !isset($meta['file']) )//this could be a PDF file
197
+ {
198
+ $qry = "SELECT * FROM " . $wpdb->prefix . "postmeta
199
+ WHERE (
200
+ post_id = $ID AND
201
+ meta_key = '_wp_attached_file'
202
+ )";
203
+ $idList = $wpdb->get_results($qry);
204
+ $idList = $idList[0];
205
+ $uploadDir = wp_upload_dir();
206
+ $filePath = $uploadDir['path'] . DIRECTORY_SEPARATOR . basename($idList->meta_value);
207
+
208
+ //check if the image file exists on disk, if not set the right params
209
+ if(!file_exists($filePath)) {
210
+ if(isset($meta['ShortPixel']['BulkProcessing'])) { unset($meta['ShortPixel']['BulkProcessing']); }
211
+ if(isset($meta['ShortPixel']['WaitingProcessing'])) { unset($meta['ShortPixel']['WaitingProcessing']); }
212
+ $meta['ShortPixel']['NoFileOnDisk'] = true;
213
+ wp_update_attachment_metadata($ID, $meta);
214
+ die;
215
+ }
216
 
217
+ $imageURLs[] = $uploadDir['url'] . DIRECTORY_SEPARATOR . basename($idList->meta_value);//URL to PDF file
218
+ }
219
+ else
220
+ {//process images
221
+ //check if the image file exists on disk, if not set the right params
222
+ if(!file_exists($imagePath)) {
223
+ if(isset($meta['ShortPixel']['BulkProcessing'])) { unset($meta['ShortPixel']['BulkProcessing']); }
224
+ if(isset($meta['ShortPixel']['WaitingProcessing'])) { unset($meta['ShortPixel']['WaitingProcessing']); }
225
+ $meta['ShortPixel']['NoFileOnDisk'] = true;
226
+ wp_update_attachment_metadata($ID, $meta);
227
+ die;
228
+ }
229
+
230
+ //figure out the base URL
231
+ $uploadDir = wp_upload_dir();
232
+ $filesURL = $uploadDir['url'] . DIRECTORY_SEPARATOR;
233
+ $imageIndex=0;
234
+ //create the images' URL list
235
+ $imageURLs[$imageIndex] = $filesURL . basename($meta['file']);//main image first
236
+ $processThumbnails = get_option('wp-short-process_thumbnails');
237
+ //handle the rest of the thumbnails generated by WP
238
+ if ( $processThumbnails )
239
+ {
240
+ foreach ( $meta['sizes'] as $pictureDetails )
241
+ {
242
+ $imageIndex++;
243
+ $imageURLs[$imageIndex] = $filesURL . $pictureDetails['file'];
244
+ }
245
+ }
246
+ }
247
 
248
+ $result = $this->_apiInterface->processImage($imageURLs, $imagePath, $ID);
249
 
250
  if(is_string($result)) {
251
  if(isset($meta['ShortPixel']['BulkProcessing'])) { unset($meta['ShortPixel']['BulkProcessing']); }
256
  die;
257
  }
258
 
259
+ //$processThumbnails = get_option('wp-short-process_thumbnails');
260
 
 
 
 
 
 
 
 
 
261
 
262
  unset($meta['ShortPixel']['WaitingProcessing']);
263
 
265
  unset($meta['ShortPixel']['BulkProcessing']);
266
  }
267
 
268
+ $meta['ShortPixelImprovement'] = $result[0]->PercentImprovement;
 
269
  wp_update_attachment_metadata($ID, $meta);
 
270
  echo "Processing done succesfully for image #{$ID}";
271
  }
272
 
831
  }
832
 
833
  print $data['ShortPixelImprovement'];
834
+ if( is_numeric($data['ShortPixelImprovement']) && !isset($data['ShortPixel']['NoBackup']) ) {
835
  print '%';
836
  print " | <a href=\"admin.php?action=shortpixel_restore_backup&amp;attachment_ID={$id}\">Restore backup</a>";
837
  return;