public function validateSave($obj)
 {
     if (SettingsManager::getInstance()->getSetting("Attendance: Time-sheet Cross Check") == "1") {
         $attendance = new Attendance();
         $list = $attendance->Find("employee = ? and in_time <= ? and out_time >= ?", array($obj->employee, $obj->date_start, $obj->date_end));
         if (empty($list) || count($list) == 0) {
             return new IceResponse(IceResponse::ERROR, "The time entry can not be added since you have not marked attendance for selected period");
         }
     }
     return new IceResponse(IceResponse::SUCCESS, "");
 }
 public function getInitData($req)
 {
     $data = array();
     $employees = new Employee();
     $data['numberOfEmployees'] = $employees->Count("1 = 1");
     $company = new CompanyStructure();
     $data['numberOfCompanyStuctures'] = $company->Count("1 = 1");
     $user = new User();
     $data['numberOfUsers'] = $user->Count("1 = 1");
     $project = new Project();
     $data['numberOfProjects'] = $project->Count("status = 'Active'");
     $attendance = new Attendance();
     $data['numberOfAttendanceLastWeek'] = $attendance->Count("in_time > '" . date("Y-m-d H:i:s", strtotime("-1 week")) . "'");
     if (empty($data['numberOfAttendanceLastWeek'])) {
         $data['numberOfAttendanceLastWeek'] = 0;
     }
     $empLeave = new EmployeeLeave();
     $data['numberOfLeaves'] = $empLeave->Count("date_start > '" . date("Y-m-d") . "'");
     $timeEntry = new EmployeeTimeEntry();
     $data['numberOfAttendanceLastWeek'] = $timeEntry->Count("in_time > '" . date("Y-m-d H:i:s", strtotime("-1 week")) . "'");
     $candidate = new Candidate();
     $data['numberOfCandidates'] = $candidate->Count("1 = 1");
     $job = new Job();
     $data['numberOfJobs'] = $job->Count("status = 'Active'");
     $course = new Course();
     $data['numberOfCourses'] = $course->Count("1 = 1");
     return new IceResponse(IceResponse::SUCCESS, $data);
 }
Пример #3
0
 public function initValidator()
 {
     $this->validator = new Violin();
     $this->validator->addRuleMessage('required', "Поле <b>{field}</b> обязательно для заполнения");
     $this->validator->addRuleMessage('matches', 'Поле <b>{field}</b> должно совпадать с полем <b>{$0}</b>');
     $this->validator->addRuleMessage('int', 'Поле <b>{field}</b> должно содержать только цифры');
     $this->validator->addRuleMessage('email', "Поле <b>{field}</b> должно иметь корректный формат адреса электронной почты(во <b>внутреннем</b> сегменте банка), например SBT-Tomarov-IV<b>@mail.ca.sbrf.ru</b> ");
     $this->validator->addRuleMessage('pwd', 'Поле {field} должно содержать только латинские буквы, цифры или спецсимволы(!@#$%*). Минимум 5 символов');
     $this->validator->addRule('pwd', function ($value, $input, $args) {
         $result = false;
         if (preg_match("/^[0-9A-Za-z!@#\$%*]{4,}\$/", $value)) {
             $result = true;
         }
         return $result;
     });
     $this->validator->addRuleMessage('userFree', 'Пользователь с именем <b>{value}</b> уже существует в системе');
     $this->validator->addRule('userFree', function ($value, $input, $args) {
         $userCount = User::where('login', strtoupper($value))->count();
         return $userCount ? false : true;
     });
     $this->validator->addRuleMessage('attendance_is_tech_supportable', 'На выбранной точке ВКС, тех. поддержка не оказывается, извините');
     $this->validator->addRule('attendance_is_tech_supportable', function ($value, $input, $args) {
         if (!$value) {
             return true;
         }
         //if value not presented, continue
         try {
             $att = Attendance::findOrFail($value);
         } catch (Exception $e) {
             return false;
         }
         return $att->tech_supportable ? true : false;
     });
 }
 public function run()
 {
     $faker = Faker::create();
     foreach (range(1, 10) as $index) {
         Attendance::create([]);
     }
 }
Пример #5
0
 function test2($date, $attendance_id)
 {
     try {
         $attendance = Attendance::findOrFail($attendance_id);
     } catch (Exception $e) {
         $this->error('404');
     }
     $vc = new Vks_controller();
     $start = date_create($date)->setTime(0, 0);
     $end = date_create($date)->setTime(23, 59);
     $requested_participant_id = intval($attendance_id);
     $vkses = Vks::where('start_date_time', ">=", $start)->where('start_date_time', '<=', $end)->whereIn('status', [VKS_STATUS_PENDING, VKS_STATUS_APPROVED])->notSimple()->with('participants')->get();
     $filtered_vkses = array();
     if (count($vkses)) {
         foreach ($vkses as $vks) {
             if (count($vks->participants)) {
                 foreach ($vks->participants as $participant) {
                     if ($participant->id === $requested_participant_id) {
                         $filtered_vkses[] = $vc->humanize($vks);
                     }
                 }
             }
         }
     }
     return $this->render('test/test2', compact('attendance', 'filtered_vkses', 'date'));
 }
 public function getInitData($req)
 {
     $data = array();
     $emp = new Employee();
     $data['numberOfEmployees'] = $emp->Count("status = 'Active' and supervisor = ?", array($this->getCurrentProfileId()));
     $data['lastTimeSheetHours'] = $this->getLastTimeSheetHours($req)->getData();
     $data['activeProjects'] = $this->getEmployeeActiveProjects($req)->getData();
     $data['pendingLeaves'] = $this->getPendingLeaves($req)->getData();
     $candidate = new Candidate();
     $data['numberOfCandidates'] = $candidate->Count("1 = 1");
     $job = new Job();
     $data['numberOfJobs'] = $job->Count("status = 'Active'");
     $attendance = new Attendance();
     $data['numberOfAttendanceLastWeek'] = $attendance->Count("in_time > '" . date("Y-m-d H:i:s", strtotime("-1 week")) . "'");
     $course = new Course();
     $data['numberOfCourses'] = $course->Count("1 = 1");
     return new IceResponse(IceResponse::SUCCESS, $data);
 }
Пример #7
0
 static function getDaysAttendanceForStudent($studentId, $batchId, $attendanceDate)
 {
     //echo "student_id".$studentId.' batchId'.$batchId.' attendanceDate'.$attendanceDate;
     $attendance = Attendance::where('student_id', '=', $studentId)->where('batch_id', '=', $batchId)->where('attendance_date', '=', $attendanceDate)->first();
     //print_r(DB::getQueryLog());
     if ($attendance) {
         return $attendance;
     }
     return false;
 }
Пример #8
0
 public function __construct()
 {
     $this->data['setting'] = Setting::all()->first();
     if (!isset($this->data['setting']) && count($this->data['setting']) == 0) {
         die('Database not uploaded.Please Upload the database');
     }
     if (count($this->data['setting'])) {
     }
     $this->data['loggedAdmin'] = Auth::admin()->get();
     $this->data['pending_applications'] = Attendance::where('application_status', '=', 'pending')->get();
 }
 /**
  * Approve the specified attendance
  *
  * @param $id
  * @return mixed
  */
 public function approve($id)
 {
     if (!Sentry::getUser()) {
         return Redirect::route('sessions.create');
     }
     $a = Attendance::find($id);
     if ($a->approved == 0) {
         $a->approved = 1;
     } elseif ($a->approved == 1) {
         $a->approved = 2;
     }
     $a->save();
     return Redirect::route('attendances.index');
 }
