Passed
Push — 1.11.x ( 295472...02ed0a )
by Julito
09:58
created

aiken_parse_file()   F

Complexity

Conditions 24
Paths 385

Size

Total Lines 129
Code Lines 70

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 24
eloc 70
c 1
b 0
f 0
nc 385
nop 4
dl 0
loc 129
rs 1.0208

How to fix   Long Method    Complexity   

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
/**
6
 * Library for the import of Aiken format.
7
 *
8
 * @author claro team <[email protected]>
9
 * @author Guillaume Lederer <[email protected]>
10
 * @author César Perales <[email protected]> Parse function for Aiken format
11
 */
12
13
/**
14
 * This function displays the form for import of the zip file with qti2.
15
 *
16
 * @param   string  Report message to show in case of error
17
 */
18
function aiken_display_form()
19
{
20
    $name_tools = get_lang('ImportAikenQuiz');
21
    $form = '<div class="actions">';
22
    $form .= '<a href="exercise.php?show=test&'.api_get_cidreq().'">'.
23
        Display::return_icon(
24
            'back.png',
25
            get_lang('BackToExercisesList'),
26
            '',
27
            ICON_SIZE_MEDIUM
28
        ).'</a>';
29
    $form .= '</div>';
30
    $form_validator = new FormValidator(
31
        'aiken_upload',
32
        'post',
33
        api_get_self()."?".api_get_cidreq(),
34
        null,
35
        ['enctype' => 'multipart/form-data']
36
    );
37
    $form_validator->addElement('header', $name_tools);
38
    $form_validator->addElement('text', 'total_weight', get_lang('TotalWeight'));
39
    $form_validator->addElement('file', 'userFile', get_lang('File'));
40
    $form_validator->addButtonUpload(get_lang('Upload'), 'submit');
41
    $form .= $form_validator->returnForm();
42
    $form .= '<blockquote>'.get_lang('ImportAikenQuizExplanation').'<br /><pre>'.get_lang('ImportAikenQuizExplanationExample').'</pre></blockquote>';
43
    echo $form;
44
}
45
46
/**
47
 * Gets the uploaded file (from $_FILES) and unzip it to the given directory.
48
 *
49
 * @param string The directory where to do the work
50
 * @param string The path of the temporary directory where the exercise was uploaded and unzipped
51
 * @param string $baseWorkDir
52
 * @param string $uploadPath
53
 *
54
 * @return bool True on success, false on failure
55
 */
56
function get_and_unzip_uploaded_exercise($baseWorkDir, $uploadPath)
57
{
58
    $_course = api_get_course_info();
59
    $_user = api_get_user_info();
60
61
    // Check if the file is valid (not to big and exists)
62
    if (!isset($_FILES['userFile']) || !is_uploaded_file($_FILES['userFile']['tmp_name'])) {
63
        // upload failed
64
        return false;
65
    }
66
67
    if (preg_match('/.zip$/i', $_FILES['userFile']['name']) &&
68
        handle_uploaded_document(
69
            $_course,
70
            $_FILES['userFile'],
71
            $baseWorkDir,
72
            $uploadPath,
73
            $_user['user_id'],
74
            0,
75
            null,
76
            1,
77
            'overwrite',
78
            false
79
        )
80
    ) {
81
        if (!function_exists('gzopen')) {
82
            return false;
83
        }
84
        // upload successful
85
        return true;
86
    } elseif (preg_match('/.txt/i', $_FILES['userFile']['name']) &&
87
        handle_uploaded_document(
88
            $_course,
89
            $_FILES['userFile'],
90
            $baseWorkDir,
91
            $uploadPath,
92
            $_user['user_id'],
93
            0,
94
            null,
95
            0,
96
            'overwrite',
97
            false
98
        )
99
    ) {
100
        return true;
101
    }
102
103
    return false;
104
}
105
106
/**
107
 * Main function to import the Aiken exercise.
108
 *
109
 * @param string $file
110
 *
111
 * @return mixed True on success, error message on failure
112
 */
