public
Description: Git mirror of the CMS Made Simple 2.0 rewrite
Homepage: http://cmsmadesimple.org
Clone URL: git://github.com/tedkulp/cmsmadesimple-2-0.git
cmsmadesimple-2-0 / lib / classes / class.cms_openid.php
100644 278 lines (244 sloc) 7.478 kb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
<?php // -*- mode:php; tab-width:4; indent-tabs-mode:t; c-basic-offset:4; -*-
#CMS - CMS Made Simple
#(c)2004-2008 by Ted Kulp (ted@cmsmadesimple.org)
#This project's homepage is: http://cmsmadesimple.org
#
#This program is free software; you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation; either version 2 of the License, or
#(at your option) any later version.
#
#This program 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 General Public License for more details.
#You should have received a copy of the GNU General Public License
#along with this program; if not, write to the Free Software
#Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
#$Id$
 
/**
* Simple implementation of the OpenID protocol for logging into
* the CMSMS system. It only handles the simple "dumb mode" of
* OpenID.
*
* @since 2.0
* @author Ted Kulp
**/
class CmsOpenid extends CmsObject
{
  public $server = '';
  public $delegate = '';
  public $mode = 'checkid_setup';
 
  function __construct()
  {
    parent::__construct();
  }
  
  /**
   * Check to see if we can support doing the backend call
   * to the server after the login procedure.
   *
   * @return boolean
   * @author Ted Kulp
   **/
  public static function is_enabled()
  {
    return ini_get('allow_url_fopen');
  }
  
  /**
   * Generate a checksum to use for matching the user and the
   * login request.
   *
   * @return string The checksum string
   * @author Ted Kulp
   **/
  public static function generate_checksum()
  {
    return sha1(time() . CMS_VERSION . ROOT_DIR);
  }
  
  /**
   * Take a given OpenId identifier and clean it up so that is
   * follows a generic format. This would mean no
   * protocol at the beginning and no slash at the end
   *
   * @param string The given OpenId identifier
   * @return string The cleaned up OpenId identifier
   * @author Ted Kulp
   **/
  public static function cleanup_openid($url)
  {
    $u = parse_url(strtolower(trim($url)));
 
    #Handle no path given
    if (!isset($u['path']) || $u['path'] == '/')
    {
      $u['path'] = '';      
    }
 
    #parse_url sometimes returns a straight domain name
    #with no path or scheme as a path. That obviously should
    #be a host.
    if (!isset($u['host']) && $u['path'] != '')
    {
      $u['host'] = $u['path'];
      $u['path'] = '';
    }
 
    #If the path ends with a /, remove it.
    if(substr($u['path'],-1,1) == '/')
    {
      $u['path'] = substr($u['path'], 0, strlen($u['path'])-1);
    }
    
    #Return the straightened-out openid
    if (isset($u['query']))
    {
      return $u['host'] . $u['path'] . '?' . $u['query'];
    }
    else
    {
      return $u['host'] . $u['path'];
    }
  }
  
  /**
   * Create a URL from the given OpenId identifier
   * for use in the initial lookup of the provider.
   *
   * @param string The OpenId identifier
   * @return string The url of the given OpenId identifier
   * @author Ted Kulp
   **/
  public static function create_url($url)
  {
    return 'http://' . self::cleanup_openid($url);
  }
  
  /**
   * Lookup the provider (and delegate, if set) from the given url.
   * These are then set internally.
   *
   * @param string The url to lookup the provider of
   * @return boolean Wether or not the provider lookup was successful
   * @author Ted Kulp
   **/
  public function find_server($url)
  {
    $file = fopen($url, 'r');
    if (!$file)
    {
      return false;
    }
    
    $this->delegate = $url;
    
    while (!feof($file))
    {
      $line = fgets($file, 1024);
      if (preg_match("/<link rel=['\"]openid\.delegate['\"] href=['\"](.*?)['\"]/", $line, $out))
      {
        $this->delegate = $out[1];
      }
      if (preg_match("/<link rel=['\"]openid\.server['\"] href=['\"](.*?)['\"]/", $line, $out))
      {
        $this->server = $out[1];
      }
    }
    
    if ($this->server != '')
      return true;
    
    return false;
  }
  
