function search_sessions($needle, $type)
{
    global $tbl_session_rel_access_url, $tbl_session, $user_id;
    $xajax_response = new xajaxResponse();
    $return = '';
    if (!empty($needle) && !empty($type)) {
        $needle = Database::escape_string($needle);
        $assigned_sessions_to_hrm = SessionManager::get_sessions_followed_by_drh($user_id);
        $assigned_sessions_id = array_keys($assigned_sessions_to_hrm);
        $without_assigned_sessions = '';
        if (count($assigned_sessions_id) > 0) {
            $without_assigned_sessions = " AND s.id NOT IN(" . implode(',', $assigned_sessions_id) . ")";
        }
        if (api_is_multiple_url_enabled()) {
            $sql = " SELECT s.id, s.name FROM {$tbl_session} s\n                        LEFT JOIN {$tbl_session_rel_access_url} a ON (s.id = a.session_id)\n                        WHERE  s.name LIKE '{$needle}%' {$without_assigned_sessions} AND access_url_id = " . api_get_current_access_url_id() . "";
        } else {
            $sql = "SELECT s.id, s.name FROM {$tbl_session} s\n                    WHERE  s.name LIKE '{$needle}%' {$without_assigned_sessions} ";
        }
        $rs = Database::query($sql);
        $return .= '<select class="form-control" id="origin" name="NoAssignedSessionsList[]" multiple="multiple" size="20">';
        while ($session = Database::fetch_array($rs)) {
            $return .= '<option value="' . $session['id'] . '" title="' . htmlspecialchars($session['name'], ENT_QUOTES) . '">' . $session['name'] . '</option>';
        }
        $return .= '</select>';
        $xajax_response->addAssign('ajax_list_sessions_multiple', 'innerHTML', api_utf8_encode($return));
    }
    return $xajax_response;
}
function search_sessions($needle, $type)
{
    global $_configuration, $tbl_session_rel_access_url, $tbl_session, $user_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 = api_convert_encoding($needle, $charset, 'utf-8');
        $assigned_sessions_to_hrm = SessionManager::get_sessions_followed_by_drh($user_id);
        $assigned_sessions_id = array_keys($assigned_sessions_to_hrm);
        $without_assigned_sessions = '';
        if (count($assigned_sessions_id) > 0) {
            $without_assigned_sessions = " AND s.id NOT IN(" . implode(',', $assigned_sessions_id) . ")";
        }
        if ($_configuration['multiple_access_urls']) {
            $sql = " SELECT s.id, s.name FROM {$tbl_session} s LEFT JOIN {$tbl_session_rel_access_url} a ON (s.id = a.session_id)\n\t\t\t\t\t\tWHERE  s.name LIKE '{$needle}%' {$without_assigned_sessions} AND access_url_id = " . api_get_current_access_url_id() . "";
        } else {
            $sql = "SELECT s.id, s.name FROM {$tbl_session} s\n\t\t\t\tWHERE  s.name LIKE '{$needle}%' {$without_assigned_sessions} ";
        }
        $rs = Database::query($sql);
        $return .= '<select id="origin" name="NoAssignedSessionsList[]" multiple="multiple" size="20" style="width:340px;">';
        while ($session = Database::fetch_array($rs)) {
            $return .= '<option value="' . $session['id'] . '" title="' . htmlspecialchars($session['name'], ENT_QUOTES) . '">' . $session['name'] . '</option>';
        }
        $return .= '</select>';
        $xajax_response->addAssign('ajax_list_sessions_multiple', 'innerHTML', api_utf8_encode($return));
    }
    return $xajax_response;
}
Beispiel #3
0
function LoginCheck($uid)
{
    $_course = api_get_course_info();
    $uid = (int) $uid;
    $online_table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ONLINE);
    if (!empty($uid)) {
        $user_ip = '';
        if (!empty($_SERVER['REMOTE_ADDR'])) {
            $user_ip = Database::escape_string(api_get_real_ip());
        }
        $login_date = api_get_utc_datetime();
        $access_url_id = 1;
        if (api_get_multiple_access_url() && api_get_current_access_url_id() != -1) {
            $access_url_id = api_get_current_access_url_id();
        }
        $session_id = api_get_session_id();
        // if the $_course array exists this means we are in a course and we have to store this in the who's online table also
        // to have the x users in this course feature working
        if (is_array($_course) && count($_course) > 0 && !empty($_course['id'])) {
            $query = "REPLACE INTO " . $online_table . " (login_id,login_user_id,login_date,user_ip, c_id, session_id, access_url_id)\n                      VALUES ({$uid},{$uid},'{$login_date}','{$user_ip}', '" . $_course['real_id'] . "' , '{$session_id}' , '{$access_url_id}' )";
        } else {
            $query = "REPLACE INTO " . $online_table . " (login_id,login_user_id,login_date,user_ip, c_id, session_id, access_url_id)\n                      VALUES ({$uid},{$uid},'{$login_date}','{$user_ip}', 0, '{$session_id}', '{$access_url_id}')";
        }
        Database::query($query);
    }
}
function search_courses($needle, $type)
{
    global $tbl_course, $tbl_course_rel_access_url, $user_id;
    $xajax_response = new xajaxResponse();
    $return = '';
    if (!empty($needle) && !empty($type)) {
        // xajax send utf8 datas... datas in db can be non-utf8 datas
        $needle = Database::escape_string($needle);
        $assigned_courses_to_hrm = CourseManager::get_courses_followed_by_drh($user_id);
        $assigned_courses_code = array_keys($assigned_courses_to_hrm);
        foreach ($assigned_courses_code as &$value) {
            $value = "'" . $value . "'";
        }
        $without_assigned_courses = '';
        if (count($assigned_courses_code) > 0) {
            $without_assigned_courses = " AND c.code NOT IN(" . implode(',', $assigned_courses_code) . ")";
        }
        if (api_is_multiple_url_enabled()) {
            $sql = "SELECT c.code, c.title\n                    FROM {$tbl_course} c\n\t\t\t\t\tLEFT JOIN {$tbl_course_rel_access_url} a\n                    ON (a.c_id = c.id)\n                \tWHERE\n                \t\tc.code LIKE '{$needle}%' {$without_assigned_courses} AND\n                \t\taccess_url_id = " . api_get_current_access_url_id();
        } else {
            $sql = "SELECT c.code, c.title\n            \t\tFROM {$tbl_course} c\n                \tWHERE\n                \t\tc.code LIKE '{$needle}%'\n                \t\t{$without_assigned_courses} ";
        }
        $rs = Database::query($sql);
        $return .= '<select id="origin" name="NoAssignedCoursesList[]" multiple="multiple" size="20" style="width:340px;">';
        while ($course = Database::fetch_array($rs)) {
            $return .= '<option value="' . $course['code'] . '" title="' . htmlspecialchars($course['title'], ENT_QUOTES) . '">' . $course['title'] . ' (' . $course['code'] . ')</option>';
        }
        $return .= '</select>';
        $xajax_response->addAssign('ajax_list_courses_multiple', 'innerHTML', api_utf8_encode($return));
    }
    return $xajax_response;
}
 /**
  * Returns users whose last login is prior from $ceiling
  *
  * @param int|string $ceiling last login date
  * @param bool $active_only if true returns only active users. Otherwise returns all users.
  * @return ResultSet
  */
 static function list_zombies($ceiling, $active_only = true)
 {
     $ceiling = is_numeric($ceiling) ? (int) $ceiling : strtotime($ceiling);
     $ceiling = date('Y-m-d H:i:s', $ceiling);
     $user_table = Database::get_main_table(TABLE_MAIN_USER);
     $login_table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN);
     $sql = 'SELECT
                 user.user_id,
                 user.firstname,
                 user.lastname,
                 user.username,
                 user.auth_source,
                 user.email,
                 user.status,
                 user.registration_date,
                 user.active,
                 access.login_date';
     global $_configuration;
     if ($_configuration['multiple_access_urls']) {
         $access_url_rel_user_table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
         $current_url_id = api_get_current_access_url_id();
         $sql .= " FROM {$user_table} as user, {$login_table} as access, {$access_url_rel_user_table} as url\n                      WHERE\n                        access.login_date = (SELECT MAX(a.login_date)\n                                             FROM {$login_table} as a\n                                             WHERE a.login_user_id = user.user_id\n                                             ) AND\n                        access.login_date <= '{$ceiling}' AND\n                        user.user_id = access.login_user_id AND\n                        url.login_user_id = user.user_id AND url.access_url_id={$current_url_id}";
     } else {
         $sql .= " FROM {$user_table} as user, {$login_table} as access\n                      WHERE\n                        access.login_date = (SELECT MAX(a.login_date)\n                                             FROM {$login_table} as a\n                                             WHERE a.login_user_id = user.user_id\n                                             ) AND\n                        access.login_date <= '{$ceiling}' AND\n                        user.user_id = access.login_user_id";
     }
     if ($active_only) {
         $sql .= ' AND user.active = 1';
     }
     return ResultSet::create($sql);
 }
