Uname:Linux EDL-STRETCH 4.19.0-27-amd64 #1 SMP Debian 4.19.316-1 (2024-06-25) x86_64

403WebShell
403Webshell
Server IP : 188.114.96.2  /  Your IP : 104.23.197.231
Web Server : Apache/2.4.59 (Debian)
System : Linux EDL-STRETCH 4.19.0-27-amd64 #1 SMP Debian 4.19.316-1 (2024-06-25) x86_64
User : edlftp ( 1002)
PHP Version : 7.4.33
Disable Function : pcntl_alarm,pcntl_fork,pcntl_waitpid,pcntl_wait,pcntl_wifexited,pcntl_wifstopped,pcntl_wifsignaled,pcntl_wifcontinued,pcntl_wexitstatus,pcntl_wtermsig,pcntl_wstopsig,pcntl_signal,pcntl_signal_get_handler,pcntl_signal_dispatch,pcntl_get_last_error,pcntl_strerror,pcntl_sigprocmask,pcntl_sigwaitinfo,pcntl_sigtimedwait,pcntl_exec,pcntl_getpriority,pcntl_setpriority,pcntl_async_signals,pcntl_unshare,
MySQL : OFF  |  cURL : ON  |  WGET : ON  |  Perl : ON  |  Python : ON  |  Sudo : ON  |  Pkexec : ON
Directory :  /home/nicolasj/www/sms.formationlangues.be/application/controllers/BO/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ Back ]     

Current File : /home/nicolasj/www/sms.formationlangues.be/application/controllers/BO/Lesson.php
<?php
/*********************
 *********************
Template : "lesson.php"
Controller : "Lesson.php"

 Creation 08/05/2019
 Aernout Guillaume
 http://codes.solutions
 *********************
 *********************/
if (!defined('BASEPATH')) {
    exit('No direct script access allowed');
}

class Lesson extends NS_Controller
{
    public function __construct()
    {
        parent::__construct(array('no_cache' => 1));

        if ($this->session->userdata('admin_login') != 1) {
            $this->error('restricted admin');
        }
        $this->load->helper('generator');
        $this->load->helper('htmlpurifier');
        $this->load->model('lesson_model');
        $this->load->model('course_model');
        $this->load->model('teacher_model');
        $this->load->model('course_product_model');
        $this->load->model('form_model');
        $this->load->model('event_model');
        $this->load->model('profile_model');
        $this->load->model('email_model');
        $this->load->database();
    }

    public function index($arg = '')
    {
        $this->load->helper('url');
        $param = $this->uri->segment(3);
        if($param == "edit") {
            $data['edit'] = $this->uri->segment(4);
        } elseif($param == "list") {
            $data['list'] = $this->uri->segment(4);
        } elseif($param == "conf") {
            $data['confirm_c'] = $this->uri->segment(4);
            $data['confirm_l'] = $this->uri->segment(5);
        } elseif($param == "assign_s") {
            $data['assign_s_c'] = $this->uri->segment(4);
            $data['assign_s_l'] = $this->uri->segment(5);
        } elseif($param == "assign_t") {
            $data['assign_t_c'] = $this->uri->segment(4);
            $data['assign_t_l'] = $this->uri->segment(5);
        } elseif($param == "presence") {
            $data['presence_c'] = $this->uri->segment(4);
            $data['presence_l'] = $this->uri->segment(5);            
        } elseif($param == "presence_c") {
            $data['presence_c'] = $this->uri->segment(4);
        }

        $data['page_name'] = 'lesson';
        $data['page_title'] = get_phrase('lesson');
        if ($this->userInfo['role'] === "teacher") {
            $data['courses_list'] = $this->crud_model->get_teacher_courses($this->session->userData('userID'));
        } elseif ($this->userInfo['role'] === "parent") {
            $parent_id = (int) $this->session->userdata('userID');
            $data['courses_list'] = $this->course_model->get_courses_by_students_ids($this->crud_model->get_parent_child((int) $parent_id));
        } elseif ($this->userInfo['role'] === "student") {
            $student_id = (int) $this->session->userdata('userID');
            $data['courses_list'] = $this->course_model->get_courses_by_students_ids([$student_id]);
        } elseif ($this->userInfo['role'] === "admin") {
            $data['course_list'] = $this->crud_model->get_courses();
        }
        $data['professors'] =  $this->crud_model->get_teachers();
        $data['dynamic_assets'] = ['tagify'];
        $this->load->view('backend/index', $data);
    }

