-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdate_api.module
More file actions
2828 lines (2637 loc) · 91.4 KB
/
date_api.module
File metadata and controls
2828 lines (2637 loc) · 91.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* @file
* This module will make the date API available to other modules.
* Designed to provide a light but flexible assortment of functions
* and constants, with more functionality in additional files that
* are not loaded unless other modules specifically include them.
*/
/**
* Set up some constants.
*
* Includes standard date types, format strings, strict regex strings for ISO
* and DATETIME formats (seconds are optional).
*
* The loose regex will find any variety of ISO date and time, with or
* without time, with or without dashes and colons separating the elements,
* and with either a 'T' or a space separating date and time.
*/
define('DATE_ISO', 'date');
define('DATE_UNIX', 'datestamp');
define('DATE_DATETIME', 'datetime');
define('DATE_ARRAY', 'array');
define('DATE_OBJECT', 'object');
define('DATE_ICAL', 'ical');
define('DATE_FORMAT_ISO', "Y-m-d\TH:i:s");
define('DATE_FORMAT_UNIX', "U");
define('DATE_FORMAT_DATETIME', "Y-m-d H:i:s");
define('DATE_FORMAT_ICAL', "Ymd\THis");
define('DATE_FORMAT_ICAL_DATE', "Ymd");
define('DATE_FORMAT_DATE', 'Y-m-d');
define('DATE_REGEX_ISO', '/(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):?(\d{2})?/');
define('DATE_REGEX_DATETIME', '/(\d{4})-(\d{2})-(\d{2})\s(\d{2}):(\d{2}):?(\d{2})?/');
define('DATE_REGEX_LOOSE', '/(\d{4})-?(\d{1,2})-?(\d{1,2})([T\s]?(\d{2}):?(\d{2}):?(\d{2})?(\.\d+)?(Z|[\+\-]\d{2}:?\d{2})?)?/');
define('DATE_REGEX_ICAL_DATE', '/(\d{4})(\d{2})(\d{2})/');
define('DATE_REGEX_ICAL_DATETIME', '/(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})(Z)?/');
/**
* Implementation of hook_init().
*/
function date_api_init() {
if (function_exists('date_default_timezone_set')) {
date_default_timezone_set(date_default_timezone_name());
}
drupal_add_css(drupal_get_path('module', 'date_api') .'/date.css');
}
/**
* Implementation of hook_menu().
*/
function date_api_menu() {
$items = array();
$items['admin/settings/date-time/formats'] = array(
'title' => 'Formats',
'description' => 'Allow users to configure date formats',
'type' => MENU_LOCAL_TASK,
'file' => 'date_api.admin.inc',
'page callback' => 'drupal_get_form',
'page arguments' => array('date_api_date_formats_form'),
'access arguments' => array('administer site configuration'),
'weight' => 1,
);
$items['admin/settings/date-time/formats/configure'] = array(
'title' => 'Configure',
'description' => 'Allow users to configure date formats',
'type' => MENU_DEFAULT_LOCAL_TASK,
'file' => 'date_api.admin.inc',
'page callback' => 'drupal_get_form',
'page arguments' => array('date_api_date_formats_form'),
'access arguments' => array('administer site configuration'),
'weight' => 1,
);
$items['admin/settings/date-time/formats/lookup'] = array(
'title' => 'Date and time lookup',
'type' => MENU_CALLBACK,
'page callback' => 'date_api_date_time_lookup',
'access arguments' => array('administer site configuration'),
);
$items['admin/settings/date-time/formats/custom'] = array(
'title' => 'Custom formats',
'description' => 'Allow users to configure custom date formats.',
'type' => MENU_LOCAL_TASK,
'file' => 'date_api.admin.inc',
'page callback' => 'date_api_configure_custom_date_formats',
'access arguments' => array('administer site configuration'),
'weight' => 2,
);
$items['admin/settings/date-time/formats/add'] = array(
'title' => 'Add format',
'description' => 'Allow users to add additional date formats.',
'type' => MENU_LOCAL_TASK,
'file' => 'date_api.admin.inc',
'page callback' => 'drupal_get_form',
'page arguments' => array('date_api_add_date_formats_form'),
'access arguments' => array('administer site configuration'),
'weight' => 3,
);
$items['admin/settings/date-time/formats/delete/%'] = array(
'title' => 'Delete date format',
'description' => 'Allow users to delete a configured date format.',
'type' => MENU_CALLBACK,
'file' => 'date_api.admin.inc',
'page callback' => 'drupal_get_form',
'page arguments' => array('date_api_delete_format_form', 5),
'access arguments' => array('administer site configuration'),
);
$items['admin/settings/date-time/delete/%'] = array(
'title' => 'Delete date format type',
'description' => 'Allow users to delete a configured date format type.',
'type' => MENU_CALLBACK,
'file' => 'date_api.admin.inc',
'page callback' => 'drupal_get_form',
'page arguments' => array('date_api_delete_format_type_form', 4),
'access arguments' => array('administer site configuration'),
);
return $items;
}
/**
* Implementation of hook_menu_alter().
*/
function date_api_menu_alter(&$callbacks) {
// Add a new 'admin/settings/date-time/configure' path and make it the same as
// the 'admin/settings/date-time'. Also set it to be the default local task -
// needed to make tabs work as expected.
$callbacks['admin/settings/date-time/configure'] = $callbacks['admin/settings/date-time'];
$callbacks['admin/settings/date-time/configure']['type'] = MENU_DEFAULT_LOCAL_TASK;
}
/**
* Helper function for getting the format string for a date type.
*/
function date_type_format($type) {
switch ($type) {
case DATE_ISO:
return DATE_FORMAT_ISO;
case DATE_UNIX:
return DATE_FORMAT_UNIX;
case DATE_DATETIME:
return DATE_FORMAT_DATETIME;
case DATE_ICAL:
return DATE_FORMAT_ICAL;
}
}
/**
* An untranslated array of month names
*
* Needed for css, translation functions, strtotime(), and other places
* that use the English versions of these words.
*
* @return
* an array of month names
*/
function date_month_names_untranslated() {
static $month_names;
if (empty($month_names)) {
$month_names = array(1 => 'January', 2 => 'February', 3 => 'March',
4 => 'April', 5 => 'May', 6 => 'June', 7 => 'July',
8 => 'August', 9 => 'September', 10 => 'October',
11 => 'November', 12 => 'December');
}
return $month_names;
}
/**
* A translated array of month names
*
* @param $required
* If not required, will include a blank value at the beginning of the list.
* @return
* an array of month names
*/
function date_month_names($required = FALSE) {
$month_names = array();
foreach (date_month_names_untranslated() as $key => $day) {
$month_names[$key] = date_t($day, 'month_name');
}
$none = array('' => '');
return !$required ? $none + $month_names : $month_names;
}
/**
* A translated array of month name abbreviations
*
* @param $required
* If not required, will include a blank value at the beginning of the list.
* @return
* an array of month abbreviations
*/
function date_month_names_abbr($required = FALSE) {
$month_names = array();
foreach (date_month_names_untranslated() as $key => $day) {
$month_names[$key] = date_t($day, 'month_abbr');
}
$none = array('' => '');
return !$required ? $none + $month_names : $month_names;
}
/**
* An untranslated array of week days
*
* Needed for css, translation functions, strtotime(), and other places
* that use the English versions of these words.
*
* @return
* an array of week day names
*/
function date_week_days_untranslated($refresh = TRUE) {
static $weekdays;
if ($refresh || empty($weekdays)) {
$weekdays = array(0 => 'Sunday', 1 => 'Monday', 2 => 'Tuesday',
3 => 'Wednesday', 4 => 'Thursday', 5 => 'Friday',
6 => 'Saturday');
}
return $weekdays;
}
/**
* A translated array of week days
*
* @param $required
* If not required, will include a blank value at the beginning of the array.
* @return
* an array of week day names
*/
function date_week_days($required = FALSE, $refresh = TRUE) {
$weekdays = array();
foreach (date_week_days_untranslated() as $key => $day) {
$weekdays[$key] = date_t($day, 'day_name');
}
$none = array('' => '');
return !$required ? $none + $weekdays : $weekdays;
}
/**
* An translated array of week day abbreviations.
*
* @param $required
* If not required, will include a blank value at the beginning of the array.
* @return
* an array of week day abbreviations
*/
function date_week_days_abbr($required = FALSE, $refresh = TRUE, $length = 3) {
$weekdays = array();
switch ($length) {
case 1:
$context = 'day_abbr1';
break;
case 2:
$context = 'day_abbr2';
break;
default:
$context = 'day_abbr';
break;
}
foreach (date_week_days_untranslated() as $key => $day) {
$weekdays[$key] = date_t($day, $context);
}
$none = array('' => '');
return !$required ? $none + $weekdays : $weekdays;
}
/**
* Order weekdays
* Correct weekdays array so first day in array matches the first day of
* the week. Use to create things like calendar headers.
*
* @param array $weekdays
* @return array
*/
function date_week_days_ordered($weekdays) {
if (variable_get('date_first_day', 1) > 0) {
for ($i = 1; $i <= variable_get('date_first_day', 1); $i++) {
$last = array_shift($weekdays);
array_push($weekdays, $last);
}
}
return $weekdays;
}
/**
* An array of years.
*
* @param int $min
* the minimum year in the array
* @param int $max
* the maximum year in the array
* @param $required
* If not required, will include a blank value at the beginning of the array.
* @return
* an array of years in the selected range
*/
function date_years($min = 0, $max = 0, $required = FALSE) {
// Have to be sure $min and $max are valid values;
if (empty($min)) $min = intval(date('Y', time()) - 3);
if (empty($max)) $max = intval(date('Y', time()) + 3);
$none = array(0 => '');
return !$required ? $none + drupal_map_assoc(range($min, $max)) : drupal_map_assoc(range($min, $max));
}
/**
* An array of days.
*
* @param $required
* If not required, returned array will include a blank value.
* @param integer $month (optional)
* @param integer $year (optional)
* @return
* an array of days for the selected month.
*/
function date_days($required = FALSE, $month = NULL, $year = NULL) {
// If we have a month and year, find the right last day of the month.
if (!empty($month) && !empty($year)) {
$date = date_make_date($year .'-'. $month .'-01 00:00:00', 'UTC');
$max = date_format('t', $date);
}
// If there is no month and year given, default to 31.
if (empty($max)) $max = 31;
$none = array(0 => '');
return !$required ? $none + drupal_map_assoc(range(1, $max)) : drupal_map_assoc(range(1, $max));
}
/**
* An array of hours.
*
* @param string $format
* @param $required
* If not required, returned array will include a blank value.
* @return
* an array of hours in the selected format.
*/
function date_hours($format = 'H', $required = FALSE) {
$hours = array();
if ($format == 'h' || $format == 'g') {
$min = 1;
$max = 12;
}
else {
$min = 0;
$max = 23;
}
for ($i = $min; $i <= $max; $i++) {
$hours[$i] = $i < 10 && ($format == 'H' || $format == 'h') ? "0$i" : $i;
}
$none = array('' => '');
return !$required ? $none + $hours : $hours;
}
/**
* An array of minutes.
*
* @param string $format
* @param $required
* If not required, returned array will include a blank value.
* @return
* an array of minutes in the selected format.
*/
function date_minutes($format = 'i', $required = FALSE, $increment = 1) {
$minutes = array();
// Have to be sure $increment has a value so we don't loop endlessly;
if (empty($increment)) $increment = 1;
for ($i = 0; $i < 60; $i += $increment) {
$minutes[$i] = $i < 10 && $format == 'i' ? "0$i" : $i;
}
$none = array('' => '');
return !$required ? $none + $minutes : $minutes;
}
/**
* An array of seconds.
*
* @param string $format
* @param $required
* If not required, returned array will include a blank value.
* @return array an array of seconds in the selected format.
*/
function date_seconds($format = 's', $required = FALSE, $increment = 1) {
$seconds = array();
// Have to be sure $increment has a value so we don't loop endlessly;
if (empty($increment)) $increment = 1;
for ($i = 0; $i < 60; $i += $increment) {
$seconds[$i] = $i < 10 && $format == 's' ? "0$i" : $i;
}
$none = array('' => '');
return !$required ? $none + $seconds : $seconds;
}
/**
* An array of am and pm options.
* @param $required
* If not required, returned array will include a blank value.
* @return array an array of am pm options.
*/
function date_ampm($required = FALSE) {
$none = array('' => '');
$ampm = array('am' => date_t('am', 'ampm'), 'pm' => date_t('pm', 'ampm'));
return !$required ? $none + $ampm : $ampm;
}
/**
* Implementation of hook_date_formats().
*
* @return
* An array of date formats with attributes 'type' (short, medium or long),
* 'format' (the format string) and 'locales'. The 'locales' attribute is an
* array of locales, which can include both 2 character language codes like
* 'en', 'fr', but also 5 character language codes like 'en-gb' and 'en-us'.
*/
function date_api_date_formats() {
include_once('./'. drupal_get_path('module', 'date_api') .'/date_api_formats_list.inc');
return _date_api_date_formats_list();
}
/**
* Implementation of hook_date_format_types().
*/
function date_api_date_format_types() {
return array(
'long' => t('Long'),
'medium' => t('Medium'),
'short' => t('Short'),
);
}
/**
* Array of regex replacement strings for date format elements.
* Used to allow input in custom formats. Based on work done for
* the Date module by Yves Chedemois (yched).
*
* @return array of date() format letters and their regex equivalents.
*/
function date_format_patterns($strict = FALSE) {
return array(
'd' => '\d{'. ($strict ? '2' : '1,2') .'}',
'm' => '\d{'. ($strict ? '2' : '1,2') .'}',
'h' => '\d{'. ($strict ? '2' : '1,2') .'}',
'H' => '\d{'. ($strict ? '2' : '1,2') .'}',
'i' => '\d{'. ($strict ? '2' : '1,2') .'}',
's' => '\d{'. ($strict ? '2' : '1,2') .'}',
'j' => '\d{1,2}', 'N' => '\d', 'S' => '\w{2}',
'w' => '\d', 'z' => '\d{1,3}', 'W' => '\d{1,2}',
'n' => '\d{1,2}', 't' => '\d{2}', 'L' => '\d', 'o' => '\d{4}',
'Y' => '\d{4}', 'y' => '\d{2}', 'B' => '\d{3}', 'g' => '\d{1,2}',
'G' => '\d{1,2}', 'e' => '\w*', 'I' => '\d', 'T' => '\w*',
'U' => '\d*', 'z' => '[+-]?\d*', 'O' => '[+-]?\d{4}',
//Using S instead of w and 3 as well as 4 to pick up non-ASCII chars like German umlaute.
// Per http://drupal.org/node/1101294, we may need as little as 2 and as many as 5 characters
// in some languages.
'D' => '\S{2,5}', 'l' => '\S*', 'M' => '\S{2,5}', 'F' => '\S*',
'P' => '[+-]?\d{2}\:\d{2}',
'c' => '(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})([+-]?\d{2}\:\d{2})',
'r' => '(\w{3}), (\d{2})\s(\w{3})\s(\d{2,4})\s(\d{2}):(\d{2}):(\d{2})([+-]?\d{4})?',
);
}
/**
* Array of granularity options and their labels
*
* @return array
*/
function date_granularity_names() {
return array(
'year' => date_t('Year', 'datetime'),
'month' => date_t('Month', 'datetime'),
'day' => date_t('Day', 'datetime'),
'hour' => date_t('Hour', 'datetime'),
'minute' => date_t('Minute', 'datetime'),
'second' => date_t('Second', 'datetime'),
);
}
/**
* Sort a granularity array.
*/
function date_granularity_sorted($granularity) {
return array_intersect(array('year', 'month', 'day', 'hour', 'minute', 'second'), $granularity);
}
/**
* Give a granularity $precision, return an array of
* all the possible granularity elements.
*/
function date_granularity_array_from_precision($precision) {
$granularity_array = array('year', 'month', 'day', 'hour', 'minute', 'second');
switch (($precision)) {
case 'year':
return array_slice($granularity_array, -6);
case 'month':
return array_slice($granularity_array, -5);
case 'day':
return array_slice($granularity_array, -4);
case 'hour':
return array_slice($granularity_array, -3);
case 'minute':
return array_slice($granularity_array, -2);
default:
return $granularity_array;
}
}
/**
* Give a granularity array, return the highest precision.
*/
function date_granularity_precision($granularity_array) {
$input = date_granularity_sorted($granularity_array);
return array_pop($input);
}
/**
* Construct an appropriate DATETIME format string for the granularity of an item.
*/
function date_granularity_format($granularity) {
if (is_array($granularity)) {
$granularity = date_granularity_precision($granularity);
}
$format = 'Y-m-d H:i:s';
switch ($granularity) {
case 'year':
return drupal_substr($format, 0, 1);
case 'month':
return drupal_substr($format, 0, 3);
case 'day':
return drupal_substr($format, 0, 5);
case 'hour';
return drupal_substr($format, 0, 7);
case 'minute':
return drupal_substr($format, 0, 9);
default:
return $format;
}
}
/**
* A translated array of timezone names.
* Cache the untranslated array, make the translated array a static variable.
*
* @param $required
* If not required, returned array will include a blank value.
* @return
* an array of timezone names
*/
function date_timezone_names($required = FALSE, $refresh = FALSE) {
static $zonenames;
if (empty($zonenames) || $refresh) {
$cached = cache_get('date_timezone_identifiers_list');
$zonenames = !empty($cached) ? $cached->data : array();
if ($refresh || empty($cached) || empty($zonenames)) {
$data = timezone_identifiers_list();
asort($data);
// Use include instead of include once in case the function gets
// refreshed via devel or other API and is called more than once.
if (module_exists('date_php4')) {
include('./'. drupal_get_path('module', 'date_php4') .'/date_php4_missing_data.inc');
}
foreach ($data as $delta => $zone) {
// Because many time zones exist in PHP only for backward
// compatibility reasons and should not be used, the list is
// filtered by a regular expression.
if (preg_match('!^((Africa|America|Antarctica|Arctic|Asia|Atlantic|Australia|Europe|Indian|Pacific)/|UTC$)!', $zone)) {
$zonenames[$zone] = $zone;
}
}
// If using PHP4, filter the list down to only the timezones
// the PHP4 wrapper has data for.
if (module_exists('date_php4')) {
foreach ($missing_timezone_data as $zone) {
unset($zonenames[$zone]);
}
}
// If using Event, further filter the list down to only
// zones that exist in the event module.
if (module_exists('event') && db_table_exists('event_timezones')) {
$result = db_query("SELECT name FROM {event_timezones} ORDER BY name");
$names = array();
while ($row = db_fetch_array($result)) {
$names[] = str_replace(' ', '_', $row['name']);
}
foreach ($zonenames as $name => $zone) {
if (!in_array($name, $names)) {
unset($zonenames[$name]);
}
}
}
if (!empty($zonenames)) {
cache_set('date_timezone_identifiers_list', $zonenames);
}
}
foreach ($zonenames as $zone) {
$zonenames[$zone] = t('!timezone', array('!timezone' => t($zone)));
}
}
$none = array('' => '');
return !$required ? $none + $zonenames : $zonenames;
}
/**
* An array of timezone abbreviations that the system allows.
* Cache an array of just the abbreviation names because the
* whole timezone_abbreviations_list is huge so we don't want
* to get it more than necessary.
*
* @return array
*/
function date_timezone_abbr($refresh = FALSE) {
$cached = cache_get('date_timezone_abbreviations');
$data = isset($cached->data) ? $cached->data : array();
if (empty($data) || $refresh) {
$data = array_keys(timezone_abbreviations_list());
cache_set('date_timezone_abbreviations', $data);
}
return $data;
}
/**
* A function to translate ambiguous short date strings.
*
* Example: Pass in 'Monday', 'day_abbr' and get the translated
* abbreviation for Monday.
*
* @param string $string
* @param string $context
* @param int $langcode
* @return translated value of the string
*/
function date_t($string, $context, $langcode = NULL) {
static $replace = array();
if (empty($replace[$langcode])) {
// The function to create the date string arrays is kept separate
// so those arrays can be directly accessed by other functions.
date_t_strings($replace, $langcode);
}
switch ($context) {
case 'day_name':
case 'day_abbr':
case 'day_abbr1':
case 'day_abbr2':
$untranslated = array_flip(date_week_days_untranslated());
break;
case 'month_name':
case 'month_abbr':
$untranslated = array_flip(date_month_names_untranslated());
break;
case 'ampm':
$untranslated = array_flip(array('am', 'pm', 'AM', 'PM'));
break;
case 'datetime':
$untranslated = array_flip(array('Year', 'Month', 'Day', 'Week', 'Hour', 'Minute', 'Second', 'All Day', 'All day'));
break;
case 'datetime_plural':
$untranslated = array_flip(array('Years', 'Months', 'Days', 'Weeks', 'Hours', 'Minutes', 'Seconds'));
break;
case 'date_order':
$untranslated = array_flip(array('Every', 'First', 'Second', 'Third', 'Fourth', 'Fifth'));
break;
case 'date_order_reverse':
$untranslated = array_flip(array('', 'Last', 'Next to last', 'Third from last', 'Fourth from last', 'Fifth from last'));
break;
case 'date_nav':
$untranslated = array_flip(array('Prev', 'Next', 'Today'));
break;
}
$pos = $untranslated[$string];
return $replace[$langcode][$context][$pos];
}
/**
* Construct translation arrays from pipe-delimited strings.
*
* Combining these strings into a single t() gives them the context needed
* for better translation.
*/
function date_t_strings(&$replace, $langcode) {
$replace[$langcode]['day_name'] = explode('|', trim(t('!day-name Sunday|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday', array('!day-name' => ''), $langcode)));
$replace[$langcode]['day_abbr'] = explode('|', trim(t('!day-abbreviation Sun|Mon|Tue|Wed|Thu|Fri|Sat', array('!day-abbreviation' => ''), $langcode)));
$replace[$langcode]['day_abbr1'] = explode('|', trim(t('!day-abbreviation S|M|T|W|T|F|S', array('!day-abbreviation' => ''), $langcode)));
$replace[$langcode]['day_abbr2'] = explode('|', trim(t('!day-abbreviation SU|MO|TU|WE|TH|FR|SA', array('!day-abbreviation' => ''), $langcode)));
$replace[$langcode]['ampm'] = explode('|', trim(t('!ampm-abbreviation am|pm|AM|PM', array('!ampm-abbreviation' => ''), $langcode)));
$replace[$langcode]['datetime'] = explode('|', trim(t('!datetime Year|Month|Day|Week|Hour|Minute|Second|All Day|All day', array('!datetime' => ''), $langcode)));
$replace[$langcode]['datetime_plural'] = explode('|', trim(t('!datetime_plural Years|Months|Days|Weeks|Hours|Minutes|Seconds', array('!datetime_plural' => ''), $langcode)));
$replace[$langcode]['date_order'] = explode('|', trim(t('!date_order Every|First|Second|Third|Fourth|Fifth', array('!date_order' => ''), $langcode)));
$replace[$langcode]['date_order_reverse'] = explode('|', trim(t('!date_order |Last|Next to last|Third from last|Fourth from last|Fifth from last', array('!date_order' => ''), $langcode)));
$replace[$langcode]['date_nav'] = explode('|', trim(t('!date_nav Prev|Next|Today', array('!date_nav' => ''), $langcode)));
// These start with a pipe so the January value will be in position 1 instead of position 0.
$replace[$langcode]['month_name'] = explode('|', trim(t('!month-name |January|February|March|April|May|June|July|August|September|October|November|December', array('!month-name' => ''), $langcode)));
$replace[$langcode]['month_abbr'] = explode('|', trim(t('!month-abbreviation |Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec', array('!month-abbreviation' => ''), $langcode)));
}
/**
* Reworked from Drupal's format_date function to handle pre-1970 and
* post-2038 dates and accept a date object instead of a timestamp as input.
*
* Translates formatted date results, unlike PHP function date_format().
*
* @param $date
* A date object, could be created by date_make_date().
* @param $type
* The format to use. Can be "small", "medium" or "large" for the preconfigured
* date formats. If "custom" is specified, then $format is required as well.
* @param $format
* A PHP date format string as required by date(). A backslash should be used
* before a character to avoid interpreting the character as part of a date
* format.
* @return
* A translated date string in the requested format.
*/
function date_format_date($date, $type = 'medium', $format = '', $langcode = NULL) {
if (empty($date)) {
return '';
}
if (function_exists('timezone_name_from_abbr') && get_class($date) != 'DateTime') {
$date = date_make_date($date);
}
switch ($type) {
case 'small':
case 'short':
$format = variable_get('date_format_short', 'm/d/Y - H:i');
break;
case 'large':
case 'long':
$format = variable_get('date_format_long', 'l, F j, Y - H:i');
break;
case 'custom':
$format = $format;
break;
case 'medium':
default:
$format = variable_get('date_format_medium', 'D, m/d/Y - H:i');
}
$max = drupal_strlen($format);
$datestring = '';
for ($i = 0; $i < $max; $i++) {
$c = $format[$i];
switch ($c) {
// Use date_t() for ambiguous short strings that need translation.
// We send long day and month names to date_t(), along with context.
case 'l':
$datestring .= date_t(date_format($date, 'l'), 'day_name', $langcode);
break;
case 'D':
$datestring .= date_t(date_format($date, 'l'), 'day_abbr', $langcode);
break;
case 'F':
$datestring .= date_t(date_format($date, 'F'), 'month_name', $langcode);
break;
case 'M':
$datestring .= date_t(date_format($date, 'F'), 'month_abbr', $langcode);
break;
case 'A':
case 'a':
$datestring .= date_t(date_format($date, $c), 'ampm', $langcode);
break;
// The timezone name translations can use t().
case 'e':
case 'T':
$datestring .= t(date_format($date, $c));
break;
// Remaining date parts need no translation.
case 'O':
$datestring .= sprintf('%s%02d%02d', (date_offset_get($date) < 0 ? '-' : '+'), abs(date_offset_get($date) / 3600), abs(date_offset_get($date) % 3600) / 60);
break;
case 'P':
$datestring .= sprintf('%s%02d:%02d', (date_offset_get($date) < 0 ? '-' : '+'), abs(date_offset_get($date) / 3600), abs(date_offset_get($date) % 3600) / 60);
break;
case 'Z':
$datestring .= date_offset_get($date);
break;
case '\\':
$datestring .= $format[++$i];
break;
case 'r':
$datestring .= date_format_date($date, 'custom', 'D, d M Y H:i:s O', $langcode);
break;
default:
if (strpos('BdcgGhHiIjLmnNosStTuUwWYyz', $c) !== FALSE) {
$datestring .= date_format($date, $c);
}
else {
$datestring .= $c;
}
}
}
return $datestring;
}
/**
* An override for interval formatting that adds past and future context
*
* @param DateTime $date
* @param integer $granularity
* @return formatted string
*/
function date_format_interval($date, $granularity = 2) {
// If no date is sent, then return nothing
if (empty($date)) {
return NULL;
}
$interval = time() - date_format($date, 'U');
if ($interval > 0 ) {
return t('!time ago', array('!time' => format_interval($interval, $granularity)));
}
else {
return format_interval(abs($interval), $granularity);
}
}
/**
* A date object for the current time.
*
* @param $timezone
* Optional method to force time to a specific timezone,
* defaults to user timezone, if set, otherwise site timezone.
* @return object date
*/
function date_now($timezone = NULL) {
return date_make_date('now', $timezone);
}
/**
* Convert a date of any type or an array of date parts into a valid date
* object.
* @param $date
* A date in any format or the string 'now'.
* @param $timezone
* Optional, the name of the timezone this date is in, defaults
* to the user timezone, if set, otherwise the site timezone.
* Accepts either a timezone name or a timezone object as input.
* @param $type
* The type of date provided, could be
* DATE_ARRAY, DATE_UNIX, DATE_DATETIME, DATE_ISO, or DATE_OBJECT.
* @param $granularity
* The granularity of the date value provided. Set this for partial
* dates so they pass validation and don't get reset to 'now'.
*/
function date_make_date($date, $timezone = NULL, $type = DATE_DATETIME, $granularity = array('year', 'month', 'day', 'hour', 'minute')) {
// Make sure some value is set for the date and timezone even if the
// site timezone is not yet set up to avoid fatal installation
// errors.
if (empty($timezone) || !date_timezone_is_valid($timezone)) {
$timezone = date_default_timezone_name();
}
// Special handling for a unix timestamp of '0', since it will fail 'empty' tests below.
if ($date === 0 && $type == DATE_UNIX) {
$date = date_convert($date, $type, DATE_DATETIME, $timezone);
$type = DATE_DATETIME;
}
// No value or one with unexpected array keys.
if (empty($date) || (is_array($date) && array_diff($granularity, array_keys($date)))) {
return NULL;
}
// Special handling for partial dates that don't need precision.
$granularity_sorted = date_granularity_sorted($granularity);
$max_granularity = end($granularity_sorted);
if (in_array($max_granularity, array('year', 'month')) || $type == DATE_ISO || $type == DATE_ARRAY) {
if ($type == DATE_UNIX) {
$date = date_convert($date, $type, DATE_DATETIME);
}
$date = date_fuzzy_datetime($date);
$type = DATE_DATETIME;
}
if (!date_is_valid($date, $type, $granularity)) {
$date = 'now';
}
if (!empty($timezone) && !empty($date)) {
if ($date == 'now') {
return date_create('now', timezone_open($timezone));
}
elseif ($datetime = date_convert($date, $type, DATE_DATETIME, $timezone)) {
return date_create($datetime, timezone_open($timezone));
}
}
return NULL;
}
function date_timezone_is_valid($timezone) {
static $timezone_names;
if (empty($timezone_names)) {
$timezone_names = array_keys(date_timezone_names(TRUE));
}
if (!in_array($timezone, $timezone_names)) {
return FALSE;
}
return TRUE;
}
/**
* Return a timezone name to use as a default.
*
* @return a timezone name
* Identify the default timezone for a user, if available, otherwise the site.
* Must return a value even if no timezone info has been set up.
*/
function date_default_timezone_name($check_user = TRUE) {
global $user;
if ($check_user && variable_get('configurable_timezones', 1) && !empty($user->timezone_name)) {
return $user->timezone_name;
}
else {
$default = variable_get('date_default_timezone_name', '');
return empty($default) ? 'UTC' : $default;
}
}
/**
* A timezone object for the default timezone.
*
* @return a timezone object
* Identify the default timezone for a user, if available, otherwise the site.
*/
function date_default_timezone($check_user = TRUE) {
$timezone = date_default_timezone_name($check_user);
return timezone_open(date_default_timezone_name($check_user));
}
/**
* Identify the number of days in a month for a date.
*/
function date_days_in_month($year, $month) {
// Pick a day in the middle of the month to avoid timezone shifts.
$datetime = date_pad($year, 4) .'-'. date_pad($month) .'-15 00:00:00';
// Just number of days calculation. No need to worry about timezone.
$date = date_create($datetime);
return date_format($date, 't');
}
/**
* Identify the number of days in a year for a date.
*
* @param mixed $date
* @param string $type
* @return integer
*/
function date_days_in_year($date = NULL, $type = DATE_OBJECT) {
if (empty($date)) {
$date = date_now();
}
if (!is_object($date)) {
$date = date_convert($date, $type, DATE_OBJECT);
}
if (is_object($date)) {
if (date_format($date, 'L')) {
return 366;
}
else {
return 365;
}
}
return NULL;
}
/**
* Identify the number of ISO weeks in a year for a date.
*
* December 28 is always in the last ISO week of the year.
*
* @param mixed $date
* @param string $type
* @return integer
*/
function date_iso_weeks_in_year($date = NULL, $type = DATE_OBJECT) {
if (empty($date)) {
$date = date_now();
}
if (!is_object($date)) {
$date = date_convert($date, $type, DATE_OBJECT);
}
if (is_object($date)) {
date_date_set($date, date_format($date, 'Y'), 12, 28);
return date_format($date, 'W');
}
return NULL;
}
/**
* Returns day of week for a given date (0 = Sunday).
*
* @param mixed $date
* a date, default is current local day
* @param string $type
* The type of date, DATE_ISO, DATE_DATETIME, or DATE_UNIX
* @return
* the number of the day in the week
*/
function date_day_of_week($date = NULL, $type = DATE_OBJECT) {
if (empty($date)) {