function search_users($needle, $type)
{
    global $_configuration, $tbl_access_url_rel_user, $tbl_user, $user_anonymous, $current_user_id, $user_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 = api_convert_encoding($needle, $charset, 'utf-8');
        $assigned_users_to_hrm = UserManager::get_users_followed_by_drh($user_id);
        $assigned_users_id = array_keys($assigned_users_to_hrm);
        $without_assigned_users = '';
        if (count($assigned_users_id) > 0) {
            $without_assigned_users = " AND user.user_id NOT IN(" . implode(',', $assigned_users_id) . ")";
        }
        if ($_configuration['multiple_access_urls']) {
            $sql = "SELECT user.user_id, username, lastname, firstname FROM {$tbl_user} user LEFT JOIN {$tbl_access_url_rel_user} au ON (au.user_id = user.user_id)\n\t\t\tWHERE  " . (api_sort_by_first_name() ? 'firstname' : 'lastname') . " LIKE '{$needle}%' AND status NOT IN(" . DRH . ", " . SESSIONADMIN . ") AND user.user_id NOT IN ({$user_anonymous}, {$current_user_id}, {$user_id}) {$without_assigned_users} AND access_url_id = " . api_get_current_access_url_id() . "";
        } else {
            $sql = "SELECT user_id, username, lastname, firstname FROM {$tbl_user} user\n\t\t\tWHERE  " . (api_sort_by_first_name() ? 'firstname' : 'lastname') . " LIKE '{$needle}%' AND status NOT IN(" . DRH . ", " . SESSIONADMIN . ") AND user_id NOT IN ({$user_anonymous}, {$current_user_id}, {$user_id}) {$without_assigned_users}";
        }
        $rs = Database::query($sql);
        $return .= '<select id="origin" name="NoAssignedUsersList[]" multiple="multiple" size="20" style="width:340px;">';
        while ($user = Database::fetch_array($rs)) {
            $person_name = api_get_person_name($user['firstname'], $user['lastname']);
            $return .= '<option value="' . $user['user_id'] . '" title="' . htmlspecialchars($person_name, ENT_QUOTES) . '">' . $person_name . ' (' . $user['username'] . ')</option>';
        }
        $return .= '</select>';
        $xajax_response->addAssign('ajax_list_users_multiple', 'innerHTML', api_utf8_encode($return));
    }
    return $xajax_response;
}
Beispiel #7
0
 /**
  * Room constructor.
  */
 public function __construct()
 {
     $this->table = \Database::get_main_table('plugin_openmeetings');
     $this->name = 'C' . api_get_real_course_id() . '-' . api_get_session_id();
     $accessUrl = api_get_access_url(api_get_current_access_url_id());
     $this->externalRoomType = substr($accessUrl['url'], strpos($accessUrl['url'], '://') + 3, -1);
     if (strcmp($this->externalRoomType, 'localhost') == 0) {
         $this->externalRoomType = substr(api_get_path(WEB_PATH), strpos(api_get_path(WEB_PATH), '://') + 3, -1);
     }
     $this->externalRoomType = 'chamilolms.' . $this->externalRoomType;
 }
/**
 * Get course data to display
 * @param int $from
 * @param int $number_of_items
 * @param int $column
 * @param string $direction
 *
 * @return array
 */
function get_course_data($from, $number_of_items, $column, $direction)
{
    $course_table = Database::get_main_table(TABLE_MAIN_COURSE);
    $sql = "SELECT  code AS col0,\n                    title AS col1,\n                    code AS col2,\n                    course_language AS col3,\n                    category_code AS col4,\n                    subscribe AS col5,\n                    unsubscribe AS col6,\n                    code AS col7,\n                    visibility AS col8,\n                    directory as col9,\n                    visual_code\n    \t\tFROM {$course_table}";
    if ((api_is_platform_admin() || api_is_session_admin()) && api_is_multiple_url_enabled() && api_get_current_access_url_id() != -1) {
        $access_url_rel_course_table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
        $sql .= " INNER JOIN {$access_url_rel_course_table} url_rel_course ON (id = url_rel_course.c_id)";
    }
    if (isset($_GET['keyword'])) {
        $keyword = Database::escape_string("%" . trim($_GET['keyword']) . "%");
        $sql .= " WHERE (\n            title LIKE '" . $keyword . "' OR\n            code LIKE '" . $keyword . "' OR\n            visual_code LIKE '" . $keyword . "'\n        )\n        ";
    } elseif (isset($_GET['keyword_code'])) {
        $keyword_code = Database::escape_string("%" . $_GET['keyword_code'] . "%");
        $keyword_title = Database::escape_string("%" . $_GET['keyword_title'] . "%");
        $keyword_category = Database::escape_string("%" . $_GET['keyword_category'] . "%");
        $keyword_language = Database::escape_string("%" . $_GET['keyword_language'] . "%");
        $keyword_visibility = Database::escape_string("%" . $_GET['keyword_visibility'] . "%");
        $keyword_subscribe = Database::escape_string($_GET['keyword_subscribe']);
        $keyword_unsubscribe = Database::escape_string($_GET['keyword_unsubscribe']);
        $sql .= " WHERE\n                (code LIKE '" . $keyword_code . "' OR visual_code LIKE '" . $keyword_code . "') AND\n                title LIKE '" . $keyword_title . "' AND\n                category_code LIKE '" . $keyword_category . "' AND\n                course_language LIKE '" . $keyword_language . "' AND\n                visibility LIKE '" . $keyword_visibility . "' AND\n                subscribe LIKE '" . $keyword_subscribe . "' AND\n                unsubscribe LIKE '" . $keyword_unsubscribe . "'";
    }
    // Adding the filter to see the user's only of the current access_url.
    if ((api_is_platform_admin() || api_is_session_admin()) && api_is_multiple_url_enabled() && api_get_current_access_url_id() != -1) {
        $sql .= " AND url_rel_course.access_url_id=" . api_get_current_access_url_id();
    }
    $sql .= " ORDER BY col{$column} {$direction} ";
    $sql .= " LIMIT {$from}, {$number_of_items}";
    $res = Database::query($sql);
    $courses = array();
    $languages = api_get_languages_to_array();
    while ($course = Database::fetch_array($res)) {
        // Place colour icons in front of courses.
        $show_visual_code = $course['visual_code'] != $course[2] ? Display::label($course['visual_code'], 'info') : null;
        $course[1] = get_course_visibility_icon($course[8]) . '<a href="' . api_get_path(WEB_COURSE_PATH) . $course[9] . '/index.php">' . $course[1] . '</a> ' . $show_visual_code;
        $course[5] = $course[5] == SUBSCRIBE_ALLOWED ? get_lang('Yes') : get_lang('No');
        $course[6] = $course[6] == UNSUBSCRIBE_ALLOWED ? get_lang('Yes') : get_lang('No');
        $language = isset($languages[$course[3]]) ? $languages[$course[3]] : $course[3];
        $course_rem = array($course[0], $course[1], $course[2], $language, $course[4], $course[5], $course[6], $course[7]);
        $courses[] = $course_rem;
    }
    return $courses;
}
function search_coachs($needle)
{
    $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
    $xajax_response = new xajaxResponse();
    $return = '';
    if (!empty($needle)) {
        $order_clause = api_sort_by_first_name() ? ' ORDER BY firstname, lastname, username' : ' ORDER BY lastname, firstname, username';
        // search users where username or firstname or lastname begins likes $needle
        $sql = 'SELECT username, lastname, firstname
		        FROM ' . $tbl_user . ' user
				WHERE (username LIKE "' . $needle . '%"
				OR firstname LIKE "' . $needle . '%"
				OR lastname LIKE "' . $needle . '%")
				AND status=1' . $order_clause . ' LIMIT 10';
        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) {
                $sql = 'SELECT 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 status=1' . $order_clause . '
                        LIMIT 10';
            }
        }
        $rs = Database::query($sql);
        while ($user = Database::fetch_array($rs)) {
            $return .= '<a href="javascript: void(0);" onclick="javascript: fill_coach_field(\'' . $user['username'] . '\')">' . api_get_person_name($user['firstname'], $user['lastname']) . ' (' . $user['username'] . ')</a><br />';
        }
    }
    $xajax_response->addAssign('ajax_list_coachs', 'innerHTML', api_utf8_encode($return));
    return $xajax_response;
}
 /**
  * Constructor (generates a connection to the API and the Chamilo settings
  * required for the connection to the video conference server)
  */
 public function __construct()
 {
     // initialize video server settings from global settings
     $plugin = \OpenMeetingsPlugin::create();
     $om_plugin = $plugin->get('tool_enable');
     $om_host = $plugin->get('host');
     $om_user = $plugin->get('user');
     $om_pass = $plugin->get('pass');
     $accessUrl = api_get_access_url(api_get_current_access_url_id());
     $this->externalType = substr($accessUrl['url'], strpos($accessUrl['url'], '://') + 3, -1);
     if (strcmp($this->externalType, 'localhost') == 0) {
         $this->externalType = substr(api_get_path(WEB_PATH), strpos(api_get_path(WEB_PATH), '://') + 3, -1);
     }
     $this->externalType = 'chamilolms.' . $this->externalType;
     $this->table = \Database::get_main_table('plugin_openmeetings');
     if ($om_plugin) {
         $user_info = api_get_user_info();
         $this->user_complete_name = $user_info['complete_name'];
         $this->user = $om_user;
         $this->pass = $om_pass;
         $this->url = $om_host;
         // Setting OM api
         define('CONFIG_OPENMEETINGS_USER', $this->user);
         define('CONFIG_OPENMEETINGS_PASS', $this->pass);
         define('CONFIG_OPENMEETINGS_SERVER_URL', $this->url);
         $this->gateway = new \OpenMeetingsGateway($this->url, $this->user, $this->pass);
         $this->plugin_enabled = $om_plugin;
         // The room has a name composed of C + course ID + '-' + session ID
         $this->chamiloCourseId = api_get_course_int_id();
         $this->chamiloSessionId = api_get_session_id();
         $this->roomName = 'C' . $this->chamiloCourseId . '-' . $this->chamiloSessionId;
         $return = $this->gateway->loginUser();
         if ($return == 0) {
             $msg = 'Could not initiate session with server through OpenMeetingsGateway::loginUser()';
             error_log(__FILE__ . '+' . __LINE__ . ': ' . $msg);
             die($msg);
         }
         $this->sessionId = $this->gateway->sessionId;
     }
 }
