/
DcaUtil.php
1674 lines (1391 loc) · 63.6 KB
/
DcaUtil.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
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
/*
* Copyright (c) 2021 Heimrich & Hannot GmbH
*
* @license LGPL-3.0-or-later
*/
namespace HeimrichHannot\UtilsBundle\Dca;
use Contao\BackendUser;
use Contao\Config;
use Contao\Controller;
use Contao\CoreBundle\Framework\ContaoFrameworkInterface;
use Contao\Database;
use Contao\DataContainer;
use Contao\DcaExtractor;
use Contao\DiffRenderer;
use Contao\FrontendUser;
use Contao\Image;
use Contao\Input;
use Contao\Model;
use Contao\RequestToken;
use Contao\StringUtil;
use Contao\System;
use Contao\Validator;
use Doctrine\DBAL\Connection;
use HeimrichHannot\UtilsBundle\Driver\DC_Table_Utils;
use HeimrichHannot\UtilsBundle\Routing\RoutingUtil;
use Symfony\Component\DependencyInjection\ContainerInterface;
class DcaUtil
{
const PROPERTY_SESSION_ID = 'sessionID';
const PROPERTY_AUTHOR = 'author';
const PROPERTY_AUTHOR_TYPE = 'authorType';
const AUTHOR_TYPE_NONE = 'none';
const AUTHOR_TYPE_MEMBER = 'member';
const AUTHOR_TYPE_USER = 'user';
/** @var ContaoFrameworkInterface */
protected $framework;
/**
* @var ContainerInterface
*/
protected $container;
/**
* @var RoutingUtil
*/
private $routingUtil;
/**
* @var Connection
*/
private $connection;
public function __construct(ContainerInterface $container, ContaoFrameworkInterface $framework, RoutingUtil $routingUtil, Connection $connection)
{
$this->container = $container;
$this->framework = $framework;
$this->routingUtil = $routingUtil;
$this->connection = $connection;
}
/**
* Get a contao backend modal edit link.
*
* @param string $module Name of the module
* @param int $id Id of the entity
* @param string|null $label The label text
*
* @return string The edit link
*/
public function getEditLink(string $module, int $id, string $label = null): string
{
$url = $this->container->get('huh.utils.url')->getCurrentUrl([
'skipParams' => true,
]);
if (!$id) {
return '';
}
$label = sprintf(StringUtil::specialchars($label ?: $GLOBALS['TL_LANG']['tl_content']['editalias'][1]), $id);
return sprintf(
' <a href="'.$url.'?do=%s&act=edit&id=%s&rt=%s" title="%s" style="padding-left: 5px; padding-top: 2px; display: inline-block;">%s</a>',
$module,
$id,
$this->container->get('security.csrf.token_manager')->getToken($this->container->getParameter('contao.csrf_token_name'))->getValue(),
$label,
Image::getHtml('alias.svg', $label, 'style="vertical-align:top"')
);
}
/**
* Get a contao backend modal edit link.
*
* @param string $module Name of the module
* @param int $id Id of the entity
* @param string|null $label The label text
* @param string $table The dataContainer table
* @param int $width The modal window width
*
* @return string The modal edit link
*
* @deprecated Use DcaUtil::getPopupWizardLink() instead
*/
public function getModalEditLink(string $module, int $id, string $label = null, string $table = '', int $width = 1024): string
{
$url = $this->container->get('huh.utils.url')->getCurrentUrl([
'skipParams' => true,
]);
if (!$id) {
return '';
}
$label = sprintf(StringUtil::specialchars($label ?: $GLOBALS['TL_LANG']['tl_content']['editalias'][1]), $id);
return sprintf(
' <a href="'.$url.'?do=%s&act=edit&id=%s%s&popup=1&nb=1&rt=%s" title="%s" '
.'style="padding-left: 5px; padding-top: 2px; display: inline-block;" onclick="Backend.openModalIframe({\'width\':%s,\'title\':\'%s'.'\',\'url\':this.href});return false">%s</a>',
$module,
$id,
($table ? '&table='.$table : ''),
$this->container->get('security.csrf.token_manager')->getToken($this->container->getParameter('contao.csrf_token_name'))->getValue(),
$label,
$width,
$label,
Image::getHtml('alias.svg', $label, 'style="vertical-align:top"')
);
}
/**
* Get a contao backend modal archive edit link.
*
* @param string $module Name of the module
* @param int $id Id of the entity
* @param string $table The dataContainer table
* @param string|null $label The label text
* @param int $width The modal window width
*
* @return string The modal archive edit link
*
* @deprecated Use DcaUtil::getPopupWizardLink() instead
*/
public function getArchiveModalEditLink(string $module, int $id, string $table, string $label = null, int $width = 1024): string
{
$url = $this->container->get('huh.utils.url')->getCurrentUrl([
'skipParams' => true,
]);
if (!$id) {
return '';
}
$label = sprintf(StringUtil::specialchars($label ?: $GLOBALS['TL_LANG']['tl_content']['editalias'][1]), $id);
return sprintf(
' <a href="'.$url.'?do=%s&id=%s&table=%s&popup=1&nb=1&rt=%s" title="%s" '
.'style="padding-left:3px; float: right" onclick="Backend.openModalIframe({\'width\':\'%s\',\'title\':\'%s'.'\',\'url\':this.href});return false">%s</a>',
$module,
$id,
$table,
$this->container->get('security.csrf.token_manager')->getToken($this->container->getParameter('contao.csrf_token_name'))->getValue(),
$label,
$width,
$label,
Image::getHtml('alias.svg', $label, 'style="vertical-align:top"')
);
}
/**
* Get a contao backend popup link.
*
* Options:
* - attributes: (array) Link attributes as key value pairs. Will override title and style option. href and onclick are not allowed and will be removed from list.
* - title: (string) Overrride default link title
* - style: (string) Override default css style properties
* - onclick: (string) Override default onclick javascript code
* - icon: (string) Link icon to show as link text. Overrides default icon.
* - linkText: (string) A linkTitle to show as link text. Will be displayed after the link icon. Default empty.
* - url-only: (boolean) Return only url instead of a complete link element
*
* @param array $parameter An array of parameter. Using string is deprecated and will be removed in a future version.
*
* @return string
*/
public function getPopupWizardLink($parameter, array $options = [])
{
if (\is_string($parameter)) {
@trigger_error('Using string as parameter is deprecated and will be removed in a future version.', E_USER_DEPRECATED);
$result = [];
$query = parse_url($parameter, PHP_URL_QUERY);
if (\is_string($query)) {
$parameter = $query;
}
parse_str($parameter, $result);
$parameter = $result;
}
$route = $options['route'] ?? 'contao_backend';
$parameter['popup'] = 1;
$parameter['nb'] = 1;
$url = $this->routingUtil->generateBackendRoute($parameter, true, true, $route);
if (isset($options['url-only']) && true === $options['url-only']) {
return $url;
}
$attributes = [];
if (isset($options['attributes'])) {
$attributes = $options['attributes'];
}
// title
if (!isset($options['title']) || !$options['title']) {
$title = $GLOBALS['TL_LANG']['tl_content']['edit'][0];
} else {
$title = StringUtil::specialchars($options['title']);
}
if (!isset($attributes['title'])) {
$attributes['title'] = $title;
}
// style
$style = !isset($options['style']) ? 'padding-left: 5px; padding-top: 2px; display: inline-block;' : $options['style'];
if (!empty($style) && !isset($attributes['style'])) {
$attributes['style'] = $style;
}
// onclick
if (!isset($options['onclick']) || !$options['onclick']) {
$popupWidth = !isset($options['popupWidth']) || !$options['popupWidth'] ? 991 : $options['popupWidth'];
$popupTitle = !isset($options['popupTitle']) || !$options['popupTitle'] ? $title : $options['popupTitle'];
$onclick = sprintf(
'onclick="Backend.openModalIframe({\'width\':%s,\'title\':\'%s'.'\',\'url\':this.href});return false"',
$popupWidth,
$popupTitle
);
} else {
$onclick = $options['onclick'];
}
if (!isset($attributes['onclick'])) {
$attributes['onclick'] = $onclick;
}
// link text and icon
$linkText = '';
if (!isset($options['icon'])) {
$linkText .= $this->framework->getAdapter(Image::class)->getHtml('alias.svg', $title, 'style="vertical-align:top"');
} elseif (!empty($options['icon'])) {
$linkText = $this->framework->getAdapter(Image::class)->getHtml($options['icon'], $title, 'style="vertical-align:top"');
}
if (isset($options['linkText']) || !empty($options['linkText'])) {
$linkText .= $options['linkText'];
}
// Attributes
$attributeQuery = '';
foreach ($attributes as $key => $value) {
if (\in_array($key, ['href', 'onclick'])) {
continue;
}
$attributeQuery .= $key.'="'.htmlspecialchars($value).'" ';
}
return sprintf(
'<a href="%s" %s %s>%s</a>',
$url,
$attributeQuery,
$onclick,
$linkText
);
}
/**
* Set initial $varData from dca.
*
* @param string $strTable Dca table name
* @param mixed $varData Object or array
*
* @return mixed Object or array with the default values
*/
public function setDefaultsFromDca($strTable, $varData = null, bool $includeSql = false)
{
$this->framework->getAdapter(Controller::class)->loadDataContainer($strTable);
if (empty($GLOBALS['TL_DCA'][$strTable])) {
return $varData;
}
$dbFields = [];
foreach (Database::getInstance()->listFields($strTable) as $data) {
if (!isset($data['default'])) {
continue;
}
$dbFields[$data['name']] = $data['default'];
}
// Get all default values for the new entry
foreach ($GLOBALS['TL_DCA'][$strTable]['fields'] as $k => $v) {
$addDefaultValue = false;
$defaultValue = null;
// check sql definition
if ($includeSql && isset($dbFields[$k])) {
$addDefaultValue = true;
$defaultValue = $dbFields[$k];
}
// check dca default value
if (\array_key_exists('default', $v)) {
$addDefaultValue = true;
$defaultValue = \is_array($v['default']) ? serialize($v['default']) : $v['default'];
}
if (!$addDefaultValue) {
continue;
}
// Encrypt the default value (see #3740)
if ($GLOBALS['TL_DCA'][$strTable]['fields'][$k]['eval']['encrypt']) {
$defaultValue = $this->container->get('huh.utils.encryption')->encrypt($defaultValue);
}
if ($addDefaultValue) {
if (\is_object($varData)) {
$varData->{$k} = $defaultValue;
} else {
if (null === $varData) {
$varData = [];
}
if (\is_array($varData)) {
$varData[$k] = $defaultValue;
}
}
}
}
return $varData;
}
/**
* Retrieves an array from a dca config (in most cases eval) in the following priorities:.
*
* 1. The value associated to $array[$property]
* 2. The value retrieved by $array[$property . '_callback'] which is a callback array like ['Class', 'method'] or ['service.id', 'method']
* 3. The value retrieved by $array[$property . '_callback'] which is a function closure array like ['Class', 'method']
*
* @param $property
*
* @return mixed|null The value retrieved in the way mentioned above or null
*/
public function getConfigByArrayOrCallbackOrFunction(array $array, $property, array $arguments = [])
{
if (isset($array[$property])) {
return $array[$property];
}
if (!isset($array[$property.'_callback'])) {
return null;
}
if (\is_array($array[$property.'_callback'])) {
$callback = $array[$property.'_callback'];
if (!isset($callback[0]) || !isset($callback[1])) {
return null;
}
try {
$instance = Controller::importStatic($callback[0]);
} catch (\Exception $e) {
return null;
}
if (!method_exists($instance, $callback[1])) {
return null;
}
try {
return \call_user_func_array([$instance, $callback[1]], $arguments);
} catch (\Error $e) {
return null;
}
} elseif (\is_callable($array[$property.'_callback'])) {
try {
return \call_user_func_array($array[$property.'_callback'], $arguments);
} catch (\Error $e) {
return null;
}
}
return null;
}
/**
* Sets the current date as the date added -> usually used on submit.
*/
public function setDateAdded(DataContainer $dc)
{
$modelUtil = $this->container->get('huh.utils.model');
if (null === $dc || null === ($model = $modelUtil->findModelInstanceByPk($dc->table, $dc->id)) || $model->dateAdded > 0) {
return null;
}
$this->framework->createInstance(Database::class)->prepare("UPDATE $dc->table SET dateAdded=? WHERE id=? AND dateAdded = 0")->execute(time(), $dc->id);
}
/**
* Sets the current date as the date added -> usually used on copy.
*
* @param $insertId
*/
public function setDateAddedOnCopy($insertId, DataContainer $dc)
{
$modelUtil = $this->container->get('huh.utils.model');
if (null === $dc || null === ($model = $modelUtil->findModelInstanceByPk($dc->table, $insertId)) || $model->dateAdded > 0) {
return null;
}
$this->framework->createInstance(Database::class)->prepare("UPDATE $dc->table SET dateAdded=? WHERE id=? AND dateAdded = 0")->execute(time(), $insertId);
}
/**
* Returns a list of fields as an option array for dca fields.
*
* Possible options:
* - array inputTypes Restrict to certain input types
* - array evalConditions restrict to certain dca eval
* - bool localizeLabels
* - bool skipSorting
*/
public function getFields(string $table, array $options = []): array
{
$fields = [];
if (!$table) {
return $fields;
}
$this->framework->getAdapter(Controller::class)->loadDataContainer($table);
System::loadLanguageFile($table);
if (!isset($GLOBALS['TL_DCA'][$table]['fields'])) {
return $fields;
}
foreach ($GLOBALS['TL_DCA'][$table]['fields'] as $name => $data) {
// restrict to certain input types
if (isset($options['inputTypes']) && \is_array($options['inputTypes']) && !empty($options['inputTypes']) && !\in_array($data['inputType'], $options['inputTypes'])) {
continue;
}
// restrict to certain dca eval
if (isset($options['evalConditions']) && \is_array($options['evalConditions']) && !empty($options['evalConditions'])) {
foreach ($options['evalConditions'] as $key => $value) {
if ($data['eval'][$key] !== $value) {
continue 2;
}
}
}
if (isset($options['localizeLabels']) && !$options['localizeLabels']) {
$fields[$name] = $name;
} else {
$label = $name;
if (isset($data['label'][0]) && $data['label'][0]) {
$label .= ' <span style="display: inline; color:#999; padding-left:3px">['.$data['label'][0].']</span>';
}
$fields[$name] = $label;
}
}
if (!isset($options['skipSorting']) || !$options['skipSorting']) {
asort($fields);
}
return $fields;
}
/**
* Adds an override selector to every field in $fields to the dca associated with $destinationTable.
*/
public function addOverridableFields(array $fields, string $sourceTable, string $destinationTable, array $options = [])
{
$this->framework->getAdapter(Controller::class)->loadDataContainer($sourceTable);
System::loadLanguageFile($sourceTable);
$sourceDca = $GLOBALS['TL_DCA'][$sourceTable];
$this->framework->getAdapter(Controller::class)->loadDataContainer($destinationTable);
System::loadLanguageFile($destinationTable);
$destinationDca = &$GLOBALS['TL_DCA'][$destinationTable];
foreach ($fields as $field) {
// add override boolean field
$overrideFieldname = 'override'.ucfirst($field);
$destinationDca['fields'][$overrideFieldname] = [
'label' => &$GLOBALS['TL_LANG'][$destinationTable][$overrideFieldname],
'exclude' => true,
'inputType' => 'checkbox',
'eval' => ['tl_class' => 'w50', 'submitOnChange' => true, 'isOverrideSelector' => true],
'sql' => "char(1) NOT NULL default ''",
];
if (isset($options['checkboxDcaEvalOverride']) && \is_array($options['checkboxDcaEvalOverride'])) {
$destinationDca['fields'][$overrideFieldname]['eval'] = array_merge($destinationDca['fields'][$overrideFieldname]['eval'], $options['checkboxDcaEvalOverride']);
}
// important: nested selectors need to be in reversed order -> see DC_Table::getPalette()
$destinationDca['palettes']['__selector__'] = array_merge([$overrideFieldname], \is_array($destinationDca['palettes']['__selector__']) ? $destinationDca['palettes']['__selector__'] : []);
// copy field
$destinationDca['fields'][$field] = $sourceDca['fields'][$field];
// subpalette
$destinationDca['subpalettes'][$overrideFieldname] = $field;
if (!isset($options['skipLocalization']) || !$options['skipLocalization']) {
$GLOBALS['TL_LANG'][$destinationTable][$overrideFieldname] = [
$this->container->get('translator')->trans('huh.utils.misc.override.label', [
'%fieldname%' => $GLOBALS['TL_DCA'][$sourceTable]['fields'][$field]['label'][0] ?: $field,
]),
$this->container->get('translator')->trans('huh.utils.misc.override.desc', [
'%fieldname%' => $GLOBALS['TL_DCA'][$sourceTable]['fields'][$field]['label'][0] ?: $field,
]),
];
}
}
}
/**
* Retrieves a property of given contao model instances by *ascending* priority, i.e. the last instance of $instances
* will have the highest priority.
*
* CAUTION: This function assumes that you have used addOverridableFields() in this class!! That means, that a value in a
* model instance is only used if it's either the first instance in $arrInstances or "overrideFieldname" is set to true
* in the instance.
*
* @param string $property The property name to retrieve
* @param array $instances An array of instances in ascending priority. Instances can be passed in the following form:
* ['tl_some_table', $instanceId] or $objInstance
*
* @return mixed
*/
public function getOverridableProperty(string $property, array $instances)
{
$result = null;
$preparedInstances = [];
// prepare instances
foreach ($instances as $instance) {
if (\is_array($instance)) {
if (null !== ($objInstance = $this->container->get('huh.utils.model')->findModelInstanceByPk($instance[0], $instance[1]))) {
$preparedInstances[] = $objInstance;
}
} elseif ($instance instanceof Model || \is_object($instance)) {
$preparedInstances[] = $instance;
}
}
foreach ($preparedInstances as $i => $preparedInstance) {
if (0 == $i || $preparedInstance->{'override'.ucfirst($property)}) {
$result = $preparedInstance->{$property};
}
}
return $result;
}
/**
* This function transforms an entity's palette (that can also contain sub palettes and concatenated type selectors) to a flatten
* palette where every field can be overridden.
*
* CAUTION: This function assumes that you have used addOverridableFields() for adding the fields that are overridable. The latter ones
* are $overridableFields
*
* This function is useful if you want to adjust a palette for sub entities that can override properties of their ancestor(s).
* Use $this->getOverridableProperty() for computing the correct value respecting the entity hierarchy.
*/
public function flattenPaletteForSubEntities(string $table, array $overridableFields)
{
$this->framework->getAdapter(Controller::class)->loadDataContainer($table);
$dca = &$GLOBALS['TL_DCA'][$table];
$arrayUtil = $this->container->get('huh.utils.array');
// palette
foreach ($overridableFields as $field) {
if (true === $dca['fields'][$field]['eval']['submitOnChange']) {
unset($dca['fields'][$field]['eval']['submitOnChange']);
if (\in_array($field, $dca['palettes']['__selector__'])) {
// flatten concatenated type selectors
foreach ($dca['subpalettes'] as $selector => $subPaletteFields) {
if (false !== strpos($selector, $field.'_')) {
if ($dca['subpalettes'][$selector]) {
$subPaletteFields = explode(',', $dca['subpalettes'][$selector]);
foreach (array_reverse($subPaletteFields) as $subPaletteField) {
$dca['palettes']['default'] = str_replace($field, $field.','.$subPaletteField, $dca['palettes']['default']);
}
}
// remove nested field in order to avoid its normal "selector" behavior
$arrayUtil->removeValue($field, $dca['palettes']['__selector__']);
unset($dca['subpalettes'][$selector]);
}
}
// flatten sub palettes
if (isset($dca['subpalettes'][$field]) && $dca['subpalettes'][$field]) {
$subPaletteFields = explode(',', $dca['subpalettes'][$field]);
foreach (array_reverse($subPaletteFields) as $subPaletteField) {
$dca['palettes']['default'] = str_replace($field, $field.','.$subPaletteField, $dca['palettes']['default']);
}
// remove nested field in order to avoid its normal "selector" behavior
$arrayUtil->removeValue($field, $dca['palettes']['__selector__']);
unset($dca['subpalettes'][$field]);
}
}
}
$dca['palettes']['default'] = str_replace($field, 'override'.ucfirst($field), $dca['palettes']['default']);
}
}
/**
* Return if the current alias already exist in table.
*
* @throws \Doctrine\DBAL\DBALException
*/
public function aliasExist(string $alias, int $id, string $table, $options = []): bool
{
$aliasField = $options['aliasField'] ?? 'alias';
$stmt = $this->connection->prepare('SELECT id FROM '.$table.' WHERE '.$aliasField.'=? AND id!=?');
$stmt->execute([$alias, $id]);
return $stmt->rowCount() > 0;
}
/**
* Generate an alias with unique check.
*
* @param mixed $alias The current alias (if available)
* @param int $id The entity's id
* @param string|null $table The entity's table (pass a comma separated list if the validation should be expanded to multiple tables like tl_news AND tl_member. ATTENTION: the first table needs to be the one we're currently in). Pass null to skip unqiue check.
* @param string $title The value to use as a base for the alias
* @param bool $keepUmlauts Set to true if German umlauts should be kept
*
* @throws \Exception
*
* @return string
*/
public function generateAlias(?string $alias, int $id, ?string $table, string $title, bool $keepUmlauts = true, $options = [])
{
$autoAlias = false;
$aliasField = $options['aliasField'] ?? 'alias';
// Generate alias if there is none
if (empty($alias)) {
$autoAlias = true;
$alias = StringUtil::generateAlias($title);
}
if (!$keepUmlauts) {
$alias = preg_replace(['/ä/i', '/ö/i', '/ü/i', '/ß/i'], ['ae', 'oe', 'ue', 'ss'], $alias);
}
if (null === $table) {
return $alias;
}
$originalAlias = $alias;
// multiple tables?
if (false !== strpos($table, ',')) {
$tables = explode(',', $table);
foreach ($tables as $i => $partTable) {
// the table in which the entity is
if (0 === $i) {
if ($this->aliasExist($alias, $id, $table, $options)) {
if (!$autoAlias) {
throw new \InvalidArgumentException(sprintf($GLOBALS['TL_LANG']['ERR']['aliasExists'], $alias));
}
$alias = $originalAlias.'-'.$id;
}
} else {
// another table
$stmt = $this->connection->prepare("SELECT id FROM {$partTable} WHERE ' . $aliasField . '=?");
$stmt->execute([$alias]);
// Check whether the alias exists
if ($stmt->rowCount() > 0) {
throw new \InvalidArgumentException(sprintf($GLOBALS['TL_LANG']['ERR']['aliasExists'], $alias));
}
}
}
} else {
if (!$this->aliasExist($alias, $id, $table, $options)) {
return $alias;
}
// Check whether the alias exists
if (!$autoAlias) {
throw new \Exception(sprintf($GLOBALS['TL_LANG']['ERR']['aliasExists'], $alias));
}
// Add ID to alias
$alias .= '-'.$id;
}
return $alias;
}
public function addAuthorFieldAndCallback(string $table, string $fieldPrefix = '')
{
$this->framework->getAdapter(Controller::class)->loadDataContainer($table);
// callbacks
$GLOBALS['TL_DCA'][$table]['config']['oncreate_callback']['setAuthorIDOnCreate'] = ['huh.utils.dca', 'setAuthorIDOnCreate'];
$GLOBALS['TL_DCA'][$table]['config']['onload_callback']['modifyAuthorPaletteOnLoad'] = ['huh.utils.dca', 'modifyAuthorPaletteOnLoad', true];
// fields
$GLOBALS['TL_DCA'][$table]['fields'][$fieldPrefix ? $fieldPrefix.ucfirst(static::PROPERTY_AUTHOR_TYPE) : static::PROPERTY_AUTHOR_TYPE] = [
'label' => &$GLOBALS['TL_LANG']['MSC']['utilsBundle']['authorType'],
'exclude' => true,
'filter' => true,
'default' => static::AUTHOR_TYPE_NONE,
'inputType' => 'select',
'options' => [
static::AUTHOR_TYPE_NONE,
static::AUTHOR_TYPE_MEMBER,
static::AUTHOR_TYPE_USER,
],
'reference' => $GLOBALS['TL_LANG']['MSC']['utilsBundle']['authorType'],
'eval' => ['doNotCopy' => true, 'submitOnChange' => true, 'mandatory' => true, 'tl_class' => 'w50 clr'],
'sql' => "varchar(255) NOT NULL default 'none'",
];
$GLOBALS['TL_DCA'][$table]['fields'][$fieldPrefix ? $fieldPrefix.ucfirst(static::PROPERTY_AUTHOR) : static::PROPERTY_AUTHOR] = [
'label' => &$GLOBALS['TL_LANG']['MSC']['utilsBundle']['author'],
'exclude' => true,
'search' => true,
'filter' => true,
'inputType' => 'select',
'options_callback' => function () {
return $this->container->get('huh.utils.choice.model_instance')->getCachedChoices([
'dataContainer' => 'tl_member',
'labelPattern' => '%firstname% %lastname% (ID %id%)',
]);
},
'eval' => [
'doNotCopy' => true,
'chosen' => true,
'includeBlankOption' => true,
'tl_class' => 'w50',
],
'sql' => "int(10) unsigned NOT NULL default '0'",
];
}
public function setAuthorIDOnCreate(string $table, int $id, array $row, DataContainer $dc)
{
$model = $this->container->get('huh.utils.model')->findModelInstanceByPk($table, $id);
/** @var Database $db */
$db = $this->framework->createInstance(Database::class);
if (null === $model
|| !$db->fieldExists(static::PROPERTY_AUTHOR_TYPE, $table)
|| !$db->fieldExists(static::PROPERTY_AUTHOR, $table)) {
return false;
}
if ($this->container->get('huh.utils.container')->isFrontend()) {
if (FE_USER_LOGGED_IN) {
$model->{static::PROPERTY_AUTHOR_TYPE} = static::AUTHOR_TYPE_MEMBER;
$model->{static::PROPERTY_AUTHOR} = $this->framework->getAdapter(FrontendUser::class)->getInstance()->id;
$model->save();
}
} else {
$model->{static::PROPERTY_AUTHOR_TYPE} = static::AUTHOR_TYPE_USER;
$model->{static::PROPERTY_AUTHOR} = $this->framework->getAdapter(BackendUser::class)->getInstance()->id;
$model->save();
}
}
public function modifyAuthorPaletteOnLoad(DataContainer $dc)
{
if (!$this->container->get('huh.utils.container')->isBackend()) {
return false;
}
if (null === $dc || !$dc->id || !$dc->table) {
return false;
}
if (null === ($model = $this->container->get('huh.utils.model')->findModelInstanceByPk($dc->table, $dc->id))) {
return false;
}
$dca = &$GLOBALS['TL_DCA'][$dc->table];
// author handling
if ($model->{static::PROPERTY_AUTHOR_TYPE} == static::AUTHOR_TYPE_NONE) {
unset($dca['fields']['author']);
}
if ($model->{static::PROPERTY_AUTHOR_TYPE} == static::AUTHOR_TYPE_USER) {
$dca['fields']['author']['options_callback'] = function () {
return $this->container->get('huh.utils.choice.model_instance')->getCachedChoices([
'dataContainer' => 'tl_user',
'labelPattern' => '%name% (ID %id%)',
]);
};
}
}
/**
* Returns (nearly) all registered datacontainers as array.
*
* Options:
* - bool onlyTableType: Return only table data containers
*
* @return array
*/
public function getDataContainers(array $options = [])
{
$dcaTables = $this->framework->createInstance(Database::class)->listTables();
if (isset($options['onlyTableType']) && true === $options['onlyTableType']) {
return $dcaTables;
}
foreach ($GLOBALS['BE_MOD'] as $arrSection) {
foreach ($arrSection as $strModule => $arrModule) {
foreach ($arrModule as $strKey => $varValue) {
if (\is_array($arrModule['tables'])) {
$dcaTables = array_merge($dcaTables, $arrModule['tables']);
}
}
}
}
$dcaTables = array_unique($dcaTables);
asort($dcaTables);
return array_values($dcaTables);
}
/**
* @param bool $includeNotificationCenterPlusTokens
*
* @return array
*/
public function getNewNotificationTypeArray($includeNotificationCenterPlusTokens = false)
{
$type = [
'recipients' => ['admin_email'],
'email_subject' => ['admin_email'],
'email_text' => ['admin_email'],
'email_html' => ['admin_email'],
'file_name' => ['admin_email'],
'file_content' => ['admin_email'],
'email_sender_name' => ['admin_email'],
'email_sender_address' => ['admin_email'],
'email_recipient_cc' => ['admin_email'],
'email_recipient_bcc' => ['admin_email'],
'email_replyTo' => ['admin_email'],
'attachment_tokens' => [],
];
if ($includeNotificationCenterPlusTokens) {
foreach ($type as $field => $tokens) {
$type[$field] = array_unique(array_merge([
'env_*',
'page_*',
'user_*',
'date',
'last_update',
], $tokens));
}
}
return $type;
}
public function activateNotificationType($strGroup, $strType, $arrType)
{
$GLOBALS['NOTIFICATION_CENTER']['NOTIFICATION_TYPE'] = array_merge_recursive(
(array) $GLOBALS['NOTIFICATION_CENTER']['NOTIFICATION_TYPE'],
[
$strGroup => [
$strType => $arrType,
],
]
);
}
/**
* Adds an alias field to the dca and to the desired palettes.
*
* @param $dca
* @param $generateAliasCallback mixed The callback to call for generating the alias
* @param $paletteField String The field after which to insert the alias field in the palettes
* @param array $palettes The palettes in which to insert the field
*/
public function addAliasToDca(string $dca, $generateAliasCallback, string $paletteField, array $palettes = ['default'])
{
Controller::loadDataContainer($dca);
$arrDca = &$GLOBALS['TL_DCA'][$dca];
// add to palettes
foreach ($palettes as $strPalette) {
$arrDca['palettes'][$strPalette] = preg_replace('/('.$paletteField.')(;|,)/', '$1,alias$2', $arrDca['palettes'][$strPalette]);
}
// add field
$arrDca['fields']['alias'] = [
'label' => &$GLOBALS['TL_LANG']['MSC']['alias'],
'exclude' => true,
'search' => true,
'inputType' => 'text',
'eval' => ['rgxp' => 'alias', 'unique' => true, 'maxlength' => 128, 'tl_class' => 'w50'],
'save_callback' => [$generateAliasCallback],
'sql' => "varchar(128) COLLATE utf8_bin NOT NULL default ''",
];
}
/**
* @param $strField
* @param $strTable
*
* @return mixed
*/
public function getLocalizedFieldName($strField, $strTable)
{
Controller::loadDataContainer($strTable);
System::loadLanguageFile($strTable);
return $GLOBALS['TL_DCA'][$strTable]['fields'][$strField]['label'][0] ?: $strField;
}
/**
* Load a data container in a testable way.
*/
public function loadDc(string $table)
{
if (!isset($GLOBALS['TL_DCA'][$table]) || null === $GLOBALS['TL_DCA'][$table]) {
/** @var Controller $controller */
$controller = $this->framework->getAdapter(Controller::class);
$controller->loadDataContainer($table);
}
}
/**
* Load a language file in a testable way.
*/
public function loadLanguageFile(string $table)
{
/** @var System $system */
$system = $this->framework->getAdapter(System::class);
$system->loadLanguageFile($table);
}
public function isDcMultilingual(string $table)
{
$this->loadDc($table);
$bundleName = 'Terminal42\DcMultilingualBundle\Terminal42DcMultilingualBundle';