php8
[web.mtrack] / Auth / OpenID.php
1 <?php
2
3 /**
4  * This is the PHP OpenID library by JanRain, Inc.
5  *
6  * This module contains core utility functionality used by the
7  * library.  See Consumer.php and Server.php for the consumer and
8  * server implementations.
9  *
10  * PHP versions 4 and 5
11  *
12  * LICENSE: See the COPYING file included in this distribution.
13  *
14  * @package OpenID
15  * @author JanRain, Inc. <openid@janrain.com>
16  * @copyright 2005-2008 Janrain, Inc.
17  * @license http://www.apache.org/licenses/LICENSE-2.0 Apache
18  */
19
20 /**
21  * The library version string
22  */
23 define('Auth_OpenID_VERSION', '2.1.2');
24
25 /**
26  * Require the fetcher code.
27  */
28 require_once "Auth/Yadis/PlainHTTPFetcher.php";
29 require_once "Auth/Yadis/ParanoidHTTPFetcher.php";
30 require_once "Auth/OpenID/BigMath.php";
31 require_once "Auth/OpenID/URINorm.php";
32
33 /**
34  * Status code returned by the server when the only option is to show
35  * an error page, since we do not have enough information to redirect
36  * back to the consumer. The associated value is an error message that
37  * should be displayed on an HTML error page.
38  *
39  * @see Auth_OpenID_Server
40  */
41 define('Auth_OpenID_LOCAL_ERROR', 'local_error');
42
43 /**
44  * Status code returned when there is an error to return in key-value
45  * form to the consumer. The caller should return a 400 Bad Request
46  * response with content-type text/plain and the value as the body.
47  *
48  * @see Auth_OpenID_Server
49  */
50 define('Auth_OpenID_REMOTE_ERROR', 'remote_error');
51
52 /**
53  * Status code returned when there is a key-value form OK response to
54  * the consumer. The value associated with this code is the
55  * response. The caller should return a 200 OK response with
56  * content-type text/plain and the value as the body.
57  *
58  * @see Auth_OpenID_Server
59  */
60 define('Auth_OpenID_REMOTE_OK', 'remote_ok');
61
62 /**
63  * Status code returned when there is a redirect back to the
64  * consumer. The value is the URL to redirect back to. The caller
65  * should return a 302 Found redirect with a Location: header
66  * containing the URL.
67  *
68  * @see Auth_OpenID_Server
69  */
70 define('Auth_OpenID_REDIRECT', 'redirect');
71
72 /**
73  * Status code returned when the caller needs to authenticate the
74  * user. The associated value is a {@link Auth_OpenID_ServerRequest}
75  * object that can be used to complete the authentication. If the user
76  * has taken some authentication action, use the retry() method of the
77  * {@link Auth_OpenID_ServerRequest} object to complete the request.
78  *
79  * @see Auth_OpenID_Server
80  */
81 define('Auth_OpenID_DO_AUTH', 'do_auth');
82
83 /**
84  * Status code returned when there were no OpenID arguments
85  * passed. This code indicates that the caller should return a 200 OK
86  * response and display an HTML page that says that this is an OpenID
87  * server endpoint.
88  *
89  * @see Auth_OpenID_Server
90  */
91 define('Auth_OpenID_DO_ABOUT', 'do_about');
92
93 /**
94  * Defines for regexes and format checking.
95  */
96 define('Auth_OpenID_letters',
97        "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");
98
99 define('Auth_OpenID_digits',
100        "0123456789");
101
102 define('Auth_OpenID_punct',
103        "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~");
104
105 if (Auth_OpenID_getMathLib() === null) {
106     Auth_OpenID_setNoMathSupport();
107 }
108
109 /**
110  * The OpenID utility function class.
111  *
112  * @package OpenID
113  * @access private
114  */
115 class Auth_OpenID {
116
117     /**
118      * Return true if $thing is an Auth_OpenID_FailureResponse object;
119      * false if not.
120      *
121      * @access private
122      */
123     function isFailure($thing)
124     {
125         return is_a($thing, 'Auth_OpenID_FailureResponse');
126     }
127
128     /**
129      * Gets the query data from the server environment based on the
130      * request method used.  If GET was used, this looks at
131      * $_SERVER['QUERY_STRING'] directly.  If POST was used, this
132      * fetches data from the special php://input file stream.
133      *
134      * Returns an associative array of the query arguments.
135      *
136      * Skips invalid key/value pairs (i.e. keys with no '=value'
137      * portion).
138      *
139      * Returns an empty array if neither GET nor POST was used, or if
140      * POST was used but php://input cannot be opened.
141      *
142      * @access private
143      */
144     function getQuery($query_str=null)
145     {
146         $data = array();
147
148         if ($query_str !== null) {
149             $data = Auth_OpenID::params_from_string($query_str);
150         } else if (!array_key_exists('REQUEST_METHOD', $_SERVER)) {
151             // Do nothing.
152         } else {
153           // XXX HACK FIXME HORRIBLE.
154           //
155           // POSTing to a URL with query parameters is acceptable, but
156           // we don't have a clean way to distinguish those parameters
157           // when we need to do things like return_to verification
158           // which only want to look at one kind of parameter.  We're
159           // going to emulate the behavior of some other environments
160           // by defaulting to GET and overwriting with POST if POST
161           // data is available.
162           $data = Auth_OpenID::params_from_string($_SERVER['QUERY_STRING']);
163
164           if ($_SERVER['REQUEST_METHOD'] == 'POST') {
165             $str = file_get_contents('php://input');
166
167             if ($str === false) {
168               $post = array();
169             } else {
170               $post = Auth_OpenID::params_from_string($str);
171             }
172
173             $data = array_merge($data, $post);
174           }
175         }
176
177         return $data;
178     }
179
180     function params_from_string($str)
181     {
182         $chunks = explode("&", $str);
183
184         $data = array();
185         foreach ($chunks as $chunk) {
186             $parts = explode("=", $chunk, 2);
187
188             if (count($parts) != 2) {
189                 continue;
190             }
191
192             list($k, $v) = $parts;
193             $data[$k] = urldecode($v);
194         }
195
196         return $data;
197     }
198
199     /**
200      * Create dir_name as a directory if it does not exist. If it
201      * exists, make sure that it is, in fact, a directory.  Returns
202      * true if the operation succeeded; false if not.
203      *
204      * @access private
205      */
206     function ensureDir($dir_name)
207     {
208         if (is_dir($dir_name) || @mkdir($dir_name)) {
209             return true;
210         } else {
211             $parent_dir = dirname($dir_name);
212
213             // Terminal case; there is no parent directory to create.
214             if ($parent_dir == $dir_name) {
215                 return true;
216             }
217
218             return (Auth_OpenID::ensureDir($parent_dir) && @mkdir($dir_name));
219         }
220     }
221
222     /**
223      * Adds a string prefix to all values of an array.  Returns a new
224      * array containing the prefixed values.
225      *
226      * @access private
227      */
228     function addPrefix($values, $prefix)
229     {
230         $new_values = array();
231         foreach ($values as $s) {
232             $new_values[] = $prefix . $s;
233         }
234         return $new_values;
235     }
236
237     /**
238      * Convenience function for getting array values.  Given an array
239      * $arr and a key $key, get the corresponding value from the array
240      * or return $default if the key is absent.
241      *
242      * @access private
243      */
244     function arrayGet($arr, $key, $fallback = null)
245     {
246         if (is_array($arr)) {
247             if (array_key_exists($key, $arr)) {
248                 return $arr[$key];
249             } else {
250                 return $fallback;
251             }
252         } else {
253             trigger_error("Auth_OpenID::arrayGet (key = ".$key.") expected " .
254                           "array as first parameter, got " .
255                           gettype($arr), E_USER_WARNING);
256
257             return false;
258         }
259     }
260
261     /**
262      * Replacement for PHP's broken parse_str.
263      */
264     function parse_str($query)
265     {
266         if ($query === null) {
267             return null;
268         }
269
270         $parts = explode('&', $query);
271
272         $new_parts = array();
273         for ($i = 0; $i < count($parts); $i++) {
274             $pair = explode('=', $parts[$i]);
275
276             if (count($pair) != 2) {
277                 continue;
278             }
279
280             list($key, $value) = $pair;
281             $new_parts[$key] = urldecode($value);
282         }
283
284         return $new_parts;
285     }
286
287     /**
288      * Implements the PHP 5 'http_build_query' functionality.
289      *
290      * @access private
291      * @param array $data Either an array key/value pairs or an array
292      * of arrays, each of which holding two values: a key and a value,
293      * sequentially.
294      * @return string $result The result of url-encoding the key/value
295      * pairs from $data into a URL query string
296      * (e.g. "username=bob&id=56").
297      */
298     function httpBuildQuery($data)
299     {
300         $pairs = array();
301         foreach ($data as $key => $value) {
302             if (is_array($value)) {
303                 $pairs[] = urlencode($value[0])."=".urlencode($value[1]);
304             } else {
305                 $pairs[] = urlencode($key)."=".urlencode($value);
306             }
307         }
308         return implode("&", $pairs);
309     }
310
311     /**
312      * "Appends" query arguments onto a URL.  The URL may or may not
313      * already have arguments (following a question mark).
314      *
315      * @access private
316      * @param string $url A URL, which may or may not already have
317      * arguments.
318      * @param array $args Either an array key/value pairs or an array of
319      * arrays, each of which holding two values: a key and a value,
320      * sequentially.  If $args is an ordinary key/value array, the
321      * parameters will be added to the URL in sorted alphabetical order;
322      * if $args is an array of arrays, their order will be preserved.
323      * @return string $url The original URL with the new parameters added.
324      *
325      */
326     function appendArgs($url, $args)
327     {
328         if (count($args) == 0) {
329             return $url;
330         }
331
332         // Non-empty array; if it is an array of arrays, use
333         // multisort; otherwise use sort.
334         if (array_key_exists(0, $args) &&
335             is_array($args[0])) {
336             // Do nothing here.
337         } else {
338             $keys = array_keys($args);
339             sort($keys);
340             $new_args = array();
341             foreach ($keys as $key) {
342                 $new_args[] = array($key, $args[$key]);
343             }
344             $args = $new_args;
345         }
346
347         $sep = '?';
348         if (strpos($url, '?') !== false) {
349             $sep = '&';
350         }
351
352         return $url . $sep . Auth_OpenID::httpBuildQuery($args);
353     }
354
355     /**
356      * Implements python's urlunparse, which is not available in PHP.
357      * Given the specified components of a URL, this function rebuilds
358      * and returns the URL.
359      *
360      * @access private
361      * @param string $scheme The scheme (e.g. 'http').  Defaults to 'http'.
362      * @param string $host The host.  Required.
363      * @param string $port The port.
364      * @param string $path The path.
365      * @param string $query The query.
366      * @param string $fragment The fragment.
367      * @return string $url The URL resulting from assembling the
368      * specified components.
369      */
370     function urlunparse($scheme, $host, $port = null, $path = '/',
371                         $query = '', $fragment = '')
372     {
373
374         if (!$scheme) {
375             $scheme = 'http';
376         }
377
378         if (!$host) {
379             return false;
380         }
381
382         if (!$path) {
383             $path = '';
384         }
385
386         $result = $scheme . "://" . $host;
387
388         if ($port) {
389             $result .= ":" . $port;
390         }
391
392         $result .= $path;
393
394         if ($query) {
395             $result .= "?" . $query;
396         }
397
398         if ($fragment) {
399             $result .= "#" . $fragment;
400         }
401
402         return $result;
403     }
404
405     /**
406      * Given a URL, this "normalizes" it by adding a trailing slash
407      * and / or a leading http:// scheme where necessary.  Returns
408      * null if the original URL is malformed and cannot be normalized.
409      *
410      * @access private
411      * @param string $url The URL to be normalized.
412      * @return mixed $new_url The URL after normalization, or null if
413      * $url was malformed.
414      */
415     function normalizeUrl($url)
416     {
417         @$parsed = parse_url($url);
418
419         if (!$parsed) {
420             return null;
421         }
422
423         if (isset($parsed['scheme']) &&
424             isset($parsed['host'])) {
425             $scheme = strtolower($parsed['scheme']);
426             if (!in_array($scheme, array('http', 'https'))) {
427                 return null;
428             }
429         } else {
430             $url = 'http://' . $url;
431         }
432
433         $normalized = Auth_OpenID_urinorm($url);
434         if ($normalized === null) {
435             return null;
436         }
437         list($defragged, $frag) = Auth_OpenID::urldefrag($normalized);
438         return $defragged;
439     }
440
441     /**
442      * Replacement (wrapper) for PHP's intval() because it's broken.
443      *
444      * @access private
445      */
446     function intval($value)
447     {
448         $re = "/^\\d+$/";
449
450         if (!preg_match($re, $value)) {
451             return false;
452         }
453
454         return intval($value);
455     }
456
457     /**
458      * Count the number of bytes in a string independently of
459      * multibyte support conditions.
460      *
461      * @param string $str The string of bytes to count.
462      * @return int The number of bytes in $str.
463      */
464     function bytes($str)
465     {
466         return strlen(bin2hex($str)) / 2;
467     }
468
469     /**
470      * Get the bytes in a string independently of multibyte support
471      * conditions.
472      */
473     function toBytes($str)
474     {
475         $hex = bin2hex($str);
476
477         if (!$hex) {
478             return array();
479         }
480
481         $b = array();
482         for ($i = 0; $i < strlen($hex); $i += 2) {
483             $b[] = chr(base_convert(substr($hex, $i, 2), 16, 10));
484         }
485
486         return $b;
487     }
488
489     function urldefrag($url)
490     {
491         $parts = explode("#", $url, 2);
492
493         if (count($parts) == 1) {
494             return array($parts[0], "");
495         } else {
496             return $parts;
497         }
498     }
499
500     function filter($callback, &$sequence)
501     {
502         $result = array();
503
504         foreach ($sequence as $item) {
505             if (call_user_func_array($callback, array($item))) {
506                 $result[] = $item;
507             }
508         }
509
510         return $result;
511     }
512
513     function update(&$dest, &$src)
514     {
515         foreach ($src as $k => $v) {
516             $dest[$k] = $v;
517         }
518     }
519
520     /**
521      * Wrap PHP's standard error_log functionality.  Use this to
522      * perform all logging. It will interpolate any additional
523      * arguments into the format string before logging.
524      *
525      * @param string $format_string The sprintf format for the message
526      */
527     function log($format_string)
528     {
529         $args = func_get_args();
530         $message = call_user_func_array('sprintf', $args);
531         error_log($message);
532     }
533
534     function autoSubmitHTML($form, $title="OpenId transaction in progress")
535     {
536         return("<html>".
537                "<head><title>".
538                $title .
539                "</title></head>".
540                "<body onload='document.forms[0].submit();'>".
541                $form .
542                "<script>".
543                "var elements = document.forms[0].elements;".
544                "for (var i = 0; i < elements.length; i++) {".
545                "  elements[i].style.display = \"none\";".
546                "}".
547                "</script>".
548                "</body>".
549                "</html>");
550     }
551 }
552 ?>