Passed
Push — dependabot/npm_and_yarn/nanoid... ( aaf2c9...c4aa90 )
by
unknown
14:37 queued 06:22
created

get_course_data_by_session()   B

Complexity

Conditions 8
Paths 36

Size

Total Lines 68
Code Lines 41

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 8
eloc 41
nc 36
nop 4
dl 0
loc 68
rs 8.0195
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
A get_course_visibility_icon() 0 43 1

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
declare(strict_types=1);
6
7
/*
8
 * This script shows a list of courses and allows searching for courses codes
9
 * and names.
10
 */
11
12
use Chamilo\CoreBundle\Component\Utils\ActionIcon;
13
use Chamilo\CoreBundle\Component\Utils\StateIcon;
14
use Chamilo\CoreBundle\Component\Utils\ToolIcon;
15
16
$cidReset = true;
17
18
require_once __DIR__.'/../inc/global.inc.php';
19
20
$this_section = SECTION_PLATFORM_ADMIN;
21
api_protect_admin_script();
22
$sessionId = $_GET['session_id'] ?? null;
23
24
/**
25
 * Get the number of courses which will be displayed.
26
 *
27
 * @return int The number of matching courses
28
 *
29
 * @throws Exception
30
 */
31
function get_number_of_courses(): int
32
{
33
    return get_course_data(0, 0, 0, 'ASC', [], true);
34
}
35
36
/**
37
 * Get course data to display.
38
 *
39
 * @throws Doctrine\DBAL\Exception
40
 * @throws Exception
41
 */
42
function get_course_data(
43
    int $from,
44
    int $number_of_items,
45
    int $column,
46
    string $direction,
47
    array $dataFunctions = [],
48
    bool $getCount = false
49
): int|array {
50
    $course_table = Database::get_main_table(TABLE_MAIN_COURSE);
51
52
    if (!in_array(strtolower($direction), ['asc', 'desc'])) {
53
        $direction = 'desc';
54
    }
55
56
    $tblCourseCategory = Database::get_main_table(TABLE_MAIN_CATEGORY);
57
    $tblCourseRelCategory = Database::get_main_table(TABLE_MAIN_COURSE_REL_CATEGORY);
58
59
    $select = 'SELECT
60
                course.code AS col0,
61
                course.title AS col1,
62
                course.code AS col2,
63
                course_language AS col3,
64
                subscribe AS col5,
65
                unsubscribe AS col6,
66
                course.code AS col7,
67
                course.visibility AS col8,
68
                directory as col9,
69
                visual_code,
70
                directory,
71
                course.id';
72
73
    if ($getCount) {
74
        $select = 'SELECT COUNT(DISTINCT(course.id)) as count ';
75
    }
76
77
    $sql = "$select FROM $course_table course ";
78
79
    if (!empty($_GET['keyword_category'])) {
80
        $sql .= "INNER JOIN $tblCourseRelCategory course_rel_category ON course.id = course_rel_category.course_id
81
            INNER JOIN $tblCourseCategory category ON course_rel_category.course_category_id = category.id ";
82
    }
83
84
    if ((api_is_platform_admin() || api_is_session_admin())
85
        && api_is_multiple_url_enabled() && -1 != api_get_current_access_url_id()
0 ignored issues
show
Deprecated Code introduced by
The function api_is_multiple_url_enabled() has been deprecated: Use AccessUrlHelper::isMultiple ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

85
        && /** @scrutinizer ignore-deprecated */ api_is_multiple_url_enabled() && -1 != api_get_current_access_url_id()

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
86
    ) {
87
        $access_url_rel_course_table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
88
        $sql .= " INNER JOIN $access_url_rel_course_table url_rel_course
89
                 ON (course.id = url_rel_course.c_id)";
90
    }
91
92
    if (!empty($_GET['session_id'])) {
93
        $session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
94
        $session = Database::get_main_table(TABLE_MAIN_SESSION);
95
96
        $sql .= " INNER JOIN $session_rel_course r ON course.id = r.c_id
97
            INNER JOIN $session s ON r.session_id = s.id ";
98
    }
99
100
    if (isset($_GET['keyword'])) {
101
        $keyword = Database::escape_string('%'.trim($_GET['keyword']).'%');
102
        $sql .= " WHERE (
103
            course.title LIKE '".$keyword."' OR
104
            course.code LIKE '".$keyword."' OR
105
            visual_code LIKE '".$keyword."'
106
        )
107
        ";
108
    } elseif (isset($_GET['keyword_code'])) {
109
        $keyword_code = Database::escape_string('%'.$_GET['keyword_code'].'%');
110
        $keyword_title = Database::escape_string('%'.$_GET['keyword_title'].'%');
111
        $keyword_category = isset($_GET['keyword_category'])
112
            ? Database::escape_string($_GET['keyword_category'])
113
            : null;
114
        $keyword_language = Database::escape_string('%'.$_GET['keyword_language'].'%');
115
        $keyword_visibility = Database::escape_string('%'.$_GET['keyword_visibility'].'%');
116
        $keyword_subscribe = Database::escape_string($_GET['keyword_subscribe']);
117
        $keyword_unsubscribe = Database::escape_string($_GET['keyword_unsubscribe']);
118
119
        $sql .= " WHERE
120
                (course.code LIKE '".$keyword_code."' OR visual_code LIKE '".$keyword_code."') AND
121
                course.title LIKE '".$keyword_title."' AND
122
                course_language LIKE '".$keyword_language."' AND
123
                visibility LIKE '".$keyword_visibility."' AND
124
                subscribe LIKE '".$keyword_subscribe."' AND
125
                unsubscribe LIKE '".$keyword_unsubscribe."'";
126
127
        if (!empty($keyword_category)) {
128
            $sql .= ' AND category.id = '.$keyword_category.' ';
129
        }
130
    }
