aboutsummaryrefslogblamecommitdiffstats
path: root/vendor/sabre/vobject/lib/Property/VCard/DateAndOrTime.php
blob: 650e19cbfa0ea4b18419f500d6327c78d4e7a949 (plain) (tree)
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




















































































































































































































































































































































































































                                                                                                                                                                        
<?php

namespace Sabre\VObject\Property\VCard;

use DateTimeInterface;
use DateTimeImmutable;
use DateTime;
use Sabre\VObject\DateTimeParser;
use Sabre\VObject\InvalidDataException;
use Sabre\VObject\Property;
use Sabre\Xml;

/**
 * DateAndOrTime property.
 *
 * This object encodes DATE-AND-OR-TIME values.
 *
 * @copyright Copyright (C) fruux GmbH (https://fruux.com/)
 * @author Evert Pot (http://evertpot.com/)
 * @license http://sabre.io/license/ Modified BSD License
 */
class DateAndOrTime extends Property {

    /**
     * Field separator.
     *
     * @var null|string
     */
    public $delimiter = null;

    /**
     * Returns the type of value.
     *
     * This corresponds to the VALUE= parameter. Every property also has a
     * 'default' valueType.
     *
     * @return string
     */
    function getValueType() {

        return 'DATE-AND-OR-TIME';

    }

    /**
     * Sets a multi-valued property.
     *
     * You may also specify DateTime objects here.
     *
     * @param array $parts
     *
     * @return void
     */
    function setParts(array $parts) {

        if (count($parts) > 1) {
            throw new \InvalidArgumentException('Only one value allowed');
        }
        if (isset($parts[0]) && $parts[0] instanceof \DateTime) {
            $this->setDateTime($parts[0]);
        } else {
            parent::setParts($parts);
        }

    }

    /**
     * Updates the current value.
     *
     * This may be either a single, or multiple strings in an array.
     *
     * Instead of strings, you may also use DateTime here.
     *
     * @param string|array|\DateTime $value
     *
     * @return void
     */
    function setValue($value) {

        if ($value instanceof \DateTime) {
            $this->setDateTime($value);
        } else {
            parent::setValue($value);
        }

    }

    /**
     * Sets the property as a DateTime object.
     *
     * @param DateTimeInterface $dt
     *
     * @return void
     */
    function setDateTime(DateTimeInterface $dt) {

        $tz = $dt->getTimeZone();
        $isUtc = in_array($tz->getName(), ['UTC', 'GMT', 'Z']);

        if ($isUtc) {
            $value = $dt->format('Ymd\\THis\\Z');
        } else {
            // Calculating the offset.
            $value = $dt->format('Ymd\\THisO');
        }

        $this->value = $value;

    }

    /**
     * Returns a date-time value.
     *
     * Note that if this property contained more than 1 date-time, only the
     * first will be returned. To get an array with multiple values, call
     * getDateTimes.
     *
     * If no time was specified, we will always use midnight (in the default
     * timezone) as the time.
     *
     * If parts of the date were omitted, such as the year, we will grab the
     * current values for those. So at the time of writing, if the year was
     * omitted, we would have filled in 2014.
     *
     * @return DateTimeImmutable
     */
    function getDateTime() {

        $now = new DateTime();

        $tzFormat = $now->getTimezone()->getOffset($now) === 0 ? '\\Z' : 'O';
        $nowParts = DateTimeParser::parseVCardDateTime($now->format('Ymd\\This' . $tzFormat));

        $dateParts = DateTimeParser::parseVCardDateTime($this->getValue());

        // This sets all the missing parts to the current date/time.
        // So if the year was missing for a birthday, we're making it 'this
        // year'.
        foreach ($dateParts as $k => $v) {
            if (is_null($v)) {
                $dateParts[$k] = $nowParts[$k];
            }
        }
        return new DateTimeImmutable("$dateParts[year]-$dateParts[month]-$dateParts[date] $dateParts[hour]:$dateParts[minute]:$dateParts[second] $dateParts[timezone]");

    }

    /**
     * Returns the value, in the format it should be encoded for json.
     *
     * This method must always return an array.
     *
     * @return array
     */
    function getJsonValue() {

        $parts = DateTimeParser::parseVCardDateTime($this->getValue());

        $dateStr = '';

        // Year
        if (!is_null($parts['year'])) {

            $dateStr .= $parts['year'];

            if (!is_null($parts['month'])) {
                // If a year and a month is set, we need to insert a separator
                // dash.
                $dateStr .= '-';
            }

        } else {

            if (!is_null($parts['month']) || !is_null($parts['date'])) {
                // Inserting two dashes
                $dateStr .= '--';
            }

        }

        // Month
        if (!is_null($parts['month'])) {

            $dateStr .= $parts['month'];

            if (isset($parts['date'])) {
                // If month and date are set, we need the separator dash.
                $dateStr .= '-';
            }

        } elseif (isset($parts['date'])) {
            // If the month is empty, and a date is set, we need a 'empty
            // dash'
            $dateStr .= '-';
        }

        // Date
        if (!is_null($parts['date'])) {
            $dateStr .= $parts['date'];
        }


        // Early exit if we don't have a time string.
        if (is_null($parts['hour']) && is_null($parts['minute']) && is_null($parts['second'])) {
            return [$dateStr];
        }

        $dateStr .= 'T';

        // Hour
        if (!is_null($parts['hour'])) {

            $dateStr .= $parts['hour'];

            if (!is_null($parts['minute'])) {
                $dateStr .= ':';
            }

        } else {
            // We know either minute or second _must_ be set, so we insert a
            // dash for an empty value.
            $dateStr .= '-';
        }

        // Minute
        if (!is_null($parts['minute'])) {

            $dateStr .= $parts['minute'];

            if (!is_null($parts['second'])) {
                $dateStr .= ':';
            }

        } elseif (isset($parts['second'])) {
            // Dash for empty minute
            $dateStr .= '-';
        }

        // Second
        if (!is_null($parts['second'])) {
            $dateStr .= $parts['second'];
        }

        // Timezone
        if (!is_null($parts['timezone'])) {
            $dateStr .= $parts['timezone'];
        }

        return [$dateStr];

    }

