Completed
Push — 1.10.x ( 320abc...039d05 )
by José
151:51 queued 109:10
created
main/inc/lib/attendance.lib.php 1 patch
Indentation   +1704 added lines, -1704 removed lines patch added patch discarded remove patch
@@ -11,50 +11,50 @@  discard block
 block discarded – undo
11 11
  */
12 12
 class Attendance
13 13
 {
14
-	private $session_id;
15
-	private $course_id;
16
-	private $date_time;
17
-	private $name;
18
-	private $description;
19
-	private $attendance_qualify_title;
20
-	private $attendance_weight;
21
-	private $course_int_id;
22
-	public $category_id;
23
-
24
-	// constants
25
-	const DONE_ATTENDANCE_LOG_TYPE = 'done_attendance_sheet';
26
-	const UPDATED_ATTENDANCE_LOG_TYPE = 'updated_attendance_sheet';
27
-	const LOCKED_ATTENDANCE_LOG_TYPE = 'locked_attendance_sheet';
28
-
29
-	/**
30
-	 * Constructor
31
-	 */
32
-	public function __construct()
33
-	{
34
-		//$this->course_int_id = api_get_course_int_id();
35
-	}
36
-
37
-	/**
38
-	 * Get the total number of attendance inside current course and current session
39
-	 * @see SortableTable#get_total_number_of_items()
40
-	 */
41
-	public static function get_number_of_attendances($active = -1)
42
-	{
43
-		$tbl_attendance = Database :: get_course_table(TABLE_ATTENDANCE);
44
-		$session_id = api_get_session_id();
45
-		$condition_session = api_get_session_condition($session_id);
46
-		$course_id = api_get_course_int_id();
47
-		$sql = "SELECT COUNT(att.id) AS total_number_of_items
14
+    private $session_id;
15
+    private $course_id;
16
+    private $date_time;
17
+    private $name;
18
+    private $description;
19
+    private $attendance_qualify_title;
20
+    private $attendance_weight;
21
+    private $course_int_id;
22
+    public $category_id;
23
+
24
+    // constants
25
+    const DONE_ATTENDANCE_LOG_TYPE = 'done_attendance_sheet';
26
+    const UPDATED_ATTENDANCE_LOG_TYPE = 'updated_attendance_sheet';
27
+    const LOCKED_ATTENDANCE_LOG_TYPE = 'locked_attendance_sheet';
28
+
29
+    /**
30
+     * Constructor
31
+     */
32
+    public function __construct()
33
+    {
34
+        //$this->course_int_id = api_get_course_int_id();
35
+    }
36
+
37
+    /**
38
+     * Get the total number of attendance inside current course and current session
39
+     * @see SortableTable#get_total_number_of_items()
40
+     */
41
+    public static function get_number_of_attendances($active = -1)
42
+    {
43
+        $tbl_attendance = Database :: get_course_table(TABLE_ATTENDANCE);
44
+        $session_id = api_get_session_id();
45
+        $condition_session = api_get_session_condition($session_id);
46
+        $course_id = api_get_course_int_id();
47
+        $sql = "SELECT COUNT(att.id) AS total_number_of_items
48 48
 				FROM $tbl_attendance att
49 49
 		        WHERE c_id = $course_id $condition_session ";
50
-		if ($active == 1 || $active == 0) {
51
-			$sql .= "AND att.active = $active";
52
-		}
53
-		$res = Database::query($sql);
54
-		$obj = Database::fetch_object($res);
50
+        if ($active == 1 || $active == 0) {
51
+            $sql .= "AND att.active = $active";
52
+        }
53
+        $res = Database::query($sql);
54
+        $obj = Database::fetch_object($res);
55 55
 
56
-		return $obj->total_number_of_items;
57
-	}
56
+        return $obj->total_number_of_items;
57
+    }
58 58
 
59 59
     /**
60 60
      * Get attendance list only the id, name and attendance_qualify_max fields
@@ -90,36 +90,36 @@  discard block
 block discarded – undo
90 90
         return $data;
91 91
     }
92 92
 
93
-	/**
94
-	 * Get the attendaces to display on the current page (fill the sortable-table)
95
-	 * @param   int     offset of first user to recover
96
-	 * @param   int     Number of users to get
97
-	 * @param   int     Column to sort on
98
-	 * @param   string  Order (ASC,DESC)
99
-	 * @see SortableTable#get_table_data($from)
100
-	 */
101
-	public static function get_attendance_data($from, $number_of_items, $column, $direction)
102
-	{
103
-		$tbl_attendance = Database::get_course_table(TABLE_ATTENDANCE);
104
-		$course_id = api_get_course_int_id();
105
-		$session_id = api_get_session_id();
106
-		$condition_session = api_get_session_condition($session_id);
107
-		$column = intval($column);
108
-		$from = intval($from);
109
-		$number_of_items = intval($number_of_items);
110
-
111
-		if (!in_array($direction, array('ASC','DESC'))) {
112
-			$direction = 'ASC';
113
-		}
114
-
115
-		$active_plus = '';
116
-		if ((isset($_GET['isStudentView']) && $_GET['isStudentView'] == 'true') ||
117
-			!api_is_allowed_to_edit(null, true)
118
-		) {
119
-			$active_plus = ' AND att.active = 1';
120
-		}
121
-
122
-		$sql = "SELECT
93
+    /**
94
+     * Get the attendaces to display on the current page (fill the sortable-table)
95
+     * @param   int     offset of first user to recover
96
+     * @param   int     Number of users to get
97
+     * @param   int     Column to sort on
98
+     * @param   string  Order (ASC,DESC)
99
+     * @see SortableTable#get_table_data($from)
100
+     */
101
+    public static function get_attendance_data($from, $number_of_items, $column, $direction)
102
+    {
103
+        $tbl_attendance = Database::get_course_table(TABLE_ATTENDANCE);
104
+        $course_id = api_get_course_int_id();
105
+        $session_id = api_get_session_id();
106
+        $condition_session = api_get_session_condition($session_id);
107
+        $column = intval($column);
108
+        $from = intval($from);
109
+        $number_of_items = intval($number_of_items);
110
+
111
+        if (!in_array($direction, array('ASC','DESC'))) {
112
+            $direction = 'ASC';
113
+        }
114
+
115
+        $active_plus = '';
116
+        if ((isset($_GET['isStudentView']) && $_GET['isStudentView'] == 'true') ||
117
+            !api_is_allowed_to_edit(null, true)
118
+        ) {
119
+            $active_plus = ' AND att.active = 1';
120
+        }
121
+
122
+        $sql = "SELECT
123 123
                     att.id AS col0,
124 124
                     att.name AS col1,
125 125
                     att.description AS col2,
@@ -134,318 +134,318 @@  discard block
 block discarded – undo
134 134
 				ORDER BY col$column $direction
135 135
 				LIMIT $from,$number_of_items ";
136 136
 
137
-		$res = Database::query($sql);
138
-		$attendances = array ();
139
-		$user_info = api_get_user_info();
140
-		$allowDelete = api_get_setting('allow_delete_attendance');
141
-
142
-		while ($attendance = Database::fetch_row($res)) {
143
-
144
-			$student_param = '';
145
-			if (api_is_drh() && $_GET['student_id']) {
146
-				$student_param = '&student_id='.intval($_GET['student_id']);
147
-			}
148
-
149
-			$session_star = '';
150
-
151
-			if (api_get_session_id() == $attendance[6]) {
152
-				$session_star = api_get_session_image(api_get_session_id(), $user_info['status']);
153
-			}
154
-			if ($attendance[5] == 1) {
155
-
156
-				$isDrhOfCourse = CourseManager::isUserSubscribedInCourseAsDrh(
157
-					api_get_user_id(),
158
-					api_get_course_info()
159
-				);
160
-
161
-				if (api_is_allowed_to_edit(null, true) || $isDrhOfCourse) {
162
-					// Link to edit
163
-					$attendance[1] = '<a href="index.php?'.api_get_cidreq().'&action=attendance_sheet_list&attendance_id='.$attendance[0].$student_param.'">'.$attendance[1].'</a>'.$session_star;
164
-				} else {
165
-					// Link to view
166
-					$attendance[1] = '<a href="index.php?'.api_get_cidreq().'&action=attendance_sheet_list_no_edit&attendance_id='.$attendance[0].$student_param.'">'.$attendance[1].'</a>'.$session_star;
167
-				}
168
-
169
-			} else {
170
-				$attendance[1] = '<a class="muted" href="index.php?'.api_get_cidreq().'&action=attendance_sheet_list&attendance_id='.$attendance[0].$student_param.'">'.$attendance[1].'</a>'.$session_star;
171
-			}
172
-
173
-			if ($attendance[5] == 1) {
174
-				$attendance[3] = '<center>'.$attendance[3].'</center>';
175
-			} else {
176
-				$attendance[3] = '<center><span class="muted">'.$attendance[3].'</span></center>';
177
-			}
178
-
179
-			$attendance[3] = '<center>'.$attendance[3].'</center>';
180
-			if (api_is_allowed_to_edit(null, true)) {
181
-				$actions  = '';
182
-				$actions .= '<center>';
183
-
184
-				if (api_is_platform_admin()) {
185
-					$actions .= '<a href="index.php?'.api_get_cidreq().'&action=attendance_edit&attendance_id='.$attendance[0].'">'.
186
-						Display::return_icon('edit.png', get_lang('Edit'), array(), ICON_SIZE_SMALL).'</a>&nbsp;';
187
-					// Visible
188
-					if ($attendance[5] == 1) {
189
-						$actions .= '<a href="index.php?'.api_get_cidreq().'&action=attendance_set_invisible&attendance_id='.$attendance[0].'">'.
190
-							Display::return_icon('visible.png', get_lang('Hide'), array(), ICON_SIZE_SMALL).'</a>';
191
-					} else {
192
-						$actions .= '<a href="index.php?'.api_get_cidreq().'&action=attendance_set_visible&attendance_id='.$attendance[0].'">'.
193
-							Display::return_icon('invisible.png', get_lang('Show'), array(), ICON_SIZE_SMALL).'</a>';
194
-						$attendance[2] = '<span class="muted">'.$attendance[2].'</span>';
195
-					}
196
-					if ($allowDelete === 'true') {
197
-						$actions .= '<a href="index.php?' . api_get_cidreq() . '&action=attendance_delete&attendance_id=' . $attendance[0]. '">' .
198
-							Display::return_icon('delete.png', get_lang('Delete'), array(), ICON_SIZE_SMALL) . '</a>';
199
-					}
200
-				} else {
201
-					$is_locked_attendance = self::is_locked_attendance($attendance[0]);
202
-					if ($is_locked_attendance) {
203
-						$actions .= Display::return_icon('edit_na.png', get_lang('Edit')).'&nbsp;';
204
-						$actions .= Display::return_icon('visible.png', get_lang('Hide'));
205
-					} else {
206
-						$actions .= '<a href="index.php?'.api_get_cidreq().'&action=attendance_edit&attendance_id='.$attendance[0].'">'.
207
-							Display::return_icon('edit.png', get_lang('Edit'), array(), ICON_SIZE_SMALL).'</a>&nbsp;';
208
-
209
-						if ($attendance[5] == 1) {
210
-							$actions .= ' <a href="index.php?'.api_get_cidreq().'&action=attendance_set_invisible&attendance_id='.$attendance[0].'">'.
211
-								Display::return_icon('visible.png', get_lang('Hide'), array(), ICON_SIZE_SMALL).'</a>';
212
-						} else {
213
-							$actions .= ' <a href="index.php?'.api_get_cidreq().'&action=attendance_set_visible&attendance_id='.$attendance[0].'">'.
214
-								Display::return_icon('invisible.png', get_lang('Show'), array(), ICON_SIZE_SMALL).'</a>';
215
-							$attendance[2] = '<span class="muted">'.$attendance[2].'</span>';
216
-						}
217
-						if ($allowDelete === 'true') {
218
-							$actions .= ' <a href="index.php?' . api_get_cidreq() . '&action=attendance_delete&attendance_id=' . $attendance[0].'">' .
219
-								Display::return_icon('delete.png', get_lang('Delete'), array(), ICON_SIZE_SMALL) . '</a>';
220
-						}
221
-					}
222
-				}
223
-
224
-				// display lock/unlock icon
225
-				$is_done_all_calendar = self::is_all_attendance_calendar_done($attendance[0]);
226
-
227
-				if ($is_done_all_calendar) {
228
-					$locked   = $attendance[4];
229
-					if ($locked == 0) {
230
-						if (api_is_platform_admin()) {
231
-							$message_alert = get_lang('AreYouSureToLockTheAttendance');
232
-						} else {
233
-							$message_alert = get_lang('UnlockMessageInformation');
234
-						}
235
-						$actions .= '&nbsp;<a onclick="javascript:if(!confirm(\''.$message_alert.'\')) return false;" href="index.php?'.api_get_cidreq().'&action=lock_attendance&attendance_id='.$attendance[0].'">'.
137
+        $res = Database::query($sql);
138
+        $attendances = array ();
139
+        $user_info = api_get_user_info();
140
+        $allowDelete = api_get_setting('allow_delete_attendance');
141
+
142
+        while ($attendance = Database::fetch_row($res)) {
143
+
144
+            $student_param = '';
145
+            if (api_is_drh() && $_GET['student_id']) {
146
+                $student_param = '&student_id='.intval($_GET['student_id']);
147
+            }
148
+
149
+            $session_star = '';
150
+
151
+            if (api_get_session_id() == $attendance[6]) {
152
+                $session_star = api_get_session_image(api_get_session_id(), $user_info['status']);
153
+            }
154
+            if ($attendance[5] == 1) {
155
+
156
+                $isDrhOfCourse = CourseManager::isUserSubscribedInCourseAsDrh(
157
+                    api_get_user_id(),
158
+                    api_get_course_info()
159
+                );
160
+
161
+                if (api_is_allowed_to_edit(null, true) || $isDrhOfCourse) {
162
+                    // Link to edit
163
+                    $attendance[1] = '<a href="index.php?'.api_get_cidreq().'&action=attendance_sheet_list&attendance_id='.$attendance[0].$student_param.'">'.$attendance[1].'</a>'.$session_star;
164
+                } else {
165
+                    // Link to view
166
+                    $attendance[1] = '<a href="index.php?'.api_get_cidreq().'&action=attendance_sheet_list_no_edit&attendance_id='.$attendance[0].$student_param.'">'.$attendance[1].'</a>'.$session_star;
167
+                }
168
+
169
+            } else {
170
+                $attendance[1] = '<a class="muted" href="index.php?'.api_get_cidreq().'&action=attendance_sheet_list&attendance_id='.$attendance[0].$student_param.'">'.$attendance[1].'</a>'.$session_star;
171
+            }
172
+
173
+            if ($attendance[5] == 1) {
174
+                $attendance[3] = '<center>'.$attendance[3].'</center>';
175
+            } else {
176
+                $attendance[3] = '<center><span class="muted">'.$attendance[3].'</span></center>';
177
+            }
178
+
179
+            $attendance[3] = '<center>'.$attendance[3].'</center>';
180
+            if (api_is_allowed_to_edit(null, true)) {
181
+                $actions  = '';
182
+                $actions .= '<center>';
183
+
184
+                if (api_is_platform_admin()) {
185
+                    $actions .= '<a href="index.php?'.api_get_cidreq().'&action=attendance_edit&attendance_id='.$attendance[0].'">'.
186
+                        Display::return_icon('edit.png', get_lang('Edit'), array(), ICON_SIZE_SMALL).'</a>&nbsp;';
187
+                    // Visible
188
+                    if ($attendance[5] == 1) {
189
+                        $actions .= '<a href="index.php?'.api_get_cidreq().'&action=attendance_set_invisible&attendance_id='.$attendance[0].'">'.
190
+                            Display::return_icon('visible.png', get_lang('Hide'), array(), ICON_SIZE_SMALL).'</a>';
191
+                    } else {
192
+                        $actions .= '<a href="index.php?'.api_get_cidreq().'&action=attendance_set_visible&attendance_id='.$attendance[0].'">'.
193
+                            Display::return_icon('invisible.png', get_lang('Show'), array(), ICON_SIZE_SMALL).'</a>';
194
+                        $attendance[2] = '<span class="muted">'.$attendance[2].'</span>';
195
+                    }
196
+                    if ($allowDelete === 'true') {
197
+                        $actions .= '<a href="index.php?' . api_get_cidreq() . '&action=attendance_delete&attendance_id=' . $attendance[0]. '">' .
198
+                            Display::return_icon('delete.png', get_lang('Delete'), array(), ICON_SIZE_SMALL) . '</a>';
199
+                    }
200
+                } else {
201
+                    $is_locked_attendance = self::is_locked_attendance($attendance[0]);
202
+                    if ($is_locked_attendance) {
203
+                        $actions .= Display::return_icon('edit_na.png', get_lang('Edit')).'&nbsp;';
204
+                        $actions .= Display::return_icon('visible.png', get_lang('Hide'));
205
+                    } else {
206
+                        $actions .= '<a href="index.php?'.api_get_cidreq().'&action=attendance_edit&attendance_id='.$attendance[0].'">'.
207
+                            Display::return_icon('edit.png', get_lang('Edit'), array(), ICON_SIZE_SMALL).'</a>&nbsp;';
208
+
209
+                        if ($attendance[5] == 1) {
210
+                            $actions .= ' <a href="index.php?'.api_get_cidreq().'&action=attendance_set_invisible&attendance_id='.$attendance[0].'">'.
211
+                                Display::return_icon('visible.png', get_lang('Hide'), array(), ICON_SIZE_SMALL).'</a>';
212
+                        } else {
213
+                            $actions .= ' <a href="index.php?'.api_get_cidreq().'&action=attendance_set_visible&attendance_id='.$attendance[0].'">'.
214
+                                Display::return_icon('invisible.png', get_lang('Show'), array(), ICON_SIZE_SMALL).'</a>';
215
+                            $attendance[2] = '<span class="muted">'.$attendance[2].'</span>';
216
+                        }
217
+                        if ($allowDelete === 'true') {
218
+                            $actions .= ' <a href="index.php?' . api_get_cidreq() . '&action=attendance_delete&attendance_id=' . $attendance[0].'">' .
219
+                                Display::return_icon('delete.png', get_lang('Delete'), array(), ICON_SIZE_SMALL) . '</a>';
220
+                        }
221
+                    }
222
+                }
223
+
224
+                // display lock/unlock icon
225
+                $is_done_all_calendar = self::is_all_attendance_calendar_done($attendance[0]);
226
+
227
+                if ($is_done_all_calendar) {
228
+                    $locked   = $attendance[4];
229
+                    if ($locked == 0) {
230
+                        if (api_is_platform_admin()) {
231
+                            $message_alert = get_lang('AreYouSureToLockTheAttendance');
232
+                        } else {
233
+                            $message_alert = get_lang('UnlockMessageInformation');
234
+                        }
235
+                        $actions .= '&nbsp;<a onclick="javascript:if(!confirm(\''.$message_alert.'\')) return false;" href="index.php?'.api_get_cidreq().'&action=lock_attendance&attendance_id='.$attendance[0].'">'.
236 236
                             Display::return_icon('unlock.png', get_lang('LockAttendance')).'</a>';
237
-					} else {
238
-						if (api_is_platform_admin()) {
239
-							$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].'">'.
240
-									Display::return_icon('locked.png', get_lang('UnlockAttendance')).'</a>';
241
-						} else {
242
-							$actions .= '&nbsp;'.Display::return_icon('locked_na.png', get_lang('LockedAttendance'));
243
-						}
244
-					}
245
-				}
246
-				$actions .= '</center>';
247
-
248
-				$attendances[] = array($attendance[0], $attendance[1], $attendance[2], $attendance[3],$actions);
249
-			} else {
250
-				$attendance[0] = '&nbsp;';
251
-				$attendances[] = array($attendance[0], $attendance[1], $attendance[2], $attendance[3]);
252
-			}
253
-		}
254
-		return $attendances;
255
-	}
256
-
257
-	/**
258
-	 * Get the attendances by id to display on the current page
259
-	 * @param  int     $attendance_id
260
-	 * @return array   attendance data
261
-	 */
262
-	public function get_attendance_by_id($attendance_id)
263
-	{
264
-		$tbl_attendance = Database :: get_course_table(TABLE_ATTENDANCE);
265
-		$attendance_id = intval($attendance_id);
266
-		$course_id = api_get_course_int_id();
267
-		$attendance_data = array();
268
-		$sql = "SELECT * FROM $tbl_attendance
237
+                    } else {
238
+                        if (api_is_platform_admin()) {
239
+                            $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].'">'.
240
+                                    Display::return_icon('locked.png', get_lang('UnlockAttendance')).'</a>';
241
+                        } else {
242
+                            $actions .= '&nbsp;'.Display::return_icon('locked_na.png', get_lang('LockedAttendance'));
243
+                        }
244
+                    }
245
+                }
246
+                $actions .= '</center>';
247
+
248
+                $attendances[] = array($attendance[0], $attendance[1], $attendance[2], $attendance[3],$actions);
249
+            } else {
250
+                $attendance[0] = '&nbsp;';
251
+                $attendances[] = array($attendance[0], $attendance[1], $attendance[2], $attendance[3]);
252
+            }
253
+        }
254
+        return $attendances;
255
+    }
256
+
257
+    /**
258
+     * Get the attendances by id to display on the current page
259
+     * @param  int     $attendance_id
260
+     * @return array   attendance data
261
+     */
262
+    public function get_attendance_by_id($attendance_id)
263
+    {
264
+        $tbl_attendance = Database :: get_course_table(TABLE_ATTENDANCE);
265
+        $attendance_id = intval($attendance_id);
266
+        $course_id = api_get_course_int_id();
267
+        $attendance_data = array();
268
+        $sql = "SELECT * FROM $tbl_attendance
269 269
 				WHERE c_id = $course_id AND id = '$attendance_id'";
270
-		$res = Database::query($sql);
271
-		if (Database::num_rows($res) > 0) {
272
-			while ($row = Database::fetch_array($res)) {
273
-				$attendance_data = $row;
274
-			}
275
-		}
276
-		return $attendance_data;
277
-	}
278
-
279
-	/**
280
-	 * Add attendances sheet inside table. This is the *list of* dates, not
281
-	 * a specific date in itself.
282
-	 * @param  bool   true for adding link in gradebook or false otherwise (optional)
283
-	 * @return int    last attendance id
284
-	 */
285
-	public function attendance_add($link_to_gradebook = false)
286
-	{
287
-		$_course = api_get_course_info();
288
-		$tbl_attendance	= Database :: get_course_table(TABLE_ATTENDANCE);
289
-		$table_link = Database:: get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
290
-		$session_id = api_get_session_id();
291
-		$user_id = api_get_user_id();
292
-		$course_code = $_course['code'];
293
-		$course_id = $_course['real_id'];
294
-		$title_gradebook= $this->attendance_qualify_title;
295
-		$value_calification = 0;
296
-		$weight_calification = floatval($this->attendance_weight);
297
-
298
-		$params = [
299
-			'c_id' => $course_id,
300
-			'name' => $this->name,
301
-			'description' => $this->description,
302
-			'attendance_qualify_title' => $title_gradebook,
303
-			'attendance_weight' => $weight_calification,
304
-			'session_id' => $session_id,
305
-			'active' => 1,
306
-			'attendance_qualify_max' => 0,
307
-			'locked' => 0
308
-		];
309
-		$last_id = Database::insert($tbl_attendance, $params);
310
-
311
-		if (!empty($last_id)) {
312
-
313
-			$sql = "UPDATE $tbl_attendance SET id = iid WHERE iid = $last_id";
314
-			Database::query($sql);
315
-
316
-			api_item_property_update(
317
-				$_course,
318
-				TOOL_ATTENDANCE,
319
-				$last_id,
320
-				"AttendanceAdded",
321
-				$user_id
322
-			);
323
-
324
-		}
325
-		// add link to gradebook
326
-		if ($link_to_gradebook && !empty($this->category_id)) {
327
-			$description = '';
270
+        $res = Database::query($sql);
271
+        if (Database::num_rows($res) > 0) {
272
+            while ($row = Database::fetch_array($res)) {
273
+                $attendance_data = $row;
274
+            }
275
+        }
276
+        return $attendance_data;
277
+    }
278
+
279
+    /**
280
+     * Add attendances sheet inside table. This is the *list of* dates, not
281
+     * a specific date in itself.
282
+     * @param  bool   true for adding link in gradebook or false otherwise (optional)
283
+     * @return int    last attendance id
284
+     */
285
+    public function attendance_add($link_to_gradebook = false)
286
+    {
287
+        $_course = api_get_course_info();
288
+        $tbl_attendance	= Database :: get_course_table(TABLE_ATTENDANCE);
289
+        $table_link = Database:: get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
290
+        $session_id = api_get_session_id();
291
+        $user_id = api_get_user_id();
292
+        $course_code = $_course['code'];
293
+        $course_id = $_course['real_id'];
294
+        $title_gradebook= $this->attendance_qualify_title;
295
+        $value_calification = 0;
296
+        $weight_calification = floatval($this->attendance_weight);
297
+
298
+        $params = [
299
+            'c_id' => $course_id,
300
+            'name' => $this->name,
301
+            'description' => $this->description,
302
+            'attendance_qualify_title' => $title_gradebook,
303
+            'attendance_weight' => $weight_calification,
304
+            'session_id' => $session_id,
305
+            'active' => 1,
306
+            'attendance_qualify_max' => 0,
307
+            'locked' => 0
308
+        ];
309
+        $last_id = Database::insert($tbl_attendance, $params);
310
+
311
+        if (!empty($last_id)) {
312
+
313
+            $sql = "UPDATE $tbl_attendance SET id = iid WHERE iid = $last_id";
314
+            Database::query($sql);
315
+
316
+            api_item_property_update(
317
+                $_course,
318
+                TOOL_ATTENDANCE,
319
+                $last_id,
320
+                "AttendanceAdded",
321
+                $user_id
322
+            );
323
+
324
+        }
325
+        // add link to gradebook
326
+        if ($link_to_gradebook && !empty($this->category_id)) {
327
+            $description = '';
328 328
             $link_info = GradebookUtils::is_resource_in_course_gradebook(
329 329
                 $course_code,
330 330
                 7,
331 331
                 $last_id,
332 332
                 $session_id
333 333
             );
334
-			$link_id = $link_info['id'];
335
-			if (!$link_info) {
336
-				GradebookUtils::add_resource_to_course_gradebook(
337
-					$this->category_id,
338
-					$course_code,
339
-					7,
340
-					$last_id,
341
-					$title_gradebook,
342
-					$weight_calification,
343
-					$value_calification,
344
-					$description,
345
-					1,
346
-					$session_id
347
-				);
348
-			} else {
349
-				Database::query('UPDATE '.$table_link.' SET weight='.$weight_calification.' WHERE id='.$link_id.'');
350
-			}
351
-		}
352
-		return $last_id;
353
-	}
354
-
355
-	/**
356
-	 * edit attendances inside table
357
-	 * @param 	int	   attendance id
358
-	 * @param  	bool   true for adding link in gradebook or false otherwise (optional)
359
-	 * @return 	int    last id
360
-	 */
361
-	public function attendance_edit($attendance_id, $link_to_gradebook = false)
362
-	{
363
-		$_course = api_get_course_info();
364
-		$tbl_attendance = Database:: get_course_table(TABLE_ATTENDANCE);
365
-		$table_link = Database:: get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
366
-
367
-		$session_id = api_get_session_id();
368
-		$user_id = api_get_user_id();
369
-		$attendance_id = intval($attendance_id);
370
-		$course_code = $_course['code'];
371
-		$course_id = $_course['real_id'];
372
-		$title_gradebook = $this->attendance_qualify_title;
373
-		$value_calification = 0;
374
-		$weight_calification = floatval($this->attendance_weight);
375
-
376
-		if (!empty($attendance_id)) {
377
-
378
-			$params = [
379
-				'name' => $this->name,
380
-				'description' => $this->description,
381
-				'attendance_qualify_title' => $title_gradebook,
382
-				'attendance_weight' => $weight_calification
383
-			];
384
-			Database::update(
385
-				$tbl_attendance,
386
-				$params,
387
-				['c_id = ? AND id = ?' => [$course_id, $attendance_id]]
388
-			);
389
-
390
-			api_item_property_update(
391
-				$_course,
392
-				TOOL_ATTENDANCE,
393
-				$attendance_id,
394
-				"AttendanceUpdated",
395
-				$user_id
396
-			);
397
-
398
-			// add link to gradebook
399
-			if ($link_to_gradebook && !empty($this->category_id)) {
400
-				$description = '';
401
-				$link_info = GradebookUtils::is_resource_in_course_gradebook(
402
-					$course_code,
403
-					7,
404
-					$attendance_id,
405
-					$session_id
406
-				);
407
-				if (!$link_info) {
408
-					GradebookUtils::add_resource_to_course_gradebook(
409
-						$this->category_id,
410
-						$course_code,
411
-						7,
412
-						$attendance_id,
413
-						$title_gradebook,
414
-						$weight_calification,
415
-						$value_calification,
416
-						$description,
417
-						1,
418
-						$session_id
419
-					);
420
-				} else {
421
-					Database::query('UPDATE '.$table_link.' SET weight='.$weight_calification.' WHERE id='.$link_info['id'].'');
422
-				}
423
-			}
424
-			return $attendance_id;
425
-		}
426
-		return null;
427
-	}
428
-
429
-	/**
430
-	 * Restore attendance
431
-	 * @param 	int|array	   one or many attendances id
432
-	 * @return 	int    		   affected rows
433
-	 */
434
-	public function attendance_restore($attendance_id)
435
-	{
436
-		$_course = api_get_course_info();
437
-		$tbl_attendance	= Database :: get_course_table(TABLE_ATTENDANCE);
438
-		$user_id = api_get_user_id();
439
-		$course_id = $_course['real_id'];
440
-		if (is_array($attendance_id)) {
441
-			foreach ($attendance_id as $id) {
442
-				$id	= intval($id);
443
-				$sql = "UPDATE $tbl_attendance SET active = 1
334
+            $link_id = $link_info['id'];
335
+            if (!$link_info) {
336
+                GradebookUtils::add_resource_to_course_gradebook(
337
+                    $this->category_id,
338
+                    $course_code,
339
+                    7,
340
+                    $last_id,
341
+                    $title_gradebook,
342
+                    $weight_calification,
343
+                    $value_calification,
344
+                    $description,
345
+                    1,
346
+                    $session_id
347
+                );
348
+            } else {
349
+                Database::query('UPDATE '.$table_link.' SET weight='.$weight_calification.' WHERE id='.$link_id.'');
350
+            }
351
+        }
352
+        return $last_id;
353
+    }
354
+
355
+    /**
356
+     * edit attendances inside table
357
+     * @param 	int	   attendance id
358
+     * @param  	bool   true for adding link in gradebook or false otherwise (optional)
359
+     * @return 	int    last id
360
+     */
361
+    public function attendance_edit($attendance_id, $link_to_gradebook = false)
362
+    {
363
+        $_course = api_get_course_info();
364
+        $tbl_attendance = Database:: get_course_table(TABLE_ATTENDANCE);
365
+        $table_link = Database:: get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
366
+
367
+        $session_id = api_get_session_id();
368
+        $user_id = api_get_user_id();
369
+        $attendance_id = intval($attendance_id);
370
+        $course_code = $_course['code'];
371
+        $course_id = $_course['real_id'];
372
+        $title_gradebook = $this->attendance_qualify_title;
373
+        $value_calification = 0;
374
+        $weight_calification = floatval($this->attendance_weight);
375
+
376
+        if (!empty($attendance_id)) {
377
+
378
+            $params = [
379
+                'name' => $this->name,
380
+                'description' => $this->description,
381
+                'attendance_qualify_title' => $title_gradebook,
382
+                'attendance_weight' => $weight_calification
383
+            ];
384
+            Database::update(
385
+                $tbl_attendance,
386
+                $params,
387
+                ['c_id = ? AND id = ?' => [$course_id, $attendance_id]]
388
+            );
389
+
390
+            api_item_property_update(
391
+                $_course,
392
+                TOOL_ATTENDANCE,
393
+                $attendance_id,
394
+                "AttendanceUpdated",
395
+                $user_id
396
+            );
397
+
398
+            // add link to gradebook
399
+            if ($link_to_gradebook && !empty($this->category_id)) {
400
+                $description = '';
401
+                $link_info = GradebookUtils::is_resource_in_course_gradebook(
402
+                    $course_code,
403
+                    7,
404
+                    $attendance_id,
405
+                    $session_id
406
+                );
407
+                if (!$link_info) {
408
+                    GradebookUtils::add_resource_to_course_gradebook(
409
+                        $this->category_id,
410
+                        $course_code,
411
+                        7,
412
+                        $attendance_id,
413
+                        $title_gradebook,
414
+                        $weight_calification,
415
+                        $value_calification,
416
+                        $description,
417
+                        1,
418
+                        $session_id
419
+                    );
420
+                } else {
421
+                    Database::query('UPDATE '.$table_link.' SET weight='.$weight_calification.' WHERE id='.$link_info['id'].'');
422
+                }
423
+            }
424
+            return $attendance_id;
425
+        }
426
+        return null;
427
+    }
428
+
429
+    /**
430
+     * Restore attendance
431
+     * @param 	int|array	   one or many attendances id
432
+     * @return 	int    		   affected rows
433
+     */
434
+    public function attendance_restore($attendance_id)
435
+    {
436
+        $_course = api_get_course_info();
437
+        $tbl_attendance	= Database :: get_course_table(TABLE_ATTENDANCE);
438
+        $user_id = api_get_user_id();
439
+        $course_id = $_course['real_id'];
440
+        if (is_array($attendance_id)) {
441
+            foreach ($attendance_id as $id) {
442
+                $id	= intval($id);
443
+                $sql = "UPDATE $tbl_attendance SET active = 1
444 444
 						WHERE c_id = $course_id AND id = '$id'";
445
-				$result = Database::query($sql);
446
-				$affected_rows = Database::affected_rows($result);
447
-				if (!empty($affected_rows)) {
448
-					// update row item property table
445
+                $result = Database::query($sql);
446
+                $affected_rows = Database::affected_rows($result);
447
+                if (!empty($affected_rows)) {
448
+                    // update row item property table
449 449
                     api_item_property_update(
450 450
                         $_course,
451 451
                         TOOL_ATTENDANCE,
@@ -453,16 +453,16 @@  discard block
 block discarded – undo
453 453
                         "restore",
454 454
                         $user_id
455 455
                     );
456
-				}
457
-			}
458
-		} else  {
459
-			$attendance_id	= intval($attendance_id);
460
-			$sql = "UPDATE $tbl_attendance SET active = 1
456
+                }
457
+            }
458
+        } else  {
459
+            $attendance_id	= intval($attendance_id);
460
+            $sql = "UPDATE $tbl_attendance SET active = 1
461 461
 					WHERE c_id = $course_id AND id = '$attendance_id'";
462
-			$result = Database::query($sql);
463
-			$affected_rows = Database::affected_rows($result);
464
-			if (!empty($affected_rows)) {
465
-				// update row item property table
462
+            $result = Database::query($sql);
463
+            $affected_rows = Database::affected_rows($result);
464
+            if (!empty($affected_rows)) {
465
+                // update row item property table
466 466
                 api_item_property_update(
467 467
                     $_course,
468 468
                     TOOL_ATTENDANCE,
@@ -470,33 +470,33 @@  discard block
 block discarded – undo
470 470
                     "restore",
471 471
                     $user_id
472 472
                 );
473
-			}
474
-		}
475
-
476
-		return $affected_rows;
477
-	}
478
-
479
-	/**
480
-	 * Delete attendances
481
-	 * @param 	int|array	$attendance_id   one or many attendances id
482
-	 * @return 	int    		   affected rows
483
-	 */
484
-	public function attendance_delete($attendance_id)
485
-	{
486
-		$_course = api_get_course_info();
487
-		$tbl_attendance	= Database :: get_course_table(TABLE_ATTENDANCE);
473
+            }
474
+        }
475
+
476
+        return $affected_rows;
477
+    }
478
+
479
+    /**
480
+     * Delete attendances
481
+     * @param 	int|array	$attendance_id   one or many attendances id
482
+     * @return 	int    		   affected rows
483
+     */
484
+    public function attendance_delete($attendance_id)
485
+    {
486
+        $_course = api_get_course_info();
487
+        $tbl_attendance	= Database :: get_course_table(TABLE_ATTENDANCE);
488 488
         $user_id = api_get_user_id();
489 489
         $course_id = $_course['real_id'];
490 490
 
491
-		if (is_array($attendance_id)) {
492
-			foreach ($attendance_id as $id) {
493
-				$id	= intval($id);
494
-				$sql = "UPDATE $tbl_attendance SET active = 2
491
+        if (is_array($attendance_id)) {
492
+            foreach ($attendance_id as $id) {
493
+                $id	= intval($id);
494
+                $sql = "UPDATE $tbl_attendance SET active = 2
495 495
 						WHERE c_id = $course_id AND id = '$id'";
496
-				$result = Database::query($sql);
497
-				$affected_rows = Database::affected_rows($result);
498
-				if (!empty($affected_rows)) {
499
-					// update row item property table
496
+                $result = Database::query($sql);
497
+                $affected_rows = Database::affected_rows($result);
498
+                if (!empty($affected_rows)) {
499
+                    // update row item property table
500 500
                     api_item_property_update(
501 501
                         $_course,
502 502
                         TOOL_ATTENDANCE,
@@ -504,142 +504,142 @@  discard block
 block discarded – undo
504 504
                         "delete",
505 505
                         $user_id
506 506
                     );
507
-				}
508
-			}
509
-		} else  {
510
-			$attendance_id= intval($attendance_id);
511
-			$sql = "UPDATE $tbl_attendance SET active = 2
507
+                }
508
+            }
509
+        } else  {
510
+            $attendance_id= intval($attendance_id);
511
+            $sql = "UPDATE $tbl_attendance SET active = 2
512 512
 					WHERE c_id = $course_id AND id = '$attendance_id'";
513 513
 
514
-			$result = Database::query($sql);
515
-			$affected_rows = Database::affected_rows($result);
516
-			if (!empty($affected_rows)) {
517
-				// update row item property table
518
-				api_item_property_update(
519
-					$_course,
520
-					TOOL_ATTENDANCE,
521
-					$attendance_id,
522
-					"delete",
523
-					$user_id
524
-				);
525
-			}
526
-		}
527
-
528
-		return $affected_rows;
529
-	}
530
-
531
-	/**
532
-	 * Changes visibility
533
-	 * @param int|array	$attendanceId   one or many attendances id
534
-	 * @param int status
514
+            $result = Database::query($sql);
515
+            $affected_rows = Database::affected_rows($result);
516
+            if (!empty($affected_rows)) {
517
+                // update row item property table
518
+                api_item_property_update(
519
+                    $_course,
520
+                    TOOL_ATTENDANCE,
521
+                    $attendance_id,
522
+                    "delete",
523
+                    $user_id
524
+                );
525
+            }
526
+        }
527
+
528
+        return $affected_rows;
529
+    }
530
+
531
+    /**
532
+     * Changes visibility
533
+     * @param int|array	$attendanceId   one or many attendances id
534
+     * @param int status
535 535
      *
536
-	 * @return 	int affected rows
537
-	 */
538
-	public function changeVisibility($attendanceId, $status = 1)
539
-	{
540
-		$_course = api_get_course_info();
541
-		$tbl_attendance	= Database :: get_course_table(TABLE_ATTENDANCE);
542
-		$user_id = api_get_user_id();
543
-		$course_id = $_course['real_id'];
544
-		$status = intval($status);
545
-
546
-		$action = 'visible';
547
-		if ($status == 0) {
548
-			$action = 'invisible';
549
-		}
550
-
551
-		if (is_array($attendanceId)) {
552
-			foreach ($attendanceId as $id) {
553
-				$id	= intval($id);
554
-				$sql = "UPDATE $tbl_attendance SET active = $status
536
+     * @return 	int affected rows
537
+     */
538
+    public function changeVisibility($attendanceId, $status = 1)
539
+    {
540
+        $_course = api_get_course_info();
541
+        $tbl_attendance	= Database :: get_course_table(TABLE_ATTENDANCE);
542
+        $user_id = api_get_user_id();
543
+        $course_id = $_course['real_id'];
544
+        $status = intval($status);
545
+
546
+        $action = 'visible';
547
+        if ($status == 0) {
548
+            $action = 'invisible';
549
+        }
550
+
551
+        if (is_array($attendanceId)) {
552
+            foreach ($attendanceId as $id) {
553
+                $id	= intval($id);
554
+                $sql = "UPDATE $tbl_attendance SET active = $status
555 555
 						WHERE c_id = $course_id AND id = '$id'";
556
-				$result = Database::query($sql);
557
-				$affected_rows = Database::affected_rows($result);
558
-				if (!empty($affected_rows)) {
559
-					// update row item property table
560
-					api_item_property_update($_course, TOOL_ATTENDANCE, $id, $action, $user_id);
561
-				}
562
-			}
563
-		} else  {
564
-			$attendanceId	= intval($attendanceId);
565
-			$sql = "UPDATE $tbl_attendance SET active = $status
556
+                $result = Database::query($sql);
557
+                $affected_rows = Database::affected_rows($result);
558
+                if (!empty($affected_rows)) {
559
+                    // update row item property table
560
+                    api_item_property_update($_course, TOOL_ATTENDANCE, $id, $action, $user_id);
561
+                }
562
+            }
563
+        } else  {
564
+            $attendanceId	= intval($attendanceId);
565
+            $sql = "UPDATE $tbl_attendance SET active = $status
566 566
 					WHERE c_id = $course_id AND id = '$attendanceId'";
567
-			$result = Database::query($sql);
568
-			$affected_rows = Database::affected_rows($result);
569
-			if (!empty($affected_rows)) {
570
-				// update row item property table
571
-				api_item_property_update(
572
-					$_course,
573
-					TOOL_ATTENDANCE,
574
-					$attendanceId,
575
-					$action,
576
-					$user_id
577
-				);
578
-			}
579
-		}
580
-
581
-		return $affected_rows;
582
-	}
583
-
584
-	/**
585
-	 * Lock or unlock an attendance
586
-	 * @param   int     attendance id
587
-	 * @param   bool    True to lock or false otherwise
588
-	 */
589
-	public function lock_attendance($attendance_id, $lock = true)
590
-	{
591
-		$tbl_attendance = Database::get_course_table(TABLE_ATTENDANCE);
592
-		$course_id = api_get_course_int_id();
593
-		$attendance_id = intval($attendance_id);
594
-		$locked = ($lock)?1:0;
595
-		$upd = "UPDATE $tbl_attendance SET locked = $locked
567
+            $result = Database::query($sql);
568
+            $affected_rows = Database::affected_rows($result);
569
+            if (!empty($affected_rows)) {
570
+                // update row item property table
571
+                api_item_property_update(
572
+                    $_course,
573
+                    TOOL_ATTENDANCE,
574
+                    $attendanceId,
575
+                    $action,
576
+                    $user_id
577
+                );
578
+            }
579
+        }
580
+
581
+        return $affected_rows;
582
+    }
583
+
584
+    /**
585
+     * Lock or unlock an attendance
586
+     * @param   int     attendance id
587
+     * @param   bool    True to lock or false otherwise
588
+     */
589
+    public function lock_attendance($attendance_id, $lock = true)
590
+    {
591
+        $tbl_attendance = Database::get_course_table(TABLE_ATTENDANCE);
592
+        $course_id = api_get_course_int_id();
593
+        $attendance_id = intval($attendance_id);
594
+        $locked = ($lock)?1:0;
595
+        $upd = "UPDATE $tbl_attendance SET locked = $locked
596 596
 				WHERE c_id = $course_id AND id = $attendance_id";
597
-		$result = Database::query($upd);
598
-		$affected_rows = Database::affected_rows($result);
599
-		if ($affected_rows && $lock) {
600
-			// Save attendance sheet log
601
-			$lastedit_date = api_get_utc_datetime();
602
-			$lastedit_type = self::LOCKED_ATTENDANCE_LOG_TYPE;
603
-			$lastedit_user_id = api_get_user_id();
604
-			$this->save_attendance_sheet_log(
605
-				$attendance_id,
606
-				$lastedit_date,
607
-				$lastedit_type,
608
-				$lastedit_user_id
609
-			);
610
-		}
611
-		return $affected_rows;
612
-	}
613
-
614
-	/**
615
-	 * Get registered users inside current course
616
-	 * @param 	int	   $attendance_id attendance id for showing attendance result field (optional)
617
-	 * @param int $groupId
618
-	 * @return 	array  users data
619
-	 */
620
-	public function get_users_rel_course($attendance_id = 0, $groupId = null)
621
-	{
622
-		$current_session_id = api_get_session_id();
623
-		$current_course_id  = api_get_course_id();
624
-		$currentCourseIntId = api_get_course_int_id();
625
-
626
-		$studentInGroup = array();
627
-
628
-		if (!empty($current_session_id)) {
629
-			$a_course_users = CourseManager:: get_user_list_from_course_code(
630
-				$current_course_id,
631
-				$current_session_id,
632
-				'',
633
-				'lastname'
634
-			);
635
-		} else {
636
-			$a_course_users = CourseManager:: get_user_list_from_course_code(
637
-				$current_course_id,
638
-				0,
639
-				'',
640
-				'lastname'
641
-			);
642
-		}
597
+        $result = Database::query($upd);
598
+        $affected_rows = Database::affected_rows($result);
599
+        if ($affected_rows && $lock) {
600
+            // Save attendance sheet log
601
+            $lastedit_date = api_get_utc_datetime();
602
+            $lastedit_type = self::LOCKED_ATTENDANCE_LOG_TYPE;
603
+            $lastedit_user_id = api_get_user_id();
604
+            $this->save_attendance_sheet_log(
605
+                $attendance_id,
606
+                $lastedit_date,
607
+                $lastedit_type,
608
+                $lastedit_user_id
609
+            );
610
+        }
611
+        return $affected_rows;
612
+    }
613
+
614
+    /**
615
+     * Get registered users inside current course
616
+     * @param 	int	   $attendance_id attendance id for showing attendance result field (optional)
617
+     * @param int $groupId
618
+     * @return 	array  users data
619
+     */
620
+    public function get_users_rel_course($attendance_id = 0, $groupId = null)
621
+    {
622
+        $current_session_id = api_get_session_id();
623
+        $current_course_id  = api_get_course_id();
624
+        $currentCourseIntId = api_get_course_int_id();
625
+
626
+        $studentInGroup = array();
627
+
628
+        if (!empty($current_session_id)) {
629
+            $a_course_users = CourseManager:: get_user_list_from_course_code(
630
+                $current_course_id,
631
+                $current_session_id,
632
+                '',
633
+                'lastname'
634
+            );
635
+        } else {
636
+            $a_course_users = CourseManager:: get_user_list_from_course_code(
637
+                $current_course_id,
638
+                0,
639
+                '',
640
+                'lastname'
641
+            );
642
+        }
643 643
 
644 644
         if (!empty($groupId)) {
645 645
             $students = GroupManager::getStudents($groupId);
@@ -650,192 +650,192 @@  discard block
 block discarded – undo
650 650
             }
651 651
         }
652 652
 
653
-		// get registered users inside current course
654
-		$a_users = array();
655
-		foreach ($a_course_users as $key => $user_data) {
656
-			$value = array();
657
-			$uid = $user_data['user_id'];
658
-			$userInfo = api_get_user_info($uid);
659
-
660
-			$status = $user_data['status'];
661
-
662
-			if (!empty($groupId)) {
663
-				if (!isset($studentInGroup[$uid])) {
664
-					continue;
665
-				}
666
-			}
667
-
668
-			$user_status_in_session = null;
669
-			$user_status_in_course  = null;
670
-
671
-			if (api_get_session_id()) {
672
-				$user_status_in_session = SessionManager::get_user_status_in_course_session(
673
-					$uid,
674
-					$currentCourseIntId,
675
-					$current_session_id
676
-				);
677
-			} else {
678
-				$user_status_in_course = CourseManager::get_user_in_course_status(
679
-					$uid,
680
-					$current_course_id
681
-				);
682
-			}
683
-
684
-			// Not taking into account DRH or COURSEMANAGER
685
-			if ($uid <= 1 ||
686
-				$status == DRH ||
687
-				$user_status_in_course == COURSEMANAGER ||
688
-				$user_status_in_session == 2
689
-			) {
690
-				continue;
691
-			}
692
-
693
-			if (!empty($attendance_id)) {
694
-				$user_faults = $this->get_faults_of_user($uid, $attendance_id, $groupId);
695
-				$value['attendance_result'] = $user_faults['faults'].'/'.$user_faults['total'].' ('.$user_faults['faults_porcent'].'%)';
696
-				$value['result_color_bar'] 	= $user_faults['color_bar'];
697
-			}
653
+        // get registered users inside current course
654
+        $a_users = array();
655
+        foreach ($a_course_users as $key => $user_data) {
656
+            $value = array();
657
+            $uid = $user_data['user_id'];
658
+            $userInfo = api_get_user_info($uid);
659
+
660
+            $status = $user_data['status'];
661
+
662
+            if (!empty($groupId)) {
663
+                if (!isset($studentInGroup[$uid])) {
664
+                    continue;
665
+                }
666
+            }
667
+
668
+            $user_status_in_session = null;
669
+            $user_status_in_course  = null;
670
+
671
+            if (api_get_session_id()) {
672
+                $user_status_in_session = SessionManager::get_user_status_in_course_session(
673
+                    $uid,
674
+                    $currentCourseIntId,
675
+                    $current_session_id
676
+                );
677
+            } else {
678
+                $user_status_in_course = CourseManager::get_user_in_course_status(
679
+                    $uid,
680
+                    $current_course_id
681
+                );
682
+            }
683
+
684
+            // Not taking into account DRH or COURSEMANAGER
685
+            if ($uid <= 1 ||
686
+                $status == DRH ||
687
+                $user_status_in_course == COURSEMANAGER ||
688
+                $user_status_in_session == 2
689
+            ) {
690
+                continue;
691
+            }
692
+
693
+            if (!empty($attendance_id)) {
694
+                $user_faults = $this->get_faults_of_user($uid, $attendance_id, $groupId);
695
+                $value['attendance_result'] = $user_faults['faults'].'/'.$user_faults['total'].' ('.$user_faults['faults_porcent'].'%)';
696
+                $value['result_color_bar'] 	= $user_faults['color_bar'];
697
+            }
698 698
 
699 699
             $photo = Display::img($userInfo['avatar_small'], $userInfo['complete_name'], [], false);
700 700
 
701
-			$value['photo'] = $photo;
702
-			$value['firstname'] = $user_data['firstname'];
703
-			$value['lastname'] = $user_data['lastname'];
704
-			$value['username'] = $user_data['username'];
705
-			$value['user_id'] = $uid;
706
-
707
-			//Sending only 5 items in the array instead of 60
708
-			$a_users[$key] = $value;
709
-		}
710
-
711
-		return $a_users;
712
-	}
713
-
714
-	/**
715
-	 * add attendances sheet inside table
716
-	 * @param 	int	   $calendar_id attendance calendar id
717
-	 * @param  	array  $users_present present users during current class
718
-	 * @param	int	   $attendance_id
719
-	 * @return 	int    affected rows
720
-	 */
721
-	public function attendance_sheet_add($calendar_id, $users_present, $attendance_id)
722
-	{
723
-		$tbl_attendance_sheet 	= Database::get_course_table(TABLE_ATTENDANCE_SHEET);
724
-		$tbl_attendance_calendar= Database::get_course_table(TABLE_ATTENDANCE_CALENDAR);
725
-
726
-		$calendar_id = intval($calendar_id);
727
-		$attendance_id = intval($attendance_id);
728
-		$users = $this->get_users_rel_course();
729
-		$course_id = api_get_course_int_id();
730
-
731
-		$user_ids = array_keys($users);
732
-		$users_absent = array_diff($user_ids,$users_present);
733
-		$affected_rows = 0;
734
-
735
-		// get last edit type
736
-		$calendar_data = $this->get_attendance_calendar_by_id($calendar_id);
737
-		$lastedit_type = self::DONE_ATTENDANCE_LOG_TYPE;
738
-		if ($calendar_data['done_attendance']) {
739
-			$lastedit_type = self::UPDATED_ATTENDANCE_LOG_TYPE;
740
-		}
741
-
742
-		// save users present in class
743
-		foreach ($users_present as $user_present) {
744
-			$uid = intval($user_present);
745
-			// check if user already was registered with the $calendar_id
746
-			$sql = "SELECT user_id FROM $tbl_attendance_sheet
701
+            $value['photo'] = $photo;
702
+            $value['firstname'] = $user_data['firstname'];
703
+            $value['lastname'] = $user_data['lastname'];
704
+            $value['username'] = $user_data['username'];
705
+            $value['user_id'] = $uid;
706
+
707
+            //Sending only 5 items in the array instead of 60
708
+            $a_users[$key] = $value;
709
+        }
710
+
711
+        return $a_users;
712
+    }
713
+
714
+    /**
715
+     * add attendances sheet inside table
716
+     * @param 	int	   $calendar_id attendance calendar id
717
+     * @param  	array  $users_present present users during current class
718
+     * @param	int	   $attendance_id
719
+     * @return 	int    affected rows
720
+     */
721
+    public function attendance_sheet_add($calendar_id, $users_present, $attendance_id)
722
+    {
723
+        $tbl_attendance_sheet 	= Database::get_course_table(TABLE_ATTENDANCE_SHEET);
724
+        $tbl_attendance_calendar= Database::get_course_table(TABLE_ATTENDANCE_CALENDAR);
725
+
726
+        $calendar_id = intval($calendar_id);
727
+        $attendance_id = intval($attendance_id);
728
+        $users = $this->get_users_rel_course();
729
+        $course_id = api_get_course_int_id();
730
+
731
+        $user_ids = array_keys($users);
732
+        $users_absent = array_diff($user_ids,$users_present);
733
+        $affected_rows = 0;
734
+
735
+        // get last edit type
736
+        $calendar_data = $this->get_attendance_calendar_by_id($calendar_id);
737
+        $lastedit_type = self::DONE_ATTENDANCE_LOG_TYPE;
738
+        if ($calendar_data['done_attendance']) {
739
+            $lastedit_type = self::UPDATED_ATTENDANCE_LOG_TYPE;
740
+        }
741
+
742
+        // save users present in class
743
+        foreach ($users_present as $user_present) {
744
+            $uid = intval($user_present);
745
+            // check if user already was registered with the $calendar_id
746
+            $sql = "SELECT user_id FROM $tbl_attendance_sheet
747 747
 					WHERE c_id = $course_id AND user_id='$uid' AND attendance_calendar_id = '$calendar_id'";
748
-			$rs  = Database::query($sql);
749
-			if (Database::num_rows($rs) == 0) {
750
-				$sql = "INSERT INTO $tbl_attendance_sheet SET
748
+            $rs  = Database::query($sql);
749
+            if (Database::num_rows($rs) == 0) {
750
+                $sql = "INSERT INTO $tbl_attendance_sheet SET
751 751
 						c_id					= $course_id,
752 752
 						user_id 				= '$uid',
753 753
 						attendance_calendar_id 	= '$calendar_id',
754 754
 						presence 				= 1";
755
-				$result = Database::query($sql);
755
+                $result = Database::query($sql);
756 756
 
757
-				$affected_rows += Database::affected_rows($result);
758
-			} else {
759
-				$sql = "UPDATE $tbl_attendance_sheet SET presence = 1
757
+                $affected_rows += Database::affected_rows($result);
758
+            } else {
759
+                $sql = "UPDATE $tbl_attendance_sheet SET presence = 1
760 760
 						WHERE
761 761
 							c_id = $course_id AND
762 762
 							user_id ='$uid' AND
763 763
 							attendance_calendar_id = '$calendar_id'
764 764
 						";
765
-				$result = Database::query($sql);
766
-				$affected_rows += Database::affected_rows($result);
767
-			}
768
-		}
769
-
770
-		// save users absent in class
771
-		foreach ($users_absent as $user_absent) {
772
-			$uid = intval($user_absent);
773
-			// check if user already was registered with the $calendar_id
774
-			$sql = "SELECT user_id FROM $tbl_attendance_sheet
765
+                $result = Database::query($sql);
766
+                $affected_rows += Database::affected_rows($result);
767
+            }
768
+        }
769
+
770
+        // save users absent in class
771
+        foreach ($users_absent as $user_absent) {
772
+            $uid = intval($user_absent);
773
+            // check if user already was registered with the $calendar_id
774
+            $sql = "SELECT user_id FROM $tbl_attendance_sheet
775 775
 					WHERE c_id = $course_id AND user_id='$uid' AND attendance_calendar_id = '$calendar_id'";
776
-			$rs  = Database::query($sql);
777
-			if (Database::num_rows($rs) == 0) {
778
-				$sql = "INSERT INTO $tbl_attendance_sheet SET
776
+            $rs  = Database::query($sql);
777
+            if (Database::num_rows($rs) == 0) {
778
+                $sql = "INSERT INTO $tbl_attendance_sheet SET
779 779
 						c_id = $course_id,
780 780
 						user_id ='$uid',
781 781
 						attendance_calendar_id = '$calendar_id',
782 782
 						presence = 0";
783
-				$result = Database::query($sql);
783
+                $result = Database::query($sql);
784 784
 
785
-				Database::insert_id();
785
+                Database::insert_id();
786 786
 
787
-				$affected_rows += Database::affected_rows($result);
788
-			} else {
789
-				$sql = "UPDATE $tbl_attendance_sheet SET presence = 0
787
+                $affected_rows += Database::affected_rows($result);
788
+            } else {
789
+                $sql = "UPDATE $tbl_attendance_sheet SET presence = 0
790 790
 						WHERE
791 791
 							c_id = $course_id AND
792 792
 							user_id ='$uid' AND
793 793
 							attendance_calendar_id = '$calendar_id'";
794
-				$result = Database::query($sql);
795
-				$affected_rows += Database::affected_rows($result);
796
-			}
797
-		}
794
+                $result = Database::query($sql);
795
+                $affected_rows += Database::affected_rows($result);
796
+            }
797
+        }
798 798
 
799
-		// update done_attendance inside attendance calendar table
800
-		$sql = "UPDATE $tbl_attendance_calendar SET done_attendance = 1
799
+        // update done_attendance inside attendance calendar table
800
+        $sql = "UPDATE $tbl_attendance_calendar SET done_attendance = 1
801 801
 				WHERE  c_id = $course_id AND id = '$calendar_id'";
802
-		Database::query($sql);
803
-
804
-		// save users' results
805
-		$this->update_users_results($user_ids, $attendance_id);
806
-
807
-		if ($affected_rows) {
808
-			//save attendance sheet log
809
-			$lastedit_date = api_get_utc_datetime();
810
-			$lastedit_user_id = api_get_user_id();
811
-			$calendar_date_value = $calendar_data['date_time'];
812
-			$this->save_attendance_sheet_log(
813
-				$attendance_id,
814
-				$lastedit_date,
815
-				$lastedit_type,
816
-				$lastedit_user_id,
817
-				$calendar_date_value
818
-			);
819
-		}
820
-
821
-		return $affected_rows;
822
-	}
823
-
824
-	/**
825
-	 * update users' attendance results
826
-	 * @param 	array  $user_ids registered users inside current course
827
-	 * @param	int	   $attendance_id
828
-	 * @return 	void
829
-	 */
830
-	public function update_users_results($user_ids, $attendance_id)
831
-	{
832
-		$tbl_attendance_sheet = Database::get_course_table(TABLE_ATTENDANCE_SHEET);
833
-		$tbl_attendance_result = Database::get_course_table(TABLE_ATTENDANCE_RESULT);
834
-		$tbl_attendance = Database::get_course_table(TABLE_ATTENDANCE);
835
-		$course_id = api_get_course_int_id();
836
-
837
-		$attendance_id = intval($attendance_id);
838
-		// fill results about presence of students
802
+        Database::query($sql);
803
+
804
+        // save users' results
805
+        $this->update_users_results($user_ids, $attendance_id);
806
+
807
+        if ($affected_rows) {
808
+            //save attendance sheet log
809
+            $lastedit_date = api_get_utc_datetime();
810
+            $lastedit_user_id = api_get_user_id();
811
+            $calendar_date_value = $calendar_data['date_time'];
812
+            $this->save_attendance_sheet_log(
813
+                $attendance_id,
814
+                $lastedit_date,
815
+                $lastedit_type,
816
+                $lastedit_user_id,
817
+                $calendar_date_value
818
+            );
819
+        }
820
+
821
+        return $affected_rows;
822
+    }
823
+
824
+    /**
825
+     * update users' attendance results
826
+     * @param 	array  $user_ids registered users inside current course
827
+     * @param	int	   $attendance_id
828
+     * @return 	void
829
+     */
830
+    public function update_users_results($user_ids, $attendance_id)
831
+    {
832
+        $tbl_attendance_sheet = Database::get_course_table(TABLE_ATTENDANCE_SHEET);
833
+        $tbl_attendance_result = Database::get_course_table(TABLE_ATTENDANCE_RESULT);
834
+        $tbl_attendance = Database::get_course_table(TABLE_ATTENDANCE);
835
+        $course_id = api_get_course_int_id();
836
+
837
+        $attendance_id = intval($attendance_id);
838
+        // fill results about presence of students
839 839
         $attendance_calendar = $this->get_attendance_calendar(
840 840
             $attendance_id,
841 841
             'all',
@@ -843,82 +843,82 @@  discard block
 block discarded – undo
843 843
             null,
844 844
             true
845 845
         );
846
-		$calendar_ids = array();
847
-		// get all dates from calendar by current attendance
848
-		foreach ($attendance_calendar as $cal) {
849
-			$calendar_ids[] = $cal['id'];
850
-		}
851
-
852
-		// get count of presences by users inside current attendance and save like results
853
-		if (count($user_ids) > 0) {
854
-			foreach ($user_ids as $uid) {
855
-				$count_presences = 0;
856
-				if (count($calendar_ids) > 0) {
857
-					$sql = "SELECT count(presence) as count_presences
846
+        $calendar_ids = array();
847
+        // get all dates from calendar by current attendance
848
+        foreach ($attendance_calendar as $cal) {
849
+            $calendar_ids[] = $cal['id'];
850
+        }
851
+
852
+        // get count of presences by users inside current attendance and save like results
853
+        if (count($user_ids) > 0) {
854
+            foreach ($user_ids as $uid) {
855
+                $count_presences = 0;
856
+                if (count($calendar_ids) > 0) {
857
+                    $sql = "SELECT count(presence) as count_presences
858 858
 							FROM $tbl_attendance_sheet
859 859
 					        WHERE
860 860
 					        	c_id = $course_id AND
861 861
 					        	user_id = '$uid' AND
862 862
 					        	attendance_calendar_id IN (".implode(',', $calendar_ids).") AND
863 863
 					        	presence = 1";
864
-					$rs_count  = Database::query($sql);
865
-					$row_count = Database::fetch_array($rs_count);
866
-					$count_presences = $row_count['count_presences'];
867
-				}
864
+                    $rs_count  = Database::query($sql);
865
+                    $row_count = Database::fetch_array($rs_count);
866
+                    $count_presences = $row_count['count_presences'];
867
+                }
868 868
 
869
-				// save results
870
-				$sql = "SELECT id FROM $tbl_attendance_result
869
+                // save results
870
+                $sql = "SELECT id FROM $tbl_attendance_result
871 871
 						WHERE
872 872
 							c_id = $course_id AND
873 873
 							user_id = '$uid' AND
874 874
 							attendance_id = '$attendance_id' ";
875
-				$rs_check_result = Database::query($sql);
875
+                $rs_check_result = Database::query($sql);
876 876
 
877
-				if (Database::num_rows($rs_check_result) > 0) {
878
-					// update result
879
-					$sql = "UPDATE $tbl_attendance_result SET
877
+                if (Database::num_rows($rs_check_result) > 0) {
878
+                    // update result
879
+                    $sql = "UPDATE $tbl_attendance_result SET
880 880
 							score = '$count_presences'
881 881
 							WHERE
882 882
 								c_id = $course_id AND
883 883
 								user_id='$uid' AND
884 884
 								attendance_id='$attendance_id'";
885
-					Database::query($sql);
886
-				} else {
887
-					// insert new result
888
-					$sql = "INSERT INTO $tbl_attendance_result SET
885
+                    Database::query($sql);
886
+                } else {
887
+                    // insert new result
888
+                    $sql = "INSERT INTO $tbl_attendance_result SET
889 889
 							c_id = $course_id ,
890 890
 							user_id			= '$uid',
891 891
 							attendance_id 	= '$attendance_id',
892 892
 							score			= '$count_presences'";
893
-					Database::query($sql);
893
+                    Database::query($sql);
894 894
 
895
-					$insertId = Database::insert_id();
895
+                    $insertId = Database::insert_id();
896 896
                     if ($insertId) {
897 897
                         $sql = "UPDATE $tbl_attendance_result SET id = iid WHERE iid = $insertId";
898 898
                         Database::query($sql);
899 899
                     }
900
-				}
901
-			}
902
-		}
900
+                }
901
+            }
902
+        }
903 903
 
904
-		// update attendance qualify max
905
-		$count_done_calendar = self::get_done_attendance_calendar($attendance_id);
904
+        // update attendance qualify max
905
+        $count_done_calendar = self::get_done_attendance_calendar($attendance_id);
906 906
 
907
-		$sql = "UPDATE $tbl_attendance SET
907
+        $sql = "UPDATE $tbl_attendance SET
908 908
 				attendance_qualify_max = '$count_done_calendar'
909 909
 				WHERE c_id = $course_id AND id = '$attendance_id'";
910
-		Database::query($sql);
911
-	}
912
-
913
-	/**
914
-	 * update attendance_sheet_log table, is used as history of an attendance sheet
915
-	 * @param   int     Attendance id
916
-	 * @param   string  Last edit datetime
917
-	 * @param   string  Event type ('locked_attendance', 'done_attendance_sheet' ...)
918
-	 * @param   int     Last edit user id
919
-	 * @param   string  Calendar datetime value (optional, when event type is 'done_attendance_sheet')
920
-	 * @return  int     Affected rows
921
-	 */
910
+        Database::query($sql);
911
+    }
912
+
913
+    /**
914
+     * update attendance_sheet_log table, is used as history of an attendance sheet
915
+     * @param   int     Attendance id
916
+     * @param   string  Last edit datetime
917
+     * @param   string  Event type ('locked_attendance', 'done_attendance_sheet' ...)
918
+     * @param   int     Last edit user id
919
+     * @param   string  Calendar datetime value (optional, when event type is 'done_attendance_sheet')
920
+     * @return  int     Affected rows
921
+     */
922 922
     public function save_attendance_sheet_log(
923 923
         $attendance_id,
924 924
         $lastedit_date,
@@ -926,22 +926,22 @@  discard block
 block discarded – undo
926 926
         $lastedit_user_id,
927 927
         $calendar_date_value = null
928 928
     ) {
929
-		$course_id = api_get_course_int_id();
929
+        $course_id = api_get_course_int_id();
930 930
 
931
-		// define table
932
-		$tbl_attendance_sheet_log = Database::get_course_table(TABLE_ATTENDANCE_SHEET_LOG);
931
+        // define table
932
+        $tbl_attendance_sheet_log = Database::get_course_table(TABLE_ATTENDANCE_SHEET_LOG);
933 933
 
934
-		// protect data
935
-		$attendance_id = intval($attendance_id);
936
-		$lastedit_user_id = intval($lastedit_user_id);
934
+        // protect data
935
+        $attendance_id = intval($attendance_id);
936
+        $lastedit_user_id = intval($lastedit_user_id);
937 937
 
938
-		if (isset($calendar_date_value)) {
939
-			$calendar_date_value = $calendar_date_value;
940
-		} else {
941
-			$calendar_date_value = '';
942
-		}
938
+        if (isset($calendar_date_value)) {
939
+            $calendar_date_value = $calendar_date_value;
940
+        } else {
941
+            $calendar_date_value = '';
942
+        }
943 943
 
944
-		// save data
944
+        // save data
945 945
         $params = [
946 946
             'c_id' => $course_id,
947 947
             'attendance_id' => $attendance_id,
@@ -950,228 +950,228 @@  discard block
 block discarded – undo
950 950
             'lastedit_user_id' => $lastedit_user_id,
951 951
             'calendar_date_value' => $calendar_date_value,
952 952
         ];
953
-		$insertId = Database::insert($tbl_attendance_sheet_log, $params);
953
+        $insertId = Database::insert($tbl_attendance_sheet_log, $params);
954 954
         if ($insertId) {
955 955
             $sql = "UPDATE $tbl_attendance_sheet_log SET id = iid WHERE iid = $insertId";
956 956
             Database::query($sql);
957 957
         }
958 958
 
959
-		return $insertId;
960
-	}
961
-
962
-	/**
963
-	 * Get number of done attendances inside current sheet
964
-	 * @param	int	   attendance id
965
-	 * @return 	int	   number of done attendances
966
-	 */
967
-	public static function get_done_attendance_calendar($attendance_id)
968
-	{
969
-		$tbl_attendance_calendar = Database::get_course_table(TABLE_ATTENDANCE_CALENDAR);
970
-		$attendance_id = intval($attendance_id);
971
-		$course_id = api_get_course_int_id();
972
-		$sql = "SELECT count(done_attendance) as count
959
+        return $insertId;
960
+    }
961
+
962
+    /**
963
+     * Get number of done attendances inside current sheet
964
+     * @param	int	   attendance id
965
+     * @return 	int	   number of done attendances
966
+     */
967
+    public static function get_done_attendance_calendar($attendance_id)
968
+    {
969
+        $tbl_attendance_calendar = Database::get_course_table(TABLE_ATTENDANCE_CALENDAR);
970
+        $attendance_id = intval($attendance_id);
971
+        $course_id = api_get_course_int_id();
972
+        $sql = "SELECT count(done_attendance) as count
973 973
                 FROM $tbl_attendance_calendar
974 974
                 WHERE
975 975
                     c_id = $course_id AND
976 976
                     attendance_id = '$attendance_id' AND
977 977
                     done_attendance = 1
978 978
                 ";
979
-		$rs  = Database::query($sql);
980
-		$row = Database::fetch_array($rs);
981
-		$count = $row['count'];
982
-		return $count;
983
-	}
984
-
985
-	/**
986
-	 * Get results of faults (absents) by user
987
-	 * @param int $user_id
988
-	 * @param int $attendance_id
989
-	 * @param int $groupId
990
-	 * @return 	array  results containing number of faults, total done attendance,
991
-	 * percent of faults and color depend on result (red, orange)
992
-	 */
993
-	public function get_faults_of_user($user_id, $attendance_id, $groupId = null)
994
-	{
995
-		// initializing database table and variables
996
-		$user_id 		= intval($user_id);
997
-		$attendance_id 	= intval($attendance_id);
998
-		$results = array();
999
-		$calendar_count = self::get_number_of_attendance_calendar($attendance_id, $groupId, NULL, $user_id);
1000
-		// $total_done_attendance 	= $attendance_data['attendance_qualify_max'];
979
+        $rs  = Database::query($sql);
980
+        $row = Database::fetch_array($rs);
981
+        $count = $row['count'];
982
+        return $count;
983
+    }
984
+
985
+    /**
986
+     * Get results of faults (absents) by user
987
+     * @param int $user_id
988
+     * @param int $attendance_id
989
+     * @param int $groupId
990
+     * @return 	array  results containing number of faults, total done attendance,
991
+     * percent of faults and color depend on result (red, orange)
992
+     */
993
+    public function get_faults_of_user($user_id, $attendance_id, $groupId = null)
994
+    {
995
+        // initializing database table and variables
996
+        $user_id 		= intval($user_id);
997
+        $attendance_id 	= intval($attendance_id);
998
+        $results = array();
999
+        $calendar_count = self::get_number_of_attendance_calendar($attendance_id, $groupId, NULL, $user_id);
1000
+        // $total_done_attendance 	= $attendance_data['attendance_qualify_max'];
1001 1001
         $total_done_attendance 	= self::get_number_of_attendance_calendar($attendance_id, $groupId, true, $user_id);
1002
-		$attendance_user_score  = $this->get_user_score($user_id, $attendance_id, $groupId);
1002
+        $attendance_user_score  = $this->get_user_score($user_id, $attendance_id, $groupId);
1003 1003
 
1004
-		//This is the main change of the BT#1381
1005
-		//$total_done_attendance = $calendar_count;
1004
+        //This is the main change of the BT#1381
1005
+        //$total_done_attendance = $calendar_count;
1006 1006
 
1007
-		// calculate results
1008
-		$faults = $total_done_attendance - $attendance_user_score;
1007
+        // calculate results
1008
+        $faults = $total_done_attendance - $attendance_user_score;
1009 1009
 
1010 1010
         if (empty($calendar_count)) {
1011 1011
             $faults = 0;
1012 1012
         }
1013 1013
 
1014 1014
         $faults = $faults > 0 ? $faults : 0;
1015
-		$faults_porcent = $calendar_count > 0 ?round(($faults*100)/$calendar_count,0):0;
1015
+        $faults_porcent = $calendar_count > 0 ?round(($faults*100)/$calendar_count,0):0;
1016 1016
         $results['faults'] = $faults;
1017 1017
         $results['total'] = $calendar_count;
1018 1018
         $results['faults_porcent'] = $faults_porcent;
1019
-		$color_bar = '';
1019
+        $color_bar = '';
1020 1020
 
1021 1021
         if ($faults_porcent > 25) {
1022 1022
             $color_bar = '#f28989';
1023
-		} else if ($faults_porcent > 10) {
1024
-			$color_bar = '#F90';
1025
-		}
1026
-		$results['color_bar'] = $color_bar;
1027
-
1028
-		return $results;
1029
-	}
1030
-
1031
-	/**
1032
-	 * Get results of faults average for all courses by user
1033
-	 * @param	int	   $user_id
1034
-	 * @return 	array  results containing number of faults, total done attendance,
1035
-	 * percentage of faults and color depend on result (red, orange)
1036
-	 */
1037
-	public function get_faults_average_inside_courses($user_id)
1038
-	{
1039
-		// get all courses of current user
1040
-		$courses = CourseManager::get_courses_list_by_user_id($user_id, true);
1041
-
1042
-		$user_id = intval($user_id);
1043
-		$results = array();
1044
-		$total_faults = $total_weight = $porcent = 0;
1045
-		foreach ($courses as $course) {
1046
-			//$course_code = $course['code'];
1047
-			//$course_info = api_get_course_info($course_code);
1048
-			$course_id = $course['real_id'];
1049
-			$tbl_attendance_result 	= Database::get_course_table(TABLE_ATTENDANCE_RESULT);
1050
-
1051
-			$attendances_by_course = $this->get_attendances_list($course_id);
1052
-
1053
-			foreach ($attendances_by_course as $attendance) {
1054
-				// get total faults and total weight
1055
-				$total_done_attendance 	= $attendance['attendance_qualify_max'];
1056
-				$sql = "SELECT score
1023
+        } else if ($faults_porcent > 10) {
1024
+            $color_bar = '#F90';
1025
+        }
1026
+        $results['color_bar'] = $color_bar;
1027
+
1028
+        return $results;
1029
+    }
1030
+
1031
+    /**
1032
+     * Get results of faults average for all courses by user
1033
+     * @param	int	   $user_id
1034
+     * @return 	array  results containing number of faults, total done attendance,
1035
+     * percentage of faults and color depend on result (red, orange)
1036
+     */
1037
+    public function get_faults_average_inside_courses($user_id)
1038
+    {
1039
+        // get all courses of current user
1040
+        $courses = CourseManager::get_courses_list_by_user_id($user_id, true);
1041
+
1042
+        $user_id = intval($user_id);
1043
+        $results = array();
1044
+        $total_faults = $total_weight = $porcent = 0;
1045
+        foreach ($courses as $course) {
1046
+            //$course_code = $course['code'];
1047
+            //$course_info = api_get_course_info($course_code);
1048
+            $course_id = $course['real_id'];
1049
+            $tbl_attendance_result 	= Database::get_course_table(TABLE_ATTENDANCE_RESULT);
1050
+
1051
+            $attendances_by_course = $this->get_attendances_list($course_id);
1052
+
1053
+            foreach ($attendances_by_course as $attendance) {
1054
+                // get total faults and total weight
1055
+                $total_done_attendance 	= $attendance['attendance_qualify_max'];
1056
+                $sql = "SELECT score
1057 1057
 						FROM $tbl_attendance_result
1058 1058
                         WHERE
1059 1059
                         	c_id = $course_id AND
1060 1060
                         	user_id = $user_id AND
1061 1061
                         	attendance_id = ".$attendance['id'];
1062
-				$rs = Database::query($sql);
1063
-				$score = 0;
1064
-				if (Database::num_rows($rs) > 0) {
1065
-					$row = Database::fetch_array($rs);
1066
-					$score = $row['score'];
1067
-				}
1068
-				$faults = $total_done_attendance-$score;
1069
-				$faults = $faults > 0 ? $faults:0;
1070
-				$total_faults += $faults;
1071
-				$total_weight += $total_done_attendance;
1072
-			}
1073
-		}
1074
-
1075
-		$porcent = $total_weight > 0 ?round(($total_faults*100)/$total_weight,0):0;
1076
-		$results['faults'] 	= $total_faults;
1077
-		$results['total']	= $total_weight;
1078
-		$results['porcent'] = $porcent;
1079
-
1080
-		return $results;
1081
-	}
1082
-
1083
-	/**
1084
-	 * Get results of faults average by course
1085
-	 * @param	int	   $user_id
1086
-	 * @param 	string	$course_code
1087
-	 * @param	int	   Session id (optional)
1088
-	 * @return 	array  results containing number of faults,
1089
-	 * total done attendance, porcent of faults and color depend on result (red, orange)
1090
-	 */
1091
-	public function get_faults_average_by_course($user_id, $course_code, $session_id = null)
1092
-	{
1093
-		// Database tables and variables
1094
-		$course_info = api_get_course_info($course_code);
1095
-		$tbl_attendance_result 	= Database::get_course_table(TABLE_ATTENDANCE_RESULT);
1096
-		$user_id = intval($user_id);
1097
-		$results = array();
1098
-		$total_faults = $total_weight = $porcent = 0;
1099
-		$attendances_by_course = $this->get_attendances_list($course_info['real_id'], $session_id);
1100
-
1101
-		foreach ($attendances_by_course as $attendance) {
1102
-			// Get total faults and total weight
1103
-			$total_done_attendance 	= $attendance['attendance_qualify_max'];
1104
-			$sql = "SELECT score FROM $tbl_attendance_result
1105
-					WHERE
1062
+                $rs = Database::query($sql);
1063
+                $score = 0;
1064
+                if (Database::num_rows($rs) > 0) {
1065
+                    $row = Database::fetch_array($rs);
1066
+                    $score = $row['score'];
1067
+                }
1068
+                $faults = $total_done_attendance-$score;
1069
+                $faults = $faults > 0 ? $faults:0;
1070
+                $total_faults += $faults;
1071
+                $total_weight += $total_done_attendance;
1072
+            }
1073
+        }
1074
+
1075
+        $porcent = $total_weight > 0 ?round(($total_faults*100)/$total_weight,0):0;
1076
+        $results['faults'] 	= $total_faults;
1077
+        $results['total']	= $total_weight;
1078
+        $results['porcent'] = $porcent;
1079
+
1080
+        return $results;
1081
+    }
1082
+
1083
+    /**
1084
+     * Get results of faults average by course
1085
+     * @param	int	   $user_id
1086
+     * @param 	string	$course_code
1087
+     * @param	int	   Session id (optional)
1088
+     * @return 	array  results containing number of faults,
1089
+     * total done attendance, porcent of faults and color depend on result (red, orange)
1090
+     */
1091
+    public function get_faults_average_by_course($user_id, $course_code, $session_id = null)
1092
+    {
1093
+        // Database tables and variables
1094
+        $course_info = api_get_course_info($course_code);
1095
+        $tbl_attendance_result 	= Database::get_course_table(TABLE_ATTENDANCE_RESULT);
1096
+        $user_id = intval($user_id);
1097
+        $results = array();
1098
+        $total_faults = $total_weight = $porcent = 0;
1099
+        $attendances_by_course = $this->get_attendances_list($course_info['real_id'], $session_id);
1100
+
1101
+        foreach ($attendances_by_course as $attendance) {
1102
+            // Get total faults and total weight
1103
+            $total_done_attendance 	= $attendance['attendance_qualify_max'];
1104
+            $sql = "SELECT score FROM $tbl_attendance_result
1105
+					WHERE
1106 1106
 						c_id = {$course_info['real_id']} AND
1107 1107
 						user_id = $user_id AND
1108 1108
 						attendance_id=".$attendance['id'];
1109
-			$rs = Database::query($sql);
1110
-			$score = 0;
1111
-			if (Database::num_rows($rs) > 0) {
1112
-				$row = Database::fetch_array($rs);
1113
-				$score = $row['score'];
1114
-			}
1115
-			$faults = $total_done_attendance-$score;
1116
-			$faults = $faults > 0 ? $faults:0;
1117
-			$total_faults += $faults;
1118
-			$total_weight += $total_done_attendance;
1119
-		}
1120
-
1121
-		$porcent = $total_weight > 0 ?round(($total_faults*100)/$total_weight,0):0;
1122
-		$results['faults'] 	= $total_faults;
1123
-		$results['total']	= $total_weight;
1124
-		$results['porcent'] = $porcent;
1125
-
1126
-		return $results;
1127
-	}
1128
-
1129
-	/**
1130
-	 * Get registered users' attendance sheet inside current course
1131
-	 * @param	int	   $attendance_id
1132
-	 * @param	int	   $user_id for showing data for only one user (optional)
1133
-	 * @return 	array  users attendance sheet data
1134
-	 */
1135
-	public function get_users_attendance_sheet($attendance_id, $user_id = 0, $groupId = null)
1136
-	{
1137
-		$tbl_attendance_sheet 	= Database::get_course_table(TABLE_ATTENDANCE_SHEET);
1138
-		$tbl_attendance_calendar= Database::get_course_table(TABLE_ATTENDANCE_CALENDAR);
1139
-
1140
-		$attendance_calendar = $this->get_attendance_calendar($attendance_id, 'all', null, $groupId);
1141
-		$calendar_ids = array();
1142
-		// get all dates from calendar by current attendance
1143
-		foreach ($attendance_calendar as $cal) {
1144
-			$calendar_ids[] = $cal['id'];
1145
-		}
1146
-
1147
-		$course_id = api_get_course_int_id();
1148
-
1149
-		$data = array();
1150
-		if (empty($user_id)) {
1151
-			// get all registered users inside current course
1152
-			$users = $this->get_users_rel_course();
1153
-			$user_ids = array_keys($users);
1154
-			if (count($calendar_ids) > 0 && count($user_ids) > 0) {
1155
-				foreach ($user_ids as $uid) {
1156
-					$sql = "SELECT * FROM $tbl_attendance_sheet
1109
+            $rs = Database::query($sql);
1110
+            $score = 0;
1111
+            if (Database::num_rows($rs) > 0) {
1112
+                $row = Database::fetch_array($rs);
1113
+                $score = $row['score'];
1114
+            }
1115
+            $faults = $total_done_attendance-$score;
1116
+            $faults = $faults > 0 ? $faults:0;
1117
+            $total_faults += $faults;
1118
+            $total_weight += $total_done_attendance;
1119
+        }
1120
+
1121
+        $porcent = $total_weight > 0 ?round(($total_faults*100)/$total_weight,0):0;
1122
+        $results['faults'] 	= $total_faults;
1123
+        $results['total']	= $total_weight;
1124
+        $results['porcent'] = $porcent;
1125
+
1126
+        return $results;
1127
+    }
1128
+
1129
+    /**
1130
+     * Get registered users' attendance sheet inside current course
1131
+     * @param	int	   $attendance_id
1132
+     * @param	int	   $user_id for showing data for only one user (optional)
1133
+     * @return 	array  users attendance sheet data
1134
+     */
1135
+    public function get_users_attendance_sheet($attendance_id, $user_id = 0, $groupId = null)
1136
+    {
1137
+        $tbl_attendance_sheet 	= Database::get_course_table(TABLE_ATTENDANCE_SHEET);
1138
+        $tbl_attendance_calendar= Database::get_course_table(TABLE_ATTENDANCE_CALENDAR);
1139
+
1140
+        $attendance_calendar = $this->get_attendance_calendar($attendance_id, 'all', null, $groupId);
1141
+        $calendar_ids = array();
1142
+        // get all dates from calendar by current attendance
1143
+        foreach ($attendance_calendar as $cal) {
1144
+            $calendar_ids[] = $cal['id'];
1145
+        }
1146
+
1147
+        $course_id = api_get_course_int_id();
1148
+
1149
+        $data = array();
1150
+        if (empty($user_id)) {
1151
+            // get all registered users inside current course
1152
+            $users = $this->get_users_rel_course();
1153
+            $user_ids = array_keys($users);
1154
+            if (count($calendar_ids) > 0 && count($user_ids) > 0) {
1155
+                foreach ($user_ids as $uid) {
1156
+                    $sql = "SELECT * FROM $tbl_attendance_sheet
1157 1157
 					        WHERE
1158 1158
 					        	c_id = $course_id AND
1159 1159
 					        	user_id = '$uid' AND
1160 1160
 					        	attendance_calendar_id IN(".implode(',',$calendar_ids).")
1161 1161
 							";
1162
-					$res = Database::query($sql);
1163
-					if (Database::num_rows($res) > 0) {
1164
-						while ($row = Database::fetch_array($res)) {
1165
-							$data[$uid][$row['attendance_calendar_id']]['presence'] = $row['presence'];
1166
-						}
1167
-					}
1168
-				}
1169
-			}
1170
-		} else {
1171
-			// Get attendance for current user
1172
-			$user_id = intval($user_id);
1173
-			if (count($calendar_ids) > 0) {
1174
-				$sql = "SELECT cal.date_time, att.presence
1162
+                    $res = Database::query($sql);
1163
+                    if (Database::num_rows($res) > 0) {
1164
+                        while ($row = Database::fetch_array($res)) {
1165
+                            $data[$uid][$row['attendance_calendar_id']]['presence'] = $row['presence'];
1166
+                        }
1167
+                    }
1168
+                }
1169
+            }
1170
+        } else {
1171
+            // Get attendance for current user
1172
+            $user_id = intval($user_id);
1173
+            if (count($calendar_ids) > 0) {
1174
+                $sql = "SELECT cal.date_time, att.presence
1175 1175
                         FROM $tbl_attendance_sheet att
1176 1176
 						INNER JOIN  $tbl_attendance_calendar cal
1177 1177
 						ON cal.id = att.attendance_calendar_id
@@ -1181,87 +1181,87 @@  discard block
 block discarded – undo
1181 1181
 							att.user_id = '$user_id' AND
1182 1182
 							att.attendance_calendar_id IN (".implode(',',$calendar_ids).")
1183 1183
                         ORDER BY date_time";
1184
-				$res = Database::query($sql);
1185
-				if (Database::num_rows($res) > 0) {
1186
-					while ($row = Database::fetch_array($res)) {
1187
-						$row['date_time'] = api_convert_and_format_date($row['date_time'], null, date_default_timezone_get());
1188
-						$data[$user_id][] = $row;
1189
-					}
1190
-				}
1191
-			}
1192
-		}
1193
-		return $data;
1194
-	}
1195
-
1196
-	/**
1197
-	 * Get next attendance calendar without presences (done attendances)
1198
-	 * @param	int	attendance id
1199
-	 * @return 	int attendance calendar id
1200
-	 */
1201
-	public function get_next_attendance_calendar_id($attendance_id)
1202
-	{
1203
-		$tbl_attendance_calendar = Database::get_course_table(TABLE_ATTENDANCE_CALENDAR);
1204
-		$attendance_id = intval($attendance_id);
1205
-		$course_id = api_get_course_int_id();
1206
-
1207
-		$sql = "SELECT id FROM $tbl_attendance_calendar
1184
+                $res = Database::query($sql);
1185
+                if (Database::num_rows($res) > 0) {
1186
+                    while ($row = Database::fetch_array($res)) {
1187
+                        $row['date_time'] = api_convert_and_format_date($row['date_time'], null, date_default_timezone_get());
1188
+                        $data[$user_id][] = $row;
1189
+                    }
1190
+                }
1191
+            }
1192
+        }
1193
+        return $data;
1194
+    }
1195
+
1196
+    /**
1197
+     * Get next attendance calendar without presences (done attendances)
1198
+     * @param	int	attendance id
1199
+     * @return 	int attendance calendar id
1200
+     */
1201
+    public function get_next_attendance_calendar_id($attendance_id)
1202
+    {
1203
+        $tbl_attendance_calendar = Database::get_course_table(TABLE_ATTENDANCE_CALENDAR);
1204
+        $attendance_id = intval($attendance_id);
1205
+        $course_id = api_get_course_int_id();
1206
+
1207
+        $sql = "SELECT id FROM $tbl_attendance_calendar
1208 1208
 		        WHERE
1209 1209
 		        	c_id = $course_id AND
1210 1210
 		        	attendance_id = '$attendance_id' AND
1211 1211
 		        	done_attendance = 0
1212 1212
 		        ORDER BY date_time
1213 1213
 		        LIMIT 1";
1214
-		$rs = Database::query($sql);
1215
-		$next_calendar_id = 0;
1216
-		if (Database::num_rows($rs) > 0) {
1217
-			$row = Database::fetch_array($rs);
1218
-			$next_calendar_id = $row['id'];
1219
-		}
1220
-		return $next_calendar_id;
1221
-	}
1222
-
1223
-	/**
1224
-	 * Get next attendance calendar datetime without presences (done attendances)
1225
-	 * @param	int	attendance id
1226
-	 * @return 	int UNIX time format datetime
1227
-	 */
1228
-	public function get_next_attendance_calendar_datetime($attendance_id)
1229
-	{
1230
-		$tbl_attendance_calendar = Database::get_course_table(TABLE_ATTENDANCE_CALENDAR);
1231
-		$course_id = api_get_course_int_id();
1232
-		$attendance_id = intval($attendance_id);
1233
-		$sql = "SELECT id, date_time FROM $tbl_attendance_calendar
1214
+        $rs = Database::query($sql);
1215
+        $next_calendar_id = 0;
1216
+        if (Database::num_rows($rs) > 0) {
1217
+            $row = Database::fetch_array($rs);
1218
+            $next_calendar_id = $row['id'];
1219
+        }
1220
+        return $next_calendar_id;
1221
+    }
1222
+
1223
+    /**
1224
+     * Get next attendance calendar datetime without presences (done attendances)
1225
+     * @param	int	attendance id
1226
+     * @return 	int UNIX time format datetime
1227
+     */
1228
+    public function get_next_attendance_calendar_datetime($attendance_id)
1229
+    {
1230
+        $tbl_attendance_calendar = Database::get_course_table(TABLE_ATTENDANCE_CALENDAR);
1231
+        $course_id = api_get_course_int_id();
1232
+        $attendance_id = intval($attendance_id);
1233
+        $sql = "SELECT id, date_time FROM $tbl_attendance_calendar
1234 1234
 				WHERE
1235 1235
 					c_id = $course_id AND
1236 1236
 					attendance_id = '$attendance_id' AND
1237 1237
 					done_attendance = 0
1238 1238
 				ORDER BY date_time
1239 1239
 				LIMIT 1";
1240
-		$rs = Database::query($sql);
1241
-		$next_calendar_datetime = 0;
1242
-		if (Database::num_rows($rs) > 0) {
1243
-			$row = Database::fetch_array($rs);
1244
-			$next_calendar_datetime = api_get_local_time($row['date_time']);
1245
-		}
1246
-
1247
-		return $next_calendar_datetime;
1248
-	}
1249
-
1250
-	/**
1251
-	 * Get user' score from current attendance
1252
-	 * @param	int	$user_id
1253
-	 * @param	int $attendance_id
1254
-	 * @return	int score
1255
-	 */
1256
-	public function get_user_score($user_id, $attendance_id, $groupId = null)
1257
-	{
1258
-		$tbl_attendance_result 	= Database::get_course_table(TABLE_ATTENDANCE_RESULT);
1240
+        $rs = Database::query($sql);
1241
+        $next_calendar_datetime = 0;
1242
+        if (Database::num_rows($rs) > 0) {
1243
+            $row = Database::fetch_array($rs);
1244
+            $next_calendar_datetime = api_get_local_time($row['date_time']);
1245
+        }
1246
+
1247
+        return $next_calendar_datetime;
1248
+    }
1249
+
1250
+    /**
1251
+     * Get user' score from current attendance
1252
+     * @param	int	$user_id
1253
+     * @param	int $attendance_id
1254
+     * @return	int score
1255
+     */
1256
+    public function get_user_score($user_id, $attendance_id, $groupId = null)
1257
+    {
1258
+        $tbl_attendance_result 	= Database::get_course_table(TABLE_ATTENDANCE_RESULT);
1259 1259
         $tbl_attendance_sheet = Database::get_course_table(TABLE_ATTENDANCE_SHEET);
1260 1260
         $tbl_attendance_cal_rel_group = Database::get_course_table(TABLE_ATTENDANCE_CALENDAR_REL_GROUP);
1261 1261
         $tbl_attendance_cal = Database::get_course_table(TABLE_ATTENDANCE_CALENDAR);
1262
-		$user_id = intval($user_id);
1263
-		$attendance_id = intval($attendance_id);
1264
-		$course_id = api_get_course_int_id();
1262
+        $user_id = intval($user_id);
1263
+        $attendance_id = intval($attendance_id);
1264
+        $course_id = api_get_course_int_id();
1265 1265
         if (empty($groupId)) {
1266 1266
             $sql = "SELECT score FROM $tbl_attendance_result
1267 1267
                     WHERE
@@ -1285,68 +1285,68 @@  discard block
 block discarded – undo
1285 1285
                         )
1286 1286
                     ";
1287 1287
         }
1288
-		$rs = Database::query($sql);
1289
-		$score = 0;
1290
-		if (Database::num_rows($rs) > 0) {
1291
-			$row = Database::fetch_array($rs);
1292
-			$score = $row['score'];
1293
-		}
1294
-
1295
-		return $score;
1296
-	}
1297
-
1298
-	/**
1299
-	 * Get attendance calendar data by id
1300
-	 * @param	int	attendance calendar id
1301
-	 * @return	array attendance calendar data
1302
-	 */
1303
-	public function get_attendance_calendar_by_id($calendar_id)
1304
-	{
1305
-		$tbl_attendance_calendar = Database::get_course_table(TABLE_ATTENDANCE_CALENDAR);
1306
-		$calendar_id = intval($calendar_id);
1307
-		$course_id = api_get_course_int_id();
1308
-		$sql = "SELECT * FROM $tbl_attendance_calendar
1288
+        $rs = Database::query($sql);
1289
+        $score = 0;
1290
+        if (Database::num_rows($rs) > 0) {
1291
+            $row = Database::fetch_array($rs);
1292
+            $score = $row['score'];
1293
+        }
1294
+
1295
+        return $score;
1296
+    }
1297
+
1298
+    /**
1299
+     * Get attendance calendar data by id
1300
+     * @param	int	attendance calendar id
1301
+     * @return	array attendance calendar data
1302
+     */
1303
+    public function get_attendance_calendar_by_id($calendar_id)
1304
+    {
1305
+        $tbl_attendance_calendar = Database::get_course_table(TABLE_ATTENDANCE_CALENDAR);
1306
+        $calendar_id = intval($calendar_id);
1307
+        $course_id = api_get_course_int_id();
1308
+        $sql = "SELECT * FROM $tbl_attendance_calendar
1309 1309
 				WHERE c_id = $course_id AND id = '$calendar_id' ";
1310
-		$rs = Database::query($sql);
1311
-		$data = array();
1312
-		if (Database::num_rows($rs) > 0) {
1313
-			while ($row = Database::fetch_array($rs)) {
1314
-				$row['date_time'] = api_get_local_time($row['date_time']);
1315
-				$data = $row;
1316
-			}
1317
-		}
1318
-
1319
-		return $data;
1320
-	}
1321
-
1322
-	/**
1323
-	 * Get all attendance calendar data inside current attendance
1324
-	 * @param int	$attendance_id
1325
-	 * @param string $type
1326
-	 * @param int $calendar_id
1327
-	 * @param int $groupId
1328
-	 * @param bool $showAll = false show group calendar items or not
1329
-	 *
1330
-	 * @return	array attendance calendar data
1331
-	 */
1332
-	public function get_attendance_calendar(
1333
-		$attendance_id,
1334
-		$type = 'all',
1335
-		$calendar_id = null,
1336
-		$groupId = null,
1337
-		$showAll = false
1338
-	) {
1339
-		$tbl_attendance_calendar = Database::get_course_table(TABLE_ATTENDANCE_CALENDAR);
1310
+        $rs = Database::query($sql);
1311
+        $data = array();
1312
+        if (Database::num_rows($rs) > 0) {
1313
+            while ($row = Database::fetch_array($rs)) {
1314
+                $row['date_time'] = api_get_local_time($row['date_time']);
1315
+                $data = $row;
1316
+            }
1317
+        }
1318
+
1319
+        return $data;
1320
+    }
1321
+
1322
+    /**
1323
+     * Get all attendance calendar data inside current attendance
1324
+     * @param int	$attendance_id
1325
+     * @param string $type
1326
+     * @param int $calendar_id
1327
+     * @param int $groupId
1328
+     * @param bool $showAll = false show group calendar items or not
1329
+     *
1330
+     * @return	array attendance calendar data
1331
+     */
1332
+    public function get_attendance_calendar(
1333
+        $attendance_id,
1334
+        $type = 'all',
1335
+        $calendar_id = null,
1336
+        $groupId = null,
1337
+        $showAll = false
1338
+    ) {
1339
+        $tbl_attendance_calendar = Database::get_course_table(TABLE_ATTENDANCE_CALENDAR);
1340 1340
         $tbl_acrg = Database::get_course_table(TABLE_ATTENDANCE_CALENDAR_REL_GROUP);
1341
-		$attendance_id = intval($attendance_id);
1342
-		$course_id = api_get_course_int_id();
1343
-		$groupCondition = null;
1341
+        $attendance_id = intval($attendance_id);
1342
+        $course_id = api_get_course_int_id();
1343
+        $groupCondition = null;
1344 1344
 
1345
-		if ($showAll) {
1346
-			$sql = "SELECT * FROM $tbl_attendance_calendar c
1345
+        if ($showAll) {
1346
+            $sql = "SELECT * FROM $tbl_attendance_calendar c
1347 1347
 					WHERE c_id = $course_id AND attendance_id = '$attendance_id'";
1348
-		} else {
1349
-			$sql = "SELECT * FROM $tbl_attendance_calendar c
1348
+        } else {
1349
+            $sql = "SELECT * FROM $tbl_attendance_calendar c
1350 1350
 					WHERE
1351 1351
 						c_id = $course_id AND
1352 1352
 						attendance_id = '$attendance_id' AND
@@ -1355,11 +1355,11 @@  discard block
 block discarded – undo
1355 1355
 							WHERE c_id = $course_id AND group_id != 0 AND group_id IS NOT NULL
1356 1356
 						)
1357 1357
 					";
1358
-		}
1358
+        }
1359 1359
 
1360
-		if (!empty($groupId)) {
1361
-			$groupId = intval($groupId);
1362
-			$sql = "SELECT c.* FROM $tbl_attendance_calendar c
1360
+        if (!empty($groupId)) {
1361
+            $groupId = intval($groupId);
1362
+            $sql = "SELECT c.* FROM $tbl_attendance_calendar c
1363 1363
 					INNER JOIN $tbl_acrg g
1364 1364
 					ON c.c_id = g.c_id AND c.id = g.calendar_id
1365 1365
 					WHERE
@@ -1367,62 +1367,62 @@  discard block
 block discarded – undo
1367 1367
 					    g.group_id = '$groupId' AND
1368 1368
 					    c.attendance_id = '$attendance_id'
1369 1369
                    ";
1370
-		}
1371
-
1372
-		if (!in_array($type, array('today', 'all', 'all_done', 'all_not_done','calendar_id'))) {
1373
-			$type = 'all';
1374
-		}
1375
-
1376
-		switch ($type) {
1377
-			case 'calendar_id':
1378
-				$calendar_id = intval($calendar_id);
1379
-				if (!empty($calendar_id)) {
1380
-					$sql.= " AND c.id = $calendar_id";
1381
-				}
1382
-				break;
1383
-			case 'today':
1384
-				//$sql .= ' AND DATE_FORMAT(date_time,"%d-%m-%Y") = DATE_FORMAT("'.api_get_utc_datetime().'", "%d-%m-%Y" )';
1385
-				break;
1386
-			case 'all_done':
1387
-				$sql .= " AND done_attendance = 1 ";
1388
-				break;
1389
-			case 'all_not_done':
1390
-				$sql .= " AND done_attendance = 0 ";
1391
-				break;
1392
-			case 'all':
1393
-			default:
1394
-				break;
1395
-		}
1396
-		$sql .= " ORDER BY date_time ";
1370
+        }
1397 1371
 
1398
-		$rs = Database::query($sql);
1399
-		$data = array();
1400
-		if (Database::num_rows($rs) > 0) {
1401
-			while ($row = Database::fetch_array($rs,'ASSOC')) {
1402
-				$row['db_date_time'] = $row['date_time'];
1403
-				$row['date_time'] = api_get_local_time($row['date_time']);
1404
-				$row['date'] = api_format_date($row['date_time'], DATE_FORMAT_SHORT);
1405
-				$row['time'] = api_format_date($row['date_time'], TIME_NO_SEC_FORMAT);
1406
-				$row['groups'] = $this->getGroupListByAttendanceCalendar($row['id'], $course_id);
1407
-				if ($type == 'today') {
1408
-					if (date('d-m-Y', api_strtotime($row['date_time'], 'UTC')) == date('d-m-Y', time())) {
1409
-						$data[] = $row;
1410
-					}
1411
-				} else {
1412
-					$data[] = $row;
1413
-				}
1414
-			}
1415
-		}
1416
-
1417
-		return $data;
1418
-	}
1419
-
1420
-	/**
1421
-	 * Get number of attendance calendar inside current attendance
1422
-	 * @param	int	$attendance_id
1423
-	 * @param	int	$groupId
1424
-	 * @return	int number of dates in attendance calendar
1425
-	 */
1372
+        if (!in_array($type, array('today', 'all', 'all_done', 'all_not_done','calendar_id'))) {
1373
+            $type = 'all';
1374
+        }
1375
+
1376
+        switch ($type) {
1377
+            case 'calendar_id':
1378
+                $calendar_id = intval($calendar_id);
1379
+                if (!empty($calendar_id)) {
1380
+                    $sql.= " AND c.id = $calendar_id";
1381
+                }
1382
+                break;
1383
+            case 'today':
1384
+                //$sql .= ' AND DATE_FORMAT(date_time,"%d-%m-%Y") = DATE_FORMAT("'.api_get_utc_datetime().'", "%d-%m-%Y" )';
1385
+                break;
1386
+            case 'all_done':
1387
+                $sql .= " AND done_attendance = 1 ";
1388
+                break;
1389
+            case 'all_not_done':
1390
+                $sql .= " AND done_attendance = 0 ";
1391
+                break;
1392
+            case 'all':
1393
+            default:
1394
+                break;
1395
+        }
1396
+        $sql .= " ORDER BY date_time ";
1397
+
1398
+        $rs = Database::query($sql);
1399
+        $data = array();
1400
+        if (Database::num_rows($rs) > 0) {
1401
+            while ($row = Database::fetch_array($rs,'ASSOC')) {
1402
+                $row['db_date_time'] = $row['date_time'];
1403
+                $row['date_time'] = api_get_local_time($row['date_time']);
1404
+                $row['date'] = api_format_date($row['date_time'], DATE_FORMAT_SHORT);
1405
+                $row['time'] = api_format_date($row['date_time'], TIME_NO_SEC_FORMAT);
1406
+                $row['groups'] = $this->getGroupListByAttendanceCalendar($row['id'], $course_id);
1407
+                if ($type == 'today') {
1408
+                    if (date('d-m-Y', api_strtotime($row['date_time'], 'UTC')) == date('d-m-Y', time())) {
1409
+                        $data[] = $row;
1410
+                    }
1411
+                } else {
1412
+                    $data[] = $row;
1413
+                }
1414
+            }
1415
+        }
1416
+
1417
+        return $data;
1418
+    }
1419
+
1420
+    /**
1421
+     * Get number of attendance calendar inside current attendance
1422
+     * @param	int	$attendance_id
1423
+     * @param	int	$groupId
1424
+     * @return	int number of dates in attendance calendar
1425
+     */
1426 1426
     public static function get_number_of_attendance_calendar($attendance_id, $groupId = 0, $done_attendance = NULL, $userId = 0)
1427 1427
     {
1428 1428
         $tbl_attendance_calendar = Database::get_course_table(TABLE_ATTENDANCE_CALENDAR);
@@ -1508,112 +1508,112 @@  discard block
 block discarded – undo
1508 1508
 
1509 1509
 
1510 1510
     /**
1511
-	 * Get count dates inside attendance calendar by attendance id
1512
-	 * @param	int	$attendance_id
1513
-	 * @return	int     count of dates
1514
-	 */
1515
-	public static function get_count_dates_inside_attendance_calendar($attendance_id)
1516
-	{
1517
-		$tbl_attendance_calendar = Database::get_course_table(TABLE_ATTENDANCE_CALENDAR);
1518
-		$attendance_id = intval($attendance_id);
1519
-		$course_id = api_get_course_int_id();
1520
-		$sql = "SELECT count(id) FROM $tbl_attendance_calendar
1511
+     * Get count dates inside attendance calendar by attendance id
1512
+     * @param	int	$attendance_id
1513
+     * @return	int     count of dates
1514
+     */
1515
+    public static function get_count_dates_inside_attendance_calendar($attendance_id)
1516
+    {
1517
+        $tbl_attendance_calendar = Database::get_course_table(TABLE_ATTENDANCE_CALENDAR);
1518
+        $attendance_id = intval($attendance_id);
1519
+        $course_id = api_get_course_int_id();
1520
+        $sql = "SELECT count(id) FROM $tbl_attendance_calendar
1521 1521
                 WHERE
1522 1522
                 	c_id = $course_id AND
1523 1523
                 	attendance_id = '$attendance_id'";
1524
-		$rs = Database::query($sql);
1525
-		$count = 0;
1526
-		if (Database::num_rows($rs) > 0) {
1527
-			$row = Database::fetch_row($rs);
1528
-			$count = $row[0];
1529
-		}
1530
-		return $count;
1531
-	}
1532
-
1533
-	/**
1534
-	 * check if all calendar of an attendance is done
1535
-	 * @param   int     $attendance_id
1536
-	 * @return  bool    True if all calendar is done, otherwise false
1537
-	 */
1538
-	public static function is_all_attendance_calendar_done($attendance_id)
1539
-	{
1540
-		$attendance_id = intval($attendance_id);
1541
-		$done_calendar = self::get_done_attendance_calendar($attendance_id);
1542
-		$count_dates_in_calendar = self::get_count_dates_inside_attendance_calendar($attendance_id);
1543
-		$number_of_dates = self::get_number_of_attendance_calendar($attendance_id);
1544
-
1545
-		$result = false;
1546
-		if ($number_of_dates && (intval($count_dates_in_calendar) == intval($done_calendar))) {
1547
-			$result = true;
1548
-		}
1549
-		return $result;
1550
-	}
1551
-
1552
-	/**
1553
-	 * check if an attendance is locked
1554
-	 * @param   int $attendance_id
1555
-	 * @param   bool
1556
-	 */
1557
-	public static function is_locked_attendance($attendance_id)
1558
-	{
1559
-		//use gradebook lock
1560
-		$result = api_resource_is_locked_by_gradebook($attendance_id, LINK_ATTENDANCE);
1561
-		return $result;
1562
-	}
1563
-
1564
-	/**
1565
-	 * Add new datetime inside attendance calendar table
1566
-	 * @param	int		$attendance_id
1567
-	 * @param 	array 	$groupList
1568
-	 * @return	int affected rows
1569
-	 */
1570
-	public function attendance_calendar_add($attendance_id, $groupList = array())
1571
-	{
1572
-		$tbl_attendance_calendar = Database::get_course_table(TABLE_ATTENDANCE_CALENDAR);
1573
-		$affected_rows = 0;
1574
-		$attendance_id = intval($attendance_id);
1575
-		$course_id = api_get_course_int_id();
1576
-		// check if datetime already exists inside the table
1577
-		/*$sql = "SELECT id FROM $tbl_attendance_calendar
1524
+        $rs = Database::query($sql);
1525
+        $count = 0;
1526
+        if (Database::num_rows($rs) > 0) {
1527
+            $row = Database::fetch_row($rs);
1528
+            $count = $row[0];
1529
+        }
1530
+        return $count;
1531
+    }
1532
+
1533
+    /**
1534
+     * check if all calendar of an attendance is done
1535
+     * @param   int     $attendance_id
1536
+     * @return  bool    True if all calendar is done, otherwise false
1537
+     */
1538
+    public static function is_all_attendance_calendar_done($attendance_id)
1539
+    {
1540
+        $attendance_id = intval($attendance_id);
1541
+        $done_calendar = self::get_done_attendance_calendar($attendance_id);
1542
+        $count_dates_in_calendar = self::get_count_dates_inside_attendance_calendar($attendance_id);
1543
+        $number_of_dates = self::get_number_of_attendance_calendar($attendance_id);
1544
+
1545
+        $result = false;
1546
+        if ($number_of_dates && (intval($count_dates_in_calendar) == intval($done_calendar))) {
1547
+            $result = true;
1548
+        }
1549
+        return $result;
1550
+    }
1551
+
1552
+    /**
1553
+     * check if an attendance is locked
1554
+     * @param   int $attendance_id
1555
+     * @param   bool
1556
+     */
1557
+    public static function is_locked_attendance($attendance_id)
1558
+    {
1559
+        //use gradebook lock
1560
+        $result = api_resource_is_locked_by_gradebook($attendance_id, LINK_ATTENDANCE);
1561
+        return $result;
1562
+    }
1563
+
1564
+    /**
1565
+     * Add new datetime inside attendance calendar table
1566
+     * @param	int		$attendance_id
1567
+     * @param 	array 	$groupList
1568
+     * @return	int affected rows
1569
+     */
1570
+    public function attendance_calendar_add($attendance_id, $groupList = array())
1571
+    {
1572
+        $tbl_attendance_calendar = Database::get_course_table(TABLE_ATTENDANCE_CALENDAR);
1573
+        $affected_rows = 0;
1574
+        $attendance_id = intval($attendance_id);
1575
+        $course_id = api_get_course_int_id();
1576
+        // check if datetime already exists inside the table
1577
+        /*$sql = "SELECT id FROM $tbl_attendance_calendar
1578 1578
 		        WHERE
1579 1579
 		        	c_id = $course_id AND
1580 1580
 		        	date_time='".Database::escape_string($this->date_time)."' AND
1581 1581
 		        	attendance_id = '$attendance_id'";
1582 1582
 		$rs = Database::query($sql);
1583 1583
 		if (Database::num_rows($rs) == 0) {*/
1584
-			$params = array(
1585
-				'c_id' =>  $course_id,
1586
-				'date_time' => $this->date_time,
1587
-				'attendance_id' => $attendance_id,
1584
+            $params = array(
1585
+                'c_id' =>  $course_id,
1586
+                'date_time' => $this->date_time,
1587
+                'attendance_id' => $attendance_id,
1588 1588
                 'done_attendance' => 0
1589
-			);
1590
-			$id = Database::insert($tbl_attendance_calendar, $params);
1591
-
1592
-			if ($id) {
1593
-				$sql = "UPDATE $tbl_attendance_calendar SET id = iid WHERE iid = $id";
1594
-				Database::query($sql);
1595
-				$affected_rows++;
1596
-			}
1597
-			$this->addAttendanceCalendarToGroup($id, $course_id, $groupList);
1598
-		//}
1599
-
1600
-		// update locked attendance
1601
-		$is_all_calendar_done = self::is_all_attendance_calendar_done($attendance_id);
1602
-		if (!$is_all_calendar_done) {
1603
-			self::lock_attendance($attendance_id, false);
1604
-		} else {
1605
-			self::lock_attendance($attendance_id);
1606
-		}
1607
-		return $affected_rows;
1608
-	}
1609
-
1610
-	/**
1611
-	 * @param int   $calendarId
1612
-	 * @param int 	$courseId
1613
-	 * @param array $groupList
1614
-	 */
1615
-	public function addAttendanceCalendarToGroup($calendarId, $courseId, $groupList)
1616
-	{
1589
+            );
1590
+            $id = Database::insert($tbl_attendance_calendar, $params);
1591
+
1592
+            if ($id) {
1593
+                $sql = "UPDATE $tbl_attendance_calendar SET id = iid WHERE iid = $id";
1594
+                Database::query($sql);
1595
+                $affected_rows++;
1596
+            }
1597
+            $this->addAttendanceCalendarToGroup($id, $course_id, $groupList);
1598
+        //}
1599
+
1600
+        // update locked attendance
1601
+        $is_all_calendar_done = self::is_all_attendance_calendar_done($attendance_id);
1602
+        if (!$is_all_calendar_done) {
1603
+            self::lock_attendance($attendance_id, false);
1604
+        } else {
1605
+            self::lock_attendance($attendance_id);
1606
+        }
1607
+        return $affected_rows;
1608
+    }
1609
+
1610
+    /**
1611
+     * @param int   $calendarId
1612
+     * @param int 	$courseId
1613
+     * @param array $groupList
1614
+     */
1615
+    public function addAttendanceCalendarToGroup($calendarId, $courseId, $groupList)
1616
+    {
1617 1617
         if (empty($groupList)) {
1618 1618
             return false;
1619 1619
         }
@@ -1641,506 +1641,506 @@  discard block
 block discarded – undo
1641 1641
                 Database::insert($table, $params);
1642 1642
             }
1643 1643
         }
1644
-	}
1645
-
1646
-	/**
1647
-	 * @param int $calendarId
1648
-	 * @param int $courseId
1649
-	 * @param int $groupId
1650
-	 * @return array
1651
-	 */
1652
-	public function getGroupListByAttendanceCalendar($calendarId, $courseId)
1653
-	{
1654
-		$table = Database::get_course_table(TABLE_ATTENDANCE_CALENDAR_REL_GROUP);
1655
-		return Database::select(
1656
-			'*',
1657
-			$table,
1658
-			array('where'=>
1659
-				array(
1660
-					'calendar_id = ? AND c_id = ?' => array($calendarId, $courseId)
1661
-				)
1662
-			)
1663
-		);
1664
-	}
1665
-
1666
-	/**
1667
-	 * @param int $calendarId
1668
-	 * @param int $courseId
1669
-	 * @param int $groupId
1670
-	 * @return array
1671
-	 */
1672
-	public function getAttendanceCalendarGroup($calendarId, $courseId, $groupId)
1673
-	{
1674
-		$table = Database::get_course_table(TABLE_ATTENDANCE_CALENDAR_REL_GROUP);
1675
-		return Database::select(
1676
-			'*',
1677
-			$table,
1678
-			array('where'=>
1679
-				array(
1680
-					'calendar_id = ? AND c_id = ? AND group_id = ?' => array($calendarId, $courseId, $groupId)
1681
-				)
1682
-			)
1683
-		);
1684
-	}
1685
-
1686
-	/**
1687
-	 * @param int $calendarId
1688
-	 * @param int $courseId
1689
-	 * @param int $groupId
1644
+    }
1645
+
1646
+    /**
1647
+     * @param int $calendarId
1648
+     * @param int $courseId
1649
+     * @param int $groupId
1650
+     * @return array
1651
+     */
1652
+    public function getGroupListByAttendanceCalendar($calendarId, $courseId)
1653
+    {
1654
+        $table = Database::get_course_table(TABLE_ATTENDANCE_CALENDAR_REL_GROUP);
1655
+        return Database::select(
1656
+            '*',
1657
+            $table,
1658
+            array('where'=>
1659
+                array(
1660
+                    'calendar_id = ? AND c_id = ?' => array($calendarId, $courseId)
1661
+                )
1662
+            )
1663
+        );
1664
+    }
1665
+
1666
+    /**
1667
+     * @param int $calendarId
1668
+     * @param int $courseId
1669
+     * @param int $groupId
1670
+     * @return array
1671
+     */
1672
+    public function getAttendanceCalendarGroup($calendarId, $courseId, $groupId)
1673
+    {
1674
+        $table = Database::get_course_table(TABLE_ATTENDANCE_CALENDAR_REL_GROUP);
1675
+        return Database::select(
1676
+            '*',
1677
+            $table,
1678
+            array('where'=>
1679
+                array(
1680
+                    'calendar_id = ? AND c_id = ? AND group_id = ?' => array($calendarId, $courseId, $groupId)
1681
+                )
1682
+            )
1683
+        );
1684
+    }
1685
+
1686
+    /**
1687
+     * @param int $calendarId
1688
+     * @param int $courseId
1689
+     * @param int $groupId
1690 1690
      *
1691
-	 * @return array
1692
-	 */
1693
-	public function deleteAttendanceCalendarGroup($calendarId, $courseId)
1694
-	{
1695
-		$table = Database::get_course_table(TABLE_ATTENDANCE_CALENDAR_REL_GROUP);
1696
-		Database::delete(
1697
-			$table,
1698
-			array(
1699
-				'calendar_id = ? AND c_id = ?' => array($calendarId, $courseId)
1700
-			)
1701
-		);
1702
-	}
1703
-
1704
-	/**
1705
-	 * save repeated date inside attendance calendar table
1706
-	 * @param int $attendance_id
1707
-	 * @param int $start_date start date in tms
1708
-	 * @param int $end_date end date in tms
1709
-	 * @param string $repeat_type daily, weekly, monthlyByDate
1710
-	 * @param array $groupList
1711
-	 */
1712
-	public function attendance_repeat_calendar_add(
1713
-		$attendance_id,
1714
-		$start_date,
1715
-		$end_date,
1716
-		$repeat_type,
1717
-		$groupList = array()
1718
-	) {
1719
-		$attendance_id = intval($attendance_id);
1720
-		// save start date
1721
-		$datetimezone = api_get_utc_datetime($start_date);
1722
-		$this->set_date_time($datetimezone);
1723
-		$this->attendance_calendar_add($attendance_id, $groupList);
1724
-
1725
-		// 86400 = 24 hours in seconds
1726
-		// 604800 = 1 week in seconds
1727
-		// Saves repeated dates
1728
-		switch ($repeat_type) {
1729
-			case 'daily':
1730
-				$j = 1;
1731
-				for ($i = $start_date + 86400; ($i <= $end_date); $i += 86400) {
1732
-					$datetimezone = api_get_utc_datetime($i);
1733
-					$this->set_date_time($datetimezone);
1734
-					$this->attendance_calendar_add($attendance_id, $groupList);
1735
-					$j++;
1736
-				}
1737
-				break;
1738
-			case 'weekly':
1739
-				$j = 1;
1740
-				for ($i = $start_date + 604800; ($i <= $end_date); $i += 604800) {
1741
-					$datetimezone = api_get_utc_datetime($i);
1742
-					$this->set_date_time($datetimezone);
1743
-					$this->attendance_calendar_add($attendance_id, $groupList);
1744
-					$j++;
1745
-				}
1746
-				break;
1747
-			case 'monthlyByDate':
1748
-				$j = 1;
1749
-				//@todo fix bug with february
1750
-				for ($i = $start_date + 2419200; ($i <= $end_date); $i += 2419200) {
1751
-					$datetimezone = api_get_utc_datetime($i);
1752
-					$this->set_date_time($datetimezone);
1753
-					$this->attendance_calendar_add($attendance_id, $groupList);
1754
-					$j++;
1755
-				}
1756
-				break;
1757
-		}
1758
-	}
1759
-
1760
-	/**
1761
-	 * Adds x months to a UNIX timestamp
1762
-	 * @param   int     The timestamp
1763
-	 * @param   int     The number of years to add
1764
-	 * @return  int     The new timestamp
1765
-	 */
1766
-	private function add_month($timestamp, $num=1)
1767
-	{
1768
-		$values = api_get_utc_datetime($timestamp);
1769
-		$values = str_replace(array(':','-',' '), '/', $values);
1770
-		list($y, $m, $d, $h, $n, $s) = split('/',$values);
1771
-		if($m+$num>12) {
1772
-			$y += floor($num/12);
1773
-			$m += $num%12;
1774
-		} else {
1775
-			$m += $num;
1776
-		}
1777
-		//date_default_timezone_set('UTC');
1778
-		// return mktime($h, $n, $s, $m, $d, $y);
1779
-		$result = api_strtotime($y.'-'.$m.'-'.$d.' '.$h.':'.$n.':'.$s, 'UTC');
1780
-		if (!empty($result)) {
1781
-			return $result;
1782
-		}
1783
-		return false;
1784
-	}
1785
-
1786
-	/**
1787
-	 * edit a datetime inside attendance calendar table
1788
-	 * @param	int	attendance calendar id
1789
-	 * @param	int	attendance id
1790
-	 * @return	int affected rows
1791
-	 */
1792
-	public function attendance_calendar_edit($calendar_id, $attendance_id)
1793
-	{
1794
-		$tbl_attendance_calendar = Database::get_course_table(TABLE_ATTENDANCE_CALENDAR);
1795
-		$affected_rows = 0;
1796
-		$attendance_id = intval($attendance_id);
1797
-		$course_id = api_get_course_int_id();
1798
-		// check if datetime already exists inside the table
1799
-		$sql = "SELECT id FROM $tbl_attendance_calendar
1691
+     * @return array
1692
+     */
1693
+    public function deleteAttendanceCalendarGroup($calendarId, $courseId)
1694
+    {
1695
+        $table = Database::get_course_table(TABLE_ATTENDANCE_CALENDAR_REL_GROUP);
1696
+        Database::delete(
1697
+            $table,
1698
+            array(
1699
+                'calendar_id = ? AND c_id = ?' => array($calendarId, $courseId)
1700
+            )
1701
+        );
1702
+    }
1703
+
1704
+    /**
1705
+     * save repeated date inside attendance calendar table
1706
+     * @param int $attendance_id
1707
+     * @param int $start_date start date in tms
1708
+     * @param int $end_date end date in tms
1709
+     * @param string $repeat_type daily, weekly, monthlyByDate
1710
+     * @param array $groupList
1711
+     */
1712
+    public function attendance_repeat_calendar_add(
1713
+        $attendance_id,
1714
+        $start_date,
1715
+        $end_date,
1716
+        $repeat_type,
1717
+        $groupList = array()
1718
+    ) {
1719
+        $attendance_id = intval($attendance_id);
1720
+        // save start date
1721
+        $datetimezone = api_get_utc_datetime($start_date);
1722
+        $this->set_date_time($datetimezone);
1723
+        $this->attendance_calendar_add($attendance_id, $groupList);
1724
+
1725
+        // 86400 = 24 hours in seconds
1726
+        // 604800 = 1 week in seconds
1727
+        // Saves repeated dates
1728
+        switch ($repeat_type) {
1729
+            case 'daily':
1730
+                $j = 1;
1731
+                for ($i = $start_date + 86400; ($i <= $end_date); $i += 86400) {
1732
+                    $datetimezone = api_get_utc_datetime($i);
1733
+                    $this->set_date_time($datetimezone);
1734
+                    $this->attendance_calendar_add($attendance_id, $groupList);
1735
+                    $j++;
1736
+                }
1737
+                break;
1738
+            case 'weekly':
1739
+                $j = 1;
1740
+                for ($i = $start_date + 604800; ($i <= $end_date); $i += 604800) {
1741
+                    $datetimezone = api_get_utc_datetime($i);
1742
+                    $this->set_date_time($datetimezone);
1743
+                    $this->attendance_calendar_add($attendance_id, $groupList);
1744
+                    $j++;
1745
+                }
1746
+                break;
1747
+            case 'monthlyByDate':
1748
+                $j = 1;
1749
+                //@todo fix bug with february
1750
+                for ($i = $start_date + 2419200; ($i <= $end_date); $i += 2419200) {
1751
+                    $datetimezone = api_get_utc_datetime($i);
1752
+                    $this->set_date_time($datetimezone);
1753
+                    $this->attendance_calendar_add($attendance_id, $groupList);
1754
+                    $j++;
1755
+                }
1756
+                break;
1757
+        }
1758
+    }
1759
+
1760
+    /**
1761
+     * Adds x months to a UNIX timestamp
1762
+     * @param   int     The timestamp
1763
+     * @param   int     The number of years to add
1764
+     * @return  int     The new timestamp
1765
+     */
1766
+    private function add_month($timestamp, $num=1)
1767
+    {
1768
+        $values = api_get_utc_datetime($timestamp);
1769
+        $values = str_replace(array(':','-',' '), '/', $values);
1770
+        list($y, $m, $d, $h, $n, $s) = split('/',$values);
1771
+        if($m+$num>12) {
1772
+            $y += floor($num/12);
1773
+            $m += $num%12;
1774
+        } else {
1775
+            $m += $num;
1776
+        }
1777
+        //date_default_timezone_set('UTC');
1778
+        // return mktime($h, $n, $s, $m, $d, $y);
1779
+        $result = api_strtotime($y.'-'.$m.'-'.$d.' '.$h.':'.$n.':'.$s, 'UTC');
1780
+        if (!empty($result)) {
1781
+            return $result;
1782
+        }
1783
+        return false;
1784
+    }
1785
+
1786
+    /**
1787
+     * edit a datetime inside attendance calendar table
1788
+     * @param	int	attendance calendar id
1789
+     * @param	int	attendance id
1790
+     * @return	int affected rows
1791
+     */
1792
+    public function attendance_calendar_edit($calendar_id, $attendance_id)
1793
+    {
1794
+        $tbl_attendance_calendar = Database::get_course_table(TABLE_ATTENDANCE_CALENDAR);
1795
+        $affected_rows = 0;
1796
+        $attendance_id = intval($attendance_id);
1797
+        $course_id = api_get_course_int_id();
1798
+        // check if datetime already exists inside the table
1799
+        $sql = "SELECT id FROM $tbl_attendance_calendar
1800 1800
 		        WHERE
1801 1801
 		        	c_id = $course_id AND
1802 1802
 		        	date_time = '".Database::escape_string($this->date_time)."' AND
1803 1803
 		        	attendance_id = '$attendance_id'";
1804
-		$rs = Database::query($sql);
1804
+        $rs = Database::query($sql);
1805 1805
 
1806
-		if (Database::num_rows($rs) == 0) {
1807
-			$sql = "UPDATE $tbl_attendance_calendar
1806
+        if (Database::num_rows($rs) == 0) {
1807
+            $sql = "UPDATE $tbl_attendance_calendar
1808 1808
 					SET date_time='".Database::escape_string($this->date_time)."'
1809 1809
 					WHERE c_id = $course_id AND id = '".intval($calendar_id)."'";
1810
-			Database::query($sql);
1811
-		}
1812
-
1813
-		// update locked attendance
1814
-		$is_all_calendar_done = self::is_all_attendance_calendar_done($attendance_id);
1815
-		if (!$is_all_calendar_done) {
1816
-			self::lock_attendance($attendance_id, false);
1817
-		} else {
1818
-			self::lock_attendance($attendance_id);
1819
-		}
1820
-
1821
-		return $affected_rows;
1822
-	}
1823
-
1824
-	/**
1825
-	 * delete a datetime from attendance calendar table
1826
-	 * @param	int		attendance calendar id
1827
-	 * @param	int		attendance id
1828
-	 * @param	bool	true for removing all calendar inside current attendance, false for removing by calendar id
1829
-	 * @return	int affected rows
1830
-	 */
1831
-	public function attendance_calendar_delete($calendar_id, $attendance_id , $all_delete = false)
1832
-	{
1833
-		$tbl_attendance_calendar = Database::get_course_table(TABLE_ATTENDANCE_CALENDAR);
1834
-		$tbl_attendance_sheet = Database::get_course_table(TABLE_ATTENDANCE_SHEET);
1835
-
1836
-		$attendance_id = intval($attendance_id);
1837
-		// get all registered users inside current course
1838
-		$users = $this->get_users_rel_course();
1839
-		$user_ids = array_keys($users);
1840
-		$course_id = api_get_course_int_id();
1841
-		$affected_rows = 0;
1842
-		if ($all_delete) {
1843
-			$attendance_calendar = $this->get_attendance_calendar($attendance_id);
1844
-			// get all dates from calendar by current attendance
1845
-			if (!empty($attendance_calendar)) {
1846
-				foreach ($attendance_calendar as $cal) {
1847
-					// delete all data from attendance sheet
1848
-					$sql = "DELETE FROM $tbl_attendance_sheet
1810
+            Database::query($sql);
1811
+        }
1812
+
1813
+        // update locked attendance
1814
+        $is_all_calendar_done = self::is_all_attendance_calendar_done($attendance_id);
1815
+        if (!$is_all_calendar_done) {
1816
+            self::lock_attendance($attendance_id, false);
1817
+        } else {
1818
+            self::lock_attendance($attendance_id);
1819
+        }
1820
+
1821
+        return $affected_rows;
1822
+    }
1823
+
1824
+    /**
1825
+     * delete a datetime from attendance calendar table
1826
+     * @param	int		attendance calendar id
1827
+     * @param	int		attendance id
1828
+     * @param	bool	true for removing all calendar inside current attendance, false for removing by calendar id
1829
+     * @return	int affected rows
1830
+     */
1831
+    public function attendance_calendar_delete($calendar_id, $attendance_id , $all_delete = false)
1832
+    {
1833
+        $tbl_attendance_calendar = Database::get_course_table(TABLE_ATTENDANCE_CALENDAR);
1834
+        $tbl_attendance_sheet = Database::get_course_table(TABLE_ATTENDANCE_SHEET);
1835
+
1836
+        $attendance_id = intval($attendance_id);
1837
+        // get all registered users inside current course
1838
+        $users = $this->get_users_rel_course();
1839
+        $user_ids = array_keys($users);
1840
+        $course_id = api_get_course_int_id();
1841
+        $affected_rows = 0;
1842
+        if ($all_delete) {
1843
+            $attendance_calendar = $this->get_attendance_calendar($attendance_id);
1844
+            // get all dates from calendar by current attendance
1845
+            if (!empty($attendance_calendar)) {
1846
+                foreach ($attendance_calendar as $cal) {
1847
+                    // delete all data from attendance sheet
1848
+                    $sql = "DELETE FROM $tbl_attendance_sheet
1849 1849
 							WHERE c_id = $course_id AND attendance_calendar_id = '".intval($cal['id'])."'";
1850
-					Database::query($sql);
1851
-					// delete data from attendance calendar
1852
-					$sql = "DELETE FROM $tbl_attendance_calendar
1850
+                    Database::query($sql);
1851
+                    // delete data from attendance calendar
1852
+                    $sql = "DELETE FROM $tbl_attendance_calendar
1853 1853
 							WHERE c_id = $course_id AND id = '".intval($cal['id'])."'";
1854
-					Database::query($sql);
1855
-
1856
-					$this->deleteAttendanceCalendarGroup($cal['id'], $course_id);
1857
-					$affected_rows++;
1858
-				}
1859
-			}
1860
-		} else {
1861
-			// delete just one row from attendance sheet by the calendar id
1862
-			$sql = "DELETE FROM $tbl_attendance_sheet
1854
+                    Database::query($sql);
1855
+
1856
+                    $this->deleteAttendanceCalendarGroup($cal['id'], $course_id);
1857
+                    $affected_rows++;
1858
+                }
1859
+            }
1860
+        } else {
1861
+            // delete just one row from attendance sheet by the calendar id
1862
+            $sql = "DELETE FROM $tbl_attendance_sheet
1863 1863
 					WHERE c_id = $course_id AND attendance_calendar_id = '".intval($calendar_id)."'";
1864
-			Database::query($sql);
1865
-			// delete data from attendance calendar
1866
-			$sql = "DELETE FROM $tbl_attendance_calendar
1864
+            Database::query($sql);
1865
+            // delete data from attendance calendar
1866
+            $sql = "DELETE FROM $tbl_attendance_calendar
1867 1867
 					WHERE c_id = $course_id AND id = '".intval($calendar_id)."'";
1868
-			Database::query($sql);
1869
-
1870
-			$this->deleteAttendanceCalendarGroup($calendar_id, $course_id);
1871
-			$affected_rows++;
1872
-		}
1873
-
1874
-		// update users' results
1875
-		$this->update_users_results($user_ids, $attendance_id);
1876
-
1877
-		return $affected_rows;
1878
-	}
1879
-
1880
-	/** Setters for fields of attendances tables **/
1881
-	public function set_session_id($session_id)
1882
-	{
1883
-		$this->session_id = $session_id;
1884
-	}
1885
-
1886
-	public function set_course_id($course_id)
1887
-	{
1888
-		$this->course_id = $course_id;
1889
-	}
1890
-
1891
-	public function set_date_time($datetime)
1892
-	{
1893
-		$this->date_time = $datetime;
1894
-	}
1895
-
1896
-	public function set_name($name)
1897
-	{
1898
-		$this->name = $name;
1899
-	}
1900
-
1901
-	public function set_description($description)
1902
-	{
1903
-		$this->description = $description;
1904
-	}
1905
-
1906
-	public function set_attendance_qualify_title($attendance_qualify_title)
1907
-	{
1908
-		$this->attendance_qualify_title = $attendance_qualify_title;
1909
-	}
1910
-
1911
-	public function set_attendance_weight($attendance_weight)
1912
-	{
1913
-		$this->attendance_weight = $attendance_weight;
1914
-	}
1915
-
1916
-	/** Getters for fields of attendances tables **/
1917
-	public function get_session_id()
1918
-	{
1919
-		return $this->session_id;
1920
-	}
1921
-
1922
-	public function get_course_id()
1923
-	{
1924
-		return $this->course_id;
1925
-	}
1926
-
1927
-	public function get_date_time()
1928
-	{
1929
-		return $this->date_time;
1930
-	}
1931
-
1932
-	public function get_name()
1933
-	{
1934
-		return $this->name;
1935
-	}
1936
-
1937
-	public function get_description()
1938
-	{
1939
-		return $this->description;
1940
-	}
1941
-
1942
-	public function get_attendance_qualify_title()
1943
-	{
1944
-		return $this->attendance_qualify_title;
1945
-	}
1946
-
1947
-	public function get_attendance_weight()
1948
-	{
1949
-		return $this->attendance_weight;
1950
-	}
1951
-
1952
-	/**
1953
-	 * @param string $startDate in UTC time
1954
-	 * @param string $endDate in UTC time
1955
-	 *
1956
-	 * @return array
1957
-	 */
1958
-	public function getAttendanceLogin($startDate, $endDate)
1959
-	{
1960
-		if (empty($startDate) || $startDate == '0000-00-00' ||
1961
-			empty($endDate) || $endDate == '0000-00-00'
1962
-		) {
1963
-			return false;
1964
-		}
1965
-
1966
-		$sessionId = api_get_session_id();
1967
-		$courseCode  = api_get_course_id();
1968
-		if (!empty($sessionId)) {
1969
-			$users = CourseManager:: get_user_list_from_course_code(
1970
-				$courseCode,
1971
-				$sessionId,
1972
-				'',
1973
-				'lastname',
1974
-				0
1975
-			);
1976
-		} else {
1977
-			$users = CourseManager:: get_user_list_from_course_code(
1978
-				$courseCode,
1979
-				0,
1980
-				'',
1981
-				'lastname',
1982
-				STUDENT
1983
-			);
1984
-		}
1985
-
1986
-		$dateTimeStartOriginal = new DateTime($startDate);
1987
-		$dateTimeStart = new DateTime($startDate);
1988
-		$dateTimeEnd= new DateTime($endDate);
1989
-		$interval = $dateTimeStart->diff($dateTimeEnd);
1990
-		$days = intval($interval->format('%a'));
1991
-
1992
-		$dateList = array($dateTimeStart->format('Y-m-d'));
1993
-		$headers = array(
1994
-			get_lang('User'),
1995
-			$dateTimeStart->format('Y-m-d')
1996
-		);
1997
-
1998
-		for ($i = 0; $i < $days; $i++) {
1999
-			$dateTimeStart = $dateTimeStart->add(new DateInterval('P1D'));
2000
-			$date = $dateTimeStart->format('Y-m-d');
2001
-			$dateList[] = $date;
2002
-			$headers[] = $date;
2003
-		}
2004
-
2005
-		$accessData = CourseManager::getCourseAccessPerCourseAndSession(
2006
-			$courseCode,
2007
-			$sessionId,
2008
-			$dateTimeStartOriginal->format('Y-m-d H:i:s'),
2009
-			$dateTimeEnd->format('Y-m-d H:i:s')
2010
-		);
2011
-
2012
-		$results = array();
2013
-		if (!empty($accessData)) {
2014
-			foreach ($accessData as $data) {
2015
-				$onlyDate = substr($data['login_course_date'], 0, 10);
2016
-				$results[$data['user_id']][$onlyDate] = true;
2017
-			}
2018
-		}
2019
-
2020
-		return array(
2021
-			'users' => $users,
2022
-			'dateList' => $dateList,
2023
-			'headers' => $headers,
2024
-			'results' => $results
2025
-		);
2026
-	}
2027
-
2028
-	/**
2029
-	 * @param string $startDate in UTC time
2030
-	 * @param string $endDate in UTC time
2031
-	 *
2032
-	 * @return string
2033
-	 */
2034
-	public function getAttendanceLoginTable($startDate, $endDate)
2035
-	{
2036
-		$data = $this->getAttendanceLogin($startDate, $endDate);
2037
-
2038
-		if (!$data) {
2039
-			return null;
2040
-		}
2041
-
2042
-		$headers = $data['headers'];
2043
-		$dateList = $data['dateList'];
2044
-		$users = $data['users'];
2045
-		$results = $data['results'];
2046
-
2047
-		$table = new HTML_Table(array('class' => 'data_table'));
2048
-		$row = 0;
2049
-		$column = 0;
2050
-		foreach ($headers as $header) {
2051
-			$table->setHeaderContents($row, $column, $header);
2052
-			$column++;
2053
-		}
2054
-		$row = 1;
2055
-		foreach ($users as $user) {
2056
-			$table->setCellContents(
2057
-				$row,
2058
-				0,
2059
-				$user['lastname'].' '.$user['firstname'].' ('.$user['username'].')'
2060
-			);
2061
-			$row ++;
2062
-		}
2063
-
2064
-		$column = 1;
2065
-		$row = 1;
2066
-		foreach ($users as $user) {
2067
-			foreach ($dateList as $date) {
2068
-				$status = null;
2069
-				if (isset($results[$user['user_id']]) &&
2070
-					isset($results[$user['user_id']][$date])
2071
-				) {
2072
-					$status = 'X';
2073
-				}
2074
-				$table->setCellContents($row, $column, $status);
2075
-				$column++;
2076
-			}
2077
-			$row++;
2078
-			$column = 1;
2079
-		}
2080
-
2081
-		return $table->toHtml();
2082
-	}
2083
-
2084
-	/**
2085
-	 * @param string $startDate in UTC time
2086
-	 * @param string $endDate in UTC time
2087
-	 *
2088
-	 * @return string
2089
-	 */
2090
-	public function exportAttendanceLogin($startDate, $endDate)
2091
-	{
2092
-		$data = $this->getAttendanceLogin($startDate, $endDate);
2093
-
2094
-		if (!$data) {
2095
-			return null;
2096
-		}
2097
-		$users = $data['users'];
2098
-		$results = $data['results'];
2099
-
2100
-		$table = new HTML_Table(array('class' => 'data_table'));
2101
-
2102
-		$table->setHeaderContents(0, 0, get_lang('User'));
2103
-		$table->setHeaderContents(0, 1, get_lang('Date'));
2104
-
2105
-		$row = 1;
2106
-		foreach ($users as $user) {
2107
-			$table->setCellContents(
2108
-				$row,
2109
-				0,
2110
-				$user['lastname'].' '.$user['firstname'].' ('.$user['username'].')'
2111
-			);
2112
-			$row++;
2113
-		}
2114
-		$table->setColAttributes(0, array('style' => 'width:28%'));
2115
-
2116
-		$row = 1;
2117
-		foreach ($users as $user) {
2118
-			if (isset($results[$user['user_id']]) &&
2119
-				!empty($results[$user['user_id']])
2120
-			) {
2121
-				$dates = implode(', ', array_keys($results[$user['user_id']]));
2122
-				$table->setCellContents($row, 1, $dates);
2123
-			}
2124
-			$row++;
2125
-		}
2126
-
2127
-		//$tableToString = null;
2128
-
2129
-		//$sessionInfo = api_get_session_info(api_get_session_id());
2130
-		//if (!empty($sessionInfo)) {
2131
-		/*$tableToString .= '<strong>'.get_lang('PeriodToDisplay').'</strong>: '.
1868
+            Database::query($sql);
1869
+
1870
+            $this->deleteAttendanceCalendarGroup($calendar_id, $course_id);
1871
+            $affected_rows++;
1872
+        }
1873
+
1874
+        // update users' results
1875
+        $this->update_users_results($user_ids, $attendance_id);
1876
+
1877
+        return $affected_rows;
1878
+    }
1879
+
1880
+    /** Setters for fields of attendances tables **/
1881
+    public function set_session_id($session_id)
1882
+    {
1883
+        $this->session_id = $session_id;
1884
+    }
1885
+
1886
+    public function set_course_id($course_id)
1887
+    {
1888
+        $this->course_id = $course_id;
1889
+    }
1890
+
1891
+    public function set_date_time($datetime)
1892
+    {
1893
+        $this->date_time = $datetime;
1894
+    }
1895
+
1896
+    public function set_name($name)
1897
+    {
1898
+        $this->name = $name;
1899
+    }
1900
+
1901
+    public function set_description($description)
1902
+    {
1903
+        $this->description = $description;
1904
+    }
1905
+
1906
+    public function set_attendance_qualify_title($attendance_qualify_title)
1907
+    {
1908
+        $this->attendance_qualify_title = $attendance_qualify_title;
1909
+    }
1910
+
1911
+    public function set_attendance_weight($attendance_weight)
1912
+    {
1913
+        $this->attendance_weight = $attendance_weight;
1914
+    }
1915
+
1916
+    /** Getters for fields of attendances tables **/
1917
+    public function get_session_id()
1918
+    {
1919
+        return $this->session_id;
1920
+    }
1921
+
1922
+    public function get_course_id()
1923
+    {
1924
+        return $this->course_id;
1925
+    }
1926
+
1927
+    public function get_date_time()
1928
+    {
1929
+        return $this->date_time;
1930
+    }
1931
+
1932
+    public function get_name()
1933
+    {
1934
+        return $this->name;
1935
+    }
1936
+
1937
+    public function get_description()
1938
+    {
1939
+        return $this->description;
1940
+    }
1941
+
1942
+    public function get_attendance_qualify_title()
1943
+    {
1944
+        return $this->attendance_qualify_title;
1945
+    }
1946
+
1947
+    public function get_attendance_weight()
1948
+    {
1949
+        return $this->attendance_weight;
1950
+    }
1951
+
1952
+    /**
1953
+     * @param string $startDate in UTC time
1954
+     * @param string $endDate in UTC time
1955
+     *
1956
+     * @return array
1957
+     */
1958
+    public function getAttendanceLogin($startDate, $endDate)
1959
+    {
1960
+        if (empty($startDate) || $startDate == '0000-00-00' ||
1961
+            empty($endDate) || $endDate == '0000-00-00'
1962
+        ) {
1963
+            return false;
1964
+        }
1965
+
1966
+        $sessionId = api_get_session_id();
1967
+        $courseCode  = api_get_course_id();
1968
+        if (!empty($sessionId)) {
1969
+            $users = CourseManager:: get_user_list_from_course_code(
1970
+                $courseCode,
1971
+                $sessionId,
1972
+                '',
1973
+                'lastname',
1974
+                0
1975
+            );
1976
+        } else {
1977
+            $users = CourseManager:: get_user_list_from_course_code(
1978
+                $courseCode,
1979
+                0,
1980
+                '',
1981
+                'lastname',
1982
+                STUDENT
1983
+            );
1984
+        }
1985
+
1986
+        $dateTimeStartOriginal = new DateTime($startDate);
1987
+        $dateTimeStart = new DateTime($startDate);
1988
+        $dateTimeEnd= new DateTime($endDate);
1989
+        $interval = $dateTimeStart->diff($dateTimeEnd);
1990
+        $days = intval($interval->format('%a'));
1991
+
1992
+        $dateList = array($dateTimeStart->format('Y-m-d'));
1993
+        $headers = array(
1994
+            get_lang('User'),
1995
+            $dateTimeStart->format('Y-m-d')
1996
+        );
1997
+
1998
+        for ($i = 0; $i < $days; $i++) {
1999
+            $dateTimeStart = $dateTimeStart->add(new DateInterval('P1D'));
2000
+            $date = $dateTimeStart->format('Y-m-d');
2001
+            $dateList[] = $date;
2002
+            $headers[] = $date;
2003
+        }
2004
+
2005
+        $accessData = CourseManager::getCourseAccessPerCourseAndSession(
2006
+            $courseCode,
2007
+            $sessionId,
2008
+            $dateTimeStartOriginal->format('Y-m-d H:i:s'),
2009
+            $dateTimeEnd->format('Y-m-d H:i:s')
2010
+        );
2011
+
2012
+        $results = array();
2013
+        if (!empty($accessData)) {
2014
+            foreach ($accessData as $data) {
2015
+                $onlyDate = substr($data['login_course_date'], 0, 10);
2016
+                $results[$data['user_id']][$onlyDate] = true;
2017
+            }
2018
+        }
2019
+
2020
+        return array(
2021
+            'users' => $users,
2022
+            'dateList' => $dateList,
2023
+            'headers' => $headers,
2024
+            'results' => $results
2025
+        );
2026
+    }
2027
+
2028
+    /**
2029
+     * @param string $startDate in UTC time
2030
+     * @param string $endDate in UTC time
2031
+     *
2032
+     * @return string
2033
+     */
2034
+    public function getAttendanceLoginTable($startDate, $endDate)
2035
+    {
2036
+        $data = $this->getAttendanceLogin($startDate, $endDate);
2037
+
2038
+        if (!$data) {
2039
+            return null;
2040
+        }
2041
+
2042
+        $headers = $data['headers'];
2043
+        $dateList = $data['dateList'];
2044
+        $users = $data['users'];
2045
+        $results = $data['results'];
2046
+
2047
+        $table = new HTML_Table(array('class' => 'data_table'));
2048
+        $row = 0;
2049
+        $column = 0;
2050
+        foreach ($headers as $header) {
2051
+            $table->setHeaderContents($row, $column, $header);
2052
+            $column++;
2053
+        }
2054
+        $row = 1;
2055
+        foreach ($users as $user) {
2056
+            $table->setCellContents(
2057
+                $row,
2058
+                0,
2059
+                $user['lastname'].' '.$user['firstname'].' ('.$user['username'].')'
2060
+            );
2061
+            $row ++;
2062
+        }
2063
+
2064
+        $column = 1;
2065
+        $row = 1;
2066
+        foreach ($users as $user) {
2067
+            foreach ($dateList as $date) {
2068
+                $status = null;
2069
+                if (isset($results[$user['user_id']]) &&
2070
+                    isset($results[$user['user_id']][$date])
2071
+                ) {
2072
+                    $status = 'X';
2073
+                }
2074
+                $table->setCellContents($row, $column, $status);
2075
+                $column++;
2076
+            }
2077
+            $row++;
2078
+            $column = 1;
2079
+        }
2080
+
2081
+        return $table->toHtml();
2082
+    }
2083
+
2084
+    /**
2085
+     * @param string $startDate in UTC time
2086
+     * @param string $endDate in UTC time
2087
+     *
2088
+     * @return string
2089
+     */
2090
+    public function exportAttendanceLogin($startDate, $endDate)
2091
+    {
2092
+        $data = $this->getAttendanceLogin($startDate, $endDate);
2093
+
2094
+        if (!$data) {
2095
+            return null;
2096
+        }
2097
+        $users = $data['users'];
2098
+        $results = $data['results'];
2099
+
2100
+        $table = new HTML_Table(array('class' => 'data_table'));
2101
+
2102
+        $table->setHeaderContents(0, 0, get_lang('User'));
2103
+        $table->setHeaderContents(0, 1, get_lang('Date'));
2104
+
2105
+        $row = 1;
2106
+        foreach ($users as $user) {
2107
+            $table->setCellContents(
2108
+                $row,
2109
+                0,
2110
+                $user['lastname'].' '.$user['firstname'].' ('.$user['username'].')'
2111
+            );
2112
+            $row++;
2113
+        }
2114
+        $table->setColAttributes(0, array('style' => 'width:28%'));
2115
+
2116
+        $row = 1;
2117
+        foreach ($users as $user) {
2118
+            if (isset($results[$user['user_id']]) &&
2119
+                !empty($results[$user['user_id']])
2120
+            ) {
2121
+                $dates = implode(', ', array_keys($results[$user['user_id']]));
2122
+                $table->setCellContents($row, 1, $dates);
2123
+            }
2124
+            $row++;
2125
+        }
2126
+
2127
+        //$tableToString = null;
2128
+
2129
+        //$sessionInfo = api_get_session_info(api_get_session_id());
2130
+        //if (!empty($sessionInfo)) {
2131
+        /*$tableToString .= '<strong>'.get_lang('PeriodToDisplay').'</strong>: '.
2132 2132
 			sprintf(get_lang('FromDateXToDateY'), $startDate, $endDate);*/
2133
-		//}
2134
-
2135
-		$tableToString = $table->toHtml();
2136
-
2137
-		$params = array(
2138
-			'filename' => get_lang('Attendance') . '_' . api_get_utc_datetime(),
2139
-			'pdf_title' => get_lang('Attendance'),
2140
-			'course_code' => api_get_course_id(),
2141
-			'show_real_course_teachers' => true
2142
-		);
2143
-		$pdf = new PDF('A4', null, $params);
2144
-		$pdf->html_to_pdf_with_template($tableToString);
2145
-	}
2133
+        //}
2134
+
2135
+        $tableToString = $table->toHtml();
2136
+
2137
+        $params = array(
2138
+            'filename' => get_lang('Attendance') . '_' . api_get_utc_datetime(),
2139
+            'pdf_title' => get_lang('Attendance'),
2140
+            'course_code' => api_get_course_id(),
2141
+            'show_real_course_teachers' => true
2142
+        );
2143
+        $pdf = new PDF('A4', null, $params);
2144
+        $pdf->html_to_pdf_with_template($tableToString);
2145
+    }
2146 2146
 }
Please login to merge, or discard this patch.
main/inc/lib/formvalidator/Element/SelectLanguage.php 1 patch
Indentation   +17 added lines, -17 removed lines patch added patch discarded remove patch
@@ -6,22 +6,22 @@
 block discarded – undo
6 6
 */
7 7
 class SelectLanguage extends HTML_QuickForm_select
8 8
 {
9
-	/**
10
-	 * Class constructor
11
-	 */
9
+    /**
10
+     * Class constructor
11
+     */
12 12
     public function __construct($elementName = null, $elementLabel = null, $options = null, $attributes = null)
13
-	{
14
-		parent::__construct($elementName, $elementLabel, $options, $attributes);
15
-		// Get all languages
16
-		$languages = api_get_languages();
17
-		$this->_options = array();
18
-		$this->_values = array();
19
-		foreach ($languages['name'] as $index => $name) {
20
-			if($languages['folder'][$index] == api_get_setting('platformLanguage')) {
21
-				$this->addOption($name,$languages['folder'][$index],array('selected'=>'selected'));
22
-			} else {
23
-				$this->addOption($name,$languages['folder'][$index]);
24
-			}
25
-		}
26
-	}
13
+    {
14
+        parent::__construct($elementName, $elementLabel, $options, $attributes);
15
+        // Get all languages
16
+        $languages = api_get_languages();
17
+        $this->_options = array();
18
+        $this->_values = array();
19
+        foreach ($languages['name'] as $index => $name) {
20
+            if($languages['folder'][$index] == api_get_setting('platformLanguage')) {
21
+                $this->addOption($name,$languages['folder'][$index],array('selected'=>'selected'));
22
+            } else {
23
+                $this->addOption($name,$languages['folder'][$index]);
24
+            }
25
+        }
26
+    }
27 27
 }
Please login to merge, or discard this patch.
main/inc/lib/login.lib.php 1 patch
Indentation   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -852,14 +852,14 @@  discard block
 block discarded – undo
852 852
             $email = false;
853 853
         }
854 854
 
855
-		if ($email) {
856
-			$condition = "LOWER(email) = '".Database::escape_string($username)."' ";
857
-		} else {
855
+        if ($email) {
856
+            $condition = "LOWER(email) = '".Database::escape_string($username)."' ";
857
+        } else {
858 858
             $condition = "LOWER(username) = '".Database::escape_string($username)."'";
859 859
         }
860 860
 
861
-		$tbl_user = Database :: get_main_table(TABLE_MAIN_USER);
862
-		$query = "SELECT 
861
+        $tbl_user = Database :: get_main_table(TABLE_MAIN_USER);
862
+        $query = "SELECT 
863 863
 		            user_id AS uid, 
864 864
 		            lastname AS lastName, 
865 865
 		            firstname AS firstName, 
@@ -874,7 +874,7 @@  discard block
 block discarded – undo
874 874
                     auth_source
875 875
 				 FROM $tbl_user
876 876
 				 WHERE ( $condition AND active = 1) ";
877
-		$result = Database::query($query);
877
+        $result = Database::query($query);
878 878
         $num_rows = Database::num_rows($result);
879 879
         if ($result && $num_rows > 0) {
880 880
             return Database::fetch_assoc($result);
Please login to merge, or discard this patch.
plugin/bbb/lib/bbb_api.php 1 patch
Indentation   +403 added lines, -403 removed lines patch added patch discarded remove patch
@@ -44,107 +44,107 @@  discard block
 block discarded – undo
44 44
 
45 45
 class BigBlueButtonBN {
46 46
 
47
-	private $_securitySalt;
48
-	private $_bbbServerBaseUrl;
47
+    private $_securitySalt;
48
+    private $_bbbServerBaseUrl;
49 49
 
50
-	/* ___________ General Methods for the BigBlueButton Class __________ */
50
+    /* ___________ General Methods for the BigBlueButton Class __________ */
51 51
 
52
-	function __construct() {
53
-	/*
52
+    function __construct() {
53
+    /*
54 54
 	Establish just our basic elements in the constructor:
55 55
 	*/
56
-		// BASE CONFIGS - set these for your BBB server in config.php and they will
57
-		// simply flow in here via the constants:
58
-		$this->_securitySalt 		= CONFIG_SECURITY_SALT;
59
-		$this->_bbbServerBaseUrl 	= CONFIG_SERVER_BASE_URL;
60
-	}
61
-
62
-	private function _processXmlResponse($url){
63
-	/*
56
+        // BASE CONFIGS - set these for your BBB server in config.php and they will
57
+        // simply flow in here via the constants:
58
+        $this->_securitySalt 		= CONFIG_SECURITY_SALT;
59
+        $this->_bbbServerBaseUrl 	= CONFIG_SERVER_BASE_URL;
60
+    }
61
+
62
+    private function _processXmlResponse($url){
63
+    /*
64 64
 	A private utility method used by other public methods to process XML responses.
65 65
 	*/
66
-		if (extension_loaded('curl')) {
67
-			$ch = curl_init() or die ( curl_error($ch) );
68
-			$timeout = 10;
69
-			curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false);
70
-			curl_setopt( $ch, CURLOPT_URL, $url );
71
-			curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
72
-			curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, $timeout);
73
-			$data = curl_exec( $ch );
74
-			curl_close( $ch );
75
-
76
-			if($data)
77
-				return (new SimpleXMLElement($data));
78
-			else
79
-				return false;
80
-		}
81
-		return (simplexml_load_file($url));
82
-	}
83
-
84
-	private function _requiredParam($param) {
85
-		/* Process required params and throw errors if we don't get values */
86
-		if ((isset($param)) && ($param != '')) {
87
-			return $param;
88
-		}
89
-		elseif (!isset($param)) {
90
-			throw new Exception('Missing parameter.');
91
-		}
92
-		else {
93
-			throw new Exception(''.$param.' is required.');
94
-		}
95
-	}
96
-
97
-	private function _optionalParam($param) {
98
-		/* Pass most optional params through as set value, or set to '' */
99
-		/* Don't know if we'll use this one, but let's build it in case. */
100
-		if ((isset($param)) && ($param != '')) {
101
-			return $param;
102
-		}
103
-		else {
104
-			$param = '';
105
-			return $param;
106
-		}
107
-	}
108
-
109
-	/* __________________ BBB ADMINISTRATION METHODS _________________ */
110
-	/* The methods in the following section support the following categories of the BBB API:
66
+        if (extension_loaded('curl')) {
67
+            $ch = curl_init() or die ( curl_error($ch) );
68
+            $timeout = 10;
69
+            curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false);
70
+            curl_setopt( $ch, CURLOPT_URL, $url );
71
+            curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
72
+            curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, $timeout);
73
+            $data = curl_exec( $ch );
74
+            curl_close( $ch );
75
+
76
+            if($data)
77
+                return (new SimpleXMLElement($data));
78
+            else
79
+                return false;
80
+        }
81
+        return (simplexml_load_file($url));
82
+    }
83
+
84
+    private function _requiredParam($param) {
85
+        /* Process required params and throw errors if we don't get values */
86
+        if ((isset($param)) && ($param != '')) {
87
+            return $param;
88
+        }
89
+        elseif (!isset($param)) {
90
+            throw new Exception('Missing parameter.');
91
+        }
92
+        else {
93
+            throw new Exception(''.$param.' is required.');
94
+        }
95
+    }
96
+
97
+    private function _optionalParam($param) {
98
+        /* Pass most optional params through as set value, or set to '' */
99
+        /* Don't know if we'll use this one, but let's build it in case. */
100
+        if ((isset($param)) && ($param != '')) {
101
+            return $param;
102
+        }
103
+        else {
104
+            $param = '';
105
+            return $param;
106
+        }
107
+    }
108
+
109
+    /* __________________ BBB ADMINISTRATION METHODS _________________ */
110
+    /* The methods in the following section support the following categories of the BBB API:
111 111
 	-- create
112 112
 	-- join
113 113
 	-- end
114 114
 	*/
115 115
 
116
-	public function getCreateMeetingUrl($creationParams) {
117
-		/*
116
+    public function getCreateMeetingUrl($creationParams) {
117
+        /*
118 118
 		USAGE:
119 119
 		(see $creationParams array in createMeetingArray method.)
120 120
 		*/
121
-		$this->_meetingId = $this->_requiredParam($creationParams['meetingId']);
122
-		$this->_meetingName = $this->_requiredParam($creationParams['meetingName']);
123
-		// Set up the basic creation URL:
124
-		$creationUrl = $this->_bbbServerBaseUrl."api/create?";
125
-		// Add params:
126
-		$params =
127
-		'name='.urlencode($this->_meetingName).
128
-		'&meetingID='.urlencode($this->_meetingId).
129
-		'&attendeePW='.urlencode($creationParams['attendeePw']).
130
-		'&moderatorPW='.urlencode($creationParams['moderatorPw']).
131
-		'&dialNumber='.urlencode($creationParams['dialNumber']).
132
-		'&voiceBridge='.urlencode($creationParams['voiceBridge']).
133
-		'&webVoice='.urlencode($creationParams['webVoice']).
134
-		'&logoutURL='.urlencode($creationParams['logoutUrl']).
135
-		'&maxParticipants='.urlencode($creationParams['maxParticipants']).
136
-		'&record='.urlencode($creationParams['record']).
137
-		'&duration='.urlencode($creationParams['duration']);
138
-		//'&meta_category='.urlencode($creationParams['meta_category']);
139
-		$welcomeMessage = $creationParams['welcomeMsg'];
140
-		if(trim($welcomeMessage))
141
-			$params .= '&welcome='.urlencode($welcomeMessage);
142
-		// Return the complete URL:
143
-		return ( $creationUrl.$params.'&checksum='.sha1("create".$params.$this->_securitySalt) );
144
-	}
145
-
146
-	public function createMeetingWithXmlResponseArray($creationParams) {
147
-		/*
121
+        $this->_meetingId = $this->_requiredParam($creationParams['meetingId']);
122
+        $this->_meetingName = $this->_requiredParam($creationParams['meetingName']);
123
+        // Set up the basic creation URL:
124
+        $creationUrl = $this->_bbbServerBaseUrl."api/create?";
125
+        // Add params:
126
+        $params =
127
+        'name='.urlencode($this->_meetingName).
128
+        '&meetingID='.urlencode($this->_meetingId).
129
+        '&attendeePW='.urlencode($creationParams['attendeePw']).
130
+        '&moderatorPW='.urlencode($creationParams['moderatorPw']).
131
+        '&dialNumber='.urlencode($creationParams['dialNumber']).
132
+        '&voiceBridge='.urlencode($creationParams['voiceBridge']).
133
+        '&webVoice='.urlencode($creationParams['webVoice']).
134
+        '&logoutURL='.urlencode($creationParams['logoutUrl']).
135
+        '&maxParticipants='.urlencode($creationParams['maxParticipants']).
136
+        '&record='.urlencode($creationParams['record']).
137
+        '&duration='.urlencode($creationParams['duration']);
138
+        //'&meta_category='.urlencode($creationParams['meta_category']);
139
+        $welcomeMessage = $creationParams['welcomeMsg'];
140
+        if(trim($welcomeMessage))
141
+            $params .= '&welcome='.urlencode($welcomeMessage);
142
+        // Return the complete URL:
143
+        return ( $creationUrl.$params.'&checksum='.sha1("create".$params.$this->_securitySalt) );
144
+    }
145
+
146
+    public function createMeetingWithXmlResponseArray($creationParams) {
147
+        /*
148 148
 		USAGE:
149 149
 		$creationParams = array(
150 150
 			'name' => 'Meeting Name',	-- A name for the meeting (or username)
@@ -162,34 +162,34 @@  discard block
 block discarded – undo
162 162
 			'meta_category' => '', 		-- Use to pass additional info to BBB server. See API docs to enable.
163 163
 		);
164 164
 		*/
165
-		$xml = $this->_processXmlResponse($this->getCreateMeetingURL($creationParams));
165
+        $xml = $this->_processXmlResponse($this->getCreateMeetingURL($creationParams));
166 166
 
167 167
         if ($xml) {
168
-			if($xml->meetingID)
169
-				return array(
170
-					'returncode' => $xml->returncode,
171
-					'message' => $xml->message,
172
-					'messageKey' => $xml->messageKey,
173
-					'meetingId' => $xml->meetingID,
174
-					'attendeePw' => $xml->attendeePW,
175
-					'moderatorPw' => $xml->moderatorPW,
176
-					'hasBeenForciblyEnded' => $xml->hasBeenForciblyEnded,
177
-					'createTime' => $xml->createTime
178
-					);
179
-			else
180
-				return array(
181
-					'returncode' => $xml->returncode,
182
-					'message' => $xml->message,
183
-					'messageKey' => $xml->messageKey
184
-					);
185
-		}
186
-		else {
187
-			return null;
188
-		}
189
-	}
190
-
191
-	public function getJoinMeetingURL($joinParams) {
192
-		/*
168
+            if($xml->meetingID)
169
+                return array(
170
+                    'returncode' => $xml->returncode,
171
+                    'message' => $xml->message,
172
+                    'messageKey' => $xml->messageKey,
173
+                    'meetingId' => $xml->meetingID,
174
+                    'attendeePw' => $xml->attendeePW,
175
+                    'moderatorPw' => $xml->moderatorPW,
176
+                    'hasBeenForciblyEnded' => $xml->hasBeenForciblyEnded,
177
+                    'createTime' => $xml->createTime
178
+                    );
179
+            else
180
+                return array(
181
+                    'returncode' => $xml->returncode,
182
+                    'message' => $xml->message,
183
+                    'messageKey' => $xml->messageKey
184
+                    );
185
+        }
186
+        else {
187
+            return null;
188
+        }
189
+    }
190
+
191
+    public function getJoinMeetingURL($joinParams) {
192
+        /*
193 193
 		NOTE: At this point, we don't use a corresponding joinMeetingWithXmlResponse here because the API
194 194
 		doesn't respond on success, but you can still code that method if you need it. Or, you can take the URL
195 195
 		that's returned from this method and simply send your users off to that URL in your code.
@@ -203,249 +203,249 @@  discard block
 block discarded – undo
203 203
 			'webVoiceConf' => ''		-- OPTIONAL - string
204 204
 		);
205 205
 		*/
206
-		$this->_meetingId = $this->_requiredParam($joinParams['meetingId']);
207
-		$this->_username = $this->_requiredParam($joinParams['username']);
208
-		$this->_password = $this->_requiredParam($joinParams['password']);
209
-		// Establish the basic join URL:
210
-		$joinUrl = $this->_bbbServerBaseUrl."api/join?";
211
-		// Add parameters to the URL:
212
-		$params =
213
-		'meetingID='.urlencode($this->_meetingId).
214
-		'&fullName='.urlencode($this->_username).
215
-		'&password='.urlencode($this->_password).
216
-		'&userID='.urlencode($joinParams['userID']).
217
-		'&webVoiceConf='.urlencode($joinParams['webVoiceConf']);
218
-		// Only use createTime if we really want to use it. If it's '', then don't pass it:
219
-		if (((isset($joinParams['createTime'])) && ($joinParams['createTime'] != ''))) {
220
-			$params .= '&createTime='.urlencode($joinParams['createTime']);
221
-		}
222
-		// Return the URL:
223
-		return ($joinUrl.$params.'&checksum='.sha1("join".$params.$this->_securitySalt));
224
-	}
225
-
226
-	public function getEndMeetingURL($endParams) {
227
-		/* USAGE:
206
+        $this->_meetingId = $this->_requiredParam($joinParams['meetingId']);
207
+        $this->_username = $this->_requiredParam($joinParams['username']);
208
+        $this->_password = $this->_requiredParam($joinParams['password']);
209
+        // Establish the basic join URL:
210
+        $joinUrl = $this->_bbbServerBaseUrl."api/join?";
211
+        // Add parameters to the URL:
212
+        $params =
213
+        'meetingID='.urlencode($this->_meetingId).
214
+        '&fullName='.urlencode($this->_username).
215
+        '&password='.urlencode($this->_password).
216
+        '&userID='.urlencode($joinParams['userID']).
217
+        '&webVoiceConf='.urlencode($joinParams['webVoiceConf']);
218
+        // Only use createTime if we really want to use it. If it's '', then don't pass it:
219
+        if (((isset($joinParams['createTime'])) && ($joinParams['createTime'] != ''))) {
220
+            $params .= '&createTime='.urlencode($joinParams['createTime']);
221
+        }
222
+        // Return the URL:
223
+        return ($joinUrl.$params.'&checksum='.sha1("join".$params.$this->_securitySalt));
224
+    }
225
+
226
+    public function getEndMeetingURL($endParams) {
227
+        /* USAGE:
228 228
 		$endParams = array (
229 229
 			'meetingId' => '1234',		-- REQUIRED - The unique id for the meeting
230 230
 			'password' => 'mp'			-- REQUIRED - The moderator password for the meeting
231 231
 		);
232 232
 		*/
233
-		$this->_meetingId = $this->_requiredParam($endParams['meetingId']);
234
-		$this->_password = $this->_requiredParam($endParams['password']);
235
-		$endUrl = $this->_bbbServerBaseUrl."api/end?";
236
-		$params =
237
-		'meetingID='.urlencode($this->_meetingId).
238
-		'&password='.urlencode($this->_password);
239
-		return ($endUrl.$params.'&checksum='.sha1("end".$params.$this->_securitySalt));
240
-	}
241
-
242
-	public function endMeetingWithXmlResponseArray($endParams) {
243
-		/* USAGE:
233
+        $this->_meetingId = $this->_requiredParam($endParams['meetingId']);
234
+        $this->_password = $this->_requiredParam($endParams['password']);
235
+        $endUrl = $this->_bbbServerBaseUrl."api/end?";
236
+        $params =
237
+        'meetingID='.urlencode($this->_meetingId).
238
+        '&password='.urlencode($this->_password);
239
+        return ($endUrl.$params.'&checksum='.sha1("end".$params.$this->_securitySalt));
240
+    }
241
+
242
+    public function endMeetingWithXmlResponseArray($endParams) {
243
+        /* USAGE:
244 244
 		$endParams = array (
245 245
 			'meetingId' => '1234',		-- REQUIRED - The unique id for the meeting
246 246
 			'password' => 'mp'			-- REQUIRED - The moderator password for the meeting
247 247
 		);
248 248
 		*/
249
-		$xml = $this->_processXmlResponse($this->getEndMeetingURL($endParams));
250
-		if ($xml) {
251
-			return array(
252
-				'returncode' => $xml->returncode,
253
-				'message' => $xml->message,
254
-				'messageKey' => $xml->messageKey
255
-				);
256
-		}
257
-		else {
258
-			return null;
259
-		}
260
-
261
-	}
262
-
263
-	/* __________________ BBB MONITORING METHODS _________________ */
264
-	/* The methods in the following section support the following categories of the BBB API:
249
+        $xml = $this->_processXmlResponse($this->getEndMeetingURL($endParams));
250
+        if ($xml) {
251
+            return array(
252
+                'returncode' => $xml->returncode,
253
+                'message' => $xml->message,
254
+                'messageKey' => $xml->messageKey
255
+                );
256
+        }
257
+        else {
258
+            return null;
259
+        }
260
+
261
+    }
262
+
263
+    /* __________________ BBB MONITORING METHODS _________________ */
264
+    /* The methods in the following section support the following categories of the BBB API:
265 265
 	-- isMeetingRunning
266 266
 	-- getMeetings
267 267
 	-- getMeetingInfo
268 268
 	*/
269 269
 
270
-	public function getIsMeetingRunningUrl($meetingId) {
271
-		/* USAGE:
270
+    public function getIsMeetingRunningUrl($meetingId) {
271
+        /* USAGE:
272 272
 		$meetingId = '1234'		-- REQUIRED - The unique id for the meeting
273 273
 		*/
274
-		$this->_meetingId = $this->_requiredParam($meetingId);
275
-		$runningUrl = $this->_bbbServerBaseUrl."api/isMeetingRunning?";
276
-		$params =
277
-		'meetingID='.urlencode($this->_meetingId);
278
-		return ($runningUrl.$params.'&checksum='.sha1("isMeetingRunning".$params.$this->_securitySalt));
279
-	}
280
-
281
-	public function isMeetingRunningWithXmlResponseArray($meetingId) {
282
-		/* USAGE:
274
+        $this->_meetingId = $this->_requiredParam($meetingId);
275
+        $runningUrl = $this->_bbbServerBaseUrl."api/isMeetingRunning?";
276
+        $params =
277
+        'meetingID='.urlencode($this->_meetingId);
278
+        return ($runningUrl.$params.'&checksum='.sha1("isMeetingRunning".$params.$this->_securitySalt));
279
+    }
280
+
281
+    public function isMeetingRunningWithXmlResponseArray($meetingId) {
282
+        /* USAGE:
283 283
 		$meetingId = '1234'		-- REQUIRED - The unique id for the meeting
284 284
 		*/
285
-		$xml = $this->_processXmlResponse($this->getIsMeetingRunningUrl($meetingId));
286
-		if($xml) {
287
-			return array(
288
-				'returncode' => $xml->returncode,
289
-				'running' => $xml->running 	// -- Returns true/false.
290
-				);
291
-		}
292
-		else {
293
-			return null;
294
-		}
295
-
296
-	}
297
-
298
-	public function getGetMeetingsUrl() {
299
-		/* Simply formulate the getMeetings URL
285
+        $xml = $this->_processXmlResponse($this->getIsMeetingRunningUrl($meetingId));
286
+        if($xml) {
287
+            return array(
288
+                'returncode' => $xml->returncode,
289
+                'running' => $xml->running 	// -- Returns true/false.
290
+                );
291
+        }
292
+        else {
293
+            return null;
294
+        }
295
+
296
+    }
297
+
298
+    public function getGetMeetingsUrl() {
299
+        /* Simply formulate the getMeetings URL
300 300
 		We do this in a separate function so we have the option to just get this
301 301
 		URL and print it if we want for some reason.
302 302
 		*/
303
-		$getMeetingsUrl = $this->_bbbServerBaseUrl."api/getMeetings?checksum=".sha1("getMeetings".$this->_securitySalt);
304
-		return $getMeetingsUrl;
305
-	}
303
+        $getMeetingsUrl = $this->_bbbServerBaseUrl."api/getMeetings?checksum=".sha1("getMeetings".$this->_securitySalt);
304
+        return $getMeetingsUrl;
305
+    }
306 306
 
307
-	public function getMeetingsWithXmlResponseArray() {
308
-		/* USAGE:
307
+    public function getMeetingsWithXmlResponseArray() {
308
+        /* USAGE:
309 309
 		We don't need to pass any parameters with this one, so we just send the query URL off to BBB
310 310
 		and then handle the results that we get in the XML response.
311 311
 		*/
312
-		$xml = $this->_processXmlResponse($this->getGetMeetingsUrl());
313
-		if($xml) {
314
-			// If we don't get a success code, stop processing and return just the returncode:
315
-			if ($xml->returncode != 'SUCCESS') {
316
-				$result = array(
317
-					'returncode' => $xml->returncode
318
-				);
319
-				return $result;
320
-			}
321
-			elseif ($xml->messageKey == 'noMeetings') {
322
-				/* No meetings on server, so return just this info: */
323
-				$result = array(
324
-					'returncode' => $xml->returncode,
325
-					'messageKey' => $xml->messageKey,
326
-					'message' => $xml->message
327
-				);
328
-				return $result;
329
-			}
330
-			else {
331
-				// In this case, we have success and meetings. First return general response:
332
-				$result = array(
333
-					'returncode' => $xml->returncode,
334
-					'messageKey' => $xml->messageKey,
335
-					'message' => $xml->message
336
-				);
337
-				// Then interate through meeting results and return them as part of the array:
338
-				foreach ($xml->meetings->meeting as $m) {
339
-					$result[] = array(
340
-						'meetingId' => $m->meetingID,
341
-						'meetingName' => $m->meetingName,
342
-						'createTime' => $m->createTime,
343
-						'attendeePw' => $m->attendeePW,
344
-						'moderatorPw' => $m->moderatorPW,
345
-						'hasBeenForciblyEnded' => $m->hasBeenForciblyEnded,
346
-						'running' => $m->running
347
-						);
348
-					}
349
-				return $result;
350
-			}
351
-		}
352
-		else {
353
-			return null;
354
-		}
355
-
356
-	}
357
-
358
-	public function getMeetingInfoUrl($infoParams) {
359
-		/* USAGE:
312
+        $xml = $this->_processXmlResponse($this->getGetMeetingsUrl());
313
+        if($xml) {
314
+            // If we don't get a success code, stop processing and return just the returncode:
315
+            if ($xml->returncode != 'SUCCESS') {
316
+                $result = array(
317
+                    'returncode' => $xml->returncode
318
+                );
319
+                return $result;
320
+            }
321
+            elseif ($xml->messageKey == 'noMeetings') {
322
+                /* No meetings on server, so return just this info: */
323
+                $result = array(
324
+                    'returncode' => $xml->returncode,
325
+                    'messageKey' => $xml->messageKey,
326
+                    'message' => $xml->message
327
+                );
328
+                return $result;
329
+            }
330
+            else {
331
+                // In this case, we have success and meetings. First return general response:
332
+                $result = array(
333
+                    'returncode' => $xml->returncode,
334
+                    'messageKey' => $xml->messageKey,
335
+                    'message' => $xml->message
336
+                );
337
+                // Then interate through meeting results and return them as part of the array:
338
+                foreach ($xml->meetings->meeting as $m) {
339
+                    $result[] = array(
340
+                        'meetingId' => $m->meetingID,
341
+                        'meetingName' => $m->meetingName,
342
+                        'createTime' => $m->createTime,
343
+                        'attendeePw' => $m->attendeePW,
344
+                        'moderatorPw' => $m->moderatorPW,
345
+                        'hasBeenForciblyEnded' => $m->hasBeenForciblyEnded,
346
+                        'running' => $m->running
347
+                        );
348
+                    }
349
+                return $result;
350
+            }
351
+        }
352
+        else {
353
+            return null;
354
+        }
355
+
356
+    }
357
+
358
+    public function getMeetingInfoUrl($infoParams) {
359
+        /* USAGE:
360 360
 		$infoParams = array(
361 361
 			'meetingId' => '1234',		-- REQUIRED - The unique id for the meeting
362 362
 			'password' => 'mp'			-- REQUIRED - The moderator password for the meeting
363 363
 		);
364 364
 		*/
365
-		$this->_meetingId = $this->_requiredParam($infoParams['meetingId']);
366
-		$this->_password = $this->_requiredParam($infoParams['password']);
367
-		$infoUrl = $this->_bbbServerBaseUrl."api/getMeetingInfo?";
368
-		$params =
369
-		'meetingID='.urlencode($this->_meetingId).
370
-		'&password='.urlencode($this->_password);
371
-		return ($infoUrl.$params.'&checksum='.sha1("getMeetingInfo".$params.$this->_securitySalt));
372
-	}
373
-
374
-	public function getMeetingInfoWithXmlResponseArray($infoParams) {
375
-		/* USAGE:
365
+        $this->_meetingId = $this->_requiredParam($infoParams['meetingId']);
366
+        $this->_password = $this->_requiredParam($infoParams['password']);
367
+        $infoUrl = $this->_bbbServerBaseUrl."api/getMeetingInfo?";
368
+        $params =
369
+        'meetingID='.urlencode($this->_meetingId).
370
+        '&password='.urlencode($this->_password);
371
+        return ($infoUrl.$params.'&checksum='.sha1("getMeetingInfo".$params.$this->_securitySalt));
372
+    }
373
+
374
+    public function getMeetingInfoWithXmlResponseArray($infoParams) {
375
+        /* USAGE:
376 376
 		$infoParams = array(
377 377
 			'meetingId' => '1234',		-- REQUIRED - The unique id for the meeting
378 378
 			'password' => 'mp'			-- REQUIRED - The moderator password for the meeting
379 379
 		);
380 380
 		*/
381
-		$xml = $this->_processXmlResponse($this->getMeetingInfoUrl($infoParams));
382
-		if($xml) {
383
-			// If we don't get a success code or messageKey, find out why:
384
-			if (($xml->returncode != 'SUCCESS') || ($xml->messageKey == null)) {
385
-				$result = array(
386
-					'returncode' => $xml->returncode,
387
-					'messageKey' => $xml->messageKey,
388
-					'message' => $xml->message
389
-				);
390
-				return $result;
391
-			}
392
-			else {
393
-				// In this case, we have success and meeting info:
394
-				$result = array(
395
-					'returncode' => $xml->returncode,
396
-					'meetingName' => $xml->meetingName,
397
-					'meetingId' => $xml->meetingID,
398
-					'createTime' => $xml->createTime,
399
-					'voiceBridge' => $xml->voiceBridge,
400
-					'attendeePw' => $xml->attendeePW,
401
-					'moderatorPw' => $xml->moderatorPW,
402
-					'running' => $xml->running,
403
-					'recording' => $xml->recording,
404
-					'hasBeenForciblyEnded' => $xml->hasBeenForciblyEnded,
405
-					'startTime' => $xml->startTime,
406
-					'endTime' => $xml->endTime,
407
-					'participantCount' => $xml->participantCount,
408
-					'maxUsers' => $xml->maxUsers,
409
-					'moderatorCount' => $xml->moderatorCount,
410
-				);
411
-				// Then interate through attendee results and return them as part of the array:
412
-				foreach ($xml->attendees->attendee as $a) {
413
-					$result[] = array(
414
-						'userId' => $a->userID,
415
-						'fullName' => $a->fullName,
416
-						'role' => $a->role
417
-						);
418
-					}
419
-				return $result;
420
-			}
421
-		}
422
-		else {
423
-			return null;
424
-		}
425
-
426
-	}
427
-
428
-	/* __________________ BBB RECORDING METHODS _________________ */
429
-	/* The methods in the following section support the following categories of the BBB API:
381
+        $xml = $this->_processXmlResponse($this->getMeetingInfoUrl($infoParams));
382
+        if($xml) {
383
+            // If we don't get a success code or messageKey, find out why:
384
+            if (($xml->returncode != 'SUCCESS') || ($xml->messageKey == null)) {
385
+                $result = array(
386
+                    'returncode' => $xml->returncode,
387
+                    'messageKey' => $xml->messageKey,
388
+                    'message' => $xml->message
389
+                );
390
+                return $result;
391
+            }
392
+            else {
393
+                // In this case, we have success and meeting info:
394
+                $result = array(
395
+                    'returncode' => $xml->returncode,
396
+                    'meetingName' => $xml->meetingName,
397
+                    'meetingId' => $xml->meetingID,
398
+                    'createTime' => $xml->createTime,
399
+                    'voiceBridge' => $xml->voiceBridge,
400
+                    'attendeePw' => $xml->attendeePW,
401
+                    'moderatorPw' => $xml->moderatorPW,
402
+                    'running' => $xml->running,
403
+                    'recording' => $xml->recording,
404
+                    'hasBeenForciblyEnded' => $xml->hasBeenForciblyEnded,
405
+                    'startTime' => $xml->startTime,
406
+                    'endTime' => $xml->endTime,
407
+                    'participantCount' => $xml->participantCount,
408
+                    'maxUsers' => $xml->maxUsers,
409
+                    'moderatorCount' => $xml->moderatorCount,
410
+                );
411
+                // Then interate through attendee results and return them as part of the array:
412
+                foreach ($xml->attendees->attendee as $a) {
413
+                    $result[] = array(
414
+                        'userId' => $a->userID,
415
+                        'fullName' => $a->fullName,
416
+                        'role' => $a->role
417
+                        );
418
+                    }
419
+                return $result;
420
+            }
421
+        }
422
+        else {
423
+            return null;
424
+        }
425
+
426
+    }
427
+
428
+    /* __________________ BBB RECORDING METHODS _________________ */
429
+    /* The methods in the following section support the following categories of the BBB API:
430 430
 	-- getRecordings
431 431
 	-- publishRecordings
432 432
 	-- deleteRecordings
433 433
 	*/
434 434
 
435
-	public function getRecordingsUrl($recordingParams) {
436
-		/* USAGE:
435
+    public function getRecordingsUrl($recordingParams) {
436
+        /* USAGE:
437 437
 		$recordingParams = array(
438 438
 			'meetingId' => '1234',		-- OPTIONAL - comma separate if multiple ids
439 439
 		);
440 440
 		*/
441
-		$recordingsUrl = $this->_bbbServerBaseUrl."api/getRecordings?";
442
-		$params = 'meetingID='.urlencode($recordingParams['meetingId']);
443
-		return ($recordingsUrl.$params.'&checksum='.sha1("getRecordings".$params.$this->_securitySalt));
441
+        $recordingsUrl = $this->_bbbServerBaseUrl."api/getRecordings?";
442
+        $params = 'meetingID='.urlencode($recordingParams['meetingId']);
443
+        return ($recordingsUrl.$params.'&checksum='.sha1("getRecordings".$params.$this->_securitySalt));
444 444
 
445
-	}
445
+    }
446 446
 
447
-	public function getRecordingsWithXmlResponseArray($recordingParams) {
448
-		/* USAGE:
447
+    public function getRecordingsWithXmlResponseArray($recordingParams) {
448
+        /* USAGE:
449 449
 		$recordingParams = array(
450 450
 			'meetingId' => '1234',		-- OPTIONAL - comma separate if multiple ids
451 451
 		);
@@ -453,121 +453,121 @@  discard block
 block discarded – undo
453 453
 		when creating a meeting, it will kick users out after the duration. Should
454 454
 		probably be required in user code when 'recording' is set to true.
455 455
 		*/
456
-		$xml = $this->_processXmlResponse($this->getRecordingsUrl($recordingParams));
457
-		if($xml) {
458
-			// If we don't get a success code or messageKey, find out why:
459
-			if (($xml->returncode != 'SUCCESS') || ($xml->messageKey == null)) {
460
-				$result = array(
461
-					'returncode' => $xml->returncode,
462
-					'messageKey' => $xml->messageKey,
463
-					'message' => $xml->message
464
-				);
465
-				return $result;
466
-			}
467
-			else {
468
-				// In this case, we have success and recording info:
469
-				$result = array(
470
-					'returncode' => $xml->returncode,
471
-					'messageKey' => $xml->messageKey,
472
-					'message' => $xml->message
473
-				);
474
-
475
-				foreach ($xml->recordings->recording as $r) {
476
-					$result[] = array(
477
-						'recordId' => $r->recordID,
478
-						'meetingId' => $r->meetingID,
479
-						'name' => $r->name,
480
-						'published' => $r->published,
481
-						'startTime' => $r->startTime,
482
-						'endTime' => $r->endTime,
483
-						'playbackFormatType' => $r->playback->format->type,
484
-						'playbackFormatUrl' => $r->playback->format->url,
485
-						'playbackFormatLength' => $r->playback->format->length,
486
-						'metadataTitle' => $r->metadata->title,
487
-						'metadataSubject' => $r->metadata->subject,
488
-						'metadataDescription' => $r->metadata->description,
489
-						'metadataCreator' => $r->metadata->creator,
490
-						'metadataContributor' => $r->metadata->contributor,
491
-						'metadataLanguage' => $r->metadata->language,
492
-						// Add more here as needed for your app depending on your
493
-						// use of metadata when creating recordings.
494
-						);
495
-					}
496
-				return $result;
497
-			}
498
-		}
499
-		else {
500
-			return null;
501
-		}
502
-	}
503
-
504
-	public function getPublishRecordingsUrl($recordingParams) {
505
-		/* USAGE:
456
+        $xml = $this->_processXmlResponse($this->getRecordingsUrl($recordingParams));
457
+        if($xml) {
458
+            // If we don't get a success code or messageKey, find out why:
459
+            if (($xml->returncode != 'SUCCESS') || ($xml->messageKey == null)) {
460
+                $result = array(
461
+                    'returncode' => $xml->returncode,
462
+                    'messageKey' => $xml->messageKey,
463
+                    'message' => $xml->message
464
+                );
465
+                return $result;
466
+            }
467
+            else {
468
+                // In this case, we have success and recording info:
469
+                $result = array(
470
+                    'returncode' => $xml->returncode,
471
+                    'messageKey' => $xml->messageKey,
472
+                    'message' => $xml->message
473
+                );
474
+
475
+                foreach ($xml->recordings->recording as $r) {
476
+                    $result[] = array(
477
+                        'recordId' => $r->recordID,
478
+                        'meetingId' => $r->meetingID,
479
+                        'name' => $r->name,
480
+                        'published' => $r->published,
481
+                        'startTime' => $r->startTime,
482
+                        'endTime' => $r->endTime,
483
+                        'playbackFormatType' => $r->playback->format->type,
484
+                        'playbackFormatUrl' => $r->playback->format->url,
485
+                        'playbackFormatLength' => $r->playback->format->length,
486
+                        'metadataTitle' => $r->metadata->title,
487
+                        'metadataSubject' => $r->metadata->subject,
488
+                        'metadataDescription' => $r->metadata->description,
489
+                        'metadataCreator' => $r->metadata->creator,
490
+                        'metadataContributor' => $r->metadata->contributor,
491
+                        'metadataLanguage' => $r->metadata->language,
492
+                        // Add more here as needed for your app depending on your
493
+                        // use of metadata when creating recordings.
494
+                        );
495
+                    }
496
+                return $result;
497
+            }
498
+        }
499
+        else {
500
+            return null;
501
+        }
502
+    }
503
+
504
+    public function getPublishRecordingsUrl($recordingParams) {
505
+        /* USAGE:
506 506
 		$recordingParams = array(
507 507
 			'recordId' => '1234',		-- REQUIRED - comma separate if multiple ids
508 508
 			'publish' => 'true',		-- REQUIRED - boolean: true/false
509 509
 		);
510 510
 		*/
511
-		$recordingsUrl = $this->_bbbServerBaseUrl."api/publishRecordings?";
512
-		$params =
513
-		'recordID='.urlencode($recordingParams['recordId']).
514
-		'&publish='.urlencode($recordingParams['publish']);
515
-		return ($recordingsUrl.$params.'&checksum='.sha1("publishRecordings".$params.$this->_securitySalt));
511
+        $recordingsUrl = $this->_bbbServerBaseUrl."api/publishRecordings?";
512
+        $params =
513
+        'recordID='.urlencode($recordingParams['recordId']).
514
+        '&publish='.urlencode($recordingParams['publish']);
515
+        return ($recordingsUrl.$params.'&checksum='.sha1("publishRecordings".$params.$this->_securitySalt));
516 516
 
517
-	}
517
+    }
518 518
 
519
-	public function publishRecordingsWithXmlResponseArray($recordingParams) {
520
-		/* USAGE:
519
+    public function publishRecordingsWithXmlResponseArray($recordingParams) {
520
+        /* USAGE:
521 521
 		$recordingParams = array(
522 522
 			'recordId' => '1234',		-- REQUIRED - comma separate if multiple ids
523 523
 			'publish' => 'true',		-- REQUIRED - boolean: true/false
524 524
 		);
525 525
 		*/
526
-		$xml = $this->_processXmlResponse($this->getPublishRecordingsUrl($recordingParams));
527
-		if($xml) {
528
-			return array(
529
-				'returncode' => $xml->returncode,
530
-				'published' => $xml->published 	// -- Returns true/false.
531
-				);
532
-		}
533
-		else {
534
-			return null;
535
-		}
536
-
537
-
538
-	}
539
-
540
-	public function getDeleteRecordingsUrl($recordingParams) {
541
-		/* USAGE:
526
+        $xml = $this->_processXmlResponse($this->getPublishRecordingsUrl($recordingParams));
527
+        if($xml) {
528
+            return array(
529
+                'returncode' => $xml->returncode,
530
+                'published' => $xml->published 	// -- Returns true/false.
531
+                );
532
+        }
533
+        else {
534
+            return null;
535
+        }
536
+
537
+
538
+    }
539
+
540
+    public function getDeleteRecordingsUrl($recordingParams) {
541
+        /* USAGE:
542 542
 		$recordingParams = array(
543 543
 			'recordId' => '1234',		-- REQUIRED - comma separate if multiple ids
544 544
 		);
545 545
 		*/
546
-		$recordingsUrl = $this->_bbbServerBaseUrl."api/deleteRecordings?";
547
-		$params =
548
-		'recordID='.urlencode($recordingParams['recordId']);
549
-		return ($recordingsUrl.$params.'&checksum='.sha1("deleteRecordings".$params.$this->_securitySalt));
550
-	}
551
-
552
-	public function deleteRecordingsWithXmlResponseArray($recordingParams) {
553
-		/* USAGE:
546
+        $recordingsUrl = $this->_bbbServerBaseUrl."api/deleteRecordings?";
547
+        $params =
548
+        'recordID='.urlencode($recordingParams['recordId']);
549
+        return ($recordingsUrl.$params.'&checksum='.sha1("deleteRecordings".$params.$this->_securitySalt));
550
+    }
551
+
552
+    public function deleteRecordingsWithXmlResponseArray($recordingParams) {
553
+        /* USAGE:
554 554
 		$recordingParams = array(
555 555
 			'recordId' => '1234',		-- REQUIRED - comma separate if multiple ids
556 556
 		);
557 557
 		*/
558 558
 
559
-		$xml = $this->_processXmlResponse($this->getDeleteRecordingsUrl($recordingParams));
560
-		if($xml) {
561
-			return array(
562
-				'returncode' => $xml->returncode,
563
-				'deleted' => $xml->deleted 	// -- Returns true/false.
564
-				);
565
-		}
566
-		else {
567
-			return null;
568
-		}
569
-
570
-	}
559
+        $xml = $this->_processXmlResponse($this->getDeleteRecordingsUrl($recordingParams));
560
+        if($xml) {
561
+            return array(
562
+                'returncode' => $xml->returncode,
563
+                'deleted' => $xml->deleted 	// -- Returns true/false.
564
+                );
565
+        }
566
+        else {
567
+            return null;
568
+        }
569
+
570
+    }
571 571
 
572 572
 
573 573
 
Please login to merge, or discard this patch.
main/inc/lib/formvalidator/Element/receivers.php 1 patch
Indentation   +66 added lines, -66 removed lines patch added patch discarded remove patch
@@ -10,65 +10,65 @@  discard block
 block discarded – undo
10 10
  */
11 11
 class HTML_QuickForm_receivers extends HTML_QuickForm_group
12 12
 {
13
-	/**
14
-	 * Array of all receivers
15
-	 */
16
-	var $receivers;
17
-	/**
18
-	 * Array of selected receivers
19
-	 */
20
-	var $receivers_selected;
21
-	/**
22
-	 * Constructor
23
-	 * @param string $elementName
24
-	 * @param string $elementLabel
25
-	 * @param array $attributes This should contain the keys 'receivers' and
26
-	 * 'receivers_selected'
27
-	 */
28
-	public function __construct($elementName = null, $elementLabel = null, $attributes = null)
29
-	{
30
-		$this->receivers = $attributes['receivers'];
31
-		$this->receivers_selected = $attributes['receivers_selected'];
32
-		unset($attributes['receivers']);
33
-		unset($attributes['receivers_selected']);
34
-		parent::__construct($elementName, $elementLabel, $attributes);
35
-		$this->_persistantFreeze = true;
36
-		$this->_appendName = true;
37
-		$this->_type = 'receivers';
38
-	}
39
-	/**
40
-	 * Create the form elements to build this element group
41
-	 */
42
-	function _createElements()
43
-	{
44
-		$this->_elements[] = new HTML_QuickForm_Radio('receivers', '', get_lang('Everybody'), '0', array ('onclick' => 'javascript:receivers_hide(\'receivers_to\')'));
45
-		$this->_elements[0]->setChecked(true);
46
-		$this->_elements[] = new HTML_QuickForm_Radio('receivers', '', get_lang('SelectGroupsUsers'), '1', array ('onclick' => 'javascript:receivers_show(\'receivers_to\')'));
47
-		$this->_elements[] = new HTML_QuickForm_advmultiselect('to', '', $this->receivers);
48
-		$this->_elements[2]->setSelected($this->receivers_selected);
49
-	}
50
-	/**
51
-	 * HTML representation
52
-	 */
53
-	public function toHtml()
54
-	{
55
-		include_once ('HTML/QuickForm/Renderer/Default.php');
56
-		$this->_separator = '<br/>';
57
-		$renderer = & new HTML_QuickForm_Renderer_Default();
58
-		$renderer->setElementTemplate('{element}');
59
-		$select_boxes = $this->_elements[2];
60
-		$select_boxes->setElementTemplate('<div style="margin-left:20px;display:block;" id="receivers_'.$select_boxes->getName().'">'.$select_boxes->_elementTemplate.'</div>');
61
-		parent :: accept($renderer);
62
-		$js = $this->getElementJS();
63
-		return $renderer->toHtml().$js;
64
-	}
13
+    /**
14
+     * Array of all receivers
15
+     */
16
+    var $receivers;
17
+    /**
18
+     * Array of selected receivers
19
+     */
20
+    var $receivers_selected;
21
+    /**
22
+     * Constructor
23
+     * @param string $elementName
24
+     * @param string $elementLabel
25
+     * @param array $attributes This should contain the keys 'receivers' and
26
+     * 'receivers_selected'
27
+     */
28
+    public function __construct($elementName = null, $elementLabel = null, $attributes = null)
29
+    {
30
+        $this->receivers = $attributes['receivers'];
31
+        $this->receivers_selected = $attributes['receivers_selected'];
32
+        unset($attributes['receivers']);
33
+        unset($attributes['receivers_selected']);
34
+        parent::__construct($elementName, $elementLabel, $attributes);
35
+        $this->_persistantFreeze = true;
36
+        $this->_appendName = true;
37
+        $this->_type = 'receivers';
38
+    }
39
+    /**
40
+     * Create the form elements to build this element group
41
+     */
42
+    function _createElements()
43
+    {
44
+        $this->_elements[] = new HTML_QuickForm_Radio('receivers', '', get_lang('Everybody'), '0', array ('onclick' => 'javascript:receivers_hide(\'receivers_to\')'));
45
+        $this->_elements[0]->setChecked(true);
46
+        $this->_elements[] = new HTML_QuickForm_Radio('receivers', '', get_lang('SelectGroupsUsers'), '1', array ('onclick' => 'javascript:receivers_show(\'receivers_to\')'));
47
+        $this->_elements[] = new HTML_QuickForm_advmultiselect('to', '', $this->receivers);
48
+        $this->_elements[2]->setSelected($this->receivers_selected);
49
+    }
50
+    /**
51
+     * HTML representation
52
+     */
53
+    public function toHtml()
54
+    {
55
+        include_once ('HTML/QuickForm/Renderer/Default.php');
56
+        $this->_separator = '<br/>';
57
+        $renderer = & new HTML_QuickForm_Renderer_Default();
58
+        $renderer->setElementTemplate('{element}');
59
+        $select_boxes = $this->_elements[2];
60
+        $select_boxes->setElementTemplate('<div style="margin-left:20px;display:block;" id="receivers_'.$select_boxes->getName().'">'.$select_boxes->_elementTemplate.'</div>');
61
+        parent :: accept($renderer);
62
+        $js = $this->getElementJS();
63
+        return $renderer->toHtml().$js;
64
+    }
65 65
 
66
-	/**
67
-	 * Get the necessary javascript
68
-	 */
66
+    /**
67
+     * Get the necessary javascript
68
+     */
69 69
     public function getElementJS()
70
-	{
71
-		$js = "<script type=\"text/javascript\">
70
+    {
71
+        $js = "<script type=\"text/javascript\">
72 72
 					/* <![CDATA[ */
73 73
 					receivers_hide('receivers_to');
74 74
 					function receivers_show(item) {
@@ -81,14 +81,14 @@  discard block
 block discarded – undo
81 81
 					}
82 82
 					/* ]]> */
83 83
 					</script>\n";
84
-		return $js;
85
-	}
86
-	/**
87
-	 * accept renderer
88
-	 */
89
-	function accept(& $renderer, $required = false, $error = null)
90
-	{
91
-		$renderer->renderElement($this, $required, $error);
92
-	}
84
+        return $js;
85
+    }
86
+    /**
87
+     * accept renderer
88
+     */
89
+    function accept(& $renderer, $required = false, $error = null)
90
+    {
91
+        $renderer->renderElement($this, $required, $error);
92
+    }
93 93
 }
94 94
 ?>
Please login to merge, or discard this patch.
main/inc/lib/xajax/xajax.inc.php 1 patch
Indentation   +1165 added lines, -1165 removed lines patch added patch discarded remove patch
@@ -47,7 +47,7 @@  discard block
 block discarded – undo
47 47
  */
48 48
 if (!defined ('XAJAX_DEFAULT_CHAR_ENCODING'))
49 49
 {
50
-	define ('XAJAX_DEFAULT_CHAR_ENCODING', 'utf-8' );
50
+    define ('XAJAX_DEFAULT_CHAR_ENCODING', 'utf-8' );
51 51
 }
52 52
 
53 53
 /**
@@ -55,11 +55,11 @@  discard block
 block discarded – undo
55 55
  */
56 56
 if (!defined ('XAJAX_GET'))
57 57
 {
58
-	define ('XAJAX_GET', 0);
58
+    define ('XAJAX_GET', 0);
59 59
 }
60 60
 if (!defined ('XAJAX_POST'))
61 61
 {
62
-	define ('XAJAX_POST', 1);
62
+    define ('XAJAX_POST', 1);
63 63
 }
64 64
 
65 65
 /**
@@ -72,1145 +72,1145 @@  discard block
 block discarded – undo
72 72
  */
73 73
 class xajax
74 74
 {
75
-	/**#@+
75
+    /**#@+
76 76
 	 * @access protected
77 77
 	 */
78
-	/**
79
-	 * @var array Array of PHP functions that will be callable through javascript wrappers
80
-	 */
81
-	var $aFunctions;
82
-	/**
83
-	 * @var array Array of object callbacks that will allow Javascript to call PHP methods (key=function name)
84
-	 */
85
-	var $aObjects;
86
-	/**
87
-	 * @var array Array of RequestTypes to be used with each function (key=function name)
88
-	 */
89
-	var $aFunctionRequestTypes;
90
-	/**
91
-	 * @var array Array of Include Files for any external functions (key=function name)
92
-	 */
93
-	var $aFunctionIncludeFiles;
94
-	/**
95
-	 * @var string Name of the PHP function to call if no callable function was found
96
-	 */
97
-	var $sCatchAllFunction;
98
-	/**
99
-	 * @var string Name of the PHP function to call before any other function
100
-	 */
101
-	var $sPreFunction;
102
-	/**
103
-	 * @var string The URI for making requests to the xajax object
104
-	 */
105
-	var $sRequestURI;
106
-	/**
107
-	 * @var string The prefix to prepend to the javascript wraper function name
108
-	 */
109
-	var $sWrapperPrefix;
110
-	/**
111
-	 * @var boolean Show debug messages (default false)
112
-	 */
113
-	var $bDebug;
114
-	/**
115
-	 * @var boolean Show messages in the client browser's status bar (default false)
116
-	 */
117
-	var $bStatusMessages;
118
-	/**
119
-	 * @var boolean Allow xajax to exit after processing a request (default true)
120
-	 */
121
-	var $bExitAllowed;
122
-	/**
123
-	 * @var boolean Use wait cursor in browser (default true)
124
-	 */
125
-	var $bWaitCursor;
126
-	/**
127
-	 * @var boolean Use an special xajax error handler so the errors are sent to the browser properly (default false)
128
-	 */
129
-	var $bErrorHandler;
130
-	/**
131
-	 * @var string Specify what, if any, file xajax should log errors to (and more information in a future release)
132
-	 */
133
-	var $sLogFile;
134
-	/**
135
-	 * @var boolean Clean all output buffers before outputting response (default false)
136
-	 */
137
-	var $bCleanBuffer;
138
-	/**
139
-	 * @var string String containing the character encoding used
140
-	 */
141
-	var $sEncoding;
142
-	/**
143
-	 * @var boolean Decode input request args from UTF-8 (default false)
144
-	 */
145
-	var $bDecodeUTF8Input;
146
-	/**
147
-	 * @var boolean Convert special characters to HTML entities (default false)
148
-	 */
149
-	var $bOutputEntities;
150
-	/**
151
-	 * @var array Array for parsing complex objects
152
-	 */
153
-	var $aObjArray;
154
-	/**
155
-	 * @var integer Position in $aObjArray
156
-	 */
157
-	var $iPos;
158
-
159
-	/**#@-*/
160
-
161
-	/**
162
-	 * Constructor. You can set some extra xajax options right away or use
163
-	 * individual methods later to set options.
164
-	 *
165
-	 * @param string  defaults to the current browser URI
166
-	 * @param string  defaults to "xajax_";
167
-	 * @param string  defaults to XAJAX_DEFAULT_CHAR_ENCODING defined above
168
-	 * @param boolean defaults to false
169
-	 */
170
-	public function __construct($sRequestURI="",$sWrapperPrefix="xajax_",$sEncoding=XAJAX_DEFAULT_CHAR_ENCODING,$bDebug=false)
171
-	{
172
-		$this->aFunctions = array();
173
-		$this->aObjects = array();
174
-		$this->aFunctionIncludeFiles = array();
175
-		$this->sRequestURI = $sRequestURI;
176
-		if ($this->sRequestURI == "")
177
-			$this->sRequestURI = $this->_detectURI();
178
-		$this->sWrapperPrefix = $sWrapperPrefix;
179
-		$this->bDebug = $bDebug;
180
-		$this->bStatusMessages = false;
181
-		$this->bWaitCursor = true;
182
-		$this->bExitAllowed = true;
183
-		$this->bErrorHandler = false;
184
-		$this->sLogFile = "";
185
-		$this->bCleanBuffer = false;
186
-		$this->setCharEncoding($sEncoding);
187
-		$this->bDecodeUTF8Input = false;
188
-		$this->bOutputEntities = false;
189
-	}
190
-
191
-	/**
192
-	 * Sets the URI to which requests will be made.
193
-	 * <i>Usage:</i> <kbd>$xajax->setRequestURI("http://www.xajaxproject.org");</kbd>
194
-	 *
195
-	 * @param string the URI (can be absolute or relative) of the PHP script
196
-	 *               that will be accessed when an xajax request occurs
197
-	 */
198
-	function setRequestURI($sRequestURI)
199
-	{
200
-		$this->sRequestURI = $sRequestURI;
201
-	}
202
-
203
-	/**
204
-	 * Sets the prefix that will be appended to the Javascript wrapper
205
-	 * functions (default is "xajax_").
206
-	 *
207
-	 * @param string
208
-	 */
209
-	//
210
-	function setWrapperPrefix($sPrefix)
211
-	{
212
-		$this->sWrapperPrefix = $sPrefix;
213
-	}
214
-
215
-	/**
216
-	 * Enables debug messages for xajax.
217
-	 * */
218
-	function debugOn()
219
-	{
220
-		$this->bDebug = true;
221
-	}
222
-
223
-	/**
224
-	 * Disables debug messages for xajax (default behavior).
225
-	 */
226
-	function debugOff()
227
-	{
228
-		$this->bDebug = false;
229
-	}
230
-
231
-	/**
232
-	 * Enables messages in the browser's status bar for xajax.
233
-	 */
234
-	function statusMessagesOn()
235
-	{
236
-		$this->bStatusMessages = true;
237
-	}
238
-
239
-	/**
240
-	 * Disables messages in the browser's status bar for xajax (default behavior).
241
-	 */
242
-	function statusMessagesOff()
243
-	{
244
-		$this->bStatusMessages = false;
245
-	}
246
-
247
-	/**
248
-	 * Enables the wait cursor to be displayed in the browser (default behavior).
249
-	 */
250
-	function waitCursorOn()
251
-	{
252
-		$this->bWaitCursor = true;
253
-	}
254
-
255
-	/**
256
-	 * Disables the wait cursor to be displayed in the browser.
257
-	 */
258
-	function waitCursorOff()
259
-	{
260
-		$this->bWaitCursor = false;
261
-	}
262
-
263
-	/**
264
-	 * Enables xajax to exit immediately after processing a request and
265
-	 * sending the response back to the browser (default behavior).
266
-	 */
267
-	function exitAllowedOn()
268
-	{
269
-		$this->bExitAllowed = true;
270
-	}
271
-
272
-	/**
273
-	 * Disables xajax's default behavior of exiting immediately after
274
-	 * processing a request and sending the response back to the browser.
275
-	 */
276
-	function exitAllowedOff()
277
-	{
278
-		$this->bExitAllowed = false;
279
-	}
280
-
281
-	/**
282
-	 * Turns on xajax's error handling system so that PHP errors that occur
283
-	 * during a request are trapped and pushed to the browser in the form of
284
-	 * a Javascript alert.
285
-	 */
286
-	function errorHandlerOn()
287
-	{
288
-		$this->bErrorHandler = true;
289
-	}
290
-
291
-	/**
292
-	 * Turns off xajax's error handling system (default behavior).
293
-	 */
294
-	function errorHandlerOff()
295
-	{
296
-		$this->bErrorHandler = false;
297
-	}
298
-
299
-	/**
300
-	 * Specifies a log file that will be written to by xajax during a request
301
-	 * (used only by the error handling system at present). If you don't invoke
302
-	 * this method, or you pass in "", then no log file will be written to.
303
-	 * <i>Usage:</i> <kbd>$xajax->setLogFile("/xajax_logs/errors.log");</kbd>
304
-	 */
305
-	function setLogFile($sFilename)
306
-	{
307
-		$this->sLogFile = $sFilename;
308
-	}
309
-
310
-	/**
311
-	 * Causes xajax to clean out all output buffers before outputting a
312
-	 * response (default behavior).
313
-	 */
314
-	function cleanBufferOn()
315
-	{
316
-		$this->bCleanBuffer = true;
317
-	}
318
-	/**
319
-	 * Turns off xajax's output buffer cleaning.
320
-	 */
321
-	function cleanBufferOff()
322
-	{
323
-		$this->bCleanBuffer = false;
324
-	}
325
-
326
-	/**
327
-	 * Sets the character encoding for the HTTP output based on
328
-	 * <kbd>$sEncoding</kbd>, which is a string containing the character
329
-	 * encoding to use. You don't need to use this method normally, since the
330
-	 * character encoding for the response gets set automatically based on the
331
-	 * <kbd>XAJAX_DEFAULT_CHAR_ENCODING</kbd> constant.
332
-	 * <i>Usage:</i> <kbd>$xajax->setCharEncoding("utf-8");</kbd>
333
-	 *
334
-	 * @param string the encoding type to use (utf-8, iso-8859-1, etc.)
335
-	 */
336
-	function setCharEncoding($sEncoding)
337
-	{
338
-		$this->sEncoding = $sEncoding;
339
-	}
340
-
341
-	/**
342
-	 * Causes xajax to decode the input request args from UTF-8 to the current
343
-	 * encoding if possible. Either the iconv or mb_string extension must be
344
-	 * present for optimal functionality.
345
-	 */
346
-	function decodeUTF8InputOn()
347
-	{
348
-		$this->bDecodeUTF8Input = true;
349
-	}
350
-
351
-	/**
352
-	 * Turns off decoding the input request args from UTF-8 (default behavior).
353
-	 */
354
-	function decodeUTF8InputOff()
355
-	{
356
-		$this->bDecodeUTF8Input = false;
357
-	}
358
-
359
-	/**
360
-	 * Tells the response object to convert special characters to HTML entities
361
-	 * automatically (only works if the mb_string extension is available).
362
-	 */
363
-	function outputEntitiesOn()
364
-	{
365
-		$this->bOutputEntities = true;
366
-	}
367
-
368
-	/**
369
-	 * Tells the response object to output special characters intact. (default
370
-	 * behavior).
371
-	 */
372
-	function outputEntitiesOff()
373
-	{
374
-		$this->bOutputEntities = false;
375
-	}
376
-
377
-	/**
378
-	 * Registers a PHP function or method to be callable through xajax in your
379
-	 * Javascript. If you want to register a function, pass in the name of that
380
-	 * function. If you want to register a static class method, pass in an
381
-	 * array like so:
382
-	 * <kbd>array("myFunctionName", "myClass", "myMethod")</kbd>
383
-	 * For an object instance method, use an object variable for the second
384
-	 * array element (and in PHP 4 make sure you put an & before the variable
385
-	 * to pass the object by reference). Note: the function name is what you
386
-	 * call via Javascript, so it can be anything as long as it doesn't
387
-	 * conflict with any other registered function name.
388
-	 *
389
-	 * <i>Usage:</i> <kbd>$xajax->registerFunction("myFunction");</kbd>
390
-	 * or: <kbd>$xajax->registerFunction(array("myFunctionName", &$myObject, "myMethod"));</kbd>
391
-	 *
392
-	 * @param mixed  contains the function name or an object callback array
393
-	 * @param mixed  request type (XAJAX_GET/XAJAX_POST) that should be used
394
-	 *               for this function.  Defaults to XAJAX_POST.
395
-	 */
396
-	function registerFunction($mFunction,$sRequestType=XAJAX_POST)
397
-	{
398
-		if (is_array($mFunction)) {
399
-			$this->aFunctions[$mFunction[0]] = 1;
400
-			$this->aFunctionRequestTypes[$mFunction[0]] = $sRequestType;
401
-			$this->aObjects[$mFunction[0]] = array_slice($mFunction, 1);
402
-		}
403
-		else {
404
-			$this->aFunctions[$mFunction] = 1;
405
-			$this->aFunctionRequestTypes[$mFunction] = $sRequestType;
406
-		}
407
-	}
408
-
409
-	/**
410
-	 * Registers a PHP function to be callable through xajax which is located
411
-	 * in some other file.  If the function is requested the external file will
412
-	 * be included to define the function before the function is called.
413
-	 *
414
-	 * <i>Usage:</i> <kbd>$xajax->registerExternalFunction("myFunction","myFunction.inc.php",XAJAX_POST);</kbd>
415
-	 *
416
-	 * @param string contains the function name or an object callback array
417
-	 *               ({@link xajax::registerFunction() see registerFunction} for
418
-	 *               more info on object callback arrays)
419
-	 * @param string contains the path and filename of the include file
420
-	 * @param mixed  the RequestType (XAJAX_GET/XAJAX_POST) that should be used
421
-	 *		          for this function. Defaults to XAJAX_POST.
422
-	 */
423
-	function registerExternalFunction($mFunction,$sIncludeFile,$sRequestType=XAJAX_POST)
424
-	{
425
-		$this->registerFunction($mFunction, $sRequestType);
426
-
427
-		if (is_array($mFunction)) {
428
-			$this->aFunctionIncludeFiles[$mFunction[0]] = $sIncludeFile;
429
-		}
430
-		else {
431
-			$this->aFunctionIncludeFiles[$mFunction] = $sIncludeFile;
432
-		}
433
-	}
434
-
435
-	/**
436
-	 * Registers a PHP function to be called when xajax cannot find the
437
-	 * function being called via Javascript. Because this is technically
438
-	 * impossible when using "wrapped" functions, the catch-all feature is
439
-	 * only useful when you're directly using the xajax.call() Javascript
440
-	 * method. Use the catch-all feature when you want more dynamic ability to
441
-	 * intercept unknown calls and handle them in a custom way.
442
-	 *
443
-	 * <i>Usage:</i> <kbd>$xajax->registerCatchAllFunction("myCatchAllFunction");</kbd>
444
-	 *
445
-	 * @param string contains the function name or an object callback array
446
-	 *               ({@link xajax::registerFunction() see registerFunction} for
447
-	 *               more info on object callback arrays)
448
-	 */
449
-	function registerCatchAllFunction($mFunction)
450
-	{
451
-		if (is_array($mFunction)) {
452
-			$this->sCatchAllFunction = $mFunction[0];
453
-			$this->aObjects[$mFunction[0]] = array_slice($mFunction, 1);
454
-		}
455
-		else {
456
-			$this->sCatchAllFunction = $mFunction;
457
-		}
458
-	}
459
-
460
-	/**
461
-	 * Registers a PHP function to be called before xajax calls the requested
462
-	 * function. xajax will automatically add the request function's response
463
-	 * to the pre-function's response to create a single response. Another
464
-	 * feature is the ability to return not just a response, but an array with
465
-	 * the first element being false (a boolean) and the second being the
466
-	 * response. In this case, the pre-function's response will be returned to
467
-	 * the browser without xajax calling the requested function.
468
-	 *
469
-	 * <i>Usage:</i> <kbd>$xajax->registerPreFunction("myPreFunction");</kbd>
470
-	 *
471
-	 * @param string contains the function name or an object callback array
472
-	 *               ({@link xajax::registerFunction() see registerFunction} for
473
-	 *               more info on object callback arrays)
474
-	 */
475
-	function registerPreFunction($mFunction)
476
-	{
477
-		if (is_array($mFunction)) {
478
-			$this->sPreFunction = $mFunction[0];
479
-			$this->aObjects[$mFunction[0]] = array_slice($mFunction, 1);
480
-		}
481
-		else {
482
-			$this->sPreFunction = $mFunction;
483
-		}
484
-	}
485
-
486
-	/**
487
-	 * Returns true if xajax can process the request, false if otherwise.
488
-	 * You can use this to determine if xajax needs to process the request or
489
-	 * not.
490
-	 *
491
-	 * @return boolean
492
-	 */
493
-	function canProcessRequests()
494
-	{
495
-		if ($this->getRequestMode() != -1) return true;
496
-		return false;
497
-	}
498
-
499
-	/**
500
-	 * Returns the current request mode (XAJAX_GET or XAJAX_POST), or -1 if
501
-	 * there is none.
502
-	 *
503
-	 * @return mixed
504
-	 */
505
-	function getRequestMode()
506
-	{
507
-		if (!empty($_GET["xajax"]))
508
-			return XAJAX_GET;
509
-
510
-		if (!empty($_POST["xajax"]))
511
-			return XAJAX_POST;
512
-
513
-		return -1;
514
-	}
515
-
516
-	/**
517
-	 * This is the main communications engine of xajax. The engine handles all
518
-	 * incoming xajax requests, calls the apporiate PHP functions (or
519
-	 * class/object methods) and passes the XML responses back to the
520
-	 * Javascript response handler. If your RequestURI is the same as your Web
521
-	 * page then this function should be called before any headers or HTML has
522
-	 * been sent.
523
-	 */
524
-	function processRequests()
525
-	{
526
-
527
-		$requestMode = -1;
528
-		$sFunctionName = "";
529
-		$bFoundFunction = true;
530
-		$bFunctionIsCatchAll = false;
531
-		$sFunctionNameForSpecial = "";
532
-		$aArgs = array();
533
-		$sPreResponse = "";
534
-		$bEndRequest = false;
535
-		$sResponse = "";
536
-
537
-		$requestMode = $this->getRequestMode();
538
-		if ($requestMode == -1) return;
539
-
540
-		if ($requestMode == XAJAX_POST)
541
-		{
542
-			$sFunctionName = $_POST["xajax"];
543
-
544
-			if (!empty($_POST["xajaxargs"]))
545
-				$aArgs = $_POST["xajaxargs"];
546
-		}
547
-		else
548
-		{
549
-			header ("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
550
-			header ("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
551
-			header ("Cache-Control: no-cache, must-revalidate");
552
-			header ("Pragma: no-cache");
553
-
554
-			$sFunctionName = $_GET["xajax"];
555
-
556
-			if (!empty($_GET["xajaxargs"]))
557
-				$aArgs = $_GET["xajaxargs"];
558
-		}
559
-
560
-		// Use xajax error handler if necessary
561
-		if ($this->bErrorHandler) {
562
-			$GLOBALS['xajaxErrorHandlerText'] = "";
563
-			set_error_handler("xajaxErrorHandler");
564
-		}
565
-
566
-		if ($this->sPreFunction) {
567
-			if (!$this->_isFunctionCallable($this->sPreFunction)) {
568
-				$bFoundFunction = false;
569
-				$objResponse = new xajaxResponse();
570
-				$objResponse->addAlert("Unknown Pre-Function ". $this->sPreFunction);
571
-				$sResponse = $objResponse->getXML();
572
-			}
573
-		}
574
-		//include any external dependencies associated with this function name
575
-		if (array_key_exists($sFunctionName,$this->aFunctionIncludeFiles))
576
-		{
577
-			ob_start();
578
-			include_once($this->aFunctionIncludeFiles[$sFunctionName]);
579
-			ob_end_clean();
580
-		}
581
-
582
-		if ($bFoundFunction) {
583
-			$sFunctionNameForSpecial = $sFunctionName;
584
-			if (!array_key_exists($sFunctionName, $this->aFunctions))
585
-			{
586
-				if ($this->sCatchAllFunction) {
587
-					$sFunctionName = $this->sCatchAllFunction;
588
-					$bFunctionIsCatchAll = true;
589
-				}
590
-				else {
591
-					$bFoundFunction = false;
592
-					$objResponse = new xajaxResponse();
593
-					$objResponse->addAlert("Unknown Function $sFunctionName.");
594
-					$sResponse = $objResponse->getXML();
595
-				}
596
-			}
597
-			else if ($this->aFunctionRequestTypes[$sFunctionName] != $requestMode)
598
-			{
599
-				$bFoundFunction = false;
600
-				$objResponse = new xajaxResponse();
601
-				$objResponse->addAlert("Incorrect Request Type.");
602
-				$sResponse = $objResponse->getXML();
603
-			}
604
-		}
605
-
606
-		if ($bFoundFunction)
607
-		{
608
-			for ($i = 0; $i < sizeof($aArgs); $i++)
609
-			{
610
-				// If magic quotes is on, then we need to strip the slashes from the args
611
-				if (get_magic_quotes_gpc() == 1 && is_string($aArgs[$i])) {
612
-
613
-					$aArgs[$i] = stripslashes($aArgs[$i]);
614
-				}
615
-				if (stristr($aArgs[$i],"<xjxobj>") != false)
616
-				{
617
-					$aArgs[$i] = $this->_xmlToArray("xjxobj",$aArgs[$i]);
618
-				}
619
-				else if (stristr($aArgs[$i],"<xjxquery>") != false)
620
-				{
621
-					$aArgs[$i] = $this->_xmlToArray("xjxquery",$aArgs[$i]);
622
-				}
623
-				else if ($this->bDecodeUTF8Input)
624
-				{
625
-					$aArgs[$i] = $this->_decodeUTF8Data($aArgs[$i]);
626
-				}
627
-			}
628
-
629
-			if ($this->sPreFunction) {
630
-				$mPreResponse = $this->_callFunction($this->sPreFunction, array($sFunctionNameForSpecial, $aArgs));
631
-				if (is_array($mPreResponse) && $mPreResponse[0] === false) {
632
-					$bEndRequest = true;
633
-					$sPreResponse = $mPreResponse[1];
634
-				}
635
-				else {
636
-					$sPreResponse = $mPreResponse;
637
-				}
638
-				if (is_a($sPreResponse, "xajaxResponse")) {
639
-					$sPreResponse = $sPreResponse->getXML();
640
-				}
641
-				if ($bEndRequest) $sResponse = $sPreResponse;
642
-			}
643
-
644
-			if (!$bEndRequest) {
645
-				if (!$this->_isFunctionCallable($sFunctionName)) {
646
-					$objResponse = new xajaxResponse();
647
-					$objResponse->addAlert("The Registered Function $sFunctionName Could Not Be Found.");
648
-					$sResponse = $objResponse->getXML();
649
-				}
650
-				else {
651
-					if ($bFunctionIsCatchAll) {
652
-						$aArgs = array($sFunctionNameForSpecial, $aArgs);
653
-					}
654
-					$sResponse = $this->_callFunction($sFunctionName, $aArgs);
655
-				}
656
-				if (is_a($sResponse, "xajaxResponse")) {
657
-					$sResponse = $sResponse->getXML();
658
-				}
659
-				if (!is_string($sResponse) || strpos($sResponse, "<xjx>") === FALSE) {
660
-					$objResponse = new xajaxResponse();
661
-					$objResponse->addAlert("No XML Response Was Returned By Function $sFunctionName.");
662
-					$sResponse = $objResponse->getXML();
663
-				}
664
-				else if ($sPreResponse != "") {
665
-					$sNewResponse = new xajaxResponse($this->sEncoding, $this->bOutputEntities);
666
-					$sNewResponse->loadXML($sPreResponse);
667
-					$sNewResponse->loadXML($sResponse);
668
-					$sResponse = $sNewResponse->getXML();
669
-				}
670
-			}
671
-		}
672
-
673
-		$sContentHeader = "Content-type: text/xml;";
674
-		if ($this->sEncoding && strlen(trim($this->sEncoding)) > 0)
675
-			$sContentHeader .= " charset=".$this->sEncoding;
676
-		header($sContentHeader);
677
-		if ($this->bErrorHandler && !empty( $GLOBALS['xajaxErrorHandlerText'] )) {
678
-			$sErrorResponse = new xajaxResponse();
679
-			$sErrorResponse->addAlert("** PHP Error Messages: **" . $GLOBALS['xajaxErrorHandlerText']);
680
-			if ($this->sLogFile) {
681
-				$fH = @fopen($this->sLogFile, "a");
682
-				if (!$fH) {
683
-					$sErrorResponse->addAlert("** Logging Error **\n\nxajax was unable to write to the error log file:\n" . $this->sLogFile);
684
-				}
685
-				else {
686
-					fwrite($fH, "** xajax Error Log - " . strftime("%b %e %Y %I:%M:%S %p") . " **" . $GLOBALS['xajaxErrorHandlerText'] . "\n\n\n");
687
-					fclose($fH);
688
-				}
689
-			}
690
-
691
-			$sErrorResponse->loadXML($sResponse);
692
-			$sResponse = $sErrorResponse->getXML();
693
-
694
-		}
695
-		if ($this->bCleanBuffer) while (@ob_end_clean());
696
-		print $sResponse;
697
-		if ($this->bErrorHandler) restore_error_handler();
698
-
699
-		if ($this->bExitAllowed)
700
-			exit();
701
-	}
702
-
703
-	/**
704
-	 * Prints the xajax Javascript header and wrapper code into your page by
705
-	 * printing the output of the getJavascript() method. It should only be
706
-	 * called between the <pre><head> </head></pre> tags in your HTML page.
707
-	 * Remember, if you only want to obtain the result of this function, use
708
-	 * {@link xajax::getJavascript()} instead.
709
-	 *
710
-	 * <i>Usage:</i>
711
-	 * <code>
712
-	 *  <head>
713
-	 *		...
714
-	 *		< ?php $xajax->printJavascript(); ? >
715
-	 * </code>
716
-	 *
717
-	 * @param string the relative address of the folder where xajax has been
718
-	 *               installed. For instance, if your PHP file is
719
-	 *               "http://www.myserver.com/myfolder/mypage.php"
720
-	 *               and xajax was installed in
721
-	 *               "http://www.myserver.com/anotherfolder", then $sJsURI
722
-	 *               should be set to "../anotherfolder". Defaults to assuming
723
-	 *               xajax is in the same folder as your PHP file.
724
-	 * @param string the relative folder/file pair of the xajax Javascript
725
-	 *               engine located within the xajax installation folder.
726
-	 *               Defaults to xajax_js/xajax.js.
727
-	 */
728
-	function printJavascript($sJsURI="", $sJsFile=NULL)
729
-	{
730
-		print $this->getJavascript($sJsURI, $sJsFile);
731
-	}
732
-
733
-	/**
734
-	 * Returns the xajax Javascript code that should be added to your HTML page
735
-	 * between the <kbd><head> </head></kbd> tags.
736
-	 *
737
-	 * <i>Usage:</i>
738
-	 * <code>
739
-	 *  < ?php $xajaxJSHead = $xajax->getJavascript(); ? >
740
-	 *	<head>
741
-	 *		...
742
-	 *		< ?php echo $xajaxJSHead; ? >
743
-	 * </code>
744
-	 *
745
-	 * @param string the relative address of the folder where xajax has been
746
-	 *               installed. For instance, if your PHP file is
747
-	 *               "http://www.myserver.com/myfolder/mypage.php"
748
-	 *               and xajax was installed in
749
-	 *               "http://www.myserver.com/anotherfolder", then $sJsURI
750
-	 *               should be set to "../anotherfolder". Defaults to assuming
751
-	 *               xajax is in the same folder as your PHP file.
752
-	 * @param string the relative folder/file pair of the xajax Javascript
753
-	 *               engine located within the xajax installation folder.
754
-	 *               Defaults to xajax_js/xajax.js.
755
-	 * @return string
756
-	 */
757
-	function getJavascript($sJsURI="", $sJsFile=NULL)
758
-	{
759
-		$html = $this->getJavascriptConfig();
760
-		$html .= $this->getJavascriptInclude($sJsURI, $sJsFile);
761
-
762
-		return $html;
763
-	}
764
-
765
-	/**
766
-	 * Returns a string containing inline Javascript that sets up the xajax
767
-	 * runtime (typically called internally by xajax from get/printJavascript).
768
-	 *
769
-	 * @return string
770
-	 */
771
-	function getJavascriptConfig()
772
-	{
773
-		$html  = "\t<script type=\"text/javascript\">\n";
774
-		$html .= "var xajaxRequestUri=\"".$this->sRequestURI."\";\n";
775
-		$html .= "var xajaxDebug=".($this->bDebug?"true":"false").";\n";
776
-		$html .= "var xajaxStatusMessages=".($this->bStatusMessages?"true":"false").";\n";
777
-		$html .= "var xajaxWaitCursor=".($this->bWaitCursor?"true":"false").";\n";
778
-		$html .= "var xajaxDefinedGet=".XAJAX_GET.";\n";
779
-		$html .= "var xajaxDefinedPost=".XAJAX_POST.";\n";
780
-		$html .= "var xajaxLoaded=false;\n";
781
-
782
-		foreach($this->aFunctions as $sFunction => $bExists) {
783
-			$html .= $this->_wrap($sFunction,$this->aFunctionRequestTypes[$sFunction]);
784
-		}
785
-
786
-		$html .= "\t</script>\n";
787
-		return $html;
788
-	}
789
-
790
-	/**
791
-	 * Returns a string containing a Javascript include of the xajax.js file
792
-	 * along with a check to see if the file loaded after six seconds
793
-	 * (typically called internally by xajax from get/printJavascript).
794
-	 *
795
-	 * @param string the relative address of the folder where xajax has been
796
-	 *               installed. For instance, if your PHP file is
797
-	 *               "http://www.myserver.com/myfolder/mypage.php"
798
-	 *               and xajax was installed in
799
-	 *               "http://www.myserver.com/anotherfolder", then $sJsURI
800
-	 *               should be set to "../anotherfolder". Defaults to assuming
801
-	 *               xajax is in the same folder as your PHP file.
802
-	 * @param string the relative folder/file pair of the xajax Javascript
803
-	 *               engine located within the xajax installation folder.
804
-	 *               Defaults to xajax_js/xajax.js.
805
-	 * @return string
806
-	 */
807
-	function getJavascriptInclude($sJsURI="", $sJsFile=NULL)
808
-	{
809
-		if ($sJsFile == NULL) $sJsFile = "xajax_js/xajax.js";
810
-
811
-		if ($sJsURI != "" && substr($sJsURI, -1) != "/") $sJsURI .= "/";
812
-
813
-		$html = "\t<script type=\"text/javascript\" src=\"" . $sJsURI . $sJsFile . "\"></script>\n";
814
-		$html .= "\t<script type=\"text/javascript\">\n";
815
-		$html .= "window.setTimeout(function () { if (!xajaxLoaded) { alert('Error: the xajax Javascript file could not be included. Perhaps the URL is incorrect?\\nURL: {$sJsURI}{$sJsFile}'); } }, 6000);\n";
816
-		$html .= "\t</script>\n";
817
-		return $html;
818
-	}
819
-
820
-	/**
821
-	 * This method can be used to create a new xajax.js file out of the
822
-	 * xajax_uncompressed.js file (which will only happen if xajax.js doesn't
823
-	 * already exist on the filesystem).
824
-	 *
825
-	 * @param string an optional argument containing the full server file path
826
-	 *               of xajax.js.
827
-	 */
828
-	function autoCompressJavascript($sJsFullFilename=NULL)
829
-	{
830
-		$sJsFile = "xajax_js/xajax.js";
831
-
832
-		if ($sJsFullFilename) {
833
-			$realJsFile = $sJsFullFilename;
834
-		}
835
-		else {
836
-			$realPath = realpath(dirname(__FILE__));
837
-			$realJsFile = $realPath . "/". $sJsFile;
838
-		}
839
-
840
-		// Create a compressed file if necessary
841
-		if (!file_exists($realJsFile)) {
842
-			$srcFile = str_replace(".js", "_uncompressed.js", $realJsFile);
843
-			if (!file_exists($srcFile)) {
844
-				trigger_error("The xajax uncompressed Javascript file could not be found in the <b>" . dirname($realJsFile) . "</b> folder. Error ", E_USER_ERROR);
845
-			}
846
-			require(dirname(__FILE__)."/xajaxCompress.php");
847
-			$javaScript = implode('', file($srcFile));
848
-			$compressedScript = xajaxCompressJavascript($javaScript);
849
-			$fH = @fopen($realJsFile, "w");
850
-			if (!$fH) {
851
-				trigger_error("The xajax compressed javascript file could not be written in the <b>" . dirname($realJsFile) . "</b> folder. Error ", E_USER_ERROR);
852
-			}
853
-			else {
854
-				fwrite($fH, $compressedScript);
855
-				fclose($fH);
856
-			}
857
-		}
858
-	}
859
-
860
-	/**
861
-	 * Returns the current URL based upon the SERVER vars.
862
-	 *
863
-	 * @access private
864
-	 * @return string
865
-	 */
866
-	function _detectURI() {
867
-		$aURL = array();
868
-
869
-		// Try to get the request URL
870
-		if (!empty($_SERVER['REQUEST_URI'])) {
871
-			$aURL = parse_url($_SERVER['REQUEST_URI']);
872
-		}
873
-
874
-		// Fill in the empty values
875
-		if (empty($aURL['scheme'])) {
876
-			if (!empty($_SERVER['HTTP_SCHEME'])) {
877
-				$aURL['scheme'] = $_SERVER['HTTP_SCHEME'];
878
-			} else {
879
-				$aURL['scheme'] = (!empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) != 'off') ? 'https' : 'http';
880
-			}
881
-		}
882
-
883
-		if (empty($aURL['host'])) {
884
-			if (!empty($_SERVER['HTTP_HOST'])) {
885
-				if (strpos($_SERVER['HTTP_HOST'], ':') > 0) {
886
-					list($aURL['host'], $aURL['port']) = explode(':', $_SERVER['HTTP_HOST']);
887
-				} else {
888
-					$aURL['host'] = $_SERVER['HTTP_HOST'];
889
-				}
890
-			} else if (!empty($_SERVER['SERVER_NAME'])) {
891
-				$aURL['host'] = $_SERVER['SERVER_NAME'];
892
-			} else {
893
-				print "xajax Error: xajax failed to automatically identify your Request URI.";
894
-				print "Please set the Request URI explicitly when you instantiate the xajax object.";
895
-				exit();
896
-			}
897
-		}
898
-
899
-		if (empty($aURL['port']) && !empty($_SERVER['SERVER_PORT'])) {
900
-			$aURL['port'] = $_SERVER['SERVER_PORT'];
901
-		}
902
-
903
-		if (empty($aURL['path'])) {
904
-			if (!empty($_SERVER['PATH_INFO'])) {
905
-				$sPath = parse_url($_SERVER['PATH_INFO']);
906
-			} else {
907
-				$sPath = parse_url(api_get_self());
908
-			}
909
-			$aURL['path'] = $sPath['path'];
910
-			unset($sPath);
911
-		}
912
-
913
-		if (!empty($aURL['query'])) {
914
-			$aURL['query'] = '?'.$aURL['query'];
915
-		}
916
-
917
-		// Build the URL: Start with scheme, user and pass
918
-		$sURL = $aURL['scheme'].'://';
919
-		if (!empty($aURL['user'])) {
920
-			$sURL.= $aURL['user'];
921
-			if (!empty($aURL['pass'])) {
922
-				$sURL.= ':'.$aURL['pass'];
923
-			}
924
-			$sURL.= '@';
925
-		}
926
-
927
-		// Add the host
928
-		$sURL.= $aURL['host'];
929
-
930
-		// Add the port if needed
931
-		if (!empty($aURL['port']) && (($aURL['scheme'] == 'http' && $aURL['port'] != 80) || ($aURL['scheme'] == 'https' && $aURL['port'] != 443))) {
932
-			$sURL.= ':'.$aURL['port'];
933
-		}
934
-
935
-		// Add the path and the query string
936
-		$sURL.= $aURL['path'].@$aURL['query'];
937
-
938
-		// Clean up
939
-		unset($aURL);
940
-		return $sURL;
941
-	}
942
-
943
-	/**
944
-	 * Returns true if the function name is associated with an object callback,
945
-	 * false if not.
946
-	 *
947
-	 * @param string the name of the function
948
-	 * @access private
949
-	 * @return boolean
950
-	 */
951
-	function _isObjectCallback($sFunction)
952
-	{
953
-		if (array_key_exists($sFunction, $this->aObjects)) return true;
954
-		return false;
955
-	}
956
-
957
-	/**
958
-	 * Returns true if the function or object callback can be called, false if
959
-	 * not.
960
-	 *
961
-	 * @param string the name of the function
962
-	 * @access private
963
-	 * @return boolean
964
-	 */
965
-	function _isFunctionCallable($sFunction)
966
-	{
967
-		if ($this->_isObjectCallback($sFunction)) {
968
-			if (is_object($this->aObjects[$sFunction][0])) {
969
-				return method_exists($this->aObjects[$sFunction][0], $this->aObjects[$sFunction][1]);
970
-			}
971
-			else {
972
-				return is_callable($this->aObjects[$sFunction]);
973
-			}
974
-		}
975
-		else {
976
-			return function_exists($sFunction);
977
-		}
978
-	}
979
-
980
-	/**
981
-	 * Calls the function, class method, or object method with the supplied
982
-	 * arguments.
983
-	 *
984
-	 * @param string the name of the function
985
-	 * @param array  arguments to pass to the function
986
-	 * @access private
987
-	 * @return mixed the output of the called function or method
988
-	 */
989
-	function _callFunction($sFunction, $aArgs)
990
-	{
991
-		if ($this->_isObjectCallback($sFunction)) {
992
-			$mReturn = call_user_func_array($this->aObjects[$sFunction], $aArgs);
993
-		}
994
-		else {
995
-			$mReturn = call_user_func_array($sFunction, $aArgs);
996
-		}
997
-		return $mReturn;
998
-	}
999
-
1000
-	/**
1001
-	 * Generates the Javascript wrapper for the specified PHP function.
1002
-	 *
1003
-	 * @param string the name of the function
1004
-	 * @param mixed  the request type
1005
-	 * @access private
1006
-	 * @return string
1007
-	 */
1008
-	function _wrap($sFunction,$sRequestType=XAJAX_POST)
1009
-	{
1010
-		$js = "function ".$this->sWrapperPrefix."$sFunction(){return xajax.call(\"$sFunction\", arguments, ".$sRequestType.");}\n";
1011
-		return $js;
1012
-	}
1013
-
1014
-	/**
1015
-	 * Takes a string containing xajax xjxobj XML or xjxquery XML and builds an
1016
-	 * array representation of it to pass as an argument to the PHP function
1017
-	 * being called.
1018
-	 *
1019
-	 * @param string the root tag of the XML
1020
-	 * @param string XML to convert
1021
-	 * @access private
1022
-	 * @return array
1023
-	 */
1024
-	function _xmlToArray($rootTag, $sXml)
1025
-	{
1026
-		$aArray = array();
1027
-		$sXml = str_replace("<$rootTag>","<$rootTag>|~|",$sXml);
1028
-		$sXml = str_replace("</$rootTag>","</$rootTag>|~|",$sXml);
1029
-		$sXml = str_replace("<e>","<e>|~|",$sXml);
1030
-		$sXml = str_replace("</e>","</e>|~|",$sXml);
1031
-		$sXml = str_replace("<k>","<k>|~|",$sXml);
1032
-		$sXml = str_replace("</k>","|~|</k>|~|",$sXml);
1033
-		$sXml = str_replace("<v>","<v>|~|",$sXml);
1034
-		$sXml = str_replace("</v>","|~|</v>|~|",$sXml);
1035
-		$sXml = str_replace("<q>","<q>|~|",$sXml);
1036
-		$sXml = str_replace("</q>","|~|</q>|~|",$sXml);
1037
-
1038
-		$this->aObjArray = explode("|~|",$sXml);
1039
-
1040
-		$this->iPos = 0;
1041
-		$aArray = $this->_parseObjXml($rootTag);
1042
-
1043
-		return $aArray;
1044
-	}
1045
-
1046
-	/**
1047
-	 * A recursive function that generates an array from the contents of
1048
-	 * $this->aObjArray.
1049
-	 *
1050
-	 * @param string the root tag of the XML
1051
-	 * @access private
1052
-	 * @return array
1053
-	 */
1054
-	function _parseObjXml($rootTag)
1055
-	{
1056
-		$aArray = array();
1057
-
1058
-		if ($rootTag == "xjxobj")
1059
-		{
1060
-			while(!stristr($this->aObjArray[$this->iPos],"</xjxobj>"))
1061
-			{
1062
-				$this->iPos++;
1063
-				if(stristr($this->aObjArray[$this->iPos],"<e>"))
1064
-				{
1065
-					$key = "";
1066
-					$value = null;
1067
-
1068
-					$this->iPos++;
1069
-					while(!stristr($this->aObjArray[$this->iPos],"</e>"))
1070
-					{
1071
-						if(stristr($this->aObjArray[$this->iPos],"<k>"))
1072
-						{
1073
-							$this->iPos++;
1074
-							while(!stristr($this->aObjArray[$this->iPos],"</k>"))
1075
-							{
1076
-								$key .= $this->aObjArray[$this->iPos];
1077
-								$this->iPos++;
1078
-							}
1079
-						}
1080
-						if(stristr($this->aObjArray[$this->iPos],"<v>"))
1081
-						{
1082
-							$this->iPos++;
1083
-							while(!stristr($this->aObjArray[$this->iPos],"</v>"))
1084
-							{
1085
-								if(stristr($this->aObjArray[$this->iPos],"<xjxobj>"))
1086
-								{
1087
-									$value = $this->_parseObjXml("xjxobj");
1088
-									$this->iPos++;
1089
-								}
1090
-								else
1091
-								{
1092
-									$value .= $this->aObjArray[$this->iPos];
1093
-									if ($this->bDecodeUTF8Input)
1094
-									{
1095
-										$value = $this->_decodeUTF8Data($value);
1096
-									}
1097
-								}
1098
-								$this->iPos++;
1099
-							}
1100
-						}
1101
-						$this->iPos++;
1102
-					}
1103
-
1104
-					$aArray[$key]=$value;
1105
-				}
1106
-			}
1107
-		}
1108
-
1109
-		if ($rootTag == "xjxquery")
1110
-		{
1111
-			$sQuery = "";
1112
-			$this->iPos++;
1113
-			while(!stristr($this->aObjArray[$this->iPos],"</xjxquery>"))
1114
-			{
1115
-				if (stristr($this->aObjArray[$this->iPos],"<q>") || stristr($this->aObjArray[$this->iPos],"</q>"))
1116
-				{
1117
-					$this->iPos++;
1118
-					continue;
1119
-				}
1120
-				$sQuery	.= $this->aObjArray[$this->iPos];
1121
-				$this->iPos++;
1122
-			}
1123
-
1124
-			parse_str($sQuery, $aArray);
1125
-			if ($this->bDecodeUTF8Input)
1126
-			{
1127
-				foreach($aArray as $key => $value)
1128
-				{
1129
-					$aArray[$key] = $this->_decodeUTF8Data($value);
1130
-				}
1131
-			}
1132
-			// If magic quotes is on, then we need to strip the slashes from the
1133
-			// array values because of the parse_str pass which adds slashes
1134
-			if (get_magic_quotes_gpc() == 1) {
1135
-				$newArray = array();
1136
-				foreach ($aArray as $sKey => $sValue) {
1137
-					if (is_string($sValue))
1138
-						$newArray[$sKey] = stripslashes($sValue);
1139
-					else
1140
-						$newArray[$sKey] = $sValue;
1141
-				}
1142
-				$aArray = $newArray;
1143
-			}
1144
-		}
1145
-
1146
-		return $aArray;
1147
-	}
1148
-
1149
-	/**
1150
-	 * Decodes string data from UTF-8 to the current xajax encoding.
1151
-	 *
1152
-	 * @param string data to convert
1153
-	 * @access private
1154
-	 * @return string converted data
1155
-	 */
1156
-	function _decodeUTF8Data($sData)
1157
-	{
1158
-		$sValue = $sData;
1159
-		if ($this->bDecodeUTF8Input)
1160
-		{
1161
-			$sFuncToUse = NULL;
1162
-
1163
-			// An adaptation for the Dokeos LMS, 22-AUG-2009.
1164
-			if (function_exists('api_convert_encoding'))
1165
-			{
1166
-				$sFuncToUse = "api_convert_encoding";
1167
-			}
1168
-			//if (function_exists('iconv'))
1169
-			elseif (function_exists('iconv'))
1170
-			//
1171
-			{
1172
-				$sFuncToUse = "iconv";
1173
-			}
1174
-			else if (function_exists('mb_convert_encoding'))
1175
-			{
1176
-				$sFuncToUse = "mb_convert_encoding";
1177
-			}
1178
-			else if ($this->sEncoding == "ISO-8859-1")
1179
-			{
1180
-				$sFuncToUse = "utf8_decode";
1181
-			}
1182
-			else
1183
-			{
1184
-				trigger_error("The incoming xajax data could not be converted from UTF-8", E_USER_NOTICE);
1185
-			}
1186
-
1187
-			if ($sFuncToUse)
1188
-			{
1189
-				if (is_string($sValue))
1190
-				{
1191
-					if ($sFuncToUse == "iconv")
1192
-					{
1193
-						$sValue = iconv("UTF-8", $this->sEncoding.'//TRANSLIT', $sValue);
1194
-					}
1195
-					else if ($sFuncToUse == "mb_convert_encoding")
1196
-					{
1197
-						$sValue = mb_convert_encoding($sValue, $this->sEncoding, "UTF-8");
1198
-					}
1199
-					// Added code, an adaptation for the Dokeos LMS, 22-AUG-2009.
1200
-					else if ($sFuncToUse == "api_convert_encoding")
1201
-					{
1202
-						$sValue = api_convert_encoding($sValue, $this->sEncoding, "UTF-8");
1203
-					}
1204
-					//
1205
-					else
1206
-					{
1207
-						$sValue = utf8_decode($sValue);
1208
-					}
1209
-				}
1210
-			}
1211
-		}
1212
-		return $sValue;
1213
-	}
78
+    /**
79
+     * @var array Array of PHP functions that will be callable through javascript wrappers
80
+     */
81
+    var $aFunctions;
82
+    /**
83
+     * @var array Array of object callbacks that will allow Javascript to call PHP methods (key=function name)
84
+     */
85
+    var $aObjects;
86
+    /**
87
+     * @var array Array of RequestTypes to be used with each function (key=function name)
88
+     */
89
+    var $aFunctionRequestTypes;
90
+    /**
91
+     * @var array Array of Include Files for any external functions (key=function name)
92
+     */
93
+    var $aFunctionIncludeFiles;
94
+    /**
95
+     * @var string Name of the PHP function to call if no callable function was found
96
+     */
97
+    var $sCatchAllFunction;
98
+    /**
99
+     * @var string Name of the PHP function to call before any other function
100
+     */
101
+    var $sPreFunction;
102
+    /**
103
+     * @var string The URI for making requests to the xajax object
104
+     */
105
+    var $sRequestURI;
106
+    /**
107
+     * @var string The prefix to prepend to the javascript wraper function name
108
+     */
109
+    var $sWrapperPrefix;
110
+    /**
111
+     * @var boolean Show debug messages (default false)
112
+     */
113
+    var $bDebug;
114
+    /**
115
+     * @var boolean Show messages in the client browser's status bar (default false)
116
+     */
117
+    var $bStatusMessages;
118
+    /**
119
+     * @var boolean Allow xajax to exit after processing a request (default true)
120
+     */
121
+    var $bExitAllowed;
122
+    /**
123
+     * @var boolean Use wait cursor in browser (default true)
124
+     */
125
+    var $bWaitCursor;
126
+    /**
127
+     * @var boolean Use an special xajax error handler so the errors are sent to the browser properly (default false)
128
+     */
129
+    var $bErrorHandler;
130
+    /**
131
+     * @var string Specify what, if any, file xajax should log errors to (and more information in a future release)
132
+     */
133
+    var $sLogFile;
134
+    /**
135
+     * @var boolean Clean all output buffers before outputting response (default false)
136
+     */
137
+    var $bCleanBuffer;
138
+    /**
139
+     * @var string String containing the character encoding used
140
+     */
141
+    var $sEncoding;
142
+    /**
143
+     * @var boolean Decode input request args from UTF-8 (default false)
144
+     */
145
+    var $bDecodeUTF8Input;
146
+    /**
147
+     * @var boolean Convert special characters to HTML entities (default false)
148
+     */
149
+    var $bOutputEntities;
150
+    /**
151
+     * @var array Array for parsing complex objects
152
+     */
153
+    var $aObjArray;
154
+    /**
155
+     * @var integer Position in $aObjArray
156
+     */
157
+    var $iPos;
158
+
159
+    /**#@-*/
160
+
161
+    /**
162
+     * Constructor. You can set some extra xajax options right away or use
163
+     * individual methods later to set options.
164
+     *
165
+     * @param string  defaults to the current browser URI
166
+     * @param string  defaults to "xajax_";
167
+     * @param string  defaults to XAJAX_DEFAULT_CHAR_ENCODING defined above
168
+     * @param boolean defaults to false
169
+     */
170
+    public function __construct($sRequestURI="",$sWrapperPrefix="xajax_",$sEncoding=XAJAX_DEFAULT_CHAR_ENCODING,$bDebug=false)
171
+    {
172
+        $this->aFunctions = array();
173
+        $this->aObjects = array();
174
+        $this->aFunctionIncludeFiles = array();
175
+        $this->sRequestURI = $sRequestURI;
176
+        if ($this->sRequestURI == "")
177
+            $this->sRequestURI = $this->_detectURI();
178
+        $this->sWrapperPrefix = $sWrapperPrefix;
179
+        $this->bDebug = $bDebug;
180
+        $this->bStatusMessages = false;
181
+        $this->bWaitCursor = true;
182
+        $this->bExitAllowed = true;
183
+        $this->bErrorHandler = false;
184
+        $this->sLogFile = "";
185
+        $this->bCleanBuffer = false;
186
+        $this->setCharEncoding($sEncoding);
187
+        $this->bDecodeUTF8Input = false;
188
+        $this->bOutputEntities = false;
189
+    }
190
+
191
+    /**
192
+     * Sets the URI to which requests will be made.
193
+     * <i>Usage:</i> <kbd>$xajax->setRequestURI("http://www.xajaxproject.org");</kbd>
194
+     *
195
+     * @param string the URI (can be absolute or relative) of the PHP script
196
+     *               that will be accessed when an xajax request occurs
197
+     */
198
+    function setRequestURI($sRequestURI)
199
+    {
200
+        $this->sRequestURI = $sRequestURI;
201
+    }
202
+
203
+    /**
204
+     * Sets the prefix that will be appended to the Javascript wrapper
205
+     * functions (default is "xajax_").
206
+     *
207
+     * @param string
208
+     */
209
+    //
210
+    function setWrapperPrefix($sPrefix)
211
+    {
212
+        $this->sWrapperPrefix = $sPrefix;
213
+    }
214
+
215
+    /**
216
+     * Enables debug messages for xajax.
217
+     * */
218
+    function debugOn()
219
+    {
220
+        $this->bDebug = true;
221
+    }
222
+
223
+    /**
224
+     * Disables debug messages for xajax (default behavior).
225
+     */
226
+    function debugOff()
227
+    {
228
+        $this->bDebug = false;
229
+    }
230
+
231
+    /**
232
+     * Enables messages in the browser's status bar for xajax.
233
+     */
234
+    function statusMessagesOn()
235
+    {
236
+        $this->bStatusMessages = true;
237
+    }
238
+
239
+    /**
240
+     * Disables messages in the browser's status bar for xajax (default behavior).
241
+     */
242
+    function statusMessagesOff()
243
+    {
244
+        $this->bStatusMessages = false;
245
+    }
246
+
247
+    /**
248
+     * Enables the wait cursor to be displayed in the browser (default behavior).
249
+     */
250
+    function waitCursorOn()
251
+    {
252
+        $this->bWaitCursor = true;
253
+    }
254
+
255
+    /**
256
+     * Disables the wait cursor to be displayed in the browser.
257
+     */
258
+    function waitCursorOff()
259
+    {
260
+        $this->bWaitCursor = false;
261
+    }
262
+
263
+    /**
264
+     * Enables xajax to exit immediately after processing a request and
265
+     * sending the response back to the browser (default behavior).
266
+     */
267
+    function exitAllowedOn()
268
+    {
269
+        $this->bExitAllowed = true;
270
+    }
271
+
272
+    /**
273
+     * Disables xajax's default behavior of exiting immediately after
274
+     * processing a request and sending the response back to the browser.
275
+     */
276
+    function exitAllowedOff()
277
+    {
278
+        $this->bExitAllowed = false;
279
+    }
280
+
281
+    /**
282
+     * Turns on xajax's error handling system so that PHP errors that occur
283
+     * during a request are trapped and pushed to the browser in the form of
284
+     * a Javascript alert.
285
+     */
286
+    function errorHandlerOn()
287
+    {
288
+        $this->bErrorHandler = true;
289
+    }
290
+
291
+    /**
292
+     * Turns off xajax's error handling system (default behavior).
293
+     */
294
+    function errorHandlerOff()
295
+    {
296
+        $this->bErrorHandler = false;
297
+    }
298
+
299
+    /**
300
+     * Specifies a log file that will be written to by xajax during a request
301
+     * (used only by the error handling system at present). If you don't invoke
302
+     * this method, or you pass in "", then no log file will be written to.
303
+     * <i>Usage:</i> <kbd>$xajax->setLogFile("/xajax_logs/errors.log");</kbd>
304
+     */
305
+    function setLogFile($sFilename)
306
+    {
307
+        $this->sLogFile = $sFilename;
308
+    }
309
+
310
+    /**
311
+     * Causes xajax to clean out all output buffers before outputting a
312
+     * response (default behavior).
313
+     */
314
+    function cleanBufferOn()
315
+    {
316
+        $this->bCleanBuffer = true;
317
+    }
318
+    /**
319
+     * Turns off xajax's output buffer cleaning.
320
+     */
321
+    function cleanBufferOff()
322
+    {
323
+        $this->bCleanBuffer = false;
324
+    }
325
+
326
+    /**
327
+     * Sets the character encoding for the HTTP output based on
328
+     * <kbd>$sEncoding</kbd>, which is a string containing the character
329
+     * encoding to use. You don't need to use this method normally, since the
330
+     * character encoding for the response gets set automatically based on the
331
+     * <kbd>XAJAX_DEFAULT_CHAR_ENCODING</kbd> constant.
332
+     * <i>Usage:</i> <kbd>$xajax->setCharEncoding("utf-8");</kbd>
333
+     *
334
+     * @param string the encoding type to use (utf-8, iso-8859-1, etc.)
335
+     */
336
+    function setCharEncoding($sEncoding)
337
+    {
338
+        $this->sEncoding = $sEncoding;
339
+    }
340
+
341
+    /**
342
+     * Causes xajax to decode the input request args from UTF-8 to the current
343
+     * encoding if possible. Either the iconv or mb_string extension must be
344
+     * present for optimal functionality.
345
+     */
346
+    function decodeUTF8InputOn()
347
+    {
348
+        $this->bDecodeUTF8Input = true;
349
+    }
350
+
351
+    /**
352
+     * Turns off decoding the input request args from UTF-8 (default behavior).
353
+     */
354
+    function decodeUTF8InputOff()
355
+    {
356
+        $this->bDecodeUTF8Input = false;
357
+    }
358
+
359
+    /**
360
+     * Tells the response object to convert special characters to HTML entities
361
+     * automatically (only works if the mb_string extension is available).
362
+     */
363
+    function outputEntitiesOn()
364
+    {
365
+        $this->bOutputEntities = true;
366
+    }
367
+
368
+    /**
369
+     * Tells the response object to output special characters intact. (default
370
+     * behavior).
371
+     */
372
+    function outputEntitiesOff()
373
+    {
374
+        $this->bOutputEntities = false;
375
+    }
376
+
377
+    /**
378
+     * Registers a PHP function or method to be callable through xajax in your
379
+     * Javascript. If you want to register a function, pass in the name of that
380
+     * function. If you want to register a static class method, pass in an
381
+     * array like so:
382
+     * <kbd>array("myFunctionName", "myClass", "myMethod")</kbd>
383
+     * For an object instance method, use an object variable for the second
384
+     * array element (and in PHP 4 make sure you put an & before the variable
385
+     * to pass the object by reference). Note: the function name is what you
386
+     * call via Javascript, so it can be anything as long as it doesn't
387
+     * conflict with any other registered function name.
388
+     *
389
+     * <i>Usage:</i> <kbd>$xajax->registerFunction("myFunction");</kbd>
390
+     * or: <kbd>$xajax->registerFunction(array("myFunctionName", &$myObject, "myMethod"));</kbd>
391
+     *
392
+     * @param mixed  contains the function name or an object callback array
393
+     * @param mixed  request type (XAJAX_GET/XAJAX_POST) that should be used
394
+     *               for this function.  Defaults to XAJAX_POST.
395
+     */
396
+    function registerFunction($mFunction,$sRequestType=XAJAX_POST)
397
+    {
398
+        if (is_array($mFunction)) {
399
+            $this->aFunctions[$mFunction[0]] = 1;
400
+            $this->aFunctionRequestTypes[$mFunction[0]] = $sRequestType;
401
+            $this->aObjects[$mFunction[0]] = array_slice($mFunction, 1);
402
+        }
403
+        else {
404
+            $this->aFunctions[$mFunction] = 1;
405
+            $this->aFunctionRequestTypes[$mFunction] = $sRequestType;
406
+        }
407
+    }
408
+
409
+    /**
410
+     * Registers a PHP function to be callable through xajax which is located
411
+     * in some other file.  If the function is requested the external file will
412
+     * be included to define the function before the function is called.
413
+     *
414
+     * <i>Usage:</i> <kbd>$xajax->registerExternalFunction("myFunction","myFunction.inc.php",XAJAX_POST);</kbd>
415
+     *
416
+     * @param string contains the function name or an object callback array
417
+     *               ({@link xajax::registerFunction() see registerFunction} for
418
+     *               more info on object callback arrays)
419
+     * @param string contains the path and filename of the include file
420
+     * @param mixed  the RequestType (XAJAX_GET/XAJAX_POST) that should be used
421
+     *		          for this function. Defaults to XAJAX_POST.
422
+     */
423
+    function registerExternalFunction($mFunction,$sIncludeFile,$sRequestType=XAJAX_POST)
424
+    {
425
+        $this->registerFunction($mFunction, $sRequestType);
426
+
427
+        if (is_array($mFunction)) {
428
+            $this->aFunctionIncludeFiles[$mFunction[0]] = $sIncludeFile;
429
+        }
430
+        else {
431
+            $this->aFunctionIncludeFiles[$mFunction] = $sIncludeFile;
432
+        }
433
+    }
434
+
435
+    /**
436
+     * Registers a PHP function to be called when xajax cannot find the
437
+     * function being called via Javascript. Because this is technically
438
+     * impossible when using "wrapped" functions, the catch-all feature is
439
+     * only useful when you're directly using the xajax.call() Javascript
440
+     * method. Use the catch-all feature when you want more dynamic ability to
441
+     * intercept unknown calls and handle them in a custom way.
442
+     *
443
+     * <i>Usage:</i> <kbd>$xajax->registerCatchAllFunction("myCatchAllFunction");</kbd>
444
+     *
445
+     * @param string contains the function name or an object callback array
446
+     *               ({@link xajax::registerFunction() see registerFunction} for
447
+     *               more info on object callback arrays)
448
+     */
449
+    function registerCatchAllFunction($mFunction)
450
+    {
451
+        if (is_array($mFunction)) {
452
+            $this->sCatchAllFunction = $mFunction[0];
453
+            $this->aObjects[$mFunction[0]] = array_slice($mFunction, 1);
454
+        }
455
+        else {
456
+            $this->sCatchAllFunction = $mFunction;
457
+        }
458
+    }
459
+
460
+    /**
461
+     * Registers a PHP function to be called before xajax calls the requested
462
+     * function. xajax will automatically add the request function's response
463
+     * to the pre-function's response to create a single response. Another
464
+     * feature is the ability to return not just a response, but an array with
465
+     * the first element being false (a boolean) and the second being the
466
+     * response. In this case, the pre-function's response will be returned to
467
+     * the browser without xajax calling the requested function.
468
+     *
469
+     * <i>Usage:</i> <kbd>$xajax->registerPreFunction("myPreFunction");</kbd>
470
+     *
471
+     * @param string contains the function name or an object callback array
472
+     *               ({@link xajax::registerFunction() see registerFunction} for
473
+     *               more info on object callback arrays)
474
+     */
475
+    function registerPreFunction($mFunction)
476
+    {
477
+        if (is_array($mFunction)) {
478
+            $this->sPreFunction = $mFunction[0];
479
+            $this->aObjects[$mFunction[0]] = array_slice($mFunction, 1);
480
+        }
481
+        else {
482
+            $this->sPreFunction = $mFunction;
483
+        }
484
+    }
485
+
486
+    /**
487
+     * Returns true if xajax can process the request, false if otherwise.
488
+     * You can use this to determine if xajax needs to process the request or
489
+     * not.
490
+     *
491
+     * @return boolean
492
+     */
493
+    function canProcessRequests()
494
+    {
495
+        if ($this->getRequestMode() != -1) return true;
496
+        return false;
497
+    }
498
+
499
+    /**
500
+     * Returns the current request mode (XAJAX_GET or XAJAX_POST), or -1 if
501
+     * there is none.
502
+     *
503
+     * @return mixed
504
+     */
505
+    function getRequestMode()
506
+    {
507
+        if (!empty($_GET["xajax"]))
508
+            return XAJAX_GET;
509
+
510
+        if (!empty($_POST["xajax"]))
511
+            return XAJAX_POST;
512
+
513
+        return -1;
514
+    }
515
+
516
+    /**
517
+     * This is the main communications engine of xajax. The engine handles all
518
+     * incoming xajax requests, calls the apporiate PHP functions (or
519
+     * class/object methods) and passes the XML responses back to the
520
+     * Javascript response handler. If your RequestURI is the same as your Web
521
+     * page then this function should be called before any headers or HTML has
522
+     * been sent.
523
+     */
524
+    function processRequests()
525
+    {
526
+
527
+        $requestMode = -1;
528
+        $sFunctionName = "";
529
+        $bFoundFunction = true;
530
+        $bFunctionIsCatchAll = false;
531
+        $sFunctionNameForSpecial = "";
532
+        $aArgs = array();
533
+        $sPreResponse = "";
534
+        $bEndRequest = false;
535
+        $sResponse = "";
536
+
537
+        $requestMode = $this->getRequestMode();
538
+        if ($requestMode == -1) return;
539
+
540
+        if ($requestMode == XAJAX_POST)
541
+        {
542
+            $sFunctionName = $_POST["xajax"];
543
+
544
+            if (!empty($_POST["xajaxargs"]))
545
+                $aArgs = $_POST["xajaxargs"];
546
+        }
547
+        else
548
+        {
549
+            header ("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
550
+            header ("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
551
+            header ("Cache-Control: no-cache, must-revalidate");
552
+            header ("Pragma: no-cache");
553
+
554
+            $sFunctionName = $_GET["xajax"];
555
+
556
+            if (!empty($_GET["xajaxargs"]))
557
+                $aArgs = $_GET["xajaxargs"];
558
+        }
559
+
560
+        // Use xajax error handler if necessary
561
+        if ($this->bErrorHandler) {
562
+            $GLOBALS['xajaxErrorHandlerText'] = "";
563
+            set_error_handler("xajaxErrorHandler");
564
+        }
565
+
566
+        if ($this->sPreFunction) {
567
+            if (!$this->_isFunctionCallable($this->sPreFunction)) {
568
+                $bFoundFunction = false;
569
+                $objResponse = new xajaxResponse();
570
+                $objResponse->addAlert("Unknown Pre-Function ". $this->sPreFunction);
571
+                $sResponse = $objResponse->getXML();
572
+            }
573
+        }
574
+        //include any external dependencies associated with this function name
575
+        if (array_key_exists($sFunctionName,$this->aFunctionIncludeFiles))
576
+        {
577
+            ob_start();
578
+            include_once($this->aFunctionIncludeFiles[$sFunctionName]);
579
+            ob_end_clean();
580
+        }
581
+
582
+        if ($bFoundFunction) {
583
+            $sFunctionNameForSpecial = $sFunctionName;
584
+            if (!array_key_exists($sFunctionName, $this->aFunctions))
585
+            {
586
+                if ($this->sCatchAllFunction) {
587
+                    $sFunctionName = $this->sCatchAllFunction;
588
+                    $bFunctionIsCatchAll = true;
589
+                }
590
+                else {
591
+                    $bFoundFunction = false;
592
+                    $objResponse = new xajaxResponse();
593
+                    $objResponse->addAlert("Unknown Function $sFunctionName.");
594
+                    $sResponse = $objResponse->getXML();
595
+                }
596
+            }
597
+            else if ($this->aFunctionRequestTypes[$sFunctionName] != $requestMode)
598
+            {
599
+                $bFoundFunction = false;
600
+                $objResponse = new xajaxResponse();
601
+                $objResponse->addAlert("Incorrect Request Type.");
602
+                $sResponse = $objResponse->getXML();
603
+            }
604
+        }
605
+
606
+        if ($bFoundFunction)
607
+        {
608
+            for ($i = 0; $i < sizeof($aArgs); $i++)
609
+            {
610
+                // If magic quotes is on, then we need to strip the slashes from the args
611
+                if (get_magic_quotes_gpc() == 1 && is_string($aArgs[$i])) {
612
+
613
+                    $aArgs[$i] = stripslashes($aArgs[$i]);
614
+                }
615
+                if (stristr($aArgs[$i],"<xjxobj>") != false)
616
+                {
617
+                    $aArgs[$i] = $this->_xmlToArray("xjxobj",$aArgs[$i]);
618
+                }
619
+                else if (stristr($aArgs[$i],"<xjxquery>") != false)
620
+                {
621
+                    $aArgs[$i] = $this->_xmlToArray("xjxquery",$aArgs[$i]);
622
+                }
623
+                else if ($this->bDecodeUTF8Input)
624
+                {
625
+                    $aArgs[$i] = $this->_decodeUTF8Data($aArgs[$i]);
626
+                }
627
+            }
628
+
629
+            if ($this->sPreFunction) {
630
+                $mPreResponse = $this->_callFunction($this->sPreFunction, array($sFunctionNameForSpecial, $aArgs));
631
+                if (is_array($mPreResponse) && $mPreResponse[0] === false) {
632
+                    $bEndRequest = true;
633
+                    $sPreResponse = $mPreResponse[1];
634
+                }
635
+                else {
636
+                    $sPreResponse = $mPreResponse;
637
+                }
638
+                if (is_a($sPreResponse, "xajaxResponse")) {
639
+                    $sPreResponse = $sPreResponse->getXML();
640
+                }
641
+                if ($bEndRequest) $sResponse = $sPreResponse;
642
+            }
643
+
644
+            if (!$bEndRequest) {
645
+                if (!$this->_isFunctionCallable($sFunctionName)) {
646
+                    $objResponse = new xajaxResponse();
647
+                    $objResponse->addAlert("The Registered Function $sFunctionName Could Not Be Found.");
648
+                    $sResponse = $objResponse->getXML();
649
+                }
650
+                else {
651
+                    if ($bFunctionIsCatchAll) {
652
+                        $aArgs = array($sFunctionNameForSpecial, $aArgs);
653
+                    }
654
+                    $sResponse = $this->_callFunction($sFunctionName, $aArgs);
655
+                }
656
+                if (is_a($sResponse, "xajaxResponse")) {
657
+                    $sResponse = $sResponse->getXML();
658
+                }
659
+                if (!is_string($sResponse) || strpos($sResponse, "<xjx>") === FALSE) {
660
+                    $objResponse = new xajaxResponse();
661
+                    $objResponse->addAlert("No XML Response Was Returned By Function $sFunctionName.");
662
+                    $sResponse = $objResponse->getXML();
663
+                }
664
+                else if ($sPreResponse != "") {
665
+                    $sNewResponse = new xajaxResponse($this->sEncoding, $this->bOutputEntities);
666
+                    $sNewResponse->loadXML($sPreResponse);
667
+                    $sNewResponse->loadXML($sResponse);
668
+                    $sResponse = $sNewResponse->getXML();
669
+                }
670
+            }
671
+        }
672
+
673
+        $sContentHeader = "Content-type: text/xml;";
674
+        if ($this->sEncoding && strlen(trim($this->sEncoding)) > 0)
675
+            $sContentHeader .= " charset=".$this->sEncoding;
676
+        header($sContentHeader);
677
+        if ($this->bErrorHandler && !empty( $GLOBALS['xajaxErrorHandlerText'] )) {
678
+            $sErrorResponse = new xajaxResponse();
679
+            $sErrorResponse->addAlert("** PHP Error Messages: **" . $GLOBALS['xajaxErrorHandlerText']);
680
+            if ($this->sLogFile) {
681
+                $fH = @fopen($this->sLogFile, "a");
682
+                if (!$fH) {
683
+                    $sErrorResponse->addAlert("** Logging Error **\n\nxajax was unable to write to the error log file:\n" . $this->sLogFile);
684
+                }
685
+                else {
686
+                    fwrite($fH, "** xajax Error Log - " . strftime("%b %e %Y %I:%M:%S %p") . " **" . $GLOBALS['xajaxErrorHandlerText'] . "\n\n\n");
687
+                    fclose($fH);
688
+                }
689
+            }
690
+
691
+            $sErrorResponse->loadXML($sResponse);
692
+            $sResponse = $sErrorResponse->getXML();
693
+
694
+        }
695
+        if ($this->bCleanBuffer) while (@ob_end_clean());
696
+        print $sResponse;
697
+        if ($this->bErrorHandler) restore_error_handler();
698
+
699
+        if ($this->bExitAllowed)
700
+            exit();
701
+    }
702
+
703
+    /**
704
+     * Prints the xajax Javascript header and wrapper code into your page by
705
+     * printing the output of the getJavascript() method. It should only be
706
+     * called between the <pre><head> </head></pre> tags in your HTML page.
707
+     * Remember, if you only want to obtain the result of this function, use
708
+     * {@link xajax::getJavascript()} instead.
709
+     *
710
+     * <i>Usage:</i>
711
+     * <code>
712
+     *  <head>
713
+     *		...
714
+     *		< ?php $xajax->printJavascript(); ? >
715
+     * </code>
716
+     *
717
+     * @param string the relative address of the folder where xajax has been
718
+     *               installed. For instance, if your PHP file is
719
+     *               "http://www.myserver.com/myfolder/mypage.php"
720
+     *               and xajax was installed in
721
+     *               "http://www.myserver.com/anotherfolder", then $sJsURI
722
+     *               should be set to "../anotherfolder". Defaults to assuming
723
+     *               xajax is in the same folder as your PHP file.
724
+     * @param string the relative folder/file pair of the xajax Javascript
725
+     *               engine located within the xajax installation folder.
726
+     *               Defaults to xajax_js/xajax.js.
727
+     */
728
+    function printJavascript($sJsURI="", $sJsFile=NULL)
729
+    {
730
+        print $this->getJavascript($sJsURI, $sJsFile);
731
+    }
732
+
733
+    /**
734
+     * Returns the xajax Javascript code that should be added to your HTML page
735
+     * between the <kbd><head> </head></kbd> tags.
736
+     *
737
+     * <i>Usage:</i>
738
+     * <code>
739
+     *  < ?php $xajaxJSHead = $xajax->getJavascript(); ? >
740
+     *	<head>
741
+     *		...
742
+     *		< ?php echo $xajaxJSHead; ? >
743
+     * </code>
744
+     *
745
+     * @param string the relative address of the folder where xajax has been
746
+     *               installed. For instance, if your PHP file is
747
+     *               "http://www.myserver.com/myfolder/mypage.php"
748
+     *               and xajax was installed in
749
+     *               "http://www.myserver.com/anotherfolder", then $sJsURI
750
+     *               should be set to "../anotherfolder". Defaults to assuming
751
+     *               xajax is in the same folder as your PHP file.
752
+     * @param string the relative folder/file pair of the xajax Javascript
753
+     *               engine located within the xajax installation folder.
754
+     *               Defaults to xajax_js/xajax.js.
755
+     * @return string
756
+     */
757
+    function getJavascript($sJsURI="", $sJsFile=NULL)
758
+    {
759
+        $html = $this->getJavascriptConfig();
760
+        $html .= $this->getJavascriptInclude($sJsURI, $sJsFile);
761
+
762
+        return $html;
763
+    }
764
+
765
+    /**
766
+     * Returns a string containing inline Javascript that sets up the xajax
767
+     * runtime (typically called internally by xajax from get/printJavascript).
768
+     *
769
+     * @return string
770
+     */
771
+    function getJavascriptConfig()
772
+    {
773
+        $html  = "\t<script type=\"text/javascript\">\n";
774
+        $html .= "var xajaxRequestUri=\"".$this->sRequestURI."\";\n";
775
+        $html .= "var xajaxDebug=".($this->bDebug?"true":"false").";\n";
776
+        $html .= "var xajaxStatusMessages=".($this->bStatusMessages?"true":"false").";\n";
777
+        $html .= "var xajaxWaitCursor=".($this->bWaitCursor?"true":"false").";\n";
778
+        $html .= "var xajaxDefinedGet=".XAJAX_GET.";\n";
779
+        $html .= "var xajaxDefinedPost=".XAJAX_POST.";\n";
780
+        $html .= "var xajaxLoaded=false;\n";
781
+
782
+        foreach($this->aFunctions as $sFunction => $bExists) {
783
+            $html .= $this->_wrap($sFunction,$this->aFunctionRequestTypes[$sFunction]);
784
+        }
785
+
786
+        $html .= "\t</script>\n";
787
+        return $html;
788
+    }
789
+
790
+    /**
791
+     * Returns a string containing a Javascript include of the xajax.js file
792
+     * along with a check to see if the file loaded after six seconds
793
+     * (typically called internally by xajax from get/printJavascript).
794
+     *
795
+     * @param string the relative address of the folder where xajax has been
796
+     *               installed. For instance, if your PHP file is
797
+     *               "http://www.myserver.com/myfolder/mypage.php"
798
+     *               and xajax was installed in
799
+     *               "http://www.myserver.com/anotherfolder", then $sJsURI
800
+     *               should be set to "../anotherfolder". Defaults to assuming
801
+     *               xajax is in the same folder as your PHP file.
802
+     * @param string the relative folder/file pair of the xajax Javascript
803
+     *               engine located within the xajax installation folder.
804
+     *               Defaults to xajax_js/xajax.js.
805
+     * @return string
806
+     */
807
+    function getJavascriptInclude($sJsURI="", $sJsFile=NULL)
808
+    {
809
+        if ($sJsFile == NULL) $sJsFile = "xajax_js/xajax.js";
810
+
811
+        if ($sJsURI != "" && substr($sJsURI, -1) != "/") $sJsURI .= "/";
812
+
813
+        $html = "\t<script type=\"text/javascript\" src=\"" . $sJsURI . $sJsFile . "\"></script>\n";
814
+        $html .= "\t<script type=\"text/javascript\">\n";
815
+        $html .= "window.setTimeout(function () { if (!xajaxLoaded) { alert('Error: the xajax Javascript file could not be included. Perhaps the URL is incorrect?\\nURL: {$sJsURI}{$sJsFile}'); } }, 6000);\n";
816
+        $html .= "\t</script>\n";
817
+        return $html;
818
+    }
819
+
820
+    /**
821
+     * This method can be used to create a new xajax.js file out of the
822
+     * xajax_uncompressed.js file (which will only happen if xajax.js doesn't
823
+     * already exist on the filesystem).
824
+     *
825
+     * @param string an optional argument containing the full server file path
826
+     *               of xajax.js.
827
+     */
828
+    function autoCompressJavascript($sJsFullFilename=NULL)
829
+    {
830
+        $sJsFile = "xajax_js/xajax.js";
831
+
832
+        if ($sJsFullFilename) {
833
+            $realJsFile = $sJsFullFilename;
834
+        }
835
+        else {
836
+            $realPath = realpath(dirname(__FILE__));
837
+            $realJsFile = $realPath . "/". $sJsFile;
838
+        }
839
+
840
+        // Create a compressed file if necessary
841
+        if (!file_exists($realJsFile)) {
842
+            $srcFile = str_replace(".js", "_uncompressed.js", $realJsFile);
843
+            if (!file_exists($srcFile)) {
844
+                trigger_error("The xajax uncompressed Javascript file could not be found in the <b>" . dirname($realJsFile) . "</b> folder. Error ", E_USER_ERROR);
845
+            }
846
+            require(dirname(__FILE__)."/xajaxCompress.php");
847
+            $javaScript = implode('', file($srcFile));
848
+            $compressedScript = xajaxCompressJavascript($javaScript);
849
+            $fH = @fopen($realJsFile, "w");
850
+            if (!$fH) {
851
+                trigger_error("The xajax compressed javascript file could not be written in the <b>" . dirname($realJsFile) . "</b> folder. Error ", E_USER_ERROR);
852
+            }
853
+            else {
854
+                fwrite($fH, $compressedScript);
855
+                fclose($fH);
856
+            }
857
+        }
858
+    }
859
+
860
+    /**
861
+     * Returns the current URL based upon the SERVER vars.
862
+     *
863
+     * @access private
864
+     * @return string
865
+     */
866
+    function _detectURI() {
867
+        $aURL = array();
868
+
869
+        // Try to get the request URL
870
+        if (!empty($_SERVER['REQUEST_URI'])) {
871
+            $aURL = parse_url($_SERVER['REQUEST_URI']);
872
+        }
873
+
874
+        // Fill in the empty values
875
+        if (empty($aURL['scheme'])) {
876
+            if (!empty($_SERVER['HTTP_SCHEME'])) {
877
+                $aURL['scheme'] = $_SERVER['HTTP_SCHEME'];
878
+            } else {
879
+                $aURL['scheme'] = (!empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) != 'off') ? 'https' : 'http';
880
+            }
881
+        }
882
+
883
+        if (empty($aURL['host'])) {
884
+            if (!empty($_SERVER['HTTP_HOST'])) {
885
+                if (strpos($_SERVER['HTTP_HOST'], ':') > 0) {
886
+                    list($aURL['host'], $aURL['port']) = explode(':', $_SERVER['HTTP_HOST']);
887
+                } else {
888
+                    $aURL['host'] = $_SERVER['HTTP_HOST'];
889
+                }
890
+            } else if (!empty($_SERVER['SERVER_NAME'])) {
891
+                $aURL['host'] = $_SERVER['SERVER_NAME'];
892
+            } else {
893
+                print "xajax Error: xajax failed to automatically identify your Request URI.";
894
+                print "Please set the Request URI explicitly when you instantiate the xajax object.";
895
+                exit();
896
+            }
897
+        }
898
+
899
+        if (empty($aURL['port']) && !empty($_SERVER['SERVER_PORT'])) {
900
+            $aURL['port'] = $_SERVER['SERVER_PORT'];
901
+        }
902
+
903
+        if (empty($aURL['path'])) {
904
+            if (!empty($_SERVER['PATH_INFO'])) {
905
+                $sPath = parse_url($_SERVER['PATH_INFO']);
906
+            } else {
907
+                $sPath = parse_url(api_get_self());
908
+            }
909
+            $aURL['path'] = $sPath['path'];
910
+            unset($sPath);
911
+        }
912
+
913
+        if (!empty($aURL['query'])) {
914
+            $aURL['query'] = '?'.$aURL['query'];
915
+        }
916
+
917
+        // Build the URL: Start with scheme, user and pass
918
+        $sURL = $aURL['scheme'].'://';
919
+        if (!empty($aURL['user'])) {
920
+            $sURL.= $aURL['user'];
921
+            if (!empty($aURL['pass'])) {
922
+                $sURL.= ':'.$aURL['pass'];
923
+            }
924
+            $sURL.= '@';
925
+        }
926
+
927
+        // Add the host
928
+        $sURL.= $aURL['host'];
929
+
930
+        // Add the port if needed
931
+        if (!empty($aURL['port']) && (($aURL['scheme'] == 'http' && $aURL['port'] != 80) || ($aURL['scheme'] == 'https' && $aURL['port'] != 443))) {
932
+            $sURL.= ':'.$aURL['port'];
933
+        }
934
+
935
+        // Add the path and the query string
936
+        $sURL.= $aURL['path'].@$aURL['query'];
937
+
938
+        // Clean up
939
+        unset($aURL);
940
+        return $sURL;
941
+    }
942
+
943
+    /**
944
+     * Returns true if the function name is associated with an object callback,
945
+     * false if not.
946
+     *
947
+     * @param string the name of the function
948
+     * @access private
949
+     * @return boolean
950
+     */
951
+    function _isObjectCallback($sFunction)
952
+    {
953
+        if (array_key_exists($sFunction, $this->aObjects)) return true;
954
+        return false;
955
+    }
956
+
957
+    /**
958
+     * Returns true if the function or object callback can be called, false if
959
+     * not.
960
+     *
961
+     * @param string the name of the function
962
+     * @access private
963
+     * @return boolean
964
+     */
965
+    function _isFunctionCallable($sFunction)
966
+    {
967
+        if ($this->_isObjectCallback($sFunction)) {
968
+            if (is_object($this->aObjects[$sFunction][0])) {
969
+                return method_exists($this->aObjects[$sFunction][0], $this->aObjects[$sFunction][1]);
970
+            }
971
+            else {
972
+                return is_callable($this->aObjects[$sFunction]);
973
+            }
974
+        }
975
+        else {
976
+            return function_exists($sFunction);
977
+        }
978
+    }
979
+
980
+    /**
981
+     * Calls the function, class method, or object method with the supplied
982
+     * arguments.
983
+     *
984
+     * @param string the name of the function
985
+     * @param array  arguments to pass to the function
986
+     * @access private
987
+     * @return mixed the output of the called function or method
988
+     */
989
+    function _callFunction($sFunction, $aArgs)
990
+    {
991
+        if ($this->_isObjectCallback($sFunction)) {
992
+            $mReturn = call_user_func_array($this->aObjects[$sFunction], $aArgs);
993
+        }
994
+        else {
995
+            $mReturn = call_user_func_array($sFunction, $aArgs);
996
+        }
997
+        return $mReturn;
998
+    }
999
+
1000
+    /**
1001
+     * Generates the Javascript wrapper for the specified PHP function.
1002
+     *
1003
+     * @param string the name of the function
1004
+     * @param mixed  the request type
1005
+     * @access private
1006
+     * @return string
1007
+     */
1008
+    function _wrap($sFunction,$sRequestType=XAJAX_POST)
1009
+    {
1010
+        $js = "function ".$this->sWrapperPrefix."$sFunction(){return xajax.call(\"$sFunction\", arguments, ".$sRequestType.");}\n";
1011
+        return $js;
1012
+    }
1013
+
1014
+    /**
1015
+     * Takes a string containing xajax xjxobj XML or xjxquery XML and builds an
1016
+     * array representation of it to pass as an argument to the PHP function
1017
+     * being called.
1018
+     *
1019
+     * @param string the root tag of the XML
1020
+     * @param string XML to convert
1021
+     * @access private
1022
+     * @return array
1023
+     */
1024
+    function _xmlToArray($rootTag, $sXml)
1025
+    {
1026
+        $aArray = array();
1027
+        $sXml = str_replace("<$rootTag>","<$rootTag>|~|",$sXml);
1028
+        $sXml = str_replace("</$rootTag>","</$rootTag>|~|",$sXml);
1029
+        $sXml = str_replace("<e>","<e>|~|",$sXml);
1030
+        $sXml = str_replace("</e>","</e>|~|",$sXml);
1031
+        $sXml = str_replace("<k>","<k>|~|",$sXml);
1032
+        $sXml = str_replace("</k>","|~|</k>|~|",$sXml);
1033
+        $sXml = str_replace("<v>","<v>|~|",$sXml);
1034
+        $sXml = str_replace("</v>","|~|</v>|~|",$sXml);
1035
+        $sXml = str_replace("<q>","<q>|~|",$sXml);
1036
+        $sXml = str_replace("</q>","|~|</q>|~|",$sXml);
1037
+
1038
+        $this->aObjArray = explode("|~|",$sXml);
1039
+
1040
+        $this->iPos = 0;
1041
+        $aArray = $this->_parseObjXml($rootTag);
1042
+
1043
+        return $aArray;
1044
+    }
1045
+
1046
+    /**
1047
+     * A recursive function that generates an array from the contents of
1048
+     * $this->aObjArray.
1049
+     *
1050
+     * @param string the root tag of the XML
1051
+     * @access private
1052
+     * @return array
1053
+     */
1054
+    function _parseObjXml($rootTag)
1055
+    {
1056
+        $aArray = array();
1057
+
1058
+        if ($rootTag == "xjxobj")
1059
+        {
1060
+            while(!stristr($this->aObjArray[$this->iPos],"</xjxobj>"))
1061
+            {
1062
+                $this->iPos++;
1063
+                if(stristr($this->aObjArray[$this->iPos],"<e>"))
1064
+                {
1065
+                    $key = "";
1066
+                    $value = null;
1067
+
1068
+                    $this->iPos++;
1069
+                    while(!stristr($this->aObjArray[$this->iPos],"</e>"))
1070
+                    {
1071
+                        if(stristr($this->aObjArray[$this->iPos],"<k>"))
1072
+                        {
1073
+                            $this->iPos++;
1074
+                            while(!stristr($this->aObjArray[$this->iPos],"</k>"))
1075
+                            {
1076
+                                $key .= $this->aObjArray[$this->iPos];
1077
+                                $this->iPos++;
1078
+                            }
1079
+                        }
1080
+                        if(stristr($this->aObjArray[$this->iPos],"<v>"))
1081
+                        {
1082
+                            $this->iPos++;
1083
+                            while(!stristr($this->aObjArray[$this->iPos],"</v>"))
1084
+                            {
1085
+                                if(stristr($this->aObjArray[$this->iPos],"<xjxobj>"))
1086
+                                {
1087
+                                    $value = $this->_parseObjXml("xjxobj");
1088
+                                    $this->iPos++;
1089
+                                }
1090
+                                else
1091
+                                {
1092
+                                    $value .= $this->aObjArray[$this->iPos];
1093
+                                    if ($this->bDecodeUTF8Input)
1094
+                                    {
1095
+                                        $value = $this->_decodeUTF8Data($value);
1096
+                                    }
1097
+                                }
1098
+                                $this->iPos++;
1099
+                            }
1100
+                        }
1101
+                        $this->iPos++;
1102
+                    }
1103
+
1104
+                    $aArray[$key]=$value;
1105
+                }
1106
+            }
1107
+        }
1108
+
1109
+        if ($rootTag == "xjxquery")
1110
+        {
1111
+            $sQuery = "";
1112
+            $this->iPos++;
1113
+            while(!stristr($this->aObjArray[$this->iPos],"</xjxquery>"))
1114
+            {
1115
+                if (stristr($this->aObjArray[$this->iPos],"<q>") || stristr($this->aObjArray[$this->iPos],"</q>"))
1116
+                {
1117
+                    $this->iPos++;
1118
+                    continue;
1119
+                }
1120
+                $sQuery	.= $this->aObjArray[$this->iPos];
1121
+                $this->iPos++;
1122
+            }
1123
+
1124
+            parse_str($sQuery, $aArray);
1125
+            if ($this->bDecodeUTF8Input)
1126
+            {
1127
+                foreach($aArray as $key => $value)
1128
+                {
1129
+                    $aArray[$key] = $this->_decodeUTF8Data($value);
1130
+                }
1131
+            }
1132
+            // If magic quotes is on, then we need to strip the slashes from the
1133
+            // array values because of the parse_str pass which adds slashes
1134
+            if (get_magic_quotes_gpc() == 1) {
1135
+                $newArray = array();
1136
+                foreach ($aArray as $sKey => $sValue) {
1137
+                    if (is_string($sValue))
1138
+                        $newArray[$sKey] = stripslashes($sValue);
1139
+                    else
1140
+                        $newArray[$sKey] = $sValue;
1141
+                }
1142
+                $aArray = $newArray;
1143
+            }
1144
+        }
1145
+
1146
+        return $aArray;
1147
+    }
1148
+
1149
+    /**
1150
+     * Decodes string data from UTF-8 to the current xajax encoding.
1151
+     *
1152
+     * @param string data to convert
1153
+     * @access private
1154
+     * @return string converted data
1155
+     */
1156
+    function _decodeUTF8Data($sData)
1157
+    {
1158
+        $sValue = $sData;
1159
+        if ($this->bDecodeUTF8Input)
1160
+        {
1161
+            $sFuncToUse = NULL;
1162
+
1163
+            // An adaptation for the Dokeos LMS, 22-AUG-2009.
1164
+            if (function_exists('api_convert_encoding'))
1165
+            {
1166
+                $sFuncToUse = "api_convert_encoding";
1167
+            }
1168
+            //if (function_exists('iconv'))
1169
+            elseif (function_exists('iconv'))
1170
+            //
1171
+            {
1172
+                $sFuncToUse = "iconv";
1173
+            }
1174
+            else if (function_exists('mb_convert_encoding'))
1175
+            {
1176
+                $sFuncToUse = "mb_convert_encoding";
1177
+            }
1178
+            else if ($this->sEncoding == "ISO-8859-1")
1179
+            {
1180
+                $sFuncToUse = "utf8_decode";
1181
+            }
1182
+            else
1183
+            {
1184
+                trigger_error("The incoming xajax data could not be converted from UTF-8", E_USER_NOTICE);
1185
+            }
1186
+
1187
+            if ($sFuncToUse)
1188
+            {
1189
+                if (is_string($sValue))
1190
+                {
1191
+                    if ($sFuncToUse == "iconv")
1192
+                    {
1193
+                        $sValue = iconv("UTF-8", $this->sEncoding.'//TRANSLIT', $sValue);
1194
+                    }
1195
+                    else if ($sFuncToUse == "mb_convert_encoding")
1196
+                    {
1197
+                        $sValue = mb_convert_encoding($sValue, $this->sEncoding, "UTF-8");
1198
+                    }
1199
+                    // Added code, an adaptation for the Dokeos LMS, 22-AUG-2009.
1200
+                    else if ($sFuncToUse == "api_convert_encoding")
1201
+                    {
1202
+                        $sValue = api_convert_encoding($sValue, $this->sEncoding, "UTF-8");
1203
+                    }
1204
+                    //
1205
+                    else
1206
+                    {
1207
+                        $sValue = utf8_decode($sValue);
1208
+                    }
1209
+                }
1210
+            }
1211
+        }
1212
+        return $sValue;
1213
+    }
1214 1214
 
1215 1215
 }// end class xajax
1216 1216
 
@@ -1220,31 +1220,31 @@  discard block
 block discarded – undo
1220 1220
  */
1221 1221
 function xajaxErrorHandler($errno, $errstr, $errfile, $errline)
1222 1222
 {
1223
-	$errorReporting = error_reporting();
1224
-	if (($errno & $errorReporting) == 0) return;
1225
-
1226
-	if ($errno == E_NOTICE) {
1227
-		$errTypeStr = "NOTICE";
1228
-	}
1229
-	else if ($errno == E_WARNING) {
1230
-		$errTypeStr = "WARNING";
1231
-	}
1232
-	else if ($errno == E_USER_NOTICE) {
1233
-		$errTypeStr = "USER NOTICE";
1234
-	}
1235
-	else if ($errno == E_USER_WARNING) {
1236
-		$errTypeStr = "USER WARNING";
1237
-	}
1238
-	else if ($errno == E_USER_ERROR) {
1239
-		$errTypeStr = "USER FATAL ERROR";
1240
-	}
1241
-	else if ($errno == E_STRICT) {
1242
-		return;
1243
-	}
1244
-	else {
1245
-		$errTypeStr = "UNKNOWN: $errno";
1246
-	}
1247
-	$GLOBALS['xajaxErrorHandlerText'] .= "\n----\n[$errTypeStr] $errstr\nerror in line $errline of file $errfile";
1223
+    $errorReporting = error_reporting();
1224
+    if (($errno & $errorReporting) == 0) return;
1225
+
1226
+    if ($errno == E_NOTICE) {
1227
+        $errTypeStr = "NOTICE";
1228
+    }
1229
+    else if ($errno == E_WARNING) {
1230
+        $errTypeStr = "WARNING";
1231
+    }
1232
+    else if ($errno == E_USER_NOTICE) {
1233
+        $errTypeStr = "USER NOTICE";
1234
+    }
1235
+    else if ($errno == E_USER_WARNING) {
1236
+        $errTypeStr = "USER WARNING";
1237
+    }
1238
+    else if ($errno == E_USER_ERROR) {
1239
+        $errTypeStr = "USER FATAL ERROR";
1240
+    }
1241
+    else if ($errno == E_STRICT) {
1242
+        return;
1243
+    }
1244
+    else {
1245
+        $errTypeStr = "UNKNOWN: $errno";
1246
+    }
1247
+    $GLOBALS['xajaxErrorHandlerText'] .= "\n----\n[$errTypeStr] $errstr\nerror in line $errline of file $errfile";
1248 1248
 }
1249 1249
 
1250 1250
 ?>
Please login to merge, or discard this patch.
main/survey/survey_invite.php 1 patch
Indentation   +93 added lines, -93 removed lines patch added patch discarded remove patch
@@ -18,10 +18,10 @@  discard block
 block discarded – undo
18 18
 $this_section = SECTION_COURSES;
19 19
 
20 20
 if (!api_is_allowed_to_edit(false, true)) {
21
-	Display :: display_header(get_lang('ToolSurvey'));
22
-	Display :: display_error_message(get_lang('NotAllowed'), false);
23
-	Display :: display_footer();
24
-	exit;
21
+    Display :: display_header(get_lang('ToolSurvey'));
22
+    Display :: display_error_message(get_lang('NotAllowed'), false);
23
+    Display :: display_footer();
24
+    exit;
25 25
 }
26 26
 
27 27
 // Database table definitions
@@ -37,15 +37,15 @@  discard block
 block discarded – undo
37 37
 $survey_id = Security::remove_XSS($_GET['survey_id']);
38 38
 $survey_data = SurveyManager::get_survey($survey_id);
39 39
 if (empty($survey_data)) {
40
-	Display :: display_header(get_lang('ToolSurvey'));
41
-	Display :: display_error_message(get_lang('InvallidSurvey'), false);
42
-	Display :: display_footer();
43
-	exit;
40
+    Display :: display_header(get_lang('ToolSurvey'));
41
+    Display :: display_error_message(get_lang('InvallidSurvey'), false);
42
+    Display :: display_footer();
43
+    exit;
44 44
 }
45 45
 
46 46
 $urlname = strip_tags(api_substr(api_html_entity_decode($survey_data['title'], ENT_QUOTES), 0, 40));
47 47
 if (api_strlen(strip_tags($survey_data['title'])) > 40) {
48
-	$urlname .= '...';
48
+    $urlname .= '...';
49 49
 }
50 50
 
51 51
 // Breadcrumbs
@@ -80,23 +80,23 @@  discard block
 block discarded – undo
80 80
 		WHERE c_id = $course_id AND code='".Database::escape_string($survey_data['code'])."'";
81 81
 $result = Database::query($sql);
82 82
 if (Database::num_rows($result) > 1) {
83
-	Display::display_warning_message(get_lang('IdenticalSurveycodeWarning'));
83
+    Display::display_warning_message(get_lang('IdenticalSurveycodeWarning'));
84 84
 }
85 85
 
86 86
 // Invited / answered message
87 87
 if ($survey_data['invited'] > 0 && !isset($_POST['submit'])) {
88
-	$message  = '<a href="'.api_get_path(WEB_CODE_PATH).'survey/survey_invitation.php?view=answered&survey_id='.$survey_data['survey_id'].'">'.$survey_data['answered'].'</a> ';
89
-	$message .= get_lang('HaveAnswered').' ';
90
-	$message .= '<a href="'.api_get_path(WEB_CODE_PATH).'survey/survey_invitation.php?view=invited&survey_id='.$survey_data['survey_id'].'">'.$survey_data['invited'].'</a> ';
91
-	$message .= get_lang('WereInvited');
92
-	Display::display_normal_message($message, false);
88
+    $message  = '<a href="'.api_get_path(WEB_CODE_PATH).'survey/survey_invitation.php?view=answered&survey_id='.$survey_data['survey_id'].'">'.$survey_data['answered'].'</a> ';
89
+    $message .= get_lang('HaveAnswered').' ';
90
+    $message .= '<a href="'.api_get_path(WEB_CODE_PATH).'survey/survey_invitation.php?view=invited&survey_id='.$survey_data['survey_id'].'">'.$survey_data['invited'].'</a> ';
91
+    $message .= get_lang('WereInvited');
92
+    Display::display_normal_message($message, false);
93 93
 }
94 94
 
95 95
 // Building the form for publishing the survey
96 96
 $form = new FormValidator(
97
-	'publish_form',
98
-	'post',
99
-	api_get_self().'?survey_id='.$survey_id.'&'.api_get_cidreq()
97
+    'publish_form',
98
+    'post',
99
+    api_get_self().'?survey_id='.$survey_id.'&'.api_get_cidreq()
100 100
 );
101 101
 $form->addElement('header', '', $tool_name);
102 102
 
@@ -109,7 +109,7 @@  discard block
 block discarded – undo
109 109
 );
110 110
 $possible_users = array();
111 111
 foreach ($complete_user_list as & $user) {
112
-	$possible_users[$user['user_id']] = api_get_person_name($user['firstname'], $user['lastname']);
112
+    $possible_users[$user['user_id']] = api_get_person_name($user['firstname'], $user['lastname']);
113 113
 }
114 114
 
115 115
 
@@ -125,10 +125,10 @@  discard block
 block discarded – undo
125 125
 
126 126
 // Additional users
127 127
 $form->addElement(
128
-	'textarea',
129
-	'additional_users',
130
-	array(get_lang('AdditonalUsers'), get_lang('AdditonalUsersComment')),
131
-	array('rows' => 5)
128
+    'textarea',
129
+    'additional_users',
130
+    array(get_lang('AdditonalUsers'), get_lang('AdditonalUsersComment')),
131
+    array('rows' => 5)
132 132
 );
133 133
 
134 134
 $form->addElement('html', '<div id="check_mail">');
@@ -141,15 +141,15 @@  discard block
 block discarded – undo
141 141
 $form->addText('mail_title', get_lang('MailTitle'), false);
142 142
 // The text of the mail
143 143
 $form->addHtmlEditor(
144
-	'mail_text',
145
-	array(get_lang('MailText'), get_lang('UseLinkSyntax')),
146
-	false,
147
-	array('ToolbarSet' => 'Survey', 'Height' => '150')
144
+    'mail_text',
145
+    array(get_lang('MailText'), get_lang('UseLinkSyntax')),
146
+    false,
147
+    array('ToolbarSet' => 'Survey', 'Height' => '150')
148 148
 );
149 149
 $form->addElement('html', '</div>');
150 150
 // You cab send a reminder to unanswered people if the survey is not anonymous
151 151
 if ($survey_data['anonymous'] != 1) {
152
-	$form->addElement('checkbox', 'remindUnAnswered', '', get_lang('RemindUnanswered'));
152
+    $form->addElement('checkbox', 'remindUnAnswered', '', get_lang('RemindUnanswered'));
153 153
 }
154 154
 // Allow resending to all selected users
155 155
 $form->addElement('checkbox', 'resend_to_all', '', get_lang('ReminderResendToAllUsers'));
@@ -163,11 +163,11 @@  discard block
 block discarded – undo
163 163
 }*/
164 164
 $portal_url = api_get_path(WEB_PATH);
165 165
 if (api_is_multiple_url_enabled()) {
166
-	$access_url_id = api_get_current_access_url_id();
167
-	if ($access_url_id != -1) {
168
-		$url = api_get_access_url($access_url_id);
169
-		$portal_url = $url['url'];
170
-	}
166
+    $access_url_id = api_get_current_access_url_id();
167
+    if ($access_url_id != -1) {
168
+        $url = api_get_access_url($access_url_id);
169
+        $portal_url = $url['url'];
170
+    }
171 171
 }
172 172
 
173 173
 // Show the URL that can be used by users to fill a survey without invitation
@@ -177,56 +177,56 @@  discard block
 block discarded – undo
177 177
 $form->addElement('label', null, $auto_survey_link);
178 178
 
179 179
 if ($form->validate()) {
180
-   	$values = $form->exportValues();
180
+        $values = $form->exportValues();
181 181
     if (isset($values['send_mail']) && $values['send_mail'] == 1) {
182 182
         if (empty($values['mail_title']) || empty($values['mail_text'])) {
183 183
             Display :: display_error_message(get_lang('FormHasErrorsPleaseComplete'));
184 184
             // Getting the invited users
185
-        	$defaults = SurveyUtil::get_invited_users($survey_data['code']);
186
-
187
-        	// Getting the survey mail text
188
-        	if (!empty($survey_data['reminder_mail'])) {
189
-        		$defaults['mail_text'] = $survey_data['reminder_mail'];
190
-        	} else {
191
-        		$defaults['mail_text'] = $survey_data['invite_mail'];
192
-        	}
193
-        	$defaults['mail_title'] = $survey_data['mail_subject'];
194
-        	$defaults['send_mail'] = 1;
195
-        	$form->setDefaults($defaults);
185
+            $defaults = SurveyUtil::get_invited_users($survey_data['code']);
186
+
187
+            // Getting the survey mail text
188
+            if (!empty($survey_data['reminder_mail'])) {
189
+                $defaults['mail_text'] = $survey_data['reminder_mail'];
190
+            } else {
191
+                $defaults['mail_text'] = $survey_data['invite_mail'];
192
+            }
193
+            $defaults['mail_title'] = $survey_data['mail_subject'];
194
+            $defaults['send_mail'] = 1;
195
+            $form->setDefaults($defaults);
196 196
             $form->display();
197 197
             return;
198 198
         }
199 199
     }
200 200
     // Save the invitation mail
201
-	SurveyUtil::save_invite_mail(
202
-		$values['mail_text'],
203
-		$values['mail_title'],
204
-		!empty($survey_data['invite_mail'])
205
-	);
201
+    SurveyUtil::save_invite_mail(
202
+        $values['mail_text'],
203
+        $values['mail_title'],
204
+        !empty($survey_data['invite_mail'])
205
+    );
206 206
 
207 207
     $resendAll = isset($values['resend_to_all']) ? $values['resend_to_all'] : '';
208 208
     $sendMail = isset($values['send_mail']) ? $values['send_mail'] : '';
209 209
     $remindUnAnswered = isset($values['remindUnAnswered']) ? $values['remindUnAnswered'] : '';
210 210
 
211
-	// Saving the invitations for the course users
212
-	$count_course_users = SurveyUtil::saveInvitations(
213
-		$values['users'],
214
-		$values['mail_title'],
215
-		$values['mail_text'],
211
+    // Saving the invitations for the course users
212
+    $count_course_users = SurveyUtil::saveInvitations(
213
+        $values['users'],
214
+        $values['mail_title'],
215
+        $values['mail_text'],
216 216
         $resendAll,
217 217
         $sendMail,
218 218
         $remindUnAnswered
219
-	);
219
+    );
220 220
 
221
-	// Saving the invitations for the additional users
222
-	$values['additional_users'] = $values['additional_users'].';'; 	// This is for the case when you enter only one email
223
-	$temp = str_replace(',', ';', $values['additional_users']);		// This is to allow , and ; as email separators
224
-	$additional_users = explode(';', $temp);
225
-	for ($i = 0; $i < count($additional_users); $i++) {
226
-		$additional_users[$i] = trim($additional_users[$i]);
227
-	}
221
+    // Saving the invitations for the additional users
222
+    $values['additional_users'] = $values['additional_users'].';'; 	// This is for the case when you enter only one email
223
+    $temp = str_replace(',', ';', $values['additional_users']);		// This is to allow , and ; as email separators
224
+    $additional_users = explode(';', $temp);
225
+    for ($i = 0; $i < count($additional_users); $i++) {
226
+        $additional_users[$i] = trim($additional_users[$i]);
227
+    }
228 228
 
229
-	$counter_additional_users = SurveyUtil::saveInvitations(
229
+    $counter_additional_users = SurveyUtil::saveInvitations(
230 230
         $additional_users,
231 231
         $values['mail_title'],
232 232
         $values['mail_text'],
@@ -235,43 +235,43 @@  discard block
 block discarded – undo
235 235
         $remindUnAnswered
236 236
     );
237 237
 
238
-	// Updating the invited field in the survey table
239
-	SurveyUtil::update_count_invited($survey_data['code']);
240
-	$total_count = $count_course_users + $counter_additional_users;
238
+    // Updating the invited field in the survey table
239
+    SurveyUtil::update_count_invited($survey_data['code']);
240
+    $total_count = $count_course_users + $counter_additional_users;
241 241
     $table_survey = Database :: get_course_table(TABLE_SURVEY);
242
-	// Counting the number of people that are invited
243
-	$sql = "SELECT * FROM $table_survey
242
+    // Counting the number of people that are invited
243
+    $sql = "SELECT * FROM $table_survey
244 244
 	        WHERE
245 245
 	        	c_id = $course_id AND
246 246
 	        	code = '".Database::escape_string($survey_data['code'])."'
247 247
 			";
248
-	$result = Database::query($sql);
249
-	$row = Database::fetch_array($result);
250
-	$total_invited = $row['invited'];
248
+    $result = Database::query($sql);
249
+    $row = Database::fetch_array($result);
250
+    $total_invited = $row['invited'];
251 251
     if ($total_invited > 0) {
252
-    	$message  = '<a href="'.api_get_path(WEB_CODE_PATH).'survey/survey_invitation.php?view=answered&survey_id='.$survey_data['survey_id'].'">'.
253
-			$survey_data['answered'].'</a> ';
254
-    	$message .= get_lang('HaveAnswered').' ';
255
-    	$message .= '<a href="'.api_get_path(WEB_CODE_PATH).'survey/survey_invitation.php?view=invited&survey_id='.$survey_data['survey_id'].'">'.
256
-			$total_invited.'</a> ';
257
-    	$message .= get_lang('WereInvited');
258
-    	Display::display_normal_message($message, false);
259
-    	Display::display_confirmation_message($total_count.' '.get_lang('InvitationsSend'));
252
+        $message  = '<a href="'.api_get_path(WEB_CODE_PATH).'survey/survey_invitation.php?view=answered&survey_id='.$survey_data['survey_id'].'">'.
253
+            $survey_data['answered'].'</a> ';
254
+        $message .= get_lang('HaveAnswered').' ';
255
+        $message .= '<a href="'.api_get_path(WEB_CODE_PATH).'survey/survey_invitation.php?view=invited&survey_id='.$survey_data['survey_id'].'">'.
256
+            $total_invited.'</a> ';
257
+        $message .= get_lang('WereInvited');
258
+        Display::display_normal_message($message, false);
259
+        Display::display_confirmation_message($total_count.' '.get_lang('InvitationsSend'));
260 260
     }
261 261
 } else {
262
-	// Getting the invited users
263
-	$defaults = SurveyUtil::get_invited_users($survey_data['code']);
264
-
265
-	// Getting the survey mail text
266
-	if (!empty($survey_data['reminder_mail'])) {
267
-		$defaults['mail_text'] = $survey_data['reminder_mail'];
268
-	} else {
269
-		$defaults['mail_text'] = $survey_data['invite_mail'];
270
-	}
271
-	$defaults['mail_title'] = $survey_data['mail_subject'];
272
-	$defaults['send_mail'] = 1;
273
-
274
-	$form->setDefaults($defaults);
262
+    // Getting the invited users
263
+    $defaults = SurveyUtil::get_invited_users($survey_data['code']);
264
+
265
+    // Getting the survey mail text
266
+    if (!empty($survey_data['reminder_mail'])) {
267
+        $defaults['mail_text'] = $survey_data['reminder_mail'];
268
+    } else {
269
+        $defaults['mail_text'] = $survey_data['invite_mail'];
270
+    }
271
+    $defaults['mail_title'] = $survey_data['mail_subject'];
272
+    $defaults['send_mail'] = 1;
273
+
274
+    $form->setDefaults($defaults);
275 275
     $form->display();
276 276
 }
277 277
 Display :: display_footer();
Please login to merge, or discard this patch.
main/inc/lib/formvalidator/Element/SelectTheme.php 1 patch
Indentation   +13 added lines, -13 removed lines patch added patch discarded remove patch
@@ -6,19 +6,19 @@
 block discarded – undo
6 6
 */
7 7
 class SelectTheme extends HTML_QuickForm_select
8 8
 {
9
-	/**
10
-	 * Class constructor
11
-	 */
9
+    /**
10
+     * Class constructor
11
+     */
12 12
     public function __construct($elementName = null, $elementLabel = null, $options = null, $attributes = null)
13 13
     {
14
-		parent::__construct($elementName, $elementLabel, $options, $attributes);
15
-		// Get all languages
16
-		$themes = api_get_themes();
17
-		$this->_options = array();
18
-		$this->_values = array();
19
-		$this->addOption('--',''); // no theme select
20
-		for ($i=0; $i < count($themes[0]); $i++) {
21
-			$this->addOption($themes[1][$i],$themes[0][$i]);
22
-		}
23
-	}
14
+        parent::__construct($elementName, $elementLabel, $options, $attributes);
15
+        // Get all languages
16
+        $themes = api_get_themes();
17
+        $this->_options = array();
18
+        $this->_values = array();
19
+        $this->addOption('--',''); // no theme select
20
+        for ($i=0; $i < count($themes[0]); $i++) {
21
+            $this->addOption($themes[1][$i],$themes[0][$i]);
22
+        }
23
+    }
24 24
 }
Please login to merge, or discard this patch.
main/exercice/exercise_submit.php 1 patch
Indentation   +188 added lines, -188 removed lines patch added patch discarded remove patch
@@ -116,7 +116,7 @@  discard block
 block discarded – undo
116 116
     if (!$objExercise->read($exerciseId) ||
117 117
         (!$objExercise->selectStatus() && !$is_allowedToEdit && $origin != 'learnpath')
118 118
     ) {
119
-    	if ($debug) {error_log('1.1. Error while reading the exercise'); };
119
+        if ($debug) {error_log('1.1. Error while reading the exercise'); };
120 120
         unset ($objExercise);
121 121
         $error = get_lang('ExerciseNotFound');
122 122
     } else {
@@ -129,13 +129,13 @@  discard block
 block discarded – undo
129 129
 }
130 130
 //2. Checking if $objExercise is set
131 131
 if (!isset($objExercise) && isset($exerciseInSession)) {
132
-	if ($debug) { error_log('2. Loading $objExercise from session'); };
132
+    if ($debug) { error_log('2. Loading $objExercise from session'); };
133 133
     $objExercise = $exerciseInSession;
134 134
 }
135 135
 
136 136
 //3. $objExercise is not set, then return to the exercise list
137 137
 if (!is_object($objExercise)) {
138
-	if ($debug) {error_log('3. $objExercise was not set, kill the script'); };
138
+    if ($debug) {error_log('3. $objExercise was not set, kill the script'); };
139 139
     header('Location: exercise.php');
140 140
     exit;
141 141
 }
@@ -156,7 +156,7 @@  discard block
 block discarded – undo
156 156
 
157 157
 $time_control = false;
158 158
 if ($objExercise->expired_time != 0) {
159
-	$time_control = true;
159
+    $time_control = true;
160 160
 }
161 161
 
162 162
 // Generating the time control key for the user
@@ -165,14 +165,14 @@  discard block
 block discarded – undo
165 165
 $_SESSION['duration_time'][$current_expired_time_key] = $current_timestamp;
166 166
 
167 167
 if ($time_control) {
168
-	// Get the expired time of the current exercise in track_e_exercises
169
-	$total_seconds = $objExercise->expired_time*60;
168
+    // Get the expired time of the current exercise in track_e_exercises
169
+    $total_seconds = $objExercise->expired_time*60;
170 170
 }
171 171
 
172 172
 $show_clock = true;
173 173
 $user_id = api_get_user_id();
174 174
 if ($objExercise->selectAttempts() > 0) {
175
-	$attempt_html = '';
175
+    $attempt_html = '';
176 176
     $attempt_count = Event::get_attempt_count(
177 177
         $user_id,
178 178
         $exerciseId,
@@ -181,9 +181,9 @@  discard block
 block discarded – undo
181 181
         $learnpath_item_view_id
182 182
     );
183 183
 
184
-	if ($attempt_count >= $objExercise->selectAttempts()) {
185
-		$show_clock = false;
186
-		if (!api_is_allowed_to_edit(null,true)) {
184
+    if ($attempt_count >= $objExercise->selectAttempts()) {
185
+        $show_clock = false;
186
+        if (!api_is_allowed_to_edit(null,true)) {
187 187
             if ($objExercise->results_disabled == 0 && $origin != 'learnpath') {
188 188
 
189 189
                 // Showing latest attempt according with task BT#1628
@@ -222,31 +222,31 @@  discard block
 block discarded – undo
222 222
                             $attempt_html .= Display::div(get_lang('Score').' '.$marks, array('id'=>'question_question_titlescore'));
223 223
                         }
224 224
                     }
225
-					$score =  ExerciseLib::show_score($last_attempt_info['exe_result'], $last_attempt_info['exe_weighting']);
226
-					$attempt_html .= Display::div(get_lang('YourTotalScore').' '.$score, array('id'=>'question_score'));
227
-				} else {
228
-					$attempt_html .= Display::return_message(sprintf(get_lang('ReachedMaxAttempts'), $exercise_title, $objExercise->selectAttempts()), 'warning', false);
229
-				}
230
-			} else {
231
-				$attempt_html .= Display::return_message(sprintf(get_lang('ReachedMaxAttempts'), $exercise_title, $objExercise->selectAttempts()), 'warning', false);
232
-			}
233
-		} else {
234
-			$attempt_html .= Display :: return_message(sprintf(get_lang('ReachedMaxAttempts'), $exercise_title, $objExercise->selectAttempts()), 'warning', false);
235
-		}
225
+                    $score =  ExerciseLib::show_score($last_attempt_info['exe_result'], $last_attempt_info['exe_weighting']);
226
+                    $attempt_html .= Display::div(get_lang('YourTotalScore').' '.$score, array('id'=>'question_score'));
227
+                } else {
228
+                    $attempt_html .= Display::return_message(sprintf(get_lang('ReachedMaxAttempts'), $exercise_title, $objExercise->selectAttempts()), 'warning', false);
229
+                }
230
+            } else {
231
+                $attempt_html .= Display::return_message(sprintf(get_lang('ReachedMaxAttempts'), $exercise_title, $objExercise->selectAttempts()), 'warning', false);
232
+            }
233
+        } else {
234
+            $attempt_html .= Display :: return_message(sprintf(get_lang('ReachedMaxAttempts'), $exercise_title, $objExercise->selectAttempts()), 'warning', false);
235
+        }
236 236
 
237
-		if ($origin == 'learnpath') {
238
-			Display :: display_reduced_header();
239
-		} else {
240
-			Display :: display_header(get_lang('Exercises'));
241
-		}
237
+        if ($origin == 'learnpath') {
238
+            Display :: display_reduced_header();
239
+        } else {
240
+            Display :: display_header(get_lang('Exercises'));
241
+        }
242 242
 
243
-		echo $attempt_html;
243
+        echo $attempt_html;
244 244
 
245 245
         if ($origin != 'learnpath') {
246 246
             Display:: display_footer();
247 247
         }
248
-		exit;
249
-	}
248
+        exit;
249
+    }
250 250
 }
251 251
 
252 252
 if ($debug) {
@@ -270,26 +270,26 @@  discard block
 block discarded – undo
270 270
 
271 271
 if (empty($exercise_stat_info)) {
272 272
     if ($debug)  error_log('5  $exercise_stat_info is empty ');
273
-	$total_weight = 0;
274
-	$questionList = $objExercise->get_validated_question_list();
275
-	foreach ($questionListUncompressed as $question_id) {
276
-		$objQuestionTmp = Question::read($question_id);
277
-		$total_weight += floatval($objQuestionTmp->weighting);
278
-	}
273
+    $total_weight = 0;
274
+    $questionList = $objExercise->get_validated_question_list();
275
+    foreach ($questionListUncompressed as $question_id) {
276
+        $objQuestionTmp = Question::read($question_id);
277
+        $total_weight += floatval($objQuestionTmp->weighting);
278
+    }
279 279
 
280
-	if ($time_control) {
281
-		$expected_time = $current_timestamp + $total_seconds;
280
+    if ($time_control) {
281
+        $expected_time = $current_timestamp + $total_seconds;
282 282
 
283
-		if ($debug)  error_log('5.1. $current_timestamp '.$current_timestamp);
284
-		if ($debug)  error_log('5.2. $expected_time '.$expected_time);
283
+        if ($debug)  error_log('5.1. $current_timestamp '.$current_timestamp);
284
+        if ($debug)  error_log('5.2. $expected_time '.$expected_time);
285 285
 
286
-		$clock_expired_time 	= api_get_utc_datetime($expected_time);
287
-		if ($debug) error_log('5.3. $expected_time '.$clock_expired_time);
286
+        $clock_expired_time 	= api_get_utc_datetime($expected_time);
287
+        if ($debug) error_log('5.3. $expected_time '.$clock_expired_time);
288 288
 
289
-		//Sessions  that contain the expired time
290
-		$_SESSION['expired_time'][$current_expired_time_key] 	 = $clock_expired_time;
291
-		if ($debug) { error_log('5.4. Setting the $_SESSION[expired_time]: '.$_SESSION['expired_time'][$current_expired_time_key] ); };
292
-	}
289
+        //Sessions  that contain the expired time
290
+        $_SESSION['expired_time'][$current_expired_time_key] 	 = $clock_expired_time;
291
+        if ($debug) { error_log('5.4. Setting the $_SESSION[expired_time]: '.$_SESSION['expired_time'][$current_expired_time_key] ); };
292
+    }
293 293
 
294 294
     $exe_id = $objExercise->save_stat_track_exercise_info(
295 295
         $clock_expired_time,
@@ -306,7 +306,7 @@  discard block
 block discarded – undo
306 306
     );
307 307
     if ($debug)  error_log("5.5  exercise_stat_info[] exists getting exe_id $exe_id");
308 308
 } else {
309
-	$exe_id = $exercise_stat_info['exe_id'];
309
+    $exe_id = $exercise_stat_info['exe_id'];
310 310
     // Remember last question id position.
311 311
     $isFirstTime = Session::read('firstTime');
312 312
     if ($isFirstTime && $objExercise->type == ONE_PER_PAGE) {
@@ -365,9 +365,9 @@  discard block
 block discarded – undo
365 365
 if ($debug) { error_log('6. $objExercise->get_stat_track_exercise_info function called::  '.print_r($exercise_stat_info, 1)); };
366 366
 
367 367
 if (!empty($exercise_stat_info['questions_to_check'])) {
368
-	$my_remind_list = $exercise_stat_info['questions_to_check'];
369
-	$my_remind_list = explode(',', $my_remind_list);
370
-	$my_remind_list = array_filter($my_remind_list);
368
+    $my_remind_list = $exercise_stat_info['questions_to_check'];
369
+    $my_remind_list = explode(',', $my_remind_list);
370
+    $my_remind_list = array_filter($my_remind_list);
371 371
 }
372 372
 
373 373
 $params = "exe_id=$exe_id&exerciseId=$exerciseId&origin=$origin&learnpath_id=$learnpath_id&learnpath_item_id=$learnpath_item_id&learnpath_item_view_id=$learnpath_item_view_id&".api_get_cidreq();
@@ -375,8 +375,8 @@  discard block
 block discarded – undo
375 375
 
376 376
 if ($reminder == 2 && empty($my_remind_list)) {
377 377
     if ($debug) { error_log("6.2 calling the exercise_reminder.php "); };
378
-	header('Location: exercise_reminder.php?'.$params);
379
-	exit;
378
+    header('Location: exercise_reminder.php?'.$params);
379
+    exit;
380 380
 }
381 381
 
382 382
 /*
@@ -384,56 +384,56 @@  discard block
 block discarded – undo
384 384
  * If the expired time is major that zero(0) then the expired time is compute on this time.
385 385
  */
386 386
 if ($time_control) {
387
-	if ($debug) error_log('7.1. Time control is enabled');
388
-	if ($debug) error_log('7.2. $current_expired_time_key  '.$current_expired_time_key);
389
-	if ($debug) error_log('7.3. $_SESSION[expired_time][$current_expired_time_key]  '.$_SESSION['expired_time'][$current_expired_time_key]);
387
+    if ($debug) error_log('7.1. Time control is enabled');
388
+    if ($debug) error_log('7.2. $current_expired_time_key  '.$current_expired_time_key);
389
+    if ($debug) error_log('7.3. $_SESSION[expired_time][$current_expired_time_key]  '.$_SESSION['expired_time'][$current_expired_time_key]);
390 390
 
391 391
     if (!isset($_SESSION['expired_time'][$current_expired_time_key])) {
392 392
         //Timer - Get expired_time for a student
393 393
         if (!empty($exercise_stat_info)) {
394
-        	if ($debug) {error_log('7.4 Seems that the session ends and the user want to retake the exam'); };
395
-	        $expired_time_of_this_attempt = $exercise_stat_info['expired_time_control'];
396
-			if ($debug) {error_log('7.5 $expired_time_of_this_attempt: '.$expired_time_of_this_attempt); }
397
-	        // Get the last attempt of an exercise
398
-	    	$last_attempt_date = Event::getLastAttemptDateOfExercise($exercise_stat_info['exe_id']);
394
+            if ($debug) {error_log('7.4 Seems that the session ends and the user want to retake the exam'); };
395
+            $expired_time_of_this_attempt = $exercise_stat_info['expired_time_control'];
396
+            if ($debug) {error_log('7.5 $expired_time_of_this_attempt: '.$expired_time_of_this_attempt); }
397
+            // Get the last attempt of an exercise
398
+            $last_attempt_date = Event::getLastAttemptDateOfExercise($exercise_stat_info['exe_id']);
399 399
 
400
-	    	/* This means that the user enters the exam but do not answer the
400
+            /* This means that the user enters the exam but do not answer the
401 401
 	    	   first question we get the date from the track_e_exercises not from
402 402
 	    	   the track_et_attempt see #2069 */
403
-	    	if (empty($last_attempt_date)) {
404
-	    		$diff = $current_timestamp - api_strtotime($exercise_stat_info['start_date'], 'UTC');
405
-	    		$last_attempt_date = api_get_utc_datetime(api_strtotime($exercise_stat_info['start_date'],'UTC') + $diff);
406
-	    	} else {
407
-	    		//Recalculate the time control due #2069
408
-	    		$diff = $current_timestamp - api_strtotime($last_attempt_date,'UTC');
409
-	    		$last_attempt_date = api_get_utc_datetime(api_strtotime($last_attempt_date,'UTC') + $diff);
410
-	    	}
411
-	        if ($debug) {error_log('7.6. $last_attempt_date: '.$last_attempt_date); }
412
-
413
-	        //New expired time - it is due to the possible closure of session
414
-	        $new_expired_time_in_seconds = api_strtotime($expired_time_of_this_attempt, 'UTC') - api_strtotime($last_attempt_date,'UTC');
415
-	        if ($debug) {error_log('7.7. $new_expired_time_in_seconds: '.$new_expired_time_in_seconds); }
416
-
417
-	        $expected_time	= $current_timestamp + $new_expired_time_in_seconds;
418
-	        if ($debug) {error_log('7.8. $expected_time1: '.$expected_time); }
419
-
420
-	        $clock_expired_time  = api_get_utc_datetime($expected_time);
421
-	        if ($debug) {error_log('7.9. $clock_expired_time: '.$clock_expired_time); }
422
-
423
-			// First we update the attempt to today
424
-			/* How the expired time is changed into "track_e_exercises" table,
403
+            if (empty($last_attempt_date)) {
404
+                $diff = $current_timestamp - api_strtotime($exercise_stat_info['start_date'], 'UTC');
405
+                $last_attempt_date = api_get_utc_datetime(api_strtotime($exercise_stat_info['start_date'],'UTC') + $diff);
406
+            } else {
407
+                //Recalculate the time control due #2069
408
+                $diff = $current_timestamp - api_strtotime($last_attempt_date,'UTC');
409
+                $last_attempt_date = api_get_utc_datetime(api_strtotime($last_attempt_date,'UTC') + $diff);
410
+            }
411
+            if ($debug) {error_log('7.6. $last_attempt_date: '.$last_attempt_date); }
412
+
413
+            //New expired time - it is due to the possible closure of session
414
+            $new_expired_time_in_seconds = api_strtotime($expired_time_of_this_attempt, 'UTC') - api_strtotime($last_attempt_date,'UTC');
415
+            if ($debug) {error_log('7.7. $new_expired_time_in_seconds: '.$new_expired_time_in_seconds); }
416
+
417
+            $expected_time	= $current_timestamp + $new_expired_time_in_seconds;
418
+            if ($debug) {error_log('7.8. $expected_time1: '.$expected_time); }
419
+
420
+            $clock_expired_time  = api_get_utc_datetime($expected_time);
421
+            if ($debug) {error_log('7.9. $clock_expired_time: '.$clock_expired_time); }
422
+
423
+            // First we update the attempt to today
424
+            /* How the expired time is changed into "track_e_exercises" table,
425 425
                then the last attempt for this student should be changed too */
426
-	        $sql = "UPDATE $exercise_attempt_table SET
426
+            $sql = "UPDATE $exercise_attempt_table SET
427 427
 	                tms = '".api_get_utc_datetime()."'
428 428
 	                WHERE
429 429
 	                    exe_id = '".$exercise_stat_info['exe_id']."' AND
430 430
 	                    tms = '".$last_attempt_date."' ";
431
-	        if ($debug) {error_log('7.10. $sql: '.$sql); }
432
-	        Database::query($sql);
431
+            if ($debug) {error_log('7.10. $sql: '.$sql); }
432
+            Database::query($sql);
433 433
 
434
-	        //Sessions  that contain the expired time
435
-	        $_SESSION['expired_time'][$current_expired_time_key] = $clock_expired_time;
436
-	        if ($debug) {error_log('7.11. Setting the $_SESSION[expired_time]: '.$_SESSION['expired_time'][$current_expired_time_key] ); };
434
+            //Sessions  that contain the expired time
435
+            $_SESSION['expired_time'][$current_expired_time_key] = $clock_expired_time;
436
+            if ($debug) {error_log('7.11. Setting the $_SESSION[expired_time]: '.$_SESSION['expired_time'][$current_expired_time_key] ); };
437 437
         }
438 438
     } else {
439 439
         $clock_expired_time =  $_SESSION['expired_time'][$current_expired_time_key];
@@ -450,7 +450,7 @@  discard block
 block discarded – undo
450 450
  * for more details of how it works see this link : http://eric.garside.name/docs.html?p=epiclock
451 451
  */
452 452
 if ($time_control) { //Sends the exercise form when the expired time is finished
453
-	$htmlHeadXtra[] = $objExercise->show_time_control_js($time_left);
453
+    $htmlHeadXtra[] = $objExercise->show_time_control_js($time_left);
454 454
 }
455 455
 
456 456
 // if the user has submitted the form
@@ -463,14 +463,14 @@  discard block
 block discarded – undo
463 463
     // selects the list of question ID
464 464
     $questionList = $objExercise->get_validated_question_list();
465 465
     if ($objExercise->isRandom() && !empty($exercise_stat_info['data_tracking'])) {
466
-    	$questionList = explode(',', $exercise_stat_info['data_tracking']);
466
+        $questionList = explode(',', $exercise_stat_info['data_tracking']);
467 467
     }
468 468
     Session::write('questionList', $questionList);
469 469
     if ($debug > 0) { error_log('$_SESSION[questionList] was set'); }
470 470
 } else {
471
-	if (isset($objExercise) && isset($_SESSION['objExercise'])) {
472
-    	$questionList = $_SESSION['questionList'];
473
-	}
471
+    if (isset($objExercise) && isset($_SESSION['objExercise'])) {
472
+        $questionList = $_SESSION['questionList'];
473
+    }
474 474
 }
475 475
 
476 476
 if ($debug) error_log('8. Question list loaded '.print_r($questionList, 1));
@@ -478,7 +478,7 @@  discard block
 block discarded – undo
478 478
 //Real question count
479 479
 $question_count = 0;
480 480
 if (!empty($questionList)) {
481
-	$question_count = count($questionList);
481
+    $question_count = count($questionList);
482 482
 }
483 483
 
484 484
 if ($formSent && isset($_POST)) {
@@ -520,11 +520,11 @@  discard block
 block discarded – undo
520 520
                 //saving each question
521 521
                 if ($objExercise->feedback_type != EXERCISE_FEEDBACK_TYPE_DIRECT) {
522 522
                     $nro_question = $current_question; // - 1;
523
-                 	$questionId   = $key;
523
+                        $questionId   = $key;
524 524
                     // gets the student choice for this question
525 525
                     $choice = $exerciseResult[$questionId];
526 526
                     if (isset($exe_id)) {
527
-                    	// Manage the question and answer attempts
527
+                        // Manage the question and answer attempts
528 528
                         if ($debug) { error_log('8.3. manage_answer exe_id: '.$exe_id.' - $questionId: '.$questionId.' Choice'.print_r($choice,1)); }
529 529
                         $objExercise->manage_answer(
530 530
                             $exe_id,
@@ -613,58 +613,58 @@  discard block
 block discarded – undo
613 613
 }
614 614
 
615 615
 if ($question_count != 0) {
616
-	if (($objExercise->type == ALL_ON_ONE_PAGE ||
616
+    if (($objExercise->type == ALL_ON_ONE_PAGE ||
617 617
         $current_question > $question_count)
618 618
     ) {
619
-	    if (api_is_allowed_to_session_edit()) {
620
-	        // goes to the script that will show the result of the exercise
621
-	        if ($objExercise->type == ALL_ON_ONE_PAGE) {
622
-	            if ($debug) { error_log('12. Exercise ALL_ON_ONE_PAGE -> Redirecting to exercise_result.php'); }
623
-
624
-	            //We check if the user attempts before sending to the exercise_result.php
625
-	            if ($objExercise->selectAttempts() > 0) {
626
-	                $attempt_count = Event::get_attempt_count(
619
+        if (api_is_allowed_to_session_edit()) {
620
+            // goes to the script that will show the result of the exercise
621
+            if ($objExercise->type == ALL_ON_ONE_PAGE) {
622
+                if ($debug) { error_log('12. Exercise ALL_ON_ONE_PAGE -> Redirecting to exercise_result.php'); }
623
+
624
+                //We check if the user attempts before sending to the exercise_result.php
625
+                if ($objExercise->selectAttempts() > 0) {
626
+                    $attempt_count = Event::get_attempt_count(
627 627
                         api_get_user_id(),
628 628
                         $exerciseId,
629 629
                         $learnpath_id,
630 630
                         $learnpath_item_id,
631 631
                         $learnpath_item_view_id
632 632
                     );
633
-	                if ($attempt_count >= $objExercise->selectAttempts()) {
634
-	                    Display :: display_warning_message(
633
+                    if ($attempt_count >= $objExercise->selectAttempts()) {
634
+                        Display :: display_warning_message(
635 635
                             sprintf(get_lang('ReachedMaxAttempts'), $exercise_title, $objExercise->selectAttempts()),
636 636
                             false
637 637
                         );
638
-	                    if ($origin != 'learnpath') {
639
-	                        //so we are not in learnpath tool
640
-	                        echo '</div>'; //End glossary div
641
-	                        Display :: display_footer();
642
-	                    } else {
643
-	                        echo '</body></html>';
644
-	                    }
645
-	                    exit;
646
-	                }
647
-	            }
648
-	        } else {
649
-	            if ($objExercise->review_answers) {
650
-	            	header('Location: exercise_reminder.php?'.$params);
651
-	            	exit;
652
-	            } else {
638
+                        if ($origin != 'learnpath') {
639
+                            //so we are not in learnpath tool
640
+                            echo '</div>'; //End glossary div
641
+                            Display :: display_footer();
642
+                        } else {
643
+                            echo '</body></html>';
644
+                        }
645
+                        exit;
646
+                    }
647
+                }
648
+            } else {
649
+                if ($objExercise->review_answers) {
650
+                    header('Location: exercise_reminder.php?'.$params);
651
+                    exit;
652
+                } else {
653 653
                     header("Location: exercise_result.php?".api_get_cidreq()."&exe_id=$exe_id&origin=$origin&learnpath_id=$learnpath_id&learnpath_item_id=$learnpath_item_id&learnpath_item_view_id=$learnpath_item_view_id");
654 654
                     exit;
655
-	            }
656
-	        }
657
-	    } else {
658
-	        if ($debug) { error_log('Redirecting to exercise_submit.php'); }
659
-	        exit;
660
-	    }
661
-	}
655
+                }
656
+            }
657
+        } else {
658
+            if ($debug) { error_log('Redirecting to exercise_submit.php'); }
659
+            exit;
660
+        }
661
+    }
662 662
 } else {
663
-	$error = get_lang('ThereAreNoQuestionsForThisExercise');
664
-	// if we are in the case where user select random by category, but didn't choose the number of random question
665
-	if ($objExercise->selectRandomByCat() > 0 && $objExercise->random <= 0) {
666
-		$error .= "<br/>".get_lang('PleaseSelectSomeRandomQuestion');
667
-	}
663
+    $error = get_lang('ThereAreNoQuestionsForThisExercise');
664
+    // if we are in the case where user select random by category, but didn't choose the number of random question
665
+    if ($objExercise->selectRandomByCat() > 0 && $objExercise->random <= 0) {
666
+        $error .= "<br/>".get_lang('PleaseSelectSomeRandomQuestion');
667
+    }
668 668
 }
669 669
 
670 670
 if (!empty ($_GET['gradebook']) && $_GET['gradebook'] == 'view') {
@@ -703,9 +703,9 @@  discard block
 block discarded – undo
703 703
 if (api_is_course_admin() && $origin != 'learnpath') {
704 704
     echo '<div class="actions">';
705 705
     if ($show_quiz_edition == false) {
706
-    	echo '<a href="exercise_admin.php?' . api_get_cidreq() . '&modifyExercise=yes&exerciseId=' . $objExercise->id . '">'.Display :: return_icon('settings.png', get_lang('ModifyExercise'),'',ICON_SIZE_MEDIUM).'</a>';
706
+        echo '<a href="exercise_admin.php?' . api_get_cidreq() . '&modifyExercise=yes&exerciseId=' . $objExercise->id . '">'.Display :: return_icon('settings.png', get_lang('ModifyExercise'),'',ICON_SIZE_MEDIUM).'</a>';
707 707
     } else {
708
-    	echo '<a href="#">'.Display::return_icon('settings_na.png', get_lang('ModifyExercise'),'',ICON_SIZE_MEDIUM).'</a>';
708
+        echo '<a href="#">'.Display::return_icon('settings_na.png', get_lang('ModifyExercise'),'',ICON_SIZE_MEDIUM).'</a>';
709 709
     }
710 710
     echo '</div>';
711 711
 }
@@ -748,7 +748,7 @@  discard block
 block discarded – undo
748 748
             $message_warning = $permission_to_start ? get_lang('ReachedTimeLimit') : get_lang('ExerciseNoStartedYet');
749 749
             Display :: display_warning_message(sprintf($message_warning, $exercise_title, $objExercise->selectAttempts()));
750 750
             if ($origin != 'learnpath') {
751
-            	Display :: display_footer();
751
+                Display :: display_footer();
752 752
             }
753 753
             exit;
754 754
         } else {
@@ -763,7 +763,7 @@  discard block
 block discarded – undo
763 763
 if (isset($_custom['exercises_hidden_when_no_start_date']) &&
764 764
     $_custom['exercises_hidden_when_no_start_date']
765 765
 ) {
766
-	if (empty($objExercise->start_time) || $objExercise->start_time == '0000-00-00 00:00:00') {
766
+    if (empty($objExercise->start_time) || $objExercise->start_time == '0000-00-00 00:00:00') {
767 767
         Display:: display_warning_message(
768 768
             sprintf(
769 769
                 get_lang('ExerciseNoStartedYet'),
@@ -771,20 +771,20 @@  discard block
 block discarded – undo
771 771
                 $objExercise->selectAttempts()
772 772
             )
773 773
         );
774
-		if ($origin != 'learnpath') {
775
-			Display :: display_footer();
776
-		}
777
-	}
774
+        if ($origin != 'learnpath') {
775
+            Display :: display_footer();
776
+        }
777
+    }
778 778
 }
779 779
 
780 780
 //Timer control
781 781
 if ($time_control) {
782 782
     echo $objExercise->return_time_left_div();
783
-	echo '<div style="display:none" class="warning-message" id="expired-message-id">'.get_lang('ExerciseExpiredTimeMessage').'</div>';
783
+    echo '<div style="display:none" class="warning-message" id="expired-message-id">'.get_lang('ExerciseExpiredTimeMessage').'</div>';
784 784
 }
785 785
 
786 786
 if ($origin != 'learnpath') {
787
-   echo '<div id="highlight-plugin" class="glossary-content">';
787
+    echo '<div id="highlight-plugin" class="glossary-content">';
788 788
 }
789 789
 
790 790
 if ($reminder == 2)  {
@@ -796,53 +796,53 @@  discard block
 block discarded – undo
796 796
     $current_question = 1; //set by default the 1st question
797 797
 
798 798
     if (!empty($my_remind_list)) {
799
-    	// Checking which questions we are going to call from the remind list
800
-		for ($i = 0; $i < count($data_tracking); $i++) {
801
-			for($j = 0; $j < count($my_remind_list); $j++) {
802
-
803
-				if (!empty($remind_question_id)) {
804
-					if ($remind_question_id == $my_remind_list[$j]) {
805
-
806
-			        	if ($remind_question_id == $data_tracking[$i]) {
807
-			        		if (isset($my_remind_list[$j+1])) {
808
-			        			$remind_question_id = $my_remind_list[$j+1];
809
-			        			$current_question = $i + 1;
810
-			        		} else {
799
+        // Checking which questions we are going to call from the remind list
800
+        for ($i = 0; $i < count($data_tracking); $i++) {
801
+            for($j = 0; $j < count($my_remind_list); $j++) {
802
+
803
+                if (!empty($remind_question_id)) {
804
+                    if ($remind_question_id == $my_remind_list[$j]) {
805
+
806
+                        if ($remind_question_id == $data_tracking[$i]) {
807
+                            if (isset($my_remind_list[$j+1])) {
808
+                                $remind_question_id = $my_remind_list[$j+1];
809
+                                $current_question = $i + 1;
810
+                            } else {
811 811
                                 // We end the remind list we go to the exercise_reminder.php please
812
-			        			$remind_question_id = -1;
813
-			        			$current_question = $i + 1; // last question
814
-			        		}
815
-			        		break 2;
816
-			            }
817
-					}
818
-				} else {
819
-					if ($my_remind_list[$j] == $data_tracking[$i]) {
820
-						if (isset($my_remind_list[$j+1])) {
821
-							$remind_question_id = $my_remind_list[$j+1];
822
-							$current_question = $i + 1; // last question
823
-						} else {
812
+                                $remind_question_id = -1;
813
+                                $current_question = $i + 1; // last question
814
+                            }
815
+                            break 2;
816
+                        }
817
+                    }
818
+                } else {
819
+                    if ($my_remind_list[$j] == $data_tracking[$i]) {
820
+                        if (isset($my_remind_list[$j+1])) {
821
+                            $remind_question_id = $my_remind_list[$j+1];
822
+                            $current_question = $i + 1; // last question
823
+                        } else {
824 824
                             // We end the remind list we go to the exercise_reminder.php please
825
-							$remind_question_id = -1;
826
-							$current_question = $i + 1; // last question
827
-						}
828
-						break 2;
829
-					}
830
-				}
831
-			}
825
+                            $remind_question_id = -1;
826
+                            $current_question = $i + 1; // last question
827
+                        }
828
+                        break 2;
829
+                    }
830
+                }
831
+            }
832 832
         }
833 833
     } else {
834
-    	if ($objExercise->review_answers) {
834
+        if ($objExercise->review_answers) {
835 835
             if ($debug) { error_log('. redirecting to exercise_reminder.php '); }
836
-	    	header("Location: exercise_reminder.php?$params");
837
-	    	exit;
838
-    	}
836
+            header("Location: exercise_reminder.php?$params");
837
+            exit;
838
+        }
839 839
     }
840 840
 }
841 841
 
842 842
 if ($objExercise->review_answers) {
843
-	$script_php = 'exercise_reminder.php';
843
+    $script_php = 'exercise_reminder.php';
844 844
 } else {
845
-	$script_php = 'exercise_result.php';
845
+    $script_php = 'exercise_result.php';
846 846
 }
847 847
 
848 848
 if (!empty($error)) {
@@ -1086,7 +1086,7 @@  discard block
 block discarded – undo
1086 1086
          <input type="hidden" name="learnpath_item_id" 		value="'.$learnpath_item_id . '" />
1087 1087
          <input type="hidden" name="learnpath_item_view_id" value="'.$learnpath_item_view_id . '" />';
1088 1088
 
1089
-	// Show list of questions
1089
+    // Show list of questions
1090 1090
     $i = 1;
1091 1091
     $attempt_list = array();
1092 1092
     if (isset($exe_id)) {
@@ -1136,10 +1136,10 @@  discard block
 block discarded – undo
1136 1136
 
1137 1137
         $attributes = array('id' =>'remind_list['.$questionId.']');
1138 1138
         if (in_array($questionId, $remind_list)) {
1139
-        	$is_remind_on = true;
1140
-        	$attributes['checked'] = 1;
1141
-        	$remind_question = true;
1142
-        	$remind_highlight = ' remind_highlight ';
1139
+            $is_remind_on = true;
1140
+            $attributes['checked'] = 1;
1141
+            $remind_question = true;
1142
+            $remind_highlight = ' remind_highlight ';
1143 1143
         }
1144 1144
 
1145 1145
         // Showing the exercise description
@@ -1213,8 +1213,8 @@  discard block
 block discarded – undo
1213 1213
     }
1214 1214
     // end foreach()
1215 1215
     if ($objExercise->type == ALL_ON_ONE_PAGE) {
1216
-    	$exercise_actions =  $objExercise->show_button($questionId, $current_question);
1217
-    	echo Display::div($exercise_actions, array('class'=>'exercise_actions'));
1216
+        $exercise_actions =  $objExercise->show_button($questionId, $current_question);
1217
+        echo Display::div($exercise_actions, array('class'=>'exercise_actions'));
1218 1218
         echo '<br>';
1219 1219
     }
1220 1220
     echo '</form>';
Please login to merge, or discard this patch.