ShortPixel Image Optimizer - Version 4.11.1

Version Description

  • compatibility with the MediaPress plugin
  • new action to be called by when thumbnails are regenerated: shortpixel-thumbnails-regenerated
  • accept '+' inside the e-mail address
  • fix optimization not working on internationalized domain names
  • better count of the not optimized thumbs for an image, in some circumstances
  • fallback to ABSPATH when get_home_path() returns '/'
  • fix settings tabs navigation when url ends with #/
  • extract all release notes < 4.9 from readme.txt into changelog.txt
  • display the thumbnail name for some errors which refer only to a specific thumbnail.
  • use update_post_meta() instead of wp_update_attachment_metadata() for cases when other plugins cannot be concerned by the meta change (specific to ShortPixel)
  • add the attributes of the original to the replacement tag, in case the "Generate WebP Markup" option is active.
  • fix action buttons in media edit view overflowing their box
  • restore full compatibility with WP < 4.1 by checking first before using wp_json_encode
  • fix admin when domain is internationalized but the setting in admin uses the punycode-encrypted version
Download this release

Release Info

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

Code changes from version 4.11.0 to 4.11.1

class/db/shortpixel-custom-meta-dao.php CHANGED
@@ -440,7 +440,7 @@ class ShortPixelCustomMetaDao {
440
  $filesWithErrors = array(); $moreFilesWithErrors = 0;
441
  foreach($failRows as $failLine) {
442
  if(count($filesWithErrors) < 50){
443
- $filesWithErrors['C-' . $failLine->id] = array('Name' => $failLine->name, 'Message' => $failLine->message, 'Path' => $failLine->path);
444
  } else {
445
  $moreFilesWithErrors++;
446
  }
440
  $filesWithErrors = array(); $moreFilesWithErrors = 0;
441
  foreach($failRows as $failLine) {
442
  if(count($filesWithErrors) < 50){
443
+ $filesWithErrors['C-' . $failLine->id] = array('Id' => 'C-' . $failLine->id, 'Name' => $failLine->name, 'Message' => $failLine->message, 'Path' => $failLine->path);
444
  } else {
445
  $moreFilesWithErrors++;
446
  }
class/db/shortpixel-meta-facade.php CHANGED
@@ -191,8 +191,9 @@ class ShortPixelMetaFacade {
191
  if($this->meta->getStatus() >= 0) {
192
  unset($rawMeta['ShortPixel']['ErrCode']);
193
  }
194
-
195
- wp_update_attachment_metadata($_ID, $rawMeta);
 
196
  update_post_meta($_ID, '_shortpixel_status', $this->meta->getStatus());
197
 
198
  if($_ID == $this->ID) {
@@ -221,7 +222,8 @@ class ShortPixelMetaFacade {
221
  unset($rawMeta['ShortPixelPng2Jpg']);
222
  }
223
  unset($this->meta);
224
- wp_update_attachment_metadata($this->ID, $rawMeta);
 
225
  $this->rawMeta = $rawMeta;
226
  } else {
227
  throw new Exception("Not implemented 1");
@@ -233,7 +235,8 @@ class ShortPixelMetaFacade {
233
  throw new Exception("Not implemented 1");
234
  } else {
235
  unset($this->rawMeta['ShortPixel']);
236
- wp_update_attachment_metadata($this->ID, $this->rawMeta);
 
237
  }
238
  }
239
 
@@ -245,7 +248,8 @@ class ShortPixelMetaFacade {
245
  unset($this->rawMeta['ShortPixel']);
246
  unset($this->rawMeta['ShortPixelPng2Jpg']);
247
  unset($this->meta);
248
- wp_update_attachment_metadata($this->ID, $this->rawMeta);
 
249
  }
250
  }
251
 
@@ -273,7 +277,8 @@ class ShortPixelMetaFacade {
273
  } else {
274
  unset($this->rawMeta['ShortPixel']['WaitingProcessing']);
275
  }
276
- wp_update_attachment_metadata($this->ID, $this->rawMeta);
 
277
  }
278
  }
279
 
@@ -290,7 +295,8 @@ class ShortPixelMetaFacade {
290
  $this->rawMeta['ShortPixelImprovement'] = $this->meta->getMessage();
291
  $this->rawMeta['ShortPixel']['ErrCode'] = $errorCode;
292
  unset($this->rawMeta['ShortPixel']['WaitingProcessing']);
293
- wp_update_attachment_metadata($this->ID, $this->rawMeta);
 
294
  }
295
  }
296
 
@@ -302,7 +308,8 @@ class ShortPixelMetaFacade {
302
  } else {
303
  $this->rawMeta['ShortPixelImprovement'] = $this->meta->getMessage();
304
  unset($this->rawMeta['ShortPixel']['WaitingProcessing']);
305
- wp_update_attachment_metadata($this->ID, $this->rawMeta);
 
306
  }
307
  }
308
 
@@ -362,8 +369,7 @@ class ShortPixelMetaFacade {
362
  &&*/ ($processThumbnails || $onlyThumbs)
363
  && count($sizes))
364
  {
365
- $uploadDir = wp_upload_dir();
366
- $Tmp = explode("/", $uploadDir['basedir']);
367
  $TmpCount = count($Tmp);
368
  $StichString = $Tmp[$TmpCount-2] . "/" . $Tmp[$TmpCount-1];
369
 
@@ -395,10 +401,10 @@ class ShortPixelMetaFacade {
395
 
396
  $origPath = $tPath = str_replace(ShortPixelAPI::MB_basename($path), $thumbnailInfo['file'], $path);
397
  if ( !file_exists($tPath) ) {
398
- $tPath = $uploadDir['basedir'] . substr($tPath, strpos($tPath, $StichString) + strlen($StichString));
399
  }
400
  if ( !file_exists($tPath) ) {
401
- $tPath = trailingslashit($uploadDir['basedir']) . $origPath;
402
  }
403
  if (file_exists($tPath)) {
404
  $tUrl = str_replace(ShortPixelAPI::MB_basename($url), $thumbnailInfo['file'], $url);
@@ -417,7 +423,7 @@ class ShortPixelMetaFacade {
417
  WPShortPixel::log("getURLsAndPATHs: no meta sizes for ID " . $this->ID . " : " . json_encode($this->rawMeta));
418
  }
419
 
420
- if($onlyThumbs && $mainExists && count($urlList) > 1) { //remove the main image
421
  array_shift($urlList);
422
  array_shift($filePaths);
423
  }
@@ -609,7 +615,11 @@ class ShortPixelMetaFacade {
609
  */
610
  static public function returnSubDir($file)
611
  {
612
- $hp = wp_normalize_path(get_home_path());
 
 
 
 
613
  $file = wp_normalize_path($file);
614
  $sp__uploads = wp_upload_dir();
615
  if(strstr($file, $hp)) {
@@ -618,8 +628,8 @@ class ShortPixelMetaFacade {
618
  $path = str_replace( trailingslashit(dirname( WP_CONTENT_DIR )), "", $file);
619
  } elseif( (strstr(realpath($file), realpath($hp)))) {
620
  $path = str_replace( realpath($hp), "", realpath($file));
621
- } elseif( strstr($file, trailingslashit(dirname(dirname( $sp__uploads['basedir'] )))) ) {
622
- $path = str_replace( trailingslashit(dirname(dirname( $sp__uploads['basedir'] ))), "", $file);
623
  } else {
624
  $path = (substr($file, 1));
625
  }
@@ -630,7 +640,7 @@ class ShortPixelMetaFacade {
630
 
631
  public static function isMediaSubfolder($path, $orParent = true) {
632
  $uploadDir = wp_upload_dir();
633
- $uploadBase = $uploadDir["basedir"];
634
  $uploadPath = $uploadDir["path"];
635
  //contains the current media upload path
636
  if($orParent && ShortPixelFolder::checkFolderIsSubfolder($uploadPath, $path)) {
191
  if($this->meta->getStatus() >= 0) {
192
  unset($rawMeta['ShortPixel']['ErrCode']);
193
  }
194
+
195
+ update_post_meta($this->ID, '_wp_attachment_metadata', $this->rawMeta);
196
+ //wp_update_attachment_metadata($_ID, $rawMeta);
197
  update_post_meta($_ID, '_shortpixel_status', $this->meta->getStatus());
198
 
199
  if($_ID == $this->ID) {
222
  unset($rawMeta['ShortPixelPng2Jpg']);
223
  }
224
  unset($this->meta);
225
+ update_post_meta($this->ID, '_wp_attachment_metadata', $this->rawMeta);
226
+ //wp_update_attachment_metadata($this->ID, $rawMeta);
227
  $this->rawMeta = $rawMeta;
228
  } else {
229
  throw new Exception("Not implemented 1");
235
  throw new Exception("Not implemented 1");
236
  } else {
237
  unset($this->rawMeta['ShortPixel']);
238
+ update_post_meta($this->ID, '_wp_attachment_metadata', $this->rawMeta);
239
+ //wp_update_attachment_metadata($this->ID, $this->rawMeta);
240
  }
241
  }
242
 
248
  unset($this->rawMeta['ShortPixel']);
249
  unset($this->rawMeta['ShortPixelPng2Jpg']);
250
  unset($this->meta);
251
+ update_post_meta($this->ID, '_wp_attachment_metadata', $this->rawMeta);
252
+ //wp_update_attachment_metadata($this->ID, $this->rawMeta);
253
  }
254
  }
255
 
277
  } else {
278
  unset($this->rawMeta['ShortPixel']['WaitingProcessing']);
279
  }
280
+ update_post_meta($this->ID, '_wp_attachment_metadata', $this->rawMeta);
281
+ //wp_update_attachment_metadata($this->ID, $this->rawMeta);
282
  }
283
  }
284
 
295
  $this->rawMeta['ShortPixelImprovement'] = $this->meta->getMessage();
296
  $this->rawMeta['ShortPixel']['ErrCode'] = $errorCode;
297
  unset($this->rawMeta['ShortPixel']['WaitingProcessing']);
298
+ update_post_meta($this->ID, '_wp_attachment_metadata', $this->rawMeta);
299
+ //wp_update_attachment_metadata($this->ID, $this->rawMeta);
300
  }
301
  }
302
 
308
  } else {
309
  $this->rawMeta['ShortPixelImprovement'] = $this->meta->getMessage();
310
  unset($this->rawMeta['ShortPixel']['WaitingProcessing']);
311
+ update_post_meta($this->ID, '_wp_attachment_metadata', $this->rawMeta);
312
+ //wp_update_attachment_metadata($this->ID, $this->rawMeta);
313
  }
314
  }
315
 
369
  &&*/ ($processThumbnails || $onlyThumbs)
370
  && count($sizes))