    public function refresh()
    {
        $this->continueIfAllowed(['allowed' => ['admin','teacher']]);
        $course_id = $this->input->post('id');
        $languages = [];
        foreach ($this->course_model->course_languages() as $lang) {
            $languages[(int) $lang->course_language_id] = strtolower($lang->code);
        }

        if ($this->userInfo['role'] === "teacher") {
            $teacher_id = (int) $this->session->userdata('userID');
            $lesson_list = $this->lesson_model->lessons_with_presences(($course_id === "all" ? null : (int) $course_id), $teacher_id);
        } elseif ($this->userInfo['role'] === "parent") {
            $parent_id = (int) $this->session->userdata('userID');
            $students_id = $this->crud_model->get_parent_child((int) $parent_id);
            $lesson_list = $this->lesson_model->lessons_with_presences(($course_id === "all" ? null : (int) $course_id), null, $students_ids);
        } elseif ($this->userInfo['role'] === "admin") {
            if($course_id == "all") {
                $lesson_list = $this->lesson_model->lessons_with_presences(null, null, null, true);
            } else {
                $lesson_list = $this->lesson_model->lessons_with_presences((int) $course_id, null, null, true);
            }
        }

        // Course shop infos (product image, etc)
        $lesson_ids = array_map(fn ($l) => $l['CourseID'], $lesson_list);
        $courses = $this->course_product_model->get_entry_by_courses($lesson_ids);
        $today = new DateTime();

        $lessons = [];
        $courses_lessons = [];
        foreach($lesson_list as $lesson) {
            $teachers_list = "";
            $teachers = json_decode("[" .$lesson['teachers_json'] . "]");
            if(!empty($teachers)) {;
                foreach($teachers as $teacher) {
                    if (!empty($teacher)) {
                        $teachers_list .= "<a class='btn btn-default teacher-" . Teacher_model::TEACHER_ROLES[$teacher->role] . "'>"
                                             . ucfirst($teacher->first_name) . " " . ucfirst($teacher->last_name) .
                                          "</a>";
                    }
                }
            } else {
                $teachers_list = "<a class='btn btn-danger'>N/A</a>";
            }
            $subject = (!empty($lesson['program_year']) && (int) $lesson['program_year'] > 0) ? $lesson['name_' . $languages[(int) $lesson['CourseLanguage']]] : $lesson['LessonName'];

            $date_field = "<span style='display:none'>". date("Ymd", strtotime(str_replace('/', '-', $lesson['LessonDate'])))."</span>" . 
                           date("d/m/Y", strtotime($lesson['LessonDate'])) . "<br>" . 
                          " [ ".substr($lesson['LessonStart'], 0, 5)." - ".substr($lesson['LessonEnd'], 0, 5)." ]<br>$teachers_list";


            if ($this->userInfo['role'] !== "teacher" || (int) $lesson['teacher_role_id'] !== 3) {
                $date_field .= "<br /><span class='entypo-feather btn btn-info' onclick='displayAssignT(\"".$lesson['ID']."\",this)'>Change Teacher</span>";
            }
            $lessons[] = [
                'id' => (int) $lesson['ID'],
                'date' => $date_field,
                'description' => html_purify($lesson['LessonDesc']),
                'subject' => $subject,
                'activities' => $lesson['LessonContent'],
                'min_tags' => Accounting_model::MIN_TAGS_VALID
            ];

            if (empty($courses_lessons[(int) $lesson['CourseID']])) {
                $courses_lessons[(int) $lesson['CourseID']] = [];
            }
            $courses_lessons[(int) $lesson['CourseID']][] = $lesson;
        }

        $courses_logbooks = [];
        foreach ($courses_lessons as $cl) {
            if (empty($cl) || empty($cl[0])) {
                continue;
            }

            $courses_logbooks[] = $this->load->view('backend/global/lesson/lesson_logbook.php', [
                'lessons' => $cl,
                'course_product' => $courses[(int) $cl[0]['CourseID']],
                'lang' => $languages[(int) $cl[0]['CourseLanguage']],
                'course_name' => $cl[0]['CourseName'],
                'today' => $today,
            ], true);
        }
        echo json_encode(['lessons' => $lessons, 'logbooks' => $courses_logbooks]);
    }

    /**
     * Return json with lesson logbooks for students and parents
     *
     * @return JSON
     */
    public function refresh_logbook()
    {
        $this->continueIfAllowed(['allowed' => ['parent', 'student']]);
        $course_id = $this->input->post('id');
        $languages = [];
        foreach ($this->course_model->course_languages() as $lang) {
            $languages[(int) $lang->course_language_id] = strtolower($lang->code);
        }

        $students_ids = [];
        if ($this->userInfo['role'] === "parent") {
            $parent_id = (int) $this->session->userdata('userID');
            $students_ids = $this->crud_model->get_parent_child((int) $parent_id);
        } elseif ($this->userInfo['role'] === "student") {
            $student_id = (int) $this->session->userdata('userID');
            $students_ids = [$student_id];
        }
        $lesson_list = $this->lesson_model->lessons_with_presences(($course_id === "all" ? null : (int) $course_id), null, $students_ids);

        // Course shop infos (product image, etc)
        $lesson_ids = array_map(fn ($l) => $l['CourseID'], $lesson_list);
        $courses = $this->course_product_model->get_entry_by_courses($lesson_ids);
        $today = new DateTime();

        $lessons = [];
        $courses_lessons = [];
        foreach($lesson_list as $lesson) {
            $subject = (!empty($lesson['program_year']) && (int) $lesson['program_year'] > 0) ? $lesson['name_' . $languages[(int) $lesson['CourseLanguage']]] : $lesson['LessonName'];
            $lessons[] = [
                'id' => (int) $lesson['ID'],
                'date' => $date_field,
                'description' => html_purify($lesson['LessonDesc']),
                'subject' => $subject,
                'activities' => $lesson['LessonContent'],
            ];

            if (empty($courses_lessons[(int) $lesson['CourseID']])) {
                $courses_lessons[(int) $lesson['CourseID']] = [];
            }
            $courses_lessons[(int) $lesson['CourseID']][] = $lesson;
        }

        $courses_logbooks = [];
        foreach ($courses_lessons as $cl) {
            if (empty($cl) || empty($cl[0])) {
                continue;
            }
            $subject = (!empty($cl[0]['program_year']) && (int) $cl[0]['program_year'] > 0) ? $cl[0]['name_' . $languages[(int) $cl[0]['CourseLanguage']]] : $cl[0]['LessonName'];
            $courses_logbooks[] = $this->load->view('backend/global/lesson/lesson_logbook.php', [
                'lessons' => $cl,
                'course_product' => $courses[(int) $cl[0]['CourseID']],
                'lang' => $languages[(int) $cl[0]['CourseLanguage']],
                'subject' => $subject,
                'course_name' => $cl[0]['CourseName'],
                'today' => $today,
            ], true);
        }
        echo json_encode($courses_logbooks);
    }

    public function lessonSubStatus()
    {
        $this->continueIfAllowed(['allowed' => ['admin','teacher']]);
        $lesson_id = (int) $this->input->post('id');
        if (empty($lesson_id)) {
            return json_encode([]);
        }

        $this->db->order_by('LessonDate', 'DESC');
        $query = $this->db->get_where('course_scheduled_new', ['ID' => $lesson_id]);
        $res = $query->result_array();
        if (empty($res)) {
            return json_encode([]);
        }
        $lesson = $res[0];
        $course = $this->course_model->get_entry((int) $lesson['CourseID']);
        if (!empty($course)) {
            $lesson['course_name'] = $course->CourseName;
            if ($language = $this->course_model->course_language($course->CourseLanguage)) {
                $lesson['language_iso'] = strtolower($language->code);
                $lesson['language_display'] = strtolower($language->name);
            }
        }
        $lesson['available_lesson_subject'] = $this->lesson_model->lesson_subjects((new DateTime($lesson['LessonDate'])), true);
        $lesson['teachers'] = $this->lesson_model->lesson_teachers($lesson_id);

        echo json_encode($lesson);
        return;

    }

