Passed
Push — 1.11.x ( bce6cd...c146d9 )
by Angel Fernando Quiroz
12:25
created

main/admin/course_edit.php (1 issue)

Labels
Severity
1
<?php
2
3
/* For licensing terms, see /license.txt */
4
5
use Chamilo\CoreBundle\Entity\CourseCategory;
0 ignored issues
show
This use statement conflicts with another class in this namespace, CourseCategory. Consider defining an alias.

Let?s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let?s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
6
use Chamilo\CoreBundle\Entity\Repository\CourseCategoryRepository;
7
use Chamilo\UserBundle\Entity\User;
8
9
$cidReset = true;
10
11
require_once __DIR__.'/../inc/global.inc.php';
12
$this_section = SECTION_PLATFORM_ADMIN;
13
14
api_protect_admin_script();
15
16
$course_table = Database::get_main_table(TABLE_MAIN_COURSE);
17
$em = Database::getManager();
18
/** @var CourseCategoryRepository $courseCategoriesRepo */
19
$courseCategoriesRepo = $em->getRepository('ChamiloCoreBundle:CourseCategory');
20
// Get all possible teachers.
21
$urlId = api_get_current_access_url_id();
22
23
$courseId = isset($_GET['id']) ? $_GET['id'] : null;
24
25
if (empty($courseId)) {
26
    api_not_allowed(true);
27
}
28
29
$courseInfo = api_get_course_info_by_id($courseId);
30
$courseCode = $courseInfo['code'];
31
32
if (empty($courseInfo)) {
33
    api_not_allowed(true);
34
}
35
36
$tool_name = get_lang('ModifyCourseInfo');
37
$interbreadcrumb[] = ['url' => 'index.php', 'name' => get_lang('PlatformAdmin')];
38
$interbreadcrumb[] = ['url' => 'course_list.php', 'name' => get_lang('CourseList')];
39
40
// Get all course categories
41
$table_user = Database::get_main_table(TABLE_MAIN_USER);
42
$course_code = $courseInfo['code'];
43
$courseId = $courseInfo['real_id'];
44
45
// Get course teachers
46
$table_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
47
$order_clause = api_sort_by_first_name() ? ' ORDER BY firstname, lastname' : ' ORDER BY lastname, firstname';
48
$sql = "SELECT user.id as user_id,lastname,firstname
49
        FROM
50
            $table_user as user,
51
            $table_course_user as course_user
52
        WHERE
53
            course_user.status='1' AND
54
            course_user.user_id=user.id AND
55
            course_user.c_id ='".$courseId."'".
56
            $order_clause;
