setExerciseInfoFromAikenText()   F
last analyzed

Complexity

Conditions 32
Paths 324

Size

Total Lines 111
Code Lines 75

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 75
dl 0
loc 111
rs 1.7833
c 0
b 0
f 0
cc 32
nc 324
nop 2

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
 * Generates aiken format using AI api.
48
 * Requires plugin ai_helper to connect to the api.
49
 */
50
function generateAikenForm()
51
{
52
    if (!('true' === api_get_plugin_setting('ai_helper', 'tool_enable') && 'true' === api_get_plugin_setting('ai_helper', 'tool_quiz_enable'))) {
53
        return false;
54
    }
55
56
    $form = new FormValidator(
57
        'aiken_generate',
58
        'post',
59
        api_get_self()."?".api_get_cidreq(),
60
        null
61
    );
62
    $form->addElement('header', get_lang('AIQuestionsGenerator'));
63
    $form->addElement('text', 'quiz_name', [get_lang('QuestionsTopic'), get_lang('QuestionsTopicHelp')]);
64
    $form->addRule('quiz_name', get_lang('ThisFieldIsRequired'), 'required');
65
    $form->addElement('number', 'nro_questions', [get_lang('NumberOfQuestions'), get_lang('AIQuestionsGeneratorNumberHelper')]);
66
    $form->addRule('nro_questions', get_lang('ThisFieldIsRequired'), 'required');
67
68
    $options = [
69
        'multiple_choice' => get_lang('MultipleAnswer'),
70
    ];
71
    $form->addElement(
72
        'select',
73
        'question_type',
74
        get_lang('QuestionType'),
75
        $options
76
    );
77
78
    $generateUrl = api_get_path(WEB_PLUGIN_PATH).'ai_helper/tool/answers.php';
79
    $language = api_get_interface_language();
80
    $form->addHtml('<script>
81
                $(function () {
82
                    $("#aiken-area").hide();
83
                    $("#generate-aiken").on("click", function (e) {
84
                      e.preventDefault();
85
                      e.stopPropagation();
86
87
                      var btnGenerate = $(this);
88
                      var quizName = $("[name=\'quiz_name\']").val();
89
                      var nroQ = parseInt($("[name=\'nro_questions\']").val());
90
                      var qType = $("[name=\'question_type\']").val();
91
                      var valid = (quizName != \'\' && nroQ > 0);
92
                      var qWeight = 1;
93
94
                      if (valid) {
95
                        btnGenerate.attr("disabled", true);
96
                        btnGenerate.text("'.get_lang('PleaseWaitThisCouldTakeAWhile').'");
97
                        $("#textarea-aiken").text("");
98
                        $("#aiken-area").hide();
99
                        $.getJSON("'.$generateUrl.'", {
100
                            "quiz_name": quizName,
101
                            "nro_questions": nroQ,
102
                            "question_type": qType,
103
                            "language": "'.$language.'"
104
                        }).done(function (data) {
105
                          btnGenerate.attr("disabled", false);
106
                          btnGenerate.text("'.get_lang('Generate').'");
107
                          if (data.success && data.success == true) {
108
                            $("#aiken-area").show();
109
                            $("#textarea-aiken").text(data.text);
110
                            $("input[name=\'ai_total_weight\']").val(nroQ * qWeight);
111
                            $("#textarea-aiken").focus();
112
                          } else {
113
                            var errorMessage = "'.get_lang('NoSearchResults').'. '.get_lang('PleaseTryAgain').'";
114
                            if (data.text) {
115
                                errorMessage = data.text;
116
                            }
117
                            alert(errorMessage);
118
                          }
119
                        });
120
                      }
121
                    });
122
                });
123
            </script>');
124
125
    $form->addButton(
126
        'generate_aiken_button',
127
        get_lang('Generate'),
128
        '',
129
        'default',
130
        'default',
131
        null,
132
        ['id' => 'generate-aiken']
133
    );
134
135
    $form->addHtml('<div id="aiken-area">');
136
    $form->addElement(
137
        'textarea',
138
        'aiken_format',
139
        get_lang('Answers'),
140
        [
141
            'id' => 'textarea-aiken',
142
            'style' => 'width: 100%; height: 250px;',
143
        ]
144
    );
145
    $form->addElement('number', 'ai_total_weight', get_lang('TotalWeight'));
146
    $form->addButtonImport(get_lang('Import'), 'submit_aiken_generated');
147
    $form->addHtml('</div>');
148
149
    echo $form->returnForm();
150
}
151
152
/**
153
 * Gets the uploaded file (from $_FILES) and unzip it to the given directory.
154
 *
155
 * @param string The directory where to do the work
156
 * @param string The path of the temporary directory where the exercise was uploaded and unzipped
157
 * @param string $baseWorkDir
158
 * @param string $uploadPath
159
 *
160
 * @return bool True on success, false on failure
161
 */
162
function get_and_unzip_uploaded_exercise($baseWorkDir, $uploadPath)
163
{
164
    $_course = api_get_course_info();
165
    $_user = api_get_user_info();
166
167
    // Check if the file is valid (not to big and exists)
168
    if (!isset($_FILES['userFile']) || !is_uploaded_file($_FILES['userFile']['tmp_name'])) {
169
        // upload failed
170
        return false;
171
    }
172
173
    if (preg_match('/.zip$/i', $_FILES['userFile']['name']) &&
174
        handle_uploaded_document(
175
            $_course,
176
            $_FILES['userFile'],
177
            $baseWorkDir,
178
            $uploadPath,
179
            $_user['user_id'],
180
            0,
181
            null,
182
            1,
183
            'overwrite',
184
            false,
185
            true
186
        )
187
    ) {
188
        if (!function_exists('gzopen')) {
189
            return false;
190
        }
191
        // upload successful
192
        return true;
193
    } elseif (preg_match('/.txt/i', $_FILES['userFile']['name']) &&
194
        handle_uploaded_document(
195
            $_course,
196
            $_FILES['userFile'],
197
            $baseWorkDir,
198
            $uploadPath,
199
            $_user['user_id'],
200
            0,
201
            null,
202
            0,
203
            'overwrite',
204
            false
205
        )
206
    ) {
207
        return true;
208
    }
209
210
    return false;
211
}
212
213
/**
214
 * Main function to import the Aiken exercise.
215
 *
216
 * @param string $file
217
 * @param array  $request
218
 *
219
 * @return mixed True on success, error message on failure
220
 */
221
function aikenImportExercise($file = null, $request = [])
222
{
223
    $exerciseInfo = [];
224
    $fileIsSet = false;
225
226
    if (isset($file)) {
227
        $fileIsSet = true;
228
        // The import is from aiken file format.
229
        $archivePath = api_get_path(SYS_ARCHIVE_PATH).'aiken/';
230
        $baseWorkDir = $archivePath;
231
232
        $uploadPath = 'aiken_'.api_get_unique_id();
233
        if (!is_dir($baseWorkDir.$uploadPath)) {
234
            mkdir($baseWorkDir.$uploadPath, api_get_permissions_for_new_directories(), true);
235
        }
236
237
        // set some default values for the new exercise
238
        $exerciseInfo['name'] = preg_replace('/.(zip|txt)$/i', '', $file);
239
        $exerciseInfo['total_weight'] = !empty($_POST['total_weight']) ? (int) ($_POST['total_weight']) : 20;
240
        $exerciseInfo['question'] = [];
241
242
        // if file is not a .zip, then we cancel all
243
        if (!preg_match('/.(zip|txt)$/i', $file)) {
244
            return 'YouMustUploadAZipOrTxtFile';
245
        }
246
247
        // unzip the uploaded file in a tmp directory
248
        if (preg_match('/.(zip|txt)$/i', $file)) {
249
            if (!get_and_unzip_uploaded_exercise($baseWorkDir.$uploadPath, '/')) {
250
                return 'ThereWasAProblemWithYourFile';
251
            }
252
        }
253
254
        // find the different manifests for each question and parse them
255
        $exerciseHandle = opendir($baseWorkDir.$uploadPath);
256
        $fileFound = false;
257
        $operation = false;
258
        $result = false;
259
260
        // Parse every subdirectory to search txt question files
261
        while (false !== ($file = readdir($exerciseHandle))) {
262
            if (is_dir($baseWorkDir.'/'.$uploadPath.$file) && $file != "." && $file != "..") {
263
                //find each manifest for each question repository found
264
                $questionHandle = opendir($baseWorkDir.'/'.$uploadPath.$file);
265
                while (false !== ($questionFile = readdir($questionHandle))) {
266
                    if (preg_match('/.txt$/i', $questionFile)) {
267
                        $result = aiken_parse_file(
268
                            $exerciseInfo,
269
                            $baseWorkDir,
270
                            $file,
271
                            $questionFile
272
                        );
273
                        $fileFound = true;
274
                    }
275
                }
276
            } elseif (preg_match('/.txt$/i', $file)) {
277
                $result = aiken_parse_file($exerciseInfo, $baseWorkDir.$uploadPath, '', $file);
278
                $fileFound = true;
279
            }
280
        }
281
282
        if (!$fileFound) {
283
            $result = 'NoTxtFileFoundInTheZip';
284
        }
285
286
        if (true !== $result) {
287
            return $result;
288
        }
289
    } elseif (!empty($request)) {
290
        // The import is from aiken generated in textarea.
291
        $exerciseInfo['name'] = $request['quiz_name'];
292
        $exerciseInfo['total_weight'] = !empty($_POST['ai_total_weight']) ? (int) ($_POST['ai_total_weight']) : (int) $request['nro_questions'];
293
        $exerciseInfo['question'] = [];
294
        $exerciseInfo['course_id'] = isset($request['course_id']) ? (int) $request['course_id'] : 0;
295
        setExerciseInfoFromAikenText($request['aiken_format'], $exerciseInfo);
296
    }
297
298
    // 1. Create exercise.
299
    if (!empty($exerciseInfo)) {
300
        $exercise = new Exercise($exerciseInfo['course_id']);
301
        $exercise->exercise = $exerciseInfo['name'];
302
        $exercise->disable(); // Invisible by default
303
        $exercise->updateResultsDisabled(0); // Auto-evaluation mode: show score and expected answers
304
        $exercise->save();
305
        $lastExerciseId = $exercise->selectId();
306
        $tableQuestion = Database::get_course_table(TABLE_QUIZ_QUESTION);
307
        $tableAnswer = Database::get_course_table(TABLE_QUIZ_ANSWER);
308
        if (!empty($lastExerciseId)) {
309
            $courseId = !empty($exerciseInfo['course_id']) ? (int) $exerciseInfo['course_id'] : api_get_course_int_id();
310
            foreach ($exerciseInfo['question'] as $key => $questionArray) {
311
                if (!isset($questionArray['title'])) {
312
                    continue;
313
                }
314
                // 2. Create question.
315
                $question = new Aiken2Question();
316
                $question->type = $questionArray['type'];
317
                $question->setAnswer();
318
                $question->updateTitle($questionArray['title']);
319
320
                if (isset($questionArray['description'])) {
321
                    $question->updateDescription($questionArray['description']);
322
                }
323
                $type = $question->selectType();
324
                $question->course = api_get_course_info_by_id($courseId);
325
                $question->type = constant($type);
326
                $question->save($exercise);
327
                $last_question_id = $question->selectId();
328
329
                // 3. Create answer
330
                $answer = new Answer($last_question_id, $courseId, $exercise, false);
331
                $answer->new_nbrAnswers = isset($questionArray['answer']) ? count($questionArray['answer']) : 0;
332
                $max_score = 0;
333
334
                $scoreFromFile = 0;
335
                if (isset($questionArray['score']) && !empty($questionArray['score'])) {
336
                    $scoreFromFile = $questionArray['score'];
337
                }
338
339
                foreach ($questionArray['answer'] as $key => $answers) {
340
                    $key++;
341
                    $answer->new_answer[$key] = $answers['value'];
342
                    $answer->new_position[$key] = $key;
343
                    $answer->new_comment[$key] = '';
344
                    // Correct answers ...
345
                    if (isset($questionArray['correct_answers']) &&
346
                        in_array($key, $questionArray['correct_answers'])
347
                    ) {
348
                        $answer->new_correct[$key] = 1;
349
                        if (isset($questionArray['feedback'])) {
350
                            $answer->new_comment[$key] = $questionArray['feedback'];
351
                        }
352
                    } else {
353
                        $answer->new_correct[$key] = 0;
354
                    }
355
356
                    if (isset($questionArray['weighting'][$key - 1])) {
357
                        $answer->new_weighting[$key] = $questionArray['weighting'][$key - 1];
358
                        $max_score += $questionArray['weighting'][$key - 1];
359
                    }
360
361
                    if (!empty($scoreFromFile) && $answer->new_correct[$key]) {
362
                        $answer->new_weighting[$key] = $scoreFromFile;
363
                    }
364
365
                    $params = [
366
                        'c_id' => $courseId,
367
                        'question_id' => $last_question_id,
368
                        'answer' => $answer->new_answer[$key],
369
                        'correct' => $answer->new_correct[$key],
370
                        'comment' => $answer->new_comment[$key],
371
                        'ponderation' => isset($answer->new_weighting[$key]) ? $answer->new_weighting[$key] : '',
372
                        'position' => $answer->new_position[$key],
373
                        'hotspot_coordinates' => '',
374
                        'hotspot_type' => '',
375
                    ];
376
377
                    $answerId = Database::insert($tableAnswer, $params);
378
                    if ($answerId) {
379
                        $params = [
380
                            'id_auto' => $answerId,
381
                            'iid' => $answerId,
382
                        ];
383
                        Database::update($tableAnswer, $params, ['iid = ?' => [$answerId]]);
384
                    }
385
                }
386
387
                if (!empty($scoreFromFile)) {
388
                    $max_score = $scoreFromFile;
389
                }
390
                $params = ['ponderation' => $max_score];
391
                Database::update(
392
                    $tableQuestion,
393
                    $params,
394
                    ['iid = ?' => [$last_question_id]]
395
                );
396
            }
397
398
            // Delete the temp dir where the exercise was unzipped
399
            if ($fileIsSet) {
400
                my_delete($baseWorkDir.$uploadPath);
401
            }
402
403
            // Invisible by default
404
            api_item_property_update(
405
                api_get_course_info(),
406
                TOOL_QUIZ,
407
                $lastExerciseId,
408
                'invisible',
409
                api_get_user_id()
410
            );
411
412
            return $lastExerciseId;
413
        }
414
    }
415
416
    return false;
417
}
418
419
/**
420
 * Set the exercise information from an aiken text formatted.
421
 */
422
function setExerciseInfoFromAikenText($aikenText, &$exerciseInfo)
423
{
424
    $detect = mb_detect_encoding($aikenText, 'ASCII', true);
425
    if ('ASCII' === $detect) {
426
        $data = explode("\n", $aikenText);
427
    } else {
428
        if (false !== stripos($aikenText, "\x0D") || false !== stripos($aikenText, "\r\n")) {
429
            $text = str_ireplace(["\x0D", "\r\n"], "\n", $aikenText); // Removes ^M char from win files.
430
            $data = explode("\n\n", $text);
431
        } else {
432
            $data = explode("\n", $aikenText);
433
        }
434
    }
435
436
    $questionIndex = 0;
437
    $answersArray = [];
438
    foreach ($data as $line => $info) {
439
        $info = trim($info);
440
        if (empty($info)) {
441
            continue;
442
        }
443
444
        //make sure it is transformed from iso-8859-1 to utf-8 if in that form
445
        if (!mb_check_encoding($info, 'utf-8') && mb_check_encoding($info, 'iso-8859-1')) {
446
            $info = utf8_encode($info);
447
        }
448
        $exerciseInfo['question'][$questionIndex]['type'] = 'MCUA';
449
450
        if (preg_match('/^([A-Za-z])(\)|\.)\s(.*)/', $info, $matches)) {
451
            //adding one of the possible answers
452
            $exerciseInfo['question'][$questionIndex]['answer'][]['value'] = $matches[3];
453
            $answersArray[] = $matches[1];
454
        } elseif (preg_match('/^ANSWER:\s?([A-Z])\s?/', $info, $matches)) {
455
            //the correct answers
456
            $correctAnswerIndex = array_search($matches[1], $answersArray);
457
            $exerciseInfo['question'][$questionIndex]['correct_answers'][] = $correctAnswerIndex + 1;
458
            //weight for correct answer
459
            $exerciseInfo['question'][$questionIndex]['weighting'][$correctAnswerIndex] = 1;
460
            $next = $line + 1;
461
462
            if (isset($data[$next]) && false !== strpos($data[$next], 'ANSWER_EXPLANATION:')) {
463
                continue;
464
            }
465
466
            if (isset($data[$next]) && false !== strpos($data[$next], 'DESCRIPTION:')) {
467
                continue;
468
            }
469
470
            // Check if next has score, otherwise loop too next question.
471
            if (isset($data[$next]) && false === strpos($data[$next], 'SCORE:')) {
472
                $answersArray = [];
473
                $questionIndex++;
474
                continue;
475
            }
476
        } elseif (preg_match('/^SCORE:\s?(.*)/', $info, $matches)) {
477
            $exerciseInfo['question'][$questionIndex]['score'] = (float) $matches[1];
478
            $answersArray = [];
479
            $questionIndex++;
480
            continue;
481
        } elseif (preg_match('/^DESCRIPTION:\s?(.*)/', $info, $matches)) {
482
            $exerciseInfo['question'][$questionIndex]['description'] = $matches[1];
483
            $next = $line + 1;
484
485
            if (isset($data[$next]) && false !== strpos($data[$next], 'ANSWER_EXPLANATION:')) {
486
                continue;
487
            }
488
            // Check if next has score, otherwise loop too next question.
489
            if (isset($data[$next]) && false === strpos($data[$next], 'SCORE:')) {
490
                $answersArray = [];
491
                $questionIndex++;
492
                continue;
493
            }
494
        } elseif (preg_match('/^ANSWER_EXPLANATION:\s?(.*)/', $info, $matches)) {
495
            // Comment of correct answer
496
            $correctAnswerIndex = array_search($matches[1], $answersArray);
497
            $exerciseInfo['question'][$questionIndex]['feedback'] = $matches[1];
498
            $next = $line + 1;
499
            // Check if next has score, otherwise loop too next question.
500
            if (isset($data[$next]) && false === strpos($data[$next], 'SCORE:')) {
501
                $answersArray = [];
502
                $questionIndex++;
503
                continue;
504
            }
505
        } elseif (preg_match('/^TEXTO_CORRECTA:\s?(.*)/', $info, $matches)) {
506
            //Comment of correct answer (Spanish e-ducativa format)
507
            $correctAnswerIndex = array_search($matches[1], $answersArray);
508
            $exerciseInfo['question'][$questionIndex]['feedback'] = $matches[1];
509
        } elseif (preg_match('/^T:\s?(.*)/', $info, $matches)) {
510
            //Question Title
511
            $correctAnswerIndex = array_search($matches[1], $answersArray);
512
            $exerciseInfo['question'][$questionIndex]['title'] = $matches[1];
513
        } elseif (preg_match('/^TAGS:\s?([A-Z])\s?/', $info, $matches)) {
514
            //TAGS for chamilo >= 1.10
515
            $exerciseInfo['question'][$questionIndex]['answer_tags'] = explode(',', $matches[1]);
516
        } elseif (preg_match('/^ETIQUETAS:\s?([A-Z])\s?/', $info, $matches)) {
517
            //TAGS for chamilo >= 1.10 (Spanish e-ducativa format)
518
            $exerciseInfo['question'][$questionIndex]['answer_tags'] = explode(',', $matches[1]);
519
        } else {
520
            if (empty($exerciseInfo['question'][$questionIndex]['title'])) {
521
                $exerciseInfo['question'][$questionIndex]['title'] = $info;
522
            }
523
        }
524
    }
525
526
    $totalQuestions = count($exerciseInfo['question']);
527
    $totalWeight = (int) $exerciseInfo['total_weight'];
528
    foreach ($exerciseInfo['question'] as $key => $question) {
529
        if (!isset($exerciseInfo['question'][$key]['weighting'])) {
530
            continue;
531
        }
532
        $exerciseInfo['question'][$key]['weighting'][current(array_keys($exerciseInfo['question'][$key]['weighting']))] = $totalWeight / $totalQuestions;
533
    }
534
}
535
536
/**
537
 * Parses an Aiken file and builds an array of exercise + questions to be
538
 * imported by the import_exercise() function.
539
 *
540
 * @param array The reference to the array in which to store the questions
541
 * @param string Path to the directory with the file to be parsed (without final /)
542
 * @param string Name of the last directory part for the file (without /)
543
 * @param string Name of the file to be parsed (including extension)
544
 * @param string $exercisePath
545
 * @param string $file
546
 * @param string $questionFile
547
 *
548
 * @return string|bool True on success, error message on error
549
 * @assert ('','','') === false
550
 */
551
function aiken_parse_file(&$exercise_info, $exercisePath, $file, $questionFile)
552
{
553
    $questionTempDir = $exercisePath.'/'.$file.'/';
554
    $questionFilePath = $questionTempDir.$questionFile;
555
556
    if (!is_file($questionFilePath)) {
557
        return 'FileNotFound';
558
    }
559
560
    $text = file_get_contents($questionFilePath);
561
    setExerciseInfoFromAikenText($text, $exercise_info);
562
563
    return true;
564
}
565
566
/**
567
 * Imports the zip file.
568
 *
569
 * @param array $array_file ($_FILES)
570
 *
571
 * @return bool
572
 */
573
function aiken_import_file($array_file)
574
{
575
    $unzip = 0;
576
    $process = process_uploaded_file($array_file, false);
577
    if (preg_match('/\.(zip|txt)$/i', $array_file['name'])) {
578
        // if it's a zip, allow zip upload
579
        $unzip = 1;
580
    }
581
582
    if ($process && $unzip == 1) {
583
        $imported = aikenImportExercise($array_file['name']);
584
        if (is_numeric($imported) && !empty($imported)) {
585
            Display::addFlash(Display::return_message(get_lang('Uploaded')));
586
587
            return $imported;
588
        } else {
589
            Display::addFlash(Display::return_message(get_lang($imported), 'error'));
590
591
            return false;
592
        }
593
    }
594
}
595