This repository was archived by the owner on Oct 12, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathImageExtra.module
More file actions
1415 lines (1213 loc) · 44.3 KB
/
ImageExtra.module
File metadata and controls
1415 lines (1213 loc) · 44.3 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
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
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php namespace ProcessWire;
/**
*
* ImageExtra
*
* See README.md for usage instructions.
*
* @author Tabea David <td@kf-interactive.com>
* @version 1.0.6
* @copyright Copyright (c) 2017
* @see https://github.com/justonestep/processwire-imageextra
* @see http://www.processwire.com
*/
/**
* Class ImageExtra
*/
class ImageExtra extends WireData implements Module {
/**
* Retrieves module meta data
* Implementation of the Module interface
*
* @return array
* @see http://processwire.com/apigen/class-Module.html
*/
public static function getModuleInfo() {
return array(
'title' => 'Image Extra',
'summary' => 'Adds custom fields to image fields (including multi-language support)',
'version' => 106,
'href' => 'https://github.com/justonestep/processwire-imageextra',
'singular' => true,
'autoload' => true,
);
}
/**
* @field array default config values for field settings
*/
protected static $defaults = array(
'orientationField' => false,
'orientationValues' => 'left,right',
'linkField' => false,
'otherField' => '',
'otherFieldSettings' => ''
);
/**
* @field array additional fields
*/
protected $additionalFields = array(
'other' => array(),
'orientation' => array(),
'link' => array()
);
/**
* @field boolean whether the language tabs module is installed
*/
protected static $hasLangTabs = null;
/**
* version breakpoint
*/
const VERSION_COMPARE = 3029;
/**
* Initialize the module - ready
*
* ProcessWire calls this when the module is loaded. For 'autoload' modules, this will be called
* when ProcessWire's API is ready. As a result, this is a good place to attach hooks.
*
* @see http://processwire.com/apigen/class-Module.html
*
*/
public function ready() {
$admin = $this->config->urls->admin;
$backend = strpos($this->page->url, $admin);
if (in_array($this->page->name, array('edit', 'field', 'module', 'users')) || $backend === false) {
$this->addHookAfter('InputfieldImage::getConfigInputfields', $this, 'addExtraFields');
$this->addHookAfter('InputfieldImage::renderItem', $this, 'manipulateDescriptionField');
$this->addHookAfter('InputfieldImage::renderAdditionalFields', $this, 'renderExtraFields');
$this->addHookBefore('ProcessField::executeSave', $this, 'checkTableColumnsAndParseSettings');
if (wire('page')->template->name === 'admin' && $this->input->get->id || wire('page')->template->name != 'admin') {
$this->addCustomMethods();
if (wire('page')->name === 'field' || !empty($this->additionalFields)) {
$this->addHookAfter('InputfieldImage::processInputFile', $this, 'processInputFileExtra');
$this->addHookMethod('Pageimage::getExtraLabel', $this, 'getExtraLabel');
// if it's a recent version use hook after instead of overwriting
if ($this->isRecentVersion()) {
$this->addHookAfter('InputfieldFile::extractMetadata', $this, 'extractMetadataExtra');
} else {
$this->addHookBefore('InputfieldFile::processInputAddFile', $this, 'processInputAddFileExtra');
}
$this->addHookBefore('InputfieldImage::fileAdded', $this, 'fileAddedExtra');
$this->addHookAfter('Fieldtype::loadPageField', $this, 'loadPageFieldExtra');
$this->addHookAfter('FieldtypeFile::sleepValue', $this, 'sleepExtraValue');
$this->addHookAfter('FieldtypeFile::wakeupValue', $this, 'wakeupExtraValue');
$this->addHookAfter('FieldtypeFile::formatValue', $this, 'formatExtraValue');
if (isset($this->additionalFields['link']) && $backend !== false) {
$this->config->scripts->append($this->config->urls->InputfieldPageListSelect . 'InputfieldPageListSelect.min.js');
}
}
}
}
}
/**
* Compare Version
*
* @return boolean
*/
private function isRecentVersion() {
$version = str_replace('.', '', $this->config->version);
// if version contains only 3 digits add leading 0 for the last part
if (strlen($version) < 4) $version = substr_replace($version, '0', -1, 0);
return (int)$version >= self::VERSION_COMPARE ? true : false;
}
/**
* Merge a multidimensional array
*
* @param array $array
* @return array
*
*/
private function array_multi_merge($array) {
$new = array();
foreach ($array as $items) {
foreach ($items as $item)
$new[$item] = $item;
}
return $new;
}
/**
* fix any backreferences
* If there's a chance your replacement text contains any strings such as "$0.95",
* You'll need to escape those $n backreferences:
*
* @see http://us1.php.net/manual/en/function.preg-replace.php#103985
* @param string $x
* @return array
*
*/
function escape_backreference($x) {
return preg_replace('/\$(\d)/', '\\\$$1', $x);
}
/**
* Add a custom method for each custom field
*
*/
public function addCustomMethods() {
$imagefields = false;
foreach ($this->fields as $field) {
if ($field->type instanceof FieldtypeImage) {
$this->getAdditionalInputFields($field);
$imagefields = true;
}
}
if ($imagefields) {
// add property and method for other fields
foreach ($this->array_multi_merge($this->additionalFields['other']) as $current) {
$this->addHookProperty('Pageimage::' . $current, function($event) {});
$this->addHook('Pageimage::' . $current, $this, 'addCustomMethod');
}
// add property and method for orientation
$this->addHookProperty('Pageimage::orientation', function($event) {});
$this->addHook('Pageimage::orientation', $this, 'addOrientation');
// add property and method for link
$this->addHookProperty('Pageimage::link', function($event) {});
$this->addHook('Pageimage::link', $this, 'addLink');
}
}
/**
* Add orientation method
*
* @param HookEvent $event
* @return string
*
*/
public function addOrientation(HookEvent $event) {
$value = $event->arguments(0);
if (!is_null($value)) {
$value = $this->wire('sanitizer')->textarea($value);
$event->object->set('orientation', $value);
}
// we only return strings, so return blank rather than null
$event->return = (is_null($value)) ? '' : $value;
}
/**
* Add link method
*
* @param HookEvent $event
* @return string
*
*/
public function addLink(HookEvent $event) {
$value = $event->arguments(0);
if (!is_null($value)) {
$value = $this->wire('sanitizer')->text($value);
$event->object->set('link', $value);
}
// we only return strings, so return blank rather than null
$event->return = (is_null($value)) ? '' : $value;
}
/**
* add custom method for custom input fields
*
* @param HookEvent $event
* @param string $current
*
*/
public function addCustomMethod(HookEvent $event) {
$language = $event->arguments(0);
$value = $event->arguments(1);
$current = $event->method;
if (!is_null($value)) {
return ($language === true) ? $this->setExtra($current, $value, null, $event->object) : $this->setExtra($current, $value, $language, $event->object);
}
if ((is_string($language) || is_int($language)) && $this->wire('languages')) {
$language = $this->wire('languages')->get($language);
}
if (is_null($language)) {
// return for current user language, or inherit from default if not available
$user = $this->wire('user');
$value = null;
if ($user->language && $user->language->id) {
$value = $event->object->get($current . $user->language);
} else {
if (empty($value) && isset($current[$event->object->data])) {
// inherit default language value
$value = $event->object->get($current);
}
}
} else if ($language === true) {
// return JSON string of all languages if applicable
$languages = $this->wire('languages');
if ($languages && $languages->count() > 1) {
$values = array(0 => $event->object->get($current));
foreach ($languages as $lang) {
if ($lang->isDefault()) continue;
$v = $event->object->get($current . $lang);
if (empty($v)) continue;
$values[$lang->id] = $v;
}
$flags = defined("JSON_UNESCAPED_UNICODE") ? JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES : 0; // more fulltext friendly
$value = json_encode($values, $flags);
} else {
// no languages present so just return string with description
$value = $event->object->get($current);
}
} else if (is_object($language) && $language->id) {
// return for specific language or blank if not available
if ($language->isDefault()) $value = $event->object->get($current);
else $value = $event->object->get($current . $language);
}
// we only return strings, so return blank rather than null
if (is_null($value)) $value = '';
$event->return = $value;
}
/**
* Sets custom value, optionally parsing JSON language-specific value to separate properties
*
* @param string $name
* @param string $value
* @param Page|Language Langage to set it for. Omit to determine automatically.
* @param Pagefile $pagefile
* @return this
*/
protected function setExtra($name, $value, Page $language = null, $pagefile) {
if (!is_null($language) && $language->id) {
if (!$language->isDefault()) $name .= $language->id;
$value = $this->wire('sanitizer')->purify($value);
$pagefile->set($name, $value);
return $pagefile;
}
// check if it contains JSON?
$first = substr($value, 0, 1);
$last = substr($value, -1);
if(($first == '{' && $last == '}') || ($first == '[' && $last == ']')) {
$values = json_decode($value, true);
} else {
$values = array();
}
if ($values && count($values)) {
$n = 0;
foreach ($values as $id => $v) {
// first item is always default language. this ensures that this will still
// work even if language support is later uninstalled.
$item = $n > 0 ? $name . $id : $name;
$value = $this->wire('sanitizer')->purify($v);
if ($n > 0) {
$pagefile->set($item, $value);
} else {
$this->setExtra($name, $value, null, $pagefile);
}
$n++;
}
} else {
// no JSON values so assume regular language
$languages = $this->wire('languages');
$language = $this->wire('user')->language;
$value = $this->wire('sanitizer')->purify($value);
if ($languages && $language && !$language->isDefault()) {
$pagefile->set($name . $language, $value);
} else {
$pagefile->set($name, $value);
}
}
return $pagefile;
}
/**
* Hook load page field
*
* @param HookEvent $event
*/
public function loadPageFieldExtra(HookEvent $event) {
$page = $event->arguments(0);
$field = $event->arguments(1);
if (!$page->id || !$field->id) return null;
if (is_null($field->inputfieldClass)) return null;
if (!$field->type instanceof FieldtypeImage) return null;
$database = $this->wire('database');
$isMulti = $field->type instanceof FieldtypeMulti;
$page_id = (int) $page->id;
$query = new DatabaseQuerySelect();
$tmpAddFields = array();
$count = 0;
// add all other fields to select query
foreach ($this->additionalFields['other'][$field->name] as $add) {
$query->select("field_{$field->name}.$add AS `" . $field->name . "__$add`");
$tmpAddFields[] = $add;
$count++;
}
// add orientation and link field to select query
foreach (array('orientation', 'link') as $add) {
if (!empty($this->additionalFields[$add][$field->name])) {
$query->select("field_{$field->name}.$add AS `" . $field->name . "__$add`");
$tmpAddFields[] = $add;
$count++;
}
}
if ($count === 0 || empty($tmpAddFields)) return null;
$table = $database->escapeTable($field->table);
$query->where("$table.pages_id='$page_id'");
$query->from($table);
if ($isMulti) $query->orderby('sort');
$value = null;
$stmt = $query->execute();
$result = $stmt->errorCode() > 0 ? false : true;
$fieldName = $database->escapeCol($field->name);
if (!$result) return $value;
$values = array();
while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
$value = array();
foreach ($tmpAddFields as $add) {
$key = $fieldName . '__' . $add;
$value[$add] = $row[$key];
}
// if there is just one 'data' field here, then don't bother with the array, just make data the value
if (count($value) == 1 && isset($value['data'])) $value = $value['data'];
if (!$isMulti) break;
$values[] = $value;
}
$stmt->closeCursor();
if ($isMulti && count($values)) $value = $values;
$return = array();
if (!empty($event->return)) {
foreach ($event->return as $key => $r) {
$return[] = $r + $value[$key];
}
$event->return = $return;
}
}
/**
* Hook sleep value
*
* @param HookEvent $event
*/
public function sleepExtraValue(HookEvent $event) {
$field = $event->arguments(1);
$value = $event->arguments(2);
if (!$field->type instanceof FieldtypeImage) return;
$tmp = array(
'other' => array(),
'orientation' => array(),
'link' => array()
);
$loop = 0;
foreach ($value as $pagefile) {
// check other fields
foreach ($this->additionalFields['other'][$field->name] as $key => $add) {
if (!is_null($pagefile->$add)) {
$tmp['other'][$loop][$add] = $pagefile->$add(true);
}
}
// check orientation and link field
foreach (array('orientation', 'link') as $add) {
if (!empty($this->additionalFields[$add][$field->name])) {
$tmp[$add][$loop][$add] = $pagefile->$add;
}
}
$loop++;
}
if (!empty($tmp)) {
$sleepValue = array();
foreach ($event->return as $key => $e) {
$other = (isset($key[$tmp['other']])) ? $tmp['other'][$key] : array();
$orientation = (isset($key[$tmp['orientation']])) ? $tmp['orientation'][$key] : array();
$link = (isset($key[$tmp['link']])) ? $tmp['link'][$key] : array();
$sleepValue[] = $e + $other + $orientation + $link;
}
$event->return = $sleepValue;
}
}
/**
* Hook wakeup value
*
* @param HookEvent $event
*/
public function wakeupExtraValue(HookEvent $event) {
$field = $event->arguments(1);
$value = $event->arguments(2);
if (!$field->type instanceof FieldtypeImage) return;
if (!is_array($value) || isset($value['data'])) $value = array($value);
$pagefiles = array();
foreach ($event->return as $pagefile) {
$pagefiles[] = $pagefile;
}
foreach ($value as $key => $v) {
if (empty($v['data'])) continue;
$pagefile = $pagefiles[$key];
// check other fields
foreach ($this->additionalFields['other'][$field->name] as $add) {
$pagefile->$add(true, $v[$add]);
}
// check orientation and link field
foreach (array('orientation', 'link') as $add) {
if (!empty($this->additionalFields[$add][$field->name]) && !empty($v[$add])) {
$pagefile->$add($v[$add]);
}
}
}
}
/**
* Hook format extra fields
*
* @param HookEvent $event
*/
public function formatExtraValue(HookEvent $event) {
$page = $event->arguments(0);
// causes an error. fixed/workaround by markus tiefenbacher 19.03.2018
//if ($page->data['title']) {
if (isset($page->data['title']) || isset($page->title)) {
$field = $event->arguments(1);
$value = $event->arguments(2);
$settings = $this->getOtherFieldSettings($field);
if ($settings && $formatters = $settings->cf_textformatter) {
foreach ($value as $v) {
foreach ($this->additionalFields['other'][$field->name] as $otherField) {
if (!property_exists($formatters, $otherField)) continue;
$formatter = $formatters->$otherField;
$currentValue = $v->$otherField;
if ($formatter) $this->modules->get($formatter)->formatValue($page, $field, $currentValue);
$v->$otherField = $currentValue;
}
}
}
}
}
/**
* Hook process input file add
*
* @param HookEvent $event
*/
public function extractMetadataExtra(HookEvent $event) {
$pagefile = $event->arguments(0);
$metadata = $event->return;
$name = $event->object->name;
foreach ($this->additionalFields['other'][$name] as $add) {
$metadata[$add] = $pagefile->$add;
}
if (!empty($this->additionalFields['orientation'][$name])) {
$metadata['orientation'] = $pagefile->orientation;
}
if (!empty($this->additionalFields['link'][$name])) {
$metadata['link'] = $pagefile->link;
}
$event->return = $metadata;
}
/**
* Hook process input file add
*
* @param HookEvent $event
*/
public function processInputAddFileExtra(HookEvent $event) {
$filename = $event->arguments(0);
$value = $event->object->attributes['value'];
$total = count($value);
$maxFiles = $value->field->maxFiles;
$overwrite = $value->field->overwrite;
$name = $event->object->name;
$tmp = array();
$rm = null;
$isAjax = $this->wire('input')->get('InputfieldFileAjax')
|| $this->wire('input')->get('reloadInputfieldAjax')
|| $this->wire('input')->get('renderInputfieldAjax');
if ($maxFiles > 1 && $total >= $maxFiles) return;
// allow replacement of file if maxFile is 1
if ($maxFiles == 1 && $total) {
$pagefile = $value->first();
$tmp['description'] = $pagefile->description;
$tmp['tags'] = $pagefile->tags;
foreach ($this->additionalFields['other'][$name] as $add) {
$tmp[$add] = $pagefile->$add;
}
if (!empty($this->additionalFields['orientation'][$name])) {
$tmp['orientation'] = $pagefile->orientation;
}
if (!empty($this->additionalFields['link'][$name])) {
$tmp['link'] = $pagefile->link;
}
$rm = true;
if ($filename == $pagefile->basename) {
// use overwrite mode rather than replace mode when single file and same filename
if ($overwrite) $rm = false;
}
if ($rm) {
if ($overwrite) $event->object->processInputDeleteFile($pagefile);
$event->object->set('singleFileReplacement', true);
}
}
if ($overwrite) {
$pagefile = $value->get($filename);
clearstatcache();
if ($pagefile) {
// already have a file of the same name
if ($pagefile instanceof Pageimage) $pagefile->removeVariations();
$tmp['description'] = $pagefile->description;
$tmp['tags'] = $pagefile->tags;
foreach ($this->additionalFields['other'][$name] as $add) {
$tmp[$add] = $pagefile->$add;
}
if (!empty($this->additionalFields['orientation'][$name])) {
$tmp['orientation'] = $pagefile->orientation;
}
if (!empty($this->additionalFields['link'][$name])) {
$tmp['link'] = $pagefile->link;
}
} else {
// we don't have a file with the same name as the one that was uploaded
// file must be in another files field on the same page, that could be problematic
$ul = $event->object->getWireUpload();
// see if any files were overwritten that weren't part of our field
// if so, we need to restore them and issue an error
$err = false;
foreach ($ul->getOverwrittenFiles() as $bakFile => $newFile) {
if (basename($newFile) != $filename) continue;
unlink($newFile);
rename($bakFile, $newFile); // restore
$ul->error(sprintf($this->_('Refused file %s because it is already on the file system and owned by a different field.'), $filename));
$err = true;
}
if ($err) return;
}
}
$value->add($filename);
$item = $value->last();
if (empty($tmp)) {
foreach ($this->additionalFields['other'][$name] as $add) {
$item->set($add, '');
}
if (!empty($this->additionalFields['orientation'][$name])) {
$item->set('orientation', '');
}
if (!empty($this->additionalFields['link'][$name])) {
$item->set('link', 0);
}
}
try {
foreach ($tmp as $key => $val) {
$item->$key = $val;
}
// items saved in ajax or uploadOnly mode are temporary till saved in non-ajax/non-uploadOnly
if ($isAjax && !$overwrite) $item->isTemp(true);
$event->object->fileAdded($item);
} catch(Exception $e) {
$item->unlink();
$value->remove($item);
throw new WireException($e->getMessage());
}
$event->replace = true;
}
/**
* Hook file added
*
* @param HookEvent $event
*/
public function fileAddedExtra(HookEvent $event) {
$image = $event->argumentsByName('pagefile');
$name = $event->object->name;
foreach ($this->additionalFields['other'][$name] as $add) {
$image->set($add, $image->$add);
}
if (!empty($this->additionalFields['orientation'][$name])) {
$image->set('orientation', $image->orientation);
}
if (!empty($this->additionalFields['link'][$name])) {
$image->set('link', $image->link);
}
}
/**
* Hook process input file
*
* @param HookEvent $event
*/
public function processInputFileExtra(HookEvent $event) {
$value = $event->object->attributes['value'];
$field = $value->field;
if (!$field->type instanceof FieldtypeImage) return;
$input = $event->arguments(0);
$pagefile = $event->arguments(1);
$n = $event->arguments(2);
$changed = $event->return;
$languages = $event->object->noLang ? null : $this->wire('languages');
$name = $event->object->name;
$id = $name . '_' . $pagefile->hash;
$fieldName = $field->name;
$combine = $this->additionalFields['other'][$fieldName];
foreach (array('orientation', 'link') as $add) {
if (!empty($this->additionalFields[$add][$fieldName])) {
$combine[$add] = $add;
}
}
foreach ($combine as $add) {
$key = $add . '_' . $id;
if (isset($input[$key])) {
$value = trim($input[$key]);
if ($value !== $pagefile->$key) {
$pagefile->$add = $value;
$changed = true;
}
}
}
// multi-language additional fields
if ($languages) foreach($languages as $language) {
foreach ($this->additionalFields['other'][$fieldName] as $add) {
$key = $language->isDefault() ? $add . '_' . $id : "{$add}_{$id}__{$language->id}";
if (!isset($input[$key])) continue;
$value = trim($input[$key]);
if ($value != $pagefile->{$add}($language)) {
$pagefile->{$add}($language, $value);
$changed = true;
}
}
}
$event->return = $changed;
}
/**
* Hook add extra fields
*
* @param HookEvent $event
*/
public function addExtraFields(HookEvent $event) {
if (!$event->object instanceof InputfieldImage) return;
$data = $this->mergeData($event->object->name);
$fieldset = $this->modules->get('InputfieldFieldset');
$fieldset->label = $this->_('Image Extra Fields');
$fieldset->collapsed = Inputfield::collapsedYes;
$fieldset->description = $this->_('Here you can add additional image fields.'); // Max image dimensions description
// move description fields
foreach ($event->return->children as $field) {
if (in_array($field->name, array('descriptionRows', 'noLang'))) {
$event->return->children->remove($field);
if ($field->name !== 'noLang') $fieldset->add($field);
}
}
// show field noLang
if ($this->wire('languages')) {
$f = $this->modules->get('InputfieldCheckbox');
$f->attr('name', 'noLang');
$f->attr('value', 1);
$f->columnWidth = 50;
$f->setAttribute('checked', $event->object->noLang ? 'checked' : '');
$f->label = $this->_('Disable multi-language fields?');
$f->description = $this->_('By default, fields are multi-language when you have Language Support installed. If you want to disable multi-language fields, check this box.'); // Disable multi-language description
$fieldset->add($f);
}
// assign fields
foreach ($this->getExtraFields($data) as $name => $s) {
// no orientation field - no orientation values needed
if ($name === 'orientationValues' && (int)$data['orientationField']== 0) {
continue;
}
// add orientation field, reduce column width
if ($name === 'orientationField' && (int)$data['orientationField'] > 0) {
$s['columnWidth'] = 25;
$s['notes'] = '';
}
$field = $this->modules->get($s['type']);
$field->name = $name;
$field->value = $data[$name];
foreach ($s as $key => $val) {
if ($key != 'type') {
$field->{$key} = $val;
}
}
$fieldset->add($field);
}
$name = $event->object->name;
$otherFields = $this->additionalFields['other'];
if (isset($otherFields[$name]) && count($otherFields[$name])) {
$addFields = $otherFields[$name];
$fieldset->add($this->addSettingsTable($addFields, $data));
}
$event->return->children->add($fieldset);
}
/**
* Add settings table for field settings
*
* @param array $addFields
* @param array $data
*/
private function addSettingsTable($addFields, $data) {
$settings = $data['otherFieldSettings'] ? json_decode($data['otherFieldSettings']) : array();
// textformatter select
$fTextformatter = $this->modules->get('InputfieldSelect');
$fTextformatter->label = $this->_('Text Formatter');
$textformatters = $this->modules->find("className^=Textformatter");
if (count($textformatters)) {
foreach ($textformatters as $textformatter) {
$info = $textformatter->getModuleInfo();
$fTextformatter->addOption($textformatter->className(), "$info[title]");
}
}
// inputfield for label text (multi-lingual)
$languages = $this->getLanguages(isset($data['noLang']) ? $data['noLang'] : 0);
$fLabel = $this->modules->get('InputfieldText');
$fLabel->label = $this->_('Custom Label');
// get table
$table = $this->modules->get('MarkupAdminDataTable');
$table->setSortable(true);
$table->setEncodeEntities(false);
$table->headerRow(array(
$this->_('Custom Field'),
$this->_('Custom Label'),
$this->_('Textformatter')
));
foreach ($addFields as $custom) {
if (count($languages) > 1) $fLabel->useLanguages = true;
$fLabel->setAttribute('name', "cf_label__{$custom}");
$doesValueExist = isset($settings->cf_label) && isset($settings->cf_label->{"cf_label__$custom"});
$value = $doesValueExist ? $settings->cf_label->{"cf_label__$custom"} : '';
$fLabel->set('value', $value);
foreach ($languages as $language) {
if (is_null($language) || $language->isDefault()) continue;
$customLang = $custom . '__' . $language->id;
$doesValueExist = isset($settings->cf_label) && isset($settings->cf_label->{"cf_label__$customLang"});
$value = $doesValueExist ? $settings->cf_label->{"cf_label__$customLang"} : '';
$fLabel->set('value' . $language->id, $value);
}
$doesValueExist = isset($settings->cf_textformatter) && isset($settings->cf_textformatter->$custom);
$value = $doesValueExist ? $settings->cf_textformatter->$custom : '';
$fTextformatter->setAttribute('name', "cf_textformatter[$custom]");
$fTextformatter->attr('value', $value);
$table->row(array(
$custom,
$fLabel->render(),
$fTextformatter->render()
));
}
// wrap inside InputfieldMarkup
$field = $this->modules->get('InputfieldMarkup');
$field->value = '<div class="InputfieldHeader">' . $this->_('Additional Settings') . '</div><div class="InputfieldContent">' . $table->render() . '</div>';
return $field;
}
/**
* get extra fields
*
* @param array $data
*/
public function getExtraFields($data) {
return array(
'orientationField' => array(
'type' => 'InputfieldCheckbox',
'label' => $this->_('Add orientation field?'),
'description' => $this->_('Enable Image Orientation Select Field') . PHP_EOL .
$this->_('(activate the checkbox to enable field `orientation`)'),
'checked' => empty($data['orientationField']) ? '' : 'checked',
'columnWidth' => 50,
'notes' => $this->_('You can set up orientation values after saving.')
),
'orientationValues' => array(
'type' => 'InputfieldText',
'label' => $this->_('Enter image orientation values'),
'description' => $this->_('Values for Image Orientation Select Field') . PHP_EOL .
$this->_('(comma-separated list)'),
'value' => $data['orientationValues'],
'size' => 45,
'columnWidth' => 25
),
'linkField' => array(
'type' => 'InputfieldCheckbox',
'label' => $this->_('Add internal link field?'),
'description' => $this->_('Enable Choose-Link Field') . PHP_EOL .
$this->_('(activate the checkbox to enable field `link`)'),
'checked' => empty($data['linkField']) ? '' : 'checked',
'columnWidth' => 50
),
'otherField' => array(
'type' => 'InputfieldText',
'label' => $this->_('Add other text input fields?'),
'description' => $this->_('Add other fields as simple inputs') . PHP_EOL .
$this->_('(comma-separated list)'),
'value' => $data['otherField'],
'size' => 80,
'columnWidth' => 50,
'notes' => $this->_('Do not use `orientation` or `link` in this list.')
),
'otherFieldSettings' => array(
'type' => 'InputfieldHidden',
'label' => $this->_('Add other text input field settings?'),
'value' => $data['otherFieldSettings'],
'size' => 80,
'columnWidth' => 50
),
);
}
/**
* merge data
*
* @param string $fieldName
*/
private function mergeData($fieldName) {
$fieldConfig = $this->fields->get($fieldName)->data;
return array_merge(self::$defaults, $fieldConfig);
}
/**
* get additional input fields
*
* @param Field $field
*/
private function getAdditionalInputFields($field) {
$data = $field->data;
$name = $field->name;
// create basic array structure
foreach (array('other', 'orientation', 'link') as $item) {
if (!isset($this->additionalFields[$item][$name])) {
$this->additionalFields[$item][$name] = ($item === 'other') ? array() : '';
}
}
// check caption field
// deprecated, move captionField otherFields
if (isset($data['captionField'])) {
if ($data['captionField'] > 0) {
$otherField = 'caption';
if (isset($data['otherField']) && strlen($data['otherField']) > 0) $otherField .= ",{$data['otherField']}";
$data['otherField'] = $otherField;
}
unset($data['captionField']);
$field->data = $data;
$field->save();