lib.php 6.25 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?php

/**
 * @package     local_asystgrade
 * @author      Artem Baranovskyi
 * @license     http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */

//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

23
use local_asystgrade\api\client;
24
25
use local_asystgrade\api\http_client;
use local_asystgrade\db\QuizQuery;
26
27
28
29
30
31
32
33
34
35
36
37

defined('MOODLE_INTERNAL') || die();

/**
 * A hook function that will process the data and insert the rating value.
 * The function must be called on the desired page like https://www.moodle.loc/mod/quiz/report.php?id=2&mode=grading&slot=1&qid=1&grade=needsgrading&includeauto=1
 *
 * @return void
 */

function local_asystgrade_before_footer()
{
38
    global $PAGE;
39
40

    // Получение параметров из URL
41
    $qid = optional_param('qid', null, PARAM_INT);
42
43
44
    $slot = optional_param('slot', false, PARAM_INT);

    if ($PAGE->url->compare(new moodle_url('/mod/quiz/report.php'), URL_MATCH_BASE) && $slot) {
45
        $quizQuery = new QuizQuery();
46

47
48
49
50
51
        if ($quizQuery->gradesExist($qid, $slot)) {
            error_log('Grades already exist in the database.');
            return;
        }

52
53
        $question_attempts = $quizQuery->get_question_attempts($qid, $slot);
        $referenceAnswer = $quizQuery->get_reference_answer($qid);
54

55
        $data = prepare_api_data($quizQuery, $question_attempts, $referenceAnswer);
56
57
58
59
60
61
        foreach ($data['studentAnswers'] as $index => $studentAnswer) {
            $userid = $data['studentIds'][$index];
            if ($quizQuery->gradesExist($qid, $userid)) {
                return;
            }
        }
62
        $inputNames = $data['inputNames'];
63
64
65
66
67
68
69
70
71
72
73

        error_log('Data prepared: ' . print_r($data, true));

        $apiendpoint = get_config('local_asystgrade', 'apiendpoint');
        if (!$apiendpoint) {
            $apiendpoint = 'http://127.0.0.1:5000/api/autograde'; // Default setting
        }

        error_log('APIendpoint: ' . $apiendpoint);

        try {
74
75
            $httpClient = new http_client();
            $apiClient = client::getInstance($apiendpoint, $httpClient);
76
77
78
79
            error_log('ApiClient initiated.');

            error_log('Sending data to API and getting grade');
            $response = $apiClient->send_data($data);
80
            $grades = json_decode($response, true);
81
82
83
84
85
86
87
88
89

            error_log('Grade obtained: ' . print_r($grades, true));
        } catch (Exception $e) {
            error_log('Error sending data to API: ' . $e->getMessage());
            return;
        }

        error_log('After API call');

90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
        pasteGradedMarks($grades, $inputNames);

        error_log('URL matches /mod/quiz/report.php in page_init');
    }
}

/**
 * Adds JavasScript scrypt to update marks
 *
 * @param mixed $grades
 * @param mixed $inputNames
 * @return void
 */
function pasteGradedMarks(mixed $grades, mixed $inputNames): void
{
    echo generate_script($grades, $inputNames);;
}

/**
 * @param QuizQuery $database
 * @param $question_attempts
 * @param $referenceAnswer
 * @return array
 */
function prepare_api_data(QuizQuery $database, $question_attempts, $referenceAnswer): array
{
    $studentAnswers = [];
    $inputNames = [];
118
    $studentIds = [];
119
120
121
122
123
124
125
126
127

    foreach ($question_attempts as $question_attempt) {
        $quizattempt_steps = $database->get_attempt_steps($question_attempt->id);

        foreach ($quizattempt_steps as $quizattempt_step) {
            if ($quizattempt_step->state === 'complete') {
                $studentAnswer = $database->get_student_answer($quizattempt_step->id);
                $studentAnswers[] = $studentAnswer;
                $inputNames[] = "q" . $question_attempt->questionusageid . ":" . $question_attempt->slot . "_-mark";
128
                $studentIds[] = $quizattempt_step->userid;
129
                error_log("Student Answer: $studentAnswer, Input Name: " . end($inputNames));
130
131
            }
        }
132

133
        $quizattempt_steps->close();
134
    }
135
136
137
138
139
140

    $question_attempts->close();

    return [
        'referenceAnswer' => $referenceAnswer,
        'studentAnswers' => $studentAnswers,
141
142
        'inputNames' => $inputNames,
        'studentIds' => $studentIds
143
    ];
144
145
}

146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
/**
 * Builds JavasScript scrypt to update marks using DOM manipulations
 *
 * @param $grades
 * @param $inputNames
 * @return string
 */
function generate_script($grades, $inputNames) {
    $script = "<script type='text/javascript'>
        document.addEventListener('DOMContentLoaded', function() {";

    foreach ($grades as $index => $grade) {
        if (isset($grade['predicted_grade'])) {
            $predicted_grade = $grade['predicted_grade'] == 'correct' ? 1 : 0;
            $input_name = $inputNames[$index];
            $script .= "
                console.log('Trying to update input: {$input_name} with grade: {$predicted_grade}');
                var gradeInput = document.querySelector('input[name=\"{$input_name}\"]');
                if (gradeInput) {
                    console.log('Found input: {$input_name}');
                    gradeInput.value = '{$predicted_grade}';
                } else {
                    console.log('Input not found: {$input_name}');
                }";
        }
    }

    $script .= "});
    </script>";

    return $script;
}

/**
 * Autoloader registration
 */
182
183
184
spl_autoload_register(function ($classname) {
    // Check if the class name starts with our plugin's namespace
    if (strpos($classname, 'local_asystgrade\\') === 0) {
185
        // Transforming the Namespace into the Path
186
187
188
189
190
191
192
193
194
        $classname = str_replace('local_asystgrade\\', '', $classname);
        $classname = str_replace('\\', DIRECTORY_SEPARATOR, $classname);
        $filepath  = __DIR__ . DIRECTORY_SEPARATOR . 'classes' . DIRECTORY_SEPARATOR . $classname . '.php';

        if (file_exists($filepath)) {
            require_once($filepath);
        }
    }
});