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

course_import.php ➔ getTeacherListInArray()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 1
dl 0
loc 8
rs 9.4285
c 0
b 0
f 0
1
<?php
2
/* For licensing terms, see /license.txt */
3
4
/**
5
 * This tool allows platform admins to create courses by uploading a CSV file
6
 * Copyright (c) 2005 Bart Mollet <[email protected]>
7
 * @package chamilo.admin
8
 */
9
10
/**
11
 * Validates imported data.
12
 */
13
function validate_data($courses)
0 ignored issues
show
Best Practice introduced by
The function validate_data() has been defined more than once; this definition is ignored, only the first definition in main/admin/class_import.php (L15-34) is considered.

This check looks for functions that have already been defined in other files.

Some Codebases, like WordPress, make a practice of defining functions multiple times. This may lead to problems with the detection of function parameters and types. If you really need to do this, you can mark the duplicate definition with the @ignore annotation.

/**
 * @ignore
 */
function getUser() {

}

function getUser($id, $realm) {

}

See also the PhpDoc documentation for @ignore.

Loading history...
14
{
15
    $errors = array ();
16
    $coursecodes = array ();
17
    foreach ($courses as $index => $course) {
18
        $course['line'] = $index +1;
19
20
        // 1. Check whether mandatory fields are set.
21
        $mandatory_fields = array ('Code', 'Title', 'CourseCategory');
22
        foreach ($mandatory_fields as $field) {
23
            if (!isset($course[$field]) || strlen($course[$field]) == 0) {
24
                $course['error'] = get_lang($field.'Mandatory');
25
                $errors[] = $course;
26
            }
27
        }
28
29
        // 2. Check current course code.
30
        if (isset ($course['Code']) && strlen($course['Code']) != 0) {
31
            // 2.1 Check whether code has been already used by this CVS-file.
32
            if (isset($coursecodes[$course['Code']])) {
33
                $course['error'] = get_lang('CodeTwiceInFile');
34
                $errors[] = $course;
35
            } else {
36
                // 2.2 Check whether course code has been occupied.
37
                $courseInfo = api_get_course_info($course['Code']);
38
                if (!empty($courseInfo)) {
39
                    $course['error'] = get_lang('CodeExists');
40
                    $errors[] = $course;
41
                }
42
            }
43
            $coursecodes[$course['Code']] = 1;
44
        }
45
46
        // 3. Check whether teacher exists.
47
        $teacherList = getTeacherListInArray($course['Teacher']);
48
49
        if (!empty($teacherList)) {
50
            foreach ($teacherList as $teacher) {
51
                $teacherInfo = api_get_user_info_from_username($teacher);
52
                if (empty($teacherInfo)) {
53
                    $course['error'] = get_lang('UnknownTeacher').' ('.$teacher.')';
54
                    $errors[] = $course;
55
                } else {
0 ignored issues
show
Unused Code introduced by
This else statement is empty and can be removed.

This check looks for the else branches of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These else branches can be removed.

if (rand(1, 6) > 3) {
print "Check failed";
} else {
    //print "Check succeeded";
}

could be turned into

if (rand(1, 6) > 3) {
    print "Check failed";
}

This is much more concise to read.

Loading history...
56
                    /*if ($teacherInfo['status'] != COURSEMANAGER) {
57
                        $course['error'] = get_lang('UserIsNotATeacher').' ('.$teacher.')';
58
                        $errors[] = $course;
59
                    }*/
60
                }
61
            }
62
        }
63
64
        // 4. Check whether course category exists.
65
        if (isset($course['CourseCategory']) && strlen($course['CourseCategory']) != 0) {
66
            $categoryInfo = getCategory($course['CourseCategory']);
67
            if (empty($categoryInfo)) {
68
                //@todo this is so bad even all lang variables are wrong ...
69
                $course['error'] = get_lang('UnkownCategoryCourseCode').' ('.$course['CourseCategory'].')';
70
                $errors[] = $course;
71
            }
72
        }
73
    }
74
75
    return $errors;
76
}
77
78
/**
79
 * @param array $teachers
80
 *
81
 * @return array
82
 */
83
function getTeacherListInArray($teachers)
84
{
85
    if (!empty($teachers)) {
86
        return explode('|', $teachers);
87
    }
88
89
    return array();
90
}
91
92
/**
93
 * Saves imported data.
94
 * @param array $courses List of courses
95
 */
96
function save_data($courses)
0 ignored issues
show
Best Practice introduced by
The function save_data() has been defined more than once; this definition is ignored, only the first definition in main/admin/class_import.php (L39-47) is considered.

This check looks for functions that have already been defined in other files.

Some Codebases, like WordPress, make a practice of defining functions multiple times. This may lead to problems with the detection of function parameters and types. If you really need to do this, you can mark the duplicate definition with the @ignore annotation.

/**
 * @ignore
 */
function getUser() {

}

function getUser($id, $realm) {

}

See also the PhpDoc documentation for @ignore.

