Passed
Push — 1.11.x ( a5a0b8...4f166c )
by Julito
13:24
created

getData()   B

Complexity

Conditions 5
Paths 8

Size

Total Lines 109
Code Lines 76

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
eloc 76
nc 8
nop 4
dl 0
loc 109
rs 8.2125
c 1
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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