Dokeos PHP Cross Reference Learning Management Systems

Source: /main/inc/lib/sessionmanager.lib.php - 1960 lines - 96164 bytes - Summary - Text - Print

   1  <?php //$id: $
   2  /* For licensing terms, see /dokeos_license.txt */
   3  /**
   4  ==============================================================================
   5  *    This class provides methods for sessions management.
   6  *    Include/require it in your code to use its features.
   7  *
   8  *    @package dokeos.library
   9  ==============================================================================
  10  */
  11  require_once ('display.lib.php');
  12  class SessionManager {
  13  	private function __construct() {
  14  
  15      }
  16      /**
  17       * Fetches a session from the database
  18       * @param   int     Session ID
  19       * @return  array   Session details (id, id_coach, name, nbr_courses, nbr_users, nbr_classes, date_start, date_end, nb_days_access_before_beginning,nb_days_access_after_end, session_admin_id)
  20       */
  21      public static function fetch($id) {
  22          $t = Database::get_main_table(TABLE_MAIN_SESSION);
  23          if ($id != strval(intval($id))) { return array(); }
  24          $s = "SELECT * FROM $t WHERE id = $id";
  25          $r = Database::query($s,__FILE__,__LINE__);
  26          if (Database::num_rows($r) != 1) { return array(); }
  27          return Database::fetch_array($r,'ASSOC');
  28      }
  29       /**
  30        * Create a session
  31        * @author Carlos Vargas <carlos.vargas@dokeos.com>,from existing code
  32        * @param    string         name
  33        * @param     integer        year_start
  34        * @param     integer        month_start
  35        * @param     integer        day_start
  36        * @param     integer        year_end
  37        * @param     integer        month_end
  38        * @param     integer        day_end
  39        * @param     integer        nb_days_acess_before
  40        * @param     integer        nb_days_acess_after
  41        * @param     integer        nolimit
  42        * @param     string        coach_username
  43        * @param     integer        id_session_category
  44        * @return $id_session;
  45        **/
  46  	public static function create_session ($sname,$sdescription,$syear_start,$smonth_start,$sday_start,$syear_end,$smonth_end,$sday_end,$nolimit,$coach_username, $id_session_category,$max_seats = -1) {
  47          global $_user;
  48          $name= trim($sname);
  49          $description= trim($sdescription);
  50          $year_start= intval($syear_start);
  51          $month_start=intval($smonth_start);
  52          $day_start=intval($sday_start);
  53          $year_end=intval($syear_end);
  54          $month_end=intval($smonth_end);
  55          $day_end=intval($sday_end);
  56      //    $nb_days_acess_before = intval($snb_days_acess_before);
  57      //    $nb_days_acess_after = intval($snb_days_acess_after);
  58          $id_session_category = intval($id_session_category);
  59      //    $id_visibility = intval($id_visibility);
  60          $tbl_user        = Database::get_main_table(TABLE_MAIN_USER);
  61          $tbl_session    = Database::get_main_table(TABLE_MAIN_SESSION);
  62  
  63          $sql = 'SELECT user_id FROM '.$tbl_user.' WHERE username="'.Database::escape_string($coach_username).'"';
  64          $rs = Database::query($sql, __FILE__, __LINE__);
  65          $id_coach = Database::result($rs,0,'user_id');
  66  
  67          if (empty($nolimit)) {            
  68              $date_start="$year_start-".(($month_start < 10)?"0$month_start":$month_start)."-".(($day_start < 10)?"0$day_start":$day_start);
  69              $date_end="$year_end-".(($month_end < 10)?"0$month_end":$month_end)."-".(($day_end < 10)?"0$day_end":$day_end);
  70          } else {
  71              $id_visibility = 1; // by default is read only
  72              $date_start="000-00-00";
  73              $date_end="000-00-00";
  74          }
  75          if (empty($name)) {
  76              $msg=get_lang('SessionNameIsRequired');
  77              return $msg;
  78          } elseif (empty($coach_username))   {
  79              $msg=get_lang('CoachIsRequired');
  80              return $msg;
  81          } elseif (empty($nolimit) && (!$month_start || !$day_start || !$year_start || !checkdate($month_start,$day_start,$year_start))) {
  82              $msg=get_lang('InvalidStartDate');
  83              return $msg;
  84          } elseif (empty($nolimit) && (!$month_end || !$day_end || !$year_end || !checkdate($month_end,$day_end,$year_end))) {
  85              $msg=get_lang('InvalidEndDate');
  86              return $msg;
  87          } elseif(empty($nolimit) && $date_start >= $date_end) {
  88              $msg=get_lang('StartDateShouldBeBeforeEndDate');
  89              return $msg;
  90          } else {
  91              $rs = Database::query("SELECT 1 FROM $tbl_session WHERE name='".addslashes($name)."'");
  92              if(Database::num_rows($rs)) {
  93                  $msg=get_lang('SessionNameAlreadyExists');
  94                  return $msg;
  95              } else {
  96                  
  97                  $sql_insert = "INSERT INTO $tbl_session(name,description,date_start,date_end,id_coach,session_admin_id, session_category_id,max_seats)
  98                                 VALUES('".Database::escape_string($name)."','".Database::escape_string($description)."','$date_start','$date_end','$id_coach',".intval($_user['user_id']).", ".$id_session_category.", '".$max_seats."')";        
  99                  Database::query($sql_insert ,__FILE__,__LINE__);
 100                  $id_session=Database::insert_id();
 101  
 102                  // add event to system log
 103                  $time = time();
 104                  $user_id = api_get_user_id();
 105                  event_system(LOG_SESSION_CREATE, LOG_SESSION_ID, $id_session, $time, $user_id);
 106  
 107                  return $id_session;
 108              }
 109          }
 110      }
 111          
 112      /**
 113       * Edit a session
 114       * @author Carlos Vargas <carlos.vargas@dokeos.com>,from existing code
 115       * @param    integer        id
 116       * @param    string         name
 117       * @param     integer        year_start
 118       * @param     integer        month_start
 119       * @param     integer        day_start
 120       * @param     integer        year_end
 121       * @param     integer        month_end
 122       * @param     integer        day_end
 123       * @param     integer        nb_days_acess_before
 124       * @param     integer        nb_days_acess_after
 125       * @param     integer        nolimit
 126       * @param     integer        id_coach
 127       * @param     integer        id_session_category
 128       * @return $id;
 129       * The parameter id is a primary key
 130      **/
 131  	public static function edit_session ($id,$name,$description,$year_start,$month_start,$day_start,$year_end,$month_end,$day_end,$nolimit,$id_coach, $id_session_category, $max_seats = -1) {
 132          global $_user;
 133          $name=trim(stripslashes($name));
 134          $description=trim(stripslashes($description));
 135          $year_start=intval($year_start);
 136          $month_start=intval($month_start);
 137          $day_start=intval($day_start);
 138          $year_end=intval($year_end);
 139          $month_end=intval($month_end);
 140          $day_end=intval($day_end);
 141          $id_coach= intval($id_coach);
 142                  $max_seats = intval($max_seats);
 143  //        $nb_days_acess_before= intval($nb_days_acess_before);
 144  //        $nb_days_acess_after = intval($nb_days_acess_after);
 145          $id_session_category = intval($id_session_category);
 146  //        $id_visibility = intval($id_visibility);
 147  
 148          $tbl_user        = Database::get_main_table(TABLE_MAIN_USER);
 149          $tbl_session    = Database::get_main_table(TABLE_MAIN_SESSION);
 150          $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
 151  
 152  
 153          if (empty($nolimit)) {
 154              $date_start="$year_start-".(($month_start < 10)?"0$month_start":$month_start)."-".(($day_start < 10)?"0$day_start":$day_start);
 155              $date_end="$year_end-".(($month_end < 10)?"0$month_end":$month_end)."-".(($day_end < 10)?"0$day_end":$day_end);
 156          } else {
 157              $date_start="000-00-00";
 158              $date_end="000-00-00";
 159              $id_visibility = 1;//force read only
 160          }
 161          if (empty($name)) {
 162              $msg=get_lang('SessionNameIsRequired');
 163              return $msg;
 164          } elseif (empty($id_coach))   {
 165              $msg=get_lang('CoachIsRequired');
 166              return $msg;
 167          } elseif (empty($nolimit) && (!$month_start || !$day_start || !$year_start || !checkdate($month_start,$day_start,$year_start))) {
 168              $msg=get_lang('InvalidStartDate');
 169              return $msg;
 170          } elseif (empty($nolimit) && (!$month_end || !$day_end || !$year_end || !checkdate($month_end,$day_end,$year_end))) {
 171              $msg=get_lang('InvalidEndDate');
 172              return $msg;
 173          } elseif (empty($nolimit) && $date_start >= $date_end) {
 174              $msg=get_lang('StartDateShouldBeBeforeEndDate');
 175              return $msg;
 176          } else {
 177              $rs = Database::query("SELECT id FROM $tbl_session WHERE name='".Database::escape_string($name)."'");
 178              $exists = false;
 179              while ($row = Database::fetch_array($rs)) {
 180                  if($row['id']!=$id)
 181                      $exists = true;
 182              }
 183              if ($exists) {
 184                  $msg=get_lang('SessionNameAlreadyExists');
 185                  return $msg;
 186              } else {
 187                  $sql="UPDATE $tbl_session " .
 188                      "SET name='".Database::escape_string($name)."',
 189                       description='".Database::escape_string($description)."',
 190                          date_start='".$date_start."',
 191                          date_end='".$date_end."',
 192                          id_coach='".$id_coach."',                        
 193                          session_category_id = ".$id_session_category." ,
 194                          max_seats = ".$max_seats."
 195                        WHERE id='$id'";                  
 196                        
 197                  Database::query($sql,__FILE__,__LINE__);
 198                  /*$sqlu = "UPDATE $tbl_session_rel_course " .
 199                            " SET id_coach='$id_coach'" .
 200                            " WHERE id_session='$id'";
 201                  Database::query($sqlu,__FILE__,__LINE__);*/
 202                  return $id;
 203              }
 204          }
 205      }
 206      /**
 207       * Delete session
 208       * @author Carlos Vargas <carlos.vargas@dokeos.com>, from existing code
 209       * @param    array    id_checked
 210       * @param   boolean  optional, true if the function is called by a webservice, false otherwise.
 211       * @return    void    Nothing, or false on error
 212       * The parameters is a array to delete sessions
 213       **/
 214  	public static function delete_session ($id_checked,$from_ws = false) {
 215          $tbl_session=                        Database::get_main_table(TABLE_MAIN_SESSION);
 216          $tbl_session_rel_course=            Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
 217          $tbl_session_rel_course_rel_user=    Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
 218          $tbl_session_rel_user=                Database::get_main_table(TABLE_MAIN_SESSION_USER);
 219          $tbl_user =                         Database::get_main_table(TABLE_MAIN_USER);
 220                  
 221                  $tbl_session_rel_category = Database::get_main_table(TABLE_MAIN_SESSION_REL_CATEGORY);    
 222                  
 223          global $_user;
 224          if(is_array($id_checked)) {
 225              $id_checked=Database::escape_string(implode(',',$id_checked));
 226          } else {
 227              $id_checked=intval($id_checked);
 228          }
 229  
 230          if (!api_is_platform_admin() && !$from_ws) {
 231              $sql = 'SELECT session_admin_id FROM '.Database :: get_main_table(TABLE_MAIN_SESSION).' WHERE id='.$id_checked;
 232              $rs = Database::query($sql,__FILE__,__LINE__);
 233              if (Database::result($rs,0,0)!=$_user['user_id']) {
 234                  api_not_allowed(true);
 235              }
 236          }
 237          Database::query("DELETE FROM $tbl_session WHERE id IN($id_checked)",__FILE__,__LINE__);
 238          Database::query("DELETE FROM $tbl_session_rel_course WHERE id_session IN($id_checked)",__FILE__,__LINE__);
 239          Database::query("DELETE FROM $tbl_session_rel_course_rel_user WHERE id_session IN($id_checked)",__FILE__,__LINE__);
 240          Database::query("DELETE FROM $tbl_session_rel_user WHERE id_session IN($id_checked)",__FILE__,__LINE__);
 241                  
 242                  Database::query("DELETE FROM $tbl_session_rel_category WHERE session_id IN($id_checked)",__FILE__,__LINE__);
 243                  
 244                  $tbl_session_rel_category = Database::get_main_table(TABLE_MAIN_SESSION_REL_CATEGORY);
 245                  
 246                  // delete from session relation with category
 247                  $cat_exist = Database::query("SELECT * FROM $tbl_session_rel_category WHERE session_id IN($id_checked)");
 248                  if (Database::num_rows($cat_exist)) {
 249                      Database::query("DELETE FROM $tbl_session_rel_category WHERE session_id IN($id_checked)",__FILE__,__LINE__);
 250                  }
 251  
 252          // delete extra session fields
 253          $t_sf         = Database::get_main_table(TABLE_MAIN_SESSION_FIELD);
 254          $t_sfv         = Database::get_main_table(TABLE_MAIN_SESSION_FIELD_VALUES);
 255  
 256          // Delete extra fields from session where field variable is "SECCION"
 257          $sql = "SELECT t_sfv.field_id FROM $t_sfv t_sfv, $t_sf t_sf  WHERE t_sfv.session_id = '$id_checked' AND t_sf.field_variable = 'SECCION' ";
 258          $rs_field = Database::query($sql,__FILE__,__LINE__);
 259  
 260          $field_id = 0;
 261          if (Database::num_rows($rs_field) == 1) {
 262              $row_field = Database::fetch_row($rs_field);
 263              $field_id = $row_field[0];
 264  
 265              $sql_delete_sfv = "DELETE FROM $t_sfv WHERE session_id = '$id_checked' AND field_id = '$field_id'";
 266              $rs_delete_sfv = Database::query($sql_delete_sfv,__FILE__,__LINE__);
 267          }
 268  
 269          $sql = "SELECT * FROM $t_sfv WHERE field_id = '$field_id' ";
 270          $rs_field_id = Database::query($sql,__FILE__,__LINE__);
 271  
 272          if (Database::num_rows($rs_field_id) == 0) {
 273              $sql_delete_sf = "DELETE FROM $t_sf WHERE id = '$field_id'";
 274              $rs_delete_sf = Database::query($sql_delete_sf,__FILE__,__LINE__);
 275          }
 276  
 277          /*
 278          $sql = "SELECT distinct field_id FROM $t_sfv  WHERE session_id = '$id_checked'";
 279          $res_field_ids = @Database::query($sql,__FILE__,__LINE__);
 280  
 281          if (Database::num_rows($res_field_ids) > 0) {
 282              while($row_field_id = Database::fetch_row($res_field_ids)){
 283                  $field_ids[] = $row_field_id[0];
 284              }
 285          }
 286  
 287          //delete from table_session_field_value from a given session id
 288  
 289          $sql_session_field_value = "DELETE FROM $t_sfv WHERE session_id = '$id_checked'";
 290          @Database::query($sql_session_field_value,__FILE__,__LINE__);
 291  
 292          $sql = "SELECT distinct field_id FROM $t_sfv";
 293          $res_field_all_ids = @Database::query($sql,__FILE__,__LINE__);
 294  
 295          if (Database::num_rows($res_field_all_ids) > 0) {
 296              while($row_field_all_id = Database::fetch_row($res_field_all_ids)){
 297                  $field_all_ids[] = $row_field_all_id[0];
 298              }
 299          }
 300  
 301          if (count($field_ids) > 0 && count($field_all_ids) > 0) {
 302              foreach($field_ids as $field_id) {
 303                  // check if field id is used into table field value
 304                  if (in_array($field_id,$field_all_ids)) {
 305                      continue;
 306                  } else {
 307                      $sql_session_field = "DELETE FROM $t_sf WHERE id = '$field_id'";
 308                      Database::query($sql_session_field,__FILE__,__LINE__);
 309                  }
 310              }
 311          }
 312          */
 313          // add event to system log
 314          $time = time();
 315          $user_id = api_get_user_id();
 316          event_system(LOG_SESSION_DELETE, LOG_SESSION_ID, $id_checked, $time, $user_id);
 317  
 318      }
 319  
 320  
 321       /**
 322        * Subscribes users to the given session and optionally (default) unsubscribes previous users
 323        * @author Carlos Vargas <carlos.vargas@dokeos.com>,from existing code
 324        * @param    integer        Session ID
 325        * @param    array        List of user IDs
 326        * @param    bool        Whether to unsubscribe existing users (true, default) or not (false)
 327        * @return    void        Nothing, or false on error
 328        **/
 329  	public static function suscribe_users_to_session ($id_session,$user_list, $visibility=SESSION_VISIBLE_READ_ONLY, $empty_users=true, $send_email=false, $check_priority_list = array(), $course_list = null) {
 330  
 331            if ($id_session!= strval(intval($id_session))) return false;
 332             foreach($user_list as $intUser){
 333                 if ($intUser!= strval(intval($intUser))) return false;
 334             }
 335             $tbl_session_rel_course                = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
 336          $tbl_session_rel_course_rel_user    = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
 337             $tbl_session_rel_user                 = Database::get_main_table(TABLE_MAIN_SESSION_USER);
 338             $tbl_session                        = Database::get_main_table(TABLE_MAIN_SESSION);
 339          
 340          $session_info         = api_get_session_info($id_session);
 341          $session_name         = $session_info['name'];
 342          
 343          //from function parameter
 344          $session_visibility = $visibility;        
 345             if (empty($session_visibility)) {
 346                 $session_visibility = $session_info['name']; 
 347                 $session_visivility    = $session_info['visibility']; //loaded from DB
 348                 //default status loaded if empty
 349              if (empty($session_visivility))
 350                  $session_visibility = SESSION_VISIBLE_READ_ONLY; // by default readonly 1
 351             }
 352          $session_info = api_get_session_info($id_session);
 353          $session_name = $session_info['name'];
 354  
 355             $sql = "SELECT id_user FROM $tbl_session_rel_user WHERE id_session='$id_session'";
 356          $result = Database::query($sql,__FILE__,__LINE__);
 357          $existingUsers = array();
 358          while($row = Database::fetch_array($result)){
 359              $existingUsers[] = $row['id_user'];
 360          }
 361                  
 362                  if (!isset($course_list)) {                
 363                      $sql = "SELECT course_code FROM $tbl_session_rel_course WHERE id_session='$id_session'";
 364                      $result=Database::query($sql,__FILE__,__LINE__);
 365                      $course_list=array();
 366                      while($row=Database::fetch_array($result)) {
 367                              $course_list[]=$row['course_code'];
 368                      }        
 369                  }
 370          
 371          if ($send_email == true) {
 372              global $_configuration;
 373              //sending emails only
 374              if(is_array($user_list) && count($user_list)>0) {            
 375                  foreach($user_list as $enreg_user) {                
 376                      if (!in_array($enreg_user,$existingUsers )) {
 377                          //send email                             
 378                          $emailbody     = '';
 379                          $emailheaders = '';
 380                          
 381                          $user_info     = UserManager::get_user_info_by_id($enreg_user);                
 382                          $firstname     = $user_info['firstname'];
 383                          $lastname     = $user_info['lastname'];
 384                          $email         = $user_info['email'];
 385                          
 386                          $emailto = '"'.$firstname.' '.$lastname.'" <'.$email.'>';
 387                          $emailsubject = '['.get_setting('siteName').'] '.get_lang('YourReg').' '.get_setting('siteName');
 388                          $emailheaders = 'From: '.get_setting('administratorName').' '.get_setting('administratorSurname').' <'.get_setting('emailAdministrator').">\n";
 389                          $emailheaders .= 'Reply-To: '.get_setting('emailAdministrator');
 390  
 391                          if ($_configuration['multiple_access_urls']==true) {
 392                              $access_url_id = api_get_current_access_url_id();
 393                              if ($access_url_id != -1 ){
 394                                  $url         = api_get_access_url($access_url_id);                                
 395                                  $emailbody    = get_lang('Dear')." ".stripslashes(api_get_person_name($firstname, $lastname)).",\n\n".get_lang('YouAreRegisterToSession')." : ". $session_name  ." \n\n" .get_lang('Address') ." ". get_setting('siteName') ." ". get_lang('Is') ." : ". $url['url'] ."\n\n". get_lang('Problem'). "\n\n". get_lang('Formula').",\n\n".get_setting('administratorName')." ".get_setting('administratorSurname')."\n". get_lang('Manager'). " ".get_setting('siteName')."\nT. ".get_setting('administratorTelephone')."\n" .get_lang('Email') ." : ".get_setting('emailAdministrator');                            
 396                              }
 397                          } else {
 398                              $emailbody    = get_lang('Dear')." ".stripslashes(api_get_person_name($firstname, $lastname)).",\n\n".get_lang('YouAreRegisterToSession')." : ". $session_name ." \n\n" .get_lang('Address') ." ". get_setting('siteName') ." ". get_lang('Is') ." : ". $_configuration['root_web'] ."\n\n". get_lang('Problem'). "\n\n". get_lang('Formula').",\n\n".get_setting('administratorName')." ".get_setting('administratorSurname')."\n". get_lang('Manager'). " ".get_setting('siteName')."\nT. ".get_setting('administratorTelephone')."\n" .get_lang('Email') ." : ".get_setting('emailAdministrator');
 399                          }
 400                          
 401                          @api_send_mail($emailto, $emailsubject, $emailbody, $emailheaders);
 402                          
 403                      }
 404                  }
 405              }        
 406          }
 407  
 408          foreach ($course_list as $enreg_course) {
 409              // for each course in the session
 410              $nbr_users=0;
 411              $enreg_course = Database::escape_string($enreg_course);
 412                  // delete existing users
 413              if ($empty_users!==false) {
 414                  foreach ($existingUsers as $existing_user) {
 415                      if(!in_array($existing_user, $user_list)) {
 416                          $sql = "DELETE FROM $tbl_session_rel_course_rel_user WHERE id_session='$id_session' AND course_code='$enreg_course' AND id_user='$existing_user' AND status != 2 ";
 417                          Database::query($sql,__FILE__,__LINE__);
 418                          if(Database::affected_rows()) {
 419                              $nbr_users--;
 420                          }
 421                      }
 422                  }
 423              }
 424              // insert new users into session_rel_course_rel_user and ignore if they already exist
 425              foreach ($user_list as $enreg_user) {
 426                  if(!in_array($enreg_user, $existingUsers)) {                    
 427                              $enreg_user = Database::escape_string($enreg_user);
 428                              $insert_sql = "INSERT IGNORE INTO $tbl_session_rel_course_rel_user(id_session,course_code,id_user,visibility) VALUES('$id_session','$enreg_course','$enreg_user','$session_visivility')";
 429                              Database::query($insert_sql,__FILE__,__LINE__);
 430                              if(Database::affected_rows()) {
 431                                  $nbr_users++;
 432                              }
 433                          /*    foreach ($check_priority_list as $each_priority_info) {
 434                                  if ($each_priority_info[1] == $enreg_course && $each_priority_info[0] == $id_session) {
 435                                      $insert_sql = "INSERT IGNORE INTO $tbl_session_rel_course_rel_user(id_session,course_code,id_user,visibility) VALUES('$id_session','$enreg_course','$enreg_user','$session_visivility')";
 436                                      Database::query($insert_sql,__FILE__,__LINE__);
 437                                      if(Database::affected_rows()) {
 438                                              $nbr_users++;
 439                                      }
 440                                  }                    
 441                              }*/
 442                  }
 443              }
 444              // count users in this session-course relation
 445              $sql = "SELECT COUNT(id_user) as nbUsers FROM $tbl_session_rel_course_rel_user WHERE id_session='$id_session' AND course_code='$enreg_course'";
 446              $rs = Database::query($sql, __FILE__, __LINE__);
 447              list($nbr_users) = Database::fetch_array($rs);
 448              // update the session-course relation to add the users total
 449              $update_sql = "UPDATE $tbl_session_rel_course SET nbr_users=$nbr_users WHERE id_session='$id_session' AND course_code='$enreg_course'";
 450              Database::query($update_sql,__FILE__,__LINE__);
 451          }
 452          // delete users from the session
 453          if ($empty_users===true){
 454              Database::query("DELETE FROM $tbl_session_rel_user WHERE id_session = $id_session",__FILE__,__LINE__);
 455          }
 456              // insert missing users into session
 457          $nbr_users = 0;
 458          foreach ($user_list as $enreg_user) {
 459              $enreg_user = Database::escape_string($enreg_user);
 460              $nbr_users++;
 461              $insert_sql = "INSERT IGNORE INTO $tbl_session_rel_user(id_session, id_user) VALUES('$id_session','$enreg_user')";
 462              Database::query($insert_sql,__FILE__,__LINE__);
 463          }
 464          // update number of users in the session
 465          $nbr_users = count($user_list);
 466          $update_sql = "UPDATE $tbl_session SET nbr_users= $nbr_users WHERE id='$id_session' ";
 467          Database::query($update_sql,__FILE__,__LINE__);
 468      }
 469          
 470      /** Subscribes courses to the given session and optionally (default) unsubscribes previous users
 471       * @author Carlos Vargas <carlos.vargas@dokeos.com>,from existing code
 472       * @param    int        Session ID
 473       * @param    array    List of courses IDs
 474       * @param    bool    Whether to unsubscribe existing users (true, default) or not (false)
 475       * @return    void    Nothing, or false on error
 476       **/
 477       public static function add_courses_to_session ($id_session, $course_list, $empty_courses=true) {
 478           // security checks
 479           if ($id_session!= strval(intval($id_session))) { return false; }
 480             foreach($course_list as $intCourse){
 481                 if ($intCourse!= strval(intval($intCourse))) { return false; }
 482             }
 483             // initialisation
 484          $tbl_session_rel_course_rel_user    = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
 485          $tbl_session                        = Database::get_main_table(TABLE_MAIN_SESSION);
 486          $tbl_session_rel_user                = Database::get_main_table(TABLE_MAIN_SESSION_USER);
 487          $tbl_session_rel_course                = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
 488          $tbl_course                            = Database::get_main_table(TABLE_MAIN_COURSE);
 489           // get general coach ID
 490          $id_coach = Database::query("SELECT id_coach FROM $tbl_session WHERE id=$id_session");
 491          $id_coach = Database::fetch_array($id_coach);
 492          $id_coach = $id_coach[0];
 493          // get list of courses subscribed to this session
 494          $rs = Database::query("SELECT course_code FROM $tbl_session_rel_course WHERE id_session=$id_session");
 495          $existingCourses = Database::store_result($rs);
 496          $nbr_courses=count($existingCourses);
 497          // get list of users subscribed to this session
 498          $sql="SELECT id_user
 499              FROM $tbl_session_rel_user
 500              WHERE id_session = $id_session";
 501          $result=Database::query($sql,__FILE__,__LINE__);
 502          $user_list=Database::store_result($result);
 503  
 504          // remove existing courses from the session
 505          if ($empty_courses===true) {
 506              foreach ($existingCourses as $existingCourse) {
 507                  if (!in_array($existingCourse['course_code'], $course_list)){
 508                      Database::query("DELETE FROM $tbl_session_rel_course WHERE course_code='".$existingCourse['course_code']."' AND id_session=$id_session");
 509                      Database::query("DELETE FROM $tbl_session_rel_course_rel_user WHERE course_code='".$existingCourse['course_code']."' AND id_session=$id_session");
 510  
 511                  }
 512              }
 513              $nbr_courses=0;
 514          }
 515  
 516          // Pass through the courses list we want to add to the session
 517          foreach ($course_list as $enreg_course) {
 518              $enreg_course = Database::escape_string($enreg_course);
 519              $exists = false;
 520              // check if the course we want to add is already subscribed
 521              foreach ($existingCourses as $existingCourse) {
 522                  if ($enreg_course == $existingCourse['course_code']) {
 523                      $exists=true;
 524                  }
 525              }
 526              if (!$exists) {
 527                  //if the course isn't subscribed yet
 528                  $sql_insert_rel_course= "INSERT INTO $tbl_session_rel_course (id_session,course_code) VALUES ('$id_session','$enreg_course')";
 529                  Database::query($sql_insert_rel_course ,__FILE__,__LINE__);
 530                  //We add the current course in the existing courses array, to avoid adding another time the current course
 531                  $existingCourses[]=array('course_code'=>$enreg_course);
 532                  $nbr_courses++;
 533  
 534                  // subscribe all the users from the session to this course inside the session
 535                  $nbr_users=0;
 536                  foreach ($user_list as $enreg_user) {
 537                      $enreg_user_id = Database::escape_string($enreg_user['id_user']);
 538                      $sql_insert = "INSERT IGNORE INTO $tbl_session_rel_course_rel_user (id_session,course_code,id_user) VALUES ('$id_session','$enreg_course','$enreg_user_id')";
 539                      Database::query($sql_insert,__FILE__,__LINE__);
 540                      if (Database::affected_rows()) {
 541                          $nbr_users++;
 542                      }
 543                  }
 544                  Database::query("UPDATE $tbl_session_rel_course SET nbr_users=$nbr_users WHERE id_session='$id_session' AND course_code='$enreg_course'",__FILE__,__LINE__);
 545              }
 546          }
 547          Database::query("UPDATE $tbl_session SET nbr_courses=$nbr_courses WHERE id='$id_session'",__FILE__,__LINE__);
 548       }
 549  
 550    /**
 551    * Creates a new extra field for a given session
 552    * @param    string    Field's internal variable name
 553    * @param    int        Field's type
 554    * @param    string    Field's language var name
 555    * @return int     new extra field id
 556    */
 557  	public static function create_session_extra_field ($fieldvarname, $fieldtype, $fieldtitle) {
 558          // database table definition
 559          $t_sf             = Database::get_main_table(TABLE_MAIN_SESSION_FIELD);
 560          $fieldvarname     = Database::escape_string($fieldvarname);
 561          $fieldtitle     = Database::escape_string($fieldtitle);
 562          $fieldtype = (int)$fieldtype;
 563          $time = time();
 564          $sql_field = "SELECT id FROM $t_sf WHERE field_variable = '$fieldvarname'";
 565          $res_field = Database::query($sql_field,__FILE__,__LINE__);
 566  
 567          $r_field = Database::fetch_row($res_field);
 568  
 569          if (Database::num_rows($res_field)>0) {
 570              $field_id = $r_field[0];
 571          } else {
 572              // save new fieldlabel into course_field table
 573              $sql = "SELECT MAX(field_order) FROM $t_sf";
 574              $res = Database::query($sql,__FILE__,__LINE__);
 575  
 576              $order = 0;
 577              if (Database::num_rows($res)>0) {
 578                  $row = Database::fetch_row($res);
 579                  $order = $row[0]+1;
 580              }
 581  
 582              $sql = "INSERT INTO $t_sf
 583                                          SET field_type = '$fieldtype',
 584                                          field_variable = '$fieldvarname',
 585                                          field_display_text = '$fieldtitle',
 586                                          field_order = '$order',
 587                                          tms = FROM_UNIXTIME($time)";
 588              $result = Database::query($sql,__FILE__,__LINE__);
 589  
 590              $field_id=Database::insert_id();
 591          }
 592          return $field_id;
 593      }
 594  
 595  /**
 596   * Update an extra field value for a given session
 597   * @param    integer    Course ID
 598   * @param    string    Field variable name
 599   * @param    string    Field value
 600   * @return    boolean    true if field updated, false otherwise
 601   */
 602  	public static function update_session_extra_field_value ($session_id,$fname,$fvalue='') {
 603  
 604          $t_sf             = Database::get_main_table(TABLE_MAIN_SESSION_FIELD);
 605          $t_sfv             = Database::get_main_table(TABLE_MAIN_SESSION_FIELD_VALUES);
 606          $fname = Database::escape_string($fname);
 607          $session_id = (int)$session_id;
 608          $fvalues = '';
 609          if(is_array($fvalue))
 610          {
 611              foreach($fvalue as $val)
 612              {
 613                  $fvalues .= Database::escape_string($val).';';
 614              }
 615              if(!empty($fvalues))
 616              {
 617                  $fvalues = substr($fvalues,0,-1);
 618              }
 619          }
 620          else
 621          {
 622              $fvalues = Database::escape_string($fvalue);
 623          }
 624  
 625          $sqlsf = "SELECT * FROM $t_sf WHERE field_variable='$fname'";
 626          $ressf = Database::query($sqlsf,__FILE__,__LINE__);
 627          if(Database::num_rows($ressf)==1)
 628          { //ok, the field exists
 629              //    Check if enumerated field, if the option is available
 630              $rowsf = Database::fetch_array($ressf);
 631  
 632              $tms = time();
 633              $sqlsfv = "SELECT * FROM $t_sfv WHERE session_id = '$session_id' AND field_id = '".$rowsf['id']."' ORDER BY id";
 634              $ressfv = Database::query($sqlsfv,__FILE__,__LINE__);
 635              $n = Database::num_rows($ressfv);
 636              if ($n>1) {
 637                  //problem, we already have to values for this field and user combination - keep last one
 638                  while($rowsfv = Database::fetch_array($ressfv))
 639                  {
 640                      if($n > 1)
 641                      {
 642                          $sqld = "DELETE FROM $t_sfv WHERE id = ".$rowsfv['id'];
 643                          $resd = Database::query($sqld,__FILE__,__LINE__);
 644                          $n--;
 645                      }
 646                      $rowsfv = Database::fetch_array($ressfv);
 647                      if($rowsfv['field_value'] != $fvalues)
 648                      {
 649                          $sqlu = "UPDATE $t_sfv SET field_value = '$fvalues', tms = FROM_UNIXTIME($tms) WHERE id = ".$rowsfv['id'];
 650                          $resu = Database::query($sqlu,__FILE__,__LINE__);
 651                          return($resu?true:false);
 652                      }
 653                      return true;
 654                  }
 655              } else if ($n==1) {
 656                  //we need to update the current record
 657                  $rowsfv = Database::fetch_array($ressfv);
 658                  if($rowsfv['field_value'] != $fvalues)
 659                  {
 660                      $sqlu = "UPDATE $t_sfv SET field_value = '$fvalues', tms = FROM_UNIXTIME($tms) WHERE id = ".$rowsfv['id'];
 661                      //error_log('UM::update_extra_field_value: '.$sqlu);
 662                      $resu = Database::query($sqlu,__FILE__,__LINE__);
 663                      return($resu?true:false);
 664                  }
 665                  return true;
 666              } else {
 667                  $sqli = "INSERT INTO $t_sfv (session_id,field_id,field_value,tms) " .
 668                      "VALUES ('$session_id',".$rowsf['id'].",'$fvalues',FROM_UNIXTIME($tms))";
 669                  //error_log('UM::update_extra_field_value: '.$sqli);
 670                  $resi = Database::query($sqli,__FILE__,__LINE__);
 671                  return($resi?true:false);
 672              }
 673          } else {
 674              return false; //field not found
 675          }
 676      }
 677  
 678      /**
 679      * Checks the relationship between a session and a course.
 680      * @param int $session_id
 681      * @param int $course_id
 682      * @return bool                Returns TRUE if the session and the course are related, FALSE otherwise.
 683      * */
 684  	public static function relation_session_course_exist ($session_id, $course_id) {
 685          $tbl_session_course    = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
 686          $return_value = false;
 687          $sql= "SELECT course_code FROM $tbl_session_course WHERE id_session = ".Database::escape_string($session_id)." AND course_code = '".Database::escape_string($course_id)."'";
 688          $result = Database::query($sql,  __FILE__, __LINE__);
 689          $num = Database::num_rows($result);
 690          if ($num>0) {
 691              $return_value = true;
 692          }
 693          return $return_value;
 694      }
 695  
 696      /**
 697      * Get the session information by name
 698      * @param string session name
 699      * @return mixed false if the session does not exist, array if the session exist
 700      * */
 701  	public static function get_session_by_name ($session_name) {
 702          $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
 703          $sql = 'SELECT id, id_coach, date_start, date_end FROM '.$tbl_session.' WHERE name="'.Database::escape_string($session_name).'"';
 704          $result = Database::query($sql,  __FILE__, __LINE__);
 705          $num = Database::num_rows($result);
 706          if ($num>0){
 707              return Database::fetch_array($result);
 708          } else {
 709              return false;
 710          }
 711      }
 712  
 713      /**
 714        * Create a session category
 715        * @author Jhon Hinojosa <jhon.hinojosa@dokeos.com>, from existing code
 716        * @param    string         name
 717        * @param     integer        year_start
 718        * @param     integer        month_start
 719        * @param     integer        day_start
 720        * @param     integer        year_end
 721        * @param     integer        month_end
 722        * @param     integer        day_end
 723        * @return $id_session;
 724        **/
 725  	public static function create_category_session ($sname,$sdescription,$syear_start,$smonth_start,$sday_start,$syear_end,$smonth_end, $sday_end, $cost = 0, $method_payment = '', $code = '') {
 726              $tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
 727              $name= trim($sname);
 728              $description = trim($sdescription);
 729              $year_start = intval($syear_start);
 730              $month_start=intval($smonth_start);
 731              $day_start=intval($sday_start);
 732              $year_end=intval($syear_end);
 733              $month_end=intval($smonth_end);
 734              $day_end=intval($sday_end);
 735  
 736              $date_start = "$year_start-".(($month_start < 10)?"0$month_start":$month_start)."-".(($day_start < 10)?"0$day_start":$day_start);
 737              $date_end = "$year_end-".(($month_end < 10)?"0$month_end":$month_end)."-".(($day_end < 10)?"0$day_end":$day_end);
 738  
 739              if (empty($name)) {
 740                  $msg=get_lang('SessionCategoryNameIsRequired');
 741                  return $msg;
 742              } elseif (!$month_start || !$day_start || !$year_start || !checkdate($month_start,$day_start,$year_start)) {
 743                  $msg=get_lang('InvalidStartDate');
 744                  return $msg;
 745              } elseif (!$month_end || !$day_end || !$year_end || !checkdate($month_end,$day_end,$year_end)) {
 746                  $msg=get_lang('InvalidEndDate');
 747                  return $msg;
 748              } elseif($date_start >= $date_end) {
 749                  $msg=get_lang('StartDateShouldBeBeforeEndDate');
 750                  return $msg;
 751              } else {
 752                  $sql = "INSERT INTO $tbl_session_category(name, description, date_start, date_end, cost, method_payment, code) VALUES('".Database::escape_string($name)."','".Database::escape_string($description)."','$date_start','$date_end', '$cost', '".Database::escape_string($method_payment)."', '".Database::escape_string($code)."')";
 753                  Database::query($sql ,__FILE__,__LINE__);
 754                  $id_session=Database::insert_id();
 755                  // add event to system log
 756                  $time = time();
 757                  $user_id = api_get_user_id();
 758                  event_system(LOG_SESSION_CATEGORY_CREATE, LOG_SESSION_CATEGORY_ID, $id_session, $time, $user_id);
 759                  return $id_session;
 760              }
 761      }
 762  
 763      /**
 764       * Edit a sessions categories
 765       * @author Jhon Hinojosa <jhon.hinojosa@dokeos.com>,from existing code
 766       * @param    integer        id
 767       * @param    string         name
 768       * @param     integer        year_start
 769       * @param     integer        month_start
 770       * @param     integer        day_start
 771       * @param     integer        year_end
 772       * @param     integer        month_end
 773       * @param     integer        day_end
 774       * @return $id;
 775       * The parameter id is a primary key
 776      **/
 777  	public static function edit_category_session($id, $sname, $sdescription, $syear_start,$smonth_start,$sday_start,$syear_end,$smonth_end, $sday_end, $cost = 0, $method_payment = '', $code = ''){
 778          $tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
 779          $name= trim($sname);
 780          $description= trim($sdescription);
 781          $year_start= intval($syear_start);
 782          $month_start=intval($smonth_start);
 783          $day_start=intval($sday_start);
 784          $year_end=intval($syear_end);
 785          $month_end=intval($smonth_end);
 786          $day_end=intval($sday_end);
 787          $id=intval($id);
 788          $date_start = "$year_start-".(($month_start < 10)?"0$month_start":$month_start)."-".(($day_start < 10)?"0$day_start":$day_start);
 789          $date_end = "$year_end-".(($month_end < 10)?"0$month_end":$month_end)."-".(($day_end < 10)?"0$day_end":$day_end);
 790  
 791          if (empty($name)) {
 792              $msg=get_lang('SessionCategoryNameIsRequired');
 793              return $msg;
 794          } elseif (!$month_start || !$day_start || !$year_start || !checkdate($month_start,$day_start,$year_start)) {
 795              $msg=get_lang('InvalidStartDate');
 796              return $msg;
 797          } elseif (!$month_end || !$day_end || !$year_end || !checkdate($month_end,$day_end,$year_end)) {
 798              $msg=get_lang('InvalidEndDate');
 799              return $msg;
 800          } elseif($date_start >= $date_end) {
 801              $msg=get_lang('StartDateShouldBeBeforeEndDate');
 802              return $msg;
 803          } else {
 804              $sql = "UPDATE $tbl_session_category SET 
 805                                   name = '".Database::escape_string($name)."', 
 806                                   description = '".Database::escape_string($description)."', 
 807                                   date_start = '$date_start', 
 808                                   date_end = '$date_end', 
 809                                   cost = '$cost', 
 810                                   method_payment = '".Database::escape_string($method_payment)."',
 811                                   code = '".Database::escape_string($code)."'
 812                                  WHERE id= '".$id."' ";
 813              $result = Database::query($sql, __FILE__,__LINE__);
 814              return ($result? true:false);
 815          }
 816      }
 817  
 818      /**
 819       * Delete sessions categories
 820       * @author Jhon Hinojosa <jhon.hinojosa@dokeos.com>, from existing code
 821       * @param    array    id_checked
 822       * @param    bool    include delete session
 823       * @param    bool    optional, true if the function is called by a webservice, false otherwise.
 824       * @return    void    Nothing, or false on error
 825       * The parameters is a array to delete sessions
 826       **/
 827  	public static function delete_session_category($id_checked, $delete_session = false,$from_ws = false){
 828          $tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
 829          $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
 830          if(is_array($id_checked)) {
 831              $id_checked=Database::escape_string(implode(',',$id_checked));
 832          } else {
 833              $id_checked=intval($id_checked);
 834          }
 835          $sql = "SELECT id FROM $tbl_session WHERE session_category_id IN (".$id_checked.")";
 836          $result = @Database::query($sql,__FILE__,__LINE__);
 837          while ($rows = Database::fetch_array($result)) {
 838              $session_id = $rows['id'];
 839              if($delete_session == true){
 840                  if ($from_ws) {
 841                      SessionManager::delete_session($session_id,true);
 842                  } else {
 843                      SessionManager::delete_session($session_id);
 844                  }
 845              }
 846          }
 847          $sql = "DELETE FROM $tbl_session_category WHERE id IN (".$id_checked.")";
 848          $rs = @Database::query($sql,__FILE__,__LINE__);
 849          $result = Database::affected_rows();
 850  
 851          // add event to system log
 852          $time = time();
 853          $user_id = api_get_user_id();
 854          event_system(LOG_SESSION_CATEGORY_DELETE, LOG_SESSION_CATEGORY_ID, $id_checked, $time, $user_id);
 855  
 856  
 857          // delete extra session fields where field variable is "PERIODO"
 858          $t_sf         = Database::get_main_table(TABLE_MAIN_SESSION_FIELD);
 859          $t_sfv         = Database::get_main_table(TABLE_MAIN_SESSION_FIELD_VALUES);
 860  
 861          $sql = "SELECT t_sfv.field_id FROM $t_sfv t_sfv, $t_sf t_sf  WHERE t_sfv.session_id = '$id_checked' AND t_sf.field_variable = 'PERIODO' ";
 862          $rs_field = Database::query($sql,__FILE__,__LINE__);
 863  
 864          $field_id = 0;
 865          if (Database::num_rows($rs_field) > 0) {
 866              $row_field = Database::fetch_row($rs_field);
 867              $field_id = $row_field[0];
 868              $sql_delete_sfv = "DELETE FROM $t_sfv WHERE session_id = '$id_checked' AND field_id = '$field_id'";
 869              $rs_delete_sfv = Database::query($sql_delete_sfv,__FILE__,__LINE__);
 870          }
 871  
 872          $sql = "SELECT * FROM $t_sfv WHERE field_id = '$field_id' ";
 873          $rs_field_id = Database::query($sql,__FILE__,__LINE__);
 874  
 875          if (Database::num_rows($rs_field_id) == 0) {
 876              $sql_delete_sf = "DELETE FROM $t_sf WHERE id = '$field_id'";
 877              $rs_delete_sf = Database::query($sql_delete_sf,__FILE__,__LINE__);
 878          }
 879  
 880          return true;
 881      }
 882  
 883          /**
 884           * 
 885           */
 886          public static function get_sessions_rel_category($category_id) {            
 887              $tbl_sess_rel_cat = Database::get_main_table(TABLE_MAIN_SESSION_REL_CATEGORY);
 888              $sessions = array();
 889              $rs = Database::query("SELECT session_id FROM $tbl_sess_rel_cat WHERE category_id = $category_id");
 890              if (Database::num_rows($rs) > 0) {
 891                  while ($row = Database::fetch_object($rs)) {
 892                      $sessions[] = api_get_session_info($row->session_id);
 893                  }
 894              }
 895              return $sessions;
 896          }
 897          
 898      /**
 899       * Get a list of sessions of which the given conditions match with an = 'cond'
 900       * @param array $conditions a list of condition (exemple : status=>STUDENT)
 901       * @param array $order_by a list of fields on which sort
 902       * @return array An array with all sessions of the platform.
 903       * @todo optional course code parameter, optional sorting parameters...
 904      */
 905  	public static function get_sessions_list ($conditions = array(), $order_by = array()) {
 906  
 907          $session_table =Database::get_main_table(TABLE_MAIN_SESSION);
 908          $session_category_table = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
 909          $user_table = Database::get_main_table(TABLE_MAIN_USER);
 910  
 911          $return_array = array();
 912  
 913          $sql_query = " SELECT s.id, s.name, s.nbr_courses,s.nbr_users,s.max_seats, s.date_start, s.date_end, u.firstname, u.lastname , sc.name as category_name
 914                  FROM $session_table s
 915                  INNER JOIN $user_table u ON s.id_coach = u.user_id
 916                  LEFT JOIN  $session_category_table sc ON s.session_category_id = sc.id ";
 917  
 918          if (count($conditions)>0) {
 919              $sql_query .= ' WHERE ';
 920              foreach ($conditions as $field=>$value) {
 921                  $field = Database::escape_string($field);
 922                  $value = Database::escape_string($value);
 923                  $sql_query .= $field.' = '.$value;
 924              }
 925          }
 926          if (count($order_by)>0) {
 927              $sql_query .= ' ORDER BY '.Database::escape_string(implode(',',$order_by));
 928          }
 929  
 930          $sql_result = Database::query($sql_query,__FILE__,__LINE__);
 931          while ($result = Database::fetch_array($sql_result)) {
 932              $return_array[] = $result;
 933          }
 934          return $return_array;
 935      }
 936      /**
 937       * Get the session category information by id
 938       * @param string session category ID
 939       * @return mixed false if the session category does not exist, array if the session category exists
 940       */
 941  	public static function get_session_category ($id) {
 942          $id = intval($id);
 943          $tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
 944          $sql = 'SELECT * FROM '.$tbl_session_category.' WHERE id="'.$id.'"';
 945          $result = Database::query($sql,  __FILE__, __LINE__);
 946          $num = Database::num_rows($result);
 947          if ($num>0){
 948              return Database::fetch_array($result);
 949          } else {
 950              return false;
 951          }
 952      }
 953  
 954           /**
 955            * Gets the training sessions of an user
 956            * @param integer $user_id
 957            * @return array
 958            */
 959           public static function get_training_sessions_of_an_user_by_user_id ($user_id) {
 960                           $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
 961                           $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
 962  
 963             $sql = "SELECT s.id,s.name,s.date_start,s.date_end FROM $tbl_session s
 964              INNER JOIN $tbl_session_rel_user sru ON s.id = sru.id_session WHERE sru.id_user='".Database::escape_string($user_id)."'";
 965             $rs = Database::query($sql, __FILE__, __LINE__);
 966             $row = Database::fetch_array($rs, 'ASSOC');
 967  
 968             return $row;
 969           }
 970           
 971      /**
 972       * Assign a coach to course in session with status = 2
 973       * @param int          - user id
 974       * @param int          - session id
 975       * @param string      - course code
 976       * @param bool      - optional, if is true the user don't be a coach now, otherwise it'll assign a coach
 977       * @return bool true if there are affected rows, otherwise false
 978       */
 979  	function set_coach_to_course_session($user_id, $session_id = 0, $course_code = '',$nocoach = false) {
 980  
 981          // Definition of variables
 982          $user_id = intval($user_id);
 983  
 984          if (!empty($session_id)) {
 985              $session_id = intval($session_id);
 986          } else {
 987              $session_id = api_get_session_id();
 988          }
 989  
 990          if (!empty($course_code)) {
 991              $course_code = Database::escape_string($course_code);
 992          } else {
 993              $course_code = api_get_course_id();
 994          }
 995  
 996          // definitios of tables
 997          $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
 998          $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
 999          $tbl_user    = Database::get_main_table(TABLE_MAIN_USER);
1000  
1001          // check if user is a teacher
1002          $sql= "SELECT * FROM $tbl_user WHERE status='1' AND user_id = '$user_id'";
1003  
1004          $rs_check_user = Database::query($sql,__FILE__,__LINE__);
1005  
1006          if (Database::num_rows($rs_check_user) > 0) {
1007  
1008              if ($nocoach) {
1009                  // check if user_id exits int session_rel_user
1010                  $sql = "SELECT id_user FROM $tbl_session_rel_user WHERE id_session = '$session_id' AND id_user = '$user_id'";
1011                  $res = Database::query($sql,__FILE__,__LINE__);
1012  
1013                  if (Database::num_rows($res) > 0) {
1014                      // The user don't be a coach now
1015                      $sql = "UPDATE $tbl_session_rel_course_rel_user SET status = 0 WHERE id_session = '$session_id' AND course_code = '$course_code' AND id_user = '$user_id' ";
1016                      $rs_update = Database::query($sql,__FILE__,__LINE__);
1017                      if (Database::affected_rows() > 0) return true;
1018                      else return false;
1019                  } else {
1020                      // The user don't be a coach now
1021                      $sql = "DELETE FROM $tbl_session_rel_course_rel_user WHERE id_session = '$session_id' AND course_code = '$course_code' AND id_user = '$user_id' ";
1022                      $rs_delete = Database::query($sql,__FILE__,__LINE__);
1023                      if (Database::affected_rows() > 0) return true;
1024                      else return false;
1025                  }
1026  
1027              } else {
1028                  // Assign user like a coach to course
1029                  // First check if the user is registered in the course
1030                  $sql = "SELECT id_user FROM $tbl_session_rel_course_rel_user WHERE id_session = '$session_id' AND course_code = '$course_code' AND id_user = '$user_id'";
1031                  $rs_check = Database::query($sql,__FILE__,__LINE__);
1032  
1033                  //Then update or insert
1034                  if (Database::num_rows($rs_check) > 0) {
1035                      $sql = "UPDATE $tbl_session_rel_course_rel_user SET status = 2 WHERE id_session = '$session_id' AND course_code = '$course_code' AND id_user = '$user_id' ";
1036                      $rs_update = Database::query($sql,__FILE__,__LINE__);
1037                      if (Database::affected_rows() > 0) return true;
1038                      else return false;
1039                  } else {
1040                      $sql = " INSERT INTO $tbl_session_rel_course_rel_user(id_session, course_code, id_user, status) VALUES('$session_id', '$course_code', '$user_id', 2)";
1041                      $rs_insert = Database::query($sql,__FILE__,__LINE__);
1042                      if (Database::affected_rows() > 0) return true;
1043                      else return false;
1044                  }
1045              }
1046          } else {
1047              return false;
1048          }
1049      }
1050      
1051      
1052  	public static function is_course_in_session_coach($id_user, $course_code){
1053          
1054          //Check if session_coach
1055          $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
1056          $tbl_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
1057          
1058          $sql = 'SELECT id_session FROM '.$tbl_session_rel_course.' WHERE course_code="'.$course_code.'"';
1059          $res = Database::query($sql,__FILE__,__LINE__);
1060          $sessions_id = array();
1061          if (Database::num_rows($res) > 0) {
1062              while ($result_row = Database::fetch_array($res)) {
1063                  array_push($sessions_id, $result_row['id_session']);
1064              }
1065          }
1066          if(count($sessions_id)>0){
1067              foreach($sessions_id as $id_session){
1068                  if(SessionManager::is_session_coach($id_user, $id_session)){
1069                      return true;
1070                  }
1071              }
1072          }
1073          
1074          //Check if the user is a training coach in a session for this course
1075          $sql = 'SELECT id_session FROM '.$tbl_session_course_user.' WHERE course_code="'.$course_code.'" AND id_user="'.$id_user.'" AND status="2"';
1076          $res = Database::query($sql,__FILE__,__LINE__);
1077          if (Database::num_rows($res) > 0) {
1078              return true;
1079          }
1080          
1081          return false;
1082          
1083      }
1084      
1085      
1086  	public static function is_session_coach($user_id, $session_id){
1087          
1088          $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
1089          $sql = 'SELECT id_coach FROM '.$tbl_session.' WHERE id="'.$session_id.'"';
1090          $res = Database::query($sql,__FILE__,__LINE__);
1091          if(mysql_result($res, 0, 'id_coach') == $user_id){
1092              return true;
1093          }
1094          return false;
1095          
1096      }
1097   
1098          public static function get_course_list_by_session_id ($session_id) {
1099              $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
1100              $course_list = array();
1101              $sql = "SELECT course_code FROM $tbl_session_rel_course WHERE id_session='".Database::escape_string($session_id)."'";
1102              $rs = Database::query($sql,__FILE__,__LINE__);
1103              while ($row = Database::fetch_array($rs)) {
1104                  $course_list[] = $row['course_code'];
1105              }
1106              return $course_list;
1107          }
1108          
1109          function get_session_priority_record_by_course_code($session_id, $course_code, $session_priority_list) {
1110              $couse_list = array();
1111              $couse_list = self::get_course_list_by_session_id ($session_id);
1112              $return = false;
1113              foreach ($session_priority_list as $priority_info) {
1114                  if ($priority_info[1] ==  $course_code) {
1115                      return false;
1116                  }
1117              }
1118              if (in_array($course_code,$couse_list)) {
1119                  $return = array($session_id,$course_code);
1120              }
1121              return $return;
1122          }
1123          
1124          /****************************************
1125           *  CATALOGUE SESSION FUNCTIONS
1126           ****************************************/        
1127          /**
1128           * Create empty catalogue sessions
1129           */
1130          public static function create_empty_catalogue_sessions($sessions, $courses_session, $session_category_id, $user_id, $session_category_id) {            
1131              // define the tables
1132              $tbl_session_user        = Database::get_main_table(TABLE_MAIN_SESSION_USER);
1133              $tbl_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
1134              $tbl_session_course      = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
1135              $tbl_session             = Database::get_main_table(TABLE_MAIN_SESSION);
1136              $tbl_session_cat_rel_user= Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY_REL_USER);
1137              $tbl_session_rel_cat     = Database::get_main_table(TABLE_MAIN_SESSION_REL_CATEGORY);
1138         
1139              if (!empty($sessions)) {                
1140                  foreach ($sessions as $key => $session_id) {
1141                      $max_seats = self::get_max_seats_session($session_id);
1142                      $nbr_users = self::get_nbr_users_in_session($session_id);
1143                      
1144                      // session is full, we create a new session
1145                      if ($max_seats <> -1 && ($nbr_users >= $max_seats)) {
1146                          $session_info = api_get_session_info($session_id);
1147                          // create the session
1148                          list($syear_start, $smonth_start, $sday_start) = explode('-', $session_info['date_start']);
1149                          list($syear_end, $smonth_end, $sday_end) = explode('-', $session_info['date_end']);                        
1150                          $session_name = $session_info['name'].'-new';                       
1151                          $last_session_id = self::create_session($session_name, $session_info['description'], $syear_start, $smonth_start, $sday_start, $syear_end, $smonth_end, $sday_end, 0, 1, '',-1);
1152                          
1153                          if ($last_session_id) {                            
1154                              // send email to administrators
1155                              self::send_email_about_new_session_to_administrators($last_session_id, $user_id, $session_category_id);
1156                              // update session name
1157                              $new_session_name = $session_info['name'].'-'.$last_session_id;
1158                              Database::query("UPDATE $tbl_session SET name = '$new_session_name' WHERE id = $last_session_id");
1159                              
1160                              // get the courses list
1161                              $courses = self::get_course_list_by_session_id($session_id);
1162                              // add courses to new session                        
1163                              if (!empty($courses)) {
1164                                  foreach ($courses as $course) {
1165                                      $rs_check = Database::query("SELECT * FROM $tbl_session_course WHERE id_session = $last_session_id AND course_code = '$course'");
1166                                      if (Database::num_rows($rs_check) == 0) {
1167                                          Database::query("INSERT INTO $tbl_session_course SET id_session = $last_session_id, course_code = '$course'");
1168                                          if (Database::affected_rows()) {
1169                                              // update nbr_courses
1170                                              Database::query("UPDATE $tbl_session SET nbr_courses = nbr_courses + 1 WHERE id = $last_session_id");
1171                                          }
1172                                      }
1173                                  }
1174                              }
1175                              // register session in category
1176                              $rs_sess_cat = Database::query("SELECT * FROM $tbl_session_rel_cat WHERE session_id = $session_id AND category_id = $session_category_id;");
1177                              if (Database::num_rows($rs_sess_cat)) {
1178                                  while ($row_sess_cat = Database::fetch_array($rs_sess_cat)) {   
1179                                      // insert new session
1180                                      Database::query("INSERT INTO $tbl_session_rel_cat SET 
1181                                                          category_id = $session_category_id,
1182                                                          session_set = '".$row_sess_cat['session_set']."',
1183                                                          session_id  = $last_session_id,
1184                                                          session_range = '".$row_sess_cat['session_range']."'                                                
1185                                                      ");                                   
1186                                      // remove current empty session_set                                
1187                                      Database::query("DELETE FROM $tbl_session_rel_cat WHERE session_id = $session_id AND category_id = $session_category_id");
1188                                  }
1189                              }  
1190                              // replace new session
1191                              if (isset($courses_session[$session_id])) {
1192                                  $courses_session[$last_session_id] = $courses_session[$session_id];
1193                                  unset($courses_session[$session_id]);
1194                              }                         
1195                          }                        
1196                      }                    
1197                  }
1198              }                 
1199              return $courses_session;            
1200          }
1201          
1202          /**
1203           * Register user to selected courses for session category, it's used for catalogue registration
1204           */
1205          public static function register_user_to_selected_courses_session($cours_rel_sessions, $user_id, $session_list, $session_category_id, $payment_type = 'credit_card') {
1206  
1207              // define the tables
1208              $tbl_session_user        = Database::get_main_table(TABLE_MAIN_SESSION_USER);
1209              $tbl_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
1210              $tbl_session_course      = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
1211              $tbl_session             = Database::get_main_table(TABLE_MAIN_SESSION);
1212              $tbl_session_cat_rel_user= Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY_REL_USER);
1213              $tbl_session_rel_cat     = Database::get_main_table(TABLE_MAIN_SESSION_REL_CATEGORY);
1214              
1215              // prepare courses in session
1216              $courses_session = array();
1217              if (!empty($cours_rel_sessions)) {
1218                  foreach ($cours_rel_sessions as $cours_rel_session) {
1219                      list($course, $session) = explode('@@', $cours_rel_session);
1220                      $courses_session[$session][] = $course;
1221                  }
1222              }                        
1223              $courses_session = self::create_empty_catalogue_sessions($session_list, $courses_session, $session_category_id, $user_id, $session_category_id);
1224              if (!empty($courses_session)) {
1225                  foreach ($courses_session as $session => $courses) {
1226                      // register session rel course user
1227                      if (!empty($courses)) {
1228                          $affected_rows = 0;
1229                          foreach ($courses as $course_code) {
1230                              $check = Database::query("SELECT * FROM $tbl_session_course_user WHERE id_session = $session AND course_code = '$course_code' AND id_user = $user_id");
1231                              if (Database::num_rows($check) == 0) {
1232                                  Database::query("INSERT INTO $tbl_session_course_user SET 
1233                                                      id_session = $session,
1234                                                      course_code = '$course_code',
1235                                                      id_user = $user_id
1236                                                  ");
1237                                  $affected_rows = Database::affected_rows();
1238                                  if ($affected_rows) {
1239                                      if (api_get_setting('automatic_group_filling') == 'true' && $payment_type != 'cheque_payment') {        
1240                                          self::automatically_add_user_to_group($course_code,$user_id);
1241                                      }
1242                                  }
1243                              }                            
1244                              // register to category
1245                              if (!empty($session_category_id)) {
1246                                  $verify_cat = Database::query("SELECT * FROM $tbl_session_cat_rel_user WHERE category_id = $session_category_id AND user_id = $user_id AND course_code='$course_code' AND session_id = $session");
1247                                  if (Database::num_rows($verify_cat) == 0) {
1248                                      Database::query("INSERT INTO $tbl_session_cat_rel_user SET 
1249                                                          category_id = $session_category_id,
1250                                                          user_id     = $user_id,
1251                                                          course_code = '$course_code',
1252                                                          session_id  = $session
1253                                                      ");
1254                                  }
1255                              }
1256                          }
1257                          if ($affected_rows) {
1258                              // insert into session user
1259                              $check_sess_user = Database::query("SELECT * FROM $tbl_session_user WHERE id_session = $session AND id_user = $user_id");
1260                              if (Database::num_rows($check) == 0) {
1261                                  Database::query("INSERT INTO $tbl_session_user SET 
1262                                                      id_session = $session,
1263                                                      id_user = $user_id
1264                                                  ");
1265                                  if (Database::affected_rows()) {
1266                                      // update numbers of students in table session
1267                                      Database::query("UPDATE $tbl_session SET nbr_users = nbr_users + 1 WHERE id = $session");
1268                                  }
1269                              }
1270                          }
1271                      }
1272                  }
1273              }
1274          }
1275  
1276          /**
1277           * Add users to group automatically
1278           * @param   course_code   Data
1279           * @param   int     user id 
1280           */
1281           public static function automatically_add_user_to_group($course_code, $user_id) {
1282              $course_info = api_get_course_info($course_code);                
1283              $tbl_group = Database::get_course_table(TABLE_GROUP, $course_info['dbName']);
1284              $table_group_user = Database :: get_course_table(TABLE_GROUP_USER, $course_info['dbName']);
1285              $user_table         = Database :: get_main_table(TABLE_MAIN_USER);                
1286              $tbl_course_rel_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);                
1287              $emailtemplate_table         = Database :: get_main_table(TABLE_MAIN_EMAILTEMPLATES);
1288              $sql = "SELECT * FROM $tbl_group";
1289              $rs = Database::query($sql,__FILE__,__LINE__);
1290              while ($row = Database::fetch_array($rs)) {
1291                  $group_id = $row['id'];
1292                  $sql_user = "SELECT * FROM ".$table_group_user." WHERE group_id = ".$group_id;
1293                  $result = Database::query($sql_user,__FILE__,__LINE__);
1294                  $num_users = Database::num_rows($result);
1295                  if($num_users < $row['max_student']){
1296                      $sql_insert = "INSERT INTO ".$table_group_user." (user_id, group_id) VALUES ('".$user_id."', '".$group_id."')";
1297                      Database::query($sql_insert,__FILE__,__LINE__);
1298                      $affected_rows = Database::affected_rows();
1299                      break;
1300                  }
1301                  else {
1302                      continue;
1303                  }    
1304              }
1305  
1306              if (!$affected_rows) {
1307                  if (api_get_setting('create_new_group') == 'true') {
1308                      $sql = "SELECT * FROM $tbl_group WHERE name like '".get_lang('GroupName')."_%' ORDER BY id";
1309                      $rs = Database::query($sql,__FILE__,__LINE__);
1310                      if (Database::num_rows($rs) == 0) {
1311                          $group_no = 1;
1312                          $new_group_name = get_lang('GroupName').'_'.$group_no;
1313                      }
1314                      else {
1315                          while($row = Database::fetch_array($rs)){
1316                                  $group_name = $row['name'];
1317                          }                            
1318                          list($grp_name,$grp_id) = split('_',$group_name);
1319                          $new_grp_id = $grp_id + 1;
1320                          $new_group_name = get_lang('GroupName').'_'.$new_grp_id;
1321                      }
1322                      $check = Database::query("SELECT * FROM $tbl_group WHERE name = '".$new_group_name."'");
1323                      if (Database::num_rows($check) == 0) {
1324                          $new_group_seats = api_get_setting('new_group_seats');    
1325                          $sql_group = "INSERT INTO $tbl_group(name,category_id,max_student) VALUES('".$new_group_name."',1,".$new_group_seats.")";
1326                          Database::query($sql_group,__FILE__,__LINE__);
1327                          $new_groupid = Database::insert_id();    
1328                          $sql_insert = "INSERT INTO ".$table_group_user." (user_id, group_id) VALUES ('".$user_id."', '".$new_groupid."')";
1329                          Database::query($sql_insert,__FILE__,__LINE__);
1330  
1331                          //Email
1332                          $sql = "SELECT content FROM $emailtemplate_table WHERE description = 'NewGroup' AND language='".api_get_interface_language()."'";
1333                          $res = Database::query($sql,__FILE__,__LINE__);
1334                          $num_rows = Database::num_rows($res);
1335                          if($num_rows == 0){
1336                          $sql = "SELECT content FROM $emailtemplate_table WHERE description = 'NewGroup' AND language = 'english'";
1337                          $res = Database::query($sql,__FILE__,__LINE__);
1338                          }
1339                          $row = Database::fetch_array($res);
1340                          $message = $row['content'];    
1341  
1342                          $sender_name = 'Automatic Mail From Dokeos';
1343                          $subject = get_lang('NewGroupCreated');
1344  
1345                          $message = str_replace("{groupName}",$new_group_name,$message);
1346                          $message = str_replace("{maxStudent}",$new_group_seats,$message);
1347                          $message = str_replace("{courseName}",$course_info['name'],$message);
1348                          $message = str_replace("{authorName}",'DILA E-Learning',$message);        
1349  
1350                          $message = str_replace('<br />',"\n\n", $message);
1351                          $sql = "SELECT u.* FROM $tbl_user u INNER JOIN $tbl_admin a ON u.user_id = a.user_id";
1352                          $rs_users = Database::query($sql,__FILE__,__LINE__);
1353                          if (Database::num_rows($rs_users)) {
1354                              $admins = array();
1355                              while ($row_users = Database::fetch_array($rs_users)) {                    
1356                                  $recipient_name = api_get_person_name($row_users['firstname'], $row_users['lastname'], null, PERSON_NAME_EMAIL_ADDRESS);
1357                                  $email_admin = $row_users['email'];                    
1358                                  $email_message =  str_replace('{adminName}', $recipient_name, $message); 
1359                                  api_mail_html($recipient_name, $email_admin, $subject, $email_message, $sender_name, api_get_setting('emailAdministrator'));                 
1360                              }
1361                          } 
1362                      }
1363                  }
1364              }            
1365           }
1366               
1367          /**
1368           * Send email to administrators about a created session
1369           */
1370          public static function send_email_about_new_session_to_administrators($session_id, $user_id, $cat_id) {
1371              global $language_interface, $_configuration;            
1372              
1373              $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
1374              $tbl_admin = Database::get_main_table(TABLE_MAIN_ADMIN);
1375              
1376              // Send automatically email at registration process     
1377              $user_info   = api_get_user_info($user_id);        
1378              // category info
1379              $category_info  = SessionManager::get_session_category($cat_id);                         
1380              $sessionList    = api_get_path(WEB_CODE_PATH).'admin/session_edit.php?page=session_list.php&id='.$session_id; 
1381  
1382              $emailsubject = '['.api_get_setting('siteName').'] '.get_lang('YourReg').' '.api_get_setting('siteName');            
1383              // template email
1384              $table_emailtemplate     = Database::get_main_table(TABLE_MAIN_EMAILTEMPLATES);    
1385              $sql = "SELECT * FROM $table_emailtemplate WHERE description = 'UserRegistrationToSession' AND language= '".$language_interface."'";
1386              $result = api_sql_query($sql, __FILE__, __LINE__);
1387              $row = Database::fetch_array($result);                
1388              $content = !empty($row['content']) ? $row['content'] : '';
1389  
1390              $content =  str_replace('{firstName}', stripslashes($user_info['firstname']), $content); 
1391              $content =  str_replace('{lastName}', stripslashes($user_info['lastname']), $content); 
1392              $content =  str_replace('{username}', $user_info['username'], $content); 
1393              $content =  str_replace('{Programme}', stripslashes($category_info['name']), $content);            
1394              $content =  str_replace('{siteName}', api_get_setting('siteName'), $content); 
1395              $content =  str_replace('{Institution}', api_get_setting('Institution'), $content); 
1396              $content =  str_replace('{administratorSurname}', api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname')), $content); 
1397              $content =  str_replace('{sessionList}', $sessionList, $content);            
1398              
1399              $content = strip_tags(str_replace('<br />',"\n", $content));
1400              $sql = "SELECT u.* FROM $tbl_user u INNER JOIN $tbl_admin a ON u.user_id = a.user_id";
1401              $rs_users = Database::query($sql,__FILE__,__LINE__);
1402              if (Database::num_rows($rs_users)) {
1403                  $admins = array();
1404                  while ($row_users = Database::fetch_array($rs_users)) {                    
1405                      $administratorname = api_get_person_name($row_users['firstname'], $row_users['lastname'], null, PERSON_NAME_EMAIL_ADDRESS);
1406                      $email_admin = $row_users['email'];                    
1407                      $content2 =  str_replace('{administratorname}', $administratorname, $content); 
1408                      @api_send_mail($email_admin, $emailsubject, $content2);                    
1409                  }
1410              }         
1411  
1412          }
1413                          
1414          /**
1415           * Save payment atos information
1416           * @param   array   Values in array ('user_id', 'sess_id', 'pay_type', 'pay_data')
1417           * @return  int     Affected rows
1418           */
1419          public static function save_payment_atos($params) {
1420              global $_configuration;
1421              require_once api_get_path(LIBRARY_PATH).'usermanager.lib.php';
1422              require_once api_get_path(LIBRARY_PATH).'export.lib.inc.php';            
1423              $tbl_fld     = Database::get_main_table(TABLE_MAIN_USER_FIELD);
1424              $tbl_fld_opt = Database::get_main_table(TABLE_MAIN_USER_FIELD_OPTIONS);            
1425              $tbl_payment_atos = Database::get_main_table(TABLE_MAIN_PAYMENT_ATOS); 
1426              $tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
1427              $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
1428              
1429              switch ($params['pay_type']) {
1430                  case 1: // online payment
1431                      $is_3install = FALSE;                                                
1432                      // it's first time, payment inmediate
1433                      $curr_cuota = 1;
1434                      $pay_data[$curr_cuota] = $params['pay_data'];
1435                      Database::query("INSERT INTO $tbl_payment_atos SET
1436                                       user_id  = ".$params['user_id'].", 
1437                                       sess_id  = ".$params['sess_id'].", 
1438                                       pay_type = ".$params['pay_type'].",
1439                                       pay_data = '".serialize($pay_data)."', 
1440                                       pay_time = ".time().",
1441                                       status   = ".($params['pay_type']==1?1:0).", 
1442                                       curr_quota = ".$curr_cuota
1443                                     ); 
1444                      // register in harmony
1445                      $saved = self::save_payment_log(array('user_id'=>$params['user_id'], 'sess_id'=>$params['sess_id'], 'pay_type'=>$params['pay_type'], 'pay_data'=>$params['pay_data'], 'curr_quota'=> $curr_cuota));
1446                      // send email with account information
1447                      if (!api_get_user_id()) {            
1448                          if (Database::affected_rows()) {
1449                              // activate user and send email                        
1450                              $user_info = api_get_user_info($params['user_id']);                                                             
1451                              if (!empty($user_info)) {
1452                                  $password   = api_generate_password();
1453                                  $encripted  = api_get_encrypted_password($password);
1454                                  Database::query('UPDATE user SET password = "'.$encripted.'", active = 1 WHERE user_id = "'.$params['user_id'].'" ');
1455                                  if (Database::affected_rows()) {                                        
1456                                      $user_params = array(
1457                                          'firstname' => $user_info['firstname'],
1458                                          'lastname'  => $user_info['lastname'],
1459                                          'username'  => $user_info['username'],
1460                                          'password'  => $password,                                            
1461                                          'email'     => $user_info['mail'],
1462                                      ); 
1463                                      self::send_email_to_registered_user_with_cc_or_intallment($user_params, $params['sess_id']);                                                                             
1464                                      return $params['user_id']; 
1465                                  }
1466                              }
1467                          }
1468                      } else {
1469                          return Database::affected_rows();
1470                      }                                                                     
1471                      break;                
1472                  case 2: // cheque payment                    
1473                      $result = 0;                                        
1474                      Database::query('INSERT INTO '.$tbl_payment_atos.' SET
1475                                       user_id  = '.$params['user_id'].',                                          
1476                                       sess_id  = '.$params['sess_id'].', 
1477                                       pay_type = '.$params['pay_type'].',
1478                                       pay_data = "'.$params['pay_data'].'", 
1479                                       pay_time = '.time().',
1480                                       status   = 0, 
1481                                       curr_quota = 0'
1482                              );
1483                      $result = Database::affected_rows();
1484                      return $result;
1485              }                        
1486          }
1487          
1488          /**
1489           * 
1490           */
1491          public static function send_email_to_registered_user_with_cc_or_intallment($user_params, $cat_id) {
1492              global $_configuration, $language_interface;            
1493              $category_info  = SessionManager::get_session_category($cat_id);             
1494              $emailto = $user_params['email'];
1495              $emailsubject  = '['.api_get_setting('siteName').'] '.get_lang('YourReg').' '.api_get_setting('siteName');            
1496              // template email
1497              $table_emailtemplate     = Database::get_main_table(TABLE_MAIN_EMAILTEMPLATES);    
1498              $sql = "SELECT * FROM $table_emailtemplate WHERE description = 'EmailsRegistrationInCaseCreditCardOrInstallment' AND language= '".$language_interface."'";
1499              $result = api_sql_query($sql, __FILE__, __LINE__);
1500              $row = Database::fetch_array($result);                
1501              $content = !empty($row['content']) ? $row['content'] : '';
1502              $content =  str_replace('{firstName}', stripslashes($user_params['firstname']), $content);
1503              $content =  str_replace('{lastName}', stripslashes($user_params['lastname']), $content);
1504              $content =  str_replace('{username}', stripslashes($user_params['username']), $content);
1505              $content =  str_replace('{password}', stripslashes($user_params['password']), $content);
1506              $content =  str_replace('{Programme}', stripslashes($category_info['name']), $content);
1507              $content =  str_replace('{siteName}', api_get_setting('siteName'), $content);
1508              $content =  str_replace('{Institution}', api_get_setting('Institution'), $content); 
1509              $content =  str_replace('{InstitutionUrl}', api_get_setting('InstitutionUrl'), $content);             
1510              $content =  str_replace('{administratorSurname}', api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname')), $content);
1511              $content =  str_replace('{detailsUrl}', '<a href="http://formation-publique.fr" target="_blank">http://formation-publique.fr</a>', $content);
1512              $content = strip_tags(str_replace('<br />',"\n", $content));
1513              @api_send_mail($emailto, $emailsubject, $content);
1514          }
1515          
1516          /**
1517           * Save a payer 
1518           */         
1519          public static function save_payer_user($params) {
1520              $tbl_payer = Database::get_main_table(TABLE_MAIN_PAYER_USER);
1521              // save payer
1522              $payer_id = 0;
1523              if (!empty($params)) {
1524                $company       = $params['company']?$params['company']:'';
1525                $firstname     = $params['firstname']?$params['firstname']:'';
1526                $lastname      = $params['lastname']?$params['lastname']:'';
1527                $email         = $params['email']?$params['email']:'';
1528                $street_number = $params['street_number']?$params['street_number']:'';
1529                $street        = $params['street']?$params['street']:'';
1530                $zipcode       = $params['zipcode']?$params['zipcode']:'';
1531                $city          = $params['city']?$params['city']:'';
1532                $country       = $params['country']?$params['country']:'';
1533                $student_id    = $params['student_id']?$params['student_id']:'';
1534                $vat_number    = $params['vatnumber']?$params['vatnumber']:'';
1535                $phone         = $params['phone']?$params['phone']:'';
1536                $civility      = $params['civility']?$params['civility']:'';                  
1537                Database::query("INSERT INTO $tbl_payer SET  
1538                                  firstname = '".Database::escape_string($firstname)."',
1539                                  lastname = '".Database::escape_string($lastname)."',
1540                                  email = '".Database::escape_string($email)."',
1541                                  street_number = '".Database::escape_string($street_number)."',
1542                                  street = '".Database::escape_string($street)."',
1543                                  zipcode = '".Database::escape_string($zipcode)."',
1544                                  city = '".Database::escape_string($city)."',
1545                                  country = '".Database::escape_string($country)."',
1546                                  student_id = '".intval($student_id)."',
1547                                  vat_number = '".Database::escape_string($vat_number)."',
1548                                  company = '".Database::escape_string($company)."',
1549                                  phone = '".Database::escape_string($phone)."',
1550                                  civility = '".Database::escape_string($civility)."'
1551                               ");
1552                $payer_id = Database::insert_id();                  
1553              }
1554              return $payer_id;
1555          }
1556                 
1557          /**
1558           *  Clear catalogue order process, unset all sessions for current order
1559           */
1560          public static function clear_catalogue_order_process() {
1561              // sessions
1562              if (isset($_SESSION['selected_sessions'])) {
1563                  unset($_SESSION['selected_sessions']);
1564              }
1565              if (isset($_SESSION['selected_courses'])) {
1566                  unset($_SESSION['selected_courses']);
1567              }
1568              if (isset($_SESSION['user_info'])) {
1569                  unset($_SESSION['user_info']);
1570              }
1571              if (isset($_SESSION['payer_info'])) {
1572                  unset($_SESSION['payer_info']);
1573              }
1574              if (isset($_SESSION['wish'])) {
1575                  unset($_SESSION['wish']);
1576              }
1577              if (isset($_SESSION['iden'])) {
1578                  unset($_SESSION['iden']);
1579              }
1580              if (isset($_SESSION['from'])) {
1581                  unset($_SESSION['from']);
1582              }
1583              if (isset($_SESSION['pay_type'])) {
1584                  unset($_SESSION['pay_type']);
1585              }       
1586              if (isset($_SESSION['steps'])) {
1587                  unset($_SESSION['steps']);
1588              }    
1589              if (isset($_SESSION['cours_rel_session'])) {
1590                  unset($_SESSION['cours_rel_session']);
1591              }
1592          }
1593          
1594          /**
1595           * Get catalogue installments payment information
1596           */ 
1597           public static function get_catalogue_installments_payment_info($catalogue_id) {
1598               $tbl_catalogue = Database::get_main_table(TABLE_MAIN_CATALOGUE);
1599               $catalogue = self::get_catalogue_info($catalogue_id);
1600               $info = array();
1601               if (!empty($catalogue)) {
1602                   // Second installment info
1603                   $info[2]['percent'] = isset($catalogue['second_installment'])?$catalogue['second_installment']:0;
1604                   $info[2]['delay']   = isset($catalogue['second_installment_delay'])?$catalogue['second_installment_delay']:0;
1605                   // Third installment info
1606                   $info[3]['percent'] = isset($catalogue['third_installment'])?$catalogue['third_installment']:0;
1607                   $info[3]['delay']   = isset($catalogue['third_installment_delay'])?$catalogue['third_installment_delay']:0;
1608                   // first installment info
1609                   $info[1]['percent'] = 100 - ($info[2]['percent'] + $info[3]['percent']);
1610                   $info[1]['delay']   = 0; // inmediate
1611               }
1612               return $info;
1613           }                   
1614                  
1615          /*        
1616           * Get information of payer
1617           */
1618           public static function get_payer_info($student_id) {
1619               $tbl_payer = Database::get_main_table(TABLE_MAIN_PAYER_USER);
1620               $info = array();
1621               $rs = Database::query("SELECT * FROM $tbl_payer WHERE student_id = $student_id");
1622               if (Database::num_rows($rs)) {
1623                   while ($row = Database::fetch_array($rs)) {
1624                       $info = $row;
1625                   }
1626               }          
1627               return $info;
1628           }
1629           
1630           /*        
1631           * Get catalogue information
1632           */
1633           public static function get_topic_info($topic_id = null) {
1634               $tbl_topic = Database::get_main_table(TABLE_MAIN_TOPIC);
1635               $info = array();
1636               $rs = Database::query("SELECT * FROM $tbl_topic");
1637               if (Database::num_rows($rs)) {
1638                   while ($row = Database::fetch_array($rs)) {
1639                       $info[$row['id']] = $row;
1640                   }
1641                   
1642               }             
1643               return isset($topic_id)?$info[$topic_id]:$info;
1644           }    
1645           
1646           /*        
1647           * Get catalogue information
1648           */
1649           public static function get_catalogue_info($catalogue_id = null) {
1650               $tbl_catalogue = Database::get_main_table(TABLE_MAIN_CATALOGUE);
1651               $info = array();
1652               $rs = Database::query("SELECT * FROM $tbl_catalogue");
1653               if (Database::num_rows($rs)) {
1654                   while ($row = Database::fetch_array($rs)) {
1655                       $info[$row['id']] = $row;
1656                   }
1657                   
1658               }             
1659               return isset($catalogue_id)?$info[$catalogue_id]:$info;
1660           }
1661           
1662           /**
1663           * Get user payment atos
1664           * @param   int     User id
1665           * @param   int     Session category id
1666           * @return  array   Result
1667           */
1668          public static function get_user_sess_payment_atos($user_id, $sess_id) {
1669              $tbl_payment_atos = Database::get_main_table(TABLE_MAIN_PAYMENT_ATOS);
1670              $data = array();
1671              $rs = Database::query("SELECT * FROM $tbl_payment_atos WHERE user_id = {$user_id} AND sess_id = {$sess_id}");
1672              if (Database::num_rows($rs)) {
1673                  $data = Database::fetch_array($rs);
1674              }
1675              return $data;
1676          }
1677          
1678          /**
1679           * Get country name by extra field
1680           */
1681          public static function get_country_name_by_extra_field($extcountry_code) {            
1682              $tbl_fld                = Database::get_main_table(TABLE_MAIN_USER_FIELD);
1683              $tbl_fld_opt            = Database::get_main_table(TABLE_MAIN_USER_FIELD_OPTIONS); 
1684              $country_name = '';
1685              $rs_fld_opt = Database::query("SELECT option_display_text FROM $tbl_fld_opt ufo INNER JOIN $tbl_fld uf ON uf.id = ufo.field_id WHERE uf.field_variable = 'country' AND ufo.option_value = '$extcountry_code'");
1686              if (Database::num_rows($rs_fld_opt) > 0) {
1687                      $row_fld_opt = Database::fetch_array($rs_fld_opt);
1688                      $country_name = $row_fld_opt['option_display_text'];
1689              }
1690              return $country_name;            
1691          }
1692          
1693          /**
1694           * Calculate cost to pay for atos
1695           */
1696           public static function get_user_amount_pay_atos($cost, $country_code) {
1697              $fr     = array('001');  // France Fixed 19.60%
1698              $ue  = array(101, 104, 105, 106, 107, 108, 109, 110, 111, 112, 114, 116, 117, 122, 126, 127, 131, 132, 134, 135, 136, 137, 139, 144, 145, 254); // CEE Fixed 19.60%
1699              $dom = array(971, 972, 973, 974, 976); // DOM 8.50%
1700              $tom = array(975, 978, 979, 983, 984, 987, 988); // TOM 0%
1701                                      
1702              $amount = 0;
1703              if (!empty($cost)) {
1704                  // TVA
1705                  if (!empty($country_code)) {                    
1706                      $tva = self::get_tva_amount($cost, $country_code);
1707                      $amount = round($cost + $tva, 2);                    
1708                  }    
1709              }                      
1710              return $amount;
1711           }
1712          
1713           /**
1714           * Calculate cost to pay for atos
1715           */
1716           public static function get_tva_amount($cost, $country_code) {
1717              $percent = self::get_percent_tva_by_country($country_code);
1718              $tva = 0;
1719              if (!empty($cost)) {
1720               $tva = ($cost * $percent)/100;                    
1721              }                        
1722              return $tva;            
1723           }
1724           
1725           /**
1726           * Get percent tva by country
1727           */         
1728           public static function get_percent_tva_by_country($country_code) {
1729              $fr  = array('001');  // France Fixed 19.60%
1730              $ue  = array(101, 104, 105, 106, 107, 108, 109, 110, 111, 112, 114, 116, 117, 122, 126, 127, 131, 132, 134, 135, 136, 137, 139, 144, 145, 254); // CEE Fixed 19.60%
1731              $dom = array(971, 972, 973, 974, 976); // DOM 8.50%
1732              $tom = array(975, 978, 979, 983, 984, 987, 988);
1733              $per = 0;
1734              if (!empty($country_code)) {
1735                  if (in_array($country_code, $fr) || in_array($country_code, $ue)) {
1736                          // European community, CEE Assujetti: 19,60 %
1737                          $per = 19.60;            
1738                  } else if (in_array($country_code, $dom)) {
1739                          // DOM: 8,50 %
1740                          $per = 8.50;            
1741                  } else {
1742                          $per = 0;
1743                  }                                        
1744              }
1745              return $per;
1746           }   
1747           
1748           /**
1749            * Get next user quota installmente to pay
1750            */
1751           public static function get_next_quota_install_to_pay($user_id, $sess_id) {
1752               $next_quota = 0;
1753               $curr_info = self::get_user_sess_payment_atos($user_id, $sess_id);    
1754               if (!empty($curr_info)) {
1755                   $curr_quota = $curr_info['curr_quota'];
1756                   $next_quota = $curr_quota + 1;
1757                   if ($next_quota > 3) {$next_quota = 0;}
1758               } else {
1759                   $next_quota = 1;
1760               }
1761               return $next_quota;
1762           }
1763           
1764           /**
1765            * Get cost of installment payment by quota without tva
1766            */
1767           public static function get_cost_installment_quota($sess_id, $quota) {
1768               $cost = $amount = 0;
1769               $category = self::get_session_category($sess_id);
1770               // get catalogue_id             
1771               $catalogue = self::get_catalogue_info_by_category($sess_id);
1772               $catalogue_id = $catalogue['id'];             
1773               // installment
1774               $installment_info  = self::get_catalogue_installments_payment_info($catalogue_id);
1775               if (!empty($category['cost'])) {
1776                   $cost = $category['cost'];
1777                   $curr_per_install = $installment_info[$quota]['percent'];
1778                   $amount = ($cost * $curr_per_install)/100;
1779               }
1780               return $amount;
1781           }
1782           
1783           /**
1784            * Get catalogue information by session category(program)
1785            * @param  int     the session category id
1786            * @return array   The catalogue information
1787            */
1788           public static function get_catalogue_info_by_category($sess_cat_id) {
1789               $category = self::get_session_category($sess_cat_id);
1790               $topic = self::get_topic_info($category['topic']);
1791               $catalogue = self::get_catalogue_info($topic['catalogue_id']);
1792               return $catalogue;
1793           }
1794           
1795           /**
1796            * Save payment logs for each user
1797            * @param  array   Fields and values for record
1798            * @return int     Last insert id
1799            */
1800           public static function save_payment_log($params) {
1801               $tbl_harmony = Database::get_main_table(TABLE_MAIN_PAYMENT_LOG);  
1802               Database::query("INSERT INTO $tbl_harmony SET 
1803                            user_id = '".intval($params['user_id'])."',
1804                            sess_id = '".intval($params['sess_id'])."',
1805                            pay_type = '".intval($params['pay_type'])."',
1806                            pay_data = '".Database::escape_string($params['pay_data'])."',
1807                            pay_time = '".time()."',
1808                            curr_quota = '".intval($params['curr_quota'])."'
1809                       ");
1810              return Database::insert_id();             
1811           }
1812           
1813           /**
1814            * Display steps breadcrumbs, it used to navegate into catalogue registration
1815            * @return string  string html 
1816            */
1817           public static function display_steps_breadcrumbs() {
1818  
1819              $class = '';
1820              $href  = 'javascript:void(0)';
1821              // step1
1822              if (isset($_SESSION['steps'][1]) || ($_GET['next'] == 1 || $_GET['next'] == 2)) {
1823                  $class = 'done';
1824                  $href  = api_get_path(WEB_CODE_PATH).'admin/category_list.php?id='.$_SESSION['cat_id'].'&prev=1';
1825                  if ((isset($_GET['next']) && $_GET['next'] == 1) || (isset($_GET['prev']) && $_GET['prev'] == 1)) {
1826                      $class = 'active';                        
1827                  }
1828                  $step1 .= '<li id="stepsbreadcrumbs1" class="'.$class.'"><a href="'.$href.'">1. '.get_lang('SelectioningOptions').'</a></li>';
1829              } else {
1830                  $step1 .= '<li id="stepsbreadcrumbs1">1. '.get_lang('SelectioningOptions').'</li>';
1831              }
1832              
1833              // step2
1834              if (isset($_SESSION['steps'][2]) || $_GET['next'] == 2) {
1835                  $class = 'done';
1836                  $href  = api_get_path(WEB_CODE_PATH).'admin/registration.php?iden='.$_SESSION['iden'].'&wish='.$_SESSION['wish'].'&id='.$_SESSION['cat_id'].'&prev=2';
1837                  if ((isset($_GET['next']) && $_GET['next'] == 2) || (isset($_GET['prev']) && $_GET['prev'] == 2)) {
1838                      $class = 'active';                        
1839                  }
1840                  $step2 .= '<li id="stepsbreadcrumbs2" class="'.$class.'"><a href="'.$href.'">2. '.get_lang('SelfRegistrationOrNot').'</a></li>';
1841              } else {
1842                  $step2 .= '<li id="stepsbreadcrumbs2">2. '.get_lang('SelfRegistrationOrNot').'</li>';
1843              }
1844              
1845              // step3
1846              if (isset($_SESSION['steps'][3]) || $_GET['next'] == '3') {
1847                  $class = 'done';
1848                  $href  = api_get_path(WEB_CODE_PATH).'admin/registration_step3.php?iden='.$_SESSION['iden'].'&wish='.$_SESSION['wish'].'&id='.$_SESSION['cat_id'].'&prev=3';
1849                  if ((isset($_GET['next']) && $_GET['next'] == '3') || (isset($_GET['prev']) && $_GET['prev'] == '3')) {
1850                      $class = 'active';                        
1851                  }
1852                  $step3 .= '<li id="stepsbreadcrumbs3" class="'.$class.'"><a href="'.$href.'">3. '.get_lang('StudentPersonalData').'</a></li>';
1853              } else {
1854                  $step3 .= '<li id="stepsbreadcrumbs3">3. '.get_lang('StudentPersonalData').'</li>';
1855              }
1856  
1857              // step 3b
1858              if (intval($_SESSION['iden']) == 1 || ($_SESSION['iden'] == 0 && $_SESSION['wish'] == 1)) {                                   
1859                  // step3b
1860                  if (isset($_SESSION['steps']['3b']) || $_GET['next'] == '3b') {
1861                      $class = 'done';
1862                      $href  = api_get_path(WEB_CODE_PATH).'admin/registration_step3b.php?iden='.$_SESSION['iden'].'&wish='.$_SESSION['wish'].'&id='.$_SESSION['cat_id'].'&prev=3b';
1863                      if ((isset($_GET['next']) && $_GET['next'] === '3b') || (isset($_GET['prev']) && $_GET['prev'] === '3b')) {
1864                          $class = 'active';                        
1865                      }
1866                      $step3b .= '<li id="stepsbreadcrumbs3b" class="'.$class.'"><a href="'.$href.'">3b. '.get_lang('SubscriptionPayerPersonalData').'</a></li>';
1867                  } else {
1868                      $step3b .= '<li id="stepsbreadcrumbs3b">3b. '.get_lang('SubscriptionPayerPersonalData').'</li>';
1869                  }
1870              }
1871              
1872              // step4
1873              $title4 = !api_get_user_id()?'4. '.get_lang('SummaryView'):'2. '.get_lang('SummaryView');
1874              if (isset($_SESSION['steps'][4]) || $_GET['next'] == 4) {
1875                  $class = 'done';
1876                  $href  = api_get_path(WEB_CODE_PATH).'admin/feedback.php?iden='.$_SESSION['iden'].'&wish='.$_SESSION['wish'].'&id='.$_SESSION['cat_id'].'&prev=4';
1877                  if ((isset($_GET['next']) && $_GET['next'] == 4) || (isset($_GET['prev']) && $_GET['prev'] == 4)) {
1878                      $class = 'active';                        
1879                  }                                                
1880                  $step4 .= '<li id="stepsbreadcrumbs4" class="'.$class.'"><a href="'.$href.'">'.$title4.'</a></li>';
1881              } else {
1882                  $step4 .= '<li id="stepsbreadcrumbs4">'.$title4.'</li>';
1883              }
1884              
1885              // step5
1886              $title5 = !api_get_user_id()?'5. '.get_lang('Payment'):'3. '.get_lang('Payment');
1887              if (isset($_SESSION['steps'][5]) || $_GET['next'] == 5) {
1888                  $class = 'done';
1889                  $href  = api_get_path(WEB_CODE_PATH).'admin/payment_options.php?iden='.$_SESSION['iden'].'&wish='.$_SESSION['wish'].'&id='.$_SESSION['cat_id'].'&prev=5';
1890                  if ((isset($_GET['next']) && $_GET['next'] == 5) || (isset($_GET['prev']) && $_GET['prev'] == 5)) {
1891                      $class = 'active';
1892                  }
1893                  $step5 .= '<li id="stepsbreadcrumbs5" class="'.$class.'"><a href="'.$href.'">'.$title5.'</a></li>';
1894              } else {
1895                  $step5 .= '<li id="stepsbreadcrumbs5">'.$title5.'</li>';
1896              }
1897              $css_width = "";
1898              // step6
1899              $title6 = !api_get_user_id()?'6. '.get_lang('ChequePayment'):'4. '.get_lang('ChequePayment');
1900              if (isset($_GET['next']) && $_GET['next'] == 6) {                
1901                  $step6 .= '<li id="stepsbreadcrumbs6" class="active"><a href="'.$href.'">'.$title6.'</a></li>';
1902                  $css_width = "height:40px;";
1903              }            
1904              $html = '';
1905              $html .= '<div style="'.$css_width.'" id="stepsbreadcrumbs"><ul>';
1906              $html .= $step1;            
1907              if (!api_get_user_id()) {
1908                  $html .= $step2;            
1909                  $html .= $step3;
1910                  $html .= $step3b;
1911              }            
1912              $html .= $step4;
1913              $html .= $step5;
1914              $html .= $step6;
1915              $html .= '</ul></div>';            
1916              echo $html;
1917           }
1918                    
1919           /**
1920            * Get number of users in a session
1921            * @param  int     Session id
1922            * @return int     number of users
1923            */
1924            public static function get_nbr_users_in_session($session_id) {
1925                $tbl_sess_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
1926                $nbr_users = 0;
1927                $rs = Database::query("SELECT count(*) FROM $tbl_sess_user WHERE id_session = $session_id");
1928                if (Database::num_rows($rs)) {
1929                    $row = Database::fetch_row($rs);
1930                    $nbr_users = $row[0];
1931                }      
1932                return $nbr_users;              
1933            }         
1934            
1935            /**
1936             * Get total seats in a session
1937             * @param   int   Session id
1938             * @return  int   the total seats
1939             */
1940            public static function get_max_seats_session($session_id) {
1941                $seats = 0;
1942                $session_info = api_get_session_info($session_id); 
1943                $max_seats = $session_info['max_seats'];
1944                $seats = intval($max_seats);    
1945                return $seats;
1946            }
1947            
1948            /**
1949             * Get countries belongins france
1950             * @return  array  country codes
1951             */
1952            public static function countries_belongins_france() {
1953              $fr  = array('001');
1954              $dom = array(971, 972, 973, 974, 976);
1955              $tom = array(975, 978, 979, 983, 984, 987, 988); 
1956              return array_merge($fr, $dom, $tom);
1957            }
1958                                
1959  }
1960  

title

Description

title

Description

title

Description

title

title

Body