[geeklog-cvs] Geeklog-1.x/system/classes/openid COPYING, NONE, 1.1 LICENSE, NONE, 1.1 association.php, NONE, 1.1 consumer.php, NONE, 1.1 httpclient.php, NONE, 1.1 interface.php, NONE, 1.1 oid_parse.php, NONE, 1.1 oid_util.php, NONE, 1.1 server.php, NONE, 1.1 trustroot.php, NONE, 1.1

Dirk Haun dhaun at qs1489.pair.com
Sat May 26 15:32:01 EDT 2007


Update of /cvsroot/geeklog/Geeklog-1.x/system/classes/openid
In directory qs1489.pair.com:/tmp/cvs-serv1378/system/classes/openid

Added Files:
	COPYING LICENSE association.php consumer.php httpclient.php 
	interface.php oid_parse.php oid_util.php server.php 
	trustroot.php 
Log Message:
OpenID support, provided by Choplair


--- NEW FILE: trustroot.php ---
<?php

/*****
PHP OpenID - OpenID consumer and server library

Copyright (C) 2005 Open Source Consulting, SA. and Dan Libby

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

Reciprocal linking.  The author humbly requests that if you should use 
PHP-OpenID on your website to provide an OpenID enabled service that you 
place a link to the author's website ( http://videntity.org ) somewhere 
that your users can discover it.  You are however under no obligation to 
do so.  

More info about PHP OpenID:
openid at videntity.org
http://videntity.org/openid/

More info about OpenID:
http://www.openid.net

*****/


define( '_oid_top_level_domains_list', <<< END
com|edu|gov|int|mil|net|org|biz|info|name|museum|coop|aero|ac|ad|ae|
af|ag|ai|al|am|an|ao|aq|ar|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|bj|
bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|
cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|ee|eg|eh|er|es|et|fi|fj|fk|fm|fo|
fr|ga|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|
ht|hu|id|ie|il|im|in|io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|
kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mk|ml|mm|
mn|mo|mp|mq|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|nr|
nu|nz|om|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ro|ru|rw|sa|
sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|sv|sy|sz|tc|td|tf|tg|th|
tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|
vn|vu|wf|ws|ye|yt|yu|za|zm|zw|localhost
END
);
define( '_oid_protocol_list', 'http|https');

class TrustRoot {
    // Represents a valid openid trust root.  The parse classmethod
    // accepts a trust root string, producing a TrustRoot object.
    
    var $_protocols;
    var $_top_level_domains;
    
    function TrustRoot($unparsed, $proto, $wildcard, $host, $port, $path) {
    
        $this->_top_level_domains = explode( '|', _oid_top_level_domains_list );
        $this->_protocols = explode( '|', _oid_protocol_list );
    
        $this->unparsed = $unparsed;
        $this->proto = $proto;
        $this->wildcard = $wildcard;
        $this->host = $host;
        $this->port = $port;
        $this->path = $path;

        $this->_is_sane = null;
    }

    function isSane() {
        // Checks the sanity of this trust root.
        // http://*.com/ for example is not sane.  Returns a bool.
        
        if( $this->_is_sane ) {
            return $this->_is_sane;
        }

        if( $this->host == 'localhost') {
            return true;
        }

        $host_parts = explode( '.', $this->host );

        // extract sane "top-level-domain
        //
        // porting note:  this is a very python-ish way of doing things.
        $host = array();
        $cnt = count( $host_parts );
        if( strlen($host_parts[$cnt-1]) == 2) {
            if( $cnt > 1 && strlen($host_parts[$cnt-1]) <= 3) {
                $host = array_slice( $host_parts, 0, $cnt-2);
            }
        }
        else if( strlen($host_parts[$cnt-1]) == 3) {
            $host = array_slice( $host_parts, 0, $cnt-1);
        }

        $this->_is_sane = count($host) ? true : false;
        return $this->_is_sane;
    }

    function validateURL($url) {
        // Validates a URL against this trust root.  Returns a bool

        if( !$this->isSane()) {
            return false;
        }

        // porting note:  PHP's parse_url() is not intended for url validation.
        $url_parts = parse_url($url);
        if( !$url_parts || !count( $url_parts ) ) {
            return false;
        }
        
        $proto = isset( $url_parts['scheme'] ) ? $url_parts['scheme'] : null;
        $host = isset( $url_parts['host'] ) ? $url_parts['host'] : null;
        $port = isset( $url_parts['port'] ) ? $url_parts['port'] : null;
        $path = isset( $url_parts['path'] ) ? $url_parts['path'] : null;

        if( $proto != $this->proto) {
            return false;
        }

        if( $port != $this->port) {
            return false;
        }

        $arr1 = explode( '?', $path, 1);
        $arr2 = explode( '?', $this->path, 1);
        
        if( !$this->startswith( $arr1[0], $arr2[0]) ) {
            return false;
        }

        if( !$this->wildcard) {
            return $host == $this->host;
        }
        else {
            return $this->endsWith( $host, $this->host );
        }
    }

    // static
    function parse($trust_root, $check_sanity=false) {
        if( !is_string($trust_root) ) {
            return null;
        }

        // porting note:  PHP's parse_url() is not intended for url validation.
        $url_parts = parse_url($trust_root);
        if( !$url_parts || !count( $url_parts ) ) {
            return false;
        }
        
        $proto = isset( $url_parts['scheme'] ) ? $url_parts['scheme'] : null;
        $host = isset( $url_parts['host'] ) ? $url_parts['host'] : null;
        $port = isset( $url_parts['port'] ) ? $url_parts['port'] : null;
        $path = isset( $url_parts['path'] ) ? $url_parts['path'] : null;

        // check for valid prototype
        $protocols = explode( '|', _oid_protocol_list );
        if( !in_array( $proto, $protocols) ) {
            return null;
        }

        // extract wildcard if it is there
        if( strchr( $host,  '*')) {
            // wildcard must be at start of domain) {  *.foo.com, not foo.*.com
            if( ! TrustRoot::startsWith( $host, '*') ) {
                return null;
            }

            // there should also be a '.' ala *.schtuff.com
            if( $host[1] != '.') {
                return null;
            }
            
            $host = substr( $host, 2 );
            $wilcard = true;
        }
        else {
            $wilcard = false;
        }
        
        // at least needs to end in a top-level-domain
        $ends_in_tld = false;
        $_top_level_domains = explode( '|', _oid_top_level_domains_list );
        
        foreach( $_top_level_domains as $tld ) {
            if( TrustRoot::endsWith($host, $tld) ) {
                $ends_in_tld = true;
                break;
            }
        }

        if( !$ends_in_tld) {
            return null;
        }

        // we have a valid trust root
        $tr = new TrustRoot($trust_root, $proto, $wilcard, $host, $port, $path);
        if( $check_sanity) {
            if( !$tr->isSane() ) {
                return null;
            }
        }

        return $tr;
    }

    // static
    function checkSanity($trust_root_string) {
        // str -> bool

        // is this a sane trust root?
        $tr = TrustRoot::parse($trust_root_string);
        return $tr->isSane();
    }

    // static
    function checkURL($trust_root, $url) {
        // quick func for validating a url against a trust root.  See the
        // TrustRoot class if you need more control.
        
        $tr = TrustRoot::parse($trust_root, true);
        return $tr && $tr->validateURL($url);
    }

    function toString() {
        return sprintf( "TrustRoot('%s', '%s', '%s', '%s', '%s', '%s')",
            $this->unparsed, $this->proto, $this->wildcard, $this->host, $this->port,
            $this->path);
    }

    function startsWith( $str, $sub ) {
       return ( substr( $str, 0, strlen( $sub ) ) == $sub );
    }
    
    // return tru if $str ends with $sub
    function endsWith( $str, $sub ) {
       $len1 = strlen( $str );
       $len2 = strlen( $sub );
       return $len1 >= $len2 && ( substr( $str, $len1 - $len2 ) == $sub );
    }        
};


function _oid_trustroot_test() {
    print 'Testing...';

    // test invalid trust root strings
    function assertBad($s) {
        $tr = TrustRoot::parse($s);
        assert( '$tr == null' );
        if( $tr != null ) {
            echo $tr->toString() . '<br/>';
            exit;
        }
    }

    assertBad('baz.org');
    assertBad('*.foo.com');
    assertBad('ftp://foo.com');
    assertBad('ftp://*.foo.com');
    assertBad('http://*.foo.notatld');
    assertBad('http://*.foo.com:80:90/');
    assertBad('');
    assertBad(' ');
    assertBad(' \t\n ');
    assertBad(null);
    assertBad(5);

    // test valid trust root string
    function assertGood($s) {
        $tr = TrustRoot::parse($s);
        assert( '$tr != null' );
        if( $tr == null ) {
            echo $tr->toString() . '<br/>';
            exit;
        }
    }

    assertGood('http://*.schtuff.com/');
    assertGood('http://*.schtuff.com');
    assertGood('http://www.schtuff.com/');
    assertGood('http://www.schtuff.com');
    assertGood('http://*.this.that.schtuff.com/');
    assertGood('http://*.com/');
    assertGood('http://*.com');
    assertGood('http://*.foo.com/path');
    assertGood('http://x.foo.com/path?action=foo2');
    assertGood('http://*.foo.com/path?action=foo2');
    assertGood('http://localhost:8081/');

    function assertSane($s, $truth) {
        $tr = TrustRoot::parse($s);
        $isSane = $tr->isSane();
        assert( '$isSane == $truth' );
        
        if( $isSane != $truth ) {
            echo "$isSane, $truth<br/>";
            exit;
        }
    }


    assertSane('http://*.schtuff.com/', true);
    assertSane('http://*.foo.schtuff.com/', true);
    assertSane('http://*.com/', false);
    assertSane('http://*.com.au/', false);
    assertSane('http://*.co.uk/', false);
    assertSane('http://localhost:8082/?action=openid', true);
    assertSane('http://greg.abstrakt.ch', true);

    // XXX: what exactly is a sane trust root?
    // assertSane('http) {//*.k12.va.us/', false)

    // validate a url against a trust root
    function assertValid($trust_root, $url, $truth) {
        $tr = TrustRoot::parse($trust_root);
        $isSane = $tr->isSane();
        $isValid = $tr->validateURL($url);
        assert( '$isSane' );
        if( !$isSane ) {
            exit;
        }
        assert( '$isValid == $truth' );
        if( $isValid != $truth ) {
            exit;
        }
    }
        

    assertValid('http://*.foo.com', 'http://b.foo.com', true);
    assertValid('http://*.foo.com', 'http://hat.baz.foo.com', true);
    assertValid('http://*.foo.com', 'http://b.foo.com', true);
    assertValid('http://*.b.foo.com', 'http://b.foo.com', true);
    assertValid('http://*.b.foo.com', 'http://x.b.foo.com', true);
    assertValid('http://*.bar.co.uk', 'http://www.bar.co.uk', true);
    assertValid('http://*.uoregon.edu', 'http://*.cs.uoregon.edu', true);

    assertValid('http://*.cs.uoregon.edu', 'http://*.uoregon.edu', false);
    assertValid('http://*.foo.com', 'http://bar.com', false);
    assertValid('http://*.foo.com', 'http://www.bar.com', false);
    assertValid('http://*.bar.co.uk', 'http://xxx.co.uk', false);

    // path validity
    assertValid('http://x.com/abc', 'http://x.com/', false);
    assertValid('http://x.com/abc', 'http://x.com/a', false);
    assertValid('http://*.x.com/abc', 'http://foo.x.com/abc', true);
    assertValid('http://*.x.com/abc', 'http://foo.x.com', false);
    assertValid('http://*.x.com', 'http://foo.x.com/gallery', true);
    assertValid('http://foo.x.com', 'http://foo.x.com/gallery', true);
    assertValid('http://foo.x.com/gallery', 'http://foo.x.com/gallery/xxx', true);
    assertValid('http://localhost:8081/x?action=openid',
                'http://localhost:8081/x?action=openid', true);
    assertValid('http://*.x.com/gallery', 'http://foo.x.com/gallery', true);

    assertValid('http://localhost:8082/?action=openid',
                'http://localhost:8082/?action=openid', true);
    assertValid('http://goathack.livejournal.org:8020/',
                'http://goathack.livejournal.org:8020/openid/login.bml', true);

    print 'All tests passed!';
}

