ShortPixel Image Optimizer - Version 2.0.6

Version Description

  • different small fixes
Download this release

Release Info

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

Code changes from version 2.0.5 to 2.0.6

Files changed (3) hide show
  1. readme.txt +5 -1
  2. shortpixel_api.php +29 -26
  3. wp-shortpixel.php +168 -114
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.5
8
  License: GPLv2 or later
9
  License URI: http://www.gnu.org/licenses/gpl-2.0.html
10
 
@@ -107,6 +107,10 @@ The ShortPixel team is here to help. <a href="https://shortpixel.com/contact">Co
107
 
108
  == Changelog ==
109
 
 
 
 
 
110
  = 2.0.5 =
111
 
112
  * small improvement to make the optimization of newly added images faster.
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.6
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.6 =
111
+
112
+ * different small fixes
113
+
114
  = 2.0.5 =
115
 
116
  * small improvement to make the optimization of newly added images faster.
shortpixel_api.php CHANGED
@@ -33,8 +33,8 @@ class shortpixel_api {
33
  add_action('processImageAction', array(&$this, 'processImageAction'), 10, 4);
34
  }
35
 
36
- public function processImageAction($url, $filePath, $ID, $time) {
37
- $this->processImage($url, $filePath, $ID, $time);
38
  }
39
 