    public function lessonPresenceSubStatus()
    {
        $this->continueIfAllowed(array('allowed' => array('teacher')));
        $id = $this->input->post('id');
        $this->db->order_by('LessonDate', 'DESC');
        $query = $this->db->get_where('course_scheduled_new', array('ID' => $id));
        $res = $query->result_array();

        $lessonList = array();
        foreach ($res as $row) {
            if(new Date($row['LessonDate']) <= new Date()) {
                $lessonList[] = [
                    'ID' => $row['ID'],
                    'CourseID' => $row['CourseID'],
                    'LessonDate' => $row['LessonDate'],
                    'LessonStart' => $row['LessonStart'],
                    'LessonEnd' => $row['LessonEnd'],
                    'LessonDone' => $row['LessonDone'],                    
                ];
            }
        }
        echo json_encode($lessonList);
    }

    public function lessonSubAssigned()
    {
        $this->continueIfAllowed(array('allowed' => array('admin','teacher')));
        $data = $this->input->post(array('id','role'));

        if($data['role'] == "teacher") {
            $query = $this->db->get_where('course_teacher', array('lesson_id' => $data['id']));
            $res = $query->result_array();
            $teacher_list = array();

            foreach ($res as $row) {
                $teacher_info = array();
                $teacher_info[0] = $row['teacher_id'];
                $teacher_info[1] = $this->crud_model->get_teacher_name($row['teacher_id']);
                $teacher_info[2] = $this->crud_model->get_lesson_info($data['id']);
                $teacher_info[3] = $data['id'];
                $teacher_info[4] = $this->crud_model->get_lesson_name($data['id']);
                $teacher_info[5] = $this->crud_model->get_lesson_info_short_iso($data['id']);
                $teacher_info[6] = $row['CourseID'];

                array_push($teacher_list, $teacher_info);
            }
            echo json_encode($teacher_list);
        } elseif($data['role'] == "student") {
            $query = $this->db->get_where('course_student_new', array('lesson_id' => $data['id']));
            $res = $query->result_array();
            $student_list = array();

            foreach ($res as $row) {
                $student_info = array();
                $student_info[0] = $row['student_id'];
                $student_info[1] = $this->crud_model->get_student_name($row['student_id']);
                $student_info[2] = $this->crud_model->get_lesson_info($data['id']);
                $student_info[3] = $data['id'];
                $student_info[4] = $this->crud_model->get_lesson_name($data['id']);
                $student_info[5] = $this->crud_model->get_lesson_info_short_iso($data['id']);
                $student_info[6] = $row['CourseID'];
                array_push($student_list, $student_info);
            }
            echo json_encode($student_list);
        } else {
            echo "-1";
        }

    }

    public function lessonSubPresence()
    {
        $this->continueIfAllowed(array('allowed' => array('admin','teacher')));
        $data = $this->input->post('id');
        $query = $this->db->get_where('course_student_new', array('lesson_id' => $data));
        $res = $query->result_array();

        $student_list = array('islocked' => $this->check_if_locked($data));

        foreach ($res as $row) {
            $student_info = array();
            $student_info[0] = $row['student_id'];
            $student_info[1] = $this->crud_model->get_student_name($row['student_id']);
            $student_info[2] = $row['status_id'];
            $student_info[3] = $row['Contested'];

            array_push($student_list, $student_info);
        }
        echo json_encode($student_list);
    }

    public function lessonCollision()
    {
        $this->continueIfAllowed(['allowed' => ['admin', 'teacher']]);
        $data = $this->input->post(['courseID', 'date', 'hourS', 'hourE']);
        if($this->lesson_model->check_collision($data['courseID'], $data['date'], $data['hourS'], $data['hourE'])) {
            echo "-1";
            return true;
        }
    }
    //
    public function lessonStatut()
    {
        $this->continueIfAllowed(['allowed' => ['admin', 'teacher']]);
        $id = (int) $this->input->post('id');
        $lessons = $this->crud_model->get_course_scheduled($id);

        $teacher_lessons_role = [];
        if ($this->userInfo['role'] === "teacher") {
            foreach ($this->teacher_model->get_course_teacher((int) $this->userInfo['user_id'], $id) as $tl) {
                $teacher_lessons_role[(int) $tl->lesson_id] = $tl;
            }
        }

        $lessons_statut = [];
        foreach ($lessons as $lesson) {
            if ($lesson['LessonDone'] != 1) {
                $duration = ((strtotime($lesson['LessonEnd']) - strtotime($lesson['LessonStart'])) / 60);
                $lesson_buffer = [
                    'id' => $lesson['ID'],
                    // TODO: Déplacer la mise en page vers le JS, le back doit envoyer de la data brute
                    'title' => substr($lesson['LessonStart'], 0, 5) . " - " . substr($lesson['LessonEnd'], 0, 5) . " |". $duration . " min",
                    'start' => $lesson['LessonDate'] . "T" . $lesson['LessonStart'],
                    'end' => $lesson['LessonDate'] . "T" . $lesson['LessonEnd'],
                    'duration' => $duration,
                    'description' => "duration: " . $duration / 60 . " H",
                ];
                
                if ($teacher_lessons_role[(int) $lesson['ID']]) {
                    $lesson_buffer['teacher_allowed'] = (int)$teacher_lessons_role[(int) $lesson['ID']]->teacher_role_id !== 3;
                }
                $lessons_statut[] = $lesson_buffer;
            }
        }
        echo json_encode($lessons_statut);
    }

    public function courseStatut()
    {
        $this->continueIfAllowed(['allowed' => ['admin', 'teacher']]);

        $id = $this->input->post('id');
        $data = $this->crud_model->get_course($id);
        $course_statut = [
            'id' => $id,
            'name' => $data[0]['CourseName'],
            'certificate' => $data[0]['CourseCertificate'],
            'lan' => $data[0]['CourseLanguage'],
            'lvl' => $data[0]['CourseLevel'],
            'type' => $data[0]['CourseType'],
            'contract' => $data[0]['CourseContract'],
            'desc' => $data[0]['CourseDescription'],
            'price' => $data[0]['CoursePrice']
        ];
        echo json_encode($course_statut);
    }