if( strstr( $_SERVER['REQUEST_URI'], 'trustroot.php' ) ) {
    _oid_trustroot_test();
}
    
?>

--- NEW FILE: LICENSE ---
		  GNU LESSER GENERAL PUBLIC LICENSE
		       Version 2.1, February 1999

 Copyright (C) 1991, 1999 Free Software Foundation, Inc.
     51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

[This is the first released version of the Lesser GPL.  It also counts
 as the successor of the GNU Library Public License, version 2, hence
 the version number 2.1.]

			    Preamble

  The licenses for most software are designed to take away your
freedom to share and change it.  By contrast, the GNU General Public
Licenses are intended to guarantee your freedom to share and change
free software--to make sure the software is free for all its users.

  This license, the Lesser General Public License, applies to some
specially designated software packages--typically libraries--of the
Free Software Foundation and other authors who decide to use it.  You
can use it too, but we suggest you first think carefully about whether
this license or the ordinary General Public License is the better
strategy to use in any particular case, based on the explanations below.

  When we speak of free software, we are referring to freedom of use,
not price.  Our General Public Licenses are designed to make sure that
you have the freedom to distribute copies of free software (and charge
for this service if you wish); that you receive source code or can get
it if you want it; that you can change the software and use pieces of
it in new free programs; and that you are informed that you can do
these things.

  To protect your rights, we need to make restrictions that forbid
distributors to deny you these rights or to ask you to surrender these
rights.  These restrictions translate to certain responsibilities for
you if you distribute copies of the library or if you modify it.

  For example, if you distribute copies of the library, whether gratis
or for a fee, you must give the recipients all the rights that we gave
you.  You must make sure that they, too, receive or can get the source
code.  If you link other code with the library, you must provide
complete object files to the recipients, so that they can relink them
with the library after making changes to the library and recompiling
it.  And you must show them these terms so they know their rights.

  We protect your rights with a two-step method: (1) we copyright the
library, and (2) we offer you this license, which gives you legal
permission to copy, distribute and/or modify the library.

  To protect each distributor, we want to make it very clear that
there is no warranty for the free library.  Also, if the library is
modified by someone else and passed on, the recipients should know
that what they have is not the original version, so that the original
author's reputation will not be affected by problems that might be
introduced by others.

  Finally, software patents pose a constant threat to the existence of
any free program.  We wish to make sure that a company cannot
effectively restrict the users of a free program by obtaining a
restrictive license from a patent holder.  Therefore, we insist that
any patent license obtained for a version of the library must be
consistent with the full freedom of use specified in this license.

  Most GNU software, including some libraries, is covered by the
ordinary GNU General Public License.  This license, the GNU Lesser
General Public License, applies to certain designated libraries, and
is quite different from the ordinary General Public License.  We use
this license for certain libraries in order to permit linking those
libraries into non-free programs.

  When a program is linked with a library, whether statically or using
a shared library, the combination of the two is legally speaking a
combined work, a derivative of the original library.  The ordinary
General Public License therefore permits such linking only if the
entire combination fits its criteria of freedom.  The Lesser General
Public License permits more lax criteria for linking other code with
the library.

  We call this license the "Lesser" General Public License because it
does Less to protect the user's freedom than the ordinary General
Public License.  It also provides other free software developers Less
of an advantage over competing non-free programs.  These disadvantages
are the reason we use the ordinary General Public License for many
libraries.  However, the Lesser license provides advantages in certain
special circumstances.

  For example, on rare occasions, there may be a special need to
encourage the widest possible use of a certain library, so that it becomes
a de-facto standard.  To achieve this, non-free programs must be
allowed to use the library.  A more frequent case is that a free
library does the same job as widely used non-free libraries.  In this
case, there is little to gain by limiting the free library to free
software only, so we use the Lesser General Public License.

  In other cases, permission to use a particular library in non-free
programs enables a greater number of people to use a large body of
free software.  For example, permission to use the GNU C Library in
non-free programs enables many more people to use the whole GNU
operating system, as well as its variant, the GNU/Linux operating
system.

  Although the Lesser General Public License is Less protective of the
users' freedom, it does ensure that the user of a program that is
linked with the Library has the freedom and the wherewithal to run
that program using a modified version of the Library.

  The precise terms and conditions for copying, distribution and
modification follow.  Pay close attention to the difference between a
"work based on the library" and a "work that uses the library".  The
former contains code derived from the library, whereas the latter must
be combined with the library in order to run.

		  GNU LESSER GENERAL PUBLIC LICENSE
   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION

  0. This License Agreement applies to any software library or other
program which contains a notice placed by the copyright holder or
other authorized party saying it may be distributed under the terms of
this Lesser General Public License (also called "this License").
Each licensee is addressed as "you".

  A "library" means a collection of software functions and/or data
prepared so as to be conveniently linked with application programs
(which use some of those functions and data) to form executables.

  The "Library", below, refers to any such software library or work
which has been distributed under these terms.  A "work based on the
Library" means either the Library or any derivative work under
copyright law: that is to say, a work containing the Library or a
portion of it, either verbatim or with modifications and/or translated
straightforwardly into another language.  (Hereinafter, translation is
included without limitation in the term "modification".)

  "Source code" for a work means the preferred form of the work for
making modifications to it.  For a library, complete source code means
all the source code for all modules it contains, plus any associated
interface definition files, plus the scripts used to control compilation
and installation of the library.

  Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope.  The act of
running a program using the Library is not restricted, and output from
such a program is covered only if its contents constitute a work based
on the Library (independent of the use of the Library in a tool for
writing it).  Whether that is true depends on what the Library does
and what the program that uses the Library does.
  
  1. You may copy and distribute verbatim copies of the Library's
complete source code as you receive it, in any medium, provided that
you conspicuously and appropriately publish on each copy an
appropriate copyright notice and disclaimer of warranty; keep intact
all the notices that refer to this License and to the absence of any
warranty; and distribute a copy of this License along with the
Library.

  You may charge a fee for the physical act of transferring a copy,
and you may at your option offer warranty protection in exchange for a
fee.

  2. You may modify your copy or copies of the Library or any portion
of it, thus forming a work based on the Library, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:

    a) The modified work must itself be a software library.

    b) You must cause the files modified to carry prominent notices
    stating that you changed the files and the date of any change.

    c) You must cause the whole of the work to be licensed at no
    charge to all third parties under the terms of this License.

    d) If a facility in the modified Library refers to a function or a
    table of data to be supplied by an application program that uses
    the facility, other than as an argument passed when the facility
    is invoked, then you must make a good faith effort to ensure that,
    in the event an application does not supply such function or
    table, the facility still operates, and performs whatever part of
    its purpose remains meaningful.

    (For example, a function in a library to compute square roots has
    a purpose that is entirely well-defined independent of the
    application.  Therefore, Subsection 2d requires that any
    application-supplied function or table used by this function must
    be optional: if the application does not supply it, the square
    root function must still compute square roots.)

These requirements apply to the modified work as a whole.  If
identifiable sections of that work are not derived from the Library,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works.  But when you
distribute the same sections as part of a whole which is a work based
on the Library, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote
it.

Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Library.

In addition, mere aggregation of another work not based on the Library
with the Library (or with a work based on the Library) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.

  3. You may opt to apply the terms of the ordinary GNU General Public
License instead of this License to a given copy of the Library.  To do
this, you must alter all the notices that refer to this License, so
that they refer to the ordinary GNU General Public License, version 2,
instead of to this License.  (If a newer version than version 2 of the
ordinary GNU General Public License has appeared, then you can specify
that version instead if you wish.)  Do not make any other change in
these notices.

  Once this change is made in a given copy, it is irreversible for
that copy, so the ordinary GNU General Public License applies to all
subsequent copies and derivative works made from that copy.

  This option is useful when you wish to copy part of the code of
the Library into a program that is not a library.

  4. You may copy and distribute the Library (or a portion or
derivative of it, under Section 2) in object code or executable form
under the terms of Sections 1 and 2 above provided that you accompany
it with the complete corresponding machine-readable source code, which
must be distributed under the terms of Sections 1 and 2 above on a
medium customarily used for software interchange.

  If distribution of object code is made by offering access to copy
from a designated place, then offering equivalent access to copy the
source code from the same place satisfies the requirement to
distribute the source code, even though third parties are not
compelled to copy the source along with the object code.

  5. A program that contains no derivative of any portion of the
Library, but is designed to work with the Library by being compiled or
linked with it, is called a "work that uses the Library".  Such a
work, in isolation, is not a derivative work of the Library, and
therefore falls outside the scope of this License.

  However, linking a "work that uses the Library" with the Library
creates an executable that is a derivative of the Library (because it
contains portions of the Library), rather than a "work that uses the
library".  The executable is therefore covered by this License.
Section 6 states terms for distribution of such executables.

  When a "work that uses the Library" uses material from a header file
that is part of the Library, the object code for the work may be a
derivative work of the Library even though the source code is not.
Whether this is true is especially significant if the work can be
linked without the Library, or if the work is itself a library.  The
threshold for this to be true is not precisely defined by law.

  If such an object file uses only numerical parameters, data
structure layouts and accessors, and small macros and small inline
functions (ten lines or less in length), then the use of the object
file is unrestricted, regardless of whether it is legally a derivative
work.  (Executables containing this object code plus portions of the
Library will still fall under Section 6.)

  Otherwise, if the work is a derivative of the Library, you may
distribute the object code for the work under the terms of Section 6.
Any executables containing that work also fall under Section 6,
whether or not they are linked directly with the Library itself.

  6. As an exception to the Sections above, you may also combine or
link a "work that uses the Library" with the Library to produce a
work containing portions of the Library, and distribute that work
under terms of your choice, provided that the terms permit
modification of the work for the customer's own use and reverse
engineering for debugging such modifications.

  You must give prominent notice with each copy of the work that the
Library is used in it and that the Library and its use are covered by
this License.  You must supply a copy of this License.  If the work
during execution displays copyright notices, you must include the
copyright notice for the Library among them, as well as a reference
directing the user to the copy of this License.  Also, you must do one
of these things:

    a) Accompany the work with the complete corresponding
    machine-readable source code for the Library including whatever
    changes were used in the work (which must be distributed under
    Sections 1 and 2 above); and, if the work is an executable linked
    with the Library, with the complete machine-readable "work that
    uses the Library", as object code and/or source code, so that the
    user can modify the Library and then relink to produce a modified
    executable containing the modified Library.  (It is understood
    that the user who changes the contents of definitions files in the
    Library will not necessarily be able to recompile the application
    to use the modified definitions.)

    b) Use a suitable shared library mechanism for linking with the
    Library.  A suitable mechanism is one that (1) uses at run time a
    copy of the library already present on the user's computer system,
    rather than copying library functions into the executable, and (2)
    will operate properly with a modified version of the library, if
    the user installs one, as long as the modified version is
    interface-compatible with the version that the work was made with.

    c) Accompany the work with a written offer, valid for at
    least three years, to give the same user the materials
    specified in Subsection 6a, above, for a charge no more
    than the cost of performing this distribution.

    d) If distribution of the work is made by offering access to copy
    from a designated place, offer equivalent access to copy the above
    specified materials from the same place.

    e) Verify that the user has already received a copy of these
    materials or that you have already sent this user a copy.

  For an executable, the required form of the "work that uses the
