aboutsummaryrefslogtreecommitdiffstats
path: root/vendor/sabre/vobject/lib/Property/Text.php
blob: ac8aa066b328ae0c7ea3beb6dd73d207b3a6278a (plain) (blame)
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
<?php

namespace Sabre\VObject\Property;

use Sabre\VObject\Component;
use Sabre\VObject\Document;
use Sabre\VObject\Parser\MimeDir;
use Sabre\VObject\Property;
use Sabre\Xml;

/**
 * Text property.
 *
 * This object represents TEXT values.
 *
 * @copyright Copyright (C) fruux GmbH (https://fruux.com/)
 * @author Evert Pot (http://evertpot.com/)
 * @license http://sabre.io/license/ Modified BSD License
 */
class Text extends Property
{
    /**
     * In case this is a multi-value property. This string will be used as a
     * delimiter.
     *
     * @var string
     */
    public $delimiter = ',';

    /**
     * List of properties that are considered 'structured'.
     *
     * @var array
     */
    protected $structuredValues = [
        // vCard
        'N',
        'ADR',
        'ORG',
        'GENDER',
        'CLIENTPIDMAP',

        // iCalendar
        'REQUEST-STATUS',
    ];

    /**
     * Some text components have a minimum number of components.
     *
     * N must for instance be represented as 5 components, separated by ;, even
     * if the last few components are unused.
     *
     * @var array
     */
    protected $minimumPropertyValues = [
        'N' => 5,
        'ADR' => 7,
    ];

    /**
     * Creates the property.
     *
     * You can specify the parameters either in key=>value syntax, in which case
     * parameters will automatically be created, or you can just pass a list of
     * Parameter objects.
     *
     * @param Component         $root       The root document
     * @param string            $name
     * @param string|array|null $value
     * @param array             $parameters List of parameters
     * @param string            $group      The vcard property group
     */
    public function __construct(Component $root, $name, $value = null, array $parameters = [], $group = null)
    {
        // There's two types of multi-valued text properties:
        // 1. multivalue properties.
        // 2. structured value properties
        //
        // The former is always separated by a comma, the latter by semi-colon.
        if (in_array($name, $this->structuredValues)) {
            $this->delimiter = ';';
        }

        parent::__construct($root, $name, $value, $parameters, $group);
    }

    /**
     * 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
     */
    public function setRawMimeDirValue($val)
    {
        $this->setValue(MimeDir::unescapeValue($val, $this->delimiter));
    }

    /**
     * Sets the value as a quoted-printable encoded string.
     *
     * @param string $val
     */
    public function setQuotedPrintableValue($val)
    {
        $val = quoted_printable_decode($val);

        // Quoted printable only appears in vCard 2.1, and the only character
        // that may be escaped there is ;. So we are simply splitting on just
        // that.
        //
        // We also don't have to unescape \\, so all we need to look for is a ;
        // that's not preceded with a \.
        $regex = '# (?<!\\\\) ; #x';
        $matches = preg_split($regex, $val);
        $this->setValue($matches);
    }

    /**
     * Returns a raw mime-dir representation of the value.
     *
     * @return string
     */
    public function getRawMimeDirValue()
    {
        $val = $this->getParts();

        if (isset($this->minimumPropertyValues[$this->name])) {
            $val = array_pad($val, $this->minimumPropertyValues[$this->name], '');
        }

        foreach ($val as &$item) {
            if (!is_array($item)) {
                $item = [$item];
            }

            foreach ($item as &$subItem) {
                $subItem = strtr(
                    $subItem,
                    [
                        '\\' => '\\\\',
                        ';' => '\;',
                        ',' => '\,',
                        "\n" => '\n',
                        "\r" => '',
                    ]
                );
            }
            $item = implode(',', $item);
        }

        return implode($this->delimiter, $val);
    }

    /**
     * Returns the value, in the format it should be encoded for json.
     *
     * This method must always return an array.
     *
     * @return array
     */
    public function getJsonValue()
    {
        // Structured text values should always be returned as a single
        // array-item. Multi-value text should be returned as multiple items in
        // the top-array.
        if (in_array($this->name, $this->structuredValues)) {
            return [$this->getParts()];
        }

        return $this->getParts();
    }

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

