コード例 #1
0
 public function handleSuccess($APIresponse, $URLs, $PATHs, $ID)
 {
     $counter = $savedSpace = $originalSpace = $optimizedSpace = $averageCompression = 0;
     //download each file from array and process it
     foreach ($APIresponse as $fileData) {
         if ($fileData->Status->Code == 2) {
             if ($counter == 0) {
                 //save percent improvement for main file
                 $percentImprovement = $fileData->PercentImprovement;
             } else {
                 //count thumbnails only
                 update_option('wp-short-pixel-thumbnail-count', get_option('wp-short-pixel-thumbnail-count') + 1);
             }
             $downloadResult = $this->handleDownload($fileData, $counter);
             //when the status is STATUS_UNCHANGED we just skip the array line for that one
             if ($downloadResult['Status'] == self::STATUS_SUCCESS) {
                 $tempFiles[$counter] = $downloadResult['Message'];
             } elseif ($downloadResult['Status'] != self::STATUS_UNCHANGED) {
                 return array("Status" => $downloadResult['Status'], "Message" => $downloadResult['Message']);
             }
         } else {
             //there was an error while trying to download a file
             $tempFiles[$counter] = "";
         }
         $counter++;
     }
     //figure out in what SubDir files should land
     $SubDir = $this->returnSubDir(get_attached_file($ID));
     //if backup is enabled - we try to save the images
     if (get_option('wp-short-backup_images')) {
         $uploadDir = wp_upload_dir();
         $source = $PATHs;
         //array with final paths for this files
         if (!file_exists(SP_BACKUP_FOLDER) && !@mkdir(SP_BACKUP_FOLDER, 0777, true)) {
             //creates backup folder if it doesn't exist
             return array("Status" => self::STATUS_FAIL, "Message" => "Backup folder does not exist and it cannot be created");
         }
         //create subdir in backup folder if needed
         @mkdir(SP_BACKUP_FOLDER . DIRECTORY_SEPARATOR . $SubDir, 0777, true);
         foreach ($source as $fileID => $filePATH) {
             $destination[$fileID] = SP_BACKUP_FOLDER . DIRECTORY_SEPARATOR . $SubDir . self::MB_basename($source[$fileID]);
         }
         //now that we have original files and where we should back them up we attempt to do just that
         if (is_writable(SP_BACKUP_FOLDER)) {
             foreach ($destination as $fileID => $filePATH) {
                 if (!file_exists($filePATH)) {
                     if (!@copy($source[$fileID], $destination[$fileID])) {
                         //file couldn't have been saved in backup folder
                         ShortPixelAPI::SaveMessageinMetadata($ID, 'Cannot save file <i>' . self::MB_basename($source[$fileID]) . '</i> in backup directory');
                         return array("Status" => self::STATUS_FAIL, "Message" => 'Cannot save file <i>' . self::MB_basename($source[$fileID]) . '</i> in backup directory');
                     }
                 }
             }
         } else {
             //cannot write to the backup dir, return with an error
             ShortPixelAPI::SaveMessageinMetadata($ID, 'Cannot save file in backup directory');
             return array("Status" => self::STATUS_FAIL, "Message" => 'Cannot save file in backup directory');
         }
     }
     //end backup section
     $writeFailed = 0;
     if (!empty($tempFiles)) {
         //overwrite the original files with the optimized ones
         foreach ($tempFiles as $tempFileID => $tempFilePATH) {
             if (file_exists($tempFilePATH) && file_exists($PATHs[$tempFileID]) && is_writable($PATHs[$tempFileID])) {
                 copy($tempFilePATH, $PATHs[$tempFileID]);
             } else {
                 $writeFailed++;
             }
             @unlink($tempFilePATH);
             if ($writeFailed > 0) {
                 ShortPixelAPI::SaveMessageinMetadata($ID, 'Error: optimized version of ' . $writeFailed . ' file(s) couldn\'t be updated.');
                 update_option('bulkProcessingStatus', "error");
                 return array("Status" => self::STATUS_FAIL, "Code" => "write-fail", "Message" => 'Error: optimized version of ' . $writeFailed . ' file(s) couldn\'t be updated.');
             } else {
                 //all files were copied, optimization data regarding the savings locally in DB
                 $fileType = $this->_compressionType ? "LossySize" : "LoselessSize";
                 $savedSpace += $APIresponse[$tempFileID]->OriginalSize - $APIresponse[$tempFileID]->{$fileType};
                 $originalSpace += $APIresponse[$tempFileID]->OriginalSize;
                 $optimizedSpace += $APIresponse[$tempFileID]->{$fileType};
                 $averageCompression += $fileData->PercentImprovement;
                 //add the number of files with < 5% optimization
                 if ((1 - $APIresponse[$tempFileID]->{$fileType} / $APIresponse[$tempFileID]->OriginalSize) * 100 < 5) {
                     update_option('wp-short-pixel-files-under-5-percent', get_option('wp-short-pixel-files-under-5-percent') + 1);
                 }
             }
         }
     }
     //old average counting
     update_option('wp-short-pixel-savedSpace', get_option('wp-short-pixel-savedSpace') + $savedSpace);
     $averageCompression = get_option('wp-short-pixel-averageCompression') * get_option('wp-short-pixel-fileCount');
     $averageCompression = $averageCompression / (get_option('wp-short-pixel-fileCount') + count($APIresponse));
     update_option('wp-short-pixel-averageCompression', $averageCompression);
     update_option('wp-short-pixel-fileCount', get_option('wp-short-pixel-fileCount') + count($APIresponse));
     //new average counting
     update_option('wp-short-pixel-total-original', get_option('wp-short-pixel-total-original') + $originalSpace);
     update_option('wp-short-pixel-total-optimized', get_option('wp-short-pixel-total-optimized') + $optimizedSpace);
     //update metadata for this file
     $meta = wp_get_attachment_metadata($ID);
     $meta['ShortPixelImprovement'] = round($percentImprovement, 2);
     wp_update_attachment_metadata($ID, $meta);
     //we reset the retry counter in case of success
     update_option('wp-short-pixel-api-retries', 0);
     return array("Status" => self::STATUS_SUCCESS, "Message" => 'Success: No pixels remained unsqueezed :-)', "PercentImprovement" => $percentImprovement);
 }
