Пример #1
0
 /**
  * Creates a new url access
  *
  * @author Julio Montoya <*****@*****.**>,
  *
  * @param string The URL of the site
  * @param string The description of the site
  * @param int is active or not
  * @param int the user_id of the owner
  * @param int The type of URL (1=multiple-access-url, 2=sincro-server, 3=sincro-client)
  * @param array If the type is different than 1, then there might be extra URL parameters to take into account
  * @return boolean if success
  */
 public static function add($url, $description, $active, $type = 1, $extra_params)
 {
     $tms = time();
     $type = intval($type);
     $table_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL);
     $u = api_get_user_id();
     if ($u == 0) {
         $u = api_get_anonymous_id();
     }
     if ($type > 1) {
         $active = 0;
     }
     $sql = "INSERT INTO {$table_access_url} " . " SET url \t= '" . Database::escape_string($url) . "', " . " description = '" . Database::escape_string($description) . "', " . " active \t\t= {$active}, " . " created_by \t= {$u}, " . " url_type        = {$type}, " . " tms = FROM_UNIXTIME(" . $tms . ")";
     $result = Database::query($sql);
     $id = Database::insert_id();
     if ($result !== false && $type == 3 && count($extra_params) > 0) {
         // Register extra parameters in the branch_sync table
         $t = Database::get_main_table(TABLE_BRANCH_SYNC);
         $sql = "INSERT INTO {$t} SET " . " access_url_id = {$id} " . (!empty($extra_params['ip']) ? ", branch_ip = '" . Database::escape_string($extra_params['ip']) . "'" : "") . (!empty($extra_params['name']) ? ", branch_name = '" . Database::escape_string($extra_params['name']) . "'" : "") . (!empty($extra_params['last_sync']) ? ", last_sync_trans_id = '" . Database::escape_string($extra_params['last_sync']) . "'" : "") . (!empty($extra_params['dwn_speed']) ? ", dwn_speed = '" . Database::escape_string($extra_params['dwn_speed']) . "'" : "") . (!empty($extra_params['up_speed']) ? ", up_speed = '" . Database::escape_string($extra_params['up_speed']) . "'" : "") . (!empty($extra_params['delay']) ? ", delay = '" . Database::escape_string($extra_params['delay']) . "'" : "") . (!empty($extra_params['admin_mail']) ? ", admin_mail = '" . Database::escape_string($extra_params['admin_mail']) . "'" : "") . (!empty($extra_params['admin_name']) ? ", admin_name = '" . Database::escape_string($extra_params['admin_name']) . "'" : "") . (!empty($extra_params['admin_phone']) ? ", admin_phone = '" . Database::escape_string($extra_params['admin_phone']) . "'" : "") . (!empty($extra_params['latitude']) ? ", latitude = '" . Database::escape_string($extra_params['latitude']) . "'" : "") . (!empty($extra_params['longitude']) ? ", longitude = '" . Database::escape_string($extra_params['longitude']) . "'" : "") . ", last_sync_trans_date = '" . api_get_utc_datetime() . "'";
         $result = $result && Database::query($sql);
     }
     return $result;
 }
Пример #2
0
    $redirect = !empty($_GET['no_redirect']) ? false : true;
    $controller->logout($redirect);
}
/* Table definitions */
/* Constants and CONFIGURATION parameters */
/** @todo these configuration settings should move to the Chamilo config settings. */
/** Defines wether or not anonymous visitors can see a list of the courses on the Chamilo homepage that are open to the world. */
$_setting['display_courses_to_anonymous_users'] = 'true';
/* LOGIN */
/**
 * Registers in the track_e_default table (view in important activities in admin
 * interface) a possible attempted break in, sending auth data through get.
 * @todo This piece of code should probably move to local.inc.php where the actual login / logout procedure is handled. The real use of this code block should be seriously considered as well. This form should just use a security token and get done with it.
 */