371
  {
372
+ $Tmp = explode("/", SHORTPIXEL_UPLOADS_BASE);
 
373
  $TmpCount = count($Tmp);
374
  $StichString = $Tmp[$TmpCount-2] . "/" . $Tmp[$TmpCount-1];
375
 
401
 
402
  $origPath = $tPath = str_replace(ShortPixelAPI::MB_basename($path), $thumbnailInfo['file'], $path);
403
  if ( !file_exists($tPath) ) {
404
+ $tPath = SHORTPIXEL_UPLOADS_BASE . substr($tPath, strpos($tPath, $StichString) + strlen($StichString));
405
  }
406
  if ( !file_exists($tPath) ) {
407
+ $tPath = trailingslashit(SHORTPIXEL_UPLOADS_BASE) . $origPath;
408
  }
409
  if (file_exists($tPath)) {
410
  $tUrl = str_replace(ShortPixelAPI::MB_basename($url), $thumbnailInfo['file'], $url);
423
  WPShortPixel::log("getURLsAndPATHs: no meta sizes for ID " . $this->ID . " : " . json_encode($this->rawMeta));
424
  }
425
 
426
+ if($onlyThumbs && $mainExists && count($urlList) >= 1) { //remove the main image
427
  array_shift($urlList);
428
  array_shift($filePaths);
429
  }
615
  */
616
  static public function returnSubDir($file)
617
  {
618
+ $homePath = get_home_path();
619
+ if($homePath == '/') {
620
+ $homePath = ABSPATH;
621
+ }
622
+ $hp = wp_normalize_path($homePath);
623
  $file = wp_normalize_path($file);
624
  $sp__uploads = wp_upload_dir();
625
  if(strstr($file, $hp)) {
628
  $path = str_replace( trailingslashit(dirname( WP_CONTENT_DIR )), "", $file);
629
  } elseif( (strstr(realpath($file), realpath($hp)))) {
630
  $path = str_replace( realpath($hp), "", realpath($file));
631
+ } elseif( strstr($file, trailingslashit(dirname(dirname( SHORTPIXEL_UPLOADS_BASE )))) ) {
632
+ $path = str_replace( trailingslashit(dirname(dirname( SHORTPIXEL_UPLOADS_BASE ))), "", $file);
633
  } else {
634
  $path = (substr($file, 1));
635
  }
640
 
641
  public static function isMediaSubfolder($path, $orParent = true) {
642
  $uploadDir = wp_upload_dir();
643
+ $uploadBase = SHORTPIXEL_UPLOADS_BASE;
644
  $uploadPath = $uploadDir["path"];
645
  //contains the current media upload path
646
  if($orParent && ShortPixelFolder::checkFolderIsSubfolder($uploadPath, $path)) {
class/db/wp-shortpixel-media-library-adapter.php CHANGED
@@ -188,7 +188,7 @@ class WpShortPixelMediaLbraryAdapter {
188
  if(count($filesWithErrors) < 50) {
189
  $filePath = explode("/", $attachment["file"]);
190
  $name = is_array($filePath)? $filePath[count($filePath) - 1] : $file->post_id;
191
- $filesWithErrors[$file->post_id] = array('Name' => $name, 'Message' => $attachment['ShortPixelImprovement']);
192
  } else {
193
  $moreFilesWithErrors++;
194
  }
188
  if(count($filesWithErrors) < 50) {
189
  $filePath = explode("/", $attachment["file"]);
190
  $name = is_array($filePath)? $filePath[count($filePath) - 1] : $file->post_id;
191
+ $filesWithErrors[$file->post_id] = array('Id' => $file->post_id, 'Name' => $name, 'Message' => $attachment['ShortPixelImprovement']);
192
  } else {
193
  $moreFilesWithErrors++;
194
  }
class/front/img-to-picture-webp.php CHANGED
@@ -35,7 +35,7 @@ class ShortPixelImgToPictureWebp {
35
  $base = explode("://", $updir['baseurl']);
36
  $updir['baseurl'] = $proto . "://" . $base[1];
37
  }
38
- $imageBase = str_replace($updir['baseurl'], $updir['basedir'], $src);
39
  if($imageBase == $src) {
40
  return $match[0];
41
  }
@@ -77,7 +77,7 @@ class ShortPixelImgToPictureWebp {
77
  //add the exclude class so if this content is processed again in other filter, the img is not converted again in picture
78
  $img['class'] = (isset($img['class']) ? $img['class'] . " " : "") . "sp-no-webp";
79
 
80
- return '<picture>'
81
  .'<source srcset="' . $srcsetWebP . '"' . ($sizes ? ' sizes="' . $sizes . '"' : '') . ' type="image/webp">'
82
  .'<source srcset="' . $srcset . '"' . ($sizes ? ' sizes="' . $sizes . '"' : '') . '>'
83
  .'<img src="' . $src . '" ' . $thisClass::create_attributes($img) . '>'
35
  $base = explode("://", $updir['baseurl']);
36
  $updir['baseurl'] = $proto . "://" . $base[1];
37
  }
38
+ $imageBase = str_replace($updir['baseurl'], SHORTPIXEL_UPLOADS_BASE, $src);
39
  if($imageBase == $src) {
40
  return $match[0];
41
  }
77
  //add the exclude class so if this content is processed again in other filter, the img is not converted again in picture
78
  $img['class'] = (isset($img['class']) ? $img['class'] . " " : "") . "sp-no-webp";
79
 
80
+ return '<picture ' . $thisClass::create_attributes($img) . '>'
81
  .'<source srcset="' . $srcsetWebP . '"' . ($sizes ? ' sizes="' . $sizes . '"' : '') . ' type="image/webp">'
82
  .'<source srcset="' . $srcset . '"' . ($sizes ? ' sizes="' . $sizes . '"' : '') . '>'
83
  .'<img src="' . $src . '" ' . $thisClass::create_attributes($img) . '>'
class/model/shortpixel-folder.php CHANGED
@@ -92,8 +92,7 @@ class ShortPixelFolder extends ShortPixelEntity{
92
  }
93
 
94
  public function getFileList($onlyNewerThan = 0) {
95
- $upl = wp_upload_dir();
96
- $fileListPath = tempnam($upl["basedir"] . '/', 'sp_');
97
  $fileHandle = fopen($fileListPath, 'w+');
98
  self::getFileListRecursive($this->getPath(), $fileHandle, $onlyNewerThan);
99
  fclose($fileHandle);
92
  }
93
 
94
  public function getFileList($onlyNewerThan = 0) {
95
+ $fileListPath = tempnam(SHORTPIXEL_UPLOADS_BASE . '/', 'sp_');
 
96
  $fileHandle = fopen($fileListPath, 'w+');
97
  self::getFileListRecursive($this->getPath(), $fileHandle, $onlyNewerThan);
98
  fclose($fileHandle);
class/shortpixel-png2jpg.php CHANGED
@@ -220,7 +220,8 @@ class ShortPixelPng2Jpg {
220
  }
221
  $meta['ShortPixel']['Retries'] = isset($meta['ShortPixel']['Retries']) ? $meta['ShortPixel']['Retries'] + 1 : 1;
222
  $meta['ShortPixel']['ErrCode'] = ShortPixelAPI::ERR_PNG2JPG_MEMORY;
223
- wp_update_attachment_metadata($ID, $meta);
 
224
 
225
  if($this->_settings->png2jpg == 2) {
226
  $doConvert = true;
@@ -244,7 +245,8 @@ class ShortPixelPng2Jpg {
244
  unset($meta['ShortPixelImprovement']);
245
  unset($meta['ShortPixel']['ErrCode']);
246
  $meta['ShortPixel']['Retries'] -= 1;
247
- wp_update_attachment_metadata($ID, $meta);
 
248
 
249
  if ($ret['type'] == 'image/jpeg') {
250
  $toUnlink[] = $retMain->unlink;
@@ -284,7 +286,8 @@ class ShortPixelPng2Jpg {
284
  $meta['ShortPixelPng2Jpg'] = array('originalFile' => $imagePath, 'originalSizes' => $originalSizes, 'originalSizes2' => $originalSizes,
285
  'backup' => $this->_settings->backupImages,
286
  'optimizationPercent' => round(100.0 * (1.00 - $jpgSize / $pngSize)));
287
- wp_update_attachment_metadata($ID, $meta);
 
288
  }
289
 
290
  self::png2JpgUpdateUrls(array(), $toReplace);
@@ -313,7 +316,8 @@ class ShortPixelPng2Jpg {
313
  $meta['type'] = 'image/jpeg';
314
  if($parentID == $ID) $parentMeta = $meta;
315
  update_attached_file($ID, $meta['file']);
316
- wp_update_attachment_metadata($ID, $meta);
 
317
  }
318
  return $duplicates;
319
  }
@@ -331,7 +335,8 @@ class ShortPixelPng2Jpg {
331
  $meta['sizes'][$size]['file'] = wp_basename($thumbnail);
332
  $meta['sizes'][$size]['mime-type'] = 'image/jpeg';
333
  if($parentID == $ID) $parentMeta = $meta;
334
- wp_update_attachment_metadata($ID, $meta);
 
335
  }
336
  }
337
 
220
  }
221
  $meta['ShortPixel']['Retries'] = isset($meta['ShortPixel']['Retries']) ? $meta['ShortPixel']['Retries'] + 1 : 1;
222
  $meta['ShortPixel']['ErrCode'] = ShortPixelAPI::ERR_PNG2JPG_MEMORY;
223
+ //wp_update_attachment_metadata($ID, $meta);
224
+ update_post_meta($ID, '_wp_attachment_metadata', $meta);
225
 
226
  if($this->_settings->png2jpg == 2) {
227
  $doConvert = true;
245
  unset($meta['ShortPixelImprovement']);
246
  unset($meta['ShortPixel']['ErrCode']);
247
  $meta['ShortPixel']['Retries'] -= 1;
248
+ //wp_update_attachment_metadata($ID, $meta);
249
+ update_post_meta($ID, '_wp_attachment_metadata', $meta);
250
 
251
  if ($ret['type'] == 'image/jpeg') {
252
  $toUnlink[] = $retMain->unlink;
286
  $meta['ShortPixelPng2Jpg'] = array('originalFile' => $imagePath, 'originalSizes' => $originalSizes, 'originalSizes2' => $originalSizes,
287
  'backup' => $this->_settings->backupImages,
288
  'optimizationPercent' => round(100.0 * (1.00 - $jpgSize / $pngSize)));
289
+ //wp_update_attachment_metadata($ID, $meta);
290
+ update_post_meta($ID, '_wp_attachment_metadata', $meta);
291
  }
292
 
293
  self::png2JpgUpdateUrls(array(), $toReplace);
316
  $meta['type'] = 'image/jpeg';
317
  if($parentID == $ID) $parentMeta = $meta;
318
  update_attached_file($ID, $meta['file']);
319
+ //wp_update_attachment_metadata($ID, $meta);
320
+ update_post_meta($ID, '_wp_attachment_metadata', $meta);
321
  }
322
  return $duplicates;
323
  }
335
  $meta['sizes'][$size]['file'] = wp_basename($thumbnail);
336
  $meta['sizes'][$size]['mime-type'] = 'image/jpeg';
337
  if($parentID == $ID) $parentMeta = $meta;
338
+ //wp_update_attachment_metadata($ID, $meta);
339
+ update_post_meta($ID, '_wp_attachment_metadata', $meta);
340
  }
341
  }
342
 
class/shortpixel_queue.php CHANGED
@@ -27,7 +27,7 @@ class ShortPixelQueue {
27
 
28
  public static function get() {
29
  $fp = self::openQ(LOCK_SH);
30
- if(!$fp) return false;
31
  $itemsRaw = fgets($fp);
32
  $items = strlen($itemsRaw) ? self::parseQ($itemsRaw) : array();
33
  self::closeQ($fp);
@@ -42,6 +42,7 @@ class ShortPixelQueue {
42
  fwrite($fp, implode(',', $items));
43
  fflush($fp); // flush output before releasing the lock
44
  self::closeQ($fp);
 
45
  }
46
 
47
  public function apply($callable, $extra = false) {
27
 
28
  public static function get() {
29
  $fp = self::openQ(LOCK_SH);
30
+ if(!$fp) return array();
31
  $itemsRaw = fgets($fp);
32
  $items = strlen($itemsRaw) ? self::parseQ($itemsRaw) : array();
33
  self::closeQ($fp);
42
  fwrite($fp, implode(',', $items));
43
  fflush($fp); // flush output before releasing the lock
44
  self::closeQ($fp);
45
+ return true;
46
  }
47
 
48
  public function apply($callable, $extra = false) {
class/view/shortpixel_view.php CHANGED
@@ -431,7 +431,7 @@ class ShortPixelView {
431
  if(ShortPixelMetaFacade::isCustomQueuedId($id)) {
432
  echo('<a href="'. ShortPixelMetaFacade::getHomeUrl() . ShortPixelMetaFacade::filenameToRootRelative($data['Path']).'" title="'.$data['Message'].'" target="_blank">'.$data['Name'].'</a>');
433
  } else {
434
- echo('<a href="post.php?post='.$id.'&action=edit" title="'.$data['Message'].'">'.$data['Name'].'</a>');
435
  }
436
  }
437
  if(isset($quotaData['moreFilesWithErrors']) && $quotaData['moreFilesWithErrors']) {
@@ -507,6 +507,7 @@ class ShortPixelView {
507
  </form>
508
  </div>
509
  <?php } ?>
 
510
  </div>
511
  <?php
512
  }
@@ -768,8 +769,10 @@ class ShortPixelView {
768
  ShortPixel.adjustSettingsTabs();
769
  });
770
  if(window.location.hash) {
771
- var target = 'tab-' + window.location.hash.substring(window.location.hash.indexOf("#")+1)
772
- ShortPixel.switchSettingsTab(target);
 
 
773
  }
774
  jQuery("article.sp-tabs a.tab-link").click(function(){ShortPixel.switchSettingsTab(jQuery(this).data("id"))});
775
  });
@@ -1470,14 +1473,16 @@ class ShortPixelView {
1470
  </a> <?php
1471
  } else {
1472
  if($data['status'] == 'retry') { ?>
1473
- <a class="button button-smaller sp-action-restore" href="admin.php?action=shortpixel_restore_backup&attachment_ID=<?php echo($id)?>" style="margin-left:5px;"
1474
- title="Cleanup the metadata and return the image to the status before the error.">
1475
- <?php _e('Cleanup','shortpixel-image-optimiser');?>
1476
- </a>
1477
- <?php } ?>
1478
- <a class='button button-smaller button-primary' href="javascript:manualOptimization('<?php echo($id)?>', false)">
1479
- <?php _e('Retry','shortpixel-image-optimiser');?>
1480
- </a>
 
 
1481
  <?php
1482
  }
1483
  break;
@@ -1508,9 +1513,7 @@ class ShortPixelView {
1508
  . $excludeSizes . $missingThumbs;
1509
  }
1510
 
1511
- $this->renderListCell($id, $data['status'], $data['showActions'],
1512
- (!$data['thumbsOpt'] && $data['thumbsTotal']) //no thumb was optimized
1513
- || (count($data['thumbsOptList']) && ($data['thumbsTotal'] - $data['thumbsOpt'] - $excluded > 0)), $data['thumbsTotal'] - $data['thumbsOpt'],
1514
  $data['backup'], $data['type'], $data['invType'], $successText);
1515
 
1516
  break;
@@ -1536,16 +1539,16 @@ class ShortPixelView {
1536
  .($retinasOpt ? '<br>' . sprintf(__('+%s Retina images optimized','shortpixel-image-optimiser') , $retinasOpt) : '' );
1537
  }
1538
 
1539
- public function renderListCell($id, $status, $showActions, $optimizeThumbs, $thumbsRemain, $backup, $type, $invType, $message, $extraClass = '') {
1540
- if($showActions && ($backup || $optimizeThumbs)) { ?>
1541
  <div class='sp-column-actions <?php echo($extraClass);?>'>
1542
  <div class="sp-dropdown">
1543
- <button onclick="ShortPixel.openImageMenu(event);" class="sp-dropbtn button <?php if($optimizeThumbs) { echo('button-primary'); } ?> dashicons dashicons-menu" title="ShortPixel Actions"></button>
1544
  <div id="sp-dd-<?php echo($id);?>" class="sp-dropdown-content">
1545
  <?php if($backup && $status == 'imgOptimized') { ?>
1546
  <a class="sp-action-compare" href="javascript:ShortPixel.loadComparer('<?php echo($id);?>')" title="Compare optimized image with the original">Compare</a>
1547
  <?php } ?>
1548
- <?php if($optimizeThumbs) { ?>
1549
  <a class="sp-action-optimize-thumbs" href="javascript:optimizeThumbs(<?php echo($id)?>);" style="background-color:#0085ba;color:white;">
1550
  <?php printf(__('Optimize %s thumbnails','shortpixel-image-optimiser'),$thumbsRemain);?>
1551
  </a>
431
  if(ShortPixelMetaFacade::isCustomQueuedId($id)) {
432
  echo('<a href="'. ShortPixelMetaFacade::getHomeUrl() . ShortPixelMetaFacade::filenameToRootRelative($data['Path']).'" title="'.$data['Message'].'" target="_blank">'.$data['Name'].'</a>');
433
  } else {
434
+ echo('<a href="post.php?post='.$data['Id'].'&action=edit" title="'.$data['Message'].'">'.$data['Name'].'</a>');
435
  }
436
  }
437
  if(isset($quotaData['moreFilesWithErrors']) && $quotaData['moreFilesWithErrors']) {
507
  </form>
508
  </div>
509
  <?php } ?>
510
+ <script>if(window.location.hash == '#pending') {jQuery('#bulkCleanupPending').css('display','')}</script>
511
  </div>
512
  <?php
513
  }
769
  ShortPixel.adjustSettingsTabs();
770
  });
771
  if(window.location.hash) {
772
+ var target = ('tab-' + window.location.hash.substring(window.location.hash.indexOf("#")+1)).replace(/\//, '');
773
+ if(jQuery("section#" + target).length) {
774
+ ShortPixel.switchSettingsTab(target);
775
+ }
776
  }
777
  jQuery("article.sp-tabs a.tab-link").click(function(){ShortPixel.switchSettingsTab(jQuery(this).data("id"))});
778
  });
1473
  </a> <?php
1474
  } else {
1475
  if($data['status'] == 'retry') { ?>
1476
+ <div style="overflow:hidden">
1477
+ <a class="button button-smaller sp-action-restore" href="admin.php?action=shortpixel_restore_backup&attachment_ID=<?php echo($id)?>" style="margin-left:5px;"
1478
+ title="Cleanup the metadata and return the image to the status before the error.">
1479
+ <?php _e('Cleanup','shortpixel-image-optimiser');?>
1480
+ </a>
1481
+ <?php } ?>
1482
+ <a class='button button-smaller button-primary' href="javascript:manualOptimization('<?php echo($id)?>', false)">
1483
+ <?php _e('Retry','shortpixel-image-optimiser');?>
1484
+ </a>
1485
+ </div>
1486
  <?php
1487
  }
1488
  break;
1513
  . $excludeSizes . $missingThumbs;
1514
  }
1515
 
1516
+ $this->renderListCell($id, $data['status'], $data['showActions'], $data['thumbsToOptimize'],
 
 
1517
  $data['backup'], $data['type'], $data['invType'], $successText);
1518
 
1519
  break;
1539
  .($retinasOpt ? '<br>' . sprintf(__('+%s Retina images optimized','shortpixel-image-optimiser') , $retinasOpt) : '' );
1540
  }
1541
 