  /**
   * Create the return_url and redirect to the set provider for authentication.
   *
   * @param string The url to return to after the authentication is complete
   * @param string The checksum to use. If none is given, one is created.
   * @return void
   * @author Ted Kulp
   **/
  public function do_authentication($return_url, $checksum = '')
  {
    if ($this->server == '' || $this->delegate == '' || $return_url == '')
      return false;
    
    if ($checksum == '')
      $checksum = self::generate_checksum();
    
    $return_url .= strpos('?', $return_url) !== FALSE ? '&' : '?';
    $return_url .= "checksum={$checksum}&endpoint=" . urlencode($this->server);
    $return_url = urlencode($return_url);
    $trust_root = urlencode(CmsConfig::get('root_url'));
    $cleaned_delegate = urlencode($this->delegate);
    CmsResponse::redirect("{$this->server}?openid.mode={$this->mode}&openid.identity={$cleaned_delegate}&" . "openid.return_to={$return_url}&openid.trust_root={$trust_root}");
  }
  
  /**
   * Does the final authentication check. This posts back to the provider the details
   * given to check that the provider did indeed approve the authentication request.
   *
   * @param array The array of parameters to send back to the provider for it's
   * checking process
   * @return boolean Whether or not the authentication process was successful
   * @author Ted Kulp
   **/
  public function check_authentication($params)
  {
    if ($params['openid_mode'] == 'id_res' || $params['openid.mode'] == 'id_res')
    {
      $params_we_need = array();
 
      #Gather up all the openid* parameters to send them back
      foreach ($params as $k=>$v)
      {
        if (starts_with($k, 'openid') && !ends_with($k, 'mode'))
        {
          $k = str_replace('openid_', 'openid.', $k);
          $params_we_need[$k] = $v;
        }
      }
      
      $params_we_need['openid.mode'] = 'check_authentication';
 
      return self::do_post_request($params['endpoint'], $params_we_need);
    }
    
    return false;
  }
  
  /**
   * Posts behind the scenes to another page.
   * Taken from: http://netevil.org/blog/2006/nov/http-post-from-php-without-curl
   *
   * @param string The url to post to
   * @param string The data to send in the post's payload
   * @param string The method to use (POST or GET -- POST is default)
   * @return string Response from the posted page
   * @author Wez Furlong, modified by Ted Kulp
   **/
  public static function do_post_request($url, $data, $method = 'POST')
  {  
    $uri = parse_url($url);
 
    $port = isset($uri['port']) ? $uri['port'] : 80;
    $host = $uri['host'] . ($port != 80 ? ':'. $port : '');
    $fp = @fsockopen($uri['host'], $port, $errno, $errstr, 15);
    if (!$fp)
    {
      return 'Error connecting to the openid server.';
    }
 
    $data = http_build_query($data);
    
    $headers = "Content-type: application/x-www-form-urlencoded; charset=utf-8\r\n" .
      "Host: $host\r\n" .
      "User-Agent: CMS Made Simple (http://cmsmadesimple.org)\r\n" .
      'Content-Length: '. strlen($data);
    
    $path = isset($uri['path']) ? $uri['path'] : '/';
    if (isset($uri['query']))
    {
      $path .= '?'. $uri['query'];
    }
    
    $request = $method .' '. $path ." HTTP/1.0\r\n";
    $request .= $headers;
    $request .= "\r\n\r\n";
    $request .= $data ."\r\n";
    
    fwrite($fp, $request);
 
    $response = '';
    while (!feof($fp) && $chunk = fread($fp, 1024))
    {
      $response .= $chunk;
    }
    fclose($fp);
    
    if (starts_with($response, 'HTTP/1.1 200 OK'))
    {
      if (strpos($response, 'is_valid:true') !== FALSE)
      {
        return true;
      }
    }
    
    return false;
  }
}
 
# vim:ts=4 sw=4 noet
?>