/
field.datetime.php
1078 lines (904 loc) · 31.5 KB
/
field.datetime.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
/**
* @package datetime
*/
/**
* This field provides an interface to manage single or multiple dates as well as date ranges.
*/
if(!defined('__IN_SYMPHONY__')) die('<h2>Symphony Error</h2><p>You cannot directly access this file</p>');
require_once TOOLKIT . '/fields/field.date.php';
require_once(EXTENSIONS . '/datetime/lib/class.calendar.php');
Class fieldDatetime extends fieldDate {
const SIMPLE = 0;
const REGEXP = 1;
const RANGE = 10;
const START = 11;
const END = 12;
const STRICT = 13;
const EXTRANGE = 14;
const ERROR = 20;
function __construct() {
parent::__construct();
$this->_name = __('Date/Time');
$this->_required = true;
$this->set('location', 'sidebar');
}
/*-------------------------------------------------------------------------
Definition:
-------------------------------------------------------------------------*/
function canPrePopulate() {
return false;
}
/**
* Method that flag the DS to add a DISTINCT keyword when retreiving entries
* @see symphony/lib/toolkit/Field::requiresSQLGrouping()
* @see http://symphony-cms.com/learn/api/2.3/toolkit/field/#requiresSQLGrouping
*/
public function requiresSQLGrouping(){
return true;
}
/*-------------------------------------------------------------------------
Setup:
-------------------------------------------------------------------------*/
function createTable() {
return Symphony::Database()->query(
"CREATE TABLE IF NOT EXISTS `tbl_entries_data_" . $this->get('id') . "` (
`id` int(11) unsigned NOT NULL auto_increment,
`entry_id` int(11) unsigned NOT NULL,
`start` datetime NOT NULL,
`end` datetime NOT NULL,
PRIMARY KEY (`id`),
KEY `entry_id` (`entry_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;"
);
}
/*-------------------------------------------------------------------------
Utilities:
-------------------------------------------------------------------------*/
/**
* Create date element.
*
* @param string $start
* start date
* @param string $end
* end date
* @param mixed $class
* class names that will be added to the date element
* @param int $prepopulate
* if set to 1, prepopulate element with the current date
* @param int $time
* if set to 1, display time
* @return XMLElement
* returns a date element
*/
public static function createDate($element, $start=NULL, $end=NULL, $class=NULL, $prepopulate=1, $time=1) {
$classes = array();
// This is hacky: remove empty end dates
if($end == $start) {
$end = NULL;
}
// Range
if(isset($end)) {
$classes[] = 'range';
}
// Additional classes
if($class) {
$classes[] = $class;
}
// Get timer
if($time == 1) {
$cutter = '<div class="timer">' .
self::__createTimeline('start') .
self::__createTimeline('end') .
'</div>';
}
// Create element
return new XMLElement(
'li',
'<header>
<div>' .
self::__createDateField($element, 'start', $start, $time, $prepopulate) .
self::__createDateField($element, 'end', $end, $time) .
' </div>
</header>
<div class="dt-calendar content">' .
self::__createCalendar() .
$cutter .
'</div>',
array('class' => implode($classes, ' '))
);
}
/**
* Create a date input field containing the given date
*
* @param string $element
* the Symphony field name
* @param string $type
* either 'start' or 'end'
* @param string $date
* a date
* @param int $time
* display the time, if set to 1; either 1 or 0
* @param int $prepopulate
* prepopulate with current date, if set to 1; either 1 or 0
* @return string
* returns an input field as string
*/
private static function __createDateField($element, $type, $date, $time, $prepopulate=0) {
// Parse date
if(isset($date) || $prepopulate) {
$parsed = Calendar::formatDate($date, $time);
// Generate field
if($parsed['status'] == 'invalid') {
$class = 'invalid';
}
}
// Generate field
return '<input type="text" name="fields[' . $element . '][' . $type . '][]" value="' . $parsed['date'] . '" data-timestamp="' . $parsed['timestamp'] . '" class="' . $type . ' ' . $class . '" autocomplete="off" /><em class="' . $type . ' label"></em>';
}
private static function __createCalendar() {
return '<div class="date">
<nav>
<a class="previous">«</a>
<div class="switch">
<ul class="months"></ul>
<ul class="years"></ul>
</div>
<a class="next">»</a>
</nav>
<table>
<thead>
<tr>
<td>' . __('Sun') . '</td>
<td>' . __('Mon') . '</td>
<td>' . __('Tue') . '</td>
<td>' . __('Wed') . '</td>
<td>' . __('Thu') . '</td>
<td>' . __('Fri') . '</td>
<td>' . __('Sat') . '</td>
</tr>
</thead>
<tbody>
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>
</tbody>
</table>
</div>';
}
private static function __createTimeline($type) {
return '<div class="timeline ' . $type . '">
<span class="hour1"></span>
<span class="hour2"></span>
<span class="hour3"></span>
<span class="hour4"></span>
<span class="hour5"></span>
<span class="hour6"></span>
<span class="hour7"></span>
<span class="hour8"></span>
<span class="hour9"></span>
<span class="hour10"></span>
<span class="hour11"></span>
<span class="hour12"></span>
<span class="hour13"></span>
<span class="hour14"></span>
<span class="hour15"></span>
<span class="hour16"></span>
<span class="hour17"></span>
<span class="hour18"></span>
<span class="hour19"></span>
<span class="hour20"></span>
<span class="hour21"></span>
<span class="hour22"></span>
<span class="hour23"></span>
<div class="range">
<code>0:00</code>
<span class="start"></span>
<span class="active"></span>
<span class="end"></span>
</div>
</div>';
}
/**
* Get filtering mode from string.
*
* @param string $string
* A filter string
* @return string
* Returns the filter mode
*/
private function __getModeFromString(&$string) {
$string = trim($string);
// Filter by start date
if(strpos($string, 'start:') === 0) {
$this->__removeModeFromString($string);
$mode = self::START;
}
// Filter by end date
elseif(strpos($string, 'end:') === 0) {
$this->__removeModeFromString($string);
$mode = self::END;
}
// Filter by full range (strict)
elseif(strpos($string, 'strict:') === 0) {
$this->__removeModeFromString($string);
$mode = self::STRICT;
}
// Remove unsupported regular expressions prefixes in order to support Publish Filtering
elseif(strpos($string, 'regexp:') === 0) {
$this->__removeModeFromString($string);
$mode = self::RANGE;
}
// Filter by extended range (end date can be null)
elseif(strpos($string, 'extended:') === 0) {
$this->__removeModeFromString($string);
$mode = self::EXTRANGE;
}
// Filter by full range
else {
$mode = self::RANGE;
}
return $mode;
}
/**
* Remove filter mode from the first data source filter.
*
* @param string $string
* Current data source filter
*/
private function __removeModeFromString(&$string) {
$filter = explode(':', $string, 2);
$string = $filter[1];
}
/**
* Build range filter sql.
*
* @param array $data
* An array of all date ranges that have been set as filters
* @param string $joins
* Tables joins
* @param string $where
* Filter statements
* @param boolean $andOperation
* Connect filters with 'AND' if true, defaults to false
*/
public function buildRangeFilterSQL($data, &$joins, &$where, $andOperation = false) {
$field_id = $this->get('id');
// Get filter connection
if($andOperation) {
$connector = ' AND ';
}
else {
$connector = ' OR ';
}
// Prepare SQL
foreach($data as $range) {
// Filter mode
switch($range['mode']) {
// Filter by start date
case self::START:
if ($range['start'] == 'IS NULL') {
$tmp[] = "(`t$field_id`.start IS NULL)";
} else {
$tmp[] = "(`t$field_id`.start BETWEEN '" . $range['start'] . "' AND '" . $range['end'] . "')";
}
break;
// Filter by end date
case self::END:
if ($range['end'] == 'IS NULL') {
$tmp[] = "(`t$field_id`.end IS NULL)";
} else {
$tmp[] = "(`t$field_id`.end BETWEEN '" . $range['start'] . "' AND '" . $range['end'] . "')";
}
break;
// Filter by full date range, start and end have to be in range
case self::STRICT:
$tmp[] = "((`t$field_id`.start BETWEEN '" . $range['start'] . "' AND '" . $range['end'] . "') AND
(`t$field_id`.end BETWEEN '" . $range['start'] . "' AND '" . $range['end'] . "'))";
break;
// Filter by full date range, start or end have to be in range
case self::RANGE:
$tmp[] = "((`t$field_id`.start BETWEEN '" . $range['start'] . "' AND '" . $range['end'] . "') OR
(`t$field_id`.end BETWEEN '" . $range['start'] . "' AND '" . $range['end'] . "') OR
(`t$field_id`.start < '" . $range['start'] . "' AND `t$field_id`.end > '" . $range['end'] . "'))";
break;
// Filter by extended date range
case self::EXTRANGE:
$tmp[] = "((`t$field_id`.start BETWEEN '" . $range['start'] . "' AND '" . $range['end'] . "') OR
(`t$field_id`.end BETWEEN '" . $range['start'] . "' AND '" . $range['end'] . "') OR
(`t$field_id`.start < '" . $range['start'] . "' AND `t$field_id`.end > '" . $range['end'] . "') OR
(`t$field_id`.start < '" . $range['start'] . "' AND `t$field_id`.end = `t$field_id`.start))";
break;
}
}
// Build SQL
$this->lastWhere = implode($connector, $tmp);
$joins .= " LEFT JOIN `tbl_entries_data_$field_id` AS `t$field_id` ON `e`.`id` = `t$field_id`.entry_id ";
$where .= " AND (" . $this->lastWhere . ") ";
}
/*-------------------------------------------------------------------------
Settings:
-------------------------------------------------------------------------*/
function displaySettingsPanel(XMLElement &$wrapper, $errors = null) {
// Initialize field settings based on class defaults (name, placement)
field::displaySettingsPanel($wrapper, $errors);
/*-----------------------------------------------------------------------*/
$columns = new XMLElement('div', null, array('class' => 'two columns'));
$wrapper->appendChild($columns);
// Prepopulation
$checkbox = Widget::Input('fields[' . $this->get('sortorder') . '][prepopulate]', 'yes', 'checkbox');
if((int)$this->get('prepopulate') === 1) {
$checkbox->setAttribute('checked', 'checked');
}
$setting = new XMLElement('label', __('%s Pre-populate with current date', array($checkbox->generate())), array('class' => 'column'));
$columns->appendChild($setting);
// Time
$checkbox = Widget::Input('fields[' . $this->get('sortorder') . '][time]', 'yes', 'checkbox');
if((int)$this->get('time') === 1) {
$checkbox->setAttribute('checked', 'checked');
}
$setting = new XMLElement('label', __('%s Display time', array($checkbox->generate())), array('class' => 'column'));
$columns->appendChild($setting);
// Multiple dates
$checkbox = Widget::Input('fields[' . $this->get('sortorder') . '][multiple]', 'yes', 'checkbox');
if((int)$this->get('multiple') === 1) {
$checkbox->setAttribute('checked', 'checked');
}
$setting = new XMLElement('label', __('%s Allow multiple dates', array($checkbox->generate())), array('class' => 'column'));
$columns->appendChild($setting);
// Date ranges
$checkbox = Widget::Input('fields[' . $this->get('sortorder') . '][range]', 'yes', 'checkbox');
if((int)$this->get('range') === 1) {
$checkbox->setAttribute('checked', 'checked');
}
$setting = new XMLElement('label', __('%s Enable date ranges', array($checkbox->generate())), array('class' => 'column'));
$columns->appendChild($setting);
/*-----------------------------------------------------------------------*/
// General
$fieldset = new XMLElement('fieldset');
$group = new XMLElement('div', NULL, array('class' => 'two columns'));
$this->appendRequiredCheckbox($group);
$this->appendShowColumnCheckbox($group);
$fieldset->appendChild($group);
$wrapper->appendChild($fieldset);
}
function commit() {
// Prepare commit
if(!field::commit()) return false;
$id = $this->get('id');
if($id === false) return false;
// Set up fields
$fields = array();
$fields['field_id'] = $id;
$fields['prepopulate'] = ($this->get('prepopulate') ? 1 : 0);
$fields['time'] = ($this->get('time') ? 1 : 0);
$fields['multiple'] = ($this->get('multiple') ? 1 : 0);
$fields['range'] = ($this->get('range') ? 1 : 0);
return FieldManager::saveSettings($id, $fields);
}
/*-------------------------------------------------------------------------
Publish:
-------------------------------------------------------------------------*/
function displayPublishPanel(XMLElement &$wrapper, $data = null, $flagWithError = null, $fieldnamePrefix = null, $fieldnamePostfix = null, $entry_id = null) {
// Houston, we have problem: we've been called out of context!
if( !Symphony::Engine() instanceof Administration ){
return;
}
$callback = Administration::instance()->getPageCallback();
if($callback['context']['page'] != 'edit' && $callback['context']['page'] != 'new') {
return;
}
// Datetime
Administration::instance()->Page->addScriptToHead(URL . '/extensions/datetime/assets/datetime.publish.js', 103, false);
Administration::instance()->Page->addStylesheetToHead(URL . '/extensions/datetime/assets/datetime.publish.css', 'screen', 104, false);
// Calendar
Administration::instance()->Page->addStylesheetToHead(URL . '/extensions/datetime/assets/calendar.publish.css', 'screen', 105, false);
Administration::instance()->Page->addScriptToHead(URL . '/extensions/datetime/assets/calendar.publish.js', 106, false);
// Timer
Administration::instance()->Page->addStylesheetToHead(URL . '/extensions/datetime/assets/timer.publish.css', 'screen', 107, false);
Administration::instance()->Page->addScriptToHead(URL . '/extensions/datetime/assets/timer.publish.js', 108, false);
// Field label
$fieldname = 'fields[' .$this->get('element_name') . ']';
$label = new XMLElement('label', $this->get('label') . '<i>' . ($this->get('required') == 'no' ? __('Optional') : '') . '</i>');
$wrapper->appendChild($label);
// Get settings
$settings = array('dark', 'frame');
if((int)$this->get('multiple') === 1) {
$settings[] = 'multiple';
}
else {
$settings[] = 'single';
}
if((int)$this->get('prepopulate') === 1) {
$settings[] = 'prepopulate';
}
if((int)$this->get('range') === 0) {
$settings[] = 'simple';
}
// Create interface
$duplicator = new XMLElement('div', null, array(
'class' => implode(' ', $settings)
));
$list = new XMLElement('ol', null, array(
'data-add' => __('Add date'),
'data-remove' => __('Remove')
));
// Existing dates
if(is_array($data)) {
if(!is_array($data['start'])) $data['start'] = array($data['start']);
if(!is_array($data['end'])) $data['end'] = array($data['end']);
for($i = 0; $i < count($data['start']); $i++) {
$list->appendChild(
self::createDate($this->get('element_name'), $data['start'][$i], $data['end'][$i], NULL, $this->get('prepopulate'), $this->get('time'))
);
}
}
// Current date and time
elseif((int)$this->get('prepopulate') === 1 || (int)$this->get('multiple') === 0) {
$list->appendChild(
self::createDate($this->get('element_name'), NULL, NULL, NULL, $this->get('prepopulate'), $this->get('time'))
);
}
// Add template
if((int)$this->get('multiple') === 1) {
$template = self::createDate($this->get('element_name'), NULL, NULL, 'template', $this->get('prepopulate'), $this->get('time'));
$template->setAttribute('data-name', 'datetime');
$template->setAttribute('data-type', 'datetime');
$list->appendChild($template);
}
// Append Duplicator
$duplicator->appendChild($list);
if(!is_null($flagWithError)) {
$wrapper->appendChild(Widget::Error($duplicator, $flagWithError));
}
else {
$wrapper->appendChild($duplicator);
}
}
public function checkPostFieldData($data, &$message, $entry_id = null) {
if($this->get('required') === 'yes' && empty($data['start'][0])) {
$message = __("‘%s’ is a required field.", array($this->get('label')));
return self::__MISSING_FIELDS__;
}
// @todo validate all dates and flag errors
return self::__OK__;
}
function processRawFieldData($data, &$status, &$message=null, $simulate=false, $entry_id=null) {
$status = self::__OK__;
if(!is_array($data)) return NULL;
// Clean up dates
$result = array('start' => array(), 'end' => array());
for($i = 0; $i < count($data['start']); $i++) {
if(!empty($data['start'][$i])) {
// Parse start date
$parsed = $this->parseDateTime($data['start'][$i]);
$result['start'][] = $parsed['date'];
// Empty end date
if(empty($data['end'][$i])) {
$result['end'][] = $parsed['date'];
}
// Specific end date
else {
$parsed = $this->parseDateTime($data['end'][$i]);
$result['end'][] = $parsed['date'];
}
}
}
// Result
if(empty($data['start'][0])) {
return NULL;
}
else {
return $result;
}
}
public function parseDateTime($dateString) {
$dateFormat = 'Y-m-d';
$timeFormat = 'H:i:s';
$format = !$this->get('time')
? "$dateFormat 00:00:00"
: "$dateFormat $timeFormat";
return Calendar::formatDate($dateString, true, $format);
}
/*-------------------------------------------------------------------------
Events:
-------------------------------------------------------------------------*/
public function getExampleFormMarkup() {
$label = Widget::Label($this->get('label'));
$label->appendChild(Widget::Input('fields['.$this->get('element_name').'][start][]'));
$label->appendChild(Widget::Input('fields['.$this->get('element_name').'][end][]'));
return $label;
}
/*-------------------------------------------------------------------------
Output:
-------------------------------------------------------------------------*/
public function appendFormattedElement(XMLElement &$wrapper, $data, $encode = false, $mode = null, $entry_id = null) {
$datetime = new XMLElement($this->get('element_name'));
// Prepare data
if(!is_array($data['start'])) $data['start'] = array($data['start']);
if(!is_array($data['end'])) $data['end'] = array($data['end']);
// Get timeline
$timeline = $data['start'];
sort($timeline);
// Generate XML
foreach($data['start'] as $id => $date) {
$date = new XMLElement('date');
$date->setAttribute('timeline', array_search($data['start'][$id], $timeline) + 1);
// Start date
$start = new DateTime($data['start'][$id]);
$date->appendChild(
$start = new XMLElement(
'start',
$start->format('Y-m-d'),
array(
'iso' => $start->format('c'),
'timestamp' => $start->getTimestamp(),
'time' => $start->format('H:i'),
'weekday' => $start->format('N'),
'offset' => $start->format('O')
)
)
);
// Date range
if($data['end'][$id] != $data['start'][$id]) {
$end = new DateTime($data['end'][$id]);
$date->appendChild(
$end = new XMLElement(
'end',
$end->format('Y-m-d'),
array(
'iso' => $end->format('c'),
'timestamp' => $end->getTimestamp(),
'time' => $end->format('H:i'),
'weekday' => $end->format('N'),
'offset' => $end->format('O')
)
)
);
$date->setAttribute('type', 'range');
}
// Single date
else {
$date->setAttribute('type', 'exact');
}
$datetime->appendChild($date);
}
// append date and time to data source
if(!empty($data['start'][0])) {
$wrapper->appendChild($datetime);
}
}
public function prepareTableValue($data, XMLElement $link = null, $entry_id = null) {
$values = implode(', <br />', $this->prepareTextArray($data, $entry_id, true));
if (empty($values)) {
$values = '<span class="inactive">' . __('No Date') . '</span>';
}
// Link?
if($link) {
$link->setValue($values);
return $link->generate();
}
return $values;
}
public function prepareReadableValue($data, $entry_id = null, $truncate = false, $defaultValue = null) {
$defaultValue = __('No Date');
return parent::prepareReadableValue($data, $entry_id, $truncate, $defaultValue);
}
public function prepareTextValue($data, $entry_id = null) {
return implode(', ', $this->prepareTextArray($data, $entry_id, false));
}
public function getScheme() {
$hasTime = (int)$this->get('time') === 1;
// Get schema
$scheme = trim($hasTime ? __SYM_DATETIME_FORMAT__ : __SYM_DATE_FORMAT__);
if (empty($scheme)) {
$scheme = $hasTime ? 'Y/m/d H:i:s' : 'Y/m/d';
}
return $scheme;
}
public function getTimeFormat() {
$timeFormat = trim(__SYM_TIME_FORMAT__);
return !empty($timeFormat) ? $timeFormat : 'H:i:s';
}
public function prepareTextArray($data, $entry_id, $html) {
if(!is_array($data['start'])) $data['start'] = array($data['start']);
if(!is_array($data['end'])) $data['end'] = array($data['end']);
// Handle empty dates
if(empty($data['start'][0])) {
return array();
}
$scheme = $this->getScheme();
$timeFormat = $this->getTimeFormat();
// Parse dates
$value = array();
for($i = 0; $i < count($data['start']); $i++) {
$start = new DateTime($data['start'][$i]);
$separator = ' – ';
// Date range
if($data['end'][$i] !== $data['start'][$i]) {
$end = new DateTime($data['end'][$i]);
// Different start and end days
if($start->format('d-m-Y') !== $end->format('d-m-Y')) {
$value[] = $this->getDatetime($start, $scheme, $html) . $separator . $this->getDatetime($end, $scheme, $html);
}
// Same day
else {
// Show time
if((int)$this->get('time') === 1) {
// Adjust separator
if($timeFormat == 'H:i') {
$separator = '–';
}
$value[] = $this->getDatetime($start, $scheme, $html) . $separator . $this->getDatetime($end, $timeFormat, $html);
}
// Hide time
else {
$value[] = $this->getDatetime($start, $scheme, $html);
}
}
}
// Single date
else {
$value[] = $this->getDatetime($start, $scheme, $html);
}
}
return $value;
}
public function getDatetime($date, $scheme, $html) {
if (!$html) {
return LANG::localizeDate($date->format($scheme));
}
return '<time datetime="' . $date->format('Y-m-d\TH:i:s\Z') . '">' . LANG::localizeDate($date->format($scheme)) . '</time>';
}
public function getParameterPoolValue(array $data, $entry_id=NULL) {
return $this->prepareExportValue($data, ExportableField::LIST_OF + ExportableField::VALUE, $entry_id);
}
/*-------------------------------------------------------------------------
Filtering:
-------------------------------------------------------------------------*/
private $lastWhere = '';
function buildDSRetrievalSQL($data, &$joins, &$where, $andOperation = false) {
// Parse dates
$dates = array();
foreach($data as $range) {
$mode = $this->__getModeFromString($range);
$result = self::parseFilter($range);
if($result !== FieldDate::ERROR && !empty($range)) {
$range['mode'] = $mode;
$dates[] = $range;
}
}
// Build filter SQL
if(!empty($dates)) {
$this->buildRangeFilterSQL($dates, $joins, $where, $andOperation);
}
else {
$this->lastWhere = '';
}
return true;
}
/*-------------------------------------------------------------------------
Sorting:
-------------------------------------------------------------------------*/
private function buildSortingSQLForTable($table, $field_id, $order) {
$sort = 'ORDER BY ';
// parse the last where clause used in filtering
$sortFilter = preg_replace( '/`t[0-9]+`/', '`m`', $this->lastWhere);
if (!$sortFilter) {
$sortFilter = '1=1';
}
else {
// clear the last where since it has been consumed
$this->lastWhere = '';
}
$op = 'MIN';
if( in_array( $order, array('random', 'rand') ) ){
$sort .= 'RAND()';
}
elseif( $order === 'asc' ){
$sort .= "`$table`.`start` $order, `$table`.`end` $order";
}
else{
$sort .= "`$table`.`start` $order";
$op = 'MAX';
}
$null_clause = '';
if ($this->get('required') != 'yes') {
$null_clause = " OR `$table`.`start` IS NULL";
}
$where = " AND (`$table`.`start` = (
SELECT $op(`m`.`start`) FROM `tbl_entries_data_".$field_id."`AS `m`
WHERE `m`.`entry_id` = `e`.`id` AND $sortFilter
GROUP BY `m`.`entry_id`
LIMIT 1
) $null_clause
)";
return array(
'sort' => $sort,
'where' => $where,
);
}
public function buildSortingSQL(&$joins, &$where, &$sort, $order = 'ASC'){
$field_id = $this->get( 'id' );
$order = strtolower( $order );
// If we already have a JOIN to the entry table, don't create another one,
// this prevents issues where an entry with multiple dates is returned multiple
// times in the SQL, but is actually the same entry.
if( !preg_match( '/`t'.$field_id.'`/', $joins ) ){
$joins .= "LEFT OUTER JOIN `tbl_entries_data_".$field_id."` AS `ed` ON (`e`.`id` = `ed`.`entry_id`) ";
$sql = $this->buildSortingSQLForTable('ed', $field_id, $order);
}
else {
$sql = $this->buildSortingSQLForTable("t$field_id", $field_id, $order);
}
$sort .= $sql['sort'];
$where .= $sql['where'];
}
public function buildSortingSelectSQL($sort, $order = 'ASC')
{
if ($this->isRandomOrder($order)) {
return null;
}
$field_id = $this->get('id');
if (!preg_match( '/`t'.$field_id.'`/', $sort)) {
return '`ed`.`start`, `ed`.`end`';
}
return "`t$field_id`.`start`, `t$field_id`.`end`";
}
/*-------------------------------------------------------------------------
Grouping:
-------------------------------------------------------------------------*/
public function groupRecords($records) {
if(!is_array($records) || empty($records)) return;
$groups = array('year' => array());
// Walk through dates
foreach($records as $entry) {
$data = $entry->getData($this->get('id'));
if(!is_array($data['start'])) $data['start'] = array($data['start']);
if(!is_array($data['end'])) $data['end'] = array($data['end']);
// Create calendar
for($i = 0; $i < count($data['start']); $i++) {
$start = new DateTime($data['start'][$i]);
$end = new DateTime($data['end'][$i]);
// Find matching months
while($start->format('Y-m-01') <= $end->format('Y-m-01')) {
$year = $start->format('Y');
$month = $start->format('n');
// Add entry
$groups['year'][$year]['attr']['value'] = $year;
$groups['year'][$year]['groups']['month'][$month]['attr']['value'] = $start->format('m');
$groups['year'][$year]['groups']['month'][$month]['records'][] = $entry;
// Jump to next month
$start->modify('+1 month');
}
}
}
// Sort years and months
ksort($groups['year']);
foreach($groups['year'] as $year) {
$current = $year['attr']['value'];
ksort($groups['year'][$current]['groups']['month']);
}
// Return calendar groups
return $groups;
}
/*-------------------------------------------------------------------------
Importing:
-------------------------------------------------------------------------*/
public function getImportModes() {
return array(
'getPostdata' => ImportableField::ARRAY_VALUE,
'getString' => ImportableField::STRING_VALUE
);
}
/**
* This function prepares values for import with XMLImporter
*
* @param string|array $data
* Data that should be prepared for import
* @param integer $entry_id
* The current entry_id, if it exists, otherwise null.
* @return array
* Return an associative array of start and end dates
*/
public function prepareImportValue($data, $mode, $entry_id = null) {
$message = $status = null;
$modes = (object)$this->getImportModes();
if($mode === $modes->getPostdata) {
if(!is_array($data)) $data = array($data);
if(is_array($data[0])) $data = $data[0];
// Reformat array
if(!array_key_exists('start', $data)) {
$datetime = array();
// Start date
$datetime['start'] = array($data[0]);
// End date
if($data[1]) {
$datetime['end'] = array($data[1]);
}
else {
$datetime['end'] = array($data[0]);
}
$data = $datetime;
}
return $this->processRawFieldData($data, $status, $message, true, $entry_id);
}
else if($mode === $modes->getString) {
$dates = explode(',', $data);
$data = array();
foreach($dates as $date_string) {
self::parseFilter($date_string);
$data['start'][] = $date_string['start'];
$data['end'][] = $date_string['end'];
}
return $this->processRawFieldData($data, $status, $message, true, $entry_id);
}
return null;
}
/*-------------------------------------------------------------------------