Library" must include any data and utility programs needed for
reproducing the executable from it.  However, as a special exception,
the materials to be distributed need not include anything that is
normally distributed (in either source or binary form) with the major
components (compiler, kernel, and so on) of the operating system on
which the executable runs, unless that component itself accompanies
the executable.

  It may happen that this requirement contradicts the license
restrictions of other proprietary libraries that do not normally
accompany the operating system.  Such a contradiction means you cannot
use both them and the Library together in an executable that you
distribute.

  7. You may place library facilities that are a work based on the
Library side-by-side in a single library together with other library
facilities not covered by this License, and distribute such a combined
library, provided that the separate distribution of the work based on
the Library and of the other library facilities is otherwise
permitted, and provided that you do these two things:

    a) Accompany the combined library with a copy of the same work
    based on the Library, uncombined with any other library
    facilities.  This must be distributed under the terms of the
    Sections above.

    b) Give prominent notice with the combined library of the fact
    that part of it is a work based on the Library, and explaining
    where to find the accompanying uncombined form of the same work.

  8. You may not copy, modify, sublicense, link with, or distribute
the Library except as expressly provided under this License.  Any
attempt otherwise to copy, modify, sublicense, link with, or
distribute the Library is void, and will automatically terminate your
rights under this License.  However, parties who have received copies,
or rights, from you under this License will not have their licenses
terminated so long as such parties remain in full compliance.

  9. You are not required to accept this License, since you have not
signed it.  However, nothing else grants you permission to modify or
distribute the Library or its derivative works.  These actions are
prohibited by law if you do not accept this License.  Therefore, by
modifying or distributing the Library (or any work based on the
Library), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Library or works based on it.

  10. Each time you redistribute the Library (or any work based on the
Library), the recipient automatically receives a license from the
original licensor to copy, distribute, link with or modify the Library
subject to these terms and conditions.  You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties with
this License.

  11. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License.  If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Library at all.  For example, if a patent
license would not permit royalty-free redistribution of the Library by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Library.

If any portion of this section is held invalid or unenforceable under any
particular circumstance, the balance of the section is intended to apply,
and the section as a whole is intended to apply in other circumstances.

It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system which is
implemented by public license practices.  Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.

This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.

  12. If the distribution and/or use of the Library is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Library under this License may add
an explicit geographical distribution limitation excluding those countries,
so that distribution is permitted only in or among countries not thus
excluded.  In such case, this License incorporates the limitation as if
written in the body of this License.

  13. The Free Software Foundation may publish revised and/or new
versions of the Lesser General Public License from time to time.
Such new versions will be similar in spirit to the present version,
but may differ in detail to address new problems or concerns.

Each version is given a distinguishing version number.  If the Library
specifies a version number of this License which applies to it and
"any later version", you have the option of following the terms and
conditions either of that version or of any later version published by
the Free Software Foundation.  If the Library does not specify a
license version number, you may choose any version ever published by
the Free Software Foundation.

  14. If you wish to incorporate parts of the Library into other free
programs whose distribution conditions are incompatible with these,
write to the author to ask for permission.  For software which is
copyrighted by the Free Software Foundation, write to the Free
Software Foundation; we sometimes make exceptions for this.  Our
decision will be guided by the two goals of preserving the free status
of all derivatives of our free software and of promoting the sharing
and reuse of software generally.

			    NO WARRANTY

  15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
LIBRARY IS WITH YOU.  SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.

  16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGES.

--- NEW FILE: interface.php ---
<?php

/*****
PHP OpenID - OpenID consumer and server library

Copyright (C) 2005 Open Source Consulting, SA. and Dan Libby

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

Reciprocal linking.  The author humbly requests that if you should use 
PHP-OpenID on your website to provide an OpenID enabled service that you 
place a link to the author's website ( http://videntity.org ) somewhere 
that your users can discover it.  You are however under no obligation to 
do so.  

More info about PHP OpenID:
openid at videntity.org
http://videntity.org/openid/

More info about OpenID:
http://www.openid.net

*****/


class ServerResponse {

    var $code;
    var $content_type;
    var $body;
    var $redirect_url;

    function ServerResponse( $vars ) {
    
        $attrs = array( 'code', 'content_type', 'body', 'redirect_url' );
        foreach( $attrs as $attr ) {
        
            if( isset( $vars[$attr] ) ) {
                $this->$attr = $vars[$attr];
            }
        }
    }

};

    
function redirect( $url ) {
    return new ServerResponse( array( 'code'=>302, 'redirect_url'=>$url) );
}

function response_page( $body ) {
    return new ServerResponse( array( 'code'=>200, 'content_type'=>'text/plain', 'body'=>$body) );
}

function error_page( $body ) {
    return new ServerResponse( array( 'code'=>400, 'content_type'=>'text/plain', 'body'=>$body) );
}




class ConsumerResponse {
    // This is a superclass to provide type unification for all the
    // various responses the consumer library can provide after
    // interpreting an openid query.

    // A Visitor pattern interface for dispatching to the various
    // subclasses is provided for users of the library who wish to use
    // it.
    function doAction( $handler ) {
        trigger_error( 'unimplemented', E_USER_WARNING );
    }
};    
        

class ActionHandler {

    function doValidLogin($login) {
        trigger_error( 'unimplemented', E_USER_WARNING );
    }

    function doInvalidLogin() {
        trigger_error( 'unimplemented', E_USER_WARNING );
    }

    function doUserCancelled() {
        trigger_error( 'unimplemented', E_USER_WARNING );
    }

    function doCheckAuthRequired($server_url, $return_to, $post_data) {
        trigger_error( 'unimplemented', E_USER_WARNING );
    }

    function doErrorFromServer($message) {
        trigger_error( 'unimplemented', E_USER_WARNING );
    }

    function createReturnTo($base_url, $identity_url, $args) {
        trigger_error( 'unimplemented', E_USER_WARNING );
    }

    function getOpenID() {
        trigger_error( 'unimplemented', E_USER_WARNING );
    }
};

class ValidLogin extends ConsumerResponse {
    // This subclass is used when the login succeeded.  The identity
    // parameter is the value that the id server has confirmed.

    // This method passes itself into its visitor pattern implementation.
    // This is so that its verifyIdentity method can be used in the
    // handler funtion.
    function ValidLogin($consumer, $identity) {
        $this->consumer = $consumer;
        $this->identity = $identity;
    }

    function doAction($handler) {
        return $handler->doValidLogin($this);
    }

    function verifyIdentity($identity) {
        // This method verifies that the identity passed in is one
        // that this response is actually claiming is valid.  It takes
        // care of checking if the identity url that the server actually
        // verified is delegated to by the identity passed in, if such a
        // check is needed.  Returns True if the identity passed in was
        // authenticated by the server, False otherwise.
error_log( "id: $identity       this_id: " . $this->identity . '      ' );        
        if( $identity == $this->identity ) {
            return true;
        }

        $ret = $this->consumer->find_identity_info($identity);
        if( !$ret ) {
            return false;
        }

        return $ret[1] == $this->identity;
    }
};    

class InvalidLogin extends ConsumerResponse {
    // This subclass is used when the login wasn't valid.
    function doAction($handler) {
        return $handler->doInvalidLogin();
    }
};        

class UserCancelled extends ConsumerResponse {
    // This subclass is used when the user cancelled the login.
    function doAction($handler) {
        return $handler->doUserCancelled();
    }
};    

class UserSetupNeeded extends ConsumerResponse {
    // This subclass is used when the UA needs to be sent to the given
    // user_setup_url to complete their login.
    function UserSetupNeeded($user_setup_url) {
        $this->user_setup_url = $user_setup_url;
    }

    function doAction($handler) {
        return $handler->doUserSetupNeeded($this->user_setup_url);
    }
};    

class ErrorFromServer extends ConsumerResponse {
    // This subclass is used
    function ErrorFromServer($message) {
        $this->message = $message;
    }

    function doAction($handler) {
        return $handler->doErrorFromServer($this->message);
    }
};    

class CheckAuthRequired extends ConsumerResponse {
    function CheckAuthRequired($server_url, $return_to, $post_data) {
        $this->server_url = $server_url;
        $this->return_to = $return_to;
        $this->post_data = $post_data;
    }

    function doAction($handler) {
        return $handler->doCheckAuthRequired(
            $this->server_url, $this->return_to, $this->post_data);
    }
};    


class Request {
    var $args;

    function Request($args, $http_method, $authentication=null) {
        // Creates a new Request object, used by both the consumer and
        // server APIs.  args should be an array map of http arguments,
        // whether via post or GET request.  http_method should be set to
        // either POST or GET, indicating how this request was made.
        //
        // authentication is a field that isn't used by any library code,
        // but exists purely as a pass-through, so that users of the
        // server library can verify that a given request has whatever
        // authentication credentials are needed to allow it correctly
        // calculate the return from get_auth_range.  A typical value of
        // the authentication field would be the username of the
        // logged-in user making the http request from the server.
        //
        // If an instance of this is created without any openid.* arguments,
        // a NoOpenIDArgs warning is raised.
        $this->args = array();
        $this->http_method = strtoupper($http_method);
        $this->authentication = $authentication;

        $found = false;
        foreach( $args as $k => $v ) {
            $needle = 'openid_';
            if( substr( $k, 0, strlen($needle)) == $needle ) {
                $found = true;
                $k = str_replace( $needle, 'openid.', $k );
            }
            $this->args[$k] = $v;
        }
        if( !$found ) {
            trigger_error( 'NoOpenIDArgs', E_USER_WARNING );
        }
    }

    function get($key, $default=null) {
        $k = 'openid.' . $key;
        return isset( $this->args[$k] ) ? $this->args[$k] : $default;
    }

/*
    function __getattr__(attr) {
        if attr[0] == '_':
            raise AttributeError

        val = $this->get(attr)
        if val is None:
            if attr == 'trust_root':
                return $this->return_to
            else:
                raise ProtocolError('Query argument %r not found' % (attr,))

        return val
  */
  
    function get_by_full_key($key, $default=null) {
        return $this->get($key, $default);
    }
    
    function toString() {
        $s = '';
        foreach( $this->args as $k => $v ) {
            $s .= "$k => $v\n";
        }
        return $s;
    }
};    

class ConsumerRequest extends Request {

    function ConsumerRequest($openid, $args, $http_method, $authentication=null) {
        parent::Request($args, $http_method, $authentication);
        $this->openid = $openid;
    }
};
        
?>

--- NEW FILE: consumer.php ---
<?php

/*****
PHP OpenID - OpenID consumer and server library

Copyright (C) 2005 Open Source Consulting, SA. and Dan Libby

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

Reciprocal linking.  The author humbly requests that if you should use 
PHP-OpenID on your website to provide an OpenID enabled service that you 
place a link to the author's website ( http://videntity.org ) somewhere 
that your users can discover it.  You are however under no obligation to 
do so.  

More info about PHP OpenID:
openid at videntity.org
http://videntity.org/openid/

More info about OpenID:
http://www.openid.net

*****/


require_once( 'httpclient.php' );
require_once( 'oid_util.php' );
require_once( 'association.php' );
require_once( 'interface.php' );
require_once( 'oid_parse.php' );

class OpenIDConsumerHelper {

    // Do not escape anything that is already 7-bit safe, so we do the
    // minimal transform on the identity URL
    function quote_minimal($s) {
        $res = '';
        for( $i = 0; $i < strlen($s); $i++ ) {
            $c = $s{$i};
            if( ord($c) >= 0x80 ) {
                $enc_c = utf8_encode( $c );
                for( $j = 0; $j < strlen( $enc_c ); $j ++ ) {
                    $b = $enc_c{$j};
                    $res .= sprintf('%%%02X', ord($b));
                }
            }
            else {
                $res .= $c;
            }
        }
        return $res;
    }
    