    /**
     * This method serializes only the value of a property. This is used to
     * create xCard or xCal documents.
     *
     * @param Xml\Writer $writer  XML writer.
     *
     * @return void
     */
    protected function xmlSerializeValue(Xml\Writer $writer) {

        $valueType = strtolower($this->getValueType());
        $parts     = DateTimeParser::parseVCardDateAndOrTime($this->getValue());
        $value     = '';

        // $d = defined
        $d = function($part) use ($parts) {
            return !is_null($parts[$part]);
        };

        // $r = read
        $r = function($part) use ($parts) {
            return $parts[$part];
        };

        // From the Relax NG Schema.
        //
        // # 4.3.1
        // value-date = element date {
        //     xsd:string { pattern = "\d{8}|\d{4}-\d\d|--\d\d(\d\d)?|---\d\d" }
        //   }
        if (($d('year') ||  $d('month')  ||  $d('date'))
            && (!$d('hour') && !$d('minute') && !$d('second') && !$d('timezone'))) {

            if ($d('year') && $d('month') && $d('date')) {
                $value .= $r('year') . $r('month') . $r('date');
            } elseif ($d('year') && $d('month') && !$d('date')) {
                $value .= $r('year') . '-' . $r('month');
            } elseif (!$d('year') && $d('month')) {
                $value .= '--' . $r('month') . $r('date');
            } elseif (!$d('year') && !$d('month') && $d('date')) {
                $value .= '---' . $r('date');
            }

        // # 4.3.2
        // value-time = element time {
        //     xsd:string { pattern = "(\d\d(\d\d(\d\d)?)?|-\d\d(\d\d?)|--\d\d)"
        //                          ~ "(Z|[+\-]\d\d(\d\d)?)?" }
        //   }
        } elseif ((!$d('year') && !$d('month')  && !$d('date'))
                  && ($d('hour') ||  $d('minute') ||  $d('second'))) {

            if ($d('hour')) {
                $value .= $r('hour') . $r('minute') . $r('second');
            } elseif ($d('minute')) {
                $value .= '-' . $r('minute') . $r('second');
            } elseif ($d('second')) {
                $value .= '--' . $r('second');
            }

            $value .= $r('timezone');

        // # 4.3.3
        // value-date-time = element date-time {
        //     xsd:string { pattern = "(\d{8}|--\d{4}|---\d\d)T\d\d(\d\d(\d\d)?)?"
        //                          ~ "(Z|[+\-]\d\d(\d\d)?)?" }
        //   }
        } elseif ($d('date') && $d('hour')) {

            if ($d('year') && $d('month') && $d('date')) {
                $value .= $r('year') . $r('month') . $r('date');
            } elseif (!$d('year') && $d('month') && $d('date')) {
                $value .= '--' . $r('month') . $r('date');
            } elseif (!$d('year') && !$d('month') && $d('date')) {
                $value .= '---' . $r('date');
            }

            $value .= 'T' . $r('hour') . $r('minute') . $r('second') .
                      $r('timezone');

        }

        $writer->writeElement($valueType, $value);

    }

    /**
     * Sets a raw value coming from a mimedir (iCalendar/vCard) file.
     *
     * This has been 'unfolded', so only 1 line will be passed. Unescaping is
     * not yet done, but parameters are not included.
     *
     * @param string $val
     *
     * @return void
     */
    function setRawMimeDirValue($val) {

        $this->setValue($val);

    }

    /**
     * Returns a raw mime-dir representation of the value.
     *
     * @return string
     */
    function getRawMimeDirValue() {

        return implode($this->delimiter, $this->getParts());

    }

    /**
     * Validates the node for correctness.
     *
     * The following options are supported:
     *   Node::REPAIR - May attempt to automatically repair the problem.
     *
     * This method returns an array with detected problems.
     * Every element has the following properties:
     *
     *  * level - problem level.
     *  * message - A human-readable string describing the issue.
     *  * node - A reference to the problematic node.
     *
     * The level means:
     *   1 - The issue was repaired (only happens if REPAIR was turned on)
     *   2 - An inconsequential issue
     *   3 - A severe issue.
     *
     * @param int $options
     *
     * @return array
     */
    function validate($options = 0) {

        $messages = parent::validate($options);
        $value = $this->getValue();

        try {
            DateTimeParser::parseVCardDateTime($value);
        } catch (InvalidDataException $e) {
            $messages[] = [
                'level'   => 3,
                'message' => 'The supplied value (' . $value . ') is not a correct DATE-AND-OR-TIME property',
                'node'    => $this,
            ];
        }

        return $messages;

    }
}