131
132
    // Adding the filter to see the user's only of the current access_url.
133
    if ((api_is_platform_admin() || api_is_session_admin())
134
        && api_is_multiple_url_enabled() && -1 != api_get_current_access_url_id()
0 ignored issues
show
Deprecated Code introduced by
The function api_is_multiple_url_enabled() has been deprecated: Use AccessUrlHelper::isMultiple ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

134
        && /** @scrutinizer ignore-deprecated */ api_is_multiple_url_enabled() && -1 != api_get_current_access_url_id()

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
135
    ) {
136
        $sql .= ' AND url_rel_course.access_url_id='.api_get_current_access_url_id();
137
    }
138
139
    if (!empty($_GET['session_id'])) {
140
        $sessionId = (int) $_GET['session_id'];
141
        $sql .= ' AND s.id = '.$sessionId.' ';
142
    }
143
144
    if ($getCount) {
145
        $res = Database::query($sql);
146
        $row = Database::fetch_array($res);
147
        if ($row) {
148
            return (int) $row['count'];
149
        }
150
151
        return 0;
152
    }
153
154
    $sql .= ' GROUP BY course.code';
155
    $sql .= " ORDER BY col$column $direction ";
156
    $sql .= " LIMIT $from, $number_of_items";
157
158
    $res = Database::query($sql);
159
    $courses = [];
160
    $languages = api_get_languages();
161
162
    $path = api_get_path(WEB_CODE_PATH);