Пример #10
0
 /**
  * Get the last absent days
  * If the user is not absent since joining then.Joining date is last absent date
  */
 public function lastAbsent($employeeID, $type = 'days')
 {
     $absent = Attendance::where('status', '=', 'absent')->where('employeeID', '=', $employeeID)->where(function ($query) {
         $query->where('application_status', '=', 'approved')->orWhere('application_status', '=', null);
     })->orderBy('date', 'desc')->first();
     $joiningDate = Employee::select('joiningDate')->where('employeeID', '=', $employeeID)->first();
     $lastDate = date('Y-m-d');
     $old_date = isset($absent->date) ? $absent->date : $joiningDate->joiningDate;
     $diff = date_diff(date_create($old_date), date_create($lastDate));
     $difference = $diff->format('%R%a') . ' day ago';
     if ($type == 'days') {
         return $difference;
     } elseif ($type == 'date') {
         return date_create($old_date)->format('d-M-Y');
     }
 }
 /**
  * Register action
  * @param type $data
  * @param type $form
  * @return \SS_HTTPResponse
  */
 public function doRegister($data, $form)
 {
     $att = Attendance::get()->filter(array('MemberID' => $data['MemberID'], 'MatchID' => $data['MatchID']));
     if ($att->exists()) {
         $r = $att->sort('LastEdited', 'DESC')->First();
     } else {
         $r = new Attendance();
     }
     $form->saveInto($r);
     $r->write();
     // $from = Email::getAdminEmail();
     // $to = $r->Email;
     // $bcc = $EventDetails->RSVPEmail;
     // $subject = "Event Registration - ".$EventDetails->Title." - ".date("d/m/Y H:ia");
     // $body = "";
     // $email = new Email($from, $to, $subject, $body, null, null, $bcc);
     // $email->setTemplate('EventRegistration');
     // $email->send();
     return Controller::curr()->redirectBack();
 }
 public function addRequest($vks_id)
 {
     try {
         $vks = Vks::with('tech_support_requests')->findOrFail($vks_id);
     } catch (Exception $e) {
         $this->error('404');
     }
     $available_points = Attendance::techSupportable()->get()->toArray();
     array_walk($available_points, function (&$e) {
         $e['selectable'] = true;
     });
     if (count($vks->tech_support_requests)) {
         foreach ($vks->tech_support_requests as $request) {
             foreach ($available_points as &$point) {
                 if ($request->att_id == $point['id']) {
                     $point['selectable'] = false;
                 }
             }
         }
     }
     return $this->render('techsupport/addRequest', compact('vks', 'available_points'));
 }
Пример #13
0
 function checkinAction()
 {
     $session = SessionWrapper::getInstance();
     $this->_helper->layout->disableLayout();
     $this->_helper->viewRenderer->setNoRender(TRUE);
     $formvalues = $this->_getAllParams();
     debugMessage('test');
     $testarray = array("userid" => 15, 'datein' => 'Jan 27, 2015', 'timein' => '08:00 AM', 'dateout' => '', 'timeout' => '', 'reason' => '', 'createdby' => 15);
     $attendance = new Attendance();
     debugMessage($attendance->toArray());
     $attendance->processPost($testarray);
     debugMessage($attendance->toArray());
     debugMessage('errors are ' . $attendance->getErrorStackAsString());
     try {
         $attendance->save();
         debugMessage('saved successfully');
         debugMessage($attendance->toArray());
     } catch (Exception $e) {
         debugMessage('error: ' . $e->getMessage());
     }
 }
Пример #14
0
}
if (isset($_GET['isStudentView']) && $_GET['isStudentView'] == 'true') {
    $action = 'attendance_list';
}
// get attendance id
$attendance_id = 0;
if (isset($_GET['attendance_id'])) {
    $attendance_id = intval($_GET['attendance_id']);
}
// get calendar id
$calendar_id = '';
if (isset($_GET['calendar_id'])) {
    $calendar_id = intval($_GET['calendar_id']);
}
// instance attendance object for using like library here
$attendance = new Attendance();
// attendance controller object
$attendance_controller = new AttendanceController();
// get attendance data
if (!empty($attendance_id)) {
    // attendance data by id
    $attendance_data = $attendance->get_attendance_by_id($attendance_id);
}
$htmlHeadXtra[] = api_get_jqgrid_js();
$htmlHeadXtra[] = '<script>

$(function() {
	$("table th img").click(function() {
		var col_id = this.id;
		var col_split = col_id.split("_");
		var calendar_id = col_split[2];
Пример #15
0
            if ($value->BookingArchived == null && $value->attended == null && strtotime(Session::getCurrentDateTime()) > strtotime($value->starting)) {
                $page['booking'] = $value;
            } else {
                Session::setError('Booking has not been completed, please try again.');
                Session::redirect('/bookings');
            }
        }
    }
}
if ($page['booking'] == null) {
    Session::setError('Booking does not exist, please try again.');
    Session::redirect('/bookings');
}
// Make sure attendance hasn't already been recorded for this booking,
// or the booking hasn't been set as cancelled
$attendance = Attendance::getAttendance($bookingId);
if ($attendance != null) {
    Session::setError('You have already recorded attendance for this workshop.');
    Session::redirect('/bookings');
}
// If the request is a post
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $createNonAttendance = Attendance::createNonAttendance($bookingId, $page['booking']->workshopID);
    $updateBooking = UTSHelpsAPI::UpdateWorkshopBooking(['workshopId' => $page['booking']->workshopID, 'studentId' => User::getPaddedId(), 'Attended' => 0, 'Canceled' => 0, 'userId' => 123]);
    if ($createNonAttendance && $updateBooking != null && $updateBooking->IsSuccess == 1 && User::addStrike()) {
        Session::setSuccess('Successfully recorded non-attendance for this booking.');
        Session::redirect('/bookings');
    }
    Session::setError('Unable to record non-attendance for this booking, please try again.');
    Session::redirect('/bookings');
}
 /**
  * Build the attendances
  * @param int $session_id Internal session ID
  * @param int $courseId Internal course ID
  * @param bool $with_base_content Whether to include content from the course without session or not
  * @param array $id_list If you want to restrict the structure to only the given IDs
  */
 public function build_attendance($session_id = 0, $courseId = 0, $with_base_content = false, $id_list = array())
 {
     $table_attendance = Database::get_course_table(TABLE_ATTENDANCE);
     $table_attendance_calendar = Database::get_course_table(TABLE_ATTENDANCE_CALENDAR);
     $sessionCondition = api_get_session_condition($session_id, true, $with_base_content);
     $sql = 'SELECT * FROM ' . $table_attendance . '
             WHERE c_id = ' . $courseId . ' ' . $sessionCondition;
     $db_result = Database::query($sql);
     while ($row = Database::fetch_array($db_result, 'ASSOC')) {
         $obj = new Attendance($row);
         $sql = 'SELECT * FROM ' . $table_attendance_calendar . '
                 WHERE c_id = ' . $courseId . ' AND attendance_id = ' . $row['id'];
         $result = Database::query($sql);
         while ($sub_row = Database::fetch_array($result, 'ASSOC')) {
             $obj->add_attendance_calendar($sub_row);
         }
         $this->course->add_resource($obj);
     }
 }
