Subversion Repositories Applications.papyrus

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
320 jpm 1
<?php
2
// +----------------------------------------------------------------------+
3
// | PEAR :: HTTP                                                         |
4
// +----------------------------------------------------------------------+
5
// | This source file is subject to version 3.0 of the PHP license,       |
6
// | that is available at http://www.php.net/license/3_0.txt              |
7
// | If you did not receive a copy of the PHP license and are unable      |
8
// | to obtain it through the world-wide-web, please send a note to       |
9
// | license@php.net so we can mail you a copy immediately.               |
10
// +----------------------------------------------------------------------+
11
// | Authors: Stig Bakken <ssb@fast.no>                                   |
12
// |          Sterling Hughes <sterling@php.net>                          |
13
// |          Tomas V.V.Cox <cox@idecnet.com>                             |
14
// |          Richard Heyes <richard@php.net>                             |
15
// |          Philippe Jausions <Philippe.Jausions@11abacus.com>          |
16
// |          Michael Wallner <mike@php.net>                              |
17
// +----------------------------------------------------------------------+
18
//
19
// $Id: HTTP.php,v 1.1 2005-03-30 08:50:19 jpm Exp $
20
 
21
/**
22
 * HTTP
23
 *
24
 * HTTP utility functions
25
 *
26
 * @package     HTTP
27
 * @category    HTTP
28
 * @license     PHP License
29
 * @access      public
30
 * @version     $Revision: 1.1 $
31
 */
32
class HTTP
33
{
34
    /**
35
     * Date
36
     *
37
     * Format a RFC compliant GMT date HTTP header.  This function honors the
38
     * "y2k_compliance" php.ini directive and formats the GMT date corresponding
39
     * to either RFC850 or RFC822.
40
     *
41
     * @static
42
     * @access  public
43
     * @return  mixed   GMT date string, or false for an invalid $time parameter
44
     * @param   mixed   $time unix timestamp or date (default = current time)
45
     */
46
    function Date($time = null)
47
    {
48
        if (!isset($time)) {
49
            $time = time();
50
        } elseif (!is_numeric($time) && (-1 === $time = strtotime($time))) {
51
            return false;
52
        }
53
 
54
        // RFC822 or RFC850
55
        $format = ini_get('y2k_compliance') ? 'D, d M Y' : 'l, d-M-y';
56
 
57
        return gmdate($format .' H:i:s \G\M\T', $time);
58
    }
59
 
60
    /**
61
     * Negotiate Language
62
     *
63
     * Negotiate language with the user's browser through the Accept-Language
64
     * HTTP header or the user's host address.  Language codes are generally in
65
     * the form "ll" for a language spoken in only one country, or "ll-CC" for a
66
     * language spoken in a particular country.  For example, U.S. English is
67
     * "en-US", while British English is "en-UK".  Portugese as spoken in
68
     * Portugal is "pt-PT", while Brazilian Portugese is "pt-BR".
69
     *
70
     * Quality factors in the Accept-Language: header are supported, e.g.:
71
     *      Accept-Language: en-UK;q=0.7, en-US;q=0.6, no, dk;q=0.8
72
     *
73
     * <code>
74
     *  require_once 'HTTP.php';
75
     *  $langs = array(
76
     *      'en'   => 'locales/en',
77
     *      'en-US'=> 'locales/en',
78
     *      'en-UK'=> 'locales/en',
79
     *      'de'   => 'locales/de',
80
     *      'de-DE'=> 'locales/de',
81
     *      'de-AT'=> 'locales/de',
82
     *  );
83
     *  $neg = HTTP::negotiateLanguage($langs);
84
     *  $dir = $langs[$neg];
85
     * </code>
86
     *
87
     * @static
88
     * @access  public
89
     * @return  string  The negotiated language result or the supplied default.
90
     * @param   array   $supported An associative array of supported languages,
91
     *                  whose values must evaluate to true.
92
     * @param   string  $default The default language to use if none is found.
93
     */
94
    function negotiateLanguage($supported, $default = 'en-US')
95
    {
96
        $supp = array();
97
        foreach ($supported as $lang => $isSupported) {
98
            if ($isSupported) {
99
                $supp[strToLower($lang)] = $lang;
100
            }
101
        }
102
 
103
        if (!count($supp)) {
104
            return $default;
105
        }
106
 
107
        $matches = array();
108
        if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
109
            foreach (explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']) as $lang) {
110
                $lang = array_map('trim', explode(';', $lang));
111
                if (isset($lang[1])) {
112
                    $l = strtolower($lang[0]);
113
                    $q = (float) str_replace('q=', '', $lang[1]);
114
                } else {
115
                    $l = strtolower($lang[0]);
116
                    $q = null;
117
                }
118
                if (isset($supp[$l])) {
119
                    $matches[$l] = isset($q) ? $q : 1000 - count($matches);
120
                }
121
            }
122
        }
123
 
124
        if (count($matches)) {
125
            asort($matches, SORT_NUMERIC);
126
            return $supp[array_pop(array_keys($matches))];
127
        }
128
 
129
        if (isset($_SERVER['REMOTE_HOST'])) {
130
            $lang = strtolower(array_pop(explode('.', $_SERVER['REMOTE_HOST'])));
131
            if (isset($supp[$lang])) {
132
                return $supp[$lang];
133
            }
134
        }
135
 
136
        return $default;
137
    }
