Project

General

Profile

Feature #3716 ยป attendance.lib.php

Yoselyn Castillo, 02/10/2012 22:38

 
1
<?php
2
/* For licensing terms, see /license.txt */
3
/**
4
 * This file contains class used like library, provides functions for attendance tool. It's also used like model to attendance_controller (MVC pattern)
5
 * @author Christian Fasanando <christian1827@gmail.com>
6
 * @author Julio Montoya <gugli100@gmail.com> improvements
7
 * @package chamilo.attendance
8
 */
9
/**
10
 * Attendance can be used to instanciate objects or as a library to manage attendances
11
 * @package chamilo.attendance
12
 */
13
class Attendance
14
{
15
	private $session_id;
16
	private $course_id;
17
	private $date_time;
18
	private $name;
19
	private $description;
20
	private $attendance_qualify_title;
21
	private $attendance_weight;
22
	private $course_int_id;
23
    public $category_id;
24

    
25
    // constants
26
	const DONE_ATTENDANCE_LOG_TYPE = 'done_attendance_sheet';
27
    const UPDATED_ATTENDANCE_LOG_TYPE = 'updated_attendance_sheet';
28
    const LOCKED_ATTENDANCE_LOG_TYPE = 'locked_attendance_sheet';
29

    
30
	public function __construct() {
31
		//$this->course_int_id = api_get_course_int_id();
32
	}
33

    
34
	/**
35
	 * Get the total number of attendance inside current course and current session
36
	 * @see SortableTable#get_total_number_of_items()
37
	 */
38
	static function get_number_of_attendances() {
39
		$tbl_attendance = Database :: get_course_table(TABLE_ATTENDANCE);
40
        
41
		$session_id = api_get_session_id();
42
		$condition_session = api_get_session_condition($session_id);
43
        $course_id = api_get_course_int_id();
44
		$sql = "SELECT COUNT(att.id) AS total_number_of_items FROM $tbl_attendance att 
45
		        WHERE c_id = $course_id AND att.active = 1 $condition_session ";
46
		$res = Database::query($sql);
47
		$res = Database::query($sql);
48
		$obj = Database::fetch_object($res);
49
		return $obj->total_number_of_items;
50
	}
51

    
52

    
53
	/**
54
	 * Get attendance list only the id, name and attendance_qualify_max fields
55
	 * @param   string  course db name (optional)
56
	 * @param   int     session id (optional)
57
	 * @return  array	attendances list
58
	 */
59
	function get_attendances_list($course_id = '', $session_id = null) {
60
		// Initializing database table and variables
61
		$tbl_attendance = Database :: get_course_table(TABLE_ATTENDANCE);
62
		$data = array();
63

    
64
		if (empty($course_id)) {
65
			$course_id = api_get_course_int_id();
66
		} else {
67
		    $course_id = intval($course_id);
68
		}
69

    
70
        $session_id = isset($session_id)?intval($session_id):api_get_session_id();
71
        $condition_session = api_get_session_condition($session_id);
72

    
73
		// Get attendance data
74
		$sql = "SELECT id, name, attendance_qualify_max FROM $tbl_attendance 
75
		        WHERE c_id = $course_id AND active = 1 $condition_session ";
76
		$rs  = Database::query($sql);
77
		if (Database::num_rows($rs) > 0) {
78
			while ($row = Database::fetch_array($rs,'ASSOC')) {
79
				$data[$row['id']] = $row;
80
			}
81
		}
82
		return $data;
83
	}
84

    
85
	/**
86
	 * Get the attendaces to display on the current page (fill the sortable-table)
87
	 * @param   int     offset of first user to recover
88
	 * @param   int     Number of users to get
89
	 * @param   int     Column to sort on
90
	 * @param   string  Order (ASC,DESC)
91
	 * @see SortableTable#get_table_data($from)
92
	 */
93
	static function get_attendance_data($from, $number_of_items, $column, $direction) {
94
        $tbl_attendance = Database :: get_course_table(TABLE_ATTENDANCE);
95
        $course_id = api_get_course_int_id();
96
        $session_id = api_get_session_id();
97
        $condition_session = api_get_session_condition($session_id);
98
        $column = intval($column);
99
        $from = intval($from);
100
        $number_of_items = intval($number_of_items);
101
        
102
        if (!in_array($direction, array('ASC','DESC'))) {
103
            $direction = 'ASC';
104
        }
105
        
106
        $active_plus = 'att.active = 1';
107
        
108
        if (api_is_platform_admin()) { 
109
            $active_plus = ' 1 = 1 ';
110
        }
111
        
112
		$sql = "SELECT
113
                    att.id AS col0,
114
                    att.name AS col1,
115
                    att.description AS col2,
116
                    att.attendance_qualify_max AS col3,
117
                    att.locked AS col4,
118
                    att.active AS col5,
119
                    att.session_id
120
				FROM $tbl_attendance att
121
				WHERE c_id = $course_id AND $active_plus $condition_session
122
				ORDER BY col$column $direction LIMIT $from,$number_of_items ";        
123
        $res = Database::query($sql);
124
		$attendances = array ();
125

    
126
		$param_gradebook = '';
127
		if (isset($_SESSION['gradebook'])) {
128
			$param_gradebook = '&gradebook='.$_SESSION['gradebook'];
129
		}
130
        $user_info = api_get_user_info();
131
		while ($attendance = Database::fetch_row($res)) {
132
		    
133
			$student_param = '';
134
			if (api_is_drh() && ($_GET['student_id'])) {
135
				$student_param = '&student_id='.Security::remove_XSS($_GET['student_id']);
136
			}
137
			
138
            $session_star = '';
139
            
140
            if (api_get_session_id() == $attendance[6]) {
141
                $session_star = api_get_session_image(api_get_session_id(), $user_info['status']);
142
            }
143
            if ($attendance[5] == 1) {
144
                if (api_is_allowed_to_edit(null, true)) {
145
                    //Link to edit
146
                    $attendance[1] = '<a href="index.php?'.api_get_cidreq().'&action=attendance_sheet_list&attendance_id='.$attendance[0].$param_gradebook.$student_param.'">'.$attendance[1].'</a>'.$session_star;
147
                } else {
148
                    //Link to view
149
                    $attendance[1] = '<a href="index.php?'.api_get_cidreq().'&action=attendance_sheet_list_no_edit&attendance_id='.$attendance[0].$param_gradebook.$student_param.'">'.$attendance[1].'</a>'.$session_star;
150
                }
151
                
152
            } else {
153
                $attendance[1] = '<a href="index.php?'.api_get_cidreq().'&action=attendance_sheet_list&attendance_id='.$attendance[0].$param_gradebook.$student_param.'"><del>'.$attendance[1].'</del></a>'.$session_star;
154
            }
155
			$attendance[3] = '<center>'.$attendance[3].'</center>';
156
			if (api_is_allowed_to_edit(null, true)) {
157
				$actions  = '';
158
				$actions .= '<center>';
159

    
160
                if (api_is_platform_admin()) {
161
                    $actions .= '<a href="index.php?'.api_get_cidreq().'&action=attendance_edit&attendance_id='.$attendance[0].$param_gradebook.'">'.Display::return_icon('edit.png',get_lang('Edit'), array(), ICON_SIZE_SMALL).'</a>&nbsp;';
162
                    if ($attendance[5] == 1) {
163
                        $actions .= '<a onclick="javascript:if(!confirm(\''.get_lang('AreYouSureToDelete').'\')) return false;" href="index.php?'.api_get_cidreq().'&action=attendance_delete&attendance_id='.$attendance[0].$param_gradebook.'">'.Display::return_icon('delete.png',get_lang('Delete'), array(), ICON_SIZE_SMALL).'</a>';
164
                    } else {
165
                        $actions .= '<a onclick="javascript:if(!confirm(\''.get_lang('AreYouSureToRestore').'\')) return false;" href="index.php?'.api_get_cidreq().'&action=attendance_restore&attendance_id='.$attendance[0].$param_gradebook.'">'.Display::return_icon('invisible.png',get_lang('Restore'), array(), ICON_SIZE_SMALL).'</a>';
166
                        $attendance[2] = '<del>'.$attendance[2].'</del>';
167
                    }
168
                } else {
169
                    $is_locked_attendance = self::is_locked_attendance($attendance[0]);
170
                    if ($is_locked_attendance) {
171
                        $actions .= Display::return_icon('edit_na.png',get_lang('Edit')).'&nbsp;';
172
                        $actions .= Display::return_icon('delete_na.png',get_lang('Delete'));
173
                    } else {
174
                        $actions .= '<a href="index.php?'.api_get_cidreq().'&action=attendance_edit&attendance_id='.$attendance[0].$param_gradebook.'">'.Display::return_icon('edit.png',get_lang('Edit'), array(), ICON_SIZE_SMALL).'</a>&nbsp;';
175
                        $actions .= '<a onclick="javascript:if(!confirm(\''.get_lang('AreYouSureToDelete').'\')) return false;" href="index.php?'.api_get_cidreq().'&action=attendance_delete&attendance_id='.$attendance[0].$param_gradebook.'">'.Display::return_icon('delete.png',get_lang('Delete'), array(), ICON_SIZE_SMALL).'</a>';
176
                    }
177
                }
178

    
179
                // display lock/unlock icon
180
                $is_done_all_calendar = self::is_all_attendance_calendar_done($attendance[0]);
181

    
182
                if ($is_done_all_calendar) {
183
                    $locked   = $attendance[4];
184
                    if ($locked == 0) {
185
                        if (api_is_platform_admin()) {
186
                            $message_alert = get_lang('AreYouSureToLockTheAttendance');
187
                        } else {
188
                            $message_alert = get_lang('UnlockMessageInformation');
189
                        }
190
                        $actions .= '&nbsp;<a onclick="javascript:if(!confirm(\''.$message_alert.'\')) return false;" href="index.php?'.api_get_cidreq().'&action=lock_attendance&attendance_id='.$attendance[0].$param_gradebook.'">'.Display::return_icon('unlock.png',get_lang('LockAttendance')).'</a>';
191
                    } else {                                        
192
                        if (api_is_platform_admin()) {
193
                            $actions .= '&nbsp;<a onclick="javascript:if(!confirm(\''.get_lang('AreYouSureToUnlockTheAttendance').'\')) return false;" href="index.php?'.api_get_cidreq().'&action=unlock_attendance&attendance_id='.$attendance[0].$param_gradebook.'">'.Display::return_icon('locked.png',get_lang('UnlockAttendance')).'</a>';
194
                        } else {
195
                            $actions .= '&nbsp;'.Display::return_icon('locked_na.png',get_lang('LockedAttendance'));
196
                        }
197
                    }
198
                } 
199
                $actions .= '</center>';
200

    
201
				$attendances[] = array($attendance[0], $attendance[1], $attendance[2], $attendance[3],$actions);
202
			} else {
203
				$attendance[0] = '&nbsp;';
204
				$attendances[] = array($attendance[0], $attendance[1], $attendance[2], $attendance[3]);
205
			}
206
		}
207
		return $attendances;
208
	}
209

    
210
	/**
211
	 * Get the attendaces by id to display on the current page
212
	 * @param  int     attendance id
213
	 * @return array   attendance data
214
	 */
215
	public function get_attendance_by_id($attendance_id) {
216
		$tbl_attendance = Database :: get_course_table(TABLE_ATTENDANCE);
217
		$attendance_id = intval($attendance_id);
218
        $course_id = api_get_course_int_id();
219
	    $attendance_data = array();
220
		$sql = "SELECT *  FROM $tbl_attendance WHERE c_id = $course_id AND  id = '$attendance_id'";
221
		$res = Database::query($sql);
222
		if (Database::num_rows($res) > 0) {
223
			while ($row = Database::fetch_array($res)) {
224
				$attendance_data = $row;
225
			}
226
		}
227
		return $attendance_data;
228
	}
229

    
230
	/**
231
	 * add attendaces inside table
232
	 * @param  bool   true for adding link in gradebook or false otherwise (optional)
233
	 * @return int    last attendance id
234
	 */
235
	public function attendance_add($link_to_gradebook = false) {
236
		global $_course;
237
		$tbl_attendance	= Database :: get_course_table(TABLE_ATTENDANCE);
238
		$table_link 	= Database :: get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
239
		$session_id 	= api_get_session_id();
240
		$user_id 		= api_get_user_id();
241
		$course_code	= api_get_course_id();	
242
        $course_id      = api_get_course_int_id();	
243
		$title_gradebook= Database::escape_string($this->attendance_qualify_title);
244
		$value_calification  = 0;
245
		$weight_calification =	floatval($this->attendance_weight);
246
		$sql = "INSERT INTO $tbl_attendance SET
247
					c_id =  $course_id, 
248
					name ='".Database::escape_string($this->name)."',
249
					description = '".Database::escape_string($this->description)."',
250
					attendance_qualify_title = '$title_gradebook',
251
					attendance_weight = '$weight_calification',
252
					session_id = '$session_id'";
253
		Database::query($sql);
254
		$affected_rows = Database::affected_rows();
255
		$last_id = 0;
256
		if (!empty($affected_rows)) {
257
			// save inside item property table
258
			$last_id = Database::insert_id();
259
			api_item_property_update($_course, TOOL_ATTENDANCE, $last_id,"AttendanceAdded", $user_id);
260
		}
261
		// add link to gradebook
262
		if ($link_to_gradebook && !empty($this->category_id)) {
263
			$description = '';
264
			$link_info = is_resource_in_course_gradebook($course_code,7,$last_id,$session_id);
265
            $link_id = $link_info['id'];
266
			if (!$link_info) {
267
				add_resource_to_course_gradebook($this->category_id, $course_code, 7, $last_id, $title_gradebook,$weight_calification,$value_calification,$description,1,$session_id);
268
			} else {
269
				Database::query('UPDATE '.$table_link.' SET weight='.$weight_calification.' WHERE id='.$link_id.'');
270
			}
271
		}
272
		return $last_id;
273
	}
274

    
275
	/**
276
	 * edit attendaces inside table
277
	 * @param 	int	   attendance id
278
	 * @param  	bool   true for adding link in gradebook or false otherwise (optional)
279
	 * @return 	int    last id
280
	 */
281
	public function attendance_edit($attendance_id, $link_to_gradebook = false) {
282
		global $_course;
283
		$tbl_attendance     = Database :: get_course_table(TABLE_ATTENDANCE);
284
		$table_link         = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
285
		$session_id         = api_get_session_id();
286
		$user_id            = api_get_user_id();
287
		$attendance_id      = intval($attendance_id);
288
		$course_code        = api_get_course_id();
289
        $course_id          = api_get_course_int_id();
290
		$title_gradebook	= Database::escape_string($this->attendance_qualify_title);
291
		$value_calification = 0;
292
		$weight_calification= floatval($this->attendance_weight);
293
		
294
        if (!empty($attendance_id)) {
295
            
296
            $sql = "UPDATE $tbl_attendance
297
                    SET name ='".Database::escape_string($this->name)."',
298
                        description = '".Database::escape_string($this->description)."',
299
                        attendance_qualify_title = '".$title_gradebook."',
300
                        attendance_weight = '".$weight_calification."'
301
                    WHERE c_id = $course_id AND id = '$attendance_id'";
302
            Database::query($sql);
303

    
304
            api_item_property_update($_course, TOOL_ATTENDANCE, $attendance_id,"AttendanceUpdated", $user_id);	
305

    
306
            // add link to gradebook
307
            if ($link_to_gradebook && !empty($this->category_id)) {
308
                $description = '';
309
                $link_id=is_resource_in_course_gradebook($course_code,7,$attendance_id,$session_id);
310
                if (!$link_id) {
311
                    add_resource_to_course_gradebook($this->category_id, $course_code, 7, $attendance_id, $title_gradebook,$weight_calification,$value_calification,$description,1,$session_id);
312
                } else {
313
                    Database::query('UPDATE '.$table_link.' SET weight='.$weight_calification.' WHERE id='.$link_id.'');
314
                }
315
            }          
316
            return $attendance_id;
317
        }
318
        return null;		
319
	}
320

    
321
	/**
322
	 * Restore attendance
323
	 * @param 	int|array	   one or many attendances id
324
	 * @return 	int    		   affected rows
325
	 */
326
	public function attendance_restore($attendance_id) {
327
		global $_course;
328
		$tbl_attendance	= Database :: get_course_table(TABLE_ATTENDANCE);
329
		$user_id 		= api_get_user_id();
330
        $course_id      = api_get_course_int_id();
331
		if (is_array($attendance_id)) {
332
			foreach ($attendance_id as $id) {
333
				$id	= intval($id);
334
				$sql = "UPDATE $tbl_attendance SET active = 1 WHERE c_id = $course_id AND id = '$id'";
335
				Database::query($sql);
336
				$affected_rows = Database::affected_rows();
337
				if (!empty($affected_rows)) {
338
					// update row item property table
339
					api_item_property_update($_course, TOOL_ATTENDANCE, $id,"restore", $user_id);
340
				}
341
			}
342
		} else  {
343
			$attendance_id	= intval($attendance_id);
344
			$sql = "UPDATE $tbl_attendance SET active = 1 WHERE c_id = $course_id AND id = '$attendance_id'";
345
			Database::query($sql);
346
			$affected_rows = Database::affected_rows();
347
			if (!empty($affected_rows)) {
348
				// update row item property table
349
				api_item_property_update($_course, TOOL_ATTENDANCE, $attendance_id,"restore", $user_id);
350
			}
351
		}
352
		return $affected_rows;
353
	}
354

    
355

    
356
	/**
357
	 * delete attendaces
358
	 * @param 	int|array	   one or many attendances id
359
	 * @return 	int    		   affected rows
360
	 */
361
	public function attendance_delete($attendance_id) {
362
		global $_course;
363
		$tbl_attendance	= Database :: get_course_table(TABLE_ATTENDANCE);
364
		$user_id 		= api_get_user_id();
365
		$course_id      = api_get_course_int_id();
366
		if (is_array($attendance_id)) {
367
			foreach ($attendance_id as $id) {
368
				$id	= intval($id);
369
				$sql = "UPDATE $tbl_attendance SET active = 0 WHERE c_id = $course_id AND id = '$id'";
370
				Database::query($sql);
371
				$affected_rows = Database::affected_rows();
372
				if (!empty($affected_rows)) {
373
					// update row item property table
374
					api_item_property_update($_course, TOOL_ATTENDANCE, $id,"delete", $user_id);
375
				}
376
			}
377
		} else  {
378
			$attendance_id	= intval($attendance_id);
379
			$sql = "UPDATE $tbl_attendance SET active = 0 WHERE c_id = $course_id AND id = '$attendance_id'";
380
			Database::query($sql);
381
			$affected_rows = Database::affected_rows();
382
			if (!empty($affected_rows)) {
383
				// update row item property table
384
				api_item_property_update($_course, TOOL_ATTENDANCE, $attendance_id,"delete", $user_id);
385
			}
386
		}
387
		return $affected_rows;
388
	}
389

    
390
        /**
391
         * Lock or unlock an attendance
392
         * @param   int     attendance id
393
         * @param   bool    True to lock or false otherwise
394
         */
395
        public function lock_attendance($attendance_id, $lock = true) {
396
            $tbl_attendance = Database::get_course_table(TABLE_ATTENDANCE);
397
            $course_id = api_get_course_int_id();
398
            $attendance_id = intval($attendance_id);
399
            $locked = ($lock)?1:0;
400
            $upd = "UPDATE $tbl_attendance SET locked = $locked WHERE c_id = $course_id AND id = $attendance_id";
401
            Database::query($upd);
402
            $affected_rows = Database::affected_rows();
403
            if ($affected_rows && $lock) {
404
                //save attendance sheet log
405
                $lastedit_date = Date('Y-m-d H:i:s');
406
                $lastedit_type = self::LOCKED_ATTENDANCE_LOG_TYPE;
407
                $lastedit_user_id = api_get_user_id();
408
                $save_attendance_log = $this->save_attendance_sheet_log($attendance_id, $lastedit_date, $lastedit_type, $lastedit_user_id);
409
            }
410
            return $affected_rows;
411
        }
412

    
413
	/**
414
	 * Get registered users inside current course
415
	 * @param 	int	   attendance id for showing attendance result field (optional)
416
	 * @return 	array  users data
417
	 */
418
	public function get_users_rel_course($attendance_id = 0) {
419
	    
420
		$current_session_id = api_get_session_id();
421
		$current_course_id  = api_get_course_id();
422
		if (!empty($current_session_id)) {
423
			$a_course_users = CourseManager :: get_user_list_from_course_code($current_course_id, $current_session_id,'','lastname');
424
		} else {
425
			$a_course_users = CourseManager :: get_user_list_from_course_code($current_course_id, 0, '','lastname');
426
		}
427
		// get registered users inside current course
428
		$a_users = array();
429
		foreach ($a_course_users as $key =>$user_data) {
430
			$value	= array();			
431
			$uid 	= $user_data['user_id'];
432
			$status = $user_data['status'];
433
			
434
			$user_status_in_session = null;
435
			$user_status_in_course  = null;
436
			
437
			if (api_get_session_id()) {
438
                $user_status_in_session = SessionManager::get_user_status_in_course_session($uid, $current_course_id, $current_session_id);                
439
			} else {
440
			    $user_status_in_course = CourseManager::get_user_in_course_status($uid, $current_course_id);
441
			}
442

    
443
			//Not taking into account DRH or COURSEMANAGER
444
			if ($uid <= 1 || $status == DRH || $user_status_in_course == COURSEMANAGER || $user_status_in_session == 2) continue;
445

    
446
			if (!empty($attendance_id)) {
447
				$user_faults = $this->get_faults_of_user($uid, $attendance_id);
448

    
449
				$value['attendance_result'] = $user_faults['faults'].'/'.$user_faults['total'].' ('.$user_faults['faults_porcent'].'%)';
450
				$value['result_color_bar'] 	= $user_faults['color_bar'];
451
			}
452

    
453
			// user's picture
454
			$image_path 	= UserManager::get_user_picture_path_by_id($uid, 'web', false);
455
			$user_profile 	= UserManager::get_picture_user($uid, $image_path['file'], 22, USER_IMAGE_SIZE_SMALL, ' width="22" height="22" ');
456

    
457
			if (!empty($image_path['file'])) {
458
				$photo = '<center><a class="thickbox" href="'.$image_path['dir'].$image_path['file'].'"  ><img src="'.$user_profile['file'].'" '.$user_profile['style'].' alt="'.api_get_person_name($user_data['firstname'], $user_data['lastname']).'"  title="'.api_get_person_name($user_data['firstname'], $user_data['lastname']).'" /></a></center>';
459
			} else {
460
				$photo = '<center><img src="'.$user_profile['file'].'" '.$user_profile['style'].' alt="'.api_get_person_name($user_data['firstname'], $user_data['lastname']).'"  title="'.api_get_person_name($user_data['firstname'], $user_data['lastname']).'" /></center>';
461
			}
462

    
463
			$value['photo']      = $photo;
464
			$value['firstname']  = $user_data['firstname'];
465
			$value['lastname']	 = $user_data['lastname'];
466
			$value['username']   = $user_data['username'];
467
            $value['user_id']    = $uid;
468

    
469
			//Sending only 5 items in the array instead of 60
470
			$a_users[$key] = $value;
471
		}
472
		return $a_users;
473
	}
474

    
475
	/**
476
	 * add attendaces sheet inside table
477
	 * @param 	int	   attendance calendar id
478
	 * @param  	array  present users during current class
479
	 * @param	int	   attendance id
480
	 * @return 	int    affected rows
481
	 */
482
	public function attendance_sheet_add($calendar_id,$users_present,$attendance_id) {
483
		$tbl_attendance_sheet 	= Database::get_course_table(TABLE_ATTENDANCE_SHEET);
484
		$tbl_attendance_calendar= Database::get_course_table(TABLE_ATTENDANCE_CALENDAR);
485
		$tbl_attendance_result 	= Database::get_course_table(TABLE_ATTENDANCE_RESULT);
486
		$tbl_attendance			= Database::get_course_table(TABLE_ATTENDANCE);
487

    
488
		$calendar_id = intval($calendar_id);
489
		$attendance_id = intval($attendance_id);
490
		$users = $this->get_users_rel_course();
491
        $course_id = api_get_course_int_id();
492
        
493
		$user_ids = array_keys($users);
494
		$users_absent = array_diff($user_ids,$users_present);
495
		$affected_rows = 0;
496

    
497
            // get last edit type
498
            $calendar_data = $this->get_attendance_calendar_by_id($calendar_id);
499
            $lastedit_type = self::DONE_ATTENDANCE_LOG_TYPE;
500
            if ($calendar_data['done_attendance']) {
501
                $lastedit_type = self::UPDATED_ATTENDANCE_LOG_TYPE;
502
            }
503

    
504
		// save users present in class
505
		foreach ($users_present as $user_present) {
506
			$uid = intval($user_present);
507
			// check if user already was registered with the $calendar_id
508
			$sql = "SELECT user_id FROM $tbl_attendance_sheet WHERE c_id = $course_id AND user_id='$uid' AND attendance_calendar_id = '$calendar_id'";
509
			$rs  = Database::query($sql);			
510
			if (Database::num_rows($rs) == 0) {
511
				$sql = "INSERT INTO $tbl_attendance_sheet SET 
512
						c_id					= $course_id, 
513
						user_id 				= '$uid', 
514
						attendance_calendar_id 	= '$calendar_id', 
515
						presence 				= 1";
516
				Database::query($sql);
517
				$affected_rows += Database::affected_rows();
518
			} else {
519
				$sql = "UPDATE $tbl_attendance_sheet SET presence = 1 WHERE c_id = $course_id AND user_id ='$uid' AND attendance_calendar_id = '$calendar_id'";
520
				Database::query($sql);
521
				$affected_rows += Database::affected_rows();
522
			}
523
		}
524

    
525
		// save users absent in class
526
		foreach ($users_absent as $user_absent) {
527
			$uid = intval($user_absent);
528
			// check if user already was registered with the $calendar_id
529
			$sql = "SELECT user_id FROM $tbl_attendance_sheet WHERE c_id = $course_id AND user_id='$uid' AND attendance_calendar_id = '$calendar_id'";
530
			$rs  = Database::query($sql);
531
			if (Database::num_rows($rs) == 0) {
532
				$sql = "INSERT INTO $tbl_attendance_sheet SET
533
						c_id = $course_id, 
534
						user_id ='$uid', 
535
						attendance_calendar_id = '$calendar_id', 
536
						presence = 0";
537
				Database::query($sql);
538
				$affected_rows += Database::affected_rows();
539
			} else {
540
				$sql = "UPDATE $tbl_attendance_sheet SET presence = 0 WHERE c_id = $course_id AND user_id ='$uid' AND attendance_calendar_id = '$calendar_id'";
541
				Database::query($sql);
542
				$affected_rows += Database::affected_rows();
543
			}
544
		}
545

    
546
		// update done_attendance inside attendance calendar table
547
		$sql = "UPDATE $tbl_attendance_calendar SET done_attendance = 1 WHERE  c_id = $course_id AND id = '$calendar_id'";
548
		Database::query($sql);
549

    
550
		// save users' results
551
		$this->update_users_results($user_ids, $attendance_id);
552

    
553
                if ($affected_rows) {
554
                    //save attendance sheet log
555
                    $lastedit_date = Date('Y-m-d H:i:s');                    
556
                    $lastedit_user_id = api_get_user_id();                                        
557
                    $calendar_date_value = $calendar_data['date_time'];
558
                    $save_attendance_log = $this->save_attendance_sheet_log($attendance_id, $lastedit_date, $lastedit_type, $lastedit_user_id, $calendar_date_value);
559
                }
560

    
561
		return $affected_rows;
562
	}
563

    
564
	/**
565
	 * update users' attendance results
566
	 * @param 	array  registered users inside current course
567
	 * @param	int	   attendance id
568
	 * @return 	void
569
	 */
570
	public function update_users_results($user_ids, $attendance_id) {
571
		$tbl_attendance_sheet 	= Database::get_course_table(TABLE_ATTENDANCE_SHEET);
572
		$tbl_attendance_calendar= Database::get_course_table(TABLE_ATTENDANCE_CALENDAR);
573
		$tbl_attendance_result  = Database::get_course_table(TABLE_ATTENDANCE_RESULT);
574
		$tbl_attendance			= Database::get_course_table(TABLE_ATTENDANCE);
575
        $course_id              = api_get_course_int_id();
576
        
577
		$attendance_id = intval($attendance_id);
578
		// fill results about presence of students
579
		$attendance_calendar = $this->get_attendance_calendar($attendance_id);
580
		$calendar_ids = array();
581
		// get all dates from calendar by current attendance
582
		foreach ($attendance_calendar as $cal) {
583
			$calendar_ids[] = $cal['id'];
584
		}
585
		// get count of presences by users inside current attendance and save like results
586
		$count_presences = 0;
587
		if (count($user_ids) > 0) {
588
			foreach ($user_ids as $uid) {
589
				$count_presences = 0;
590
				if (count($calendar_ids) > 0) {
591
					$sql = "SELECT count(presence) as count_presences FROM $tbl_attendance_sheet 
592
					        WHERE c_id = $course_id AND user_id = '$uid' AND attendance_calendar_id IN(".implode(',',$calendar_ids).") AND presence = 1";
593
					$rs_count  = Database::query($sql);
594
					$row_count = Database::fetch_array($rs_count);
595
					$count_presences = $row_count['count_presences'];
596
				}
597
				// save results
598
				$sql = "SELECT id FROM $tbl_attendance_result WHERE c_id = $course_id AND user_id='$uid' AND attendance_id='$attendance_id'";
599
				$rs_check_result = Database::query($sql);
600
				if (Database::num_rows($rs_check_result) > 0) {
601
					// update result
602
					$sql = "UPDATE $tbl_attendance_result SET 
603
							score='$count_presences' 
604
							WHERE c_id = $course_id AND user_id='$uid' AND attendance_id='$attendance_id'";
605
					Database::query($sql);
606
				} else {
607
					// insert new result
608
					$sql = "INSERT INTO $tbl_attendance_result SET
609
								c_id = $course_id , 
610
								user_id			= '$uid', 
611
								attendance_id 	= '$attendance_id', 
612
								score			= '$count_presences'";
613
					Database::query($sql);
614
				}
615
			}
616
		}
617
		// update attendance qualify max
618
		$count_done_calendar = self::get_done_attendance_calendar($attendance_id);
619
		$sql = "UPDATE $tbl_attendance SET attendance_qualify_max='$count_done_calendar' WHERE c_id = $course_id AND id = '$attendance_id'";
620
		Database::query($sql);
621
	}
622

    
623

    
624
    /**
625
        * update attendance_sheet_log table, is used as history of an attendance sheet
626
        * @param   int     Attendance id
627
        * @param   string  Last edit datetime
628
        * @param   string  Event type ('locked_attendance', 'done_attendance_sheet' ...)
629
        * @param   int     Last edit user id
630
        * @param   string  Calendar datetime value (optional, when event type is 'done_attendance_sheet')
631
        * @return  int     Affected rows
632
        */
633
    public function save_attendance_sheet_log($attendance_id, $lastedit_date, $lastedit_type, $lastedit_user_id, $calendar_date_value = null) {
634
        $course_id = api_get_course_int_id();
635

    
636
        // define table
637
        $tbl_attendance_sheet_log = Database::get_course_table(TABLE_ATTENDANCE_SHEET_LOG);
638

    
639
        // protect data
640
        $attendance_id = intval($attendance_id);
641
        $lastedit_date = Database::escape_string($lastedit_date);
642
        $lastedit_type = Database::escape_string($lastedit_type);
643
        $lastedit_user_id = intval($lastedit_user_id);
644

    
645
        if (isset($calendar_date_value)) {
646
            $calendar_date_value = Database::escape_string($calendar_date_value);
647
        } else {
648
            $calendar_date_value = '';
649
        }
650

    
651
        // save data
652
        $ins = "INSERT INTO $tbl_attendance_sheet_log(c_id, attendance_id, lastedit_date, lastedit_type, lastedit_user_id, calendar_date_value)
653
                VALUES($course_id, $attendance_id, '$lastedit_date', '$lastedit_type', $lastedit_user_id, '$calendar_date_value')";
654

    
655
        Database::query($ins);
656

    
657
        return Database::affected_rows();            
658
   }
659

    
660
	/**
661
	 * Get number of done attendances inside current sheet
662
	 * @param	int	   attendance id
663
	 * @return 	int	   number of done attendances
664
	 */
665
	public static function get_done_attendance_calendar($attendance_id) {
666
		$tbl_attendance_calendar = Database::get_course_table(TABLE_ATTENDANCE_CALENDAR);
667
		$attendance_id = intval($attendance_id);
668
        $course_id = api_get_course_int_id();
669
		$sql = "SELECT count(done_attendance) as count 
670
                FROM $tbl_attendance_calendar 
671
                WHERE c_id = $course_id AND attendance_id = '$attendance_id' AND done_attendance=1";
672
		$rs  = Database::query($sql);
673
		$row = Database::fetch_array($rs);
674
		$count = $row['count'];
675
		return $count;
676
	}
677

    
678
	/**
679
	 * Get results of faults (absents) by user
680
	 * @param	int	   user id
681
	 * @param	int	   attendance id
682
	 * @return 	array  results containing number of faults, total done attendance, porcent of faults and color depend on result (red, orange)
683
	 */
684
	public function get_faults_of_user($user_id, $attendance_id) {
685

    
686
		// initializing database table and variables
687
		$tbl_attendance_result 	= Database::get_course_table(TABLE_ATTENDANCE_RESULT);
688
		$user_id 		= intval($user_id);
689
		$attendance_id 	= intval($attendance_id);
690
		$results = array();
691
		$attendance_data 	= $this->get_attendance_by_id($attendance_id);
692
		
693
		$calendar_count 	= self::get_number_of_attendance_calendar($attendance_id);
694
		
695
		$total_done_attendance 	= $attendance_data['attendance_qualify_max'];
696
		
697
		$attendance_user_score  = $this->get_user_score($user_id, $attendance_id);
698
		
699
		//This is the main change of the BT#1381
700
		//$total_done_attendance = $calendar_count;
701

    
702
		// calculate results
703
		$faults = $total_done_attendance - $attendance_user_score;	
704
		
705
		$faults = $faults > 0 ? $faults:0;
706
		$faults_porcent = $calendar_count > 0 ?round(($faults*100)/$calendar_count,0):0;
707
		$results['faults'] 			= $faults;
708
		$results['total']			= $calendar_count;
709
		$results['faults_porcent'] 	= $faults_porcent;
710
		$color_bar = '';
711

    
712
		if ($faults_porcent > 25  ) {
713
			$color_bar = '#F11';
714
		} else if ($faults_porcent > 10) {
715
			$color_bar = '#F90';
716
		}
717
		$results['color_bar'] = $color_bar;
718

    
719
		return $results;
720
	}
721

    
722
	/**
723
	 * Get results of faults average for all courses by user
724
	 * @param	int	   user id
725
	 * @return 	array  results containing number of faults, total done attendance, porcent of faults and color depend on result (red, orange)
726
	 */
727
	public function get_faults_average_inside_courses($user_id) {
728

    
729
		// get all courses of current user
730
		$courses = CourseManager::get_courses_list_by_user_id($user_id, true);
731

    
732
		$user_id = intval($user_id);
733
		$results = array();
734
		$total_faults = $total_weight = $porcent = 0;
735
		foreach ($courses as $course) {
736
			//$course_code = $course['code'];
737
			//$course_info = api_get_course_info($course_code);
738
			$course_id = $course['real_id'];
739
			$tbl_attendance_result 	= Database::get_course_table(TABLE_ATTENDANCE_RESULT);
740

    
741
			$attendances_by_course = $this->get_attendances_list($course_id);
742

    
743
			foreach ($attendances_by_course as $attendance) {
744
				// get total faults and total weight
745
				$total_done_attendance 	= $attendance['attendance_qualify_max'];
746
				$sql = "SELECT score FROM $tbl_attendance_result
747
                        WHERE c_id = $course_id AND user_id = $user_id AND attendance_id = ".$attendance['id'];
748
				$rs = Database::query($sql);
749
				$score = 0;
750
				if (Database::num_rows($rs) > 0) {
751
					$row = Database::fetch_array($rs);
752
					$score = $row['score'];
753
				}
754
				$faults = $total_done_attendance-$score;
755
				$faults = $faults > 0 ? $faults:0;
756
				$total_faults += $faults;
757
				$total_weight += $total_done_attendance;
758
			}
759
		}
760

    
761
		$porcent = $total_weight > 0 ?round(($total_faults*100)/$total_weight,0):0;
762
		$results['faults'] 	= $total_faults;
763
		$results['total']	= $total_weight;
764
		$results['porcent'] = $porcent;
765

    
766
		return $results;
767
	}
768

    
769
	/**
770
	 * Get results of faults average by course
771
	 * @param	int	   user id
772
	 * @param	int	   Session id (optional)
773
	 * @return 	array  results containing number of faults, total done attendance, porcent of faults and color depend on result (red, orange)
774
	 */
775
	public function get_faults_average_by_course($user_id, $course_code, $session_id = null) {
776
		// Database tables and variables
777
		$course_info = api_get_course_info($course_code);
778
		$tbl_attendance_result 	= Database::get_course_table(TABLE_ATTENDANCE_RESULT);
779
		$user_id = intval($user_id);
780
		$results = array();
781
		$total_faults = $total_weight = $porcent = 0;
782
		$attendances_by_course = $this->get_attendances_list($course_info['real_id'], $session_id);
783

    
784
		foreach ($attendances_by_course as $attendance) {
785
			// Get total faults and total weight
786
			$total_done_attendance 	= $attendance['attendance_qualify_max'];
787
			$sql = "SELECT score FROM $tbl_attendance_result WHERE c_id = {$course_info['real_id']} AND user_id=$user_id AND attendance_id=".$attendance['id'];
788
			$rs = Database::query($sql);
789
			$score = 0;
790
			if (Database::num_rows($rs) > 0) {
791
				$row = Database::fetch_array($rs);
792
				$score = $row['score'];
793
			}
794
			$faults = $total_done_attendance-$score;
795
			$faults = $faults > 0 ? $faults:0;
796
			$total_faults += $faults;
797
			$total_weight += $total_done_attendance;
798
		}
799

    
800
		$porcent = $total_weight > 0 ?round(($total_faults*100)/$total_weight,0):0;
801
		$results['faults'] 	= $total_faults;
802
		$results['total']	= $total_weight;
803
		$results['porcent'] = $porcent;
804
		return $results;        
805
	}
806

    
807
	/**
808
	 * Get registered users' attendance sheet inside current course
809
	 * @param	int	   attendance id
810
	 * @param	int	   user id for showing data for only one user (optional)
811
	 * @return 	array  users attendance sheet data
812
	 */
813
	public function get_users_attendance_sheet($attendance_id, $user_id = 0) {		
814
		$tbl_attendance_sheet 	= Database::get_course_table(TABLE_ATTENDANCE_SHEET);
815
		$tbl_attendance_calendar= Database::get_course_table(TABLE_ATTENDANCE_CALENDAR);
816

    
817
		$attendance_calendar = $this->get_attendance_calendar($attendance_id);
818
		$calendar_ids = array();
819
		// get all dates from calendar by current attendance
820
		foreach ($attendance_calendar as $cal) {
821
			$calendar_ids[] = $cal['id'];
822
		}
823
		
824
		$course_id = api_get_course_int_id();
825

    
826
		$data = array();
827
		if (empty($user_id)) {
828
			// get all registered users inside current course
829
			$users = $this->get_users_rel_course();
830
			$user_ids = array_keys($users);
831
			if (count($calendar_ids) > 0 && count($user_ids) > 0) {
832
				foreach ($user_ids as $uid) {
833
					$sql = "SELECT * FROM $tbl_attendance_sheet 
834
					        WHERE c_id = $course_id AND user_id = '$uid' AND attendance_calendar_id IN(".implode(',',$calendar_ids).") ";                    
835
					$res = Database::query($sql);
836
					if (Database::num_rows($res) > 0) {
837
						while ($row = Database::fetch_array($res)) {
838
							$data[$uid][$row['attendance_calendar_id']]['presence'] = $row['presence'];
839
						}
840
					}
841
				}
842
			}
843
		} else {
844
			// Get attendance for current user
845
			$user_id = intval($user_id);
846
			if (count($calendar_ids) > 0) {
847
				$sql = "SELECT cal.date_time, att.presence 
848
                        FROM $tbl_attendance_sheet att 
849
                            INNER JOIN  $tbl_attendance_calendar cal 
850
                            ON cal.id = att.attendance_calendar_id 
851
						WHERE 	att.c_id = $course_id AND
852
								cal.c_id =  $course_id AND
853
								att.user_id = '$user_id' AND 
854
								att.attendance_calendar_id IN(".implode(',',$calendar_ids).") 
855
                        ORDER BY date_time";
856
				$res = Database::query($sql);
857
				if (Database::num_rows($res) > 0) {
858
					while ($row = Database::fetch_array($res)) {
859
						$row['date_time'] = api_convert_and_format_date($row['date_time'], null, date_default_timezone_get());
860
						$data[$user_id][] = $row;
861
					}
862
				}
863
			}
864
		}
865
		return $data;
866
	}
867

    
868
	/**
869
	 * Get next attendance calendar without presences (done attendances)
870
	 * @param	int	attendance id
871
	 * @return 	int attendance calendar id
872
	 */
873
	public function get_next_attendance_calendar_id($attendance_id) {
874
		$tbl_attendance_calendar = Database::get_course_table(TABLE_ATTENDANCE_CALENDAR);
875
		$attendance_id = intval($attendance_id);
876
        $course_id = api_get_course_int_id();
877
        
878
		$sql = "SELECT id FROM $tbl_attendance_calendar 
879
		        WHERE c_id = $course_id AND attendance_id = '$attendance_id' AND done_attendance = 0 ORDER BY date_time limit 1";
880
		$rs = Database::query($sql);
881
		$next_calendar_id = 0;
882
		if (Database::num_rows($rs) > 0) {
883
			$row = Database::fetch_array($rs);
884
			$next_calendar_id = $row['id'];
885
		}
886
		return $next_calendar_id;
887
	}
888

    
889
	/**
890
	 * Get next attendance calendar datetime without presences (done attendances)
891
	 * @param	int	attendance id
892
	 * @return 	int UNIX time format datetime
893
	 */
894
	public function get_next_attendance_calendar_datetime($attendance_id) {
895
		$tbl_attendance_calendar = Database::get_course_table(TABLE_ATTENDANCE_CALENDAR);
896
        $course_id = api_get_course_int_id();
897
		$attendance_id = intval($attendance_id);
898
		$sql = "SELECT id, date_time FROM $tbl_attendance_calendar WHERE c_id = $course_id AND attendance_id = '$attendance_id' AND done_attendance = 0 ORDER BY date_time limit 1";
899
		$rs = Database::query($sql);
900
		$next_calendar_datetime = 0;
901
		if (Database::num_rows($rs) > 0) {
902
			$row = Database::fetch_array($rs);
903
			$next_calendar_datetime = api_get_local_time($row['date_time']);
904
		}
905
		return $next_calendar_datetime;
906
	}
907

    
908
	/**
909
	 * Get user' score from current attendance
910
	 * @param	int	user id
911
	 * @param	int attendance id
912
	 * @return	int score
913
	 */
914
	public function get_user_score($user_id, $attendance_id) {
915
		$tbl_attendance_result 	= Database::get_course_table(TABLE_ATTENDANCE_RESULT);
916
		$user_id = intval($user_id);
917
		$attendance_id = intval($attendance_id);
918
        $course_id = api_get_course_int_id();
919
		$sql = "SELECT score FROM $tbl_attendance_result WHERE c_id = $course_id AND user_id='$user_id' AND attendance_id='$attendance_id'";
920
		$rs = Database::query($sql);
921
		$score = 0;
922
		if (Database::num_rows($rs) > 0) {
923
			$row = Database::fetch_array($rs);
924
			$score = $row['score'];
925
		}
926
		return $score;
927
	}
928

    
929
	/**
930
	 * Get attendance calendar data by id
931
	 * @param	int	attendance calendar id
932
	 * @return	array attendance calendar data
933
	 */
934
	public function get_attendance_calendar_by_id($calendar_id) {
935
		$tbl_attendance_calendar = Database::get_course_table(TABLE_ATTENDANCE_CALENDAR);
936
		$calendar_id = intval($calendar_id);
937
        $course_id = api_get_course_int_id();
938
		$sql = "SELECT * FROM $tbl_attendance_calendar WHERE c_id = $course_id AND id = '$calendar_id' ";
939
		$rs = Database::query($sql);
940
		$data = array();
941
		if (Database::num_rows($rs) > 0) {
942
			while ($row = Database::fetch_array($rs)) {
943
				$row['date_time'] = api_get_local_time($row['date_time']);
944
				$data = $row;
945
			}
946
		}
947
		return $data;
948
	}	
949
	
950
	/**
951
	 * Get all attendance calendar data inside current attendance
952
	 * @param	int	attendance id
953
	 * @return	array attendance calendar data
954
	 */
955
	public function get_attendance_calendar($attendance_id, $type = 'all', $calendar_id = null) {
956
		global $dateFormatShort, $timeNoSecFormat;
957
		$tbl_attendance_calendar = Database::get_course_table(TABLE_ATTENDANCE_CALENDAR);
958
		$attendance_id = intval($attendance_id);		
959
        $course_id = api_get_course_int_id();
960
		$sql = "SELECT * FROM $tbl_attendance_calendar WHERE c_id = $course_id AND attendance_id = '$attendance_id' ";				
961
		if (!in_array($type, array('today', 'all', 'all_done', 'all_not_done','calendar_id'))) {
962
			$type = 'all';
963
		}		
964
		switch ($type) {
965
		    case 'calendar_id':
966
		        $calendar_id = intval($calendar_id);		        
967
		        if (!empty($calendar_id)) {
968
		            $sql.= " AND id = $calendar_id";
969
		        }
970
		        break;
971
			case 'today':
972
				//$sql .= ' AND DATE_FORMAT(date_time,"%d-%m-%Y") = DATE_FORMAT("'.api_get_utc_datetime().'", "%d-%m-%Y" )';
973
				break;				
974
			case 'all_done':
975
				$sql .= " AND done_attendance = 1 ";
976
				break;
977
			case 'all_not_done':
978
				$sql .= " AND done_attendance = 0 ";
979
				break;
980
			case 'all':					
981
			default:				
982
				break;	
983
		}		
984
		$sql .= " ORDER BY date_time ";		
985
        
986
		$rs = Database::query($sql);
987
		$data = array();
988
		if (Database::num_rows($rs) > 0) {
989
			while ($row = Database::fetch_array($rs,'ASSOC')) {
990
                $row['db_date_time']    = $row['date_time'];
991
                $row['date_time']       = api_get_local_time($row['date_time']);
992
                $row['date']            = api_format_date($row['date_time'], DATE_FORMAT_SHORT);
993
                $row['time']            = api_format_date($row['date_time'], TIME_NO_SEC_FORMAT);              
994
                if ($type == 'today') {                    
995
                    if (date('d-m-Y', api_strtotime($row['date_time'], 'UTC')) == date('d-m-Y', time())) {
996
                        $data[] = $row;                        
997
                    }
998
                } else {
999
                	$data[] = $row;
1000
                }
1001
			}
1002
		}
1003
		return $data;
1004
	}
1005
	
1006

    
1007
        /**
1008
	 * Get number of attendance calendar inside current attendance
1009
	 * @param	int	attendance id
1010
	 * @return	int     number of dates in attendance calendar
1011
	 */
1012
	public static function get_number_of_attendance_calendar($attendance_id) {
1013
		$tbl_attendance_calendar = Database::get_course_table(TABLE_ATTENDANCE_CALENDAR);
1014
		$attendance_id = intval($attendance_id);
1015
        $course_id = api_get_course_int_id();
1016
		$sql = "SELECT count(id) FROM $tbl_attendance_calendar 
1017
                WHERE c_id = $course_id AND attendance_id = '$attendance_id'";
1018
		$rs = Database::query($sql);
1019
                $row = Database::fetch_row($rs);
1020
		$count = $row[0];
1021
		return $count;
1022
	}
1023

    
1024
        /**
1025
	 * Get count dates inside attendance calendar by attendance id
1026
	 * @param	int	attendance id
1027
	 * @return	int     count of dates
1028
	 */
1029
	public static function get_count_dates_inside_attendance_calendar($attendance_id) {
1030
		$tbl_attendance_calendar = Database::get_course_table(TABLE_ATTENDANCE_CALENDAR);
1031
		$attendance_id = intval($attendance_id);
1032
         $course_id = api_get_course_int_id();
1033
		$sql = "SELECT count(id) FROM $tbl_attendance_calendar 
1034
                WHERE c_id = $course_id AND attendance_id = '$attendance_id'";
1035
		$rs = Database::query($sql);
1036
		$count = 0;
1037
		if (Database::num_rows($rs) > 0) {
1038
                    $row = Database::fetch_row($rs);
1039
                    $count = $row[0];
1040
		}
1041
		return $count;
1042
	}
1043

    
1044

    
1045
    /**
1046
     * check if all calendar of an attendance is done
1047
     * @param   int     attendance id
1048
     * @return  bool    True if all calendar is done, otherwise false
1049
     */
1050
    public static function is_all_attendance_calendar_done($attendance_id) {
1051
        $attendance_id = intval($attendance_id);
1052
        $done_calendar = self::get_done_attendance_calendar($attendance_id);
1053
        $count_dates_in_calendar = self::get_count_dates_inside_attendance_calendar($attendance_id);
1054
        $number_of_dates = self::get_number_of_attendance_calendar($attendance_id);
1055

    
1056
        $result = false;
1057
        if ($number_of_dates && (intval($count_dates_in_calendar) == intval($done_calendar))) {
1058
            $result = true;
1059
        }
1060
        return $result;
1061
    }
1062

    
1063
    /**
1064
     * check if an attendance is locked
1065
     * @param   int   attendance id
1066
     * @param   bool
1067
     */
1068
    public static function is_locked_attendance($attendance_id) {
1069
        //use gradebook lock
1070
        $result = api_resource_is_locked_by_gradebook($attendance_id, LINK_ATTENDANCE);            
1071
        return $result;  
1072
    }       
1073

    
1074
	/**
1075
	 * Add new datetime inside attendance calendar table
1076
	 * @param	int	attendance id
1077
	 * @return	int affected rows
1078
	 */
1079
	public function attendance_calendar_add($attendance_id) {
1080
		$tbl_attendance_calendar = Database::get_course_table(TABLE_ATTENDANCE_CALENDAR);
1081
		$affected_rows = 0;
1082
		$attendance_id = intval($attendance_id);
1083
        $course_id = api_get_course_int_id();
1084
		// check if datetime already exists inside the table
1085
		$sql = "SELECT id FROM $tbl_attendance_calendar 
1086
		        WHERE c_id = $course_id AND date_time='".Database::escape_string($this->date_time)."' AND attendance_id = '$attendance_id'";
1087
		$rs = Database::query($sql);
1088
		if (Database::num_rows($rs) == 0) {
1089
			$sql = "INSERT INTO $tbl_attendance_calendar SET
1090
					c_id			= $course_id,  
1091
					date_time		= '".Database::escape_string($this->date_time)."', 
1092
					attendance_id 	= '$attendance_id'";
1093
			Database::query($sql);
1094
			$affected_rows = Database::affected_rows();
1095
		}
1096

    
1097
        // update locked attendance
1098
        $is_all_calendar_done = self::is_all_attendance_calendar_done($attendance_id);
1099
        if (!$is_all_calendar_done) {
1100
            $unlock = self::lock_attendance($attendance_id, false);
1101
        } else {
1102
            $unlock = self::lock_attendance($attendance_id);
1103
        }
1104
		return $affected_rows;
1105
	}
1106

    
1107
    /**
1108
     * save repeated date inside attendance calendar table
1109
     * @param   int attendance id
1110
     * @param   int start date in tms
1111
     * @param   int end date in tms
1112
     * @param   string  repeat type  daily, weekly, monthlyByDate
1113

    
1114
     */
1115
    public function attendance_repeat_calendar_add($attendance_id, $start_date, $end_date, $repeat_type) {
1116
        $attendance_id = intval($attendance_id);
1117
        // save start date
1118
        $datetimezone = api_get_utc_datetime($start_date);
1119
        $this->set_date_time($datetimezone);
1120
        $res = $this->attendance_calendar_add($attendance_id);
1121

    
1122
        //86400 = 24 hours in seconds
1123
        //604800 = 1 week in seconds
1124
        // Saves repeated dates
1125
        switch($repeat_type) {
1126
            case 'daily':
1127
                $j = 1;
1128
                for ($i = $start_date + 86400; ($i <= $end_date); $i += 86400) {
1129
                    //$datetimezone = api_get_utc_date_add(api_get_utc_datetime($start_date), 0 , 0, $j);    //to support europe timezones                    
1130
                    $datetimezone = api_get_utc_datetime($i);
1131
                    $this->set_date_time($datetimezone);
1132
                    $res = $this->attendance_calendar_add($attendance_id);
1133
                    $j++;
1134
                }
1135
                break;
1136
                exit;
1137
            case 'weekly':
1138
                $j = 1;
1139
                for ($i = $start_date + 604800; ($i <= $end_date); $i += 604800) {                        
1140
                    $datetimezone = api_get_utc_datetime($i);
1141
                    //$datetimezone = api_get_utc_date_add(api_get_utc_datetime($start_date), 0 , 0, $j*7); //to support europe timezones
1142
                    $this->set_date_time($datetimezone);
1143
                    $res = $this->attendance_calendar_add($attendance_id);
1144
                    $j++;
1145
                }
1146
                break;
1147
            case 'monthlyByDate':
1148
                $j = 1;
1149
                //@todo fix bug with february
1150
                for ($i = $start_date + 2419200; ($i <= $end_date); $i += 2419200) {                        
1151
                    $datetimezone = api_get_utc_datetime($i);
1152
                    //$datetimezone = api_get_utc_date_add(api_get_utc_datetime($start_date), 0 , $j); //to support europe timezones
1153
                    $this->set_date_time($datetimezone);
1154
                    $res = $this->attendance_calendar_add($attendance_id);
1155
                    $j++;
1156
                }                
1157
                break;
1158
        }
1159
    }
1160

    
1161
    /**
1162
     * Adds x months to a UNIX timestamp
1163
     * @param   int     The timestamp
1164
     * @param   int     The number of years to add
1165
     * @return  int     The new timestamp
1166
     */
1167
    private function add_month($timestamp, $num=1) {
1168
        $values = api_get_utc_datetime($timestamp);
1169
        $values = str_replace(array(':','-',' '), '/', $values);            
1170
        list($y, $m, $d, $h, $n, $s) = split('/',$values);            
1171
        if($m+$num>12) {
1172
            $y += floor($num/12);
1173
            $m += $num%12;
1174
        } else {
1175
            $m += $num;
1176
        }
1177
        //date_default_timezone_set('UTC');
1178
       // return mktime($h, $n, $s, $m, $d, $y);                
1179
        $result = api_strtotime($y.'-'.$m.'-'.$d.' '.$h.':'.$n.':'.$s, 'UTC');           
1180
        if (!empty($result)) {
1181
            return $result;
1182
        }
1183
        return false;
1184
    }
1185

    
1186
	/**
1187
	 * edit a datetime inside attendance calendar table
1188
	 * @param	int	attendance calendar id
1189
	 * @param	int	attendance id
1190
	 * @return	int affected rows
1191
	 */
1192
	public function attendance_calendar_edit($calendar_id, $attendance_id) {
1193
		$tbl_attendance_calendar = Database::get_course_table(TABLE_ATTENDANCE_CALENDAR);
1194
		$affected_rows = 0;
1195
		$attendance_id = intval($attendance_id);
1196
        $course_id = api_get_course_int_id();
1197
		// check if datetime already exists inside the table
1198
		$sql = "SELECT id FROM $tbl_attendance_calendar 
1199
		        WHERE c_id = $course_id AND date_time = '".Database::escape_string($this->date_time)."' AND attendance_id = '$attendance_id'";
1200
		$rs = Database::query($sql);
1201
		if (Database::num_rows($rs) == 0) {
1202
			$sql = "UPDATE $tbl_attendance_calendar SET date_time='".Database::escape_string($this->date_time)."' WHERE c_id = $course_id AND id = '".intval($calendar_id)."'";
1203
			Database::query($sql);
1204
			$affected_rows = Database::affected_rows();
1205
		}
1206

    
1207
        // update locked attendance
1208
        $is_all_calendar_done = self::is_all_attendance_calendar_done($attendance_id);
1209
        if (!$is_all_calendar_done) {
1210
            $unlock = self::lock_attendance($attendance_id, false);
1211
        } else {
1212
            $unlock = self::lock_attendance($attendance_id);
1213
        }
1214
                
1215
		return $affected_rows;
1216
	}
1217

    
1218
	/**
1219
	 * delete a datetime from attendance calendar table
1220
	 * @param	int		attendance calendar id
1221
	 * @param	int		attendance id
1222
	 * @param	bool	true for removing all calendar inside current attendance, false for removing by calendar id
1223
	 * @return	int affected rows
1224
	 */
1225
	public function attendance_calendar_delete($calendar_id, $attendance_id , $all_delete = false) {
1226
		$tbl_attendance_calendar = Database::get_course_table(TABLE_ATTENDANCE_CALENDAR);
1227
		$tbl_attendance_sheet 	 = Database::get_course_table(TABLE_ATTENDANCE_SHEET);
1228
		$session_id = api_get_session_id();
1229
		$attendance_id = intval($attendance_id);
1230
		// get all registered users inside current course
1231
		$users = $this->get_users_rel_course();
1232
		$user_ids = array_keys($users);
1233
        $course_id = api_get_course_int_id();
1234

    
1235
		if ($all_delete) {
1236
			$attendance_calendar = $this->get_attendance_calendar($attendance_id);
1237
			$calendar_ids = array();
1238
			// get all dates from calendar by current attendance
1239
			if (!empty($attendance_calendar)) {
1240
				foreach ($attendance_calendar as $cal) {
1241
					// delete all data from attendance sheet
1242
					$sql = "DELETE FROM $tbl_attendance_sheet WHERE c_id = $course_id AND attendance_calendar_id = '".intval($cal['id'])."'";
1243
					Database::query($sql);
1244
					// delete data from attendance calendar
1245
					$sql = "DELETE FROM $tbl_attendance_calendar WHERE c_id = $course_id AND id = '".intval($cal['id'])."'";
1246
					Database::query($sql);
1247
				}
1248
			}
1249
		} else {
1250
			// delete just one row from attendance sheet by the calendar id
1251
			$sql = "DELETE FROM $tbl_attendance_sheet WHERE c_id = $course_id AND attendance_calendar_id = '".intval($calendar_id)."'";
1252
			Database::query($sql);
1253
			// delete data from attendance calendar
1254
			$sql = "DELETE FROM $tbl_attendance_calendar WHERE c_id = $course_id AND id = '".intval($calendar_id)."'";
1255
			Database::query($sql);
1256
		}
1257

    
1258
		$affected_rows = Database::affected_rows();
1259
		// update users' results
1260
		$this->update_users_results($user_ids, $attendance_id);                
1261

    
1262
		return $affected_rows;
1263
	}
1264

    
1265
	/**
1266
	 * buid a string datetime from array
1267
	 * @param	array	array containing data e.g: $array('Y'=>'2010',  'F' => '02', 'd' => '10', 'H' => '12', 'i' => '30')
1268
	 * @return	string	date and time e.g: '2010-02-10 12:30:00'
1269
	 */
1270
	public function build_datetime_from_array($array) {
1271
		$year	 = '0000';
1272
		$month = $day = $hours = $minutes = $seconds = '00';
1273
		if (isset($array['Y']) && (isset($array['F']) || isset($array['M']))  && isset($array['d']) && isset($array['H']) && isset($array['i'])) {
1274
			$year = $array['Y'];
1275
			$month = isset($array['F'])?$array['F']:$array['M'];
1276
			if (intval($month) < 10 ) $month = '0'.$month;
1277
			$day = $array['d'];
1278
			if (intval($day) < 10 ) $day = '0'.$day;
1279
			$hours = $array['H'];
1280
			if (intval($hours) < 10 ) $hours = '0'.$hours;
1281
			$minutes = $array['i'];
1282
			if (intval($minutes) < 10 ) $minutes = '0'.$minutes;
1283
		}
1284
		if (checkdate($month,$day,$year)) {
1285
			$datetime = $year.'-'.$month.'-'.$day.' '.$hours.':'.$minutes.':'.$seconds;
1286
		}
1287
		return $datetime;
1288
	}
1289

    
1290
	/** Setters for fields of attendances tables **/
1291
	public function set_session_id($session_id) {
1292
		$this->session_id = $session_id;
1293
	}
1294

    
1295
	public function set_course_id($course_id) {
1296
		$this->course_id = $course_id;
1297
	}
1298

    
1299
	public function set_date_time($datetime) {
1300
		$this->date_time = $datetime;
1301
	}
1302

    
1303
	public function set_name($name) {
1304
		$this->name = $name;
1305
	}
1306

    
1307
	public function set_description($description) {
1308
		$this->description = $description;
1309
	}
1310

    
1311
	public function set_attendance_qualify_title($attendance_qualify_title) {
1312
		$this->attendance_qualify_title = $attendance_qualify_title;
1313
	}
1314

    
1315
	public function set_attendance_weight($attendance_weight) {
1316
		$this->attendance_weight = $attendance_weight;
1317
	}
1318

    
1319
	/** Getters for fields of attendances tables **/
1320
	public function get_session_id() {
1321
		return $this->session_id;
1322
	}
1323

    
1324
	public function get_course_id() {
1325
		return $this->course_id;
1326
	}
1327

    
1328
	public function get_date_time() {
1329
		return $this->date_time;
1330
	}
1331

    
1332
	public function get_name($name) {
1333
		return $this->name;
1334
	}
1335

    
1336
	public function get_description($description) {
1337
		return $this->description;
1338
	}
1339

    
1340
	public function get_attendance_qualify_title($attendance_qualify_title) {
1341
		return $this->attendance_qualify_title;
1342
	}
1343

    
1344
	public function get_attendance_weight($attendance_weight) {
1345
		return $this->attendance_weight;
1346
	}
1347
}
    (1-1/1)