40
  public function doRequests($urls, $filePath, $ID = null) {
@@ -59,11 +59,12 @@ class shortpixel_api {
59
  'lossy' => $this->_compressionType,
60
  'urllist' => $imageList
61
  );
62
-
63
  $response = wp_remote_post($this->_apiEndPoint, array(
64
  'method' => 'POST',
65
  'timeout' => 45,
66
- 'redirection' => 5,
 
67
  'httpversion' => '1.0',
68
  'blocking' => $blocking,
69
  'headers' => array(),
@@ -82,7 +83,7 @@ class shortpixel_api {
82
  }
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
@@ -93,7 +94,7 @@ class shortpixel_api {
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?
@@ -114,11 +115,11 @@ class shortpixel_api {
114
  case 1:
115
  //handle image has been scheduled
116
  sleep(1);
117
- return $this->processImage($url, $filePath, $ID, $startTime);
118
  break;
119
  case 2:
120
  //handle image has been processed
121
- $this->handleSuccess($data, $url, $filePath, $ID);
122
  break;
123
  case -403:
124
  return 'Quota exceeded</br>';
@@ -128,7 +129,9 @@ class shortpixel_api {
128
  return 'Images does not exists</br>';
129
  default:
130
  //handle error
131
- return $data->Status->Message;
 
 
132
  }
133
 
134
  return $data;
@@ -177,14 +180,12 @@ class shortpixel_api {
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();
190
 
@@ -192,42 +193,41 @@ class shortpixel_api {
192
  return sprintf("Backup folder does not exist and it could not be created");
193
  }
194
  $meta = wp_get_attachment_metadata($ID);
195
- $source[$imageIndex] = $filePath;
196
-
197
  //create destination dir if it isn't already created
198
  @mkdir( SP_BACKUP_FOLDER . $uploadDir['subdir'], 0777, true);
199
-
200
  $destination[$imageIndex] = SP_BACKUP_FOLDER . $uploadDir['subdir'] . DIRECTORY_SEPARATOR . basename($source[$imageIndex]);
201
-
202
- foreach ( $meta['sizes'] as $pictureDetails )
203
  {
204
- $imageIndex++;
205
- $source[$imageIndex] = $uploadDir['path'] . DIRECTORY_SEPARATOR . $pictureDetails['file'];
206
- $destination[$imageIndex] = SP_BACKUP_FOLDER . $uploadDir['subdir'] . DIRECTORY_SEPARATOR . basename($source[$imageIndex]);
207
-
 
 
208
  }
209
 
210
-
211
  if(is_writable(SP_BACKUP_FOLDER)) {
212
  if(!file_exists($destination[0]))
213
- {
214
  foreach ( $source as $imageIndex => $fileSource )
215
  {
216
  $fileDestination = $destination[$imageIndex];
217
  @copy($fileSource, $fileDestination);
218
  }
219
-
220
  }
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
@@ -239,6 +239,9 @@ class shortpixel_api {
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
  {
33
  add_action('processImageAction', array(&$this, 'processImageAction'), 10, 4);
34
  }
35
 
36
+ public function processImageAction($url, $filePaths, $ID, $time) {
37
+ $this->processImage($url, $filePaths, $ID, $time);
38
  }
39
 
40
  public function doRequests($urls, $filePath, $ID = null) {
59
  'lossy' => $this->_compressionType,
60
  'urllist' => $imageList
61
  );
62
+
63
  $response = wp_remote_post($this->_apiEndPoint, array(
64
  'method' => 'POST',
65
  'timeout' => 45,
66
+ 'redirection' => 3,
67
+ 'sslverify' => false,
68
  'httpversion' => '1.0',
69
  'blocking' => $blocking,
70
  'headers' => array(),
83
  }
84
 
85
  //handles the processing of the image using the ShortPixel API
86
+ public function processImage($url, $filePaths, $ID = null, $startTime = 0) {
87
 
88
  if($startTime == 0) { $startTime = time(); }
89
  if(time() - $startTime > MAX_EXECUTION_TIME) {//keeps track of time
94
  return 'Could not determine compression';
95
  }
96
 
97
+ $response = $this->doRequests($url, $filePaths, $ID);//send requests to API
98
  if(!$response) return $response;
99
 
100
  if($response['response']['code'] != 200) {//response <> 200 -> there was an error apparently?
115
  case 1:
116
  //handle image has been scheduled
117
  sleep(1);
118
+ return $this->processImage($url, $filePaths, $ID, $startTime);
119
  break;
120
  case 2:
121
  //handle image has been processed
122
+ $this->handleSuccess($data, $url, $filePaths, $ID);
123
  break;
124
  case -403:
125
  return 'Quota exceeded</br>';
129
  return 'Images does not exists</br>';
130
  default:
131
  //handle error
132
+ if ( isset($data[0]->Status->Message) )
133
+ return $data[0]->Status->Message;
134
+
135
  }
136
 
137
  return $data;
180
  return sprintf("Unable to locate downloaded file (%s)", $tempFiles[$counter]);
181
  die;
182
  }
 
183
  $counter++;
184
  }
185
 
186
  //if backup is enabled
187
  if(get_option('wp-short-backup_images'))
188
  {
 
189
  $imageIndex = 0;
190
  $uploadDir = wp_upload_dir();
191
 
193
  return sprintf("Backup folder does not exist and it could not be created");
194
  }
195
  $meta = wp_get_attachment_metadata($ID);
196
+ $source = $filePath;
197
+
198
  //create destination dir if it isn't already created
199
  @mkdir( SP_BACKUP_FOLDER . $uploadDir['subdir'], 0777, true);
200
+
201
  $destination[$imageIndex] = SP_BACKUP_FOLDER . $uploadDir['subdir'] . DIRECTORY_SEPARATOR . basename($source[$imageIndex]);
202
+
203
+ if ( strtolower(substr($source[0], strrpos($source[0],".") + 1 )) <> "pdf" )//backup works differently if it is a PDF file
204
  {
205
+ foreach ( $meta['sizes'] as $pictureDetails )
206
+ {
207
+ $imageIndex++;
208
+ $source[$imageIndex] = $uploadDir['path'] . DIRECTORY_SEPARATOR . $pictureDetails['file'];
209
+ $destination[$imageIndex] = SP_BACKUP_FOLDER . $uploadDir['subdir'] . DIRECTORY_SEPARATOR . basename($source[$imageIndex]);
210
+ }
211
  }
212
 
 
213
  if(is_writable(SP_BACKUP_FOLDER)) {
214
  if(!file_exists($destination[0]))
215
+ {
216
  foreach ( $source as $imageIndex => $fileSource )
217
  {
218
  $fileDestination = $destination[$imageIndex];
219
  @copy($fileSource, $fileDestination);
220
  }
 
221
  }
222
  } else {
223
  return sprintf("Backup folder exists but is not writable");
224
  }
 
225
 
226
+ }//end backup section
227
 
228
  $counter = 0;
229
  $meta = wp_get_attachment_metadata($ID);//we'll need the metadata for subdir
230
+ if ( !isset($meta['file']) )//it is likely a PDF file so we treat this differently
 
231
  {
232
  global $wpdb;
233
  $qry = "SELECT * FROM " . $wpdb->prefix . "postmeta
239
  $metaPDF = $idList[0];
240
  $SubDir = trim(substr($metaPDF->meta_value,0,strrpos($metaPDF->meta_value,"/")+1));
241
  }
242
+ else //its an image
243
+ $SubDir = trim(substr($meta['file'],0,strrpos($meta['file'],"/")+1));
244
+
245
 
246
  foreach ( $tempFiles as $tempFile )
247
  {
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.5
7
  * Author: ShortPixel
8
  * Author URI: https://shortpixel.com
9
  */
@@ -149,15 +149,17 @@ class WPShortPixel {
149
  $url = wp_get_attachment_url($ID);
150
  $path = get_attached_file($ID);
151
  if(self::isProcesable($path) != false) {
152
- $this->_apiInterface->doRequests($url, $path, $ID);
 
153
 
154
- //send request for thumbs as well
155
- if($this->_processThumbnails && !empty($meta['sizes'])) {
 
156
  foreach($meta['sizes'] as $thumbnailInfo) {
157
- $thumbURL = str_replace(basename($url), $thumbnailInfo['file'], $url);
158
- $thumbPath = str_replace(basename($path), $thumbnailInfo['file'], $path);
159
- $this->_apiInterface->doRequests($thumbURL, $thumbPath);
160
  }
 
161
  }
162
  } else {
163
  $meta['ShortPixelImprovement'] = 'File is not an image';
@@ -184,115 +186,125 @@ class WPShortPixel {
184
  ORDER BY post_id DESC
185
  LIMIT " . BATCH_SIZE; //add also meta_key='_wp_attachment_metadata' AND ?
186
  $idList = $wpdb->get_results($qry);
187
-
188
  if(empty($idList)) { echo 'Empty queue'; die; }
189
 
190
- foreach($idList as $post) {
191
- $ID = $post->post_id;
192
- $imageURL = wp_get_attachment_url($ID);
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']); }
252
- if(isset($meta['ShortPixel']['WaitingProcessing'])) { unset($meta['ShortPixel']['WaitingProcessing']); }
253
- $meta['ShortPixelImprovement'] = $result;
254
- wp_update_attachment_metadata($ID, $meta);
255
- echo "Error processing image: " . $result;
256
- die;
257
- }
258
-
259
- //$processThumbnails = get_option('wp-short-process_thumbnails');
260
 
 
 
 
 
 
 
 
 
261
 
262
- unset($meta['ShortPixel']['WaitingProcessing']);
263
 
264
- if(isset($meta['ShortPixel']['BulkProcessing'])) {
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
 
 
 
 
 
273
  die();
274
  }
275
 
276
  public function handleManualOptimization() {
277
  $attachmentID = intval($_GET['attachment_ID']);
278
 
279
- $url = wp_get_attachment_url($attachmentID);
280
- $filePath = get_attached_file($attachmentID);
281
  $meta = wp_get_attachment_metadata($attachmentID);
282
 
283
- $result = $this->_apiInterface->processImage($url, $filePath, $attachmentID);
284
-
285
  $processThumbnails = get_option('wp-short-process_thumbnails');
286
 
287
- //handle the rest of the thumbnails generated by WP
288
- if($processThumbnails && $result && !empty($meta['sizes'])) {
289
- foreach($meta['sizes'] as $thumbnailInfo) {
290
- $thumbURL = str_replace(basename($filePath), $thumbnailInfo['file'], $filePath);
291
- $thumbPath = str_replace(basename($filePath), $thumbnailInfo['file'], $filePath);
292
- $this->_apiInterface->processImage($thumbURL, $thumbPath);
 
 
293
  }
294
  }
295
 
 
 
296
  // store the referring webpage location
297
  $sendback = wp_get_referer();
298
  // sanitize the referring webpage location
@@ -307,22 +319,33 @@ class WPShortPixel {
307
 
308
  $uploadFilePath = get_attached_file($attachmentID);
309
  $meta = wp_get_attachment_metadata($attachmentID);
 
310
  $pathInfo = pathinfo($uploadFilePath);
311
- $SubDirs = substr($meta['file'],0,strrpos($meta['file'],"/")+1);
 
 
 
 
 
 
 
 
 
 
312
 
313
  try {
314
- //main file
315
  @rename(SP_BACKUP_FOLDER . DIRECTORY_SEPARATOR . $SubDirs . basename($uploadFilePath), $uploadFilePath);
316
 
317
  //overwriting thumbnails
318
- if(is_array($meta["sizes"])) {
319
  foreach($meta["sizes"] as $size => $imageData) {
320
  $source = SP_BACKUP_FOLDER . DIRECTORY_SEPARATOR . $SubDirs . $imageData['file'];
321
  $destination = $pathInfo['dirname'] . DIRECTORY_SEPARATOR . $imageData['file'];
322
  @rename($source, $destination);
323
  }
324
  }
325
-
326
  unset($meta["ShortPixelImprovement"]);
327
  wp_update_attachment_metadata($attachmentID, $meta);
328
 
@@ -385,22 +408,15 @@ class WPShortPixel {
385
  add_media_page( 'ShortPixel Bulk Process', 'Bulk ShortPixel', 'edit_others_posts', 'wp-short-pixel-bulk', array( &$this, 'bulkProcesss' ) );
386
  }
387
 
388
- public function bulkProcesss() {
389
  echo '<h1>Bulk Image Optimisation by ShortPixel</h1>';
390
 
391
- if(MUST_HAVE_KEY && $this->_verifiedKey == false) {
392
  echo "<p>In order to start processing your images, you need to validate your API key in the ShortPixel Settings. If you don’t have an API Key, you can get one delivered to your inbox.</p>";
393
  echo "<p>Don’t have an API Key yet? Get it now at <a href=\"https://shortpixel.com/wp-apikey\" target=\"_blank\">www.ShortPixel.com</a>, for free.</p>";
394
  return;
395
  }
396
-
397
- $attachments = null;
398
- $attachments = get_posts( array(
399
- 'numberposts' => -1,
400
- 'post_type' => 'attachment',
401
- 'post_mime_type' => 'image'
402
- ));
403
-
404
  if($_GET['cancel']) {
405
  foreach($attachments as $attachment) {
406
  $meta = wp_get_attachment_metadata($attachment->ID);
@@ -409,24 +425,52 @@ class WPShortPixel {
409
  }
410
  }
411
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
412
  if($_POST["bulkProcess"]) {
 
 
 
 
413
  //remove all ShortPixel data from metadata
414
  $imageList = array();
415
  $processThumbnails = get_option('wp-short-process_thumbnails');
416
 
417
  foreach($attachments as $attachment) {
418
- if(self::isProcesable(get_attached_file($attachment->ID)) == false) continue;
419
-
 
420
  //prepare bulk call for processing
421
  $imagePath = wp_get_attachment_url($attachment->ID);
 
 
422
  $imageList[] = $imagePath;
423
 
424
  $meta = wp_get_attachment_metadata($attachment->ID);
 
425
 
426
  if($processThumbnails && isset($meta['sizes'])) {
427
  foreach($meta['sizes'] as $thumbnailData) {
428
- $thumbPath = substr($imagePath, 0, strrpos($imagePath, '/')) . '/' . $thumbnailData["file"];
429
- $imageList[] = $thumbPath;
 
 
 
 
 
 
430
  }
431
  }
432
 
@@ -434,27 +478,29 @@ class WPShortPixel {
434
  wp_update_attachment_metadata($attachment->ID, $meta);
435
  }
436
 
 
437
  if(count($imageList) > 10) {
 
438
  $batchList = array();
439
  foreach($imageList as $image) {
440
  $batchList[] = $image;
441
 
442
  if(count($batchList) == 10) {
443
- $this->_apiInterface->doBulkRequest($batchList);
444
  $batchList = array();
445
  }
446
  }
447
  //send the rest of the images in the list
448
- if(count($batchList) > 0) { $this->_apiInterface->doBulkRequest($batchList); }
449
 
450
  } else {
451
- $this->_apiInterface->doBulkRequest($imageList);
452
  }
453
-
454
 
455
 
456
  update_option('bulkProcessingStatus', 'running');
457
- }
458
 
459
  global $wpdb;
460
  $qry = "SELECT * FROM " . $wpdb->prefix . "postmeta
@@ -521,6 +567,7 @@ class WPShortPixel {
521
  </script>
522
  ';
523
  }
 
524
 
525
  public function renderSettingsMenu() {
526
  if ( !current_user_can( 'manage_options' ) ) {
@@ -823,7 +870,9 @@ HTML;
823
  public function generateCustomColumn( $column_name, $id ) {
824
  if( 'wp-shortPixel' == $column_name ) {
825
  $data = wp_get_attachment_metadata($id);
826
-
 
 
827
  if ( isset( $data['ShortPixelImprovement'] ) ) {
828
  if(isset($meta['ShortPixel']['BulkProcessing'])) {
829
  print 'Waiting for bulk processing';
@@ -850,6 +899,11 @@ HTML;
850
  print " | <a href=\"admin.php?action=shortpixel_manual_optimize&amp;attachment_ID={$id}\">Optimize now</a>";
851
  return;
852
  }
 
 
 
 
 
853
  }
854
  }
855
  }
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.6
7
  * Author: ShortPixel
8
  * Author URI: https://shortpixel.com
9
  */
149
  $url = wp_get_attachment_url($ID);
150
  $path = get_attached_file($ID);
151
  if(self::isProcesable($path) != false) {
152
+ $urlList[] = $url;
153
+ $filePath[] = $path;
154
 
155
+ //send request for thumbs as well, if needed
156
+ if( !empty($meta['sizes']) )
157
+ {
158
  foreach($meta['sizes'] as $thumbnailInfo) {
159
+ $urlList[] = str_replace(basename($url), $thumbnailInfo['file'], $url);
160
+ $filePath[] = str_replace(basename($path), $thumbnailInfo['file'], $path);
 
161
  }
162
+ $this->_apiInterface->doRequests($urlList, $filePath);//send a processing request right after a file was uploaded
163
  }
164
  } else {
165
  $meta['ShortPixelImprovement'] = 'File is not an image';
186
  ORDER BY post_id DESC
187
  LIMIT " . BATCH_SIZE; //add also meta_key='_wp_attachment_metadata' AND ?
188
  $idList = $wpdb->get_results($qry);
189
+
190
  if(empty($idList)) { echo 'Empty queue'; die; }
191
 
192
+ $fileCounter=0;
193
+ $ID=array();
194
+ foreach($idList as $post)
195
+ {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196
  $imageIndex=0;
197
+ $ID = $post->post_id;
198
+ $imageURL = wp_get_attachment_url($ID);
199
+ $imagePath = get_attached_file($ID);
200
+ $meta = wp_get_attachment_metadata($ID);
201
+
202
+ if ( !isset($meta['file']) )//this could be a PDF file
203
  {
204
+ $qry = "SELECT * FROM " . $wpdb->prefix . "postmeta
205
+ WHERE (
206
+ post_id = $ID AND
207
+ meta_key = '_wp_attached_file'
208
+ )";
209
+ $idList = $wpdb->get_results($qry);
210
+ $idList = $idList[0];
211
+ $uploadDir = wp_upload_dir();
212
+ $filePath = $uploadDir['path'] . DIRECTORY_SEPARATOR . basename($idList->meta_value);
213
+
214
+ //check if the image file exists on disk, if not set the right params
215
+ if(!file_exists($filePath)) {
216
+ if(isset($meta['ShortPixel']['BulkProcessing'])) { unset($meta['ShortPixel']['BulkProcessing']); }
217
+ if(isset($meta['ShortPixel']['WaitingProcessing'])) { unset($meta['ShortPixel']['WaitingProcessing']); }
218
+ $meta['ShortPixel']['NoFileOnDisk'] = true;
219
+ wp_update_attachment_metadata($ID, $meta);
220
+ die;
221
+ }
222
+
223
+ $imageURLs[] = $uploadDir['url'] . DIRECTORY_SEPARATOR . basename($idList->meta_value);//URL to PDF file
224
+ $imagePaths[] = $filePath;
225
+ }
226
+ else
227
+ {//process images
228
+ //check if the image file exists on disk, if not set the right params
229
+ if(!file_exists($imagePath)) {
230
+ if(isset($meta['ShortPixel']['BulkProcessing'])) { unset($meta['ShortPixel']['BulkProcessing']); }
231
+ if(isset($meta['ShortPixel']['WaitingProcessing'])) { unset($meta['ShortPixel']['WaitingProcessing']); }
232
+ $meta['ShortPixel']['NoFileOnDisk'] = true;
233
+ wp_update_attachment_metadata($ID, $meta);
234
+ die;
235
+ }
236
+
237
+ //figure out the base URL
238
+ $uploadDir = wp_upload_dir();
239
+ $filesURL = $uploadDir['url'] . DIRECTORY_SEPARATOR;
240
+ $filesPath = $uploadDir['path'] . DIRECTORY_SEPARATOR;
241
+ //create the images' URL list
242
+ $imageURLs[$imageIndex] = $filesURL . basename($meta['file']);//main image first
243
+ $imagePaths[$imageIndex] = $filesPath . basename($meta['file']);
244
+ $processThumbnails = get_option('wp-short-process_thumbnails');
245
+ //handle the rest of the thumbnails generated by WP
246
+ if ( $processThumbnails )
247
  {
248
+ foreach ( $meta['sizes'] as $pictureDetails )
249
+ {
250
+ $imageIndex++;
251
+ $imageURLs[$imageIndex] = $filesURL . $pictureDetails['file'];
252
+ $imagePaths[$imageIndex] = $filesPath . $pictureDetails['file'];
253
+ }
254
  }
255
  }
256
+
257
+ $fileCounter++;
258
+ }
259
+
260
+ $result = $this->_apiInterface->processImage($imageURLs, $imagePaths, $ID);
 
 
 
 
 
 
 
 
 
261
 
262
+ if(is_string($result)) {
263
+ if(isset($meta['ShortPixel']['BulkProcessing'])) { unset($meta['ShortPixel']['BulkProcessing']); }
264
+ if(isset($meta['ShortPixel']['WaitingProcessing'])) { unset($meta['ShortPixel']['WaitingProcessing']); }
265
+ $meta['ShortPixelImprovement'] = $result;
266
+ wp_update_attachment_metadata($ID, $meta);
267
+ echo "Error processing image: " . $result;
268
+ die;
269
+ }
270
 
271
+ //$processThumbnails = get_option('wp-short-process_thumbnails');
272
 
273
+ unset($meta['ShortPixel']['WaitingProcessing']);
 
 
274
 
275
+ if(isset($meta['ShortPixel']['BulkProcessing'])) {
276
+ unset($meta['ShortPixel']['BulkProcessing']);
 
277
  }
278
 
279
+ $meta['ShortPixelImprovement'] = $result[0]->PercentImprovement;
280
+ wp_update_attachment_metadata($ID, $meta);
281
+ echo "Processing done succesfully for image #{$ID}";
282
+
283
  die();
284
  }
285
 
286
  public function handleManualOptimization() {
287
  $attachmentID = intval($_GET['attachment_ID']);
288
 
289
+ $urlList[] = wp_get_attachment_url($attachmentID);
290
+ $filePath[] = get_attached_file($attachmentID);
291
  $meta = wp_get_attachment_metadata($attachmentID);
292
 
 
 
293
  $processThumbnails = get_option('wp-short-process_thumbnails');
294
 
295
+ //process all files (including thumbs)
296
+ if($processThumbnails && !empty($meta['sizes'])) {
297
+ //we generate an array with the URLs that need to be handled
298
+ $SubDirs = substr($meta['file'],0,strrpos($meta['file'],"/")+1);
299
+ foreach($meta['sizes'] as $thumbnailInfo)
300
+ {
301
+ $urlList[]= str_replace(basename($filePath[0]), $thumbnailInfo['file'], $urlList[0]);
302
+ $filePath[] = str_replace(basename($filePath[0]), $thumbnailInfo['file'], $filePath[0]);
303
  }
304
  }
305
 
306
+ $result = $this->_apiInterface->processImage($urlList, $filePath, $attachmentID);//request to process all the images
307
+
308
  // store the referring webpage location
309
  $sendback = wp_get_referer();
310
  // sanitize the referring webpage location
319
 
320
  $uploadFilePath = get_attached_file($attachmentID);
321
  $meta = wp_get_attachment_metadata($attachmentID);
322
+ $uploadDir = wp_upload_dir();
323
  $pathInfo = pathinfo($uploadFilePath);
324
+ $file = get_attached_file($attachmentID);
325
+ $fileExtension = strtolower(substr($file,strrpos($file,".")+1));
326
+ if ( $fileExtension <> "pdf" )
327
+ $SubDirs = substr($meta['file'],0,strrpos($meta['file'],"/")+1);
328
+ else
329
+ $SubDirs = substr(str_replace($uploadDir['basedir'],"", $pathInfo['dirname']),1) . "/";//generate subdirs for PDF files
330
+
331
+ //sometimes the month of original file and backup can differ
332
+ if ( !file_exists(SP_BACKUP_FOLDER . DIRECTORY_SEPARATOR . $SubDirs . basename($uploadFilePath)) )
333
+ $SubDirs = date("Y") . "/" . date("m") . "/";
334
+
335
 
336
  try {
337
+ //main file
338
  @rename(SP_BACKUP_FOLDER . DIRECTORY_SEPARATOR . $SubDirs . basename($uploadFilePath), $uploadFilePath);
339
 
340
  //overwriting thumbnails
341
+ if($fileExtension <> "pdf") {
342
  foreach($meta["sizes"] as $size => $imageData) {
343
  $source = SP_BACKUP_FOLDER . DIRECTORY_SEPARATOR . $SubDirs . $imageData['file'];
344
  $destination = $pathInfo['dirname'] . DIRECTORY_SEPARATOR . $imageData['file'];
345
  @rename($source, $destination);
346
  }
347
  }
348
+
349
  unset($meta["ShortPixelImprovement"]);
350
  wp_update_attachment_metadata($attachmentID, $meta);
351
 
408
  add_media_page( 'ShortPixel Bulk Process', 'Bulk ShortPixel', 'edit_others_posts', 'wp-short-pixel-bulk', array( &$this, 'bulkProcesss' ) );
409
  }
410
 
411
+ public function bulkProcesss() {//fai
412
  echo '<h1>Bulk Image Optimisation by ShortPixel</h1>';
413
 
414
+ if(MUST_HAVE_KEY && $this->_verifiedKey == false) {//invalid API Key
415
  echo "<p>In order to start processing your images, you need to validate your API key in the ShortPixel Settings. If you don’t have an API Key, you can get one delivered to your inbox.</p>";
416
  echo "<p>Don’t have an API Key yet? Get it now at <a href=\"https://shortpixel.com/wp-apikey\" target=\"_blank\">www.ShortPixel.com</a>, for free.</p>";
417
  return;
418
  }
419
+
 
 
 
 
 
 
 
420
  if($_GET['cancel']) {
421
  foreach($attachments as $attachment) {
422
  $meta = wp_get_attachment_metadata($attachment->ID);
425
  }
426
  }
427
 
428
+ $attachments = null;
429
+ $attachments_images = get_posts( array(
430
+ 'numberposts' => -1,
431
+ 'post_type' => 'attachment',
432
+ 'post_mime_type' => 'image'
433
+ ));
434
+ $attachments_pdf = get_posts( array(
435
+ 'numberposts' => -1,
436
+ 'post_type' => 'attachment',
437
+ 'post_mime_type' => 'application/pdf'
438
+ ));
439
+ $attachments = array_merge($attachments_images, $attachments_pdf);
440
+
441
+
442
  if($_POST["bulkProcess"]) {
443
+
444
+ $uploadDir = wp_upload_dir();
445
+ $uploadDir = $uploadDir['basedir'];
446
+
447
  //remove all ShortPixel data from metadata
448
  $imageList = array();
449
  $processThumbnails = get_option('wp-short-process_thumbnails');
450
 
451
  foreach($attachments as $attachment) {
452
+ if(self::isProcesable(get_attached_file($attachment->ID)) == false) continue;//skip this record
453
+ //apparently if the main image isn't on disk -> the result is false above
454
+
455
  //prepare bulk call for processing
456
  $imagePath = wp_get_attachment_url($attachment->ID);
457
+ $filePathOnDisk = get_attached_file($attachment->ID);
458
+ $imageDiskPath[] = $filePathOnDisk;
459
  $imageList[] = $imagePath;
460
 
461
  $meta = wp_get_attachment_metadata($attachment->ID);
462
+ $SubDirs = substr($meta['file'],0,strrpos($meta['file'],"/")+1);
463
 
464
  if($processThumbnails && isset($meta['sizes'])) {
465
  foreach($meta['sizes'] as $thumbnailData) {
466
+ $imageOnDisk = $uploadDir . DIRECTORY_SEPARATOR . $SubDirs . basename($thumbnailData["file"]);
467
+
468
+ if ( file_exists($imageOnDisk) )//make sure each version of the main file is on disk
469
+ {
470
+ $thumbPath = substr($imagePath, 0, strrpos($imagePath, '/')) . '/' . $thumbnailData["file"];
471
+ $imageList[] = $thumbPath;
472
+ $imageDiskPath[] = $imageOnDisk;
473
+ }
474
  }
475
  }
476
 
478
  wp_update_attachment_metadata($attachment->ID, $meta);
479
  }
480
 
481
+
482
  if(count($imageList) > 10) {
483
+ echo "<BR>Counter going";
484
  $batchList = array();
485
  foreach($imageList as $image) {
486
  $batchList[] = $image;
487
 
488
  if(count($batchList) == 10) {
489
+ // $this->_apiInterface->doBulkRequest($batchList);
490
  $batchList = array();
491
  }
492
  }
493
  //send the rest of the images in the list
494
+ // if(count($batchList) > 0) { $this->_apiInterface->doBulkRequest($batchList); }
495
 
496
  } else {
497
+ // $this->_apiInterface->doBulkRequest($imageList);
498
  }
499
+ echo "again<BR>";
500
 
501
 
502
  update_option('bulkProcessingStatus', 'running');
503
+ }//end bulk process
504
 
505
  global $wpdb;
506
  $qry = "SELECT * FROM " . $wpdb->prefix . "postmeta
567
  </script>
568
  ';
569
  }
570
+ //end bulk processing
571
 
572
  public function renderSettingsMenu() {
573
  if ( !current_user_can( 'manage_options' ) ) {
870
  public function generateCustomColumn( $column_name, $id ) {
871
  if( 'wp-shortPixel' == $column_name ) {
872
  $data = wp_get_attachment_metadata($id);
873
+ $file = get_attached_file($id);
874
+ $fileExtension = strtolower(substr($file,strrpos($file,".")+1));
875
+
876
  if ( isset( $data['ShortPixelImprovement'] ) ) {
877
  if(isset($meta['ShortPixel']['BulkProcessing'])) {
878
  print 'Waiting for bulk processing';
899
  print " | <a href=\"admin.php?action=shortpixel_manual_optimize&amp;attachment_ID={$id}\">Optimize now</a>";
900
  return;
901
  }
902
+ elseif ( $fileExtension == "pdf" ){
903
+ print 'PDF not processed';
904
+ print " | <a href=\"admin.php?action=shortpixel_manual_optimize&amp;attachment_ID={$id}\">Optimize now</a>";
905
+ return;
906
+ }
907
  }
908
  }
909
  }