Exemplo n.º 1
0
/**
 * @author Sebastien Piraux <*****@*****.**>
 * @desc Record information for login event
 * (when an user identifies himself with username & password)
 */
function event_login()
{
    global $TABLETRACK_LOGIN;
    global $_user;
    // @todo use api_get_user_info();
    //$userInfo = api_get_user_info();
    $userInfo = $_user;
    if (empty($userInfo)) {
        return false;
    }
    $userId = api_get_user_id();
    $reallyNow = api_get_utc_datetime();
    $sql = "INSERT INTO " . $TABLETRACK_LOGIN . " (login_user_id, login_ip, login_date, logout_date) VALUES\n            ('" . $userId . "',\n            '" . Database::escape_string(api_get_real_ip()) . "',\n            '" . $reallyNow . "',\n            '" . $reallyNow . "'\n            )";
    Database::query($sql);
    // Auto subscribe
    $user_status = $userInfo['status'] == SESSIONADMIN ? 'sessionadmin' : $userInfo['status'] == COURSEMANAGER ? 'teacher' : $userInfo['status'] == DRH ? 'DRH' : 'student';
    $autoSubscribe = api_get_setting($user_status . '_autosubscribe');
    if ($autoSubscribe) {
        $autoSubscribe = explode('|', $autoSubscribe);
        foreach ($autoSubscribe as $code) {
            if (CourseManager::course_exists($code)) {
                CourseManager::subscribe_user($userId, $code);
            }
        }
    }
}
Exemplo n.º 2
0
 /**
  * @author Sebastien Piraux <*****@*****.**> old code
  * @author Julio Montoya 2013
  * @desc Record information for login event when an user identifies himself with username & password
  */
 function event_login(User $user)
 {
     $userId = $user->getUserId();
     $TABLETRACK_LOGIN = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN);
     $reallyNow = api_get_utc_datetime();
     $sql = "INSERT INTO " . $TABLETRACK_LOGIN . " (login_user_id, login_ip, login_date, logout_date) VALUES\n                    ('" . $userId . "',\n                    '" . Database::escape_string(api_get_real_ip()) . "',\n                    '" . $reallyNow . "',\n                    '" . $reallyNow . "'\n                    )";
     Database::query($sql);
     $roles = $user->getRoles();
     // auto subscribe
     foreach ($roles as $role) {
         $userStatusParsed = 'student';
         switch ($role) {
             case 'ROLE_SESSION_MANAGER':
                 $userStatusParsed = 'sessionadmin';
                 break;
             case 'ROLE_TEACHER':
                 $userStatusParsed = 'teacher';
                 break;
             case 'ROLE_RRHH':
                 $userStatusParsed = 'DRH';
                 break;
         }
         $autoSubscribe = api_get_setting($userStatusParsed . '_autosubscribe');
         if ($autoSubscribe) {
             $autoSubscribe = explode('|', $autoSubscribe);
             foreach ($autoSubscribe as $code) {
                 if (CourseManager::course_exists($code)) {
                     CourseManager::subscribe_user($userId, $code);
                 }
             }
         }
     }
 }
 /**
  * @Route("/courses/{cidReq}/{sessionId}")
  * @Method({"GET"})
  *
  * @param string $cidReq
  * @param int $id_session
  * @return Response
  */
 public function indexAction($cidReq, $id_session = null)
 {
     $courseCode = api_get_course_id();
     $sessionId = api_get_session_id();
     $userId = $this->getUser()->getUserId();
     $coursesAlreadyVisited = $this->getRequest()->getSession()->get('coursesAlreadyVisited');
     $result = $this->autolaunch();
     $showAutoLaunchLpWarning = $result['show_autolaunch_lp_warning'];
     $showAutoLaunchExerciseWarning = $result['show_autolaunch_exercise_warning'];
     if ($showAutoLaunchLpWarning) {
         $this->getTemplate()->assign('lp_warning', Display::return_message(get_lang('TheLPAutoLaunchSettingIsONStudentsWillBeRedirectToAnSpecificLP'), 'warning'));
     }
     if ($showAutoLaunchExerciseWarning) {
         $this->getTemplate()->assign('exercise_warning', Display::return_message(get_lang('TheExerciseAutoLaunchSettingIsONStudentsWillBeRedirectToAnSpecificExercise'), 'warning'));
     }
     if ($this->isCourseTeacher()) {
         $editIcons = Display::url(Display::return_icon('edit.png'), $this->generateUrl('course_home.controller:iconListAction', array('course' => api_get_course_id())));
         $this->getTemplate()->assign('edit_icons', $editIcons);
     }
     if (!isset($coursesAlreadyVisited[$courseCode])) {
         event_access_course();
         $coursesAlreadyVisited[$courseCode] = 1;
         $this->getRequest()->getSession()->set('coursesAlreadyVisited', $coursesAlreadyVisited);
     }
     $this->getRequest()->getSession()->remove('toolgroup');
     $this->getRequest()->getSession()->remove('_gid');
     $isSpecialCourse = \CourseManager::is_special_course($courseCode);
     if ($isSpecialCourse) {
         $autoreg = $this->getRequest()->get('autoreg');
         if ($autoreg == 1) {
             \CourseManager::subscribe_user($userId, $courseCode, STUDENT);
         }
     }
     $script = 'activity.php';
     if (api_get_setting('homepage_view') == 'activity' || api_get_setting('homepage_view') == 'activity_big') {
         $script = 'activity.php';
     } elseif (api_get_setting('homepage_view') == '2column') {
         $script = '2column.php';
     } elseif (api_get_setting('homepage_view') == '3column') {
         $script = '3column.php';
     } elseif (api_get_setting('homepage_view') == 'vertical_activity') {
         $script = 'vertical_activity.php';
     }
     $result = (require_once api_get_path(SYS_CODE_PATH) . 'course_home/' . $script);
     $toolList = $result['tool_list'];
     $this->getTemplate()->assign('icons', $result['content']);
     $introduction = Display::return_introduction_section($this->get('url_generator'), TOOL_COURSE_HOMEPAGE, $toolList);
     $this->getTemplate()->assign('introduction_text', $introduction);
     if (api_get_setting('show_session_data') == 'true' && $sessionId) {
         $sessionInfo = \CourseHome::show_session_data($sessionId);
         $this->getTemplate()->assign('session_info', $sessionInfo);
     }
     $response = $this->get('template')->render_template($this->getTemplatePath() . 'index.tpl');
     return new Response($response, 200, array());
 }
Exemplo n.º 4
0
 /**
  * @Route("/", name="course_home")
  * @Route("/index.php")
  * @Method({"GET"})
  *
  * @param Request $request
  * @return Response
  */
 public function indexAction(Request $request)
 {
     $sessionId = api_get_session_id();
     $course = $this->getCourse();
     $courseCode = $course->getId();
     $result = $this->autoLaunch();
     $showAutoLaunchLpWarning = $result['show_autolaunch_lp_warning'];
     $showAutoLaunchExerciseWarning = $result['show_autolaunch_exercise_warning'];
     if ($showAutoLaunchLpWarning) {
         $this->addFlash('warning', $this->trans('TheLPAutoLaunchSettingIsONStudentsWillBeRedirectToAnSpecificLP'));
     }
     if ($showAutoLaunchExerciseWarning) {
         $this->addFlash('warning', $this->trans('TheExerciseAutoLaunchSettingIsONStudentsWillBeRedirectToAnSpecificExercise'));
     }
     if (true) {
         $editIcons = Display::url(Display::return_icon('edit.png'), $this->generateUrl('chamilo_course_home_home_iconlist', array('course' => api_get_course_id())));
     }
     $isSpecialCourse = \CourseManager::isSpecialCourse($courseCode);
     if ($isSpecialCourse) {
         $user = $this->getUser();
         if (!empty($user)) {
             $userId = $this->getUser()->getId();
             $autoreg = $request->get('autoreg');
             if ($autoreg == 1) {
                 \CourseManager::subscribe_user($userId, $courseCode, STUDENT);
             }
         }
     }
     $homeView = api_get_setting('course.homepage_view');
     if ($homeView == 'activity' || $homeView == 'activity_big') {
         $result = $this->renderActivityView();
     } elseif ($homeView == '2column') {
         $result = $this->render2ColumnView();
     } elseif ($homeView == '3column') {
         $result = $this->render3ColumnView();
     } elseif ($homeView == 'vertical_activity') {
         $result = $this->renderVerticalActivityView();
     }
     $toolList = $result['tool_list'];
     $introduction = Display::return_introduction_section(TOOL_COURSE_HOMEPAGE, $toolList);
     $sessionInfo = null;
     if (api_get_setting('session.show_session_data') == 'true' && $sessionId) {
         $sessionInfo = CourseHome::show_session_data($sessionId);
     }
     return $this->render('ChamiloCourseBundle:Home:index.html.twig', array('course' => $course, 'session_info' => $sessionInfo, 'icons' => $result['content'], 'edit_icons' => $editIcons, 'introduction_text' => $introduction, 'exercise_warning' => null, 'lp_warning' => null));
 }
