1<?php
2
3/**
4 * OpenID protocol key-value/comma-newline format parsing and
5 * serialization
6 *
7 * PHP versions 4 and 5
8 *
9 * LICENSE: See the COPYING file included in this distribution.
10 *
11 * @access private
12 * @package OpenID
13 * @author JanRain, Inc. <openid@janrain.com>
14 * @copyright 2005-2008 Janrain, Inc.
15 * @license http://www.apache.org/licenses/LICENSE-2.0 Apache
16 */
17
18/**
19 * Container for key-value/comma-newline OpenID format and parsing
20 */
21class Auth_OpenID_KVForm {
22    /**
23     * Convert an OpenID colon/newline separated string into an
24     * associative array
25     *
26     * @static
27     * @access private
28     * @param string $kvs
29     * @param bool $strict
30     * @return array|bool
31     */
32    static function toArray($kvs, $strict=false)
33    {
34        $lines = explode("\n", $kvs);
35
36        $last = array_pop($lines);
37        if ($last !== '') {
38            array_push($lines, $last);
39            if ($strict) {
40                return false;
41            }
42        }
43
44        $values = [];
45
46        for ($lineno = 0; $lineno < count($lines); $lineno++) {
47            $line = $lines[$lineno];
48            $kv = explode(':', $line, 2);
49            if (count($kv) != 2) {
50                if ($strict) {
51                    return false;
52                }
53                continue;
54            }
55
56            $key = $kv[0];
57            $tkey = trim($key);
58            if ($tkey != $key) {
59                if ($strict) {
60                    return false;
61                }
62            }
63
64            $value = $kv[1];
65            $tval = trim($value);
66            if ($tval != $value) {
67                if ($strict) {
68                    return false;
69                }
70            }
71
72            $values[$tkey] = $tval;
73        }
74
75        return $values;
76    }
77
78    /**
79     * Convert an array into an OpenID colon/newline separated string
80     *
81     * @static
82     * @access private
83     * @param null|array $values
84     * @return null|string
85     */
86    static function fromArray($values)
87    {
88        if ($values === null) {
89            return null;
90        }
91
92        ksort($values);
93
94        $serialized = '';
95        foreach ($values as $key => $value) {
96            if (is_array($value)) {
97                list($key, $value) = [$value[0], $value[1]];
98            }
99
100            if (strpos($key, ':') !== false) {
101                return null;
102            }
103
104            if (strpos($key, "\n") !== false) {
105                return null;
106            }
107
108            if (strpos($value, "\n") !== false) {
109                return null;
110            }
111            $serialized .= "$key:$value\n";
112        }
113        return $serialized;
114    }
115}
116
117