    // From openID spec:
    // The delegate identity URL must be canonical. It will not be further 
    // processed by the consumer, so be sure it has the "http://" and trailing 
    // slash, if there's no path component.
    function normalize_url($url) {
        assert( 'is_string( $url )' );
        $url = trim( $url );
        
        // Note: we use parse_url() here rather than checking for http(s) because
        // possibly the url contains eg ftp:// and it would be silly to prepend
        // http:// to such a url.
        $parts = parse_url( $url );
        $scheme = isset( $parts['scheme'] ) ? $parts['scheme'] : null;

        if( !$scheme ) {
            $url = 'http://' . $url;
            // If no scheme was found, then path will contain the whole url, which is not what we want,
            // so we parse it again.
            $parts = parse_url( $url );
        }

        $path = isset( $parts['path'] ) ? $parts['path'] : null;
        
        if( !$path ) {
            $url .= '/';
        }
        
    
        // Porting Todo: handle unicode urls.
        /*
        if isinstance(url, unicode) {
            parsed = urlparse.urlparse(url)
            authority = parsed[1].encode('idna')
            tail = map(quote_minimal, parsed[2:])
            encoded = (str(parsed[0]), authority) + tuple(tail)
            url = urlparse.urlunparse(encoded)
            assert type(url) is str
        */
    
        return $url;
    }

};

class OpenIDConsumer {
    function OpenIDConsumer($http_client=null, $assoc_mngr=null) {
        $this->http_client = $http_client ? $http_client : HTTPClient::getHTTPClient();
        $this->assoc_mngr = $assoc_mngr ? $assoc_mngr : new DumbAssociationManager();
    }

    function handle_request($server_id, $server_url, $return_to,
                       $trust_root=null, $immediate=false,
                       $required_fields=null) {
        // Returns the url to redirect to, where server_id is the
        // identity url the server is checking and server_url is the url
        // of the openid server.
        $redir_args = array( 'openid.identity' => $server_id,
                             'openid.return_to' => $return_to );

        if( $trust_root ) {
            $redir_args['openid.trust_root'] = $trust_root;
        }

        if( $immediate ) {
            $mode = 'checkid_immediate';
        }
        else {
            $mode = 'checkid_setup';
        }

        $redir_args['openid.mode'] = $mode;

        if ($required_fields) {
            $redir_args['openid.sreg.required'] = $required_fields;
        }

        $assoc_handle = $this->assoc_mngr->associate($server_url);

        if( $assoc_handle ) {
            $redir_args['openid.assoc_handle'] = $assoc_handle;
        }
        
        return oidUtil::append_args($server_url, $redir_args);
    }

    function handle_response($req) {
        // Handles an OpenID GET request with openid.mode in the
        // arguments. req should be a Request instance, properly
        // initialized with the http arguments given, and the http method
        // used to make the request.

        // This method returns a subclass of
        // openid.interface.ConsumerResponse.  See the openid.interface
        // module for the list of subclasses possible.

        if( $req->http_method != 'GET' ) {
            $error = sprintf( 'Expected HTTP Method "GET", got %s', $req->get('http_method') );
            // raise ProtocolError( $error )
            trigger_error( $error, E_USER_ERROR );
        }
        $func = 'do_' . $req->get('mode');
        if( !method_exists( $this, $func ) ) {
            $error = sprintf( "Unknown Mode: %s", $req->get('mode') );
            // raise ProtocolError( $error )
            trigger_error( $error, E_USER_ERROR );
        }
        
        return $this->$func($req);
    }

    function find_identity_info($identity_url) {
        // Returns (consumer_id, server_id, server_url) or null if no
        // server found. Fetch url and parse openid.server and
        // potentially openid.delegate urls.  consumer_id is the identity
        // url the consumer should use.  It is the url after following
        // any redirects the url passed in might use.  server_id is the
        // url actually sent to the server to verify, and may be the
        // result of finding a delegate link.
        $url = OpenIDConsumerHelper::normalize_url($identity_url);
        
        $ret = $this->http_client->get($url);
        if( !$ret ) {
            return null;
        }

        list( $consumer_id, $data ) = $ret;
        
        $server = null;
        $delegate = null;
        $link_attrs = oidParse::parseLinkAttrs($data);
        foreach( $link_attrs as $attrs ) {
            $rel = isset( $attrs['rel'] ) ? $attrs['rel'] : null;
            if( $rel == 'openid.server' && !$server ) {
                $href = isset( $attrs['href'] ) ? $attrs['href'] : null;
                if( $href ) {
                    $server = $href;
                }
            }

            if( $rel == 'openid.delegate' && !$delegate ) {
                $href = isset( $attrs['href'] ) ? $attrs['href'] : null;
                if( $href ) {
                    $delegate = $href;
                }
            }
        }

        if( !$server ) {
            return null;
        }

        if( $delegate ) {
            $server_id = $delegate;
        }
        else {
            $server_id = $consumer_id;
        }

        return array( $consumer_id, $server_id, $server );
    }

    function create_return_to($url, $identity_url, $kwargs) {
        // Returns an return_to url, with required identity_url, and
        // optional args
        $kwargs['identity'] = $identity_url;
        return oidUtil::append_args($url, $kwargs);
    }

    function check_auth($server_url, $return_to, $post_data, $openid) {
        // This method is called to perform the openid.mode =
        // check_authentication call.  The identity argument should be
        // the identity url you are confirming (from the consumer's
        // viewpoint, ie. not a delegated identity).  The return_to and
        // post_data arguments should be as contained in the
        // CheckAuthRequired object returned by a previous call to
        // handle_response.

        if( !$this->verify_return_to($return_to) ) {
            return new InvalidLogin();
        }

        // This is *required* because of PHP changing "." to "_" in URL
        // argument attributes, but not in values. And here some items
        // of the signed field argument value should exactly match the
        // name of some attributes given in the same URL. Understood?!
        //  (Choplair)
        $post_data = str_replace('sreg_', 'sreg.', $post_data);

        $ret = $this->http_client->post($server_url, $post_data);
        if( !$ret ) {
            return new InvalidLogin();
        }

        $data = $ret[1];

        $results = oidUtil::parsekv($data);
        $is_valid = isset( $results['is_valid'] ) ? $results['is_valid'] : 'false';
        if( $is_valid == 'true' ) {
            $invalidate_handle = isset( $results['invalidate_handle'] ) ? $results['invalidate_handle'] : null;
            if( $invalidate_handle ) {
                $this->assoc_mngr->invalidate($server_url, $invalidate_handle);
            }

            parse_str( $post_data, $vars );
            error_log( "post_data: $post_data        " );
            error_log( serialize($vars) . "        " );
            $key = 'openid_identity';  // php replaces . with _
            
            $identity = isset( $vars[$key] ) ? $vars[$key] : null;
            $vl = new ValidLogin($this, $identity);
            if( $vl->verifyIdentity($openid) ) {
                return $vl;
            }
        }
        else {
            $error = isset( $results['openid.error'] ) ? $results['openid.error'] : null;
            if( $error ) {
                $str = sprintf( 'Server Response: %s', $error );
                return new ErrorFromServer( $str );
            }
        }

        return new InvalidLogin();
    }

    function do_id_res($req) {

        if( !$this->verify_return_to($req->get('return_to')) ) {
            return new InvalidLogin();
        }

        $user_setup_url = $req->get('user_setup_url');
        if( $user_setup_url ) {
            return new UserSetupNeeded($user_setup_url);
        }

        $server_url = $this->determine_server_url($req);

        $assoc = $this->assoc_mngr->get_association($server_url, $req->get('assoc_handle'));
        
        if( !$assoc ) {

            // No matching association found. I guess we're in dumb mode...
            $check_args = array();
            foreach( $req->args as $k => $v ) {
                if( oidUtil::startsWith($k, 'openid.') ) {
                    $check_args[$k] = $v;
                }
            }

            $check_args['openid.mode'] = 'check_authentication';

            $post_data = http_build_query( $check_args );
            return new CheckAuthRequired($server_url, $req->get('return_to'), $post_data);
        }

        // Check the signature
        $sig = $req->get('sig');
        $signed_fields = explode( ',', trim( $req->get('signed') ) );
        
        list( $_signed, $v_sig ) = oidUtil::sign_reply($req->args, $assoc->secret, $signed_fields);
        
        if( $v_sig != $sig ) {
            
            return new InvalidLogin();
        }

        $vl = new ValidLogin($this, $req->get('identity') );
        if( $vl->verifyIdentity($req->openid  ) ) {

            return $vl;
        }
        return new InvalidLogin();
    }

    function do_error($req) {
        $error = $req->get('error');
        if( !$error ) {
            $str = sprintf( 'Unspecified Server Error: %s', $req->toString() );
            return new ErrorFromServer( $str );
        }
        else {
            $str = sprintf( 'Server Response: %s', $error );
            return new ErrorFromServer($str);
        }
    }

    function do_cancel($unused_req) {
        return new UserCancelled();
    }


    // Callbacks
    function determine_server_url($req) {
        // Returns the url of the identity server for the identity in
        // the request.

        // Subclasses might extract the server_url from a cache or from a
        // signed parameter specified in the return_to url passed to
        // initialRequest.

        // The default implementation fetches the identity page again,
        // and parses the server url out of it.
        
        // Grab the server_url from the identity in args
        $ret = $this->find_identity_info($req->get('identity'));
        if( !$ret ) {
            $error = sprintf( 'ID URL %s seems not to be an OpenID identity.', $req->get('identity') );
            // raise ValueMismatchError( $error )
            trigger_error( $error, E_USER_ERROR );
        }

        list( $unused, $server_id, $server_url ) = $ret;
        if( $req->get('identity') != $server_id ) {
            $error = sprintf( 'ID URL %r seems to have moved: %s', $req->get('identity'), $server_id );
            // raise ValueMismatchError( $error )
            trigger_error( $error, E_USER_ERROR );
        }

        return $server_url;
    }

    function verify_return_to($return_to) {
        // This method is called before the consumer makes a
        // check_authentication call to the server.  It helps verify that
        // the request being authenticated is valid by confirming that
        // the openid.return_to value signed by the server corresponds to
        // this consumer.  The return value should be True if the
        // return_to field corresponds to this consumer, or false
        // otherwise.  This method must be overridden, as it has no
        // default implementation.
        trigger_error( 'unimplemented', E_USER_WARNING );
    }
    
};    
        
        
?>

--- NEW FILE: oid_parse.php ---
<?php

/*****
PHP OpenID - OpenID consumer and server library

Copyright (C) 2005 Open Source Consulting, SA. and Dan Libby

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

Reciprocal linking.  The author humbly requests that if you should use 
PHP-OpenID on your website to provide an OpenID enabled service that you 
place a link to the author's website ( http://videntity.org ) somewhere 
that your users can discover it.  You are however under no obligation to 
do so.  

More info about PHP OpenID:
openid at videntity.org
http://videntity.org/openid/

More info about OpenID:
http://www.openid.net

*****/


class oidParse {

    // static, public
    // parses html data and returns <link> tag attributes.
    //
    // The return value is an array where each element 
    // is a sub-array containing all attribute/value
    // pairs from a single <link> tag.
    function parseLinkAttrs($data) {
    
        $tidy_ver = phpversion('tidy');
        if( (int)$tidy_ver == 2  ) {
            return oidParse::_parseLinkAttrsWithTidy2( $data );
        }
        // Todo: We could also have a method that uses Tidy1. volunteers?
        else {
            return oidParse::_parseLinkAttrsWithPreg( $data );
        }
        // Todo: We could also have a method that uses ereg. volunteers?
    }
    