if (isset($_GET['submitAuth']) && $_GET['submitAuth'] == 1) {
    $i = api_get_anonymous_id();
    Event::addEvent(LOG_ATTEMPTED_FORCED_LOGIN, 'tried_hacking_get', $_SERVER['REMOTE_ADDR'] . (empty($_POST['login']) ? '' : '/' . $_POST['login']), null, $i);
    echo 'Attempted breakin - sysadmins notified.';
    session_destroy();
    die;
}
// Delete session neccesary for legal terms
if (api_get_setting('allow_terms_conditions') == 'true') {
    Session::erase('term_and_condition');
}
//If we are not logged in and customapages activated
if (!api_get_user_id() && CustomPages::enabled()) {
    if (Request::get('loggedout')) {
        CustomPages::display(CustomPages::LOGGED_OUT);
    } else {
        CustomPages::display(CustomPages::INDEX_UNLOGGED);
// setting the section (for the tabs)
$this_section = SECTION_PLATFORM_ADMIN;
// Access restrictions
api_protect_admin_script(true);
// setting breadcrumbs
$interbreadcrumb[] = array('url' => 'index.php', 'name' => get_lang('PlatformAdmin'));
$interbreadcrumb[] = array('url' => 'user_list.php', 'name' => get_lang('UserList'));
// Database Table Definitions
$tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
$tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
$tbl_session_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
// initializing variables
$id_session = intval($_GET['id_session']);
$user_id = intval($_GET['user']);
$user_info = api_get_user_info($user_id);
$user_anonymous = api_get_anonymous_id();
$current_user_id = api_get_user_id();
// setting the name of the tool
if (UserManager::is_admin($user_id)) {
    $tool_name = get_lang('AssignSessionsToPlatformAdministrator');
} else {
    if ($user_info['status'] == SESSIONADMIN) {
        $tool_name = get_lang('AssignSessionsToSessionsAdministrator');
    } else {
        $tool_name = get_lang('AssignSessionsToHumanResourcesManager');
    }
}
$add_type = 'multiple';
if (isset($_GET['add_type']) && $_GET['add_type'] != '') {
    $add_type = Security::remove_XSS($_REQUEST['add_type']);
}
Пример #4
0
 /**
  * Record an event for this attempt at answering an exercise
  * @param	float	Score achieved
  * @param	string	Answer given
  * @param	integer	Question ID
  * @param	integer Exercise attempt ID a.k.a exe_id (from track_e_exercise)
  * @param	integer	Position
  * @param	integer Exercise ID (from c_quiz)
  * @param	bool update results?
  * @param	string  Filename (for audio answers - using nanogong)
  * @param	integer User ID The user who's going to get this score. Default value of null means "get from context".
  * @param	integer	Course ID (from the "id" column of course table). Default value of null means "get from context".
  * @param	integer	Session ID (from the session table). Default value of null means "get from context".
  * @param	integer	Learnpath ID (from c_lp table). Default value of null means "get from context".
  * @param	integer	Learnpath item ID (from the c_lp_item table). Default value of null means "get from context".
  * @return	boolean	Result of the insert query
  */
 public static function saveQuestionAttempt($score, $answer, $question_id, $exe_id, $position, $exercise_id = 0, $updateResults = false, $nano = null, $user_id = null, $course_id = null, $session_id = null, $learnpath_id = null, $learnpath_item_id = null)
 {
     global $debug;
     $question_id = Database::escape_string($question_id);
     $exe_id = Database::escape_string($exe_id);
     $position = Database::escape_string($position);
     $now = api_get_utc_datetime();
     // check user_id or get from context
     if (empty($user_id)) {
         $user_id = api_get_user_id();
         // anonymous
         if (empty($user_id)) {
             $user_id = api_get_anonymous_id();
         }
     }
     // check course_id or get from context
     if (empty($course_id) or intval($course_id) != $course_id) {
         $course_id = api_get_course_int_id();
     }
     // check session_id or get from context
     if (empty($session_id)) {
         $session_id = api_get_session_id();
     }
     // check learnpath_id or get from context
     if (empty($learnpath_id)) {
         global $learnpath_id;
     }
     // check learnpath_item_id or get from context
     if (empty($learnpath_item_id)) {
         global $learnpath_item_id;
     }
     $TBL_TRACK_ATTEMPT = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
     if ($debug) {
         error_log("----- entering saveQuestionAttempt() function ------");
         error_log("answer: {$answer}");
         error_log("score: {$score}");
         error_log("question_id : {$question_id}");
         error_log("position: {$position}");
     }
     //Validation in case of fraud with active control time
     if (!ExerciseLib::exercise_time_control_is_valid($exercise_id, $learnpath_id, $learnpath_item_id)) {
         if ($debug) {
             error_log("exercise_time_control_is_valid is false");
         }
         $score = 0;
         $answer = 0;
     }
     $file = '';
     if (isset($nano)) {
         $file = Database::escape_string(basename($nano->load_filename_if_exists(false)));
     }
     $session_id = api_get_session_id();
     if (!empty($question_id) && !empty($exe_id) && !empty($user_id)) {
         $attempt = array('user_id' => $user_id, 'question_id' => $question_id, 'answer' => $answer, 'marks' => $score, 'c_id' => $course_id, 'session_id' => $session_id, 'position' => $position, 'tms' => $now, 'filename' => $file);
         // Check if attempt exists.
         $sql = "SELECT exe_id FROM {$TBL_TRACK_ATTEMPT}\n                    WHERE\n                        c_id = {$course_id} AND\n                        session_id = {$session_id} AND\n                        exe_id = {$exe_id} AND\n                        user_id = {$user_id} AND\n                        question_id = {$question_id} AND\n                        position = {$position}";
         $result = Database::query($sql);
         if (Database::num_rows($result)) {
             if ($debug) {
                 error_log("Attempt already exist: exe_id: {$exe_id} - user_id:{$user_id} - question_id:{$question_id}");
             }
             if ($updateResults == false) {
                 //The attempt already exist do not update use  update_event_exercise() instead
                 return false;
             }
         } else {
             $attempt['exe_id'] = $exe_id;
         }
         if ($debug) {
             error_log("updateResults : {$updateResults}");
             error_log("Saving question attempt: ");
             error_log($sql);
         }
         $recording_table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT_RECORDING);
         if ($updateResults == false) {
             $attempt_id = Database::insert($TBL_TRACK_ATTEMPT, $attempt);
             if (defined('ENABLED_LIVE_EXERCISE_TRACKING')) {
                 if ($debug) {
                     error_log("Saving e attempt recording ");
                 }
                 $attempt_recording = array('exe_id' => $attempt_id, 'question_id' => $question_id, 'marks' => $score, 'insert_date' => $now, 'author' => '', 'session_id' => $session_id);
                 Database::insert($recording_table, $attempt_recording);
             }
         } else {
             Database::update($TBL_TRACK_ATTEMPT, $attempt, array('exe_id = ? AND question_id = ? AND user_id = ? ' => array($exe_id, $question_id, $user_id)));
             if (defined('ENABLED_LIVE_EXERCISE_TRACKING')) {
                 $attempt_recording = array('exe_id' => $exe_id, 'question_id' => $question_id, 'marks' => $score, 'insert_date' => $now, 'author' => '', 'session_id' => $session_id);
                 Database::update($recording_table, $attempt_recording, array('exe_id = ? AND question_id = ? AND session_id = ? ' => array($exe_id, $question_id, $session_id)));
             }
             $attempt_id = $exe_id;
         }
         return $attempt_id;
     } else {
         return false;
     }
 }
Пример #5
0
/**
 * Checks wether a user can or can't view the contents of a course.
 *
 * @param   int $userid     User id or NULL to get it from $_SESSION
 * @param   int $cid        Course id to check whether the user is allowed.
 * @return  bool
 */
function api_is_course_visible_for_user($userid = null, $cid = null)
{
    if ($userid == null) {
        $userid = api_get_user_id();
    }
    if (empty($userid) || strval(intval($userid)) != $userid) {
        if (api_is_anonymous()) {
            $userid = api_get_anonymous_id();
        } else {
            return false;
        }
    }
    $cid = Database::escape_string($cid);
    $courseInfo = api_get_course_info($cid);
    $courseId = $courseInfo['real_id'];
    $is_platformAdmin = api_is_platform_admin();
    $course_table = Database::get_main_table(TABLE_MAIN_COURSE);
    $course_cat_table = Database::get_main_table(TABLE_MAIN_CATEGORY);
    $sql = "SELECT\n                {$course_table}.category_code,\n                {$course_table}.visibility,\n                {$course_table}.code,\n                {$course_cat_table}.code\n            FROM {$course_table}\n            LEFT JOIN {$course_cat_table}\n                ON {$course_table}.category_code = {$course_cat_table}.code\n            WHERE\n                {$course_table}.code = '{$cid}'\n            LIMIT 1";
    $result = Database::query($sql);
    if (Database::num_rows($result) > 0) {
        $visibility = Database::fetch_array($result);
        $visibility = $visibility['visibility'];
    } else {
        $visibility = 0;
    }
    // Shortcut permissions in case the visibility is "open to the world".
    if ($visibility === COURSE_VISIBILITY_OPEN_WORLD) {
        return true;
    }
    $tbl_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
    $sql = "SELECT\n                is_tutor, status\n            FROM {$tbl_course_user}\n            WHERE\n                user_id  = '{$userid}' AND\n                relation_type <> '" . COURSE_RELATION_TYPE_RRHH . "' AND\n                c_id = {$courseId}\n            LIMIT 1";
    $result = Database::query($sql);
    if (Database::num_rows($result) > 0) {
        // This user has got a recorded state for this course.
        $cuData = Database::fetch_array($result);
        $is_courseMember = true;
        $is_courseTutor = $cuData['is_tutor'] == 1;
        $is_courseAdmin = $cuData['status'] == 1;
    }
    if (!$is_courseAdmin) {
        // This user has no status related to this course.
        // Is it the session coach or the session admin?
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
        $tbl_session_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
        $tbl_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
        $sql = "SELECT\n                    session.id_coach, session_admin_id, session.id\n                FROM\n                    {$tbl_session} as session\n                INNER JOIN {$tbl_session_course}\n                    ON session_rel_course.session_id = session.id\n                    AND session_rel_course.c_id = '{$courseId}'\n                LIMIT 1";
        $result = Database::query($sql);
        $row = Database::store_result($result);
        if ($row[0]['id_coach'] == $userid) {
            $is_courseMember = true;
            $is_courseTutor = true;
            $is_courseAdmin = false;
            $is_courseCoach = true;
            $is_sessionAdmin = false;
        } elseif ($row[0]['session_admin_id'] == $userid) {
            $is_courseMember = false;
            $is_courseTutor = false;
            $is_courseAdmin = false;
            $is_courseCoach = false;
            $is_sessionAdmin = true;
        } else {
            // Check if the current user is the course coach.
            $sql = "SELECT 1\n                    FROM {$tbl_session_course}\n                    WHERE session_rel_course.c_id = '{$courseId}'\n                    AND session_rel_course.id_coach = '{$userid}'\n                    LIMIT 1";
            $result = Database::query($sql);
            //if ($row = Database::fetch_array($result)) {
            if (Database::num_rows($result) > 0) {
                $is_courseMember = true;
                $is_courseTutor = true;
                $is_courseCoach = true;
                $is_sessionAdmin = false;
                $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
                $sql = "SELECT status FROM {$tbl_user}\n                        WHERE user_id = {$userid}\n                        LIMIT 1";
                $result = Database::query($sql);
                if (Database::result($result, 0, 0) == 1) {
                    $is_courseAdmin = true;
                } else {
                    $is_courseAdmin = false;
                }
            } else {
                // Check if the user is a student is this session.
                $sql = "SELECT  id\n                        FROM {$tbl_session_course_user}\n                        WHERE\n                            user_id  = '{$userid}' AND\n                            c_id = '{$courseId}'\n                        LIMIT 1";
                if (Database::num_rows($result) > 0) {
                    // This user haa got a recorded state for this course.
                    while ($row = Database::fetch_array($result)) {
                        $is_courseMember = true;
                        $is_courseTutor = false;
                        $is_courseAdmin = false;
                        $is_sessionAdmin = false;
                    }
                }
            }
        }
    }
    switch ($visibility) {
        case COURSE_VISIBILITY_OPEN_WORLD:
            return true;
        case COURSE_VISIBILITY_OPEN_PLATFORM:
            return isset($userid);
        case COURSE_VISIBILITY_REGISTERED:
        case COURSE_VISIBILITY_CLOSED:
            return $is_platformAdmin || $is_courseMember || $is_courseAdmin;
        case COURSE_VISIBILITY_HIDDEN:
            return $is_platformAdmin;
    }
    return false;
}
function search_users($needle, $type, $relation_type)
{
    global $tbl_user, $tbl_user_rel_access_url, $tbl_group_rel_user, $group_id;
    $xajax_response = new xajaxResponse();
    $return = $return_origin = $return_destination = '';
    $without_user_id = $without_user_id = $condition_relation = '';
    if (!empty($group_id) && !empty($relation_type)) {
        $group_id = intval($group_id);
        $relation_type = intval($relation_type);
        // get user_id from relation type and group id
        $sql = "SELECT user_id FROM {$tbl_group_rel_user}\n                WHERE group_id = '{$group_id}'\n                AND relation_type IN (" . GROUP_USER_PERMISSION_ADMIN . "," . GROUP_USER_PERMISSION_READER . "," . GROUP_USER_PERMISSION_PENDING_INVITATION . "," . GROUP_USER_PERMISSION_MODERATOR . ", " . GROUP_USER_PERMISSION_HRM . ") ";
        $res = Database::query($sql);
        $user_ids = array();
        if (Database::num_rows($res) > 0) {
            while ($row = Database::fetch_row($res)) {
                $user_ids[] = $row[0];
            }
            $without_user_id = " AND user.user_id NOT IN(" . implode(',', $user_ids) . ") ";
        }
        $condition_relation = " AND groups.relation_type = '{$relation_type}' ";
        // data for destination user list
        $sql = "SELECT user.user_id, user.username, user.lastname, user.firstname\n                FROM {$tbl_group_rel_user} groups\n                INNER JOIN  {$tbl_user} user ON user.user_id = groups.user_id\n                WHERE groups.group_id = '{$group_id}' {$condition_relation} ";
        $rs_destination = Database::query($sql);
        if (Database::num_rows($rs_destination) > 0) {
            $return_destination .= '<select id="destination_users" name="sessionUsersList[]" multiple="multiple" size="15" style="width:360px;">';
            while ($row = Database::fetch_array($rs_destination)) {
                $person_name = api_get_person_name($row['firstname'], $row['lastname']);
                $return_destination .= '<option value="' . $row['user_id'] . '">' . $person_name . ' (' . $row['username'] . ')</option>';
            }
            $return_destination .= '</select>';
        } else {
            $return_destination .= '<select id="destination_users" name="sessionUsersList[]" multiple="multiple" size="15" style="width:360px;"></select>';
        }
        $xajax_response->addAssign('ajax_destination_list', 'innerHTML', api_utf8_encode($return_destination));
    } else {
        $return_destination .= '<select id="destination_users" name="sessionUsersList[]" multiple="multiple" size="15" style="width:360px;"></select>';
        $xajax_response->addAssign('ajax_destination_list', 'innerHTML', api_utf8_encode($return_destination));
        if ($type == 'single') {
            $return .= '';
            $xajax_response->addAssign('ajax_list_users_single', 'innerHTML', api_utf8_encode($return));
        } else {
            $return_origin .= '<select id="origin_users" name="nosessionUsersList[]" multiple="multiple" size="15" style="width:360px;"></select>';
            $xajax_response->addAssign('ajax_origin_list_multiple', 'innerHTML', api_utf8_encode($return_origin));
        }
    }
    if (!empty($needle) && !empty($type)) {
        $user_anonymous = api_get_anonymous_id();
        $order_clause = api_sort_by_first_name() ? ' ORDER BY firstname, lastname, username' : ' ORDER BY lastname, firstname, username';
        if ($type == 'single') {
            if (!empty($group_id) && !empty($relation_type)) {
                // search users where username or firstname or lastname begins likes $needle
                $sql = "SELECT user_id, username, lastname, firstname\n                        FROM {$tbl_user} user\n                        WHERE (username LIKE '{$needle}%' OR firstname LIKE '{$needle}%' OR lastname LIKE '{$needle}%')\n                        AND user_id<>'{$user_anonymous}' {$without_user_id} {$order_clause} LIMIT 11";
                if (api_is_multiple_url_enabled()) {
                    $access_url_id = api_get_current_access_url_id();
                    if ($access_url_id != -1) {
                        $sql = "SELECT user.user_id, username, lastname, firstname FROM {$tbl_user} user\n                                INNER JOIN {$tbl_user_rel_access_url} url_user ON (url_user.user_id=user.user_id)\n                                WHERE access_url_id = '{$access_url_id}'  AND (username LIKE '{$needle}%' OR firstname LIKE '{$needle}%' OR lastname LIKE '{$needle}%')\n                                AND user.user_id<>'{$user_anonymous}' {$without_user_id} {$order_clause} LIMIT 11 ";
                    }
                }
                $rs_single = Database::query($sql);
                $i = 0;
                while ($user = Database::fetch_array($rs_single)) {
                    $i++;
                    if ($i <= 10) {
                        $person_name = api_get_person_name($user['firstname'], $user['lastname']);
                        $return .= '<a href="javascript: void(0);" onclick="javascript: add_user(\'' . $user['user_id'] . '\',\'' . $person_name . ' (' . $user['username'] . ')' . '\')">' . $person_name . ' (' . $user['username'] . ')</a><br />';
                    } else {
                        $return .= '...<br />';
                    }
                }
                $xajax_response->addAssign('ajax_list_users_single', 'innerHTML', api_utf8_encode($return));
            } else {
                $xajax_response->addAlert(get_lang('YouMustChooseARelationType'));
                $xajax_response->addClear('user_to_add', 'value');
            }
        } else {
            // multiple
            if (!empty($group_id) && !empty($relation_type)) {
                $sql = "SELECT user_id, username, lastname, firstname FROM {$tbl_user} user\n                        WHERE " . (api_sort_by_first_name() ? 'firstname' : 'lastname') . " LIKE '{$needle}%' AND user_id<>'{$user_anonymous}' {$without_user_id} {$order_clause} ";
                if (api_is_multiple_url_enabled()) {
                    $access_url_id = api_get_current_access_url_id();
                    if ($access_url_id != -1) {
                        $sql = "SELECT user.user_id, username, lastname, firstname\n                                FROM {$tbl_user} user\n                                INNER JOIN {$tbl_user_rel_access_url} url_user ON (url_user.user_id=user.user_id)\n                                WHERE\n                                    access_url_id = '{$access_url_id}' AND\n                                    " . (api_sort_by_first_name() ? 'firstname' : 'lastname') . " LIKE '{$needle}%' AND\n                                    user.user_id<>'{$user_anonymous}' {$without_user_id} {$order_clause} ";
                    }
                }
                $rs_multiple = Database::query($sql);
                $return_origin .= '<select id="origin_users" name="nosessionUsersList[]" multiple="multiple" size="15" style="width:360px;">';
                while ($user = Database::fetch_array($rs_multiple)) {
                    $person_name = api_get_person_name($user['firstname'], $user['lastname']);
                    $return_origin .= '<option value="' . $user['user_id'] . '">' . $person_name . ' (' . $user['username'] . ')</option>';
                }
                $return_origin .= '</select>';
                $xajax_response->addAssign('ajax_origin_list_multiple', 'innerHTML', api_utf8_encode($return_origin));
            }
        }
    }
    return $xajax_response;
}
Пример #7
0
/**
 * Record an event for this attempt at answering an exercise
 * @param	float	Score achieved
 * @param	string	Answer given
 * @param	integer	Question ID
 * @param	integer Exercise ID
 * @param	integer	Position
 * @return	boolean	Result of the insert query
 */
function exercise_attempt($score, $answer, $question_id, $exe_id, $position, $exercise_id = 0, $nano = null)
{
    require_once api_get_path(SYS_CODE_PATH) . 'exercice/exercise.lib.php';
    global $debug, $learnpath_id, $learnpath_item_id;
    $score = Database::escape_string($score);
    $answer = Database::escape_string($answer);
    $question_id = Database::escape_string($question_id);
    $exe_id = Database::escape_string($exe_id);
    $position = Database::escape_string($position);
    $now = api_get_utc_datetime();
    $user_id = api_get_user_id();
    $TBL_TRACK_ATTEMPT = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
    if ($debug) {
        error_log("----- entering exercise_attempt() function ------");
    }
    if ($debug) {
        error_log("answer: {$answer}");
    }
    if ($debug) {
        error_log("score: {$score}");
    }
    if ($debug) {
        error_log("question_id : {$question_id}");
    }
    if ($debug) {
        error_log("position: {$position}");
    }
    //Validation in case of fraud with actived control time
    if (!exercise_time_control_is_valid($exercise_id, $learnpath_id, $learnpath_item_id)) {
        if ($debug) {
            error_log("exercise_time_control_is_valid is false");
        }
        $score = 0;
        $answer = 0;
    }
    if (!empty($user_id)) {
        $user_id = "'" . $user_id . "'";
    } else {
        // anonymous
        $user_id = api_get_anonymous_id();
    }
    $file = '';
    if (isset($nano)) {
        $file = Database::escape_string(basename($nano->load_filename_if_exists(false)));
    }
    $course_code = api_get_course_id();
    $session_id = api_get_session_id();
    if (!empty($question_id) && !empty($exe_id) && !empty($user_id)) {
        // Check if attempt exists
        $sql = "SELECT exe_id FROM {$TBL_TRACK_ATTEMPT}\n                WHERE\n                    course_code = '{$course_code}' AND\n                    session_id = {$session_id} AND\n                    exe_id = {$exe_id} AND\n                    user_id = {$user_id} AND\n                    question_id = {$question_id} AND\n                    position = {$position}";
        $result = Database::query($sql);
        if (Database::num_rows($result)) {
            if ($debug) {
                error_log("Attempt already exist: exe_id: {$exe_id} - user_id:{$user_id} - question_id:{$question_id}");
            }
            //The attempt already exist do not update use  update_event_exercice() instead
            return false;
        }
        $sql = "INSERT INTO {$TBL_TRACK_ATTEMPT} (exe_id, user_id, question_id, answer, marks, course_code, session_id, position, tms, filename)\n                  VALUES (\n                  " . $exe_id . ",\n                  " . $user_id . ",\n                   '" . $question_id . "',\n                   '" . $answer . "',\n                   '" . $score . "',\n                   '" . $course_code . "',\n                   '" . $session_id . "',\n                   '" . $position . "',\n                   '" . $now . "',\n                   '" . $file . "'\n                )";
        if ($debug) {
            error_log("Saving question attempt: ");
        }
        if ($debug) {
            error_log($sql);
        }
        $res = Database::query($sql);
        if (defined('ENABLED_LIVE_EXERCISE_TRACKING')) {
            $recording_table = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT_RECORDING);
            if ($debug) {
                error_log("Saving e attempt recording ");
            }
            $recording_changes = "INSERT INTO {$recording_table} (exe_id, question_id, marks, insert_date, author, session_id)\n            VALUES ('{$exe_id}','{$question_id}','{$score}','" . api_get_utc_datetime() . "','', '" . api_get_session_id() . "') ";
            Database::query($recording_changes);
        }
        return $res;
    } else {
        return false;
    }
}
function search_users($needle, $type)
{
    global $tbl_user, $tbl_group_rel_user, $group_id;
    $xajax_response = new XajaxResponse();
    $return = '';
    if (!empty($needle) && !empty($type)) {
        // xajax send utf8 datas... datas in db can be non-utf8 datas
        $charset = api_get_system_encoding();
        $needle = Database::escape_string($needle);
        $needle = api_convert_encoding($needle, $charset, 'utf-8');
        $user_anonymous = api_get_anonymous_id();
        $order_clause = api_sort_by_first_name() ? ' ORDER BY firstname, lastname, username' : ' ORDER BY lastname, firstname, username';
        $cond_user_id = '';
        if (!empty($id_session)) {
            $group_id = Database::escape_string($group_id);
            // check id_user from session_rel_user table
            $sql = 'SELECT id_user FROM ' . $tbl_group_rel_user . ' WHERE usergroup_id ="' . (int) $group_id . '"';
            $res = Database::query($sql);
            $user_ids = array();
            if (Database::num_rows($res) > 0) {
                while ($row = Database::fetch_row($res)) {
                    $user_ids[] = (int) $row[0];
                }
            }
            if (count($user_ids) > 0) {
                $cond_user_id = ' AND user_id NOT IN(' . implode(",", $user_ids) . ')';
            }
        }
        if ($type == 'single') {
            // search users where username or firstname or lastname begins likes $needle
            $sql = 'SELECT user_id, username, lastname, firstname FROM ' . $tbl_user . ' user
					WHERE ( username LIKE "' . $needle . '%" OR
					        firstname LIKE "' . $needle . '%" OR
					        lastname LIKE "' . $needle . '%"
                          ) AND
					      user_id<>"' . $user_anonymous . '"' . $order_clause . ' LIMIT 11';
        } else {
            $sql = 'SELECT user_id, username, lastname, firstname FROM ' . $tbl_user . ' user
					WHERE ' . (api_sort_by_first_name() ? 'firstname' : 'lastname') . ' LIKE "' . $needle . '%" AND user_id<>"' . $user_anonymous . '"' . $cond_user_id . $order_clause;
        }
        if (api_is_multiple_url_enabled()) {
            $tbl_user_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
            $access_url_id = api_get_current_access_url_id();
            if ($access_url_id != -1) {
                if ($type == 'single') {
                    $sql = 'SELECT user.user_id, username, lastname, firstname
					FROM ' . $tbl_user . ' user
					INNER JOIN ' . $tbl_user_rel_access_url . ' url_user ON (url_user.user_id=user.user_id)
					WHERE access_url_id = ' . $access_url_id . '  AND (
					    username LIKE "' . $needle . '%" OR
					    firstname LIKE "' . $needle . '%" OR
					    lastname LIKE "' . $needle . '%")
					    AND user.user_id <> "' . $user_anonymous . '"' . $order_clause . ' LIMIT 11';
                } else {
                    $sql = 'SELECT user.user_id, username, lastname, firstname
					FROM ' . $tbl_user . ' user
					INNER JOIN ' . $tbl_user_rel_access_url . ' url_user ON (url_user.user_id=user.user_id)
					WHERE access_url_id = ' . $access_url_id . ' AND
					       ' . (api_sort_by_first_name() ? 'firstname' : 'lastname') . ' LIKE "' . $needle . '%" AND
					       user.user_id<>"' . $user_anonymous . '"' . $cond_user_id . $order_clause;
                }
            }
        }
        $rs = Database::query($sql);
        $i = 0;
        if ($type == 'single') {
            while ($user = Database::fetch_array($rs)) {
                $i++;
                if ($i <= 10) {
                    $person_name = api_get_person_name($user['firstname'], $user['lastname']);
                    $return .= '<a href="javascript: void(0);" onclick="javascript: add_user(\'' . $user['user_id'] . '\',\'' . $person_name . ' (' . $user['username'] . ')' . '\')">' . $person_name . ' (' . $user['username'] . ')</a><br />';
                } else {
                    $return .= '...<br />';
                }
            }
            $xajax_response->addAssign('ajax_list_users_single', 'innerHTML', api_utf8_encode($return));
        } else {
            global $nosessionUsersList;
            $return .= '<select id="origin_users" name="nosessionUsersList[]" multiple="multiple" size="15" style="width:360px;">';
            while ($user = Database::fetch_array($rs)) {
                $person_name = api_get_person_name($user['firstname'], $user['lastname']);
                $return .= '<option value="' . $user['user_id'] . '">' . $person_name . ' (' . $user['username'] . ')</option>';
            }
            $return .= '</select>';
            $xajax_response->addAssign('ajax_list_users_multiple', 'innerHTML', api_utf8_encode($return));
        }
    }
    return $xajax_response;
}