function WSCreateUsersPasswordCrypted($params)
{
    global $_user, $_configuration;
    if (!WSHelperVerifyKey($params)) {
        return return_error(WS_ERROR_SECRET_KEY);
    }
    // database table definition
    $table_user = Database::get_main_table(TABLE_MAIN_USER);
    $t_uf = Database::get_main_table(TABLE_EXTRA_FIELD);
    $t_ufv = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
    $users_params = $params['users'];
    $results = array();
    $orig_user_id_value = array();
    foreach ($users_params as $user_param) {
        $password = $user_param['password'];
        $encrypt_method = $user_param['encrypt_method'];
        $firstName = $user_param['firstname'];
        $lastName = $user_param['lastname'];
        $status = $user_param['status'];
        $email = $user_param['email'];
        $loginName = $user_param['loginname'];
        $official_code = $user_param['official_code'];
        $language = '';
        $phone = '';
        $picture_uri = '';
        $auth_source = PLATFORM_AUTH_SOURCE;
        $expiration_date = '';
        $active = 1;
        $hr_dept_id = 0;
        $extra = null;
        $original_user_id_name = $user_param['original_user_id_name'];
        $original_user_id_value = $user_param['original_user_id_value'];
        $orig_user_id_value[] = $user_param['original_user_id_value'];
        $extra_list = $user_param['extra'];
        $salt = '';
        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";
                    $results[] = $msg;
                    continue;
                } else {
                    if ($encrypt_method == 'sha1' && !preg_match('/^[A-Fa-f0-9]{40}$/', $password)) {
                        $msg = "Encryption {$encrypt_method} is invalid";
                        $results[] = $msg;
                        continue;
                    }
                }
            } else {
                $msg = "This encryption {$encrypt_method} is not configured";
                $results[] = $msg;
                continue;
            }
        } else {
            $msg = 'The chamilo setting $_configuration["password_encryption"] is not configured';
            $results[] = $msg;
            continue;
        }
        if (is_array($extra_list) && count($extra_list) > 0) {
            foreach ($extra_list as $extra) {
                if ($extra['field_name'] == 'salt') {
                    $salt = $extra['field_value'];
                    break;
                }
            }
        }
        if (!empty($user_param['language'])) {
            $language = $user_param['language'];
        }
        if (!empty($user_param['phone'])) {
            $phone = $user_param['phone'];
        }
        if (!empty($user_param['expiration_date'])) {
            $expiration_date = $user_param['expiration_date'];
        }
        $extraFieldType = EntityExtraField::USER_FIELD_TYPE;
        // Check whether x_user_id exists into user_field_values table.
        $sql = "SELECT value as field_value,item_id as user_id\n                FROM {$t_uf} uf, {$t_ufv} ufv\n                WHERE\n                    uf.extra_field_type = {$extraFieldType}\n                    ufv.field_id=uf.id AND\n                    variable='{$original_user_id_name}' AND\n                    value ='{$original_user_id_value}'";
        $res = Database::query($sql);
        $row = Database::fetch_row($res);
        $count_row = Database::num_rows($res);
        if ($count_row > 0) {
            // Check if user is not active.
            $sql = "SELECT user_id FROM {$table_user} WHERE user_id ='" . $row[1] . "' 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) {
                $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] . "'";
                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.
                        $res = UserManager::update_extra_field_value($r_check_user[0], $extra_field_name, $extra_field_value);
                    }
                }
                $results[] = $r_check_user[0];
                continue;
            } else {
                $results[] = 0;
                continue;
                // User id already exits.
            }
        }
        // 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 (api_set_failure('login-pass already taken')) {
                $results[] = 0;
                continue;
            }
        }
        $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 = now(),\n                    expiration_date = '" . Database::escape_string($expiration_date) . "',\n                    hr_dept_id = '" . Database::escape_string($hr_dept_id) . "',\n                    active = '" . Database::escape_string($active) . "'";
        $result = Database::query($sql);
        if ($result) {
            //echo "id returned";
            $return = Database::insert_id();
            $sql = "UPDATE {$table_user} SET user_id = id WHERE id = {$return}";
            Database::query($sql);
            if (api_is_multiple_url_enabled()) {
                if (api_get_current_access_url_id() != -1) {
                    UrlManager::add_user_to_url($return, api_get_current_access_url_id());
                } else {
                    UrlManager::add_user_to_url($return, 1);
                }
            } else {
                // We add by default the access_url_user table with access_url_id = 1
                UrlManager::add_user_to_url($return, 1);
            }
            // 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 {
            $results[] = 0;
            continue;
        }
        $results[] = $return;
    }
    // end principal foreach
    $count_results = count($results);
    $output = array();
    for ($i = 0; $i < $count_results; $i++) {
        $output[] = array('original_user_id_value' => $orig_user_id_value[$i], 'result' => $results[$i]);
    }
    return $output;
}
 /**
  * Creates a new user for the platform
  * @author Hugues Peeters <*****@*****.**>,
  * @author Roan Embrechts <*****@*****.**>
  * @param  string Firstname
  * @param  string Lastname
  * @param  int    Status (1 for course tutor, 5 for student, 6 for anonymous)
  * @param  string e-mail address
  * @param  string Login
  * @param  string Password
  * @param  string Any official code (optional)
  * @param  string User language    (optional)
  * @param  string Phone number    (optional)
  * @param  string Picture URI        (optional)
  * @param  string Authentication source    (optional, defaults to 'platform', dependind on constant)
  * @param  string Account expiration date (optional, defaults to null)
  * @param  int     Whether the account is enabled or disabled by default
  * @param  int     The department of HR in which the user is registered (optional, defaults to 0)
  * @param  array Extra fields
  * @param  string Encrypt method used if password is given encrypted. Set to an empty string by default
  * @param  bool $send_mail
  * @param  bool $isAdmin
  *
  * @return mixed   new user id - if the new user creation succeeds, false otherwise
  * @desc The function tries to retrieve user id from the session.
  * If it exists, the current user id is the creator id. If a problem arises,
  * it stores the error message in global $api_failureList
  * @assert ('Sam','Gamegie',5,'*****@*****.**','jo','jo') > 1
  * @assert ('Pippin','Took',null,null,'jo','jo') === false
  */
 public static function create_user($firstName, $lastName, $status, $email, $loginName, $password, $official_code = '', $language = '', $phone = '', $picture_uri = '', $auth_source = PLATFORM_AUTH_SOURCE, $expirationDate = null, $active = 1, $hr_dept_id = 0, $extra = null, $encrypt_method = '', $send_mail = false, $isAdmin = false)
 {
     $currentUserId = api_get_user_id();
     $hook = HookCreateUser::create();
     if (!empty($hook)) {
         $hook->notifyCreateUser(HOOK_EVENT_TYPE_PRE);
     }
     global $_configuration;
     $original_password = $password;
     $access_url_id = 1;
     if (api_get_multiple_access_url()) {
         $access_url_id = api_get_current_access_url_id();
     }
     if (is_array($_configuration[$access_url_id]) && isset($_configuration[$access_url_id]['hosting_limit_users']) && $_configuration[$access_url_id]['hosting_limit_users'] > 0) {
         $num = self::get_number_of_users();
         if ($num >= $_configuration[$access_url_id]['hosting_limit_users']) {
             api_warn_hosting_contact('hosting_limit_users');
             Display::addFlash(Display::return_message(get_lang('PortalUsersLimitReached'), 'warning'));
             return false;
         }
     }
     if ($status === 1 && is_array($_configuration[$access_url_id]) && isset($_configuration[$access_url_id]['hosting_limit_teachers']) && $_configuration[$access_url_id]['hosting_limit_teachers'] > 0) {
         $num = self::get_number_of_users(1);
         if ($num >= $_configuration[$access_url_id]['hosting_limit_teachers']) {
             Display::addFlash(Display::return_message(get_lang('PortalTeachersLimitReached'), 'warning'));
             api_warn_hosting_contact('hosting_limit_teachers');
             return false;
         }
     }
     if (empty($password)) {
         Display::addFlash(Display::return_message(get_lang('ThisFieldIsRequired') . ': ' . get_lang('Password'), 'warning'));
         return false;
     }
     // database table definition
     $table_user = Database::get_main_table(TABLE_MAIN_USER);
     //Checking the user language
     $languages = api_get_languages();
     $language = strtolower($language);
     if (!in_array($language, $languages['folder'])) {
         $language = api_get_setting('platformLanguage');
     }
     if (!empty($currentUserId)) {
         $creator_id = $currentUserId;
     } else {
         $creator_id = '';
     }
     // First check wether the login already exists
     if (!self::is_username_available($loginName)) {
         return api_set_failure('login-pass already taken');
     }
     $currentDate = api_get_utc_datetime();
     $now = new DateTime($currentDate);
     if (empty($expirationDate)) {
         // Default expiration date
         // if there is a default duration of a valid account then
         // we have to change the expiration_date accordingly
         if (api_get_setting('account_valid_duration') != '') {
             $expirationDate = new DateTime($currentDate);
             $days = intval(api_get_setting('account_valid_duration'));
             $expirationDate->modify('+' . $days . ' day');
         }
     } else {
         $expirationDate = api_get_utc_datetime($expirationDate);
         $expirationDate = new \DateTime($expirationDate, new DateTimeZone('UTC'));
     }
     $userManager = self::getManager();
     /** @var User $user */
     $user = $userManager->createUser();
     $user->setLastname($lastName)->setFirstname($firstName)->setUsername($loginName)->setStatus($status)->setPlainPassword($password)->setEmail($email)->setOfficialCode($official_code)->setPictureUri($picture_uri)->setCreatorId($creator_id)->setAuthSource($auth_source)->setPhone($phone)->setLanguage($language)->setRegistrationDate($now)->setHrDeptId($hr_dept_id)->setActive($active);
     if (!empty($expirationDate)) {
         $user->setExpirationDate($expirationDate);
     }
     $userManager->updateUser($user, true);
     $userId = $user->getId();
     if (!empty($userId)) {
         $return = $userId;
         $sql = "UPDATE {$table_user} SET user_id = {$return} WHERE id = {$return}";
         Database::query($sql);
         if ($isAdmin) {
             UserManager::add_user_as_admin($userId);
         }
         if (api_get_multiple_access_url()) {
             UrlManager::add_user_to_url($return, api_get_current_access_url_id());
         } else {
             //we are adding by default the access_url_user table with access_url_id = 1
             UrlManager::add_user_to_url($return, 1);
         }
         if (!empty($email) && $send_mail) {
             $recipient_name = api_get_person_name($firstName, $lastName, null, PERSON_NAME_EMAIL_ADDRESS);
             $tplSubject = new Template(null, false, false, false, false, false);
             $layoutSubject = $tplSubject->get_template('mail/subject_registration_platform.tpl');
             $emailSubject = $tplSubject->fetch($layoutSubject);
             $sender_name = api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'), null, PERSON_NAME_EMAIL_ADDRESS);
             $email_admin = api_get_setting('emailAdministrator');
             if (api_is_multiple_url_enabled()) {
                 $access_url_id = api_get_current_access_url_id();
                 if ($access_url_id != -1) {
                     $url = api_get_access_url($access_url_id);
                 }
             } else {
                 $url = $_configuration['root_web'];
             }
             $tplContent = new Template(null, false, false, false, false, false);
             // variables for the default template
             $tplContent->assign('complete_name', stripslashes(api_get_person_name($firstName, $lastName)));
             $tplContent->assign('login_name', $loginName);
             $tplContent->assign('original_password', stripslashes($original_password));
             $tplContent->assign('mailWebPath', $url);
             $layoutContent = $tplContent->get_template('mail/content_registration_platform.tpl');
             $emailBody = $tplContent->fetch($layoutContent);
             /* MANAGE EVENT WITH MAIL */
             if (EventsMail::check_if_using_class('user_registration')) {
                 $values["about_user"] = $return;
                 $values["password"] = $original_password;
                 $values["send_to"] = array($return);
                 $values["prior_lang"] = null;
                 EventsDispatcher::events('user_registration', $values);
             } else {
                 $phoneNumber = isset($extra['mobile_phone_number']) ? $extra['mobile_phone_number'] : null;
                 $additionalParameters = array('smsType' => SmsPlugin::WELCOME_LOGIN_PASSWORD, 'userId' => $return, 'mobilePhoneNumber' => $phoneNumber, 'password' => $original_password);
                 api_mail_html($recipient_name, $email, $emailSubject, $emailBody, $sender_name, $email_admin, null, null, null, $additionalParameters);
             }
             /* ENDS MANAGE EVENT WITH MAIL */
         }
         Event::addEvent(LOG_USER_CREATE, LOG_USER_ID, $return);
     } else {
         return api_set_failure('error inserting in Database');
     }
     if (is_array($extra) && count($extra) > 0) {
         $res = true;
         foreach ($extra as $fname => $fvalue) {
             $res = $res && self::update_extra_field_value($return, $fname, $fvalue);
         }
     }
     self::update_extra_field_value($return, 'already_logged_in', 'false');
     if (!empty($hook)) {
         $hook->setEventData(array('return' => $return, 'originalPassword' => $original_password));
         $hook->notifyCreateUser(HOOK_EVENT_TYPE_POST);
     }
     return $return;
 }
 /**
  * Creates a course
  * @param   array $params columns in the main.course table
  *
  * @return  mixed  false if the course was not created, array with the course info
  */
 public static function create_course($params, $extraFields = array())
 {
     global $_configuration;
     // Check portal limits
     $access_url_id = 1;
     if (api_get_multiple_access_url()) {
         $access_url_id = api_get_current_access_url_id();
     }
     if (isset($_configuration[$access_url_id]) && is_array($_configuration[$access_url_id])) {
         if (isset($_configuration[$access_url_id]['hosting_limit_courses']) && $_configuration[$access_url_id]['hosting_limit_courses'] > 0) {
             $num = self::count_courses($access_url_id);
             if ($num >= $_configuration[$access_url_id]['hosting_limit_courses']) {
                 api_warn_hosting_contact('hosting_limit_courses');
                 return api_set_failure(get_lang('PortalCoursesLimitReached'));
             }
         }
         if (isset($_configuration[$access_url_id]['hosting_limit_active_courses']) && $_configuration[$access_url_id]['hosting_limit_active_courses'] > 0) {
             $num = self::countActiveCourses($access_url_id);
             if ($num >= $_configuration[$access_url_id]['hosting_limit_active_courses']) {
                 api_warn_hosting_contact('hosting_limit_active_courses');
                 return api_set_failure(get_lang('PortalActiveCoursesLimitReached'));
             }
         }
     }
     if (empty($params['title'])) {
         return false;
     }
     if (empty($params['wanted_code'])) {
         $params['wanted_code'] = $params['title'];
         // Check whether the requested course code has already been occupied.
         $params['wanted_code'] = CourseManager::generate_course_code(api_substr($params['title'], 0, self::MAX_COURSE_LENGTH_CODE));
     }
     // Create the course keys
     $keys = AddCourse::define_course_keys($params['wanted_code']);
     $params['exemplary_content'] = isset($params['exemplary_content']) ? $params['exemplary_content'] : false;
     if (count($keys)) {
         $params['code'] = $keys['currentCourseCode'];
         $params['visual_code'] = $keys['currentCourseId'];
         $params['directory'] = $keys['currentCourseRepository'];
         $course_info = api_get_course_info($params['code']);
         if (empty($course_info)) {
             $course_id = AddCourse::register_course($params);
             $course_info = api_get_course_info_by_id($course_id);
             if (!empty($course_info)) {
                 AddCourse::prepare_course_repository($course_info['directory'], $course_info['code']);
                 AddCourse::fill_db_course($course_id, $course_info['directory'], $course_info['course_language'], $params['exemplary_content']);
                 if (api_get_setting('gradebook.gradebook_enable_grade_model') == 'true') {
                     //Create gradebook_category for the new course and add
                     // a gradebook model for the course
                     if (isset($params['gradebook_model_id']) && !empty($params['gradebook_model_id']) && $params['gradebook_model_id'] != '-1') {
                         GradebookUtils::create_default_course_gradebook($course_info['code'], $params['gradebook_model_id']);
                     }
                 }
                 // If parameter defined, copy the contents from a specific
                 // template course into this new course
                 $template = api_get_setting('course.course_creation_use_template');
                 if (!empty($template)) {
                     // Include the necessary libraries to generate a course copy
                     require_once api_get_path(SYS_CODE_PATH) . 'coursecopy/classes/CourseBuilder.class.php';
                     require_once api_get_path(SYS_CODE_PATH) . 'coursecopy/classes/CourseRestorer.class.php';
                     require_once api_get_path(SYS_CODE_PATH) . 'coursecopy/classes/CourseSelectForm.class.php';
                     // Call the course copy object
                     $originCourse = api_get_course_info_by_id($template);
                     $originCourse['official_code'] = $originCourse['code'];
                     $cb = new CourseBuilder(null, $originCourse);
                     $course = $cb->build(null, $originCourse['code']);
                     $cr = new CourseRestorer($course);
                     $cr->set_file_option();
                     $cr->restore($course_info['id']);
                     //course_info[id] is the course.code value (I know...)
                 }
                 $params['course_code'] = $course_info['code'];
                 $params['item_id'] = $course_info['real_id'];
                 $courseFieldValue = new ExtraFieldValue('course');
                 $courseFieldValue->saveFieldValues($params);
                 return $course_info;
             }
         }
     }
     return false;
 }