    public function save()
    {
        $this->continueIfAllowed(['allowed' => ['admin', 'teacher']]);
        $data = $this->input->post(['courseID', 'date', 'hourS', 'hourE', 'name', 'desc', 'assign']);

        // TODO: Validation des informations avant injection dans la DB.
        $lessonSql = [
            'CourseID' => $data['courseID'],
            'LessonName' => $data['name'],
            'LessonDesc' => $data['desc'],
            'LessonDate' => $data['date'],
            'LessonStart' => $data['hourS'],
            'LessonEnd' => $data['hourE'],
            'Creation_Author' => $this->session->userdata('userID')
        ];

        $this->db->insert('course_scheduled_new', $lessonSql);
        $id = $this->db->insert_id();
        echo $id;
        $assign = $data['assign'];

        //set teacher to his lesson
        if ($this->userInfo['role'] == "teacher") {
            $teacher_id = $this->session->userdata('userID');
            $sql_t = array(
              'course_id' => $data['courseID'],
              'lesson_id' => $id,
              'status_id' => '0',
              'teacher_id' => $teacher_id
            );
            $this->db->insert('course_teacher', $sql_t);
        } elseif ($this->userInfo['role'] == "admin") {

            $previous_lesson = $this->get_previous_lesson($id, $data['courseID']);

            if ($previous_lesson != "no lesson") {
                $query  = $this->db->get_where('course_teacher', array('lesson_id' => $previous_lesson[0],'course_id' => $previous_lesson[1]));
                $query = $query->result_array();

                if (count($query) != 0) {
                    foreach ($query as $key => $row) {
                        $sql = array(
                          'lesson_id' => $id,
                          'status_id' => '0',
                          'teacher_id' => $row['teacher_id'],
                          'course_id' => $data['courseID']
                        );

                        $this->db->insert('course_teacher', $sql);
                        $this->event_model->trigger_first_lesson('Course_Teacher_First_Assignation', $isoLang, $userId, $id);
                        $this->event_model->trigger_lesson('Course_Teacher_Assignation', $isoLang, $userId, $id);
                    }
                }
            }
        }

        if($assign == "true") {
            $previous_lesson = $this->get_previous_lesson($id, $data['courseID']);
            $query  = 0;

            if($previous_lesson != "no lesson") {
                $query  = $this->db->get_where('course_student_new', array('lesson_id' => $previous_lesson[0],'course_id' => $previous_lesson[1]));
                $query = $query->result_array();
            }

            if(count($query) == 0) {
                if($this->userInfo['role'] == "teacher") {
                    $this->db->delete('course_scheduled_new', array('ID' => $id));
                    $this->db->delete('course_teacher', array('lesson_id' => $id));
                    echo "Can't set empty lessons, please contact administrators #no student on previous lesson";
                    return;
                } else {
                    echo "no student on previous lesson";
                }
            } else {
                foreach ($query as $key => $row) {
                    $sql = [
                      'lesson_id' => $id,
                      'status_id' => '0',
                      'student_id' => $row['student_id'],
                      'group_id' => $row['group_id'],
                      'course_id' => $data['courseID']
                    ];
                    $this->db->insert('course_student_new', $sql);
                    $this->event_model->trigger_first_lesson('Course_Student_First_Assignation', 'en', $row['student_id'], $id);
                    $this->event_model->trigger_lesson('Course_Student_Assignation', 'en', $row['student_id'], $id);

                    $teachers_list = $this->crud_model->get_course_teachers($data['courseID']);
                    if(count($teachers_list) > 0) {
                        foreach ($teachers_list as $key => $t) {
                            $this->event_model->trigger_lesson('Teacher_Student_Assignation', 'en', $t['teacher_id'], $id);
                        }
                    }

                }
            }
        }

        if(($this->userInfo['role'] == "teacher") && ($this->lesson_model->approve_creation($data['date']) != true)) {
            echo "-1";
            //return true; // bypass the teachear security
        } else {
            echo $id;
        }
    }

    //
    public function update()
    {
        $this->continueIfAllowed(['allowed' => ['admin', 'teacher']]);
        $data = $this->input->post(['lessonID','date','hourS','hourE','name','desc', 'LessonSubjectId', 'lesson_content']);
        $user_id = (int) $this->session->userdata('userID');

        if(($this->userInfo['role'] == "teacher") && $this->teacher_model->can_edit_lesson((int) $data['lessonID'], $user_id) === false) {
            echo json_encode(['success' => false, 'errors' => 'Permission for #edit missing']);
            return;
        }

        $update_lesson = [            
            'LessonName' => $data['name'],            
            'LessonSubjectId' => (int) $data['LessonSubjectId']
        ];
        if (isset($data['lesson_content'])) {
            $update_lesson['LessonContent'] = $data['lesson_content'];
        }
        if (isset($data['desc'])) {
            $update_lesson['LessonDesc'] = $data['desc'];
        }
        if (!empty($data['date'])) {
            $update_lesson['LessonDate'] = $data['date'];
        }
        if (!empty($data['hourS'])) {
            $update_lesson['LessonStart'] = $data['hourS'];
        }
        if (!empty($data['hourE'])) {
            $update_lesson['LessonEnd'] = $data['hourE'];
        }
        $this->db->set($update_lesson);
        $this->db->where('ID', $data['lessonID']);

        if ($this->db->update('course_scheduled_new')) {
            echo json_encode(['success' => true]);
        } else {
            echo json_encode(['success' => false]);
        }
    }