コード例 #2
0
ファイル: wp-shortpixel.php プロジェクト: sumwander/unyil
 public function getURLsAndPATHs($ID, $meta = NULL)
 {
     if (!parse_url(WP_CONTENT_URL, PHP_URL_SCHEME)) {
         //no absolute URLs used -> we implement a hack
         $url = get_site_url() . wp_get_attachment_url($ID);
         //get the file URL
     } else {
         $url = wp_get_attachment_url($ID);
     }
     //get the file URL
     $urlList[] = $url;
     $path = get_attached_file($ID);
     //get the full file PATH
     $filePath[] = $path;
     if ($meta == NULL) {
         $meta = wp_get_attachment_metadata($ID);
     }
     //it is NOT a PDF file and thumbs are processable
     if (strtolower(substr($filePath[0], strrpos($filePath[0], ".") + 1)) != "pdf" && $this->_processThumbnails && isset($meta['sizes']) && is_array($meta['sizes'])) {
         foreach ($meta['sizes'] as $thumbnailInfo) {
             $urlList[] = str_replace(ShortPixelAPI::MB_basename($urlList[0]), $thumbnailInfo['file'], $url);
             $filePath[] = str_replace(ShortPixelAPI::MB_basename($filePath[0]), $thumbnailInfo['file'], $path);
         }
     }
     if (!isset($meta['sizes']) || !is_array($meta['sizes'])) {
         self::log("getURLsAndPATHs: no meta sizes for ID {$ID} : " . json_encode($meta));
     }
     return array("URLs" => $urlList, "PATHs" => $filePath);
 }