Beispiel #11
0
function get_settings($category = null)
{
    $url_id = api_get_current_access_url_id();
    $settings_by_access_list = array();
    if ($url_id == 1) {
        $settings = api_get_settings($category, 'group', $url_id);
    } else {
        $url_info = api_get_access_url($url_id);
        if ($url_info['active'] == 1) {
            // The default settings of Chamilo
            $settings = api_get_settings($category, 'group', 1, 0);
            // The settings that are changeable from a particular site.
            $settings_by_access = api_get_settings($category, 'group', $url_id, 1);
            foreach ($settings_by_access as $row) {
                if (empty($row['variable'])) {
                    $row['variable'] = 0;
                }
                if (empty($row['subkey'])) {
                    $row['subkey'] = 0;
                }
                if (empty($row['category'])) {
                    $row['category'] = 0;
                }
                // One more validation if is changeable.
                if ($row['access_url_changeable'] == 1) {
                    $settings_by_access_list[$row['variable']][$row['subkey']][$row['category']] = $row;
                } else {
                    $settings_by_access_list[$row['variable']][$row['subkey']][$row['category']] = array();
                }
            }
        }
    }
    if (isset($category) && $category == 'search_setting') {
        if (!empty($_REQUEST['search_field'])) {
            $settings = search_setting($_REQUEST['search_field']);
        }
    }
    return array('settings' => $settings, 'settings_by_access_list' => $settings_by_access_list);
}
    function display_default()
    {
        $message = get_lang('RemoveOldDatabaseMessage');
        $message_table = get_lang('RemoveOldTables');
        $message_table .= "<br />" . implode(' , ', self::get_tables_to_delete());
        $token = Security::get_token();
        $url = $this->url(array(self::PARAM_ACTION => 'drop_old_databases', self::PARAM_SECURITY_TOKEN => $token));
        $url_table = $this->url(array(self::PARAM_ACTION => 'drop_old_tables', self::PARAM_SECURITY_TOKEN => $token));
        $go = get_lang('Go');
        $access_url_id = api_get_current_access_url_id();
        $message2 = '';
        if ($access_url_id === 1) {
            if (api_is_windows_os()) {
                $message2 .= get_lang('SpaceUsedOnSystemCannotBeMeasuredOnWindows');
            } else {
                $dir = api_get_path(SYS_PATH);
                $du = exec('du -sh ' . $dir, $err);
                list($size, $none) = explode("\t", $du);
                $limit = $_configuration[$url]['hosting_limit_disk_space'];
                $message2 .= sprintf(get_lang('TotalSpaceUsedByPortalXLimitIsYMB'), $size, $limit);
            }
        }
        if (!empty($message2)) {
            $message2 = '<li>' . $message2 . '</li>';
        }
        echo <<<EOT
        <ul>
        <li>
            <div>{$message}</div>        
            <a class="btn" href={$url}>{$go}</a>
        </li>
        <li>
            <div>{$message_table}</div>        
            <a class="btn" href={$url_table}>{$go}</a>
        </li>
        {$message2}
        </ul>
EOT;
    }
 /**
  * Returns users whose last login is prior from $ceiling
  *
  * @param int|string $ceiling last login date
  * @param bool $active_only if true returns only active users. Otherwise returns all users.
  * @return ResultSet
  */
 static function listZombies($ceiling, $active_only = true, $count = 0, $from = 10, $column = 'user.firstname', $direction = 'desc')
 {
     if (empty($column)) {
         $column = 'user.firstname';
     }
     $ceiling = is_numeric($ceiling) ? (int) $ceiling : strtotime($ceiling);
     $ceiling = date('Y-m-d H:i:s', $ceiling);
     $user_table = Database::get_main_table(TABLE_MAIN_USER);
     $login_table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN);
     $sql = 'SELECT
                 user.user_id,
                 user.firstname,
                 user.lastname,
                 user.username,
                 user.auth_source,
                 user.email,
                 user.status,
                 user.registration_date,
                 user.active,
                 access.login_date';
     if (api_is_multiple_url_enabled()) {
         $access_url_rel_user_table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
         $current_url_id = api_get_current_access_url_id();
         $sql .= " FROM {$user_table} as user, {$login_table} as access, {$access_url_rel_user_table} as url\n                      WHERE\n                        access.login_date = (SELECT MAX(a.login_date)\n                                             FROM {$login_table} as a\n                                             WHERE a.login_user_id = user.user_id\n                                             ) AND\n                        access.login_date <= '{$ceiling}' AND\n                        user.user_id = access.login_user_id AND\n                        url.user_id = user.user_id AND url.access_url_id={$current_url_id}";
     } else {
         $sql .= " FROM {$user_table} as user, {$login_table} as access\n                      WHERE\n                        access.login_date = (SELECT MAX(a.login_date)\n                                             FROM {$login_table} as a\n                                             WHERE a.login_user_id = user.user_id\n                                             ) AND\n                        access.login_date <= '{$ceiling}' AND\n                        user.user_id = access.login_user_id";
     }
     if ($active_only) {
         $sql .= ' AND user.active = 1';
     }
     $count = intval($count);
     $from = intval($from);
     $sql .= " ORDER BY {$column} {$direction}";
     $sql .= " LIMIT {$count}, {$from} ";
     $result = Database::query($sql);
     return Database::store_result($result, 'ASSOC');
 }
