class.openid.v3.php 10 KB

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