    // static, private
    // parses all link attrs from an html page using perl regex ( preg/pcre )
    function _parseLinkAttrsWithPreg( $text ) {
    
        $tag_list = array();
    
        // find all tags
        preg_match_all('/<[^>]+>/s',$text,$tags);
        
        foreach ($tags[0] as $tag) {
               $gotten = preg_match('/^<\s*link\s*(.*)>/i',$tag,$alist);
               if ($gotten) {
                    // print "<b>$alist[1]</b><br>";
                    $cleaned = preg_replace('/\s+=\s+/','=',$alist[1]);
                    preg_match_all('/(?:^|\s)(\w+)="([^">]+)"/',$cleaned,$qatts);
                    preg_match_all('/(?:^|\s)(\w+)=([^"\s>]+)/',$cleaned,$patts);
                    $allatts = array_merge($patts[1],$qatts[1]);
                    $allvals = array_merge($patts[2],$qatts[2]);
                    $attrs = array();
                    for ($k=0; $k<count($allatts); $k++) {
                        $attrs[$allatts[$k]] = $allvals[$k];
                    }
                    $tag_list[] = $attrs;
               }
        }
        
        return $tag_list;
    }

    // static, private
    function _parseLinkAttrsWithTidy2Worker( $node, &$link_tags ) {
        
        $link_tags = $link_tags ? $link_tags : array();
        
        if(isset($node->id)) {
            if($node->id == TIDY_TAG_LINK ) {
            
                // $node->attribute is actually a mapped array with
                // key/val pairs for each of the nodes attributes.
                $link_tags[]  = $node->attribute;
                
            }
        }
        
        if( $node->hasChildren() ) {
    
            foreach($node->child as $next) {
                oidParse::_parseLinkAttrsWithTidy2Worker($next, $link_tags );
            }
    
        }
        
        return $link_tags;
    }
    
    // static, private
    function _parseLinkAttrsWithTidy2( $html ) {
        $tree = tidy_parse_string( $html );
        $tags = null;
        return oidParse::_parseLinkAttrsWithTidy2Worker( $tree->html(), $tags );
    }
    
    
};
        
        
?>

--- NEW FILE: server.php ---
<?php

/*****
PHP OpenID - OpenID consumer and server library

Copyright (C) 2005 Open Source Consulting, SA. and Dan Libby

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

Reciprocal linking.  The author humbly requests that if you should use 
PHP-OpenID on your website to provide an OpenID enabled service that you 
place a link to the author's website ( http://videntity.org ) somewhere 
that your users can discover it.  You are however under no obligation to 
do so.  

More info about PHP OpenID:
openid at videntity.org
http://videntity.org/openid/

More info about OpenID:
http://www.openid.net

*****/


require_once( 'oid_util.php' );
require_once( 'interface.php' );
require_once( 'trustroot.php' );


define( '_oid_authentication_error', -1);

class OpenIDServer {

    function OpenIDServer($internal_store, $external_store, $srand=null) {
        // srand should be a cryptographic-quality source of random
        // bytes, if Diffie-Helman secret exchange is to be supported.
        // On systems where it is available, an instance of
        // random.SystemRandom is a good choice.
        $this->istore = $internal_store;
        $this->estore = $external_store;
        $this->srand = $srand;
    }

    function handle($req) {
        // Handles an OpenID request.  req should be a Request
        // instance, properly initialized with the http arguments given,
        // and the method used to make the request.  Returns a Response
        // instance with the necessary fields set to indicate the
        // appropriate action.

        $method_name = 'do_' . $req->get('mode');
        
        if( !method_exists( $this, $method_name ) ) {
            $error = sprintf('Unsupported openid.mode: %s', $req->get('mode') );

            $return_to = $req->get( 'return_to' );
            if( $req->get( 'http_method' ) == 'GET' && $return_to ) {
                return redirect( oidUtil::append_args(return_to, $edict));
            }
            else {
                return OpenIDServer::_error_page( $error );
            }
        }
        
        return $this->$method_name($req);
    }

    function do_associate($req) {
        // Performs the actions needed for openid.mode=associate.  If
        // srand was provided when constructing this server instance,
        // this method supports the DH-SHA1 openid.session_type when
        // requested.  This function requires that $this->get_new_secret be
        // overriden to function properly.  Returns a Response object
        // indicating what should be sent back to the consumer.
        $reply = array();
        $assoc_type = $req->get('openid.assoc_type', 'HMAC-SHA1');
        $assoc = $this->estore->get($assoc_type);

        $session_type = $req->get('session_type');
        if( $session_type ) {
            if( $session_type == 'DH-SHA1' ) {
                $p = $req->get('dh_modulus');
                $g = $req->get('dh_gen');
                
                $dh = DiffieHellman::fromBase64($p, $g, $this->srand);
                
                $cpub = oidUtil::a2long( oidUtil::from_b64($req->get( 'dh_consumer_public' )) );

                $dh_shared = $dh->decryptKeyExchange($cpub);

                $mac_key = oidUtil::strxor( $assoc->secret, oidUtil::sha1( oidUtil::long2a($dh_shared) ));

                $spub = $dh->createKeyExchange();

                $reply['session_type'] = $session_type;
                $reply['dh_server_public'] = oidUtil::to_b64(oidUtil::long2a($spub));
                $reply['enc_mac_key'] = oidUtil::to_b64($mac_key);
                
                // error_log( "assoc.secret: " . $assoc->secret );
                // error_log( "dh_server_public: " . $reply['dh_server_public'] );
                // error_log( "dh_server_public_raw: " . $spub );
                // error_log( "enc_mac_key: " . $reply['enc_mac_key'] );
                
            }
            else {
                // raise ProtocolError('session_type must be DH-SHA1');
                $error = 'session_type must be DH-SHA1';
                return OpenIDServer::_error_page( $error );
            }
        }
        else {
            $reply['mac_key'] = oidUtil::to_b64($assoc->secret);
        }

        $reply['assoc_type'] = $assoc_type;
        $reply['assoc_handle'] = $assoc->handle;
        $reply['expires_in'] = $assoc->get_expires_in();
        
        return response_page(oidUtil::kvform($reply));
    }

    function do_checkid_immediate($req) {
    /*
        try:
            return $this->checkid(req)
        except AuthenticationError:
            user_setup_url = $this->get_user_setup_url(req)
            reply = {
                'openid.mode': 'id_res',
                'openid.user_setup_url': user_setup_url,
                }
            return redirect(append_args(req.return_to, reply))
     */
     
        $rc = $this->checkid($req);
        if( is_int($rc) && $rc == _oid_authentication_error ) {
            $user_setup_url = $this->get_user_setup_url($req);
            $reply = array(
                'openid.mode' => 'id_res',
                'openid.user_setup_url' => $user_setup_url
            );
            return redirect(oidUtil::append_args($req->get( 'return_to' ), $reply));
        }
        return $rc;
    }
            
     

    function do_checkid_setup($req) {
    /*
        try:
            return $this->checkid(req)
        except AuthenticationError:
            return $this->get_setup_response(req)
     */
     
        $rc = $this->checkid($req);
        if( is_int( $rc ) && $rc == _oid_authentication_error ) {
            return $this->get_setup_response($req);
        }
        return $rc;
    }

    // errors:
    //   _oid_authentication_error
    function checkid($req) {
        // This function does the logic for the checkid functions.
        // Since the only difference in behavior between them is how
        // authentication errors are handled, this does all logic for
        // dealing with successful authentication, and raises an
        // exception for its caller to handle on a failed authentication.
        
        $tr = TrustRoot::parse($req->get('trust_root') );
        if( !$tr ) {
            //raise ProtocolError('Malformed trust_root: %s' % req.trust_root)
            $error = sprintf('Malformed trust_root: %s', $req->get('trust_root'));
            return OpenIDServer::_error_page( $error );
        }

        if( !$tr->isSane() ) {
            // raise ProtocolError('trust_root %r makes no sense' % req.trust_root)
            $error = sprintf( 'trust_root %s makes no sense', $req->get('trust_root'));
            return OpenIDServer::_error_page( $error );
        }

        if( !$tr->validateURL($req->get('return_to')) ) {
        //    raise ProtocolError('url(%s) not valid against trust_root(%s)' % (
        //        req.return_to, req.trust_root))
            $error = sprintf( 'url(%s) not valid against trust_root(%s)', $req->get('return_to'), $req->get('trust_root'));
            return OpenIDServer::_error_page( $error );
        }

        if( !$this->is_valid($req) ) {
            // raise AuthenticationError
            return _oid_authentication_error;
        }

        $reply = array(
            'openid.mode' => 'id_res',
            'openid.return_to' => $req->get('return_to'),
            'openid.identity' => $req->get('identity')
        );

        $assoc_handle = $req->get('assoc_handle');
        if( $assoc_handle ) {
            $assoc = $this->estore->lookup($assoc_handle, 'HMAC-SHA1');

            // fall back to dumb mode if assoc_handle not found,
            // and send the consumer an invalidate_handle message
            if( !$assoc || $assoc->get_expires_in() <= 0 ) {
                if( $assoc && $assoc->get_expires_in() <= 0 ) {
                    $this->estore->remove($assoc->handle);
                }
                $assoc = $this->istore->get('HMAC-SHA1');
                $reply['openid.invalidate_handle'] = $assoc_handle;
            }
        }
        else {
            $assoc = $this->istore->get('HMAC-SHA1');
        }

        $reply['openid.assoc_handle'] = $assoc->handle;

        $_signed_fields = array('mode', 'identity', 'return_to');

        list( $signed, $sig ) = oidUtil::sign_reply($reply, $assoc->secret, $_signed_fields );

        $reply['openid.signed'] = $signed;
        $reply['openid.sig'] = $sig;
        
        return redirect(oidUtil::append_args($req->get('return_to'), $reply));
    }

    function do_check_authentication($req) {
    
        $handle = $req->get('assoc_handle');
    
        // Last step in dumb mode
        $assoc = $this->istore->lookup($req->get('assoc_handle'), 'HMAC-SHA1');

        if( !$assoc ) {
            // raise ProtocolError('no secret found for %r' % req.assoc_handle)
            $error = sprintf( 'no secret found for %r', $req->get('assoc_handle') );
            // trigger_error( $error, $E_USER_WARNING );
            
            return OpenIDServer::_error_page( $error );
        }

        $reply = array();
        if( $assoc->get_expires_in() > 0 ) {
            $token = $req->args;
            $token['openid.mode'] = 'id_res';

            $signed_fields = explode(',', trim($req->get('signed')));
            list( $ignore, $v_sig ) = oidUtil::sign_reply($token, $assoc->secret, $signed_fields);

            if( $v_sig == $req->get('sig') ) {
                $is_valid = 'true';

                // if an invalidate_handle request is present, verify it
                $invalidate_handle = $req->get('invalidate_handle');
                if( $invalidate_handle ) {
                    if( !$this->estore->lookup($invalidate_handle, 'HMAC-SHA1') ) {
                        $reply['invalidate_handle'] = $invalidate_handle;
                    }
                }
            }
            else {
            
                $is_valid = 'false';
            }
        }

        else {
        
            $this->istore->remove($req->get('assoc_handle'));
            $is_valid = 'false';
        }

        $reply['is_valid'] = $is_valid;
        return response_page(oidUtil::kvform($reply));
    }
    
    // private
    function _error_page( $error ) {
    
        $edict = array(
            'openid.mode' => 'error',
            'openid.error' => $error
        );

        return error_page(oidUtil::kvform($edict));
    }
    

    // Callbacks:
    function is_valid($req) {
        // If a valid authentication is supplied as part of the
        // request, and allows the given trust_root to authenticate the
        // identity url, this returns True.  Otherwise, it returns False.
        
        trigger_error( 'unimplemented', E_USER_WARNING );
    }

