Completed
Push — 1.10.x ( a9323e...dc10cd )
by Angel Fernando Quiroz
124:05 queued 70:15
created

main/admin/course_user_import.php (1 issue)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
/* For licensing terms, see /license.txt */
3
4
/**
5
 * This tool allows platform admins to update course-user relations by uploading
6
 * a CSV file
7
 * @package chamilo.admin
8
 */
9
10
/**
11
 * Validates the imported data.
12
 */
13 View Code Duplication
function validate_data($users_courses)
14
{
15
    $errors = array();
16
    $coursecodes = array();
17
    foreach ($users_courses as $index => $user_course) {
18
        $user_course['line'] = $index + 1;
19
        // 1. Check whether mandatory fields are set.
20
        $mandatory_fields = array('UserName', 'CourseCode', 'Status');
21
        foreach ($mandatory_fields as $key => $field) {
22
            if (!isset($user_course[$field]) || strlen($user_course[$field]) == 0) {
23
                $user_course['error'] = get_lang($field.'Mandatory');
24
                $errors[]             = $user_course;
25
            }
26
        }
27
28
        // 2. Check whether coursecode exists.
29
        if (isset ($user_course['CourseCode']) && strlen($user_course['CourseCode']) != 0) {
30
            // 2.1 Check whethher code has been allready used by this CVS-file.
31
            if (!isset($coursecodes[$user_course['CourseCode']])) {
32
                // 2.1.1 Check whether course with this code exists in the system.
33
                $course_table = Database :: get_main_table(TABLE_MAIN_COURSE);
34
                $sql = "SELECT * FROM $course_table
35
                        WHERE code = '".Database::escape_string($user_course['CourseCode'])."'";
36
                $res = Database::query($sql);
37
                if (Database::num_rows($res) == 0) {
38
                    $user_course['error'] = get_lang('CodeDoesNotExists');
39
                    $errors[]             = $user_course;
40
                } else {
41
                    $coursecodes[$user_course['CourseCode']] = 1;
42
                }
43
            }
44
        }
45
46
47
        // 3. Check whether username exists.
48
        if (isset ($user_course['UserName']) && strlen($user_course['UserName']) != 0) {
49
            if (UserManager::is_username_available($user_course['UserName'])) {
50
                $user_course['error'] = get_lang('UnknownUser');
51
                $errors[]             = $user_course;
52
            }
53
        }
54
55
        // 4. Check whether status is valid.
56
        if (isset ($user_course['Status']) && strlen($user_course['Status']) != 0) {
57
            if ($user_course['Status'] != COURSEMANAGER && $user_course['Status'] != STUDENT) {
58
                $user_course['error'] = get_lang('UnknownStatus');
59
                $errors[]             = $user_course;
60
            }
61
        }
62
    }
63
64
    return $errors;
65
}
66
67
/**
68
 * Saves imported data.
69
 */
70
function save_data($users_courses)
71
{
72
    $user_table = Database::get_main_table(TABLE_MAIN_USER);
73
    $course_user_table = Database::get_main_table(TABLE_MAIN_COURSE_USER);
74
    $csv_data = array();
75
    $inserted_in_course = array();
76
    $courseListCache = [];
77
    $courseListById = [];
78
    foreach ($users_courses as $user_course) {
79
        if (!in_array($user_course['CourseCode'], array_keys($courseListCache))) {
80
            $courseInfo = api_get_course_info($user_course['CourseCode']);
81
            $courseListCache[$user_course['CourseCode']] = $courseInfo;
82
        } else {
83
            $courseInfo = $courseListCache[$user_course['CourseCode']];
84
        }
85
        $courseListById[$courseInfo['real_id']] = $courseInfo;
86
        $csv_data[$user_course['UserName']][$courseInfo['real_id']] = $user_course['Status'];
87
    }
88
89
    foreach ($csv_data as $username => $csv_subscriptions) {
90
91
        $sql = "SELECT * FROM $user_table u
92
                WHERE u.username = '".Database::escape_string($username)."'";
93
        $res = Database::query($sql);
94
        $obj = Database::fetch_object($res);
95
        $user_id = $obj->user_id;
96
        $sql = "SELECT * FROM $course_user_table cu
97
                WHERE cu.user_id = $user_id AND cu.relation_type <> ".COURSE_RELATION_TYPE_RRHH." ";
98
        $res = Database::query($sql);
99
        $db_subscriptions = array();
100
        while ($obj = Database::fetch_object($res)) {
101
            $db_subscriptions[$obj->c_id] = $obj->status;
102
        }
103
104
        $to_subscribe   = array_diff(array_keys($csv_subscriptions), array_keys($db_subscriptions));
105
        $to_unsubscribe = array_diff(array_keys($db_subscriptions), array_keys($csv_subscriptions));
106
107
        if ($_POST['subscribe']) {
108
            foreach ($to_subscribe as $courseId) {
109
                $courseInfo = $courseListById[$courseId];
110
                $courseCode = $courseInfo['code'];
111
112
                CourseManager::subscribe_user(
113
                    $user_id,
114
                    $courseCode,
115
                    $csv_subscriptions[$courseId]
116
                );
117
                $inserted_in_course[$courseInfo['code']] = $courseInfo['title'];
118
119
            }
120
        }
121
122
        if ($_POST['unsubscribe']) {
123
            foreach ($to_unsubscribe as $courseId) {
124
                $courseInfo = $courseListById[$courseId];
125
                $courseCode = $courseInfo['code'];
126
                CourseManager::unsubscribe_user($user_id, $courseCode);
127
            }
128
        }
129
    }
130
131
    return $inserted_in_course;
132
}
133
134
/**
135
 * Reads CSV-file.
136
 * @param string $file Path to the CSV-file
137
 * @return array All course-information read from the file
138
 */