$courseInfo['real_code'] = $courseInfo['code'];
$courseInfo['add_teachers_to_sessions_courses'] = isset($courseInfo['add_teachers_to_sessions_courses']) ? $courseInfo['add_teachers_to_sessions_courses'] : 0;
$form->setDefaults($courseInfo);
// Validate form
if ($form->validate()) {
    $course = $form->getSubmitValues();
    $visibility = $course['visibility'];
    global $_configuration;
    $urlId = api_get_current_access_url_id();
    if (isset($_configuration[$urlId]) && isset($_configuration[$urlId]['hosting_limit_active_courses']) && $_configuration[$urlId]['hosting_limit_active_courses'] > 0) {
        // Check if
        if ($courseInfo['visibility'] == COURSE_VISIBILITY_HIDDEN && $visibility != $courseInfo['visibility']) {
            $num = CourseManager::countActiveCourses($urlId);
            if ($num >= $_configuration[$urlId]['hosting_limit_active_courses']) {
                api_warn_hosting_contact('hosting_limit_active_courses');
                api_set_failure(get_lang('PortalActiveCoursesLimitReached'));
                header('Location: course_list.php?action=show_msg&warn=' . urlencode(get_lang('PortalActiveCoursesLimitReached')));
                exit;
            }
        }
    }
    $visual_code = $course['visual_code'];
    $visual_code = CourseManager::generate_course_code($visual_code);
    // Check if the visual code is already used by *another* course
    $visual_code_is_used = false;
    $warn = get_lang('TheFollowingCoursesAlreadyUseThisVisualCode');
    if (!empty($visual_code)) {
        $list = CourseManager::get_courses_info_from_visual_code($visual_code);
        foreach ($list as $course_temp) {
            if ($course_temp['code'] != $course_code) {
                $visual_code_is_used = true;
Exemple #5
0
 /**
  * Creates a course
  * @param   array   with the columns in the main.course table
  * @param   mixed   false if the course was not created, array with the course info
  * @return mixed False on error, or an array with course attributes on success
  * @todo remove globals
  * @assert () === false
  */
 public static function create_course($params)
 {
     global $_configuration;
     // Check portal limits
     $access_url_id = 1;
     if (api_get_multiple_access_url()) {
         $access_url_id = api_get_current_access_url_id();
     }
     if (is_array($_configuration[$access_url_id]) && isset($_configuration[$access_url_id]['hosting_limit_courses']) && $_configuration[$access_url_id]['hosting_limit_courses'] > 0) {
         $num = self::count_courses();
         if ($num >= $_configuration[$access_url_id]['hosting_limit_courses']) {
             return api_set_failure('PortalCoursesLimitReached');
         }
     }
     if (empty($params['title'])) {
         return false;
     }
     if (empty($params['wanted_code'])) {
         $params['wanted_code'] = $params['title'];
         // Check whether the requested course code has already been occupied.
         $params['wanted_code'] = self::generate_course_code(api_substr($params['title'], 0, self::MAX_COURSE_LENGTH_CODE));
     }
     // Create the course keys
     $keys = self::define_course_keys($params['wanted_code']);
     $params['exemplary_content'] = isset($params['exemplary_content']) ? $params['exemplary_content'] : false;
     if (count($keys)) {
         $params['code'] = $keys['currentCourseCode'];
         $params['visual_code'] = $keys['currentCourseId'];
         $params['directory'] = $keys['currentCourseRepository'];
         $course_info = api_get_course_info($params['code']);
         if (empty($course_info)) {
             $course_id = self::register_course($params);
             $course_info = api_get_course_info_by_id($course_id);
             if (!empty($course_info)) {
                 self::prepare_course_repository($course_info['directory'], $course_info['code']);
                 self::fill_db_course($course_id, $course_info['directory'], $course_info['course_language'], $params['exemplary_content']);
                 //Create an empty gradebook
                 if (isset($params['create_gradebook_evaluation']) && $params['create_gradebook_evaluation'] == true) {
                     require_once api_get_path(SYS_CODE_PATH) . 'gradebook/lib/gradebook_functions.inc.php';
                     $category_id = create_default_course_gradebook($course_info['code']);
                     if ($category_id && isset($params['gradebook_params'])) {
                         $eval = new Evaluation();
                         $eval->set_name($params['gradebook_params']['name']);
                         $eval->set_user_id($params['gradebook_params']['user_id']);
                         $eval->set_course_code($course_info['code']);
                         $eval->set_category_id($category_id);
                         $eval->set_weight($params['gradebook_params']['weight']);
                         $eval->set_max($params['gradebook_params']['max']);
                         $eval->set_visible(0);
                         $eval->add();
                     }
                 }
                 if (api_get_setting('gradebook.gradebook_enable_grade_model') == 'true') {
                     //Create gradebook_category for the new course and add a gradebook model for the course
                     if (isset($params['gradebook_model_id']) && !empty($params['gradebook_model_id']) && $params['gradebook_model_id'] != '-1') {
                         require_once api_get_path(SYS_CODE_PATH) . 'gradebook/lib/gradebook_functions.inc.php';
                         create_default_course_gradebook($course_info['code'], $params['gradebook_model_id']);
                     }
                 }
                 //Saving extra course fields
                 $field_value = new ExtraFieldValue('course');
                 $params['course_code'] = $course_info['code'];
                 $field_value->save_field_values($params);
                 return $course_info;
             }
         } else {
             //Course already exists
             if (isset($params['return_item_if_already_exists']) && $params['return_item_if_already_exists']) {
                 return $course_info;
             }
         }
     }
     return false;
 }
 /**
  * Creates a new extra field
  * @param    string    Field's internal variable name
  * @param    int        Field's type
  * @param    string    Field's language var name
  * @param    string    Field's default value
  * @param    string    Optional comma-separated list of options to provide for select and radio
  * @return int     new user id - if the new user creation succeeds, false otherwise
  */
 public static function create_extra_field($fieldvarname, $fieldtype, $fieldtitle, $fielddefault, $fieldoptions = '')
 {
     // database table definition
     $table_field = Database::get_main_table(TABLE_MAIN_USER_FIELD);
     $table_field_options = Database::get_main_table(TABLE_MAIN_USER_FIELD_OPTIONS);
     // First check wether the login already exists
     if (self::is_extra_field_available($fieldvarname)) {
         return api_set_failure('login-pass already taken');
     }
     $sql = "SELECT MAX(field_order) FROM {$table_field}";
     $res = Database::query($sql);
     $order = 0;
     if (Database::num_rows($res) > 0) {
         $row = Database::fetch_array($res);
         $order = $row[0] + 1;
     }
     $time = api_get_utc_datetime();
     $sql = "INSERT INTO {$table_field}\n                SET field_type = '" . Database::escape_string($fieldtype) . "',\n                field_variable = '" . Database::escape_string($fieldvarname) . "',\n                field_display_text = '" . Database::escape_string($fieldtitle) . "',\n                field_default_value = '" . Database::escape_string($fielddefault) . "',\n                field_order = '{$order}',\n                tms = '{$time}'";
     $result = Database::query($sql);
     if ($result) {
         //echo "id returned";
         $return = Database::insert_id();
     } else {
         //echo "false - failed" ;
         return false;
     }
     if (!empty($fieldoptions) && in_array($fieldtype, array(ExtraField::FIELD_TYPE_RADIO, ExtraField::FIELD_TYPE_SELECT, ExtraField::FIELD_TYPE_SELECT_MULTIPLE, ExtraField::FIELD_TYPE_DOUBLE_SELECT))) {
         if ($fieldtype == ExtraField::FIELD_TYPE_DOUBLE_SELECT) {
             $twolist = explode('|', $fieldoptions);
             $counter = 0;
             foreach ($twolist as $individual_list) {
                 $splitted_individual_list = split(';', $individual_list);
                 foreach ($splitted_individual_list as $individual_list_option) {
                     //echo 'counter:'.$counter;
                     if ($counter == 0) {
                         $list[] = $individual_list_option;
                     } else {
                         $list[] = str_repeat('*', $counter) . $individual_list_option;
                     }
                 }
                 $counter++;
             }
         } else {
             $list = split(';', $fieldoptions);
         }
         foreach ($list as $option) {
             $option = Database::escape_string($option);
             $sql = "SELECT * FROM {$table_field_options} WHERE field_id = {$return} AND option_value = '" . $option . "'";
             $res = Database::query($sql);
             if (Database::num_rows($res) > 0) {
                 //the option already exists, do nothing
             } else {
                 $sql = "SELECT MAX(option_order) FROM {$table_field_options} WHERE field_id = {$return}";
                 $res = Database::query($sql);
                 $max = 1;
                 if (Database::num_rows($res) > 0) {
                     $row = Database::fetch_array($res);
                     $max = $row[0] + 1;
                 }
                 $time = time();
                 $sql = "INSERT INTO {$table_field_options} (field_id,option_value,option_display_text,option_order,tms) VALUES ({$return},'{$option}','{$option}',{$max}, '{$time}')";
                 $res = Database::query($sql);
                 if ($res === false) {
                     $return = false;
                 }
             }
         }
     }
     return $return;
 }