-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathImageCompression.php
More file actions
executable file
·461 lines (411 loc) · 13.2 KB
/
ImageCompression.php
File metadata and controls
executable file
·461 lines (411 loc) · 13.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
<?php
require_once("vendor/autoload.php");
/**
* Class ImageCompression
*
* @copyright Copyright (c) 2016 (eyakushdev@gmail.com)
* @author Eugene Yakush (eyakushdev@gmail.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
class ImageCompression
{
/**
* @var array
*/
protected $_apiKeys = [];
/**
* @var int
*/
protected $_activeKeyIndex = 0;
/**
* @var array
*/
protected $_sourcePath = [];
/**
* @var array
*/
protected $_availableExt = ["*.png", "*.jpg"];
/**
* @var string
*/
protected $_resultPath;
/**
* @var string
*/
protected $_logPath = "../log";
/**
* @var string
*/
protected $_archivePath = "../archive";
/**
* @var array
*/
protected $_originFiles = [];
/**
* @var array
*/
protected $_compressedFiles = [];
/**
* @var array
*/
protected $_logRows = [];
/**
* @var resource
*/
protected $_logFile;
/**
* @var string
*/
protected $_uid;
/**
* @var int
*/
protected $_processedFilesCount = 0;
/**
* ImageCompression constructor.
*/
public function __construct()
{
if (strtoupper($_SERVER['REQUEST_METHOD']) !== 'POST') {
return null;
}
if (isset($_SESSION['compressorObj']) && isset($_POST["type"])) {
foreach ($_SESSION['compressorObj'] as $field => $data) {
$this->$field = $data;
}
try {
switch ($_POST["type"]) {
case "progress":
$this->_runCompression();
break;
case "log":
$this->_downloadLogFile();
break;
case "archive":
$this->_downloadArchiveFile();
break;
case "break":
$this->_removeUnnecessaryFile();
break;
}
} catch (Exception $e) {
$this->_response([
"error" => $e->getMessage()
]);
}
} else {
$this->_apiKeys = (array)$_POST["apiKey"];
$this->_sourcePath = (array)$_POST["sourcePath"];
$this->_uid = md5(time() . rand());
$this->_prepareFilesList();
$_SESSION['compressorObj'] = $this;
$this->_response([
"files" => count($this->_originFiles),
"progress" => $this->_getCurrentProgress()
]);
}
}
/**
* Read array of folders and collects files from theirs
*/
protected function _prepareFilesList()
{
$files = [];
foreach ($this->_availableExt as $ext) {
foreach ($this->_sourcePath as $path) {
$files += $this->_globRecursive(rtrim($path, "/") . DIRECTORY_SEPARATOR . $ext);
}
}
foreach ($files as $filePath) {
$data = pathinfo($filePath);
$this->_originFiles[] = [
"filePath" => $filePath,
"path" => $data["dirname"],
"fileName" => $data["basename"],
"size" => filesize($filePath)
];
}
}
/**
* Reads files in folders recursively
*
* @param $pattern
* @param int $flags
* @return array
*/
protected function _globRecursive($pattern, $flags = 0)
{
$filesList = glob($pattern, $flags);
foreach (glob(dirname($pattern) . '/*', GLOB_ONLYDIR | GLOB_NOSORT) as $dir) {
$filesList = array_merge($filesList, $this->_globRecursive($dir . '/' . basename($pattern), $flags));
}
return $filesList;
}
/**
* Returns bytes in human format
* @param $size
* @param int $precision
* @return string
*/
protected function _formatBytes($size, $precision = 2)
{
$base = log($size, 1024);
$suffixes = ['', 'k', 'M', 'G', 'T'];
return round(pow(1024, $base - floor($base)), $precision) . $suffixes[floor($base)];
}
/**
* Checks folder on exists and create one if folder does not exists
*
* @param $path
*/
protected function _checkFolder($path)
{
if (!file_exists($path)) {
mkdir($path, 0777, true);
}
}
protected function _runCompression()
{
$fileInfo = $this->_originFiles[$this->_processedFilesCount];
$resultPath = $this->_getPathToResults() . $fileInfo['path'];
$this->_checkFolder($resultPath);
$resultFilePath = $resultPath . DIRECTORY_SEPARATOR . $fileInfo["fileName"];
$this->_compress($this->_apiKeys[$this->_activeKeyIndex], $fileInfo, $resultFilePath);
$compressedFile = [
"filePath" => $resultFilePath,
"path" => $resultPath,
"fileName" => $fileInfo["fileName"],
"size" => filesize($resultFilePath)
];
$this->_compressedFiles[] = $compressedFile;
$this->_processedFilesCount++;
$this->_log("{$fileInfo['filePath']};{$fileInfo['size']};" .
$this->_formatBytes($fileInfo['size']) .
";" . @filesize($resultFilePath) . ";" . $this->_formatBytes(@filesize($resultFilePath)));
$compression = number_format((1 - (@filesize($resultFilePath) / $fileInfo['size'])) * 100, 2);
$this->_response([
"files" => count($this->_originFiles),
"progress" => $this->_getCurrentProgress(),
"processedFiles" => $this->_getPrecessedFilesCount(),
"details" => [
"filePath" => $fileInfo['filePath'],
"sizeBefore" => $this->_formatBytes($fileInfo['size']),
"sizeAfter" => $this->_formatBytes(@filesize($resultFilePath)),
"compression" => $compression
]
]);
}
/**
* @param array $data
*/
protected function _response($data = [])
{
$_SESSION['compressorObj'] = $this;
header('Content-Type: application/json');
echo json_encode($data);
exit;
}
/**
* @return int
*/
protected function _getCurrentProgress()
{
$result = ceil(($this->_getPrecessedFilesCount() / count($this->_originFiles)) * 100);
if ($result === 100 && $this->_getPrecessedFilesCount() < count($this->_originFiles)) {
$result = 99;
}
return $result;
}
/**
* @return int
*/
protected function _getPrecessedFilesCount()
{
return (int)$this->_processedFilesCount;
}
/**
* @param $apiKey
* @param $fileInfo
* @param $resultFilePath
* @return bool
* @throws Exception
*/
protected function _compress($apiKey, $fileInfo, $resultFilePath)
{
try {
\Tinify\setKey($apiKey);
$source = \Tinify\fromFile($fileInfo["filePath"]);
$source->toFile($resultFilePath);
return true;
} catch (Exception $e) {
$this->_activeKeyIndex++;
$_SESSION['compressorObj'] = $this;
if ($this->_activeKeyIndex >= count($this->_apiKeys)) {
throw new Exception("You have already used free limit on image compression for this API");
}
$this->_compress($this->_apiKeys[$this->_activeKeyIndex], $fileInfo, $resultFilePath);
exit;
}
}
/**
* @param $string
*/
protected function _log($string)
{
$this->_logRows[] = $string;
if (is_null($this->_logFile)) {
$this->_checkFolder($this->_logPath);
$this->_logFile = $this->_logPath . DIRECTORY_SEPARATOR . "compression_" . $this->_uid . ".csv";
if ($f = fopen($this->_logFile, 'a+')) {
$header = "File;Origin bytes;Origin size;Compressed bytes;Compressed size;" . PHP_EOL;
fwrite($f, $header);
}
}
if (count($this->_logRows) > 100) {
if ($f = fopen($this->_logFile, 'a+')) {
fwrite($f, join(PHP_EOL, $this->_logRows));
$this->_logRows = [];
}
}
if ($this->_getPrecessedFilesCount() === count($this->_originFiles)) {
if ($f = fopen($this->_logFile, 'a+')) {
fwrite($f, join(PHP_EOL, $this->_logRows));
$this->_logRows = [];
fclose($f);
}
}
}
/**
* @source http://stackoverflow.com/questions/1334613/how-to-recursively-zip-a-directory-in-php?answertab=active#tab-top
* @param $source
* @param $destination
* @return bool
*/
protected function _zip($source, $destination)
{
if (!extension_loaded('zip') || !file_exists($source)) {
return false;
}
$zip = new ZipArchive();
if (!$zip->open($destination, ZIPARCHIVE::CREATE)) {
return false;
}
$source = str_replace('\\', '/', realpath($source));
if (is_dir($source) === true) {
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($source),
RecursiveIteratorIterator::SELF_FIRST
);
foreach ($files as $file) {
$file = str_replace('\\', '/', $file);
// Ignore "." and ".." folders
if (in_array(substr($file, 1 + strrpos($file, '/')), ['.', '..']))
continue;
$file = realpath($file);
if (is_dir($file) === true) {
$zip->addEmptyDir(str_replace($source . '/', '', $file . '/'));
} else if (is_file($file) === true) {
$zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file));
}
}
} else if (is_file($source) === true) {
$zip->addFromString(basename($source), file_get_contents($source));
}
return $zip->close();
}
/**
* @param string $file
*/
protected function _prepareHeadersForDownloading($file)
{
if (ob_get_level()) {
ob_end_clean();
}
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
}
/**
*
*/
protected function _downloadLogFile()
{
if (file_exists($this->_logFile)) {
$this->_prepareHeadersForDownloading($this->_logFile);
// читаем файл и отправляем его пользователю
if ($fd = fopen($this->_logFile, 'r')) {
while (!feof($fd)) {
print fread($fd, 1024);
}
fclose($fd);
}
exit;
}
}
/**
*
*/
protected function _downloadArchiveFile()
{
$archiveFile = $this->_archivePath . DIRECTORY_SEPARATOR . basename($this->_logFile) . ".zip";
$this->_zip(trim($this->_getPathToResults(), DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR, $archiveFile);
if (file_exists($archiveFile)) {
$this->_prepareHeadersForDownloading($archiveFile);
// читаем файл и отправляем его пользователю
readfile($archiveFile);
exit;
}
}
/**
* @return string
*/
protected function _getPathToResults()
{
if (is_null($this->_resultPath)) {
$this->_resultPath = "../result" . DIRECTORY_SEPARATOR . $this->_uid;
$_SESSION['compressorObj'] = $this;
}
return $this->_resultPath;
}
/**
* @param $path
* @return bool
*
*/
protected function _remove($path)
{
if (is_dir($path) === true) {
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($path),
RecursiveIteratorIterator::CHILD_FIRST
);
foreach ($files as $file) {
if (in_array($file->getBasename(), ['.', '..']) !== true) {
if ($file->isDir() === true) {
rmdir($file->getPathName());
} else if (($file->isFile() === true) || ($file->isLink() === true)) {
unlink($file->getPathname());
}
}
}
return rmdir($path);
} else if ((is_file($path) === true) || (is_link($path) === true)) {
return unlink($path);
}
return false;
}
/**
* Removes files for current user. Used after click on break button
*/
protected function _removeUnnecessaryFile()
{
$this->_remove($this->_getPathToResults());
$this->_remove($this->_logFile);
unset($_SESSION["compressorObj"]);
}
}