Loading history...
97
{
98
    $msg = '';
99
    foreach ($courses as $course) {
100
        $course_language = $course['Language'];
101
        $teachers = getTeacherListInArray($course['Teacher']);
102
        $teacherList = array();
103
        $creatorId = api_get_user_id();
104
105
        if (!empty($teachers)) {
106
            foreach ($teachers as $teacher) {
107
                $teacherInfo = api_get_user_info_from_username($teacher);
108
                if (!empty($teacherInfo)) {
109
                    $teacherList[] = $teacherInfo;
110
                }
111
            }
112
        }
113
114
        $params = array();
115
        $params['title'] = $course['Title'];
116
        $params['wanted_code'] = $course['Code'];
117
        $params['tutor_name'] = null;
118
        $params['course_category'] = $course['CourseCategory'];
119
        $params['course_language'] = $course_language;
120
        $params['user_id'] = $creatorId;
121
122
        $addMeAsTeacher = isset($_POST['add_me_as_teacher']) ? $_POST['add_me_as_teacher'] : false;
123
        $params['add_user_as_teacher'] = $addMeAsTeacher;
124
125
        $courseInfo = CourseManager::create_course($params);
126
127
        if (!empty($courseInfo)) {
128
            if (!empty($teacherList)) {
129
                foreach ($teacherList as $teacher) {
130
                    CourseManager::add_user_to_course(
131
                        $teacher['user_id'],
132
                        $courseInfo['code'],
133
                        COURSEMANAGER
134
                    );
135
                }
136
            }
137
            $msg .= '<a href="'.api_get_path(WEB_COURSE_PATH).$courseInfo['directory'].'/">
138
                    '.$courseInfo['title'].'</a> '.get_lang('Created').'<br />';
139
        }
140
    }
141
142
    if (!empty($msg)) {
143
        Display::display_normal_message($msg, false);
144
    }
145
}
146
147
/**
148
 * Read the CSV-file
149
 * @param string $file Path to the CSV-file
150
 * @return array All course-information read from the file
151
 */
152
function parse_csv_data($file)
0 ignored issues
show
Best Practice introduced by
The function parse_csv_data() has been defined more than once; this definition is ignored, only the first definition in main/admin/class_user_import.php (L129-132) is considered.

This check looks for functions that have already been defined in other files.

Some Codebases, like WordPress, make a practice of defining functions multiple times. This may lead to problems with the detection of function parameters and types. If you really need to do this, you can mark the duplicate definition with the @ignore annotation.

/**
 * @ignore
 */
function getUser() {

}

function getUser($id, $realm) {

}

See also the PhpDoc documentation for @ignore.

Loading history...
153
{
154
    $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...
155
    return $courses;
156
}
157
158
$cidReset = true;
159
160
require '../inc/global.inc.php';
161
162
$this_section = SECTION_PLATFORM_ADMIN;
163
api_protect_admin_script();
164
165
$defined_auth_sources[] = PLATFORM_AUTH_SOURCE;
166
167
if (isset($extAuthSource) && is_array($extAuthSource)) {
168
    $defined_auth_sources = array_merge($defined_auth_sources, array_keys($extAuthSource));
169
}
170
171
$tool_name = get_lang('ImportCourses').' CSV';
172
173
$interbreadcrumb[] = array('url' => 'index.php', 'name' => get_lang('PlatformAdmin'));
174
175
set_time_limit(0);
176
Display :: display_header($tool_name);
177
178
if (isset($_POST['formSent']) && $_POST['formSent']) {
179
    if (empty($_FILES['import_file']['tmp_name'])) {
180
        $error_message = get_lang('UplUploadFailed');
181
        Display :: display_error_message($error_message, false);
182
    } else {
183
        $allowed_file_mimetype = array('csv');
184
185
        $ext_import_file = substr($_FILES['import_file']['name'], (strrpos($_FILES['import_file']['name'], '.') + 1));
186
187 View Code Duplication
        if (!in_array($ext_import_file, $allowed_file_mimetype)) {
188
            Display :: display_error_message(get_lang('YouMustImportAFileAccordingToSelectedOption'));
189
        } else {
190
            $courses = parse_csv_data($_FILES['import_file']['tmp_name']);
191
            $errors = validate_data($courses);
192
            if (count($errors) == 0) {
193
                save_data($courses);
194
            }
195
        }
196
    }
197
}
198
199
if (isset($errors) && count($errors) != 0) {
200
    $error_message = '<ul>';
201
    foreach ($errors as $index => $error_course) {
202
        $error_message .= '<li>'.get_lang('Line').' '.$error_course['line'].': <strong>'.$error_course['error'].'</strong>: ';
203
        $error_message .= get_lang('Course').': '.$error_course['Title'].' ('.$error_course['Code'].')';
204
        $error_message .= '</li>';
205
    }
206
    $error_message .= '</ul>';
207
    Display :: display_error_message($error_message, false);
208
}
209
210
$form = new FormValidator('import', 'post', api_get_self(), null, array('enctype' => 'multipart/form-data'));
211
$form->addHeader($tool_name);
212
$form->addElement('file', 'import_file', get_lang('ImportCSVFileLocation'));
213
$form->addElement('checkbox', 'add_me_as_teacher', null, get_lang('AddMeAsTeacherInCourses'));
214
$form->addButtonImport(get_lang('Import'), 'save');
215
$form->addElement('hidden', 'formSent', 1);
216
$form->display();
217
218
?>
219
<div style="clear: both;"></div>
220
<p><?php echo get_lang('CSVMustLookLike').' ('.get_lang('MandatoryFields').')'; ?> :</p>
221
222
<blockquote>
223
<pre>
224
<strong>Code</strong>;<strong>Title</strong>;<strong>CourseCategory</strong>;Teacher;Language
225
BIO0015;Biology;BIO;teacher1;english
226
BIO0016;Maths;MATH;teacher2|teacher3;english
227
BIO0017;Language;LANG;;english
228
</pre>
229
</blockquote>
230
231
<?php
232
Display :: display_footer();
233