    /**
     * Delete lesson
     * TODO: change CourseID to LessonID or CourseScheduledId
     * @return void
     */
    public function delete()
    {
        $this->continueIfAllowed(array('allowed' => array('admin','teacher')));
        $data = $this->input->post(array('courseID','date'));

        $courseID = $this->crud_model->get_course_id_from_lesson($data['courseID']);
        $lessonNumber = $this->crud_model->get_lessons_number($courseID);

        if(($this->userInfo['role'] == "teacher") && ($lessonNumber == 1)) {
            echo "-1";
            return false;
        }

        if($this->userInfo['role'] == "teacher") {
            //if only one teacher
            $lesson_assignation = count($this->crud_model->get_course_teacher_2($this->session->userdata('userID')));
            if($lesson_assignation == 1 || $lesson_assignation == 0) {
                $this->db->where('id', $data['courseID']);

                if($this->db->delete('course_scheduled_new')) {

                    echo "1";
                    $this->db->where('lesson_id', $data['courseID']); //course refer to lesson
                    $this->db->delete('course_student_new');
                    $this->db->where('lesson_id', $data['courseID']); //course refer to lesson
                    $this->db->delete('course_teacher');
                } else {
                    echo "0";
                }
                //$this->db->insert('course_scheduled_new',$lessonSql);
            } else {
                echo "remove assignation, not lesson (lesson assigned to two teacher or more)";
                $this->db->where(array('lesson_id' => $data['courseID'],'teacher_id' => $this->session->userdata('userID')));//course refer to lesson
                $this->db->delete('course_teacher');
            }
        } else {
            //admin
            $this->db->where(array('lesson_id' => $data['courseID']));//course refer to lesson
            $this->db->delete('course_teacher');
            $this->db->where(array('lesson_id' => $data['courseID']));//course refer to lesson
            $this->db->delete('course_student_new');
            $this->db->where(array('id' => $data['courseID']));//course refer to lesson
            $this->db->delete('course_scheduled_new');
            echo "1";
        }
    }

    public function assign()
    {
        $this->continueIfAllowed(array('allowed' => array('admin')));
        $data = $this->input->post(array('courseID','lessonID','userID','role'));

        if($data['role'] == "teacher") {
            $sql = array(
                'course_id' => $data['courseID'],
                'lesson_id' => $data['lessonID'],
                'teacher_id' => $data['userID'],
                'status_id' => ''
            );

            if(!$this->crud_model->check_assigned_t($data['courseID'], $data['lessonID'], $data['userID'])) {
                $this->db->insert('course_teacher', $sql);
                $id = $this->db->insert_id();
                echo "$id";
                ($this->event_model->trigger_first_lesson('Course_Teacher_First_Assignation', 'en', $data['userID'], $data['lessonID']));
                $this->event_model->trigger_lesson('Course_Teacher_Assignation', 'en', $data['userID'], $id);

            } else {
                echo "duplicate id";
            }
        } elseif($data['role'] == "student") {
            if ((int) $data['courseID'] > 0 && (int) $data['lessonID'] > 0 && (int) $data['userID'] > 0) {
                $sql = array(
                    'course_id' => $data['courseID'],
                    'lesson_id' => $data['lessonID'],
                    'student_id' => $data['userID'],
                    'status_id' => ''
                );

                if(!$this->crud_model->check_assigned_s($data['courseID'], $data['lessonID'], $data['userID'])) {
                    $this->db->insert('course_student_new', $sql);
                    $id = $this->db->insert_id();
                    $this->form_model->remove_pending_s($id);
                    ($this->event_model->trigger_first_lesson('Course_Student_First_Assignation', 'en', $data['userID'], $data['lessonID']));
                    $this->event_model->trigger_lesson('Course_Student_Assignation', 'en', $data['userID'], $data['lessonID']);
                    echo "$id";
                } else {
                    echo "duplicate id";
                }
            } else {
                echo 'missing fields';
            }
        } else {
            echo "error on role selection";
        }

    }

    public function presence()
    {
        $this->continueIfAllowed(array('allowed' => array('admin','teacher')));
        $data = $this->input->post(array('courseID','lessonID','userID','presenceID'));

        $sql = [
            'course_id'  => (int) $data['courseID'],
            'lesson_id'  => (int) $data['lessonID'],
            'student_id' => (int) $data['userID']
        ];

        try {
            $this->db->set('status_id', (int) $data['presenceID']);
            $this->db->set('status_update', date('Y-m-d h:i:s'));
            $this->db->where($sql);
            $this->db->update('course_student_new');
            //$id = $this->db->insert_id();
            $lang_id = $this->crud_model->get_user_lang($data['userID']);
            $lang_iso = $this->profile_model->intToIso($lang_id);

            switch ($data['presenceID']) {
                case '1':
                    //$this->event_model->trigger_lesson('Presence_Present',$lang_iso,$data['userID'],$data['lessonID']);
                    break;
                case '2':
                    //$this->event_model->trigger_lesson('Presence_Absent',$lang_iso,$data['userID'],$data['lessonID']);
                    break;
                case '3':
                    //$this->event_model->trigger_lesson('Presence_Excused',$lang_iso,$data['userID'],$data['lessonID']);
                    break;

                default:
                    // code...
                    break;
            }

            echo 1;
        } catch (Exception $e) {
            echo 'Error : ',  $e->getMessage(), "\n";
        }
        //print_r($this->db->last_query());
    }
    //
    public function removeAssign()
    {
        $this->continueIfAllowed(array('allowed' => array('admin','teacher')));
        $data = $this->input->post(array('userId','lessonId','role'));
        //echo ">".$data['lessonId'].">".$data['userId']."|";
        if($data['role'] == "teacher") {
            $clause = array('lesson_id' => $data['lessonId'],'teacher_id' => $data['userId']);
            $this->db->where($clause);
            if($this->db->delete('course_teacher')) {
                echo "1";
            } else {
                echo "-1";
            }
        } elseif($data['role'] == "student") {
            $clause = array('lesson_id' => $data['lessonId'],'student_id' => $data['userId']);
            $this->db->where($clause);
            if($this->db->delete('course_student_new')) {
                echo "1";
            } else {
                echo "-1";
            }
        } else {
            echo "error";
        }

    }
    //
    public function removeAssignAll()
    {
        $this->continueIfAllowed(array('allowed' => array('admin','teacher')));
        $data = $this->input->post(array('userId','courseId','role'));
        //echo ">".$data['lessonId'].">".$data['userId']."|";
        if($data['role'] == "teacher") {
            $clause = array('course_id' => $data['courseId'],'teacher_id' => $data['userId']);
            $this->db->where($clause);
            if($this->db->delete('course_teacher')) {
                echo "1";
            } else {
                echo "-1";
            }
            //echo $this->db->last_query();
        } elseif($data['role'] == "student") {
            $clause = array('course_id' => $data['courseId'],'student_id' => $data['userId']);
            $this->db->where($clause);
            if($this->db->delete('course_student_new')) {
                echo "1";
            } else {
                echo "-1";
            }
        } else {
            echo "error";
        }
    }