138
 
139
    /**
140
     * Head
141
     *
142
     * Sends a "HEAD" HTTP command to a server and returns the headers
143
     * as an associative array. Example output could be:
144
     * <code>
145
     *     Array
146
     *     (
147
     *         [response_code] => 200          // The HTTP response code
148
     *         [response] => HTTP/1.1 200 OK   // The full HTTP response string
149
     *         [Date] => Fri, 11 Jan 2002 01:41:44 GMT
150
     *         [Server] => Apache/1.3.20 (Unix) PHP/4.1.1
151
     *         [X-Powered-By] => PHP/4.1.1
152
     *         [Connection] => close
153
     *         [Content-Type] => text/html
154
     *     )
155
     * </code>
156
     *
157
     * @see HTTP_Client::head()
158
     * @see HTTP_Request
159
     *
160
     * @static
161
     * @access  public
162
     * @return  mixed   Returns associative array of response headers on success
163
     *                  or PEAR error on failure.
164
     * @param   string  $url A valid URL, e.g.: http://pear.php.net/credits.php
165
     * @param   integer $timeout Timeout in seconds (default = 10)
166
     */
167
    function head($url, $timeout = 10)
168
    {
169
        $p = parse_url($url);
170
        if (!isset($p['scheme'])) {
171
            $p = parse_url(HTTP::absoluteURI($url));
172
        } elseif ($p['scheme'] != 'http') {
173
            return HTTP::raiseError('Unsupported protocol: '. $p['scheme']);
174
        }
175
 
176
        $port = isset($p['port']) ? $p['port'] : 80;
177
 
178
        if (!$fp = @fsockopen($p['host'], $port, $eno, $estr, $timeout)) {
179
            return HTTP::raiseError("Connection error: $estr ($eno)");
180
        }
181
 
182
        $path  = !empty($p['path']) ? $p['path'] : '/';
183
        $path .= !empty($p['query']) ? '?' . $p['query'] : '';
184
 
185
        fputs($fp, "HEAD $path HTTP/1.0\r\n");
186
        fputs($fp, 'Host: ' . $p['host'] . ':' . $port . "\r\n");
187
        fputs($fp, "Connection: close\r\n\r\n");
188
 
189
        $response = rtrim(fgets($fp, 4096));
190
        if (preg_match("|^HTTP/[^\s]*\s(.*?)\s|", $response, $status)) {
191
            $headers['response_code'] = $status[1];
192
        }
193
        $headers['response'] = $response;
194
 
195
        while ($line = fgets($fp, 4096)) {
196
            if (!trim($line)) {
197
                break;
198
            }
199
            if (($pos = strpos($line, ':')) !== false) {
200
                $header = substr($line, 0, $pos);
201
                $value  = trim(substr($line, $pos + 1));
202
                $headers[$header] = $value;
203
            }
204
        }
205
        fclose($fp);
206
        return $headers;
207
    }
208
 
209
    /**
210
     * Redirect
211
     *
212
     * This function redirects the client. This is done by issuing
213
     * a "Location" header and exiting if wanted.  If you set $rfc2616 to true
214
     * HTTP will output a hypertext note with the location of the redirect.
215
     *
216
     * @static
217
     * @access  public
218
     * @return  mixed   Returns true on succes (or exits) or false if headers
219
     *                  have already been sent.
220
     * @param   string  $url URL where the redirect should go to.
221
     * @param   bool    $exit Whether to exit immediately after redirection.
222
     * @param   bool    $rfc2616 Wheter to output a hypertext note where we're
223
     *                  redirecting to (Redirecting to <a href="...">...</a>.)
224
     */
225
    function redirect($url, $exit = true, $rfc2616 = false)