Пример #17
0
	public function savePunch($req){
		$req->date = $req->time;
		
		/*
		if(strtotime($req->date) > strtotime($req->cdate)){
			return new IceResponse(IceResponse::ERROR,"You are not allowed to punch a future time");
		}
		*/
		
		//check if there is an open punch
		$openPunch = $this->getPunch($req)->getData();
		
		if(empty($openPunch)){
			$openPunch = new Attendance();
		}

		$dateTime = $req->date;
		$arr = explode(" ",$dateTime);
		$date = $arr[0];
		
		$currentDateTime = $req->cdate;
		$arr = explode(" ",$currentDateTime);
		$currentDate = $arr[0];
		
		if($currentDate != $date){
			return new IceResponse(IceResponse::ERROR,"You are not allowed to punch time for a previous date");
		}
	
		$employee = $this->baseService->getElement('Employee',$this->getCurrentProfileId(),null,true);
		
		//check if dates are differnet
		$arr = explode(" ",$openPunch->in_time);
		$inDate = $arr[0];
		if(!empty($openPunch->in_time) && $inDate != $date){
			return new IceResponse(IceResponse::ERROR,"Attendance entry should be within a single day");
		}
		
		//compare dates
		if(!empty($openPunch->in_time) && strtotime($dateTime) <= strtotime($openPunch->in_time)){
			return new IceResponse(IceResponse::ERROR,"Punch-in time should be lesser than Punch-out time");
		}
	
		//Find all punches for the day
		$attendance = new Attendance();
		$attendanceList = $attendance->Find("employee = ? and DATE_FORMAT( in_time,  '%Y-%m-%d' ) = ?",array($employee->id,$date));
		
		foreach($attendanceList as $attendance){
			if(!empty($openPunch->in_time)){
				if($openPunch->id == $attendance->id){
					continue;
				}
				if(strtotime($attendance->out_time) >= strtotime($dateTime) && strtotime($attendance->in_time) <= strtotime($dateTime)){
					//-1---0---1---0 || ---0--1---1---0
					return new IceResponse(IceResponse::ERROR,"Time entry is overlapping with an existing one 1");
				}else if(strtotime($attendance->out_time) >= strtotime($openPunch->in_time) && strtotime($attendance->in_time) <= strtotime($openPunch->in_time)){
					//---0---1---0---1 || ---0--1---1---0
					return new IceResponse(IceResponse::ERROR,"Time entry is overlapping with an existing one 2");
				}else if(strtotime($attendance->out_time) <= strtotime($dateTime) && strtotime($attendance->in_time) >= strtotime($openPunch->in_time)){
					//--1--0---0--1--
					return new IceResponse(IceResponse::ERROR,"Time entry is overlapping with an existing one 3 ".$attendance->id);
				}	
			}else{
				if(strtotime($attendance->out_time) >= strtotime($dateTime) && strtotime($attendance->in_time) <= strtotime($dateTime)){
					//---0---1---0 
					return new IceResponse(IceResponse::ERROR,"Time entry is overlapping with an existing one 4");
				}	
			}
		}
		if(!empty($openPunch->in_time)){
			$openPunch->out_time = $dateTime;
			$openPunch->note = $req->note;
			$this->baseService->audit(IceConstants::AUDIT_ACTION, "Punch Out \ time:".$openPunch->out_time);
		}else{
			$openPunch->in_time = $dateTime;
			$openPunch->out_time = '0000-00-00 00:00:00';
			$openPunch->note = $req->note;
			$openPunch->employee = $employee->id;
			$this->baseService->audit(IceConstants::AUDIT_ACTION, "Punch In \ time:".$openPunch->in_time);
		}
		$ok = $openPunch->Save();
		
		if(!$ok){
			LogManager::getInstance()->info($openPunch->ErrorMsg());
			return new IceResponse(IceResponse::ERROR,"Error occured while saving attendance");
		}
		return new IceResponse(IceResponse::SUCCESS,$openPunch);
	
	}
