Advertisement
Guest User

Modified Simple OpenID PHP Class

a guest
May 20th, 2010
2,314
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 13.13 KB | None | 0 0
  1. <?
  2. /*
  3.     FREE TO USE
  4.         Under License: GPLv3
  5.     Simple OpenID PHP Class
  6.    
  7.     Some modifications by Eddie Roosenmaallen, eddie@roosenmaallen.com
  8.    
  9. -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
  10.  
  11. This Class was written to make easy for you to integrate OpenID on your website.
  12. This is just a client, which checks for user's identity. This Class Requires CURL Module.
  13. It should be easy to use some other HTTP Request Method, but remember, often OpenID servers
  14. are using SSL.
  15. We need to be able to perform SSL Verification on the background to check for valid signature.
  16.  
  17. HOW TO USE THIS CLASS:
  18.   STEP 1)
  19.     $openid = new SimpleOpenID;
  20.     :: SET IDENTITY ::
  21.         $openid->SetIdentity($_POST['openid_url']);
  22.     :: SET RETURN URL ::
  23.         $openid->SetApprovedURL('http://www.yoursite.com/return.php'); // Script which handles a response from OpenID Server
  24.     :: SET TRUST ROOT ::
  25.         $openid->SetTrustRoot('http://www.yoursite.com/');
  26.     :: FETCH SERVER URL FROM IDENTITY PAGE ::  [Note: It is recomended to cache this (Session, Cookie, Database)]
  27.         $openid->GetOpenIDServer(); // Returns false if server is not found
  28.     :: REDIRECT USER TO OPEN ID SERVER FOR APPROVAL ::
  29.    
  30.     :: (OPTIONAL) SET OPENID SERVER ::
  31.         $openid->SetOpenIDServer($server_url); // If you have cached previously this, you don't have to call GetOpenIDServer and set value this directly
  32.        
  33.     STEP 2)
  34.     Once user gets returned we must validate signature
  35.     :: VALIDATE REQUEST ::
  36.         true|false = $openid->ValidateWithServer();
  37.        
  38.     ERRORS:
  39.         array = $openid->GetError();    // Get latest Error code
  40.    
  41.     FIELDS:
  42.         OpenID allowes you to retreive a profile. To set what fields you'd like to get use (accepts either string or array):
  43.         $openid->SetRequiredFields(array('email','fullname','dob','gender','postcode','country','language','timezone'));
  44.          or
  45.         $openid->SetOptionalFields('postcode');
  46.        
  47. IMPORTANT TIPS:
  48. OPENID as is now, is not trust system. It is a great single-sign on method. If you want to
  49. store information about OpenID in your database for later use, make sure you handle url identities
  50. properly.
  51.   For example:
  52.     https://steve.myopenid.com/
  53.     https://steve.myopenid.com
  54.     http://steve.myopenid.com/
  55.     http://steve.myopenid.com
  56.     ... are representing one single user. Some OpenIDs can be in format openidserver.com/users/user/ - keep this in mind when storing identities
  57.  
  58.     To help you store an OpenID in your DB, you can use function:
  59.         $openid_db_safe = $openid->OpenID_Standarize($upenid);
  60.     This may not be comatible with current specs, but it works in current enviroment. Use this function to get openid
  61.     in one format like steve.myopenid.com (without trailing slashes and http/https).
  62.     Use output to insert Identity to database. Don't use this for validation - it may fail.
  63.  
  64. */
  65.  
  66. class SimpleOpenID{
  67.     var $openid_url_identity;
  68.     var $google_openid = 0;
  69.     var $openid_user = '';
  70.     var $URLs = array();
  71.     var $error = array();
  72.     var $fields = array(
  73.         'required'   => array(),
  74.         'optional'   => array(),
  75.     );
  76.    
  77.     function SetOpenIDUser($s){
  78.         $this->openid_user = $s;
  79.     }
  80.    
  81.     function GetOpenIDUser(){
  82.         //var_dump($_GET);
  83.         if (!empty($_GET['openid_ext1_value_firstname']) && !empty($_GET['openid_ext1_type_lastname'])){
  84.             return urldecode($_GET['openid_ext1_value_firstname'].' '.$_GET['openid_ext1_value_lastname']);
  85.         }else if (!empty($_GET['openid_ext1_value_email'])){
  86.             return urldecode($_GET['openid_ext1_value_email']);
  87.         }else{
  88.             $id = $this->GetIdentity();
  89.             if (preg_match('/^http[s]*:\/\/([\S]+)$/', $id, $arr)){
  90.                 if (strrpos($arr[1],'/') == strlen($arr[1])-1){
  91.                     return substr($arr[1], 0, strlen($arr[1])-1);
  92.                 }else{
  93.                     return $arr[1];
  94.                 }
  95.             }else{
  96.                 return $id;
  97.             }
  98.         }
  99.     }
  100.    
  101.     function SetGoogleOpenID(){
  102.         $this->google_openid = 1;
  103.     }
  104.    
  105.     function SimpleOpenID(){
  106.         if (!function_exists('curl_exec')) {
  107.             die('Error: Class SimpleOpenID requires curl extension to work');
  108.         }
  109.     }
  110.     function SetOpenIDServer($a){
  111.         $this->URLs['openid_server'] = $a;
  112.     }
  113.     function SetTrustRoot($a){
  114.         $this->URLs['trust_root'] = $a;
  115.     }
  116.     function SetCancelURL($a){
  117.         $this->URLs['cancel'] = $a;
  118.     }
  119.     function SetApprovedURL($a){
  120.         $this->URLs['approved'] = $a;
  121.     }
  122.     function SetRequiredFields($a){
  123.         if (is_array($a)){
  124.             $this->fields['required'] = $a;
  125.         }else{
  126.             $this->fields['required'][] = $a;
  127.         }
  128.     }
  129.     function SetOptionalFields($a){
  130.         if (is_array($a)){
  131.             $this->fields['optional'] = $a;
  132.         }else{
  133.             $this->fields['optional'][] = $a;
  134.         }
  135.     }
  136.     function SetIdentity($a){   // Set Identity URL
  137.             if ((stripos($a, 'http://') === false)
  138.                && (stripos($a, 'https://') === false)){
  139.                 $a = 'http://'.$a;
  140.             }
  141. /*
  142.             $u = parse_url(trim($a));
  143.             if (!isset($u['path'])){
  144.                 $u['path'] = '/';
  145.             }else if(substr($u['path'],-1,1) == '/'){
  146.                 $u['path'] = substr($u['path'], 0, strlen($u['path'])-1);
  147.             }
  148.             if (isset($u['query'])){ // If there is a query string, then use identity as is
  149.                 $identity = $a;
  150.             }else{
  151.                 $identity = $u['scheme'] . '://' . $u['host'] . $u['path'];
  152.             }
  153. //*/
  154.             $this->openid_url_identity = $a;
  155.     }
  156.     function GetIdentity(){     // Get Identity
  157.         return $this->openid_url_identity;
  158.     }
  159.     function GetError(){
  160.         $e = $this->error;
  161.         return array('code'=>$e[0],'description'=>$e[1]);
  162.     }
  163.  
  164.     function ErrorStore($code, $desc = null){
  165.         $errs['OPENID_NOSERVERSFOUND'] = 'Cannot find OpenID Server TAG on Identity page.';
  166.         if ($desc == null){
  167.             $desc = $errs[$code];
  168.         }
  169.         $this->error = array($code,$desc);
  170.     }
  171.  
  172.     function IsError(){
  173.         if (count($this->error) > 0){
  174.             return true;
  175.         }else{
  176.             return false;
  177.         }
  178.     }
  179.    
  180.     function splitResponse($response) {
  181.         $r = array();
  182.         $response = explode("\n", $response);
  183.         foreach($response as $line) {
  184.             $line = trim($line);
  185.             if ($line != "") {
  186.                 list($key, $value) = explode(":", $line, 2);
  187.                 $r[trim($key)] = trim($value);
  188.             }
  189.         }
  190.         return $r;
  191.     }
  192.    
  193.     function OpenID_Standarize($openid_identity = null){
  194.         if ($openid_identity === null)
  195.             $openid_identity = $this->openid_url_identity;
  196.  
  197.         $u = parse_url(strtolower(trim($openid_identity)));
  198.        
  199.         if (!isset($u['path']) || ($u['path'] == '/')) {
  200.             $u['path'] = '';
  201.         }
  202.         if(substr($u['path'],-1,1) == '/'){
  203.             $u['path'] = substr($u['path'], 0, strlen($u['path'])-1);
  204.         }
  205.         if (isset($u['query'])){ // If there is a query string, then use identity as is
  206.             return $u['host'] . $u['path'] . '?' . $u['query'];
  207.         }else{
  208.             return $u['host'] . $u['path'];
  209.         }
  210.     }
  211.    
  212.     function array2url($arr){ // converts associated array to URL Query String
  213.         if (!is_array($arr)){
  214.             return false;
  215.         }
  216.         $query = '';
  217.         foreach($arr as $key => $value){
  218.             $query .= $key . "=" . $value . "&";
  219.         }
  220.         return $query;
  221.     }
  222.     function FSOCK_Request($url, $method="GET", $params = ""){
  223.         $fp = fsockopen("ssl://www.myopenid.com", 443, $errno, $errstr, 3); // Connection timeout is 3 seconds
  224.         if (!$fp) {
  225.             $this->ErrorStore('OPENID_SOCKETERROR', $errstr);
  226.             return false;
  227.         } else {
  228.             $request = $method . " /server HTTP/1.0\r\n";
  229.             $request .= "User-Agent: Simple OpenID PHP Class (http://www.phpclasses.org/simple_openid)\r\n";
  230.             $request .= "Connection: close\r\n\r\n";
  231.             fwrite($fp, $request);
  232.             stream_set_timeout($fp, 4); // Connection response timeout is 4 seconds
  233.             $res = fread($fp, 2000);
  234.             $info = stream_get_meta_data($fp);
  235.             fclose($fp);
  236.        
  237.             if ($info['timed_out']) {
  238.                $this->ErrorStore('OPENID_SOCKETTIMEOUT');
  239.             } else {
  240.                 return $res;
  241.             }
  242.         }
  243.     }
  244.     function CURL_Request($url, $method="GET", $params = "") { // Remember, SSL MUST BE SUPPORTED
  245.             //var_dump($url);
  246.             $url = trim($url);
  247.             if (is_array($params)) $params = $this->array2url($params);
  248.             $curl = curl_init($url . ($method == "GET" && $params != "" ? "?" . $params : ""));
  249.             //var_dump($curl);
  250.             curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
  251.             curl_setopt($curl, CURLOPT_HEADER, false);
  252.             curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
  253.             curl_setopt($curl, CURLOPT_HTTPGET, ($method == "GET"));
  254.             curl_setopt($curl, CURLOPT_POST, ($method == "POST"));
  255.             if ($method == "POST") curl_setopt($curl, CURLOPT_POSTFIELDS, $params);
  256.             curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  257.             $response = curl_exec($curl);
  258.             //var_dump($curl);
  259.             if (curl_errno($curl) == 0){
  260.                 $response;
  261.             }else{
  262.                 $this->ErrorStore('OPENID_CURL', curl_error($curl));
  263.             }
  264.             return $response;
  265.     }
  266.    
  267.      function HTML2OpenIDServer($content) {
  268.        
  269.         if (preg_match('/<xrds:/',$content)){
  270.             $this->SetGoogleOpenID();
  271.             preg_match_all('/<URI>([^>]*)<\/URI>/', $content, $servers);
  272.             $ret = array($servers[1], array());
  273.         }else{
  274.             preg_match_all('/<link[^>]*rel=[\'"][openid2.provider ]*openid.server[\'"][^>]*href=[\'"]([^\'"]+)[\'"][^>]*\/?>/', $content, $matches1);
  275.             preg_match_all('/<link[^>]*href=\'"([^\'"]+)[\'"][^>]*rel=[\'"]openid.server[\'"][^>]*\/?>/', $content, $matches2);
  276.            
  277.             $servers = array_merge($matches1[1], $matches2[1]);
  278.            
  279.             preg_match_all('/<link[^>]*rel=[\'"]openid.delegate[\'"][^>]*href=[\'"]([^\'"]+)[\'"][^>]*\/?>/', $content, $matches1);
  280.            
  281.             preg_match_all('/<link[^>]*href=[\'"]([^\'"]+)[\'"][^>]*rel=[\'"]openid.delegate[\'"][^>]*\/?>/', $content, $matches2);
  282.            
  283.             $delegates = array_merge($matches1[1], $matches2[1]);
  284.            
  285.             $ret = array($servers, $delegates);
  286.         }
  287.          
  288.        
  289.         return $ret;
  290.     }
  291.    
  292.     function GetOpenIDServer(){
  293.        
  294.         $response = $this->CURL_Request($this->openid_url_identity);
  295.         list($servers, $delegates) = $this->HTML2OpenIDServer($response);
  296.         //var_dump($servers, $delegates);exit;
  297.         if (count($servers) == 0){
  298.             $this->ErrorStore('OPENID_NOSERVERSFOUND');
  299.             return false;
  300.         }
  301.         if (isset($delegates[0])
  302.           && ($delegates[0] != "")){
  303.             $this->SetIdentity($delegates[0]);
  304.         }
  305.         $this->SetOpenIDServer($servers[0]);
  306.         return $servers[0];
  307.     }
  308.    
  309.     function GetRedirectURL(){
  310.         $params = array();
  311.         $params['openid.return_to'] = urlencode($this->URLs['approved']);
  312.         $params['openid.mode'] = 'checkid_setup';
  313.         //$params['openid.identity'] = urlencode($this->openid_url_identity);
  314.         $params['openid.trust_root'] = urlencode($this->URLs['trust_root']);
  315.        
  316.         $params['openid.ns'] = urlencode('http://specs.openid.net/auth/2.0');
  317.         $params['openid.claimed_id'] = urlencode('http://specs.openid.net/auth/2.0/identifier_select');
  318.         $params['openid.identity'] = urlencode('http://specs.openid.net/auth/2.0/identifier_select');
  319.         $params['openid.realm'] = urlencode($this->URLs['trust_root']);
  320.        
  321.         $params['openid.ns.ax'] = 'http://openid.net/srv/ax/1.0';
  322.         $params['openid.ax.mode'] = 'fetch_request';
  323.         $params['openid.ax.type.email'] = 'http%3A%2F%2Faxschema.org%2Fcontact%2Femail';
  324.         $params['openid.ax.type.language'] = 'http%3A%2F%2Faxschema.org%2Fpref%2Flanguage';
  325.         $params['openid.ax.type.firstname'] = urlencode('http://axschema.org/namePerson/first');
  326.         $params['openid.ax.type.lastname'] = urlencode('http://axschema.org/namePerson/last');
  327.         $params['openid.ax.required'] = urlencode(implode(',',$this->fields['required']));
  328.         //var_dump($params);exit;
  329.         if (isset($this->fields['required'])
  330.           && (count($this->fields['required']) > 0)) {
  331.             $params['openid.sreg.required'] = urlencode(implode(',',$this->fields['required']));
  332.         }
  333.         if (isset($this->fields['optional'])
  334.           && (count($this->fields['optional']) > 0)) {
  335.             $params['openid.sreg.optional'] = urlencode(implode(',',$this->fields['optional']));
  336.         }
  337.         return $this->URLs['openid_server'] . "?". $this->array2url($params);
  338.     }
  339.    
  340.     function Redirect(){
  341.         $redirect_to = $this->GetRedirectURL();
  342.         if (headers_sent()){ // Use JavaScript to redirect if content has been previously sent (not recommended, but safe)
  343.             echo '<script language="JavaScript" type="text/javascript">window.location=\'';
  344.             echo $redirect_to;
  345.             echo '\';</script>';
  346.         }else{  // Default Header Redirect
  347.             header('Location: ' . $redirect_to);
  348.         }
  349.     }
  350.    
  351.     function ValidateWithServer(){
  352.        
  353.         $params = array(
  354.             'openid.assoc_handle' => urlencode($_GET['openid_assoc_handle']),
  355.             'openid.signed' => urlencode($_GET['openid_signed']),
  356.             'openid.sig' => urlencode($_GET['openid_sig'])
  357.         );
  358.         // Send only required parameters to confirm validity
  359.         $arr_signed = explode(",",str_replace('sreg.','sreg_',$_GET['openid_signed']));
  360.         for ($i=0; $i<count($arr_signed); $i++){
  361.             $s = str_replace('sreg_','sreg.', $arr_signed[$i]);
  362.             $c = @$_GET['openid_' . $arr_signed[$i]];
  363.             // if ($c != ""){
  364.                 $params['openid.' . $s] = urlencode($c);
  365.             // }
  366.         }
  367.         $params['openid.mode'] = "check_authentication";
  368.  
  369.         $openid_server = $this->GetOpenIDServer();
  370.        
  371.         if ($openid_server == false){
  372.             return false;
  373.         }elseif (preg_match('/[google.com|gmail.com|googlemail.com]/',$openid_server)){
  374.             return true;
  375.         }
  376.        
  377.         $response = $this->CURL_Request($openid_server,'POST',$params);
  378.         $data = $this->splitResponse($response);
  379.  
  380.         if ($data['is_valid'] == "true") {
  381.             return true;
  382.         }else{
  383.             return false;
  384.         }
  385.     }
  386. }
  387.  
  388. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement