Beispiel #1
0
 function loadBody()
 {
     switch ($GLOBALS['op']) {
         case 'showresults':
             $id_course = Get::req('id_course', DOTY_INT, false);
             $_SESSION['idCourse'] = $id_course;
             Util::jump_to('index.php?modname=organization&op=showresults&idcourse=' . $id_course);
             break;
         case "mycourses":
         case "unregistercourse":
             require_once $GLOBALS['where_lms'] . '/modules/' . $this->module_name . '/course.php';
             require_once _base_ . '/lib/lib.urlmanager.php';
             $url =& UrlManager::getInstance('course');
             $url->setStdQuery('r=' . _after_login_);
             mycourses($url);
             break;
         case "donwloadmaterials":
             downloadMaterials();
             break;
         default:
             require_once $GLOBALS['where_lms'] . '/modules/' . $this->module_name . '/infocourse.php';
             infocourseDispatch($GLOBALS['op']);
             break;
     }
 }
Beispiel #2
0
function mycompetencesDispatch($op)
{
    require_once _base_ . '/lib/lib.urlmanager.php';
    $url =& UrlManager::getInstance('competences');
    $url->setStdQuery('modname=mycompetences&op=mycompetences');
    switch ($op) {
        case "mycompetences":
        default:
            mycompetences($url);
    }
}
Beispiel #3
0
 function reservation()
 {
     checkPerm('view');
     require_once _base_ . '/lib/lib.tab.php';
     require_once _base_ . '/lib/lib.urlmanager.php';
     require_once _base_ . '/lib/lib.form.php';
     require_once $GLOBALS['where_lms'] . '/lib/lib.course.php';
     $mod_perm = checkPerm('mod', true);
     $lang =& DoceboLanguage::createInstance('reservation');
     $um =& UrlManager::getInstance("reservation");
     $out = $GLOBALS['page'];
     $out->setWorkingZone('content');
     $man_res = new Man_Reservation();
     $tab_man = new TabView('reservation', '');
     $tab_events = new TabElemDefault('events', $lang->def('_RESERVATION_EVENTS'));
     $tab_my_events = new TabElemDefault('my_events', $lang->def('_RESERVATION_MY_EVENTS'));
     $tab_past_event = new TabElemDefault('past_events', $lang->def('_RESERVATION_PAST_EVENTS'));
     if ($mod_perm) {
         $tab_subscribed_user = new TabElemDefault('subscribed_user', $lang->def('_RESERVATION_SUBSCRIBED_USER'));
     }
     $tab_man->addTab($tab_events);
     $tab_man->addTab($tab_my_events);
     $tab_man->addTab($tab_past_event);
     if ($mod_perm) {
         $tab_man->addTab($tab_subscribed_user);
     }
     $tab_man->parseInput($_POST, $_SESSION);
     $active_tab = $tab_man->getActiveTab();
     if ($active_tab != 'events' && $active_tab != 'my_events' && $active_tab != 'past_events' && $active_tab != 'subscribed_user') {
         $active_tab = importVar('active_tab', false, 'events');
         $tab_man->setActiveTab($active_tab);
     }
     $out->add(getTitleArea(Lang::t('_RESERVATION', 'reservation')) . '<div class="std_block">', 'content');
     $out->add(Form::openForm('tab_reservation', 'index.php?modname=reservation&amp;op=reservation&amp;confirm=1&amp;ap=mod_profile&amp;from=2') . $tab_man->printTabView_Begin('', false), 'content');
     switch ($active_tab) {
         case 'events':
             events();
             break;
         case 'my_events':
             myEvents();
             break;
         case 'past_events':
             pastEvents();
             break;
         case 'subscribed_user':
             subscribedUser();
             break;
     }
     $out->add($tab_man->printTabView_End() . Form::closeForm(), 'content');
     $out->add('</div>', 'content');
 }
 /**
  * Does not look like this function is being used is being used 
  * 
  * @param type $url_id
  * @return string 
  */
 public static function getURLImages($url_id = null)
 {
     if (is_null($url_id)) {
         $url = 'http://' . $_SERVER['HTTP_HOST'] . '/';
         $url_id = UrlManager::get_url_id($url);
     }
     $url_images_dir = api_get_path(SYS_PATH) . 'custompages/url-images/';
     $images = array();
     for ($img_id = 1; $img_id <= 3; $img_id++) {
         if (file_exists($url_images_dir . $url_id . '_url_image_' . $img_id . '.png')) {
             $images[] = api_get_path(WEB_PATH) . 'custompages/url-images/' . $url_id . '_url_image_' . $img_id . '.png';
         }
     }
     return $images;
 }
 public function reverse($name, $args = [])
 {
     if ($this->langInQuery) {
         $url = parent::reverse($name, $args);
         if (strpos($url, '?') === false) {
             $url .= '?lang=' . $this->lang;
         } else {
             $url .= '&lang=' . $this->lang;
         }
         return $url;
     } else {
         if (strpos($name, 'admin') === false) {
             $args = array_merge(['lang' => $this->lang], $args);
         }
         return parent::reverse($name, $args);
     }
 }
$form->addElement('textarea', 'description', get_lang('Description'));
//the first url with id = 1 will be always active
if (isset($_GET['url_id']) && $_GET['url_id'] != 1) {
    $form->addElement('checkbox', 'active', null, get_lang('Active'));
}
$defaults['url'] = 'http://';
$form->setDefaults($defaults);
$submit_name = get_lang('AddUrl');
if (isset($_GET['url_id'])) {
    $url_id = intval($_GET['url_id']);
    $num_url_id = UrlManager::url_id_exist($url_id);
    if ($num_url_id != 1) {
        header('Location: access_urls.php');
        exit;
    }
    $url_data = UrlManager::get_url_data_from_id($url_id);
    $form->addElement('hidden', 'id', $url_data['id']);
    $form->setDefaults($url_data);
    $submit_name = get_lang('AddUrl');
}
if (!api_is_multiple_url_enabled()) {
    header('Location: index.php');
    exit;
}
$tool_name = get_lang('AddUrl');
$interbreadcrumb[] = array("url" => 'index.php', "name" => get_lang('PlatformAdmin'));
$interbreadcrumb[] = array("url" => 'access_urls.php', "name" => get_lang('MultipleAccessURLs'));
Display::display_header($tool_name);
if (isset($_GET['action'])) {
    switch ($_GET['action']) {
        case 'show_message':
 /**
  * Function register_course to create a record in the course table of the main database
  * @param array Course details (see code for details)
  * @return int  Created course ID
  * @todo use an array called $params instead of lots of params
  * @assert (null) === false
  */
 public static function register_course($params)
 {
     global $error_msg, $firstExpirationDelay;
     $title = $params['title'];
     $code = $params['code'];
     $visual_code = $params['visual_code'];
     $directory = $params['directory'];
     $tutor_name = isset($params['tutor_name']) ? $params['tutor_name'] : null;
     //$description        = $params['description'];
     $category_code = isset($params['course_category']) ? $params['course_category'] : '';
     $course_language = isset($params['course_language']) && !empty($params['course_language']) ? $params['course_language'] : api_get_setting('language.platform_language');
     $user_id = empty($params['user_id']) ? api_get_user_id() : intval($params['user_id']);
     $department_name = isset($params['department_name']) ? $params['department_name'] : null;
     $department_url = isset($params['department_url']) ? $params['department_url'] : null;
     $disk_quota = isset($params['disk_quota']) ? $params['disk_quota'] : null;
     if (!isset($params['visibility'])) {
         $default_course_visibility = api_get_setting('course.courses_default_creation_visibility');
         if ($default_course_visibility != '') {
             $visibility = $default_course_visibility;
         } else {
             $visibility = COURSE_VISIBILITY_OPEN_PLATFORM;
         }
     } else {
         $visibility = $params['visibility'];
     }
     $subscribe = isset($params['subscribe']) ? intval($params['subscribe']) : ($visibility == COURSE_VISIBILITY_OPEN_PLATFORM ? 1 : 0);
     $unsubscribe = isset($params['unsubscribe']) ? intval($params['unsubscribe']) : 0;
     $expiration_date = isset($params['expiration_date']) ? $params['expiration_date'] : null;
     $teachers = isset($params['teachers']) ? $params['teachers'] : null;
     $status = isset($params['status']) ? $params['status'] : null;
     $TABLECOURSE = Database::get_main_table(TABLE_MAIN_COURSE);
     $TABLECOURSUSER = Database::get_main_table(TABLE_MAIN_COURSE_USER);
     $ok_to_register_course = true;
     // Check whether all the needed parameters are present.
     if (empty($code)) {
         $error_msg[] = 'courseSysCode is missing';
         $ok_to_register_course = false;
     }
     if (empty($visual_code)) {
         $error_msg[] = 'courseScreenCode is missing';
         $ok_to_register_course = false;
     }
     if (empty($directory)) {
         $error_msg[] = 'courseRepository is missing';
         $ok_to_register_course = false;
     }
     if (empty($title)) {
         $error_msg[] = 'title is missing';
         $ok_to_register_course = false;
     }
     if (empty($expiration_date)) {
         $expiration_date = api_get_utc_datetime(time() + $firstExpirationDelay);
     } else {
         $expiration_date = api_get_utc_datetime($expiration_date);
     }
     if ($visibility < 0 || $visibility > 4) {
         $error_msg[] = 'visibility is invalid';
         $ok_to_register_course = false;
     }
     if (empty($disk_quota)) {
         $disk_quota = api_get_setting('document.default_document_quotum');
     }
     $time = api_get_utc_datetime();
     if (stripos($department_url, 'http://') === false && stripos($department_url, 'https://') === false) {
         $department_url = 'http://' . $department_url;
     }
     //just in case
     if ($department_url == 'http://') {
         $department_url = '';
     }
     $course_id = 0;
     if ($ok_to_register_course) {
         // Here we must add 2 fields.
         $sql = "INSERT INTO " . $TABLECOURSE . " SET\n                        code = '" . Database::escape_string($code) . "',\n                        directory = '" . Database::escape_string($directory) . "',\n                        course_language = '" . Database::escape_string($course_language) . "',\n                        title = '" . Database::escape_string($title) . "',\n                        description = '" . self::lang2db(get_lang('CourseDescription')) . "',\n                        category_code = '" . Database::escape_string($category_code) . "',\n                        visibility      = '" . $visibility . "',\n                        show_score      = '1',\n                        disk_quota      = '" . intval($disk_quota) . "',\n                        creation_date   = '{$time}',\n                        expiration_date = '" . $expiration_date . "',\n                        last_edit       = '{$time}',\n                        last_visit      = NULL,\n                        tutor_name = '" . Database::escape_string($tutor_name) . "',\n                        department_name = '" . Database::escape_string($department_name) . "',\n                        department_url = '" . Database::escape_string($department_url) . "',\n                        subscribe = '" . intval($subscribe) . "',\n                        unsubscribe = '" . intval($unsubscribe) . "',\n                        visual_code = '" . Database::escape_string($visual_code) . "'";
         Database::query($sql);
         $course_id = Database::insert_id();
         if ($course_id) {
             $sort = api_max_sort_value('0', api_get_user_id());
             // Default true
             $addTeacher = isset($params['add_user_as_teacher']) ? $params['add_user_as_teacher'] : true;
             if ($addTeacher) {
                 $i_course_sort = CourseManager::userCourseSort($user_id, $code);
                 if (!empty($user_id)) {
                     $sql = "INSERT INTO " . $TABLECOURSUSER . " SET\n                                c_id     = '" . $course_id . "',\n                                user_id         = '" . intval($user_id) . "',\n                                status          = '1',\n                                is_tutor        = '0',\n                                sort            = '" . $i_course_sort . "',\n                                user_course_cat = '0'";
                     Database::query($sql);
                 }
             }
             if (!empty($teachers)) {
                 if (!is_array($teachers)) {
                     $teachers = array($teachers);
                 }
                 foreach ($teachers as $key) {
                     //just in case
                     if ($key == $user_id) {
                         continue;
                     }
                     if (empty($key)) {
                         continue;
                     }
                     $sql = "INSERT INTO " . $TABLECOURSUSER . " SET\n                            c_id     = '" . Database::escape_string($course_id) . "',\n                            user_id         = '" . Database::escape_string($key) . "',\n                            status          = '1',\n                            is_tutor        = '0',\n                            sort            = '" . ($sort + 1) . "',\n                            user_course_cat = '0'";
                     Database::query($sql);
                 }
             }
             // Adding the course to an URL.
             if (api_is_multiple_url_enabled()) {
                 $url_id = 1;
                 if (api_get_current_access_url_id() != -1) {
                     $url_id = api_get_current_access_url_id();
                 }
                 UrlManager::add_course_to_url($course_id, $url_id);
             } else {
                 UrlManager::add_course_to_url($course_id, 1);
             }
             // Add event to the system log.
             $user_id = api_get_user_id();
             Event::addEvent(LOG_COURSE_CREATE, LOG_COURSE_CODE, $code, api_get_utc_datetime(), $user_id, $course_id);
             $send_mail_to_admin = api_get_setting('course.send_email_to_admin_when_create_course');
             // @todo Improve code to send to all current portal administrators.
             if ($send_mail_to_admin == 'true') {
                 $siteName = api_get_setting('platform.site_name');
                 $recipient_email = api_get_setting('admin.administrator_email');
                 $recipient_name = api_get_person_name(api_get_setting('admin.administrator_name'), api_get_setting('admin.administrator_surname'));
                 $iname = api_get_setting('platform.institution');
                 $subject = get_lang('NewCourseCreatedIn') . ' ' . $siteName . ' - ' . $iname;
                 $message = get_lang('Dear') . ' ' . $recipient_name . ",\n\n" . get_lang('MessageOfNewCourseToAdmin') . ' ' . $siteName . ' - ' . $iname . "\n";
                 $message .= get_lang('CourseName') . ' ' . $title . "\n";
                 $message .= get_lang('Category') . ' ' . $category_code . "\n";
                 $message .= get_lang('Tutor') . ' ' . $tutor_name . "\n";
                 $message .= get_lang('Language') . ' ' . $course_language;
                 $userInfo = api_get_user_info($user_id);
                 $additionalParameters = array('smsType' => SmsPlugin::NEW_COURSE_BEEN_CREATED, 'userId' => $user_id, 'courseName' => $title, 'creatorUsername' => $userInfo['username']);
                 api_mail_html($recipient_name, $recipient_email, $subject, $message, $siteName, $recipient_email, null, null, null, $additionalParameters);
             }
         }
     }
     return $course_id;
 }
 /**
  * @param int $id
  *
  * @return bool
  */
 function addToUrl($id)
 {
     if (!self::isMultipleUrlSupport()) {
         return false;
     }
     UrlManager::addCourseCategoryListToUrl(array($id), array(api_get_current_access_url_id()));
 }
Beispiel #9
0
function dispatchConference($op)
{
    require_once _base_ . '/lib/lib.urlmanager.php';
    $url =& UrlManager::getInstance();
    $url->setStdQuery('modname=conference&op=list');
    if (isset($_POST['undo'])) {
        $op = 'list';
    }
    switch ($op) {
        case 'list':
            conference_list($url);
            break;
        case 'startnewconf':
            conference_startnewconf($url);
            break;
        case 'modconf':
            conference_modconf();
            break;
        case 'delconf':
            conference_delconf();
            break;
        case 'booking':
            booking();
            break;
        case 'modbooking':
            modBooking();
            break;
        case 'history':
            showHistory();
            break;
        case 'log':
            showLog();
            break;
        default:
            conference_list($url);
    }
}
echo '</div>';
api_display_tool_title($tool_name);
if ($_POST['form_sent']) {
    $form_sent = $_POST['form_sent'];
    $users = is_array($_POST['user_list']) ? $_POST['user_list'] : array();
    $url_list = is_array($_POST['url_list']) ? $_POST['url_list'] : array();
    $first_letter_user = $_POST['first_letter_user'];
    foreach ($users as $key => $value) {
        $users[$key] = intval($value);
    }
    if ($form_sent == 1) {
        if (count($users) == 0 || count($url_list) == 0) {
            Display::display_error_message(get_lang('AtLeastOneUserAndOneURL'));
            //header('Location: access_urls.php?action=show_message&message='.get_lang('AtLeastOneUserAndOneURL'));
        } else {
            UrlManager::add_users_to_urls($users, $url_list);
            Display::display_confirmation_message(get_lang('UsersBelongURL'));
            //header('Location: access_urls.php?action=show_message&message='.get_lang('UsersBelongURL'));
        }
    }
}
/*	Display GUI	*/
if (empty($first_letter_user)) {
    $sql = "SELECT count(*) as nb_users FROM {$tbl_user}";
    $result = Database::query($sql);
    $num_row = Database::fetch_array($result);
    if ($num_row['nb_users'] > 1000) {
        //if there are too much users to gracefully handle with the HTML select list,
        // assign a default filter on users names
        $first_letter_user = '******';
    }
Beispiel #11
0
function mycertificateDispatch($op)
{
    require_once $GLOBALS['where_lms'] . '/lib/lib.certificate.php';
    require_once _base_ . '/lib/lib.urlmanager.php';
    $url =& UrlManager::getInstance('mycertificate');
    $url->setStdQuery('modname=mycertificate&op=mycertificate');
    switch ($op) {
        case "preview_cert":
            preview_cert($url);
            break;
        case "release_cert":
            release_cert($url);
            break;
        case "mycertificate":
        default:
            mycertificate($url);
    }
}
Beispiel #12
0
 $conditions = array('username' => $keyword);
 $user_list = UserManager::get_user_list($conditions, array(), false, ' OR ');
 if (!empty($user_list)) {
     $extra_search_options = Display::page_subheader(get_lang('UsersFoundInOtherPortals'));
     $table = new HTML_Table(array('class' => 'data_table'));
     $column = 0;
     $row = 0;
     $headers = array(get_lang('User'), 'URL', get_lang('Actions'));
     foreach ($headers as $header) {
         $table->setHeaderContents($row, $column, $header);
         $column++;
     }
     $row++;
     foreach ($user_list as $user) {
         $column = 0;
         $access_info = UrlManager::get_access_url_from_user($user['id']);
         $access_info_to_string = '';
         $add_user = true;
         if (!empty($access_info)) {
             foreach ($access_info as $url_info) {
                 if ($current_access_url_id == $url_info['access_url_id']) {
                     $add_user = false;
                 }
                 $access_info_to_string .= $url_info['url'] . '<br />';
             }
         }
         if ($add_user) {
             $row_table = array();
             $row_table[] = api_get_person_name($user['firstname'], $user['lastname']) . ' (' . $user['username'] . ') ';
             $row_table[] = $access_info_to_string;
             $url = api_get_self() . '?action=add_user_to_my_url&user_id=' . $user['id'] . '&sec_token=' . $_SESSION['sec_token'];
 /**
  * Delete a user from the platform, and all its belongings. This is a
  * very dangerous function that should only be accessible by
  * super-admins. Other roles should only be able to disable a user,
  * which removes access to the platform but doesn't delete anything.
  * @param int The ID of th user to be deleted
  * @return boolean true if user is successfully deleted, false otherwise
  * @assert (null) === false
  * @assert ('abc') === false
  */
 public static function delete_user($user_id)
 {
     if ($user_id != strval(intval($user_id))) {
         return false;
     }
     if ($user_id === false) {
         return false;
     }
     if (!self::can_delete_user($user_id)) {
         return false;
     }
     $table_user = Database::get_main_table(TABLE_MAIN_USER);
     $usergroup_rel_user = Database::get_main_table(TABLE_USERGROUP_REL_USER);
     $table_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
     $table_course = Database::get_main_table(TABLE_MAIN_COURSE);
     $table_session = Database::get_main_table(TABLE_MAIN_SESSION);
     $table_admin = Database::get_main_table(TABLE_MAIN_ADMIN);
     $table_session_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
     $table_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
     $table_group = Database::get_course_table(TABLE_GROUP_USER);
     $table_work = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
     // Unsubscribe the user from all groups in all his courses
     $sql = "SELECT c.id FROM {$table_course} c, {$table_course_user} cu\n                WHERE\n                    cu.user_id = '" . $user_id . "' AND\n                    relation_type<>" . COURSE_RELATION_TYPE_RRHH . " AND\n                    c.id = cu.c_id";
     $res = Database::query($sql);
     while ($course = Database::fetch_object($res)) {
         $sql = "DELETE FROM {$table_group}\n                    WHERE c_id = {$course->id} AND user_id = {$user_id}";
         Database::query($sql);
     }
     // Unsubscribe user from all classes
     //Classes are not longer supported
     /* $sql = "DELETE FROM $table_class_user WHERE user_id = '".$user_id."'";
        Database::query($sql); */
     // Unsubscribe user from usergroup_rel_user
     $sql = "DELETE FROM {$usergroup_rel_user} WHERE user_id = '" . $user_id . "'";
     Database::query($sql);
     // Unsubscribe user from all courses
     $sql = "DELETE FROM {$table_course_user} WHERE user_id = '" . $user_id . "'";
     Database::query($sql);
     // Unsubscribe user from all courses in sessions
     $sql = "DELETE FROM {$table_session_course_user} WHERE user_id = '" . $user_id . "'";
     Database::query($sql);
     // If the user was added as a id_coach then set the current admin as coach see BT#
     $currentUserId = api_get_user_id();
     $sql = "UPDATE {$table_session} SET id_coach = {$currentUserId}  WHERE id_coach = '" . $user_id . "'";
     Database::query($sql);
     $sql = "UPDATE {$table_session} SET id_coach = {$currentUserId}  WHERE session_admin_id = '" . $user_id . "'";
     Database::query($sql);
     // Unsubscribe user from all sessions
     $sql = "DELETE FROM {$table_session_user} WHERE user_id = '" . $user_id . "'";
     Database::query($sql);
     // Delete user picture
     /* TODO: Logic about api_get_setting('split_users_upload_directory') == 'true'
        a user has 4 different sized photos to be deleted. */
     $user_info = api_get_user_info($user_id);
     if (strlen($user_info['picture_uri']) > 0) {
         $path = self::getUserPathById($user_id, 'system');
         $img_path = $path . $user_info['picture_uri'];
         if (file_exists($img_path)) {
             unlink($img_path);
         }
     }
     // Delete the personal course categories
     $course_cat_table = Database::get_main_table(TABLE_USER_COURSE_CATEGORY);
     $sql = "DELETE FROM {$course_cat_table} WHERE user_id = '" . $user_id . "'";
     Database::query($sql);
     // Delete user from database
     $sql = "DELETE FROM {$table_user} WHERE id = '" . $user_id . "'";
     Database::query($sql);
     // Delete user from the admin table
     $sql = "DELETE FROM {$table_admin} WHERE user_id = '" . $user_id . "'";
     Database::query($sql);
     // Delete the personal agenda-items from this user
     $agenda_table = Database::get_main_table(TABLE_PERSONAL_AGENDA);
     $sql = "DELETE FROM {$agenda_table} WHERE user = '******'";
     Database::query($sql);
     $gradebook_results_table = Database::get_main_table(TABLE_MAIN_GRADEBOOK_RESULT);
     $sql = 'DELETE FROM ' . $gradebook_results_table . ' WHERE user_id = ' . $user_id;
     Database::query($sql);
     $extraFieldValue = new ExtraFieldValue('user');
     $extraFieldValue->deleteValuesByItem($user_id);
     if (api_get_multiple_access_url()) {
         $url_id = api_get_current_access_url_id();
         UrlManager::delete_url_rel_user($user_id, $url_id);
     } else {
         //we delete the user from the url_id =1
         UrlManager::delete_url_rel_user($user_id, 1);
     }
     if (api_get_setting('allow_social_tool') == 'true') {
         $userGroup = new UserGroup();
         //Delete user from portal groups
         $group_list = $userGroup->get_groups_by_user($user_id);
         if (!empty($group_list)) {
             foreach ($group_list as $group_id => $data) {
                 $userGroup->delete_user_rel_group($user_id, $group_id);
             }
         }
         // Delete user from friend lists
         SocialManager::remove_user_rel_user($user_id, true);
     }
     // Removing survey invitation
     SurveyManager::delete_all_survey_invitations_by_user($user_id);
     // Delete students works
     $sql = "DELETE FROM {$table_work} WHERE user_id = {$user_id} AND c_id <> 0";
     Database::query($sql);
     // Add event to system log
     $user_id_manager = api_get_user_id();
     Event::addEvent(LOG_USER_DELETE, LOG_USER_ID, $user_id, api_get_utc_datetime(), $user_id_manager);
     Event::addEvent(LOG_USER_DELETE, LOG_USER_OBJECT, $user_info, api_get_utc_datetime(), $user_id_manager);
     return true;
 }
Beispiel #14
0
 /**
  * Delete a course
  * This function deletes a whole course-area from the platform. When the
  * given course is a virtual course, the database and directory will not be
  * deleted.
  * When the given course is a real course, also all virtual courses refering
  * to the given course will be deleted.
  * Considering the fact that we remove all traces of the course in the main
  * database, it makes sense to remove all tracking as well (if stats databases exist)
  * so that a new course created with this code would not use the remains of an older
  * course.
  *
  * @param string The code of the course to delete
  * @todo When deleting a virtual course: unsubscribe users from that virtual
  * course from the groups in the real course if they are not subscribed in
  * that real course.
  * @todo Remove globals
  */
 public static function delete_course($code)
 {
     $table_course = Database::get_main_table(TABLE_MAIN_COURSE);
     $table_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
     $table_session_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
     $table_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
     $table_course_survey = Database::get_main_table(TABLE_MAIN_SHARED_SURVEY);
     $table_course_survey_question = Database::get_main_table(TABLE_MAIN_SHARED_SURVEY_QUESTION);
     $table_course_survey_question_option = Database::get_main_table(TABLE_MAIN_SHARED_SURVEY_QUESTION_OPTION);
     $table_course_rel_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
     $table_stats_hotpots = Database::get_main_table(TABLE_STATISTIC_TRACK_E_HOTPOTATOES);
     $table_stats_attempt = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
     $table_stats_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
     $table_stats_access = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ACCESS);
     $table_stats_lastaccess = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LASTACCESS);
     $table_stats_course_access = Database::get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
     $table_stats_online = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ONLINE);
     $table_stats_default = Database::get_main_table(TABLE_STATISTIC_TRACK_E_DEFAULT);
     $table_stats_downloads = Database::get_main_table(TABLE_STATISTIC_TRACK_E_DOWNLOADS);
     $table_stats_links = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LINKS);
     $table_stats_uploads = Database::get_main_table(TABLE_STATISTIC_TRACK_E_UPLOADS);
     $codeFiltered = Database::escape_string($code);
     $sql = "SELECT * FROM {$table_course} WHERE code='" . $codeFiltered . "'";
     $res = Database::query($sql);
     if (Database::num_rows($res) == 0) {
         return;
     }
     $sql = "SELECT * FROM {$table_course}\n                WHERE code = '" . $codeFiltered . "'";
     $res = Database::query($sql);
     $course = Database::fetch_array($res);
     $courseId = $course['id'];
     $count = 0;
     if (api_is_multiple_url_enabled()) {
         $url_id = 1;
         if (api_get_current_access_url_id() != -1) {
             $url_id = api_get_current_access_url_id();
         }
         UrlManager::delete_url_rel_course($courseId, $url_id);
         $count = UrlManager::getCountUrlRelCourse($courseId);
     }
     if ($count == 0) {
         self::create_database_dump($code);
         $course_tables = AddCourse::get_course_tables();
         // Cleaning c_x tables
         if (!empty($courseId)) {
             foreach ($course_tables as $table) {
                 $table = Database::get_course_table($table);
                 $sql = "DELETE FROM {$table} WHERE c_id = {$courseId} ";
                 Database::query($sql);
             }
         }
         $course_dir = api_get_path(SYS_COURSE_PATH) . $course['directory'];
         $archive_dir = api_get_path(SYS_ARCHIVE_PATH) . $course['directory'] . '_' . time();
         if (is_dir($course_dir)) {
             rename($course_dir, $archive_dir);
         }
         // Unsubscribe all users from the course
         $sql = "DELETE FROM {$table_course_user} WHERE c_id='" . $courseId . "'";
         Database::query($sql);
         // Delete the course from the sessions tables
         $sql = "DELETE FROM {$table_session_course} WHERE c_id='" . $courseId . "'";
         Database::query($sql);
         $sql = "DELETE FROM {$table_session_course_user} WHERE c_id='" . $courseId . "'";
         Database::query($sql);
         // Delete from Course - URL
         $sql = "DELETE FROM {$table_course_rel_url} WHERE c_id = '" . $courseId . "'";
         Database::query($sql);
         $sql = 'SELECT survey_id FROM ' . $table_course_survey . ' WHERE course_code="' . $codeFiltered . '"';
         $result_surveys = Database::query($sql);
         while ($surveys = Database::fetch_array($result_surveys)) {
             $survey_id = $surveys[0];
             $sql = 'DELETE FROM ' . $table_course_survey_question . ' WHERE survey_id="' . $survey_id . '"';
             Database::query($sql);
             $sql = 'DELETE FROM ' . $table_course_survey_question_option . ' WHERE survey_id="' . $survey_id . '"';
             Database::query($sql);
             $sql = 'DELETE FROM ' . $table_course_survey . ' WHERE survey_id="' . $survey_id . '"';
             Database::query($sql);
         }
         // Cleaning group categories
         $groupCategories = GroupManager::get_categories($course['code']);
         if (!empty($groupCategories)) {
             foreach ($groupCategories as $category) {
                 GroupManager::delete_category($category['id'], $course['code']);
             }
         }
         // Cleaning groups
         $groups = GroupManager::get_groups();
         if (!empty($groups)) {
             $groupList = array_column($groups, 'id');
             GroupManager::delete_groups($groupList);
         }
         // Delete the course from the stats tables
         $sql = "DELETE FROM {$table_stats_hotpots} WHERE c_id = {$courseId}";
         Database::query($sql);
         $sql = "DELETE FROM {$table_stats_attempt} WHERE c_id = {$courseId}";
         Database::query($sql);
         $sql = "DELETE FROM {$table_stats_exercises} WHERE c_id = {$courseId}";
         Database::query($sql);
         $sql = "DELETE FROM {$table_stats_access} WHERE c_id = {$courseId}";
         Database::query($sql);
         $sql = "DELETE FROM {$table_stats_lastaccess} WHERE c_id = {$courseId}";
         Database::query($sql);
         $sql = "DELETE FROM {$table_stats_course_access} WHERE c_id = {$courseId}";
         Database::query($sql);
         $sql = "DELETE FROM {$table_stats_online} WHERE c_id = {$courseId}";
         Database::query($sql);
         // Do not delete rows from track_e_default as these include course
         // creation and other important things that do not take much space
         // but give information on the course history
         //$sql = "DELETE FROM $table_stats_default WHERE c_id = $courseId";
         //Database::query($sql);
         $sql = "DELETE FROM {$table_stats_downloads} WHERE c_id = {$courseId}";
         Database::query($sql);
         $sql = "DELETE FROM {$table_stats_links} WHERE c_id = {$courseId}";
         Database::query($sql);
         $sql = "DELETE FROM {$table_stats_uploads} WHERE c_id = {$courseId}";
         Database::query($sql);
         // Delete the course from the database
         $sql = "DELETE FROM {$table_course} WHERE code = '" . $codeFiltered . "'";
         Database::query($sql);
         // delete extra course fields
         $extraFieldValues = new ExtraFieldValue('course');
         $extraFieldValues->deleteValuesByItem($courseId);
         // Add event to system log
         $user_id = api_get_user_id();
         Event::addEvent(LOG_COURSE_DELETE, LOG_COURSE_CODE, $code, api_get_utc_datetime(), $user_id, $courseId);
     }
 }
$interbreadcrumb[] = array('url' => 'access_urls.php', 'name' => get_lang('MultipleAccessURLs'));
Display::display_header($tool_name);
echo '<div class="actions">';
echo Display::url(Display::return_icon('edit.png', get_lang('EditUserGroupToURL'), ''), api_get_path(WEB_CODE_PATH) . 'admin/access_url_edit_usergroup_to_url.php');
echo '</div>';
api_display_tool_title($tool_name);
if (isset($_POST['form_sent']) && $_POST['form_sent']) {
    $form_sent = $_POST['form_sent'];
    $userGroups = is_array($_POST['user_group_list']) ? $_POST['user_group_list'] : array();
    $urlList = is_array($_POST['url_list']) ? $_POST['url_list'] : array();
    $firstLetterUserGroup = $_POST['first_letter_user_group'];
    if ($form_sent == 1) {
        if (count($userGroups) == 0 || count($urlList) == 0) {
            Display::display_error_message(get_lang('AtLeastOneUserGroupAndOneURL'));
        } else {
            UrlManager::addUserGroupListToUrl($userGroups, $urlList);
            Display::display_confirmation_message(get_lang('UserGroupBelongURL'));
        }
    }
}
$firstLetterUser = null;
if ($userGroup->getTotalCount() > 1000) {
    //if there are too much num_courses to gracefully handle with the HTML select list,
    // assign a default filter on users names
    $firstLetterUser = '******';
}
$dbUserGroups = $userGroup->filterByFirstLetter($firstLetterUserGroup);
$sql = "SELECT id, url FROM {$tbl_access_url}  WHERE active = 1 ORDER BY url";
$result = Database::query($sql);
$db_urls = Database::store_result($result);
?>
 /**
  * Updates the access_url_rel_session table with a given user list
  * @author Julio Montoya
  * @param array user list
  * @param int access_url_id
  * */
 public static function update_urls_rel_session($session_list, $access_url_id)
 {
     $table_url_rel_session = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
     $sql = "SELECT session_id FROM {$table_url_rel_session} WHERE access_url_id=" . intval($access_url_id);
     $result = Database::query($sql);
     $existing_sessions = array();
     while ($row = Database::fetch_array($result)) {
         $existing_sessions[] = $row['session_id'];
     }
     // Adding users
     foreach ($session_list as $session) {
         if (!in_array($session, $existing_sessions)) {
             if (!empty($session) && !empty($access_url_id)) {
                 UrlManager::add_session_to_url($session, $access_url_id);
             }
         }
     }
     // Deleting old users
     foreach ($existing_sessions as $existing_session) {
         if (!in_array($existing_session, $session_list)) {
             if (!empty($existing_session) && !empty($access_url_id)) {
                 UrlManager::delete_url_rel_session($existing_session, $access_url_id);
             }
         }
     }
 }
Beispiel #17
0
function externalCourselist()
{
    require_once $GLOBALS['where_lms'] . '/modules/coursecatalogue/lib.coursecatalogue.php';
    require_once _base_ . '/lib/lib.form.php';
    require_once _base_ . '/lib/lib.user_profile.php';
    require_once _base_ . '/lib/lib.navbar.php';
    require_once $GLOBALS['where_lms'] . '/lib/lib.preassessment.php';
    require_once $GLOBALS['where_lms'] . '/lib/lib.catalogue.php';
    require_once $GLOBALS['where_lms'] . '/lib/lib.coursepath.php';
    require_once $GLOBALS['where_lms'] . '/lib/lib.course.php';
    require_once _base_ . '/lib/lib.urlmanager.php';
    $url =& UrlManager::getInstance('login');
    $url->setStdQuery('modname=login&op=courselist');
    addCss('style_tab', 'lms');
    login_coursecatalogueJsSetup();
    $GLOBALS['page']->add('<!--[if lt IE 7.]>
		<script type="text/javascript" src="' . $GLOBALS['where_framework_relative'] . '/lib/lib.pngfix.js"></script>
	<![endif]-->', 'page_head');
    $lang =& DoceboLanguage::createInstance('catalogue');
    $lang_c =& DoceboLanguage::createInstance('course');
    // list of tab ---------------------------------------------------------------------------
    $tab_list = array('time' => $lang->def('_TAB_VIEW_TIME'), 'category' => $lang->def('_TAB_VIEW_CATEGORY'), 'all' => $lang->def('_ALL'));
    if (Get::sett('use_coursepath') == '1') {
        $tab_list['pathcourse'] = $lang->def('_COURSEPATH');
    }
    if (Get::sett('use_social_courselist') == 'on') {
        $tab_list['mostscore'] = $lang->def('_TAB_VIEW_MOSTSCORE');
        $tab_list['popular'] = $lang->def('_TAB_VIEW_MOSTPOPULAR');
        $tab_list['recent'] = $lang->def('_TAB_VIEW_RECENT');
    }
    $tab_selected = unserialize(urldecode(Get::sett('tablist_coursecatalogue')));
    foreach ($tab_list as $tab_code => $v) {
        if (!isset($tab_selected[$tab_code])) {
            unset($tab_list[$tab_code]);
        }
    }
    reset($tab_list);
    // tab selected for courses -------------------------------------------------------------
    $first_coursecatalogue_tab = Get::sett('first_coursecatalogue_tab', key($tab_list));
    if (!isset($tab_list[$first_coursecatalogue_tab])) {
        $first_coursecatalogue_tab = key($tab_list);
    }
    if (isset($_GET['tab']) || isset($_POST['tab'])) {
        $selected_tab = $_SESSION['cc_tab'] = Get::req('tab', DOTY_MIXED, $first_coursecatalogue_tab);
    } elseif (isset($_SESSION['cc_tab'])) {
        $selected_tab = $_SESSION['cc_tab'];
    } else {
        $selected_tab = $first_coursecatalogue_tab;
    }
    $GLOBALS['page']->add('<div id="coursecatalogue_tab_container">' . '<ul class="flat_tab">', 'content');
    foreach ($tab_list as $key => $tab_name) {
        $GLOBALS['page']->add('<li' . ($selected_tab == $key ? ' class="now_selected"' : '') . '>' . '<a href="' . $url->getUrl('tab=' . $key) . '"><span>' . $tab_name . '</span></a></li>', 'content');
    }
    $GLOBALS['page']->add('</ul>' . '</div>' . '<div class="std_block" id="coursecatalogue">', 'content');
    switch ($selected_tab) {
        case "pathcourse":
            displayCoursePathList($url, $selected_tab);
            break;
            /*
            		case "time" : {
            			displayTimeCourseList($url, $selected_tab);
            		};break;*/
        /*
        		case "time" : {
        			displayTimeCourseList($url, $selected_tab);
        		};break;*/
        default:
            displayCourseList($url, $selected_tab);
    }
    $GLOBALS['page']->add('</div>', 'content');
    // end of function ----------------------------------------------------------------
}
 /**
  * initialize the internal url manager instance
  * @param string $std_query the std_query for the address
  */
 function initUrlManager($std_query)
 {
     require_once _base_ . '/lib/lib.urlmanager.php';
     $this->_url_man =& UrlManager::getInstance();
     $this->_url_man->setStdQuery($std_query);
 }
Beispiel #19
0
function myfriendsDispatch($op)
{
    require_once _base_ . '/lib/lib.urlmanager.php';
    $url =& UrlManager::getInstance('myfriends');
    $url->setStdQuery('modname=myfriends&op=myfriends');
    if (isset($_POST['undo']) || isset($_GET['undo'])) {
        $op = 'myfriends';
    }
    switch ($op) {
        case "myfriends":
            myfriends($url);
            break;
        case "searchuser":
            searchUser($url);
            break;
        case "approveuser":
            approveuser($url);
            break;
        case "delfriend":
            delfriend($url);
            break;
    }
}
Beispiel #20
0
function WSRemoveCourseFromPortal($params)
{
    if (!WSHelperVerifyKey($params['secret_key'])) {
        return return_error(WS_ERROR_SECRET_KEY);
    }
    $courseInfo = CourseManager::getCourseInfoFromOriginalId($params['original_course_id_value'], $params['original_course_id_name']);
    $courseId = $courseInfo['real_id'];
    $portalId = $params['portal_id'];
    UrlManager::delete_url_rel_course($courseId, $portalId);
    $result = UrlManager::relation_url_course_exist($courseId, $portalId);
    if (empty($result)) {
        return true;
    }
    return false;
}
         $rs_session = Database::query($sql_session);
         $session_id = Database::query("SELECT id FROM {$tbl_session} WHERE name='{$session_name}'");
         list($session_id) = Database::fetch_array($session_id);
         Database::query("DELETE FROM {$tbl_session_user} WHERE id_session='{$session_id}'");
         Database::query("DELETE FROM {$tbl_session_course} WHERE id_session='{$session_id}'");
         Database::query("DELETE FROM {$tbl_session_course_user} WHERE id_session='{$session_id}'");
     }
 }
 // Associate the session with access_url.
 global $_configuration;
 if ($_configuration['multiple_access_urls']) {
     $access_url_id = api_get_current_access_url_id();
     UrlManager::add_session_to_url($session_id, $access_url_id);
 } else {
     // We fill by default the access_url_rel_session table.
     UrlManager::add_session_to_url($session_id, 1);
 }
 // Adding users to the new session.
 foreach ($node_session->User as $node_user) {
     $username = UserManager::purify_username(api_utf8_decode($node_user), $purification_option_for_usernames);
     $user_id = UserManager::get_user_id_from_username($username);
     if ($user_id !== false) {
         $sql = "INSERT IGNORE INTO {$tbl_session_user} SET\n                                        id_user='******',\n                                        id_session = '{$session_id}'";
         $rs_user = Database::query($sql);
         $user_counter++;
     }
 }
 // Adding courses to a session.
 foreach ($node_session->Course as $node_course) {
     $course_code = Database::escape_string(trim(api_utf8_decode($node_course->CourseCode)));
     // Verify that the course pointed by the course code node exists.
 /**
  * @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);
 }
 /**
  * @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 $user_id
  * @param $logger
  * @param array 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 array extra fields
  * @param string extra field id
  * @param int $daysCoachAccessBeforeBeginning
  * @param int $daysCoachAccessAfterBeginning
  * @param int $sessionVisibility
  * @return array
  */
 static function importCSV($file, $updatesession, $defaultUserId = null, $logger = null, $extraFields = array(), $extraFieldId = null, $daysCoachAccessBeforeBeginning = null, $daysCoachAccessAfterBeginning = null, $sessionVisibility = 1, $fieldsToAvoidUpdate = array())
 {
     $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);
     }
     $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;
                 }
             }
         }
         // 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] = $enreg[$original];
                 }
             }
             $session_name = Database::escape_string($enreg['SessionName']);
             $date_start = $enreg['DateStart'];
             $date_end = $enreg['DateEnd'];
             $visibility = isset($enreg['Visibility']) ? $enreg['Visibility'] : $sessionVisibility;
             $session_category_id = isset($enreg['SessionCategory']) ? $enreg['SessionCategory'] : null;
             // 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;
                 // This MUST be initializead.
                 $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;
                     }
                 }
                 // Creating the session.
                 /*$sql_session = "INSERT IGNORE INTO $tbl_session SET
                           name = '".$session_name."',
                           id_coach = '$coach_id',
                           date_start = '$date_start',
                           date_end = '$date_end',
                           visibility = '$visibility',
                           session_category_id = '$session_category_id',
                           session_admin_id=".intval($defaultUserId).$extraParameters;
                   Database::query($sql_session);*/
                 $params = array('id_coach' => $coach_id, 'visibility' => $visibility, 'name' => $session_name, 'access_start_date' => $date_start, 'access_end_date' => $date_end, 'session_category_id' => $session_category_id, 'session_admin_id' => $defaultUserId);
                 $session_id = SessionManager::add($params);
                 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)) {
                     $sessionId = self::get_session_id_from_original_id($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_session = "INSERT IGNORE INTO $tbl_session SET
                       name = '$session_name',
                       id_coach = '$coach_id',
                       date_start = '$date_start',
                       date_end = '$date_end',
                       visibility = '$visibility',
                       session_category_id = '$session_category_id' ".$extraParameters;*/
                     $params = array('id_coach' => $coach_id, 'visibility' => $visibility, 'name' => $session_name, 'access_start_date' => $date_start, 'access_end_date' => $date_end, 'session_category_id' => $session_category_id, 'session_admin_id' => $defaultUserId);
                     $session_id = SessionManager::add($params);
                     // We get the last insert id.
                     /*$my_session_result = SessionManager::get_session_by_name($enreg['SessionName']);
                       $session_id = $my_session_result['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_id} created: {$session_name}");
                         } else {
                             $logger->addError("Sessions - Session NOT created: {$session_name}");
                         }
                     }
                 } else {
                     $params = array('id_coach' => $coach_id, 'date_start' => $date_start, 'date_end' => $date_end, 'visibility' => $visibility, 'session_category_id' => $session_category_id);
                     if (!empty($fieldsToAvoidUpdate)) {
                         foreach ($fieldsToAvoidUpdate as $field) {
                             unset($params[$field]);
                         }
                     }
                     if (isset($sessionId) && !empty($sessionId)) {
                         // The session already exists, update it then.
                         Database::update($tbl_session, $params, array('id = ?' => $sessionId));
                         $session_id = $sessionId;
                     } else {
                         Database::update($tbl_session, $params, array("name = '?' " => $enreg['SessionName']));
                         $row = Database::query("SELECT id FROM {$tbl_session} WHERE name = '{$session_name}'");
                         list($session_id) = Database::fetch_array($row);
                     }
                     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);
                         }
                     }
                     Database::query("DELETE FROM {$tbl_session_user} WHERE id_session='{$session_id}'");
                     Database::query("DELETE FROM {$tbl_session_course} WHERE id_session='{$session_id}'");
                     Database::query("DELETE FROM {$tbl_session_course_user} WHERE id_session='{$session_id}'");
                 }
                 $session_counter++;
             }
             $users = explode('|', $enreg['Users']);
             // Adding the relationship "Session - User".
             if (is_array($users)) {
                 foreach ($users as $user) {
                     $user_id = UserManager::get_user_id_from_username($user);
                     if ($user_id !== false) {
                         // Insert new users.
                         $sql = "INSERT IGNORE INTO {$tbl_session_user} SET\n                                    id_user = '******',\n                                    id_session = '{$session_id}'";
                         Database::query($sql);
                         if ($debug) {
                             $logger->addInfo("Sessions - Adding User #{$user_id} ({$user}) to session #{$session_id}");
                         }
                         $user_counter++;
                     }
                 }
             }
             $courses = explode('|', $enreg['Courses']);
             foreach ($courses as $course) {
                 $course_code = api_strtoupper(api_substr($course, 0, api_strpos($course, '[')));
                 if (CourseManager::course_exists($course_code)) {
                     $courseInfo = api_get_course_info($course_code);
                     $courseId = $courseInfo['real_id'];
                     // Adding the course to a session.
                     $sql_course = "INSERT IGNORE INTO {$tbl_session_course}\n                                       SET c_id = '" . $courseId . "', id_session = '{$session_id}'";
                     Database::query($sql_course);
                     if ($debug) {
                         $logger->addInfo("Sessions - Adding course '{$course_code}' to session #{$session_id}");
                     }
                     $course_counter++;
                     $pattern = "/\\[(.*?)\\]/";
                     preg_match_all($pattern, $course, $matches);
                     if (isset($matches[1])) {
                         $course_coaches = $matches[1][0];
                         $course_users = $matches[1][1];
                     }
                     $course_users = explode(',', $course_users);
                     $course_coaches = explode(',', $course_coaches);
                     // Adding coaches to session course user
                     if (!empty($course_coaches)) {
                         foreach ($course_coaches as $course_coach) {
                             $coach_id = UserManager::get_user_id_from_username($course_coach);
                             if ($coach_id !== false) {
                                 $sql = "INSERT IGNORE INTO {$tbl_session_course_user} SET\n                                            id_user='******',\n                                            c_id ='{$courseId}',\n                                            id_session = '{$session_id}',\n                                            status = 2 ";
                                 Database::query($sql);
                                 if ($debug) {
                                     $logger->addInfo("Sessions - Adding course coach: user #{$coach_id} ({$course_coach}) to course: '{$course_code}' and session #{$session_id}");
                                 }
                             } else {
                                 $error_message .= get_lang('UserDoesNotExist') . ' : ' . $course_coach . $eol;
                             }
                         }
                     }
                     $users_in_course_counter = 0;
                     // Adding the relationship "Session - Course - User".
                     foreach ($course_users as $user) {
                         $user_id = UserManager::get_user_id_from_username($user);
                         if ($user_id !== false) {
                             $sql = "INSERT IGNORE INTO {$tbl_session_course_user} SET\n                                        id_user='******',\n                                        c_id = '{$courseId}',\n                                        id_session = '{$session_id}'";
                             Database::query($sql);
                             if ($debug) {
                                 $logger->addInfo("Sessions - Adding student: user #{$user_id} ({$user}) to course: '{$course_code}' and session #{$session_id}");
                             }
                             $users_in_course_counter++;
                         } else {
                             $error_message .= get_lang('UserDoesNotExist') . ': ' . $user . $eol;
                         }
                     }
                     $sql = "UPDATE {$tbl_session_course} SET nbr_users='{$users_in_course_counter}' WHERE c_id ='{$courseId}'";
                     Database::query($sql);
                     $course_info = CourseManager::get_course_information($course_code);
                     $inserted_in_course[$course_code] = $course_info['title'];
                 }
             }
             $access_url_id = api_get_current_access_url_id();
             UrlManager::add_session_to_url($session_id, $access_url_id);
             $sql_update_users = "UPDATE {$tbl_session} SET nbr_users ='{$user_counter}', nbr_courses='{$course_counter}' WHERE id='{$session_id}'";
             Database::query($sql_update_users);
         }
     }
     return array('error_message' => $error_message, 'session_counter' => $session_counter);
 }
        }
        if (!empty($_GET['user'])) {
            SessionManager::unsubscribe_user_from_session($sessionId, $_GET['user']);
        }
        break;
}
$sessionHeader = Display::page_header(Display::return_icon('session.png', get_lang('Session')) . ' ' . $sessionInfo['name'], null, 'h3');
$url = Display::url(Display::return_icon('edit.png', get_lang('Edit'), array(), ICON_SIZE_SMALL), "session_edit.php?page=resume_session.php&id={$sessionId}");
$sessionTitle = Display::page_subheader(get_lang('GeneralProperties') . $url);
$generalCoach = api_get_user_info($sessionInfo['id_coach']);
$sessionField = new ExtraField('session');
$extraFieldData = $sessionField->getDataAndFormattedValues($sessionId);
$multiple_url_is_on = api_get_multiple_access_url();
$urlList = [];
if ($multiple_url_is_on) {
    $urlList = UrlManager::get_access_url_from_session($sessionId);
}
$url = Display::url(Display::return_icon('edit.png', get_lang('Edit'), array(), ICON_SIZE_SMALL), "add_courses_to_session.php?page=resume_session.php&id_session={$sessionId}");
$courseListToShow = Display::page_subheader(get_lang('CourseList') . $url);
$courseListToShow .= '<table id="session-list-course" class="data_table">
<tr>
  <th width="35%">' . get_lang('CourseTitle') . '</th>
  <th width="30%">' . get_lang('CourseCoach') . '</th>
  <th width="10%">' . get_lang('UsersNumber') . '</th>
  <th width="25%">' . get_lang('Actions') . '</th>
</tr>';
if ($sessionInfo['nbr_courses'] == 0) {
    $courseListToShow .= '<tr>
			<td colspan="4">' . get_lang('NoCoursesForThisSession') . '</td>
		</tr>';
} else {
Beispiel #25
0
        $result = TrackingUserLogCSV::getToolInformation($user['user_id'], $courseInfo, 0);
        $courseToolInformationTotal .= $result['html'];
        $csvContent = array_merge($csvContent, $result['array']);
    }
    $courseInformation = Display::page_subheader(get_lang('Courses'));
    $courseInformation .= Display::return_sortable_table($header, $data, array(), array(), array('user_id' => intval($_GET['user_id'])));
    $courseInformation .= $courseToolInformationTotal;
} else {
    $courseInformation = '<p>' . get_lang('NoCoursesForThisUser') . '</p>';
}
/**
 * Show the URL in which this user is subscribed
 */
$urlInformation = null;
if (api_is_multiple_url_enabled()) {
    $urlList = UrlManager::get_access_url_from_user($user['user_id']);
    if (count($urlList) > 0) {
        $header = array();
        $header[] = array('URL', true);
        $data = array();
        $csvContent[] = array();
        $csvContent[] = array('Url');
        foreach ($urlList as $url) {
            $row = array();
            $row[] = Display::url($url['url'], $url['url']);
            $csvContent[] = array_map('strip_tags', $row);
            $data[] = $row;
        }
        $urlInformation = Display::page_subheader(get_lang('URLList'));
        $urlInformation .= Display::return_sortable_table($header, $data, array(), array(), array('user_id' => intval($_GET['user_id'])));
    } else {
    $courses = Database::store_result($result);
    $course_list_leys = array_keys($course_list);
    foreach ($courses as $course) {
        if (!in_array($course['id'], $course_list_leys)) {
            $no_course_list[$course['id']] = $course;
        }
    }
}
if ($add_type == 'multiple') {
    $link_add_type_unique = '<a href="' . api_get_self() . '?add_type=unique&access_url_id=' . $access_url_id . '">' . get_lang('SessionAddTypeUnique') . '</a>';
    $link_add_type_multiple = get_lang('SessionAddTypeMultiple');
} else {
    $link_add_type_unique = get_lang('SessionAddTypeUnique');
    $link_add_type_multiple = '<a href="' . api_get_self() . '?add_type=multiple&access_url_id=' . $access_url_id . '">' . get_lang('SessionAddTypeMultiple') . '</a>';
}
$url_list = UrlManager::get_url_data();
?>

<div style="text-align: left;">
	<?php 
echo $link_add_type_unique;
?>
&nbsp;|&nbsp;<?php 
echo $link_add_type_multiple;
?>
</div>
<br /><br />
<form name="formulaire" method="post" action="<?php 
echo api_get_self();
?>
" style="margin:0px;" <?php 
Beispiel #27
0
<?php

defined("IN_FORMA") or die('Direct access is forbidden.');
/* ======================================================================== \
|   FORMA - The E-Learning Suite                                            |
|                                                                           |
|   Copyright (c) 2013 (Forma)                                              |
|   http://www.formalms.org                                                 |
|   License  http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt           |
|                                                                           |
|   from docebo 4.0.5 CE 2008-2012 (c) docebo                               |
|   License http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt            |
\ ======================================================================== */
if (Docebo::user()->isAnonymous()) {
    die("You can't access");
}
require_once _base_ . '/lib/lib.urlmanager.php';
$um =& UrlManager::getInstance("message");
$um->setStdQuery("modname=message&op=message");
if (!defined('IN_LMS')) {
    define("IN_LMS", TRUE);
}
define("_PATH_MESSAGE", '/appLms/' . Get::sett('pathmessage'));
define("_MESSAGE_VISU_ITEM", Get::sett('visuItem'));
define("_MESSAGE_PL_URL", Get::sett('url'));
require_once _adm_ . '/lib/lib.message.php';
Beispiel #28
0
}
// action menu
echo '<div class="actions">';
echo Display::url(Display::return_icon('new_link.png', get_lang('AddUrl'), array(), ICON_SIZE_MEDIUM), api_get_path(WEB_CODE_PATH) . 'admin/access_url_edit.php');
echo Display::url(Display::return_icon('user.png', get_lang('ManageUsers'), array(), ICON_SIZE_MEDIUM), api_get_path(WEB_CODE_PATH) . 'admin/access_url_edit_users_to_url.php');
echo Display::url(Display::return_icon('course.png', get_lang('ManageCourses'), array(), ICON_SIZE_MEDIUM), api_get_path(WEB_CODE_PATH) . 'admin/access_url_edit_courses_to_url.php');
//echo Display::url(Display::return_icon('session.png',   get_lang('ManageSessions'), array(), ICON_SIZE_MEDIUM), api_get_path(WEB_CODE_PATH).'admin/access_url_edit_sessions_to_url.php');
$userGroup = new UserGroup();
if ($userGroup->getUseMultipleUrl()) {
    echo Display::url(Display::return_icon('class.png', get_lang('ManageUserGroup'), array(), ICON_SIZE_MEDIUM), api_get_path(WEB_CODE_PATH) . 'admin/access_url_edit_usergroup_to_url.php');
}
if (CourseCategoryManager::isMultipleUrlSupport()) {
    echo Display::url(Display::return_icon('folder.png', get_lang('ManageCourseCategories'), array(), ICON_SIZE_MEDIUM), api_get_path(WEB_CODE_PATH) . 'admin/access_url_edit_course_category_to_url.php');
}
echo '</div>';
$sortable_data = UrlManager::get_url_data();
$urls = array();
foreach ($sortable_data as $row) {
    //title
    $url = Display::url($row['url'], $row['url'], array('target' => '_blank'));
    $description = $row['description'];
    //Status
    $active = $row['active'];
    if ($active == '1') {
        $action = 'lock';
        $image = 'right';
    }
    if ($active == '0') {
        $action = 'unlock';
        $image = 'wrong';
    }
function WSCreateUserPasswordCrypted($params)
{
    global $_user, $_configuration, $debug;
    $debug = 1;
    if ($debug) {
        error_log('WSCreateUserPasswordCrypted');
    }
    if ($debug) {
        error_log(print_r($params, 1));
    }
    if (!WSHelperVerifyKey($params)) {
        return return_error(WS_ERROR_SECRET_KEY);
    }
    // Database table definition.
    $table_user = Database::get_main_table(TABLE_MAIN_USER);
    $orig_user_id_value = array();
    $password = $params['password'];
    $encrypt_method = $params['encrypt_method'];
    $firstName = $params['firstname'];
    $lastName = $params['lastname'];
    $status = $params['status'];
    $email = $params['email'];
    $loginName = $params['loginname'];
    $official_code = isset($params['official_code']) ? $params['official_code'] : '';
    $language = '';
    $phone = $params['phone'];
    $picture_uri = '';
    $auth_source = PLATFORM_AUTH_SOURCE;
    $expiration_date = '';
    $active = 1;
    $hr_dept_id = 0;
    $extra = null;
    $original_user_id_name = $params['original_user_id_name'];
    $original_user_id_value = $params['original_user_id_value'];
    $orig_user_id_value[] = $params['original_user_id_value'];
    $extra_list = isset($params['extra']) ? $params['extra'] : '';
    if (!empty($_configuration['password_encryption'])) {
        if ($_configuration['password_encryption'] === $encrypt_method) {
            if ($encrypt_method == 'md5' && !preg_match('/^[A-Fa-f0-9]{32}$/', $password)) {
                $msg = "Encryption {$encrypt_method} is invalid";
                if ($debug) {
                    error_log($msg);
                }
                return $msg;
            } else {
                if ($encrypt_method == 'sha1' && !preg_match('/^[A-Fa-f0-9]{40}$/', $password)) {
                    $msg = "Encryption {$encrypt_method} is invalid";
                    if ($debug) {
                        error_log($msg);
                    }
                    return $msg;
                }
            }
        } else {
            $msg = "This encryption {$encrypt_method} is not configured";
            if ($debug) {
                error_log($msg);
            }
            return $msg;
        }
    } else {
        $msg = 'The chamilo setting $_configuration["password_encryption"] is not configured';
        if ($debug) {
            error_log($msg);
        }
        return $msg;
    }
    if (!empty($params['language'])) {
        $language = $params['language'];
    }
    if (!empty($params['phone'])) {
        $phone = $params['phone'];
    }
    if (!empty($params['expiration_date'])) {
        $expiration_date = $params['expiration_date'];
    }
    // Check whether x_user_id exists into user_field_values table.
    $user_id = UserManager::get_user_id_from_original_id($original_user_id_value, $original_user_id_name);
    if ($debug) {
        error_log('Ready to create user');
    }
    if ($user_id > 0) {
        if ($debug) {
            error_log('User found with id: ' . $user_id);
        }
        // Check whether user is not active
        //@todo why this condition exists??
        $sql = "SELECT user_id FROM {$table_user}\n                WHERE user_id ='" . $user_id . "' AND active= '0' ";
        $resu = Database::query($sql);
        $r_check_user = Database::fetch_row($resu);
        $count_check_user = Database::num_rows($resu);
        if ($count_check_user > 0) {
            if ($debug) {
                error_log('User id: ' . $user_id . ' exists and is NOT active. Updating user and setting setting active = 1');
            }
            $sql = "UPDATE {$table_user} SET\n                    lastname='" . Database::escape_string($lastName) . "',\n                    firstname='" . Database::escape_string($firstName) . "',\n                    username='******',";
            if (!is_null($auth_source)) {
                $sql .= " auth_source='" . Database::escape_string($auth_source) . "',";
            }
            $sql .= "\n                    password='******',\n                    email='" . Database::escape_string($email) . "',\n                    status='" . Database::escape_string($status) . "',\n                    official_code='" . Database::escape_string($official_code) . "',\n                    phone='" . Database::escape_string($phone) . "',\n                    expiration_date='" . Database::escape_string($expiration_date) . "',\n                    active='1',\n                    hr_dept_id=" . intval($hr_dept_id);
            $sql .= " WHERE user_id='" . $r_check_user[0] . "'";
            if ($debug) {
                error_log($sql);
            }
            Database::query($sql);
            if (is_array($extra_list) && count($extra_list) > 0) {
                foreach ($extra_list as $extra) {
                    $extra_field_name = $extra['field_name'];
                    $extra_field_value = $extra['field_value'];
                    // Save the external system's id into user_field_value table.
                    UserManager::update_extra_field_value($r_check_user[0], $extra_field_name, $extra_field_value);
                }
            }
            return $r_check_user[0];
        } else {
            if ($debug) {
                error_log('User exists but is active. Cant be updated');
            }
            return 0;
        }
    } else {
        if ($debug) {
            error_log("User not found with original_id = {$original_user_id_value} and original_name = {$original_user_id_name}");
        }
    }
    // Default language.
    if (empty($language)) {
        $language = api_get_setting('platformLanguage');
    }
    if (!empty($_user['user_id'])) {
        $creator_id = $_user['user_id'];
    } else {
        $creator_id = '';
    }
    // First check wether the login already exists
    if (!UserManager::is_username_available($loginName)) {
        if ($debug) {
            error_log("Username {$loginName} is not available");
        }
        return 0;
    }
    $sql = "INSERT INTO {$table_user} SET\n            lastname            = '" . Database::escape_string(trim($lastName)) . "',\n            firstname           = '" . Database::escape_string(trim($firstName)) . "',\n            username            = '******',\n            status              = '" . Database::escape_string($status) . "',\n            password            = '******',\n            email               = '" . Database::escape_string($email) . "',\n            official_code       = '" . Database::escape_string($official_code) . "',\n            picture_uri         = '" . Database::escape_string($picture_uri) . "',\n            creator_id          = '" . Database::escape_string($creator_id) . "',\n            auth_source         = '" . Database::escape_string($auth_source) . "',\n            phone               = '" . Database::escape_string($phone) . "',\n            language            = '" . Database::escape_string($language) . "',\n            registration_date   = '" . api_get_utc_datetime() . "',\n            expiration_date     = '" . Database::escape_string($expiration_date) . "',\n            hr_dept_id          = '" . Database::escape_string($hr_dept_id) . "',\n            active              = '" . Database::escape_string($active) . "'";
    if ($debug) {
        error_log($sql);
    }
    $result = Database::query($sql);
    if ($result) {
        $return = Database::insert_id();
        $sql = "UPDATE {$table_user} SET user_id = id WHERE id = {$return}";
        Database::query($sql);
        $url_id = api_get_current_access_url_id();
        UrlManager::add_user_to_url($return, $url_id);
        if ($debug) {
            error_log("Adding user_id = {$return} to URL id {$url_id} ");
        }
        // Save new fieldlabel into user_field table.
        $field_id = UserManager::create_extra_field($original_user_id_name, 1, $original_user_id_name, '');
        // Save the remote system's id into user_field_value table.
        UserManager::update_extra_field_value($return, $original_user_id_name, $original_user_id_value);
        if (is_array($extra_list) && count($extra_list) > 0) {
            foreach ($extra_list as $extra) {
                $extra_field_name = $extra['field_name'];
                $extra_field_value = $extra['field_value'];
                // save new fieldlabel into user_field table
                $field_id = UserManager::create_extra_field($extra_field_name, 1, $extra_field_name, '');
                // save the external system's id into user_field_value table'
                UserManager::update_extra_field_value($return, $extra_field_name, $extra_field_value);
            }
        }
    } else {
        return 0;
    }
    return $return;
}
// setting the section (for the tabs)
$this_section = SECTION_PLATFORM_ADMIN;
api_protect_admin_script(true);
$tool_name = get_lang('SessionOverview');
$interbreadcrumb[] = array('url' => Container::getRouter()->generate('administration'), 'name' => get_lang('PlatformAdmin'));
$interbreadcrumb[] = array('url' => 'session_list.php', 'name' => get_lang('SessionList'));
// Database Table Definitions
$tbl_user = Database::get_main_table(TABLE_MAIN_USER);
$tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
$table_access_url_user = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
$url_id = api_get_current_access_url_id();
$action = $_GET['action'];
switch ($action) {
    case 'add_user_to_url':
        $user_id = $_REQUEST['user_id'];
        $result = UrlManager::add_user_to_url($user_id, $url_id);
        $user_info = api_get_user_info($user_id);
        if ($result) {
            $message = Display::return_message(get_lang('UserAdded') . ' ' . api_get_person_name($user_info['firstname'], $user_info['lastname']), 'confirm');
        }
        break;
}
Display::display_header($tool_name);
if (!empty($message)) {
    echo $message;
}
$multiple_url_is_on = api_get_multiple_access_url();
$order_clause = api_sort_by_first_name() ? ' ORDER BY firstname, lastname' : ' ORDER BY lastname, firstname';
$session_list = SessionManager::get_sessions_list();
$html = '';
$show_users_with_problems = isset($_REQUEST['show_users_with_problems']) && $_REQUEST['show_users_with_problems'] == 1 ? true : false;