Completed
Push — master ( c34076...6cb4af )
by Julito
11:15
created

getCount()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 32
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 23
nc 2
nop 0
dl 0
loc 32
rs 9.552
c 1
b 0
f 0
1
<?php
2
3
/* For licensing terms, see /license.txt */
4
5
use ChamiloSession as Session;
6
7
require_once __DIR__.'/../inc/global.inc.php';
8
9
api_protect_course_script();
10
11
$sessionId = api_get_session_id();
12
$courseId = api_get_course_int_id();
13
14
// Access restrictions.
15
$is_allowedToTrack = Tracking::isAllowToTrack($sessionId);
16
17
if (!$is_allowedToTrack) {
18
    api_not_allowed(true);
19
    exit;
20
}
21
22
$action = isset($_GET['action']) ? $_GET['action'] : null;
23
$lps = learnpath::getLpList($courseId);
24
Session::write('lps', $lps);
25
26
/**
27
 * Prepares the shared SQL query for the user table.
28
 * See get_user_data() and get_number_of_users().
29
 *
30
 * @param bool $getCount Whether to count, or get data
31
 *
32
 * @return string SQL query
33
 */
34
function prepare_user_sql_query($getCount)
35
{
36
    $sql = '';
37
    $user_table = Database::get_main_table(TABLE_MAIN_USER);
38
    $admin_table = Database::get_main_table(TABLE_MAIN_ADMIN);
39
40
    if ($getCount) {
41
        $sql .= "SELECT COUNT(u.id) AS total_number_of_items FROM $user_table u";
42
    } else {
43
        $sql .= 'SELECT u.id AS col0, u.official_code AS col2, ';
44
45
        if (api_is_western_name_order()) {
46
            $sql .= 'u.firstname AS col3, u.lastname AS col4, ';
47
        } else {
48
            $sql .= 'u.lastname AS col3, u.firstname AS col4, ';
49
        }
50
51
        $sql .= " u.username AS col5,
52
                    u.email AS col6,
53
                    u.status AS col7,
54
                    u.active AS col8,
55
                    u.registration_date AS col9,
56
                    u.last_login as col10,
57
                    u.id AS col11,
58
                    u.expiration_date AS exp,
59
                    u.password
60
                FROM $user_table u";
61
    }
62
63
    // adding the filter to see the user's only of the current access_url
64
    if ((api_is_platform_admin() || api_is_session_admin()) && api_get_multiple_access_url()) {
65
        $access_url_rel_user_table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
66
        $sql .= " INNER JOIN $access_url_rel_user_table url_rel_user
67
                  ON (u.id=url_rel_user.user_id)";
68
    }
69
70
    $keywordList = [
71
        'keyword_firstname',
72
        'keyword_lastname',
73
        'keyword_username',
74
        'keyword_email',
75
        'keyword_officialcode',
76
        'keyword_status',
77
        'keyword_active',
78
        'keyword_inactive',
79
        'check_easy_passwords',
80
    ];
81
82
    $keywordListValues = [];
83
    $atLeastOne = false;
84
    foreach ($keywordList as $keyword) {
85
        $keywordListValues[$keyword] = null;
86
        if (isset($_GET[$keyword]) && !empty($_GET[$keyword])) {
87
            $keywordListValues[$keyword] = $_GET[$keyword];
88
            $atLeastOne = true;
89
        }
90
    }
91
92
    if ($atLeastOne == false) {
93
        $keywordListValues = [];
94
    }
95
96
    if (isset($_GET['keyword']) && !empty($_GET['keyword'])) {
97
        $keywordFiltered = Database::escape_string("%".$_GET['keyword']."%");
98
        $sql .= " WHERE (
99
                    u.firstname LIKE '$keywordFiltered' OR
100
                    u.lastname LIKE '$keywordFiltered' OR
101
                    concat(u.firstname, ' ', u.lastname) LIKE '$keywordFiltered' OR
102
                    concat(u.lastname,' ',u.firstname) LIKE '$keywordFiltered' OR
103
                    u.username LIKE '$keywordFiltered' OR
104
                    u.official_code LIKE '$keywordFiltered' OR
105
                    u.email LIKE '$keywordFiltered'
106
                )
107
        ";
108
    } elseif (isset($keywordListValues) && !empty($keywordListValues)) {
109
        $query_admin_table = '';
110
        $keyword_admin = '';
111
112
        if (isset($keywordListValues['keyword_status']) &&
113
            $keywordListValues['keyword_status'] == PLATFORM_ADMIN
114
        ) {
115
            $query_admin_table = " , $admin_table a ";
116
            $keyword_admin = ' AND a.user_id = u.id ';
117
            $keywordListValues['keyword_status'] = '%';
118
        }
119
120
        $keyword_extra_value = '';
121
        $sql .= " $query_admin_table
122
            WHERE (
123
                u.firstname LIKE '".Database::escape_string("%".$keywordListValues['keyword_firstname']."%")."' AND
124
                u.lastname LIKE '".Database::escape_string("%".$keywordListValues['keyword_lastname']."%")."' AND
125
                u.username LIKE '".Database::escape_string("%".$keywordListValues['keyword_username']."%")."' AND
126
                u.email LIKE '".Database::escape_string("%".$keywordListValues['keyword_email']."%")."' AND
127
                u.status LIKE '".Database::escape_string($keywordListValues['keyword_status'])."' ";
128
        if (!empty($keywordListValues['keyword_officialcode'])) {
129
            $sql .= " AND u.official_code LIKE '".Database::escape_string("%".$keywordListValues['keyword_officialcode']."%")."' ";
130
        }
131
132
        $sql .= "
133
            $keyword_admin
134
            $keyword_extra_value
135
        ";
136
137
        if (isset($keywordListValues['keyword_active']) &&
138
            !isset($keywordListValues['keyword_inactive'])
139
        ) {
140
            $sql .= ' AND u.active = 1';
141
        } elseif (isset($keywordListValues['keyword_inactive']) &&
142
            !isset($keywordListValues['keyword_active'])
143
        ) {
144
            $sql .= ' AND u.active = 0';
145
        }
146
        $sql .= ' ) ';
147
    }
148
149
    $preventSessionAdminsToManageAllUsers = api_get_setting('prevent_session_admins_to_manage_all_users');
150
    if (api_is_session_admin() && $preventSessionAdminsToManageAllUsers === 'true') {
151
        $sql .= ' AND u.creator_id = '.api_get_user_id();
152
    }
153
154
    $variables = Session::read('variables_to_show', []);
155
    if (!empty($variables)) {
156
        $extraField = new ExtraField('user');
157
        $extraFieldResult = [];
158
        $extraFieldHasData = [];
159
        foreach ($variables as $variable) {
160
            if (isset($_GET['extra_'.$variable])) {
161
                if (is_array($_GET['extra_'.$variable])) {
162
                    $values = $_GET['extra_'.$variable];
163
                } else {
164
                    $values = [$_GET['extra_'.$variable]];
165
                }
166
167
                if (empty($values)) {
168
                    continue;
169
                }
170
171
                $info = $extraField->get_handler_field_info_by_field_variable(
172
                    $variable
173
                );
174
175
                if (empty($info)) {
176
                    continue;
177
                }
178
179
                foreach ($values as $value) {
180
                    if (empty($value)) {
181
                        continue;
182
                    }
183
                    if ($info['field_type'] == ExtraField::FIELD_TYPE_TAG) {
184
                        $result = $extraField->getAllUserPerTag(
185
                            $info['id'],
186
                            $value
187
                        );
188
                        $result = empty($result) ? [] : array_column(
189
                            $result,
190
                            'user_id'
191
                        );
192
                    } else {
193
                        $result = UserManager::get_extra_user_data_by_value(
194
                            $variable,
195
                            $value
196
                        );
197
                    }
198
                    $extraFieldHasData[] = true;
199
                    if (!empty($result)) {
200
                        $extraFieldResult = array_merge(
201
                            $extraFieldResult,
202
                            $result
203
                        );
204
                    }
205
                }
206
            }
207
        }
208
209
        if (!empty($extraFieldHasData)) {
210
            $sql .= " AND (u.id IN ('".implode("','", $extraFieldResult)."')) ";
211
        }
212
    }
213
214
    // adding the filter to see the user's only of the current access_url
215
    if ((api_is_platform_admin() || api_is_session_admin()) &&
216
        api_get_multiple_access_url()
217
    ) {
218
        $sql .= ' AND url_rel_user.access_url_id = '.api_get_current_access_url_id();
219
    }
220
221
    return $sql;
222
}
223
224
function getCount()
225
{
226
    $sessionId = api_get_session_id();
227
    $courseCode = api_get_course_id();
228
229
    if (empty($sessionId)) {
230
        // Registered students in a course outside session.
231
        $count = CourseManager::get_student_list_from_course_code(
232
            $courseCode,
233
            false,
234
            null,
235
            null,
236
            null,
237
            null,
238
            null,
239
            true
240
        );
241
    } else {
242
        // Registered students in session.
243
        $count = CourseManager::get_student_list_from_course_code(
244
            $courseCode,
245
            true,
246
            $sessionId,
247
            null,
248
            null,
249
            null,
250
            null,
251
            true
252
        );
253
    }
254
255
    return $count;
256
}
257
258
/**
259
 * Get the users to display on the current page (fill the sortable-table).
260
 *
261
 * @param   int     offset of first user to recover
262
 * @param   int     Number of users to get
263
 * @param   int     Column to sort on
264
 * @param   string  Order (ASC,DESC)
265
 *
266
 * @return array Users list
267
 *
268
 * @see SortableTable#get_table_data($from)
269
 */