    //
    public function notify_presence($lesson)
    {
        //moved into notification model
        /*
        //$this->continueIfAllowed(array('allowed'=>array('admin','teacher')));

        if(!isset($lesson)){
          $lesson = $this->input->post('lesson');
        }
        $query = $this->db->get_where('course_student_new',array('lesson_id' => $lesson));
        $query = $query->result_array();

        //var_dump($query);
        foreach ($query as $key => $row) {
            if($row['status_id']=="3"){
              echo 'notify student:'.$row['student_id'].' for presence:'.$row['lesson_id'];
              //echo $this->security_model->generateToken($lesson.$row['student_id']);
              echo "\n Debug:";
              //$this->email_model->presence_notification_email($row['student_id'],$row['lesson_id'],$row['course_id'],'en');
              $lang = $this->profile_model->get_user_master_lang($row['student_id']);

              //var_dump($lang);
              var_dump($this->email_model->presence_notification_email($row['student_id'],$row['lesson_id'],$row['course_id'],$lang));
            }
        }

        $this->db->set(array("LessonLocked"=>"1"));
        $this->db->where('ID',$lesson);
        $this->db->update('course_scheduled_new');
        //echo "ok";
        */
    }

    public function send_notification_missing_presences()
    {
        $this->continueIfAllowed(['allowed' => ['admin']]);

        $course_id = (int) $this->input->post('course_id');
        if (empty($course_id) || $course_id <= 0) {
            echo json_encode([
                'msg' => 'Bad course ID',
                'success' => false
            ]);
            return;
        }
        $teachers = $this->course_model->get_courses_teachers([$course_id]);

        foreach($teachers[$course_id] as $t) {
            $this->event_model->trigger_course('missing_presences_course', 'fr', (int) $t['id']);
        }

        echo json_encode([
            'success' => true
        ]);
        return;
    }
    //
    public function confirm()
    {
        $this->continueIfAllowed(array('allowed' => array('admin','teacher')));
        $data = $this->input->post(array('id','status','comment'));
        if(isset($data)) {
            $sql = array(
                'LessonDone' => $data['status'],
                'LessonComment' => $data['comment']
            );
            //$this->error(var_dump($sql));
            $this->db->set($sql);
            $this->db->where('ID', $data['id']);
            $this->db->update('course_scheduled_new');
            echo "1";
        } else {
            echo "please re-select the course";
        }
    }
    //
    public function get_previous_lesson($lesson_id, $course)
    {
        /*  $lesson_id = '2804';
          $course = '262';*/

        $this->db->order_by('LessonDate', 'ASC');
        $data = $this->db->get_where('course_scheduled_new', array('CourseID' => $course))->result_array();
        foreach ($data as $key => $lesson) {
            if($lesson['ID'] == $lesson_id) {
                $previous_lesson = $data[$key - 1];
                if(count($previous_lesson) > 0) {
                    return(array($previous_lesson['ID'],$previous_lesson['CourseID']));
                }
            }
        }

        $this->db->order_by('ID', 'DESC');
        $data = $this->db->get_where('course_scheduled_new', array('CourseID' => $course))->result_array();

        foreach ($data as $key => $lesson) {
            if($lesson['ID'] == $lesson_id) {

                $previous_lesson = $data[$key + 1];
                //var_dump($previous_lesson);
                if(count($previous_lesson) > 0) {
                    return(array($previous_lesson['ID'],$previous_lesson['CourseID']));
                }
            }
        }
        return "no lesson";
    }

    public function check_if_locked($lesson)
    {
        $data = $this->db->get_where('course_scheduled_new', array('ID' => $lesson))->result_array();
        return $data[0]['LessonLocked'];
    }

    public function check_professor()
    {
        $c = $this->input->post('course');
        $p = $this->crud_model->get_course_teachers($c);
        //var_dump($p);
        //echo "false"; return;
        if($p != '[]') {
            echo "true";
        } else {
            echo "false";
        }
    }


    //========================
    //   Assign V2
    //========================
    public function get_lessons_assign()
    {
        $course = $this->input->post('course');
        $target = $this->input->post('target'); // teacher / student

        if($target == "student") {
            $lessons_list = $this->lesson_model->lessons_with_students((int) $course);
        } elseif($target == "teacher") {            
            $lessons_list = $this->lesson_model->lessons_with_teachers((int) $course);
        }

        echo json_encode($lessons_list);
    }

    public function assign_lesson()
    {
        $this->continueIfAllowed(['allowed' => ['admin']]);

        $lesson_id = $this->input->post('lesson');
        $course_id = (int) $this->input->post('course');
        $user_id = (int) $this->input->post('user');
        $target = $this->input->post('target');
        $teacher_role_id = (int) $this->input->post('teacher_role_id');

        if (empty($user_id) || empty($course_id) || empty($lesson_id) || empty($target)) {
            echo json_encode(['success' => false, 'message' => 'Missing field(s)']);
            return;
        }
        if ($target === "teacher" && empty(Teacher_model::TEACHER_ROLES[$teacher_role_id])) {
            echo json_encode(['success' => false, 'message' => 'Bad teacher role']);
            return;
        }

        $user = $this->users_model->get_entry($user_id);
        if (empty($user)) {
            echo json_encode(['success' => false, 'message' => 'User not found']);
            return;
        }

        if($target == "student") {
            if($lesson_id == "#") {
                /* assigns the student to each lesson in the course */
                $lessons = $this->crud_model->get_course_lessons($course_id);

                foreach ($lessons as $key => $l) {
                    if(!$this->crud_model->check_assigned_s($course_id, $l['ID'], $user_id)) {
                        $this->db->insert('course_student_new', [
                            'course_id' => $course_id,
                            'lesson_id' => $l['ID'],
                            'student_id' => $user_id,
                            'status_id' => ''
                        ]);
                    }
                }
            } elseif(is_numeric($lesson_id)) {
                /* Assign student for one lesson */
                if(!$this->crud_model->check_assigned_s($course_id, $lesson_id, $user_id)) {
                    $this->db->insert('course_student_new', [
                        'course_id' => $course_id,
                        'lesson_id' => $lesson_id,
                        'student_id' => $user_id,
                        'status_id' => ''
                    ]);
                }
            }
            echo json_encode(['success' => true]);
            return;
        } elseif ($target == "teacher") {

            if($lesson_id == "#") {
                /* assigns the teacher to each lesson in the course */
                $lessons = $this->crud_model->get_course_lessons($course_id);

                foreach ($lessons as $key => $l) {
                    if(!$this->crud_model->check_assigned_t($course_id, $l['ID'], $user_id)) {
                        $this->db->insert('course_teacher', [
                            'course_id' => $course_id,
                            'lesson_id' => $l['ID'],
                            'teacher_id' => $user_id,
                            'teacher_role_id' => $teacher_role_id,
                            'status_id' => ''
                        ]);
                        $this->event_model->trigger_first_lesson('Course_Teacher_First_Assignation', 'en', $user_id, $l['ID']);
                    }
                }
            } elseif(is_numeric($lesson_id)) {
                /* Assign teacher for one lesson */
                if(!$this->crud_model->check_assigned_t($course_id, $lesson_id, $user_id)) {
                    $this->db->insert('course_teacher', [
                        'course_id' => $course_id,
                        'lesson_id' => $lesson_id,
                        'teacher_id' => $user_id,
                        'teacher_role_id' => $teacher_role_id,
                        'status_id' => ''
                    ]);
                    $this->event_model->trigger_first_lesson('Course_Teacher_First_Assignation', 'en', $user_id, $lesson_id);
                }
            }

            echo json_encode(['success' => true]);
            return;
        } else {
            echo json_encode(['success' => false, 'message' => 'Target is not processable']);
            return;
        }
    }

