MDL-26257 Authentication : whitespace/style fixes
[moodle.git] / auth / shibboleth / auth.php
CommitLineData
b9ddb2d5 1<?php
2/**
3 * @author Martin Dougiamas
3ea28768 4 * @author Lukas Haemmerle
b9ddb2d5 5 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
6 * @package moodle multiauth
7 *
8 * Authentication Plugin: Shibboleth Authentication
9 *
10 * Authentication using Shibboleth.
11 *
b9ddb2d5 12 * Distributed under GPL (c)Markus Hagman 2004-2006
13 *
3ea28768 14 * 10.2004 SHIBBOLETH Authentication functions v.0.1
15 * 05.2005 Various extensions and fixes by Lukas Haemmerle
16 * 10.2005 Added better error messags
17 * 05.2006 Added better handling of mutli-valued attributes
b9ddb2d5 18 * 2006-08-28 File created, code imported from lib.php
19 * 2006-10-27 Upstream 1.7 changes merged in, added above credits from lib.php :-)
3ea28768 20 * 2007-03-09 Fixed authentication but may need some other changes
1432ac14 21 * 2007-10-03 Removed requirement for email address, surname and given name on request of Markus Hagman
eefd788b 22 * 2008-01-21 Added WAYF functionality
23
b9ddb2d5 24 */
25
139ebfdb 26if (!defined('MOODLE_INTERNAL')) {
27 die('Direct access to this script is forbidden.'); /// It must be included from a Moodle page
28}
b9ddb2d5 29
6bc1e5d5 30require_once($CFG->libdir.'/authlib.php');
31
b9ddb2d5 32/**
33 * Shibboleth authentication plugin.
34 */
6bc1e5d5 35class auth_plugin_shibboleth extends auth_plugin_base {
b9ddb2d5 36
37 /**
38 * Constructor.
39 */
40 function auth_plugin_shibboleth() {
6bc1e5d5 41 $this->authtype = 'shibboleth';
b9ddb2d5 42 $this->config = get_config('auth/shibboleth');
43 }
44
45 /**
46 * Returns true if the username and password work and false if they are
47 * wrong or don't exist.
48 *
2f5237ed 49 * @param string $username The username (with system magic quotes)
50 * @param string $password The password (with system magic quotes)
139ebfdb 51 * @return bool Authentication success or failure.
b9ddb2d5 52 */
53 function user_login($username, $password) {
2db6ec19 54 global $SESSION;
55
b9ddb2d5 56 // If we are in the shibboleth directory then we trust the server var
3ea28768 57 if (!empty($_SERVER[$this->config->user_attribute])) {
2db6ec19 58 // Associate Shibboleth session with user for SLO preparation
59 $sessionkey = '';
60 if (isset($_SERVER['Shib-Session-ID'])){
61 // This is only available for Shibboleth 2.x SPs
62 $sessionkey = $_SERVER['Shib-Session-ID'];
63 } else {
64 // Try to find out using the user's cookie
65 foreach ($_COOKIE as $name => $value){
6dbcacee 66 if (preg_match('/_shibsession_/i', $name)){
2db6ec19 67 $sessionkey = $value;
68 }
69 }
70 }
5117d598 71
2db6ec19 72 // Set shibboleth session ID for logout
73 $SESSION->shibboleth_session_id = $sessionkey;
74
f309632a 75 return (strtolower($_SERVER[$this->config->user_attribute]) == strtolower($username));
b9ddb2d5 76 } else {
77 // If we are not, the user has used the manual login and the login name is
78 // unknown, so we return false.
79 return false;
80 }
81 }
82
3ea28768 83
5117d598 84
3ea28768 85 /**
86 * Returns the user information for 'external' users. In this case the
87 * attributes provided by Shibboleth
88 *
89 * @return array $result Associative array of user data
90 */
b9ddb2d5 91 function get_userinfo($username) {
92 // reads user information from shibboleth attributes and return it in array()
93 global $CFG;
94
95 // Check whether we have got all the essential attributes
1432ac14 96 if ( empty($_SERVER[$this->config->user_attribute]) ) {
2b06294b 97 print_error( 'shib_not_all_attributes_error', 'auth_shibboleth' , '', "'".$this->config->user_attribute."' ('".$_SERVER[$this->config->user_attribute]."'), '".$this->config->field_map_firstname."' ('".$_SERVER[$this->config->field_map_firstname]."'), '".$this->config->field_map_lastname."' ('".$_SERVER[$this->config->field_map_lastname]."') and '".$this->config->field_map_email."' ('".$_SERVER[$this->config->field_map_email]."')");
b9ddb2d5 98 }
99
100 $attrmap = $this->get_attributes();
101
102 $result = array();
103 $search_attribs = array();
139ebfdb 104
b9ddb2d5 105 foreach ($attrmap as $key=>$value) {
5117d598 106 // Check if attribute is present
c31f631b 107 if (!isset($_SERVER[$value])){
108 $result[$key] = '';
109 continue;
110 }
73f1e3b2 111
f309632a 112 // Make usename lowercase
113 if ($key == 'username'){
114 $result[$key] = strtolower($this->get_first_string($_SERVER[$value]));
115 } else {
116 $result[$key] = $this->get_first_string($_SERVER[$value]);
117 }
b9ddb2d5 118 }
119
120 // Provide an API to modify the information to fit the Moodle internal
121 // data representation
139ebfdb 122 if (
3ea28768 123 $this->config->convert_data
124 && $this->config->convert_data != ''
125 && is_readable($this->config->convert_data)
b9ddb2d5 126 ) {
139ebfdb 127
b9ddb2d5 128 // Include a custom file outside the Moodle dir to
129 // modify the variable $moodleattributes
3ea28768 130 include($this->config->convert_data);
b9ddb2d5 131 }
139ebfdb 132
b9ddb2d5 133 return $result;
134 }
135
eefd788b 136 /**
b9ddb2d5 137 * Returns array containg attribute mappings between Moodle and Shibboleth.
eefd788b 138 *
139 * @return array
b9ddb2d5 140 */
141 function get_attributes() {
142 $configarray = (array) $this->config;
2f5237ed 143
b9ddb2d5 144 $moodleattributes = array();
4105caff 145 foreach ($this->userfields as $field) {
f309632a 146 if (isset($configarray["field_map_$field"])) {
b9ddb2d5 147 $moodleattributes[$field] = $configarray["field_map_$field"];
148 }
149 }
5261baf1 150 $moodleattributes['username'] = $configarray["user_attribute"];
b9ddb2d5 151
152 return $moodleattributes;
153 }
154
edb5da83
PS
155 function prevent_local_passwords() {
156 return true;
157 }
158
b9ddb2d5 159 /**
160 * Returns true if this authentication plugin is 'internal'.
161 *
139ebfdb 162 * @return bool
b9ddb2d5 163 */
164 function is_internal() {
165 return false;
166 }
167
168 /**
169 * Returns true if this authentication plugin can change the user's
170 * password.
171 *
139ebfdb 172 * @return bool
b9ddb2d5 173 */
174 function can_change_password() {
175 return false;
176 }
139ebfdb 177
eefd788b 178 /**
179 * Hook for login page
180 *
181 */
f5fd4347 182 function loginpage_hook() {
6bc1e5d5 183 global $SESSION, $CFG;
a044c05d 184
185 // Prevent username from being shown on login page after logout
186 $CFG->nolastloggedin = true;
6bc1e5d5 187
6bc1e5d5 188 return;
6bc1e5d5 189 }
5117d598 190
c49e414b 191 /**
192 * Hook for logout page
193 *
194 */
195 function logoutpage_hook() {
f4831673 196 global $SESSION, $redirect;
5117d598 197
f4831673 198 // Only do this if logout handler is defined, and if the user is actually logged in via Shibboleth
af4f1cc7
AB
199 $logouthandlervalid = isset($this->config->logout_handler) && !empty($this->config->logout_handler);
200 if (isset($SESSION->shibboleth_session_id) && $logouthandlervalid ) {
ad9f023c 201 // Check if there is an alternative logout return url defined
af4f1cc7 202 if (isset($this->config->logout_return_url) && !empty($this->config->logout_return_url)) {
ad9f023c 203 // Set temp_redirect to alternative return url
204 $temp_redirect = $this->config->logout_return_url;
205 } else {
206 // Backup old redirect url
207 $temp_redirect = $redirect;
208 }
5117d598 209
c49e414b 210 // Overwrite redirect in order to send user to Shibboleth logout page and let him return back
211 $redirect = $this->config->logout_handler.'?return='.urlencode($temp_redirect);
212 }
213 }
214
215
6bc1e5d5 216
b9ddb2d5 217 /**
218 * Prints a form for configuring this authentication plugin.
219 *
220 * This function is called from admin/auth.php, and outputs a full page with
221 * a form for configuring this plugin.
222 *
223 * @param array $page An object containing all the data for this page.
224 */
139ebfdb 225 function config_form($config, $err, $user_fields) {
b9ddb2d5 226 include "config.html";
227 }
228
229 /**
230 * Processes and stores configuration data for this authentication plugin.
3ea28768 231 *
232 *
233 * @param object $config Configuration object
b9ddb2d5 234 */
235 function process_config($config) {
c31f631b 236 global $CFG;
1531d1ef 237
b9ddb2d5 238 // set to defaults if undefined
239 if (!isset($config->auth_instructions) or empty($config->user_attribute)) {
cd138b26 240 $config->auth_instructions = get_string('auth_shib_instructions', 'auth_shibboleth', $CFG->wwwroot.'/auth/shibboleth/index.php');
b9ddb2d5 241 }
242 if (!isset ($config->user_attribute)) {
243 $config->user_attribute = '';
244 }
245 if (!isset ($config->convert_data)) {
246 $config->convert_data = '';
247 }
5117d598 248
b9ddb2d5 249 if (!isset($config->changepasswordurl)) {
250 $config->changepasswordurl = '';
251 }
5117d598 252
eefd788b 253 if (!isset($config->login_name)) {
254 $config->login_name = 'Shibboleth Login';
255 }
5117d598 256
eefd788b 257 // Clean idp list
258 if (isset($config->organization_selection) && !empty($config->organization_selection) && isset($config->alt_login) && $config->alt_login == 'on') {
259 $idp_list = get_idp_list($config->organization_selection);
260 if (count($idp_list) < 1){
261 return false;
262 }
263 $config->organization_selection = '';
264 foreach ($idp_list as $idp => $value){
265 $config->organization_selection .= $idp.', '.$value[0].', '.$value[1]."\n";
266 }
267 }
5117d598 268
b9ddb2d5 269
270 // save settings
271 set_config('user_attribute', $config->user_attribute, 'auth/shibboleth');
5117d598 272
eefd788b 273 if (isset($config->organization_selection) && !empty($config->organization_selection)) {
274 set_config('organization_selection', $config->organization_selection, 'auth/shibboleth');
275 }
c49e414b 276 set_config('logout_handler', $config->logout_handler, 'auth/shibboleth');
ad9f023c 277 set_config('logout_return_url', $config->logout_return_url, 'auth/shibboleth');
eefd788b 278 set_config('login_name', $config->login_name, 'auth/shibboleth');
b9ddb2d5 279 set_config('convert_data', $config->convert_data, 'auth/shibboleth');
280 set_config('auth_instructions', $config->auth_instructions, 'auth/shibboleth');
281 set_config('changepasswordurl', $config->changepasswordurl, 'auth/shibboleth');
5117d598 282
c49e414b 283 // Overwrite alternative login URL if integrated WAYF is used
eefd788b 284 if (isset($config->alt_login) && $config->alt_login == 'on'){
285 set_config('alt_login', $config->alt_login, 'auth/shibboleth');
286 set_config('alternateloginurl', $CFG->wwwroot.'/auth/shibboleth/login.php');
287 } else {
c49e414b 288 // Check if integrated WAYF was enabled and is now turned off
5117d598 289 // If it was and only then, reset the Moodle alternate URL
cd138b26 290 if (isset($this->config->alt_login) and $this->config->alt_login == 'on'){
c49e414b 291 set_config('alt_login', 'off', 'auth/shibboleth');
292 set_config('alternateloginurl', '');
293 }
eefd788b 294 $config->alt_login = 'off';
295 }
5117d598 296
3ea28768 297 // Check values and return false if something is wrong
c31f631b 298 // Patch Anyware Technologies (14/05/07)
299 if (($config->convert_data != '')&&(!file_exists($config->convert_data) || !is_readable($config->convert_data))){
3ea28768 300 return false;
301 }
5117d598 302
eefd788b 303 // Check if there is at least one entry in the IdP list
304 if (isset($config->organization_selection) && empty($config->organization_selection) && isset($config->alt_login) && $config->alt_login == 'on'){
305 return false;
306 }
3ea28768 307
b9ddb2d5 308 return true;
309 }
310
311 /**
312 * Cleans and returns first of potential many values (multi-valued attributes)
3ea28768 313 *
314 * @param string $string Possibly multi-valued attribute from Shibboleth
b9ddb2d5 315 */
316 function get_first_string($string) {
7785dc2e 317 $list = explode( ';', $string);
b9ddb2d5 318 $clean_string = rtrim($list[0]);
319
320 return $clean_string;
321 }
322}
323
5117d598 324
eefd788b 325 /**
326 * Sets the standard SAML domain cookie that is also used to preselect
327 * the right entry on the local wayf
328 *
329 * @param IdP identifiere
330 */
331 function set_saml_cookie($selectedIDP) {
332 if (isset($_COOKIE['_saml_idp']))
333 {
334 $IDPArray = generate_cookie_array($_COOKIE['_saml_idp']);
335 }
336 else
337 {
338 $IDPArray = array();
339 }
340 $IDPArray = appendCookieValue($selectedIDP, $IDPArray);
341 setcookie ('_saml_idp', generate_cookie_value($IDPArray), time() + (100*24*3600));
342 }
5117d598 343
eefd788b 344 /**
5117d598 345 * Prints the option elements for the select element of the drop down list
eefd788b 346 *
347 */
348 function print_idp_list(){
349 $config = get_config('auth/shibboleth');
5117d598 350
eefd788b 351 $IdPs = get_idp_list($config->organization_selection);
352 if (isset($_COOKIE['_saml_idp'])){
353 $idp_cookie = generate_cookie_array($_COOKIE['_saml_idp']);
354 do {
355 $selectedIdP = array_pop($idp_cookie);
356 } while (!isset($IdPs[$selectedIdP]) && count($idp_cookie) > 0);
5117d598 357
eefd788b 358 } else {
359 $selectedIdP = '-';
360 }
5117d598 361
eefd788b 362 foreach($IdPs as $IdP => $data){
363 if ($IdP == $selectedIdP){
364 echo '<option value="'.$IdP.'" selected="selected">'.$data[0].'</option>';
365 } else {
366 echo '<option value="'.$IdP.'">'.$data[0].'</option>';
367 }
368 }
369 }
5117d598
PS
370
371
eefd788b 372 /**
373 * Generate array of IdPs from Moodle Shibboleth settings
374 *
375 * @param string Text containing tuble/triple of IdP entityId, name and (optionally) session initiator
5117d598 376 * @return array Identifier of IdPs and their name/session initiator
eefd788b 377 */
378
379 function get_idp_list($organization_selection) {
380 $idp_list = array();
5117d598 381
7785dc2e 382 $idp_raw_list = explode("\n", $organization_selection);
5117d598 383
eefd788b 384 foreach ($idp_raw_list as $idp_line){
7785dc2e 385 $idp_data = explode(',', $idp_line);
eefd788b 386 if (isset($idp_data[2]))
387 {
5117d598 388 $idp_list[trim($idp_data[0])] = array(trim($idp_data[1]),trim($idp_data[2]));
eefd788b 389 }
390 elseif(isset($idp_data[1]))
391 {
392 $idp_list[trim($idp_data[0])] = array(trim($idp_data[1]));
393 }
394 }
5117d598 395
eefd788b 396 return $idp_list;
397 }
5117d598 398
eefd788b 399 /**
400 * Generates an array of IDPs using the cookie value
401 *
5117d598
PS
402 * @param string Value of SAML domain cookie
403 * @return array Identifiers of IdPs
eefd788b 404 */
405 function generate_cookie_array($value) {
5117d598 406
eefd788b 407 // Decodes and splits cookie value
7785dc2e 408 $CookieArray = explode(' ', $value);
eefd788b 409 $CookieArray = array_map('base64_decode', $CookieArray);
5117d598 410
eefd788b 411 return $CookieArray;
412 }
5117d598 413
eefd788b 414 /**
415 * Generate the value that is stored in the cookie using the list of IDPs
416 *
5117d598 417 * @param array IdP identifiers
eefd788b 418 * @return string SAML domain cookie value
419 */
420 function generate_cookie_value($CookieArray) {
5117d598 421
eefd788b 422 // Merges cookie content and encodes it
423 $CookieArray = array_map('base64_encode', $CookieArray);
424 $value = implode(' ', $CookieArray);
425 return $value;
426 }
5117d598 427
eefd788b 428 /**
429 * Append a value to the array of IDPs
430 *
431 * @param string IdP identifier
432 * @param array IdP identifiers
5117d598 433 * @return array IdP identifiers with appended IdP
eefd788b 434 */
435 function appendCookieValue($value, $CookieArray) {
5117d598 436
eefd788b 437 array_push($CookieArray, $value);
438 $CookieArray = array_reverse($CookieArray);
439 $CookieArray = array_unique($CookieArray);
440 $CookieArray = array_reverse($CookieArray);
5117d598 441
eefd788b 442 return $CookieArray;
443 }
444
445
5117d598 446