]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/OpenID/openid.php
Merge branch '0.9.x' of git://gitorious.org/statusnet/mainline into 0.9.x
[quix0rs-gnu-social.git] / plugins / OpenID / openid.php
1 <?php
2 /*
3  * StatusNet - the distributed open-source microblogging tool
4  * Copyright (C) 2008, 2009, StatusNet, Inc.
5  *
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.
10  *
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.
15  *
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/>.
18  */
19
20 if (!defined('STATUSNET') && !defined('LACONICA')) { exit(1); }
21
22 require_once(INSTALLDIR.'/plugins/OpenID/User_openid.php');
23
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');
29
30 # About one year cookie expiry
31
32 define('OPENID_COOKIE_EXPIRY', round(365.25 * 24 * 60 * 60));
33 define('OPENID_COOKIE_KEY', 'lastusedopenid');
34
35 function oid_store()
36 {
37     static $store = null;
38     if (!$store) {
39         # Cannot be called statically
40         $user = new User();
41         $conn = $user->getDatabaseConnection();
42         $store = new Auth_OpenID_MySQLStore($conn);
43     }
44     return $store;
45 }
46
47 function oid_consumer()
48 {
49     $store = oid_store();
50     $consumer = new Auth_OpenID_Consumer($store);
51     return $consumer;
52 }
53
54 function oid_server()
55 {
56     $store = oid_store();
57     $server = new Auth_OpenID_Server($store, common_local_url('openidserver'));
58     return $server;
59 }
60
61 function oid_clear_last()
62 {
63     oid_set_last('');
64 }
65
66 function oid_set_last($openid_url)
67 {
68     common_set_cookie(OPENID_COOKIE_KEY,
69                      $openid_url,
70                      time() + OPENID_COOKIE_EXPIRY);
71 }
72
73 function oid_get_last()
74 {
75     if (empty($_COOKIE[OPENID_COOKIE_KEY])) {
76         return null;
77     }
78     $openid_url = $_COOKIE[OPENID_COOKIE_KEY];
79     if ($openid_url && strlen($openid_url) > 0) {
80         return $openid_url;
81     } else {
82         return null;
83     }
84 }
85
86 function oid_link_user($id, $canonical, $display)
87 {
88
89     $oid = new User_openid();
90     $oid->user_id = $id;
91     $oid->canonical = $canonical;
92     $oid->display = $display;
93     $oid->created = DB_DataObject_Cast::dateTime();
94
95     if (!$oid->insert()) {
96         $err = PEAR::getStaticProperty('DB_DataObject','lastError');
97         common_debug('DB error ' . $err->code . ': ' . $err->message, __FILE__);
98         return false;
99     }
100
101     return true;
102 }
103
104 function oid_get_user($openid_url)
105 {
106     $user = null;
107     $oid = User_openid::staticGet('canonical', $openid_url);
108     if ($oid) {
109         $user = User::staticGet('id', $oid->user_id);
110     }
111     return $user;
112 }
113
114 function oid_check_immediate($openid_url, $backto=null)
115 {
116     if (!$backto) {
117         $action = $_REQUEST['action'];
118         $args = common_copy_args($_GET);
119         unset($args['action']);
120         $backto = common_local_url($action, $args);
121     }
122     common_debug('going back to "' . $backto . '"', __FILE__);
123
124     common_ensure_session();
125
126     $_SESSION['openid_immediate_backto'] = $backto;
127     common_debug('passed-in variable is "' . $backto . '"', __FILE__);
128     common_debug('session variable is "' . $_SESSION['openid_immediate_backto'] . '"', __FILE__);
129
130     oid_authenticate($openid_url,
131                      'finishimmediate',
132                      true);
133 }
134
135 function oid_authenticate($openid_url, $returnto, $immediate=false)
136 {
137
138     $consumer = oid_consumer();
139
140     if (!$consumer) {
141         common_server_error(_('Cannot instantiate OpenID consumer object.'));
142         return false;
143     }
144
145     common_ensure_session();
146
147     $auth_request = $consumer->begin($openid_url);
148
149     // Handle failure status return values.
150     if (!$auth_request) {
151         return _('Not a valid OpenID.');
152     } else if (Auth_OpenID::isFailure($auth_request)) {
153         return sprintf(_('OpenID failure: %s'), $auth_request->message);
154     }
155
156     $sreg_request = Auth_OpenID_SRegRequest::build(// Required
157                                                    array(),
158                                                    // Optional
159                                                    array('nickname',
160                                                          'email',
161                                                          'fullname',
162                                                          'language',
163                                                          'timezone',
164                                                          'postcode',
165                                                          'country'));
166
167     if ($sreg_request) {
168         $auth_request->addExtension($sreg_request);
169     }
170
171     $trust_root = common_root_url(true);
172     $process_url = common_local_url($returnto);
173
174     if ($auth_request->shouldSendRedirect()) {
175         $redirect_url = $auth_request->redirectURL($trust_root,
176                                                    $process_url,
177                                                    $immediate);
178         if (!$redirect_url) {
179         } else if (Auth_OpenID::isFailure($redirect_url)) {
180             return sprintf(_('Could not redirect to server: %s'), $redirect_url->message);
181         } else {
182             common_redirect($redirect_url, 303);
183         }
184     } else {
185         // Generate form markup and render it.
186         $form_id = 'openid_message';
187         $form_html = $auth_request->formMarkup($trust_root, $process_url,
188                                                $immediate, array('id' => $form_id));
189
190         # XXX: This is cheap, but things choke if we don't escape ampersands
191         # in the HTML attributes
192
193         $form_html = preg_replace('/&/', '&amp;', $form_html);
194
195         // Display an error if the form markup could not be generated;
196         // otherwise, render the HTML.
197         if (Auth_OpenID::isFailure($form_html)) {
198             common_server_error(sprintf(_('Could not create OpenID form: %s'), $form_html->message));
199         } else {
200             $action = new AutosubmitAction(); // see below
201             $action->form_html = $form_html;
202             $action->form_id = $form_id;
203             $action->prepare(array('action' => 'autosubmit'));
204             $action->handle(array('action' => 'autosubmit'));
205         }
206     }
207 }
208
209 # Half-assed attempt at a module-private function
210
211 function _oid_print_instructions()
212 {
213     common_element('div', 'instructions',
214                    _('This form should automatically submit itself. '.
215                       'If not, click the submit button to go to your '.
216                       'OpenID provider.'));
217 }
218
219 # update a user from sreg parameters
220
221 function oid_update_user(&$user, &$sreg)
222 {
223
224     $profile = $user->getProfile();
225
226     $orig_profile = clone($profile);
227
228     if ($sreg['fullname'] && strlen($sreg['fullname']) <= 255) {
229         $profile->fullname = $sreg['fullname'];
230     }
231
232     if ($sreg['country']) {
233         if ($sreg['postcode']) {
234             # XXX: use postcode to get city and region
235             # XXX: also, store postcode somewhere -- it's valuable!
236             $profile->location = $sreg['postcode'] . ', ' . $sreg['country'];
237         } else {
238             $profile->location = $sreg['country'];
239         }
240     }
241
242     # XXX save language if it's passed
243     # XXX save timezone if it's passed
244
245     if (!$profile->update($orig_profile)) {
246         common_server_error(_('Error saving the profile.'));
247         return false;
248     }
249
250     $orig_user = clone($user);
251
252     if ($sreg['email'] && Validate::email($sreg['email'], common_config('email', 'check_domain'))) {
253         $user->email = $sreg['email'];
254     }
255
256     if (!$user->update($orig_user)) {
257         common_server_error(_('Error saving the user.'));
258         return false;
259     }
260
261     return true;
262 }
263
264 class AutosubmitAction extends Action
265 {
266     var $form_html = null;
267     var $form_id = null;
268
269     function handle($args)
270     {
271         parent::handle($args);
272         $this->showPage();
273     }
274
275     function title()
276     {
277         return _('OpenID Auto-Submit');
278     }
279
280     function showContent()
281     {
282         $this->raw($this->form_html);
283         $this->element('script', null,
284                        '$(document).ready(function() { ' .
285                        '    $(\'#'. $this->form_id .'\').submit(); '.
286                        '});');
287     }
288 }