    public function unassign_lesson()
    {
        $lesson = $this->input->post('lesson');
        $course = $this->input->post('course');
        $user = $this->input->post('student');
        if($user == null) {
            $user = $this->input->post('user');
        }
        $target = $this->input->post('target');
        $notify = $this->input->post('notify') === "true";

        if($target == "student") {
            if ($lesson == "#" && (int) $user > 0) {
                $this->db->where(['course_id' => (int) $course, 'student_id' => (int) $user]);
                if($this->db->delete('course_student_new')) {
                    echo '1';
                    if ($notify) {
                        $this->notify_teachers((int) $course, (int) $user);
                    }
                } else {
                    echo '-1';
                }
                return;
            } elseif(is_numeric($lesson) == true && (int) $user > 0) {
                $this->db->where([
                    'lesson_id' => (int) $lesson,
                    'student_id' => (int) $user
                ]);

                if($this->db->delete('course_student_new')) {
                    echo '1';
                    if ($notify) {
                        $this->notify_teachers((int) $course, (int) $user);
                    }
                } else {
                    echo '-1';
                }
            } else {
                // error on lesson id
                echo "error : lesson/student id null or not numeric";
            }

        } elseif ($target == "teacher") {
            if($lesson == "#" && $user == "#") {
                //remove all
                $this->db->where(array('course_id' => $course));
                if(!$this->db->delete('course_teacher')) {
                    echo '-1';
                } else {
                    echo "1";
                }
                return;
            } elseif ($lesson == "#" && (int) $user > 0) {
                $this->db->where(['course_id' => $course, 'teacher_id' => $user]);
                if(!$this->db->delete('course_teacher')) {
                    echo '-1';
                } else {
                    echo "1";
                }
                return;
            } elseif (is_numeric($lesson) == true && is_numeric($user) == true) {
                //focused lesson
                $clause = array(
                  'lesson_id' => $lesson,
                  'teacher_id' => $user
                );
                $this->db->where($clause);

                if(!$this->db->delete('course_teacher')) {
                    echo '-1';
                } else {
                    echo '1';
                }

            } else {
                // error on lesson id
                echo "error : lesson/teacher id null or not numeric";
            }

        }
    }

    /**
     * Change teacher for a lesson.
     * Refactoring of switch_assign
     *
     * @return String
     */
    public function change_assign_teacher()
    {
        $this->continueIfAllowed(['allowed' => ['admin', 'teacher']]);

        $teacher_lesson_id = (int) $this->input->post('teacher_lesson_id');
        $lesson_id = (int) $this->input->post('lesson_id');
        $new_teacher_id = (int) $this->input->post('new_teacher_id');        
        $switch_next_lessons = $this->input->post('switch_next_lessons') === "true";
        $old_teacher_id = ($this->userInfo['role'] == 'teacher') ? (int) $this->session->userdata('userID') : null;

        /** There are two way to change teacher assignement: by teacher_lesson_id directly or indirectly by lesson_id and teacher_id */
        if (empty($teacher_lesson_id) && (empty($old_teacher_id) || empty($lesson_id))) {
            echo json_encode(['error' => true, 'message' => 'missing field(s)']);
            return;
        }
        if (empty($new_teacher_id)){
            echo json_encode(['error' => true, 'message' => 'missing field(s)']);
            return;
        }

        $selected_teacher_lesson = null;
        if (!empty($teacher_lesson_id)) {
            $selected_teacher_lesson = $this->teacher_model->lesson_teacher_assignment($teacher_lesson_id);
        } else {
            $selected_teacher_lesson = $this->teacher_model->lesson_teacher_assignment_by_lesson_id($old_teacher_id, $lesson_id);
        }

        if (empty($selected_teacher_lesson)) {
            echo json_encode(['error' => true, 'message' => 'Lesson assignment not found']);
            return;
        }

        if ($switch_next_lessons) {
            $lessons_teacher = $this->teacher_model->lessons_teacher_assignment((int) $selected_teacher_lesson->teacher_id, (int) $selected_teacher_lesson->course_id);
            if (empty($selected_teacher_lesson)) {
                echo json_encode(['error' => true, 'message' => 'Lesson assignment not found']);
                return;
            }
            // Select only future lessons
            $selected_lesson_date = new Datetime($selected_teacher_lesson->LessonDate . " " . $selected_teacher_lesson->LessonStart);
            foreach ($lessons_teacher as $lesson_teacher) {
                if ((new Datetime($lesson_teacher->LessonDate . " " . $lesson_teacher->LessonStart)) < $selected_lesson_date) {
                    continue;
                }
                
                $update_row = $this->db->update('course_teacher', ['teacher_id' => (int) $new_teacher_id], [
                    'lesson_id' => (int) $lesson_teacher->lesson_id,
                    'teacher_id' => (int) $selected_teacher_lesson->teacher_id
                ]);
                if ($lesson_teacher->lesson_id) {
                    $this->db->insert('course_teacher_history', [
                        'Lesson' => (int) $lesson_teacher->lesson_id,
                        'Old_Teacher' => (int) $lesson_teacher->teacher_id,
                        'New_Teacher' => $new_teacher_id,
                        'Operator' => (int) $this->session->userdata('userID')
                    ]);

                    // Notify old teacher
                    $this->event_model->trigger_user('Course_Teacher_Unassignation', 'fr', (int) $selected_teacher_lesson->teacher_id);
                    // Notify new teacher
                    $this->event_model->trigger_lesson('Course_Teacher_Assignation_Switch', 'fr', $new_teacher_id, $lesson_teacher->lesson_id, (int) $lesson_teacher->teacher_id);
                }
            }

            echo json_encode(['error' => false, 'message' => 'Assignment successfuly changed']);
            return;
        } else {
            if ($this->db->update('course_teacher', ['teacher_id' => $new_teacher_id], ['id' => $selected_teacher_lesson->id])) {
                $this->db->insert('course_teacher_history', [
                    'Lesson' => (int) $selected_teacher_lesson->lesson_id,
                    'Old_Teacher' => (int) $selected_teacher_lesson->teacher_id,
                    'New_Teacher' => $new_teacher_id,
                    'Operator' => (int) $this->session->userdata('userID')
                ]);

                // Notify old teacher
                $this->event_model->trigger_user('Course_Teacher_Unassignation', 'fr', (int) $selected_teacher_lesson->teacher_id);
                // Notify new teacher
                $this->event_model->trigger_lesson('Course_Teacher_Assignation_Switch', 'fr', $new_teacher_id, $selected_teacher_lesson->lesson_id, (int) $selected_teacher_lesson->teacher_id);

                echo json_encode(['error' => false, 'message' => 'Assignment successfuly changed']);
                return;
            }
        }

        echo json_encode(['error' => true, 'message' => 'Assignment cannot be changed']);
        return;
    }