163
164
    while ($course = Database::fetch_array($res)) {
165
        $courseInfo = api_get_course_info_by_id($course['id']);
166
167
        // get categories
168
        $sqlCategoriesByCourseId = "SELECT category.title FROM $tblCourseCategory category
169
            INNER JOIN $tblCourseRelCategory course_rel_category ON category.id = course_rel_category.course_category_id
170
            WHERE course_rel_category.course_id = ".$course['id'];
171
        $resultCategories = Database::query($sqlCategoriesByCourseId);
172
        $categories = [];
173
174
        while ($category = Database::fetch_array($resultCategories)) {
175
            $categories[] = $category['title'];
176
        }
177
178
        // Place colour icons in front of courses.
179
        $show_visual_code = $course['visual_code'] != $course['col2'] ? Display::label($course['visual_code'], 'info') : null;
180
        $course['col1'] = get_course_visibility_icon($courseInfo['visibility']).\PHP_EOL
181
            .Display::url(Security::remove_XSS($course['col1']), $courseInfo['course_public_url']).\PHP_EOL
182
            .$show_visual_code;
183
        $course['col5'] = SUBSCRIBE_ALLOWED == $course['col5'] ? get_lang('Yes') : get_lang('No');
184
        $course['col6'] = UNSUBSCRIBE_ALLOWED == $course['col6'] ? get_lang('Yes') : get_lang('No');
185
186
        $courseId = $course['id'];
187
188
        $actions = [];
189
        $actions[] = Display::url(
190
            Display::getMdiIcon(
191
                ActionIcon::INFORMATION,
192
                'ch-tool-icon',
193
                null,
194
                ICON_SIZE_SMALL,
195
                get_lang('Information')
196
            ),
197
            "course_information.php?id=$courseId"
198
        );
199
        $actions[] = Display::url(
200
            Display::getMdiIcon(
201
                ToolIcon::COURSE_HOME,
202
                'ch-tool-icon',
203
                null,
204
                ICON_SIZE_SMALL,
205
                get_lang('Course home')
206
            ),
207
            $courseInfo['course_public_url']
208
        );
209
        $actions[] = Display::url(
210
            Display::getMdiIcon(
211
                ToolIcon::TRACKING,
212
                'ch-tool-icon',
213
                null,
214
                ICON_SIZE_SMALL,
215
                get_lang('Reporting')
216
            ),
217
            $path.'tracking/courseLog.php?'.api_get_cidreq_params($courseId)
218
        );
219
        $actions[] = Display::url(
220
            Display::getMdiIcon(
221
                ActionIcon::EDIT,
222
                'ch-tool-icon',
223
                null,
224
                ICON_SIZE_SMALL,
225
                get_lang('Edit')
226
            ),
227
            $path.'admin/course_edit.php?id='.$courseId
228
        );
229
        $actions[] = Display::url(
230
            Display::getMdiIcon(
231
                ActionIcon::TAKE_BACKUP,
232
                'ch-tool-icon',
233
                null,
234
                ICON_SIZE_SMALL,
235
                get_lang('Create a backup')
236
            ),
237
            $path.'course_copy/create_backup.php?'.api_get_cidreq_params($courseId)
238
        );
239
        $actions[] = Display::url(
240
            Display::getMdiIcon(
241
                ActionIcon::DELETE,
242
                'ch-tool-icon',
243
                null,
244
                ICON_SIZE_SMALL,
245
                get_lang('Delete')
246
            ),
247
            $path.'admin/course_list.php?delete_course='.$course['col0'],
248
            [
249
                'onclick' => "javascript: if (!confirm('"
250
                    .addslashes(api_htmlentities(get_lang('Please confirm your choice'), \ENT_QUOTES))
251
                    ."')) return false;",
252
            ]
253
        );
254
255
        $courseItem = [
256
            $course['col0'],
257
            $course['col1'],
258
            $course['col2'],
259
            $languages[$course['col3']] ?? $course['col3'],
260
            implode(', ', $categories),
261
            $course['col5'],
262
            $course['col6'],
263
            implode(\PHP_EOL, $actions),
264
        ];
265
        $courses[] = $courseItem;
266
    }
267
268
    return $courses;
269
}
270
271
/**
272
 * Return an icon representing the visibility of the course.
273
 *
274
 * @param int $visibility
275
 */