    /**
     * Turns the object back into a serialized blob.
     *
     * @return string
     */
    public function serialize()
    {
        // We need to kick in a special type of encoding, if it's a 2.1 vcard.
        if (Document::VCARD21 !== $this->root->getDocumentType()) {
            return parent::serialize();
        }

        $val = $this->getParts();

        if (isset($this->minimumPropertyValues[$this->name])) {
            $val = \array_pad($val, $this->minimumPropertyValues[$this->name], '');
        }

        // Imploding multiple parts into a single value, and splitting the
        // values with ;.
        if (\count($val) > 1) {
            foreach ($val as $k => $v) {
                $val[$k] = \str_replace(';', '\;', $v);
            }
            $val = \implode(';', $val);
        } else {
            $val = $val[0];
        }

        $str = $this->name;
        if ($this->group) {
            $str = $this->group.'.'.$this->name;
        }
        foreach ($this->parameters as $param) {
            if ('QUOTED-PRINTABLE' === $param->getValue()) {
                continue;
            }
            $str .= ';'.$param->serialize();
        }

        // If the resulting value contains a \n, we must encode it as
        // quoted-printable.
        if (false !== \strpos($val, "\n")) {
            $str .= ';ENCODING=QUOTED-PRINTABLE:';
            $lastLine = $str;
            $out = null;

            // The PHP built-in quoted-printable-encode does not correctly
            // encode newlines for us. Specifically, the \r\n sequence must in
            // vcards be encoded as =0D=OA and we must insert soft-newlines
            // every 75 bytes.
            for ($ii = 0; $ii < \strlen($val); ++$ii) {
                $ord = \ord($val[$ii]);
                // These characters are encoded as themselves.
                if ($ord >= 32 && $ord <= 126) {
                    $lastLine .= $val[$ii];
                } else {
                    $lastLine .= '='.\strtoupper(\bin2hex($val[$ii]));
                }
                if (\strlen($lastLine) >= 75) {
                    // Soft line break
                    $out .= $lastLine."=\r\n ";
                    $lastLine = null;
                }
            }
            if (!\is_null($lastLine)) {
                $out .= $lastLine."\r\n";
            }

            return $out;
        } else {
            $str .= ':'.$val;

            $str = \preg_replace(
                '/(
                    (?:^.)?         # 1 additional byte in first line because of missing single space (see next line)
                    .{1,74}         # max 75 bytes per line (1 byte is used for a single space added after every CRLF)
                    (?![\x80-\xbf]) # prevent splitting multibyte characters
                )/x',
                "$1\r\n ",
                $str
            );

            // remove single space after last CRLF
            return \substr($str, 0, -1);
        }
    }

    /**
     * This method serializes only the value of a property. This is used to
     * create xCard or xCal documents.
     *
     * @param Xml\Writer $writer XML writer
     */
    protected function xmlSerializeValue(Xml\Writer $writer)
    {
        $values = $this->getParts();

        $map = function ($items) use ($values, $writer) {
            foreach ($items as $i => $item) {
                $writer->writeElement(
                    $item,
                    !empty($values[$i]) ? $values[$i] : null
                );
            }
        };

        switch ($this->name) {
            // Special-casing the REQUEST-STATUS property.
            //
            // See:
            // http://tools.ietf.org/html/rfc6321#section-3.4.1.3
            case 'REQUEST-STATUS':
                $writer->writeElement('code', $values[0]);
                $writer->writeElement('description', $values[1]);

                if (isset($values[2])) {
                    $writer->writeElement('data', $values[2]);
                }
                break;

            case 'N':
                $map([
                    'surname',
                    'given',
                    'additional',
                    'prefix',
                    'suffix',
                ]);
                break;

            case 'GENDER':
                $map([
                    'sex',
                    'text',
                ]);
                break;

            case 'ADR':
                $map([
                    'pobox',
                    'ext',
                    'street',
                    'locality',
                    'region',
                    'code',
                    'country',
                ]);
                break;

            case 'CLIENTPIDMAP':
                $map([
                    'sourceid',
                    'uri',
                ]);
                break;

            default:
                parent::xmlSerializeValue($writer);
        }
    }

    /**
     * Validates the node for correctness.
     *
     * The following options are supported:
     *   - Node::REPAIR - If something is broken, and automatic repair may
     *                    be attempted.
     *
     * An array is returned with warnings.
     *
     * Every item in the array has the following properties:
     *    * level - (number between 1 and 3 with severity information)
     *    * message - (human readable message)
     *    * node - (reference to the offending node)
     *
     * @param int $options
     *
     * @return array
     */
    public function validate($options = 0)
    {
        $warnings = parent::validate($options);

        if (isset($this->minimumPropertyValues[$this->name])) {
            $minimum = $this->minimumPropertyValues[$this->name];
            $parts = $this->getParts();
            if (count($parts) < $minimum) {
                $warnings[] = [
                    'level' => $options & self::REPAIR ? 1 : 3,
                    'message' => 'The '.$this->name.' property must have at least '.$minimum.' values. It only has '.count($parts),
                    'node' => $this,
                ];
                if ($options & self::REPAIR) {
                    $parts = array_pad($parts, $minimum, '');
                    $this->setParts($parts);
                }
            }
        }

        return $warnings;
    }
}