[ Index ]

PHP Cross Reference of Joomla 1.5.26 DE

title

Body

[close]

/libraries/openid/Auth/ -> OpenID.php (source)

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


Generated: Wed Mar 28 15:54:07 2012 Cross-referenced by PHPXref 0.7.1