1542
+ public function renderListCell($id, $status, $showActions, $thumbsRemain, $backup, $type, $invType, $message, $extraClass = '') {
1543
+ if($showActions && ($backup || $thumbsRemain)) { ?>
1544
  <div class='sp-column-actions <?php echo($extraClass);?>'>
1545
  <div class="sp-dropdown">
1546
+ <button onclick="ShortPixel.openImageMenu(event);" class="sp-dropbtn button <?php if($thumbsRemain) { echo('button-primary'); } ?> dashicons dashicons-menu" title="ShortPixel Actions"></button>
1547
  <div id="sp-dd-<?php echo($id);?>" class="sp-dropdown-content">
1548
  <?php if($backup && $status == 'imgOptimized') { ?>
1549
  <a class="sp-action-compare" href="javascript:ShortPixel.loadComparer('<?php echo($id);?>')" title="Compare optimized image with the original">Compare</a>
1550
  <?php } ?>
1551
+ <?php if($thumbsRemain) { ?>
1552
  <a class="sp-action-optimize-thumbs" href="javascript:optimizeThumbs(<?php echo($id)?>);" style="background-color:#0085ba;color:white;">
1553
  <?php printf(__('Optimize %s thumbnails','shortpixel-image-optimiser'),$thumbsRemain);?>
1554
  </a>
class/wp-short-pixel.php CHANGED
@@ -78,6 +78,7 @@ class WPShortPixel {
78
 
79
  //custom hook
80
  add_action( 'shortpixel-optimize-now', array( &$this, 'optimizeNowHook' ), 10, 1);
 
81
 
82
  if($isAdminUser) {
83
  //add settings page
@@ -184,6 +185,7 @@ class WPShortPixel {
184
  ShortPixelQueue::resetBulk();
185
  ShortPixelQueue::resetPrio();
186
  WPShortPixelSettings::onDeactivate();
 
187
  }
188
 
189
  public static function shortPixelUninstallPlugin()//reset some params to avoid trouble for plugins that were activated/deactivated/activated
@@ -345,7 +347,7 @@ class WPShortPixel {
345
 
346
  static protected function doLog($message) {
347
  if(defined('SHORTPIXEL_DEBUG_TARGET')) {
348
- file_put_contents(SHORTPIXEL_BACKUP_FOLDER . "/shortpixel_log", '[' . date('Y-m-d H:i:s') . "] $message\n", FILE_APPEND);
349
  } else {
350
  error_log($message);
351
  }
@@ -363,7 +365,7 @@ class WPShortPixel {
363
  //output the comparer html
364
  $this->view->outputComparerHTML();
365
  //render a template of the list cell to be used by the JS
366
- $this->view->renderListCell("__SP_ID__", 'imgOptimized', true, true, "__SP_THUMBS_TOTAL__", true, true,
367
  array("__SP_FIRST_TYPE__", "__SP_SECOND_TYPE__"), "__SP_CELL_MESSAGE__", 'sp-column-actions-template');
368
  }
369
  }
@@ -512,8 +514,12 @@ class WPShortPixel {
512
  || (isset($meta['ShortPixel']['WaitingProcessing']) && $meta['ShortPixel']['WaitingProcessing'] == true))
513
  && (!isset($meta['ShortPixelImprovement']) || $meta['ShortPixelImprovement'] == __('Optimization N/A','shortpixel-image-optimiser'))) {
514
  $this->prioQ->push($ID);
 
 
 
515
  $meta['ShortPixel']['WaitingProcessing'] = true;
516
- wp_update_attachment_metadata($ID, $meta);
 
517
  }
518
  }
519
  break;
@@ -541,7 +547,8 @@ class WPShortPixel {
541
  $meta = $this->doRestore($ID);
542
  if($meta) { //restore succeeded
543
  $meta['ShortPixel'] = array("type" => $type, 'WaitingProcessing' => true);
544
- wp_update_attachment_metadata($ID, $meta);
 
545
  $this->prioQ->push($ID);
546
  }
547
  }
@@ -569,6 +576,7 @@ class WPShortPixel {
569
  }
570
 
571
  self::log("Handle Media Library Image Upload #{$ID}");
 
572
 
573
  if(!$this->_settings->optimizePdfs && 'pdf' === pathinfo(get_attached_file($ID), PATHINFO_EXTENSION)) {
574
  //pdf is not optimized automatically as per the option, but can be optimized by button. Nothing to do.
@@ -600,7 +608,7 @@ class WPShortPixel {
600
  && !is_plugin_active('easy-watermark/index.php')) {
601
  try {
602
  $URLsAndPATHs = $this->getURLsAndPATHs($itemHandler);
603
- //send a processing request right after a file was uploaded, do NOT wait for response
604
  $this->_apiInterface->doRequests($URLsAndPATHs['URLs'], false, $itemHandler, false, $refresh);
605
  } catch(Exception $e) {
606
  $meta['ShortPixelImprovement'] = $e->getMessage();
@@ -665,8 +673,7 @@ class WPShortPixel {
665
  }
666
 
667
  public function handleGravityFormsImageField($value) {
668
- $uploadDir = wp_upload_dir();
669
- if(!($folder = $this->spMetaDao->getFolder($uploadDir['basedir'] . '/gravity_forms'))) {
670
  return;
671
  }
672
  if(strpos($value , '|:|')) {
@@ -674,7 +681,8 @@ class WPShortPixel {
674
  $value = $cleanup[0];
675
  }
676
  //ShortPixel is monitoring the gravity forms folder, add the image to queue
677
- $localPath = str_replace($uploadDir['baseurl'], $uploadDir['basedir'], $value);
 
678
 
679
  return $this->addPathToCustomFolder($localPath, $folder->getId(), 0);
680
  }
@@ -1021,7 +1029,7 @@ class WPShortPixel {
1021
  //var_dump($ids);
1022
  //die("za stop 2");
1023
 
1024
- //self::log("HIP: 1 Prio Queue: ".json_encode($this->prioQ->get()));
1025
  if(count($ids)) {$idl='';foreach($ids as $i){$idl.=$i->getId().' ';} self::log("HIP: 1 Selected IDs: $idl");}
1026
 
1027
  //2: Send up to 3 files to the server for processing
@@ -1270,7 +1278,7 @@ class WPShortPixel {
1270
 
1271
  //WpShortPixelMediaLbraryAdapter::cleanupFoundThumbs($itemHandler);
1272
  $URLsAndPATHs = $this->getURLsAndPATHs($itemHandler, NULL, $onlyThumbs);
1273
-
1274
  $meta = $itemHandler->getMeta();
1275
  //find thumbs that are not listed in the metadata and add them in the sizes array
1276
  if( $itemHandler->getType() == ShortPixelMetaFacade::MEDIA_LIBRARY_TYPE
@@ -1375,6 +1383,7 @@ class WPShortPixel {
1375
 
1376
  //custom hook
1377
  public function optimizeNowHook($imageId, $manual = false) {
 
1378
  if($this->isProcessable($imageId)) {
1379
  $this->prioQ->push($imageId);
1380
  $itemHandler = new ShortPixelMetaFacade($imageId);
@@ -1397,6 +1406,44 @@ class WPShortPixel {
1397
  }
1398
  die(json_encode($ret));
1399
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1400
 
1401
  //WP/LR Sync plugin integration
1402
  public function onWpLrUpdateMedia($imageId, $galleryIdsUnused) {
@@ -1406,7 +1453,8 @@ class WPShortPixel {
1406
  $meta['ShortPixel'] = array();
1407
  $meta['ShortPixel']['WaitingProcessing'] = true;
1408
  $this->prioQ->push($imageId);
1409
- wp_update_attachment_metadata($imageId, $meta);
 
1410
  }
1411
  }
1412
 
@@ -1416,7 +1464,8 @@ class WPShortPixel {
1416
  {
1417
  $meta = wp_get_attachment_metadata($ID);
1418
  $meta['ShortPixelImprovement'] = $result;
1419
- wp_update_attachment_metadata($ID, $meta);
 
1420
  }
1421
 
1422
  public function getBackupFolder($file) {
@@ -1611,7 +1660,8 @@ class WPShortPixel {
1611
  add_filter( 'wp_generate_attachment_metadata', 'shortPixelHandleImageUploadHook', 10, 2 );
1612
  }
1613
  }
1614
- wp_update_attachment_metadata($ID, $crtMeta);
 
1615
  }
1616
  unset($rawMeta["ShortPixelImprovement"]);
1617
  unset($rawMeta['ShortPixel']);
@@ -1728,7 +1778,8 @@ class WPShortPixel {
1728
  $meta = $this->doRestore($ID);
1729
  if($meta) { //restore succeeded
1730
  $meta['ShortPixel'] = array("type" => $compressionType);
1731
- wp_update_attachment_metadata($ID, $meta);
 
1732
  try {
1733
  $this->sendToProcessing(new ShortPixelMetaFacade($ID), ShortPixelAPI::getCompressionTypeCode($compressionType));
1734
  $this->prioQ->push($ID);
@@ -1737,7 +1788,8 @@ class WPShortPixel {
1737
  $meta['ShortPixelImprovement'] = $e->getMessage();
1738
  $meta['ShortPixel']['ErrCode'] = $e->getCode() < 0 ? $e->getCode() : ShortPixelAPI::STATUS_FAIL;
1739
  unset($meta['ShortPixel']['WaitingProcessing']);
1740
- wp_update_attachment_metadata($ID, $meta);
 
1741
  $ret = array("Status" => ShortPixelAPI::STATUS_FAIL, "Message" => $e->getMessage());
1742
  }
1743
  } else {
@@ -1757,7 +1809,8 @@ class WPShortPixel {
1757
  && ( !isset($meta['ShortPixel']['thumbsOpt']) || $meta['ShortPixel']['thumbsOpt'] == 0
1758
  || (isset($meta['sizes']) && isset($meta['ShortPixel']['thumbsOptList']) && $meta['ShortPixel']['thumbsOpt'] < $thumbsCount))) { //optimized without thumbs, thumbs exist
1759
  $meta['ShortPixel']['thumbsTodo'] = true;
1760
- wp_update_attachment_metadata($ID, $meta);
 
1761
  $this->prioQ->push($ID);
1762
  try {
1763
  $this->sendToProcessing(new ShortPixelMetaFacade($ID), false, true);
@@ -1766,7 +1819,8 @@ class WPShortPixel {
1766
  $meta['ShortPixelImprovement'] = $e->getMessage();
1767
  $meta['ShortPixel']['ErrCode'] = $e->getCode() < 0 ? $e->getCode() : ShortPixelAPI::STATUS_FAIL;
1768
  unset($meta['ShortPixel']['WaitingProcessing']);
1769
- wp_update_attachment_metadata($ID, $meta);
 
1770
  $ret = array("Status" => ShortPixelAPI::STATUS_FAIL, "Message" => $e->getMessage());
1771
  }
1772
  } else {
@@ -1793,7 +1847,8 @@ class WPShortPixel {
1793
  public function handleDeleteAttachmentInBackup($ID) {
1794
  $file = get_attached_file($ID);
1795
  $meta = wp_get_attachment_metadata($ID);
1796
-
 
1797
  if(self::_isProcessable($ID) != false) //we use the static isProcessable to bypass the exclude patterns
1798
  {
1799
  try {
@@ -2112,7 +2167,9 @@ class WPShortPixel {
2112
  }
2113
 
2114
  public function backupFolderIsEmpty() {
2115
- return count(scandir(SHORTPIXEL_BACKUP_FOLDER)) > 2 ? false : true;
 
 
2116
  }
2117
 
2118
  public function getBackupSize() {
@@ -2182,10 +2239,10 @@ class WPShortPixel {
2182
  $uploadsUrl = ShortPixelMetaFacade::getHomeUrl();
2183
  $urlBkPath = ShortPixelMetaFacade::returnSubDir($meta->getPath());
2184
  $ret['origUrl'] = $backupUrl . $urlBkPath . $meta->getName();
2185
- $ret['optUrl'] = $uploadsUrl . $urlBkPath . $meta->getName();
2186
  $ret['width'] = $rawMeta['width'];
2187
- $ret['height'] = $rawMeta['height'];
2188
-
2189
  die(json_encode((object)$ret));
2190
  }
2191
 
@@ -2453,10 +2510,9 @@ class WPShortPixel {
2453
  //delete_option('wp-short-pixel-keep-exif');
2454
  $this->_settings->resizeImages = (isset($_POST['resize']) ? 1: 0);
2455
  $this->_settings->resizeType = (isset($_POST['resize_type']) ? $_POST['resize_type']: false);
2456
- $this->_settings->resizeWidth = (isset($_POST['width']) ? $_POST['width']: $this->_settings->resizeWidth);
2457
- $this->_settings->resizeHeight = (isset($_POST['height']) ? $_POST['height']: $this->_settings->resizeHeight);
2458
- $uploadDir = wp_upload_dir();
2459
- $uploadPath = realpath($uploadDir["basedir"]);
2460
 
2461
  if(isset($_POST['nextGen'])) {
2462
  WpShortPixelDb::checkCustomTables(); // check if custom tables are created, if not, create them
@@ -2815,6 +2871,18 @@ class WPShortPixel {
2815
  && !($data['ShortPixelImprovement'] == 0 && isset($data['ShortPixel']['WaitingProcessing'])) //for images that erroneously have ShortPixelImprovement = 0 when WaitingProcessing
2816
  ) { //already optimized
2817
  $sizesCount = isset($data['sizes']) ? WpShortPixelMediaLbraryAdapter::countSizesNotExcluded($data['sizes']) : 0;
 
 
 
 
 
 
 
 
 
 
 
 
2818
 
2819
  $renderData['status'] = $fileExtension == "pdf" ? 'pdfOptimized' : 'imgOptimized';
2820
  $renderData['percent'] = $this->optimizationPercentIfPng2Jpg($data);
@@ -2824,7 +2892,8 @@ class WPShortPixel {
2824
  $renderData['invType'] = ShortPixelAPI::getCompressionTypeName($this->getOtherCompressionTypes(ShortPixelAPI::getCompressionTypeCode($renderData['type'])));
2825
  $renderData['thumbsTotal'] = $sizesCount;
2826
  $renderData['thumbsOpt'] = isset($data['ShortPixel']['thumbsOpt']) ? $data['ShortPixel']['thumbsOpt'] : $sizesCount;
2827
- $renderData['thumbsOptList'] = isset($data['ShortPixel']['thumbsOptList']) ? $data['ShortPixel']['thumbsOptList'] : array();
 
2828
  $renderData['excludeSizes'] = isset($data['ShortPixel']['excludeSizes']) ? $data['ShortPixel']['excludeSizes'] : null;
2829
  $renderData['thumbsMissing'] = isset($data['ShortPixel']['thumbsMissing']) ? $data['ShortPixel']['thumbsMissing'] : array();
2830
  $renderData['retinasOpt'] = isset($data['ShortPixel']['retinasOpt']) ? $data['ShortPixel']['retinasOpt'] : null;
78
 
79
  //custom hook
80
  add_action( 'shortpixel-optimize-now', array( &$this, 'optimizeNowHook' ), 10, 1);
81
+ add_action( 'shortpixel-thumbnails-regenerated', array( &$this, 'thumbnailsRegeneratedHook' ), 10, 3);
82
 
83
  if($isAdminUser) {
84
  //add settings page
185
  ShortPixelQueue::resetBulk();
186
  ShortPixelQueue::resetPrio();
187
  WPShortPixelSettings::onDeactivate();
188
+ @unlink(SHORTPIXEL_BACKUP_FOLDER . "/shortpixel_log");
189
  }
190
 
191
  public static function shortPixelUninstallPlugin()//reset some params to avoid trouble for plugins that were activated/deactivated/activated
347
 
348
  static protected function doLog($message) {
349
  if(defined('SHORTPIXEL_DEBUG_TARGET')) {
350
+ file_put_contents(SHORTPIXEL_BACKUP_FOLDER . "/shortpixel_log", '[' . date('Y-m-d H:i:s') . "] $message\n", FILE_APPEND);
351
  } else {
352
  error_log($message);
353
  }
365
  //output the comparer html
366
  $this->view->outputComparerHTML();
367
  //render a template of the list cell to be used by the JS
368
+ $this->view->renderListCell("__SP_ID__", 'imgOptimized', true, "__SP_THUMBS_TOTAL__", true, true,
369
  array("__SP_FIRST_TYPE__", "__SP_SECOND_TYPE__"), "__SP_CELL_MESSAGE__", 'sp-column-actions-template');
370
  }
371
  }
514
  || (isset($meta['ShortPixel']['WaitingProcessing']) && $meta['ShortPixel']['WaitingProcessing'] == true))
515
  && (!isset($meta['ShortPixelImprovement']) || $meta['ShortPixelImprovement'] == __('Optimization N/A','shortpixel-image-optimiser'))) {
516
  $this->prioQ->push($ID);
517
+ if(!isset($meta['ShortPixel'])) {
518
+ $meta['ShortPixel'] = array();
519
+ }
520
  $meta['ShortPixel']['WaitingProcessing'] = true;
521
+ //wp_update_attachment_metadata($ID, $meta);
522
+ update_post_meta($ID, '_wp_attachment_metadata', $meta);
523
  }
524
  }
525
  break;
547
  $meta = $this->doRestore($ID);
548
  if($meta) { //restore succeeded
549
  $meta['ShortPixel'] = array("type" => $type, 'WaitingProcessing' => true);
550
+ //wp_update_attachment_metadata($ID, $meta);
551
+ update_post_meta($ID, '_wp_attachment_metadata', $meta);
552
  $this->prioQ->push($ID);
553
  }
554
  }
576
  }
577
 
578
  self::log("Handle Media Library Image Upload #{$ID}");
579
+ //self::log("STACK: " . json_encode(debug_backtrace()));
580
 
581
  if(!$this->_settings->optimizePdfs && 'pdf' === pathinfo(get_attached_file($ID), PATHINFO_EXTENSION)) {
582
  //pdf is not optimized automatically as per the option, but can be optimized by button. Nothing to do.
608
  && !is_plugin_active('easy-watermark/index.php')) {
609
  try {
610
  $URLsAndPATHs = $this->getURLsAndPATHs($itemHandler);
611
+ //send a processing request right after a file was uploaded, do NOT wait for response
612
  $this->_apiInterface->doRequests($URLsAndPATHs['URLs'], false, $itemHandler, false, $refresh);
613
  } catch(Exception $e) {
614
  $meta['ShortPixelImprovement'] = $e->getMessage();
673
  }
674
 
675
  public function handleGravityFormsImageField($value) {
676
+ if(!($folder = $this->spMetaDao->getFolder(SHORTPIXEL_UPLOADS_BASE . '/gravity_forms'))) {
 
677
  return;
678
  }
679
  if(strpos($value , '|:|')) {
681
  $value = $cleanup[0];
682
  }
683
  //ShortPixel is monitoring the gravity forms folder, add the image to queue
684
+ $uploadDir = wp_upload_dir();
685
+ $localPath = str_replace($uploadDir['baseurl'], SHORTPIXEL_UPLOADS_BASE, $value);
686
 
687
  return $this->addPathToCustomFolder($localPath, $folder->getId(), 0);
688
  }
1029
  //var_dump($ids);
1030
  //die("za stop 2");
1031
 
1032
+ //self::log("HIP: 1 Ids: ".json_encode($ids));
1033
  if(count($ids)) {$idl='';foreach($ids as $i){$idl.=$i->getId().' ';} self::log("HIP: 1 Selected IDs: $idl");}
1034
 
1035
  //2: Send up to 3 files to the server for processing
1278
 
1279
  //WpShortPixelMediaLbraryAdapter::cleanupFoundThumbs($itemHandler);
1280
  $URLsAndPATHs = $this->getURLsAndPATHs($itemHandler, NULL, $onlyThumbs);
1281
+
1282
  $meta = $itemHandler->getMeta();
1283
  //find thumbs that are not listed in the metadata and add them in the sizes array
1284
  if( $itemHandler->getType() == ShortPixelMetaFacade::MEDIA_LIBRARY_TYPE
1383
 
1384
  //custom hook
1385
  public function optimizeNowHook($imageId, $manual = false) {
1386
+ //WpShortPixel::log("OPTIMIZE NOW HOOK for ID: $imageId STACK: " . json_encode(debug_backtrace()));
1387
  if($this->isProcessable($imageId)) {
1388
  $this->prioQ->push($imageId);
1389
  $itemHandler = new ShortPixelMetaFacade($imageId);
1406
  }
1407
  die(json_encode($ret));
1408
  }
1409
+
1410
+ /**
1411
+ * to be called by thumbnail regeneration plugins when regenerating the thumbnails for an image
1412
+ * @param $postId - the postId of the image
1413
+ * @param $originalMeta - the metadata before the regeneration
1414
+ * @param array $regeneratedSizes - the list of the regenerated thumbnails - if empty then all were regenerated.
1415
+ * @param bool $bulk - true if the regeneration is done in bulk - in this case the image will not be immediately scheduled for processing but the user will need to launch the ShortPixel bulk after regenerating.
1416
+ */
1417
+ public function thumbnailsRegeneratedHook($postId, $originalMeta, $regeneratedSizes = array(), $bulk = false) {
1418
+
1419
+ if(isset($originalMeta["ShortPixelImprovement"]) && is_numeric($originalMeta["ShortPixelImprovement"])) {
1420
+ $shortPixelMeta = $originalMeta["ShortPixel"];
1421
+ if(count($regeneratedSizes) == 0 || !isset($shortPixelMeta["thumbsOptList"])) {
1422
+ $shortPixelMeta["thumbsOpt"] = 0;
1423
+ $shortPixelMeta["thumbsOptList"] = array();
1424
+ $shortPixelMeta["retinasOpt"] = 0;
1425
+ } else {
1426
+ foreach($regeneratedSizes as $size) {
1427
+ if(isset($shortPixelMeta["thumbsOptList"][$size])) {
1428
+ unset($shortPixelMeta["thumbsOptList"][$size]);
1429
+ $shortPixelMeta["thumbsOpt"] = max(0, $shortPixelMeta["thumbsOpt"] - 1);
1430
+ $shortPixelMeta["retinasOpt"] = max(0, $shortPixelMeta["retinasOpt"] - 1);
1431
+ }
1432
+ }
1433
+ }
1434
+ $meta = wp_get_attachment_metadata($postId);
1435
+ $meta["ShortPixel"] = $shortPixelMeta;
1436
+ $meta["ShortPixelImprovement"] = $originalMeta["ShortPixelImprovement"];
1437
+ if(isset($originalMeta["ShortPixelPng2Jpg"])) {
1438
+ $meta["ShortPixelPng2Jpg"] = $originalMeta["ShortPixelPng2Jpg"];
1439
+ }
1440
+ //wp_update_attachment_metadata($postId, $meta);
1441
+ update_post_meta($postId, '_wp_attachment_metadata', $meta);
1442
+ if(!$bulk) {
1443
+ $this->prioQ->push($postId);
1444
+ }
1445
+ }
1446
+ }
1447
 
1448
  //WP/LR Sync plugin integration
1449
  public function onWpLrUpdateMedia($imageId, $galleryIdsUnused) {
1453
  $meta['ShortPixel'] = array();
1454
  $meta['ShortPixel']['WaitingProcessing'] = true;
1455
  $this->prioQ->push($imageId);
1456
+ //wp_update_attachment_metadata($imageId, $meta);
1457
+ update_post_meta($imageId, '_wp_attachment_metadata', $meta);
1458
  }
1459
  }
1460
 
1464
  {
1465
  $meta = wp_get_attachment_metadata($ID);
1466
  $meta['ShortPixelImprovement'] = $result;
1467
+ //wp_update_attachment_metadata($ID, $meta);
1468
+ update_post_meta($ID, '_wp_attachment_metadata', $meta);
1469
  }
1470
 
1471
  public function getBackupFolder($file) {
1660
  add_filter( 'wp_generate_attachment_metadata', 'shortPixelHandleImageUploadHook', 10, 2 );
1661
  }
1662
  }
1663
+ //wp_update_attachment_metadata($ID, $crtMeta);
1664
+ update_post_meta($ID, '_wp_attachment_metadata', $crtMeta);
1665
  }
1666
  unset($rawMeta["ShortPixelImprovement"]);
1667
  unset($rawMeta['ShortPixel']);
1778
  $meta = $this->doRestore($ID);
1779
  if($meta) { //restore succeeded
1780
  $meta['ShortPixel'] = array("type" => $compressionType);
1781
+ //wp_update_attachment_metadata($ID, $meta);
1782
+ update_post_meta($ID, '_wp_attachment_metadata', $meta);
1783
  try {
1784
  $this->sendToProcessing(new ShortPixelMetaFacade($ID), ShortPixelAPI::getCompressionTypeCode($compressionType));
1785
  $this->prioQ->push($ID);
1788
  $meta['ShortPixelImprovement'] = $e->getMessage();
1789
  $meta['ShortPixel']['ErrCode'] = $e->getCode() < 0 ? $e->getCode() : ShortPixelAPI::STATUS_FAIL;
1790
  unset($meta['ShortPixel']['WaitingProcessing']);
1791
+ //wp_update_attachment_metadata($ID, $meta);
1792
+ update_post_meta($ID, '_wp_attachment_metadata', $meta);
1793
  $ret = array("Status" => ShortPixelAPI::STATUS_FAIL, "Message" => $e->getMessage());
1794
  }
1795
  } else {
1809
  && ( !isset($meta['ShortPixel']['thumbsOpt']) || $meta['ShortPixel']['thumbsOpt'] == 0
1810
  || (isset($meta['sizes']) && isset($meta['ShortPixel']['thumbsOptList']) && $meta['ShortPixel']['thumbsOpt'] < $thumbsCount))) { //optimized without thumbs, thumbs exist
1811
  $meta['ShortPixel']['thumbsTodo'] = true;
1812
+ //wp_update_attachment_metadata($ID, $meta);
1813
+ update_post_meta($ID, '_wp_attachment_metadata', $meta);
1814
  $this->prioQ->push($ID);
1815
  try {
1816
  $this->sendToProcessing(new ShortPixelMetaFacade($ID), false, true);
1819
  $meta['ShortPixelImprovement'] = $e->getMessage();
1820
  $meta['ShortPixel']['ErrCode'] = $e->getCode() < 0 ? $e->getCode() : ShortPixelAPI::STATUS_FAIL;
1821
  unset($meta['ShortPixel']['WaitingProcessing']);
1822
+ //wp_update_attachment_metadata($ID, $meta);
1823
+ update_post_meta($ID, '_wp_attachment_metadata', $meta);
1824
  $ret = array("Status" => ShortPixelAPI::STATUS_FAIL, "Message" => $e->getMessage());
1825
  }
1826
  } else {
1847
  public function handleDeleteAttachmentInBackup($ID) {
1848
  $file = get_attached_file($ID);
1849
  $meta = wp_get_attachment_metadata($ID);
1850
+
1851
+
1852
  if(self::_isProcessable($ID) != false) //we use the static isProcessable to bypass the exclude patterns
1853
  {
1854
  try {
2167
  }
2168
 
2169
  public function backupFolderIsEmpty() {
2170
+ if(file_exists(SHORTPIXEL_BACKUP_FOLDER)) {
2171
+ return count(scandir(SHORTPIXEL_BACKUP_FOLDER)) > 2 ? false : true;
2172
+ }
2173
  }
2174
 
2175
  public function getBackupSize() {
2239
  $uploadsUrl = ShortPixelMetaFacade::getHomeUrl();
2240
  $urlBkPath = ShortPixelMetaFacade::returnSubDir($meta->getPath());
2241
  $ret['origUrl'] = $backupUrl . $urlBkPath . $meta->getName();
2242
+ $ret['optUrl'] = wp_get_attachment_url( $_POST['id'] ); //$uploadsUrl . $urlBkPath . $meta->getName();
2243
  $ret['width'] = $rawMeta['width'];
2244
+ $ret['height'] = $rawMeta['height'];
2245
+
2246
  die(json_encode((object)$ret));
2247
  }
2248
 
2510
  //delete_option('wp-short-pixel-keep-exif');
2511
  $this->_settings->resizeImages = (isset($_POST['resize']) ? 1: 0);
2512
  $this->_settings->resizeType = (isset($_POST['resize_type']) ? $_POST['resize_type']: false);
2513
+ $this->_settings->resizeWidth = (isset($_POST['width']) ? intval($_POST['width']): $this->_settings->resizeWidth);
2514
+ $this->_settings->resizeHeight = (isset($_POST['height']) ? intval($_POST['height']): $this->_settings->resizeHeight);
2515
+ $uploadPath = realpath(SHORTPIXEL_UPLOADS_BASE);
 
2516
 
2517
  if(isset($_POST['nextGen'])) {
2518
  WpShortPixelDb::checkCustomTables(); // check if custom tables are created, if not, create them
2871
  && !($data['ShortPixelImprovement'] == 0 && isset($data['ShortPixel']['WaitingProcessing'])) //for images that erroneously have ShortPixelImprovement = 0 when WaitingProcessing
2872
  ) { //already optimized
2873
  $sizesCount = isset($data['sizes']) ? WpShortPixelMediaLbraryAdapter::countSizesNotExcluded($data['sizes']) : 0;
2874
+
2875
+ $thumbsToOptimize = 0;
2876
+ $thumbsOptList = isset($data['ShortPixel']['thumbsOptList']) ? $data['ShortPixel']['thumbsOptList'] : array();
2877
+ if($sizesCount && $this->_settings->processThumbnails) {
2878
+ $exclude = $this->_settings->excludeSizes;
2879
+ $exclude = is_array($exclude) ? $exclude : array();
2880
+ foreach($data['sizes'] as $size => $sizeData) {
2881
+ if(!in_array($size, $exclude) && !in_array($sizeData['file'], $thumbsOptList)) {
2882
+ $thumbsToOptimize++;
2883
+ }
2884
+ }
2885
+ }
2886
 
2887
  $renderData['status'] = $fileExtension == "pdf" ? 'pdfOptimized' : 'imgOptimized';
2888
  $renderData['percent'] = $this->optimizationPercentIfPng2Jpg($data);
2892
  $renderData['invType'] = ShortPixelAPI::getCompressionTypeName($this->getOtherCompressionTypes(ShortPixelAPI::getCompressionTypeCode($renderData['type'])));
2893
  $renderData['thumbsTotal'] = $sizesCount;
2894
  $renderData['thumbsOpt'] = isset($data['ShortPixel']['thumbsOpt']) ? $data['ShortPixel']['thumbsOpt'] : $sizesCount;
2895
+ $renderData['thumbsToOptimize'] = $thumbsToOptimize;
2896
+ $renderData['thumbsOptList'] = $thumbsOptList;
2897
  $renderData['excludeSizes'] = isset($data['ShortPixel']['excludeSizes']) ? $data['ShortPixel']['excludeSizes'] : null;
2898
  $renderData['thumbsMissing'] = isset($data['ShortPixel']['thumbsMissing']) ? $data['ShortPixel']['thumbsMissing'] : array();
2899
  $renderData['retinasOpt'] = isset($data['ShortPixel']['retinasOpt']) ? $data['ShortPixel']['retinasOpt'] : null;
class/wp-shortpixel-cloudflare-api.php CHANGED
@@ -105,7 +105,7 @@ class ShortPixelCloudFlareApi {
105
  if ( ! empty( $image_url_for_purge ) ) {
106
  $prepare_request_info['files'] = $image_url_for_purge;
107
  // Encode the data into JSON before send
108
- $dispatch_purge_info = wp_json_encode( $prepare_request_info );
109
  // Set headers for remote API to authenticate for the request
110
  $dispatch_header = array(
111
  'X-Auth-Email: ' . $cloudflare_auth_email,
105
  if ( ! empty( $image_url_for_purge ) ) {
106
  $prepare_request_info['files'] = $image_url_for_purge;
107
  // Encode the data into JSON before send
108
+ $dispatch_purge_info = function_exists('wp_json_encode') ? wp_json_encode( $prepare_request_info ) : json_encode( $prepare_request_info );
109
  // Set headers for remote API to authenticate for the request
110
  $dispatch_header = array(
111
  'X-Auth-Email: ' . $cloudflare_auth_email,
readme.txt CHANGED
@@ -4,7 +4,7 @@ Tags: compress, image, compression, optimize, image optimizer, image optimiser,
4
  Requires at least: 3.2.0
5
  Tested up to: 4.9
6
  Requires PHP: 5.2
7
- Stable tag: 4.11.0
8
  License: GPLv2 or later
9
  License URI: http://www.gnu.org/licenses/gpl-2.0.html
10
 
@@ -241,6 +241,22 @@ The ShortPixel Image Optimiser plugin calls the following actions and filters:
241
 
242
  == Changelog ==
243
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
244
  = 4.11.0 =
245
  * add bulk menu options: restore, reoptimize
246
  * filter the media list by optimization status
@@ -299,4 +315,4 @@ The ShortPixel Image Optimiser plugin calls the following actions and filters:
299
  * display the x close link for the bulk warning box.
300
 
301
  = EARLIER VERSIONS =
302
- * please refer to the changelog.txt file
4
  Requires at least: 3.2.0
5
  Tested up to: 4.9
6
  Requires PHP: 5.2
7
+ Stable tag: 4.11.1
8
  License: GPLv2 or later
9
  License URI: http://www.gnu.org/licenses/gpl-2.0.html
10
 
241
 
242
  == Changelog ==
243
 
244
+ = 4.11.1 =
245
+ * compatibility with the MediaPress plugin
246
+ * new action to be called by when thumbnails are regenerated: shortpixel-thumbnails-regenerated
247
+ * accept '+' inside the e-mail address
248
+ * fix optimization not working on internationalized domain names
249
+ * better count of the not optimized thumbs for an image, in some circumstances
250
+ * fallback to ABSPATH when get_home_path() returns '/'
251
+ * fix settings tabs navigation when url ends with #/
252
+ * extract all release notes < 4.9 from readme.txt into changelog.txt
253
+ * display the thumbnail name for some errors which refer only to a specific thumbnail.
254
+ * use update_post_meta() instead of wp_update_attachment_metadata() for cases when other plugins cannot be concerned by the meta change (specific to ShortPixel)
255
+ * add the attributes of the original <img> to the <picture> replacement tag, in case the "Generate WebP Markup" option is active.
256
+ * fix action buttons in media edit view overflowing their box
257
+ * restore full compatibility with WP < 4.1 by checking first before using wp_json_encode
258
+ * fix admin when domain is internationalized but the setting in admin uses the punycode-encrypted version
259
+
260
  = 4.11.0 =
261
  * add bulk menu options: restore, reoptimize
262
  * filter the media list by optimization status
315
  * display the x close link for the bulk warning box.
316
 
317
  = EARLIER VERSIONS =
318
+ * please refer to the changelog.txt file inside the plugin archive.
res/js/short-pixel.js CHANGED
@@ -51,7 +51,7 @@ var ShortPixel = function() {
51
  }
52
 
53
  function isEmailValid(email) {
54
- return /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{1,63})+$/.test(email);
55
  }
56
 
57
  function updateSignupEmail() {
@@ -601,6 +601,15 @@ var ShortPixel = function() {
601
  jQuery(document).unbind('keyup.sp_modal_active');
602
  }
603
 
 
 
 
 
 
 
 
 
 
604
  return {
605
  init : init,
606
  setOptions : setOptions,
@@ -643,6 +652,7 @@ var ShortPixel = function() {
643
  loadComparer : loadComparer,
644
  displayComparerPopup: displayComparerPopup,
645
  closeComparerPopup : closeComparerPopup,
 
646
  comparerData : {
647
  cssLoaded : false,
648
  jsLoaded : false,
@@ -736,9 +746,8 @@ function checkBulkProgress() {
736
 
737
  //handle possible Punycode domain names.
738
  if(url.search(adminUrl) < 0) {
739
- var parser = document.createElement('a');
740
- parser.href = url;
741
- url = url.replace(parser.protocol + '//' + parser.hostname, parser.protocol + '//' + parser.hostname.split('.').map(function(part) {return sp_punycode.toASCII(part)}).join('.'));
742
  }
743
 
744
  if( url.search(adminUrl + "upload.php") < 0
51
  }
52
 
53
  function isEmailValid(email) {
54
+ return /^\w+([\.+-]?\w+)*@\w+([\.-]?\w+)*(\.\w{1,63})+$/.test(email);
55
  }
56
 
57
  function updateSignupEmail() {
601
  jQuery(document).unbind('keyup.sp_modal_active');
602
  }
603
 
604
+ function convertPunycode(url) {
605
+ var parser = document.createElement('a');
606
+ parser.href = url;
607
+ if(url.indexOf(parser.protocol + '//' + parser.hostname) < 0) {
608
+ return parser.href;
609
+ }
610
+ return url.replace(parser.protocol + '//' + parser.hostname, parser.protocol + '//' + parser.hostname.split('.').map(function(part) {return sp_punycode.toASCII(part)}).join('.'));
611
+ }
612
+
613
  return {
614
  init : init,
615
  setOptions : setOptions,
652
  loadComparer : loadComparer,
653
  displayComparerPopup: displayComparerPopup,
654
  closeComparerPopup : closeComparerPopup,
655
+ convertPunycode : convertPunycode,
656
  comparerData : {
657
  cssLoaded : false,
658
  jsLoaded : false,
746
 
747
  //handle possible Punycode domain names.
748
  if(url.search(adminUrl) < 0) {
749
+ url = ShortPixel.convertPunycode(url);
750
+ adminUrl = ShortPixel.convertPunycode(adminUrl);
 
751
  }
752
 
753
  if( url.search(adminUrl + "upload.php") < 0
res/js/short-pixel.min.js CHANGED
@@ -1 +1 @@
1
- jQuery(document).ready(function(a){ShortPixel.init()});var ShortPixel=function(){function G(){if(typeof ShortPixel.API_KEY!=="undefined"){return}if(jQuery("table.wp-list-table.media").length>0){jQuery('select[name^="action"] option:last-child').before('<option value="short-pixel-bulk">'+_spTr.optimizeWithSP+'</option><option value="short-pixel-bulk-lossy"> → '+_spTr.redoLossy+'</option><option value="short-pixel-bulk-glossy"> → '+_spTr.redoGlossy+'</option><option value="short-pixel-bulk-lossless"> → '+_spTr.redoLossless+'</option><option value="short-pixel-bulk-restore"> → '+_spTr.restoreOriginal+"</option>")}ShortPixel.setOptions(ShortPixelConstants);if(jQuery("#backup-folder-size").length){jQuery("#backup-folder-size").html(ShortPixel.getBackupSize())}if(ShortPixel.MEDIA_ALERT=="todo"&&jQuery("div.media-frame.mode-grid").length>0){jQuery("div.media-frame.mode-grid").before('<div id="short-pixel-media-alert" class="notice notice-warning"><p>'+_spTr.changeMLToListMode.format('<a href="upload.php?mode=list" class="view-list"><span class="screen-reader-text">'," </span>",'</a><a class="alignright" href="javascript:ShortPixel.dismissMediaAlert();">',"</a>")+"</p></div>")}jQuery(window).on("beforeunload",function(){if(ShortPixel.bulkProcessor==true){clearBulkProcessor()}});checkQuotaExceededAlert();checkBulkProgress()}function l(O){for(var P in O){ShortPixel[P]=O[P]}}function s(O){return/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{1,63})+$/.test(O)}function m(){var O=jQuery("#pluginemail").val();if(ShortPixel.isEmailValid(O)){jQuery("#request_key").removeClass("disabled")}jQuery("#request_key").attr("href",jQuery("#request_key").attr("href").split("?")[0]+"?pluginemail="+O)}function a(){jQuery("#valid").val("validate");jQuery("#wp_shortpixel_options").submit()}jQuery("#key").keypress(function(O){if(O.which==13){jQuery("#valid").val("validate")}});function J(O){if(jQuery(O).is(":checked")){jQuery("#width,#height").removeAttr("disabled")}else{jQuery("#width,#height").attr("disabled","disabled")}}function e(O,Q,S){for(var P=0,R=null;P<O.length;P++){O[P].onclick=function(){if(this!==R){R=this}if(typeof ShortPixel.setupGeneralTabAlert!=="undefined"){return}alert(_spTr.alertOnlyAppliesToNewImages);ShortPixel.setupGeneralTabAlert=1}}ShortPixel.enableResize("#resize");jQuery("#resize").change(function(){J(this)});jQuery(".resize-sizes").blur(function(U){var V=jQuery(this);if(ShortPixel.resizeSizesAlert==V.val()){return}ShortPixel.resizeSizesAlert=V.val();var T=jQuery("#min-"+V.attr("name")).val();if(V.val()<Math.min(T,1024)){if(T>1024){alert(_spTr.pleaseDoNotSetLesser1024.format(V.attr("name")))}else{alert(_spTr.pleaseDoNotSetLesserSize.format(V.attr("name"),V.attr("name"),T))}U.preventDefault();V.focus()}else{this.defaultValue=V.val()}});jQuery(".shortpixel-confirm").click(function(U){var T=confirm(U.target.getAttribute("data-confirm"));if(!T){U.preventDefault();return false}return true})}function A(){jQuery(".wp-shortpixel-options .shortpixel-key-valid").css("display","none");jQuery(".wp-shortpixel-options button#validate").css("display","inline-block")}function t(){jQuery("input.remove-folder-button").click(function(){var P=jQuery(this).data("value");var O=confirm(_spTr.areYouSureStopOptimizing.format(P));if(O==true){jQuery("#removeFolder").val(P);jQuery("#wp_shortpixel_options").submit()}});jQuery("input.recheck-folder-button").click(function(){var P=jQuery(this).data("value");var O=confirm(_spTr.areYouSureStopOptimizing.format(P));if(O==true){jQuery("#recheckFolder").val(P);jQuery("#wp_shortpixel_options").submit()}})}function I(O){var P=jQuery("#"+(O.checked?"total":"main")+"ToProcess").val();jQuery("div.bulk-play span.total").text(P);jQuery("#displayTotal").text(P)}function w(P){var O=jQuery("section#"+P);if(O.length>0){jQuery("section").removeClass("sel-tab");jQuery("section#"+P).addClass("sel-tab")}}function x(){var O=jQuery("section#tab-settings .wp-shortpixel-options").height()+90;O=Math.max(O,jQuery("section#tab-adv-settings .wp-shortpixel-options").height()+20);O=Math.max(O,jQuery("section#tab-resources .area1").height()+60);jQuery("#shortpixel-settings-tabs").css("height",O);jQuery("#shortpixel-settings-tabs section").css("height",O)}function K(){var O={action:"shortpixel_dismiss_media_alert"};jQuery.get(ShortPixel.AJAX_URL,O,function(P){O=JSON.parse(P);if(O.Status=="success"){jQuery("#short-pixel-media-alert").hide();console.log("dismissed")}})}function j(){var O={action:"shortpixel_check_quota"};jQuery.get(ShortPixel.AJAX_URL,O,function(){console.log("quota refreshed")})}function z(O){if(O.checked){jQuery("#with-thumbs").css("display","inherit");jQuery("#without-thumbs").css("display","none")}else{jQuery("#without-thumbs").css("display","inherit");jQuery("#with-thumbs").css("display","none")}}function b(S,Q,P,R,O){return(Q>0?"<div class='sp-column-info'>"+_spTr.reducedBy+" <strong><span class='percent'>"+Q+"%</span></strong> ":"")+(Q>0&&Q<5?"<br>":"")+(Q<5?_spTr.bonusProcessing:"")+(P.length>0?" ("+P+")":"")+(0+R>0?"<br>"+_spTr.plusXthumbsOpt.format(R):"")+(0+O>0?"<br>"+_spTr.plusXretinasOpt.format(O):"")+"</div>"}function o(P,O){jQuery(P).knob({readOnly:true,width:O,height:O,fgColor:"#1CAECB",format:function(Q){return Q+"%"}})}function c(V,Q,T,S,P,U){if(P==1){var R=jQuery(".sp-column-actions-template").clone();if(!R.length){return false}var O;if(Q.length==0){O=["lossy","lossless"]}else{O=["lossy","glossy","lossless"].filter(function(W){return !(W==Q)})}R.html(R.html().replace(/__SP_ID__/g,V));if(U.substr(U.lastIndexOf(".")+1).toLowerCase()=="pdf"){jQuery(".sp-action-compare",R).remove()}if(T==0&&S>0){R.html(R.html().replace("__SP_THUMBS_TOTAL__",S))}else{jQuery(".sp-action-optimize-thumbs",R).remove();jQuery(".sp-dropbtn",R).removeClass("button-primary")}R.html(R.html().replace(/__SP_FIRST_TYPE__/g,O[0]));R.html(R.html().replace(/__SP_SECOND_TYPE__/g,O[1]));return R.html()}return""}function h(S,R){S=S.substring(2);if(jQuery(".shortpixel-other-media").length){var Q=["optimize","retry","restore","redo","quota","view"];for(var P=0,O=Q.length;P<O;P++){jQuery("#"+Q[P]+"_"+S).css("display","none")}for(var P=0,O=R.length;P<O;P++){jQuery("#"+R[P]+"_"+S).css("display","")}}}function i(O){ShortPixel.retries++;if(isNaN(ShortPixel.retries)){ShortPixel.retries=1}if(ShortPixel.retries<6){console.log("Invalid response from server (Error: "+O+"). Retrying pass "+(ShortPixel.retries+1)+"...");setTimeout(checkBulkProgress,5000)}else{ShortPixel.bulkShowError(-1,"Invalid response from server received 6 times. Please retry later by reloading this page, or <a href='https://shortpixel.com/contact' target='_blank'>contact support</a>. (Error: "+O+")","");console.log("Invalid response from server 6 times. Giving up.")}}function k(O){O.action="shortpixel_browse_content";var P="";jQuery.ajax({type:"POST",url:ShortPixel.AJAX_URL,data:O,success:function(Q){P=Q},async:false});return P}function d(){var O={action:"shortpixel_get_backup_size"};var P="";jQuery.ajax({type:"POST",url:ShortPixel.AJAX_URL,data:O,success:function(Q){P=Q},async:false});return P}function f(P){if(!jQuery("#tos").is(":checked")){P.preventDefault();jQuery("#tos-robo").fadeIn(400,function(){jQuery("#tos-hand").fadeIn()});jQuery("#tos").click(function(){jQuery("#tos-robo").css("display","none");jQuery("#tos-hand").css("display","none")});return}jQuery("#request_key").addClass("disabled");jQuery("#pluginemail_spinner").addClass("is-active");ShortPixel.updateSignupEmail();if(ShortPixel.isEmailValid(jQuery("#pluginemail").val())){jQuery("#pluginemail-error").css("display","none");var O={action:"shortpixel_new_api_key",email:jQuery("#pluginemail").val()};jQuery.ajax({type:"POST",async:false,url:ShortPixel.AJAX_URL,data:O,success:function(Q){data=JSON.parse(Q);if(data.Status=="success"){P.preventDefault();window.location.reload()}else{if(data.Status=="invalid"){jQuery("#pluginemail-error").html("<b>"+data.Details+"</b>");jQuery("#pluginemail-error").css("display","");jQuery("#pluginemail-info").css("display","none");P.preventDefault()}else{}}}});jQuery("#request_key").removeAttr("onclick")}else{jQuery("#pluginemail-error").css("display","");jQuery("#pluginemail-info").css("display","none");P.preventDefault()}jQuery("#request_key").removeClass("disabled");jQuery("#pluginemail_spinner").removeClass("is-active")}function L(){jQuery("#shortPixelProposeUpgrade .sp-modal-body").addClass("sptw-modal-spinner");jQuery("#shortPixelProposeUpgrade .sp-modal-body").html("");jQuery("#shortPixelProposeUpgradeShade").css("display","block");jQuery("#shortPixelProposeUpgrade").removeClass("shortpixel-hide");var O={action:"shortpixel_propose_upgrade"};jQuery.ajax({type:"POST",url:ShortPixel.AJAX_URL,data:O,success:function(P){jQuery("#shortPixelProposeUpgrade .sp-modal-body").removeClass("sptw-modal-spinner");jQuery("#shortPixelProposeUpgrade .sp-modal-body").html(P)}})}function E(){jQuery("#shortPixelProposeUpgradeShade").css("display","none");jQuery("#shortPixelProposeUpgrade").addClass("shortpixel-hide");if(ShortPixel.toRefresh){ShortPixel.recheckQuota()}}function u(){jQuery("#short-pixel-notice-unlisted").hide();jQuery("#optimizeUnlisted").prop("checked",true);var O={action:"shortpixel_dismiss_notice",notice_id:"unlisted",notice_data:"true"};jQuery.get(ShortPixel.AJAX_URL,O,function(P){O=JSON.parse(P);if(O.Status==ShortPixel.STATUS_SUCCESS){console.log("dismissed")}})}function n(){jQuery(".select-folder-button").click(function(){jQuery(".sp-folder-picker-shade").css("display","block");jQuery(".sp-folder-picker").fileTree({script:ShortPixel.browseContent,multiFolder:false})});jQuery(".shortpixel-modal input.select-folder-cancel").click(function(){jQuery(".sp-folder-picker-shade").css("display","none")});jQuery(".shortpixel-modal input.select-folder").click(function(){var O=jQuery("UL.jqueryFileTree LI.directory.selected A").attr("rel").trim();if(O){var P=jQuery("#customFolderBase").val()+O;if(P.slice(-1)=="/"){P=P.slice(0,-1)}jQuery("#addCustomFolder").val(P);jQuery("#addCustomFolderView").val(P);jQuery(".sp-folder-picker-shade").css("display","none")}else{alert("Please select a folder from the list.")}})}function D(S,R,Q){var P=jQuery(".bulk-notice-msg.bulk-lengthy");if(P.length==0){return}var O=jQuery("a",P);O.text(R);if(Q){O.attr("href",Q)}else{O.attr("href",O.data("href").replace("__ID__",S))}P.css("display","block")}function y(){jQuery(".bulk-notice-msg.bulk-lengthy").css("display","none")}function v(O){var P=jQuery(".bulk-notice-msg.bulk-"+O);if(P.length==0){return}P.css("display","block")}function M(O){jQuery(".bulk-notice-msg.bulk-"+O).css("display","none")}function r(U,S,T,R){var O=jQuery("#bulk-error-template");if(O.length==0){return}var Q=O.clone();Q.attr("id","bulk-error-"+U);if(U==-1){jQuery("span.sp-err-title",Q).remove();Q.addClass("bulk-error-fatal")}else{jQuery("img",Q).remove();jQuery("#bulk-error-".id).remove()}jQuery("span.sp-err-content",Q).html(S);var P=jQuery("a.sp-post-link",Q);if(R){P.attr("href",R)}else{P.attr("href",P.attr("href").replace("__ID__",U))}P.text(T);O.after(Q);Q.css("display","block")}function B(O,P){if(!confirm(_spTr["confirmBulk"+O])){P.stopPropagation();P.preventDefault();return false}return true}function q(O){jQuery(O).parent().parent().remove()}function F(O){return O.substring(0,2)=="C-"}function H(){window.location.href=window.location.href+(window.location.href.indexOf("?")>0?"&":"?")+"checkquota=1"}function g(P){P.preventDefault();if(!this.menuCloseEvent){jQuery(window).click(function(Q){if(!Q.target.matches(".sp-dropbtn")){jQuery(".sp-dropdown.sp-show").removeClass("sp-show")}});this.menuCloseEvent=true}var O=P.target.parentElement.classList.contains("sp-show");jQuery(".sp-dropdown.sp-show").removeClass("sp-show");if(!O){P.target.parentElement.classList.add("sp-show")}}function N(O){this.comparerData.origUrl=false;if(this.comparerData.cssLoaded===false){jQuery("<link>").appendTo("head").attr({type:"text/css",rel:"stylesheet",href:this.WP_PLUGIN_URL+"/res/css/twentytwenty.min.css"});this.comparerData.cssLoaded=2}if(this.comparerData.jsLoaded===false){jQuery.getScript(this.WP_PLUGIN_URL+"/res/js/jquery.twentytwenty.min.js",function(){ShortPixel.comparerData.jsLoaded=2;if(ShortPixel.comparerData.origUrl.length>0){ShortPixel.displayComparerPopup(ShortPixel.comparerData.width,ShortPixel.comparerData.height,ShortPixel.comparerData.origUrl,ShortPixel.comparerData.optUrl)}});this.comparerData.jsLoaded=1;jQuery(".sp-close-button").click(ShortPixel.closeComparerPopup)}if(this.comparerData.origUrl===false){jQuery.ajax({type:"POST",url:ShortPixel.AJAX_URL,data:{action:"shortpixel_get_comparer_data",id:O},success:function(P){data=JSON.parse(P);jQuery.extend(ShortPixel.comparerData,data);if(ShortPixel.comparerData.jsLoaded==2){ShortPixel.displayComparerPopup(ShortPixel.comparerData.width,ShortPixel.comparerData.height,ShortPixel.comparerData.origUrl,ShortPixel.comparerData.optUrl)}}});this.comparerData.origUrl=""}}function C(S,Q,P,R){var V=S;var U=(Q<150||S<350);var T=jQuery(U?"#spUploadCompareSideBySide":"#spUploadCompare");if(!U){jQuery("#spCompareSlider").html('<img class="spUploadCompareOriginal"/><img class="spUploadCompareOptimized"/>')}S=Math.max(350,Math.min(800,(S<350?(S+25)*2:(Q<150?S+25:S))));Q=Math.max(150,(U?(V>350?2*(Q+45):Q+45):Q*S/V));jQuery(".sp-modal-body",T).css("width",S);jQuery(".shortpixel-slider",T).css("width",S);T.css("width",S);jQuery(".sp-modal-body",T).css("height",Q);T.css("display","block");T.parent().css("display","block");if(!U){jQuery("#spCompareSlider").twentytwenty({slider_move:"mousemove"})}jQuery(document).on("keyup.sp_modal_active",ShortPixel.closeComparerPopup);var O=jQuery(".spUploadCompareOptimized",T);jQuery(".spUploadCompareOriginal",T).attr("src",P);setTimeout(function(){jQuery(window).trigger("resize")},1000);O.load(function(){jQuery(window).trigger("resize")});O.attr("src",R)}function p(O){jQuery("#spUploadCompareSideBySide").parent().css("display","none");jQuery("#spUploadCompareSideBySide").css("display","none");jQuery("#spUploadCompare").css("display","none");jQuery(document).unbind("keyup.sp_modal_active")}return{init:G,setOptions:l,isEmailValid:s,updateSignupEmail:m,validateKey:a,enableResize:J,setupGeneralTab:e,apiKeyChanged:A,setupAdvancedTab:t,checkThumbsUpdTotal:I,switchSettingsTab:w,adjustSettingsTabs:x,onBulkThumbsCheck:z,dismissMediaAlert:K,checkQuota:j,percentDial:o,successMsg:b,successActions:c,otherMediaUpdateActions:h,retry:i,initFolderSelector:n,browseContent:k,getBackupSize:d,newApiKey:f,proposeUpgrade:L,closeProposeUpgrade:E,includeUnlisted:u,bulkShowLengthyMsg:D,bulkHideLengthyMsg:y,bulkShowMaintenanceMsg:v,bulkHideMaintenanceMsg:M,bulkShowError:r,confirmBulkAction:B,removeBulkMsg:q,isCustomImageId:F,recheckQuota:H,openImageMenu:g,menuCloseEvent:false,loadComparer:N,displayComparerPopup:C,closeComparerPopup:p,comparerData:{cssLoaded:false,jsLoaded:false,origUrl:false,optUrl:false,width:0,height:0},toRefresh:false,resizeSizesAlert:false}}();function showToolBarAlert(c,b,d){var a=jQuery("li.shortpixel-toolbar-processing");switch(c){case ShortPixel.STATUS_QUOTA_EXCEEDED:if(window.location.href.search("wp-short-pixel-bulk")>0&&jQuery(".sp-quota-exceeded-alert").length==0){location.reload();return}a.addClass("shortpixel-alert");a.addClass("shortpixel-quota-exceeded");jQuery("a",a).attr("href","options-general.php?page=wp-shortpixel");jQuery("a div",a).attr("title","ShortPixel quota exceeded. Click for details.");break;case ShortPixel.STATUS_SKIP:case ShortPixel.STATUS_FAIL:a.addClass("shortpixel-alert shortpixel-processing");jQuery("a div",a).attr("title",b);if(typeof d!=="undefined"){jQuery("a",a).attr("href","post.php?post="+d+"&action=edit")}break;case ShortPixel.STATUS_NO_KEY:a.addClass("shortpixel-alert");a.addClass("shortpixel-quota-exceeded");jQuery("a",a).attr("href","options-general.php?page=wp-shortpixel");jQuery("a div",a).attr("title","Get API Key");break;case ShortPixel.STATUS_SUCCESS:case ShortPixel.STATUS_RETRY:a.addClass("shortpixel-processing");a.removeClass("shortpixel-alert");jQuery("a",a).removeAttr("target");jQuery("a",a).attr("href",jQuery("a img",a).attr("success-url"))}a.removeClass("shortpixel-hide")}function hideToolBarAlert(){jQuery("li.shortpixel-toolbar-processing.shortpixel-processing").addClass("shortpixel-hide")}function hideQuotaExceededToolBarAlert(){jQuery("li.shortpixel-toolbar-processing.shortpixel-quota-exceeded").addClass("shortpixel-hide")}function checkQuotaExceededAlert(){if(typeof shortPixelQuotaExceeded!="undefined"){if(shortPixelQuotaExceeded==1){showToolBarAlert(ShortPixel.STATUS_QUOTA_EXCEEDED)}else{hideQuotaExceededToolBarAlert()}}}function checkBulkProgress(){var b=function(f){if(!d){d=true;return f}return"/"};var d=false;var a=window.location.href.toLowerCase().replace(/\/\//g,b);d=false;var c=ShortPixel.WP_ADMIN_URL.toLowerCase().replace(/\/\//g,b);if(a.search(c)<0){var e=document.createElement("a");e.href=a;a=a.replace(e.protocol+"//"+e.hostname,e.protocol+"//"+e.hostname.split(".").map(function(f){return sp_punycode.toASCII(f)}).join("."))}if(a.search(c+"upload.php")<0&&a.search(c+"edit.php")<0&&a.search(c+"edit-tags.php")<0&&a.search(c+"post-new.php")<0&&a.search(c+"post.php")<0&&a.search("page=nggallery-manage-gallery")<0&&(ShortPixel.FRONT_BOOTSTRAP==0||a.search(c)==0)){hideToolBarAlert();return}if(ShortPixel.bulkProcessor==true&&window.location.href.search("wp-short-pixel-bulk")<0&&typeof localStorage.bulkPage!=="undefined"&&localStorage.bulkPage>0){ShortPixel.bulkProcessor=false}if(window.location.href.search("wp-short-pixel-bulk")>=0){ShortPixel.bulkProcessor=true;localStorage.bulkTime=Math.floor(Date.now()/1000);localStorage.bulkPage=1}if(ShortPixel.bulkProcessor==true||typeof localStorage.bulkTime=="undefined"||Math.floor(Date.now()/1000)-localStorage.bulkTime>90){ShortPixel.bulkProcessor=true;localStorage.bulkPage=(window.location.href.search("wp-short-pixel-bulk")>=0?1:0);localStorage.bulkTime=Math.floor(Date.now()/1000);console.log(localStorage.bulkTime);checkBulkProcessingCallApi()}else{setTimeout(checkBulkProgress,5000)}}function checkBulkProcessingCallApi(){var a={action:"shortpixel_image_processing"};jQuery.ajax({type:"POST",url:ShortPixel.AJAX_URL,data:a,success:function(g){if(g.length>0){var i=null;try{var i=JSON.parse(g)}catch(k){ShortPixel.retry(k.message);return}ShortPixel.retries=0;var d=i.ImageID;var j=(jQuery("div.short-pixel-bulk-page").length>0);switch(i.Status){case ShortPixel.STATUS_NO_KEY:setCellMessage(d,i.Message,"<a class='button button-smaller button-primary' href=\"https://shortpixel.com/wp-apikey"+ShortPixel.AFFILIATE+'" target="_blank">'+_spTr.getApiKey+"</a>");showToolBarAlert(ShortPixel.STATUS_NO_KEY);break;case ShortPixel.STATUS_QUOTA_EXCEEDED:setCellMessage(d,i.Message,"<a class='button button-smaller button-primary' href=\"https://shortpixel.com/login/"+ShortPixel.API_KEY+'" target="_blank">'+_spTr.extendQuota+"</a><a class='button button-smaller' href='admin.php?action=shortpixel_check_quota'>"+_spTr.check__Quota+"</a>");showToolBarAlert(ShortPixel.STATUS_QUOTA_EXCEEDED);if(i.Stop==false){setTimeout(checkBulkProgress,5000)}ShortPixel.otherMediaUpdateActions(d,["quota","view"]);break;case ShortPixel.STATUS_FAIL:setCellMessage(d,i.Message,"<a class='button button-smaller button-primary' href=\"javascript:manualOptimization('"+d+"', false)\">"+_spTr.retry+"</a>");showToolBarAlert(ShortPixel.STATUS_FAIL,i.Message,d);if(j){ShortPixel.bulkShowError(d,i.Message,i.Filename,i.CustomImageLink);if(i.BulkPercent){progressUpdate(i.BulkPercent,i.BulkMsg)}ShortPixel.otherMediaUpdateActions(d,["retry","view"])}console.log(i.Message);setTimeout(checkBulkProgress,5000);break;case ShortPixel.STATUS_EMPTY_QUEUE:console.log(i.Message);clearBulkProcessor();hideToolBarAlert();var c=jQuery("#bulk-progress");if(j&&c.length&&i.BulkStatus!="2"){progressUpdate(100,"Bulk finished!");jQuery("a.bulk-cancel").attr("disabled","disabled");hideSlider();setTimeout(function(){window.location.reload()},3000)}break;case ShortPixel.STATUS_SUCCESS:if(j){ShortPixel.bulkHideLengthyMsg();ShortPixel.bulkHideMaintenanceMsg()}var l=i.PercentImprovement;showToolBarAlert(ShortPixel.STATUS_SUCCESS,"");var b=ShortPixel.isCustomImageId(d)?"":ShortPixel.successActions(d,i.Type,i.ThumbsCount,i.ThumbsTotal,i.BackupEnabled,i.Filename);setCellMessage(d,ShortPixel.successMsg(d,l,i.Type,i.ThumbsCount,i.RetinasCount),b);var h=jQuery(["restore","view","redolossy","redoglossy","redolossless"]).not(["redo"+i.Type]).get();ShortPixel.otherMediaUpdateActions(d,h);var f=new PercentageAnimator("#sp-msg-"+d+" span.percent",l);f.animate(l);if(j&&typeof i.Thumb!=="undefined"){if(i.BulkPercent){progressUpdate(i.BulkPercent,i.BulkMsg)}if(i.Thumb.length>0){sliderUpdate(d,i.Thumb,i.BkThumb,i.PercentImprovement,i.Filename);if(typeof i.AverageCompression!=="undefined"&&0+i.AverageCompression>0){jQuery("#sp-avg-optimization").html('<input type="text" class="dial" value="'+Math.round(i.AverageCompression)+'"/>');ShortPixel.percentDial("#sp-avg-optimization .dial",60)}}}console.log("Server response: "+g);if(j&&typeof i.BulkPercent!=="undefined"){progressUpdate(i.BulkPercent,i.BulkMsg)}setTimeout(checkBulkProgress,5000);break;case ShortPixel.STATUS_SKIP:if(i.Silent!==1){ShortPixel.bulkShowError(d,i.Message,i.Filename,i.CustomImageLink)}case ShortPixel.STATUS_ERROR:if(typeof i.Message!=="undefined"){showToolBarAlert(ShortPixel.STATUS_SKIP,i.Message+" Image ID: "+d);setCellMessage(d,i.Message,"")}ShortPixel.otherMediaUpdateActions(d,["retry","view"]);case ShortPixel.STATUS_RETRY:console.log("Server response: "+g);showToolBarAlert(ShortPixel.STATUS_RETRY,"");if(j&&typeof i.BulkPercent!=="undefined"){progressUpdate(i.BulkPercent,i.BulkMsg)}if(j&&i.Count>3){ShortPixel.bulkShowLengthyMsg(d,i.Filename,i.CustomImageLink)}setTimeout(checkBulkProgress,5000);break;case ShortPixel.STATUS_MAINTENANCE:ShortPixel.bulkShowMaintenanceMsg("maintenance");setTimeout(checkBulkProgress,60000);break;case ShortPixel.STATUS_QUEUE_FULL:ShortPixel.bulkShowMaintenanceMsg("queue-full");setTimeout(checkBulkProgress,60000);break;default:ShortPixel.retry("Unknown status "+i.Status+". Retrying...");break}}},error:function(b){ShortPixel.retry(b.statusText)}})}function clearBulkProcessor(){ShortPixel.bulkProcessor=false;localStorage.bulkTime=0;if(window.location.href.search("wp-short-pixel-bulk")>=0){localStorage.bulkPage=0}}function setCellMessage(d,a,c){var b=jQuery("#sp-msg-"+d);if(b.length>0){b.html("<div class='sp-column-actions'>"+c+"</div><div class='sp-column-info'>"+a+"</div>");b.css("color","")}b=jQuery("#sp-cust-msg-"+d);if(b.length>0){b.html("<div class='sp-column-info'>"+a+"</div>")}}function manualOptimization(c,a){setCellMessage(c,"<img src='"+ShortPixel.WP_PLUGIN_URL+"/res/img/loading.gif' class='sp-loading-small'>Image waiting to be processed","");jQuery("li.shortpixel-toolbar-processing").removeClass("shortpixel-hide");jQuery("li.shortpixel-toolbar-processing").removeClass("shortpixel-alert");jQuery("li.shortpixel-toolbar-processing").addClass("shortpixel-processing");var b={action:"shortpixel_manual_optimization",image_id:c,cleanup:a};jQuery.ajax({type:"GET",url:ShortPixel.AJAX_URL,data:b,success:function(d){var e=JSON.parse(d);if(e.Status==ShortPixel.STATUS_SUCCESS){setTimeout(checkBulkProgress,2000)}else{setCellMessage(c,typeof e.Message!=="undefined"?e.Message:_spTr.thisContentNotProcessable,"")}},error:function(d){b.action="shortpixel_check_status";jQuery.ajax({type:"GET",url:ShortPixel.AJAX_URL,data:b,success:function(e){var f=JSON.parse(e);if(f.Status!==ShortPixel.STATUS_SUCCESS){setCellMessage(c,typeof f.Message!=="undefined"?f.Message:_spTr.thisContentNotProcessable,"")}}})}})}function reoptimize(c,a){setCellMessage(c,"<img src='"+ShortPixel.WP_PLUGIN_URL+"/res/img/loading.gif' class='sp-loading-small'>Image waiting to be reprocessed","");jQuery("li.shortpixel-toolbar-processing").removeClass("shortpixel-hide");jQuery("li.shortpixel-toolbar-processing").addClass("shortpixel-processing");var b={action:"shortpixel_redo",attachment_ID:c,type:a};jQuery.get(ShortPixel.AJAX_URL,b,function(d){b=JSON.parse(d);if(b.Status==ShortPixel.STATUS_SUCCESS){setTimeout(checkBulkProgress,2000)}else{$msg=typeof b.Message!=="undefined"?b.Message:_spTr.thisContentNotProcessable;setCellMessage(c,$msg,"");showToolBarAlert(ShortPixel.STATUS_FAIL,$msg)}})}function optimizeThumbs(b){setCellMessage(b,"<img src='"+ShortPixel.WP_PLUGIN_URL+"/res/img/loading.gif' class='sp-loading-small'>"+_spTr.imageWaitOptThumbs,"");jQuery("li.shortpixel-toolbar-processing").removeClass("shortpixel-hide");jQuery("li.shortpixel-toolbar-processing").addClass("shortpixel-processing");var a={action:"shortpixel_optimize_thumbs",attachment_ID:b};jQuery.get(ShortPixel.AJAX_URL,a,function(c){a=JSON.parse(c);if(a.Status==ShortPixel.STATUS_SUCCESS){setTimeout(checkBulkProgress,2000)}else{setCellMessage(b,typeof a.Message!=="undefined"?a.Message:_spTr.thisContentNotProcessable,"")}})}function dismissShortPixelNoticeExceed(b){jQuery("#wp-admin-bar-shortpixel_processing").hide();var a={action:"shortpixel_dismiss_notice",notice_id:"exceed"};jQuery.get(ShortPixel.AJAX_URL,a,function(c){a=JSON.parse(c);if(a.Status==ShortPixel.STATUS_SUCCESS){console.log("dismissed")}});b.preventDefault()}function dismissShortPixelNotice(b){jQuery("#short-pixel-notice-"+b).hide();var a={action:"shortpixel_dismiss_notice",notice_id:b};jQuery.get(ShortPixel.AJAX_URL,a,function(c){a=JSON.parse(c);if(a.Status==ShortPixel.STATUS_SUCCESS){console.log("dismissed")}})}function PercentageAnimator(b,a){this.animationSpeed=10;this.increment=2;this.curPercentage=0;this.targetPercentage=a;this.outputSelector=b;this.animate=function(c){this.targetPercentage=c;setTimeout(PercentageTimer.bind(null,this),this.animationSpeed)}}function PercentageTimer(a){if(a.curPercentage-a.targetPercentage<-a.increment){a.curPercentage+=a.increment}else{if(a.curPercentage-a.targetPercentage>a.increment){a.curPercentage-=a.increment}else{a.curPercentage=a.targetPercentage}}jQuery(a.outputSelector).text(a.curPercentage+"%");if(a.curPercentage!=a.targetPercentage){setTimeout(PercentageTimer.bind(null,a),a.animationSpeed)}}function progressUpdate(c,b){var a=jQuery("#bulk-progress");if(a.length){jQuery(".progress-left",a).css("width",c+"%");jQuery(".progress-img",a).css("left",c+"%");if(c>24){jQuery(".progress-img span",a).html("");jQuery(".progress-left",a).html(c+"%")}else{jQuery(".progress-img span",a).html(c+"%");jQuery(".progress-left",a).html("")}jQuery(".bulk-estimate").html(b)}}function sliderUpdate(g,c,d,e,b){var f=jQuery(".bulk-slider div.bulk-slide:first-child");if(f.length===0){return}if(f.attr("id")!="empty-slide"){f.hide()}f.css("z-index",1000);jQuery(".bulk-img-opt",f).attr("src","");if(typeof d==="undefined"){d=""}if(d.length>0){jQuery(".bulk-img-orig",f).attr("src","")}var a=f.clone();a.attr("id","slide-"+g);jQuery(".bulk-img-opt",a).attr("src",c);if(d.length>0){jQuery(".img-original",a).css("display","inline-block");jQuery(".bulk-img-orig",a).attr("src",d)}else{jQuery(".img-original",a).css("display","none")}jQuery(".bulk-opt-percent",a).html('<input type="text" class="dial" value="'+e+'"/>');jQuery(".bulk-slider").append(a);ShortPixel.percentDial("#"+a.attr("id")+" .dial",100);jQuery(".bulk-slider-container span.filename").html("&nbsp;&nbsp;"+b);if(f.attr("id")=="empty-slide"){f.remove();jQuery(".bulk-slider-container").css("display","block")}else{f.animate({left:f.width()+f.position().left},"slow","swing",function(){f.remove();a.fadeIn("slow")})}}function hideSlider(){jQuery(".bulk-slider-container").css("display","none")}function showStats(){var a=jQuery(".bulk-stats");if(a.length>0){}}if(!(typeof String.prototype.format=="function")){String.prototype.format=function(){var b=this,a=arguments.length;while(a--){b=b.replace(new RegExp("\\{"+a+"\\}","gm"),arguments[a])}return b}};
1
+ jQuery(document).ready(function(a){ShortPixel.init()});var ShortPixel=function(){function H(){if(typeof ShortPixel.API_KEY!=="undefined"){return}if(jQuery("table.wp-list-table.media").length>0){jQuery('select[name^="action"] option:last-child').before('<option value="short-pixel-bulk">'+_spTr.optimizeWithSP+'</option><option value="short-pixel-bulk-lossy"> → '+_spTr.redoLossy+'</option><option value="short-pixel-bulk-glossy"> → '+_spTr.redoGlossy+'</option><option value="short-pixel-bulk-lossless"> → '+_spTr.redoLossless+'</option><option value="short-pixel-bulk-restore"> → '+_spTr.restoreOriginal+"</option>")}ShortPixel.setOptions(ShortPixelConstants);if(jQuery("#backup-folder-size").length){jQuery("#backup-folder-size").html(ShortPixel.getBackupSize())}if(ShortPixel.MEDIA_ALERT=="todo"&&jQuery("div.media-frame.mode-grid").length>0){jQuery("div.media-frame.mode-grid").before('<div id="short-pixel-media-alert" class="notice notice-warning"><p>'+_spTr.changeMLToListMode.format('<a href="upload.php?mode=list" class="view-list"><span class="screen-reader-text">'," </span>",'</a><a class="alignright" href="javascript:ShortPixel.dismissMediaAlert();">',"</a>")+"</p></div>")}jQuery(window).on("beforeunload",function(){if(ShortPixel.bulkProcessor==true){clearBulkProcessor()}});checkQuotaExceededAlert();checkBulkProgress()}function l(P){for(var Q in P){ShortPixel[Q]=P[Q]}}function s(P){return/^\w+([\.+-]?\w+)*@\w+([\.-]?\w+)*(\.\w{1,63})+$/.test(P)}function m(){var P=jQuery("#pluginemail").val();if(ShortPixel.isEmailValid(P)){jQuery("#request_key").removeClass("disabled")}jQuery("#request_key").attr("href",jQuery("#request_key").attr("href").split("?")[0]+"?pluginemail="+P)}function a(){jQuery("#valid").val("validate");jQuery("#wp_shortpixel_options").submit()}jQuery("#key").keypress(function(P){if(P.which==13){jQuery("#valid").val("validate")}});function K(P){if(jQuery(P).is(":checked")){jQuery("#width,#height").removeAttr("disabled")}else{jQuery("#width,#height").attr("disabled","disabled")}}function e(P,R,T){for(var Q=0,S=null;Q<P.length;Q++){P[Q].onclick=function(){if(this!==S){S=this}if(typeof ShortPixel.setupGeneralTabAlert!=="undefined"){return}alert(_spTr.alertOnlyAppliesToNewImages);ShortPixel.setupGeneralTabAlert=1}}ShortPixel.enableResize("#resize");jQuery("#resize").change(function(){K(this)});jQuery(".resize-sizes").blur(function(V){var W=jQuery(this);if(ShortPixel.resizeSizesAlert==W.val()){return}ShortPixel.resizeSizesAlert=W.val();var U=jQuery("#min-"+W.attr("name")).val();if(W.val()<Math.min(U,1024)){if(U>1024){alert(_spTr.pleaseDoNotSetLesser1024.format(W.attr("name")))}else{alert(_spTr.pleaseDoNotSetLesserSize.format(W.attr("name"),W.attr("name"),U))}V.preventDefault();W.focus()}else{this.defaultValue=W.val()}});jQuery(".shortpixel-confirm").click(function(V){var U=confirm(V.target.getAttribute("data-confirm"));if(!U){V.preventDefault();return false}return true})}function B(){jQuery(".wp-shortpixel-options .shortpixel-key-valid").css("display","none");jQuery(".wp-shortpixel-options button#validate").css("display","inline-block")}function t(){jQuery("input.remove-folder-button").click(function(){var Q=jQuery(this).data("value");var P=confirm(_spTr.areYouSureStopOptimizing.format(Q));if(P==true){jQuery("#removeFolder").val(Q);jQuery("#wp_shortpixel_options").submit()}});jQuery("input.recheck-folder-button").click(function(){var Q=jQuery(this).data("value");var P=confirm(_spTr.areYouSureStopOptimizing.format(Q));if(P==true){jQuery("#recheckFolder").val(Q);jQuery("#wp_shortpixel_options").submit()}})}function J(P){var Q=jQuery("#"+(P.checked?"total":"main")+"ToProcess").val();jQuery("div.bulk-play span.total").text(Q);jQuery("#displayTotal").text(Q)}function w(Q){var P=jQuery("section#"+Q);if(P.length>0){jQuery("section").removeClass("sel-tab");jQuery("section#"+Q).addClass("sel-tab")}}function x(){var P=jQuery("section#tab-settings .wp-shortpixel-options").height()+90;P=Math.max(P,jQuery("section#tab-adv-settings .wp-shortpixel-options").height()+20);P=Math.max(P,jQuery("section#tab-resources .area1").height()+60);jQuery("#shortpixel-settings-tabs").css("height",P);jQuery("#shortpixel-settings-tabs section").css("height",P)}function L(){var P={action:"shortpixel_dismiss_media_alert"};jQuery.get(ShortPixel.AJAX_URL,P,function(Q){P=JSON.parse(Q);if(P.Status=="success"){jQuery("#short-pixel-media-alert").hide();console.log("dismissed")}})}function j(){var P={action:"shortpixel_check_quota"};jQuery.get(ShortPixel.AJAX_URL,P,function(){console.log("quota refreshed")})}function A(P){if(P.checked){jQuery("#with-thumbs").css("display","inherit");jQuery("#without-thumbs").css("display","none")}else{jQuery("#without-thumbs").css("display","inherit");jQuery("#with-thumbs").css("display","none")}}function b(T,R,Q,S,P){return(R>0?"<div class='sp-column-info'>"+_spTr.reducedBy+" <strong><span class='percent'>"+R+"%</span></strong> ":"")+(R>0&&R<5?"<br>":"")+(R<5?_spTr.bonusProcessing:"")+(Q.length>0?" ("+Q+")":"")+(0+S>0?"<br>"+_spTr.plusXthumbsOpt.format(S):"")+(0+P>0?"<br>"+_spTr.plusXretinasOpt.format(P):"")+"</div>"}function o(Q,P){jQuery(Q).knob({readOnly:true,width:P,height:P,fgColor:"#1CAECB",format:function(R){return R+"%"}})}function c(W,R,U,T,Q,V){if(Q==1){var S=jQuery(".sp-column-actions-template").clone();if(!S.length){return false}var P;if(R.length==0){P=["lossy","lossless"]}else{P=["lossy","glossy","lossless"].filter(function(X){return !(X==R)})}S.html(S.html().replace(/__SP_ID__/g,W));if(V.substr(V.lastIndexOf(".")+1).toLowerCase()=="pdf"){jQuery(".sp-action-compare",S).remove()}if(U==0&&T>0){S.html(S.html().replace("__SP_THUMBS_TOTAL__",T))}else{jQuery(".sp-action-optimize-thumbs",S).remove();jQuery(".sp-dropbtn",S).removeClass("button-primary")}S.html(S.html().replace(/__SP_FIRST_TYPE__/g,P[0]));S.html(S.html().replace(/__SP_SECOND_TYPE__/g,P[1]));return S.html()}return""}function h(T,S){T=T.substring(2);if(jQuery(".shortpixel-other-media").length){var R=["optimize","retry","restore","redo","quota","view"];for(var Q=0,P=R.length;Q<P;Q++){jQuery("#"+R[Q]+"_"+T).css("display","none")}for(var Q=0,P=S.length;Q<P;Q++){jQuery("#"+S[Q]+"_"+T).css("display","")}}}function i(P){ShortPixel.retries++;if(isNaN(ShortPixel.retries)){ShortPixel.retries=1}if(ShortPixel.retries<6){console.log("Invalid response from server (Error: "+P+"). Retrying pass "+(ShortPixel.retries+1)+"...");setTimeout(checkBulkProgress,5000)}else{ShortPixel.bulkShowError(-1,"Invalid response from server received 6 times. Please retry later by reloading this page, or <a href='https://shortpixel.com/contact' target='_blank'>contact support</a>. (Error: "+P+")","");console.log("Invalid response from server 6 times. Giving up.")}}function k(P){P.action="shortpixel_browse_content";var Q="";jQuery.ajax({type:"POST",url:ShortPixel.AJAX_URL,data:P,success:function(R){Q=R},async:false});return Q}function d(){var P={action:"shortpixel_get_backup_size"};var Q="";jQuery.ajax({type:"POST",url:ShortPixel.AJAX_URL,data:P,success:function(R){Q=R},async:false});return Q}function f(Q){if(!jQuery("#tos").is(":checked")){Q.preventDefault();jQuery("#tos-robo").fadeIn(400,function(){jQuery("#tos-hand").fadeIn()});jQuery("#tos").click(function(){jQuery("#tos-robo").css("display","none");jQuery("#tos-hand").css("display","none")});return}jQuery("#request_key").addClass("disabled");jQuery("#pluginemail_spinner").addClass("is-active");ShortPixel.updateSignupEmail();if(ShortPixel.isEmailValid(jQuery("#pluginemail").val())){jQuery("#pluginemail-error").css("display","none");var P={action:"shortpixel_new_api_key",email:jQuery("#pluginemail").val()};jQuery.ajax({type:"POST",async:false,url:ShortPixel.AJAX_URL,data:P,success:function(R){data=JSON.parse(R);if(data.Status=="success"){Q.preventDefault();window.location.reload()}else{if(data.Status=="invalid"){jQuery("#pluginemail-error").html("<b>"+data.Details+"</b>");jQuery("#pluginemail-error").css("display","");jQuery("#pluginemail-info").css("display","none");Q.preventDefault()}else{}}}});jQuery("#request_key").removeAttr("onclick")}else{jQuery("#pluginemail-error").css("display","");jQuery("#pluginemail-info").css("display","none");Q.preventDefault()}jQuery("#request_key").removeClass("disabled");jQuery("#pluginemail_spinner").removeClass("is-active")}function M(){jQuery("#shortPixelProposeUpgrade .sp-modal-body").addClass("sptw-modal-spinner");jQuery("#shortPixelProposeUpgrade .sp-modal-body").html("");jQuery("#shortPixelProposeUpgradeShade").css("display","block");jQuery("#shortPixelProposeUpgrade").removeClass("shortpixel-hide");var P={action:"shortpixel_propose_upgrade"};jQuery.ajax({type:"POST",url:ShortPixel.AJAX_URL,data:P,success:function(Q){jQuery("#shortPixelProposeUpgrade .sp-modal-body").removeClass("sptw-modal-spinner");jQuery("#shortPixelProposeUpgrade .sp-modal-body").html(Q)}})}function F(){jQuery("#shortPixelProposeUpgradeShade").css("display","none");jQuery("#shortPixelProposeUpgrade").addClass("shortpixel-hide");if(ShortPixel.toRefresh){ShortPixel.recheckQuota()}}function u(){jQuery("#short-pixel-notice-unlisted").hide();jQuery("#optimizeUnlisted").prop("checked",true);var P={action:"shortpixel_dismiss_notice",notice_id:"unlisted",notice_data:"true"};jQuery.get(ShortPixel.AJAX_URL,P,function(Q){P=JSON.parse(Q);if(P.Status==ShortPixel.STATUS_SUCCESS){console.log("dismissed")}})}function n(){jQuery(".select-folder-button").click(function(){jQuery(".sp-folder-picker-shade").css("display","block");jQuery(".sp-folder-picker").fileTree({script:ShortPixel.browseContent,multiFolder:false})});jQuery(".shortpixel-modal input.select-folder-cancel").click(function(){jQuery(".sp-folder-picker-shade").css("display","none")});jQuery(".shortpixel-modal input.select-folder").click(function(){var P=jQuery("UL.jqueryFileTree LI.directory.selected A").attr("rel").trim();if(P){var Q=jQuery("#customFolderBase").val()+P;if(Q.slice(-1)=="/"){Q=Q.slice(0,-1)}jQuery("#addCustomFolder").val(Q);jQuery("#addCustomFolderView").val(Q);jQuery(".sp-folder-picker-shade").css("display","none")}else{alert("Please select a folder from the list.")}})}function E(T,S,R){var Q=jQuery(".bulk-notice-msg.bulk-lengthy");if(Q.length==0){return}var P=jQuery("a",Q);P.text(S);if(R){P.attr("href",R)}else{P.attr("href",P.data("href").replace("__ID__",T))}Q.css("display","block")}function z(){jQuery(".bulk-notice-msg.bulk-lengthy").css("display","none")}function v(P){var Q=jQuery(".bulk-notice-msg.bulk-"+P);if(Q.length==0){return}Q.css("display","block")}function N(P){jQuery(".bulk-notice-msg.bulk-"+P).css("display","none")}function r(V,T,U,S){var P=jQuery("#bulk-error-template");if(P.length==0){return}var R=P.clone();R.attr("id","bulk-error-"+V);if(V==-1){jQuery("span.sp-err-title",R).remove();R.addClass("bulk-error-fatal")}else{jQuery("img",R).remove();jQuery("#bulk-error-".id).remove()}jQuery("span.sp-err-content",R).html(T);var Q=jQuery("a.sp-post-link",R);if(S){Q.attr("href",S)}else{Q.attr("href",Q.attr("href").replace("__ID__",V))}Q.text(U);P.after(R);R.css("display","block")}function C(P,Q){if(!confirm(_spTr["confirmBulk"+P])){Q.stopPropagation();Q.preventDefault();return false}return true}function q(P){jQuery(P).parent().parent().remove()}function G(P){return P.substring(0,2)=="C-"}function I(){window.location.href=window.location.href+(window.location.href.indexOf("?")>0?"&":"?")+"checkquota=1"}function g(Q){Q.preventDefault();if(!this.menuCloseEvent){jQuery(window).click(function(R){if(!R.target.matches(".sp-dropbtn")){jQuery(".sp-dropdown.sp-show").removeClass("sp-show")}});this.menuCloseEvent=true}var P=Q.target.parentElement.classList.contains("sp-show");jQuery(".sp-dropdown.sp-show").removeClass("sp-show");if(!P){Q.target.parentElement.classList.add("sp-show")}}function O(P){this.comparerData.origUrl=false;if(this.comparerData.cssLoaded===false){jQuery("<link>").appendTo("head").attr({type:"text/css",rel:"stylesheet",href:this.WP_PLUGIN_URL+"/res/css/twentytwenty.min.css"});this.comparerData.cssLoaded=2}if(this.comparerData.jsLoaded===false){jQuery.getScript(this.WP_PLUGIN_URL+"/res/js/jquery.twentytwenty.min.js",function(){ShortPixel.comparerData.jsLoaded=2;if(ShortPixel.comparerData.origUrl.length>0){ShortPixel.displayComparerPopup(ShortPixel.comparerData.width,ShortPixel.comparerData.height,ShortPixel.comparerData.origUrl,ShortPixel.comparerData.optUrl)}});this.comparerData.jsLoaded=1;jQuery(".sp-close-button").click(ShortPixel.closeComparerPopup)}if(this.comparerData.origUrl===false){jQuery.ajax({type:"POST",url:ShortPixel.AJAX_URL,data:{action:"shortpixel_get_comparer_data",id:P},success:function(Q){data=JSON.parse(Q);jQuery.extend(ShortPixel.comparerData,data);if(ShortPixel.comparerData.jsLoaded==2){ShortPixel.displayComparerPopup(ShortPixel.comparerData.width,ShortPixel.comparerData.height,ShortPixel.comparerData.origUrl,ShortPixel.comparerData.optUrl)}}});this.comparerData.origUrl=""}}function D(T,R,Q,S){var W=T;var V=(R<150||T<350);var U=jQuery(V?"#spUploadCompareSideBySide":"#spUploadCompare");if(!V){jQuery("#spCompareSlider").html('<img class="spUploadCompareOriginal"/><img class="spUploadCompareOptimized"/>')}T=Math.max(350,Math.min(800,(T<350?(T+25)*2:(R<150?T+25:T))));R=Math.max(150,(V?(W>350?2*(R+45):R+45):R*T/W));jQuery(".sp-modal-body",U).css("width",T);jQuery(".shortpixel-slider",U).css("width",T);U.css("width",T);jQuery(".sp-modal-body",U).css("height",R);U.css("display","block");U.parent().css("display","block");if(!V){jQuery("#spCompareSlider").twentytwenty({slider_move:"mousemove"})}jQuery(document).on("keyup.sp_modal_active",ShortPixel.closeComparerPopup);var P=jQuery(".spUploadCompareOptimized",U);jQuery(".spUploadCompareOriginal",U).attr("src",Q);setTimeout(function(){jQuery(window).trigger("resize")},1000);P.load(function(){jQuery(window).trigger("resize")});P.attr("src",S)}function p(P){jQuery("#spUploadCompareSideBySide").parent().css("display","none");jQuery("#spUploadCompareSideBySide").css("display","none");jQuery("#spUploadCompare").css("display","none");jQuery(document).unbind("keyup.sp_modal_active")}function y(P){var Q=document.createElement("a");Q.href=P;if(P.indexOf(Q.protocol+"//"+Q.hostname)<0){return Q.href}return P.replace(Q.protocol+"//"+Q.hostname,Q.protocol+"//"+Q.hostname.split(".").map(function(R){return sp_punycode.toASCII(R)}).join("."))}return{init:H,setOptions:l,isEmailValid:s,updateSignupEmail:m,validateKey:a,enableResize:K,setupGeneralTab:e,apiKeyChanged:B,setupAdvancedTab:t,checkThumbsUpdTotal:J,switchSettingsTab:w,adjustSettingsTabs:x,onBulkThumbsCheck:A,dismissMediaAlert:L,checkQuota:j,percentDial:o,successMsg:b,successActions:c,otherMediaUpdateActions:h,retry:i,initFolderSelector:n,browseContent:k,getBackupSize:d,newApiKey:f,proposeUpgrade:M,closeProposeUpgrade:F,includeUnlisted:u,bulkShowLengthyMsg:E,bulkHideLengthyMsg:z,bulkShowMaintenanceMsg:v,bulkHideMaintenanceMsg:N,bulkShowError:r,confirmBulkAction:C,removeBulkMsg:q,isCustomImageId:G,recheckQuota:I,openImageMenu:g,menuCloseEvent:false,loadComparer:O,displayComparerPopup:D,closeComparerPopup:p,convertPunycode:y,comparerData:{cssLoaded:false,jsLoaded:false,origUrl:false,optUrl:false,width:0,height:0},toRefresh:false,resizeSizesAlert:false}}();function showToolBarAlert(c,b,d){var a=jQuery("li.shortpixel-toolbar-processing");switch(c){case ShortPixel.STATUS_QUOTA_EXCEEDED:if(window.location.href.search("wp-short-pixel-bulk")>0&&jQuery(".sp-quota-exceeded-alert").length==0){location.reload();return}a.addClass("shortpixel-alert");a.addClass("shortpixel-quota-exceeded");jQuery("a",a).attr("href","options-general.php?page=wp-shortpixel");jQuery("a div",a).attr("title","ShortPixel quota exceeded. Click for details.");break;case ShortPixel.STATUS_SKIP:case ShortPixel.STATUS_FAIL:a.addClass("shortpixel-alert shortpixel-processing");jQuery("a div",a).attr("title",b);if(typeof d!=="undefined"){jQuery("a",a).attr("href","post.php?post="+d+"&action=edit")}break;case ShortPixel.STATUS_NO_KEY:a.addClass("shortpixel-alert");a.addClass("shortpixel-quota-exceeded");jQuery("a",a).attr("href","options-general.php?page=wp-shortpixel");jQuery("a div",a).attr("title","Get API Key");break;case ShortPixel.STATUS_SUCCESS:case ShortPixel.STATUS_RETRY:a.addClass("shortpixel-processing");a.removeClass("shortpixel-alert");jQuery("a",a).removeAttr("target");jQuery("a",a).attr("href",jQuery("a img",a).attr("success-url"))}a.removeClass("shortpixel-hide")}function hideToolBarAlert(){jQuery("li.shortpixel-toolbar-processing.shortpixel-processing").addClass("shortpixel-hide")}function hideQuotaExceededToolBarAlert(){jQuery("li.shortpixel-toolbar-processing.shortpixel-quota-exceeded").addClass("shortpixel-hide")}function checkQuotaExceededAlert(){if(typeof shortPixelQuotaExceeded!="undefined"){if(shortPixelQuotaExceeded==1){showToolBarAlert(ShortPixel.STATUS_QUOTA_EXCEEDED)}else{hideQuotaExceededToolBarAlert()}}}function checkBulkProgress(){var b=function(e){if(!d){d=true;return e}return"/"};var d=false;var a=window.location.href.toLowerCase().replace(/\/\//g,b);d=false;var c=ShortPixel.WP_ADMIN_URL.toLowerCase().replace(/\/\//g,b);if(a.search(c)<0){a=ShortPixel.convertPunycode(a);c=ShortPixel.convertPunycode(c)}if(a.search(c+"upload.php")<0&&a.search(c+"edit.php")<0&&a.search(c+"edit-tags.php")<0&&a.search(c+"post-new.php")<0&&a.search(c+"post.php")<0&&a.search("page=nggallery-manage-gallery")<0&&(ShortPixel.FRONT_BOOTSTRAP==0||a.search(c)==0)){hideToolBarAlert();return}if(ShortPixel.bulkProcessor==true&&window.location.href.search("wp-short-pixel-bulk")<0&&typeof localStorage.bulkPage!=="undefined"&&localStorage.bulkPage>0){ShortPixel.bulkProcessor=false}if(window.location.href.search("wp-short-pixel-bulk")>=0){ShortPixel.bulkProcessor=true;localStorage.bulkTime=Math.floor(Date.now()/1000);localStorage.bulkPage=1}if(ShortPixel.bulkProcessor==true||typeof localStorage.bulkTime=="undefined"||Math.floor(Date.now()/1000)-localStorage.bulkTime>90){ShortPixel.bulkProcessor=true;localStorage.bulkPage=(window.location.href.search("wp-short-pixel-bulk")>=0?1:0);localStorage.bulkTime=Math.floor(Date.now()/1000);console.log(localStorage.bulkTime);checkBulkProcessingCallApi()}else{setTimeout(checkBulkProgress,5000)}}function checkBulkProcessingCallApi(){var a={action:"shortpixel_image_processing"};jQuery.ajax({type:"POST",url:ShortPixel.AJAX_URL,data:a,success:function(g){if(g.length>0){var i=null;try{var i=JSON.parse(g)}catch(k){ShortPixel.retry(k.message);return}ShortPixel.retries=0;var d=i.ImageID;var j=(jQuery("div.short-pixel-bulk-page").length>0);switch(i.Status){case ShortPixel.STATUS_NO_KEY:setCellMessage(d,i.Message,"<a class='button button-smaller button-primary' href=\"https://shortpixel.com/wp-apikey"+ShortPixel.AFFILIATE+'" target="_blank">'+_spTr.getApiKey+"</a>");showToolBarAlert(ShortPixel.STATUS_NO_KEY);break;case ShortPixel.STATUS_QUOTA_EXCEEDED:setCellMessage(d,i.Message,"<a class='button button-smaller button-primary' href=\"https://shortpixel.com/login/"+ShortPixel.API_KEY+'" target="_blank">'+_spTr.extendQuota+"</a><a class='button button-smaller' href='admin.php?action=shortpixel_check_quota'>"+_spTr.check__Quota+"</a>");showToolBarAlert(ShortPixel.STATUS_QUOTA_EXCEEDED);if(i.Stop==false){setTimeout(checkBulkProgress,5000)}ShortPixel.otherMediaUpdateActions(d,["quota","view"]);break;case ShortPixel.STATUS_FAIL:setCellMessage(d,i.Message,"<a class='button button-smaller button-primary' href=\"javascript:manualOptimization('"+d+"', false)\">"+_spTr.retry+"</a>");showToolBarAlert(ShortPixel.STATUS_FAIL,i.Message,d);if(j){ShortPixel.bulkShowError(d,i.Message,i.Filename,i.CustomImageLink);if(i.BulkPercent){progressUpdate(i.BulkPercent,i.BulkMsg)}ShortPixel.otherMediaUpdateActions(d,["retry","view"])}console.log(i.Message);setTimeout(checkBulkProgress,5000);break;case ShortPixel.STATUS_EMPTY_QUEUE:console.log(i.Message);clearBulkProcessor();hideToolBarAlert();var c=jQuery("#bulk-progress");if(j&&c.length&&i.BulkStatus!="2"){progressUpdate(100,"Bulk finished!");jQuery("a.bulk-cancel").attr("disabled","disabled");hideSlider();setTimeout(function(){window.location.reload()},3000)}break;case ShortPixel.STATUS_SUCCESS:if(j){ShortPixel.bulkHideLengthyMsg();ShortPixel.bulkHideMaintenanceMsg()}var l=i.PercentImprovement;showToolBarAlert(ShortPixel.STATUS_SUCCESS,"");var b=ShortPixel.isCustomImageId(d)?"":ShortPixel.successActions(d,i.Type,i.ThumbsCount,i.ThumbsTotal,i.BackupEnabled,i.Filename);setCellMessage(d,ShortPixel.successMsg(d,l,i.Type,i.ThumbsCount,i.RetinasCount),b);var h=jQuery(["restore","view","redolossy","redoglossy","redolossless"]).not(["redo"+i.Type]).get();ShortPixel.otherMediaUpdateActions(d,h);var f=new PercentageAnimator("#sp-msg-"+d+" span.percent",l);f.animate(l);if(j&&typeof i.Thumb!=="undefined"){if(i.BulkPercent){progressUpdate(i.BulkPercent,i.BulkMsg)}if(i.Thumb.length>0){sliderUpdate(d,i.Thumb,i.BkThumb,i.PercentImprovement,i.Filename);if(typeof i.AverageCompression!=="undefined"&&0+i.AverageCompression>0){jQuery("#sp-avg-optimization").html('<input type="text" class="dial" value="'+Math.round(i.AverageCompression)+'"/>');ShortPixel.percentDial("#sp-avg-optimization .dial",60)}}}console.log("Server response: "+g);if(j&&typeof i.BulkPercent!=="undefined"){progressUpdate(i.BulkPercent,i.BulkMsg)}setTimeout(checkBulkProgress,5000);break;case ShortPixel.STATUS_SKIP:if(i.Silent!==1){ShortPixel.bulkShowError(d,i.Message,i.Filename,i.CustomImageLink)}case ShortPixel.STATUS_ERROR:if(typeof i.Message!=="undefined"){showToolBarAlert(ShortPixel.STATUS_SKIP,i.Message+" Image ID: "+d);setCellMessage(d,i.Message,"")}ShortPixel.otherMediaUpdateActions(d,["retry","view"]);case ShortPixel.STATUS_RETRY:console.log("Server response: "+g);showToolBarAlert(ShortPixel.STATUS_RETRY,"");if(j&&typeof i.BulkPercent!=="undefined"){progressUpdate(i.BulkPercent,i.BulkMsg)}if(j&&i.Count>3){ShortPixel.bulkShowLengthyMsg(d,i.Filename,i.CustomImageLink)}setTimeout(checkBulkProgress,5000);break;case ShortPixel.STATUS_MAINTENANCE:ShortPixel.bulkShowMaintenanceMsg("maintenance");setTimeout(checkBulkProgress,60000);break;case ShortPixel.STATUS_QUEUE_FULL:ShortPixel.bulkShowMaintenanceMsg("queue-full");setTimeout(checkBulkProgress,60000);break;default:ShortPixel.retry("Unknown status "+i.Status+". Retrying...");break}}},error:function(b){ShortPixel.retry(b.statusText)}})}function clearBulkProcessor(){ShortPixel.bulkProcessor=false;localStorage.bulkTime=0;if(window.location.href.search("wp-short-pixel-bulk")>=0){localStorage.bulkPage=0}}function setCellMessage(d,a,c){var b=jQuery("#sp-msg-"+d);if(b.length>0){b.html("<div class='sp-column-actions'>"+c+"</div><div class='sp-column-info'>"+a+"</div>");b.css("color","")}b=jQuery("#sp-cust-msg-"+d);if(b.length>0){b.html("<div class='sp-column-info'>"+a+"</div>")}}function manualOptimization(c,a){setCellMessage(c,"<img src='"+ShortPixel.WP_PLUGIN_URL+"/res/img/loading.gif' class='sp-loading-small'>Image waiting to be processed","");jQuery("li.shortpixel-toolbar-processing").removeClass("shortpixel-hide");jQuery("li.shortpixel-toolbar-processing").removeClass("shortpixel-alert");jQuery("li.shortpixel-toolbar-processing").addClass("shortpixel-processing");var b={action:"shortpixel_manual_optimization",image_id:c,cleanup:a};jQuery.ajax({type:"GET",url:ShortPixel.AJAX_URL,data:b,success:function(d){var e=JSON.parse(d);if(e.Status==ShortPixel.STATUS_SUCCESS){setTimeout(checkBulkProgress,2000)}else{setCellMessage(c,typeof e.Message!=="undefined"?e.Message:_spTr.thisContentNotProcessable,"")}},error:function(d){b.action="shortpixel_check_status";jQuery.ajax({type:"GET",url:ShortPixel.AJAX_URL,data:b,success:function(e){var f=JSON.parse(e);if(f.Status!==ShortPixel.STATUS_SUCCESS){setCellMessage(c,typeof f.Message!=="undefined"?f.Message:_spTr.thisContentNotProcessable,"")}}})}})}function reoptimize(c,a){setCellMessage(c,"<img src='"+ShortPixel.WP_PLUGIN_URL+"/res/img/loading.gif' class='sp-loading-small'>Image waiting to be reprocessed","");jQuery("li.shortpixel-toolbar-processing").removeClass("shortpixel-hide");jQuery("li.shortpixel-toolbar-processing").addClass("shortpixel-processing");var b={action:"shortpixel_redo",attachment_ID:c,type:a};jQuery.get(ShortPixel.AJAX_URL,b,function(d){b=JSON.parse(d);if(b.Status==ShortPixel.STATUS_SUCCESS){setTimeout(checkBulkProgress,2000)}else{$msg=typeof b.Message!=="undefined"?b.Message:_spTr.thisContentNotProcessable;setCellMessage(c,$msg,"");showToolBarAlert(ShortPixel.STATUS_FAIL,$msg)}})}function optimizeThumbs(b){setCellMessage(b,"<img src='"+ShortPixel.WP_PLUGIN_URL+"/res/img/loading.gif' class='sp-loading-small'>"+_spTr.imageWaitOptThumbs,"");jQuery("li.shortpixel-toolbar-processing").removeClass("shortpixel-hide");jQuery("li.shortpixel-toolbar-processing").addClass("shortpixel-processing");var a={action:"shortpixel_optimize_thumbs",attachment_ID:b};jQuery.get(ShortPixel.AJAX_URL,a,function(c){a=JSON.parse(c);if(a.Status==ShortPixel.STATUS_SUCCESS){setTimeout(checkBulkProgress,2000)}else{setCellMessage(b,typeof a.Message!=="undefined"?a.Message:_spTr.thisContentNotProcessable,"")}})}function dismissShortPixelNoticeExceed(b){jQuery("#wp-admin-bar-shortpixel_processing").hide();var a={action:"shortpixel_dismiss_notice",notice_id:"exceed"};jQuery.get(ShortPixel.AJAX_URL,a,function(c){a=JSON.parse(c);if(a.Status==ShortPixel.STATUS_SUCCESS){console.log("dismissed")}});b.preventDefault()}function dismissShortPixelNotice(b){jQuery("#short-pixel-notice-"+b).hide();var a={action:"shortpixel_dismiss_notice",notice_id:b};jQuery.get(ShortPixel.AJAX_URL,a,function(c){a=JSON.parse(c);if(a.Status==ShortPixel.STATUS_SUCCESS){console.log("dismissed")}})}function PercentageAnimator(b,a){this.animationSpeed=10;this.increment=2;this.curPercentage=0;this.targetPercentage=a;this.outputSelector=b;this.animate=function(c){this.targetPercentage=c;setTimeout(PercentageTimer.bind(null,this),this.animationSpeed)}}function PercentageTimer(a){if(a.curPercentage-a.targetPercentage<-a.increment){a.curPercentage+=a.increment}else{if(a.curPercentage-a.targetPercentage>a.increment){a.curPercentage-=a.increment}else{a.curPercentage=a.targetPercentage}}jQuery(a.outputSelector).text(a.curPercentage+"%");if(a.curPercentage!=a.targetPercentage){setTimeout(PercentageTimer.bind(null,a),a.animationSpeed)}}function progressUpdate(c,b){var a=jQuery("#bulk-progress");if(a.length){jQuery(".progress-left",a).css("width",c+"%");jQuery(".progress-img",a).css("left",c+"%");if(c>24){jQuery(".progress-img span",a).html("");jQuery(".progress-left",a).html(c+"%")}else{jQuery(".progress-img span",a).html(c+"%");jQuery(".progress-left",a).html("")}jQuery(".bulk-estimate").html(b)}}function sliderUpdate(g,c,d,e,b){var f=jQuery(".bulk-slider div.bulk-slide:first-child");if(f.length===0){return}if(f.attr("id")!="empty-slide"){f.hide()}f.css("z-index",1000);jQuery(".bulk-img-opt",f).attr("src","");if(typeof d==="undefined"){d=""}if(d.length>0){jQuery(".bulk-img-orig",f).attr("src","")}var a=f.clone();a.attr("id","slide-"+g);jQuery(".bulk-img-opt",a).attr("src",c);if(d.length>0){jQuery(".img-original",a).css("display","inline-block");jQuery(".bulk-img-orig",a).attr("src",d)}else{jQuery(".img-original",a).css("display","none")}jQuery(".bulk-opt-percent",a).html('<input type="text" class="dial" value="'+e+'"/>');jQuery(".bulk-slider").append(a);ShortPixel.percentDial("#"+a.attr("id")+" .dial",100);jQuery(".bulk-slider-container span.filename").html("&nbsp;&nbsp;"+b);if(f.attr("id")=="empty-slide"){f.remove();jQuery(".bulk-slider-container").css("display","block")}else{f.animate({left:f.width()+f.position().left},"slow","swing",function(){f.remove();a.fadeIn("slow")})}}function hideSlider(){jQuery(".bulk-slider-container").css("display","none")}function showStats(){var a=jQuery(".bulk-stats");if(a.length>0){}}if(!(typeof String.prototype.format=="function")){String.prototype.format=function(){var b=this,a=arguments.length;while(a--){b=b.replace(new RegExp("\\{"+a+"\\}","gm"),arguments[a])}return b}};
shortpixel_api.php CHANGED
@@ -82,7 +82,17 @@ class ShortPixelAPI {
82
  public function doRequests($URLs, $Blocking, $itemHandler, $compressionType = false, $refresh = false) {
83
 
84
  if(!count($URLs)) {
85
- throw new Exception(__('Image files are missing.','shortpixel-image-optimiser'));
 
 
 
 
 
 
 
 
 
 
86
  }
87
 
88
  //WpShortPixel::log("DO REQUESTS for META: " . json_encode($itemHandler->getRawMeta()) . " STACK: " . json_encode(debug_backtrace()));
@@ -97,14 +107,19 @@ class ShortPixelAPI {
97
  'resize' => $this->_settings->resizeImages ? 1 + 2 * ($this->_settings->resizeType == 'inner' ? 1 : 0) : 0,
98
  'resize_width' => $this->_settings->resizeWidth,
99
  'resize_height' => $this->_settings->resizeHeight,
 
100
  'urllist' => $URLs
101
  );
102
  if($refresh) {
103
  $requestParameters['refresh'] = 1;
104
  }
105
 
 
 
106
  $response = wp_remote_post($this->_apiEndPoint, $this->prepareRequest($requestParameters, $Blocking) );
107
-
 
 
108
  //only if $Blocking is true analyze the response
109
  if ( $Blocking )
110
  {
@@ -252,7 +267,7 @@ class ShortPixelAPI {
252
  //return array("Status" => self::STATUS_FAIL, "Message" => "There was an error and your request was not processed (" . $APIresponse[0]->Status->Message . "). REQ: " . json_encode($URLs));
253
  $err = array("Status" => self::STATUS_FAIL, "Code" => (isset($APIresponse[0]->Status->Code) ? $APIresponse[0]->Status->Code : self::ERR_UNKNOWN),
254
  "Message" => __('There was an error and your request was not processed.','shortpixel-image-optimiser')
255
- . " (" . $APIresponse[0]->Status->Message . ")");
256
  } else {
257
  $err = array("Status" => self::STATUS_FAIL, "Message" => __('There was an error and your request was not processed.','shortpixel-image-optimiser'),
258
  "Code" => (isset($APIresponse[0]->Status->Code) ? $APIresponse[0]->Status->Code : self::ERR_UNKNOWN));
@@ -318,7 +333,13 @@ class ShortPixelAPI {
318
 
319
 
320
  }
321
-
 
 
 
 
 
 
322
  /**
323
  * handles the download of an optimized image from ShortPixel API
324
  * @param type $fileData - info about the file
@@ -332,14 +353,12 @@ class ShortPixelAPI {
332
  $fileType = "LossyURL";
333
  $fileSize = "LossySize";
334
  $webpType = "WebPLossyURL";
335
- $webpSize = "WebPLossySize";
336
- }
337
  else
338
  {
339
  $fileType = "LosslessURL";
340
  $fileSize = "LoselessSize";
341
  $webpType = "WebPLosslessURL";
342
- $webpSize = "WebPLosslessSize";
343
  }
344
 
345
  $downloadTimeout = max(ini_get('max_execution_time') - 10, 15);
@@ -653,8 +672,7 @@ class ShortPixelAPI {
653
  static public function CheckAndFixImagePaths($PATHs){
654
 
655
  $ErrorCount = 0;
656
- $uploadDir = wp_upload_dir();
657
- $Tmp = explode("/", $uploadDir['basedir']);
658
  $TmpCount = count($Tmp);
659
  $StichString = $Tmp[$TmpCount-2] . "/" . $Tmp[$TmpCount-1];
660
  //files exist on disk?
@@ -664,11 +682,11 @@ class ShortPixelAPI {
664
  //we try again with a different path
665
  if ( !file_exists($File) ){
666
  //$NewFile = $uploadDir['basedir'] . "/" . substr($File,strpos($File, $StichString));//+strlen($StichString));
667
- $NewFile = $uploadDir['basedir'] . substr($File,strpos($File, $StichString)+strlen($StichString));
668
  if (file_exists($NewFile)) {
669
  $PATHs[$Id] = $NewFile;
670
  } else {
671
- $NewFile = $uploadDir['basedir'] . "/" . $File;
672
  if (file_exists($NewFile)) {
673
  $PATHs[$Id] = $NewFile;
674
  } else {
82
  public function doRequests($URLs, $Blocking, $itemHandler, $compressionType = false, $refresh = false) {
83
 
84
  if(!count($URLs)) {
85
+ $meta = $itemHandler->getMeta();
86
+ $files = " (";
87
+ if(count($meta->getThumbsMissing())) {
88
+ foreach ($meta->getThumbsMissing() as $miss) {
89
+ $files .= $miss . ", ";
90
+ }
91
+ if(strrpos($files, ', ')) {
92
+ $files = substr_replace($files , ')', strrpos($files , ', '));
93
+ }
94
+ }
95
+ throw new Exception(__('Image files are missing.' . (strlen($files) > 1 ? $files : '') ,'shortpixel-image-optimiser'));
96
  }
97
 
98
  //WpShortPixel::log("DO REQUESTS for META: " . json_encode($itemHandler->getRawMeta()) . " STACK: " . json_encode(debug_backtrace()));
107
  'resize' => $this->_settings->resizeImages ? 1 + 2 * ($this->_settings->resizeType == 'inner' ? 1 : 0) : 0,
108
  'resize_width' => $this->_settings->resizeWidth,
109
  'resize_height' => $this->_settings->resizeHeight,
110
+ 'group_id' => $itemHandler->getId(),
111
  'urllist' => $URLs
112
  );
113
  if($refresh) {
114
  $requestParameters['refresh'] = 1;
115
  }
116
 
117
+ //WpShortPixel::log("DO REQUESTS SENDING: " . json_encode($requestParameters));
118
+
119
  $response = wp_remote_post($this->_apiEndPoint, $this->prepareRequest($requestParameters, $Blocking) );
120
+
121
+ //WpShortPixel::log('RESPONSE: ' . json_encode($response));
122
+
123
  //only if $Blocking is true analyze the response
124
  if ( $Blocking )
125
  {
267
  //return array("Status" => self::STATUS_FAIL, "Message" => "There was an error and your request was not processed (" . $APIresponse[0]->Status->Message . "). REQ: " . json_encode($URLs));
268
  $err = array("Status" => self::STATUS_FAIL, "Code" => (isset($APIresponse[0]->Status->Code) ? $APIresponse[0]->Status->Code : self::ERR_UNKNOWN),
269
  "Message" => __('There was an error and your request was not processed.','shortpixel-image-optimiser')
270
+ . " (" . wp_basename($APIresponse[0]->OriginalURL) . ": " . $APIresponse[0]->Status->Message . ")");
271
  } else {
272
  $err = array("Status" => self::STATUS_FAIL, "Message" => __('There was an error and your request was not processed.','shortpixel-image-optimiser'),
273
  "Code" => (isset($APIresponse[0]->Status->Code) ? $APIresponse[0]->Status->Code : self::ERR_UNKNOWN));
333
 
334
 
335
  }
336
+
337
+ function downloadAll($target) {
338
+ //TODO DOCS
339
+ //http://php.net/manual/en/phardata.buildfromiterator.php
340
+ //http://php.net/manual/en/phardata.extractto.php
341
+ }
342
+
343
  /**
344
  * handles the download of an optimized image from ShortPixel API
345
  * @param type $fileData - info about the file
353
  $fileType = "LossyURL";
354
  $fileSize = "LossySize";
355
  $webpType = "WebPLossyURL";
356
+ }
 
357
  else
358
  {
359
  $fileType = "LosslessURL";
360
  $fileSize = "LoselessSize";
361
  $webpType = "WebPLosslessURL";
 
362
  }
363
 
364
  $downloadTimeout = max(ini_get('max_execution_time') - 10, 15);
672
  static public function CheckAndFixImagePaths($PATHs){
673
 
674
  $ErrorCount = 0;
675
+ $Tmp = explode("/", SHORTPIXEL_UPLOADS_BASE);
 
676
  $TmpCount = count($Tmp);
677
  $StichString = $Tmp[$TmpCount-2] . "/" . $Tmp[$TmpCount-1];
678
  //files exist on disk?
682
  //we try again with a different path
683
  if ( !file_exists($File) ){
684
  //$NewFile = $uploadDir['basedir'] . "/" . substr($File,strpos($File, $StichString));//+strlen($StichString));
685
+ $NewFile = SHORTPIXEL_UPLOADS_BASE . substr($File,strpos($File, $StichString)+strlen($StichString));
686
  if (file_exists($NewFile)) {
687
  $PATHs[$Id] = $NewFile;
688
  } else {
689
+ $NewFile = SHORTPIXEL_UPLOADS_BASE . "/" . $File;
690
  if (file_exists($NewFile)) {
691
  $PATHs[$Id] = $NewFile;
692
  } else {
wp-shortpixel.php CHANGED
@@ -3,7 +3,7 @@
3
  * Plugin Name: ShortPixel Image Optimizer
4
  * Plugin URI: https://shortpixel.com/
5
  * Description: ShortPixel optimizes images automatically, while guarding the quality of your images. Check your <a href="options-general.php?page=wp-shortpixel" target="_blank">Settings &gt; ShortPixel</a> page on how to start optimizing your image library and make your website load faster.
6
- * Version: 4.11.0
7
  * Author: ShortPixel
8
  * Author URI: https://shortpixel.com
9
  * Text Domain: shortpixel-image-optimiser
@@ -18,7 +18,7 @@ define('SHORTPIXEL_PLUGIN_FILE', __FILE__);
18
 
19
  //define('SHORTPIXEL_AFFILIATE_CODE', '');
20
 
21
- define('SHORTPIXEL_IMAGE_OPTIMISER_VERSION', "4.11.0");
22
  define('SHORTPIXEL_MAX_TIMEOUT', 10);
23
  define('SHORTPIXEL_VALIDATE_MAX_TIMEOUT', 15);
24
  define('SHORTPIXEL_BACKUP', 'ShortpixelBackups');
@@ -37,7 +37,7 @@ define('SHORTPIXEL_MAX_EXECUTION_TIME', ini_get('max_execution_time'));
37
  require_once(ABSPATH . 'wp-admin/includes/file.php');
38
 
39
  $sp__uploads = wp_upload_dir();
40
- define('SHORTPIXEL_UPLOADS_BASE', $sp__uploads['basedir']);
41
  define('SHORTPIXEL_UPLOADS_URL', is_main_site() ? $sp__uploads['baseurl'] : dirname(dirname($sp__uploads['baseurl'])));
42
  define('SHORTPIXEL_UPLOADS_NAME', basename(is_main_site() ? SHORTPIXEL_UPLOADS_BASE : dirname(dirname(SHORTPIXEL_UPLOADS_BASE))));
43
  $sp__backupBase = is_main_site() ? SHORTPIXEL_UPLOADS_BASE : dirname(dirname(SHORTPIXEL_UPLOADS_BASE));
@@ -187,11 +187,13 @@ if ( !function_exists( 'vc_action' ) || vc_action() !== 'vc_inline' ) { //handle
187
  $autoPng2Jpg = get_option('wp-short-pixel-png2jpg');
188
  if($autoPng2Jpg) {
189
  add_action( 'wp_handle_upload', 'shortPixelPng2JpgHook');
 
190
  }
191
  add_action('wp_handle_replace', 'shortPixelReplaceHook');
192
  $autoMediaLibrary = get_option('wp-short-pixel-auto-media-library');
193
  if($autoMediaLibrary) {
194
  add_filter( 'wp_generate_attachment_metadata', 'shortPixelHandleImageUploadHook', 10, 2 );
 
195
  }
196
 
197
  register_activation_hook( __FILE__, 'shortPixelActivatePlugin' );
3
  * Plugin Name: ShortPixel Image Optimizer
4
  * Plugin URI: https://shortpixel.com/
5
  * Description: ShortPixel optimizes images automatically, while guarding the quality of your images. Check your <a href="options-general.php?page=wp-shortpixel" target="_blank">Settings &gt; ShortPixel</a> page on how to start optimizing your image library and make your website load faster.
6
+ * Version: 4.11.1
7
  * Author: ShortPixel
8
  * Author URI: https://shortpixel.com
9
  * Text Domain: shortpixel-image-optimiser
18
 
19
  //define('SHORTPIXEL_AFFILIATE_CODE', '');
20
 
21
+ define('SHORTPIXEL_IMAGE_OPTIMISER_VERSION', "4.11.1");
22
  define('SHORTPIXEL_MAX_TIMEOUT', 10);
23
  define('SHORTPIXEL_VALIDATE_MAX_TIMEOUT', 15);
24
  define('SHORTPIXEL_BACKUP', 'ShortpixelBackups');
37
  require_once(ABSPATH . 'wp-admin/includes/file.php');
38
 
39
  $sp__uploads = wp_upload_dir();
40
+ define('SHORTPIXEL_UPLOADS_BASE', (file_exists($sp__uploads['basedir']) ? '' : ABSPATH) . $sp__uploads['basedir'] );
41
  define('SHORTPIXEL_UPLOADS_URL', is_main_site() ? $sp__uploads['baseurl'] : dirname(dirname($sp__uploads['baseurl'])));
42
  define('SHORTPIXEL_UPLOADS_NAME', basename(is_main_site() ? SHORTPIXEL_UPLOADS_BASE : dirname(dirname(SHORTPIXEL_UPLOADS_BASE))));
43
  $sp__backupBase = is_main_site() ? SHORTPIXEL_UPLOADS_BASE : dirname(dirname(SHORTPIXEL_UPLOADS_BASE));
187
  $autoPng2Jpg = get_option('wp-short-pixel-png2jpg');
188
  if($autoPng2Jpg) {
189
  add_action( 'wp_handle_upload', 'shortPixelPng2JpgHook');
190
+ add_action( 'mpp_handle_upload', 'shortPixelPng2JpgHook');
191
  }
192
  add_action('wp_handle_replace', 'shortPixelReplaceHook');
193
  $autoMediaLibrary = get_option('wp-short-pixel-auto-media-library');
194
  if($autoMediaLibrary) {
195
  add_filter( 'wp_generate_attachment_metadata', 'shortPixelHandleImageUploadHook', 10, 2 );
196
+ add_filter( 'mpp_generate_metadata', 'shortPixelHandleImageUploadHook', 10, 2 );
197
  }
198
 
199
  register_activation_hook( __FILE__, 'shortPixelActivatePlugin' );