113
function aiken_import_exercise($file)
114
{
115
    $archive_path = api_get_path(SYS_ARCHIVE_PATH).'aiken/';
116
    $baseWorkDir = $archive_path;
117
118
    if (!is_dir($baseWorkDir)) {
119
        mkdir($baseWorkDir, api_get_permissions_for_new_directories(), true);
120
    }
121
122
    $uploadPath = 'aiken_'.api_get_unique_id().'/';
123
124
    // set some default values for the new exercise
125
    $exercise_info = [];
126
    $exercise_info['name'] = preg_replace('/.(zip|txt)$/i', '', $file);
127
    $exercise_info['question'] = [];
128
129
    // if file is not a .zip, then we cancel all
130
    if (!preg_match('/.(zip|txt)$/i', $file)) {
131
        return 'YouMustUploadAZipOrTxtFile';
132
    }
133
134
    // unzip the uploaded file in a tmp directory
135
    if (preg_match('/.(zip|txt)$/i', $file)) {
136
        if (!get_and_unzip_uploaded_exercise($baseWorkDir, $uploadPath)) {
137
            return 'ThereWasAProblemWithYourFile';
138
        }
139
    }
140
141
    // find the different manifests for each question and parse them
142
    $exerciseHandle = opendir($baseWorkDir.$uploadPath);
143
    $file_found = false;
144
    $operation = false;
145
    $result = false;
146
147
    // Parse every subdirectory to search txt question files
148
    while (false !== ($file = readdir($exerciseHandle))) {
149
        if (is_dir($baseWorkDir.'/'.$uploadPath.$file) && $file != "." && $file != "..") {
150
            //find each manifest for each question repository found
151
            $questionHandle = opendir($baseWorkDir.'/'.$uploadPath.$file);
152
            while (false !== ($questionFile = readdir($questionHandle))) {
153
                if (preg_match('/.txt$/i', $questionFile)) {
154
                    $result = aiken_parse_file(
155
                        $exercise_info,
156
                        $baseWorkDir,
157
                        $file,
158
                        $questionFile
159
                    );
160
                    $file_found = true;
161
                }
162
            }
163
        } elseif (preg_match('/.txt$/i', $file)) {
164
            $result = aiken_parse_file($exercise_info, $baseWorkDir.$uploadPath, '', $file);
165
            $file_found = true;
166
        }
167
    }
168
169
    if (!$file_found) {
170
        $result = 'NoTxtFileFoundInTheZip';
171
    }
172
173
    if (true !== $result) {
174
        return $result;
175
    }
176
177
    // 1. Create exercise.
178
    $exercise = new Exercise();
179
    $exercise->exercise = $exercise_info['name'];
180
    $exercise->save();
181
    $last_exercise_id = $exercise->selectId();
182
    $tableQuestion = Database::get_course_table(TABLE_QUIZ_QUESTION);
183
    $tableAnswer = Database::get_course_table(TABLE_QUIZ_ANSWER);
184
    if (!empty($last_exercise_id)) {
185
        $courseId = api_get_course_int_id();
186
        foreach ($exercise_info['question'] as $key => $question_array) {
187
            // 2. Create question.
188
            $question = new Aiken2Question();
189
            $question->type = $question_array['type'];
190
            $question->setAnswer();
191
            $question->updateTitle($question_array['title']);
192
193
            if (isset($question_array['description'])) {
194
                $question->updateDescription($question_array['description']);
195
            }
196
            $type = $question->selectType();
197
            $question->type = constant($type);
198
            $question->save($exercise);
199
            $last_question_id = $question->selectId();
200
201
            // 3. Create answer
202
            $answer = new Answer($last_question_id, $courseId, $exercise, false);
203
            $answer->new_nbrAnswers = count($question_array['answer']);
204
            $max_score = 0;
205
206
            $scoreFromFile = 0;
207
            if (isset($question_array['score']) && !empty($question_array['score'])) {
208
                $scoreFromFile = $question_array['score'];
209
            }
210
211
            foreach ($question_array['answer'] as $key => $answers) {
212
                $key++;
213
                $answer->new_answer[$key] = $answers['value'];
214
                $answer->new_position[$key] = $key;
215
                $answer->new_comment[$key] = '';
216
                // Correct answers ...
217
                if (in_array($key, $question_array['correct_answers'])) {
218
                    $answer->new_correct[$key] = 1;
219
                    if (isset($question_array['feedback'])) {
220
                        $answer->new_comment[$key] = $question_array['feedback'];
221
                    }
222
                } else {
223
                    $answer->new_correct[$key] = 0;
224
                }
225
226
                if (isset($question_array['weighting'][$key - 1])) {
227
                    $answer->new_weighting[$key] = $question_array['weighting'][$key - 1];
228
                    $max_score += $question_array['weighting'][$key - 1];
229
                }
230
231
                if (!empty($scoreFromFile) && $answer->new_correct[$key]) {
232
                    $answer->new_weighting[$key] = $scoreFromFile;
233
                }
234
235
                $params = [
236
                    'c_id' => $courseId,
237
                    'question_id' => $last_question_id,
238
                    'answer' => $answer->new_answer[$key],
239
                    'correct' => $answer->new_correct[$key],
240
                    'comment' => $answer->new_comment[$key],
241
                    'ponderation' => isset($answer->new_weighting[$key]) ? $answer->new_weighting[$key] : '',
242
                    'position' => $answer->new_position[$key],
243
                    'hotspot_coordinates' => '',
244
                    'hotspot_type' => '',
245
                ];
246
247
                $answerId = Database::insert($tableAnswer, $params);
248
                if ($answerId) {
249
                    $params = [
250
                        'id_auto' => $answerId,
251
                        'id' => $answerId,
252
                    ];
253
                    Database::update($tableAnswer, $params, ['iid = ?' => [$answerId]]);
254
                }
255
            }
256
257
            if (!empty($scoreFromFile)) {
258
                $max_score = $scoreFromFile;
259
            }
260
            $params = ['ponderation' => $max_score];
261
            Database::update(
262
                $tableQuestion,
263
                $params,
264
                ['iid = ?' => [$last_question_id]]
265
            );
266
        }
267
268
        // Delete the temp dir where the exercise was unzipped
269
        my_delete($baseWorkDir.$uploadPath);
270
        $operation = $last_exercise_id;
271
    }
272
273
    return $operation;
274
}
275
276
/**
277
 * Parses an Aiken file and builds an array of exercise + questions to be
278
 * imported by the import_exercise() function.
279
 *
280
 * @param array The reference to the array in which to store the questions
281
 * @param string Path to the directory with the file to be parsed (without final /)
282
 * @param string Name of the last directory part for the file (without /)
283
 * @param string Name of the file to be parsed (including extension)
284
 * @param string $exercisePath
285
 * @param string $file
286
 * @param string $questionFile
287
 *
288
 * @return string|bool True on success, error message on error
289
 * @assert ('','','') === false
290
 */