    public function switch_assign()
    {
        $this->continueIfAllowed(['allowed' => ['admin', 'teacher']]);

        $lesson = $this->input->post('lesson');
        $user = $this->input->post('user');
        $target = $this->input->post('target');
        $next = $this->input->post('next');

        if ($target == "teacher") {
            if(is_numeric($lesson) == true && is_numeric($user) == true) {

                if($next == 'false') {
                    $old_teacher = $this->crud_model->get_lesson_teacher($lesson)[0];
                    $sql = array(
                      'Lesson' => $lesson,
                      'Old_Teacher' => $old_teacher,
                      'New_Teacher' => $user,
                      'Operator' => $this->session->userdata('userID')
                    );
                    $this->db->insert('course_teacher_history', $this->crud_model->cleanArray($sql));

                    $this->event_model->trigger_user('Course_Teacher_Unassignation', 'fr', $this->crud_model->get_lesson_teacher($lesson)[0]);

                    //switch one
                    $this->db->where(array('lesson_id' => $lesson));
                    $this->db->set(array('teacher_id' => $user));
                    $this->db->update('course_teacher');


                    if($this->userInfo['role'] != "admin") {
                        $this->event_model->trigger_lesson('Course_Teacher_Assignation', 'fr', $user, $lesson);
                        echo "passed trigger Course_Teacher_Assignation \n";
                        echo $old_teacher;
                        var_dump($this->event_model->trigger_lesson('Course_Teacher_Assignation_Switch', 'fr', $user, $lesson, $old_teacher));
                        echo "passed trigger Course_Teacher_Assignation_Switch \n";
                    }
                } elseif($next == 'true') {
                    $future_lesson = $this->crud_model->get_future_lessons($lesson);

                    $error = false;
                    foreach ($future_lesson as $key => $fl) {
                        $this->db->where(array('lesson_id' => $fl['ID']));
                        $this->db->delete('course_teacher');
                        $success_insert = $this->db->insert('course_teacher', $this->crud_model->cleanArray([
                            'course_id' => $fl['CourseID'],
                            'lesson_id' => $fl['ID'],
                            'status_id' => '0',
                            'teacher_id' => $user
                        ]));

                        if($success_insert === false) {
                            $error = true;
                        }
                    }
                    echo $error ? 'true' : 'false';
                } else {
                    echo "error on next";
                }
            } else {
                // error on lesson id
                echo "error : lesson/teacher id null or not numeric";
            }
        }
    }

    /**
     * Change teacher role for an specific lesson
     * Ajax function
     *
     * @return void
     */
    public function change_teacher_role()
    {
        $this->continueIfAllowed(['allowed' => ['admin']]);

        $role_id = $this->input->post('role_id');
        $teacher_lesson_id = (int) $this->input->post('teacher_lesson_id');

        if (!isset($role_id) || empty(Teacher_model::TEACHER_ROLES[(int) $role_id])) {
            echo json_encode(['success' => false, 'message' => 'Bad teacher role']);
            return;
        }
        $role_id = (int) $role_id;

        $teacher_lesson = $this->teacher_model->lesson_teacher_assignment((int) $teacher_lesson_id);
        if (empty($teacher_lesson)) {
            echo json_encode(['success' => false, 'message' => 'Teacher or lesson don\'t exist']);
            return;
        }

        if ($this->teacher_model->change_lesson_role($teacher_lesson_id, $role_id)) {
            echo json_encode(['success' => true]);
            return;
        }

        echo json_encode(['success' => false, 'message' => 'Failed to update']);
        return;
    }

    private function notify_teachers(int $course_id, int $student_id) : bool
    {
        if ($course_id <= 0) {
            return false;
        }

        $this->load->model('users_model');
        $student = $this->users_model->get_entry($student_id, true);
        if (empty($student)) {
            return false;
        }

        $teachers = $this->crud_model->get_course_futur_teacher((int) $course_id);
        foreach($teachers as $teacher) {
            $this->event_model->trigger_assignation('Course_Student_Unassignation_To_Teacher', 'fr', (int) $teacher[0], [
                'teacher' => (int) $teacher[0], // Teacher ID
                'course' => (int) $course_id,
                'student' => strtoupper($student->last_name) . " " . ucfirst(strtolower($student->first_name))
            ]);
        }

        return true;
    }
}

Youez - 2016 - github.com/yon3zu
LinuXploit