Пример #18
0
 /**
  * This method is used for thematic advance control (update, insert or listing)
  * render to thematic_advance.php
  * @param 	string	$action
  *
  */
 public function thematic_advance($action)
 {
     $thematic = new Thematic();
     $attendance = new Attendance();
     $data = array();
     $displayHeader = !empty($_REQUEST['display']) && $_REQUEST['display'] === 'no_header' ? false : true;
     // get data for attendance input select
     $attendance_list = $attendance->get_attendances_list();
     $attendance_select = array();
     $attendance_select[0] = get_lang('SelectAnAttendance');
     foreach ($attendance_list as $attendance_id => $attendance_data) {
         $attendance_select[$attendance_id] = $attendance_data['name'];
     }
     $thematic_id = intval($_REQUEST['thematic_id']);
     $thematic_advance_id = isset($_REQUEST['thematic_advance_id']) ? intval($_REQUEST['thematic_advance_id']) : null;
     $thematic_advance_data = array();
     switch ($action) {
         case 'thematic_advance_delete':
             if (!empty($thematic_advance_id)) {
                 if (api_is_allowed_to_edit(null, true)) {
                     $thematic->thematic_advance_destroy($thematic_advance_id);
                 }
                 header('Location: index.php');
                 exit;
             }
             break;
         case 'thematic_advance_list':
             if (!api_is_allowed_to_edit(null, true)) {
                 echo '';
                 exit;
             }
             if (isset($_REQUEST['start_date_type']) && $_REQUEST['start_date_type'] == 1 && empty($_REQUEST['start_date_by_attendance']) || !empty($_REQUEST['duration_in_hours']) && !is_numeric($_REQUEST['duration_in_hours'])) {
                 if ($_REQUEST['start_date_type'] == 1 && empty($_REQUEST['start_date_by_attendance'])) {
                     $start_date_error = true;
                     $data['start_date_error'] = $start_date_error;
                 }
                 if (!empty($_REQUEST['duration_in_hours']) && !is_numeric($_REQUEST['duration_in_hours'])) {
                     $duration_error = true;
                     $data['duration_error'] = $duration_error;
                 }
                 $data['action'] = $_REQUEST['action'];
                 $data['thematic_id'] = $_REQUEST['thematic_id'];
                 $data['attendance_select'] = $attendance_select;
                 if (isset($_REQUEST['thematic_advance_id'])) {
                     $data['thematic_advance_id'] = $_REQUEST['thematic_advance_id'];
                     $thematic_advance_data = $thematic->get_thematic_advance_list($_REQUEST['thematic_advance_id']);
                     $data['thematic_advance_data'] = $thematic_advance_data;
                 }
             } else {
                 if (api_is_allowed_to_edit(null, true)) {
                     $thematic_advance_id = isset($_REQUEST['thematic_advance_id']) ? $_REQUEST['thematic_advance_id'] : null;
                     $thematic_id = $_REQUEST['thematic_id'];
                     $content = isset($_REQUEST['content']) ? $_REQUEST['content'] : null;
                     $duration = isset($_REQUEST['duration_in_hours']) ? $_REQUEST['duration_in_hours'] : null;
                     if (isset($_REQUEST['start_date_type']) && $_REQUEST['start_date_type'] == 2) {
                         $start_date = $_REQUEST['custom_start_date'];
                         $attendance_id = 0;
                     } else {
                         $start_date = isset($_REQUEST['start_date_by_attendance']) ? $_REQUEST['start_date_by_attendance'] : null;
                         $attendance_id = isset($_REQUEST['attendance_select']) ? $_REQUEST['attendance_select'] : null;
                     }
                     $thematic->set_thematic_advance_attributes($thematic_advance_id, $thematic_id, $attendance_id, $content, $start_date, $duration);
                     $affected_rows = $thematic->thematic_advance_save();
                     if ($affected_rows) {
                         // get last done thematic advance before move thematic list
                         $last_done_thematic_advance = $thematic->get_last_done_thematic_advance();
                         // update done advances with de current thematic list
                         if (!empty($last_done_thematic_advance)) {
                             $thematic->update_done_thematic_advances($last_done_thematic_advance);
                         }
                     }
                 }
             }
             break;
         default:
             $thematic_advance_data = $thematic->get_thematic_advance_list($thematic_advance_id);
             break;
     }
     // get calendar select by attendance id
     $calendar_select = array();
     if (!empty($thematic_advance_data)) {
         if (!empty($thematic_advance_data['attendance_id'])) {
             $attendance_calendar = $attendance->get_attendance_calendar($thematic_advance_data['attendance_id']);
             if (!empty($attendance_calendar)) {
                 foreach ($attendance_calendar as $calendar) {
                     $calendar_select[$calendar['date_time']] = $calendar['date_time'];
                 }
             }
         }
     }
     $data['action'] = $action;
     $data['thematic_id'] = $thematic_id;
     $data['thematic_advance_id'] = $thematic_advance_id;
     $data['attendance_select'] = $attendance_select;
     $data['thematic_advance_data'] = $thematic_advance_data;
     $data['calendar_select'] = $calendar_select;
     $layoutName = $displayHeader ? 'layout' : 'layout_no_header';
     // render to the view
     $this->view->set_data($data);
     $this->view->set_layout($layoutName);
     $this->view->set_template('thematic_advance');
     $this->view->render();
 }
 /**
  * Gets attendance base in the table:
  * TABLE_STATISTIC_TRACK_E_COURSE_ACCESS
  * @param bool $showForm
  * @throws ViewException
  */
 public function getAttendanceBaseInLogin($showForm = false, $exportToPdf = true)
 {
     $table = null;
     $formToDisplay = null;
     $startDate = null;
     $endDate = null;
     $sessionId = api_get_session_id();
     if ($showForm) {
         $form = new FormValidator('search', 'post', api_get_self() . '?' . api_get_cidreq() . '&action=calendar_logins');
         $form->addDateRangePicker('range', get_lang('DateRange'));
         $form->addButton('submit', get_lang('Submit'));
         if ($form->validate()) {
             $values = $form->getSubmitValues();
             $startDate = api_get_utc_datetime($values['range_start']);
             $endDate = api_get_utc_datetime($values['range_end']);
         }
         $formToDisplay = $form->returnForm();
     } else {
         if (!empty($sessionId)) {
             $sessionInfo = api_get_session_info($sessionId);
             $startDate = $sessionInfo['access_start_date'];
             $endDate = $sessionInfo['access_end_date'];
         }
     }
     $attendance = new Attendance();
     if ($exportToPdf) {
         $result = $attendance->exportAttendanceLogin($startDate, $endDate);
         if (empty($result)) {
             api_not_allowed(true, get_lang('NoDataAvailable'));
         }
     }
     $table = $attendance->getAttendanceLoginTable($startDate, $endDate);
     $data = array('form' => $formToDisplay, 'table' => $table);
     $this->view->set_data($data);
     $this->view->set_layout('layout');
     $this->view->set_template('calendar_logins');
     $this->view->render();
 }
Пример #20
0
 * @package chamilo.attendance
 */