291
function aiken_parse_file(&$exercise_info, $exercisePath, $file, $questionFile)
292
{
293
    $questionTempDir = $exercisePath.'/'.$file.'/';
294
    $questionFilePath = $questionTempDir.$questionFile;
295
296
    if (!is_file($questionFilePath)) {
297
        return 'FileNotFound';
298
    }
299
300
    $text = file_get_contents($questionFilePath);
301
    $detect = mb_detect_encoding($text, 'ASCII', true);
302
    if ('ASCII' === $detect) {
303
        $data = explode("\n", $text);
304
    } else {
305
        $text = str_ireplace(["\x0D", "\r\n"], "\n", $text); // Removes ^M char from win files.
306
        $data = explode("\n\n", $text);
307
    }
308
309
    $question_index = 0;
310
    $answers_array = [];
311
    foreach ($data as $line => $info) {
312
        $info = trim($info);
313
        if (empty($info)) {
314
            continue;
315
        }
316
317
        //make sure it is transformed from iso-8859-1 to utf-8 if in that form
318
        if (!mb_check_encoding($info, 'utf-8') && mb_check_encoding($info, 'iso-8859-1')) {
319
            $info = utf8_encode($info);
320
        }
321
        $exercise_info['question'][$question_index]['type'] = 'MCUA';
322
323
        if (preg_match('/^([A-Za-z])(\)|\.)\s(.*)/', $info, $matches)) {
324
            //adding one of the possible answers
325
            $exercise_info['question'][$question_index]['answer'][]['value'] = $matches[3];
326
            $answers_array[] = $matches[1];
327
        } elseif (preg_match('/^ANSWER:\s?([A-Z])\s?/', $info, $matches)) {
328
            //the correct answers
329
            $correct_answer_index = array_search($matches[1], $answers_array);
330
            $exercise_info['question'][$question_index]['correct_answers'][] = $correct_answer_index + 1;
331
            //weight for correct answer
332
            $exercise_info['question'][$question_index]['weighting'][$correct_answer_index] = 1;
333
            $next = $line + 1;
334
335
            if (false !== strpos($data[$next], 'ANSWER_EXPLANATION:')) {
336
                continue;
337
            }
338
339
            // Check if next has score, otherwise loop too next question.
340
            if (false === strpos($data[$next], 'SCORE:')) {
341
                $answers_array = [];
342
                $question_index++;
343
                continue;
344
            }
345
        } elseif (preg_match('/^SCORE:\s?(.*)/', $info, $matches)) {
346
            $exercise_info['question'][$question_index]['score'] = (float) $matches[1];
347
            $answers_array = [];
348
            $question_index++;
349
            continue;
350
        } elseif (preg_match('/^DESCRIPTION:\s?(.*)/', $info, $matches)) {
351
            $exercise_info['question'][$question_index]['description'] = $matches[1];
352
        } elseif (preg_match('/^ANSWER_EXPLANATION:\s?(.*)/', $info, $matches)) {
353
            // Comment of correct answer
354
            $correct_answer_index = array_search($matches[1], $answers_array);
355
            $exercise_info['question'][$question_index]['feedback'] = $matches[1];
356
357
            $next = $line + 1;
358
            // Check if next has score, otherwise loop too next question.
359
            if (false === strpos($data[$next], 'SCORE:')) {
360
                $answers_array = [];
361
                $question_index++;
362
                continue;
363
            }
364
365
        } elseif (preg_match('/^TEXTO_CORRECTA:\s?(.*)/', $info, $matches)) {
366
            //Comment of correct answer (Spanish e-ducativa format)
367
            $correct_answer_index = array_search($matches[1], $answers_array);
368
            $exercise_info['question'][$question_index]['feedback'] = $matches[1];
369
        } elseif (preg_match('/^T:\s?(.*)/', $info, $matches)) {
370
            //Question Title
371
            $correct_answer_index = array_search($matches[1], $answers_array);
372
            $exercise_info['question'][$question_index]['title'] = $matches[1];
373
        } elseif (preg_match('/^TAGS:\s?([A-Z])\s?/', $info, $matches)) {
374
            //TAGS for chamilo >= 1.10
375
            $exercise_info['question'][$question_index]['answer_tags'] = explode(',', $matches[1]);
376
        } elseif (preg_match('/^ETIQUETAS:\s?([A-Z])\s?/', $info, $matches)) {
377
            //TAGS for chamilo >= 1.10 (Spanish e-ducativa format)
378
            $exercise_info['question'][$question_index]['answer_tags'] = explode(',', $matches[1]);
379
        } elseif (empty($info)) {
380
            /*if (empty($exercise_info['question'][$question_index]['title'])) {
381
                $exercise_info['question'][$question_index]['title'] = $info;
382
            }
383
            //moving to next question (tolerate \r\n or just \n)
384
            if (empty($exercise_info['question'][$question_index]['correct_answers'])) {
385
                error_log('Aiken: Error in question index '.$question_index.': no correct answer defined');
386
387
                return 'ExerciseAikenErrorNoCorrectAnswerDefined';
388
            }
389
            if (empty($exercise_info['question'][$question_index]['answer'])) {
390
                error_log('Aiken: Error in question index '.$question_index.': no answer option given');
391
392
                return 'ExerciseAikenErrorNoAnswerOptionGiven';
393
            }
394
            $question_index++;
395
            //emptying answers array when moving to next question
396
            $answers_array = [];
397
            //$new_question = true;*/
398
        } else {
399
            if (empty($exercise_info['question'][$question_index]['title'])) {
400
                $exercise_info['question'][$question_index]['title'] = $info;
401
            }
402
            /*$question_index++;
403
            //emptying answers array when moving to next question
404
            $answers_array = [];
405
            $new_question = true;*/
406
        }
407
    }
408
409
    $total_questions = count($exercise_info['question']);
410
    $total_weight = !empty($_POST['total_weight']) ? (int) ($_POST['total_weight']) : 20;
411
    foreach ($exercise_info['question'] as $key => $question) {
412
        if (!isset($exercise_info['question'][$key]['weighting'])) {
413
            continue;
414
        }
415
        $exercise_info['question'][$key]['weighting'][current(array_keys($exercise_info['question'][$key]['weighting']))] = $total_weight / $total_questions;
416
    }
417
418
    //exit;
419
    return true;
420
}
421
422
/**
423
 * Imports the zip file.
424
 *
425
 * @param array $array_file ($_FILES)
426
 *
427
 * @return bool
428
 */
429
function aiken_import_file($array_file)
430
{
431
    $unzip = 0;
432
    $process = process_uploaded_file($array_file, false);
433
    if (preg_match('/\.(zip|txt)$/i', $array_file['name'])) {
434
        // if it's a zip, allow zip upload
435
        $unzip = 1;
436
    }
437
438
    if ($process && $unzip == 1) {
439
        $imported = aiken_import_exercise($array_file['name']);
440
        if (is_numeric($imported) && !empty($imported)) {
441
            Display::addFlash(Display::return_message(get_lang('Uploaded')));
442
443
            return $imported;
444
        } else {
445
            Display::addFlash(Display::return_message(get_lang($imported), 'error'));
446
447
            return false;
448
        }
449
    }
450
}
451