forked from symphonycms/jit_image_manipulation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
extension.driver.php
executable file
·584 lines (509 loc) · 23.8 KB
/
extension.driver.php
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
<?php
class extension_JIT_Image_Manipulation extends Extension
{
const __OK__ = 100;
const __ERROR_TRUSTED__ = 200;
const __INVALID_RECIPES__ = 250;
const __ERROR_SAVING_RECIPES__ = 300;
public $recipes_errors = array();
public function getSubscribedDelegates()
{
return array(
array(
'page' => '/system/preferences/',
'delegate' => 'AddCustomPreferenceFieldsets',
'callback' => 'appendPreferences'
),
array(
'page' => '/system/preferences/',
'delegate' => 'Save',
'callback' => '__SavePreferences'
),
array(
'page' => '/all/',
'delegate' => 'ModifySymphonyLauncher',
'callback' => 'modifySymphonyLauncher'
)
);
}
public function modifySymphonyLauncher($context)
{
if ($_REQUEST['mode'] !== 'jit') {
return;
}
$previousLauncher = SYMPHONY_LAUNCHER;
function jit_launcher($mode)
{
if (strtolower($mode) == 'jit') {
require_once __DIR__ . '/lib/class.jit.php';
$renderer = JIT\JIT::instance();
$renderer->display();
} else if (is_callable($previousLauncher)) {
$previousLauncher($mode);
} else {
symphony_launcher($mode);
}
}
define('SYMPHONY_LAUNCHER', 'jit_launcher');
}
public function install()
{
require_once 'lib/class.htaccess.php';
$htaccess = new HTAccess();
try {
if ($htaccess->exists()) {
if (!$htaccess->is_writable()) {
throw new Exception(__('.htaccess exists but is not writable.'));
}
$htaccess->enableExtension();
}
// Create workspace directory
General::realiseDirectory(WORKSPACE . '/jit-image-manipulation', Symphony::Configuration()->get('write_mode', 'directory'));
// Now add Configuration values
Symphony::Configuration()->set('cache', '1', 'image');
Symphony::Configuration()->set('quality', '90', 'image');
Symphony::Configuration()->write();
} catch (Exception $ex) {
$message = __(
'An error occured while installing %s. %s',
array(
__('JIT Image Manipulation'),
$ex->getMessage()
)
);
throw new Exception($message);
}
}
public function enable()
{
return $this->install();
}
public function update($previousVersion = false)
{
require_once 'lib/class.htaccess.php';
$htaccess = new HTAccess();
if ($htaccess->exists() && !$htaccess->is_writable()) {
throw new Exception(__('.htaccess exists but is not writable.'));
}
if (version_compare($previousVersion, '1.15', '<')) {
// Move /manifest/jit-trusted-sites into /workspace/jit-image-manipulation
if (General::realiseDirectory(WORKSPACE . '/jit-image-manipulation', Symphony::Configuration()->get('write_mode', 'directory')) && file_exists(MANIFEST . '/jit-trusted-sites')) {
if (!@rename(MANIFEST . '/jit-trusted-sites', WORKSPACE . '/jit-image-manipulation/trusted-sites')) {
$message = __(
'An error occured while updating %s. Could not move the trusted file to %s',
array(
__('JIT Image Manipulation'),
WORKSPACE . '/jit-image-manipulation/trusted-sites'
)
);
throw new Exception($message);
}
}
}
if (version_compare($previousVersion, '1.17', '<')) {
// Add [B] flag to the .htaccess rule [#37]
try {
if ($htaccess->exists()) {
$htaccess->addBFlagToRule();
}
} catch (Exception $ex) {
$message = __(
'An error occured while updating %s. %s',
array(
__('JIT Image Manipulation'),
$ex->getMessage()
)
);
throw new Exception($message);
}
}
if (version_compare($previousVersion, '1.21', '<')) {
try {
// Simplify JIT htaccess rule [#75]
if ($htaccess->exists()) {
$htaccess->simplifyJITAccessRule();
}
} catch (Exception $ex) {
$message = __(
'An error occured while updating %s. %s',
array(
__('JIT Image Manipulation'),
$ex->getMessage()
)
);
throw new Exception($message);
}
}
if (version_compare($previousVersion, '2.0.0', '<')) {
try {
if ($htaccess->exists()) {
$htaccess->transformRuleToSymphonyLauncher();
}
} catch (Exception $ex) {
$message = __(
'An error occured while updating %s. %s',
array(
__('JIT Image Manipulation'),
$ex->getMessage()
)
);
throw new Exception($message);
}
}
}
public function uninstall()
{
General::deleteDirectory(WORKSPACE . '/jit-image-manipulation');
return $this->disable();
}
public function disable()
{
require_once 'lib/class.htaccess.php';
$htaccess = new HTAccess();
try {
if ($htaccess->exists()) {
$htaccess->disableExtension();
}
} catch (Exception $ex) {
$message = __(
'An error occured while disabling %s. %s',
array(
__('JIT Image Manipulation'),
$ex->getMessage()
)
);
throw new Exception($message);
}
}
/*-------------------------------------------------------------------------
Utilities:
-------------------------------------------------------------------------*/
public function trusted()
{
return is_readable(WORKSPACE . '/jit-image-manipulation/trusted-sites')
? file_get_contents(WORKSPACE . '/jit-image-manipulation/trusted-sites')
: null;
}
public function saveTrusted($string)
{
$written = General::writeFile(WORKSPACE . '/jit-image-manipulation/trusted-sites', $string, Symphony::Configuration()->get('write_mode', 'file'));
return ($written ? self::__OK__ : self::__ERROR_TRUSTED__);
}
public function saveRecipes($recipes)
{
$string = "<?php" . PHP_EOL;
$string .= PHP_EOL ."\t\$recipes = array(" . PHP_EOL;
if (is_array($recipes) && !empty($recipes)) {
// array to collect recipe handles
$handles = array();
foreach ($recipes as $position => $recipe) {
if (empty($recipe['name'])) {
$this->recipes_errors[$position] = array(
'missing' => __('This is a required field.')
);
break;
}
if (empty($recipe['url-parameter']) && $recipe['mode'] !== 'regex') {
$recipe['url-parameter'] = $_POST['jit_image_manipulation']['recipes'][$position]['url-parameter'] = Lang::createHandle($recipe['name']);
}
// check for recipes with same handles
if (!in_array($recipe['url-parameter'], $handles)) {
// handle does not exist => save recipe
$string .= PHP_EOL . "\t\t########";
$string .= PHP_EOL . "\t\tarray(";
foreach ($recipe as $key => $value) {
$string .= PHP_EOL . "\t\t\t'$key' => ".(strlen($value) > 0 ? "'".addslashes($value)."'" : 'NULL').",";
}
$string .= PHP_EOL . "\t\t),";
$string .= PHP_EOL . "\t\t########" . PHP_EOL;
// collect recipe handle
$handles[] = $recipe['url-parameter'];
} elseif ($recipe['mode'] === 'regex') {
// regex already exists => set error
$this->recipes_errors[$position] = array(
'invalid' => __('A recipe with this regular expression already exists.')
);
} else {
// handle does exist => set error
$this->recipes_errors[$position] = array(
'invalid' => __('A recipe with this handle already exists. All handles must be unique.')
);
}
}
}
$string .= PHP_EOL ."\t);" . PHP_EOL;
// notify for duplicate recipes handles
if (!empty($this->recipes_errors)) {
return self::__INVALID_RECIPES__;
}
// try to write recipes file
if (!General::writeFile(WORKSPACE . '/jit-image-manipulation/recipes.php', $string, Symphony::Configuration()->get('write_mode', 'file'))) {
return self::__ERROR_SAVING_RECIPES__;
}
// all went fine
return self::__OK__;
}
public function createRecipeDuplicatorTemplate($mode = '0', $position = '-1', $values = array(), $error = false)
{
$modes = array(
'0' => __('Direct display'),
'1' => __('Resize'),
'2' => __('Crop to Fill'),
'3' => __('Resize Canvas'),
'4' => __('Resize to Fit'),
'regex' => __('Custom')
);
$referencePositions = array(
__('Top left'),
__('Top center'),
__('Top right'),
__('Center left'),
__('Center'),
__('Center right'),
__('Bottom left'),
__('Bottom center'),
__('Bottom right'),
);
$positionOptions = array();
if (empty($values)) {
$values = array(
'position' => null,
'name' => null,
'url-parameter' => null,
'external' => null,
'width' => null,
'height' => null,
'background' => null,
'quality' => null,
'jit-parameter' => null
);
}
foreach ($referencePositions as $i => $p) {
$positionOptions[] = array($i + 1, $i + 1 == $values['position'] ? true : false, $p);
}
// general template settings
$li = new XMLElement('li');
$li->setAttribute('class', $position >= 0 ? 'instance expanded' : 'template');
$li->setAttribute('data-type', 'mode-' . $mode);
$header = new XMLElement('header', null, array('data-name' => $modes[$mode]));
$label = (!empty($values['name'])) ? $values['name'] : __('New Recipe');
$header->appendChild(new XMLElement('h4', '<strong>' . $label . '</strong> <span class="type">' . $modes[$mode] . '</span>'));
$li->appendChild($header);
$li->appendChild(Widget::Input("jit_image_manipulation[recipes][{$position}][mode]", $mode, 'hidden'));
$group = new XMLElement('div');
$group->setAttribute('class', 'two columns');
// Name
$label = Widget::Label(__('Name'), null, 'column');
$label->appendChild(Widget::Input("jit_image_manipulation[recipes][{$position}][name]", $values['name']));
if (is_array($error) && isset($error['missing'])) {
$group->appendChild(Widget::Error($label, $error['missing']));
} else {
$group->appendChild($label);
}
// Handle
$label_text = $mode === 'regex' ? __('Regular Expression') : __('Handle') . '<i>e.g. /image/{handle}/path/to/my-image.jpg</i>';
$label = Widget::Label(__($label_text), null, 'column');
$label->appendChild(Widget::Input("jit_image_manipulation[recipes][{$position}][url-parameter]", $values['url-parameter']));
if (is_array($error) && isset($error['invalid'])) {
$group->appendChild(Widget::Error($label, $error['invalid']));
} else {
$group->appendChild($label);
}
$li->appendChild($group);
// width and height for modes 1, 2, 3 and 4
if ($mode === '1' || $mode === '2' || $mode === '3' || $mode === '4') {
$group = new XMLElement('div');
$group->setAttribute('class', 'two columns');
$label = Widget::Label(__('Width'), null, 'column');
$label->appendChild(Widget::Input("jit_image_manipulation[recipes][{$position}][width]", $values['width']));
$group->appendChild($label);
$label = Widget::Label(__('Height'), null, 'column');
$label->appendChild(Widget::Input("jit_image_manipulation[recipes][{$position}][height]", $values['height']));
$group->appendChild($label);
$li->appendChild($group);
}
// position and background for mode 2 and 3
if ($mode === '2' || $mode === '3') {
$group = new XMLElement('div');
$group->setAttribute('class', 'two columns');
$label = Widget::Label(__('Position'), null, 'column');
$label->appendChild(Widget::Select("jit_image_manipulation[recipes][{$position}][position]", $positionOptions));
$group->appendChild($label);
$label = Widget::Label(__('Background Color'), null, 'column');
$label->appendChild(new XMLElement('i', __('Optional')));
$label->appendChild(Widget::Input("jit_image_manipulation[recipes][{$position}][background]", $values['background']));
$group->appendChild($label);
$li->appendChild($group);
}
// regex mode
if ($mode === 'regex') {
$label = Widget::Label(__('JIT Parameter'));
$label->appendChild(Widget::Input("jit_image_manipulation[recipes][{$position}][jit-parameter]", $values['jit-parameter']));
$li->appendChild($label);
}
// more general settings, except quality for direct display and external image for regex mode
$group = new XMLElement('div');
$group->setAttribute('class', 'two columns');
if ($mode !== '0') {
$label = Widget::Label(__('Image quality'), null, 'column');
$label->appendChild(new XMLElement('i', __('Optional')));
$label->appendChild(Widget::Input("jit_image_manipulation[recipes][{$position}][quality]", $values['quality']));
$group->appendChild($label);
}
if ($mode !== 'regex') {
$label = Widget::Label();
$label->setAttribute('class', 'column justified');
$hidden = Widget::Input("jit_image_manipulation[recipes][{$position}][external]", '0', 'hidden');
$input = Widget::Input("jit_image_manipulation[recipes][{$position}][external]", '1', 'checkbox');
if ($values['external'] == '1') {
$input->setAttribute('checked', 'checked');
}
$label->setValue($input->generate() . ' ' . __('External Image'));
$group->appendChild($hidden);
$group->appendChild($label);
}
$li->appendChild($group);
return $li;
}
/*-------------------------------------------------------------------------
Delegates:
-------------------------------------------------------------------------*/
public function appendPreferences($context)
{
// Check if JIT configuration folder exists
if (!file_exists(WORKSPACE . '/jit-image-manipulation/')) {
Administration::instance()->Page->pageAlert(__('The JIT configuration folder, %s, does not exist. You will not be able to save recipes and trusted sites.', array('<code>/workspace/jit-image-manipulation/</code>')), Alert::ERROR);
}
// Alert messages for JIT configuration errors
$errors = $context['errors'];
if (isset($errors['jit-trusted-sites'])) {
Administration::instance()->Page->pageAlert($errors['jit-trusted-sites'], Alert::ERROR);
}
if (isset($errors['jit-recipes'])) {
Administration::instance()->Page->pageAlert($errors['jit-recipes'], Alert::ERROR);
}
// JavaScript for recipes duplicator
Administration::instance()->Page->addScriptToHead(URL . '/extensions/jit_image_manipulation/assets/jit_image_manipulation.preferences.js', 3134);
$group = new XMLElement('fieldset');
$group->setAttribute('class', 'settings');
$group->appendChild(new XMLElement('legend', __('JIT Image Manipulation')));
$group->appendChild(
new XMLElement('p', __('Recipes are named rules for the JIT settings.'), array('class' => 'help'))
);
// recipes duplicator
$group->appendChild(new XMLElement('p', __('Recipes'), array('class' => 'label')));
$div = new XMLElement('div', null, array('class' => 'frame jit-duplicator'));
$duplicator = new XMLElement('ol');
$duplicator->setAttribute('data-add', __('Add recipe'));
$duplicator->setAttribute('data-remove', __('Remove recipe'));
$duplicator->appendChild(self::createRecipeDuplicatorTemplate('0'));
$duplicator->appendChild(self::createRecipeDuplicatorTemplate('1'));
$duplicator->appendChild(self::createRecipeDuplicatorTemplate('2'));
$duplicator->appendChild(self::createRecipeDuplicatorTemplate('3'));
$duplicator->appendChild(self::createRecipeDuplicatorTemplate('4'));
$duplicator->appendChild(self::createRecipeDuplicatorTemplate('regex'));
// use recipes POST datain case of an error
$post_recipes = (isset($_POST['jit_image_manipulation']['recipes'])) ? $_POST['jit_image_manipulation']['recipes'] : array();
if (!empty($post_recipes) && !empty($this->recipes_errors)) {
foreach ($post_recipes as $position => $recipe) {
$duplicator->appendChild(
self::createRecipeDuplicatorTemplate($recipe['mode'], $position, $recipe, $this->recipes_errors[$position])
);
}
} // otherwise use saved recipes data
else {
(file_exists(WORKSPACE . '/jit-image-manipulation/recipes.php')) ? include(WORKSPACE . '/jit-image-manipulation/recipes.php') : $recipes = array();
if (is_array($recipes) && !empty($recipes)) {
foreach ($recipes as $position => $recipe) {
$duplicator->appendChild(
self::createRecipeDuplicatorTemplate($recipe['mode'], $position, $recipe)
);
}
}
}
$div->appendChild($duplicator);
$group->appendChild($div);
// checkbox to disable regular rules
$label = Widget::Label();
$input = Widget::Input('settings[image][disable_regular_rules]', 'yes', 'checkbox');
if (Symphony::Configuration()->get('disable_regular_rules', 'image') == 'yes') {
$input->setAttribute('checked', 'checked');
}
$label->setValue($input->generate() . ' ' . __('Disable dynamic URLs and use named recipes only.') . '<i><strong>' . __('Warning:') . '</strong>' . __(' this will break image previews in the backend') . '</i>');
$group->appendChild($label);
// checkbox to disable up-scaling
$label = Widget::Label();
$input = Widget::Input('settings[image][disable_upscaling]', 'yes', 'checkbox');
if (Symphony::Configuration()->get('disable_upscaling', 'image') == 'yes') {
$input->setAttribute('checked', 'checked');
}
$label->setValue($input->generate() . ' ' . __('Disable upscaling of images beyond the original size'));
$group->appendChild($label);
// checkbox to diable proxy transformation of images
$label = Widget::Label();
$input = Widget::Input('settings[image][disable_proxy_transform]', 'yes', 'checkbox');
if (Symphony::Configuration()->get('disable_proxy_transform', 'image') == 'yes') {
$input->setAttribute('checked', 'checked');
}
$label->setValue($input->generate() . ' ' . __('Prevent ISP proxy transformation'));
$group->appendChild($label);
// text input to allow external request origins
$label = Widget::Label(__('Add Cross-Origin Header'));
$input = Widget::Input('settings[image][allow_origin]', Symphony::Configuration()->get('allow_origin', 'image'));
$label->appendChild($input);
$group->appendChild($label);
// textarea for trusted sites
$label = Widget::Label(__('Trusted Sites'));
$label->appendChild(Widget::Textarea('jit_image_manipulation[trusted_external_sites]', 5, 50, $this->trusted()));
$group->appendChild($label);
$group->appendChild(new XMLElement('p', __('Leave empty to disable external linking. Single rule per line. Add * at end for wild card matching.'), array('class' => 'help')));
$context['wrapper']->appendChild($group);
}
public function __SavePreferences($context)
{
$recipes_saved = self::__OK__;
if (!isset($context['settings']['image']['disable_regular_rules'])) {
$context['settings']['image']['disable_regular_rules'] = 'no';
}
if (!isset($context['settings']['image']['disable_upscaling'])) {
$context['settings']['image']['disable_upscaling'] = 'no';
}
if (!isset($context['settings']['image']['disable_proxy_transform'])) {
$context['settings']['image']['disable_proxy_transform'] = 'no';
}
if (!isset($context['settings']['image']['allow_origin'])) {
$context['settings']['image']['allow_origin'] = '"null"';
}
// save trusted sites
$trusted_saved = $this->saveTrusted(stripslashes($_POST['jit_image_manipulation']['trusted_external_sites']));
// there were errors saving the trusted files
if ($trusted_saved == self::__ERROR_TRUSTED__) {
$context['errors']['jit-trusted-sites'] = __('An error occurred while saving the JIT trusted sites. Make sure the trusted sites file, %s, exists and is writable and the directory, %s, is also writable.',
array(
'<code>/workspace/jit-image-manipulation/trusted-sites</code>',
'<code>/workspace/jit-image-manipulation</code>',
)
);
};
// save recipes (if they exist)
if (isset($_POST['jit_image_manipulation']['recipes'])) {
$recipes_saved = $this->saveRecipes($_POST['jit_image_manipulation']['recipes']);
} // nothing posted, so clear recipes
else {
$recipes_saved = $this->saveRecipes(array());
}
// there were errors saving the recipes
if ($recipes_saved == self::__ERROR_SAVING_RECIPES__) {
$context['errors']['jit-recipes'] = __('An error occurred while saving the JIT recipes. Make sure the recipes file, %s, exists and is writable and the directory, %s, is also writable.',
array(
'<code>/workspace/jit-image-manipulation/recipes.php</code>',
'<code>/workspace/jit-image-manipulation</code>',
)
);
}
// there were duplicate recipes handles
if ($recipes_saved == self::__INVALID_RECIPES__) {
$context['errors']['jit-recipes'] = __('An error occurred while saving the JIT recipes.');
}
}
}