3 * StatusNet - the distributed open-source microblogging tool
4 * Copyright (C) 2008, 2009, StatusNet, Inc.
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU Affero General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU Affero General Public License for more details.
16 * You should have received a copy of the GNU Affero General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
20 if (!defined('STATUSNET') && !defined('LACONICA')) { exit(1); }
22 require_once(INSTALLDIR.'/plugins/OpenID/User_openid.php');
24 require_once('Auth/OpenID.php');
25 require_once('Auth/OpenID/Consumer.php');
26 require_once('Auth/OpenID/Server.php');
27 require_once('Auth/OpenID/SReg.php');
28 require_once('Auth/OpenID/MySQLStore.php');
30 # About one year cookie expiry
32 define('OPENID_COOKIE_EXPIRY', round(365.25 * 24 * 60 * 60));
33 define('OPENID_COOKIE_KEY', 'lastusedopenid');
39 # Can't be called statically
41 $conn = $user->getDatabaseConnection();
42 $store = new Auth_OpenID_MySQLStore($conn);
47 function oid_consumer()
50 $consumer = new Auth_OpenID_Consumer($store);
57 $server = new Auth_OpenID_Server($store, common_local_url('openidserver'));
61 function oid_clear_last()
66 function oid_set_last($openid_url)
68 common_set_cookie(OPENID_COOKIE_KEY,
70 time() + OPENID_COOKIE_EXPIRY);
73 function oid_get_last()
75 if (empty($_COOKIE[OPENID_COOKIE_KEY])) {
78 $openid_url = $_COOKIE[OPENID_COOKIE_KEY];
79 if ($openid_url && strlen($openid_url) > 0) {
86 function oid_link_user($id, $canonical, $display)
89 $oid = new User_openid();
91 $oid->canonical = $canonical;
92 $oid->display = $display;
93 $oid->created = DB_DataObject_Cast::dateTime();
95 if (!$oid->insert()) {
96 $err = PEAR::getStaticProperty('DB_DataObject','lastError');
103 function oid_get_user($openid_url)
106 $oid = User_openid::staticGet('canonical', $openid_url);
108 $user = User::staticGet('id', $oid->user_id);
113 function oid_check_immediate($openid_url, $backto=null)
116 $action = $_REQUEST['action'];
117 $args = common_copy_args($_GET);
118 unset($args['action']);
119 $backto = common_local_url($action, $args);
122 common_ensure_session();
124 $_SESSION['openid_immediate_backto'] = $backto;
126 oid_authenticate($openid_url,
131 function oid_authenticate($openid_url, $returnto, $immediate=false)
134 $consumer = oid_consumer();
137 common_server_error(_m('Cannot instantiate OpenID consumer object.'));
141 common_ensure_session();
143 $auth_request = $consumer->begin($openid_url);
145 // Handle failure status return values.
146 if (!$auth_request) {
147 common_log(LOG_ERR, __METHOD__ . ": mystery fail contacting $openid_url");
148 return _m('Not a valid OpenID.');
149 } else if (Auth_OpenID::isFailure($auth_request)) {
150 common_log(LOG_ERR, __METHOD__ . ": OpenID fail to $openid_url: $auth_request->message");
151 return sprintf(_m('OpenID failure: %s'), $auth_request->message);
154 $sreg_request = Auth_OpenID_SRegRequest::build(// Required
166 $auth_request->addExtension($sreg_request);
169 $requiredTeam = common_config('openid', 'required_team');
171 // LaunchPad OpenID extension
172 $team_request = new Auth_OpenID_TeamsRequest(array($requiredTeam));
174 $auth_request->addExtension($team_request);
178 $trust_root = common_root_url(true);
179 $process_url = common_local_url($returnto);
181 if ($auth_request->shouldSendRedirect()) {
182 $redirect_url = $auth_request->redirectURL($trust_root,
185 if (!$redirect_url) {
186 } else if (Auth_OpenID::isFailure($redirect_url)) {
187 return sprintf(_m('Could not redirect to server: %s'), $redirect_url->message);
189 common_redirect($redirect_url, 303);
192 // Generate form markup and render it.
193 $form_id = 'openid_message';
194 $form_html = $auth_request->formMarkup($trust_root, $process_url,
195 $immediate, array('id' => $form_id));
197 # XXX: This is cheap, but things choke if we don't escape ampersands
198 # in the HTML attributes
200 $form_html = preg_replace('/&/', '&', $form_html);
202 // Display an error if the form markup couldn't be generated;
203 // otherwise, render the HTML.
204 if (Auth_OpenID::isFailure($form_html)) {
205 common_server_error(sprintf(_m('Could not create OpenID form: %s'), $form_html->message));
207 $action = new AutosubmitAction(); // see below
208 $action->form_html = $form_html;
209 $action->form_id = $form_id;
210 $action->prepare(array('action' => 'autosubmit'));
211 $action->handle(array('action' => 'autosubmit'));
216 # Half-assed attempt at a module-private function
218 function _oid_print_instructions()
220 common_element('div', 'instructions',
221 _m('This form should automatically submit itself. '.
222 'If not, click the submit button to go to your '.
223 'OpenID provider.'));
227 * Update a user from sreg parameters
229 * @param array $sreg fields from OpenID sreg response
232 function oid_update_user($user, $sreg)
234 $profile = $user->getProfile();
236 $orig_profile = clone($profile);
238 if (!empty($sreg['fullname']) && strlen($sreg['fullname']) <= 255) {
239 $profile->fullname = $sreg['fullname'];
242 if (!empty($sreg['country'])) {
243 if ($sreg['postcode']) {
244 # XXX: use postcode to get city and region
245 # XXX: also, store postcode somewhere -- it's valuable!
246 $profile->location = $sreg['postcode'] . ', ' . $sreg['country'];
248 $profile->location = $sreg['country'];
252 # XXX save language if it's passed
253 # XXX save timezone if it's passed
255 if (!$profile->update($orig_profile)) {
256 common_server_error(_m('Error saving the profile.'));
260 $orig_user = clone($user);
262 if (!empty($sreg['email']) && Validate::email($sreg['email'], common_config('email', 'check_domain'))) {
263 $user->email = $sreg['email'];
266 if (!$user->update($orig_user)) {
267 common_server_error(_m('Error saving the user.'));
274 function oid_assert_allowed($url)
276 $blacklist = common_config('openid', 'blacklist');
277 $whitelist = common_config('openid', 'whitelist');
279 if (empty($blacklist)) {
280 $blacklist = array();
283 if (empty($whitelist)) {
284 $whitelist = array();
287 foreach ($blacklist as $pattern) {
288 if (preg_match("/$pattern/", $url)) {
289 common_log(LOG_INFO, "Matched OpenID blacklist pattern {$pattern} with {$url}");
290 foreach ($whitelist as $exception) {
291 if (preg_match("/$exception/", $url)) {
292 common_log(LOG_INFO, "Matched OpenID whitelist pattern {$exception} with {$url}");
296 throw new ClientException(_m("Unauthorized URL used for OpenID login."), 403);
304 * Check the teams available in the given OpenID response
305 * Using Launchpad's OpenID teams extension
307 * @return boolean whether this user is acceptable
309 function oid_check_teams($response)
311 $requiredTeam = common_config('openid', 'required_team');
313 $team_resp = new Auth_OpenID_TeamsResponse($response);
315 $teams = $team_resp->getTeams();
320 $match = in_array($requiredTeam, $teams);
321 $is = $match ? 'is' : 'is not';
322 common_log(LOG_DEBUG, "Remote user $is in required team $requiredTeam: [" . implode(', ', $teams) . "]");
330 class AutosubmitAction extends Action
332 var $form_html = null;
335 function handle($args)
337 parent::handle($args);
343 return _m('OpenID Login Submission');
346 function showContent()
348 $this->raw('<p style="margin: 20px 80px">');
349 // @fixme this would be better using standard CSS class, but the present theme's a bit scary.
350 $this->element('img', array('src' => Theme::path('images/icons/icon_processing.gif', 'base'),
351 // for some reason the base CSS sets <img>s as block display?!
352 'style' => 'display: inline'));
353 $this->text(_m('Requesting authorization from your login provider...'));
355 $this->raw('<p style="margin-top: 60px; font-style: italic">');
356 $this->text(_m('If you are not redirected to your login provider in a few seconds, try pushing the button below.'));
358 $this->raw($this->form_html);
361 function showScripts()
363 parent::showScripts();
364 $this->element('script', null,
365 'document.getElementById(\'' . $this->form_id . '\').submit();');