226
    {
227
        if (headers_sent()) {
228
            return false;
229
        }
230
 
231
        $url = HTTP::absoluteURI($url);
232
        header('Location: '. $url);
233
 
234
        if (    $rfc2616 && isset($_SERVER['REQUEST_METHOD']) &&
235
                $_SERVER['REQUEST_METHOD'] != 'HEAD') {
236
            printf('Redirecting to: <a href="%s">%s</a>.', $url, $url);
237
        }
238
        if ($exit) {
239
            exit;
240
        }
241
        return true;
242
    }
243
 
244
    /**
245
     * Absolute URI
246
     *
247
     * This function returns the absolute URI for the partial URL passed.
248
     * The current scheme (HTTP/HTTPS), host server, port, current script
249
     * location are used if necessary to resolve any relative URLs.
250
     *
251
     * Offsets potentially created by PATH_INFO are taken care of to resolve
252
     * relative URLs to the current script.
253
     *
254
     * You can choose a new protocol while resolving the URI.  This is
255
     * particularly useful when redirecting a web browser using relative URIs
256
     * and to switch from HTTP to HTTPS, or vice-versa, at the same time.
257
     *
258
     * @author  Philippe Jausions <Philippe.Jausions@11abacus.com>
259
     * @static
260
     * @access  public
261
     * @return  string  The absolute URI.
262
     * @param   string  $url Absolute or relative URI the redirect should go to.
263
     * @param   string  $protocol Protocol to use when redirecting URIs.
264
     * @param   integer $port A new port number.
265
     */
266
    function absoluteURI($url = null, $protocol = null, $port = null)
267
    {
268
        // filter CR/LF
269
        $url = str_replace(array("\r", "\n"), ' ', $url);
270
 
271
        // Mess around with already absolute URIs
272
        if (preg_match('!^([a-z0-9]+)://!i', $url)) {
273
            if (empty($protocol) && empty($port)) {
274
                return $url;
275
            }
276
            if (!empty($protocol)) {
277
                $url = $protocol .':'. array_pop(explode(':', $url, 2));
278
            }
279
            if (!empty($port)) {
280
                $url = preg_replace('!^(([a-z0-9]+)://[^/:]+)(:[\d]+)?!i',
281
                    '\1:'. $port, $url);
282
            }
283
            return $url;
284
        }
285
 
286
        $host = 'localhost';
287
        if (!empty($_SERVER['HTTP_HOST'])) {
288
            list($host) = explode(':', $_SERVER['HTTP_HOST']);
289
        } elseif (!empty($_SERVER['SERVER_NAME'])) {
290
            list($host) = explode(':', $_SERVER['SERVER_NAME']);
291
        }
292
 
293
        if (empty($protocol)) {
294
            if (isset($_SERVER['HTTPS']) && !strcasecmp($_SERVER['HTTPS'], 'on')) {
295
                $protocol = 'https';
296
            } else {
297
                $protocol = 'http';
298
            }
299
            if (!isset($port) || $port != intval($port)) {
300
                $port = isset($_SERVER['SERVER_PORT']) ? $_SERVER['SERVER_PORT'] : 80;
301
            }
302
        }
303
 
304
        if ($protocol == 'http' && $port == 80) {
305
            unset($port);
306
        }
307
        if ($protocol == 'https' && $port == 443) {
308
            unset($port);
309
        }
310
 
311
        $server = $protocol .'://'. $host . (isset($port) ? ':'. $port : '');
312
 
313
        if (!strlen($url)) {
314
            $url = isset($_SERVER['REQUEST_URI']) ?
315
                $_SERVER['REQUEST_URI'] : $_SERVER['PHP_SELF'];
316
        }
317
 
318
        if ($url{0} == '/') {
319
            return $server . $url;
320
        }
321
 
322
        // Check for PATH_INFO
323
        if (isset($_SERVER['PATH_INFO']) && $_SERVER['PHP_SELF'] != $_SERVER['PATH_INFO']) {
324
            $path = dirname(substr($_SERVER['PHP_SELF'], 0, -strlen($_SERVER['PATH_INFO'])));
325
        } else {
326
            $path = dirname($_SERVER['PHP_SELF']);
327
        }
328
 
329
        if (substr($path = strtr($path, '\\', '/'), -1) != '/') {
330
            $path .= '/';
331
        }
332
 
333
        return $server . $path . $url;
334
    }
335
 
336
    /**
337
     * Raise Error
338
     *
339
     * Lazy raising of PEAR_Errors.
340
     *
341
     * @static
342
     * @access  protected
343
     * @return  object PEAR_Error
344
     * @param   mixed   $error
345
     * @param   int     $code
346
     */
347
    function raiseError($error = null, $code = null)
348
    {
349
        require_once 'PEAR.php';
350
        return PEAR::raiseError($error, $code);
351
    }
352
}
353
?>