270
function getData($from, $numberOfItems, $column, $direction)
271
{
272
    $sessionId = api_get_session_id();
273
    $courseCode = api_get_course_id();
274
    $courseId = api_get_course_int_id();
275
276
    $lps = Session::read('lps');
277
278
    if (empty($sessionId)) {
279
        // Registered students in a course outside session.
280
        $students = CourseManager::get_student_list_from_course_code(
281
            $courseCode,
282
            false,
283
            null,
284
            null,
285
            null,
286
            null,
287
            null,
288
            false,
289
            $from,
290
            $numberOfItems
291
        );
292
    } else {
293
        // Registered students in session.
294
        $students = CourseManager::get_student_list_from_course_code(
295
            $courseCode,
296
            true,
297
            $sessionId,
298
            null,
299
            null,
300
            null,
301
            null,
302
            false,
303
            $from,
304
            $numberOfItems
305
        );
306
    }
307
308
    $useNewTable = Tracking::minimumTimeAvailable($sessionId, $courseId);
309
310
    $users = [];
311
    foreach ($students as $student) {
312
        $user = [];
313
        $userId = $student['id'];
314
        $user[] = $student['firstname'];
315
        $user[] = $student['lastname'];
316
        $user[] = $student['username'];
317
318
        $lpTimeList = [];
319
        if ($useNewTable) {
320
            $lpTimeList = Tracking::getCalculateTime($userId, $courseId, $sessionId);
321
        }
322
        foreach ($lps as $lp) {
323
            $lpId = $lp['id'];
324
            $progress = Tracking::get_avg_student_progress(
325
                $userId,
326
                $courseCode,
327
                [$lpId],
328
                $sessionId
329
            );
330
331
            if ($useNewTable) {
332
                $time = isset($lpTimeList[TOOL_LEARNPATH][$lpId]) ? $lpTimeList[TOOL_LEARNPATH][$lpId] : 0;
333
            } else {
334
                $time = Tracking::get_time_spent_in_lp(
335
                    $userId,
336
                    $courseCode,
337
                    [$lpId],
338
                    $sessionId
339
                );
340
            }
341
            $time = api_time_to_hms($time);
342
343
            $first = Tracking::getFirstConnectionTimeInLp(
344
                $userId,
345
                $courseCode,
346
                $lpId,
347
                $sessionId
348
            );
349
350
            $first = api_convert_and_format_date(
351
                $first,
352
                DATE_TIME_FORMAT_LONG
353
            );
354
355
            $last = Tracking::get_last_connection_time_in_lp(
356
                $userId,
357
                $courseCode,
358
                $lpId,
359
                $sessionId
360
            );
361
            $last = api_convert_and_format_date(
362
                $last,
363
                DATE_TIME_FORMAT_LONG
364
            );
365
366
            $score = Tracking::getAverageStudentScore(
367
                $userId,
368
                $courseCode,
369
                [$lpId],
370
                $sessionId
371
            );
372
373
            if (is_numeric($score)) {
374
                $score = $score.'%';
375
            }
376
377
            $user[] = $progress;
378
            $user[] = $first;
379
            $user[] = $last;
380
            $user[] = $time;
381
            $user[] = $score;
382
        }
383
384
        $users[] = $user;
385
    }
386
387
    return $users;
388
}
389
390
$interbreadcrumb[] = [
391
    'url' => api_get_path(WEB_CODE_PATH).'tracking/courseLog.php?'.api_get_cidreq(),
392
    'name' => get_lang('Tracking'),
393
];
394
395
$tool_name = get_lang('CourseLPsGenericStats');
396
397
$headers = [];
398
$headers[] = get_lang('FirstName');
399
$headers[] = get_lang('LastName');
400
$headers[] = get_lang('Username');
401
foreach ($lps as $lp) {
402
    $lpName = $lp['name'];
403
    $headers[] = get_lang('Progress').': '.$lpName;
404
    $headers[] = get_lang('FirstAccess').': '.$lpName;
405
    $headers[] = get_lang('LastAccess').': '.$lpName;
406
    $headers[] = get_lang('Time').': '.$lpName;
407
    $headers[] = get_lang('Score').': '.$lpName;
408
}
409
410
if (!empty($action)) {
411
    switch ($action) {
412
        case 'export':
413
            $data = getData(0, 100000, null, null);
414
            $data = array_merge([$headers], $data);
415
            $name = api_get_course_id().'_'.get_lang('Learnpath').'_'.get_lang('Export');
416
            Export::arrayToXls($data, $name);
417
            exit;
418
            break;
419
    }
420
}
421
422
$actionsLeft = TrackingCourseLog::actionsLeft('lp');
423
$actionsCenter = '';
424
$actionsRight = Display::url(
425
    Display::return_icon('export_excel.png', get_lang('ExportAsXLS'), null, ICON_SIZE_MEDIUM),
426
    api_get_self().'?action=export&'.api_get_cidreq()
427
);
428
429
// Create a sortable table with user-data
430
$parameters = [];
431
$parameters['sec_token'] = Security::get_token();
432
$parameters['cidReq'] = api_get_course_id();
433
$parameters['id_session'] = api_get_session_id();
434
435
$table = new SortableTable(
436
    'lps',
437
    'getCount',
438
    'getData'
439
);
440
$table->set_additional_parameters($parameters);
441
$column = 0;
442
foreach ($headers as $header) {
443
    $lpName = $lp['name'];
444
    $table->set_header($column++, $header, false);
445
}
446
447
$tableToString = $table->return_table();
448
$toolbarActions = Display::toolbarAction(
449
    'toolbarUser',
450
    [$actionsLeft, $actionsCenter, $actionsRight],
451
    [4, 4, 4]
452
);
453
454
$tpl = new Template($tool_name);
455
$tpl->assign('actions', $toolbarActions);
456
$tpl->assign('content', $tableToString);
457
$tpl->display_one_col_template();
458