function search_users($needle, $type)
{
    global $tbl_user, $tbl_session_rel_user, $id_session;
    $xajax_response = new XajaxResponse();
    $return = '';
    if (!empty($needle) && !empty($type)) {
        //normal behaviour
        if ($type == 'any_session' && $needle == 'false') {
            $type = 'multiple';
            $needle = '';
        }
        // 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');
        $order_clause = api_sort_by_first_name() ? ' ORDER BY firstname, lastname, username' : ' ORDER BY lastname, firstname, username';
        $cond_user_id = '';
        //Only for single & multiple
        if (in_array($type, array('single', 'multiple'))) {
            if (!empty($id_session)) {
                $id_session = intval($id_session);
                // check id_user from session_rel_user table
                $sql = 'SELECT id_user FROM ' . $tbl_session_rel_user . '
                    WHERE id_session ="' . $id_session . '" AND relation_type<>' . SESSION_RELATION_TYPE_RRHH . ' ';
                $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.user_id NOT IN(' . implode(",", $user_ids) . ')';
                }
            }
        }
        switch ($type) {
            case 'single':
                // search users where username or firstname or lastname begins likes $needle
                $sql = 'SELECT user.user_id, username, lastname, firstname, official_code
                        FROM ' . $tbl_user . ' user
                        WHERE (username LIKE "' . $needle . '%" OR firstname LIKE "' . $needle . '%"
                            OR lastname LIKE "' . $needle . '%") AND user.status<>6 AND user.status<>' . DRH . '' . $order_clause . ' LIMIT 11';
                break;
            case 'multiple':
                $sql = 'SELECT user.user_id, username, lastname, firstname, official_code
                        FROM ' . $tbl_user . ' user
                        WHERE ' . (api_sort_by_first_name() ? 'firstname' : 'lastname') . ' LIKE "' . $needle . '%" AND user.status<>' . DRH . ' AND user.status<>6 ' . $cond_user_id . $order_clause;
                break;
            case 'any_session':
                $sql = 'SELECT DISTINCT user.user_id, username, lastname, firstname, official_code
                        FROM ' . $tbl_user . ' user
                        LEFT OUTER JOIN ' . $tbl_session_rel_user . ' s ON (s.id_user = user.user_id)
                        WHERE   s.id_user IS null AND user.status<>' . DRH . ' AND
                                user.status<>6 ' . $cond_user_id . $order_clause;
                break;
        }
        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) {
                switch ($type) {
                    case 'single':
                        $sql = 'SELECT user.user_id, username, lastname, firstname, official_code
                        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.status<>6 AND user.status<>' . DRH . ' ' . $order_clause . ' LIMIT 11';
                        break;
                    case 'multiple':
                        $sql = 'SELECT user.user_id, username, lastname, firstname , official_code
                        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.status<>' . DRH . ' AND
                                user.status<>6 ' . $cond_user_id . $order_clause;
                        break;
                    case 'any_session':
                        $sql = 'SELECT DISTINCT user.user_id, username, lastname, firstname, official_code
                            FROM ' . $tbl_user . ' user
                            LEFT OUTER JOIN ' . $tbl_session_rel_user . ' s ON (s.id_user = user.user_id)
                            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
                                s.id_user IS null AND
                                user.status<>' . DRH . ' AND
                                user.status<>6 ' . $cond_user_id . $order_clause;
                        break;
                }
            }
        }
        $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']) . ' (' . $user['username'] . ') ' . $user['official_code'];
                    $return .= '<a href="javascript: void(0);" onclick="javascript: add_user_to_session(\'' . $user['user_id'] . '\',\'' . $person_name . ' ' . '\')">' . $person_name . ' </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']) . ' (' . $user['username'] . ') ' . $user['official_code'];
                $return .= '<option value="' . $user['user_id'] . '">' . $person_name . ' </option>';
            }
            $return .= '</select>';
            $xajax_response->addAssign('ajax_list_users_multiple', 'innerHTML', api_utf8_encode($return));
        }
    }
    return $xajax_response;
}
    $filterData = $searchForm->getSubmitValues();
}
$conditions = array();
if (!empty($filters) && !empty($filterData)) {
    foreach ($filters as $filter) {
        if (isset($filter['name']) && isset($filterData[$filter['name']])) {
            $value = $filterData[$filter['name']];
            if (!empty($value)) {
                $conditions[$filter['name']] = $value;
            }
        }
    }
}
$data = $usergroup->get($id);
$course_list_in = $usergroup->get_courses_by_usergroup($id, true);
$course_list = CourseManager::get_courses_list(0, 0, 'title', 'asc', -1, null, api_get_current_access_url_id(), false, $conditions);
$elements_not_in = $elements_in = array();
foreach ($course_list_in as $course) {
    $elements_in[$course['id']] = $course['title'] . " (" . $course['visual_code'] . ")";
}
if (!empty($course_list)) {
    foreach ($course_list as $item) {
        $elements_not_in[$item['id']] = $item['title'] . " (" . $item['visual_code'] . ")";
    }
}
$ajax_search = $add_type == 'unique' ? true : false;
//checking for extra field with filter on
function search($needle, $type)
{
    global $elements_in;
    $xajax_response = new xajaxResponse();
 public static function who_is_online_count($time_limit = null, $friends = false)
 {
     if (empty($time_limit)) {
         $time_limit = api_get_setting('time_limit_whosonline');
     } else {
         $time_limit = intval($time_limit);
     }
     $track_online_table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ONLINE);
     $friend_user_table = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
     $table_user = Database::get_main_table(TABLE_MAIN_USER);
     $query = '';
     $online_time = time() - $time_limit * 60;
     $current_date = api_get_utc_datetime($online_time);
     if ($friends) {
         // 	who friends from social network is online
         $query = "SELECT DISTINCT count(login_user_id) as count\n                      FROM {$track_online_table} INNER JOIN {$friend_user_table} ON (friend_user_id = login_user_id)\n                      WHERE login_date >= '{$current_date}' AND friend_user_id <> '" . api_get_user_id() . "' AND relation_type='" . USER_RELATION_TYPE_FRIEND . "' AND user_id = '" . api_get_user_id() . "' ";
     } else {
         // All users online
         $query = "SELECT count(login_id) as count\n                      FROM {$track_online_table} track INNER JOIN {$table_user} u ON (u.user_id=track.login_user_id)\n                      WHERE u.status != " . ANONYMOUS . " AND login_date >= '{$current_date}'  ";
     }
     if (api_get_multiple_access_url()) {
         $access_url_id = api_get_current_access_url_id();
         if ($access_url_id != -1) {
             if ($friends) {
                 // 	friends from social network is online
                 $query = "SELECT DISTINCT count(login_user_id) as count\n                                FROM {$track_online_table} track\n                                INNER JOIN {$friend_user_table} ON (friend_user_id = login_user_id)\n                                WHERE track.access_url_id = {$access_url_id} AND login_date >= '" . $current_date . "' AND friend_user_id <> '" . api_get_user_id() . "' AND relation_type='" . USER_RELATION_TYPE_FRIEND . "'  ";
             } else {
                 // all users online
                 $query = "SELECT count(login_id) as count FROM {$track_online_table} track\n                              INNER JOIN {$table_user} u ON (u.user_id=track.login_user_id)\n                              WHERE u.status != " . ANONYMOUS . " AND track.access_url_id =  {$access_url_id} AND login_date >= '{$current_date}' ";
             }
         }
     }
     //Dev purposes show all users online
     /*$table_user = Database::get_main_table(TABLE_MAIN_USER);
       $query = "SELECT count(*)  as count FROM ".$table_user ."   ";*/
     $result = Database::query($query);
     if (Database::num_rows($result) > 0) {
         $row = Database::fetch_array($result);
         return $row['count'];
     } else {
         return false;
     }
 }