57
$res = Database::query($sql);
58
$course_teachers = [];
59
while ($obj = Database::fetch_object($res)) {
60
    $course_teachers[] = $obj->user_id;
61
}
62
63
// Get all possible teachers without the course teachers
64
if (api_is_multiple_url_enabled()) {
65
    $access_url_rel_user_table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
66
    $sql = "SELECT u.id as user_id,lastname,firstname
67
            FROM $table_user as u
68
            INNER JOIN $access_url_rel_user_table url_rel_user
69
            ON (u.id=url_rel_user.user_id)
70
            WHERE
71
                url_rel_user.access_url_id = $urlId AND
72
                status = 1".$order_clause;
73
} else {
74
    $sql = "SELECT id as user_id, lastname, firstname
75
            FROM $table_user WHERE status='1'".$order_clause;
76
}
77
$courseInfo['tutor_name'] = null;
78
79
$res = Database::query($sql);
80
$teachers = [];
81
$allTeachers = [];
82
$platform_teachers[0] = '-- '.get_lang('NoManager').' --';
83
while ($obj = Database::fetch_object($res)) {
84
    $allTeachers[$obj->user_id] = api_get_person_name($obj->firstname, $obj->lastname);
85
    if (!array_key_exists($obj->user_id, $course_teachers)) {
86
        $teachers[$obj->user_id] = api_get_person_name($obj->firstname, $obj->lastname);
87
    }
88
89
    if (isset($course_teachers[$obj->user_id]) &&
90
        $courseInfo['tutor_name'] == $course_teachers[$obj->user_id]
91
    ) {
92
        $courseInfo['tutor_name'] = $obj->user_id;
93
    }
94
    // We add in the array platform teachers
95
    $platform_teachers[$obj->user_id] = api_get_person_name($obj->firstname, $obj->lastname);
96
}
97
98
// Case where there is no teacher in the course
99
if (count($course_teachers) == 0) {
100
    $sql = 'SELECT tutor_name FROM '.$course_table.' WHERE code="'.$course_code.'"';
101
    $res = Database::query($sql);
102
    $tutor_name = Database::result($res, 0, 0);
103
    $courseInfo['tutor_name'] = array_search($tutor_name, $platform_teachers);
104
}
105
106
// Build the form
107
$form = new FormValidator(
108
    'update_course',
109
    'post',
110
    api_get_self().'?id='.$courseId
111
);
112
$form->addHeader(get_lang('Course').'  #'.$courseInfo['real_id'].' '.$course_code);
113
$form->addElement('hidden', 'code', $course_code);
114
115
//title
116
$form->addText('title', get_lang('Title'), true);
117
$form->applyFilter('title', 'html_filter');
118
$form->applyFilter('title', 'trim');
119
120
// Code
121
$element = $form->addElement(
122
    'text',
123
    'real_code',
124
    [get_lang('CourseCode'), get_lang('ThisValueCantBeChanged')]
125
);
126
$element->freeze();
127
128
// Visual code
129
$form->addText(
130
    'visual_code',
131
    [
132
        get_lang('VisualCode'),
133
        get_lang('OnlyLettersAndNumbers'),
134
        get_lang('ThisValueIsUsedInTheCourseURL'),
135
    ],
136
    true,
137
    [
138
        'maxlength' => CourseManager::MAX_COURSE_LENGTH_CODE,
139
        'pattern' => '[a-zA-Z0-9]+',
140
        'title' => get_lang('OnlyLettersAndNumbers'),
141
    ]
142
);
143
144
$form->applyFilter('visual_code', 'strtoupper');
145
$form->applyFilter('visual_code', 'html_filter');
146
147
$countCategories = $courseCategoriesRepo->countAllInAccessUrl(
148
    $urlId,
149
    api_get_configuration_value('allow_base_course_category')
150
);
151
if ($countCategories >= 100) {
152
    // Category code
153
    $url = api_get_path(WEB_AJAX_PATH).'course.ajax.php?a=search_category';
154
155
    $categorySelect = $form->addElement(
156
        'select_ajax',
157
        'category_code',
158
        get_lang('CourseFaculty'),
159
        null,
160
        ['url' => $url]
161
    );
162
163
    if (!empty($courseInfo['categoryCode'])) {
164
        $data = \CourseCategory::getCategory($courseInfo['categoryCode']);
165
        $categorySelect->addOption($data['name'], $data['code']);
166
    }
167
} else {
168
    $courseInfo['category_code'] = $courseInfo['categoryCode'];
169
    $categories = $courseCategoriesRepo->findAllInAccessUrl(
170
        $urlId,
171
        api_get_configuration_value('allow_base_course_category')
172
    );
173
    $categoriesOptions = [null => get_lang('None')];
174
175
    /** @var CourseCategory $category */
176
    foreach ($categories as $category) {
177
        $categoriesOptions[$category->getCode()] = (string) $category;
178
    }
179
180
    $form->addSelect(
181
        'category_code',
182
        get_lang('CourseFaculty'),
183
        $categoriesOptions
184
    );
185
}
186
187
$courseTeacherNames = [];
188
foreach ($course_teachers as $courseTeacherId) {
189
    /** @var User $courseTeacher */
190
    $courseTeacher = UserManager::getRepository()->find($courseTeacherId);
191
    $courseTeacherNames[$courseTeacher->getId()] = UserManager::formatUserFullName($courseTeacher, true);
192
}
193
194
$form->addSelectAjax(
195
    'course_teachers',
196
    get_lang('CourseTeachers'),
197
    $courseTeacherNames,
198
    ['url' => api_get_path(WEB_AJAX_PATH).'user_manager.ajax.php?a=teacher_to_basis_course', 'multiple' => 'multiple']
199
);
200
$courseInfo['course_teachers'] = $course_teachers;
201
if (array_key_exists('add_teachers_to_sessions_courses', $courseInfo)) {
202
    $form->addElement(
203
        'checkbox',
204
        'add_teachers_to_sessions_courses',
205
        null,
206
        get_lang('TeachersWillBeAddedAsCoachInAllCourseSessions')
207
    );
208
}
209
210
$allowEditSessionCoaches = api_get_configuration_value('disabled_edit_session_coaches_course_editing_course') === false;
211
$coursesInSession = SessionManager::get_session_by_course($courseInfo['real_id']);
212
if (!empty($coursesInSession) && $allowEditSessionCoaches) {
213
    foreach ($coursesInSession as $session) {
214
        $sessionId = $session['id'];
215
        $coaches = SessionManager::getCoachesByCourseSession(
216
            $sessionId,
217
            $courseInfo['real_id']
218
        );
219
        $teachers = $allTeachers;
220
221
        $sessionTeachers = [];
222
        foreach ($coaches as $coachId) {
223
            $sessionTeachers[] = $coachId;
224
225
            if (isset($teachers[$coachId])) {
226
                unset($teachers[$coachId]);
227
            }
228
        }
229
230
        $groupName = 'session_coaches_'.$sessionId;
231
        $sessionUrl = api_get_path(WEB_CODE_PATH).'session/resume_session.php?id_session='.$sessionId;
232
        $form->addElement(
233
            'advmultiselect',
234
            $groupName,
235
            Display::url(
236
                $session['name'],
237
                $sessionUrl,
238
                ['target' => '_blank']
239
            ).' - '.get_lang('Coaches'),
240
            $allTeachers
241
        );
242
        $courseInfo[$groupName] = $sessionTeachers;
243
    }
244
}
245
246
$form->addText('department_name', get_lang('CourseDepartment'), false, ['size' => '60']);
247
$form->applyFilter('department_name', 'html_filter');
248
$form->applyFilter('department_name', 'trim');
249
250
$form->addText('department_url', get_lang('CourseDepartmentURL'), false, ['size' => '60']);
251
$form->applyFilter('department_url', 'html_filter');
252
$form->applyFilter('department_url', 'trim');
253
254
$form->addSelectLanguage('course_language', get_lang('CourseLanguage'));
255
256
$group = [];
257
$group[] = $form->createElement(
258
    'radio',
259
    'visibility',
260
    get_lang('CourseAccess'),
261
    get_lang('OpenToTheWorld'),
262
    COURSE_VISIBILITY_OPEN_WORLD
263
);
264
$group[] = $form->createElement(
265
    'radio',
266
    'visibility',
267
    null,
268
    get_lang('OpenToThePlatform'),
269
    COURSE_VISIBILITY_OPEN_PLATFORM
270
);
271
$group[] = $form->createElement('radio', 'visibility', null, get_lang('Private'), COURSE_VISIBILITY_REGISTERED);
272
$group[] = $form->createElement(
273
    'radio',
274
    'visibility',
275
    null,
276
    get_lang('CourseVisibilityClosed'),
277
    COURSE_VISIBILITY_CLOSED
278
);
279
$group[] = $form->createElement(
280
    'radio',
281
    'visibility',
282
    null,
283
    get_lang('CourseVisibilityHidden'),
284
    COURSE_VISIBILITY_HIDDEN
285
);
286
$form->addGroup($group, '', get_lang('CourseAccess'));
287
288
$group = [];
289
$group[] = $form->createElement('radio', 'subscribe', get_lang('Subscription'), get_lang('Allowed'), 1);
290
$group[] = $form->createElement('radio', 'subscribe', null, get_lang('Denied'), 0);
291
$form->addGroup($group, '', get_lang('Subscription'));
292
293
$group = [];
294
$group[] = $form->createElement(
295
    'radio',
296
    'unsubscribe',
297
    get_lang('Unsubscription'),
298
    get_lang('AllowedToUnsubscribe'),
299
    1
300
);
301
$group[] = $form->createElement('radio', 'unsubscribe', null, get_lang('NotAllowedToUnsubscribe'), 0);
302
$form->addGroup($group, '', get_lang('Unsubscription'));
303
304
$form->addElement('text', 'disk_quota', [get_lang('CourseQuota'), null, get_lang('MB')]);
305
$form->addRule('disk_quota', get_lang('ThisFieldIsRequired'), 'required');
306
$form->addRule('disk_quota', get_lang('ThisFieldShouldBeNumeric'), 'numeric');
307
308
// Extra fields
309
$extra_field = new ExtraField('course');
310
$extra = $extra_field->addElements(
311
    $form,
312
    $courseId,
313
    [],
314
    false,
315
    false,
316
    [],
317
    [],
318
    [],
319
    false,
320
    true
321
);
322
323
if (api_get_configuration_value('multiple_access_url_show_shared_course_marker')) {
324
    $urls = UrlManager::get_access_url_from_course($courseId);
325
    $urlToString = '';
326
    foreach ($urls as $url) {
327
        $urlToString .= $url['url'].'<br />';
328
    }
329
    $form->addLabel('URLs', $urlToString);
330
}
331
332
$htmlHeadXtra[] = '
333
<script>
334
$(function() {
335
    '.$extra['jquery_ready_content'].'
336
});
337
</script>';
338
339
$form->addButtonUpdate(get_lang('ModifyCourseInfo'));
340
341
// Set some default values
342
$courseInfo['disk_quota'] = round(DocumentManager::get_course_quota($courseInfo['code']) / 1024 / 1024, 1);
343
$courseInfo['real_code'] = $courseInfo['code'];
344
$courseInfo['add_teachers_to_sessions_courses'] = isset($courseInfo['add_teachers_to_sessions_courses']) ? $courseInfo['add_teachers_to_sessions_courses'] : 0;
345
$form->setDefaults($courseInfo);
346
347
// Validate form
348
if ($form->validate()) {
349
    $course = $form->getSubmitValues();
350
    $visibility = $course['visibility'];
351
352
    global $_configuration;
353
354
    if (isset($_configuration[$urlId]) &&
355
        isset($_configuration[$urlId]['hosting_limit_active_courses']) &&
356
        $_configuration[$urlId]['hosting_limit_active_courses'] > 0
357
    ) {
358
        // Check if
359
        if ($courseInfo['visibility'] == COURSE_VISIBILITY_HIDDEN &&
360
            $visibility != $courseInfo['visibility']
361
        ) {
362
            $num = CourseManager::countActiveCourses($urlId);
363
            if ($num >= $_configuration[$urlId]['hosting_limit_active_courses']) {
364
                api_warn_hosting_contact('hosting_limit_active_courses');
365
366
                Display::addFlash(
367
                    Display::return_message(get_lang('PortalActiveCoursesLimitReached'))
368
                );
369
370
                header('Location: course_list.php');
371
                exit;
372
            }
373
        }
374
    }
375
376
    $visual_code = $course['visual_code'];
377
    $visual_code = CourseManager::generate_course_code($visual_code);
378
379
    // Check if the visual code is already used by *another* course
380
    $visual_code_is_used = false;
381
382
    $warn = get_lang('TheFollowingCoursesAlreadyUseThisVisualCode');
383
    if (!empty($visual_code)) {
384
        $list = CourseManager::get_courses_info_from_visual_code($visual_code);
385
        foreach ($list as $course_temp) {
386
            if ($course_temp['code'] != $course_code) {
387
                $visual_code_is_used = true;
388
                $warn .= ' '.$course_temp['title'].' ('.$course_temp['code'].'),';
389
            }
390
        }
391
        $warn = substr($warn, 0, -1);
392
    }
393
394
    $teachers = isset($course['course_teachers']) ? $course['course_teachers'] : '';
395
    $title = $course['title'];
396
    $category_code = isset($course['category_code']) ? $course['category_code'] : '';
397
    $department_name = $course['department_name'];
398
    $department_url = $course['department_url'];
399
    $course_language = $course['course_language'];
400
    $course['disk_quota'] = $course['disk_quota'] * 1024 * 1024;
401
    $disk_quota = $course['disk_quota'];
402
    $subscribe = $course['subscribe'];
403
    $unsubscribe = $course['unsubscribe'];
404
    $course['course_code'] = $course_code;
405
406
    if (!stristr($department_url, 'http://')) {
407
        $department_url = 'http://'.$department_url;
408
    }
409
410
    Database::query($sql);
411
412
    $courseInfoBeforeUpdate = api_get_course_info_by_id($courseId);
413
    $title = str_replace('&amp;', '&', $title);
414
    $params = [
415
        'course_language' => $course_language,
416
        'title' => $title,
417
        'category_code' => $category_code,
418
        'visual_code' => $visual_code,
419
        'department_name' => $department_name,
420
        'department_url' => $department_url,
421
        'disk_quota' => $disk_quota,
422
        'visibility' => $visibility,
423
        'subscribe' => $subscribe,
424
        'unsubscribe' => $unsubscribe,
425
    ];
426
    Database::update($course_table, $params, ['id = ?' => $courseId]);
427
    CourseManager::saveSettingChanges($courseInfoBeforeUpdate, $params);
428
429
    // update the extra fields
430
    $courseFieldValue = new ExtraFieldValue('course');
431
    $courseFieldValue->saveFieldValues($course);
432
    $addTeacherToSessionCourses = isset($course['add_teachers_to_sessions_courses']) && !empty($course['add_teachers_to_sessions_courses']) ? 1 : 0;
433
434
    // Updating teachers
435
    if ($addTeacherToSessionCourses) {
436
        foreach ($coursesInSession as $session) {
437
            $sessionId = $session['id'];
438
            // Updating session coaches
439
            $sessionCoaches = isset($course['session_coaches_'.$sessionId]) ? $course['session_coaches_'.$sessionId] : [];
440
441
            if (!empty($sessionCoaches)) {
442
                foreach ($sessionCoaches as $teacherInfo) {
443
                    $coachesToSubscribe = isset($teacherInfo['coaches_by_session']) ? $teacherInfo['coaches_by_session'] : [];
444
                    SessionManager::updateCoaches(
445
                        $sessionId,
446
                        $courseId,
447
                        $coachesToSubscribe,
448
                        true
449
                    );
450
                }
451
            }
452
        }
453
454
        CourseManager::updateTeachers(
455
            $courseInfo,
456
            $teachers,
457
            true,
458
            true,
459
            false
460
        );
461
    } else {
462
        // Normal behaviour
463
        CourseManager::updateTeachers($courseInfo, $teachers, true, false);
464
465
        foreach ($coursesInSession as $session) {
466
            $sessionId = $session['id'];
467
            // Updating session coaches
468
            $sessionCoaches = isset($course['session_coaches_'.$sessionId]) ? $course['session_coaches_'.$sessionId] : [];
469
470
            if (!empty($sessionCoaches)) {
471
                SessionManager::updateCoaches(
472
                    $sessionId,
473
                    $courseId,
474
                    $sessionCoaches,
475
                    true
476
                );
477
            }
478
        }
479
    }
480
481
    if (array_key_exists('add_teachers_to_sessions_courses', $courseInfo)) {
482
        $sql = "UPDATE $course_table SET
483
                add_teachers_to_sessions_courses = '$addTeacherToSessionCourses'
484
                WHERE id = ".$courseInfo['real_id'];
485
        Database::query($sql);
486
    }
487
488
    $courseInfo = api_get_course_info($courseInfo['code']);
489
    $message = Display::url($courseInfo['title'], $courseInfo['course_public_url']);
490
    Display::addFlash(Display::return_message(get_lang('ItemUpdated').': '.$message, 'info', false));
491
    if ($visual_code_is_used) {
492
        Display::addFlash(Display::return_message($warn));
493
    }
494
    header('Location: course_list.php');
495
    exit;
496
}
497
498
Display::display_header($tool_name);
499
500
echo '<div class="actions">';
501
echo Display::url(
502
    Display::return_icon('back.png', get_lang('Back')),
503
    api_get_path(WEB_CODE_PATH).'admin/course_list.php'
504
);
505
echo Display::url(
506
    Display::return_icon('course_home.png', get_lang('CourseHome')),
507
    $courseInfo['course_public_url'],
508
    ['target' => '_blank']
509
);
510
511
echo Display::url(
512
    Display::return_icon('info2.png', get_lang('Info')),
513
    api_get_path(WEB_CODE_PATH)."admin/course_information.php?code=$courseCode"
514
);
515
516
echo '</div>';
517
518
echo "<script>
519
function moveItem(origin , destination) {
520
    for (var i = 0 ; i<origin.options.length ; i++) {
521
        if (origin.options[i].selected) {
522
            destination.options[destination.length] = new Option(origin.options[i].text,origin.options[i].value);
523
            origin.options[i]=null;
524
            i = i-1;
525
        }
526
    }
527
    destination.selectedIndex = -1;
528
    sortOptions(destination.options);
529
}
530
531
function sortOptions(options) {
532
533
    newOptions = new Array();
534
    for (i = 0 ; i<options.length ; i++) {
535
        newOptions[i] = options[i];
536
    }
537
    newOptions = newOptions.sort(mysort);
538
    options.length = 0;
539
    for (i = 0 ; i < newOptions.length ; i++) {
540
        options[i] = newOptions[i];
541
    }
542
}
543
544
function mysort(a, b) {
545
    if (a.text.toLowerCase() > b.text.toLowerCase()) {
546
        return 1;
547
    }
548
    if (a.text.toLowerCase() < b.text.toLowerCase()) {
549
        return -1;
550
    }
551
    return 0;
552
}
553
554
function valide() {
555
    // Checking all multiple
556
    $('select').filter(function() {
557
        if ($(this).attr('multiple')) {
558
            $(this).find('option').each(function() {
559
                $(this).attr('selected', true);
560
            });
561
        }
562
    });
563
}
564
</script>";
565
566
$form->display();
567
568
Display::display_footer();
569