139
function parse_csv_data($file)
140
{
141
    $courses = Import :: csvToArray($file);
0 ignored issues
show
Deprecated Code introduced by
The method Import::csvToArray() has been deprecated with message: use cvs_reader instead

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

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

Loading history...
142
    return $courses;
143
}
144
145
$cidReset = true;
146
147
include '../inc/global.inc.php';
148
149
// Setting the section (for the tabs).
150
$this_section = SECTION_PLATFORM_ADMIN;
151
152
// Protecting the admin section.
153
api_protect_admin_script();
154
155
$tool_name = get_lang('AddUsersToACourse').' CSV';
156
157
$interbreadcrumb[] = array('url' => 'index.php', 'name' => get_lang('PlatformAdmin'));
158
159
set_time_limit(0);
160
161
// Creating the form.
162
$form = new FormValidator('course_user_import');
163
$form->addElement('header', '', $tool_name);
164
$form->addElement('file', 'import_file', get_lang('ImportFileLocation'));
165
$form->addElement('checkbox', 'subscribe', get_lang('Action'), get_lang('SubscribeUserIfNotAllreadySubscribed'));
166
$form->addElement('checkbox', 'unsubscribe', '', get_lang('UnsubscribeUserIfSubscriptionIsNotInFile'));
167
$form->addButtonImport(get_lang('Import'));
168
$form->setDefaults(array('subscribe' => '1', 'unsubscribe' => 1));
169
$errors = array();
170
171
if ($form->validate()) {
172
    $users_courses = parse_csv_data($_FILES['import_file']['tmp_name']);
173
    $errors = validate_data($users_courses);
174
175
    if (count($errors) == 0) {
176
        $inserted_in_course = save_data($users_courses);
177
        // Build the alert message in case there were visual codes subscribed to.
178
        if ($_POST['subscribe']) {
179
            $warn = get_lang('UsersSubscribedToBecauseVisualCode').': ';
180
        } else {
181
            $warn = get_lang('UsersUnsubscribedFromBecauseVisualCode').': ';
182
        }
183
184
        if (!empty($inserted_in_course)) {
185
            $warn = $warn.' '.get_lang('FileImported');
186
            // The users have been inserted in more than one course.
187
            foreach ($inserted_in_course as $code => $info) {
188
                $warn .= ' '.$info.' ('.$code.') ';
189
            }
190
        } else {
191
            $warn = get_lang('ErrorsWhenImportingFile');
192
        }
193
194
        Display::addFlash(Display::return_message($warn));
195
196
        Security::clear_token();
197
        $tok = Security::get_token();
198
        header('Location: '.api_get_self());
199
        exit();
200
    }
201
}
202
203
// Displaying the header.
204
Display :: display_header($tool_name);
205
206 View Code Duplication
if (count($errors) != 0) {
207
    $error_message = '<ul>';
208
    foreach ($errors as $index => $error_course) {
209
        $error_message .= '<li>'.get_lang('Line').' '.$error_course['line'].': <strong>'.$error_course['error'].'</strong>: ';
210
        $error_message .= $error_course['Code'].' '.$error_course['Title'];
211
        $error_message .= '</li>';
212
    }
213
    $error_message .= '</ul>';
214
    Display :: display_error_message($error_message, false);
215
}
216
217
// Displaying the form.
218
$form->display();
219
?>
220
    <p><?php echo get_lang('CSVMustLookLike').' ('.get_lang('MandatoryFields').')'; ?> :</p>
221
    <blockquote>
222
<pre>
223
<b>UserName</b>;<b>CourseCode</b>;<b>Status</b>
224
jdoe;course01;<?php echo COURSEMANAGER; ?>
225
226
adam;course01;<?php echo STUDENT; ?>
227
</pre>
228
        <?php
229
        echo COURSEMANAGER.': '.get_lang('Teacher').'<br />';
230
        echo STUDENT.': '.get_lang('Student').'<br />';
231
        ?>
232
    </blockquote>
233
<?php
234
235
Display :: display_footer();
236