Merge "Add a test for named vs. positional parameter whitespace stripping"
[lhc/web/wiklou.git] / includes / Cookie.php
1 <?php
2 /**
3 * Cookie for HTTP requests.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @ingroup HTTP
22 */
23
24 class Cookie {
25 protected $name;
26 protected $value;
27 protected $expires;
28 protected $path;
29 protected $domain;
30 protected $isSessionKey = true;
31 // TO IMPLEMENT protected $secure
32 // TO IMPLEMENT? protected $maxAge (add onto expires)
33 // TO IMPLEMENT? protected $version
34 // TO IMPLEMENT? protected $comment
35
36 function __construct( $name, $value, $attr ) {
37 $this->name = $name;
38 $this->set( $value, $attr );
39 }
40
41 /**
42 * Sets a cookie. Used before a request to set up any individual
43 * cookies. Used internally after a request to parse the
44 * Set-Cookie headers.
45 *
46 * @param $value String: the value of the cookie
47 * @param $attr Array: possible key/values:
48 * expires A date string
49 * path The path this cookie is used on
50 * domain Domain this cookie is used on
51 * @throws MWException
52 */
53 public function set( $value, $attr ) {
54 $this->value = $value;
55
56 if ( isset( $attr['expires'] ) ) {
57 $this->isSessionKey = false;
58 $this->expires = strtotime( $attr['expires'] );
59 }
60
61 if ( isset( $attr['path'] ) ) {
62 $this->path = $attr['path'];
63 } else {
64 $this->path = '/';
65 }
66
67 if ( isset( $attr['domain'] ) ) {
68 if ( self::validateCookieDomain( $attr['domain'] ) ) {
69 $this->domain = $attr['domain'];
70 }
71 } else {
72 throw new MWException( 'You must specify a domain.' );
73 }
74 }
75
76 /**
77 * Return the true if the cookie is valid is valid. Otherwise,
78 * false. The uses a method similar to IE cookie security
79 * described here:
80 * http://kuza55.blogspot.com/2008/02/understanding-cookie-security.html
81 * A better method might be to use a blacklist like
82 * http://publicsuffix.org/
83 *
84 * @todo fixme fails to detect 3-letter top-level domains
85 * @todo fixme fails to detect 2-letter top-level domains for single-domain use (probably not a big problem in practice, but there are test cases)
86 *
87 * @param $domain String: the domain to validate
88 * @param $originDomain String: (optional) the domain the cookie originates from
89 * @return Boolean
90 */
91 public static function validateCookieDomain( $domain, $originDomain = null ) {
92 // Don't allow a trailing dot
93 if ( substr( $domain, -1 ) == '.' ) {
94 return false;
95 }
96
97 $dc = explode( ".", $domain );
98
99 // Only allow full, valid IP addresses
100 if ( preg_match( '/^[0-9.]+$/', $domain ) ) {
101 if ( count( $dc ) != 4 ) {
102 return false;
103 }
104
105 if ( ip2long( $domain ) === false ) {
106 return false;
107 }
108
109 if ( $originDomain == null || $originDomain == $domain ) {
110 return true;
111 }
112
113 }
114
115 // Don't allow cookies for "co.uk" or "gov.uk", etc, but allow "supermarket.uk"
116 if ( strrpos( $domain, "." ) - strlen( $domain ) == -3 ) {
117 if ( ( count( $dc ) == 2 && strlen( $dc[0] ) <= 2 )
118 || ( count( $dc ) == 3 && strlen( $dc[0] ) == "" && strlen( $dc[1] ) <= 2 ) ) {
119 return false;
120 }
121 if ( ( count( $dc ) == 2 || ( count( $dc ) == 3 && $dc[0] == '' ) )
122 && preg_match( '/(com|net|org|gov|edu)\...$/', $domain ) ) {
123 return false;
124 }
125 }
126
127 if ( $originDomain != null ) {
128 if ( substr( $domain, 0, 1 ) != '.' && $domain != $originDomain ) {
129 return false;
130 }
131
132 if ( substr( $domain, 0, 1 ) == '.'
133 && substr_compare( $originDomain, $domain, -strlen( $domain ),
134 strlen( $domain ), true ) != 0 ) {
135 return false;
136 }
137 }
138
139 return true;
140 }
141
142 /**
143 * Serialize the cookie jar into a format useful for HTTP Request headers.
144 *
145 * @param $path String: the path that will be used. Required.
146 * @param $domain String: the domain that will be used. Required.
147 * @return String
148 */
149 public function serializeToHttpRequest( $path, $domain ) {
150 $ret = '';
151
152 if ( $this->canServeDomain( $domain )
153 && $this->canServePath( $path )
154 && $this->isUnExpired() ) {
155 $ret = $this->name . '=' . $this->value;
156 }
157
158 return $ret;
159 }
160
161 /**
162 * @param $domain
163 * @return bool
164 */
165 protected function canServeDomain( $domain ) {
166 if ( $domain == $this->domain
167 || ( strlen( $domain ) > strlen( $this->domain )
168 && substr( $this->domain, 0, 1 ) == '.'
169 && substr_compare( $domain, $this->domain, -strlen( $this->domain ),
170 strlen( $this->domain ), true ) == 0 ) ) {
171 return true;
172 }
173
174 return false;
175 }
176
177 /**
178 * @param $path
179 * @return bool
180 */
181 protected function canServePath( $path ) {
182 return ( $this->path && substr_compare( $this->path, $path, 0, strlen( $this->path ) ) == 0 );
183 }
184
185 /**
186 * @return bool
187 */
188 protected function isUnExpired() {
189 return $this->isSessionKey || $this->expires > time();
190 }
191 }
192
193 class CookieJar {
194 private $cookie = array();
195
196 /**
197 * Set a cookie in the cookie jar. Make sure only one cookie per-name exists.
198 * @see Cookie::set()
199 */
200 public function setCookie ( $name, $value, $attr ) {
201 /* cookies: case insensitive, so this should work.
202 * We'll still send the cookies back in the same case we got them, though.
203 */
204 $index = strtoupper( $name );
205
206 if ( isset( $this->cookie[$index] ) ) {
207 $this->cookie[$index]->set( $value, $attr );
208 } else {
209 $this->cookie[$index] = new Cookie( $name, $value, $attr );
210 }
211 }
212
213 /**
214 * @see Cookie::serializeToHttpRequest
215 * @return string
216 */
217 public function serializeToHttpRequest( $path, $domain ) {
218 $cookies = array();
219
220 foreach ( $this->cookie as $c ) {
221 $serialized = $c->serializeToHttpRequest( $path, $domain );
222
223 if ( $serialized ) {
224 $cookies[] = $serialized;
225 }
226 }
227
228 return implode( '; ', $cookies );
229 }
230
231 /**
232 * Parse the content of an Set-Cookie HTTP Response header.
233 *
234 * @param $cookie String
235 * @param $domain String: cookie's domain
236 * @return null
237 */
238 public function parseCookieResponseHeader ( $cookie, $domain ) {
239 $len = strlen( 'Set-Cookie:' );
240
241 if ( substr_compare( 'Set-Cookie:', $cookie, 0, $len, true ) === 0 ) {
242 $cookie = substr( $cookie, $len );
243 }
244
245 $bit = array_map( 'trim', explode( ';', $cookie ) );
246
247 if ( count( $bit ) >= 1 ) {
248 list( $name, $value ) = explode( '=', array_shift( $bit ), 2 );
249 $attr = array();
250
251 foreach ( $bit as $piece ) {
252 $parts = explode( '=', $piece );
253 if ( count( $parts ) > 1 ) {
254 $attr[strtolower( $parts[0] )] = $parts[1];
255 } else {
256 $attr[strtolower( $parts[0] )] = true;
257 }
258 }
259
260 if ( !isset( $attr['domain'] ) ) {
261 $attr['domain'] = $domain;
262 } elseif ( !Cookie::validateCookieDomain( $attr['domain'], $domain ) ) {
263 return null;
264 }
265
266 $this->setCookie( $name, $value, $attr );
267 }
268 }
269 }