276
function get_course_visibility_icon(int $visibility): string
277
{
278
    $style = 'margin-bottom:0;margin-right:5px;';
279
280
    return match ($visibility) {
281
        0 => Display::getMdiIcon(
282
            StateIcon::CLOSED_VISIBILITY,
283
            'ch-tool-icon',
284
            null,
285
            22,
286
            get_lang('Closed - the course is only accessible to the teachers')
287
        ),
288
        1 => Display::getMdiIcon(
289
            StateIcon::PRIVATE_VISIBILITY,
290
            'ch-tool-icon',
291
            null,
292
            22,
293
            get_lang(
294
                'Private access (access authorized to group members only) access (access authorized to group members only)'
295
            )
296
        ),
297
        2 => Display::getMdiIcon(
298
            StateIcon::OPEN_VISIBILITY,
299
            'ch-tool-icon',
300
            null,
301
            22,
302
            get_lang(' Open - access allowed for users registered on the platform')
303
        ),
304
        3 => Display::getMdiIcon(
305
            StateIcon::PUBLIC_VISIBILITY,
306
            'ch-tool-icon',
307
            null,
308
            22,
309
            get_lang('Public - access allowed for the whole world')
310
        ),
311
        4 => Display::getMdiIcon(
312
            StateIcon::HIDDEN_VISIBILITY,
313
            'ch-tool-icon',
314
            null,
315
            22,
316
            get_lang('Hidden - Completely hidden to all users except the administrators')
317
        ),
318
        default => '',
319
    };
320
}
321
322
if (isset($_POST['action'])) {
323
    // Delete selected courses
324
    if ('delete_courses' == $_POST['action']) {
325
        if (!empty($_POST['course'])) {
326
            $course_codes = $_POST['course'];
327
            if (count($course_codes) > 0) {
328
                foreach ($course_codes as $course_code) {
329
                    CourseManager::delete_course($course_code);
330
                }
331
            }
332
333
            Display::addFlash(Display::return_message(get_lang('Deleted')));
334
        }
335
        api_location(api_get_self());
336
    }
337
}
338
$content = '';
339
$message = '';
340
$actions = '';
341
342
$interbreadcrumb[] = [
343
    'url' => 'index.php',
344
    'name' => get_lang('Administration'),
345
];
346
347
if (isset($_GET['search']) && 'advanced' === $_GET['search']) {
348
    // Get all course categories
349
    $interbreadcrumb[] = [
350
        'url' => 'course_list.php',
351
        'name' => get_lang('Course list'),
352
    ];
353
    $tool_name = get_lang('Search for a course');
354
    $form = new FormValidator('advanced_course_search', 'get');
355
    $form->addElement('header', $tool_name);
356
    $form->addText('keyword_code', get_lang('Course code'), false);
357
    $form->addText('keyword_title', get_lang('Title'), false);
358
359
    // Category code
360
    $url = api_get_path(WEB_AJAX_PATH).'course.ajax.php?a=search_category';
361
362
    $form->addElement(
363
        'select_ajax',
364
        'keyword_category',
365
        get_lang('Category'),
366
        null,
367
        [
368
            'url' => $url,
369
        ]
370
    );
371
372
    $el = $form->addSelectLanguage('keyword_language', get_lang('Course language'));
373
    $el->addOption(get_lang('All'), '%');
374
    $form->addElement('radio', 'keyword_visibility', get_lang('Course access'), get_lang('Public - access allowed for the whole world'), COURSE_VISIBILITY_OPEN_WORLD);
375
    $form->addElement('radio', 'keyword_visibility', null, get_lang(' Open - access allowed for users registered on the platform'), COURSE_VISIBILITY_OPEN_PLATFORM);
376
    $form->addElement('radio', 'keyword_visibility', null, get_lang('Private access (access authorized to group members only) access (access authorized to group members only)'), COURSE_VISIBILITY_REGISTERED);
377
    $form->addElement('radio', 'keyword_visibility', null, get_lang('Closed - the course is only accessible to the teachers'), COURSE_VISIBILITY_CLOSED);
378
    $form->addElement('radio', 'keyword_visibility', null, get_lang('Hidden - Completely hidden to all users except the administrators'), COURSE_VISIBILITY_HIDDEN);
379
    $form->addElement('radio', 'keyword_visibility', null, get_lang('All'), '%');
380
    $form->addElement('radio', 'keyword_subscribe', get_lang('Subscription'), get_lang('Allowed'), 1);
381
    $form->addElement('radio', 'keyword_subscribe', null, get_lang('This function is only available to trainers'), 0);
382
    $form->addElement('radio', 'keyword_subscribe', null, get_lang('All'), '%');
383
    $form->addElement('radio', 'keyword_unsubscribe', get_lang('Unsubscribe'), get_lang('Users are allowed to unsubscribe from this course'), 1);
384
    $form->addElement('radio', 'keyword_unsubscribe', null, get_lang('Users are not allowed to unsubscribe from this course'), 0);
385
    $form->addElement('radio', 'keyword_unsubscribe', null, get_lang('All'), '%');
386
    $form->addButtonSearch(get_lang('Search courses'));
387
    $defaults['keyword_language'] = '%';
388
    $defaults['keyword_visibility'] = '%';
389
    $defaults['keyword_subscribe'] = '%';
390
    $defaults['keyword_unsubscribe'] = '%';
391
    $form->setDefaults($defaults);
392
    $content .= $form->returnForm();
393
} else {
394
    $tool_name = get_lang('Course list');
395
    if (isset($_GET['delete_course'])) {
396
        $result = CourseManager::delete_course($_GET['delete_course']);
397
        if ($result) {
398
            Display::addFlash(Display::return_message(get_lang('Deleted')));
399
        }
400
401
        api_location(api_get_self());
402
    }
403
    // Create a search-box
404
    $form = new FormValidator(
405
        'search_simple',
406
        'get',
407
        '',
408
        '',
409
        [],
410
        FormValidator::LAYOUT_BOX_SEARCH
411
    );
412
    $form->addElement(
413
        'text',
414
        'keyword',
415
        null,
416
        ['id' => 'course-search-keyword', 'aria-label' => get_lang('Search courses')]
417
    );
418
    $form->addButtonSearch(get_lang('Search courses'));
419
    $advanced = '<a class="btn btn--plain" href="'.api_get_path(WEB_CODE_PATH).'admin/course_list.php?search=advanced">
420
        <em class="pi pi-search"></em> '.
421
        get_lang('Advanced search').'</a>';
422
423
    // Create a filter by session
424
    $sessionFilter = new FormValidator(
425
        'course_filter',
426
        'get',
427
        '',
428
        '',
429
        [],
430
        FormValidator::LAYOUT_INLINE
431
    );
432
    $url = api_get_path(WEB_AJAX_PATH).'session.ajax.php?a=search_session';
433
    $sessionSelect = $sessionFilter->addSelectAjax(
434
        'session_name',
435
        get_lang('Search course by session'),
436
        [],
437
        ['id' => 'session_name', 'url' => $url]
438
    );
439
440
    if (!empty($sessionId)) {
441
        $sessionInfo = SessionManager::fetch($sessionId);
442
        $sessionSelect->addOption(
443
            $sessionInfo['name'],
444
            $sessionInfo['id'],
445
            ['selected' => 'selected']
446
        );
447
    }
448
449
    $courseListUrl = api_get_self();
450
    $actions1 = Display::url(
451
        Display::getMdiIcon(
452
            ToolIcon::COURSE,
453
            'ch-tool-icon-gradient',
454
            null,
455
            32,
456
            get_lang('Create a course')
457
        ),
458
        api_get_path(WEB_CODE_PATH).'admin/course_add.php'
459
    );
460
461
    if ('true' === api_get_setting('course_validation')) {
462
        $actions1 .= Display::url(
463
            Display::getMdiIcon(
464
                'book-heart-outline',
465
                'ch-tool-icon',
466
                null,
467
                ICON_SIZE_MEDIUM,
468
                get_lang('Review incoming course requests')
469
            ),
470
            api_get_path(WEB_CODE_PATH).'admin/course_request_review.php'
471
        );
472
    }
473
474
    $actions2 = $form->returnForm();
475
    $actions3 = $sessionFilter->returnForm();
476
    $actions4 = $advanced;
477
    $actions4 .= '
478
    <script>
479
        $(function() {
480
            $("#session_name").on("change", function() {
481
                var sessionId = $(this).val();
482
                if (!sessionId) {
483
                    return;
484
                }
485
                window.location = "'.$courseListUrl.'?session_id="+sessionId;
486
            });
487
        });
488
    </script>';
489
490
    $actions = Display::toolbarAction('toolbar', [$actions1, $actions3.$actions4.$actions2]);
491
    // Create a sortable table with the course data
492
    $table = new SortableTable(
493
        'courses',
494
        'get_number_of_courses',
495
        'get_course_data',
496
        2,
497
        20,
498
        'ASC',
499
        'course-list'
500
    );
501
502
    $parameters = [];
503
    if (isset($_GET['keyword'])) {
504
        $parameters = ['keyword' => Security::remove_XSS($_GET['keyword'])];
505
    } elseif (isset($_GET['keyword_code'])) {
506
        $parameters['keyword_code'] = Security::remove_XSS($_GET['keyword_code']);
507
        $parameters['keyword_title'] = Security::remove_XSS($_GET['keyword_title']);
508
        if (isset($_GET['keyword_category'])) {
509
            $parameters['keyword_category'] = Security::remove_XSS($_GET['keyword_category']);
510
        }
511
        $parameters['keyword_language'] = Security::remove_XSS($_GET['keyword_language']);
512
        $parameters['keyword_visibility'] = Security::remove_XSS($_GET['keyword_visibility']);
513
        $parameters['keyword_subscribe'] = Security::remove_XSS($_GET['keyword_subscribe']);
514
        $parameters['keyword_unsubscribe'] = Security::remove_XSS($_GET['keyword_unsubscribe']);
515
    }
516
517
    $table->set_additional_parameters($parameters);
518
519
    $table->set_header(0, '', false, 'width="8px"');
520
    $table->set_header(1, get_lang('Title'), true, null, ['class' => 'title']);
521
    $table->set_header(2, get_lang('Course code'));
522
    $table->set_header(3, get_lang('Language'), false, 'width="70px"');
523
    $table->set_header(4, get_lang('Categories'));
524
    $table->set_header(5, get_lang('Registr. allowed'), true, 'width="60px"');
525
    $table->set_header(6, get_lang('Unreg. allowed'), false, 'width="50px"');
526
    $table->set_header(
527
        7,
528
        get_lang('Action'),
529
        false,
530
        null,
531
        ['class' => 'td_actions']
532
    );
533
    $table->set_form_actions(
534
        ['delete_courses' => get_lang('Delete selected course(s)')],
535
        'course'
536
    );
537
538
    $tab = CourseManager::getCourseListTabs('simple');
539
540
    $content .= $tab.$table->return_table();
541
}
542
543
$tpl = new Template($tool_name);
544
$tpl->assign('actions', $actions);
545
$tpl->assign('message', $message);
546
$tpl->assign('content', $content);
547
$tpl->display_one_col_template();
548