/**
* this function displays the form to upload a new item to the dropbox.
*
* @author Patrick Cool <*****@*****.**>, Ghent University
* @version march 2006
*/
function display_add_form($dropbox_unid, $viewReceivedCategory, $viewSentCategory, $view)
{
    $course_info = api_get_course_info();
    $_user = api_get_user_info();
    $is_courseAdmin = api_is_course_admin();
    $is_courseTutor = api_is_course_tutor();
    $origin = isset($_GET['origin']) ? $_GET['origin'] : null;
    $token = Security::get_token();
    $dropbox_person = new Dropbox_Person(api_get_user_id(), $is_courseAdmin, $is_courseTutor);
    $form = new FormValidator('sent_form', 'post', api_get_self() . '?view_received_category=' . $viewReceivedCategory . '&view_sent_category=' . $viewSentCategory . '&view=' . $view . '&' . api_get_cidreq(), null, array('enctype' => 'multipart/form-data', 'onsubmit' => 'javascript: return checkForm(this);'));
    $form->addElement('header', get_lang('UploadNewFile'));
    $form->addElement('hidden', 'MAX_FILE_SIZE', dropbox_cnf('maxFilesize'));
    $form->addElement('hidden', 'dropbox_unid', $dropbox_unid);
    $form->addElement('hidden', 'sec_token', $token);
    $form->addElement('hidden', 'origin', $origin);
    $form->addElement('file', 'file', get_lang('UploadFile'), array('onChange' => 'javascript: checkfile(this.value);'));
    if (dropbox_cnf('allowOverwrite')) {
        $form->addElement('checkbox', 'cb_overwrite', null, get_lang('OverwriteFile'), array('id' => 'cb_overwrite'));
    }
    // List of all users in this course and all virtual courses combined with it
    if (api_get_session_id()) {
        $complete_user_list_for_dropbox = array();
        if (api_get_setting('dropbox_allow_student_to_student') == 'true' || $_user['status'] != STUDENT) {
            $complete_user_list_for_dropbox = CourseManager::get_user_list_from_course_code($course_info['code'], api_get_session_id());
        }
        $complete_user_list2 = CourseManager::get_coach_list_from_course_code($course_info['code'], api_get_session_id());
        $complete_user_list_for_dropbox = array_merge($complete_user_list_for_dropbox, $complete_user_list2);
    } else {
        if (api_get_setting('dropbox_allow_student_to_student') == 'true' || $_user['status'] != STUDENT) {
            $complete_user_list_for_dropbox = CourseManager::get_user_list_from_course_code($course_info['code'], api_get_session_id());
        } else {
            $complete_user_list_for_dropbox = CourseManager::get_teacher_list_from_course_code($course_info['code'], false);
        }
    }
    if (!empty($complete_user_list_for_dropbox)) {
        foreach ($complete_user_list_for_dropbox as $k => $e) {
            $complete_user_list_for_dropbox[$k] = $e + array('lastcommafirst' => api_get_person_name($e['firstname'], $e['lastname']));
        }
        $complete_user_list_for_dropbox = TableSort::sort_table($complete_user_list_for_dropbox, 'lastcommafirst');
    }
    /*
        Create the options inside the select box:
        List all selected users their user id as value and a name string as display
    */
    $current_user_id = '';
    $options = array();
    foreach ($complete_user_list_for_dropbox as $current_user) {
        if (($dropbox_person->isCourseTutor || $dropbox_person->isCourseAdmin || dropbox_cnf('allowStudentToStudent') || $current_user['status'] != 5 || $current_user['tutor_id'] == 1) && $current_user['user_id'] != $_user['user_id']) {
            // Don't include yourself.
            if ($current_user['user_id'] == $current_user_id) {
                continue;
            }
            $full_name = $current_user['lastcommafirst'];
            $current_user_id = $current_user['user_id'];
            $options['user_' . $current_user_id] = $full_name;
            //echo '<option value="user_' . $current_user_id . '">' . $full_name . '</option>';
        }
    }
    /*
     * Show groups
     */
    if (($dropbox_person->isCourseTutor || $dropbox_person->isCourseAdmin) && dropbox_cnf('allowGroup') || dropbox_cnf('allowStudentToStudent')) {
        $complete_group_list_for_dropbox = GroupManager::get_group_list(null, dropbox_cnf('courseId'));
        if (count($complete_group_list_for_dropbox) > 0) {
            foreach ($complete_group_list_for_dropbox as $current_group) {
                if ($current_group['number_of_members'] > 0) {
                    //echo '<option value="group_'.$current_group['id'].'">G: '.$current_group['name'].' - '.$current_group['number_of_members'].' '.get_lang('Users').'</option>';
                    $options['group_' . $current_group['id']] = 'G: ' . $current_group['name'] . ' - ' . $current_group['number_of_members'] . ' ' . get_lang('Users');
                }
            }
        }
    }
    if (dropbox_cnf('allowJustUpload')) {
        //echo '<option value="upload">'.get_lang('JustUploadInSelect').'</option>';
        //echo '<option value="user_'.$_user['user_id'].'">'.get_lang('JustUploadInSelect').'</option>';
        $options['user_' . $_user['user_id']] = get_lang('JustUploadInSelect');
    }
    $form->addElement('select', 'recipients', get_lang('SendTo'), $options, array('multiple' => 'multiple', 'size' => '10', 'class' => 'span4'));
    $form->addElement('button', 'submitWork', get_lang('Upload'));
    $form->display();
}
             $columns[] = $extra['1'];
             $column_names[] = $extra['3'];
         }
     }
     if (api_is_student_boss()) {
         $columns[] = 'group';
         $column_names[] = get_lang('Group');
     }
     if (!in_array($sidx, array('title'))) {
         $sidx = 'title';
     }
     if (api_is_student_boss() && empty($userIdList)) {
         $result = [];
         break;
     }
     $result = CourseManager::get_user_list_from_course_code(null, null, "LIMIT {$start}, {$limit}", " {$sidx} {$sord}", null, null, true, false, null, $courseCodeList, $userIdList, null, $sessionIdList);
     if (api_is_student_boss()) {
         $userGroup = new UserGroup();
         foreach ($result as &$item) {
             $userGroups = $userGroup->get_groups_by_user($item['user_id']);
             $item['group'] = implode(", ", array_column($userGroups, 'name'));
             unset($item['user_id']);
         }
     }
     break;
 case 'get_user_skill_ranking':
     $columns = array('photo', 'firstname', 'lastname', 'skills_acquired', 'currently_learning', 'rank');
     $result = $skill->get_user_list_skill_ranking($start, $limit, $sidx, $sord, $whereCondition);
     $result = ArrayClass::msort($result, 'skills_acquired', 'asc');
     $skills_in_course = array();
     if (!empty($result)) {
 /**
  *    Get a combined list of all users of the real course $course_code
  *        and all users in virtual courses linked to this course $course_code
  *    Filter user list: remove duplicate users; plus
  *        remove users that
  *        - are already in the current group $group_id;
  *        - do not have student status in these courses;
  *        - are not appointed as tutor (group assistent) for this group;
  *        - have already reached their maximum # of groups in this course.
  *
  *    Originally to get the correct list of users a big SQL statement was used,
  *    but this has become more complicated now there is not just one real course but many virtual courses.
  *    Still, that could have worked as well.
  *
  *    @version 1.1.3
  *    @author Roan Embrechts
  */
 public static function get_complete_list_of_users_that_can_be_added_to_group($course_code, $group_id)
 {
     global $_course, $_user;
     $category = self::get_category_from_group($group_id, $course_code);
     $number_of_groups_limit = $category['groups_per_user'] == self::GROUP_PER_MEMBER_NO_LIMIT ? self::INFINITE : $category['groups_per_user'];
     $real_course_code = $_course['sysCode'];
     $real_course_info = Database::get_course_info($real_course_code);
     $real_course_user_list = CourseManager::get_user_list_from_course_code($real_course_code);
     //get list of all virtual courses
     $user_subscribed_course_list = CourseManager::get_list_of_virtual_courses_for_specific_user_and_real_course($_user['user_id'], $real_course_code);
     //add real course to the list
     $user_subscribed_course_list[] = $real_course_info;
     if (!is_array($user_subscribed_course_list)) {
         return;
     }
     //for all courses...
     foreach ($user_subscribed_course_list as $this_course) {
         $this_course_code = $this_course['code'];
         $course_user_list = CourseManager::get_user_list_from_course_code($this_course_code);
         //for all users in the course
         foreach ($course_user_list as $this_user) {
             $user_id = $this_user['user_id'];
             $loginname = $this_user['username'];
             $lastname = $this_user['lastname'];
             $firstname = $this_user['firstname'];
             $status = $this_user['status'];
             //$role =  $this_user['role'];
             $tutor_id = $this_user['tutor_id'];
             $full_name = api_get_person_name($firstname, $lastname);
             if ($lastname == "" || $firstname == '') {
                 $full_name = $loginname;
             }
             $complete_user['user_id'] = $user_id;
             $complete_user['full_name'] = $full_name;
             $complete_user['firstname'] = $firstname;
             $complete_user['lastname'] = $lastname;
             $complete_user['status'] = $status;
             $complete_user['tutor_id'] = $tutor_id;
             $student_number_of_groups = self::user_in_number_of_groups($user_id, $category['id']);
             //filter: only add users that have not exceeded their maximum amount of groups
             if ($student_number_of_groups < $number_of_groups_limit) {
                 $complete_user_list[] = $complete_user;
             }
         }
     }
     if (is_array($complete_user_list)) {
         //sort once, on array field "full_name"
         $complete_user_list = TableSort::sort_table($complete_user_list, "full_name");
         //filter out duplicates, based on field "user_id"
         $complete_user_list = self::filter_duplicates($complete_user_list, "user_id");
         $complete_user_list = self::filter_users_already_in_group($complete_user_list, $group_id);
     }
     return $complete_user_list;
 }
Exemple #4
0
/**
 * Get the users to display on the current page.
 */
function get_user_data($from, $number_of_items, $column, $direction)
{
    global $origin;
    global $course_info;
    global $is_western_name_order;
    global $session_id;
    $a_users = array();
    // limit
    $limit = 'LIMIT ' . intval($from) . ',' . intval($number_of_items);
    if (!in_array($direction, array('ASC', 'DESC'))) {
        $direction = 'ASC';
    }
    switch ($column) {
        case 2:
            //official code
            $order_by = 'ORDER BY user.official_code ' . $direction;
            break;
        case 3:
            if ($is_western_name_order) {
                $order_by = 'ORDER BY user.firstname ' . $direction . ', user.lastname ' . $direction;
            } else {
                $order_by = 'ORDER BY user.lastname ' . $direction . ', user.firstname ' . $direction;
            }
            break;
        case 4:
            if ($is_western_name_order) {
                $order_by = 'ORDER BY user.lastname ' . $direction . ', user.firstname ' . $direction;
            } else {
                $order_by = 'ORDER BY user.firstname ' . $direction . ', user.lastname ' . $direction;
            }
            break;
        case 5:
            //username
            $order_by = 'ORDER BY user.username ' . $direction;
            break;
        default:
            if ($is_western_name_order) {
                $order_by = 'ORDER BY user.lastname ' . $direction . ', user.firstname ' . $direction;
            } else {
                $order_by = 'ORDER BY user.firstname ' . $direction . ', user.lastname ' . $direction;
            }
            break;
    }
    $session_id = api_get_session_id();
    $course_code = api_get_course_id();
    $keyword = isset($_REQUEST['keyword']) ? $_REQUEST['keyword'] : null;
    $a_course_users = CourseManager::get_user_list_from_course_code($course_code, $session_id, $limit, $order_by, null, $keyword);
    foreach ($a_course_users as $user_id => $o_course_user) {
        $groups_name = GroupManager::get_user_group_name($user_id);
        $temp = array();
        if (api_is_allowed_to_edit(null, true)) {
            //if (api_get_setting('allow_user_course_subscription_by_course_admin') == 'true') {
            $temp[] = $user_id;
            //}
            $image_path = UserManager::get_user_picture_path_by_id($user_id, 'web', false, true);
            $user_profile = UserManager::get_picture_user($user_id, $image_path['file'], 22, USER_IMAGE_SIZE_SMALL, ' width="22" height="22" ');
            if (!api_is_anonymous()) {
                $photo = '<a href="userInfo.php?' . api_get_cidreq() . '&origin=' . $origin . '&amp;uInfo=' . $user_id . '" title="' . get_lang('Info') . '"  ><img src="' . $user_profile['file'] . '" ' . $user_profile['style'] . ' alt="' . api_get_person_name($o_course_user['firstname'], $o_course_user['lastname']) . '"  title="' . api_get_person_name($o_course_user['firstname'], $o_course_user['lastname']) . '" /></a>';
            } else {
                $photo = '<img src="' . $user_profile['file'] . '" ' . $user_profile['style'] . ' alt="' . api_get_person_name($o_course_user['firstname'], $o_course_user['lastname']) . '" title="' . api_get_person_name($o_course_user['firstname'], $o_course_user['lastname']) . '" />';
            }
            $temp[] = $photo;
            $temp[] = $o_course_user['official_code'];
            if ($is_western_name_order) {
                $temp[] = $o_course_user['firstname'];
                $temp[] = $o_course_user['lastname'];
            } else {
                $temp[] = $o_course_user['lastname'];
                $temp[] = $o_course_user['firstname'];
            }
            $temp[] = $o_course_user['username'];
            $temp[] = isset($o_course_user['role']) ? $o_course_user['role'] : null;
            //Description
            $temp[] = implode(', ', $groups_name);
            //Group
            // Status
            $default_status = '-';
            if (isset($o_course_user['status_rel']) && $o_course_user['status_rel'] == 1 || isset($o_course_user['status_session']) && $o_course_user['status_session'] == 2) {
                $default_status = get_lang('CourseManager');
            } elseif (isset($o_course_user['tutor_id']) && $o_course_user['tutor_id'] == 1) {
                $default_status = get_lang('Tutor');
            }
            $temp[] = $default_status;
            //Active
            $temp[] = $o_course_user['active'];
            //User id for actions
            $temp[] = $user_id;
        } else {
            $image_path = UserManager::get_user_picture_path_by_id($user_id, 'web', false, true);
            $image_repository = $image_path['dir'];
            $existing_image = $image_path['file'];
            if (!api_is_anonymous()) {
                $photo = '<a href="userInfo.php?' . api_get_cidreq() . '&origin=' . $origin . '&amp;uInfo=' . $user_id . '" title="' . get_lang('Info') . '"  ><img src="' . $image_repository . $existing_image . '" alt="' . api_get_person_name($o_course_user['firstname'], $o_course_user['lastname']) . '"  width="22" height="22" title="' . api_get_person_name($o_course_user['firstname'], $o_course_user['lastname']) . '" /></a>';
            } else {
                $photo = '<img src="' . $image_repository . $existing_image . '" alt="' . api_get_person_name($o_course_user['firstname'], $o_course_user['lastname']) . '"  width="22" height="22" title="' . api_get_person_name($o_course_user['firstname'], $o_course_user['lastname']) . '" />';
            }
            $temp[] = $user_id;
            $temp[] = $photo;
            $temp[] = $o_course_user['official_code'];
            if ($is_western_name_order) {
                $temp[] = $o_course_user['firstname'];
                $temp[] = $o_course_user['lastname'];
            } else {
                $temp[] = $o_course_user['lastname'];
                $temp[] = $o_course_user['firstname'];
            }
            $temp[] = $o_course_user['username'];
            $temp[] = $o_course_user['role'];
            $temp[] = implode(', ', $groups_name);
            //Group
            if ($course_info['unsubscribe'] == 1) {
                //User id for actions
                $temp[] = $user_id;
            }
            //$temp[] = $o_course_user['official_code'];
        }
        $a_users[$user_id] = $temp;
    }
    return $a_users;
}
 /**
  * Shows the user detail progress (when clicking in the details link)
  * @param   int     $user_id
  * @param   string  $course_code
  * @param   int     $session_id
  * @return  string  html code
  */
 public static function show_course_detail($user_id, $course_code, $session_id)
 {
     $html = '';
     if (isset($course_code)) {
         $user_id = intval($user_id);
         $session_id = intval($session_id);
         $course = Database::escape_string($course_code);
         $course_info = CourseManager::get_course_information($course);
         $html .= Display::page_subheader($course_info['title']);
         $html .= '<table class="data_table" width="100%">';
         //Course details
         $html .= '
             <tr>
             <th class="head" style="color:#000">' . get_lang('Exercises') . '</th>
             <th class="head" style="color:#000">' . get_lang('Attempts') . '</th>
             <th class="head" style="color:#000">' . get_lang('BestAttempt') . '</th>
             <th class="head" style="color:#000">' . get_lang('Ranking') . '</th>
             <th class="head" style="color:#000">' . get_lang('BestResultInCourse') . '</th>
             <th class="head" style="color:#000">' . get_lang('Statistics') . ' ' . Display::return_icon('info3.gif', get_lang('OnlyBestResultsPerStudent'), array('align' => 'absmiddle', 'hspace' => '3px')) . '</th>
             </tr>';
         if (empty($session_id)) {
             $user_list = CourseManager::get_user_list_from_course_code($course, $session_id, null, null, STUDENT);
         } else {
             $user_list = CourseManager::get_user_list_from_course_code($course, $session_id, null, null, 0);
         }
         // Show exercise results of invisible exercises? see BT#4091
         $exercise_list = ExerciseLib::get_all_exercises($course_info, $session_id, false, null, false, 2);
         $to_graph_exercise_result = array();
         if (!empty($exercise_list)) {
             $score = $weighting = $exe_id = 0;
             foreach ($exercise_list as $exercices) {
                 $exercise_obj = new Exercise($course_info['real_id']);
                 $exercise_obj->read($exercices['id']);
                 $visible_return = $exercise_obj->is_visible();
                 $score = $weighting = $attempts = 0;
                 // Getting count of attempts by user
                 $attempts = Event::count_exercise_attempts_by_user(api_get_user_id(), $exercices['id'], $course_info['real_id'], $session_id);
                 $html .= '<tr class="row_even">';
                 $url = api_get_path(WEB_CODE_PATH) . "exercice/overview.php?cidReq={$course_info['code']}&id_session={$session_id}&exerciseId={$exercices['id']}";
                 if ($visible_return['value'] == true) {
                     $exercices['title'] = Display::url($exercices['title'], $url, array('target' => SESSION_LINK_TARGET));
                 }
                 $html .= Display::tag('td', $exercices['title']);
                 // Exercise configuration show results or show only score
                 if ($exercices['results_disabled'] == 0 || $exercices['results_disabled'] == 2) {
                     //For graphics
                     $best_exercise_stats = Event::get_best_exercise_results_by_user($exercices['id'], $course_info['real_id'], $session_id);
                     $to_graph_exercise_result[$exercices['id']] = array('title' => $exercices['title'], 'data' => $best_exercise_stats);
                     $latest_attempt_url = '';
                     $best_score = $position = $percentage_score_result = '-';
                     $graph = $normal_graph = null;
                     // Getting best results
                     $best_score_data = ExerciseLib::get_best_attempt_in_course($exercices['id'], $course_info['real_id'], $session_id);
                     $best_score = '';
                     if (!empty($best_score_data)) {
                         $best_score = ExerciseLib::show_score($best_score_data['exe_result'], $best_score_data['exe_weighting']);
                     }
                     if ($attempts > 0) {
                         $exercise_stat = ExerciseLib::get_best_attempt_by_user(api_get_user_id(), $exercices['id'], $course_info['real_id'], $session_id);
                         if (!empty($exercise_stat)) {
                             //Always getting the BEST attempt
                             $score = $exercise_stat['exe_result'];
                             $weighting = $exercise_stat['exe_weighting'];
                             $exe_id = $exercise_stat['exe_id'];
                             $latest_attempt_url .= api_get_path(WEB_CODE_PATH) . 'exercice/result.php?id=' . $exe_id . '&cidReq=' . $course_info['code'] . '&show_headers=1&id_session=' . $session_id;
                             $percentage_score_result = Display::url(ExerciseLib::show_score($score, $weighting), $latest_attempt_url);
                             $my_score = 0;
                             if (!empty($weighting) && intval($weighting) != 0) {
                                 $my_score = $score / $weighting;
                             }
                             //@todo this function slows the page
                             $position = ExerciseLib::get_exercise_result_ranking($my_score, $exe_id, $exercices['id'], $course_info['code'], $session_id, $user_list);
                             $graph = self::generate_exercise_result_thumbnail_graph($to_graph_exercise_result[$exercices['id']]);
                             $normal_graph = self::generate_exercise_result_graph($to_graph_exercise_result[$exercices['id']]);
                         }
                     }
                     $html .= Display::div($normal_graph, array('id' => 'main_graph_' . $exercices['id'], 'class' => 'dialog', 'style' => 'display:none'));
                     if (empty($graph)) {
                         $graph = '-';
                     } else {
                         $graph = Display::url('<img src="' . $graph . '" >', $normal_graph, array('id' => $exercices['id'], 'class' => 'expand-image'));
                     }
                     $html .= Display::tag('td', $attempts, array('align' => 'center'));
                     $html .= Display::tag('td', $percentage_score_result, array('align' => 'center'));
                     $html .= Display::tag('td', $position, array('align' => 'center'));
                     $html .= Display::tag('td', $best_score, array('align' => 'center'));
                     $html .= Display::tag('td', $graph, array('align' => 'center'));
                     //$html .= Display::tag('td', $latest_attempt_url,       array('align'=>'center', 'width'=>'25'));
                 } else {
                     // Exercise configuration NO results
                     $html .= Display::tag('td', $attempts, array('align' => 'center'));
                     $html .= Display::tag('td', '-', array('align' => 'center'));
                     $html .= Display::tag('td', '-', array('align' => 'center'));
                     $html .= Display::tag('td', '-', array('align' => 'center'));
                     $html .= Display::tag('td', '-', array('align' => 'center'));
                 }
                 $html .= '</tr>';
             }
         } else {
             $html .= '<tr><td colspan="5" align="center">' . get_lang('NoEx') . '</td></tr>';
         }
         $html .= '</table>';
         // LP table results
         $html .= '<table class="data_table">';
         $html .= Display::tag('th', get_lang('Learnpaths'), array('class' => 'head', 'style' => 'color:#000'));
         $html .= Display::tag('th', get_lang('LatencyTimeSpent'), array('class' => 'head', 'style' => 'color:#000'));
         $html .= Display::tag('th', get_lang('Progress'), array('class' => 'head', 'style' => 'color:#000'));
         $html .= Display::tag('th', get_lang('Score'), array('class' => 'head', 'style' => 'color:#000'));
         $html .= Display::tag('th', get_lang('LastConnexion'), array('class' => 'head', 'style' => 'color:#000'));
         $html .= '</tr>';
         $list = new LearnpathList(api_get_user_id(), $course_info['code'], $session_id, 'publicated_on ASC', true);
         $lp_list = $list->get_flat_list();
         if (!empty($lp_list) > 0) {
             foreach ($lp_list as $lp_id => $learnpath) {
                 $progress = Tracking::get_avg_student_progress($user_id, $course, array($lp_id), $session_id);
                 $last_connection_in_lp = Tracking::get_last_connection_time_in_lp($user_id, $course, $lp_id, $session_id);
                 $time_spent_in_lp = Tracking::get_time_spent_in_lp($user_id, $course, array($lp_id), $session_id);
                 $percentage_score = Tracking::get_avg_student_score($user_id, $course, array($lp_id), $session_id);
                 if (is_numeric($percentage_score)) {
                     $percentage_score = $percentage_score . '%';
                 } else {
                     $percentage_score = '0%';
                 }
                 $time_spent_in_lp = api_time_to_hms($time_spent_in_lp);
                 $html .= '<tr class="row_even">';
                 $url = api_get_path(WEB_CODE_PATH) . "newscorm/lp_controller.php?cidReq={$course_code}&id_session={$session_id}&lp_id={$lp_id}&action=view";
                 if ($learnpath['lp_visibility'] == 0) {
                     $html .= Display::tag('td', $learnpath['lp_name']);
                 } else {
                     $html .= Display::tag('td', Display::url($learnpath['lp_name'], $url, array('target' => SESSION_LINK_TARGET)));
                 }
                 $html .= Display::tag('td', $time_spent_in_lp, array('align' => 'center'));
                 if (is_numeric($progress)) {
                     $progress = $progress . '%';
                 }
                 $html .= Display::tag('td', $progress, array('align' => 'center'));
                 $html .= Display::tag('td', $percentage_score);
                 $last_connection = '-';
                 if (!empty($last_connection_in_lp)) {
                     $last_connection = api_convert_and_format_date($last_connection_in_lp, DATE_TIME_FORMAT_LONG);
                 }
                 $html .= Display::tag('td', $last_connection, array('align' => 'center', 'width' => '180px'));
                 $html .= "</tr>";
             }
         } else {
             $html .= '<tr>
                     <td colspan="4" align="center">
                         ' . get_lang('NoLearnpath') . '
                     </td>
                   </tr>';
         }
         $html .= '</table>';
     }
     return $html;
 }
Exemple #6
0
 /**
  * Search the courses database for a course that matches the search term.
  * The search is done on the code, title and tutor field of the course table.
  * @param string $search_term The string that the user submitted, what we are looking for
  * @param array $limit
  * @return array An array containing a list of all the courses matching the the search term.
  */
 public function search_courses($search_term, $limit)
 {
     $courseTable = Database::get_main_table(TABLE_MAIN_COURSE);
     $extraFieldTable = Database::get_main_table(TABLE_EXTRA_FIELD);
     $extraFieldValuesTable = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
     $limitFilter = getLimitFilterFromArray($limit);
     // get course list auto-register
     $sql = "SELECT item_id\n                FROM {$extraFieldValuesTable} tcfv\n                INNER JOIN {$extraFieldTable} tcf ON tcfv.field_id =  tcf.id\n                WHERE\n                    tcf.variable = 'special_course' AND\n                    tcfv.value = 1 ";
     $special_course_result = Database::query($sql);
     if (Database::num_rows($special_course_result) > 0) {
         $special_course_list = array();
         while ($result_row = Database::fetch_array($special_course_result)) {
             $special_course_list[] = '"' . $result_row['item_id'] . '"';
         }
     }
     $without_special_courses = '';
     if (!empty($special_course_list)) {
         $without_special_courses = ' AND course.code NOT IN (' . implode(',', $special_course_list) . ')';
     }
     $search_term_safe = Database::escape_string($search_term);
     $sql_find = "SELECT * FROM {$courseTable}\n                    WHERE (\n                            code LIKE '%" . $search_term_safe . "%' OR\n                            title LIKE '%" . $search_term_safe . "%' OR\n                            tutor_name LIKE '%" . $search_term_safe . "%'\n                        )\n                        {$without_special_courses}\n                    ORDER BY title, visual_code ASC\n                    {$limitFilter}\n                    ";
     if (api_is_multiple_url_enabled()) {
         $url_access_id = api_get_current_access_url_id();
         if ($url_access_id != -1) {
             $tbl_url_rel_course = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
             $sql_find = "SELECT *\n                            FROM {$courseTable} as course\n                            INNER JOIN {$tbl_url_rel_course} as url_rel_course\n                            ON (url_rel_course.c_id = course.id)\n                            WHERE\n                                access_url_id = {$url_access_id} AND (\n                                    code LIKE '%" . $search_term_safe . "%' OR\n                                    title LIKE '%" . $search_term_safe . "%' OR\n                                    tutor_name LIKE '%" . $search_term_safe . "%'\n                                )\n                                {$without_special_courses}\n                            ORDER BY title, visual_code ASC\n                            {$limitFilter}\n                            ";
         }
     }
     $result_find = Database::query($sql_find);
     $courses = array();
     while ($row = Database::fetch_array($result_find)) {
         $row['registration_code'] = !empty($row['registration_code']);
         $count_users = count(CourseManager::get_user_list_from_course_code($row['code']));
         $count_connections_last_month = Tracking::get_course_connections_count($row['id'], 0, api_get_utc_datetime(time() - 30 * 86400));
         $point_info = CourseManager::get_course_ranking($row['id'], 0);
         $courses[] = array('real_id' => $row['id'], 'point_info' => $point_info, 'code' => $row['code'], 'directory' => $row['directory'], 'visual_code' => $row['visual_code'], 'title' => $row['title'], 'tutor' => $row['tutor_name'], 'subscribe' => $row['subscribe'], 'unsubscribe' => $row['unsubscribe'], 'registration_code' => $row['registration_code'], 'creation_date' => $row['creation_date'], 'visibility' => $row['visibility'], 'count_users' => $count_users, 'count_connections' => $count_connections_last_month);
     }
     return $courses;
 }
     }
     // Checking "id" field
     if (isset($user_data['id']) && !empty($user_data['id'])) {
         $user_id = $user_data['id'];
     }
     if (UserManager::is_user_id_valid($user_id)) {
         $clean_users[] = $user_id;
     } else {
         $invalid_users[] = $user_data;
     }
 }
 if (empty($invalid_users)) {
     $type = 'confirmation';
     $message = get_lang('ListOfUsersSubscribedToCourse');
     if ($unsubscribe_users) {
         $current_user_list = CourseManager::get_user_list_from_course_code($course_code, $session_id);
         if (!empty($current_user_list)) {
             $user_ids = array();
             foreach ($current_user_list as $user) {
                 $user_ids[] = $user['user_id'];
             }
             CourseManager::unsubscribe_user($user_ids, $course_code, $session_id);
         }
     }
     foreach ($clean_users as $userId) {
         $userInfo = api_get_user_info($userId);
         CourseManager::subscribe_user($userId, $course_code, STUDENT, $session_id);
         if (empty($session_id)) {
             //just to make sure
             if (CourseManager::is_user_subscribed_in_course($userId, $course_code)) {
                 $user_to_show[] = $userInfo['complete_name'];
	/**
	 * List courses
	 *
	 * @param string API secret key
	 * @param string A list of visibility filter we want to apply
	 * @return array An array with elements of the form ('id' => 'Course internal id', 'code' => 'Course code', 'title' => 'Course title', 'language' => 'Course language', 'visibility' => 'Course visibility',
	 * 'category_name' => 'Name of the category of the course', 'number_students' => 'Number of students in the course', 'external_course_id' => 'External course id')
	 */
	public function ListCourses($secret_key, $visibility = 'public,public-registered,private,closed') {
		$verifKey = $this->verifyKey($secret_key);
		if($verifKey instanceof WSError) {
			$this->handleError($verifKey);
		} else {
            $visibilities = split(',',$visibility);
            $vis = array('public' => '3', 'public-registered' => '2', 'private' => '1', 'closed' => '0');
            foreach ($visibilities as $p => $visibility) {
                $visibilities[$p] = $vis[$visibility];
            }
			$courses_result = array();
			$category_names = array();

			$courses = CourseManager::get_courses_list();
			foreach($courses as $course) {
                //skip elements that do not match required visibility
                if (!in_array($course['visibility'],$visibilities)) { continue; }
				$course_tmp = array();
				$course_tmp['id'] = $course['id'];
				$course_tmp['code'] = $course['code'];
				$course_tmp['title'] = $course['title'];
				$course_tmp['language'] = $course['course_language'];
				$course_tmp['visibility'] = $course['visibility'];

				// Determining category name
				if($category_names[$course['category_code']]) {
					$course_tmp['category_name'] = $category_names[$course['category_code']];
				} else {
					$category = CourseManager::get_course_category($course['category_code']);
					$category_names[$course['category_code']] = $category['name'];
					$course_tmp['category_name'] = $category['name'];
				}

				// Determining number of students registered in course
				$user_list = CourseManager::get_user_list_from_course_code($course['code'], 0);
				$course_tmp['number_students'] = count($user_list);

				// Determining external course id - this code misses the external course id field name
				// $course_tmp['external_course_id'] = CourseManager::get_course_extra_field_value($course_field_name, $course['code']);


				$courses_result[] = $course_tmp;
			}

			return $courses_result;
		}
	}
Exemple #9
0
    foreach ($items as $data) {
        $myUserId = $data['user_id'];
        $usersAdded[] = $myUserId;
        $userInfo = api_get_user_info($myUserId);
        $url = api_get_path(WEB_CODE_PATH) . 'work/add_user.php?action=delete&id=' . $workId . '&user_id=' . $myUserId;
        $link = Display::url('<em class="fa fa-trash"></em> ' . get_lang('Delete'), $url, array('class' => 'btn btn-danger btn-sm'));
        echo '<li class="list-group-item">' . $userInfo['complete_name_with_username'] . '<div class="pull-right">' . $link . '</div></li>';
    }
    echo '</ul>';
}
if (empty($sessionId)) {
    $status = STUDENT;
} else {
    $status = 0;
}
$userList = CourseManager::get_user_list_from_course_code($courseInfo['code'], $sessionId, null, null, $status);
$userToAddList = array();
foreach ($userList as $user) {
    if (!in_array($user['user_id'], $usersAdded)) {
        $userToAddList[] = $user;
    }
}
if (!empty($userToAddList)) {
    echo Display::page_subheader(get_lang('UsersToAdd'));
    echo '<ul class="list-group">';
    foreach ($userToAddList as $user) {
        $userName = api_get_person_name($user['firstname'], $user['lastname']) . ' (' . $user['username'] . ') ';
        $url = api_get_path(WEB_CODE_PATH) . 'work/add_user.php?action=add&id=' . $workId . '&user_id=' . $user['user_id'];
        $link = Display::url('<em class="fa fa-plus"></em> ' . get_lang('Add'), $url, array('class' => 'btn btn-primary btn-sm'));
        echo '<li class="list-group-item">' . $userName . '<div class="pull-right"> ' . $link . '</div></li>';
    }
Exemple #10
0
/**
 * @param string $courseCode
 * @param int $sessionId
 * @param int $groupId
 * @param int $start
 * @param int $limit
 * @param string $sidx
 * @param string $sord
 * @param $getCount
 * @return array|int
 */
function getWorkUserList($courseCode, $sessionId, $groupId, $start, $limit, $sidx, $sord, $getCount = false)
{
    if (!empty($groupId)) {
        $userList = GroupManager::get_users(
            $groupId,
            false,
            $start,
            $limit,
            $getCount,
            null,
            $sidx,
            $sord
        );
    } else {
        $limitString = null;
        if (!empty($start) && !empty($limit)) {
            $start = intval($start);
            $limit = intval($limit);
            $limitString = " LIMIT $start, $limit";
        }

        $orderBy = null;

        if (!empty($sidx) && !empty($sord)) {
            if (in_array($sidx, array('firstname', 'lastname'))) {
                $orderBy = "ORDER BY $sidx $sord";
            }
        }

        if (empty($sessionId)) {
            $userList = CourseManager::get_user_list_from_course_code(
                $courseCode,
                $sessionId,
                $limitString,
                $orderBy ,
                STUDENT,
                $getCount
            );
        } else {
            $userList = CourseManager::get_user_list_from_course_code(
                $courseCode,
                $sessionId,
                $limitString,
                $orderBy,
                0,
                $getCount
            );
        }

        if ($getCount == false) {
            $userList = array_keys($userList);
        }
    }
    return $userList;
}
Exemple #11
0
if (Database::num_rows($result) > 1) {
    Display::display_warning_message(get_lang('IdenticalSurveycodeWarning'));
}
// Invited / answered message
if ($survey_data['invited'] > 0 && !isset($_POST['submit'])) {
    $message = '<a href="' . api_get_path(WEB_CODE_PATH) . 'survey/survey_invitation.php?view=answered&amp;survey_id=' . $survey_data['survey_id'] . '">' . $survey_data['answered'] . '</a> ';
    $message .= get_lang('HaveAnswered') . ' ';
    $message .= '<a href="' . api_get_path(WEB_CODE_PATH) . 'survey/survey_invitation.php?view=invited&amp;survey_id=' . $survey_data['survey_id'] . '">' . $survey_data['invited'] . '</a> ';
    $message .= get_lang('WereInvited');
    Display::display_normal_message($message, false);
}
// Building the form for publishing the survey
$form = new FormValidator('publish_form', 'post', api_get_self() . '?survey_id=' . $survey_id . '&' . api_get_cidReq());
$form->addElement('header', '', $tool_name);
// Course users
$complete_user_list = CourseManager::get_user_list_from_course_code(api_get_course_id(), api_get_session_id(), '', api_sort_by_first_name() ? 'ORDER BY firstname' : 'ORDER BY lastname');
$possible_users = array();
foreach ($complete_user_list as &$user) {
    $possible_users[$user['user_id']] = api_get_person_name($user['firstname'], $user['lastname']);
}
$users = $form->addElement('advmultiselect', 'course_users', get_lang('CourseUsers'), $possible_users, 'style="width: 250px; height: 200px;"');
$users->setElementTemplate('
{javascript}
<table{class}>
<!-- BEGIN label_2 --><tr><th>{label_2}</th><!-- END label_2 -->
<!-- BEGIN label_3 --><th>&nbsp;</th><th>{label_3}</th></tr><!-- END label_3 -->
<tr>
  <td valign="top">{unselected}</td>
  <td align="center">{add}<br /><br />{remove}</td>
  <td valign="top">{selected}</td>
</tr>
 /**
  *
  * @Route("/results")
  * @Method({"GET"})
  */
 public function resultsAction()
 {
     $breadcrumbs = array(array('name' => get_lang('Curriculum'), 'url' => array('route' => 'curriculum_user.controller:indexAction', 'routeParameters' => array('course' => $this->getCourse()->getCode()))), array('name' => get_lang('Categories'), 'url' => array('route' => 'curriculum_category.controller:indexAction', 'routeParameters' => array('course' => $this->getCourse()->getCode()))), array('name' => get_lang('Results')));
     $this->setBreadcrumb($breadcrumbs);
     if (!api_is_allowed_to_edit(true, true, true)) {
         $this->abort('405');
     }
     $session = $this->getSession();
     $sessionId = 0;
     if ($session) {
         $sessionId = $this->getSession()->getId();
     }
     // @todo move in a function
     $users = \CourseManager::get_user_list_from_course_code($this->getCourse()->getCode(), $sessionId, null, null, STUDENT);
     $qb = $this->getManager()->createQueryBuilder()->select('node.id, u.userId, SUM(i.score) as score')->from('Entity\\CurriculumCategory', 'node')->innerJoin('node.course', 'c')->innerJoin('node.items', 'i')->innerJoin('i.userItems', 'u')->groupby('u.userId');
     $this->setCourseParameters($qb, 'node');
     $query = $qb->getQuery();
     $userResults = $query->getResult();
     $userResultsByUserId = array();
     if (!empty($userResults)) {
         foreach ($userResults as $item) {
             $userResultsByUserId[$item['userId']] = $item['score'];
         }
     }
     if (!empty($users)) {
         foreach ($users as &$user) {
             if (!empty($userResultsByUserId)) {
                 if (isset($userResultsByUserId[$user['user_id']])) {
                     $user['score'] = $userResultsByUserId[$user['user_id']];
                 } else {
                     $user['score'] = 0;
                 }
             }
         }
     }
     $template = $this->getTemplate();
     $template->assign('users', $users);
     $response = $template->render_template($this->getTemplatePath() . 'results.tpl');
     return new Response($response, 200, array());
 }
 }
 if (!empty($courses)) {
     if (!file_exists($archivePath)) {
         mkdir($archivePath, api_get_permissions_for_new_directories(), true);
     }
     $archiveFile = 'export_courses_list_' . date('Y-m-d_H-i-s') . '.' . $file_type;
     $fp = fopen($archivePath . $archiveFile, 'w');
     if ($file_type == 'csv') {
         $add = "Code;Title;CourseCategory;Teacher;Language;OtherTeachers;Users;" . PHP_EOL;
         foreach ($courses as $course) {
             $course['code'] = str_replace(';', ',', $course['code']);
             $course['title'] = str_replace(';', ',', $course['title']);
             $course['category_code'] = str_replace(';', ',', $course['category_code']);
             $course['tutor_name'] = str_replace(';', ',', $course['tutor_name']);
             $course['course_language'] = str_replace(';', ',', $course['course_language']);
             $course['course_users'] = CourseManager::get_user_list_from_course_code($course['code']);
             $course['students'] = '';
             $course['teachers'] = '';
             foreach ($course['course_users'] as $user) {
                 if ($user['status_rel'] == 1) {
                     $course['teachers'] .= $user['username'] . '|';
                 } else {
                     $course['students'] .= $user['username'] . '|';
                 }
             }
             $course['students'] = substr($course['students'], 0, -1);
             $course['teachers'] = substr($course['teachers'], 0, -1);
             $add .= $course['code'] . ';' . $course['title'] . ';' . $course['category_code'] . ';' . $course['tutor_name'] . ';' . $course['course_language'] . ';' . $course['teachers'] . ';' . $course['students'] . ';' . PHP_EOL;
         }
         fputs($fp, $add);
     }
Exemple #14
0
 /**
  * Function wizard individual assignment
  * @author Juan Carlos Raña <*****@*****.**>
  */
 public function auto_add_page_users($values)
 {
     $assignment_type = $values['assignment'];
     $session_id = $this->session_id;
     $groupId = api_get_group_id();
     if ($groupId == 0) {
         //extract course members
         if (!empty($session_id)) {
             $a_users_to_add = CourseManager::get_user_list_from_course_code(api_get_course_id(), $session_id);
         } else {
             $a_users_to_add = CourseManager::get_user_list_from_course_code(api_get_course_id(), 0);
         }
     } else {
         //extract group members
         $subscribed_users = GroupManager::get_subscribed_users($groupId);
         $subscribed_tutors = GroupManager::get_subscribed_tutors($groupId);
         $a_users_to_add_with_duplicates = array_merge($subscribed_users, $subscribed_tutors);
         //remove duplicates
         $a_users_to_add = $a_users_to_add_with_duplicates;
         //array_walk($a_users_to_add, create_function('&$value,$key', '$value = json_encode($value);'));
         $a_users_to_add = array_unique($a_users_to_add);
         //array_walk($a_users_to_add, create_function('&$value,$key', '$value = json_decode($value, true);'));
     }
     $all_students_pages = array();
     // Data about teacher
     $userId = api_get_user_id();
     $userinfo = api_get_user_info($userId);
     $username = api_htmlentities(sprintf(get_lang('LoginX'), $userinfo['username'], ENT_QUOTES));
     $name = $userinfo['complete_name'] . " - " . $username;
     $photo = '<img src="' . $userinfo['avatar'] . '" alt="' . $name . '"  width="40" height="50" align="top" title="' . $name . '"  />';
     // teacher assignment title
     $title_orig = $values['title'];
     // teacher assignment reflink
     $link2teacher = $values['title'] = $title_orig . "_uass" . $userId;
     // first: teacher name, photo, and assignment description (original content)
     $content_orig_A = '<div align="center" style="background-color: #F5F8FB; border:solid; border-color: #E6E6E6">
     <table border="0">
         <tr><td style="font-size:24px">' . get_lang('AssignmentDesc') . '</td></tr>
         <tr><td>' . $photo . '<br />' . Display::tag('span', api_get_person_name($userinfo['firstname'], $userinfo['lastname']), array('title' => $username)) . '</td></tr>
     </table></div>';
     $content_orig_B = '<br/><div align="center" style="font-size:24px">' . get_lang('AssignmentDescription') . ': ' . $title_orig . '</div><br/>' . $_POST['content'];
     //Second: student list (names, photo and links to their works).
     //Third: Create Students work pages.
     foreach ($a_users_to_add as $o_user_to_add) {
         if ($o_user_to_add['user_id'] != $userId) {
             // except that puts the task
             $assig_user_id = $o_user_to_add['user_id'];
             // identifies each page as created by the student, not by teacher
             $userPicture = UserManager::getUserPicture($assig_user_id);
             $username = api_htmlentities(sprintf(get_lang('LoginX'), $o_user_to_add['username'], ENT_QUOTES));
             $name = api_get_person_name($o_user_to_add['firstname'], $o_user_to_add['lastname']) . " . " . $username;
             $photo = '<img src="' . $userPicture . '" alt="' . $name . '"  width="40" height="50" align="bottom" title="' . $name . '"  />';
             $is_tutor_of_group = GroupManager::is_tutor_of_group($assig_user_id, $groupId);
             //student is tutor
             $is_tutor_and_member = GroupManager::is_tutor_of_group($assig_user_id, $groupId) && GroupManager::is_subscribed($assig_user_id, $groupId);
             // student is tutor and member
             if ($is_tutor_and_member) {
                 $status_in_group = get_lang('GroupTutorAndMember');
             } else {
                 if ($is_tutor_of_group) {
                     $status_in_group = get_lang('GroupTutor');
                 } else {
                     $status_in_group = " ";
                     //get_lang('GroupStandardMember')
                 }
             }
             if ($assignment_type == 1) {
                 $values['title'] = $title_orig;
                 $values['content'] = '<div align="center" style="background-color: #F5F8FB; border:solid; border-color: #E6E6E6">
                 <table border="0">
                 <tr><td style="font-size:24px">' . get_lang('AssignmentWork') . '</td></tr>
                 <tr><td>' . $photo . '<br />' . $name . '</td></tr></table>
                 </div>[[' . $link2teacher . ' | ' . get_lang('AssignmentLinktoTeacherPage') . ']] ';
                 //If $content_orig_B is added here, the task written by the professor was copied to the page of each student. TODO: config options
                 // AssignmentLinktoTeacherPage
                 $all_students_pages[] = '<li>' . Display::tag('span', strtoupper($o_user_to_add['lastname']) . ', ' . $o_user_to_add['firstname'], array('title' => $username)) . ' [[' . $_POST['title'] . "_uass" . $assig_user_id . ' | ' . $photo . ']] ' . $status_in_group . '</li>';
                 //don't change this line without guaranteeing that users will be ordered by last names in the following format (surname, name)
                 $values['assignment'] = 2;
             }
             $this->assig_user_id = $assig_user_id;
             self::save_new_wiki($values);
         }
     }
     foreach ($a_users_to_add as $o_user_to_add) {
         if ($o_user_to_add['user_id'] == $userId) {
             $assig_user_id = $o_user_to_add['user_id'];
             if ($assignment_type == 1) {
                 $values['title'] = $title_orig;
                 $values['comment'] = get_lang('AssignmentDesc');
                 sort($all_students_pages);
                 $values['content'] = $content_orig_A . $content_orig_B . '<br/>
                 <div align="center" style="font-size:18px; background-color: #F5F8FB; border:solid; border-color:#E6E6E6">
                 ' . get_lang('AssignmentLinkstoStudentsPage') . '
                 </div><br/>
                 <div style="background-color: #F5F8FB; border:solid; border-color:#E6E6E6">
                 <ol>' . implode($all_students_pages) . '</ol>
                 </div>
                 <br/>';
                 $values['assignment'] = 1;
             }
             $this->assig_user_id = $assig_user_id;
             self::save_new_wiki($values);
         }
     }
 }
 /**
  * @param array $form
  * @param $to_already_selected
  */
 public static function show_to_form($form, $to_already_selected)
 {
     $order = 'lastname';
     if (api_is_western_name_order()) {
         $order = 'firstname';
     }
     $user_list = CourseManager::get_user_list_from_course_code(api_get_course_id(), api_get_session_id(), null, $order);
     $group_list = CourseManager::get_group_list_of_course(api_get_course_id(), api_get_session_id());
     self::construct_not_selected_select_form_validator($form, $group_list, $user_list, $to_already_selected);
 }
             $new_result[] = $row;
         }
         $result = $new_result;
     }
     break;
 case 'get_user_course_report':
     $columns = array('course', 'user', 'time', 'certificate', 'progress_100', 'progress');
     $column_names = array(get_lang('Course'), get_lang('User'), get_lang('ManHours'), get_lang('CertificateGenerated'), get_lang('Approved'), get_lang('CourseAdvance'));
     $extra_fields = UserManager::get_extra_fields(0, 100, null, null, true, true);
     if (!empty($extra_fields)) {
         foreach ($extra_fields as $extra) {
             $columns[] = $extra['1'];
             $column_names[] = $extra['3'];
         }
     }
     $result = CourseManager::get_user_list_from_course_code(null, null, "LIMIT {$start}, {$limit}", " {$sidx} {$sord}", null, null, true);
     break;
 case 'get_user_skill_ranking':
     $columns = array('photo', 'firstname', 'lastname', 'skills_acquired', 'currently_learning', 'rank');
     $result = $skill->get_user_list_skill_ranking($start, $limit, $sidx, $sord, $where_condition);
     $result = ArrayClass::msort($result, 'skills_acquired', 'asc');
     $skills_in_course = array();
     if (!empty($result)) {
         //$counter = 1;
         foreach ($result as &$item) {
             $user_info = api_get_user_info($item['user_id']);
             $personal_course_list = UserManager::get_personal_session_course_list($item['user_id']);
             $count_skill_by_course = array();
             foreach ($personal_course_list as $course_item) {
                 if (!isset($skills_in_course[$course_item['code']])) {
                     $count_skill_by_course[$course_item['code']] = $skill->get_count_skills_by_course($course_item['code']);
/**
 * Get the users to display on the current page.
 */
function get_user_data($from, $number_of_items, $column, $direction)
{
    global $_configuration;
    $url_access_id = api_get_current_access_url_id();
    $course_code = api_get_course_id();
    $courseId = api_get_course_int_id();
    $session_id = api_get_session_id();
    // Database table definitions
    $user_table = Database::get_main_table(TABLE_MAIN_USER);
    $course_user_table = Database::get_main_table(TABLE_MAIN_COURSE_USER);
    $tbl_session_rel_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
    $table_user_field_values = Database::get_main_table(TABLE_MAIN_USER_FIELD_VALUES);
    $tbl_url_rel_user = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
    // adding teachers
    $is_western_name_order = api_is_western_name_order();
    if (api_get_setting('show_email_addresses') == 'true') {
        $select_fields = "u.user_id              AS col0,\n                u.official_code        AS col1,\n                " . ($is_western_name_order ? "u.firstname         AS col2,\n                u.lastname             AS col3," : "u.lastname          AS col2,\n                u.firstname            AS col3,") . "\n                u.email \t           AS col4,\n                u.active               AS col5,\n                u.user_id              AS col6";
    } else {
        $select_fields = "u.user_id              AS col0,\n                u.official_code        AS col1,\n                " . ($is_western_name_order ? "u.firstname         AS col2,\n                u.lastname             AS col3," : "u.lastname          AS col2,\n                u.firstname            AS col3,") . "\n                u.active               AS col4,\n                u.user_id              AS col5";
    }
    if (isset($_REQUEST['type']) && $_REQUEST['type'] == 'teacher') {
        // adding a teacher through a session
        if (!empty($session_id)) {
            $sql = "SELECT {$select_fields}\n\t\t\t\t\tFROM {$user_table} u\n\t\t\t\t\tLEFT JOIN {$tbl_session_rel_course_user} cu on u.user_id = cu.id_user AND cu.c_id ='" . $courseId . "' AND id_session ='" . $session_id . "'\n                    INNER JOIN  {$tbl_url_rel_user} as url_rel_user ON (url_rel_user.user_id = u.user_id) ";
            // applying the filter of the additional user profile fields
            if (isset($_GET['subscribe_user_filter_value']) and !empty($_GET['subscribe_user_filter_value']) and api_get_setting('ProfilingFilterAddingUsers') == 'true') {
                $field_identification = explode('*', $_GET['subscribe_user_filter_value']);
                $sql .= "\n\t\t\t\t\tLEFT JOIN {$table_user_field_values} field_values\n\t\t\t\t\t\tON field_values.user_id = u.user_id\n\t\t\t\t\tWHERE cu.id_user IS NULL AND u.status=1 AND (u.official_code <> 'ADMIN' OR u.official_code IS NULL)\n\t\t\t\t\t\tAND field_values.field_id = '" . Database::escape_string($field_identification[0]) . "'\n\t\t\t\t\t\tAND field_values.field_value = '" . Database::escape_string($field_identification[1]) . "'";
            } else {
                $sql .= "WHERE cu.id_user IS NULL AND u.status=1 AND (u.official_code <> 'ADMIN' OR u.official_code IS NULL) ";
            }
            $sql .= " AND access_url_id= {$url_access_id}";
        } else {
            // adding a teacher NOT through a session
            $sql = "SELECT {$select_fields}\n                    FROM {$user_table} u\n                    LEFT JOIN {$course_user_table} cu on u.user_id = cu.user_id and cu.c_id = '" . $courseId . "'";
            // applying the filter of the additional user profile fields
            if (isset($_GET['subscribe_user_filter_value']) and !empty($_GET['subscribe_user_filter_value']) and api_get_setting('ProfilingFilterAddingUsers') == 'true') {
                $field_identification = explode('*', $_GET['subscribe_user_filter_value']);
                $sql .= "\n\t\t\t\t\t\tLEFT JOIN {$table_user_field_values} field_values\n\t\t\t\t\t\t\tON field_values.user_id = u.user_id\n\t\t\t\t\t\tWHERE cu.user_id IS NULL AND u.status<>" . DRH . "\n\t\t\t\t\t\t\tAND field_values.field_id = '" . Database::escape_string($field_identification[0]) . "'\n\t\t\t\t\t\t\tAND field_values.field_value = '" . Database::escape_string($field_identification[1]) . "'";
            } else {
                $sql .= "WHERE cu.user_id IS NULL AND u.status<>" . DRH . " ";
            }
            // adding a teacher NOT trough a session on a portal with multiple URLs
            if ($_configuration['multiple_access_urls']) {
                if ($url_access_id != -1) {
                    $sql = "SELECT {$select_fields}\n\t\t\t\t\t\tFROM {$user_table} u\n\t\t\t\t\t\tLEFT JOIN {$course_user_table} cu on u.user_id = cu.user_id and cu.c_id ='" . $courseId . "'\n\t\t\t\t\t\tINNER JOIN  {$tbl_url_rel_user} as url_rel_user ON (url_rel_user.user_id = u.user_id) ";
                    // applying the filter of the additional user profile fields
                    if (isset($_GET['subscribe_user_filter_value']) and !empty($_GET['subscribe_user_filter_value']) and api_get_setting('ProfilingFilterAddingUsers') == 'true') {
                        $field_identification = explode('*', $_GET['subscribe_user_filter_value']);
                        $sql .= "\n\t\t\t\t\t\t\tLEFT JOIN {$table_user_field_values} field_values\n\t\t\t\t\t\t\t\tON field_values.user_id = u.user_id\n\t\t\t\t\t\t\tWHERE cu.user_id IS NULL AND u.status<>" . DRH . "\n\t\t\t\t\t\t\t\tAND field_values.field_id = '" . Database::escape_string($field_identification[0]) . "'\n\t\t\t\t\t\t\t\tAND field_values.field_value = '" . Database::escape_string($field_identification[1]) . "'";
                    } else {
                        $sql .= "WHERE cu.user_id IS NULL AND u.status<>" . DRH . " AND access_url_id= {$url_access_id} ";
                    }
                }
            }
        }
    } else {
        // adding a student
        if (!empty($session_id)) {
            $sql = "SELECT {$select_fields}\n                    FROM {$user_table} u\n                    LEFT JOIN {$tbl_session_rel_course_user} cu ON u.user_id = cu.id_user AND cu.c_id ='" . $courseId . "' AND id_session ='" . $session_id . "' ";
            if (api_is_multiple_url_enabled()) {
                $sql .= " INNER JOIN  {$tbl_url_rel_user} as url_rel_user ON (url_rel_user.user_id = u.user_id) ";
            }
            // applying the filter of the additional user profile fields
            if (isset($_GET['subscribe_user_filter_value']) and !empty($_GET['subscribe_user_filter_value'])) {
                $field_identification = explode('*', $_GET['subscribe_user_filter_value']);
                $sql .= "\n                    LEFT JOIN {$table_user_field_values} field_values\n                        ON field_values.user_id = u.user_id\n                    WHERE cu.id_user IS NULL AND u.status<>" . DRH . " AND (u.official_code <> 'ADMIN' OR u.official_code IS NULL)\n                        AND field_values.field_id = '" . Database::escape_string($field_identification[0]) . "'\n                        AND field_values.field_value = '" . Database::escape_string($field_identification[1]) . "'";
            } else {
                $sql .= "WHERE cu.id_user IS NULL AND u.status<>" . DRH . " AND (u.official_code <> 'ADMIN' OR u.official_code IS NULL) ";
            }
            if (api_is_multiple_url_enabled()) {
                $sql .= "AND access_url_id = {$url_access_id}";
            }
        } else {
            $sql = "SELECT {$select_fields}\n                    FROM {$user_table} u\n                    LEFT JOIN {$course_user_table} cu on u.user_id = cu.user_id and cu.c_id ='" . $courseId . "'";
            // applying the filter of the additional user profile fields
            if (isset($_GET['subscribe_user_filter_value']) and !empty($_GET['subscribe_user_filter_value'])) {
                $field_identification = explode('*', $_GET['subscribe_user_filter_value']);
                $sql .= "\n\t\t\t\t\tLEFT JOIN {$table_user_field_values} field_values\n\t\t\t\t\t\tON field_values.user_id = u.user_id\n\t\t\t\t\tWHERE cu.user_id IS NULL AND u.status<>" . DRH . "\n\t\t\t\t\t\tAND field_values.field_id = '" . Database::escape_string($field_identification[0]) . "'\n\t\t\t\t\t\tAND field_values.field_value = '" . Database::escape_string($field_identification[1]) . "'";
            } else {
                $sql .= "WHERE cu.user_id IS NULL AND u.status<>" . DRH . " ";
            }
            //showing only the courses of the current Chamilo access_url_id
            if (api_is_multiple_url_enabled()) {
                if ($url_access_id != -1) {
                    $sql = "SELECT {$select_fields}\n\t\t\t\t\t\tFROM {$user_table} u\n\t\t\t\t\t\tLEFT JOIN {$course_user_table} cu on u.user_id = cu.user_id and cu.c_id ='" . $courseId . "'\n\t\t\t\t\t\tINNER JOIN  {$tbl_url_rel_user} as url_rel_user\n\t\t\t\t\t\tON (url_rel_user.user_id = u.user_id) ";
                    // applying the filter of the additional user profile fields
                    if (isset($_GET['subscribe_user_filter_value']) and !empty($_GET['subscribe_user_filter_value']) and api_get_setting('ProfilingFilterAddingUsers') == 'true') {
                        $field_identification = explode('*', $_GET['subscribe_user_filter_value']);
                        $sql .= "\n\t\t\t\t\t\t\tLEFT JOIN {$table_user_field_values} field_values\n\t\t\t\t\t\t\t\tON field_values.user_id = u.user_id\n\t\t\t\t\t\t\tWHERE cu.user_id IS NULL AND u.status<>" . DRH . "\n\t\t\t\t\t\t\t\tAND field_values.field_id = '" . Database::escape_string($field_identification[0]) . "'\n\t\t\t\t\t\t\t\tAND field_values.field_value = '" . Database::escape_string($field_identification[1]) . "' AND access_url_id= {$url_access_id}  ";
                    } else {
                        $sql .= "WHERE  cu.user_id IS NULL AND u.status<>" . DRH . " AND access_url_id= {$url_access_id} ";
                    }
                }
            }
        }
    }
    // adding additional WHERE statements to the SQL for the search functionality
    if (isset($_REQUEST['keyword'])) {
        $keyword = Database::escape_string(trim($_REQUEST['keyword']));
        $sql .= " AND (firstname LIKE '%" . $keyword . "%' OR lastname LIKE '%" . $keyword . "%'   OR email LIKE '%" . $keyword . "%'  OR username LIKE '%" . $keyword . "%'  OR official_code LIKE '%" . $keyword . "%')";
        if (api_get_setting('ProfilingFilterAddingUsers') == 'true') {
            // we also want to search for users who have something in their profile fields that matches the keyword
            $additional_users = search_additional_profile_fields($keyword);
        }
        // getting all the users of the course (to make sure that we do not display users that are already in the course)
        if (!empty($session_id)) {
            $a_course_users = CourseManager::get_user_list_from_course_code($course_code, $session_id);
        } else {
            $a_course_users = CourseManager::get_user_list_from_course_code($course_code, 0);
        }
        foreach ($a_course_users as $user_id => $course_user) {
            $users_of_course[] = $course_user['user_id'];
        }
    }
    $sql .= " AND u.status != " . ANONYMOUS . " ";
    // Sorting and pagination (used by the sortable table)
    $sql .= " ORDER BY col{$column} {$direction} ";
    $sql .= " LIMIT {$from},{$number_of_items}";
    $res = Database::query($sql);
    $users = array();
    while ($user = Database::fetch_row($res)) {
        $users[] = $user;
        $_SESSION['session_user_id'][] = $user[0];
        if ($is_western_name_order) {
            $_SESSION['session_user_name'][] = api_get_person_name($user[2], $user[3]);
        } else {
            $_SESSION['session_user_name'][] = api_get_person_name($user[3], $user[2]);
        }
    }
    // adding additional users based on the search on the additional profile fields
    if (isset($_REQUEST['keyword'])) {
        if (isset($additional_users) && is_array($additional_users)) {
            foreach ($additional_users as $additional_user_key => $additional_user_value) {
                if (!in_array($additional_user_key, $_SESSION['session_user_id']) and !in_array($additional_user_key, $users_of_course)) {
                    $users[] = array($additional_user_value['col0'], $additional_user_value['col1'], $additional_user_value['col2'] . '*', $additional_user_value['col3'] . '*', $additional_user_value['col4'], $additional_user_value['col5'], $additional_user_value['col6']);
                }
            }
        }
    }
    return $users;
}
 /**
  * Function used by SortableTable to generate the data to display
  * @param int $from
  * @param int $per_page
  * @param int $column
  * @param string $direction
  * @param int $sort
  * @return array|mixed
  */
 public function get_table_data($from = 1, $per_page = null, $column = null, $direction = null, $sort = null)
 {
     //variables load in index.php
     global $certificate_min_score;
     // determine sorting type
     $col_adjust = api_is_allowed_to_edit() ? 1 : 0;
     // By id
     $this->column = 5;
     switch ($this->column) {
         // Type
         case 0 + $col_adjust:
             $sorting = GradebookDataGenerator::GDG_SORT_TYPE;
             break;
         case 1 + $col_adjust:
             $sorting = GradebookDataGenerator::GDG_SORT_NAME;
             break;
         case 2 + $col_adjust:
             $sorting = GradebookDataGenerator::GDG_SORT_DESCRIPTION;
             break;
         case 3 + $col_adjust:
             $sorting = GradebookDataGenerator::GDG_SORT_WEIGHT;
             break;
         case 4 + $col_adjust:
             $sorting = GradebookDataGenerator::GDG_SORT_DATE;
         case 5 + $col_adjust:
             $sorting = GradebookDataGenerator::GDG_SORT_ID;
             break;
     }
     if ($this->direction == 'DESC') {
         $sorting |= GradebookDataGenerator::GDG_SORT_DESC;
     } else {
         $sorting |= GradebookDataGenerator::GDG_SORT_ASC;
     }
     // Status of user in course.
     $user_id = $this->userId;
     $course_code = api_get_course_id();
     $session_id = api_get_session_id();
     $status_user = api_get_status_of_user_in_course(api_get_user_id(), api_get_course_int_id());
     if (empty($session_id)) {
         $statusToFilter = STUDENT;
     } else {
         $statusToFilter = 0;
     }
     if (empty($this->studentList)) {
         $studentList = CourseManager::get_user_list_from_course_code($course_code, $session_id, null, null, $statusToFilter);
         $this->studentList = $studentList;
     }
     $this->datagen->userId = $this->userId;
     $data_array = $this->datagen->get_data($sorting, $from, $this->per_page, false, $this->studentList);
     // generate the data to display
     $sortable_data = array();
     $weight_total_links = 0;
     $main_categories = array();
     $main_cat = Category::load(null, null, $course_code, null, null, $session_id, 'ORDER BY id');
     $total_categories_weight = 0;
     $scoredisplay = ScoreDisplay::instance();
     $totalResult = [0, 0];
     $totalBest = [0, 0];
     $totalAverage = [0, 0];
     $type = 'detail';
     if ($this->exportToPdf) {
         $type = 'simple';
     }
     // Categories.
     if (!empty($data_array)) {
         foreach ($data_array as $data) {
             // list of items inside the gradebook (exercises, lps, forums, etc)
             $row = array();
             /** @var AbstractLink $item */
             $item = $mainCategory = $data[0];
             //if the item is invisible, wrap it in a span with class invisible
             $invisibility_span_open = api_is_allowed_to_edit() && $item->is_visible() == '0' ? '<span class="invisible">' : '';
             $invisibility_span_close = api_is_allowed_to_edit() && $item->is_visible() == '0' ? '</span>' : '';
             // Id
             if ($this->teacherView) {
                 if ($this->exportToPdf == false) {
                     $row[] = $this->build_id_column($item);
                 }
             }
             // Type.
             $row[] = $this->build_type_column($item);
             // Name.
             if (get_class($item) == 'Category') {
                 $row[] = $invisibility_span_open . '<strong>' . $item->get_name() . '</strong>' . $invisibility_span_close;
                 $main_categories[$item->get_id()]['name'] = $item->get_name();
             } else {
                 $name = $this->build_name_link($item, $type);
                 $row[] = $invisibility_span_open . $name . $invisibility_span_close;
                 $main_categories[$item->get_id()]['name'] = $name;
             }
             $this->dataForGraph['categories'][] = $item->get_name();
             $main_categories[$item->get_id()]['weight'] = $item->get_weight();
             $total_categories_weight += $item->get_weight();
             // Description.
             if ($this->exportToPdf == false) {
                 $row[] = $invisibility_span_open . $data[2] . $invisibility_span_close;
             }
             // Weight.
             $weight = $scoredisplay->display_score(array($data['3'], $this->currentcat->get_weight()), SCORE_SIMPLE, SCORE_BOTH, true);
             if ($this->teacherView) {
                 $row[] = $invisibility_span_open . Display::tag('p', $weight, array('class' => 'score')) . $invisibility_span_close;
             } else {
                 $row[] = $invisibility_span_open . $weight . $invisibility_span_close;
             }
             $category_weight = $item->get_weight();
             $mainCategoryWeight = $main_cat[0]->get_weight();
             if ($this->teacherView) {
                 $weight_total_links += $data[3];
             } else {
                 $cattotal = Category::load($_GET['selectcat']);
                 $scoretotal = $cattotal[0]->calc_score($this->userId);
                 $item_value = $scoredisplay->display_score($scoretotal, SCORE_SIMPLE);
             }
             // Edit (for admins).
             if ($this->teacherView) {
                 $cat = new Category();
                 $show_message = $cat->show_message_resource_delete($item->get_course_code());
                 if ($show_message === false) {
                     $row[] = $this->build_edit_column($item);
                 }
             } else {
                 $score = $item->calc_score($this->userId);
                 if (!empty($score[1])) {
                     $completeScore = $scoredisplay->display_score($score, SCORE_DIV_PERCENT);
                     $score = $score[0] / $score[1] * $item->get_weight();
                     $score = $scoredisplay->display_score(array($score, null), SCORE_SIMPLE);
                     $scoreToDisplay = Display::tip($score, $completeScore);
                 } else {
                     $scoreToDisplay = '-';
                     $categoryScore = null;
                 }
                 // Students get the results and certificates columns
                 //if (count($this->evals_links) > 0 && $status_user != 1) {
                 if (1) {
                     $value_data = isset($data[4]) ? $data[4] : null;
                     $best = isset($data['best']) ? $data['best'] : null;
                     $average = isset($data['average']) ? $data['average'] : null;
                     $ranking = isset($data['ranking']) ? $data['ranking'] : null;
                     $totalResult = [$totalResult[0] + $data['result_score_weight'][0], $totalResult[1] + $data['result_score_weight'][1]];
                     $totalBest = [$totalBest[0] + $data['best_score'][0], $totalBest[1] + $data['best_score'][1]];
                     $totalAverage = [$totalAverage[0] + $data['average_score'][0], $totalAverage[1] + $data['average_score'][1]];
                     // Student result
                     $row[] = $value_data;
                     $totalResultAverageValue = strip_tags($scoredisplay->display_score($totalResult, SCORE_AVERAGE));
                     $this->dataForGraph['my_result'][] = (double) str_replace('%', '', $totalResultAverageValue);
                     $totalAverageValue = strip_tags($scoredisplay->display_score($totalAverage, SCORE_AVERAGE));
                     $this->dataForGraph['average'][] = (double) str_replace('%', '', $totalAverageValue);
                     // Ranking
                     $row[] = $ranking;
                     // Best
                     $row[] = $best;
                     // Average
                     $row[] = $average;
                     if (get_class($item) == 'Category') {
                         if ($this->exportToPdf == false) {
                             $row[] = $this->build_edit_column($item);
                         }
                     }
                 } else {
                     $row[] = $scoreToDisplay;
                     if (!empty($this->cats)) {
                         if ($this->exportToPdf == false) {
                             $row[] = $this->build_edit_column($item);
                         }
                     }
                 }
             }
             // Category added.
             $sortable_data[] = $row;
             // Loading children
             if (get_class($item) == 'Category') {
                 $course_code = api_get_course_id();
                 $session_id = api_get_session_id();
                 $parent_id = $item->get_id();
                 $cats = Category::load($parent_id, null, null, null, null, null);
                 if (isset($cats[0])) {
                     $allcat = $cats[0]->get_subcategories($this->userId, $course_code, $session_id);
                     $alleval = $cats[0]->get_evaluations($this->userId);
                     $alllink = $cats[0]->get_links($this->userId);
                     $sub_cat_info = new GradebookDataGenerator($allcat, $alleval, $alllink);
                     $sub_cat_info->userId = $user_id;
                     $data_array2 = $sub_cat_info->get_data($sorting, $from, $this->per_page, false, $this->studentList);
                     $total_weight = 0;
                     // Links.
                     foreach ($data_array2 as $data) {
                         $row = array();
                         $item = $data[0];
                         //if the item is invisible, wrap it in a span with class invisible
                         $invisibility_span_open = api_is_allowed_to_edit() && $item->is_visible() == '0' ? '<span class="invisible">' : '';
                         $invisibility_span_close = api_is_allowed_to_edit() && $item->is_visible() == '0' ? '</span>' : '';
                         if (isset($item)) {
                             $main_categories[$parent_id]['children'][$item->get_id()]['name'] = $item->get_name();
                             $main_categories[$parent_id]['children'][$item->get_id()]['weight'] = $item->get_weight();
                         }
                         if ($this->teacherView) {
                             if ($this->exportToPdf == false) {
                                 $row[] = $this->build_id_column($item);
                             }
                         }
                         // Type
                         $row[] = $this->build_type_column($item, array('style' => 'padding-left:5px'));
                         // Name.
                         $row[] = $invisibility_span_open . "&nbsp;&nbsp;&nbsp;  " . $this->build_name_link($item, $type) . $invisibility_span_close;
                         // Description.
                         if ($this->exportToPdf == false) {
                             $row[] = $invisibility_span_open . $data[2] . $invisibility_span_close;
                         }
                         $weight = $data[3];
                         $total_weight += $weight;
                         // Weight
                         $row[] = $invisibility_span_open . $weight . $invisibility_span_close;
                         if ($this->teacherView) {
                             //$weight_total_links += intval($data[3]);
                         } else {
                             $cattotal = Category::load($_GET['selectcat']);
                             $scoretotal = $cattotal[0]->calc_score($this->userId);
                             $item_value = $scoretotal[0];
                         }
                         // Admins get an edit column.
                         if (api_is_allowed_to_edit(null, true) && isset($_GET['user_id']) == false && (isset($_GET['action']) && $_GET['action'] != 'export_all' || !isset($_GET['action']))) {
                             $cat = new Category();
                             $show_message = $cat->show_message_resource_delete($item->get_course_code());
                             if ($show_message === false) {
                                 if ($this->exportToPdf == false) {
                                     $row[] = $this->build_edit_column($item);
                                 }
                             }
                         } else {
                             // Students get the results and certificates columns
                             $eval_n_links = array_merge($alleval, $alllink);
                             if (count($eval_n_links) > 0) {
                                 $value_data = isset($data[4]) ? $data[4] : null;
                                 if (!is_null($value_data)) {
                                     //$score = $item->calc_score(api_get_user_id());
                                     //$new_score = $data[3] * $score[0] / $score[1];
                                     //$new_score = floatval(number_format($new_score, api_get_setting('gradebook_number_decimals')));
                                     // Result
                                     $row[] = $value_data;
                                     $best = isset($data['best']) ? $data['best'] : null;
                                     $average = isset($data['average']) ? $data['average'] : null;
                                     $ranking = isset($data['ranking']) ? $data['ranking'] : null;
                                     // Ranking
                                     $row[] = $ranking;
                                     // Best
                                     $row[] = $best;
                                     // Average
                                     $row[] = $average;
                                 }
                             }
                             if (!empty($cats)) {
                                 if ($this->exportToPdf == false) {
                                     $row[] = null;
                                 }
                             }
                         }
                         if ($this->exportToPdf == false) {
                             $row['child_of'] = $parent_id;
                         }
                         $sortable_data[] = $row;
                     }
                     // "Warning row"
                     if (!empty($data_array)) {
                         if ($this->teacherView) {
                             // Compare the category weight to the sum of all weights inside the category
                             if (intval($total_weight) == $category_weight) {
                                 $label = null;
                                 $total = GradebookUtils::score_badges(array($total_weight . ' / ' . $category_weight, '100'));
                             } else {
                                 $label = Display::return_icon('warning.png', sprintf(get_lang('TotalWeightMustBeX'), $category_weight));
                                 $total = Display::badge($total_weight . ' / ' . $category_weight, 'warning');
                             }
                             $row = array(null, null, "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<h5>" . get_lang('SubTotal') . '</h5>', null, $total . ' ' . $label, 'child_of' => $parent_id);
                             $sortable_data[] = $row;
                         }
                     }
                 }
             }
         }
     }
     //end looping categories
     $main_weight = 0;
     if (count($main_cat) > 1) {
         /** @var Category $myCat */
         foreach ($main_cat as $myCat) {
             $myParentId = $myCat->get_parent_id();
             if ($myParentId == 0) {
                 $main_weight = intval($myCat->get_weight());
             }
         }
     }
     if ($this->teacherView) {
         // Total for teacher.
         if (count($main_cat) > 1) {
             if (intval($total_categories_weight) == $main_weight) {
                 $total = GradebookUtils::score_badges(array($total_categories_weight . ' / ' . $main_weight, '100'));
             } else {
                 $total = Display::badge($total_categories_weight . ' / ' . $main_weight, 'warning');
             }
             $row = array(null, null, '<strong>' . get_lang('Total') . '</strong>', null, $total);
             $sortable_data[] = $row;
         }
     } else {
         // Total for student.
         if (count($main_cat) > 1) {
             $main_weight = intval($main_cat[0]->get_weight());
             $global = null;
             $average = null;
             // Overwrite main weight
             $totalResult[1] = $main_weight;
             $totalResult = $scoredisplay->display_score($totalResult, SCORE_DIV);
             $totalRanking = array();
             $invalidateRanking = true;
             $average = 0;
             foreach ($this->studentList as $student) {
                 $score = $main_cat[0]->calc_score($student['user_id']);
                 if (!empty($score[0])) {
                     $invalidateRanking = false;
                 }
                 $totalRanking[$student['user_id']] = $score[0];
                 $average += $score[0];
             }
             $totalRanking = AbstractLink::getCurrentUserRanking($user_id, $totalRanking);
             $totalRanking = $scoredisplay->display_score($totalRanking, SCORE_DIV, SCORE_BOTH, true);
             if ($invalidateRanking) {
                 $totalRanking = null;
             }
             // Overwrite main weight
             $totalBest[1] = $main_weight;
             $totalBest = $scoredisplay->display_score($totalBest, SCORE_DIV, SCORE_BOTH, true);
             // Overwrite main weight
             $totalAverage[0] = $average / count($this->studentList);
             $totalAverage[1] = $main_weight;
             $totalAverage = $scoredisplay->display_score($totalAverage, SCORE_DIV, SCORE_BOTH, true);
             if ($this->exportToPdf) {
                 $row = array(null, '<h3>' . get_lang('Total') . '</h3>', $main_weight, $totalResult, $totalRanking, $totalBest, $totalAverage);
             } else {
                 $row = array(null, '<h3>' . get_lang('Total') . '</h3>', null, $main_weight, $totalResult, $totalRanking, $totalBest, $totalAverage);
             }
             $sortable_data[] = $row;
         }
     }
     // Warning messages
     $view = isset($_GET['view']) ? $_GET['view'] : null;
     if ($this->teacherView) {
         if (isset($_GET['selectcat']) && $_GET['selectcat'] > 0 && $view != 'presence') {
             $id_cat = intval($_GET['selectcat']);
             $category = Category::load($id_cat);
             $weight_category = intval($this->build_weight($category[0]));
             $course_code = $this->build_course_code($category[0]);
             $weight_total_links = round($weight_total_links);
             if ($weight_total_links > $weight_category || $weight_total_links < $weight_category || $weight_total_links > $weight_category) {
                 $warning_message = sprintf(get_lang('TotalWeightMustBeX'), $weight_category);
                 $modify_icons = '<a href="gradebook_edit_cat.php?editcat=' . $id_cat . '&cidReq=' . $course_code . '&id_session=' . api_get_session_id() . '">' . Display::return_icon('edit.png', $warning_message, array(), ICON_SIZE_SMALL) . '</a>';
                 $warning_message .= $modify_icons;
                 Display::display_warning_message($warning_message, false);
             }
             $content_html = DocumentManager::replace_user_info_into_html(api_get_user_id(), $course_code);
             if (!empty($content_html)) {
                 $new_content = explode('</head>', $content_html['content']);
             }
             if (empty($new_content[0])) {
                 // Set default certificate
                 $courseData = api_get_course_info($course_code);
                 DocumentManager::generateDefaultCertificate($courseData);
             }
         }
         if (empty($_GET['selectcat'])) {
             $categories = Category::load();
             $weight_categories = $certificate_min_scores = $course_codes = array();
             foreach ($categories as $category) {
                 $course_code_category = $this->build_course_code($category);
                 if (!empty($course_code)) {
                     if ($course_code_category == $course_code) {
                         $weight_categories[] = intval($this->build_weight($category));
                         $certificate_min_scores[] = intval($this->build_certificate_min_score($category));
                         $course_codes[] = $course_code;
                         break;
                     }
                 } else {
                     $weight_categories[] = intval($this->build_weight($category));
                     $certificate_min_scores[] = intval($this->build_certificate_min_score($category));
                     $course_codes[] = $course_code_category;
                 }
             }
             if (is_array($weight_categories) && is_array($certificate_min_scores) && is_array($course_codes)) {
                 $warning_message = '';
                 for ($x = 0; $x < count($weight_categories); $x++) {
                     $weight_category = intval($weight_categories[$x]);
                     $certificate_min_score = intval($certificate_min_scores[$x]);
                     $course_code = $course_codes[$x];
                     if (empty($certificate_min_score) || $certificate_min_score > $weight_category) {
                         $warning_message .= $course_code . '&nbsp;-&nbsp;' . get_lang('CertificateMinimunScoreIsRequiredAndMustNotBeMoreThan') . '&nbsp;' . $weight_category . '<br />';
                     }
                 }
                 if (!empty($warning_message)) {
                     Display::display_warning_message($warning_message, false);
                 }
             }
         }
     }
     return $sortable_data;
 }
 /**
  * @param FormValidator $form
  * @param array $sendTo array('everyone' => false, 'users' => [1, 2], 'groups' => [3, 4])
  * @param array $attributes
  * @param bool $addOnlyItemsInSendTo
  * @param bool $required
  * @return bool
  */
 public function showToForm($form, $sendTo = array(), $attributes = array(), $addOnlyItemsInSendTo = false, $required = false)
 {
     if ($this->type != 'course') {
         return false;
     }
     $order = 'lastname';
     if (api_is_western_name_order()) {
         $order = 'firstname';
     }
     $userList = CourseManager::get_user_list_from_course_code(api_get_course_id(), $this->sessionId, null, $order);
     $groupList = CourseManager::get_group_list_of_course(api_get_course_id(), $this->sessionId);
     $this->setSendToSelect($form, $groupList, $userList, $sendTo, $attributes, $addOnlyItemsInSendTo, $required);
     return true;
 }
$items = getAllUserToWork($workId, api_get_course_int_id());
$usersAdded = array();
if (!empty($items)) {
    echo Display::page_subheader(get_lang('UsersAdded'));
    echo '<div class="well">';
    foreach ($items as $data) {
        $myUserId = $data['user_id'];
        $usersAdded[] = $myUserId;
        $userInfo = api_get_user_info($myUserId);
        $url = api_get_path(WEB_CODE_PATH) . 'work/add_user.php?action=delete&id=' . $workId . '&user_id=' . $myUserId;
        $link = Display::url(get_lang('Delete'), $url);
        echo $userInfo['complete_name'] . ' ' . $link . '<br />';
    }
    echo '</div>';
}
$userList = CourseManager::get_user_list_from_course_code($courseInfo['code'], api_get_session_id(), null, null, STUDENT);
echo Display::page_subheader(get_lang('UserToAdd'));
if (!empty($userList)) {
    echo '<div class="well">';
    foreach ($userList as $user) {
        if (in_array($user['user_id'], $usersAdded)) {
            continue;
        }
        $userName = api_get_person_name($user['firstname'], $user['lastname']);
        $url = api_get_path(WEB_CODE_PATH) . 'work/add_user.php?action=add&id=' . $workId . '&user_id=' . $user['user_id'];
        $link = Display::url(get_lang('Add'), $url);
        echo $userName . ' ' . $link . '<br />';
    }
    echo '</div>';
}
echo '<hr /><div class="clear"></div>';
Exemple #21
0
 /**
  * Gets the paths of all folders in a course
  * can show all folders (except for the deleted ones) or only visible ones
  *
  * @param array $_course
  * @param int $to_group_id
  * @param boolean $can_see_invisible
  *
  * @return array with paths
  */
 public static function get_all_document_folders($_course, $to_group_id = 0, $can_see_invisible = false)
 {
     $TABLE_ITEMPROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY);
     $TABLE_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT);
     $to_group_id = intval($to_group_id);
     $document_folders = array();
     $students = CourseManager::get_user_list_from_course_code($_course['code'], api_get_session_id());
     $sharedCondition = null;
     if (!empty($students)) {
         $conditionList = array();
         foreach ($students as $studentId => $studentInfo) {
             $conditionList[] = '/shared_folder/sf_user_' . $studentInfo['user_id'];
         }
     }
     $groupCondition = " last.to_group_id = {$to_group_id}";
     if (empty($to_group_id)) {
         $groupCondition = " (last.to_group_id = 0 OR last.to_group_id IS NULL)";
     }
     if ($can_see_invisible) {
         // condition for the session
         $session_id = api_get_session_id();
         $condition_session = api_get_session_condition($session_id, true, false, 'docs.session_id');
         $show_users_condition = "";
         if (api_get_setting('document.show_users_folders') == 'false') {
             $show_users_condition = " AND docs.path NOT LIKE '%shared_folder%'";
         }
         if ($to_group_id != 0) {
             $sql = "SELECT DISTINCT docs.id, path\n                       FROM {$TABLE_ITEMPROPERTY}  AS last\n                       INNER JOIN {$TABLE_DOCUMENT}  AS docs\n                       ON (\n                            docs.id = last.ref AND\n                            last.tool = '" . TOOL_DOCUMENT . "' AND\n                            last.c_id = {$_course['real_id']} AND\n                            docs.c_id = {$_course['real_id']}\n                       )\n                       WHERE\n                            docs.filetype \t\t= 'folder' AND\n                            {$groupCondition} AND\n                            docs.path NOT LIKE '%shared_folder%' AND\n                            docs.path NOT LIKE '%_DELETED_%' AND\n                            last.visibility \t<> 2\n                            {$condition_session} ";
         } else {
             $sql = "SELECT DISTINCT docs.id, path\n                        FROM {$TABLE_ITEMPROPERTY}  AS last\n                        INNER JOIN {$TABLE_DOCUMENT}  AS docs\n                        ON (\n                            docs.id = last.ref AND\n                            last.tool = '" . TOOL_DOCUMENT . "' AND\n                            last.c_id = {$_course['real_id']} AND\n                            docs.c_id = {$_course['real_id']}\n                        )\n                        WHERE\n                            docs.filetype \t\t= 'folder' AND\n                            docs.path NOT LIKE '%_DELETED_%' AND\n                            {$groupCondition} AND\n                            last.visibility \t<> 2\n                            {$show_users_condition} {$condition_session} ";
         }
         $result = Database::query($sql);
         if ($result && Database::num_rows($result) != 0) {
             while ($row = Database::fetch_array($result, 'ASSOC')) {
                 if (DocumentManager::is_folder_to_avoid($row['path'])) {
                     continue;
                 }
                 if (strpos($row['path'], '/shared_folder/') !== false) {
                     if (!in_array($row['path'], $conditionList)) {
                         continue;
                     }
                 }
                 $document_folders[$row['id']] = $row['path'];
             }
             if (!empty($document_folders)) {
                 natsort($document_folders);
             }
             return $document_folders;
         } else {
             return false;
         }
     } else {
         // No invisible folders
         // Condition for the session
         $session_id = api_get_session_id();
         $condition_session = api_get_session_condition($session_id, true, false, 'docs.session_id');
         //get visible folders
         $sql = "SELECT DISTINCT docs.id, path\n                    FROM\n                        {$TABLE_ITEMPROPERTY} AS last, {$TABLE_DOCUMENT} AS docs\n                    WHERE\n                        docs.id = last.ref AND\n                        docs.filetype = 'folder' AND\n                        last.tool = '" . TOOL_DOCUMENT . "' AND\n                        {$groupCondition} AND\n                        last.visibility = 1\n                        {$condition_session} AND\n                        last.c_id = {$_course['real_id']}  AND\n                        docs.c_id = {$_course['real_id']} ";
         $result = Database::query($sql);
         $visibleFolders = array();
         while ($row = Database::fetch_array($result, 'ASSOC')) {
             $visibleFolders[$row['id']] = $row['path'];
         }
         // Condition for the session
         $session_id = api_get_session_id();
         $condition_session = api_get_session_condition($session_id, true, false, 'docs.session_id');
         //get invisible folders
         $sql = "SELECT DISTINCT docs.id, path\n                    FROM {$TABLE_ITEMPROPERTY} AS last, {$TABLE_DOCUMENT} AS docs\n                    WHERE\n                        docs.id = last.ref AND\n                        docs.filetype = 'folder' AND\n                        last.tool = '" . TOOL_DOCUMENT . "' AND\n                        {$groupCondition} AND\n                        last.visibility = 0 {$condition_session} AND\n                        last.c_id = {$_course['real_id']} AND\n                        docs.c_id = {$_course['real_id']} ";
         $result = Database::query($sql);
         $invisibleFolders = array();
         while ($row = Database::fetch_array($result, 'ASSOC')) {
             //condition for the session
             $session_id = api_get_session_id();
             $condition_session = api_get_session_condition($session_id, true, false, 'docs.session_id');
             //get visible folders in the invisible ones -> they are invisible too
             $sql = "SELECT DISTINCT docs.id, path\n                        FROM {$TABLE_ITEMPROPERTY} AS last, {$TABLE_DOCUMENT} AS docs\n                        WHERE\n                            docs.id = last.ref AND\n                            docs.path LIKE '" . Database::escape_string($row['path'] . '/%') . "' AND\n                            docs.filetype = 'folder' AND\n                            last.tool = '" . TOOL_DOCUMENT . "' AND\n                            {$groupCondition} AND\n                            last.visibility = 1 {$condition_session} AND\n                            last.c_id = {$_course['real_id']} AND\n                            docs.c_id = {$_course['real_id']}  ";
             $folder_in_invisible_result = Database::query($sql);
             while ($folders_in_invisible_folder = Database::fetch_array($folder_in_invisible_result, 'ASSOC')) {
                 $invisibleFolders[$folders_in_invisible_folder['id']] = $folders_in_invisible_folder['path'];
             }
         }
         //if both results are arrays -> //calculate the difference between the 2 arrays -> only visible folders are left :)
         if (is_array($visibleFolders) && is_array($invisibleFolders)) {
             $document_folders = array_diff($visibleFolders, $invisibleFolders);
             natsort($document_folders);
             return $document_folders;
         } elseif (is_array($visibleFolders)) {
             natsort($visibleFolders);
             return $visibleFolders;
         } else {
             //no visible folders found
             return false;
         }
     }
 }
Exemple #22
0
 $my_folder_data = get_work_data_by_id($work_id);
 $work_parents = array();
 if (empty($my_folder_data)) {
     $work_parents = getWorkList($work_id, $my_folder_data, $add_query);
 }
 if (api_is_allowed_to_edit()) {
     // Work list
     echo '<div class="row">';
     echo '<div class="span9">';
     if (!empty($group_id)) {
         $userList = GroupManager::get_users($group_id);
     } else {
         if (empty($session_id)) {
             $userList = CourseManager::get_user_list_from_course_code($course_code, $session_id, null, null, STUDENT);
         } else {
             $userList = CourseManager::get_user_list_from_course_code($course_code, $session_id, null, null, 0);
         }
         $userList = array_keys($userList);
     }
     display_student_publications_list($work_id, $my_folder_data, $work_parents, $origin, $add_query, $userList);
     echo '</div>';
     echo '<div class="span3">';
     $table = new HTML_Table(array('class' => 'data_table'));
     $column = 0;
     $row = 0;
     $headers = array(get_lang('Students'), get_lang('Works'));
     foreach ($headers as $header) {
         $table->setHeaderContents($row, $column, $header);
         $column++;
     }
     $row++;
                 $thisAnnouncementOrderFound = true;
             }
         }
         Display::addFlash(Display::return_message(get_lang('AnnouncementMoved')));
         header('Location: ' . $homeUrl);
         exit;
     }
     break;
 case 'view':
     $content = AnnouncementManager::display_announcement($announcement_id);
     break;
 case 'list':
     $htmlHeadXtra[] = api_get_jqgrid_js();
     $searchForm = new FormValidator('search_simple', 'post', api_get_self() . '?' . api_get_cidreq(), '', array(), FormValidator::LAYOUT_INLINE);
     $searchForm->addElement('text', 'keyword', get_lang('Title'));
     $users = CourseManager::get_user_list_from_course_code(api_get_course_id(), $sessionId);
     $userList = array('' => '');
     if (!empty($users)) {
         foreach ($users as $user) {
             $userList[$user['user_id']] = api_get_person_name($user['firstname'], $user['lastname']);
         }
     }
     $users = [];
     $searchForm->addElement('select', 'user_id', get_lang('Users'), $userList);
     $searchForm->addButtonSearch(get_lang('Search'));
     $filterData = array();
     $keyword = '';
     $userIdToSearch = 0;
     if ($searchForm->validate()) {
         $filterData = $searchForm->getSubmitValues();
         $keyword = $filterData['keyword'];
 /**
  * Get registered users inside current course
  * @param 	int	   attendance id for showing attendance result field (optional)
  * @return 	array  users data
  */
 public function get_users_rel_course($attendance_id = 0)
 {
     $current_course_id = $this->get_course_id();
     $courseInfo = api_get_course_info($current_course_id);
     $courseId = $courseInfo['real_id'];
     $current_session_id = $this->get_session_id();
     if (!empty($current_session_id)) {
         $a_course_users = CourseManager::get_user_list_from_course_code($current_course_id, $current_session_id, '', 'lastname');
     } else {
         $a_course_users = CourseManager::get_user_list_from_course_code($current_course_id, 0, '', 'lastname');
     }
     // get registered users inside current course
     $a_users = array();
     foreach ($a_course_users as $key => $user_data) {
         $value = array();
         $uid = $user_data['user_id'];
         $status = $user_data['status'];
         $user_status_in_session = null;
         $user_status_in_course = null;
         if ($current_session_id) {
             $user_status_in_session = SessionManager::get_user_status_in_course_session($uid, $courseId, $current_session_id);
         } else {
             $user_status_in_course = CourseManager::get_user_in_course_status($uid, $courseId);
         }
         //Not taking into account DRH or COURSEMANAGER
         if ($uid <= 1 || $status == DRH || $user_status_in_course == COURSEMANAGER || $user_status_in_session == 2) {
             continue;
         }
         if (!empty($attendance_id)) {
             $user_faults = $this->get_faults_of_user($uid, $attendance_id);
             $value['attendance_result'] = $user_faults['faults'] . '/' . $user_faults['total'] . ' (' . $user_faults['faults_porcent'] . '%)';
             $value['result_color_bar'] = $user_faults['color_bar'];
         }
         // user's picture
         $image_path = UserManager::get_user_picture_path_by_id($uid, 'web', false);
         $user_profile = UserManager::get_picture_user($uid, $image_path['file'], 22, USER_IMAGE_SIZE_SMALL, ' width="22" height="22" ');
         if (!empty($image_path['file'])) {
             $photo = '<center><a class="thickbox" href="' . $image_path['dir'] . $image_path['file'] . '"  ><img src="' . $user_profile['file'] . '" ' . $user_profile['style'] . ' alt="' . api_get_person_name($user_data['firstname'], $user_data['lastname']) . '"  title="' . api_get_person_name($user_data['firstname'], $user_data['lastname']) . '" /></a></center>';
         } else {
             $photo = '<center><img src="' . $user_profile['file'] . '" ' . $user_profile['style'] . ' alt="' . api_get_person_name($user_data['firstname'], $user_data['lastname']) . '"  title="' . api_get_person_name($user_data['firstname'], $user_data['lastname']) . '" /></center>';
         }
         $value['photo'] = $photo;
         $value['firstname'] = $user_data['firstname'];
         $value['lastname'] = $user_data['lastname'];
         $value['username'] = $user_data['username'];
         $value['user_id'] = $uid;
         //Sending only 5 items in the array instead of 60
         $a_users[$key] = $value;
     }
     return $a_users;
 }
Exemple #25
0
 /**
  * @param string $startDate in UTC time
  * @param string $endDate in UTC time
  *
  * @return array
  */
 public function getAttendanceLogin($startDate, $endDate)
 {
     if (empty($startDate) || $startDate == '0000-00-00' || empty($endDate) || $endDate == '0000-00-00') {
         return false;
     }
     $sessionId = api_get_session_id();
     $courseCode = api_get_course_id();
     if (!empty($sessionId)) {
         $users = CourseManager::get_user_list_from_course_code($courseCode, $sessionId, '', 'lastname', 0);
     } else {
         $users = CourseManager::get_user_list_from_course_code($courseCode, 0, '', 'lastname', STUDENT);
     }
     $dateTimeStartOriginal = new DateTime($startDate);
     $dateTimeStart = new DateTime($startDate);
     $dateTimeEnd = new DateTime($endDate);
     $interval = $dateTimeStart->diff($dateTimeEnd);
     $days = intval($interval->format('%a'));
     $dateList = array($dateTimeStart->format('Y-m-d'));
     $headers = array(get_lang('User'), $dateTimeStart->format('Y-m-d'));
     for ($i = 0; $i < $days; $i++) {
         $dateTimeStart = $dateTimeStart->add(new DateInterval('P1D'));
         $date = $dateTimeStart->format('Y-m-d');
         $dateList[] = $date;
         $headers[] = $date;
     }
     $accessData = CourseManager::getCourseAccessPerCourseAndSession($courseCode, $sessionId, $dateTimeStartOriginal->format('Y-m-d H:i:s'), $dateTimeEnd->format('Y-m-d H:i:s'));
     $results = array();
     if (!empty($accessData)) {
         foreach ($accessData as $data) {
             $onlyDate = substr($data['login_course_date'], 0, 10);
             $results[$data['user_id']][$onlyDate] = true;
         }
     }
     return array('users' => $users, 'dateList' => $dateList, 'headers' => $headers, 'results' => $results);
 }
 /**
  * Send emails to users.
  * @param bool $sendToUsersInSession
  * @param bool $sendToDrhUsers send a copy of the message to the DRH users
  * related to the main user
  */
 public function send($sendToUsersInSession = false, $sendToDrhUsers = false)
 {
     $sender = $this->sender();
     $subject = $this->subject();
     // Send email one by one to avoid antispam
     $users = $this->sent_to();
     foreach ($users as $user) {
         $message = $this->message($user['user_id']);
         MessageManager::send_message_simple($user['user_id'], $subject, $message, $sender['user_id'], $sendToDrhUsers, true);
     }
     if ($sendToUsersInSession) {
         $sessionList = SessionManager::get_session_by_course($this->course['real_id']);
         if (!empty($sessionList)) {
             foreach ($sessionList as $sessionInfo) {
                 $sessionId = $sessionInfo['id'];
                 $message = $this->message(null, $sessionId);
                 $userList = CourseManager::get_user_list_from_course_code($this->course['code'], $sessionId);
                 if (!empty($userList)) {
                     foreach ($userList as $user) {
                         MessageManager::send_message_simple($user['user_id'], $subject, $message, $sender['user_id'], false, true);
                     }
                 }
             }
         }
     }
     $this->log_mail_sent();
 }
Exemple #27
0
/**
 * Get the users to display on the current page.
 */
function get_user_data($from, $number_of_items, $column, $direction)
{
    global $is_western_name_order;
    global $extraFields;
    $type = isset($_REQUEST['type']) ? intval($_REQUEST['type']) : STUDENT;
    $course_info = api_get_course_info();
    $sessionId = api_get_session_id();
    $course_code = $course_info['code'];
    $a_users = array();
    // limit
    if (!isset($_GET['keyword']) || empty($_GET['keyword'])) {
        $limit = 'LIMIT ' . intval($from) . ',' . intval($number_of_items);
    }
    if (!in_array($direction, array('ASC', 'DESC'))) {
        $direction = 'ASC';
    }
    switch ($column) {
        case 2:
            //official code
            $order_by = 'ORDER BY user.official_code ' . $direction;
            break;
        case 3:
            if ($is_western_name_order) {
                $order_by = 'ORDER BY user.firstname ' . $direction . ', user.lastname ' . $direction;
            } else {
                $order_by = 'ORDER BY user.lastname ' . $direction . ', user.firstname ' . $direction;
            }
            break;
        case 4:
            if ($is_western_name_order) {
                $order_by = 'ORDER BY user.lastname ' . $direction . ', user.firstname ' . $direction;
            } else {
                $order_by = 'ORDER BY user.firstname ' . $direction . ', user.lastname ' . $direction;
            }
            break;
        case 5:
            //username
            $order_by = 'ORDER BY user.username ' . $direction;
            break;
        default:
            if ($is_western_name_order) {
                $order_by = 'ORDER BY user.lastname ' . $direction . ', user.firstname ' . $direction;
            } else {
                $order_by = 'ORDER BY user.firstname ' . $direction . ', user.lastname ' . $direction;
            }
            break;
    }
    $active = isset($_GET['active']) ? $_GET['active'] : null;
    if (empty($sessionId)) {
        $status = $type;
    } else {
        if ($type == COURSEMANAGER) {
            $status = 2;
        } else {
            $status = 0;
        }
    }
    $a_course_users = CourseManager::get_user_list_from_course_code($course_code, $sessionId, $limit, $order_by, $status, null, false, false, null, array(), array(), $active);
    foreach ($a_course_users as $user_id => $o_course_user) {
        if (isset($_GET['keyword']) && searchUserKeyword($o_course_user['firstname'], $o_course_user['lastname'], $o_course_user['username'], $o_course_user['official_code'], $_GET['keyword']) || !isset($_GET['keyword']) || empty($_GET['keyword'])) {
            $groupsNameList = GroupManager::getAllGroupPerUserSubscription($user_id);
            $groupsNameListParsed = [];
            if (!empty($groupsNameList)) {
                $groupsNameListParsed = array_column($groupsNameList, 'name');
            }
            $temp = array();
            if (api_is_allowed_to_edit(null, true)) {
                $userInfo = api_get_user_info($user_id);
                $photo = '<img src="' . $userInfo['avatar_small'] . '" alt="' . $userInfo['complete_name'] . '" title="' . $userInfo['complete_name'] . '" />';
                $temp[] = $user_id;
                $temp[] = $photo;
                $temp[] = $o_course_user['official_code'];
                if ($is_western_name_order) {
                    $temp[] = $o_course_user['firstname'];
                    $temp[] = $o_course_user['lastname'];
                } else {
                    $temp[] = $o_course_user['lastname'];
                    $temp[] = $o_course_user['firstname'];
                }
                $temp[] = $o_course_user['username'];
                // Groups.
                $temp[] = implode(', ', $groupsNameListParsed);
                // Status
                $default_status = get_lang('Student');
                if (isset($o_course_user['status_rel']) && $o_course_user['status_rel'] == 1 || isset($o_course_user['status_session']) && $o_course_user['status_session'] == 2) {
                    $default_status = get_lang('CourseManager');
                } elseif (isset($o_course_user['is_tutor']) && $o_course_user['is_tutor'] == 1) {
                    $default_status = get_lang('Tutor');
                }
                $temp[] = $default_status;
                // Active
                $temp[] = $o_course_user['active'];
                if (!empty($extraFields)) {
                    foreach ($extraFields as $extraField) {
                        $extraFieldValue = new ExtraFieldValue('user');
                        $data = $extraFieldValue->get_values_by_handler_and_field_id($user_id, $extraField['id']);
                        $temp[] = $data['value'];
                    }
                }
                // User id for actions
                $temp[] = $user_id;
                $temp['is_tutor'] = isset($o_course_user['is_tutor']) ? $o_course_user['is_tutor'] : '';
                $temp['user_status_in_course'] = isset($o_course_user['status_rel']) ? $o_course_user['status_rel'] : '';
            } else {
                $userInfo = api_get_user_info($user_id);
                $userPicture = $userInfo['avatar'];
                $photo = '<img src="' . $userPicture . '" alt="' . $userInfo['complete_name'] . '" width="22" height="22" title="' . $userInfo['complete_name'] . '" />';
                $temp[] = $user_id;
                $temp[] = $photo;
                $temp[] = $o_course_user['official_code'];
                if ($is_western_name_order) {
                    $temp[] = $o_course_user['firstname'];
                    $temp[] = $o_course_user['lastname'];
                } else {
                    $temp[] = $o_course_user['lastname'];
                    $temp[] = $o_course_user['firstname'];
                }
                $temp[] = $o_course_user['username'];
                // Group.
                $temp[] = implode(', ', $groupsNameListParsed);
                if ($course_info['unsubscribe'] == 1) {
                    //User id for actions
                    $temp[] = $user_id;
                }
            }
            $a_users[$user_id] = $temp;
        }
    }
    return $a_users;
}
Exemple #28
0
 /**
  * @param int $user_id
  * @param bool $include_sessions
  * @return array
  */
 public static function get_user_list_from_courses_as_coach($user_id, $include_sessions = true)
 {
     $students_in_courses = array();
     $sessions = CourseManager::get_course_list_as_coach($user_id, true);
     if (!empty($sessions)) {
         foreach ($sessions as $session_id => $courses) {
             if (!$include_sessions) {
                 if (!empty($session_id)) {
                     continue;
                 }
             }
             if (empty($session_id)) {
                 foreach ($courses as $course_code) {
                     $students_in_course = CourseManager::get_user_list_from_course_code($course_code);
                     foreach ($students_in_course as $user_item) {
                         //Only students
                         if ($user_item['status_rel'] == STUDENT) {
                             $students_in_courses[$user_item['user_id']] = $user_item['user_id'];
                         }
                     }
                 }
             } else {
                 $students_in_course = SessionManager::get_users_by_session($session_id, '0');
                 if (is_array($students_in_course)) {
                     foreach ($students_in_course as $user_item) {
                         $students_in_courses[$user_item['user_id']] = $user_item['user_id'];
                     }
                 }
             }
         }
     }
     $students = Tracking::get_student_followed_by_coach($user_id);
     if (!empty($students_in_courses)) {
         if (!empty($students)) {
             $students = array_merge($students, $students_in_courses);
         } else {
             $students = $students_in_courses;
         }
     }
     if (!empty($students)) {
         $students = array_unique($students);
     }
     return $students;
 }
$filterOfficialCodeGet = isset($_GET['filter']) ? Security::remove_XSS($_GET['filter']) : null;
switch ($action) {
    case 'export_all_certificates':
        if (api_is_student_boss()) {
            $userGroup = new UserGroup();
            $userList = $userGroup->getGroupUsersByUser(api_get_user_id());
        } else {
            $userList = array();
            if (!empty($filterOfficialCodeGet)) {
                $userList = UserManager::getUsersByOfficialCode($filterOfficialCodeGet);
            }
        }
        Category::exportAllCertificates($cat_id, $userList);
        break;
    case 'generate_all_certificates':
        $user_list = CourseManager::get_user_list_from_course_code(api_get_course_id(), api_get_session_id());
        if (!empty($user_list)) {
            foreach ($user_list as $user_info) {
                if ($user_info['status'] == INVITEE) {
                    continue;
                }
                Category::register_user_certificate($cat_id, $user_info['user_id']);
            }
        }
        break;
    case 'delete_all_certificates':
        Category::deleteAllCertificates($cat_id);
        break;
}
$course_code = api_get_course_id();
$interbreadcrumb[] = array('url' => Security::remove_XSS($_SESSION['gradebook_dest']) . '?', 'name' => get_lang('Gradebook'));
 /**
  * @param int $announcementId
  */
 public static function addAnnouncementToAllUsersInSessions($announcementId)
 {
     $courseCode = api_get_course_id();
     $_course = api_get_course_info();
     $sessionList = SessionManager::get_session_by_course(api_get_course_int_id());
     if (!empty($sessionList)) {
         foreach ($sessionList as $sessionInfo) {
             $sessionId = $sessionInfo['id'];
             $userList = CourseManager::get_user_list_from_course_code($courseCode, $sessionId);
             if (!empty($userList)) {
                 foreach ($userList as $user) {
                     api_item_property_update($_course, TOOL_ANNOUNCEMENT, $announcementId, "AnnouncementUpdated", api_get_user_id(), 0, $user['user_id'], 0, 0, $sessionId);
                 }
             }
         }
     }
 }