    function get_user_setup_url($req) {
        // If an identity has failed to authenticate for a given
        // trust_root in immediate mode, this is called.  It returns the
        // URL to include as the user_setup_url in the redirect sent to
        // the consumer.
        trigger_error( 'unimplemented', E_USER_WARNING );
    }

    function get_setup_response($req) {
        // If an identity has failed to authenticate for a given
        // trust_root in setup mode, this is called.  It returns a
        // Response object containing either a page to draw or a redirect
        // to issue.
        trigger_error( 'unimplemented', E_USER_WARNING );
    }

};

?>

--- NEW FILE: COPYING ---
PHP OpenID - OpenID consumer and server library

Copyright (C) 2005 Open Source Consulting, SA. and Dan Libby

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

Reciprocal linking.  The author humbly requests that if you should use 
PHP-OpenID on your website to provide an OpenID enabled service that you 
place a link to the author's website ( http://videntity.org ) somewhere 
that your users can discover it.  You are however under no obligation to 
do so.  

More info about PHP OpenID:
openid at videntity.org
http://videntity.org/openid/

More info about OpenID:
http://www.openid.net
--- NEW FILE: oid_util.php ---
<?php

/*****
PHP OpenID - OpenID consumer and server library

Copyright (C) 2005 Open Source Consulting, SA. and Dan Libby

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

Reciprocal linking.  The author humbly requests that if you should use 
PHP-OpenID on your website to provide an OpenID enabled service that you 
place a link to the author's website ( http://videntity.org ) somewhere 
that your users can discover it.  You are however under no obligation to 
do so.  

More info about PHP OpenID:
openid at videntity.org
http://videntity.org/openid/

More info about OpenID:
http://www.openid.net

*****/


// for compatibility with versions of php without http_build_query
// from http://php.net/manual/en/function.http-build-query.php#52789
// Note: It does not work with complex arrays.
if (!function_exists('http_build_query')) {
   function http_build_query($formdata, $numeric_prefix = "")
   {
       $arr = array();
       foreach ($formdata as $key => $val)
         $arr[] = urlencode($numeric_prefix.$key)."=".urlencode($val);
       return implode($arr, '&');
   }
}


class oidUtil {

    function hmacsha1( $key, $text ) {
        return oidUtilPhpSha1::hmacsha1( $key, $text );
    }

    function sha1( $s ) {
        return oidUtilPhpSha1::sha1( $s );
    }
    
    // Note: in php we don't really convert to a long because php doesn't
    // support values this large.
    // 
    // instead we return a string converted from hex to base 10.
    function a2long($l) {
    
        $len = strlen($l);
        // transform bytes/char values into hex number
        $foo = unpack("H".(2*$len), $l);
        $hex = array_pop($foo);

        return oidUtilPhpBigInt::base_convert( $hex, 16, 10 );
    }


    // Note: in php we aren't really expecting a long as input.
    // Rather we expect a string containing a base 10 number.
    // 
    // we return a packed (byte) string containing a base 16 number.
    function long2a($a) {

        $hex = oidUtilPhpBigInt::base_convert( $a, 10, 16 );

        // pad
        if (strlen($hex) % 2) {
         $hex = "0" . $hex;   // pad leading hex nibble
        }
        if (ord($hex[0]) >= ord('8')) {
         $hex = "00" . $hex;  // pad if it looks like negative number 
        }
        // into bytestream
        return pack("H*", $hex);
    
    }
    
    function to_b64($s) {
        // Represent string s as base64, omitting newlines
        return base64_encode($s);
    }
    
    function from_b64($s) {
        return base64_decode($s);
    }    
    
    function kvform($ma) {
    
        // Represent mapped array ma as newline-terminated key:value pairs
        $str = '';
        foreach( $ma as $key => $val ) {
            $str .= sprintf( "%s:%s\n", $key, $val );
        }
        return $str;
    }    
    
    function parsekv( $d ) {
        $d = trim($d);
        $args = array();
        $lines = explode( "\n", $d );
        foreach( $lines as $line ) {
            $pair = explode( ':', $line, 2 );
            if( count($pair) != 2 ) {
                continue;
            }
            list($k,$v) = $pair;
            $args[trim($k)] = trim($v);
        }
        return $args;
    }
    
    function strxor( $aa, $bb ) {
    
        $buf = '';
        $len = min( strlen($aa), strlen($bb) );
        
        for ($i=0; $i<$len; $i++) {
          $buf .= chr( ord($aa[$i]) ^ ord($bb[$i]) );
        }
        return $buf;
    }
    
    function sign_reply($reply, $key, $signed_fields ) {
        // Sign the given fields from the reply with the specified key.
        // Return signed and sig
        
        $text = '';
        
        foreach( $signed_fields as $i ) {
            $val = $reply['openid.' . $i];
            $text .= sprintf( "%s:%s\n", $i, $val );
        }
        
        $sha1 = oidUtil::hmacsha1($key, $text);
        $b64_sha1 = oidUtil::to_b64( $sha1 );
        
        return array( implode( ',', $signed_fields ), $b64_sha1 );
    }
    
    function append_args( $url, $args ) {
        if( count($args) == 0 ) {
            return url;
        }
        $sep = strchr( $url, '?') ? '&' : '?';
        return sprintf('%s%s%s',  $url, $sep, http_build_query($args));
    }
    
    function random_string($length, $srand = null) {
    
        if( $srand ) {
            srand( $srand );
        }
    
        $a = '';
        for( $i = 0; $i < $length; $i++ ) {
            $a .= chr(rand(0,255));
        }
        return $a;
    }
    
    // PHP lacks these very handy string functions, startsWith and endsWith.
    // included here for easier porting from python.
    
    function startsWith( $str, $sub ) {
       return ( substr( $str, 0, strlen( $sub ) ) == $sub );
    }
    
    // return tru if $str ends with $sub
    function endsWith( $str, $sub ) {
       $len1 = strlen( $str );
       $len2 = strlen( $sub );
       return $len1 >= $len2 && ( substr( $str, $len1 - $len2 ) == $sub );
    }

};

// Porting note. This class does not exist in python.
// It was created to abstract the various implementations of sha1
// available ( or not available ) in php >= 4.x
class oidUtilPhpSha1 {

    // static 
    function hmacsha1( $key, $text ) {
        if( function_exists( 'mhash' ) ) {
            // yay, we have mhash!
            return mhash(MHASH_SHA1, $text, $key);
        }
        else {
            // do it ourselves.
            return oidUtilPhpSha1::_hmacsha1( $key, $text );
        }
    }
    
    // static
    function sha1( $s ) {
        if( function_exists( 'mhash' ) ) {
            // we have mhash, yay!
            return mhash(MHASH_SHA1, $s);
        }
        else if( function_exists( 'sha1' ) ) {
            // we have php's sha1, okie dokie
            if ((int)PHP_VERSION>=5) {
                return sha1($s, true);
            } else {
                // before php5, php does not support raw output.
                return pack("H*", sha1($s));
            }
        }
        else {
            // gotta do it ourselves.
            return oidUtilPhpSha1::_sha1_raw( $s );
        }
    }

    // private
    // adapted from from http://php.net/manual/en/function.sha1.php#39492
    // mark at dot BANSPAM dot pronexus dot nl
    function _hmacsha1($key,$data) {
       $blocksize=64;
       if (strlen($key)>$blocksize) {
           $key=oidUtilPhpSha1::sha1($key);
       }
       $key=str_pad($key,$blocksize,chr(0x00));
       $ipad=str_repeat(chr(0x36),$blocksize);
       $opad=str_repeat(chr(0x5c),$blocksize);
       $hmac = oidUtilPhpSha1::sha1( ($key^$opad) . oidUtilPhpSha1::sha1( ($key^$ipad) . $data ) );
       return $hmac;
    }    
    
    // private
    // php implementation of sha1, for older php versions. reportedly fast.
    // adapted from http://php.net/manual/en/function.sha1.php#48856
    // mina86 at tlen dot pl
	function _sha1_step(&$H, $str) {
		$A = $H[0]; $B = $H[1]; $C = $H[2]; $D = $H[3]; $E = $H[4];
		$W = array_values(unpack('N16', $str));
		for ($i = 0; $i<16; ++$i) {
			$W[$i+16] = &$W[$i];
		}

		$t = 0;
		do {		//  0 <= t < 20
			$s = $t & 0xf;
			if ($t>=16) {
				$W[$s] = oidUtilPhpSha1::_sha1_s($W[$s+13] ^ $W[$s+8] ^ $W[$s+ 2] ^ $W[$s]);
			}

			$TEMP = ($D ^ ($B & ($C ^ $D))) + 0x5A827999 +
				 oidUtilPhpSha1::_sha1_s($A, 5) + $E + $W[$s];
			$E = $D; $D = $C; $C = oidUtilPhpSha1::_sha1_s($B, 30); $B = $A; $A = $TEMP;
		} while (++$t<20);

		do {		// 20 <= t < 40
			$s = $t & 0xf;
			$W[$s] = oidUtilPhpSha1::_sha1_s($W[$s+13] ^ $W[$s+8] ^ $W[$s+ 2] ^ $W[$s]);

			$TEMP = ($B ^ $C ^ $D) + 0x6ED9EBA1 +
				 oidUtilPhpSha1::_sha1_s($A, 5) + $E + $W[$s];
			$E = $D; $D = $C; $C = oidUtilPhpSha1::_sha1_s($B, 30); $B = $A; $A = $TEMP;
		} while (++$t<40);

		do {		// 40 <= t < 60
			$s = $t & 0xf;
			$W[$s] = oidUtilPhpSha1::_sha1_s($W[$s+13] ^ $W[$s+8] ^ $W[$s+ 2] ^ $W[$s]);

			$TEMP = (($B & $C) | ($D & ($B | $C))) + 0x8F1BBCDC +
				 oidUtilPhpSha1::_sha1_s($A, 5) + $E + $W[$s];
			$E = $D; $D = $C; $C = oidUtilPhpSha1::_sha1_s($B, 30); $B = $A; $A = $TEMP;
		} while (++$t<60);

		do {		// 60 <= t < 80
			$s = $t & 0xf;
			$W[$s] = oidUtilPhpSha1::_sha1_s($W[$s+13] ^ $W[$s+8] ^ $W[$s+ 2] ^ $W[$s]);

			$TEMP = ($B ^ $C ^ $D) + 0xCA62C1D6 +
				 oidUtilPhpSha1::_sha1_s($A, 5) + $E + $W[$s];
			$E = $D; $D = $C; $C = oidUtilPhpSha1::_sha1_s($B, 30); $B = $A; $A = $TEMP;
		} while (++$t<80);

		$H = array($H[0] + $A, $H[1] + $B, $H[2] + $C, $H[3] + $D, $H[4] + $E);
	}

    // private
    // php implementation of sha1, for older php versions. reportedly fast.
    // adapted from http://php.net/manual/en/function.sha1.php#48856
    // mina86 at tlen dot pl
    function _sha1_s($X, $n = 1) {
		return ($X << $n) | (($X & 0x80000000)?
			 (($X>>1) & 0x07fffffff | 0x40000000)>>(31-$n):$X>>(32-$n));
	}

    // private
    // php implementation of sha1, for older php versions. reportedly fast.
    // adapted from http://php.net/manual/en/function.sha1.php#48856
    // mina86 at tlen dot pl
	function &_sha1_raw($str) {
		$l = strlen($str);
		$str = str_pad("$str\x80\0\0\0\0", ($l&~63)+((($l&63)<56)?60:124),
					   "\0") .  pack('N', $l<<3);
		$l = strlen($str);

		$H = array(0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0);
		for ($i = 0; $i<$l; $i += 64) {
			oidUtilPhpSha1::_sha1_step($H, substr($str, $i, 64));
		}

        $raw = pack('N*', $H[0], $H[1], $H[2], $H[3], $H[4]);
		return $raw;
	}
};


