dokeos-auth-ldap
[ class tree: dokeos-auth-ldap ] [ index: dokeos-auth-ldap ] [ all elements ]

Source for file authldap.php

Documentation is available at authldap.php

  1. <?php // $Id: authldap.php 15253 2008-05-09 03:00:19Z yannoo $
  2. /*
  3. ==============================================================================
  4.     Dokeos - elearning and course management software
  5.  
  6.     Copyright (c) 2004 Dokeos SPRL
  7.     Copyright (c) 2003 Ghent University (UGent)
  8.     Copyright (c) 2001 Universite catholique de Louvain (UCL)
  9.     Copyright (c) Universite Jean Monnet de Saint Etienne
  10.     Copyright (c) Roan Embrechts (Vrije Universiteit Brussel)
  11.  
  12.     For a full list of contributors, see "credits.txt".
  13.     The full license can be read in "license.txt".
  14.  
  15.     This program is free software; you can redistribute it and/or
  16.     modify it under the terms of the GNU General Public License
  17.     as published by the Free Software Foundation; either version 2
  18.     of the License, or (at your option) any later version.
  19.  
  20.     See the GNU General Public License for more details.
  21.  
  22.     Contact address: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium
  23.     Mail: info@dokeos.com
  24. ==============================================================================
  25. */
  26. /**
  27. =======================================================================
  28. *    LDAP module functions
  29. *
  30. *    If the application uses LDAP, these functions are used
  31. *    for logging in, searching user info, adding this info
  32. *    to the Dokeos database...
  33. =======================================================================
  34.     - function ldap_authentication_check()
  35.     - function ldap_find_user_info()
  36.     - function ldap_login()
  37.     - function ldap_put_user_info_locally()
  38.     - ldap_set_version()
  39.  
  40.     known bugs
  41.     ----------
  42.     - (fixed 18 june 2003) code has been internationalized
  43.     - (fixed 07/05/2003) fixed some non-relative urls or includes
  44.     - (fixed 28/04/2003) we now use global config.inc variables instead of local ones
  45.     - (fixed 22/04/2003) the last name of a user was restricted to the first part
  46.     - (fixed 11/04/2003) the user was never registered as a course manager
  47.  
  48.     version history
  49.     ---------------
  50.     3.2 - updated to allow for specific term search for teachers identification
  51.     3.1 - updated code to use database settings, to respect coding conventions as much as possible (camel-case removed) and to allow for non-anonymous login 
  52.     3.0    - updated to use ldap_var.inc.php instead of ldap_var.inc (deprecated)
  53.         (November 2003)
  54.     2.9    - further changes for new login procedure
  55.         - (busy) translating french functions to english
  56.         (October 2003)
  57.     2.8    - adapted for new Claroline login procedure
  58.         - ldap package now becomes a standard, in auth/ldap
  59.     2.7 - uses more standard LDAP field names: mail, sn, givenname
  60.             instead of mail, preferredsn, preferredgivenname
  61.             there are still
  62.         - code cleanup
  63.         - fixed bug: dc = xx, dc = yy was configured for UGent
  64.             and put literally in the code, this is now a variable
  65.             in configuration.php ($LDAPbasedn)
  66.  
  67.     with thanks to
  68.     - Stefan De Wannemacker (Ghent University)
  69.     - Universite Jean Monet (J Dubois / Michel Courbon)
  70.     - Michel Panckoucke for reporting and fixing a bug
  71.     - Patrick Cool: fixing security hole
  72.  
  73.     *    @author Roan Embrechts
  74.     *    @version 3.0
  75.     *    @package dokeos.auth.ldap
  76. =======================================================================
  77. */
  78.  
  79. require('ldap_var.inc.php');
  80.  
  81. /**
  82. ===============================================================
  83.     function
  84.     CHECK LOGIN & PASSWORD WITH LDAP
  85. *    @return true when login & password both OK, false otherwise
  86. ===============================================================
  87. *    @author Roan Embrechts (based on code from Universit� Jean Monet)
  88. */
  89. //require_once(api_get_path(INCLUDE_PATH).'../connect/authldap.php');
  90.  
  91. function ldap_login($login$password)
  92. {
  93.     //error_log('Entering ldap_login('.$login.','.$password.')',0);
  94.     $res ldap_authentication_check($login$password);
  95.  
  96.     // res=-1 -> the user does not exist in the ldap database
  97.     // res=1 -> invalid password (user does exist)
  98.  
  99.     if ($res==1//WRONG PASSWORD
  100.     {
  101.         //$errorMessage = "LDAP Username or password incorrect, please try again.<br>";
  102.         if (isset($log)) unset($log)if (isset($uid)) unset($uid);
  103.         $loginLdapSucces false;
  104.     }
  105.     if ($res==-1//WRONG USERNAME
  106.     {
  107.         //$errorMessage =  "LDAP Username or password incorrect, please try again.<br>";
  108.         $login_ldap_success false;
  109.     }
  110.     if ($res==0//LOGIN & PASSWORD OK - SUCCES
  111.     {
  112.         //$errorMessage = "Successful login w/ LDAP.<br>";
  113.         $login_ldap_success true;
  114.     }
  115.  
  116.     //$result = "This is the result: $errorMessage";
  117.     $result $login_ldap_success;
  118.     return $result;
  119. }
  120.  
  121.  
  122. /**
  123. ===============================================================
  124.     function
  125.     FIND USER INFO IN LDAP
  126. *    @return an array with positions "firstname", "name", "email", "employeenumber"
  127. ===============================================================
  128. *    @author Stefan De Wannemacker
  129. *    @author Roan Embrechts
  130. */
  131. function ldap_find_user_info ($login)
  132. {
  133.     //error_log('Entering ldap_find_user_info('.$login.')',0);
  134.     global $ldap_host$ldap_port$ldap_basedn$ldap_rdn$ldap_pass$ldap_search_dn;
  135.     // basic sequence with LDAP is connect, bind, search,
  136.     // interpret search result, close connection
  137.  
  138.     //echo "Connecting ...";
  139.     $ldap_connect ldap_connect$ldap_host$ldap_port);
  140.     ldap_set_version($ldap_connect);
  141.     if ($ldap_connect{
  142.             //echo " Connect to LDAP server successful ";
  143.             //echo "Binding ...";
  144.             $ldap_bind false;
  145.             $ldap_bind_res ldap_handle_bind($ldap_connect,$ldap_bind);
  146.             if ($ldap_bind_res)
  147.             {
  148.                 //echo " LDAP bind successful... ";
  149.                   //echo " Searching for uid... ";
  150.                 // Search surname entry
  151.                 //OLD: $sr=ldap_search($ldapconnect,"dc=rug, dc=ac, dc=be", "uid=$login");
  152.                 //echo "<p> ldapDc = '$LDAPbasedn' </p>";
  153.                 if(!empty($ldap_search_dn))
  154.                 {
  155.                     $sr=ldap_search($ldap_connect$ldap_search_dn"uid=$login");
  156.                 }
  157.                 else
  158.                 {
  159.                     $sr=ldap_search($ldap_connect$ldap_basedn"uid=$login");
  160.                 }
  161.  
  162.                 //echo " Search result is ".$sr;
  163.                 //echo " Number of entries returned is ".ldap_count_entries($ldapconnect,$sr);
  164.  
  165.                 //echo " Getting entries ...";
  166.                 $info ldap_get_entries($ldap_connect$sr);
  167.                 //echo "Data for ".$info["count"]." items returned:<p>";
  168.  
  169.             }
  170.         else
  171.         {
  172.             //echo "LDAP bind failed...";
  173.         }
  174.         //echo "Closing LDAP connection<hr>";
  175.         ldap_close($ldap_connect);
  176.     }
  177.     else
  178.     {
  179.         //echo "<h3>Unable to connect to LDAP server</h3>";
  180.     }
  181.  
  182.     //DEBUG: $result["firstname"] = "Jan"; $result["name"] = "De Test"; $result["email"] = "email@ugent.be";
  183.     $result["firstname"$info[0]["givenname"][0];
  184.     $result["name"$info[0]["sn"][0];
  185.     $result["email"$info[0]["mail"][0];
  186.     $tutor_field api_get_setting('ldap_filled_tutor_field');
  187.     $result[$tutor_field$info[0][$tutor_field]//employeenumber by default
  188.  
  189.     return $result;
  190. }
  191.  
  192.  
  193. /**
  194. *    This function uses the data from ldap_find_user_info()
  195. *    to add the userdata to Dokeos
  196. *
  197. *    "firstname", "name", "email", "isEmployee"
  198. ===============================================================
  199. *    @author Roan Embrechts
  200. */
  201. function ldap_put_user_info_locally($login$info_array)
  202. {
  203.     //error_log('Entering ldap_put_user_info_locally('.$login.',info_array)',0);
  204.     global $ldap_pass_placeholder;
  205.     global $submitRegistration$submit$uname$email,
  206.             $nom$prenom$password$password1$status;
  207.     global $platformLanguage;
  208.     global $loginFailed$uidReset$_user;
  209.  
  210.     /*----------------------------------------------------------
  211.         1. set the necessary variables
  212.     ------------------------------------------------------------ */
  213.  
  214.     $uname      $login;
  215.     $email      $info_array["email"];
  216.     $nom        $info_array["name"];
  217.     $prenom     $info_array["firstname"];
  218.     $password   $ldap_pass_placeholder;
  219.     $password1  $ldap_pass_placeholder;
  220.     $official_code '';
  221.  
  222.     define ("STUDENT",5);
  223.     define ("COURSEMANAGER",1);
  224.  
  225.     $tutor_field api_get_setting('ldap_filled_tutor_field');
  226.     $tutor_value api_get_setting('ldap_filled_tutor_field_value');
  227.     if(empty($tutor_field))
  228.     {
  229.         $status STUDENT;
  230.     }
  231.     else
  232.     {
  233.         if(empty($tutor_value))
  234.         {
  235.             //in this case, we are assuming that the admin didn't give a criteria
  236.             // so that if the field is not empty, it is a tutor
  237.             if(!empty($info_array[$tutor_field]))
  238.             {
  239.                 $status COURSEMANAGER;
  240.             }
  241.             else
  242.             {
  243.                 $status STUDENT;
  244.             }
  245.         }
  246.         else
  247.         {
  248.             //the tutor_value is filled, so we need to check the contents of the LDAP field
  249.             if (is_array($info_array[$tutor_field]&& in_array($tutor_value,$info_array[$tutor_field]))
  250.             {
  251.                 $status COURSEMANAGER;
  252.             }
  253.             else
  254.             {
  255.                 $status STUDENT;
  256.             }
  257.         }
  258.     }
  259.     //$official_code = xxx; //example: choose an attribute
  260.  
  261.     /*----------------------------------------------------------
  262.         2. add info to Dokeos
  263.     ------------------------------------------------------------ */
  264.  
  265.     require_once(api_get_path(LIBRARY_PATH).'usermanager.lib.php');
  266.     $_userId UserManager::create_user($prenom$nom$status,
  267.                      $email$uname$password$official_code,
  268.                      'english','''''ldap');
  269.  
  270.     //echo "new user added to Dokeos, id = $_userId";
  271.  
  272.     //user_id, username, password, auth_source
  273.  
  274.     /*----------------------------------------------------------
  275.         3. register session
  276.     ------------------------------------------------------------ */
  277.  
  278.     $uData['user_id'$_userId;
  279.     $uData['username'$uname;
  280.     $uData['auth_source'"ldap";
  281.  
  282.     $loginFailed false;
  283.     $uidReset true;
  284.     $_user['user_id'$uData['user_id'];
  285.     api_session_register('_uid');
  286. }
  287.  
  288. /* >>>>>>>>>>>>>>>> end of UGent LDAP routines <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< */
  289.  
  290. /* >>>>> Older but necessary code of Universite Jean-Monet <<<<< */
  291.  
  292. /*
  293. ===========================================================
  294.     The code of UGent uses these functions to authenticate.
  295.     * function AuthVerifEnseignant ($uname, $passwd)
  296.     * function AuthVerifEtudiant ($uname, $passwd)
  297.     * function Authentif ($uname, $passwd)
  298. ===========================================================
  299.     To Do
  300.     * translate the comments and code to english
  301.     * let these functions use the variables in config.inc instead of ldap_var.inc
  302. */
  303.  
  304. //*** variables en entree
  305. // $uname : username entre au clavier
  306. // $passwd : password fournit par l'utilisateur
  307.  
  308. //*** en sortie : 3 valeurs possibles
  309. // 0 -> authentif reussie
  310. // 1 -> password incorrect
  311. // -1 -> ne fait partie du LDAP
  312.  
  313. //---------------------------------------------------
  314. // verification de l'existence du membre dans le LDAP
  315. function ldap_authentication_check ($uname$passwd)
  316. {
  317.     //error_log('Entering ldap_authentication_check('.$uname.','.$passwd.')',0);
  318.     global $ldap_host$ldap_port$ldap_basedn$ldap_host2$ldap_port2,$ldap_rdn,$ldap_pass;
  319.     //error_log('Entering ldap_authentication_check('.$uname.','.$passwd.')',0);
  320.     // Establish anonymous connection with LDAP server
  321.     // Etablissement de la connexion anonyme avec le serveur LDAP
  322.     $ds=ldap_connect($ldap_host,$ldap_port);
  323.     ldap_set_version($ds);
  324.     
  325.     $test_bind false;
  326.     $test_bind_res ldap_handle_bind($ds,$test_bind);
  327.        //en cas de probleme on utlise le replica
  328.        if($test_bind_res===false){
  329.         $ds=ldap_connect($ldap_host2,$ldap_port2);
  330.         ldap_set_version($ds);
  331.        }
  332.        else
  333.        {
  334.            //error_log('Connected to server '.$ldap_host);
  335.        }
  336.      if ($ds!==false{
  337.         // Creation du filtre contenant les valeurs saisies par l'utilisateur
  338.         $filter="(uid=$uname)";
  339.         // Open anonymous LDAP connection
  340.         // Ouverture de la connection anonyme ldap
  341.         $result=false;
  342.         $ldap_bind_res ldap_handle_bind($ds,$result);
  343.         // Execution de la recherche avec $filtre en parametre
  344.         //error_log('Searching for '.$filter.' on LDAP server',0);
  345.         $sr=ldap_search($ds,$ldap_basedn,$filter);
  346.         // La variable $info recoit le resultat de la requete
  347.         $info ldap_get_entries($ds$sr);
  348.         $dn=($info[0]["dn"]);
  349.         //affichage debug !!    echo"<br> dn = $dn<br> pass = $passwd<br>";
  350.         // fermeture de la 1ere connexion
  351.         ldap_close($ds);
  352.     }
  353.  
  354.     // teste le Distinguish Name de la 1ere connection
  355.       if ($dn==""){
  356.          return (-1);        // ne fait pas partie de l'annuaire
  357.     }
  358.     //bug ldap.. si password vide.. retourne vrai !!
  359.     if ($passwd==""{
  360.         return(1);
  361.     }
  362.     // Ouverture de la 2em connection Ldap : connexion user pour verif mot de passe
  363.     $ds=ldap_connect($ldap_host,$ldap_port);
  364.     ldap_set_version($ds);
  365.     if(!$test_bind){
  366.         $ds=ldap_connect($ldap_host2,$ldap_port2);
  367.         ldap_set_version($ds);
  368.        }
  369.     // retour en cas d'erreur de connexion password incorrecte
  370.      if (@ldap_bind$ds$dn $passwd=== false{
  371.         return (1)// mot passe invalide
  372.     }
  373.     // connection correcte
  374.     else
  375.     {
  376.         return (0);
  377.     }
  378. // end of check
  379. /**
  380.  * Set the protocol version with version from config file (enables LDAP version 3)
  381.  * @param    resource    The LDAP connexion resource, passed by reference.
  382.  * @return    void 
  383.  */
  384. function ldap_set_version(&$resource)
  385. {
  386.     //error_log('Entering ldap_set_version(&$resource)',0);
  387.     global $ldap_version;
  388.     if($ldap_version>2)
  389.     {
  390.         if(ldap_set_option($resourceLDAP_OPT_PROTOCOL_VERSION3))
  391.         {
  392.             //ok - don't do anything
  393.         }
  394.         else
  395.         {
  396.             //failure - should switch back to version 2 by default
  397.         }
  398.     }
  399. }
  400. /**
  401.  * Handle bind (whether authenticated or not)
  402.  * @param    resource    The LDAP handler to which we are connecting (by reference)
  403.  * @param    resource    The LDAP bind handler we will be modifying
  404.  * @return    boolean        Status of the bind assignment. True for success, false for failure.
  405.  */
  406. function ldap_handle_bind(&$ldap_handler,&$ldap_bind)
  407. {
  408.     //error_log('Entering ldap_handle_bind(&$ldap_handler,&$ldap_bind)',0);
  409.     global $ldap_rdn,$ldap_pass;
  410.     if(!empty($ldap_rdnand !empty($ldap_pass))
  411.     {
  412.         //error_log('Trying authenticated login :'.$ldap_rdn.'/'.$ldap_pass,0);
  413.         $ldap_bind ldap_bind($ldap_handler,$ldap_rdn,$ldap_pass);
  414.         if(!$ldap_bind)
  415.         {
  416.             //error_log('Authenticated login failed',0);
  417.             //try in anonymous mode, you never know...
  418.             $ldap_bind ldap_bind($ldap_handler);
  419.         }
  420.     }
  421.     else
  422.     {
  423.         // this is an "anonymous" bind, typically read-only access:
  424.         $ldap_bind ldap_bind($ldap_handler);
  425.     }
  426.     if(!$ldap_bind)
  427.     {
  428.         return false;
  429.     }
  430.     else
  431.     {
  432.         //error_log('Login finally OK',0);
  433.         return true;
  434.     }
  435. }
  436. /**
  437.  * Get the total number of users on the platform
  438.  * @see SortableTable#get_total_number_of_items()
  439.  * @author    Mustapha Alouani
  440.  */
  441. function ldap_get_users()
  442. {
  443.  
  444.     global $ldap_basedn$ldap_host$ldap_port$ldap_rdn$ldap_pass;
  445.     
  446.     $keyword_firstname trim(Database::escape_string($_GET['keyword_firstname']));
  447.     $keyword_lastname trim(Database::escape_string($_GET['keyword_lastname']));
  448.     $keyword_username trim(Database::escape_string($_GET['keyword_username']));
  449.     $keyword_type Database::escape_string($_GET['keyword_type']);
  450.     
  451.     $ldap_query=array();
  452.     
  453.     if ($keyword_username != ""{
  454.         $ldap_query[]="(uid=".$keyword_username."*)";
  455.     else if ($keyword_lastname!=""){
  456.         $ldap_query[]="(sn=".$keyword_lastname."*)";
  457.         if ($keyword_firstname!=""{
  458.             $ldap_query[]="(givenName=".$keyword_firstname."*)";
  459.         }
  460.     }
  461.     if ($keyword_type !="" && $keyword_type !="all"{
  462.         $ldap_query[]="(employeeType=".$keyword_type.")";
  463.     }
  464.     
  465.     if (count($ldap_query)>1){
  466.         $str_query.="(& ";
  467.         foreach ($ldap_query as $query){
  468.             $str_query.=" $query";
  469.         }
  470.         $str_query.=" )"
  471.     else {
  472.         $str_query=$ldap_query[0];
  473.     }
  474.  
  475.     $ds ldap_connect($ldap_host$ldap_port);
  476.     ldap_set_version($ds);
  477.     if ($ds && count($ldap_query)>0{
  478.         $r false;
  479.         $res ldap_handle_bind($ds$r);
  480.         //$sr = ldap_search($ds, "ou=test-ou,$ldap_basedn", $str_query);
  481.         $sr ldap_search($ds$ldap_basedn$str_query);
  482.         //echo "Le nombre de resultats est : ".ldap_count_entries($ds,$sr)."<p>";
  483.         $info ldap_get_entries($ds$sr);
  484.         return $info;
  485.  
  486.     else {
  487.         if (count($ldap_query)!=0)
  488.             Display :: display_error_message(get_lang('LDAPConnectionError'));
  489.         return array();
  490.     }
  491. }
  492.  
  493.  
  494.  
  495. /**
  496.  * Get the total number of users on the platform
  497.  * @see SortableTable#get_total_number_of_items()
  498.  * @author    Mustapha Alouani
  499.  */
  500. {
  501.         
  502.     $info ldap_get_users();
  503.     if (count($info)>0)
  504.         return $info['count'];
  505.     else 
  506.         return 0;
  507.  
  508. }
  509.  
  510. /**
  511.  * Get the users to display on the current page.
  512.  * @see SortableTable#get_table_data($from)
  513.  * @author    Mustapha Alouani
  514.  */
  515. function ldap_get_user_data($from$number_of_items$column$direction)
  516. {
  517.     $users array();
  518.     if (isset($_GET['submit']))
  519.     {
  520.         $info ldap_get_users();
  521.         if ($info['count']>0)
  522.         {
  523.             for ($key 0$key $info["count"]$key ++)
  524.             {
  525.                 $user=array();
  526.                 // Get uid from dn
  527.                 //YW: this might be a variation between LDAP 2 and LDAP 3, but in LDAP 3, the uid is in
  528.                 //the corresponding index of the array
  529.                 //$dn_array=ldap_explode_dn($info[$key]["dn"],1);
  530.                 //$user[] = $dn_array[0]; // uid is first key
  531.                 //$user[] = $dn_array[0]; // uid is first key
  532.                 $user[$info[$key]['uid'][0];
  533.                 $user[$info[$key]['uid'][0];
  534.                 $user[iconv('utf-8'api_get_setting('platform_charset')$info[$key]['sn'][0]);
  535.                 $user[iconv('utf-8'api_get_setting('platform_charset')$info[$key]['givenname'][0]);
  536.                 $user[$info[$key]['mail'][0];
  537.                 $outab[$info[$key]['eduPersonPrimaryAffiliation'][0]// Ici "student"
  538.                 $users[$user;
  539.             }
  540.             
  541.         
  542.         else
  543.         {
  544.             Display :: display_error_message(get_lang('NoUser'));
  545.         }    
  546.     }
  547.     return $users;
  548. }
  549.  
  550. /**
  551.  * Build the modify-column of the table
  552.  * @param int $user_id The user id
  553.  * @param string $url_params 
  554.  * @return string Some HTML-code with modify-buttons
  555.  * @author    Mustapha Alouani
  556.  */
  557. function modify_filter($user_id,$url_params$row)
  558. {
  559.     $url_params_id="id[]=".$row[0];
  560.     //$url_params_id="id=".$row[0];    
  561.     $result .= '<a href="ldap_users_list.php?action=add_user&amp;user_id='.$user_id.'&amp;id_session='.Security::remove_XSS($_GET['id_session']).'&amp;'.$url_params_id.'&amp;sec_token='.$_SESSION['sec_token'].'"  onclick="javascript:if(!confirm('."'".addslashes(htmlentities(get_lang("ConfirmYourChoice")))."'".')) return false;"><img src="../img/add_user.gif" border="0" style="vertical-align: middle;" title="'.get_lang('AddUsers').'" alt="'.get_lang('AddUsers').'"/></a>';
  562.     return $result;
  563. }
  564.  
  565. /**
  566.  * Adds a user to the Dokeos database or updates its data
  567.  * @param    string    username (and uid inside LDAP)
  568.  * @author    Mustapha Alouani
  569.  */
  570. function ldap_add_user($login)
  571. {
  572.     global $ldap_basedn$ldap_host$ldap_port$ldap_rdn$ldap_pass;
  573.     
  574.     $ds ldap_connect($ldap_host$ldap_port);
  575.     ldap_set_version($ds);
  576.     if ($ds)
  577.     {
  578.         $str_query="(uid=".$login.")";
  579.         $r false;
  580.         $res ldap_handle_bind($ds$r);
  581.         $sr ldap_search($ds$ldap_basedn$str_query);
  582.         //echo "Le nombre de resultats est : ".ldap_count_entries($ds,$sr)."<p>";
  583.         $info ldap_get_entries($ds$sr);
  584.  
  585.         for ($key 0$key $info['count']$key ++)
  586.         {
  587.             $lastname iconv('utf-8'api_get_setting('platform_charset')$info[$key]['sn'][0]);
  588.             $firstname iconv('utf-8'api_get_setting('platform_charset')$info[$key]['givenname'][0]);
  589.             $email $info[$key]['mail'][0];
  590.             // Get uid from dn
  591.             $dn_array=ldap_explode_dn($info[$key]['dn'],1);
  592.             $username $dn_array[0]// uid is first key
  593.             $outab[$info[$key]['edupersonprimaryaffiliation'][0]// Ici "student"
  594.             //$val = ldap_get_values_len($ds, $entry, "userPassword");
  595.             //$val = ldap_get_values_len($ds, $info[$key], "userPassword");
  596.             //$password = $val[0];
  597.             // TODO the password, if encrypted at the source, will be encrypted twice, which makes it useless. Try to fix that.
  598.             $password $info[$key]['userPassword'][0];
  599.             $structure=$info[$key]['edupersonprimaryorgunitdn'][0];
  600.             $array_structure=explode(","$structure);
  601.             $array_val=explode("="$array_structure[0]);
  602.             $etape=$array_val[1];
  603.             $array_val=explode("="$array_structure[1]);
  604.             $annee=$array_val[1];
  605.             // Pour faciliter la gestion on ajoute le code "etape-annee"
  606.             $official_code=$etape."-".$annee;
  607.             $auth_source='ldap';
  608.             // Pas de date d'expiration d'etudiant (a recuperer par rapport au shadow expire LDAP)
  609.             $expiration_date='0000-00-00 00:00:00';
  610.             $active=1;
  611.             if(empty($status)){$status 5;}
  612.             if(empty($phone)){$phone '';}
  613.             if(empty($picture_uri)){$picture_uri '';}
  614.             // Ajout de l'utilisateur
  615.             if (UserManager::is_username_available($username))
  616.             {
  617.                 $user_id UserManager::create_user($firstname,$lastname,$status,$email,$username,$password,$official_code,api_get_setting('platformLanguage'),$phone,$picture_uri,$auth_source,$expiration_date,$active);
  618.             }
  619.             else
  620.             {
  621.                 $user UserManager::get_user_info($username);
  622.                 $user_id=$user['user_id'];
  623.                 UserManager::update_user($user_id$firstname$lastname$usernamenullnull$email$status$official_code$phone$picture_uri$expiration_date$active);
  624.             }
  625.         }
  626.  
  627.     
  628.     else 
  629.     {
  630.         Display :: display_error_message(get_lang('LDAPConnectionError'));
  631.     }
  632.     return $user_id;;
  633. }
  634.  
  635. /**
  636.  * Adds a list of users to one session
  637.  * @param    array    Array of user ids
  638.  * @param    string    Course code
  639.  * @return    void 
  640.  */
  641. function ldap_add_user_to_session($UserList$id_session)
  642. {
  643.  
  644.     // Database Table Definitions
  645.     $tbl_session                        Database::get_main_table(TABLE_MAIN_SESSION);
  646.     $tbl_session_rel_class                Database::get_main_table(TABLE_MAIN_SESSION_CLASS);
  647.     $tbl_session_rel_course                Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  648.     $tbl_session_rel_course_rel_user    Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  649.     $tbl_course                            Database::get_main_table(TABLE_MAIN_COURSE);
  650.     $tbl_user                            Database::get_main_table(TABLE_MAIN_USER);
  651.     $tbl_session_rel_user                Database::get_main_table(TABLE_MAIN_SESSION_USER);
  652.     $tbl_class                            Database::get_main_table(TABLE_MAIN_CLASS);
  653.     $tbl_class_user                        Database::get_main_table(TABLE_MAIN_CLASS_USER);
  654.  
  655.     $id_session = (int) $id_session;
  656.     // Une fois les utilisateurs importer dans la base des utilisateurs, on peux les affecter a� la session
  657.     $result=api_sql_query("SELECT course_code FROM $tbl_session_rel_course .
  658.             "WHERE id_session='$id_session'",__FILE__,__LINE__);
  659.     $CourseList=array();
  660.     while($row=Database::fetch_array($result))
  661.     {
  662.         $CourseList[]=$row['course_code'];
  663.     }
  664.     foreach($CourseList as $enreg_course)
  665.     {
  666.         foreach($UserList as $enreg_user)
  667.         {
  668.             $enreg_user = (int) $enreg_user;
  669.             api_sql_query("INSERT IGNORE INTO $tbl_session_rel_course_rel_user(id_session,course_code,id_user) VALUES('$id_session','$enreg_course','$enreg_user')",__FILE__,__LINE__);
  670.         }
  671.         $sql "SELECT COUNT(id_user) as nbUsers FROM $tbl_session_rel_course_rel_user .
  672.                 "WHERE id_session='$id_session' AND course_code='$enreg_course'";
  673.         $rs api_sql_query($sql__FILE____LINE__);
  674.         list($nbr_usersDatabase::fetch_array($rs);
  675.         api_sql_query("UPDATE $tbl_session_rel_course  SET nbr_users=$nbr_users .
  676.                 "WHERE id_session='$id_session' AND course_code='$enreg_course'",__FILE__,__LINE__);
  677.     }
  678.     foreach($UserList as $enreg_user)
  679.     {
  680.         $enreg_user = (int) $enreg_user;
  681.         api_sql_query("INSERT IGNORE INTO $tbl_session_rel_user(id_session, id_user) .
  682.                 "VALUES('$id_session','$enreg_user')",__FILE__,__LINE__);
  683.     }
  684.     // On mets a jour le nombre d'utilisateurs dans la session
  685.     $sql "SELECT COUNT(id_user) as nbUsers FROM $tbl_session_rel_user WHERE id_session='$id_session'";
  686.     $rs api_sql_query($sql__FILE____LINE__);
  687.     list($nbr_usersDatabase::fetch_array($rs);
  688.     api_sql_query("UPDATE $tbl_session SET nbr_users=$nbr_users WHERE id='$id_session'",__FILE__,__LINE__);
  689. }
  690. ?>

Documentation generated on Thu, 12 Jun 2008 12:59:50 -0500 by phpDocumentor 1.4.1