-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJkImagePlaceholder.module
1316 lines (1170 loc) · 48.9 KB
/
JkImagePlaceholder.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
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
declare(strict_types=1);
namespace ProcessWire;
/**
*
* JKImagePlaceholder
*
* @author Jürgen K.
* @copyright Copyright (c) 2023
* @see http://www.processwire.com
*/
use Exception;
class JkImagePlaceholder extends WireData implements Module, ConfigurableModule
{
protected string $input_module_color_inputfield = 'InputfieldText';
protected string|int $input_width = '600';
protected string|int $input_height = '400';
protected string|int $input_font_size = '35';
protected string $input_background_color = '#dddddd';
protected string $input_shadow_color = '#ffffff';
protected string|int $input_x_offset = '2';
protected string|int $input_y_offset = '2';
protected string $input_css_class = '';
protected string $input_text_color = '#666666';
protected string $input_font_family = '';
protected array $input_delete_font_family = [];
protected string $pathToFonts = ''; // the path to the font folder of the module
protected string $pathToCustomFonts = ''; // the path to the custom font folder of the module
protected string $altText = ''; // the alternative text for the alt attribute of the image tag
/**
* @return array
*/
public static function getModuleInfo():array
{
return [
'title' => 'Image Placeholder',
'summary' => 'A configurable module for creating placeholder images by using TrueTypeFonts for the placeholder text',
'author' => 'Jürgen Kern',
'autoload' => true,
'singular' => true,
'requires' => 'ProcessWire>=3.0.181, PHP>=8.1.0',
'href' => 'https://github.com/juergenweb/JkImagePlaceholder',
'icon' => 'image',
'version' => '1.5.2'
];
}
/**
* @throws WireException
*/
public function __construct()
{
parent::__construct();
// create a property of each item according to the configuration setting from DB
foreach ($this->wire('modules')->getConfig($this) as $key => $value) {
$this->$key = $value;
}
// set the default alternative text for the alt attribute of the image tag in multi-language
$this->setAltText($this->_('Placeholder image'));
// set path to the default font folder inside this module directory
$this->pathToFonts = $this->wire('config')->paths->$this . 'fonts/';
// set path to the custom font folder
$this->pathToCustomFonts = $this->wire('config')->paths->assets . 'files/JkImagePlaceholder/';
}
/**
* These are the default values that will be saved in the db during the installation process
* @return array
*/
public static function getDefaultData():array
{
return [
'input_module_color_inputfield' => 'InputfieldText',
'input_width' => 600,
'input_height' => 400,
'input_font_size' => 35,
'input_background_color' => '#dddddd',
'input_shadow_color' => '#ffffff',
'input_x_offset' => 2,
'input_y_offset' => 2,
'input_css_class' => '',
'input_text_color' => '#666666',
'input_font_family' => '',
'font_files' => [],
'input_text' => ''
];
}
/**
* @return void
* @throws WireException
*/
public function init():void
{
$this->addHookBefore('InputfieldColorPicker::render', $this, 'removeHashtag');
$this->addHookAfter("Inputfield::processInput", $this, "sanitizeValidateColorField");
$this->addHookAfter('InputfieldFile::fileAdded', $this, 'addFont');
$this->addHookBefore('Modules::saveConfig', $this, 'deleteFonts');
$this->addHookBefore('ProcessModule::executeEdit', $this, 'scanProject');
// add CSS for fonts to the backend if it exists
$version = $this->getModuleInfo()['version'] . '-' . time();
$this->wire('config')->styles->add($this->wire('config')->urls->siteModules . 'JkImagePlaceholder/assets/jkimageplaceholderfont.css?v=' . $version);
}
/**
* Method to remove the leading hashtag from color values
* This is only needed if FieldtypeColorPicker is used for color inputs
* @param HookEvent $event
* @return void
*/
public function removeHashtag(HookEvent $event):void
{
$field = $event->object;
$color_fields = ['input_background_color', 'input_text_color', 'input_shadow_color'];
if (in_array($field->name, $color_fields)) {
$value = $field->attributes['value'];
$field->value = $field->swatch = ltrim($value, '#');
}
}
/**
* Convert absolute path into relative url
* @param string $filename
* @param null $extension
* @return string
*/
protected function pwPath2url(string $filename, $extension = null):string
{
$filename = str_replace('\\', '/', $filename);
$info = pathinfo($filename);
$dir = str_replace(wire('config')->paths->root, wire('config')->urls->root, $info['dirname'] . '/');
return $dir . $info['filename'] . '.' . (is_string($extension) ? $extension : $info['extension']);
}
/**
* Find all ttf fonts inside the project that can be used for the placeholder text
* Scans the complete project for TrueTypeFonts and returns all files as an array
* with path to the font as key and font name as value
* @return array
* @throws WireException
*/
protected function findAllFontfiles():array
{
$files = [];
$results = $this->wire('files')->find($this->wire('config')->paths->root,
['recursive' => true, 'extensions' => ['ttf', 'TTF']]);
if ($results) {
foreach ($results as $pathToFont) {
// exclude FontAwesome and Entypo ttf icons
if (!str_contains($pathToFont, 'fontawesome') && !str_contains($pathToFont, 'entypo')) {
$files[$this->pwPath2url($pathToFont)] = ucfirst(pathinfo($pathToFont, PATHINFO_BASENAME));
}
}
}
return array_unique($files);
}
/**
* Minify CSS string to be a one-liner
* @param string $css
* @return string
*/
protected function minimizeCSSsimple(string $css):string
{
$css = preg_replace('/\/\*((?!\*\/).)*\*\//', '', $css); // negative look ahead
$css = preg_replace('/\s{2,}/', ' ', $css);
$css = preg_replace('/\s*([:;{}])\s*/', '$1', $css);
return preg_replace('/;}/', '}', $css);
}
/**
* Creates a CSS file that includes the CSS for all TrueTypeFonts
* @param array $results - array that holds all fonts with key = path, value = font name
* @param bool $minify - true: CSS will be minified (default), false: not minified (for dev)
* @return void
* @throws WireException
*/
protected function createCSSFile(array $results, bool $minify = true):void
{
if ($results) {
$date_time_format = $this->wire('config')->dateFormat;
$current_date_time = $this->wire('datetime')->date($date_time_format);
$css = '
/*
This CSS file was created automatically by the JkImagePlaceholder module
It contains the CSS for all TrueTypeFonts found in the whole project
Creation date: ' . $current_date_time . '
*/
';
foreach ($results as $pathToFont => $fontfile) {
$font_name = strtolower(str_ireplace('.ttf', '', $fontfile));
//create the css
$css .= '
@font-face {
font-family: ' . $font_name . ';
src: url(\'' . $pathToFont . '\');
}
.css-' . $font_name . ' {
font-family: ' . $font_name . ';
}
';
}
if ($minify) {
$css = $this->minimizeCSSsimple($css); // minify CSS file
}
// write css to file
if ($this->wire('files')->filePutContents($this->wire('config')->paths->$this . 'assets/jkimageplaceholderfont.css',
$css)) {
$this->wire('session')->message($this->_('CSS file for the TrueTypeFonts was recreated due to changes.'));
}
}
}
/**
* Save the new font in the database and recreate the CSS-file
* @param HookEvent $event
* @return void
* @throws WireException
*/
protected function addFont(HookEvent $event):void
{
if ($event->object->name === 'input_font_upload') {
// get all font TTF-files in the custom fonts directory of this module
$ttf_files = $this->wire('files')->find($this->pathToCustomFonts, ['extensions' => ['ttf', 'TTF']]);
$filesInDir = [];
// create new array for $filesInDir which can be merged with $this->font_files afterwards
array_walk($ttf_files, function ($value) use (&$filesInDir) {
$filesInDir[$this->pwPath2url($value)] = ucfirst(pathinfo($value, PATHINFO_BASENAME));
});
$this->wire('session')->set('addfonts', array_merge($this->font_files, $filesInDir));
}
}
/**
* Delete one or more custom uploaded fonts
* @param HookEvent $event
* @return void
* @throws WireException
*/
protected function deleteFonts(HookEvent $event):void
{
$data = $event->arguments(1);
if ($event->arguments(0) === 'JkImagePlaceholder') {
//check if a new font has been uploaded
$font_session = $this->wire('session')->get('addfonts');
// add the new font file from the addFont() method to the data array for storing it in the db afterwards
if ($font_session) {
$diff = array_diff($font_session,
array_map('ucfirst', $this->font_files)); // get the recently uploaded file(s)
$this->message(sprintf($this->_('The following font has been uploaded and saved inside the database: %s'),
implode(', ', array_map("ucfirst",
$diff)))); // array_map is for future purposes if more than 1 font will be uploaded at once
$data['font_files'] = $this->wire('session')->get('addfonts');
$this->createCSSFile($data['font_files']); // re-create the CSS file
}
$this->wire('session')->remove('addfonts');
// check if files were marked to delete
if (isset($_POST['input_delete_font_family'])) {
$labels = [];
$files = $data['font_files']; // all files as stored inside the database
foreach ($data['input_delete_font_family'] as $font) {
$font_name = ucfirst(pathinfo($font, PATHINFO_BASENAME));
// check if a font file is selected for deletion that is selected as default font family
if ($this->input_font_family == $this->pwPath2url($font)) {
$this->wire('session')->warning(sprintf($this->_('The font %s cannot be deleted, because it was set as the default font.'),
$font_name));
} else {
// delete font file
if ($this->wire('files')->unlink($font)) {
// remove the files from the database too
unset($files[$this->pwPath2url($font)]);
$labels[] = $font_name;
}
}
}
$data['font_files'] = $files;
if ($labels) {
$this->wire('session')->message(sprintf($this->_('The following fonts have been deleted: %s'),
implode(', ', $labels)));
}
$this->createCSSFile($data['font_files']); // re-create the CSS file
}
$event->arguments(1, $data);
}
}
/**
* Search the whole project for TrueTypeFonts, save them inside the database and re-create the CSS file
* @return array
* If the array is empty means that no changes have been found
* If the array key is positive (>0) means that more files were found as stored inside the database
* If the array key is negative (0<) means that fewer files were found as stored inside the database
* If changes have been found - the CSS file will be recreated and the values will be stored in the database
* @throws WireException
*/
protected function searchAndSave():array
{
$result = [];
$fonts_found = $this->findAllFontfiles();
$fonts_db = $this->font_files;
// First check if both arrays are identical
if (($fonts_found !== $fonts_db)) {
// check if more fonts were found (positive result) or fewer fonts were found (negative result)
$diff = count($fonts_found) - count($fonts_db);
if (wire('modules')->saveConfig($this, 'font_files', $fonts_found)) {
// create CSS file
$this->createCSSFile($fonts_found);
// set positive or negative result as key and the font names as values
if ($diff > 0) { // more fonts were found
$value = array_diff($fonts_found, $fonts_db);
} else { // fewer fonts were found
$value = array_diff($fonts_db, $fonts_found);
}
$result = [$diff => $value];
}
}
// set property font_files
$this->font_files = $fonts_found;
return $result;
}
/**
* Scan the whole project to find new fonts if the refresh button was pressed
* @return void
* @throws WireException
*/
protected function scanProject():void
{
if ($this->input->post->input_submit_refreshFonts_jkimageplaceholder) {
// save all values first
$data = $this->wire('modules')->getConfig($this); // get values from the database
// cut of the last 4 post values from post array
$post_values = array_slice($this->wire('input')->post()->getArray(), 0, -4);
// save all post data
foreach ($post_values as $name => $value) {
$data[$name] = $value;
// set the values back to the form
$this->$name = $value;
}
// check if font selected is still present - otherwise set default font as value
if (!array_key_exists($this->wire('input')->post('input_font_family'), $this->findAllFontfiles())) {
$data['input_font_family'] = $this->pwPath2url($this->pathToFonts . 'fjallaone-regular.ttf');
$this->input_font_family = $data['input_font_family']; // set it back to the config form
$this->warning($this->_('The font family you have chosen was not found. Instead "FjallaOne-Regular" was set as default family.'));
}
// save the config data to the db before going on to find new fonts
wire('modules')->saveConfig($this, $data);
$result = $this->searchAndSave(); // output a number if higher or lower or equal 0
if ($result) { // number is higher or lower than 0
if (key($result) > 0) {
// more fonts were found
$this->message(sprintf($this->_('The whole project has been scanned, and the following new TrueTypeFonts were found and added to the selectable font families: %s'),
implode(', ', $result[key($result)])));
} else {
// fewer fonts were found
$this->message(sprintf($this->_('The whole project has been scanned, and the following TrueTypeFonts are no longer present and were removed from the database: %s'),
implode(', ', $result[key($result)])));
}
} else {
// number is equal 0, which means no changes at all
$this->message($this->_('The whole project has been scanned, but no new TrueTypeFonts were found.'));
}
}
}
/**
* Validate field value if it is in hexadecimal format (# as first letter)
* @param HookEvent $event
* @return void
* @throws Exception
*/
public function sanitizeValidateColorField(HookEvent $event):void
{
$inputfield = $event->object;
$color_fields = ['input_background_color', 'input_text_color', 'input_shadow_color'];
if (in_array($inputfield->name, $color_fields)) {
if ($inputfield->value) {
// sanitize hashtags by removing all hashtags first
$val = str_replace('#', '', $inputfield->value);
$inputfield->value = '#' . $val; // add # at the beginning
if (!$this->validateHexadecimal($inputfield->value)) {
$inputfield->error($this->_("Only valid hexadecimal values are allowed. They must start with # and can only consist of 3 (shorthand syntax) or 6 letters and numbers."));
} else {
if (strlen($inputfield->value) == 4) { // shorthand syntax
$letters = ltrim($inputfield->value, '#');
$inputfield->value = '#' . $letters . $letters; // create long syntax
}
}
}
}
}
/**
* Check if entered color code is in hexadecimal format (# as first letter)
* @param string $hexadecimal
* @return bool
*/
private function validateHexadecimal(string $hexadecimal):bool
{
$hex = ltrim($hexadecimal, '#');
if ((strlen($hex) == 3) || (strlen($hex) == 6)) {
return ctype_xdigit($hex);
}
return false;
}
/**
* Check if hashtag (#) is present
* If not, add one before out-putting
* This method is necessary, because Color-picker saves the HEX value without the hashtag # in the db
* @param string|NULL $color
* @return string|null
*/
protected function addHashTagToString(string|null $color = null):?string
{
if (($color) && ($color[0] != '#')) {
$color = '#' . $color;
}
return $color;
}
/**
* Helper method for sanitizing hexadecimal colors
* checks for correct hexadecimal color code first and change short notation to default notation (fe. #f0e to #ff00ee)
* @param string|null $hexcolor
* @return string
* @throws Exception
*/
private function sanitizeHex(string $hexcolor = null):string
{
if ($hexcolor) {
$color = trim($hexcolor);
if ($this->validateHexadecimal($color)) {
// check if # is present, otherwise add it
if (!str_starts_with($color, '#')) {
$color = '#' . $color;
}
$number = strlen($color);
switch ($number) {
case ($number === 4):
//shorthand syntax is used (fe #fc9) -> so double every letter -> #ffcc99
$first = substr($color, -3, 1);
$second = substr($color, -2, 1);
$third = substr($color, -1);
$color = '#' . $first . $first . $second . $second . $third . $third;
break;
case ($number < 7):
//no shorthand syntax is used but syntax is not correct - add a fallback to generate hex color with 6 times the same letter
$lastLetter = substr($color, -1);
$color = str_pad($color, 7, $lastLetter);
break;
case ($number > 7):
// remove all letters after the 7. position
$color = substr($color, 0, 7);
break;
default:
}
return $color;
} else {
throw new Exception($this->_("Only valid hexadecimal values are allowed. They must start with # and can only consist of 3 (shorthand syntax) or 6 letters and numbers."));
}
} else {
return '';
}
}
/**
* Set the width of the placeholder image
* @param int $width (fe 400); required value
* @return self
*/
public function setWidth(int $width):self
{
if ($width > 0) {
$this->input_width = $width;
}
return $this;
}
/**
* Get the width of the placeholder image
* @return int
*/
public function getWidth():int
{
return (int)$this->input_width;
}
/**
* Set the Height of the placeholder image
* @param int $height (fe 300)
* @return self
*/
public function setHeight(int $height):self
{
if ($height > 0) {
$this->input_height = $height;
}
return $this;
}
/**
* Get the height of the placeholder image
* @return int
*/
public function getHeight():int
{
return (int)$this->input_height;
}
/**
* Set the background color of the placeholder image
* If nothing is entered (null) means that the background is transparent
* @param string|null $backgroundColor
* @return self
* @throws Exception
*/
public function setBackgroundColor(?string $backgroundColor = null):self
{
if ($backgroundColor) {
$backgroundColor = $this->sanitizeHex($backgroundColor);
}
$this->input_background_color = $backgroundColor;
return $this;
}
/**
* Get the background color of the placeholder image
* @return string|null
*/
public function getBackgroundColor():?string
{
return $this->addHashTagToString($this->input_background_color);
}
/**
* Set the CSS class of the placeholder image
* @param string $css_class
* @return self
*/
public function setCSSClass(string $css_class):self
{
$this->input_css_class = $css_class;
return $this;
}
/**
* Get the CSS class of the placeholder image
* @return string|null
*/
public function getCSSClass():?string
{
return $this->input_css_class;
}
/**
* Set the text color of the placeholder image
* @param string $textColor
* @return self
* @throws Exception
*/
public function setTextColor(string $textColor):self
{
$this->input_text_color = $this->sanitizeHex($textColor);
return $this;
}
/**
* Get the text color of the placeholder image
* @return string
*/
protected function getTextColor():string
{
return $this->addHashTagToString($this->input_text_color);
}
/**
* Set the text shadow color for the placeholder image
* If no shadow color is set (null) means that the shadow is disabled
* @param string|null $shadowColor
* @return self
* @throws Exception
*/
public function setShadowColor(?string $shadowColor = null):self
{
if ($shadowColor) {
$shadowColor = $this->sanitizeHex($shadowColor);
}
$this->input_shadow_color = $shadowColor;
return $this;
}
/**
* Get the text shadow color for the placeholder image
* @return string|null
*/
protected function getShadowColor():?string
{
return $this->input_shadow_color;
}
/**
* Set the x-offset for the text shadow
* @param int $xoffset
* @return $this
*/
public function setXOffset(int $xoffset):self
{
$this->input_x_offset = $xoffset;
return $this;
}
/**
* Get the x-offset for the text shadow
* @return int
*/
protected function getXOffset():int
{
return $this->input_x_offset;
}
/**
* Set the y-offset for the text shadow
* @param int $yoffset
* @return $this
*/
public function setYOffset(int $yoffset):self
{
$this->input_y_offset = $yoffset;
return $this;
}
/**
* Get the y-offset for the text shadow
* @return int
*/
protected function getYOffset():int
{
return $this->input_y_offset;
}
/**
* Set the text of the placeholder image
* @param string|null $text
* @return self
*/
public function setText(?string $text = null):self
{
if (($text != null) || ($text != '')) {
$text = trim($text);
}
$this->input_text = $text;
return $this;
}
/**
* Get the text of the placeholder image depending on the user language
* @return string|null
* @throws WireException
*/
public function getText():?string
{
if ($this->wire('modules')->isInstalled('LanguageSupport')) {
// grab current user lang
if ($this->wire('user')->language->id == $this->wire('languages')->getDefault()->id) {
$text = $this->input_text;
} else {
$langID = $this->wire('user')->language;
$textLang = 'input_text__' . $langID;
$text = $this->$textLang;
}
} else {
$text = $this->input_text;
}
return $text;
}
/**
* Set the font size for the placeholder text
* @param int $fontsize
* @return self
*/
public function setFontSize(int $fontsize):self
{
if ($fontsize > 0) {
$this->input_font_size = $fontsize;
}
return $this;
}
/**
* Get the default fontsize of the placeholder text
* @return float
*/
public function getFontSize():float
{
return (float)$this->input_font_size;
}
/**
* Set the font family for the placeholder text
* @param string $fontfamily
* @return self
* @throws Exception
*/
public function setFontFamily(string $fontfamily):self
{
$rawfontfamily = $fontfamily;
$fontfamily = strtolower(trim($fontfamily));
if (!str_ends_with($fontfamily, '.ttf')) {
$fontfamily = $fontfamily . '.ttf'; // add the extension
}
// convert all uppercase letters to lowercase
$fontfiles = array_map('strtolower', $this->getFontFiles());
// check if file exists inside the database
$key = array_search($fontfamily, $fontfiles);
if ($key) {
// check if physical file exists under the given path too
if ($this->wire('files')->exists($this->wire('config')->paths->root . $key)) {
$this->input_font_family = $key;
} else {
// start a new site search and update all fonts
$this->searchAndSave();
}
} else {
$this->searchAndSave(); // do a site search first
// convert all uppercase letters to lowercase
$fontfiles = array_map('strtolower', $this->getFontFiles());
// check if file exists inside the database
$key = array_search($fontfamily, $fontfiles);
if ($key) {
$this->input_font_family = $key;
} else {
throw new Exception(sprintf($this->_('The font %s does not exist! Please select another one or check if your spelling is wrong and causes this error. Possible fonts to select are: %s.'),
$rawfontfamily, implode(', ', $this->getFontFiles())));
}
}
return $this;
}
/**
* Get the absolute path to font family of the placeholder text
* @param bool $absolutePath
* @return string
*/
public function getFontFamily(bool $absolutePath = false):string
{
$path = wire('config')->paths->root . $this->input_font_family;
if (!$absolutePath) {
$path = $this->input_font_family;
}
return $path;
}
/**
* Return array of all font files with name as key and path to the file as value
* @return array
*/
public function getFontFiles():array
{
if ($this->font_files) {
return $this->font_files;
}
return [];
}
/**
* Create an array of all ttf files for the select options
* @return array - returns each array item in the format ['font-file-name' => 'font name']
*/
private function createFontFamilySelect():array
{
$selectOptions = [];
foreach ($this->getFontFiles() as $k => $v) {
$selectOptions[$k] = ucwords($v);
}
return $selectOptions;
}
/**
* Get all custom uploaded fonts inside the custom font folder of this module
* @return array
* @throws WireException
*/
protected function getAllCustomFonts():array
{
$result = $this->wire('files')->find($this->pathToCustomFonts, ['extensions' => 'ttf', 'TTF']);
$fonts = [];
foreach ($result as $path) {
$fonts[$path] = pathinfo($path, PATHINFO_BASENAME);
}
return $fonts;
}
/**
* Set the alternative text for the alt attribute of the image tag
* @param string $altText
* @return $this
*/
public function setAltText(string $altText):self
{
$this->altText = $altText;
return $this;
}
/**
* Get the alternative text of the alt attribute of the image text
* @return string
*/
public function getAltText():string
{
return $this->altText;
}
/**
* Render the image src or the complete image tag
* @param bool $tag - true: tag will be rendered, false: only the src will be returned (default)
* @return string
* @throws WireException
*/
public function render(bool $tag = false):string
{
if (empty($this->getHeight())) {
$this->setHeight($this->getWidth()); // make squared image
}
// Create the image
$image = imagecreatetruecolor($this->getWidth(), $this->getHeight());
// Set the background color of image
if ($this->getBackgroundColor()) {
list($r, $g, $b) = sscanf($this->getBackgroundColor(), '#%02x%02x%02x');
$background_color = imagecolorallocate($image, $r, $g, $b);
// Fill background with above selected color
imagefilledrectangle($image, 0, 0, $this->getWidth(), $this->getHeight(), $background_color);
} else {
// Transparent Background
imagealphablending($image, false);
$transparency = imagecolorallocatealpha($image, 0, 0, 0, 127);
imagefill($image, 0, 0, $transparency);
imagesavealpha($image, true);
}
if (!is_null($this->input_text)) {
// set the text color for the image text
list($r, $g, $b) = sscanf($this->getTextColor(), '#%02x%02x%02x');
$text_color = imagecolorallocate($image, $r, $g, $b);
if (array_key_exists($this->getFontFamily(), $this->getFontFiles())) {
if ($this->getText()) {
$text = $this->getText();
// get the coordinates for width and height of the text in pixel
$coordinates = imagettfbbox($this->getFontSize(), 0, $this->getFontFamily(true), $text);
// Center text horizontally
$center = ceil($this->getWidth() / 2);
$x = (int)($center - (ceil($coordinates[4] / 2)));
// Center text vertically
$center = ceil($this->getHeight() / 2);
$y = (int)($center - (ceil($coordinates[7] / 2)));
if ($this->getShadowColor()) {
// Draw the shadow for the text if set
list($rs, $gs, $bs) = sscanf($this->getShadowColor(), '#%02x%02x%02x');
$shadow_color = imagecolorallocate($image, $rs, $gs, $bs);
imagettftext($image, $this->getFontSize(), 0, $x + $this->getXOffset(),
$y + $this->getYOffset(), $shadow_color, $this->getFontFamily(true), $text);
}
// Draw text string
imagettftext($image, $this->getFontSize(), 0, $x, $y, $text_color, $this->getFontFamily(true),
$text);
}
}
}
ob_start();
imagepng($image);
$contents = ob_get_contents();
ob_end_clean();
imagedestroy($image);
$html = 'data:image/png;base64,' . base64_encode($contents);
$class = ($this->getCSSClass()) ? ' class="' . $this->getCSSClass() . '"' : '';
if ($tag) {
$html = '<img' . $class . ' src="' . $html . '" width="' . $this->getWidth() . 'px" height="' . $this->getHeight() . 'px" alt="' . $this->getAltText() . '" />';
}
return $html;
}
/**
* Method to set multi-language value to a multi-language configuration field
* @param string $inputfield_name
* @param object $fieldObject
* @return void
* @throws WireException
*/
protected function setLanguageValue(string $inputfield_name, object $fieldObject):void
{
$languages = $this->wire('languages');
if ($languages) { // check if multi-lang site
$fieldObject->useLanguages = true;
foreach ($languages as $language) {
if ($language->isDefault()) {
$fieldObject->set('value', (string)$this->get($inputfield_name));
} else {
$fieldObject->set("value$language", (string)$this->get($inputfield_name . '__' . $language->id));
}
}
}
}
/**
* Config input fields
* @param InputfieldWrapper $inputfields
* @return InputfieldWrapper
* @throws WireException
* @throws WirePermissionException
*/
public function getModuleConfigInputfields(InputfieldWrapper $inputfields):InputfieldWrapper
{
$markup = InputfieldWrapper::getMarkup();
if (($this->wire('modules')->isInstalled('FieldtypeColor')) || ($this->wire('modules')->isInstalled('FieldtypeColorPicker'))) {
$options = [
'InputfieldText' => 'InputfieldText'
];
if ($this->wire('modules')->isInstalled('FieldtypeColorPicker')) {
$options['InputfieldColorPicker'] = 'FieldtypeColorPicker';
}
if ($this->wire('modules')->isInstalled('FieldtypeColor')) {
$options['InputfieldColor'] = 'FieldtypeColor';
}
/* @var InputfieldSelect $f */
$f = $this->modules->get('InputfieldSelect');
$f->attr('id+name', 'input_module_color_inputfield');
$f->label = $this->_('Select the inputfield for colors');
$f->addOptions($options);
$f->notes = $this->_('Please select your preferred input type for color input fields.');
$f->value = $this->input_module_color_inputfield;
$f->required = true;
$inputfields->add($f);
}
$sizesFieldset = $this->wire('modules')->get('InputfieldFieldset');
$sizesFieldset->label = $this->_('Global dimensions');
$sizesFieldset->collapsed = true;
$sizesFieldset->columnWidth = 100;
/* @var InputfieldInteger $f */