PageRenderTime 51ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 0ms

/branches/RunPolitics_576/system/application/libraries/SimpleOpenID.php

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