-
Notifications
You must be signed in to change notification settings - Fork 1
/
AutoSmushPDF.module
749 lines (624 loc) · 24.4 KB
/
AutoSmushPDF.module
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
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
<?php
/**
* AutoSmushPDF
* Compress PDF files
*
* @version 1.0.2
* @author Matjaz Potocnik (matjazp)
* @link https://github.com/matjazpotocnik/AutoSmushPDF
*
* ProcessWire 2.x/3.x, Copyright 2011 by Ryan Cramer
* Licensed under GNU/GPL v2, see LICENSE
* https://processwire.com
*
*/
class AutoSmushPDF extends FieldtypeFile implements Module, ConfigurableModule {
/**
* Module info
*
* @return array
*
*/
public static function getModuleInfo() {
return array(
'title' => 'Auto Smush PDF',
'class' => 'AutoSmushPDF',
'author' => 'Matjaž Potočnik',
'version' => '1.0.2',
'summary' => 'Compress PDF files',
'href' => '',
'icon' => 'leaf',
'singular' => true,
'autoload' => true
);
}
/**
* Module configuraton values
*
*/
const API_WEBSERVICE = 'https://api.labstack.com/compress';
const API_SIZELIMIT = 10000000; // aka no limit
const API_ALLOWED_EXTENSIONS = 'pdf';
//const API_QUALITY_DEFAULT = '90'; // not used
const CONNECTION_TIMEOUT = 30; // for large files and slow connection 30 sec might not be enough
//const THRESHOLD = 5; // 5%, not used
/**
* Array of messages reported by this module
* @var array
*/
static $messages = array();
/**
* Array of settings for compressor - not used
* @var array
*/
protected $compressSettings = array();
/**
* Array of allowed extensions for files
* @var array
*/
protected $allowedExtensions = array();
/**
* Array of error codes returned by web service
* @var array
*/
protected $apiErrorCodes = array();
/**
* This module config data
* @var array
*/
protected $configData = array();
/**
* PW FileLog object
* @var array
*/
protected $log;
/**
* Construct and set default configuration
*
*/
public function __construct() {
self::$messages = array(
'start' => __('Starting...'),
'complete' => __('All done'),
'error' => __('An error occured, please try again'),
'error_read_file' => __('Error reading file'),
'error_write_file' => __('Error writing file'),
'save_first' => __('Module settings have been modified, please save first'),
'confirm' => __('Are you sure to continue?'),
'canceled' => __('Canceled')
);
$this->optimizeSettings = array(
);
$this->allowedExtensions = array_map('trim', explode(',', self::API_ALLOWED_EXTENSIONS));
// not used
$this->apiErrorCodes = array(
'400' => __('no url of image provided'),
'401' => __('impossible to fetch the image from URL (usually a local URL)'),
'402' => __('impossible to fetch the image from $_FILES (usually a local URL)'),
'403' => __('forbidden file format provided. Works strictly with jpg, png, gif, tif and bmp files.'),
'501' => __('internal error, cannot create a local copy'),
'502' => __('image provided too large (must be below 5MB)'),
'503' => __('internal error, could not reach remote reSmush.it servers for image optimization'),
'504' => __('internal error, could not fetch picture from remote reSmush.it servers')
);
}
/**
* Initialize log file
*
*/
public function init() {
$cls = strtolower(__CLASS__);
// pruneBytes returns error in PW prior to 3.0.13 if file does not exist
if(!file_exists($this->wire('log')->getFilename($cls))) {
$this->wire('log')->save($cls, 'log file created', array('showUser' => false, 'showURL' => false));
}
$this->log = new FileLog($this->wire('log')->getFilename($cls));
method_exists($this->log, __CLASS__) ? $this->log->pruneBytes(20000) : $this->log->prune(20000);
}
/**
* Hook before InputfieldFile::fileAdded in auto mode
* Compress on upload
*
* @param HookEvent $event
* @return bool false if image extension is not in allowedExtensions
*
*/
public function compressOnUpload($event) {
$pdf = $event->argumentsByName('pagefile');
// ensure only pdf files are compressed
if(!$pdf instanceof Pagefile) return;
if(!in_array($pdf->ext, $this->allowedExtensions)) return;
// compress
$this->compress($pdf, true, 'auto');
}
/**
* Hook after InputfieldFile::renderItem in manual mode
* Add compress link to the file markup
*
* @param HookEvent $event
*
*/
public function addOptButton($event) {
// $event->object = InputfieldFile
// $event->object->value = Pagefiles
// $event->arguments[0] or $event->argumentsByName('pagefile') = Pagefile
$file = $event->argumentsByName('pagefile');
if(!in_array($file->ext, $this->allowedExtensions)) return; // is not pdf file
$url = $this->wire('config')->urls->admin . 'module/edit?name=' . __CLASS__ . "&mode=compresspdf&id={$file->page->id}&file={$file->url}";
$link = "<a href='$url' class='InputfieldFileCompress' title='Compress file'>" . $this->_("Compress") ."</a>";
if(stripos($event->return, '</p>')) { //insert link right before </p>
$event->return = str_replace("</p>", $link . "</p>", $event->return);
}
}
/**
* Compress file via ajax request when compress link is clicked
*
* @return string
*
*/
public function onclickCompress() {
$err = "<i style='color:red' class='fa fa-times-circle'></i>";
$file = $this->wire('input')->get('file'); // /site/assets/files/1234/file.ext
$id = (int) $this->wire('input')->get('id');
$pdf = $this->getPageimageOrPagefileFromPath($file, $this->wire('pages')->get($id));
if(!in_array($pdf->ext, $this->allowedExtensions)) return; // is not pdf file
$src_size = $pdf->filesize;
$this->compress($pdf, true, 'manual');
clearstatcache(true, $pdf->filename);
$dest_size = $pdf->filesize;
$percentNew = 100 - (int) ($dest_size / $src_size * 100);
printf(__('Compressed, reduced by %1$d%%'), $percentNew);
exit(0);
}
/**
* Process bulk optimize of all images, called from this module settings
* in bulk mode, on button click
*
*/
public function bulkCompress() {
// check if engine is selected
if(!isset($this->configData['optBulkEngine'])) {
$this->writeProgressFile($this->getProgressFile(), array(
'percentComplete' => '',
'error' => 'ERROR: No engine selected.', // message displayed in progressbar
'file' => 'ERROR', // indicator that error occured
'basedir' => '',
'url' => ''
));
$this->log->save("No engine selected (bulk).");
exit(0);
}
$allFiles = array();
$selector = 'type=FieldtypeFile';
// find all pages with FieldtypeFile fields that has allowed (pdf) extension
foreach($this->wire('fields')->find($selector) as $f) {
foreach($this->wire('pages')->find("$f>0, include=all") as $p) {
$files = $p->getUnformatted($f->name);
foreach($files as $file) {
if(in_array($file->ext, $this->allowedExtensions)) {
$allFiles[] = $file;
}
}
}
}
$totalItems = count($allFiles);
@unlink($this->getProgressFile());
@unlink($this->getCancelFile());
// important!
@session_write_close();
set_time_limit(3600);
for ($i = 0; $i < $totalItems; $i ++) {
$pdf = $allFiles[$i];
$error = null;
if(!file_exists($pdf->filename)) {
$error = $this->getMessage('error_read_file');
$this->log->save($error);
} else {
$this->compress($pdf, true, 'bulk', $i+1, $totalItems, $error);
}
if(file_get_contents($this->getCancelFile()) === '1') {
// Cancel button pressed, bail out
break;
}
}
exit(0);
}
/**
* Compress file
*
* @param Pagefile $pdf Pagefile object
* @param boolean $force true, when you want to force file compress
* @param string $mode 'auto', 'manual' or 'bulk'
* @param int|null $counter used when called from bulkCompress(), current file number
* @param int $total used when called from bulkCompress(), total number of files
* @param string|null $error error message
* @return boolean false on error
*
*/
public function compress($pdf, $force = false, $mode = 'auto', $counter = null, $total = 1, $error = null) {
if(!is_null($error)) {
$this->writeProgressFile($this->getProgressFile(), array(
'percentComplete' => (int) ($counter / $total * 100) . "", //type casting
'error' => $error,
'file' => $pdf->basename,
'basedir' => basename(dirname($pdf->filename)),
'url' => $pdf->httpUrl
));
$this->log->save($error);
return false;
}
if(!in_array($pdf->ext, $this->allowedExtensions)) {
$error = 'Error compressing ' . $pdf->filename . ': unsupported extension';
$this->log->save($error);
return false;
}
$percentNew = 0;
$opt = $src_size = $dest_size = $q = '';
$mode1 = ucfirst(strtolower($mode));
//if(isset($this->configData["opt{$mode1}Quality"])) $q = $this->configData["opt{$mode1}Quality"];
//array_push($this->optimizeSettings['jpegoptim_options'], '-m' . $q);
//$this->optimizeSettings['jpegoptim_options'] = array_unique($this->optimizeSettings['jpegoptim_options']);
if(isset($this->configData["opt{$mode1}Engine"]) && $this->configData["opt{$mode1}Engine"] == 'labstack') {
// use labStack web service
$opt = "labStack ($mode): ";
if($pdf->filesize >= self::API_SIZELIMIT) {
$error = 'Error compressing ' . $pdf->filename . ': file larger then ' . self::API_SIZELIMIT . ' bytes';
$this->log->save($opt . $error);
return false;
}
/* alternative using curl instead od WireHttp class
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, self::API_WEBSERVICE);
// https options
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3);
curl_setopt($ch, CURLOPT_TIMEOUT, self::CONNECTION_TIMEOUT);
curl_setopt($ch, CURLOPT_POST, true);
if(version_compare(PHP_VERSION, '5.5') >= 0) {
$postfields = array ('file' => new CURLFile($pdf->filename, 'application/pdf', $pdf->basename));
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, true);
} else {
$postfields = array ('file' => '@'.$pdf->filename);
}
curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);
$data = curl_exec($ch);
if($data === false || curl_errno($ch)) {
$error = 'Error compressing ' . $pdf->filename . ': cURL error: ' . curl_error($ch);
$this->log->save($error);
return false;
}
curl_close($ch);
*/
$http = new WireHttp();
$http->setTimeout(self::CONNECTION_TIMEOUT); // important!!! default is 4.5 sec and that is to low
$eol = "\r\n";
$content = '';
$boundary = strtolower(md5(time()));
$content .= '--' . $boundary . $eol;
$content .= 'Content-Disposition: form-data; name="file"; filename="' . $pdf->basename . '"' . $eol;
$content .= 'Content-Type: application/pdf' . $eol . $eol; // two eol's!!!!!
$content .= file_get_contents($pdf->filename) .$eol;
$content .= "--" . $boundary . "--" . $eol;
$http->setHeader('Authorization', 'Bearer 4pjdl6a9bIsGD1OlTP6kWfPs5p9kIj1u'); //todo: make this configurable
$http->setHeader('Content-Type', 'multipart/form-data; boundary=' . $boundary);
$data = $http->post(self::API_WEBSERVICE, $content);
if(is_bool($data)) {
$error = 'Error compressing ' . $pdf->filename . ': ';
$error .= $data === true ? "request timeout" : $http->getHttpCode(true);
$this->log->save($error);
return false;
}
$response = json_decode($data);
if($response === null) {
$error = 'Error compressing ' . $pdf->filename . ': returned data is empty';
$this->log->save($opt . $error);
return false;
}
// write api error from webservice to json and log file
// don't know what I get back...
/*if(isset($response->error)) {
$error = isset($this->apiErrorCodes[$response->error]) ? ucfirst($this->apiErrorCodes[$response->error]) : $response->error;
$this->writeProgressFile($this->getProgressFile(), array(
'error_api' => $error,
'percentComplete' => (int) ($counter / $total * 100) . "", //type casting
'file' => $pdf->basename,
'basedir' => basename(dirname($pdf->filename)),
'url' => $pdf->httpUrl
));
$error = 'Error compressing ' . $pdf->filename . ': ' . $error;
$this->log->save($opt . $error);
return false;
}*/
$dest_size = $response->compressed_file->size;
$src_size = $response->file->size;
// write to file only if compressed file is smaller
if((int) $dest_size < (int) $src_size) {
$http = new WireHttp();
try {
$http->download(self::API_WEBSERVICE . "/" . $response->id . "/download", $pdf->filename);
$percentNew = 100 - (int) ($dest_size / $src_size * 100);
} catch(Exception $e) {
$error = 'Error retreiving file: ' . $e->getMessage();
$this->log->save($opt . $error);
return false;
}
}
} else if(isset($this->configData["opt{$mode1}Engine"]) && $this->configData["opt{$mode1}Engine"] == 'localtools') {
// use local tools
$opt = "LocalTools ($mode): ";
$src_size = filesize($pdf->filename);
// Compress
clearstatcache(true, $pdf->filename);
$dest_size = filesize($pdf->filename);
$percentNew = 100 - (int) ($dest_size / $src_size * 100);
} else {
// no engine selected
$opt = "No engine selected ($mode). ";
$src_size = filesize($pdf->filename);
$this->log->save($opt . $pdf->filename . ', source ' . $src_size . ' bytes');
return $opt;
}
$this->log->save($opt . $pdf->filename . ', source ' . $src_size . ' bytes, destination ' . $dest_size . ' bytes, reduction ' . $percentNew . '%');
if(!is_null($counter) && !is_null($total)) {
$this->writeProgressFile($this->getProgressFile(), array(
'percentComplete' => (int) ($counter / $total * 100) . "",
'counter' => sprintf(__('Compressed file %1$d out of %2$d - %3$d%% complete'),
$counter, $total, (int) ($counter / $total * 100)),
'percentNew' => $percentNew . "",
'error' => $error,
'file' => $pdf->basename,
'basedir' => basename(dirname($pdf->filename)),
'url' => $pdf->httpUrl
));
}
}
/**
* Module fields
*
* @param array $data config data
* @return InputfieldWrapper
*
*/
public function getModuleConfigInputfields(array $data) {
$fields = new InputfieldWrapper();
$modules = $this->wire('modules');
// automatic mode
$fieldset = $modules->get('InputfieldFieldset');
$fieldset->label = __('Automatic Mode');
$fieldset->description = __('Automatically optimize PDF files on upload.');
$fields->add($fieldset);
/*$field = $modules->get('InputfieldRadios');
$field->name = 'optAutoEngine';
$field->label = __('Engine');
$field->columnWidth = 50;
$field->addOption('labstack', __('Use labStack online service'));
//$field->addOption('localtools', __('Use local optimization tools'));
$field->value = isset($data['optAutoEngine']) ? $data['optAutoEngine'] : 'labstack';
$fieldset->add($field);*/
$data['optAutoEngine'] = 'labstack';
$field = $modules->get('InputfieldCheckboxes');
$field->name = 'optAutoAction';
$field->label = __('Action');
//$field->columnWidth = 50;
$field->addOption('compress_originals', __('Compress on upload'));
$field->value = isset($data['optAutoAction']) ? $data['optAutoAction'] : array();
$fieldset->add($field);
// manual mode
$fieldset = $modules->get('InputfieldFieldset');
$fieldset->label = __('Manual Mode');
$fieldset->description = __('Add "Compress" link to page.');
$fields->add($fieldset);
/*$field = $modules->get('InputfieldRadios');
$field->name = 'optManualEngine';
$field->label = __('Engine');
$field->columnWidth = 50;
$field->addOption('labstack', __('Use labStack online service'));
//$field->addOption('localtools', __('Use local optimization tools'));
$field->value = isset($data['optManualEngine']) ? $data['optManualEngine'] : 'labstack';
$fieldset->add($field);*/
$data['optManualEngine'] = 'labstack';
$field = $modules->get('InputfieldCheckboxes');
$field->name = 'optManualAction';
$field->label = __('Action');
//$field->columnWidth = 50;
$field->addOption('compress_originals', __('Add link to file edit page'));
$field->value = isset($data['optManualAction']) ? $data['optManualAction'] : array('compress_originals');
$fieldset->add($field);
// bulk mode
$fieldset = $modules->get('InputfieldFieldset');
$fieldset->name = 'bulkcompress_fieldset';
$fieldset->label = __('Bulk Mode');
$fieldset->description = __('Compress ALL PDF files on button click.');
$fields->add($fieldset);
/*$field = $modules->get('InputfieldRadios');
$field->attr('id+name', 'optBulkEngine');
$field->label = __('Engine');
$field->columnWidth = 50;
$field->addOption('labstack', __('Use labStack online service'));
//$field->addOption('localtools', __('Use local optimization tools'));
$field->value = isset($data['optBulkEngine']) ? $data['optBulkEngine'] : 'labstack';
$fieldset->add($field);*/
$data['optBulkEngine'] = 'labstack';
$field = $modules->get('InputfieldMarkup');
$field->id = 'bulkcompress';
$field->label = __('Bulk compress');
$field->icon = 'coffee';
$field->description = __('Click the button below to process all PDF files sitewide.');
$field->value = '<p class="description" style="margin-bottom:0;margin-top:-1em"><strong>' .
__('WARNING: this process may take a while to finish!') .
'</strong></p>';
$field_button = $modules->get('InputfieldButton');
$field_button->attr('id+name', 'compress_all');
$field_button->attr('data-url', 'edit?name=' . __CLASS__ . '&mode=bulkpdf');
$field_button->attr('data-progress-url', $this->getProgressFile(true));
$field_button->attr('data-start-msg', $this->getMessage('start'));
$field_button->attr('data-complete-msg', $this->getMessage('complete'));
$field_button->attr('data-error-msg', $this->getMessage('error'));
$field_button->attr('data-confirm-msg', $this->getMessage('confirm'));
$field_button->attr('data-save-first-msg', $this->getMessage('save_first'));
$field_button->value = __('Start bulk pdf compress');
$field->add($field_button);
$field_button = $modules->get('InputfieldButton');
$field_button->attr('id+name', 'cancel_all');
$field_button->attr('data-url', 'edit?name=' . __CLASS__ . '&mode=cancelpdf');
$field_button->attr('data-cancel-url', $this->getCancelFile(true));
$field_button->attr('data-canceled-msg', $this->getMessage('canceled'));
$field_button->value = __('Cancel');
$field->add($field_button);
$fieldm = $modules->get('InputfieldMarkup');
$fieldm->attr('id', 'progbarwrapper');
$fieldm->value = '<progress max="100" value="0" id="progressbar"></progress><span id="percent"></span><p id="result"></p>';
$field->add($fieldm);
$fieldset->add($field);
return $fields;
}
/**
* Get message text
*
* @param string $key
* @return string
*
*/
private function getMessage($key = '') {
return isset(self::$messages[$key]) ? self::$messages[$key] : '';
}
/**
* Return path or url of the progress file
*
* @param bool $url if true return url, if false return path
* @return string
*
*/
private function getProgressFile($url = false) {
$mode = ($url === true) ? 'urls' : 'paths';
return $this->wire('config')->$mode->assets . strtolower(__CLASS__) . '/progress.json';
}
/**
* Return path or url of the cancel file
*
* @param bool $url if true return url, if false return path
* @return string
*
*/
private function getCancelFile($url = false) {
$mode = ($url === true) ? 'urls' : 'paths';
return $this->wire('config')->$mode->assets . strtolower(__CLASS__) . '/cancel.json';
}
/**
* Write json encoded array to the file
*
* @param string $file
* @param array|mixed $content
*
*/
private function writeProgressFile($file, $content = null) {
if(!is_null($content)) file_put_contents($file, json_encode($content));
}
/**
* Returns Pageimage or Pagefile object from file path
* getPageimageOrPagefileFromPath('/site/assets/files/1234/file.jpg'); // returns either Pageimage or Pagefile object
* getPageimageOrPagefileFromPath('/site/assets/files/1234/file.txt'); // returns Pagefile object
* getPageimageOrPagefileFromPath('/site/assets/files/1234/none.txt'); // returns null
*
* @param straing $filename full path to the file eg. /site/assets/files/1234/file.jpg
* @param Page|null $page if null, page will be contructed based on id present in the file path
* @return Pagefile|Pageimage|null
*
*/
private function getPageimageOrPagefileFromPath($filename, $page = null) {
if(is_null($page)) {
// try to get id from filename
$id = (int) explode('/', str_replace(wire('config')->urls->files, '', $filename))[0];
$page = $this->wire('pages')->get($id);
}
if(!$page->id) return null; // throw new WireException('Invalid page id');
$basename = basename($filename);
// get file field types, that includes image file type
$field = new Field();
$field->type = $this->wire('modules')->get('FieldtypeFile');
$fieldtypes = $field->type->getCompatibleFieldtypes($field)->getItems();
$selector = 'type=' . implode('|', array_keys($fieldtypes));
//foreach($this->wire('fields')->find($selector) as $field) {
foreach($page->fields->find($selector) as $field) {
$files = $page->getUnformatted($field->name);
if($files) {
$file = $files[$basename];
if($file) return $file; // match found, return Pagefile or Pageimage
//check for image variations
foreach($files as $file) {
//if(method_exists($file, "getVariations")) {
if($file instanceof Pageimage) {
$variation = $file->getVariations()->get($basename);
if($variation) return $variation; // match found, return Pageimage
}
}
}
}
return null; // no match
}
/**
* Main entry point
* Set hooks and handle ajax requests
*
*/
public function ready() {
$page = $this->wire('page');
if($page->template != 'admin') return;
$this->configData = $this->wire('modules')->getModuleConfigData($this);
$config = $this->wire('config');
$input = $this->wire('input');
$mode = $input->get('mode');
if($input->get('name') === __CLASS__) {
$this->wire('modules')->get('JqueryMagnific');
$config->scripts->add($config->urls->siteModules . __CLASS__ . '/' . __CLASS__ . '.js');//?v=' . time());
$config->styles->add($config->urls->siteModules . __CLASS__ . '/' . __CLASS__ . '.css');//?v=' . time());
// compress files in bulk mode on button click
if($mode === 'bulkpdf') $this->bulkCompress();
// compress files in manual mode on clicking compress link
if($mode === 'compresspdf') $this->onclickCompress();
// process cancel request in bulk mode
if($mode === 'cancelpdf') {
$this->writeProgressFile($this->getCancelFile(), 1);
$this->log->save("Canceled.");
echo "1"; //success
exit (0);
}
}
// add compress link in manual mode on page edit
if($page->process == 'ProcessPageEdit' && isset($this->configData['optManualEngine'])) {
if(isset($this->configData['optManualAction']) && in_array('compress_originals', $this->configData['optManualAction'])) {
// add link
$this->addHookAfter('InputfieldFile::renderItem', $this, 'addOptButton');
}
$config->scripts->add($config->urls->siteModules . __CLASS__ . '/' . __CLASS__ . 'PageEdit.js');//?v=' . time());
$config->styles->add($config->urls->siteModules . __CLASS__ . '/' . __CLASS__ . 'PageEdit.css');//?v=' . time());
}
// compress files in auto mode on upload
if(isset($this->configData['optAutoAction']) && in_array('compress_originals', $this->configData['optAutoAction'])) {
$this->addHookBefore('InputfieldFile::fileAdded', $this, 'compressOnUpload');
}
}
/**
* Creates directory /site/assets/autosmushpdf on module install
*
*/
public function ___install() {
$logFolder = $this->wire('config')->paths->assets . strtolower(__CLASS__);
if(!is_dir($logFolder)) {
if(wireMkdir($logFolder) === false) throw new WireException("{$logFolder} could not be created, check permissions");
}
$this->writeProgressFile($this->getCancelFile(), 1);
if(!is_file($this->getCancelFile())) throw new WireException("{$logFolder} is not writable, check permissions");
@unlink($this->getCancelFile());
}
/**
* Removes directory /site/assets/autosmushpdf on module uninstall
*
*/
public function ___uninstall() {
$logFolder = $this->wire('config')->paths->assets . strtolower(__CLASS__);
if(is_dir($logFolder)) {
if(wireRmdir($logFolder, true) === false) throw new WireException("{$logFolder} could not be removed");
}
}
}