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')) {
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)
90 $oid = new User_openid();
92 $oid->canonical = $canonical;
93 $oid->display = $display;
94 $oid->created = common_sql_now();
96 if (!$oid->insert()) {
97 $err = &$_PEAR->getStaticProperty('DB_DataObject','lastError');
104 function oid_get_user($openid_url)
107 $oid = User_openid::getKV('canonical', $openid_url);
109 $user = User::getKV('id', $oid->user_id);
114 function oid_check_immediate($openid_url, $backto=null)
117 $action = $_REQUEST['action'];
118 $args = common_copy_args($_GET);
119 unset($args['action']);
120 $backto = common_local_url($action, $args);
123 common_ensure_session();
125 $_SESSION['openid_immediate_backto'] = $backto;
127 oid_authenticate($openid_url,
132 function oid_authenticate($openid_url, $returnto, $immediate=false)
134 if (!common_valid_http_url($openid_url)) {
135 throw new ClientException(_m('No valid URL provided for OpenID.'));
138 $consumer = oid_consumer();
141 // TRANS: OpenID plugin server error.
142 throw new ServerException(_m('Cannot instantiate OpenID consumer object.'));
145 common_ensure_session();
147 $auth_request = $consumer->begin($openid_url);
149 // Handle failure status return values.
150 if (!$auth_request) {
151 common_log(LOG_ERR, __METHOD__ . ": mystery fail contacting $openid_url");
152 // TRANS: OpenID plugin message. Given when an OpenID is not valid.
153 throw new ServerException(_m('Not a valid OpenID.'));
154 } else if (Auth_OpenID::isFailure($auth_request)) {
155 common_log(LOG_ERR, __METHOD__ . ": OpenID fail to $openid_url: $auth_request->message");
156 // TRANS: OpenID plugin server error. Given when the OpenID authentication request fails.
157 // TRANS: %s is the failure message.
158 throw new ServerException(sprintf(_m('OpenID failure: %s.'), $auth_request->message));
161 $sreg_request = Auth_OpenID_SRegRequest::build(// Required
173 $auth_request->addExtension($sreg_request);
176 $requiredTeam = common_config('openid', 'required_team');
178 // LaunchPad OpenID extension
179 $team_request = new Auth_OpenID_TeamsRequest(array($requiredTeam));
181 $auth_request->addExtension($team_request);
185 $trust_root = common_root_url(true);
186 $process_url = common_local_url($returnto);
188 // Net::OpenID::Server as used on LiveJournal appears to incorrectly
189 // reject POST requests for data submissions that OpenID 1.1 specs
190 // as GET, although 2.0 allows them:
191 // https://rt.cpan.org/Public/Bug/Display.html?id=42202
193 // Our OpenID libraries would have switched in the redirect automatically
194 // if it were detecting 1.1 compatibility mode, however the server is
195 // advertising itself as 2.0-compatible, so we got switched to the POST.
197 // Since the GET should always work anyway, we'll just take out the
198 // autosubmitter for now.
200 //if ($auth_request->shouldSendRedirect()) {
201 $redirect_url = $auth_request->redirectURL($trust_root,
204 if (Auth_OpenID::isFailure($redirect_url)) {
205 // TRANS: OpenID plugin server error. Given when the OpenID authentication request cannot be redirected.
206 // TRANS: %s is the failure message.
207 throw new ServerException(sprintf(_m('Could not redirect to server: %s.'), $redirect_url->message));
209 common_redirect($redirect_url, 303);
212 // Generate form markup and render it.
213 $form_id = 'openid_message';
214 $form_html = $auth_request->formMarkup($trust_root, $process_url,
215 $immediate, array('id' => $form_id));
217 // XXX: This is cheap, but things choke if we don't escape ampersands
218 // in the HTML attributes
220 $form_html = preg_replace('/&/', '&', $form_html);
222 // Display an error if the form markup couldn't be generated;
223 // otherwise, render the HTML.
224 if (Auth_OpenID::isFailure($form_html)) {
225 // TRANS: OpenID plugin server error if the form markup could not be generated.
226 // TRANS: %s is the failure message.
227 common_server_error(sprintf(_m('Could not create OpenID form: %s'), $form_html->message));
229 $action = new AutosubmitAction(); // see below
230 $action->form_html = $form_html;
231 $action->form_id = $form_id;
232 $action->prepare(array('action' => 'autosubmit'));
233 $action->handle(array('action' => 'autosubmit'));
239 // Half-assed attempt at a module-private function
241 function _oid_print_instructions()
243 common_element('div', 'instructions',
244 // TRANS: OpenID plugin user instructions.
245 _m('This form should automatically submit itself. '.
246 'If not, click the submit button to go to your '.
247 'OpenID provider.'));
251 * Update a user from sreg parameters
253 * @param array $sreg fields from OpenID sreg response
256 function oid_update_user($user, $sreg)
258 $profile = $user->getProfile();
260 $orig_profile = clone($profile);
262 if (!empty($sreg['fullname']) && strlen($sreg['fullname']) <= 255) {
263 $profile->fullname = $sreg['fullname'];
266 if (!empty($sreg['country'])) {
267 if ($sreg['postcode']) {
268 // XXX: use postcode to get city and region
269 // XXX: also, store postcode somewhere -- it's valuable!
270 $profile->location = $sreg['postcode'] . ', ' . $sreg['country'];
272 $profile->location = $sreg['country'];
276 // XXX save language if it's passed
277 // XXX save timezone if it's passed
279 if (!$profile->update($orig_profile)) {
280 // TRANS: OpenID plugin server error.
281 common_server_error(_m('Error saving the profile.'));
285 $orig_user = clone($user);
287 if (!empty($sreg['email']) && Validate::email($sreg['email'], common_config('email', 'check_domain'))) {
288 $user->email = $sreg['email'];
291 if (!$user->update($orig_user)) {
292 // TRANS: OpenID plugin server error.
293 common_server_error(_m('Error saving the user.'));
300 function oid_assert_allowed($url)
302 $blacklist = common_config('openid', 'blacklist');
303 $whitelist = common_config('openid', 'whitelist');
305 if (empty($blacklist)) {
306 $blacklist = array();
309 if (empty($whitelist)) {
310 $whitelist = array();
313 foreach ($blacklist as $pattern) {
314 if (preg_match("/$pattern/", $url)) {
315 common_log(LOG_INFO, "Matched OpenID blacklist pattern {$pattern} with {$url}");
316 foreach ($whitelist as $exception) {
317 if (preg_match("/$exception/", $url)) {
318 common_log(LOG_INFO, "Matched OpenID whitelist pattern {$exception} with {$url}");
322 // TRANS: OpenID plugin client exception (403).
323 throw new ClientException(_m('Unauthorized URL used for OpenID login.'), 403);
331 * Check the teams available in the given OpenID response
332 * Using Launchpad's OpenID teams extension
334 * @return boolean whether this user is acceptable
336 function oid_check_teams($response)
338 $requiredTeam = common_config('openid', 'required_team');
340 $team_resp = new Auth_OpenID_TeamsResponse($response);
342 $teams = $team_resp->getTeams();
347 $match = in_array($requiredTeam, $teams);
348 $is = $match ? 'is' : 'is not';
349 common_debug("Remote user $is in required team $requiredTeam: [" . implode(', ', $teams) . "]");
357 class AutosubmitAction extends Action
359 var $form_html = null;
362 function handle(array $args=array())
364 parent::handle($args);
371 return _m('OpenID Login Submission');
374 function showContent()
376 $this->raw('<p style="margin: 20px 80px">');
377 // @todo FIXME: This would be better using standard CSS class, but the present theme's a bit scary.
378 $this->element('img', array('src' => Theme::path('images/icons/icon_processing.gif', 'base'),
379 // for some reason the base CSS sets <img>s as block display?!
380 'style' => 'display: inline'));
381 // TRANS: OpenID plugin message used while requesting authorization user's OpenID login provider.
382 $this->text(_m('Requesting authorization from your login provider...'));
384 $this->raw('<p style="margin-top: 60px; font-style: italic">');
385 // TRANS: OpenID plugin message. User instruction while requesting authorization user's OpenID login provider.
386 $this->text(_m('If you are not redirected to your login provider in a few seconds, try pushing the button below.'));
388 $this->raw($this->form_html);
391 function showScripts()
393 parent::showScripts();
394 $this->element('script', null,
395 'document.getElementById(\'' . $this->form_id . '\').submit();');