Merge branch 'wip-mdl-29079-m21' of git://github.com/rajeshtaneja/moodle into MOODLE_...
[moodle.git] / auth / shibboleth / auth.php
blob842b7351153de79e2ac99f4d032da4fdb6cf46f0
1 <?php
2 /**
3 * @author Martin Dougiamas
4 * @author Lukas Haemmerle
5 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
6 * @package moodle multiauth
8 * Authentication Plugin: Shibboleth Authentication
10 * Authentication using Shibboleth.
12 * Distributed under GPL (c)Markus Hagman 2004-2006
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
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 :-)
20 * 2007-03-09 Fixed authentication but may need some other changes
21 * 2007-10-03 Removed requirement for email address, surname and given name on request of Markus Hagman
22 * 2008-01-21 Added WAYF functionality
26 if (!defined('MOODLE_INTERNAL')) {
27 die('Direct access to this script is forbidden.'); /// It must be included from a Moodle page
30 require_once($CFG->libdir.'/authlib.php');
32 /**
33 * Shibboleth authentication plugin.
35 class auth_plugin_shibboleth extends auth_plugin_base {
37 /**
38 * Constructor.
40 function auth_plugin_shibboleth() {
41 $this->authtype = 'shibboleth';
42 $this->config = get_config('auth/shibboleth');
45 /**
46 * Returns true if the username and password work and false if they are
47 * wrong or don't exist.
49 * @param string $username The username (with system magic quotes)
50 * @param string $password The password (with system magic quotes)
51 * @return bool Authentication success or failure.
53 function user_login($username, $password) {
54 global $SESSION;
56 // If we are in the shibboleth directory then we trust the server var
57 if (!empty($_SERVER[$this->config->user_attribute])) {
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){
66 if (preg_match('/_shibsession_/i', $name)){
67 $sessionkey = $value;
72 // Set shibboleth session ID for logout
73 $SESSION->shibboleth_session_id = $sessionkey;
75 return (strtolower($_SERVER[$this->config->user_attribute]) == strtolower($username));
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;
85 /**
86 * Returns the user information for 'external' users. In this case the
87 * attributes provided by Shibboleth
89 * @return array $result Associative array of user data
91 function get_userinfo($username) {
92 // reads user information from shibboleth attributes and return it in array()
93 global $CFG;
95 // Check whether we have got all the essential attributes
96 if ( empty($_SERVER[$this->config->user_attribute]) ) {
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]."')");
100 $attrmap = $this->get_attributes();
102 $result = array();
103 $search_attribs = array();
105 foreach ($attrmap as $key=>$value) {
106 // Check if attribute is present
107 if (!isset($_SERVER[$value])){
108 $result[$key] = '';
109 continue;
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]);
120 // Provide an API to modify the information to fit the Moodle internal
121 // data representation
122 if (
123 $this->config->convert_data
124 && $this->config->convert_data != ''
125 && is_readable($this->config->convert_data)
128 // Include a custom file outside the Moodle dir to
129 // modify the variable $moodleattributes
130 include($this->config->convert_data);
133 return $result;
137 * Returns array containg attribute mappings between Moodle and Shibboleth.
139 * @return array
141 function get_attributes() {
142 $configarray = (array) $this->config;
144 $moodleattributes = array();
145 foreach ($this->userfields as $field) {
146 if (isset($configarray["field_map_$field"])) {
147 $moodleattributes[$field] = $configarray["field_map_$field"];
150 $moodleattributes['username'] = $configarray["user_attribute"];
152 return $moodleattributes;
155 function prevent_local_passwords() {
156 return true;
160 * Returns true if this authentication plugin is 'internal'.
162 * @return bool
164 function is_internal() {
165 return false;
169 * Returns true if this authentication plugin can change the user's
170 * password.
172 * @return bool
174 function can_change_password() {
175 return false;
179 * Hook for login page
182 function loginpage_hook() {
183 global $SESSION, $CFG;
185 // Prevent username from being shown on login page after logout
186 $CFG->nolastloggedin = true;
188 return;
192 * Hook for logout page
195 function logoutpage_hook() {
196 global $SESSION, $redirect;
198 // Only do this if logout handler is defined, and if the user is actually logged in via Shibboleth
199 $logouthandlervalid = isset($this->config->logout_handler) && !empty($this->config->logout_handler);
200 if (isset($SESSION->shibboleth_session_id) && $logouthandlervalid ) {
201 // Check if there is an alternative logout return url defined
202 if (isset($this->config->logout_return_url) && !empty($this->config->logout_return_url)) {
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;
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);
218 * Prints a form for configuring this authentication plugin.
220 * This function is called from admin/auth.php, and outputs a full page with
221 * a form for configuring this plugin.
223 * @param array $page An object containing all the data for this page.
225 function config_form($config, $err, $user_fields) {
226 include "config.html";
230 * Processes and stores configuration data for this authentication plugin.
233 * @param object $config Configuration object
235 function process_config($config) {
236 global $CFG;
238 // set to defaults if undefined
239 if (!isset($config->auth_instructions) or empty($config->user_attribute)) {
240 $config->auth_instructions = get_string('auth_shib_instructions', 'auth_shibboleth', $CFG->wwwroot.'/auth/shibboleth/index.php');
242 if (!isset ($config->user_attribute)) {
243 $config->user_attribute = '';
245 if (!isset ($config->convert_data)) {
246 $config->convert_data = '';
249 if (!isset($config->changepasswordurl)) {
250 $config->changepasswordurl = '';
253 if (!isset($config->login_name)) {
254 $config->login_name = 'Shibboleth Login';
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;
263 $config->organization_selection = '';
264 foreach ($idp_list as $idp => $value){
265 $config->organization_selection .= $idp.', '.$value[0].', '.$value[1]."\n";
270 // save settings
271 set_config('user_attribute', $config->user_attribute, 'auth/shibboleth');
273 if (isset($config->organization_selection) && !empty($config->organization_selection)) {
274 set_config('organization_selection', $config->organization_selection, 'auth/shibboleth');
276 set_config('logout_handler', $config->logout_handler, 'auth/shibboleth');
277 set_config('logout_return_url', $config->logout_return_url, 'auth/shibboleth');
278 set_config('login_name', $config->login_name, 'auth/shibboleth');
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');
283 // Overwrite alternative login URL if integrated WAYF is used
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 {
288 // Check if integrated WAYF was enabled and is now turned off
289 // If it was and only then, reset the Moodle alternate URL
290 if (isset($this->config->alt_login) and $this->config->alt_login == 'on'){
291 set_config('alt_login', 'off', 'auth/shibboleth');
292 set_config('alternateloginurl', '');
294 $config->alt_login = 'off';
297 // Check values and return false if something is wrong
298 // Patch Anyware Technologies (14/05/07)
299 if (($config->convert_data != '')&&(!file_exists($config->convert_data) || !is_readable($config->convert_data))){
300 return false;
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;
308 return true;
312 * Cleans and returns first of potential many values (multi-valued attributes)
314 * @param string $string Possibly multi-valued attribute from Shibboleth
316 function get_first_string($string) {
317 $list = explode( ';', $string);
318 $clean_string = rtrim($list[0]);
320 return $clean_string;
326 * Sets the standard SAML domain cookie that is also used to preselect
327 * the right entry on the local wayf
329 * @param IdP identifiere
331 function set_saml_cookie($selectedIDP) {
332 if (isset($_COOKIE['_saml_idp']))
334 $IDPArray = generate_cookie_array($_COOKIE['_saml_idp']);
336 else
338 $IDPArray = array();
340 $IDPArray = appendCookieValue($selectedIDP, $IDPArray);
341 setcookie ('_saml_idp', generate_cookie_value($IDPArray), time() + (100*24*3600));
345 * Prints the option elements for the select element of the drop down list
348 function print_idp_list(){
349 $config = get_config('auth/shibboleth');
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);
358 } else {
359 $selectedIdP = '-';
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>';
373 * Generate array of IdPs from Moodle Shibboleth settings
375 * @param string Text containing tuble/triple of IdP entityId, name and (optionally) session initiator
376 * @return array Identifier of IdPs and their name/session initiator
379 function get_idp_list($organization_selection) {
380 $idp_list = array();
382 $idp_raw_list = explode("\n", $organization_selection);
384 foreach ($idp_raw_list as $idp_line){
385 $idp_data = explode(',', $idp_line);
386 if (isset($idp_data[2]))
388 $idp_list[trim($idp_data[0])] = array(trim($idp_data[1]),trim($idp_data[2]));
390 elseif(isset($idp_data[1]))
392 $idp_list[trim($idp_data[0])] = array(trim($idp_data[1]));
396 return $idp_list;
400 * Generates an array of IDPs using the cookie value
402 * @param string Value of SAML domain cookie
403 * @return array Identifiers of IdPs
405 function generate_cookie_array($value) {
407 // Decodes and splits cookie value
408 $CookieArray = explode(' ', $value);
409 $CookieArray = array_map('base64_decode', $CookieArray);
411 return $CookieArray;
415 * Generate the value that is stored in the cookie using the list of IDPs
417 * @param array IdP identifiers
418 * @return string SAML domain cookie value
420 function generate_cookie_value($CookieArray) {
422 // Merges cookie content and encodes it
423 $CookieArray = array_map('base64_encode', $CookieArray);
424 $value = implode(' ', $CookieArray);
425 return $value;
429 * Append a value to the array of IDPs
431 * @param string IdP identifier
432 * @param array IdP identifiers
433 * @return array IdP identifiers with appended IdP
435 function appendCookieValue($value, $CookieArray) {
437 array_push($CookieArray, $value);
438 $CookieArray = array_reverse($CookieArray);
439 $CookieArray = array_unique($CookieArray);
440 $CookieArray = array_reverse($CookieArray);
442 return $CookieArray;