// Porting note. This class does not exist in python.
// It was created to abstract the various implementations of bigint
// available ( or not available ) in php >= 4.x
class oidUtilPhpBigInt {

    // static
    // adapted from xprofile's openlid
    //  http://xprofile.berlios.de/OpenLid
    function powm( $base, $exponent, $modulus ) {

        if( function_exists('gmp_powm')) {
            return gmp_strval(gmp_powm($base, $exponent, $modulus));
        }
        else if( function_exists('bi_powmod'))  {
            return bi_sto_str(bi_powmod($base, $exponent, $modulus));
        }
        else if( function_exists( 'bcpowmod' ) ) {
            return bcpowmod( $base, $exponent, $modulus );
        }
        // Warning: here we give up on php and call python or perl to help us out.
        // I'd like to replace this with native php code. Anyone know of
        // a good/fast implementation of powmod in php?
        // Anyway, if you don't want perl or python executed, comment out
        // this else clause.
        else if( preg_match("/^\d+,\d+,\d+$/", "$base,$exponent,$modulus")) {
            //@FIX: this is insecure - a bi-directional proc_open() is required
            if (is_executable("/usr/bin/python")) {
                $r = trim(`python -c "print pow($base, $exponent, $modulus)"`);
            }
            else {
                $r = trim(`perl -e "use Math::BigInt; print Math::BigInt->new('$base')->bmodpow('$exponent', '$modulus')->bstr();"`);
            }
            if (preg_match("/^\d+$/", $r)) {
                return($r);
            }
        }
        trigger_error("powmod: unsupported or non-integer argument", E_USER_ERROR);
    }

    // static
    function random( $minval ) {
    
        if( function_exists( 'gmp_random' ) ) {
            $limb_cnt = 31;
            do {
                $rdm = gmp_random($limb_cnt--);
            } while (gmp_cmp( $minval, $rdm) > 0);
            return gmp_strval($rdm);
        }
        else {
            // FIXME: does not honor minval
            return rand( 0, getrandmax() );
        }
    }

    // static
    function base_convert( $numstring, $frombase, $tobase ) {
    
        if ( function_exists('gmp_strval')) {
            return gmp_strval( gmp_init($numstring, $frombase), $tobase);
        }
        else if ( function_exists('bi_base_convert')) {
            return bi_base_convert($numstring, $frombase, $tobase );
        }
        else {
            return oidUtilPhpBigInt::_base_convert($numstring, $frombase, $tobase);
        }
    
    }
    
    // private
    //
    // From comment at http://php.net/manual/en/function.base-convert.php
    // by rithiur at mbnet dot fi
    //
    // Here is a simple function that can convert numbers of any size. 
    // However, note that as the division is performed manually to the 
    // number, this function is not very efficient and may not be suitable 
    // for converting strings with more than a few hundred numbers 
    // (depending on the number bases).
    function _base_convert($numstring, $frombase, $tobase)
    {
       $hex = '0123456789abcdef';
       $from_count = $frombase;
       $to_count = $tobase;
       $length = strlen($numstring);
       $result = '';
       $number = array();
       
       for ($i = 0; $i < $length; $i++)
       {
           $number[$i] = strpos($hex, $numstring{$i});
       }
       do // Loop until whole number is converted
       {
           $divide = 0;
           $newlen = 0;
           for ($i = 0; $i < $length; $i++) // Perform division manually (which is why this works with big numbers)
           {
               $divide = $divide * $from_count + $number[$i];
               if ($divide >= $to_count)
               {
                   $number[$newlen++] = (int)($divide / $to_count);
                   $divide = $divide % $to_count;
               }
               elseif ($newlen > 0)
               {
                   $number[$newlen++] = 0;
               }
           }
           $length = $newlen;

           $result = $hex{$divide} . $result; // Divide is basically $numstring % $to_count (i.e. the new character)
       }
       while ($newlen != 0);
       return $result;
    }
    
};

class DiffieHellman {

    var $DEFAULT_MOD = '155172898181473697471232257763715539915724801966915404479707795314057629378541917580651227423698188993727816152646631438561595825688188889951272158842675419950341258706556549803580104870537681476726513255747040765857479291291572334510643245094715007229621094194349783925984760375594985848253359305585439638443';
    var $DEFAULT_GEN = '2';
    
    var $p;
    var $g;
    var $x;
    
    // static
    function fromBase64( $p = null, $g = null, $srand = null ) {
    
        if( $p ) {
            $p = oidUtil::a2long(oidUtil::from_b64($p));
        }
        if( $g ) {
            $g = oidUtil::a2long(oidUtil::from_b64($g));
        }
        return new DiffieHellman($p, $g, $srand);
    }
    
    function DiffieHellman( $p = null, $g = null, $srand = null ) {
    
        $this->p = $p ? $p : $this->DEFAULT_MOD;
        $this->g = $g ? $g : $this->DEFAULT_GEN;
        
        if( $srand ) {
            $this->x = $srand;
        }
        else {
            $this->x = oidUtilPhpBigInt::random( $this->p );
        }
    }
    
    function createKeyExchange( ) {
    
        return oidUtilPhpBigInt::powm( $this->g, $this->x, $this->p);
    }

    function decryptKeyExchange( $keyEx ) {
    
        return oidUtilPhpBigInt::powm( $keyEx, $this->x, $this->p );
    
    }
    
}


?>

--- NEW FILE: association.php ---
<?php

/*****
PHP OpenID - OpenID consumer and server library

Copyright (C) 2005 Open Source Consulting, SA. and Dan Libby

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

Reciprocal linking.  The author humbly requests that if you should use 
PHP-OpenID on your website to provide an OpenID enabled service that you 
place a link to the author's website ( http://videntity.org ) somewhere 
that your users can discover it.  You are however under no obligation to 
do so.  

More info about PHP OpenID:
openid at videntity.org
http://videntity.org/openid/

More info about OpenID:
http://www.openid.net

*****/


require_once( 'oid_util.php' );

class Association {
    // static
    function from_expires_in( $handle, $secret, $expires_in ) {
        return new Association( $handle, $secret, time(), $expires_in );
    }

    function Association($handle, $secret, $issued, $lifetime) {
        $this->handle = $handle;
        $this->secret = $secret;
        $this->issued = (int)$issued;
        $this->lifetime = (int)$lifetime;
    }

    function get_expires_in() {
        return max(0, $this->issued + $this->lifetime - time());
    }

    // expires_in = property(get_expires_in)
};

class ConsumerAssociation extends Association {

    // static
    function from_expires_in( $expires_in, $server_url, $handle, $secret ) {
        return new ConsumerAssociation( $server_url, $handle, $secret, time(), $expires_in );
    }

    function ConsumerAssociation($server_url, $handle, $secret, $issued, $lifetime) {
        parent::Association( $handle, $secret, $issued, $lifetime );
        $this->server_url = $server_url;
    }
};        


class ConsumerAssociationManager {
    // Base class for type unification of Association Managers.  Most
    // implementations of this should extend the BaseAssociationManager
    // class below.
    function get_association($server_url, $assoc_handle) {
        trigger_error( 'unimplemented', E_USER_WARNING );
    }
    
    function associate($server_url) {
        trigger_error( 'unimplemented', E_USER_WARNING );
    }
    
    function invalidate($server_url, $assoc_handle) {
        trigger_error( 'unimplemented', E_USER_WARNING );
    }
}    


class DumbAssociationManager extends ConsumerAssociationManager {
    // Using this class will cause a consumer to behave in dumb mode.
    function get_association($server_url, $assoc_handle) {
        return null;
    }
    
    function associate($server_url) {
        return null;
    }
    
    function invalidate($server_url, $assoc_handle) {
        return;
    }
};

class AbstractConsumerAssociationManager extends ConsumerAssociationManager {
    // Abstract base class for association manager implementations.

    function AbstractConsumerAssociationManager($associator) {
        $this->associator = $associator;
    }

    function associate($server_url) {
        // Returns assoc_handle associated with server_url
        $expired = array();
        $assoc = null;
        $all = $this->get_all($server_url);
        foreach( $all as $current) {
            if( $current->get_expires_in() <= 0 ) {
                $expired[] = $current;
            }
            else if( !$assoc || $current->get_expires_in() > $assoc->get_expires_in() ) {
                $assoc = $current;
            }
        }

        $new_assoc = null;
        if( !$assoc ) {
            $assoc = $new_assoc = $this->associator->associate($server_url);
        }

        // print "assoc.secret:"
        // print to_b64(assoc.secret)
        if( $new_assoc || $expired ) {
            $this->update($new_assoc, $expired);
        }

        return $assoc->handle;
    }

    function get_association($server_url, $assoc_handle) {
        // Find the secret matching server_url and assoc_handle
        $associations = $this->get_all($server_url);
        foreach( $associations as $assoc ) {
            if( $assoc->handle == $assoc_handle ) {
                return $assoc;
            }
        }

        return null;
    }

    // Subclass need to implement the following methods:
    function update($new_assoc, $expired) {
        // new_assoc is either a new association object or None.
        // Expired is a possibly empty list of expired associations.
        // Subclasses should add new_assoc if it is not None and expire
        // each association in the expired list.
        trigger_error( 'unimplemented', E_USER_WARNING );
    }
    
    function get_all($server_url) {
        // Subclasses should return a list of ConsumerAssociation
        // objects whose server_url attribute is equal to server_url.
        trigger_error( 'unimplemented', E_USER_WARNING );
    }

    function invalidate($server_url, $assoc_handle) {
        // Subclasses should remove the ConsumerAssociation for the
        // given server_url and assoc_handle from their stores.
        trigger_error( 'unimplemented', E_USER_WARNING );
    }

};


class DiffieHelmanAssociator {
    function DiffieHelmanAssociator($http_client, $srand=null) {
        $this->http_client = $http_client;
        $this->srand = $srand;
    }

    function get_mod_gen() {
        // -> (modulus, generator) for Diffie-Helman

        // override this function to use different values
        $dh = new DiffieHellman();
        return array( $dh->DEFAULT_MOD, $dh->DEFAULT_GEN);
    }
    
    function getResult( $results, $key ) {
    
        if( !isset( $results[$key] ) ) {
            trigger_error( sprintf( 'protocol error : Association server response missing argument %s', $key ), E_USER_WARNING );
            return null;
        }
        return $results[$key];
    }

    function associate($server_url) {
        list( $p, $g ) = $this->get_mod_gen();
        $dh = new DiffieHellman($p, $g, $this->srand);
        $cpub = $dh->createKeyExchange();

        $args = array(
            'openid.mode' => 'associate',
            'openid.assoc_type' =>'HMAC-SHA1',
            'openid.session_type' =>'DH-SHA1',
            'openid.dh_modulus' => oidUtil::to_b64(oidUtil::long2a($dh->p)),
            'openid.dh_gen' => oidUtil::to_b64(oidUtil::long2a($dh->g)),
            'openid.dh_consumer_public' => oidUtil::to_b64(oidUtil::long2a($cpub)),
        );

        $body = http_build_query($args);

        list( $url, $data ) = $this->http_client->post($server_url, $body);
        $results = oidUtil::parsekv($data);

        $assoc_type = $this->getResult( $results, 'assoc_type');
        if( $assoc_type != 'HMAC-SHA1' ) {
            trigger_error( sprintf( 'runtime error : Unknown association type %s', $assoc_type ), E_USER_WARNING );
        }

        $assoc_handle = $this->getResult( $results, 'assoc_handle');
        $expires_in = isset( $results['expires_in'] ) ? $results['expires_in'] : 0;

        $session_type = isset( $results['session_type'] ) ? $results['session_type'] : 0;
        if( !$session_type ) {
            $secret = oidUtil::from_b64( $this->getResult( $results, 'mac_key'));
        }
        else {
            if( $session_type != 'DH-SHA1' ) {
                trigger_error( sprintf( 'runtime error : Unknown Session Type: %s', $session_type ), E_USER_WARNING );
            }

            $spub = oidUtil::a2long(oidUtil::from_b64( $this->getResult( $results, 'dh_server_public')));
            $dh_shared = $dh->decryptKeyExchange($spub);
            $enc_mac_key = $this->getResult( $results, 'enc_mac_key');
            
            // print "enc_mac_key: " . $enc_mac_key;
            $secret = oidUtil::strxor(oidUtil::from_b64($enc_mac_key), oidUtil::sha1(oidUtil::long2a($dh_shared)));
        }
                                    
        return ConsumerAssociation::from_expires_in( $expires_in, $server_url, $assoc_handle, $secret );
    }
};