Exemplo n.º 5
0
    }
}
if (isset($_POST['action'])) {
    switch ($_POST['action']) {
        case 'subscribe':
            if (is_array($_POST['user'])) {
                foreach ($_POST['user'] as $index => $user_id) {
                    $user_id = intval($user_id);
                    if (isset($_REQUEST['type']) && $_REQUEST['type'] == 'teacher') {
                        if (!empty($current_session_id)) {
                            $is_suscribe[] = SessionManager::set_coach_to_course_session($user_id, $current_session_id, $_course['sysCode']);
                        } else {
                            $is_suscribe[] = CourseManager::subscribe_user($user_id, $_course['sysCode'], COURSEMANAGER);
                        }
                    } else {
                        $is_suscribe[] = CourseManager::subscribe_user($user_id, $_course['sysCode']);
                    }
                    $is_suscribe_user_id[] = $user_id;
                }
            }
            $user_id_temp = $_SESSION['session_user_id'];
            $user_name_temp = $_SESSION['session_user_name'];
            unset($_SESSION['session_user_id']);
            unset($_SESSION['session_user_name']);
            $counter = 0;
            $is_suscribe_counter = count($is_suscribe_user_id);
            $list_register_user = '';
            //if ($$is_suscribe_counter!=1) {
            for ($i = 0; $i < $is_suscribe_counter; $i++) {
                for ($j = 0; $j < count($user_id_temp); $j++) {
                    if ($is_suscribe_user_id[$i] == $user_id_temp[$j]) {
Exemplo n.º 6
0
    exit;
}
if (isset($_POST['action'])) {
    switch ($_POST['action']) {
        case 'subscribe':
            if (is_array($_POST['user'])) {
                foreach ($_POST['user'] as $index => $user_id) {
                    $user_id = intval($user_id);
                    if ($type == COURSEMANAGER) {
                        if (!empty($current_session_id)) {
                            $is_suscribe[] = SessionManager::set_coach_to_course_session($user_id, $current_session_id, $courseInfo['code']);
                        } else {
                            $is_suscribe[] = CourseManager::subscribe_user($user_id, $courseInfo['code'], COURSEMANAGER);
                        }
                    } else {
                        $is_suscribe[] = CourseManager::subscribe_user($user_id, $courseInfo['code']);
                    }
                    $is_suscribe_user_id[] = $user_id;
                }
            }
            $user_id_temp = $_SESSION['session_user_id'];
            $user_name_temp = $_SESSION['session_user_name'];
            unset($_SESSION['session_user_id']);
            unset($_SESSION['session_user_name']);
            $counter = 0;
            $is_suscribe_counter = count($is_suscribe_user_id);
            $list_register_user = '';
            for ($i = 0; $i < $is_suscribe_counter; $i++) {
                for ($j = 0; $j < count($user_id_temp); $j++) {
                    if ($is_suscribe_user_id[$i] == $user_id_temp[$j]) {
                        if ($is_suscribe[$i]) {
Exemplo n.º 7
0
if (api_is_invitee()) {
    $isInASession = $sessionId > 0;
    $isSubscribed = CourseManager::is_user_subscribed_in_course($user_id, $course_code, $isInASession, $sessionId);
    if (!$isSubscribed) {
        api_not_allowed(true);
    }
}
//Deleting group session
Session::erase('toolgroup');
Session::erase('_gid');
$isSpecialCourse = CourseManager::isSpecialCourse($courseId);
if ($isSpecialCourse) {
    if (isset($_GET['autoreg'])) {
        $autoRegistration = Security::remove_XSS($_GET['autoreg']);
        if ($autoRegistration == 1) {
            if (CourseManager::subscribe_user($user_id, $course_code, STUDENT)) {
                Session::write('is_allowed_in_course', true);
            }
        }
    }
}
if (isset($_GET['action']) && $_GET['action'] == 'subscribe') {
    if (Security::check_token('get')) {
        Security::clear_token();
        $auth = new Auth();
        $msg = $auth->subscribe_user($course_code);
        if (CourseManager::is_user_subscribed_in_course($user_id, $course_code)) {
            Session::write('is_allowed_in_course', true);
        }
        if (!empty($msg)) {
            $show_message .= Display::return_message(get_lang($msg['message']), 'info', false);
Exemplo n.º 8
0
 /**
  * Subscribe users to a group
  * @param int     $usergroup_id usergroup id
  * @param array   $list list of user ids     *
  * @param bool $delete_users_not_present_in_list
  * @param array $relationType
  */
 public function subscribe_users_to_usergroup($usergroup_id, $list, $delete_users_not_present_in_list = true, $relationType = '')
 {
     $current_list = self::get_users_by_usergroup($usergroup_id);
     $course_list = self::get_courses_by_usergroup($usergroup_id);
     $session_list = self::get_sessions_by_usergroup($usergroup_id);
     $delete_items = array();
     $new_items = array();
     if (!empty($list)) {
         foreach ($list as $user_id) {
             if (!in_array($user_id, $current_list)) {
                 $new_items[] = $user_id;
             }
         }
     }
     if (!empty($current_list)) {
         foreach ($current_list as $user_id) {
             if (!in_array($user_id, $list)) {
                 $delete_items[] = $user_id;
             }
         }
     }
     // Deleting items
     if (!empty($delete_items) && $delete_users_not_present_in_list) {
         foreach ($delete_items as $user_id) {
             // Removing courses
             if (!empty($course_list)) {
                 foreach ($course_list as $course_id) {
                     $course_info = api_get_course_info_by_id($course_id);
                     CourseManager::unsubscribe_user($user_id, $course_info['code']);
                 }
             }
             // Removing sessions
             if (!empty($session_list)) {
                 foreach ($session_list as $session_id) {
                     SessionManager::unsubscribe_user_from_session($session_id, $user_id);
                 }
             }
             Database::delete($this->usergroup_rel_user_table, array('usergroup_id = ? AND user_id = ? AND relation_type = ?' => array($usergroup_id, $user_id, $relationType)));
         }
     }
     // Adding new relationships
     if (!empty($new_items)) {
         // Adding sessions
         if (!empty($session_list)) {
             foreach ($session_list as $session_id) {
                 SessionManager::suscribe_users_to_session($session_id, $new_items, null, false);
             }
         }
         foreach ($new_items as $user_id) {
             // Adding courses
             if (!empty($course_list)) {
                 foreach ($course_list as $course_id) {
                     $course_info = api_get_course_info_by_id($course_id);
                     CourseManager::subscribe_user($user_id, $course_info['code']);
                 }
             }
             $params = array('user_id' => $user_id, 'usergroup_id' => $usergroup_id, 'relation_type' => $relationType);
             Database::insert($this->usergroup_rel_user_table, $params);
         }
     }
 }
/**
 * Saves imported data.
 */
function save_data($users_courses)
{
    $user_table = Database::get_main_table(TABLE_MAIN_USER);
    $course_user_table = Database::get_main_table(TABLE_MAIN_COURSE_USER);
    $csv_data = array();
    $inserted_in_course = array();
    foreach ($users_courses as $user_course) {
        $csv_data[$user_course['Email']][$user_course['CourseCode']] = $user_course['Status'];
    }
    foreach ($csv_data as $email => $csv_subscriptions) {
        $sql = "SELECT * FROM {$user_table} u\n                WHERE u.email = '" . Database::escape_string($email) . "' LIMIT 1";
        $res = Database::query($sql);
        $obj = Database::fetch_object($res);
        $user_id = $obj->user_id;
        $sql = "SELECT * FROM {$course_user_table} cu\n                WHERE cu.user_id = {$user_id} AND cu.relation_type <> " . COURSE_RELATION_TYPE_RRHH . " ";
        $res = Database::query($sql);
        $db_subscriptions = array();
        while ($obj = Database::fetch_object($res)) {
            $db_subscriptions[$obj->c_id] = $obj->status;
        }
        $to_subscribe = array_diff(array_keys($csv_subscriptions), array_keys($db_subscriptions));
        $to_unsubscribe = array_diff(array_keys($db_subscriptions), array_keys($csv_subscriptions));
        if ($_POST['subscribe']) {
            foreach ($to_subscribe as $courseId) {
                $courseInfo = api_get_course_info_by_id($courseId);
                $course_code = $courseInfo['code'];
                if (CourseManager::course_exists($course_code)) {
                    $course_info = CourseManager::get_course_information($course_code);
                    $inserted_in_course[$course_code] = $course_info['title'];
                    CourseManager::subscribe_user($user_id, $course_code, $csv_subscriptions[$course_code]);
                    $inserted_in_course[$course_info['code']] = $course_info['title'];
                }
            }
        }
        if ($_POST['unsubscribe']) {
            foreach ($to_unsubscribe as $courseId) {
                $courseInfo = api_get_course_info_by_id($courseId);
                $course_code = $courseInfo['code'];
                if (CourseManager::course_exists($course_code)) {
                    CourseManager::unsubscribe_user($user_id, $course_code);
                    $course_info = CourseManager::get_course_information($course_code);
                    CourseManager::unsubscribe_user($user_id, $course_code);
                    $inserted_in_course[$course_info['code']] = $course_info['title'];
                }
            }
        }
    }
    return $inserted_in_course;
}
Exemplo n.º 10
0
/**
 * Save the imported data
 */
function save_data($users)
{
    $user_table = Database::get_main_table(TABLE_MAIN_USER);
    if (is_array($users)) {
        foreach ($users as $index => $user) {
            $user = complete_missing_data($user);
            $user['Status'] = api_status_key($user['Status']);
            $user_id = UserManager::create_user($user['FirstName'], $user['LastName'], $user['Status'], $user['Email'], $user['UserName'], $user['Password'], $user['OfficialCode'], api_get_setting('PlatformLanguage'), $user['PhoneNumber'], '', $user['AuthSource']);
            foreach ($user['Courses'] as $index => $course) {
                if (CourseManager::course_exists($course)) {
                    CourseManager::subscribe_user($user_id, $course, $user['Status']);
                }
            }
            if (strlen($user['ClassName']) > 0) {
                $class_id = ClassManager::get_class_id($user['ClassName']);
                ClassManager::add_user($user_id, $class_id);
            }
            // TODO: Hard-coded French texts.
            // Qualite
            if (!empty($user['Qualite'])) {
                UserManager::update_extra_field_value($user_id, 'qualite', $user['Qualite']);
            }
            // Categorie
            if (!empty($user['Categorie'])) {
                UserManager::update_extra_field_value($user_id, 'categorie', $user['Categorie']);
            }
            // Etat
            if (!empty($user['Etat'])) {
                UserManager::update_extra_field_value($user_id, 'etat', $user['Etat']);
            }
            // Niveau
            if (!empty($user['Niveau'])) {
                UserManager::update_extra_field_value($user_id, 'niveau', $user['Niveau']);
            }
        }
    }
}
Exemplo n.º 11
0
 /**
  * Subscribe all members of a class to a course
  * @param  int $class_id The class id
  * @param string $course_code The course code
  */
 public static function subscribe_to_course($class_id, $course_code)
 {
     $tbl_course_class = Database::get_main_table(TABLE_MAIN_COURSE_CLASS);
     $tbl_class_user = Database::get_main_table(TABLE_MAIN_CLASS_USER);
     $tbl_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
     $sql = "INSERT IGNORE INTO {$tbl_course_class} SET course_code = '" . Database::escape_string($course_code) . "', class_id = '" . Database::escape_string($class_id) . "'";
     Database::query($sql);
     $sql = "SELECT user_id FROM {$tbl_class_user} WHERE class_id = '" . intval($class_id) . "'";
     $res = Database::query($sql);
     while ($user = Database::fetch_object($res)) {
         CourseManager::subscribe_user($user->user_id, $course_code);
     }
 }
Exemplo n.º 12
0
/**
 * Update the user in chamilo database. It upgrade only info that is present in the
 * new_user array
 *
 * @param $new_user associative array with the value to upgrade
 *    WARNING user_id key is MANDATORY
 *    Possible keys are :
 *      - firstname
 *      - lastname
 *      - username
 *      - auth_source
 *      - email
 *      - status
 *      - official_code
 *      - phone
 *      - picture_uri
 *      - expiration_date
 *      - active
 *      - creator_id
 *      - hr_dept_id
 *      - extra : array of custom fields
 *      - language
 *      - courses : string of all courses code separated by '|'
 *      - admin : boolean
 * @return boolean
 * @author ndiechburg <*****@*****.**>
 * */
function external_update_user($new_user)
{
    $old_user = api_get_user_info($new_user['user_id']);
    $u = array_merge($old_user, $new_user);
    $updated = UserManager::update_user($u['user_id'], $u['firstname'], $u['lastname'], $u['username'], null, $u['auth_source'], $u['email'], $u['status'], $u['official_code'], $u['phone'], $u['picture_uri'], $u['expiration_date'], $u['active'], $u['creator_id'], $u['hr_dept_id'], $u['extra'], $u['language'], '');
    if (isset($u['courses']) && !empty($u['courses'])) {
        $autoSubscribe = explode('|', $u['courses']);
        foreach ($autoSubscribe as $code) {
            if (CourseManager::course_exists($code)) {
                CourseManager::subscribe_user($u['user_id'], $code);
            }
        }
    }
    // Is User Admin ?
    //TODO decomments and check that user_is is not already in admin table
    /*
          if (isset($u['admin']) && $u['admin']){
    
          $table = Database::get_main_table(TABLE_MAIN_ADMIN);
          $res = Database::query("SELECT * from $table WHERE user_id = ".$u['user_id']);
          } */
}
Exemplo n.º 13
0
 /**
  * @Route("/", name="course_home")
  * @Route("/index.php")
  * @Method({"GET"})
  * @return Response
  */
 public function indexAction(Request $request)
 {
     $course = $this->getCourse();
     $session = $this->getSession();
     // Already added in the listener.
     /*if (false === $this->isGranted('view', $course)) {
           throw new AccessDeniedException('Unauthorised access!');
       }*/
     $courseCode = $course->getId();
     $sessionId = api_get_session_id();
     $sessionHandler = $request->getSession();
     $coursesAlreadyVisited = $sessionHandler->get('coursesAlreadyVisited');
     $result = $this->autolaunch();
     $showAutoLaunchLpWarning = $result['show_autolaunch_lp_warning'];
     $showAutoLaunchExerciseWarning = $result['show_autolaunch_exercise_warning'];
     if ($showAutoLaunchLpWarning) {
         $this->addFlash('warning', 'TheLPAutoLaunchSettingIsONStudentsWillBeRedirectToAnSpecificLP');
     }
     if ($showAutoLaunchExerciseWarning) {
         $this->addFlash('warning', 'TheExerciseAutoLaunchSettingIsONStudentsWillBeRedirectToAnSpecificExercise');
     }
     if (true) {
         $editIcons = Display::url(Display::return_icon('edit.png'), $this->generateUrl('chamilo_course_home_home_iconlist', array('course' => api_get_course_id())));
     }
     // Course access events
     $dispatcher = $this->container->get('event_dispatcher');
     $dispatcher->dispatch('chamilo_course.course.access', new CourseAccess($this->getUser(), $course));
     if (!isset($coursesAlreadyVisited[$courseCode])) {
         $dispatcher = $this->container->get('event_dispatcher');
         if (empty($sessionId)) {
             $dispatcher->dispatch('chamilo_course.course.access', new CourseAccess($this->getUser(), $course));
         } else {
             $dispatcher->dispatch('chamilo_course.course.access', new SessionAccess($this->getUser(), $course, $session));
         }
         $coursesAlreadyVisited[$courseCode] = 1;
         $sessionHandler->set('coursesAlreadyVisited', $coursesAlreadyVisited);
     }
     $sessionHandler->remove('toolgroup');
     $sessionHandler->remove('_gid');
     $isSpecialCourse = \CourseManager::is_special_course($courseCode);
     if ($isSpecialCourse) {
         $user = $this->getUser();
         if (!empty($user)) {
             $userId = $this->getUser()->getId();
             $autoreg = $this->getRequest()->get('autoreg');
             if ($autoreg == 1) {
                 \CourseManager::subscribe_user($userId, $courseCode, STUDENT);
             }
         }
     }
     $homeView = api_get_setting('course.homepage_view');
     $homeView = 'activity_big';
     if ($homeView == 'activity' || $homeView == 'activity_big') {
         $result = $this->renderActivityView();
     } elseif ($homeView == '2column') {
         $result = $this->render2ColumnView();
     } elseif ($homeView == '3column') {
         $result = $this->render3ColumnView();
     } elseif ($homeView == 'vertical_activity') {
         $result = $this->renderVerticalActivityView();
     }
     $toolList = $result['tool_list'];
     $introduction = Display::return_introduction_section($this->get('router'), TOOL_COURSE_HOMEPAGE, $toolList);
     $sessionInfo = null;
     if (api_get_setting('session.show_session_data') == 'true' && $sessionId) {
         $sessionInfo = CourseHome::show_session_data($sessionId);
     }
     /*$response = $this->render(
                 'ChamiloCoreBundle:Tool:Home/index.html.twig',
                 array(
                     'session_info' => $sessionInfo,
                     'icons' => $result['content'],
                     'edit_icons' => $editIcons,
                     'introduction_text' => $introduction,
                     'exercise_warning' => null,
                     'lp_warning' => null
                 )
             );
     
             return new Response($response, 200, array());*/
     return $this->render('ChamiloCourseBundle:Home:index.html.twig', array('course' => $course, 'session_info' => $sessionInfo, 'icons' => $result['content'], 'edit_icons' => $editIcons, 'introduction_text' => $introduction, 'exercise_warning' => null, 'lp_warning' => null));
 }
Exemplo n.º 14
0
} else {
    $user = external_get_user_info($login, $password);
}
if ($user !== false && ($chamilo_uid = external_add_user($user)) !== false) {
    //log in the user
    $loginFailed = false;
    $_user['user_id'] = $chamilo_uid;
    $_user['uidReset'] = true;
    Session::write('_user', $_user);
    $uidReset = true;
    //Autosubscribe to courses
    if (!empty($user['courses'])) {
        $autoSubscribe = explode('|', $user['courses']);
        foreach ($autoSubscribe as $code) {
            if (CourseManager::course_exists($code)) {
                CourseManager::subscribe_user($_user['user_id'], $code);
            }
        }
    }
    // Is User Admin ?
    if ($user['admin']) {
        $is_platformAdmin = true;
        Database::query("INSERT INTO admin values ('{$chamilo_uid}')");
    }
    // Can user create course
    $is_allowedCreateCourse = (bool) ($user['status'] == COURSEMANAGER or api_get_setting('drhCourseManagerRights') and $user['status'] == SESSIONADMIN);
    event_login();
} else {
    $loginFailed = true;
    unset($_user['user_id']);
    $uidReset = false;
Exemplo n.º 15
0
/**
 * Save the imported data
 * @param   array   $users List of users
 * @return  void
 * @uses global variable $inserted_in_course, which returns the list of courses the user was inserted in
 */
function save_data($users)
{
    global $inserted_in_course;
    // Not all scripts declare the $inserted_in_course array (although they should).
    if (!isset($inserted_in_course)) {
        $inserted_in_course = array();
    }
    $usergroup = new UserGroup();
    $send_mail = $_POST['sendMail'] ? true : false;
    if (is_array($users)) {
        foreach ($users as $user) {
            $user = complete_missing_data($user);
            $user['Status'] = api_status_key($user['Status']);
            $user_id = UserManager::create_user($user['FirstName'], $user['LastName'], $user['Status'], $user['Email'], $user['UserName'], $user['Password'], $user['OfficialCode'], $user['language'], $user['PhoneNumber'], '', $user['AuthSource'], $user['ExpiryDate'], 1, 0, null, null, $send_mail);
            if (!is_array($user['Courses']) && !empty($user['Courses'])) {
                $user['Courses'] = array($user['Courses']);
            }
            if (is_array($user['Courses'])) {
                foreach ($user['Courses'] as $course) {
                    if (CourseManager::course_exists($course)) {
                        CourseManager::subscribe_user($user_id, $course, $user['Status']);
                        $course_info = CourseManager::get_course_information($course);
                        $inserted_in_course[$course] = $course_info['title'];
                    }
                }
            }
            if (!empty($user['ClassId'])) {
                $classId = explode('|', trim($user['ClassId']));
                foreach ($classId as $id) {
                    $usergroup->subscribe_users_to_usergroup($id, array($user_id), false);
                }
            }
            // Saving extra fields.
            global $extra_fields;
            // We are sure that the extra field exists.
            foreach ($extra_fields as $extras) {
                if (isset($user[$extras[1]])) {
                    $key = $extras[1];
                    $value = $user[$extras[1]];
                    UserManager::update_extra_field_value($user_id, $key, $value);
                }
            }
        }
    }
}
Exemplo n.º 16
0
    $text_after_registration .= $form_register->returnForm();
    // Just in case
    Session::erase('course_redirect');
    Session::erase('exercise_redirect');
    if (CustomPages::enabled()) {
        CustomPages::display(CustomPages::REGISTRATION_FEEDBACK, array('info' => $text_after_registration));
    } else {
        //$tpl = new Template($tool_name);
        echo Container::getTemplating()->render('@template_style/auth/inscription.html.twig', ['inscription_content' => $content, 'text_after_registration' => $text_after_registration, 'hide_header' => $hideHeaders]);
    }
} else {
    // Custom pages
    if (CustomPages::enabled()) {
        CustomPages::display(CustomPages::REGISTRATION, array('form' => $form));
    } else {
        if (!api_is_anonymous()) {
            // Saving user to course if it was set.
            if (!empty($course_code_redirect)) {
                $course_info = api_get_course_info($course_code_redirect);
                if (!empty($course_info)) {
                    if (in_array($course_info['visibility'], array(COURSE_VISIBILITY_OPEN_PLATFORM, COURSE_VISIBILITY_OPEN_WORLD))) {
                        CourseManager::subscribe_user($user_id, $course_info['code']);
                    }
                }
            }
            CourseManager::redirectToCourse([]);
        }
        //$tpl = new Template($tool_name);
        echo Container::getTemplating()->render('@template_style/auth/inscription.html.twig', ['inscription_header' => Display::page_header($tool_name), 'inscription_content' => $content, 'hide_header' => $hideHeaders, 'form', $form->returnForm()]);
    }
}
 /**
  * Complete sale process. Update sale status to completed
  * @param int $saleId The sale ID
  * @return boolean
  */
 public function completeSale($saleId)
 {
     $sale = $this->getSale($saleId);
     if ($sale['status'] == self::SALE_STATUS_COMPLETED) {
         return true;
     }
     $saleIsCompleted = false;
     switch ($sale['product_type']) {
         case self::PRODUCT_TYPE_COURSE:
             $course = api_get_course_info_by_id($sale['product_id']);
             $saleIsCompleted = CourseManager::subscribe_user($sale['user_id'], $course['code']);
             break;
         case self::PRODUCT_TYPE_SESSION:
             SessionManager::suscribe_users_to_session($sale['product_id'], [$sale['user_id']], api_get_session_visibility($sale['product_id']), false);
             $saleIsCompleted = true;
             break;
     }
     if ($saleIsCompleted) {
         $this->updateSaleStatus($sale['id'], self::SALE_STATUS_COMPLETED);
     }
     return $saleIsCompleted;
 }
Exemplo n.º 18
0
 if (empty($invalid_users)) {
     $type = 'confirmation';
     $message = get_lang('ListOfUsersSubscribedToCourse');
     if ($unsubscribe_users) {
         $current_user_list = CourseManager::get_user_list_from_course_code($course_code, $session_id);
         if (!empty($current_user_list)) {
             $user_ids = array();
             foreach ($current_user_list as $user) {
                 $user_ids[] = $user['user_id'];
             }
             CourseManager::unsubscribe_user($user_ids, $course_code, $session_id);
         }
     }
     foreach ($clean_users as $userId) {
         $userInfo = api_get_user_info($userId);
         CourseManager::subscribe_user($userId, $course_code, STUDENT, $session_id);
         if (empty($session_id)) {
             //just to make sure
             if (CourseManager::is_user_subscribed_in_course($userId, $course_code)) {
                 $user_to_show[] = $userInfo['complete_name'];
             }
         } else {
             //just to make sure
             if (CourseManager::is_user_subscribed_in_course($userId, $course_code, true, $session_id)) {
                 $user_to_show[] = $userInfo['complete_name'];
             }
         }
     }
 } else {
     $message = get_lang('CheckUsersWithId');
     $type = 'warning';
Exemplo n.º 19
0
	/**
	 * Subscribe or unsubscribe user to a course (helper method)
	 *
	 * @param string Course id field name. Use "chamilo_course_id" to use internal id
	 * @param string Course id value.
	 * @param string User id field name. Use "chamilo_user_id" to use internal id
	 * @param string User id value
	 * @param int Set to 1 to subscribe, 0 to unsubscribe
	 * @param int Status (STUDENT or TEACHER) Used for subscription only
	 * @return mixed True if subscription or unsubscription was successful, false otherwise
	 */
	protected function changeUserSubscription($course_id_field_name, $course_id_value, $user_id_field_name, $user_id_value, $state, $status = STUDENT) {
		$course_id = $this->getCourseId($course_id_field_name, $course_id_value);
		if($course_id instanceof WSError) {
			return $course_id;
		} else {
			$user_id = $this->getUserId($user_id_field_name, $user_id_value);
			if($user_id instanceof WSError) {
				return $user_id;
			} else {
				$course_code = CourseManager::get_course_code_from_course_id($course_id);
				if($state == 0) {
					// Unsubscribe user
					CourseManager::unsubscribe_user($user_id, $course_code);
					return true;
				} else {
					// Subscribe user
					if(CourseManager::subscribe_user($user_id, $course_code, $status)) {
						return true;
					} else {
						return new WSError(203, 'An error occured subscribing to this course');
					}
				}
			}
		}
	}
Exemplo n.º 20
0
/**
 * Update users from the imported data
 * @param   array   $users List of users
 * @return  void
 * @uses global variable $inserted_in_course, which returns the list of courses the user was inserted in
 */
function updateUsers($users)
{
    global $insertedIn_course;
    // Not all scripts declare the $inserted_in_course array (although they should).
    if (!isset($inserted_in_course)) {
        $inserted_in_course = array();
    }
    $usergroup = new UserGroup();
    $send_mail = $_POST['sendMail'] ? true : false;
    if (is_array($users)) {
        foreach ($users as $user) {
            $user = complete_missing_data($user);
            $user['Status'] = api_status_key($user['Status']);
            $userName = $user['UserName'];
            $userInfo = api_get_user_info_from_username($userName);
            $user_id = $userInfo['user_id'];
            if ($user_id == 0) {
                return false;
            }
            $firstName = isset($user['FirstName']) ? $user['FirstName'] : $userInfo['firstname'];
            $lastName = isset($user['LastName']) ? $user['LastName'] : $userInfo['lastname'];
            $userName = isset($user['NewUserName']) ? $user['NewUserName'] : $userInfo['username'];
            $password = isset($user['Password']) ? $user['Password'] : $userInfo['password'];
            $authSource = isset($user['AuthSource']) ? $user['AuthSource'] : $userInfo['auth_source'];
            $email = isset($user['Email']) ? $user['Email'] : $userInfo['email'];
            $status = isset($user['Status']) ? $user['Status'] : $userInfo['status'];
            $officialCode = isset($user['OfficialCode']) ? $user['OfficialCode'] : $userInfo['official_code'];
            $phone = isset($user['PhoneNumber']) ? $user['PhoneNumber'] : $userInfo['phone'];
            $pictureUrl = isset($user['PictureUri']) ? $user['PictureUri'] : $userInfo['picture_uri'];
            $expirationDate = isset($user['ExpiryDate']) ? $user['ExpiryDate'] : $userInfo['expiration_date'];
            $active = isset($user['Active']) ? $user['Active'] : $userInfo['active'];
            $creatorId = $userInfo['creator_id'];
            $hrDeptId = $userInfo['hr_dept_id'];
            $language = isset($user['Language']) ? $user['Language'] : $userInfo['language'];
            $sendEmail = isset($user['SendEmail']) ? $user['SendEmail'] : $userInfo['language'];
            $userUpdated = UserManager::update_user($user_id, $firstName, $lastName, $userName, $password, $authSource, $email, $status, $officialCode, $phone, $pictureUrl, $expirationDate, $active, $creatorId, $hrDeptId, null, $language, '', '', '');
            if (!is_array($user['Courses']) && !empty($user['Courses'])) {
                $user['Courses'] = array($user['Courses']);
            }
            if (is_array($user['Courses'])) {
                foreach ($user['Courses'] as $course) {
                    if (CourseManager::course_exists($course)) {
                        CourseManager::subscribe_user($user_id, $course, $user['Status']);
                        $course_info = CourseManager::get_course_information($course);
                        $inserted_in_course[$course] = $course_info['title'];
                    }
                }
            }
            if (!empty($user['ClassId'])) {
                $classId = explode('|', trim($user['ClassId']));
                foreach ($classId as $id) {
                    $usergroup->subscribe_users_to_usergroup($id, array($user_id), false);
                }
            }
            // Saving extra fields.
            global $extra_fields;
            // We are sure that the extra field exists.
            foreach ($extra_fields as $extras) {
                if (isset($user[$extras[1]])) {
                    $key = $extras[1];
                    $value = $user[$extras[1]];
                    UserManager::update_extra_field_value($user_id, $key, $value);
                }
            }
        }
    }
}
Exemplo n.º 21
0
 /**
  * @param string $file
  * @param bool $updateSession options:
  *  true: if the session exists it will be updated.
  *  false: if session exists a new session will be created adding a counter session1, session2, etc
  * @param int $defaultUserId
  * @param mixed $logger
  * @param array $extraFields convert a file row to an extra field. Example in CSV file there's a SessionID then it will
  * converted to extra_external_session_id if you set this: array('SessionId' => 'extra_external_session_id')
  * @param string $extraFieldId
  * @param int $daysCoachAccessBeforeBeginning
  * @param int $daysCoachAccessAfterBeginning
  * @param int $sessionVisibility
  * @param array $fieldsToAvoidUpdate
  * @param bool $deleteUsersNotInList
  * @param bool $updateCourseCoaches
  * @param bool $sessionWithCoursesModifier
  * @param int $showDescription
  * @return array
  */
 static function importCSV($file, $updateSession, $defaultUserId = null, $logger = null, $extraFields = array(), $extraFieldId = null, $daysCoachAccessBeforeBeginning = null, $daysCoachAccessAfterBeginning = null, $sessionVisibility = 1, $fieldsToAvoidUpdate = array(), $deleteUsersNotInList = false, $updateCourseCoaches = false, $sessionWithCoursesModifier = false, $addOriginalCourseTeachersAsCourseSessionCoaches = true, $removeAllTeachersFromCourse = true, $showDescription = null)
 {
     $content = file($file);
     $error_message = null;
     $session_counter = 0;
     if (empty($defaultUserId)) {
         $defaultUserId = api_get_user_id();
     }
     $eol = PHP_EOL;
     if (PHP_SAPI != 'cli') {
         $eol = '<br />';
     }
     $debug = false;
     if (isset($logger)) {
         $debug = true;
     }
     $extraParameters = null;
     if (!empty($daysCoachAccessBeforeBeginning) && !empty($daysCoachAccessAfterBeginning)) {
         $extraParameters .= ' , nb_days_access_before_beginning = ' . intval($daysCoachAccessBeforeBeginning);
         $extraParameters .= ' , nb_days_access_after_end = ' . intval($daysCoachAccessAfterBeginning);
     }
     if (!is_null($showDescription)) {
         $extraParameters .= ' , show_description = ' . intval($showDescription);
     }
     $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
     $tbl_session_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
     $tbl_session_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
     $tbl_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
     $sessions = array();
     if (!api_strstr($content[0], ';')) {
         $error_message = get_lang('NotCSV');
     } else {
         $tag_names = array();
         foreach ($content as $key => $enreg) {
             $enreg = explode(';', trim($enreg));
             if ($key) {
                 foreach ($tag_names as $tag_key => $tag_name) {
                     $sessions[$key - 1][$tag_name] = $enreg[$tag_key];
                 }
             } else {
                 foreach ($enreg as $tag_name) {
                     $tag_names[] = api_preg_replace('/[^a-zA-Z0-9_\\-]/', '', $tag_name);
                 }
                 if (!in_array('SessionName', $tag_names) || !in_array('DateStart', $tag_names) || !in_array('DateEnd', $tag_names)) {
                     $error_message = get_lang('NoNeededData');
                     break;
                 }
             }
         }
         $sessionList = array();
         // Looping the sessions.
         foreach ($sessions as $enreg) {
             $user_counter = 0;
             $course_counter = 0;
             if (isset($extraFields) && !empty($extraFields)) {
                 foreach ($extraFields as $original => $to) {
                     $enreg[$to] = isset($enreg[$original]) ? $enreg[$original] : null;
                 }
             }
             $session_name = Database::escape_string($enreg['SessionName']);
             // Default visibility
             $visibilityAfterExpirationPerSession = $sessionVisibility;
             if (isset($enreg['VisibilityAfterExpiration'])) {
                 $visibility = $enreg['VisibilityAfterExpiration'];
                 switch ($visibility) {
                     case 'read_only':
                         $visibilityAfterExpirationPerSession = SESSION_VISIBLE_READ_ONLY;
                         break;
                     case 'accessible':
                         $visibilityAfterExpirationPerSession = SESSION_VISIBLE;
                         break;
                     case 'not_accessible':
                         $visibilityAfterExpirationPerSession = SESSION_INVISIBLE;
                         break;
                 }
             }
             if (empty($session_name)) {
                 continue;
             }
             $date_start = $enreg['DateStart'];
             $date_end = $enreg['DateEnd'];
             $session_category_id = isset($enreg['SessionCategory']) ? $enreg['SessionCategory'] : null;
             $sessionDescription = isset($enreg['SessionDescription']) ? $enreg['SessionDescription'] : null;
             $extraSessionParameters = null;
             if (!empty($sessionDescription)) {
                 $extraSessionParameters = " , description = '" . Database::escape_string($sessionDescription) . "'";
             }
             // Searching a general coach.
             if (!empty($enreg['Coach'])) {
                 $coach_id = UserManager::get_user_id_from_username($enreg['Coach']);
                 if ($coach_id === false) {
                     // If the coach-user does not exist - I'm the coach.
                     $coach_id = $defaultUserId;
                 }
             } else {
                 $coach_id = $defaultUserId;
             }
             if (!$updateSession) {
                 // Always create a session.
                 $unique_name = false;
                 $i = 0;
                 // Change session name, verify that session doesn't exist.
                 $suffix = null;
                 while (!$unique_name) {
                     if ($i > 1) {
                         $suffix = ' - ' . $i;
                     }
                     $sql = 'SELECT 1 FROM ' . $tbl_session . '
                             WHERE name="' . $session_name . $suffix . '"';
                     $rs = Database::query($sql);
                     if (Database::result($rs, 0, 0)) {
                         $i++;
                     } else {
                         $unique_name = true;
                         $session_name .= $suffix;
                     }
                 }
                 $sessionCondition = '';
                 if (!empty($session_category_id)) {
                     $sessionCondition = "session_category_id = '{$session_category_id}',";
                 }
                 // Creating the session.
                 $sql = "INSERT IGNORE INTO {$tbl_session} SET\n                            name = '" . $session_name . "',\n                            id_coach = '{$coach_id}',\n                            access_start_date = '{$date_start}',\n                            access_end_date = '{$date_end}',\n                            visibility = '{$visibilityAfterExpirationPerSession}',\n                            {$sessionCondition}\n                            session_admin_id = " . intval($defaultUserId) . $extraParameters . $extraSessionParameters;
                 Database::query($sql);
                 $session_id = Database::insert_id();
                 if ($debug) {
                     if ($session_id) {
                         foreach ($enreg as $key => $value) {
                             if (substr($key, 0, 6) == 'extra_') {
                                 //an extra field
                                 self::update_session_extra_field_value($session_id, substr($key, 6), $value);
                             }
                         }
                         $logger->addInfo("Sessions - Session created: #{$session_id} - {$session_name}");
                     } else {
                         $logger->addError("Sessions - Session NOT created: {$session_name}");
                     }
                 }
                 $session_counter++;
             } else {
                 $sessionId = null;
                 if (isset($extraFields) && !empty($extraFields) && !empty($enreg['extra_' . $extraFieldId])) {
                     $sessionId = self::getSessionIdFromOriginalId($enreg['extra_' . $extraFieldId], $extraFieldId);
                     if (empty($sessionId)) {
                         $my_session_result = false;
                     } else {
                         $my_session_result = true;
                     }
                 } else {
                     $my_session_result = self::get_session_by_name($enreg['SessionName']);
                 }
                 if ($my_session_result === false) {
                     // Creating a session.
                     $sql = "INSERT IGNORE INTO {$tbl_session} SET\n                                name = '{$session_name}',\n                                id_coach = '{$coach_id}',\n                                access_start_date = '{$date_start}',\n                                access_end_date = '{$date_end}',\n                                visibility = '{$visibilityAfterExpirationPerSession}',\n                                session_category_id = '{$session_category_id}' " . $extraParameters . $extraSessionParameters;
                     Database::query($sql);
                     // We get the last insert id.
                     $my_session_result = SessionManager::get_session_by_name($enreg['SessionName']);
                     $session_id = $my_session_result['id'];
                     if ($session_id) {
                         foreach ($enreg as $key => $value) {
                             if (substr($key, 0, 6) == 'extra_') {
                                 //an extra field
                                 self::update_session_extra_field_value($session_id, substr($key, 6), $value);
                             }
                         }
                         if ($debug) {
                             $logger->addInfo("Sessions - #{$session_id} created: {$session_name}");
                         }
                         // Delete session-user relation only for students
                         $sql = "DELETE FROM {$tbl_session_user}\n                                    WHERE session_id = '{$session_id}' AND relation_type <> " . SESSION_RELATION_TYPE_RRHH;
                         Database::query($sql);
                         $sql = "DELETE FROM {$tbl_session_course} WHERE session_id = '{$session_id}'";
                         Database::query($sql);
                         // Delete session-course-user relationships students and coaches.
                         if ($updateCourseCoaches) {
                             $sql = "DELETE FROM {$tbl_session_course_user}\n                                        WHERE session_id = '{$session_id}' AND status in ('0', '2')";
                             Database::query($sql);
                         } else {
                             // Delete session-course-user relation ships *only* for students.
                             $sql = "DELETE FROM {$tbl_session_course_user}\n                                        WHERE session_id = '{$session_id}' AND status <> 2";
                             Database::query($sql);
                         }
                     }
                 } else {
                     if ($debug) {
                         $logger->addError("Sessions - Session to be updated: {$session_name}");
                     }
                     // Updating the session.
                     $params = array('id_coach' => $coach_id, 'access_start_date' => $date_start, 'access_end_date' => $date_end, 'visibility' => $visibilityAfterExpirationPerSession, 'session_category_id' => $session_category_id);
                     if (!empty($sessionDescription)) {
                         $params['description'] = $sessionDescription;
                     }
                     if (!empty($fieldsToAvoidUpdate)) {
                         foreach ($fieldsToAvoidUpdate as $field) {
                             unset($params[$field]);
                         }
                     }
                     if (isset($sessionId) && !empty($sessionId)) {
                         if (!empty($enreg['SessionName'])) {
                             $params['name'] = $enreg['SessionName'];
                         }
                         $session_id = $sessionId;
                     } else {
                         $row = Database::query("SELECT id FROM {$tbl_session} WHERE name = '{$session_name}'");
                         list($session_id) = Database::fetch_array($row);
                     }
                     if ($session_id) {
                         if ($debug) {
                             $logger->addError("Sessions - Session to be updated #{$session_id}");
                         }
                         $sessionInfo = api_get_session_info($session_id);
                         $params['show_description'] = isset($sessionInfo['show_description']) ? $sessionInfo['show_description'] : intval($showDescription);
                         if (!empty($daysCoachAccessBeforeBeginning) && !empty($daysCoachAccessAfterBeginning)) {
                             if (empty($sessionInfo['nb_days_access_before_beginning']) || !empty($sessionInfo['nb_days_access_before_beginning']) && $sessionInfo['nb_days_access_before_beginning'] < $daysCoachAccessBeforeBeginning) {
                                 $params['nb_days_access_before_beginning'] = intval($daysCoachAccessBeforeBeginning);
                             }
                             if (empty($sessionInfo['nb_days_access_after_end']) || !empty($sessionInfo['nb_days_access_after_end']) && $sessionInfo['nb_days_access_after_end'] < $daysCoachAccessAfterBeginning) {
                                 $params['nb_days_access_after_end'] = intval($daysCoachAccessAfterBeginning);
                             }
                         }
                         Database::update($tbl_session, $params, array('id = ?' => $session_id));
                         foreach ($enreg as $key => $value) {
                             if (substr($key, 0, 6) == 'extra_') {
                                 //an extra field
                                 self::update_session_extra_field_value($session_id, substr($key, 6), $value);
                             }
                         }
                         // Delete session-user relation only for students
                         $sql = "DELETE FROM {$tbl_session_user}\n                                    WHERE session_id = '{$session_id}' AND relation_type <> " . SESSION_RELATION_TYPE_RRHH;
                         Database::query($sql);
                         $sql = "DELETE FROM {$tbl_session_course} WHERE session_id = '{$session_id}'";
                         Database::query($sql);
                         // Delete session-course-user relationships students and coaches.
                         if ($updateCourseCoaches) {
                             $sql = "DELETE FROM {$tbl_session_course_user}\n                                        WHERE session_id = '{$session_id}' AND status in ('0', '2')";
                             Database::query($sql);
                         } else {
                             // Delete session-course-user relation ships *only* for students.
                             $sql = "DELETE FROM {$tbl_session_course_user}\n                                        WHERE session_id = '{$session_id}' AND status <> 2";
                             Database::query($sql);
                         }
                     } else {
                         if ($debug) {
                             $logger->addError("Sessions - Session not found");
                         }
                     }
                 }
                 $session_counter++;
             }
             $sessionList[] = $session_id;
             $users = explode('|', $enreg['Users']);
             // Adding the relationship "Session - User" for students
             $userList = array();
             if (is_array($users)) {
                 foreach ($users as $user) {
                     $user_id = UserManager::get_user_id_from_username($user);
                     if ($user_id !== false) {
                         $userList[] = $user_id;
                         // Insert new users.
                         $sql = "INSERT IGNORE INTO {$tbl_session_user} SET\n                                    user_id = '{$user_id}',\n                                    session_id = '{$session_id}',\n                                    registered_at = '" . api_get_utc_datetime() . "'";
                         Database::query($sql);
                         if ($debug) {
                             $logger->addInfo("Sessions - Adding User #{$user_id} ({$user}) to session #{$session_id}");
                         }
                         $user_counter++;
                     }
                 }
             }
             if ($deleteUsersNotInList) {
                 // Getting user in DB in order to compare to the new list.
                 $usersListInDatabase = self::get_users_by_session($session_id, 0);
                 if (!empty($usersListInDatabase)) {
                     if (empty($userList)) {
                         foreach ($usersListInDatabase as $userInfo) {
                             self::unsubscribe_user_from_session($session_id, $userInfo['user_id']);
                         }
                     } else {
                         foreach ($usersListInDatabase as $userInfo) {
                             if (!in_array($userInfo['user_id'], $userList)) {
                                 self::unsubscribe_user_from_session($session_id, $userInfo['user_id']);
                             }
                         }
                     }
                 }
             }
             $courses = explode('|', $enreg['Courses']);
             // See BT#6449
             $onlyAddFirstCoachOrTeacher = false;
             if ($sessionWithCoursesModifier) {
                 if (count($courses) >= 2) {
                     // Only first teacher in course session;
                     $onlyAddFirstCoachOrTeacher = true;
                     // Remove all teachers from course.
                     $removeAllTeachersFromCourse = false;
                 }
             }
             foreach ($courses as $course) {
                 $courseArray = bracketsToArray($course);
                 $course_code = $courseArray[0];
                 if (CourseManager::course_exists($course_code)) {
                     $courseInfo = api_get_course_info($course_code);
                     $courseId = $courseInfo['real_id'];
                     // Adding the course to a session.
                     $sql = "INSERT IGNORE INTO {$tbl_session_course}\n                                SET c_id = '{$courseId}', session_id='{$session_id}'";
                     Database::query($sql);
                     SessionManager::installCourse($session_id, $courseInfo['real_id']);
                     if ($debug) {
                         $logger->addInfo("Sessions - Adding course '{$course_code}' to session #{$session_id}");
                     }
                     $course_counter++;
                     $course_coaches = isset($courseArray[1]) ? $courseArray[1] : null;
                     $course_users = isset($courseArray[2]) ? $courseArray[2] : null;
                     $course_users = explode(',', $course_users);
                     $course_coaches = explode(',', $course_coaches);
                     // Checking if the flag is set TeachersWillBeAddedAsCoachInAllCourseSessions (course_edit.php)
                     $addTeachersToSession = true;
                     if (array_key_exists('add_teachers_to_sessions_courses', $courseInfo)) {
                         $addTeachersToSession = $courseInfo['add_teachers_to_sessions_courses'];
                     }
                     // If any user provided for a course, use the users array.
                     if (empty($course_users)) {
                         if (!empty($userList)) {
                             SessionManager::subscribe_users_to_session_course($userList, $session_id, $course_code);
                             if ($debug) {
                                 $msg = "Sessions - Adding student list " . implode(', #', $userList) . " to course: '{$course_code}' and session #{$session_id}";
                                 $logger->addInfo($msg);
                             }
                         }
                     }
                     // Adding coaches to session course user.
                     if (!empty($course_coaches)) {
                         $savedCoaches = array();
                         // only edit if add_teachers_to_sessions_courses is set.
                         if ($addTeachersToSession) {
                             if ($addOriginalCourseTeachersAsCourseSessionCoaches) {
                                 // Adding course teachers as course session teachers.
                                 $alreadyAddedTeachers = CourseManager::get_teacher_list_from_course_code($course_code);
                                 if (!empty($alreadyAddedTeachers)) {
                                     $teachersToAdd = array();
                                     foreach ($alreadyAddedTeachers as $user) {
                                         $teachersToAdd[] = $user['username'];
                                     }
                                     $course_coaches = array_merge($course_coaches, $teachersToAdd);
                                 }
                             }
                             foreach ($course_coaches as $course_coach) {
                                 $coach_id = UserManager::get_user_id_from_username($course_coach);
                                 if ($coach_id !== false) {
                                     // Just insert new coaches
                                     SessionManager::updateCoaches($session_id, $courseId, array($coach_id), false);
                                     if ($debug) {
                                         $logger->addInfo("Sessions - Adding course coach: user #{$coach_id} ({$course_coach}) to course: '{$course_code}' and session #{$session_id}");
                                     }
                                     $savedCoaches[] = $coach_id;
                                 } else {
                                     $error_message .= get_lang('UserDoesNotExist') . ' : ' . $course_coach . $eol;
                                 }
                             }
                         }
                         // Custom courses/session coaches
                         $teacherToAdd = null;
                         // Only one coach is added.
                         if ($onlyAddFirstCoachOrTeacher == true) {
                             foreach ($course_coaches as $course_coach) {
                                 $coach_id = UserManager::get_user_id_from_username($course_coach);
                                 if ($coach_id !== false) {
                                     $teacherToAdd = $coach_id;
                                     break;
                                 }
                             }
                             // Un subscribe everyone that's not in the list.
                             $teacherList = CourseManager::get_teacher_list_from_course_code($course_code);
                             if (!empty($teacherList)) {
                                 foreach ($teacherList as $teacher) {
                                     if ($teacherToAdd != $teacher['user_id']) {
                                         CourseManager::unsubscribe_user($teacher['user_id'], $course_code);
                                     }
                                 }
                             }
                             if (!empty($teacherToAdd)) {
                                 SessionManager::updateCoaches($session_id, $courseId, array($teacherToAdd), true);
                                 CourseManager::subscribe_user($teacherToAdd, $course_code, COURSEMANAGER);
                             }
                         }
                         // See BT#6449#note-195
                         // All coaches are added.
                         if ($removeAllTeachersFromCourse) {
                             $teacherToAdd = null;
                             foreach ($course_coaches as $course_coach) {
                                 $coach_id = UserManager::get_user_id_from_username($course_coach);
                                 if ($coach_id !== false) {
                                     $teacherToAdd[] = $coach_id;
                                 }
                             }
                             if (!empty($teacherToAdd)) {
                                 // Deleting all course teachers and adding the only coach as teacher.
                                 $teacherList = CourseManager::get_teacher_list_from_course_code($course_code);
                                 if (!empty($teacherList)) {
                                     foreach ($teacherList as $teacher) {
                                         if (!in_array($teacher['user_id'], $teacherToAdd)) {
                                             CourseManager::unsubscribe_user($teacher['user_id'], $course_code);
                                         }
                                     }
                                 }
                                 foreach ($teacherToAdd as $teacherId) {
                                     CourseManager::subscribe_user($teacherId, $course_code, COURSEMANAGER);
                                 }
                             }
                         }
                         // Continue default behaviour.
                         if ($onlyAddFirstCoachOrTeacher == false) {
                             // Checking one more time see BT#6449#note-149
                             $coaches = SessionManager::getCoachesByCourseSession($session_id, $courseId);
                             // Update coaches if only there's 1 course see BT#6449#note-189
                             if (empty($coaches) || count($courses) == 1) {
                                 foreach ($course_coaches as $course_coach) {
                                     $course_coach = trim($course_coach);
                                     $coach_id = UserManager::get_user_id_from_username($course_coach);
                                     if ($coach_id !== false) {
                                         // Just insert new coaches
                                         SessionManager::updateCoaches($session_id, $courseId, array($coach_id), false);
                                         if ($debug) {
                                             $logger->addInfo("Sessions - Adding course coach: user #{$coach_id} ({$course_coach}) to course: '{$course_code}' and session #{$session_id}");
                                         }
                                         $savedCoaches[] = $coach_id;
                                     } else {
                                         $error_message .= get_lang('UserDoesNotExist') . ' : ' . $course_coach . $eol;
                                     }
                                 }
                             }
                         }
                     }
                     // Adding Students, updating relationship "Session - Course - User".
                     $course_users = array_filter($course_users);
                     if (!empty($course_users)) {
                         foreach ($course_users as $user) {
                             $user_id = UserManager::get_user_id_from_username($user);
                             if ($user_id !== false) {
                                 SessionManager::subscribe_users_to_session_course(array($user_id), $session_id, $course_code);
                                 if ($debug) {
                                     $logger->addInfo("Sessions - Adding student: user #{$user_id} ({$user}) to course: '{$course_code}' and session #{$session_id}");
                                 }
                             } else {
                                 $error_message .= get_lang('UserDoesNotExist') . ': ' . $user . $eol;
                             }
                         }
                     }
                     $inserted_in_course[$course_code] = $courseInfo['title'];
                 }
             }
             $access_url_id = api_get_current_access_url_id();
             UrlManager::add_session_to_url($session_id, $access_url_id);
             $sql = "UPDATE {$tbl_session} SET nbr_users = '{$user_counter}', nbr_courses = '{$course_counter}' WHERE id = '{$session_id}'";
             Database::query($sql);
         }
     }
     return array('error_message' => $error_message, 'session_counter' => $session_counter, 'session_list' => $sessionList);
 }
    $courses = is_array($_POST['CourseList']) ? $_POST['CourseList'] : array();
    $first_letter_user = $_POST['firstLetterUser'];
    $first_letter_course = $_POST['firstLetterCourse'];
    foreach ($users as $key => $value) {
        $users[$key] = intval($value);
    }
    if ($form_sent == 1) {
        if (count($users) == 0 || count($courses) == 0) {
            Display::display_error_message(get_lang('AtLeastOneUserAndOneCourse'));
        } else {
            $errorDrh = 0;
            foreach ($courses as $course_code) {
                foreach ($users as $user_id) {
                    $user = api_get_user_info($user_id);
                    if ($user['status'] != DRH) {
                        CourseManager::subscribe_user($user_id, $course_code);
                    } else {
                        $errorDrh = 1;
                    }
                }
            }
            if ($errorDrh == 0) {
                Display::display_confirmation_message(get_lang('UsersAreSubscibedToCourse'));
            } else {
                Display::display_error_message(get_lang('HumanResourcesManagerShouldNotBeRegisteredToCourses'));
            }
        }
    }
}
/* Display GUI */
if (empty($first_letter_user)) {
Exemplo n.º 23
0
/**
 * Save the imported data
 * @param   array   List of users
 * @return  void
 * @uses global variable $inserted_in_course, which returns the list of courses the user was inserted in
 */
function save_data($users)
{
    global $inserted_in_course;
    // Not all scripts declare the $inserted_in_course array (although they should).
    if (!isset($inserted_in_course)) {
        $inserted_in_course = array();
    }
    $send_mail = $_POST['sendMail'] ? 1 : 0;
    if (is_array($users)) {
        foreach ($users as $index => $user) {
            $user = complete_missing_data($user);
            $user['Status'] = api_status_key($user['Status']);
            $user_id = UserManager::create_user($user['FirstName'], $user['LastName'], $user['Status'], $user['Email'], $user['UserName'], $user['Password'], $user['OfficialCode'], $user['language'], $user['PhoneNumber'], '', $user['AuthSource'], null, 1, 0, null, null, $send_mail);
            if (!is_array($user['Courses']) && !empty($user['Courses'])) {
                $user['Courses'] = array($user['Courses']);
            }
            if (is_array($user['Courses'])) {
                foreach ($user['Courses'] as $index => $course) {
                    if (CourseManager::course_exists($course)) {
                        CourseManager::subscribe_user($user_id, $course, $user['Status']);
                        $course_info = CourseManager::get_course_information($course);
                        $inserted_in_course[$course] = $course_info['title'];
                    }
                    if (CourseManager::course_exists($course, true)) {
                        // Also subscribe to virtual courses through check on visual code.
                        $list = CourseManager::get_courses_info_from_visual_code($course);
                        foreach ($list as $vcourse) {
                            if ($vcourse['code'] == $course) {
                                // Ignore, this has already been inserted.
                            } else {
                                CourseManager::subscribe_user($user_id, $vcourse['code'], $user['Status']);
                                $inserted_in_course[$vcourse['code']] = $vcourse['title'];
                            }
                        }
                    }
                }
            }
            if (!empty($user['ClassName'])) {
                $class_id = ClassManager::get_class_id($user['ClassName']);
                ClassManager::add_user($user_id, $class_id);
            }
            // Saving extra fields.
            global $extra_fields;
            // We are sure that the extra field exists.
            foreach ($extra_fields as $extras) {
                if (isset($user[$extras[1]])) {
                    $key = $extras[1];
                    $value = $user[$extras[1]];
                    UserManager::update_extra_field_value($user_id, $key, $value);
                }
            }
        }
    }
}