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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
|
<?php
/**
* @file
* Common functions that many Drupal modules will need to reference.
*
* The functions that are critical and need to be available even when serving
* a cached page are instead located in bootstrap.inc.
*/
use Drupal\Component\Serialization\Json;
use Drupal\Component\Utility\Bytes;
use Drupal\Component\Utility\Html;
use Drupal\Component\Utility\SortArray;
use Drupal\Component\Utility\UrlHelper;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Render\Element\Link;
use Drupal\Core\Render\Markup;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\Core\PhpStorage\PhpStorageFactory;
use Drupal\Core\StringTranslation\PluralTranslatableMarkup;
use Drupal\Core\Render\BubbleableMetadata;
use Drupal\Core\Render\Element;
/**
* @defgroup php_wrappers PHP wrapper functions
* @{
* Functions that are wrappers or custom implementations of PHP functions.
*
* Certain PHP functions should not be used in Drupal. Instead, Drupal's
* replacement functions should be used.
*
* For example, for improved or more secure UTF8-handling, or RFC-compliant
* handling of URLs in Drupal.
*
* For ease of use and memorizing, all these wrapper functions use the same name
* as the original PHP function, but prefixed with "drupal_". Beware, however,
* that not all wrapper functions support the same arguments as the original
* functions.
*
* You should always use these wrapper functions in your code.
*
* Wrong:
* @code
* $my_substring = substr($original_string, 0, 5);
* @endcode
*
* Correct:
* @code
* $my_substring = Unicode::substr($original_string, 0, 5);
* @endcode
*
* @}
*/
/**
* Return status for saving which involved creating a new item.
*/
const SAVED_NEW = 1;
/**
* Return status for saving which involved an update to an existing item.
*/
const SAVED_UPDATED = 2;
/**
* Return status for saving which deleted an existing item.
*/
const SAVED_DELETED = 3;
/**
* The default aggregation group for CSS files added to the page.
*/
const CSS_AGGREGATE_DEFAULT = 0;
/**
* The default aggregation group for theme CSS files added to the page.
*/
const CSS_AGGREGATE_THEME = 100;
/**
* The default weight for CSS rules that style HTML elements ("base" styles).
*/
const CSS_BASE = -200;
/**
* The default weight for CSS rules that layout a page.
*/
const CSS_LAYOUT = -100;
/**
* The default weight for CSS rules that style design components (and their associated states and themes.)
*/
const CSS_COMPONENT = 0;
/**
* The default weight for CSS rules that style states and are not included with components.
*/
const CSS_STATE = 100;
/**
* The default weight for CSS rules that style themes and are not included with components.
*/
const CSS_THEME = 200;
/**
* The default group for JavaScript settings added to the page.
*/
const JS_SETTING = -200;
/**
* The default group for JavaScript and jQuery libraries added to the page.
*/
const JS_LIBRARY = -100;
/**
* The default group for module JavaScript code added to the page.
*/
const JS_DEFAULT = 0;
/**
* The default group for theme JavaScript code added to the page.
*/
const JS_THEME = 100;
/**
* The delimiter used to split plural strings.
*
* @deprecated in Drupal 8.0.x-dev, will be removed before Drupal 9.0.0.
* Use \Drupal\Core\StringTranslation\PluralTranslatableMarkup::DELIMITER
* instead.
*/
const LOCALE_PLURAL_DELIMITER = PluralTranslatableMarkup::DELIMITER;
/**
* Prepares a 'destination' URL query parameter.
*
* Used to direct the user back to the referring page after completing a form.
* By default the current URL is returned. If a destination exists in the
* previous request, that destination is returned. As such, a destination can
* persist across multiple pages.
*
* @return array
* An associative array containing the key:
* - destination: The value of the current request's 'destination' query
* parameter, if present. This can be either a relative or absolute URL.
* However, for security, redirection to external URLs is not performed.
* If the query parameter isn't present, then the URL of the current
* request is returned.
*
* @see \Drupal\Core\EventSubscriber\RedirectResponseSubscriber::checkRedirectUrl()
*
* @ingroup form_api
*
* @deprecated in Drupal 8.0.x-dev, will be removed before Drupal 9.0.0.
* Use the redirect.destination service.
*/
function drupal_get_destination() {
return \Drupal::destination()->getAsArray();
}
/**
* @defgroup validation Input validation
* @{
* Functions to validate user input.
*/
/**
* Verifies the syntax of the given email address.
*
* @param string $mail
* A string containing an email address.
*
* @return bool
* TRUE if the address is in a valid format.
*
* @deprecated in Drupal 8.0.x-dev, will be removed before Drupal 9.0.0.
* Use \Drupal::service('email.validator')->isValid().
*/
function valid_email_address($mail) {
return \Drupal::service('email.validator')->isValid($mail);
}
/**
* @} End of "defgroup validation".
*/
/**
* @defgroup sanitization Sanitization functions
* @{
* Functions to sanitize values.
*
* See https://www.drupal.org/writing-secure-code for information
* on writing secure code.
*/
/**
* Strips dangerous protocols from a URI and encodes it for output to HTML.
*
* @param $uri
* A plain-text URI that might contain dangerous protocols.
*
* @return string
* A URI stripped of dangerous protocols and encoded for output to an HTML
* attribute value. Because it is already encoded, it should not be set as a
* value within a $attributes array passed to Drupal\Core\Template\Attribute,
* because Drupal\Core\Template\Attribute expects those values to be
* plain-text strings. To pass a filtered URI to
* Drupal\Core\Template\Attribute, call
* \Drupal\Component\Utility\UrlHelper::stripDangerousProtocols() instead.
*
* @see \Drupal\Component\Utility\UrlHelper::stripDangerousProtocols()
* @see \Drupal\Component\Utility\UrlHelper::filterBadProtocol()
*
* @deprecated in Drupal 8.0.x-dev, will be removed before Drupal 9.0.0.
* Use UrlHelper::stripDangerousProtocols() or UrlHelper::filterBadProtocol()
* instead. UrlHelper::stripDangerousProtocols() can be used in conjunction
* with \Drupal\Component\Utility\SafeMarkup::format() and an @variable
* placeholder which will perform the necessary escaping.
* UrlHelper::filterBadProtocol() is functionality equivalent to check_url()
* apart from the fact it is protected from double escaping bugs. Note that
* this method no longer marks its output as safe.
*/
function check_url($uri) {
return Html::escape(UrlHelper::stripDangerousProtocols($uri));
}
/**
* @} End of "defgroup sanitization".
*/
/**
* @defgroup format Formatting
* @{
* Functions to format numbers, strings, dates, etc.
*/
/**
* Generates a string representation for the given byte count.
*
* @param $size
* A size in bytes.
* @param $langcode
* Optional language code to translate to a language other than what is used
* to display the page.
*
* @return \Drupal\Core\StringTranslation\TranslatableMarkup
* A translated string representation of the size.
*/
function format_size($size, $langcode = NULL) {
if ($size < Bytes::KILOBYTE) {
return \Drupal::translation()->formatPlural($size, '1 byte', '@count bytes', array(), array('langcode' => $langcode));
}
else {
$size = $size / Bytes::KILOBYTE; // Convert bytes to kilobytes.
$units = ['KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
foreach ($units as $unit) {
if (round($size, 2) >= Bytes::KILOBYTE) {
$size = $size / Bytes::KILOBYTE;
}
else {
break;
}
}
$args = ['@size' => round($size, 2)];
$options = ['langcode' => $langcode];
switch ($unit) {
case 'KB':
return new TranslatableMarkup('@size KB', $args, $options);
case 'MB':
return new TranslatableMarkup('@size MB', $args, $options);
case 'GB':
return new TranslatableMarkup('@size GB', $args, $options);
case 'TB':
return new TranslatableMarkup('@size TB', $args, $options);
case 'PB':
return new TranslatableMarkup('@size PB', $args, $options);
case 'EB':
return new TranslatableMarkup('@size EB', $args, $options);
case 'ZB':
return new TranslatableMarkup('@size ZB', $args, $options);
case 'YB':
return new TranslatableMarkup('@size YB', $args, $options);
}
}
}
/**
* Formats a date, using a date type or a custom date format string.
*
* @param $timestamp
* A UNIX timestamp to format.
* @param $type
* (optional) The format to use, one of:
* - One of the built-in formats: 'short', 'medium',
* 'long', 'html_datetime', 'html_date', 'html_time',
* 'html_yearless_date', 'html_week', 'html_month', 'html_year'.
* - The name of a date type defined by a date format config entity.
* - The machine name of an administrator-defined date format.
* - 'custom', to use $format.
* Defaults to 'medium'.
* @param $format
* (optional) If $type is 'custom', a PHP date format string suitable for
* input to date(). Use a backslash to escape ordinary text, so it does not
* get interpreted as date format characters.
* @param $timezone
* (optional) Time zone identifier, as described at
* http://php.net/manual/timezones.php Defaults to the time zone used to
* display the page.
* @param $langcode
* (optional) Language code to translate to. Defaults to the language used to
* display the page.
*
* @return
* A translated date string in the requested format.
*
* @see \Drupal\Core\Datetime\DateFormatter::format()
*
* @deprecated in Drupal 8.0.0, will be removed before Drupal 9.0.0.
* Use \Drupal::service('date.formatter')->format().
*/
function format_date($timestamp, $type = 'medium', $format = '', $timezone = NULL, $langcode = NULL) {
return \Drupal::service('date.formatter')->format($timestamp, $type, $format, $timezone, $langcode);
}
/**
* Returns an ISO8601 formatted date based on the given date.
*
* @param $date
* A UNIX timestamp.
*
* @return string
* An ISO8601 formatted date.
*/
function date_iso8601($date) {
// The DATE_ISO8601 constant cannot be used here because it does not match
// date('c') and produces invalid RDF markup.
return date('c', $date);
}
/**
* @} End of "defgroup format".
*/
/**
* Formats an attribute string for an HTTP header.
*
* @param $attributes
* An associative array of attributes such as 'rel'.
*
* @return
* A ; separated string ready for insertion in a HTTP header. No escaping is
* performed for HTML entities, so this string is not safe to be printed.
*/
function drupal_http_header_attributes(array $attributes = array()) {
foreach ($attributes as $attribute => &$data) {
if (is_array($data)) {
$data = implode(' ', $data);
}
$data = $attribute . '="' . $data . '"';
}
return $attributes ? ' ' . implode('; ', $attributes) : '';
}
/**
* Attempts to set the PHP maximum execution time.
*
* This function is a wrapper around the PHP function set_time_limit().
* When called, set_time_limit() restarts the timeout counter from zero.
* In other words, if the timeout is the default 30 seconds, and 25 seconds
* into script execution a call such as set_time_limit(20) is made, the
* script will run for a total of 45 seconds before timing out.
*
* If the current time limit is not unlimited it is possible to decrease the
* total time limit if the sum of the new time limit and the current time spent
* running the script is inferior to the original time limit. It is inherent to
* the way set_time_limit() works, it should rather be called with an
* appropriate value every time you need to allocate a certain amount of time
* to execute a task than only once at the beginning of the script.
*
* Before calling set_time_limit(), we check if this function is available
* because it could be disabled by the server administrator. We also hide all
* the errors that could occur when calling set_time_limit(), because it is
* not possible to reliably ensure that PHP or a security extension will
* not issue a warning/error if they prevent the use of this function.
*
* @param $time_limit
* An integer specifying the new time limit, in seconds. A value of 0
* indicates unlimited execution time.
*
* @ingroup php_wrappers
*/
function drupal_set_time_limit($time_limit) {
if (function_exists('set_time_limit')) {
$current = ini_get('max_execution_time');
// Do not set time limit if it is currently unlimited.
if ($current != 0) {
@set_time_limit($time_limit);
}
}
}
/**
* Returns the base URL path (i.e., directory) of the Drupal installation.
*
* base_path() adds a "/" to the beginning and end of the returned path if the
* path is not empty. At the very least, this will return "/".
*
* Examples:
* - http://example.com returns "/" because the path is empty.
* - http://example.com/drupal/folder returns "/drupal/folder/".
*/
function base_path() {
return $GLOBALS['base_path'];
}
/**
* Deletes old cached CSS files.
*
* @deprecated in Drupal 8.x, will be removed before Drupal 9.0.
* Use \Drupal\Core\Asset\AssetCollectionOptimizerInterface::deleteAll().
*/
function drupal_clear_css_cache() {
\Drupal::service('asset.css.collection_optimizer')->deleteAll();
}
/**
* Constructs an array of the defaults that are used for JavaScript assets.
*
* @param $data
* (optional) The default data parameter for the JavaScript asset array.
*
* @see hook_js_alter()
*/
function drupal_js_defaults($data = NULL) {
return array(
'type' => 'file',
'group' => JS_DEFAULT,
'weight' => 0,
'scope' => 'header',
'cache' => TRUE,
'preprocess' => TRUE,
'attributes' => array(),
'version' => NULL,
'data' => $data,
'browsers' => array(),
);
}
/**
* Adds JavaScript to change the state of an element based on another element.
*
* A "state" means a certain property on a DOM element, such as "visible" or
* "checked". A state can be applied to an element, depending on the state of
* another element on the page. In general, states depend on HTML attributes and
* DOM element properties, which change due to user interaction.
*
* Since states are driven by JavaScript only, it is important to understand
* that all states are applied on presentation only, none of the states force
* any server-side logic, and that they will not be applied for site visitors
* without JavaScript support. All modules implementing states have to make
* sure that the intended logic also works without JavaScript being enabled.
*
* #states is an associative array in the form of:
* @code
* array(
* STATE1 => CONDITIONS_ARRAY1,
* STATE2 => CONDITIONS_ARRAY2,
* ...
* )
* @endcode
* Each key is the name of a state to apply to the element, such as 'visible'.
* Each value is a list of conditions that denote when the state should be
* applied.
*
* Multiple different states may be specified to act on complex conditions:
* @code
* array(
* 'visible' => CONDITIONS,
* 'checked' => OTHER_CONDITIONS,
* )
* @endcode
*
* Every condition is a key/value pair, whose key is a jQuery selector that
* denotes another element on the page, and whose value is an array of
* conditions, which must bet met on that element:
* @code
* array(
* 'visible' => array(
* JQUERY_SELECTOR => REMOTE_CONDITIONS,
* JQUERY_SELECTOR => REMOTE_CONDITIONS,
* ...
* ),
* )
* @endcode
* All conditions must be met for the state to be applied.
*
* Each remote condition is a key/value pair specifying conditions on the other
* element that need to be met to apply the state to the element:
* @code
* array(
* 'visible' => array(
* ':input[name="remote_checkbox"]' => array('checked' => TRUE),
* ),
* )
* @endcode
*
* For example, to show a textfield only when a checkbox is checked:
* @code
* $form['toggle_me'] = array(
* '#type' => 'checkbox',
* '#title' => t('Tick this box to type'),
* );
* $form['settings'] = array(
* '#type' => 'textfield',
* '#states' => array(
* // Only show this field when the 'toggle_me' checkbox is enabled.
* 'visible' => array(
* ':input[name="toggle_me"]' => array('checked' => TRUE),
* ),
* ),
* );
* @endcode
*
* The following states may be applied to an element:
* - enabled
* - disabled
* - required
* - optional
* - visible
* - invisible
* - checked
* - unchecked
* - expanded
* - collapsed
*
* The following states may be used in remote conditions:
* - empty
* - filled
* - checked
* - unchecked
* - expanded
* - collapsed
* - value
*
* The following states exist for both elements and remote conditions, but are
* not fully implemented and may not change anything on the element:
* - relevant
* - irrelevant
* - valid
* - invalid
* - touched
* - untouched
* - readwrite
* - readonly
*
* When referencing select lists and radio buttons in remote conditions, a
* 'value' condition must be used:
* @code
* '#states' => array(
* // Show the settings if 'bar' has been selected for 'foo'.
* 'visible' => array(
* ':input[name="foo"]' => array('value' => 'bar'),
* ),
* ),
* @endcode
*
* @param $elements
* A renderable array element having a #states property as described above.
*
* @see form_example_states_form()
*/
function drupal_process_states(&$elements) {
$elements['#attached']['library'][] = 'core/drupal.states';
// Elements of '#type' => 'item' are not actual form input elements, but we
// still want to be able to show/hide them. Since there's no actual HTML input
// element available, setting #attributes does not make sense, but a wrapper
// is available, so setting #wrapper_attributes makes it work.
$key = ($elements['#type'] == 'item') ? '#wrapper_attributes' : '#attributes';
$elements[$key]['data-drupal-states'] = Json::encode($elements['#states']);
}
/**
* Assists in attaching the tableDrag JavaScript behavior to a themed table.
*
* Draggable tables should be used wherever an outline or list of sortable items
* needs to be arranged by an end-user. Draggable tables are very flexible and
* can manipulate the value of form elements placed within individual columns.
*
* To set up a table to use drag and drop in place of weight select-lists or in
* place of a form that contains parent relationships, the form must be themed
* into a table. The table must have an ID attribute set and it
* may be set as follows:
* @code
* $table = array(
* '#type' => 'table',
* '#header' => $header,
* '#rows' => $rows,
* '#attributes' => array(
* 'id' => 'my-module-table',
* ),
* );
* return drupal_render($table);
* @endcode
*
* In the theme function for the form, a special class must be added to each
* form element within the same column, "grouping" them together.
*
* In a situation where a single weight column is being sorted in the table, the
* classes could be added like this (in the theme function):
* @code
* $form['my_elements'][$delta]['weight']['#attributes']['class'] = array('my-elements-weight');
* @endcode
*
* Each row of the table must also have a class of "draggable" in order to
* enable the drag handles:
* @code
* $row = array(...);
* $rows[] = array(
* 'data' => $row,
* 'class' => array('draggable'),
* );
* @endcode
*
* When tree relationships are present, the two additional classes
* 'tabledrag-leaf' and 'tabledrag-root' can be used to refine the behavior:
* - Rows with the 'tabledrag-leaf' class cannot have child rows.
* - Rows with the 'tabledrag-root' class cannot be nested under a parent row.
*
* Calling drupal_attach_tabledrag() would then be written as such:
* @code
* drupal_attach_tabledrag('my-module-table', array(
* 'action' => 'order',
* 'relationship' => 'sibling',
* 'group' => 'my-elements-weight',
* );
* @endcode
*
* In a more complex case where there are several groups in one column (such as
* the block regions on the admin/structure/block page), a separate subgroup
* class must also be added to differentiate the groups.
* @code
* $form['my_elements'][$region][$delta]['weight']['#attributes']['class'] = array('my-elements-weight', 'my-elements-weight-' . $region);
* @endcode
*
* The 'group' option is still 'my-element-weight', and the additional
* 'subgroup' option will be passed in as 'my-elements-weight-' . $region. This
* also means that you'll need to call drupal_attach_tabledrag() once for every
* region added.
*
* @code
* foreach ($regions as $region) {
* drupal_attach_tabledrag('my-module-table', array(
* 'action' => 'order',
* 'relationship' => 'sibling',
* 'group' => 'my-elements-weight',
* 'subgroup' => 'my-elements-weight-' . $region,
* ));
* }
* @endcode
*
* In a situation where tree relationships are present, adding multiple
* subgroups is not necessary, because the table will contain indentations that
* provide enough information about the sibling and parent relationships. See
* MenuForm::BuildOverviewForm for an example creating a table
* containing parent relationships.
*
* @param $element
* A form element to attach the tableDrag behavior to.
* @param array $options
* These options are used to generate JavaScript settings necessary to
* configure the tableDrag behavior appropriately for this particular table.
* An associative array containing the following keys:
* - 'table_id': String containing the target table's id attribute.
* If the table does not have an id, one will need to be set,
* such as <table id="my-module-table">.
* - 'action': String describing the action to be done on the form item.
* Either 'match' 'depth', or 'order':
* - 'match' is typically used for parent relationships.
* - 'order' is typically used to set weights on other form elements with
* the same group.
* - 'depth' updates the target element with the current indentation.
* - 'relationship': String describing where the "action" option
* should be performed. Either 'parent', 'sibling', 'group', or 'self':
* - 'parent' will only look for fields up the tree.
* - 'sibling' will look for fields in the same group in rows above and
* below it.
* - 'self' affects the dragged row itself.
* - 'group' affects the dragged row, plus any children below it (the entire
* dragged group).
* - 'group': A class name applied on all related form elements for this action.
* - 'subgroup': (optional) If the group has several subgroups within it, this
* string should contain the class name identifying fields in the same
* subgroup.
* - 'source': (optional) If the $action is 'match', this string should contain
* the classname identifying what field will be used as the source value
* when matching the value in $subgroup.
* - 'hidden': (optional) The column containing the field elements may be
* entirely hidden from view dynamically when the JavaScript is loaded. Set
* to FALSE if the column should not be hidden.
* - 'limit': (optional) Limit the maximum amount of parenting in this table.
*
* @see MenuForm::BuildOverviewForm()
*/
function drupal_attach_tabledrag(&$element, array $options) {
// Add default values to elements.
$options = $options + array(
'subgroup' => NULL,
'source' => NULL,
'hidden' => TRUE,
'limit' => 0
);
$group = $options['group'];
$tabledrag_id = &drupal_static(__FUNCTION__);
$tabledrag_id = (!isset($tabledrag_id)) ? 0 : $tabledrag_id + 1;
// If a subgroup or source isn't set, assume it is the same as the group.
$target = isset($options['subgroup']) ? $options['subgroup'] : $group;
$source = isset($options['source']) ? $options['source'] : $target;
$element['#attached']['drupalSettings']['tableDrag'][$options['table_id']][$group][$tabledrag_id] = array(
'target' => $target,
'source' => $source,
'relationship' => $options['relationship'],
'action' => $options['action'],
'hidden' => $options['hidden'],
'limit' => $options['limit'],
);
$element['#attached']['library'][] = 'core/drupal.tabledrag';
}
/**
* Deletes old cached JavaScript files and variables.
*
* @deprecated in Drupal 8.x, will be removed before Drupal 9.0.
* Use \Drupal\Core\Asset\AssetCollectionOptimizerInterface::deleteAll().
*/
function drupal_clear_js_cache() {
\Drupal::service('asset.js.collection_optimizer')->deleteAll();
}
/**
* Pre-render callback: Renders a link into #markup.
*
* @deprecated in Drupal 8.x, will be removed before Drupal 9.0.
* Use \Drupal\Core\Render\Element\Link::preRenderLink().
*/
function drupal_pre_render_link($element) {
return Link::preRenderLink($element);
}
/**
* Pre-render callback: Collects child links into a single array.
*
* This function can be added as a pre_render callback for a renderable array,
* usually one which will be themed by links.html.twig. It iterates through all
* unrendered children of the element, collects any #links properties it finds,
* merges them into the parent element's #links array, and prevents those
* children from being rendered separately.
*
* The purpose of this is to allow links to be logically grouped into related
* categories, so that each child group can be rendered as its own list of
* links if drupal_render() is called on it, but calling drupal_render() on the
* parent element will still produce a single list containing all the remaining
* links, regardless of what group they were in.
*
* A typical example comes from node links, which are stored in a renderable
* array similar to this:
* @code
* $build['links'] = array(
* '#theme' => 'links__node',
* '#pre_render' => array('drupal_pre_render_links'),
* 'comment' => array(
* '#theme' => 'links__node__comment',
* '#links' => array(
* // An array of links associated with node comments, suitable for
* // passing in to links.html.twig.
* ),
* ),
* 'statistics' => array(
* '#theme' => 'links__node__statistics',
* '#links' => array(
* // An array of links associated with node statistics, suitable for
* // passing in to links.html.twig.
* ),
* ),
* 'translation' => array(
* '#theme' => 'links__node__translation',
* '#links' => array(
* // An array of links associated with node translation, suitable for
* // passing in to links.html.twig.
* ),
* ),
* );
* @endcode
*
* In this example, the links are grouped by functionality, which can be
* helpful to themers who want to display certain kinds of links independently.
* For example, adding this code to node.html.twig will result in the comment
* links being rendered as a single list:
* @code
* {{ content.links.comment }}
* @endcode
*
* (where a node's content has been transformed into $content before handing
* control to the node.html.twig template).
*
* The pre_render function defined here allows the above flexibility, but also
* allows the following code to be used to render all remaining links into a
* single list, regardless of their group:
* @code
* {{ content.links }}
* @endcode
*
* In the above example, this will result in the statistics and translation
* links being rendered together in a single list (but not the comment links,
* which were rendered previously on their own).
*
* Because of the way this function works, the individual properties of each
* group (for example, a group-specific #theme property such as
* 'links__node__comment' in the example above, or any other property such as
* #attributes or #pre_render that is attached to it) are only used when that
* group is rendered on its own. When the group is rendered together with other
* children, these child-specific properties are ignored, and only the overall
* properties of the parent are used.
*/
function drupal_pre_render_links($element) {
$element += array('#links' => array(), '#attached' => array());
foreach (Element::children($element) as $key) {
$child = &$element[$key];
// If the child has links which have not been printed yet and the user has
// access to it, merge its links in to the parent.
if (isset($child['#links']) && empty($child['#printed']) && Element::isVisibleElement($child)) {
$element['#links'] += $child['#links'];
// Mark the child as having been printed already (so that its links
// cannot be mistakenly rendered twice).
$child['#printed'] = TRUE;
}
// Merge attachments.
if (isset($child['#attached'])) {
$element['#attached'] = BubbleableMetadata::mergeAttachments($element['#attached'], $child['#attached']);
}
}
return $element;
}
/**
* Renders final HTML given a structured array tree.
*
* @deprecated as of Drupal 8.0.x, will be removed before Drupal 9.0.0. Use the
* 'renderer' service instead.
*
* @see \Drupal\Core\Render\RendererInterface::renderRoot()
*/
function drupal_render_root(&$elements) {
return \Drupal::service('renderer')->renderRoot($elements);
}
/**
* Renders HTML given a structured array tree.
*
* @deprecated as of Drupal 8.0.x, will be removed before Drupal 9.0.0. Use the
* 'renderer' service instead.
*
* @see \Drupal\Core\Render\RendererInterface::render()
*/
function drupal_render(&$elements, $is_recursive_call = FALSE) {
return \Drupal::service('renderer')->render($elements, $is_recursive_call);
}
/**
* Renders children of an element and concatenates them.
*
* @param array $element
* The structured array whose children shall be rendered.
* @param array $children_keys
* (optional) If the keys of the element's children are already known, they
* can be passed in to save another run of
* \Drupal\Core\Render\Element::children().
*
* @return string|\Drupal\Component\Render\MarkupInterface
* The rendered HTML of all children of the element.
*
* @deprecated in Drupal 8.0.x and will be removed before 9.0.0. Avoid early
* rendering when possible or loop through the elements and render them as
* they are available.
*
* @see drupal_render()
*/
function drupal_render_children(&$element, $children_keys = NULL) {
if ($children_keys === NULL) {
$children_keys = Element::children($element);
}
$output = '';
foreach ($children_keys as $key) {
if (!empty($element[$key])) {
$output .= drupal_render($element[$key]);
}
}
return Markup::create($output);
}
/**
* Renders an element.
*
* This function renders an element. The top level element is shown with show()
* before rendering, so it will always be rendered even if hide() had been
* previously used on it.
*
* @param $element
* The element to be rendered.
*
* @return
* The rendered element.
*
* @see \Drupal\Core\Render\RendererInterface
* @see show()
* @see hide()
*/
function render(&$element) {
if (!$element && $element !== 0) {
return NULL;
}
if (is_array($element)) {
// Early return if this element was pre-rendered (no need to re-render).
if (isset($element['#printed']) && $element['#printed'] == TRUE && isset($element['#markup']) && strlen($element['#markup']) > 0) {
return $element['#markup'];
}
show($element);
return \Drupal::service('renderer')->render($element);
}
else {
// Safe-guard for inappropriate use of render() on flat variables: return
// the variable as-is.
return $element;
}
}
/**
* Hides an element from later rendering.
*
* The first time render() or drupal_render() is called on an element tree,
* as each element in the tree is rendered, it is marked with a #printed flag
* and the rendered children of the element are cached. Subsequent calls to
* render() or drupal_render() will not traverse the child tree of this element
* again: they will just use the cached children. So if you want to hide an
* element, be sure to call hide() on the element before its parent tree is
* rendered for the first time, as it will have no effect on subsequent
* renderings of the parent tree.
*
* @param $element
* The element to be hidden.
*
* @return
* The element.
*
* @see render()
* @see show()
*/
function hide(&$element) {
$element['#printed'] = TRUE;
return $element;
}
/**
* Shows a hidden element for later rendering.
*
* You can also use render($element), which shows the element while rendering
* it.
*
* The first time render() or drupal_render() is called on an element tree,
* as each element in the tree is rendered, it is marked with a #printed flag
* and the rendered children of the element are cached. Subsequent calls to
* render() or drupal_render() will not traverse the child tree of this element
* again: they will just use the cached children. So if you want to show an
* element, be sure to call show() on the element before its parent tree is
* rendered for the first time, as it will have no effect on subsequent
* renderings of the parent tree.
*
* @param $element
* The element to be shown.
*
* @return
* The element.
*
* @see render()
* @see hide()
*/
function show(&$element) {
$element['#printed'] = FALSE;
return $element;
}
/**
* Retrieves the default properties for the defined element type.
*
* @param $type
* An element type as defined by an element plugin.
*
* @deprecated in Drupal 8.0.0, will be removed before Drupal 9.0.0.
* Use \Drupal::service('element_info')->getInfo() instead.
*/
function element_info($type) {
return \Drupal::service('element_info')->getInfo($type);
}
/**
* Retrieves a single property for the defined element type.
*
* @param $type
* An element type as defined by an element plugin.
* @param $property_name
* The property within the element type that should be returned.
* @param $default
* (Optional) The value to return if the element type does not specify a
* value for the property. Defaults to NULL.
*
* @deprecated in Drupal 8.0.0, will be removed before Drupal 9.0.0.
* Use \Drupal::service('element_info')->getInfoProperty() instead.
*/
function element_info_property($type, $property_name, $default = NULL) {
return \Drupal::service('element_info')->getInfoProperty($type, $property_name, $default);
}
/**
* Flushes all persistent caches, resets all variables, and rebuilds all data structures.
*
* At times, it is necessary to re-initialize the entire system to account for
* changed or new code. This function:
* - Clears all persistent caches:
* - The bootstrap cache bin containing base system, module system, and theme
* system information.
* - The common 'default' cache bin containing arbitrary caches.
* - The page cache.
* - The URL alias path cache.
* - Resets all static variables that have been defined via drupal_static().
* - Clears asset (JS/CSS) file caches.
* - Updates the system with latest information about extensions (modules and
* themes).
* - Updates the bootstrap flag for modules implementing bootstrap_hooks().
* - Rebuilds the full database schema information (invoking hook_schema()).
* - Rebuilds data structures of all modules (invoking hook_rebuild()). In
* core this means
* - blocks, node types, date formats and actions are synchronized with the
* database
* - The 'active' status of fields is refreshed.
* - Rebuilds the menu router.
*
* This means the entire system is reset so all caches and static variables are
* effectively empty. After that is guaranteed, information about the currently
* active code is updated, and rebuild operations are successively called in
* order to synchronize the active system according to the current information
* defined in code.
*
* All modules need to ensure that all of their caches are flushed when
* hook_cache_flush() is invoked; any previously known information must no
* longer exist. All following hook_rebuild() operations must be based on fresh
* and current system data. All modules must be able to rely on this contract.
*
* @see \Drupal\Core\Cache\CacheHelper::getBins()
* @see hook_cache_flush()
* @see hook_rebuild()
*
* This function also resets the theme, which means it is not initialized
* anymore and all previously added JavaScript and CSS is gone. Normally, this
* function is called as an end-of-POST-request operation that is followed by a
* redirect, so this effect is not visible. Since the full reset is the whole
* point of this function, callers need to take care for backing up all needed
* variables and properly restoring or re-initializing them on their own. For
* convenience, this function automatically re-initializes the maintenance theme
* if it was initialized before.
*
* @todo Try to clear page/JS/CSS caches last, so cached pages can still be
* served during this possibly long-running operation. (Conflict on bootstrap
* cache though.)
* @todo Add a global lock to ensure that caches are not primed in concurrent
* requests.
*/
function drupal_flush_all_caches() {
$module_handler = \Drupal::moduleHandler();
// Flush all persistent caches.
// This is executed based on old/previously known information, which is
// sufficient, since new extensions cannot have any primed caches yet.
$module_handler->invokeAll('cache_flush');
foreach (Cache::getBins() as $service_id => $cache_backend) {
$cache_backend->deleteAll();
}
// Flush asset file caches.
\Drupal::service('asset.css.collection_optimizer')->deleteAll();
\Drupal::service('asset.js.collection_optimizer')->deleteAll();
_drupal_flush_css_js();
// Reset all static caches.
drupal_static_reset();
// Invalidate the container.
\Drupal::service('kernel')->invalidateContainer();
// Wipe the Twig PHP Storage cache.
PhpStorageFactory::get('twig')->deleteAll();
// Rebuild module and theme data.
$module_data = system_rebuild_module_data();
/** @var \Drupal\Core\Extension\ThemeHandlerInterface $theme_handler */
$theme_handler = \Drupal::service('theme_handler');
$theme_handler->refreshInfo();
// In case the active theme gets requested later in the same request we need
// to reset the theme manager.
\Drupal::theme()->resetActiveTheme();
// Rebuild and reboot a new kernel. A simple DrupalKernel reboot is not
// sufficient, since the list of enabled modules might have been adjusted
// above due to changed code.
$files = array();
foreach ($module_data as $name => $extension) {
if ($extension->status) {
$files[$name] = $extension;
}
}
\Drupal::service('kernel')->updateModules($module_handler->getModuleList(), $files);
// New container, new module handler.
$module_handler = \Drupal::moduleHandler();
// Ensure that all modules that are currently supposed to be enabled are
// actually loaded.
$module_handler->loadAll();
// Rebuild all information based on new module data.
$module_handler->invokeAll('rebuild');
// Clear all plugin caches.
\Drupal::service('plugin.cache_clearer')->clearCachedDefinitions();
// Rebuild the menu router based on all rebuilt data.
// Important: This rebuild must happen last, so the menu router is guaranteed
// to be based on up to date information.
\Drupal::service('router.builder')->rebuild();
// Re-initialize the maintenance theme, if the current request attempted to
// use it. Unlike regular usages of this function, the installer and update
// scripts need to flush all caches during GET requests/page building.
if (function_exists('_drupal_maintenance_theme')) {
\Drupal::theme()->resetActiveTheme();
drupal_maintenance_theme();
}
}
/**
* Changes the dummy query string added to all CSS and JavaScript files.
*
* Changing the dummy query string appended to CSS and JavaScript files forces
* all browsers to reload fresh files.
*/
function _drupal_flush_css_js() {
// The timestamp is converted to base 36 in order to make it more compact.
Drupal::state()->set('system.css_js_query_string', base_convert(REQUEST_TIME, 10, 36));
}
/**
* Outputs debug information.
*
* The debug information is passed on to trigger_error() after being converted
* to a string using _drupal_debug_message().
*
* @param $data
* Data to be output.
* @param $label
* Label to prefix the data.
* @param $print_r
* Flag to switch between print_r() and var_export() for data conversion to
* string. Set $print_r to FALSE to use var_export() instead of print_r().
* Passing recursive data structures to var_export() will generate an error.
*/
function debug($data, $label = NULL, $print_r = TRUE) {
// Print $data contents to string.
$string = Html::escape($print_r ? print_r($data, TRUE) : var_export($data, TRUE));
// Display values with pre-formatting to increase readability.
$string = '<pre>' . $string . '</pre>';
trigger_error(trim($label ? "$label: $string" : $string));
}
/**
* Checks whether a version is compatible with a given dependency.
*
* @param $v
* A parsed dependency structure e.g. from ModuleHandler::parseDependency().
* @param $current_version
* The version to check against (like 4.2).
*
* @return
* NULL if compatible, otherwise the original dependency version string that
* caused the incompatibility.
*
* @see \Drupal\Core\Extension\ModuleHandler::parseDependency()
*/
function drupal_check_incompatibility($v, $current_version) {
if (!empty($v['versions'])) {
foreach ($v['versions'] as $required_version) {
if ((isset($required_version['op']) && !version_compare($current_version, $required_version['version'], $required_version['op']))) {
return $v['original_version'];
}
}
}
}
/**
* Returns a string of supported archive extensions.
*
* @return
* A space-separated string of extensions suitable for use by the file
* validation system.
*/
function archiver_get_extensions() {
$valid_extensions = array();
foreach (\Drupal::service('plugin.manager.archiver')->getDefinitions() as $archive) {
foreach ($archive['extensions'] as $extension) {
foreach (explode('.', $extension) as $part) {
if (!in_array($part, $valid_extensions)) {
$valid_extensions[] = $part;
}
}
}
}
return implode(' ', $valid_extensions);
}
/**
* Creates the appropriate archiver for the specified file.
*
* @param $file
* The full path of the archive file. Note that stream wrapper paths are
* supported, but not remote ones.
*
* @return
* A newly created instance of the archiver class appropriate
* for the specified file, already bound to that file.
* If no appropriate archiver class was found, will return FALSE.
*/
function archiver_get_archiver($file) {
// Archivers can only work on local paths
$filepath = drupal_realpath($file);
if (!is_file($filepath)) {
throw new Exception(t('Archivers can only operate on local files: %file not supported', array('%file' => $file)));
}
return \Drupal::service('plugin.manager.archiver')->getInstance(array('filepath' => $filepath));
}
/**
* Assembles the Drupal Updater registry.
*
* An Updater is a class that knows how to update various parts of the Drupal
* file system, for example to update modules that have newer releases, or to
* install a new theme.
*
* @return array
* The Drupal Updater class registry.
*
* @see \Drupal\Core\Updater\Updater
* @see hook_updater_info()
* @see hook_updater_info_alter()
*/
function drupal_get_updaters() {
$updaters = &drupal_static(__FUNCTION__);
if (!isset($updaters)) {
$updaters = \Drupal::moduleHandler()->invokeAll('updater_info');
\Drupal::moduleHandler()->alter('updater_info', $updaters);
uasort($updaters, array(SortArray::class, 'sortByWeightElement'));
}
return $updaters;
}
/**
* Assembles the Drupal FileTransfer registry.
*
* @return
* The Drupal FileTransfer class registry.
*
* @see \Drupal\Core\FileTransfer\FileTransfer
* @see hook_filetransfer_info()
* @see hook_filetransfer_info_alter()
*/
function drupal_get_filetransfer_info() {
$info = &drupal_static(__FUNCTION__);
if (!isset($info)) {
$info = \Drupal::moduleHandler()->invokeAll('filetransfer_info');
\Drupal::moduleHandler()->alter('filetransfer_info', $info);
uasort($info, array(SortArray::class, 'sortByWeightElement'));
}
return $info;
}
|