コード例 #3
0
 public function handleSuccess($APIresponse, $URLs, $PATHs, $ID, $compressionType)
 {
     $counter = $savedSpace = $originalSpace = $optimizedSpace = $averageCompression = 0;
     $NoBackup = true;
     //download each file from array and process it
     foreach ($APIresponse as $fileData) {
         if ($fileData->Status->Code == 2) {
             if ($counter == 0) {
                 //save percent improvement for main file
                 $percentImprovement = $fileData->PercentImprovement;
             } else {
                 //count thumbnails only
                 update_option('wp-short-pixel-thumbnail-count', get_option('wp-short-pixel-thumbnail-count') + 1);
             }
             $downloadResult = $this->handleDownload($fileData, $counter, $compressionType);
             //when the status is STATUS_UNCHANGED we just skip the array line for that one
             if ($downloadResult['Status'] == self::STATUS_SUCCESS) {
                 $tempFiles[$counter] = $downloadResult['Message'];
             } elseif ($downloadResult['Status'] != self::STATUS_UNCHANGED) {
                 return array("Status" => $downloadResult['Status'], "Message" => $downloadResult['Message']);
             }
         } else {
             //there was an error while trying to download a file
             $tempFiles[$counter] = "";
         }
         $counter++;
     }
     //figure out in what SubDir files should land
     $SubDir = $this->returnSubDir(get_attached_file($ID));
     //if backup is enabled - we try to save the images
     if ($this->_settings->backupImages) {
         $uploadDir = wp_upload_dir();
         $source = $PATHs;
         //array with final paths for these files
         if (!file_exists(SP_BACKUP_FOLDER) && !@mkdir(SP_BACKUP_FOLDER, 0777, true)) {
             //creates backup folder if it doesn't exist
             return array("Status" => self::STATUS_FAIL, "Message" => "Backup folder does not exist and it cannot be created");
         }
         //create subdir in backup folder if needed
         @mkdir(SP_BACKUP_FOLDER . DIRECTORY_SEPARATOR . $SubDir, 0777, true);
         foreach ($source as $fileID => $filePATH) {
             $destination[$fileID] = SP_BACKUP_FOLDER . DIRECTORY_SEPARATOR . $SubDir . self::MB_basename($source[$fileID]);
         }
         //now that we have original files and where we should back them up we attempt to do just that
         if (is_writable(SP_BACKUP_FOLDER)) {
             foreach ($destination as $fileID => $filePATH) {
                 if (!file_exists($filePATH)) {
                     if (!@copy($source[$fileID], $destination[$fileID])) {
                         //file couldn't be saved in backup folder
                         ShortPixelAPI::SaveMessageinMetadata($ID, 'Cannot save file <i>' . self::MB_basename($source[$fileID]) . '</i> in backup directory');
                         return array("Status" => self::STATUS_FAIL, "Message" => 'Cannot save file <i>' . self::MB_basename($source[$fileID]) . '</i> in backup directory');
                     }
                 }
             }
             $NoBackup = true;
         } else {
             //cannot write to the backup dir, return with an error
             ShortPixelAPI::SaveMessageinMetadata($ID, 'Cannot save file in backup directory');
             return array("Status" => self::STATUS_FAIL, "Message" => 'Cannot save file in backup directory');
         }
     }
     //end backup section
     $writeFailed = 0;
     if (!empty($tempFiles)) {
         //overwrite the original files with the optimized ones
         foreach ($tempFiles as $tempFileID => $tempFilePATH) {
             if (file_exists($tempFilePATH) && file_exists($PATHs[$tempFileID]) && is_writable($PATHs[$tempFileID])) {
                 copy($tempFilePATH, $PATHs[$tempFileID]);
             } else {
                 $writeFailed++;
             }
             @unlink($tempFilePATH);
         }
         if ($writeFailed > 0) {
             ShortPixelAPI::SaveMessageinMetadata($ID, 'Error: optimized version of ' . $writeFailed . ' file(s) couldn\'t be updated.');
             update_option('bulkProcessingStatus', "error");
             return array("Status" => self::STATUS_FAIL, "Code" => "write-fail", "Message" => 'Error: optimized version of ' . $writeFailed . ' file(s) couldn\'t be updated.');
         } else {
             //all files were copied, optimization data regarding the savings locally in DB
             $fileType = $this->_settings->compressionType ? "LossySize" : "LoselessSize";
             $savedSpace += $APIresponse[$tempFileID]->OriginalSize - $APIresponse[$tempFileID]->{$fileType};
             $originalSpace += $APIresponse[$tempFileID]->OriginalSize;
             $optimizedSpace += $APIresponse[$tempFileID]->{$fileType};
             $averageCompression += $fileData->PercentImprovement;
             //add the number of files with < 5% optimization
             if ((1 - $APIresponse[$tempFileID]->{$fileType} / $APIresponse[$tempFileID]->OriginalSize) * 100 < 5) {
                 $this->_settings->under5Percent++;
             }
         }
     } elseif (0 + $fileData->PercentImprovement < 5) {
         $this->_settings->under5Percent++;
     }
     //old average counting
     $this->_settings->savedSpace += $savedSpace;
     $averageCompression = $this->_settings->averageCompression * $this->_settings->fileCount;
     $averageCompression = $averageCompression / ($this->_settings->fileCount + count($APIresponse));
     $this->_settings->averageCompression = $averageCompression;
     $this->_settings->fileCount += count($APIresponse);
     //new average counting
     $this->_settings->totalOriginal += $originalSpace;
     $this->_settings->totalOptimized += $optimizedSpace;
     //update metadata for this file
     $duplicates = self::getWPMLDuplicates($ID);
     foreach ($duplicates as $_ID) {
         $meta = wp_get_attachment_metadata($_ID);
         $meta['ShortPixel']['type'] = self::getCompressionTypeName($compressionType);
         $meta['ShortPixel']['exifKept'] = $this->_settings->keepExif;
         $meta['ShortPixel']['date'] = date("Y-m-d");
         //thumbs were processed if settings or if they were explicitely requested
         $meta['ShortPixel']['thumbsOpt'] = (isset($meta['ShortPixel']['thumbsTodo']) || $this->_settings->processThumbnails) && isset($meta['sizes']) ? count($meta['sizes']) : 0;
         //if thumbsTodo - this means there was an explicit request to process thumbs for an image that was previously processed without
         // don't update the ShortPixelImprovement ratio as this is only calculated based on main image
         if (isset($meta['ShortPixel']['thumbsTodo'])) {
             unset($meta['ShortPixel']['thumbsTodo']);
             $percentImprovement = $meta['ShortPixelImprovement'];
         } else {
             $meta['ShortPixelImprovement'] = "" . round($percentImprovement, 2);
         }
         if ($NoBackup) {
             $meta['ShortPixel']['NoBackup'] = true;
         }
         wp_update_attachment_metadata($_ID, $meta);
     }
     //we reset the retry counter in case of success
     update_option('wp-short-pixel-api-retries', 0);
     return array("Status" => self::STATUS_SUCCESS, "Message" => 'Success: No pixels remained unsqueezed :-)', "PercentImprovement" => $percentImprovement);
 }