class ServerAssociationStore {
    // This is the interface the OpenIDServer class expects its
    // internal_store and external_store objects to support.

    function get($assoc_type) {
        // This method returns an association handle for the given
        // association type.  For the internal_store, implementations may
        // return either a new association, or an existing one, as long
        // as the association it returns won't expire too soon to be
        // useable.  For the external_store, implementations must return
        // a new association each time this method is called.
        trigger_error( 'unimplemented', E_USER_WARNING );
    }

    function lookup($assoc_handle, $assoc_type) {
        // This method returns the stored association for a given
        // handle and association type.  If there is no such stored
        // association, it should return None.
        trigger_error( 'unimplemented', E_USER_WARNING );
    }

    function remove($handle) {
        // If the server code notices that an association it retrieves
        // has expired, it will call this method to let the store know it
        // should remove the given association.  In general, the
        // implementation should take care of that without the server
        // code getting involved.  This exists primarily to deal with
        // corner cases correctly.
        trigger_error( 'unimplemented', E_USER_WARNING );
    }

}

?>

--- NEW FILE: httpclient.php ---
<?php

/*****
PHP OpenID - OpenID consumer and server library

Copyright (C) 2005 Open Source Consulting, SA. and Dan Libby

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

Reciprocal linking.  The author humbly requests that if you should use 
PHP-OpenID on your website to provide an OpenID enabled service that you 
place a link to the author's website ( http://videntity.org ) somewhere 
that your users can discover it.  You are however under no obligation to 
do so.  

More info about PHP OpenID:
openid at videntity.org
http://videntity.org/openid/

More info about OpenID:
http://www.openid.net

*****/


class HTTPClient {
    // Object used by Consumer to send http messages

    function get( $url) {
        // -->(final_url, data)
        // Fetch the content of url, following redirects, and return the
        // final url and page data as a tuple.  Return None on failure.

        trigger_error( 'unimplemented', E_USER_WARNING );
    }

    function post( $url, $body) {
        // -->(final_url, data)
        // Post the body string argument to url.
        // Reutrn the resulting final url and page data as a
        // tuple. Return None on failure.

        trigger_error( 'unimplemented', E_USER_WARNING );
    }
    
    // static
    function getHTTPClient() {

        // try to import find curl_init, which will let us use ParanoidHTTPClient
        if( function_exists( 'curl_init' ) ) {
            return new ParanoidHTTPClient();
        }
    
        return new SimpleHTTPClient();
    }
    
};



class SimpleHTTPClient extends HTTPClient {

    // var $user_agent = "Mozilla/4.0 (compatible; MSIE 5.5; Windows 98)";
    var $user_agent = "PHP-OpenID SimpleHTTPClient";
    var $ALLOWED_TIME = 20;   // seconds

    function _findRedirect( $headers) {
        foreach( $headers as $line ) {
            $loc = 'Location: ';
            if( substr( $line, 0, strlen($loc) ) == $loc ) {
                return trim( substr( $line, strlen($loc)-1 ) );
            }
        }
        return null;
    }


    function get( $url) {
    
        do {
            $stop = time() + $this->ALLOWED_TIME;
            $off = $this->ALLOWED_TIME;
        
            $parts = parse_url( $url );
            $scheme = isset( $parts['scheme'] ) ? $parts['scheme'] : null;
            $host = isset( $parts['host'] ) ? $parts['host'] : null;
            $port = isset( $parts['port'] ) ? $parts['port'] : ( $scheme == 'https' ? 443 : 80 );
            $path = isset( $parts['path'] ) ? $parts['path'] : null;
            $query = isset( $parts['query'] ) ? $parts['query'] : null;

            $uri = $path . ( $query ? '?' . $query : '' );
            
            // FIXME: perform some error checking on this URL.
            // See request at http://lists.danga.com/pipermail/yadis/2005-September/001401.html
            // Also, paranoidHttpClient should have a _checkURL method, so may
            // want to use same mechanism here.
        
            if( !in_array( $scheme, array( 'http', 'https' ) ) || !$host || !$port || !$uri ) {
                return null;
            }
            if( $scheme == 'https' ) {
                $host = 'ssl://' . $host;
            }
    
            $user_agent = $this->user_agent;
        	$headers = 
                "GET $path HTTP/1.0\r\n" .
                "User-Agent: $user_agent\r\n" .
                "Host: $host:$port\r\n" .
                "Port: $port\r\n" .
                "Cache-Control: no-cache\r\n" .
                "\r\n";
            
        	$fp = @fsockopen($host, $port, $errno, $errstr);
        	if (!$fp) {
        		return false;
        	}
    
        	fputs($fp, $headers);
        	
        	$data = '';
        	while (!feof($fp)) {
        		$data.= fgets($fp, 1024);
            }
                
        	fclose($fp);

            // Split response into header and body sections
            list($response_headers, $response_body) = explode("\r\n\r\n", $data, 2);
            $response_header_lines = explode("\r\n", $response_headers);

            $redir = false;
            if( strstr( $response_header_lines[0], '301') || strstr( $response_header_lines[0], '302') ) {
                $url = $this->_findRedirect($response_header_lines);
                $redir = true;
            }

            $off = $stop - time();
            
        } while( $redir && $off > 0 );
    	
    	return array( $url, $response_body );
    }
    
    // Simple function to post http data.
    // notes: 
    //   - handles both http and https
    //   - does not follow redirects
    function post($url, $body) {
    
    	$content_length = $this->strlen_bytes($body);
        $accept = '*/*';

        $parts = parse_url( $url );
        $scheme = isset( $parts['scheme'] ) ? $parts['scheme'] : null;
        $host = isset( $parts['host'] ) ? $parts['host'] : null;
        $port = isset( $parts['port'] ) ? $parts['port'] : ( $scheme == 'https' ? 443 : 80 );
    
        if( !in_array( $scheme, array( 'http', 'https' ) ) || !$host || !$port ) {
            return null;
        }
        if( $scheme == 'https' ) {
            $host = 'ssl://' . $host;
        }

        $user_agent = $this->user_agent;
    	$headers = 
            "POST $url HTTP/1.0\r\n" .
            "Accept: $accept\r\n" .
            "Content-Type: application/x-www-form-urlencoded\r\n" .
            "User-Agent: $user_agent\r\n" .
            "Host: $host:$port\r\n" .
            "Cache-Control: no-cache\r\n" .
            "Content-Length: $content_length\r\n" .
            "\r\n";
        
    	$fp = fsockopen($host, $port, $errno, $errstr);
    	if (!$fp) {
    		return false;
    	}
    
    	fputs($fp, $headers);
    	fputs($fp, $body);
    	
    	$data = '';
    	while (!feof($fp)) {
    		$data.= fgets($fp, 1024);
        }
            
    	fclose($fp);
        
        // Split response into header and body sections
        list($response_headers, $response_body) = explode("\r\n\r\n", $data, 2);
        $response_header_lines = explode("\r\n", $response_headers);
    	
    	return array( $url, $response_body );
    }    

    // static
    function strlen_bytes( $str ) {
        // if mb_* are in effect, there is a good chance $this->strlen_bytes is shadowed to return
        // mb_$this->strlen_bytes, which can give incorrect byte count.  so we force mb_$this->strlen_bytes to give us latin1 count.
        return function_exists('mb_strlen') ? mb_strlen($str, 'latin1') : strlen($str);
    }

};
    

class ParanoidHTTPClient extends HTTPClient {
    // A paranoid HTTPClient that uses curl for fecthing.
    // See http://php.net/curl
    var $ALLOWED_TIME = 20;   // seconds
    
    var $headers;

    function ParanoidHTTPClient() {
    }

    function _findRedirect( $headers) {
        foreach( $headers as $line ) {
            $loc = 'Location: ';
            if( substr( $line, strlen($loc) ) == $loc ) {
                return trim( substr( $line, strlen($loc)-1 ) );
            }
        }
        return null;
    }


    function _checkURL( $url) {
        // TODO: make sure url is welformed and route-able
        //       ie. the Paranoid part.
        return true;
    }
    

    function get( $url) {
    
        $retval = null;
        
        $c = curl_init( $url );
        
        if( $c ) {
            // CURLOPT_NOSIGNAL was added in php 5.
            if( defined( 'CURLOPT_NOSIGNAL' ) ) {
                curl_setopt( $c, CURLOPT_NOSIGNAL, true);
            }

            curl_setopt( $c, CURLOPT_RETURNTRANSFER, true);
            curl_setopt( $c, CURLOPT_HEADER, true);

            $stop = time() + $this->ALLOWED_TIME;
            $off = $this->ALLOWED_TIME;
            
            while( $off > 0 ) {
                
                if( !$this->_checkURL($url) ) {
                    break;
                }
                
                curl_setopt( $c, CURLOPT_URL, $url);
                curl_setopt( $c, CURLOPT_TIMEOUT, $off );

                $response_full = curl_exec( $c );
                if( !$response_full ) {
                    break;
                }
                // Split response into header and body sections
                list($response_headers, $response_body) = explode("\r\n\r\n", $response_full, 2);
                $response_header_lines = explode("\r\n", $response_headers);

                $code = curl_getinfo( $c, CURLINFO_HTTP_CODE );
                if( in_array( $code, array(301, 302) ) ) {
                    $url = $this->_findRedirect($response_header_lines);
                }
                else {
                    $retval = array( $url, $response_body );
                    break;
                }

                $off = $stop - time();
            }
            
            curl_close( $c );

        }
        return $retval;
    }

    function post( $url, $body) {
        $retval = null;
    
        if( !$this->_checkURL($url) ) {
            return null;
        }

        $c = curl_init( $url );
        
        if( $c ) {
            // CURLOPT_NOSIGNAL was added in php 5.
            if( defined( 'CURLOPT_NOSIGNAL' ) ) {
                curl_setopt( $c, CURLOPT_NOSIGNAL, true);
            }
            curl_setopt( $c, CURLOPT_POST, true);
            curl_setopt( $c, CURLOPT_POSTFIELDS, $body);
            curl_setopt( $c, CURLOPT_TIMEOUT, $this->ALLOWED_TIME);
            curl_setopt( $c, CURLOPT_URL, $url);
            curl_setopt( $c, CURLOPT_RETURNTRANSFER, true);

            $data = curl_exec( $c );
            
            curl_close( $c );
            
            if( $data ) {
                $retval = array( $url, $data );
            }
        }
        return $retval;
    }
            
    
    // static        
    function startsWith( $str, $sub ) {
       return ( substr( $str, 0, strlen( $sub ) ) == $sub );
    }
};

function _oid_httpclient_test() {

    $url_get = 'http://www.google.com';

    $c1 = new SimpleHttpClient();
    $response = $c1->get( $url_get );
    if( $response ) {
        list( $url, $data ) = $response;
        echo $data ;
    }
    else {
        echo "test 1 failed";
    }

}

if( strstr( $_SERVER['REQUEST_URI'], 'httpclient.php' ) ) {
    _oid_httpclient_test();
}
            
            
?>




More information about the geeklog-cvs mailing list