function search_users($needle, $type)
{
    global $tbl_access_url_rel_user, $tbl_user, $user_anonymous, $current_user_id, $user_id, $userStatus;
    $xajax_response = new xajaxResponse();
    $return = '';
    if (!empty($needle) && !empty($type)) {
        $assigned_users_to_hrm = array();
        switch ($userStatus) {
            case DRH:
                //no break;
            //no break;
            case PLATFORM_ADMIN:
                $assigned_users_to_hrm = UserManager::get_users_followed_by_drh($user_id);
                break;
            case STUDENT_BOSS:
                $assigned_users_to_hrm = UserManager::getUsersFollowedByStudentBoss($user_id);
                break;
        }
        $assigned_users_id = array_keys($assigned_users_to_hrm);
        $without_assigned_users = '';
        $westernOrder = api_is_western_name_order();
        if ($westernOrder) {
            $order_clause = " ORDER BY firstname, lastname";
        } else {
            $order_clause = " ORDER BY lastname, firstname";
        }
        if (count($assigned_users_id) > 0) {
            $without_assigned_users = " AND user.user_id NOT IN(" . implode(',', $assigned_users_id) . ")";
        }
        if (api_is_multiple_url_enabled()) {
            $sql = "SELECT user.user_id, username, lastname, firstname\n                    FROM {$tbl_user} user\n                    LEFT JOIN {$tbl_access_url_rel_user} au ON (au.user_id = user.user_id)\n                    WHERE\n                        " . (api_sort_by_first_name() ? 'firstname' : 'lastname') . " LIKE '{$needle}%' AND\n                        status NOT IN(" . DRH . ", " . SESSIONADMIN . ", " . STUDENT_BOSS . ") AND\n                        user.user_id NOT IN ({$user_anonymous}, {$current_user_id}, {$user_id})\n                        {$without_assigned_users} AND\n                        access_url_id = " . api_get_current_access_url_id() . "\n                    {$order_clause}\n                    ";
        } else {
            $sql = "SELECT user_id, username, lastname, firstname\n                    FROM {$tbl_user} user\n                    WHERE\n                        " . (api_sort_by_first_name() ? 'firstname' : 'lastname') . " LIKE '{$needle}%' AND\n                        status NOT IN(" . DRH . ", " . SESSIONADMIN . ", " . STUDENT_BOSS . ") AND\n                        user_id NOT IN ({$user_anonymous}, {$current_user_id}, {$user_id})\n                    {$without_assigned_users}\n                    {$order_clause}\n            ";
        }
        $rs = Database::query($sql);
        $xajax_response->addAssign('ajax_list_users_multiple', 'innerHTML', api_utf8_encode($return));
        if ($type == 'single') {
            $tbl_user_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
            $access_url_id = api_get_current_access_url_id();
            $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 ';
            switch ($userStatus) {
                case DRH:
                    $sql .= " user.status <> 6 AND user.status <> " . DRH;
                    break;
                case STUDENT_BOSS:
                    $sql .= " user.status <> 6 AND user.status <> " . STUDENT_BOSS;
                    break;
            }
            $sql .= " {$order_clause} LIMIT 11";
            $rs = Database::query($sql);
            $i = 0;
            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_to_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 {
            $return .= '<select id="origin" class="form-control" name="NoAssignedUsersList[]" multiple="multiple" size="15" ">';
            while ($user = Database::fetch_array($rs)) {
                $person_name = api_get_person_name($user['firstname'], $user['lastname']);
                $return .= '<option value="' . $user['user_id'] . '" title="' . htmlspecialchars($person_name, ENT_QUOTES) . '">' . $person_name . ' (' . $user['username'] . ')</option>';
            }
            $return .= '</select>';
            $xajax_response->addAssign('ajax_list_users_multiple', 'innerHTML', api_utf8_encode($return));
        }
    }
    return $xajax_response;
}
            $form->setDefaults($categoryInfo);
            $form->addButtonSave($text);
        } else {
            $class = "add";
            $text = get_lang('AddCategory');
            $form->setDefaults(array('auth_course_child' => 'TRUE'));
            $form->addButtonCreate($text);
        }
        $form->display();
    } elseif (api_get_multiple_access_url() && api_get_current_access_url_id() != 1) {
        // If multiple URLs and not main URL, prevent edition and inform user
        Display::display_warning_message(get_lang('CourseCategoriesAreGlobal'));
    }
} else {
    // If multiple URLs and not main URL, prevent deletion and inform user
    if ($action == 'delete' && api_get_multiple_access_url() && api_get_current_access_url_id() != 1) {
        Display::display_warning_message(get_lang('CourseCategoriesAreGlobal'));
    }
    echo '<div class="actions">';
    $link = null;
    if (!empty($parentInfo)) {
        $parentCode = $parentInfo['parent_id'];
        echo Display::url(Display::return_icon('back.png', get_lang("Back"), '', ICON_SIZE_MEDIUM), api_get_path(WEB_CODE_PATH) . 'admin/course_category.php?category=' . $parentCode);
    }
    if (empty($parentInfo) || $parentInfo['auth_cat_child'] == 'TRUE') {
        echo Display::url(Display::return_icon('new_folder.png', get_lang("AddACategory"), '', ICON_SIZE_MEDIUM), api_get_path(WEB_CODE_PATH) . 'admin/course_category.php?action=add&category=' . Security::remove_XSS($category));
    }
    echo '</div>';
    if (!empty($parentInfo)) {
        echo Display::page_subheader($parentInfo['name'] . ' (' . $parentInfo['code'] . ')');
    }
 /**
  * Get the HTML code for an announcement
  * @param int $announcementId The announcement ID
  * @param int $visibility The announcement visibility
  * @return string The HTML code
  */
 public static function displayAnnouncement($announcementId, $visibility)
 {
     $selectedUserLanguage = Database::escape_string(api_get_interface_language());
     $announcementTable = Database::get_main_table(TABLE_MAIN_SYSTEM_ANNOUNCEMENTS);
     $now = api_get_utc_datetime();
     $whereConditions = ["(lang = ? OR lang IS NULL) " => $selectedUserLanguage, "AND (? >= date_start AND ? <= date_end) " => [$now, $now], "AND id = ? " => intval($announcementId)];
     switch ($visibility) {
         case self::VISIBLE_GUEST:
             $whereConditions["AND visible_guest = ? "] = 1;
             break;
         case self::VISIBLE_STUDENT:
             $whereConditions["AND visible_student = ? "] = 1;
             break;
         case self::VISIBLE_TEACHER:
             $whereConditions["AND visible_teacher = ? "] = 1;
             break;
     }
     if (api_is_multiple_url_enabled()) {
         $whereConditions["AND access_url_id IN (1, ?) "] = api_get_current_access_url_id();
     }
     $announcement = Database::select("*", $announcementTable, ["where" => $whereConditions, "order" => "date_start"], 'first');
     $template = new Template(null, false, false);
     $template->assign('announcement', $announcement);
     return $template->fetch('default/announcement/view.tpl');
 }
unset($result);
$sql = "SELECT code,visual_code,title\n        FROM {$tbl_course}\n        WHERE visual_code LIKE '" . $first_letter_course . "%'\n        ORDER BY " . (count($courses) > 0 ? "(code IN('" . implode("','", $courses) . "')) DESC," : "") . " visual_code";
if (api_is_multiple_url_enabled()) {
    $tbl_course_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
    $access_url_id = api_get_current_access_url_id();
    if ($access_url_id != -1) {
        $sql = "SELECT code, visual_code, title\n                FROM {$tbl_course} as course\n                INNER JOIN {$tbl_course_rel_access_url} course_rel_url\n                ON (course_rel_url.course_code= course.code)\n                WHERE\n                    access_url_id =  {$access_url_id}  AND\n                    (visual_code LIKE '" . $first_letter_course . "%' )\n                ORDER BY " . (count($courses) > 0 ? "(code IN('" . implode("','", $courses) . "')) DESC," : "") . " visual_code";
    }
}
$result = Database::query($sql);
$db_courses = Database::store_result($result);
unset($result);
if (api_is_multiple_url_enabled()) {
    $tbl_course_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
    $tbl_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
    $access_url_id = api_get_current_access_url_id();
    if ($access_url_id != -1) {
        $sqlNbCours = "\tSELECT course_rel_user.course_code, course.title\n            FROM {$tbl_course_user} as course_rel_user\n            INNER JOIN {$tbl_course} as course\n            ON course.code = course_rel_user.course_code\n            INNER JOIN {$tbl_course_rel_access_url} course_rel_url\n            ON (course_rel_url.course_code= course.code)\n            WHERE\n                access_url_id =  {$access_url_id}  AND\n                course_rel_user.user_id='" . $_user['user_id'] . "' AND\n                course_rel_user.status='1'\n            ORDER BY course.title";
    }
}
?>
<form name="formulaire" method="post" action="<?php 
echo api_get_self();
?>
" style="margin:0px;">
<?php 
if (is_array($extra_field_list)) {
    if (is_array($new_field_list) && count($new_field_list) > 0) {
        echo '<h3>' . get_lang('FilterUsers') . '</h3>';
        foreach ($new_field_list as $new_field) {
            echo $new_field['name'];
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;
}
 /**
  * @param array $list
  * @return array
  */
 function searchCategoryById($list)
 {
     if (empty($list)) {
         return array();
     } else {
         $list = array_map('intval', $list);
         $list = implode("','", $list);
     }
     $tableCategory = Database::get_main_table(TABLE_MAIN_CATEGORY);
     $conditions = null;
     $whereCondition = null;
     if (self::isMultipleUrlSupport()) {
         $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE_CATEGORY);
         $conditions = " INNER JOIN {$table} a ON (c.id = a.course_category_id)";
         $whereCondition = " AND a.access_url_id = " . api_get_current_access_url_id();
     }
     $sql = "SELECT c.*, c.name as text FROM {$tableCategory} c {$conditions}\n                WHERE c.id IN {$list} {$whereCondition}";
     $result = Database::query($sql);
     return Database::store_result($result, 'ASSOC');
 }
     $subject = isset($_REQUEST['subject']) ? trim($_REQUEST['subject']) : null;
     $invitationContent = isset($_REQUEST['content']) ? trim($_REQUEST['content']) : null;
     SocialManager::send_invitation_friend_user($_REQUEST['user_id'], $subject, $invitationContent);
     break;
 case 'find_users':
     if (api_is_anonymous()) {
         echo '';
         break;
     }
     $track_online_table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ONLINE);
     $tbl_my_user = Database::get_main_table(TABLE_MAIN_USER);
     $tbl_my_user_friend = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
     $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
     $tbl_access_url_rel_user = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
     $search = Database::escape_string($_REQUEST['q']);
     $access_url_id = api_get_multiple_access_url() == 'true' ? api_get_current_access_url_id() : 1;
     $user_id = api_get_user_id();
     $is_western_name_order = api_is_western_name_order();
     $likeCondition = " AND (firstname LIKE '%{$search}%' OR lastname LIKE '%{$search}%' OR email LIKE '%{$search}%') ";
     if (api_get_setting('social.allow_social_tool') == 'true' && api_get_setting('message.allow_message_tool') == 'true') {
         // All users
         if (api_get_setting('message.allow_send_message_to_all_platform_users') == 'true' || api_is_platform_admin()) {
             if ($access_url_id != 0) {
                 $sql = "SELECT DISTINCT u.user_id as id, u.firstname, u.lastname, u.email\n                            FROM {$tbl_user} u LEFT JOIN {$tbl_access_url_rel_user} r ON u.user_id = r.user_id\n                            WHERE\n                                u.status <> 6  AND\n                                u.user_id <> {$user_id} AND\n                                r.access_url_id = {$access_url_id}\n                                {$likeCondition} ";
             } else {
                 $sql = "SELECT DISTINCT u.user_id as id, u.firstname, u.lastname, u.email\n                            FROM {$tbl_user} u\n                            WHERE\n                                u.status <> 6  AND\n                                u.user_id <> {$user_id}\n                                {$likeCondition} ";
             }
         } else {
             //only my contacts
             if ($access_url_id != 0) {
                 $sql = "SELECT DISTINCT u.user_id as id, u.firstname, u.lastname, u.email\n                            FROM {$tbl_access_url_rel_user} r, {$tbl_my_user_friend} uf\n                            INNER JOIN {$tbl_my_user} AS u\n                            ON uf.friend_user_id = u.user_id\n                            WHERE\n                                u.status <> 6 AND\n                                relation_type NOT IN(" . USER_RELATION_TYPE_DELETED . ", " . USER_RELATION_TYPE_RRHH . ") AND\n                                uf.user_id = {$user_id} AND\n                                friend_user_id <> {$user_id} AND\n                                u.user_id = r.user_id AND\n                                r.access_url_id = {$access_url_id}\n                                {$likeCondition}";
 /**
  * This function returns an icon path that represents the favicon of the website of which the url given.
  * Defaults to the current Chamilo favicon
  * @param    string    URL of website where to look for favicon.ico
  * @param    string    Optional second URL of website where to look for favicon.ico
  * @return    string    Path of icon to load
  */
 public static function get_favicon_from_url($url1, $url2 = null)
 {
     $icon_link = '';
     $url = $url1;
     if (empty($url1)) {
         $url = $url2;
         if (empty($url)) {
             $url = api_get_access_url(api_get_current_access_url_id());
             $url = $url[0];
         }
     }
     if (!empty($url)) {
         $pieces = parse_url($url);
         $icon_link = $pieces['scheme'] . '://' . $pieces['host'] . '/favicon.ico';
     }
     return $icon_link;
 }
Beispiel #25
0
 /**
  * @param int $id
  * @return bool|void
  */
 public function delete($id)
 {
     if ($this->useMultipleUrl) {
         if ($result) {
             $this->unsubscribeToUrl($id, api_get_current_access_url_id());
         }
     }
     $sql = "DELETE FROM {$this->usergroup_rel_user_table}\n                WHERE usergroup_id = {$id}";
     Database::query($sql);
     $sql = "DELETE FROM {$this->usergroup_rel_course_table}\n                WHERE usergroup_id = {$id}";
     Database::query($sql);
     $sql = "DELETE FROM {$this->usergroup_rel_session_table}\n                WHERE usergroup_id = {$id}";
     Database::query($sql);
     /*$sql = "DELETE FROM $this->usergroup_rel_
               WHERE usergroup_id = $id";
       Database::query($sql);*/
     $result = parent::delete($id);
 }
$id_session = isset($_GET['id_session']) ? $_GET['id_session'] : 0;
$table = new SortableTableFromArray(get_course_usage($course->code, $id_session), 0, 20, 'usage_table');
$table->set_additional_parameters(array('code' => Security::remove_XSS($_GET['code'])));
$table->set_other_tables(array('user_table', 'class_table'));
$table->set_header(0, get_lang('Tool'), true);
$table->set_header(1, get_lang('NumberOfItems'), true);
$table->display();
/**
 * Show all users subscribed in this course
 */
echo Display::page_header(get_lang('Users'));
$table_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
$table_user = Database::get_main_table(TABLE_MAIN_USER);
$sql = "SELECT *,cu.status as course_status\n        FROM {$table_course_user} cu, {$table_user} u";
if (api_is_multiple_url_enabled()) {
    $sql .= " INNER JOIN " . Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER) . " url_rel_user\n        ON u.user_id = url_rel_user.user_id\n        AND url_rel_user.access_url_id = " . intval(api_get_current_access_url_id());
}
$sql .= " WHERE cu.user_id = u.user_id AND cu.course_code = '" . $code . "'\n        AND cu.relation_type <> " . COURSE_RELATION_TYPE_RRHH;
$res = Database::query($sql);
$is_western_name_order = api_is_western_name_order();
if (Database::num_rows($res) > 0) {
    $users = array();
    while ($obj = Database::fetch_object($res)) {
        $user = array();
        $user[] = $obj->official_code;
        if ($is_western_name_order) {
            $user[] = $obj->firstname;
            $user[] = $obj->lastname;
        } else {
            $user[] = $obj->lastname;
            $user[] = $obj->firstname;
    /**
     * Set header parameters
     */
    private function set_header_parameters()
    {
        global $httpHeadXtra, $_course, $interbreadcrumb, $language_file, $noPHP_SELF, $_configuration, $this_section;
        $help = $this->help;
        $nameTools             = $this->title;
        $navigation            = return_navigation_array();
        $this->menu_navigation = $navigation['menu_navigation'];

        $this->assign('system_charset', api_get_system_encoding());

        if (isset($httpHeadXtra) && $httpHeadXtra) {
            foreach ($httpHeadXtra as & $thisHttpHead) {
                header($thisHttpHead);
            }
        }

        $this->assign('online_button', Display::return_icon('online.png'));
        $this->assign('offline_button',Display::return_icon('offline.png'));

        // Get language iso-code for this page - ignore errors
        $this->assign('document_language', api_get_language_isocode());

        $course_title = isset($_course['name']) ? $_course['name'] : null;

        $title_list = array();

        $title_list[] = api_get_setting('Institution');
        $title_list[] = api_get_setting('siteName');

        if (!empty($course_title)) {
            $title_list[] = $course_title;
        }
        if ($nameTools != '') {
            $title_list[] = $nameTools;
        }

        $title_string = '';
        for ($i = 0; $i < count($title_list); $i++) {
            $title_string .= $title_list[$i];
            if (isset($title_list[$i + 1])) {
                $item = trim($title_list[$i + 1]);
                if (!empty($item)) {
                    $title_string .= ' - ';
                }
            }
        }

        $this->assign('title_string', $title_string);

        //Setting the theme and CSS files
        $this->set_css_files();
        $this->set_js_files();
        //$this->set_js_files_post();

        $browser = api_browser_support('check_browser');
        if ($browser[0] == 'Internet Explorer' && $browser[1] >= '11') {
            $browser_head = '<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE9" />';
            $this->assign('browser_specific_head', $browser_head);
        }

        // Implementation of prefetch.
        // See http://cdn.chamilo.org/main/img/online.png for details
        $prefetch = '';
        if (!empty($_configuration['cdn_enable'])) {
            $prefetch .= '<meta http-equiv="x-dns-prefetch-control" content="on">';
            foreach ($_configuration['cdn'] as $host => $exts) {
                $prefetch .= '<link rel="dns-prefetch" href="'.$host.'">';
            }
        }

        $this->assign('prefetch', $prefetch);
        $this->assign('text_direction', api_get_text_direction());
        $this->assign('section_name', 'section-'.$this_section);

        $favico = '<link rel="shortcut icon" href="'.api_get_path(WEB_PATH).'favicon.ico" type="image/x-icon" />';

        if (isset($_configuration['multiple_access_urls']) && $_configuration['multiple_access_urls']) {
            $access_url_id = api_get_current_access_url_id();
            if ($access_url_id != -1) {
                $url_info  = api_get_access_url($access_url_id);
                $url       = api_remove_trailing_slash(preg_replace('/https?:\/\//i', '', $url_info['url']));
                $clean_url = replace_dangerous_char($url);
                $clean_url = str_replace('/', '-', $clean_url);
                $clean_url .= '/';
                $homep           = api_get_path(REL_PATH).'home/'.$clean_url; //homep for Home Path
                $icon_real_homep = api_get_path(SYS_PATH).'home/'.$clean_url;

                //we create the new dir for the new sites
                if (is_file($icon_real_homep.'favicon.ico')) {
                    $favico = '<link rel="shortcut icon" href="'.$homep.'favicon.ico" type="image/x-icon" />';
                }
            }
        }

        $this->assign('favico', $favico);

        $this->set_help();

        //@todo move this in the template
        $bug_notification_link = '';
        if (api_get_setting('show_link_bug_notification') == 'true' && $this->user_is_logged_in) {
            $bug_notification_link = '<li class="report">
		        						<a href="http://support.chamilo.org/projects/chamilo-18/wiki/How_to_report_bugs" target="_blank">
		        						<img src="'.api_get_path(WEB_IMG_PATH).'bug.large.png" style="vertical-align: middle;" alt="'.get_lang('ReportABug').'" title="'.get_lang(
                    'ReportABug'
                ).'"/></a>
		    						  </li>';
        }

        $this->assign('bug_notification_link', $bug_notification_link);

        $notification = return_notification_menu();
        $this->assign('notification_menu', $notification);

        //Preparing values for the menu

        //Logout link
        if (isset($_configuration['hide_logout_button']) && $_configuration['hide_logout_button'] == 'true') {
            $this->assign('logout_link', null);
        } else {
            $this->assign('logout_link', api_get_path(WEB_PATH).'index.php?logout=logout&uid='.api_get_user_id());
        }

        //Profile link
        if (api_get_setting('allow_social_tool') == 'true') {
            $profile_url  = api_get_path(WEB_CODE_PATH).'social/home.php';
            $profile_link = Display::url(get_lang('Profile'), $profile_url);
        } else {
            $profile_url  = api_get_path(WEB_CODE_PATH).'auth/profile.php';
            $profile_link = Display::url(get_lang('Profile'), $profile_url);
        }
        $this->assign('profile_link', $profile_link);
        $this->assign('profile_url', $profile_url);

        //Message link
        $message_link = null;
        $message_url  = null;
        if (api_get_setting('allow_message_tool') == 'true') {
            $message_url  = api_get_path(WEB_CODE_PATH).'messages/inbox.php';
            $message_link = '<a href="'.api_get_path(WEB_CODE_PATH).'messages/inbox.php">'.get_lang('Inbox').'</a>';
        }
        $this->assign('message_link', $message_link);
        $this->assign('message_url', $message_url);

        $institution = api_get_setting('Institution');
        $portal_name = empty($institution) ? api_get_setting('siteName') : $institution;

        $this->assign('portal_name', $portal_name);

        //Menu
        $menu = return_menu();
        $this->assign('menu', $menu);

        //Setting notifications


        $count_unread_message = 0;
        if (api_get_setting('allow_message_tool') == 'true') {
            // get count unread message and total invitations
            $count_unread_message = MessageManager::get_number_of_messages(true);
        }

        $total_invitations = 0;
        if (api_get_setting('allow_social_tool') == 'true') {
            $number_of_new_messages_of_friend = SocialManager::get_message_number_invitation_by_user_id(
                api_get_user_id()
            );
            $group_pending_invitations        = GroupPortalManager::get_groups_by_user(
                api_get_user_id(),
                GROUP_USER_PERMISSION_PENDING_INVITATION,
                false
            );
            $group_pending_invitations        = 0;
            if (!empty($group_pending_invitations)) {
                $group_pending_invitations = count($group_pending_invitations);
            }
            $total_invitations = intval($number_of_new_messages_of_friend) + $group_pending_invitations + intval(
                    $count_unread_message
                );
        }
        $total_invitations = (!empty($total_invitations) ? Display::badge($total_invitations) : null);

        $this->assign('user_notifications', $total_invitations);


        //Breadcrumb
        $breadcrumb = return_breadcrumb($interbreadcrumb, $language_file, $nameTools);
        $this->assign('breadcrumb', $breadcrumb);

        //Extra content
        $extra_header = null;
        if (!api_is_platform_admin()) {
            $extra_header = trim(api_get_setting('header_extra_content'));
        }
        $this->assign('header_extra_content', $extra_header);

        //if ($this->show_header == 1) {
            header('Content-Type: text/html; charset='.api_get_system_encoding());
            header(
                'X-Powered-By: '.$_configuration['software_name'].' '.substr($_configuration['system_version'], 0, 1)
            );
        //}
    }
 static function get_coaches_by_keyword($tag)
 {
     $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
     $order_clause = api_sort_by_first_name() ? ' ORDER BY firstname, lastname, username' : ' ORDER BY lastname, firstname, username';
     $select = "SELECT user.user_id, lastname, firstname, username ";
     $sql = " {$select} FROM {$tbl_user} user WHERE status='1'";
     $tag = Database::escape_string($tag);
     $where_condition = array();
     if (!empty($tag)) {
         $condition = ' LIKE "%' . $tag . '%"';
         $where_condition = array("firstname {$condition}", "lastname {$condition}", "username {$condition}");
         $where_condition = ' AND  (' . implode(' OR ', $where_condition) . ') ';
     }
     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) {
             $sql = $select . ' 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 status = 1';
         }
     }
     $sql .= $where_condition . $order_clause;
     $result = Database::query($sql);
     return Database::store_result($result, 'ASSOC');
 }
 /**
  * Print the number of users that didn't login for a certain period of time
  */
 static function print_users_not_logged_in_stats()
 {
     $total_logins = array();
     $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN);
     $access_url_rel_user_table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
     $current_url_id = api_get_current_access_url_id();
     $total = self::count_users();
     if (api_is_multiple_url_enabled()) {
         $table_url = ", {$access_url_rel_user_table}";
         $where_url = " AND login_user_id=user_id AND access_url_id='" . $current_url_id . "'";
     } else {
         $table_url = '';
         $where_url = '';
     }
     $sql[get_lang('Thisday')] = "SELECT count(distinct(login_user_id)) AS number " . " FROM {$table} {$table_url} " . " WHERE DATE_ADD(login_date, INTERVAL 1 DAY) >= NOW() {$where_url}";
     $sql[get_lang('Last7days')] = "SELECT count(distinct(login_user_id)) AS number " . " FROM {$table} {$table_url} " . " WHERE DATE_ADD(login_date, INTERVAL 7 DAY) >= NOW() {$where_url}";
     $sql[get_lang('Last31days')] = "SELECT count(distinct(login_user_id)) AS number " . " FROM {$table} {$table_url} " . " WHERE DATE_ADD(login_date, INTERVAL 31 DAY) >= NOW() {$where_url}";
     $sql[sprintf(get_lang('LastXMonths'), 6)] = "SELECT count(distinct(login_user_id)) AS number " . " FROM {$table} {$table_url} " . " WHERE DATE_ADD(login_date, INTERVAL 6 MONTH) >= NOW() {$where_url}";
     $sql[get_lang('NeverConnected')] = "SELECT count(distinct(login_user_id)) AS number " . " FROM {$table} {$table_url} WHERE 1=1 {$where_url}";
     foreach ($sql as $index => $query) {
         $res = Database::query($query);
         $obj = Database::fetch_object($res);
         $r = $total - $obj->number;
         $total_logins[$index] = $r < 0 ? 0 : $r;
     }
     Statistics::print_stats(get_lang('StatsUsersDidNotLoginInLastPeriods'), $total_logins, false);
 }
Beispiel #30
0
 /**
  * Get data for users list in sortable with pagination
  * @param $from
  * @param $number_of_items
  * @param $column
  * @param $direction
  * @param $includeInvitedUsers boolean Whether include the invited users
  * @return array
  */
 public static function get_user_data($from, $number_of_items, $column, $direction, $includeInvitedUsers = false)
 {
     global $user_ids, $course_code, $additional_user_profile_info, $export_csv, $is_western_name_order, $csv_content, $session_id;
     $course_code = Database::escape_string($course_code);
     $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
     $tbl_url_rel_user = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
     $access_url_id = api_get_current_access_url_id();
     // get all users data from a course for sortable with limit
     if (is_array($user_ids)) {
         $user_ids = array_map('intval', $user_ids);
         $condition_user = "******" . implode(',', $user_ids) . ") ";
     } else {
         $user_ids = intval($user_ids);
         $condition_user = "******";
     }
     if (!empty($_GET['user_keyword'])) {
         $keyword = trim(Database::escape_string($_GET['user_keyword']));
         $condition_user .= " AND (\n                user.firstname LIKE '%" . $keyword . "%' OR\n                user.lastname LIKE '%" . $keyword . "%'  OR\n                user.username LIKE '%" . $keyword . "%'  OR\n                user.email LIKE '%" . $keyword . "%'\n             ) ";
     }
     $url_table = null;
     $url_condition = null;
     if (api_is_multiple_url_enabled()) {
         $url_table = ", " . $tbl_url_rel_user . "as url_users";
         $url_condition = " AND user.user_id = url_users.user_id AND access_url_id='{$access_url_id}'";
     }
     $invitedUsersCondition = '';
     if (!$includeInvitedUsers) {
         $invitedUsersCondition = " AND user.status != " . INVITEE;
     }
     $sql = "SELECT  user.user_id as user_id,\n                    user.official_code  as col0,\n                    user.lastname       as col1,\n                    user.firstname      as col2,\n                    user.username       as col3\n                FROM {$tbl_user} as user {$url_table}\n    \t        {$condition_user} {$url_condition} {$invitedUsersCondition}";
     if (!in_array($direction, array('ASC', 'DESC'))) {
         $direction = 'ASC';
     }
     $column = intval($column);
     $from = intval($from);
     $number_of_items = intval($number_of_items);
     $sql .= " ORDER BY col{$column} {$direction} ";
     $sql .= " LIMIT {$from},{$number_of_items}";
     $res = Database::query($sql);
     $users = array();
     $course_info = api_get_course_info($course_code);
     $total_surveys = 0;
     $total_exercises = ExerciseLib::get_all_exercises($course_info, $session_id, false, null, false, 3);
     if (empty($session_id)) {
         $survey_user_list = array();
         $survey_list = SurveyManager::get_surveys($course_code, $session_id);
         $total_surveys = count($survey_list);
         if (!empty($survey_list)) {
             foreach ($survey_list as $survey) {
                 $user_list = SurveyManager::get_people_who_filled_survey($survey['survey_id'], false, $course_info['real_id']);
                 foreach ($user_list as $user_id) {
                     isset($survey_user_list[$user_id]) ? $survey_user_list[$user_id]++ : ($survey_user_list[$user_id] = 1);
                 }
             }
         }
     }
     while ($user = Database::fetch_array($res, 'ASSOC')) {
         $courseInfo = api_get_course_info($course_code);
         $courseId = $courseInfo['real_id'];
         $user['official_code'] = $user['col0'];
         $user['lastname'] = $user['col1'];
         $user['firstname'] = $user['col2'];
         $user['username'] = $user['col3'];
         $user['time'] = api_time_to_hms(Tracking::get_time_spent_on_the_course($user['user_id'], $courseId, $session_id));
         $avg_student_score = Tracking::get_avg_student_score($user['user_id'], $course_code, array(), $session_id);
         $avg_student_progress = Tracking::get_avg_student_progress($user['user_id'], $course_code, array(), $session_id);
         if (empty($avg_student_progress)) {
             $avg_student_progress = 0;
         }
         $user['average_progress'] = $avg_student_progress . '%';
         $total_user_exercise = Tracking::get_exercise_student_progress($total_exercises, $user['user_id'], $courseId, $session_id);
         $user['exercise_progress'] = $total_user_exercise;
         $total_user_exercise = Tracking::get_exercise_student_average_best_attempt($total_exercises, $user['user_id'], $courseId, $session_id);
         $user['exercise_average_best_attempt'] = $total_user_exercise;
         if (is_numeric($avg_student_score)) {
             $user['student_score'] = $avg_student_score . '%';
         } else {
             $user['student_score'] = $avg_student_score;
         }
         $user['count_assignments'] = Tracking::count_student_assignments($user['user_id'], $course_code, $session_id);
         $user['count_messages'] = Tracking::count_student_messages($user['user_id'], $course_code, $session_id);
         $user['first_connection'] = Tracking::get_first_connection_date_on_the_course($user['user_id'], $courseId, $session_id);
         $user['last_connection'] = Tracking::get_last_connection_date_on_the_course($user['user_id'], $courseInfo, $session_id);
         // we need to display an additional profile field
         $user['additional'] = '';
         if (isset($_GET['additional_profile_field']) && is_numeric($_GET['additional_profile_field'])) {
             if (isset($additional_user_profile_info[$user['user_id']]) && is_array($additional_user_profile_info[$user['user_id']])) {
                 $user['additional'] = implode(', ', $additional_user_profile_info[$user['user_id']]);
             }
         }
         if (empty($session_id)) {
             $user['survey'] = (isset($survey_user_list[$user['user_id']]) ? $survey_user_list[$user['user_id']] : 0) . ' / ' . $total_surveys;
         }
         $user['link'] = '<center><a href="../mySpace/myStudents.php?student=' . $user['user_id'] . '&details=true&course=' . $course_code . '&origin=tracking_course&id_session=' . $session_id . '"><img src="' . api_get_path(WEB_IMG_PATH) . 'icons/22/2rightarrow.png" border="0" /></a></center>';
         // store columns in array $users
         $is_western_name_order = api_is_western_name_order();
         $user_row = array();
         $user_row[] = $user['official_code'];
         //0
         if ($is_western_name_order) {
             $user_row[] = $user['firstname'];
             $user_row[] = $user['lastname'];
         } else {
             $user_row[] = $user['lastname'];
             $user_row[] = $user['firstname'];
         }
         $user_row[] = $user['username'];
         $user_row[] = $user['time'];
         $user_row[] = $user['average_progress'];
         $user_row[] = $user['exercise_progress'];
         $user_row[] = $user['exercise_average_best_attempt'];
         $user_row[] = $user['student_score'];
         $user_row[] = $user['count_assignments'];
         $user_row[] = $user['count_messages'];
         if (empty($session_id)) {
             $user_row[] = $user['survey'];
         }
         $user_row[] = $user['first_connection'];
         $user_row[] = $user['last_connection'];
         if (isset($_GET['additional_profile_field']) && is_numeric($_GET['additional_profile_field'])) {
             $user_row[] = $user['additional'];
         }
         $user_row[] = $user['link'];
         $users[] = $user_row;
         if ($export_csv) {
             if (empty($session_id)) {
                 $user_row = array_map('strip_tags', $user_row);
                 unset($user_row[14]);
                 unset($user_row[15]);
             } else {
                 $user_row = array_map('strip_tags', $user_row);
                 unset($user_row[13]);
                 unset($user_row[14]);
             }
             $csv_content[] = $user_row;
         }
     }
     return $users;
 }