Merge "Separate select() parameter summary from detail"
[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 string $value The value of the cookie
47 * @param array $attr 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
86 * not a big problem in practice, but there are test cases)
87 *
88 * @param string $domain The domain to validate
89 * @param string $originDomain (optional) the domain the cookie originates from
90 * @return bool
91 */
92 public static function validateCookieDomain( $domain, $originDomain = null ) {
93 $dc = explode( ".", $domain );
94
95 // Don't allow a trailing dot or addresses without a or just a leading dot
96 if ( substr( $domain, -1 ) == '.' ||
97 count( $dc ) <= 1 ||
98 count( $dc ) == 2 && $dc[0] === '' ) {
99 return false;
100 }
101
102 // Only allow full, valid IP addresses
103 if ( preg_match( '/^[0-9.]+$/', $domain ) ) {
104 if ( count( $dc ) != 4 ) {
105 return false;
106 }
107
108 if ( ip2long( $domain ) === false ) {
109 return false;
110 }
111
112 if ( $originDomain == null || $originDomain == $domain ) {
113 return true;
114 }
115
116 }
117
118 // Don't allow cookies for "co.uk" or "gov.uk", etc, but allow "supermarket.uk"
119 if ( strrpos( $domain, "." ) - strlen( $domain ) == -3 ) {
120 if ( ( count( $dc ) == 2 && strlen( $dc[0] ) <= 2 )
121 || ( count( $dc ) == 3 && strlen( $dc[0] ) == "" && strlen( $dc[1] ) <= 2 ) ) {
122 return false;
123 }
124 if ( ( count( $dc ) == 2 || ( count( $dc ) == 3 && $dc[0] == '' ) )
125 && preg_match( '/(com|net|org|gov|edu)\...$/', $domain ) ) {
126 return false;
127 }
128 }
129
130 if ( $originDomain != null ) {
131 if ( substr( $domain, 0, 1 ) != '.' && $domain != $originDomain ) {
132 return false;
133 }
134
135 if ( substr( $domain, 0, 1 ) == '.'
136 && substr_compare(
137 $originDomain,
138 $domain,
139 -strlen( $domain ),
140 strlen( $domain ),
141 true
142 ) != 0
143 ) {
144 return false;
145 }
146 }
147
148 return true;
149 }
150
151 /**
152 * Serialize the cookie jar into a format useful for HTTP Request headers.
153 *
154 * @param string $path The path that will be used. Required.
155 * @param string $domain The domain that will be used. Required.
156 * @return string
157 */
158 public function serializeToHttpRequest( $path, $domain ) {
159 $ret = '';
160
161 if ( $this->canServeDomain( $domain )
162 && $this->canServePath( $path )
163 && $this->isUnExpired() ) {
164 $ret = $this->name . '=' . $this->value;
165 }
166
167 return $ret;
168 }
169
170 /**
171 * @param string $domain
172 * @return bool
173 */
174 protected function canServeDomain( $domain ) {
175 if ( $domain == $this->domain
176 || ( strlen( $domain ) > strlen( $this->domain )
177 && substr( $this->domain, 0, 1 ) == '.'
178 && substr_compare(
179 $domain,
180 $this->domain,
181 -strlen( $this->domain ),
182 strlen( $this->domain ),
183 true
184 ) == 0
185 )
186 ) {
187 return true;
188 }
189
190 return false;
191 }
192
193 /**
194 * @param string $path
195 * @return bool
196 */
197 protected function canServePath( $path ) {
198 return ( $this->path && substr_compare( $this->path, $path, 0, strlen( $this->path ) ) == 0 );
199 }
200
201 /**
202 * @return bool
203 */
204 protected function isUnExpired() {
205 return $this->isSessionKey || $this->expires > time();
206 }
207 }
208
209 class CookieJar {
210 private $cookie = array();
211
212 /**
213 * Set a cookie in the cookie jar. Make sure only one cookie per-name exists.
214 * @see Cookie::set()
215 * @param string $name
216 * @param string $value
217 * @param array $attr
218 */
219 public function setCookie( $name, $value, $attr ) {
220 /* cookies: case insensitive, so this should work.
221 * We'll still send the cookies back in the same case we got them, though.
222 */
223 $index = strtoupper( $name );
224
225 if ( isset( $this->cookie[$index] ) ) {
226 $this->cookie[$index]->set( $value, $attr );
227 } else {
228 $this->cookie[$index] = new Cookie( $name, $value, $attr );
229 }
230 }
231
232 /**
233 * @see Cookie::serializeToHttpRequest
234 * @param string $path
235 * @param string $domain
236 * @return string
237 */
238 public function serializeToHttpRequest( $path, $domain ) {
239 $cookies = array();
240
241 foreach ( $this->cookie as $c ) {
242 $serialized = $c->serializeToHttpRequest( $path, $domain );
243
244 if ( $serialized ) {
245 $cookies[] = $serialized;
246 }
247 }
248
249 return implode( '; ', $cookies );
250 }
251
252 /**
253 * Parse the content of an Set-Cookie HTTP Response header.
254 *
255 * @param string $cookie
256 * @param string $domain Cookie's domain
257 * @return null
258 */
259 public function parseCookieResponseHeader( $cookie, $domain ) {
260 $len = strlen( 'Set-Cookie:' );
261
262 if ( substr_compare( 'Set-Cookie:', $cookie, 0, $len, true ) === 0 ) {
263 $cookie = substr( $cookie, $len );
264 }
265
266 $bit = array_map( 'trim', explode( ';', $cookie ) );
267
268 if ( count( $bit ) >= 1 ) {
269 list( $name, $value ) = explode( '=', array_shift( $bit ), 2 );
270 $attr = array();
271
272 foreach ( $bit as $piece ) {
273 $parts = explode( '=', $piece );
274 if ( count( $parts ) > 1 ) {
275 $attr[strtolower( $parts[0] )] = $parts[1];
276 } else {
277 $attr[strtolower( $parts[0] )] = true;
278 }
279 }
280
281 if ( !isset( $attr['domain'] ) ) {
282 $attr['domain'] = $domain;
283 } elseif ( !Cookie::validateCookieDomain( $attr['domain'], $domain ) ) {
284 return null;
285 }
286
287 $this->setCookie( $name, $value, $attr );
288 }
289 }
290 }