// protect a course script
api_protect_course_script(true);
if (api_is_allowed_to_edit(null, true)) {
    $param_gradebook = '';
    if (isset($_SESSION['gradebook'])) {
        $param_gradebook = '&gradebook=' . Security::remove_XSS($_SESSION['gradebook']);
    }
    echo '<div class="actions">';
    echo '<a href="index.php?' . api_get_cidreq() . $param_gradebook . '&action=attendance_add">' . Display::return_icon('new_attendance_list.png', get_lang('CreateANewAttendance'), '', ICON_SIZE_MEDIUM) . '</a>';
    /*echo '<a href="index.php?'.api_get_cidreq().$param_gradebook.'&action=calendar_logins">'.
      Display::return_icon('attendance_list.png',get_lang('Logins'),'',ICON_SIZE_MEDIUM).'</a>';*/
    echo '</div>';
}
$attendance = new Attendance();
if ($attendance->get_number_of_attendances() == 0) {
    $attendance->set_name(get_lang('Attendances'));
    $attendance->set_description(get_lang('Attendances'));
    $attendance->attendance_add();
}
$table = new SortableTable('attendance_list', array('Attendance', 'get_number_of_attendances'), array('Attendance', 'get_attendance_data'), $default_column);
$table->set_additional_parameters($parameters);
$table->set_header(0, '', false, array('style' => 'width:20px;'));
$table->set_header(1, get_lang('Name'), true);
$table->set_header(2, get_lang('Description'), true);
$table->set_header(3, get_lang('CountDoneAttendance'), true, array('style' => 'width:90px;'));
if (api_is_allowed_to_edit(null, true)) {
    $table->set_header(4, get_lang('Actions'), false, array('style' => 'text-align:center'));
    $actions = array('attendance_set_invisible_select' => get_lang('SetInvisible'), 'attendance_set_visible_select' => get_lang('SetVisible'));
    $allow = api_get_configuration_value('allow_delete_attendance');
Пример #21
0
 </tr>
 </table>
 <?php 
 $table_title = '';
 if (!empty($sessionId)) {
     $session_name = api_get_session_name($sessionId);
     $table_title = $session_name ? Display::return_icon('session.png', get_lang('Session'), array(), ICON_SIZE_SMALL) . ' ' . $session_name . ' ' : '';
 }
 if (!empty($info_course['title'])) {
     $table_title .= $info_course ? Display::return_icon('course.png', get_lang('Course'), array(), ICON_SIZE_SMALL) . ' ' . $info_course['title'] . '  ' : '';
 }
 echo Display::page_subheader($table_title);
 if (empty($_GET['details'])) {
     $csv_content[] = array();
     $csv_content[] = array(get_lang('Session', ''), get_lang('Course', ''), get_lang('Time', ''), get_lang('Progress', ''), get_lang('Score', ''), get_lang('AttendancesFaults', ''), get_lang('Evaluations'));
     $attendance = new Attendance();
     foreach ($courses_in_session as $key => $courses) {
         $sessionId = $key;
         $session_info = api_get_session_info($sessionId);
         $session_name = '';
         if ($session_info) {
             $session_name = $session_info['name'];
         }
         $access_start_date = '';
         if (!empty($session_info['access_start_date']) && $session_info['access_start_date'] != '0000-00-00') {
             $access_start_date = api_format_date($session_info['access_start_date'], DATE_FORMAT_SHORT);
         }
         $access_end_date = '';
         if (!empty($session_info['access_end_date']) && $session_info['access_end_date'] != '0000-00-00') {
             $access_end_date = api_format_date($session_info['access_end_date'], DATE_FORMAT_SHORT);
         }
Пример #22
0
                                <?php 
    if ($data['rootId'] == 1) {
        ?>
                                    <option value="<?php 
        echo $data['rootId'];
        ?>
">Корневой контейнер</option>
                                <?php 
    } else {
        ?>
                                    <option
                                        value="<?php 
        echo $data['rootId'];
        ?>
"><?php 
        echo Attendance::findOrFail($data['rootId'])->name;
        ?>
</option>
                                <?php 
    }
    ?>
                                <?php 
    foreach ($data['containers'] as $container) {
        ?>
                                    <?php 
        if ($container->id != $data['rootId']) {
            ?>
                                        <?php 
            if ($container->id == 1) {
                ?>
                                            <option value="<?php 
    public function get_students_content_html_for_drh()
    {
        $attendance = new Attendance();
        $students = $this->students;
        $content = '<div style="margin:5px;">';
        $content .= '<h3><font color="#000">' . get_lang('YourStudents') . '</font></h3>';
        $students_table = null;
        if (count($students) > 0) {
            $students_table .= '<table class="data_table">';
            $students_table .= '<tr>
									<th>' . get_lang('User') . '</th>
									<th>' . get_lang('AttendancesFaults') . '</th>
									<th>' . get_lang('Evaluations') . '</th>
								</tr>';
            $i = 1;
            foreach ($students as $student) {
                $student_id = $student['user_id'];
                $firstname = $student['firstname'];
                $lastname = $student['lastname'];
                $username = $student['username'];
                // get average of faults in attendances by student
                $results_faults_avg = $attendance->get_faults_average_inside_courses($student_id);
                if (!empty($results_faults_avg)) {
                    $attendances_faults_avg = '<a title="' . get_lang('GoToStudentDetails') . '" href="' . api_get_path(WEB_CODE_PATH) . 'mySpace/myStudents.php?student=' . $student_id . '">' . $results_faults_avg['faults'] . '/' . $results_faults_avg['total'] . ' (' . $results_faults_avg['porcent'] . '%)</a>';
                } else {
                    $attendances_faults_avg = '0%';
                }
                $courses_by_user = CourseManager::get_courses_list_by_user_id($student_id, true);
                $evaluations_avg = 0;
                $score = $weight = 0;
                foreach ($courses_by_user as $course) {
                    $course_code = $course['code'];
                    $cats = Category::load(null, null, $course_code, null, null, null, false);
                    $scoretotal = array();
                    if (isset($cats) && isset($cats[0])) {
                        $scoretotal = $cats[0]->calc_score($student_id, $course_code);
                    }
                    if (!empty($scoretotal)) {
                        $score += $scoretotal[0];
                        $weight += $scoretotal[1];
                    }
                }
                if (!empty($weight)) {
                    $evaluations_avg = '<a title="' . get_lang('GoToStudentDetails') . '" href="' . api_get_path(WEB_CODE_PATH) . 'mySpace/myStudents.php?student=' . $student_id . '">' . round($score, 2) . '/' . round($weight, 2) . '(' . round($score / $weight * 100, 2) . ' %)</a>';
                }
                if ($i % 2 == 0) {
                    $class_tr = 'row_odd';
                } else {
                    $class_tr = 'row_even';
                }
                $students_table .= '<tr class="' . $class_tr . '">
										<td>' . api_get_person_name($firstname, $lastname) . ' (' . $username . ')</td>
										<td>' . $attendances_faults_avg . '</td>
										<td>' . $evaluations_avg . '</td>
									</tr>';
                $i++;
            }
            $students_table .= '</table>';
        } else {
            $students_table .= get_lang('ThereIsNoInformationAboutYourStudents');
        }
        $content .= $students_table;
        if (count($students) > 0) {
            $content .= '<div style="text-align:right;margin-top:10px;">
                            <a href="' . api_get_path(WEB_CODE_PATH) . 'mySpace/index.php?view=admin&display=yourstudents">' . get_lang('SeeMore') . '</a>
                         </div>';
        }
        $content .= '</div>';
        return $content;
    }
 /**
  * It's used to print attendance sheet
  * @param string action
  * @param int    attendance id
  */
 public function attendance_sheet_export_to_pdf($action, $attendance_id, $student_id = 0, $course_id = '')
 {
     $attendance = new Attendance();
     $courseInfo = CourseManager::get_course_information($course_id);
     $attendance->set_course_id($courseInfo['code']);
     $data_array = array();
     $data_array['attendance_id'] = $attendance_id;
     $data_array['users_in_course'] = $attendance->get_users_rel_course($attendance_id);
     $filter_type = 'today';
     if (!empty($_REQUEST['filter'])) {
         $filter_type = $_REQUEST['filter'];
     }
     $my_calendar_id = null;
     if (is_numeric($filter_type)) {
         $my_calendar_id = $filter_type;
         $filter_type = 'calendar_id';
     }
     $data_array['attendant_calendar'] = $attendance->get_attendance_calendar($attendance_id, $filter_type, $my_calendar_id);
     if (api_is_allowed_to_edit(null, true) || api_is_drh()) {
         $data_array['users_presence'] = $attendance->get_users_attendance_sheet($attendance_id);
     } else {
         if (!empty($student_id)) {
             $user_id = intval($student_id);
         } else {
             $user_id = api_get_user_id();
         }
         $data_array['users_presence'] = $attendance->get_users_attendance_sheet($attendance_id, $user_id);
         $data_array['faults'] = $attendance->get_faults_of_user($user_id, $attendance_id);
         $data_array['user_id'] = $user_id;
     }
     $data_array['next_attendance_calendar_id'] = $attendance->get_next_attendance_calendar_id($attendance_id);
     //Set headers pdf
     $courseCategory = CourseManager::get_course_category($courseInfo['category_code']);
     $teacherInfo = CourseManager::get_teacher_list_from_course_code($courseInfo['real_id']);
     $teacherName = null;
     foreach ($teacherInfo as $dados) {
         if ($teacherName != null) {
             $teacherName = $teacherName . " / ";
         }
         $teacherName .= $dados['firstname'] . " " . $dados['lastname'];
     }
     // Get data table - Marco - ordenacao fixa - just fullname
     $data_table = array();
     $head_table = array('#', get_lang('Name'));
     foreach ($data_array['attendant_calendar'] as $class_day) {
         //$head_table[] = api_format_date($class_day['date_time'], DATE_FORMAT_SHORT).' <br />'.api_format_date($class_day['date_time'], TIME_NO_SEC_FORMAT);
         $head_table[] = api_format_date($class_day['date_time'], DATE_FORMAT_NUMBER_NO_YEAR);
     }
     $data_table[] = $head_table;
     $dataClass = array();
     $max_dates_per_page = 10;
     $data_attendant_calendar = $data_array['attendant_calendar'];
     $data_users_presence = $data_array['users_presence'];
     $count = 1;
     if (!empty($data_array['users_in_course'])) {
         foreach ($data_array['users_in_course'] as $user) {
             $cols = 1;
             $result = array();
             $result['count'] = $count;
             $result['full_name'] = api_get_person_name($user['firstname'], $user['lastname']);
             foreach ($data_array['attendant_calendar'] as $class_day) {
                 if ($class_day['done_attendance'] == 1) {
                     if ($data_users_presence[$user['user_id']][$class_day['id']]['presence'] == 1) {
                         $result[$class_day['id']] = get_lang('UserAttendedSymbol');
                     } else {
                         $result[$class_day['id']] = get_lang('UserNotAttendedSymbol');
                     }
                 } else {
                     $result[$class_day['id']] = " ";
                 }
                 $cols++;
             }
             $count++;
             $data_table[] = $result;
         }
     }
     $max_cols_per_page = 12;
     //10 dates + 2 name and number
     $max_dates_per_page = $max_dates_per_page_original = $max_cols_per_page - 2;
     //10
     $rows = count($data_table);
     if ($cols > $max_cols_per_page) {
         $number_tables = round(($cols - 2) / $max_dates_per_page);
         $headers = $data_table[0];
         $all = array();
         $tables = array();
         $changed = 1;
         for ($i = 0; $i <= $rows; $i++) {
             $row = $data_table[$i];
             $key = 1;
             $max_dates_per_page = 10;
             $item = $data_table[$i];
             $count_j = 0;
             if (!empty($item)) {
                 foreach ($item as $value) {
                     if ($count_j >= $max_dates_per_page) {
                         $key++;
                         $max_dates_per_page = $max_dates_per_page_original * $key;
                         //magic hack
                         $tables[$key][$i][] = $tables[1][$i][0];
                         $tables[$key][$i][] = $tables[1][$i][1];
                     }
                     $tables[$key][$i][] = $value;
                     $count_j++;
                 }
             }
         }
         $content = null;
         if (!empty($tables)) {
             foreach ($tables as $sub_table) {
                 $content .= Export::convert_array_to_html($sub_table) . '<br /><br />';
             }
         }
     } else {
         $content .= Export::convert_array_to_html($data_table, array('header_attributes' => array('align' => 'center')));
     }
     $params = array('filename' => get_lang('Attendance') . '-' . api_get_local_time(), 'pdf_title' => $courseInfo['title'], 'course_code' => $courseInfo['code'], 'add_signatures' => true, 'orientation' => 'landscape', 'pdf_teachers' => $teacherName, 'pdf_course_category' => $courseCategory['name'], 'format' => 'A4-L', 'orientation' => 'L');
     Export::export_html_to_pdf($content, $params);
     exit;
 }
Пример #25
0
 public function Find($whereOrderBy, $bindarr = false, $pkeysArr = false, $extra = array())
 {
     $shift = intval(SettingsManager::getInstance()->getSetting("Attendance: Shift (Minutes)"));
     $employee = new Employee();
     $data = array();
     $employees = $employee->Find("1=1");
     $attendance = new Attendance();
     $attendanceToday = $attendance->Find("date(in_time) = ?", array(date("Y-m-d")));
     $attendanceData = array();
     //Group by employee
     foreach ($attendanceToday as $attendance) {
         if (isset($attendanceData[$attendance->employee])) {
             $attendanceData[$attendance->employee][] = $attendance;
         } else {
             $attendanceData[$attendance->employee] = array($attendance);
         }
     }
     foreach ($employees as $employee) {
         $entry = new stdClass();
         $entry->id = $employee->id;
         $entry->employee = $employee->id;
         if (isset($attendanceData[$employee->id])) {
             $attendanceEntries = $attendanceData[$employee->id];
             foreach ($attendanceEntries as $atEntry) {
                 if ($atEntry->out_time == "0000-00-00 00:00:00" || empty($atEntry->out_time)) {
                     if (strtotime($atEntry->in_time) < time() + $shift * 60) {
                         $entry->status = "Clocked In";
                         $entry->statusId = 0;
                     }
                 }
             }
             if (empty($entry->status)) {
                 $entry->status = "Clocked Out";
                 $entry->statusId = 1;
             }
         } else {
             $entry->status = "Not Clocked In";
             $entry->statusId = 2;
         }
         $data[] = $entry;
     }
     function cmp($a, $b)
     {
         return $a->statusId - $b->statusId;
     }
     usort($data, "cmp");
     return $data;
 }
Пример #26
0
 public static function absentEveryEmployee()
 {
     $employees = Employee::where('status', '=', 'active')->get();
     $absentess = [];
     foreach ($employees as $employee) {
         //Count the absent except half days
         foreach (Leavetype::where('leaveType', '<>', 'half day')->get() as $leave) {
             //$absentess[$employee->employeeID][$leave->leaveType] = 0;
             //      Half Day leaves are added to casual leaves.2 half days are equal to one Casual Leave
             $absentess[$employee->employeeID][$leave->leaveType] = Attendance::where('status', '=', 'absent')->where('employeeID', '=', $employee->employeeID)->where(function ($query) {
                 $query->where('application_status', '=', 'approved')->orWhere('application_status', '=', null);
             })->where('leaveType', '=', $leave->leaveType)->count();
         }
         // half days count
         foreach (Leavetype::where('leaveType', '=', 'half day')->get() as $leave) {
             $half_day = Attendance::select('halfDayType', DB::raw('count(*) as total'))->where('status', '=', 'absent')->where('employeeID', '=', $employee->employeeID)->where(function ($query) {
                 $query->where('application_status', '=', 'approved')->orWhere('application_status', '=', null);
             })->where('leaveType', '=', $leave->leaveType)->groupBy('halfDayType')->get();
             foreach ($half_day as $half) {
                 $absentess[$employee->employeeID][$half->halfDayType] += $half->total / 2;
             }
         }
         //  Total of All leaves
         $absentess[$employee->employeeID]['total'] = array_sum($absentess[$employee->employeeID]);
     }
     return $absentess;
 }
Пример #27
0
 /**
  * Run method with main page logic
  * 
  * Populate template and Display form for editing an event entry. For POST requests,
  * check user credentials, check if event exists and then update entry in database.
  * Available to admins only
  * @access public
  */
 public function run()
 {
     $session = Session::getInstance();
     $user = $session->getUser();
     //if (!$user || !$user->isAdmin ()) {
     if (!$user || !$user->validUser()) {
         $session->setMessage("Do not have permission to access", Session::MESSAGE_ERROR);
         header("Location: " . BASE_URL);
         return;
     }
     $form_errors = array();
     $form_values = array("id" => "", "title" => "", "description" => "", "sanctioned" => "", "status" => "", "date" => "", "platform" => "");
     $eventDAO = EventDAO::getInstance();
     $event = null;
     if (!empty($_POST)) {
         $form_values["id"] = isset($_POST["id"]) && is_numeric($_POST["id"]) ? intval($_POST["id"]) : "";
         $form_values["title"] = isset($_POST["title"]) ? trim($_POST["title"]) : "";
         $form_values["description"] = isset($_POST["description"]) ? trim($_POST["description"]) : "";
         $form_values["platform"] = isset($_POST["platform"]) ? trim($_POST["platform"]) : "";
         $form_values["sanctioned"] = isset($_POST["sanctioned"]) ? trim($_POST["sanctioned"]) : "";
         $form_values["status"] = isset($_POST["status"]) ? trim($_POST["status"]) : "";
         $form_values["date"] = isset($_POST["date"]) ? trim($_POST["date"]) : "";
         if (empty($form_values["id"])) {
             $form_errors["id"] = "No id specified";
         }
         if (empty($form_values["title"])) {
             $form_errors["title"] = "No title specified";
         }
         if (empty($form_values["description"])) {
             $form_errors["description"] = "No description specified";
         }
         if (empty($form_values["platform"])) {
             $form_errors["platform"] = "No platform specified";
         } else {
             if (!is_numeric($form_values["platform"])) {
                 $form_errors["platform"] = "Platform choice must be an integer value";
             } else {
                 $platformDAO = PlatformDAO::getInstance();
                 $platform = $platformDAO->load($form_values["platform"]);
                 if (!$platform) {
                     $form_errors["platform"] = "Invalid platform specified";
                 }
             }
         }
         if ($user->isAdmin() && empty($form_values["sanctioned"])) {
             $form_errors["sanctioned"] = "No sanctioned flag specified";
         } else {
             if ($user->isAdmin() && strcmp($form_values["sanctioned"], "true") != 0 && strcmp($form_values["sanctioned"], "false") != 0) {
                 $form_errors["sanctioned"] = "sanctioned flag must be a boolean value";
             }
         }
         if ($user->isAdmin() && empty($form_values["status"])) {
             $form_errors["status"] = "No status flag specified";
         } else {
             if ($user->isAdmin() && !is_numeric($form_values["status"])) {
                 $form_errors["status"] = "Status flag must be an integer value";
             } else {
                 if ($user->isAdmin()) {
                     $status = intval($form_values["status"]);
                     $tmp = new Event();
                     try {
                         $tmp->setStatus($status);
                     } catch (Exception $e) {
                         $form_errors["status"] = "Invalid value for status";
                     }
                 }
             }
         }
         if (empty($form_values["date"])) {
             $form_errors["date"] = "No date specified";
         } else {
             if (strtotime($_POST["date"]) == 0) {
                 $form_errors["date"] = "An invalid date was specified";
                 $form_values["date"] = "";
             }
         }
         if (empty($form_errors)) {
             $event = $eventDAO->load($form_values["id"]);
             if ($event && ($user->isAdmin() || $event->getUserId() == $user->getId())) {
                 $event->setTitle($form_values["title"]);
                 $event->setDescription($form_values["description"]);
                 $event->setPlatformId(intval($form_values["platform"]));
                 if ($user->isAdmin() || $user->validUser() && $user->getUserType() == User::TRUSTED_TYPE) {
                     $sanctioned_value = strcmp($form_values["sanctioned"], "true") == 0 ? true : false;
                     $event->setSanctioned($sanctioned_value);
                     $event->setStatus($form_values["status"]);
                 }
                 $pubtimestamp = strtotime($_POST["date"]);
                 $event->setDate($pubtimestamp);
                 $event->setUserId($user->id);
                 //print_r ($event);
                 if ($eventDAO->save($event)) {
                     // Attempt to ignore for regular admin edits
                     if ($event->getUserId() == $user->getId()) {
                         require_once joinPath(INCLUDES_DIR, "models", "Attendance.php");
                         Attendance::emailAttendees($event, $user);
                     }
                     $session->setMessage("Event details saved");
                     header("Location: edit_event.php?id={$event->getId()}");
                     return;
                 } else {
                     $session->setMessage("Event details could not be saved", Session::MESSAGE_ERROR);
                 }
             }
         } else {
             if (empty($form_errors["id"])) {
                 $event = $eventDAO->load($form_values["id"]);
             }
         }
     } else {
         if (!empty($_GET)) {
             $form_values["id"] = isset($_GET["id"]) ? $_GET["id"] : "";
             if (empty($form_values["id"])) {
                 header("Location: " . BASE_URL);
                 return;
             } else {
                 $event = $eventDAO->load($form_values["id"]);
                 // Event does not exist. Pass null to template
                 if (!$event) {
                 } else {
                     if (!$user->isAdmin() && $event->userId != $user->id) {
                         $session->setMessage("Do not have permission to edit page", Session::MESSAGE_ERROR);
                         header("Location: " . BASE_URL);
                         return;
                     } else {
                         $form_values["id"] = $event->getId();
                         $form_values["title"] = $event->getTitle();
                         $form_values["description"] = $event->getDescription();
                         $form_values["sanctioned"] = $event->getSanctioned() == true ? "true" : "false";
                         $form_values["status"] = $event->getStatus();
                         $form_values["date"] = strftime("%d %B %Y", $event->getDate());
                         $form_values["platform"] = $event->getPlatformId();
                     }
                 }
             }
         }
     }
     $platformDAO = PlatformDAO::getInstance();
     $platform_array = $platformDAO->all();
     $this->template->render(array("title" => "Edit Event", "extra_header" => joinPath("headers", "jscal_header_tpl.php"), "main_page" => "edit_event_tpl.php", "session" => $session, "event" => $event, "form_values" => $form_values, "form_errors" => $form_errors, "platform_array" => $platform_array));
 }
Пример #28
0
         					$update_done_advances = $thematic->update_done_thematic_advances($last_done_thematic_advance);
         				}
     				}
     			}
     		}
     		$thematic_advance_data = $thematic->get_thematic_advance_list(null, null, true);
     		$return = $thematic->get_thematic_advance_div($thematic_advance_data);
     		echo $return[$_REQUEST['thematic_id']][$_REQUEST['thematic_advance_id']];*/
     break;
 case 'get_datetime_by_attendance':
     $attendance_id = intval($_REQUEST['attendance_id']);
     $thematic_advance_id = intval($_REQUEST['thematic_advance_id']);
     $label = '';
     $input_select = '';
     if (!empty($attendance_id)) {
         $attendance = new Attendance();
         $thematic = new Thematic();
         $thematic_list = $thematic->get_thematic_list();
         $my_list = $thematic_list_temp = array();
         foreach ($thematic_list as $item) {
             $my_list = $thematic->get_thematic_advance_by_thematic_id($item['id']);
             $thematic_list_temp = array_merge($my_list, $thematic_list_temp);
         }
         $new_thematic_list = array();
         foreach ($thematic_list_temp as $item) {
             if (!empty($item['attendance_id'])) {
                 $new_thematic_list[$item['id']] = array('attendance_id' => $item['attendance_id'], 'start_date' => $item['start_date']);
             }
         }
         $attendance_calendar = $attendance->get_attendance_calendar($attendance_id);
         $label = get_lang('StartDate');
Пример #29
0
                    <?php 
if ($data['backPack']->parent_id == 1) {
    ?>
                        <option value="<?php 
    echo $data['backPack']->parent_id;
    ?>
">Корневой контейнер</option>
                    <?php 
} else {
    ?>
                        <option
                            value="<?php 
    echo $data['backPack']->parent_id;
    ?>
"><?php 
    echo Attendance::findOrFail($data['backPack']->parent_id)->name;
    ?>
</option>
                    <?php 
}
?>
                    <?php 
foreach ($data['containers'] as $container) {
    ?>
                        <?php 
    if ($backPack->parent_id != $container->id) {
        ?>
                            <?php 
        if ($container->id !== $backPack->id) {
            ?>
                                <option value="<?php 
Пример #30
0
 /**
  * Get the attendaces to display on the current page (fill the sortable-table)
  * @param   int     offset of first user to recover
  * @param   int     Number of users to get
  * @param   int     Column to sort on
  * @param   string  Order (ASC,DESC)
  * @see SortableTable#get_table_data($from)
  */
 static function get_attendance_data($from = 0, $number_of_items = 20, $column = 1, $direction = 'desc')
 {
     $tbl_attendance = Database::get_course_table(TABLE_ATTENDANCE);
     $course_id = api_get_course_int_id();
     $session_id = api_get_session_id();
     $condition_session = api_get_session_condition($session_id);
     $column = intval($column);
     $from = intval($from);
     $number_of_items = intval($number_of_items);
     if (!in_array($direction, array('ASC', 'DESC'))) {
         $direction = 'ASC';
     }
     $att = new Attendance();
     $att->set_session_id($session_id);
     $att->set_course_int_id($course_id);
     $active_plus = 'att.active = 1';
     if (api_is_platform_admin()) {
         $active_plus = ' 1 = 1 ';
     }
     $sql = "SELECT\n                    att.id,\n                    att.name,\n                    att.description,\n                    att.attendance_qualify_max,\n                    att.locked,\n                    att.active,\n                    att.session_id\n\t\t\t\tFROM {$tbl_attendance} att\n\t\t\t\tWHERE c_id = {$course_id} AND {$active_plus} {$condition_session}\n\t\t\t\tORDER BY {$column} {$direction}\n                LIMIT {$from}, {$number_of_items} ";
     $res = Database::query($sql);
     $attendances = array();
     $param_gradebook = '';
     if (isset($_SESSION['gradebook'])) {
         $param_gradebook = '&gradebook=' . $_SESSION['gradebook'];
     }
     $user_info = api_get_user_info();
     while ($attendance = Database::fetch_array($res, 'ASSOC')) {
         $id = $attendance['id'];
         $student_param = '';
         if (api_is_drh() && $_GET['student_id']) {
             $student_param = '&student_id=' . Security::remove_XSS($_GET['student_id']);
         }
         $session_star = '';
         if (api_get_session_id() == $attendance['session_id']) {
             $session_star = api_get_session_image(api_get_session_id(), $user_info['status']);
         }
         if ($attendance['active'] == 0) {
             $attendance['name'] = "<del>" . $attendance['name'] . "</del>";
         }
         if ($attendance['locked'] == 1) {
             if (api_is_allowed_to_edit(null, true)) {
                 //Link to edit
                 $attendance['name'] = '<a href="index.php?' . api_get_cidreq() . '&action=attendance_sheet_list&attendance_id=' . $id . $param_gradebook . $student_param . '">' . $attendance['name'] . '</a>' . $session_star;
             } else {
                 //Link to view
                 $attendance['name'] = '<a href="index.php?' . api_get_cidreq() . '&action=attendance_sheet_list_no_edit&attendance_id=' . $id . $param_gradebook . $student_param . '">' . $attendance['name'] . '</a>' . $session_star;
             }
         } else {
             $attendance['name'] = '<a href="index.php?' . api_get_cidreq() . '&action=attendance_sheet_list&attendance_id=' . $id . $param_gradebook . $student_param . '">' . $attendance['name'] . '</a>' . $session_star;
         }
         //description
         $attendance['description'] = '<center>' . $attendance['description'] . '</center>';
         if (api_is_allowed_to_edit(null, true)) {
             $actions = '';
             $actions .= '<center>';
             if (api_is_platform_admin()) {
                 $actions .= '<a href="index.php?' . api_get_cidreq() . '&action=attendance_edit&attendance_id=' . $id . $param_gradebook . '">' . Display::return_icon('edit.png', get_lang('Edit'), array(), ICON_SIZE_SMALL) . '</a>&nbsp;';
                 if ($attendance['locked'] == 0) {
                     //    $actions .= '<a onclick="javascript:if(!confirm(\''.get_lang('AreYouSureToDelete').'\')) return false;" href="index.php?'.api_get_cidreq().'&action=attendance_delete&attendance_id='.$id.$param_gradebook.'">'.Display::return_icon('delete.png',get_lang('Delete'), array(), ICON_SIZE_SMALL).'</a>';
                 }
                 if ($attendance['active'] == 1) {
                     $actions .= '<a onclick="javascript:if(!confirm(\'' . get_lang('AreYouSureToDelete') . '\')) return false;" href="index.php?' . api_get_cidreq() . '&action=attendance_delete&attendance_id=' . $id . $param_gradebook . '">' . Display::return_icon('delete.png', get_lang('Delete'), array(), ICON_SIZE_SMALL) . '</a>';
                 } else {
                     $actions .= '<a onclick="javascript:if(!confirm(\'' . get_lang('AreYouSureToRestore') . '\')) return false;" href="index.php?' . api_get_cidreq() . '&action=attendance_restore&attendance_id=' . $id . $param_gradebook . '">' . Display::return_icon('invisible.png', get_lang('Restore'), array(), ICON_SIZE_SMALL) . '</a>';
                 }
             } else {
                 $is_locked_attendance = self::is_locked_attendance($attendance['id']);
                 if ($is_locked_attendance) {
                     $actions .= Display::return_icon('edit_na.png', get_lang('Edit')) . '&nbsp;';
                     $actions .= Display::return_icon('delete_na.png', get_lang('Delete'));
                 } else {
                     $actions .= '<a href="index.php?' . api_get_cidreq() . '&action=attendance_edit&attendance_id=' . $id . $param_gradebook . '">' . Display::return_icon('edit.png', get_lang('Edit'), array(), ICON_SIZE_SMALL) . '</a>&nbsp;';
                     $actions .= '<a onclick="javascript:if(!confirm(\'' . get_lang('AreYouSureToDelete') . '\')) return false;" href="index.php?' . api_get_cidreq() . '&action=attendance_delete&attendance_id=' . $id . $param_gradebook . '">' . Display::return_icon('delete.png', get_lang('Delete'), array(), ICON_SIZE_SMALL) . '</a>';
                 }
             }
             // display lock/unlock icon
             $is_done_all_calendar = $att->is_all_attendance_calendar_done($id);
             if ($is_done_all_calendar) {
                 $locked = $attendance['attendance_qualify_max'];
                 if ($locked == 0) {
                     if (api_is_platform_admin()) {
                         $message_alert = get_lang('AreYouSureToLockTheAttendance');
                     } else {
                         $message_alert = get_lang('UnlockMessageInformation');
                     }
                     $actions .= '&nbsp;<a onclick="javascript:if(!confirm(\'' . $message_alert . '\')) return false;" href="index.php?' . api_get_cidreq() . '&action=lock_attendance&attendance_id=' . $id . $param_gradebook . '">' . Display::return_icon('unlock.png', get_lang('LockAttendance')) . '</a>';
                 } else {
                     if (api_is_platform_admin()) {
                         $actions .= '&nbsp;<a onclick="javascript:if(!confirm(\'' . get_lang('AreYouSureToUnlockTheAttendance') . '\')) return false;" href="index.php?' . api_get_cidreq() . '&action=unlock_attendance&attendance_id=' . $id . $param_gradebook . '">' . Display::return_icon('lock.png', get_lang('UnlockAttendance')) . '</a>';
                     } else {
                         $actions .= '&nbsp;' . Display::return_icon('locked_na.png', get_lang('LockedAttendance'));
                     }
                 }
             }
             $actions .= '</center>';
             $attendance['actions'] = $actions;
             $attendances[] = $attendance;
         } else {
             $attendances[] = $attendance;
         }
     }
     return $attendances;
 }