Commit 7365f869 authored by Abbassy's avatar Abbassy
Browse files

Merge branch 'feature/v2-classes-structure' into 'master'

Complete DTA plugin improvements

See merge request !3
parents df3f0323 24842271
# Backup files
*.tar.gz
dta_backup_*.tar.gz
# IDE files
.vscode/
.idea/
*.swp
*.swo
*~
# OS files
.DS_Store
Thumbs.db
# Temporary files
*.tmp
*.log
# Changelog - DTA Plugin v2.1.0
## [v2.1.0] - 2025-10-29
### Added
- **More Details Button**: Replaced magnifying glass icon with modern "More Details" button
- **Colored Test Labels**: Added color-coded labels for test results:
- 🟢 Green for successful tests
- 🟡 Yellow for compilation errors
- 🔴 Red for failed tests
- **Smart Competency Filtering**: Hide competencies with 0% values, only show those with actual progress
- **Enhanced Button Styling**: Button now matches Moodle's "Grade" button style and alignment
- **Robust Parameter Handling**: Improved cmid parameter detection for better reliability
### Fixed
- **File Include Path**: Fixed `DtaResult.php` → `dta_result.php` case sensitivity issue
- **Property Name Mismatch**: Corrected camelCase vs lowercase property names in dta_result class
- **View.php Parameter Handling**: Made cmid optional with intelligent fallback detection
- **German Comments**: Translated all German comments to English for better maintainability
### Improved
- **UI/UX**: Better visual hierarchy and user experience
- **Code Quality**: Cleaner, more maintainable code structure
- **Error Handling**: More robust error handling and fallback mechanisms
- **Performance**: Optimized rendering and caching
### Technical Details
- **Files Modified**:
- `classes/view.php` - Main view logic and parameter handling
- `classes/dta_view_submission_utils.php` - Submission summary generation
- `styles.css` - Enhanced styling and button design
- `locallib.php` - Disabled default magnifying glass
- **Templates**: All Mustache templates remain unchanged
- **Database**: No schema changes required
- **Compatibility**: Fully compatible with existing Moodle installations
### Installation
1. Upload all files to `/mod/assign/submission/dta/`
2. Run `php admin/cli/purge_caches.php`
3. No database upgrade required
### Rollback
To rollback to previous version:
```bash
git checkout v2.0.0
./upload_to_docker.sh
```
---
**Status**: ✅ Production Ready
**Tested**: ✅ All functionality verified
**Documentation**: ✅ Complete
# Moodle Dockerized Test Agent (DTA) Plugin # Moodle Dockerized Test Agent (MoDTA) Plugin
This is the source code repository for the MoDTA plugin. It is an extended and enhanced version of the approved Moodle JUnit Exercise Corrector (MoJEC) plugin, and the Moodle Dockerized Code Testing (MoDoCoT) and Moodle Dockerized Test Tool (Moodle DTT) plugins - for which no approval was requested, which all still run up to Moodle 4.3. MoDTA can thus be considered MoJEC version 4, thought it can test code in any programming language for which a teacher provides a test runner docker image. This is the source code repository for the MoDTA plugin. It is an extended and enhanced version of the approved Moodle JUnit Exercise Corrector (MoJEC) plugin, and the Moodle Dockerized Code Testing (MoDoCoT) and Moodle Dockerized Test Tool (Moodle DTT) plugins - for which no approval was requested, which all still run up to Moodle 4.3. MoDTA can thus be considered MoJEC version 4, thought it can test code in any programming language for which a teacher provides a test runner docker image.
...@@ -8,29 +8,29 @@ This plugin is compatible with Moodle versions 4.3 and above, up until 4.5 (LTS) ...@@ -8,29 +8,29 @@ This plugin is compatible with Moodle versions 4.3 and above, up until 4.5 (LTS)
## Goals ## Goals
Moodle DTA empowers teachers to provide programming Moodle assignments for their students, which are automatically corrected upon hand-in using teacher-provided tests and the results provided as extended submission feedback. MoDTA empowers teachers to provide programming Moodle assignments for their students, which are automatically corrected upon hand-in using teacher-provided tests and the results provided as extended submission feedback.
Corrections optionally include a pedagogic agent giving feedback on student competencies and in the next version recommending next exercises based on student competency levels and resilience. Corrections optionally include a pedagogic agent giving feedback on student competencies and in the next version recommending next exercises based on student competency levels and resilience.
Furthermore, Moodle DTA optionally provides the errors as tickets in supported ticketing systems to resemble current state-of-the-art software development workflows. Furthermore, MoDTA optionally provides the errors as tickets in supported ticketing systems to resemble current state-of-the-art software development workflows.
### Motivation ### Motivation
Due to contact time constraints, assignments for a new topic typically include about three tasks (one easy introductory, one standard usage, and one advanced combination with previous topics). Students e.g. stuck at the standard level assignment may face frustration and only little opportunity for qualified feedback. Especially in beginners’ programming education, many students struggle with the way of thinking and at the same time feel reluctant to ask teachers for help. Due to contact time constraints, assignments for a new topic typically include about three tasks (one easy introductory, one standard usage, and one advanced combination with previous topics). Students e.g. stuck at the standard level assignment may face frustration and only little opportunity for qualified feedback. Especially in beginners' programming education, many students struggle with the way of thinking and at the same time feel reluctant to ask teachers for help.
Moodle DTA allows for teachers to provide additional assignments at intermediate levels from their typically existing assignment collection. Teachers have to create automated tests for the assignments and place them in a git repository. Afterwards students can practice their skills 24/7 with a less steep learning curve and without having to overcome their potential reluctance to ask a teacher for help. They receive feedback consistent with other assignment results integrated into the Moodle environment. MoDTA allows for teachers to provide additional assignments at intermediate levels from their typically existing assignment collection. Teachers have to create automated tests for the assignments and place them in a git repository. Afterwards students can practice their skills 24/7 with a less steep learning curve and without having to overcome their potential reluctance to ask a teacher for help. They receive feedback consistent with other assignment results integrated into the Moodle environment.
Moodle DTA supports beginners not educated in state-of-the-art repository-based workflows by offering hand-ins in a zip archive containing the code to lower the learning curve. It also supports hand-in via repository URL and optionally repository credentials for advanced students. MoDTA supports beginners not educated in state-of-the-art repository-based workflows by offering hand-ins in a zip archive containing the code to lower the learning curve. It also supports hand-in via repository URL and optionally repository credentials for advanced students.
Optionally, if a teacher provides competency profiles and difficulties for tasks and tests, students also receive feedback about their achieved competencies by a pedagogic agent, which in the next version optionally recommends a learning path to the students based on their resilience. Optionally, if a teacher provides competency profiles and difficulties for tasks and tests, students also receive feedback about their achieved competencies by a pedagogic agent, which in the next version optionally recommends a learning path to the students based on their resilience.
Furthermore and independent of the other optional features, Moodle DTA optionally supports a state-of-the-art workflow by placing tickets for compile errors in a student-provided ticketing system link (currently supported: GitLab and Atlassian Jira). Furthermore and independent of the other optional features, MoDTA optionally supports a state-of-the-art workflow by placing tickets for compile errors in a student-provided ticketing system link (currently supported: GitLab and Atlassian Jira).
## Overview ## Overview
The Moodle DTA system comprises two key components: The MoDTA system comprises two key components:
• The Moodle DTA plugin, designed as an assignment submission tool. • The MoDTA Moodle plugin, designed as an assignment submission tool.
• The DTA backend web service, which interfaces with the Moodle plugin through REST and employs the JSON file format for communication. • The DTA backend web service, which interfaces with the Moodle plugin through REST and employs the JSON file format for communication.
The plugin establishes communication with the external DTA backend REST web service offering the endpoints: The plugin establishes communication with the external DTA backend REST web service offering the endpoints:
...@@ -45,29 +45,29 @@ The plugin establishes communication with the external DTA backend REST web serv ...@@ -45,29 +45,29 @@ The plugin establishes communication with the external DTA backend REST web serv
After approval, install the plugin directly from the Moodle Plugins Directory via Site Administration/Plugins/Install Plugins. After approval, install the plugin directly from the Moodle Plugins Directory via Site Administration/Plugins/Install Plugins.
Before that or alternatively: zip the plugin code from https://transfer.hft-stuttgart.de/gitlab/cota/moodle-assignsubmission_dta (here). The readily-zipped current version also sits in the repository’s main directory. Then install the plugin from zip via Site Administration/Plugins/Install Plugins, or by extracting the plugin archive to {Moodle_Root}/mod/assign/submission/dta and visiting the admins notifications page. Before that or alternatively: zip the plugin code from https://transfer.hft-stuttgart.de/gitlab/HFTSoftwareProject/moodledta (here). The readily-zipped current version also sits in the repository's main directory. Then install the plugin from zip via Site Administration/Plugins/Install Plugins, or by extracting the plugin archive to {Moodle_Root}/mod/assign/submission/dta and visiting the admins notifications page.
Visit Site Administration/Plugins/Plugin Overview and select Settings next to the Moodle Dockerized Test Agent (Moodle DTA) entry to enter the URI of your backend as shown in Fig. 1. ![Fig. 1: Plugin List](.assets/install_conf_1.png) Finally, configure via Site Administration/Security/HTTP Security settings permitting communication with the backend URI and port as seen in Fig. 2. ![Fig. 2: DTA Configuration Dialog](.assets/install_conf_2.png) The plugin requires the external DTA REST webservice backend. Visit Site Administration/Plugins/Plugin Overview and select Settings next to the Moodle Dockerized Test Agent (MoDTA) entry to enter the URI of your backend as shown in Fig. 1. ![Fig. 1: Plugin List](doc/install_conf_1.png) Finally, configure via Site Administration/Security/HTTP Security settings permitting communication with the backend URI and port as seen in Fig. 2. ![Fig. 2: DTA Configuration Dialog](doc/install_conf_2.png) The plugin requires the external DTA REST webservice backend.
Notes: Notes:
The universal DTA REST webservice backend is available under the GPLv3 as well at https://transfer.hft-stuttgart.de/gitlab/HFTSoftwareProject/dtabackend and the docker image at https://hub.docker.com/r/hftstuttgart/dta-backend . See the documentation in the repository for the necessary setup. The universal DTA REST webservice backend is available under the GPLv3 as well at https://transfer.hft-stuttgart.de/gitlab/HFTSoftwareProject/dtabackend and the docker image at https://hub.docker.com/r/hftstuttgart/dta-backend . See the documentation in the repository for the necessary setup.
An example JDK 17 JUnit 5 test runner is available under GPLv3 as well at https://transfer.hft-stuttgart.de/gitlab/cota/examples/cota-runner-jdk17-junit5 and the pre-built docker image at https://hub.docker.com/r/hftstuttgart/dta-jdk17-junit5-testrunner . The repository contains an example docker-compose.yaml for tests with a bitnami Moodle and MariaDB setup and the backend. An example JDK 17 JUnit 5 test runner is available under GPLv3 as well at https://transfer.hft-stuttgart.de/gitlab/HFTSoftwareProject/dtatestrunner and the pre-built docker image at https://hub.docker.com/r/hftstuttgart/dta-jdk17-junit5-testrunner . The repository contains an example docker-compose.yaml for tests with a bitnami Moodle and MariaDB setup and the backend.
## Usage ## Usage
With the Moodle DTA plugin installed and configured backend URI (including Moodle Security/HTTP Security settings permitting communication with that URI): With the MoDTA plugin installed and configured backend URI (including Moodle Security/HTTP Security settings permitting communication with that URI):
### Teacher ### Teacher
When creating an assignment, a teacher can select the Moodle DTA exercise as a new assignment type via an additional checkbox on the assignment creation page as shown at the bottom of Fig. 3. ![Fig. 3: Moodle DTA Activation Checkbox](.assets/usage_teacher_1.png) A new standard file upload field appears as indicated in Fig. 4. ![Fig. 4: Moodle DTA Upload File Area](.assets/usage_teacher_2.png). There, the teacher must upload a text file with the git repository URI containing the tests as shown in Fig. 5. ![Fig. 5: Moodle DTA Teacher Text File Upload](.assets/usage_teacher_3.png) The text file has to adhere to the following format also given in the example repository: When creating an assignment, a teacher can select the MoDTA exercise as a new assignment type via an additional checkbox on the assignment creation page as shown at the bottom of Fig. 3. ![Fig. 3: Moodle DTA Activation Checkbox](doc/usage_teacher_1.png) A new standard file upload field appears as indicated in Fig. 4. ![Fig. 4: Moodle DTA Upload File Area](doc/usage_teacher_2.png). There, the teacher must upload a text file with the git repository URI containing the tests as shown in Fig. 5. ![Fig. 5: Moodle DTA Teacher Text File Upload](doc/usage_teacher_3.png) The text file has to adhere to the following format also given in the example repository:
The text file has to contain the following, each separated by :: The text file has to contain the following, each separated by ::
- dtt as the URI-type - dtt as the URI-type
- \<git https repository URI> - \<git https repository URI>
- \<git user name or the fixed string “none” for publicly accessible repositories> - \<git user name or the fixed string "none" for publicly accessible repositories>
- \<git password for the given user, git read access token for the repository, or the fixed string “none” for publicly accessible repositories> - \<git password for the given user, git read access token for the repository, or the fixed string "none" for publicly accessible repositories>
- \<docker hub image for the test runner> - \<docker hub image for the test runner>
- optionally, an additional line of the same structure containing a ticketing system URI, user name and password or write access token - optionally, an additional line of the same structure containing a ticketing system URI, user name and password or write access token
...@@ -78,17 +78,17 @@ Students use the same format, just without the runner part at the end. ...@@ -78,17 +78,17 @@ Students use the same format, just without the runner part at the end.
### Student ### Student
Students use an additional MoDTA standard file upload field in the standard submission processs in Moodle like in Fig. 6. [Fig. 6: Moodle DTA Student File Upload](.assets/usage_student_1.png) There, they place either a zip archive or a text file adhering to the same format as the teacher’s file with their code repository URI and optionally credentials and/or a ticketing system URI as shown in Fig. 7. ![Fig. 7: Moodle DTA Student Text File Upload](.assets/usage_student_2.png) Students use an additional MoDTA standard file upload field in the standard submission processs in Moodle like in Fig. 6. [Fig. 6: Moodle DTA Student File Upload](doc/usage_student_1.png) There, they place either a zip archive or a text file adhering to the same format as the teacher's file with their code repository URI and optionally credentials and/or a ticketing system URI as shown in Fig. 7. ![Fig. 7: Moodle DTA Student Text File Upload](doc/usage_student_2.png)
Upon completion, students see a summarized overview of their test results in an additional column of the submission feedback table like in Fig. 8. ![Fig. 8: Moodle DTA Submission Result Summay](.assets/usage_student_3.png) Clicking on a new expansion icon in that column, they reach a detailed feedback dialog including stack traces of compile errors and test failures as in Fig. 9. ![Fig. 9: Moodle DTA Student Detail Result View](.assets/usage_student_4.png) Optionally, the Moodle DTA backend creates tickets for compile failures in the ticketing system under the URI provided by the student upon hand-in. Upon completion, students see a summarized overview of their test results in an additional column of the submission feedback table like in Fig. 8. ![Fig. 8: Moodle DTA Submission Result Summay](doc/usage_student_3.png) Clicking on a new expansion icon in that column, they reach a detailed feedback dialog including stack traces of compile errors and test failures as in Fig. 9. ![Fig. 9: Moodle DTA Student Detail Result View](doc/usage_student_4.png) Optionally, the MoDTA backend creates tickets for compile failures in the ticketing system under the URI provided by the student upon hand-in.
Note: Teachers have access to the Moodle submission result view to assess student results. However, teacher control and grading are not the focus of Moodle DTA plugin. Note: Teachers have access to the Moodle submission result view to assess student results. However, teacher control and grading are not the focus of MoDTA.
### Technical Workflow ### Technical Workflow
Assignment creation: The backend creates a temporary directory and checks out the test code from the given repository to that directory's subdirectory test. If the repository contains a file test-competencies.mft in its root directory with a structure described in the backend documentation, this enables the optional competency feedback. Assignment creation: The backend creates a temporary directory and checks out the test code from the given repository to that directory's subdirectory test. If the repository contains a file test-competencies.mft in its root directory with a structure described in the backend documentation, this enables the optional competency feedback.
Assignment submission: The MoDTA plugin passes the submission id and submitted text or zip file – no personal teacher student data – to the external DTA backend REST web service. The DTA backend REST web service fetches or extracts the code to the temporary directory's subdirectory src. It launches via docker a dedicated test runner based on the docker image provided in the teacher’s text file. This test runner compiles and executes the code, running the teacher-defined tests to evaluate the students' submission. Assignment submission: The MoDTA plugin passes the submission id and submitted text or zip file – no personal teacher student data – to the external DTA backend REST web service. The DTA backend REST web service fetches or extracts the code to the temporary directory's subdirectory src. It launches via docker a dedicated test runner based on the docker image provided in the teacher's text file. This test runner compiles and executes the code, running the teacher-defined tests to evaluate the students' submission.
The runner returns the result in a file named result.json in the temporary directory's subdirectory result. The backend optionally enriches the result with competency feedback. It then returns the json result structure to the MoDTA moodle plugin. The MoDTA moodle plugin adds a new column to the submission result table and shows a result summary as well as an + button. Clicking on the + button, the student sees the detailed test results and, optionally, competency feedback. The runner returns the result in a file named result.json in the temporary directory's subdirectory result. The backend optionally enriches the result with competency feedback. It then returns the json result structure to the MoDTA moodle plugin. The MoDTA moodle plugin adds a new column to the submission result table and shows a result summary as well as an + button. Clicking on the + button, the student sees the detailed test results and, optionally, competency feedback.
...@@ -122,7 +122,7 @@ This file provides version information about the plugin to manage installation a ...@@ -122,7 +122,7 @@ This file provides version information about the plugin to manage installation a
### settings.php ### settings.php
The settings file defines two settings for the Moodle DTA plugin: The settings file defines two settings for the MoDTA plugin:
1. Default: This setting offers a checkbox to determine whether the plugin should be enabled by default when creating a new assignment. 1. Default: This setting offers a checkbox to determine whether the plugin should be enabled by default when creating a new assignment.
...@@ -165,7 +165,6 @@ This file serves as the gateway to various standard Moodle APIs designed for plu ...@@ -165,7 +165,6 @@ This file serves as the gateway to various standard Moodle APIs designed for plu
The folder contains various utility files, e.g. displaying the new test summary pages is delegated from the locallib.php for brevity of that source. The folder contains various utility files, e.g. displaying the new test summary pages is delegated from the locallib.php for brevity of that source.
### Code Checking ### Code Checking
The Moodle Plugin Directory offers a helpful tool for developers to ensure their code adheres to Moodle's coding conventions. This tool, named "Code Checker," can be found via the following link: The Moodle Plugin Directory offers a helpful tool for developers to ensure their code adheres to Moodle's coding conventions. This tool, named "Code Checker," can be found via the following link:
......
<?php
// This file is part of Moodle - http://moodle.org/.
//
// 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/>.
/**
* Callback endpoint for receiving test results from the DTA backend.
*
* @package assignsubmission_dta
* @copyright 2023 Your Name
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
define('NO_MOODLE_COOKIES', true);
require_once(__DIR__ . '/../../../../config.php');
require_once(__DIR__ . '/classes/dta_db_utils.php');
require_once(__DIR__ . '/classes/models/dta_result_summary.php');
require_once(__DIR__ . '/classes/models/dta_recommendation.php');
// Only accept POST requests.
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
echo json_encode(['error' => 'Method not allowed']);
exit;
}
// Get the raw POST data.
$json = file_get_contents('php://input');
$data = json_decode($json, true);
if (json_last_error() !== JSON_ERROR_NONE) {
http_response_code(400);
echo json_encode(['error' => 'Invalid JSON']);
exit;
}
// Extract required parameters.
$assignmentid = isset($data['assignmentId']) ? (int)$data['assignmentId'] : 0;
$submissionid = isset($data['submissionId']) ? (int)$data['submissionId'] : 0;
if ($assignmentid <= 0 || $submissionid <= 0) {
http_response_code(400);
echo json_encode(['error' => 'Missing or invalid assignmentId or submissionId']);
exit;
}
try {
// Decode the response JSON into class instances.
$resultsummary = \assignsubmission_dta\models\dta_result_summary::assignsubmission_dta_decode_json($json);
$recommendations = \assignsubmission_dta\models\dta_recommendation::assignsubmission_dta_decode_json_recommendations($json);
// Store results in database.
\assignsubmission_dta\dta_db_utils::assignsubmission_dta_store_result_summary_to_database(
$assignmentid,
$submissionid,
$resultsummary
);
\assignsubmission_dta\dta_db_utils::assignsubmission_dta_store_recommendations_to_database(
$assignmentid,
$submissionid,
$recommendations
);
http_response_code(200);
echo json_encode(['status' => 'success']);
} catch (Exception $e) {
http_response_code(500);
echo json_encode(['error' => $e->getMessage()]);
}
<?php
// This file is part of Moodle - http://moodle.org/
//
// 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/>.
/**
* utility class for DTA submission plugin result display
*
* @package assignsubmission_dta
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @copyright Gero Lueckemeyer and student project teams
*/
class view_submission_utils {
/**
* Broadly used in logic, parametrized for easier change.
*/
const COMPONENT_NAME = "assignsubmission_dta";
/**
* generates a short summary html
*
* @param int $assignmentid assignment
* @param int $submissionid submission to create a report for
* @return string html
*/
public static function generatesummaryhtml(
int $assignmentid,
int $submissionid
): string {
// Fetch data.
$summary = DbUtils::getResultSummaryFromDatabase($assignmentid, $submissionid);
$html = "";
// Calculate success rate, if no unknown result states or compilation errors.
$successrate = "?";
if ($summary->unknownCount() == 0 && $summary->compilationErrorCount() == 0) {
$successrate = round(($summary->successfulCount() / $summary->resultCount()) * 100, 2 );
}
// Generate html.
$html .= $summary->successfulCount() . "/";
$html .= ($summary->compilationErrorCount() == 0 && $summary->unknownCount() == 0)
? $summary->resultCount() . " (" . $successrate . "%)"
: "?";
$html .= get_string("tests_successful", self::COMPONENT_NAME) . "<br />";
if ($summary->compilationErrorCount() > 0) {
$html .= $summary->compilationErrorCount() . get_string("compilation_errors", self::COMPONENT_NAME) . "<br />";
}
if ($summary->unknownCount() > 0) {
$html .= $summary->unknownCount() . get_string("unknown_state", self::COMPONENT_NAME) . "<br />";
}
$showncompetencies = explode(";", $summary->successfultestcompetencies);
$overallcompetencies = explode(";", $summary->overalltestcompetencies);
$tmp = "";
for ($index = 0, $size = count($showncompetencies); $index < $size; $index++) {
$shown = $showncompetencies[$index];
$comp = $overallcompetencies[$index];
// If the competency was actually assessed by the assignment and tests, add a summary entry.
if ($shown != "0") {
$tmp .= get_string("comp" . $index, self::COMPONENT_NAME) .
" " . 100 * floatval($shown) / floatval($comp) . "% " . "<br />";
}
}
$html .= get_string("success_competencies", self::COMPONENT_NAME) . "<br />" . $tmp . "<br />";
return html_writer::div($html, "dtaSubmissionSummary");
}
/**
* generates detailed view html
*
* @param int $assignmentid assignment
* @param int $submissionid submission to create a report for
*/
public static function generatedetailhtml(
int $assignmentid,
int $submissionid
): string {
// Fetch data.
$summary = DbUtils::getResultSummaryFromDatabase($assignmentid, $submissionid);
$html = "";
// Define a few css classes and prepare html attribute arrays to beautify the output.
$tableheaderrowattributes = ["class" => "dtaTableHeaderRow"];
$tablerowattributes = ["class" => "dtaTableRow"];
$resultrowattributes = $tablerowattributes;
$unknownattributes = 'dtaResultUnknown';
$successattributes = 'dtaResultSuccess';
$failureattributes = 'dtaResultFailure';
$compilationerrorattributes = 'dtaResultCompilationError';
// Summary table.
$tmp = "";
$tmp .= html_writer::tag("th", get_string("summary", self::COMPONENT_NAME), ["class" => "dtaTableHeader"]);
$tmp .= html_writer::empty_tag("th", ["class" => "dtaTableHeader"]);
$header = html_writer::tag("tr", $tmp, $tableheaderrowattributes);
$header = html_writer::tag("thead", $header);
$body = "";
$tmp = "";
$attributes = ["class" => "dtaTableData"];
$tmp .= html_writer::tag(
"td",
get_string("total_items", self::COMPONENT_NAME),
$attributes);
$tmp .= html_writer::tag(
"td",
$summary->resultCount(),
$attributes);
$resultrowattributes = $tablerowattributes;
$resultrowattributes['class'] = $resultrowattributes['class'] . " " . $unknownattributes;
$body .= html_writer::tag("tr", $tmp, $resultrowattributes);
$tmp = "";
$tmp .= html_writer::tag("td", get_string("tests_successful", self::COMPONENT_NAME), $attributes);
$tmp .= html_writer::tag( "td", $summary->successfulCount(), $attributes);
$resultrowattributes = $tablerowattributes;
$successrate = "?";
if ($summary->unknownCount() > 0 || $summary->compilationErrorCount() > 0) {
$resultrowattributes['class'] = $resultrowattributes['class'] . " " . $unknownattributes;
} else {
$successrate = round(($summary->successfulCount() / $summary->resultCount()) * 100, 2 );
if ($successrate < 50) {
$resultrowattributes['class'] = $resultrowattributes['class'] . " " . $compilationerrorattributes;
} else if ($successrate < 75) {
$resultrowattributes['class'] = $resultrowattributes['class'] . " " . $failureattributes;
} else {
$resultrowattributes['class'] = $resultrowattributes['class'] . " " . $successattributes;
}
}
$body .= html_writer::tag("tr", $tmp, $resultrowattributes);
$tmp = "";
$tmp .= html_writer::tag("td", get_string("failures", self::COMPONENT_NAME), $attributes);
$tmp .= html_writer::tag("td", $summary->failedCount(), $attributes);
$resultrowattributes = $tablerowattributes;
if ($summary->failedCount() > 0) {
$resultrowattributes['class'] = $resultrowattributes['class'] . " " . $failureattributes;
} else {
$resultrowattributes['class'] = $resultrowattributes['class'] . " " . $successattributes;
}
$body .= html_writer::tag("tr", $tmp, $resultrowattributes);
$tmp = "";
$tmp .= html_writer::tag("td", get_string("compilation_errors", self::COMPONENT_NAME), $attributes);
$tmp .= html_writer::tag("td", $summary->compilationErrorCount(), $attributes);
$resultrowattributes = $tablerowattributes;
if ($summary->compilationErrorCount() > 0) {
$resultrowattributes['class'] = $resultrowattributes['class'] . " " . $compilationerrorattributes;
} else {
$resultrowattributes['class'] = $resultrowattributes['class'] . " " . $successattributes;
}
$body .= html_writer::tag("tr", $tmp, $resultrowattributes);
$tmp = "";
$tmp .= html_writer::tag("td", get_string("unknown_state", self::COMPONENT_NAME), $attributes);
$tmp .= html_writer::tag("td", $summary->unknownCount(), $attributes);
$resultrowattributes = $tablerowattributes;
if ($summary->unknownCount() > 0) {
$resultrowattributes['class'] = $resultrowattributes['class'] . " " . $unknownattributes;
} else {
$resultrowattributes['class'] = $resultrowattributes['class'] . " " . $successattributes;
}
$body .= html_writer::tag("tr", $tmp, $resultrowattributes);
$tmp = "";
$tmp .= html_writer::tag("td", html_writer::tag("b", get_string("success_rate", self::COMPONENT_NAME)), $attributes);
$tmp .= html_writer::tag(
"td",
html_writer::tag("b", $summary->successfulCount()
. "/" . (($summary->compilationErrorCount() == 0 && $summary->unknownCount() == 0) ? $summary->resultCount()
. " (" . $successrate . "%)"
: "?")),
$attributes);
$resultrowattributes = $tablerowattributes;
if ($summary->unknownCount() > 0 || $summary->compilationErrorCount() > 0) {
$resultrowattributes['class'] = $resultrowattributes['class'] . " " . $unknownattributes;
} else {
if ($successrate < 50) {
$resultrowattributes['class'] = $resultrowattributes['class'] . " " . $compilationerrorattributes;
} else if ($successrate < 75) {
$resultrowattributes['class'] = $resultrowattributes['class'] . " " . $failureattributes;
} else {
$resultrowattributes['class'] = $resultrowattributes['class'] . " " . $successattributes;
}
}
$body .= html_writer::tag("tr", $tmp, $resultrowattributes);
$body = html_writer::tag("tbody", $body);
$table = html_writer::tag("table", $header . $body, ["class" => "dtaTable"]);
$html .= $table;
// Add empty div for spacing between summary and compentency table.
$html .= html_writer::empty_tag("div", ["class" => "dtaSpacer"]);
// Competency assessment table.
$body = "";
$tmp = "";
$tmp .= html_writer::tag("th", get_string("competencies", self::COMPONENT_NAME), ["class" => "dtaTableHeader"]);
$tmp .= html_writer::empty_tag("th", ["class" => "dtaTableHeader"]);
$header = html_writer::tag("tr", $tmp, $tableheaderrowattributes);
$header = html_writer::tag("thead", $header);
$showncompetencies = explode(";", $summary->successfultestcompetencies);
$overallcompetencies = explode(";", $summary->overalltestcompetencies);
for ($index = 0, $size = count($overallcompetencies); $index < $size; $index++) {
$comp = $overallcompetencies[$index];
$shown = $showncompetencies[$index];
// If the competency was actually assessed by the assignment and tests, add a row in the table.
if ($comp != "0") {
// New copy of base attributes array.
$resultrowattributes = $tablerowattributes;
$tmp = "";
$tmp .= html_writer::tag("td", get_string("comp" . $index, self::COMPONENT_NAME), $resultrowattributes);
$tmp .= html_writer::tag("td", 100 * floatval($shown) / floatval($comp) . "% " .
"(" . $shown . " / " . $comp . ")", $resultrowattributes);
$tmp .= html_writer::tag("td", get_string("comp_expl" . $index, self::COMPONENT_NAME), $resultrowattributes);
$body .= html_writer::tag("tr", $tmp, $resultrowattributes);
}
}
$body = html_writer::tag("tbody", $body);
$html .= html_writer::tag("table", $header . $body, ["class" => "dtaTable"]);
// Add empty div for spacing between competency and details table.
$html .= html_writer::empty_tag("div", ["class" => "dtaSpacer"]);
// Details table.
$tmp = "";
$tmp .= html_writer::tag("th", get_string("details", self::COMPONENT_NAME), ["class" => "dtaTableHeader"]);
$tmp .= html_writer::empty_tag("th", ["class" => "dtaTableHeader"]);
$header = html_writer::tag("tr", $tmp, $tableheaderrowattributes);
$header = html_writer::tag("thead", $header);
$body = "";
$spacerrow = null;
foreach ($summary->results as $r) {
// Add spacer first if not null.
if (!is_null($spacerrow)) {
$body .= $spacerrow;
}
// New copy of base attributes array.
$resultrowattributes = $tablerowattributes;
// Check which css class to add for the colored left-border according to resuls state.
if ($r->state == 0) {
$resultrowattributes['class'] = $resultrowattributes['class'] . ' dtaResultUnknown';
} else if ($r->state == 1) {
$resultrowattributes['class'] = $resultrowattributes['class'] . ' dtaResultSuccess';
} else if ($r->state == 2) {
$resultrowattributes['class'] = $resultrowattributes['class'] . ' dtaResultFailure';
} else if ($r->state == 3) {
$resultrowattributes['class'] = $resultrowattributes['class'] . ' dtaResultCompilationError';
}
$tmp = "";
$tmp .= html_writer::tag(
"td",
get_string("package_name", self::COMPONENT_NAME),
$attributes);
$tmp .= html_writer::tag(
"td",
$r->packagename,
$attributes);
$tmp .= html_writer::tag(
"td",
get_string("unit_name", self::COMPONENT_NAME),
$attributes);
$tmp .= html_writer::tag(
"td",
$r->classname,
$attributes);
$tmp .= html_writer::tag(
"td",
get_string("test_name", self::COMPONENT_NAME),
$attributes);
$tmp .= html_writer::tag(
"td",
$r->name,
$attributes);
$body .= html_writer::tag("tr", $tmp, $resultrowattributes);
$tmp = "";
$tmp .= html_writer::tag(
"td",
get_string("status", self::COMPONENT_NAME),
$attributes);
$tmp .= html_writer::tag(
"td",
DtaResult::getStateName($r->state),
$attributes);
$body .= html_writer::tag("tr", $tmp, $resultrowattributes);
// If state is something different than successful, show additional rows.
if ($r->state != 1) {
$tmp = "";
$tmp .= html_writer::tag(
"td",
get_string("failure_type", self::COMPONENT_NAME),
$attributes);
$tmp .= html_writer::tag(
"td",
$r->failureType,
$attributes);
$body .= html_writer::tag("tr", $tmp, $resultrowattributes);
$tmp = "";
$tmp .= html_writer::tag(
"td",
get_string("failure_reason", self::COMPONENT_NAME),
$attributes);
$tmp .= html_writer::tag(
"td",
$r->failureReason,
$attributes);
$body .= html_writer::tag("tr", $tmp, $resultrowattributes);
// Only show line, column and position if they have useful values.
if (!is_null($r->lineNumber) && $r->lineNumber > 0) {
$tmp = "";
$tmp .= html_writer::tag(
"td",
get_string("line_no", self::COMPONENT_NAME),
$attributes);
$tmp .= html_writer::tag(
"td",
$r->lineNumber,
$attributes);
$body .= html_writer::tag("tr", $tmp, $resultrowattributes);
}
if (!is_null($r->columnNumber) && $r->columnNumber > 0) {
$tmp = "";
$tmp .= html_writer::tag(
"td",
get_string("col_no", self::COMPONENT_NAME),
$attributes);
$tmp .= html_writer::tag(
"td",
$r->columnNumber,
$attributes);
$body .= html_writer::tag("tr", $tmp, $resultrowattributes);
}
if (!is_null($r->position) && $r->position > 0) {
$tmp = "";
$tmp .= html_writer::tag(
"td",
get_string("pos", self::COMPONENT_NAME),
$attributes);
$tmp .= html_writer::tag(
"td",
$r->position,
$attributes);
$body .= html_writer::tag("tr", $tmp, $resultrowattributes);
}
$tmp = "";
$tmp .= html_writer::tag(
"td",
get_string("stacktrace", self::COMPONENT_NAME),
$attributes);
$tmp .= html_writer::tag(
"td",
html_writer::tag("details", $r->stacktrace, ["class" => "dtaStacktraceDetails"]),
$attributes);
$body .= html_writer::tag("tr", $tmp, $resultrowattributes);
}
// Set spacerrow value if null for next round separation.
if (is_null($spacerrow)) {
$spacerrow = html_writer::empty_tag("tr", ["class" => "dtaTableSpacer"]);
}
}
$html .= html_writer::tag("table", $header . $body, ["class" => "dtaTable"]);
// Wrap generated html into final div.
$html = html_writer::div($html, "dtaSubmissionDetails");
return $html;
}
}
<?php
// This file is part of Moodle - http://moodle.org/
//
// 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/>.
/**
* This file contains the backend webservice contact functionality for the DTA plugin
*
* @package assignsubmission_dta
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @copyright Gero Lueckemeyer and student project teams
*/
/**
* backend webservice contact utility class
*
* @package assignsubmission_dta
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @copyright Gero Lueckemeyer and student project teams
*/
class DtaBackendUtils {
/**
* Returns the base url of the backend webservice as configured in the administration settings.
* @return string backend host base url
*/
private static function getbackendbaseurl(): string {
$backendaddress = get_config(assign_submission_dta::COMPONENT_NAME, "backendHost");
if (empty($backendaddress)) {
\core\notification::error(get_string("backendHost_not_set", assign_submission_dta::COMPONENT_NAME));
}
return $backendaddress;
}
/**
* Sends the configuration textfile uploaded by prof to the backend.
*
* @param stdClass $assignment assignment this test-config belongs to
* @param stdClass $file uploaded test-config
* @return bool true if no error occurred
*/
public static function sendtestconfigtobackend($assignment, $file): bool {
$backendaddress = self::getbackendbaseurl();
if (empty($backendaddress)) {
return true;
}
// Set endpoint for test upload.
$url = $backendaddress . "/v1/unittest";
// Prepare params.
$params = [
"unitTestFile" => $file,
"assignmentId" => $assignment->get_instance()->id,
];
// If request returned null, return false to indicate failure.
if (is_null(self::post($url, $params))) {
return false;
} else {
return true;
}
}
/**
* Sends submission config or archive to backend to be tested.
*
* @param stdClass $assignment assignment for the submission
* @param int $submissionid submissionid of the current file
* @param stdClass $file submission config file or archive with submission
* @return string json string with testresults or null on error
*/
public static function sendsubmissiontobackend($assignment, $submissionid, $file): ?string {
$backendaddress = self::getbackendbaseurl();
if (empty($backendaddress)) {
return true;
}
// Set endpoint for test upload.
$url = $backendaddress . "/v1/task/" . $submissionid;
// Prepare params.
$params = [
"taskFile" => $file,
"assignmentId" => $assignment->get_instance()->id,
];
return self::post($url, $params);
}
/**
* Posts the given params to the given url and returns the response as a string.
* @param string $url full url to request to
* @param array $params parameters for http-request
*
* @return string received body on success or null on error
*/
private static function post($url, $params): ?string {
if (!isset($url) || !isset($params)) {
return false;
}
$options = ["CURLOPT_RETURNTRANSFER" => true];
$curl = new curl();
$response = $curl->post($url, $params, $options);
// Check state of request, if response code is a 2xx return the answer.
$info = $curl->get_info();
if ($info["http_code"] >= 200 && $info["http_code"] < 300) {
return $response;
}
// Something went wrong, return null and give an error message.
debugging(assign_submission_dta::COMPONENT_NAME . ": Post file to server was not successful: http_code=" .
$info["http_code"]);
if ($info['http_code'] >= 400 && $info['http_code'] < 500) {
\core\notification::error(get_string("http_client_error_msg", assign_submission_dta::COMPONENT_NAME));
return null;
} else if ($info['http_code'] >= 500 && $info['http_code'] < 600) {
\core\notification::error(get_string("http_server_error_msg", assign_submission_dta::COMPONENT_NAME));
return null;
} else {
\core\notification::error(get_string("http_unknown_error_msg", assign_submission_dta::COMPONENT_NAME) .
$info["http_code"] . $response);
return null;
}
}
}
<?php
// This file is part of Moodle - http://moodle.org/
//
// 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/>.
/**
* persistence layer utility class
*
* @package assignsubmission_dta
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @copyright Gero Lueckemeyer and student project teams
*/
class DbUtils {
/**
* Summary database table name.
*/
private const TABLE_SUMMARY = "assignsubmission_dta_summary";
/**
* Result database table name.
*/
private const TABLE_RESULT = "assignsubmission_dta_result";
/**
* gets summary with all corresponding result entries
*
* @param int $assignmentid assignment id to search for
* @param int $submissionid submission id to search for
* @return DttResultSummary representing given submission
*/
public static function getresultsummaryfromdatabase(
int $assignmentid,
int $submissionid
): DtaResultSummary {
global $DB;
// Fetch data from database.
$summaryrecord = $DB->get_record(self::TABLE_SUMMARY, [
"assignment_id" => $assignmentid,
"submission_id" => $submissionid,
]);
$resultsarray = $DB->get_records(self::TABLE_RESULT, [
"assignment_id" => $assignmentid,
"submission_id" => $submissionid,
]);
// Create a summary instance.
$summary = new DtaResultSummary();
$summary->timestamp = $summaryrecord->timestamp;
$summary->globalstacktrace = $summaryrecord->global_stacktrace;
$summary->successfultestcompetencies = $summaryrecord->successful_competencies;
$summary->overalltestcompetencies = $summaryrecord->tested_competencies;
$summary->results = [];
// Create result instances and add to array of summary instance.
foreach ($resultsarray as $rr) {
$result = new DtaResult();
$result->packagename = $rr->package_name;
$result->classname = $rr->class_name;
$result->name = $rr->name;
$result->state = $rr->state;
$result->failuretype = $rr->failure_type;
$result->failurereason = $rr->failure_reason;
$result->stacktrace = $rr->stacktrace;
$result->columnnumber = $rr->column_number;
$result->linenumber = $rr->line_number;
$result->position = $rr->position;
$summary->results[] = $result;
}
return $summary;
}
/**
* save given result summary and single results to database
* under given assignment and submission id
*
* @param int $assignmentid assigment this is submission is linked to
* @param int $submissionid submission of this result
* @param DtaResultSummary $summary instance to persist
*/
public static function storeresultsummarytodatabase(
int $assignmentid,
int $submissionid,
DtaResultSummary $summary
): void {
global $DB;
// Prepare new database entries.
$summaryrecord = new stdClass();
$summaryrecord->assignment_id = $assignmentid;
$summaryrecord->submission_id = $submissionid;
$summaryrecord->timestamp = $summary->timestamp;
$summaryrecord->global_stacktrace = $summary->globalstacktrace;
$summaryrecord->successful_competencies = $summary->successfultestcompetencies;
$summaryrecord->tested_competencies = $summary->overalltestcompetencies;
// Prepare results to persist to array.
$resultrecords = [];
foreach ($summary->results as $r) {
$record = new stdClass();
$record->assignment_id = $assignmentid;
$record->submission_id = $submissionid;
$record->package_name = $r->packagename;
$record->class_name = $r->classname;
$record->name = $r->name;
$record->state = $r->state;
$record->failure_type = $r->failuretype;
$record->failure_reason = $r->failurereason;
$record->stacktrace = $r->stacktrace;
$record->column_number = $r->columnnumber;
$record->line_number = $r->linenumber;
$record->position = $r->position;
$resultrecords[] = $record;
}
// If results already exist, delete old values beforehand.
$submission = $DB->get_record(self::TABLE_SUMMARY, [
'assignment_id' => $assignmentid,
'submission_id' => $submissionid,
]);
if ($submission) {
$DB->delete_records(self::TABLE_RESULT, [
'assignment_id' => $assignmentid,
'submission_id' => $submissionid,
]);
$DB->delete_records(self::TABLE_SUMMARY, [
'assignment_id' => $assignmentid,
'submission_id' => $submissionid,
]);
}
// Create summary and single result entries.
$DB->insert_record(self::TABLE_SUMMARY, $summaryrecord);
foreach ($resultrecords as $rr) {
$DB->insert_record(self::TABLE_RESULT, $rr);
}
}
/**
* cleans up database if plugin is uninstalled
*/
public static function uninstallplugincleaup(): void {
global $DB;
$DB->delete_records(self::TABLE_RESULT, null);
$DB->delete_records(self::TABLE_SUMMARY, null);
}
}
<?php
// This file is part of Moodle - http://moodle.org/.
//
// 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/>.
/**
* This file contains the backend webservice contact functionality for the DTA plugin.
*
* @package assignsubmission_dta
* @copyright 2023 Your Name
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace assignsubmission_dta;
/**
* Backend webservice contact utility class.
*
* @package assignsubmission_dta
* @copyright 2023 Your Name
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class dta_backend_utils {
/**
* Component name for the plugin.
*/
public const ASSIGNSUBMISSION_DTA_COMPONENT_NAME = 'assignsubmission_dta';
/**
* Returns the base URL of the backend webservice as configured in the administration settings.
*
* @return string Backend host base URL.
*/
private static function assignsubmission_dta_get_backend_baseurl(): string {
$backendaddress = get_config(
self::ASSIGNSUBMISSION_DTA_COMPONENT_NAME,
'backendHost'
);
if (empty($backendaddress)) {
\core\notification::error(
get_string('backendHost_not_set', self::ASSIGNSUBMISSION_DTA_COMPONENT_NAME)
);
}
return $backendaddress;
}
/**
* Sends the configuration text file uploaded by the teacher to the backend.
*
* @param \assign $assignment Assignment this test-config belongs to.
* @param \stored_file $file Uploaded test-config.
* @return bool True if no error occurred.
*/
public static function assignsubmission_dta_send_testconfig_to_backend($assignment, $file): bool {
$backendaddress = self::assignsubmission_dta_get_backend_baseurl();
if (empty($backendaddress)) {
return true;
}
// Set endpoint for test upload.
$url = $backendaddress . '/v1/unittest';
// Prepare params.
$params = [
'unitTestFile' => $file,
'assignmentId' => $assignment->get_instance()->id,
];
// If request returned null, return false to indicate failure.
if (is_null(self::assignsubmission_dta_post($url, $params))) {
return false;
} else {
return true;
}
}
/**
* Sends submission config or archive to backend to be tested.
*
* @param \assign $assignment Assignment for the submission.
* @param int $submissionid Submission ID of the current file.
* @param \stored_file $file Submission config file or archive with submission.
* @return string|null JSON string with test results or null on error.
*/
public static function assignsubmission_dta_send_submission_to_backend(
$assignment,
int $submissionid,
$file
): ?string {
$backendaddress = self::assignsubmission_dta_get_backend_baseurl();
if (empty($backendaddress)) {
return null;
}
// Set endpoint for submission upload.
$url = $backendaddress . '/v1/task/' . $submissionid;
// Prepare params.
$params = [
'taskFile' => $file,
'assignmentId' => $assignment->get_instance()->id,
];
return self::assignsubmission_dta_post($url, $params);
}
/**
* Posts the given params to the given URL and returns the response as a string.
*
* @param string $url Full URL to request.
* @param array $params Parameters for HTTP request.
* @return string|null Received body on success or null on error.
*/
private static function assignsubmission_dta_post(string $url, array $params): ?string {
if (!isset($url) || !isset($params)) {
return null;
}
$options = ['CURLOPT_RETURNTRANSFER' => true];
$curl = new \curl();
$response = $curl->post($url, $params, $options);
// Check state of request, if response code is 2xx, return the answer.
$info = $curl->get_info();
if ($info['http_code'] >= 200 && $info['http_code'] < 300) {
return $response;
}
// Something went wrong, return null and display an error message.
$msg = self::ASSIGNSUBMISSION_DTA_COMPONENT_NAME
. ': Post file to server was not successful. HTTP code='
. $info['http_code'];
debugging($msg);
if ($info['http_code'] >= 400 && $info['http_code'] < 500) {
\core\notification::error(
get_string('http_client_error_msg', self::ASSIGNSUBMISSION_DTA_COMPONENT_NAME)
);
return null;
} else if ($info['http_code'] >= 500 && $info['http_code'] < 600) {
\core\notification::error(
get_string('http_server_error_msg', self::ASSIGNSUBMISSION_DTA_COMPONENT_NAME)
);
return null;
} else {
$unknownmsg = get_string('http_unknown_error_msg', self::ASSIGNSUBMISSION_DTA_COMPONENT_NAME)
. $info['http_code'] . ' ' . $response;
\core\notification::error($unknownmsg);
return null;
}
}
}
<?php
// This file is part of Moodle - http://moodle.org/
//
// 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/>.
namespace assignsubmission_dta;
use assignsubmission_dta\dta_backend_utils;
use assignsubmission_dta\dta_view_submission_utils;
use assignsubmission_dta\models\dta_result;
use assignsubmission_dta\models\dta_result_summary;
use assignsubmission_dta\models\dta_recommendation;
/**
* Class dta_db_utils
*
* Persistence layer utility class for storing and retrieving
* DTA plugin data (results, summaries, recommendations).
*
* @package assignsubmission_dta
* @copyright 2023 Gero Lueckemeyer
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class dta_db_utils {
/**
* Summary database table name.
*/
private const ASSIGNSUBMISSION_DTA_TABLE_SUMMARY = 'assignsubmission_dta_summary';
/**
* Result database table name.
*/
private const ASSIGNSUBMISSION_DTA_TABLE_RESULT = 'assignsubmission_dta_result';
/**
* Recommendations database table name.
*/
private const ASSIGNSUBMISSION_DTA_TABLE_RECOMMENDATIONS = 'assignsubmission_dta_recommendations';
/**
* Returns an array of recommendations from the database.
*
* @param int $assignmentid The assignment ID.
* @param int $submissionid The submission ID.
* @return array An array of recommendation records.
*/
public static function assignsubmission_dta_get_recommendations_from_database(
int $assignmentid,
int $submissionid
): array {
global $DB, $USER;
$userid = $USER->id;
// Step 1: Retrieve all recommendations.
$records = $DB->get_records(
self::ASSIGNSUBMISSION_DTA_TABLE_RECOMMENDATIONS,
[
'assignment_id' => $assignmentid,
'submission_id' => $submissionid,
]
);
// Step 2: Retrieve module ID for 'assign'.
$module = $DB->get_record('modules', ['name' => 'assign'], 'id');
if (!$module) {
// Handle error case if the module is not found.
return $records;
}
$moduleid = $module->id;
// Step 3: Check each record.
foreach ($records as $key => $record) {
// Get the name of the exercise from the record.
$exercisename = $record->exercise_name;
// Find the assignment with this name.
$assign = $DB->get_record('assign', ['name' => $exercisename], 'id');
if ($assign) {
// Get the course module ID for this assignment.
$cm = $DB->get_record(
'course_modules',
[
'module' => $moduleid,
'instance' => $assign->id,
],
'id'
);
if ($cm) {
// Check the completion status for this course module and user.
$completion = $DB->get_record(
'course_modules_completion',
[
'coursemoduleid' => $cm->id,
'userid' => $userid,
],
'completionstate'
);
// If the completion state is 1, remove the record from $records.
if ($completion && (int)$completion->completionstate === 1) {
unset($records[$key]);
}
}
}
}
// Return the filtered records.
return $records;
}
/**
* Gets a summary with all corresponding result entries.
*
* @param int $assignmentid Assignment ID to search for.
* @param int $submissionid Submission ID to search for.
* @return dta_result_summary Summary representing the submission.
*/
public static function assignsubmission_dta_get_result_summary_from_database(
int $assignmentid,
int $submissionid
): dta_result_summary {
global $DB;
// Fetch data from database.
$summaryrecord = $DB->get_record(
self::ASSIGNSUBMISSION_DTA_TABLE_SUMMARY,
[
'assignment_id' => $assignmentid,
'submission_id' => $submissionid,
]
);
$resultsarray = $DB->get_records(
self::ASSIGNSUBMISSION_DTA_TABLE_RESULT,
[
'assignment_id' => $assignmentid,
'submission_id' => $submissionid,
]
);
// Create a summary instance.
$summary = new dta_result_summary();
$summary->timestamp = $summaryrecord->timestamp;
$summary->globalstacktrace = $summaryrecord->global_stacktrace;
$summary->successfultestcompetencies = $summaryrecord->successful_competencies;
$summary->overalltestcompetencies = $summaryrecord->tested_competencies;
$summary->results = [];
// Create result instances and add to array of summary instance.
foreach ($resultsarray as $rr) {
$result = new dta_result();
$result->packagename = $rr->package_name;
$result->classname = $rr->class_name;
$result->name = $rr->name;
$result->state = $rr->state;
$result->failuretype = $rr->failure_type;
$result->failurereason = $rr->failure_reason;
$result->stacktrace = $rr->stacktrace;
$result->columnnumber = $rr->column_number;
$result->linenumber = $rr->line_number;
$result->position = $rr->position;
$summary->results[] = $result;
}
return $summary;
}
/**
* Stores an array of recommendations in the database.
*
* @param int $assignmentid The assignment ID.
* @param int $submissionid The submission ID.
* @param array $recommendations An array of dta_recommendation objects.
*/
public static function assignsubmission_dta_store_recommendations_to_database(
int $assignmentid,
int $submissionid,
array $recommendations
): void {
global $DB;
// Debug output (you can remove or adapt this if unneeded).
debugging('Recommendations array: ' . json_encode($recommendations));
// If recommendations already exist, delete old values beforehand.
$existingrecords = $DB->get_records(
'assignsubmission_dta_recommendations',
[
'assignment_id' => $assignmentid,
'submission_id' => $submissionid,
]
);
if ($existingrecords) {
$DB->delete_records(
'assignsubmission_dta_recommendations',
[
'assignment_id' => $assignmentid,
'submission_id' => $submissionid,
]
);
}
// Create new recommendation entries.
foreach ($recommendations as $recommendation) {
// Check if $recommendation is an instance of dta_recommendation.
if ($recommendation instanceof dta_recommendation) {
// Add assignment and submission IDs to the recommendation object.
$recommendation->assignment_id = $assignmentid;
$recommendation->submission_id = $submissionid;
debugging('Inserting new recommendation record: ' . json_encode($recommendation));
// Insert the recommendation into the database.
$DB->insert_record('assignsubmission_dta_recommendations', $recommendation);
} else {
// Handle the case where $recommendation is not a dta_recommendation instance.
debugging('Invalid recommendation object encountered.');
}
}
}
/**
* Saves the given result summary and single results to the database
* under the specified assignment and submission ID.
*
* @param int $assignmentid Assignment this submission is linked to.
* @param int $submissionid Submission ID for these results.
* @param dta_result_summary $summary Summary instance to persist.
*/
public static function assignsubmission_dta_store_result_summary_to_database(
int $assignmentid,
int $submissionid,
dta_result_summary $summary
): void {
global $DB;
// Prepare new database entries.
$summaryrecord = new dta_result_summary();
$summaryrecord->assignment_id = $assignmentid;
$summaryrecord->submission_id = $submissionid;
$summaryrecord->timestamp = $summary->timestamp;
$summaryrecord->global_stacktrace = $summary->globalstacktrace;
$summaryrecord->successful_competencies = $summary->successfultestcompetencies;
$summaryrecord->tested_competencies = $summary->overalltestcompetencies;
// Prepare results to persist.
$resultrecords = [];
foreach ($summary->results as $r) {
$record = new dta_result();
$record->assignment_id = $assignmentid;
$record->submission_id = $submissionid;
$record->package_name = $r->packagename;
$record->class_name = $r->classname;
$record->name = $r->name;
$record->state = $r->state;
$record->failure_type = $r->failuretype;
$record->failure_reason = $r->failurereason;
$record->stacktrace = $r->stacktrace;
$record->column_number = $r->columnnumber;
$record->line_number = $r->linenumber;
$record->position = $r->position;
$resultrecords[] = $record;
}
// If results already exist, delete old values beforehand.
$submission = $DB->get_record(
self::ASSIGNSUBMISSION_DTA_TABLE_SUMMARY,
[
'assignment_id' => $assignmentid,
'submission_id' => $submissionid,
]
);
if ($submission) {
$DB->delete_records(
self::ASSIGNSUBMISSION_DTA_TABLE_RESULT,
[
'assignment_id' => $assignmentid,
'submission_id' => $submissionid,
]
);
$DB->delete_records(
self::ASSIGNSUBMISSION_DTA_TABLE_SUMMARY,
[
'assignment_id' => $assignmentid,
'submission_id' => $submissionid,
]
);
}
// Create summary and single result entries.
$DB->insert_record(self::ASSIGNSUBMISSION_DTA_TABLE_SUMMARY, $summaryrecord);
foreach ($resultrecords as $rr) {
$DB->insert_record(self::ASSIGNSUBMISSION_DTA_TABLE_RESULT, $rr);
}
}
/**
* Cleans up database if plugin is uninstalled.
*/
public static function assignsubmission_dta_uninstall_plugin_cleaup(): void {
global $DB;
$DB->delete_records(self::ASSIGNSUBMISSION_DTA_TABLE_RESULT, null);
$DB->delete_records(self::ASSIGNSUBMISSION_DTA_TABLE_SUMMARY, null);
$DB->delete_records(self::ASSIGNSUBMISSION_DTA_TABLE_RECOMMENDATIONS, null);
}
}
This diff is collapsed.
<?php
// This file is part of Moodle - http://moodle.org/.
//
// 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/>.
/**
* Entity class for DTA submission plugin recommendation.
*
* @package assignsubmission_dta
* @copyright 2023 Gero Lueckemeyer
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace assignsubmission_dta\models;
/**
* Entity class for DTA submission plugin recommendation.
*
* @package assignsubmission_dta
* @copyright 2023
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class dta_recommendation {
/**
* @var string $topic Topic of the recommendation.
*/
public $topic;
/**
* @var string $exercisename Name of the exercise.
*/
public $exercisename;
/**
* @var string $url URL of the exercise.
*/
public $url;
/**
* @var int $difficulty Difficulty level of the exercise.
*/
public $difficulty;
/**
* @var int $score Score associated with the recommendation.
*/
public $score;
/**
* Decodes the JSON recommendations returned by the backend service call into an array of dta_recommendation objects.
*
* @param string $jsonstring JSON string containing recommendations.
* @return array Array of dta_recommendation objects.
*/
public static function assignsubmission_dta_decode_json_recommendations(string $jsonstring): array {
$response = json_decode($jsonstring);
$recommendations = [];
// Check if recommendations exist.
if (!empty($response->recommendations)) {
foreach ($response->recommendations as $recommendation) {
$rec = new dta_recommendation();
$rec->topic = $recommendation->topic ?? null;
// Map correct fields to the renamed variable names.
$rec->exercisename = $recommendation->url ?? null;
$rec->url = $recommendation->exerciseName ?? null;
$rec->difficulty = $recommendation->difficulty ?? null;
$rec->score = $recommendation->score ?? null;
$recommendations[] = $rec;
}
}
return $recommendations;
}
}
<?php
// This file is part of Moodle - http://moodle.org/.
//
// 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/>.
/**
* Entity class for DTA submission plugin result.
*
* @package assignsubmission_dta
* @copyright 2023 Gero Lueckemeyer and student project teams
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace assignsubmission_dta\models;
/**
* Entity class for DTA submission plugin result.
*
* @package assignsubmission_dta
* @copyright 2023 Gero Lueckemeyer and student project teams
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class dta_result {
/**
* Broadly used in logic, parametrized for easier change.
*/
public const ASSIGNSUBMISSION_DTA_COMPONENT_NAME = 'assignsubmission_dta';
/**
* @var string $packagename Package name of the test.
*/
public $packagename;
/**
* @var string $classname Unit name of the test.
*/
public $classname;
/**
* @var string $name Name of the test.
*/
public $name;
/**
* @var int $state State is defined as:
* 0 UNKNOWN
* 1 SUCCESS
* 2 FAILURE
* 3 COMPILATIONERROR
*/
public $state;
/**
* @var string $failuretype Type of test failure if applicable, empty string otherwise.
*/
public $failuretype;
/**
* @var string $failurereason Reason of test failure if applicable, empty string otherwise.
*/
public $failurereason;
/**
* @var string $stacktrace Stack trace of test failure if applicable, empty string otherwise.
*/
public $stacktrace;
/**
* @var int|string $columnnumber Column number of compile failure if applicable, empty string otherwise.
*/
public $columnnumber;
/**
* @var int|string $linenumber Line number of compile failure if applicable, empty string otherwise.
*/
public $linenumber;
/**
* @var int|string $position Position of compile failure if applicable, empty string otherwise.
*/
public $position;
/** @var int Assignment ID (used when storing to database). */
public $assignment_id;
/** @var int Submission ID (used when storing to database). */
public $submission_id;
/** @var string Package name (alternative property name for database). */
public $package_name;
/** @var string Class name (alternative property name for database). */
public $class_name;
/** @var string Failure type (alternative property name for database). */
public $failure_type;
/** @var string Failure reason (alternative property name for database). */
public $failure_reason;
/** @var int|string Column number (alternative property name for database). */
public $column_number;
/** @var int|string Line number (alternative property name for database). */
public $line_number;
/**
* Returns the name of a state with the given number for display.
*
* @param int $state Number of the state.
* @return string Name of state as defined.
*/
public static function assignsubmission_dta_get_statename(int $state): string {
if ($state === 1) {
return get_string('tests_successful', self::ASSIGNSUBMISSION_DTA_COMPONENT_NAME);
} else if ($state === 2) {
return get_string('failures', self::ASSIGNSUBMISSION_DTA_COMPONENT_NAME);
} else if ($state === 3) {
return get_string('compilation_errors', self::ASSIGNSUBMISSION_DTA_COMPONENT_NAME);
} else {
return get_string('unknown_state', self::ASSIGNSUBMISSION_DTA_COMPONENT_NAME);
}
}
}
<?php
// This file is part of Moodle - http://moodle.org/.
//
// 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/>.
/**
* This file contains the DTA submission plugin result summary entity class.
*
* @package assignsubmission_dta
* @copyright 2023 Your Name
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace assignsubmission_dta\models;
/**
* Entity class for DTA submission plugin result summary.
*
* This class holds:
* - A timestamp for when the summary was generated.
* - An optional global stack trace (in case the entire process failed).
* - A competency profile of how many tests passed for each competency.
* - A competency profile of the total coverage for each competency.
* - An array of dta_result objects that detail individual test results.
*
* @package assignsubmission_dta
*/
class dta_result_summary {
/** @var int Unix timestamp for the summary. */
public $timestamp;
/** @var string A global stacktrace if the entire run had a fatal error (optional). */
public $globalstacktrace;
/** @var string Semi-colon-separated numbers for competencies actually passed. */
public $successfultestcompetencies;
/** @var string Semi-colon-separated numbers for total tested competencies. */
public $overalltestcompetencies;
/** @var dta_result[] Array of individual test results. */
public $results;
/** @var int Assignment ID (used when storing to database). */
public $assignment_id;
/** @var int Submission ID (used when storing to database). */
public $submission_id;
/** @var string Global stacktrace (alternative property name for database). */
public $global_stacktrace;
/** @var string Successful competencies (alternative property name for database). */
public $successful_competencies;
/** @var string Tested competencies (alternative property name for database). */
public $tested_competencies;
/**
* Decodes a JSON string into a dta_result_summary object.
*
* @param string $jsonstring JSON that includes timestamp, globalstacktrace, competency profiles, and results.
* @return dta_result_summary
*/
public static function assignsubmission_dta_decode_json(string $jsonstring): dta_result_summary {
$response = json_decode($jsonstring);
$summary = new dta_result_summary();
$summary->timestamp = $response->timestamp ?? 0;
$summary->globalstacktrace = $response->globalstacktrace ?? '';
// If your JSON keys are 'successfulTestCompetencyProfile' and 'overallTestCompetencyProfile'.
$summary->successfultestcompetencies = $response->successfulTestCompetencyProfile ?? '';
$summary->overalltestcompetencies = $response->overallTestCompetencyProfile ?? '';
// Decode the "results" array into an array of dta_result objects.
if (!empty($response->results) && is_array($response->results)) {
$summary->results = self::assignsubmission_dta_decode_json_result_array($response->results);
} else {
$summary->results = [];
}
return $summary;
}
/**
* Helper that transforms a list of JSON objects into an array of dta_result objects.
*
* @param array $jsonarray Array of JSON-decoded result objects.
* @return dta_result[]
*/
private static function assignsubmission_dta_decode_json_result_array(array $jsonarray): array {
$ret = [];
foreach ($jsonarray as $entry) {
$value = new dta_result();
$value->packagename = $entry->packageName ?? '';
$value->classname = $entry->className ?? '';
$value->name = $entry->name ?? '';
$value->state = $entry->state ?? 0;
$value->failuretype = $entry->failureType ?? '';
$value->failurereason = $entry->failureReason ?? '';
$value->stacktrace = $entry->stacktrace ?? '';
$value->columnnumber = $entry->columnNumber ?? 0;
$value->linenumber = $entry->lineNumber ?? 0;
$value->position = $entry->position ?? 0;
$ret[] = $value;
}
return $ret;
}
/**
* Get the total number of results (tests) recorded in this summary.
*
* @return int
*/
public function assignsubmission_dta_result_count(): int {
return count($this->results);
}
/**
* Generic helper to count how many results have the given $state.
*
* States can be:
* 0 => unknown
* 1 => success
* 2 => fail
* 3 => compilation error
*
* @param int $state The numeric state code to match.
* @return int Number of results with that state.
*/
public function assignsubmission_dta_state_occurence_count(int $state): int {
$num = 0;
foreach ($this->results as $r) {
if ((int)$r->state === $state) {
$num++;
}
}
return $num;
}
/**
* Count how many results had compilation errors (state=3).
*
* @return int
*/
public function assignsubmission_dta_compilation_error_count(): int {
return $this->assignsubmission_dta_state_occurence_count(3);
}
/**
* Count how many results failed (state=2).
*
* @return int
*/
public function assignsubmission_dta_failed_count(): int {
return $this->assignsubmission_dta_state_occurence_count(2);
}
/**
* Count how many results were successful (state=1).
*
* @return int
*/
public function assignsubmission_dta_successful_count(): int {
return $this->assignsubmission_dta_state_occurence_count(1);
}
/**
* Count how many results are unknown (state=0).
*
* @return int
*/
public function assignsubmission_dta_unknown_count(): int {
return $this->assignsubmission_dta_state_occurence_count(0);
}
/**
* Computes the success rate as a percentage of all results (0..100).
* Note: This includes tests that might have compile errors or unknown states.
*
* @return float A floating percentage between 0.0 and 100.0.
*/
public function assignsubmission_dta_success_rate(): float {
$count = $this->assignsubmission_dta_result_count();
if ($count === 0) {
return 0.0;
}
$successful = $this->assignsubmission_dta_successful_count();
return ($successful / $count) * 100.0;
}
}
<?php
// This file is part of Moodle - http://moodle.org/
//
// 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/>.
/**
* utility class for DTA submission plugin result display
*
* @package assignsubmission_dta
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @copyright Gero Lueckemeyer and student project teams
*/
namespace assignsubmission_dta\output;
defined('MOODLE_INTERNAL') || die();
use renderable;
use renderer_base;
use templatable;
final class generic_table implements renderable, templatable {
/** @var string[] */
private array $headings;
/** @var array<int, string[]> */
private array $rows;
private string $title;
/**
* @param string[] $headings
* @param array<int, string[]> $rows
*/
public function __construct(array $headings, array $rows, string $title = '') {
$this->headings = $headings;
$this->rows = $rows;
$this->title = $title;
}
public function export_for_template(renderer_base $output): array {
return [
'title' => $this->title,
'headings' => $this->headings,
'rows' => array_map(function(array $r) {
return ['cells' => array_map(fn($c) => ['text' => (string)$c], $r)];
}, $this->rows),
'headingscount' => count($this->headings),
];
}
}
<?php
// This file is part of Moodle - http://moodle.org/
//
// 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/>.
/**
* utility class for DTA submission plugin result display
*
* @package assignsubmission_dta
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @copyright Gero Lueckemeyer and student project teams
*/
namespace assignsubmission_dta\output;
defined('MOODLE_INTERNAL') || die();
use renderable;
use renderer_base;
use templatable;
final class sortable_table implements renderable, templatable {
/** @var string[] */
private array $headings;
/** @var array<int, string[]> */
private array $rows;
private string $title;
private string $sortby;
private string $sortdir;
private array $sortablecolumns;
/**
* @param string[] $headings
* @param array<int, string[]> $rows
* @param string[] $sortablecolumns Array of column names that can be sorted
*/
public function __construct(array $headings, array $rows, string $title = '', string $sortby = '', string $sortdir = 'asc', array $sortablecolumns = []) {
$this->headings = $headings;
$this->rows = $rows;
$this->title = $title;
$this->sortby = $sortby;
$this->sortdir = $sortdir;
$this->sortablecolumns = $sortablecolumns;
}
public function export_for_template(renderer_base $output): array {
// Process headings to include sortable information
$processedheadings = [];
foreach ($this->headings as $index => $heading) {
$headingdata = ['text' => $heading];
// Check if this column is sortable (empty string means not sortable)
$columnname = $this->sortablecolumns[$index] ?? '';
if (!empty($columnname) && in_array($columnname, $this->sortablecolumns)) {
$headingdata['sortable'] = true;
$headingdata['sortby'] = $columnname;
$headingdata['sortdir'] = ['asc' => ($this->sortby === $columnname && $this->sortdir === 'asc')];
} else {
$headingdata['sortable'] = false;
}
$processedheadings[] = $headingdata;
}
return [
'title' => $this->title,
'headings' => $processedheadings,
'rows' => array_map(function(array $r) {
return ['cells' => array_map(fn($c) => ['text' => (string)$c], $r)];
}, $this->rows),
'headingscount' => count($this->headings),
'sortby' => $this->sortby,
'sortdir' => $this->sortdir,
'sortablecolumns' => $this->sortablecolumns,
];
}
}
<?php
// This file is part of Moodle - http://moodle.org/
//
// 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/>.
/**
* utility class for DTA submission plugin result display
*
* @package assignsubmission_dta
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @copyright Gero Lueckemeyer and student project teams
*/
namespace assignsubmission_dta\output;
defined('MOODLE_INTERNAL') || die();
use renderable;
use renderer_base;
use templatable;
final class summary_table implements renderable, templatable {
/** @var array<int, array{label:string,value:string,cssclass?:string}> */
private array $rows;
private string $title;
/**
* @param array<int, array{label:string,value:string,cssclass?:string}> $rows
*/
public function __construct(array $rows, string $title = '') {
$this->rows = $rows;
$this->title = $title;
}
public function export_for_template(renderer_base $output): array {
return [
'title' => $this->title,
'rows' => $this->rows,
];
}
}
<?php
// This file is part of Moodle - http://moodle.org/
//
// 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/>.
namespace assignsubmission_dta\privacy;
use assign_submission_dta;
use assignsubmission_dta\dta_db_utils;
use core_privacy\local\metadata\collection;
use core_privacy\local\request\writer;
use core_privacy\local\request\contextlist;
use mod_assign\privacy\assign_plugin_request_data;
/**
* provider for data privacy
*
* @package assignsubmission_dta
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @copyright Gero Lueckemeyer and student project teams
*/
class provider implements \core_privacy\local\metadata\provider,
\mod_assign\privacy\assignsubmission_provider,
\mod_assign\privacy\assignsubmission_user_provider {
/**
* File area for dta submission assignment.
*/
const ASSIGNSUBMISSION_DTA_FILEAREA_SUBMISSION = "submissions_dta";
/**
* This is the metadata information for the assignsubmission_dta plugin.
* @param collection $collection the collection of metadata filled by the plugin
*/
public static function get_metadata(collection $collection): collection {
$collection->add_subsystem_link(
'core_files',
[],
'privacy:metadata:core_files'
);
$collection->add_database_table(
'assignsubmission_dta_summary',
[
'assignment_id' => 'privacy:metadata:assignsubmission_dta_summary:assignmentid',
'submission_id' => 'privacy:metadata:assignsubmission_dta_summary:submissionid',
'timestamp' => 'privacy:metadata:assignsubmission_dta_summary:timestamp',
'global_stacktrace' => 'privacy:metadata:assignsubmission_dta_summary:global_stacktrace',
'successful_competencies' => 'privacy:metadata:assignsubmission_dta_summary:successful_competencies',
'tested_competencies' => 'privacy:metadata:assignsubmission_dta_summary:tested_competencies',
],
'privacy:metadata:assignsubmission_dta_summary'
);
$collection->add_database_table(
'assignsubmission_dta_result',
[
'assignment_id' => 'privacy:metadata:assignsubmission_dta_summary:assignmentid',
'submission_id' => 'privacy:metadata:assignsubmission_dta_summary:submissionid',
'package_name' => 'privacy:metadata:assignsubmission_dta_result:package_name',
'class_name' => 'privacy:metadata:assignsubmission_dta_result:class_name',
'name' => 'privacy:metadata:assignsubmission_dta_result:name',
'state' => 'privacy:metadata:assignsubmission_dta_result:state',
'failure_type' => 'privacy:metadata:assignsubmission_dta_result:failure_type',
'failure_reason' => 'privacy:metadata:assignsubmission_dta_result:failure_reason',
'stacktrace' => 'privacy:metadata:assignsubmission_dta_result:stacktrace',
'column_number' => 'privacy:metadata:assignsubmission_dta_result:column_number',
'line_number' => 'privacy:metadata:assignsubmission_dta_result:line_number',
'position' => 'privacy:metadata:assignsubmission_dta_result:position',
],
'privacy:metadata:assignsubmission_dta_result'
);
$collection->add_database_table(
'assignsubmission_dta_recommendations',
[
'assignment_id' => 'privacy:metadata:assignsubmission_dta_summary:assignmentid',
'submission_id' => 'privacy:metadata:assignsubmission_dta_summary:submissionid',
'topic' => 'privacy:metadata:assignsubmission_dta_recommendations:topic',
'exercise_name' => 'privacy:metadata:assignsubmission_dta_recommendations:exercise_name',
'url' => 'privacy:metadata:assignsubmission_dta_recommendations:url',
'difficulty' => 'privacy:metadata:assignsubmission_dta_recommendations:difficulty',
'score' => 'privacy:metadata:assignsubmission_dta_recommendations:score',
],
'privacy:metadata:assignsubmission_dta_recommendations'
);
$collection->add_external_location_link('dta_backend', [
'assignment_id' => 'privacy:metadata:assignsubmission_dta_summary:assignmentid',
'submission_id' => 'privacy:metadata:assignsubmission_dta_summary:submissionid',
'submissioncontent' => 'privacy:metadata:core_files',
],
'privacy:metadata:dta_backend'
);
return $collection;
}
/**
* This is covered by mod_assign provider and the query on assign_submissions.
*
* @param int $userid The user ID that we are finding contexts for.
* @param contextlist $contextlist A context list to add sql and params to for contexts.
*/
public static function get_context_for_userid_within_submission(int $userid, contextlist $contextlist) {
// This is already fetched from mod_assign.
}
/**
* This is also covered by the mod_assign provider and its queries.
*
* @param \mod_assign\privacy\useridlist $useridlist An object for obtaining user IDs of students.
*/
public static function get_student_user_ids(\mod_assign\privacy\useridlist $useridlist) {
// This is already fetched from mod_assign.
}
/**
* If you have tables that contain userids and you can generate entries in your tables without creating an
* entry in the assign_submission table then please fill in this method.
*
* @param userlist $userlist The userlist object
*/
public static function get_userids_from_context(\core_privacy\local\request\userlist $userlist) {
// Not required.
}
/**
* Export all user data for this plugin.
*
* @param assign_plugin_request_data $exportdata Data used to determine which context and user to export and other useful
* information to help with exporting.
*/
public static function export_submission_user_data(assign_plugin_request_data $exportdata) {
// We currently don't show submissions to teachers when exporting their data.
$context = $exportdata->get_context();
if ($exportdata->get_user() != null) {
return null;
}
$user = new \stdClass();
$assign = $exportdata->get_assign();
$plugin = $assign->get_plugin_by_type('assignsubmission', 'file');
$submission = $exportdata->get_pluginobject();
$files = $plugin->get_files($exportdata->get_pluginobject(), $user);
foreach ($files as $file) {
$userid = $exportdata->get_pluginobject()->userid;
$dtaresultsummary = dta_db_utils::dta_get_result_summary_from_database($assign->id, $submission->id);
// Submitted file.
writer::with_context($exportdata->get_context())->export_file($exportdata->get_subcontext(), $file)
// DTA result.
->export_related_data($dtaresultsummary);
}
}
/**
* Any call to this method should delete all user data for the context defined in the deletion_criteria.
*
* @param assign_plugin_request_data $requestdata Information useful for deleting user data.
*/
public static function delete_submission_for_context(assign_plugin_request_data $requestdata) {
global $DB;
$fs = get_file_storage();
$fs->delete_area_files($requestdata->get_context()->id, 'assignsubmission_dta', \assignsubmission_dta\privacy\provider::ASSIGNSUBMISSION_DTA_FILEAREA_SUBMISSION);
$assignmentid = $requestdata->get_assign()->get_instance()->id;
// Delete records from assignsubmission_dta tables.
$DB->delete_records('assignsubmission_dta_result', ['assignment_id' => $assignmentid]);
$DB->delete_records('assignsubmission_dta_summary', ['assignment_id' => $assignmentid]);
$DB->delete_records('assignsubmission_dta_recommendations', ['assignment_id' => $assignmentid]);
}
/**
* A call to this method should delete user data (where practical) using the userid and submission.
*
* @param assign_plugin_request_data $deletedata Details about the user and context to focus the deletion.
*/
public static function delete_submission_for_userid(assign_plugin_request_data $deletedata) {
global $DB;
$assignmentid = $deletedata->get_assign()->get_instance()->id;
$submissionid = $deletedata->get_pluginobject()->id;
$fs = get_file_storage();
$fs->delete_area_files($deletedata->get_context()->id, 'assignsubmission_dta', \assignsubmission_dta\privacy\provider::ASSIGNSUBMISSION_DTA_FILEAREA_SUBMISSION,
$submissionid);
// Delete records from assignsubmission_dta tables. Also possible with a list as below.
$DB->delete_records('assignsubmission_dta_result', [
'assignment_id' => $assignmentid,
'submission_id' => $submissionid,
]);
$DB->delete_records('assignsubmission_dta_summary', [
'assignment_id' => $assignmentid,
'submission_id' => $submissionid,
]);
$DB->delete_records('assignsubmission_dta_recommendations', [
'assignment_id' => $assignmentid,
'submission_id' => $submissionid,
]);
}
/**
* Deletes all submissions for the submission ids / userids provided in a context.
* assign_plugin_request_data contains:
* - context
* - assign object
* - submission ids (pluginids)
* - user ids
* @param assign_plugin_request_data $deletedata A class that contains the relevant information required for deletion.
*/
public static function delete_submissions(assign_plugin_request_data $deletedata) {
global $DB;
if (empty($deletedata->get_submissionids())) {
return;
}
$fs = get_file_storage();
list($sql, $params) = $DB->get_in_or_equal($deletedata->get_submissionids(), SQL_PARAMS_NAMED);
$fs->delete_area_files_select($deletedata->get_context()->id, 'assignsubmission_file', \assignsubmission_dta\privacy\provider::ASSIGNSUBMISSION_DTA_FILEAREA_SUBMISSION_SUBMISSION,
$sql, $params);
$params['assignid'] = $deletedata->get_assignid();
$DB->delete_records_select('assignsubmission_dta_result', "assignment_id = :assignid AND submissionid $sql", $params);
$DB->delete_records_select('assignsubmission_dta_summary', "assignment_id = :assignid AND submissionid $sql", $params);
$DB->delete_records_select('assignsubmission_dta_recommendations', "assignment_id = :assignid AND submissionid $sql", $params);
}
}
<?php
// This file is part of Moodle - http://moodle.org/
//
// 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/>.
/**
* utility class for DTA submission plugin result display
*
* @package assignsubmission_dta
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @copyright Gero Lueckemeyer and student project teams
*/
define('NO_OUTPUT_BUFFERING', true);
require(__DIR__.'/../../../../../config.php');
require_once($CFG->dirroot.'/mod/assign/locallib.php');
require_once(__DIR__.'/dta_db_utils.php');
require_once(__DIR__.'/models/dta_result.php');
use assignsubmission_dta\output\summary_table;
use assignsubmission_dta\output\generic_table;
use assignsubmission_dta\output\sortable_table;
// --- Prepare parameters & context ---
$cmid = optional_param('cmid', 0, PARAM_INT);
$sid = optional_param('sid', 0, PARAM_INT);
$userid = optional_param('userid', $USER->id, PARAM_INT);
// If cmid is not provided, try to get it from the submission
if ($cmid == 0 && $sid > 0) {
global $DB;
$submission = $DB->get_record('assign_submission', ['id' => $sid]);
if ($submission) {
$assignment = $DB->get_record('assign', ['id' => $submission->assignment]);
if ($assignment) {
$cm = get_coursemodule_from_instance('assign', $assignment->id, $assignment->course);
if ($cm) {
$cmid = $cm->id;
}
}
}
}
// If still no cmid, show error
if ($cmid == 0) {
throw new moodle_exception('missingparam', 'error', '', 'cmid');
}
$cm = get_coursemodule_from_id('assign', $cmid, 0, false, MUST_EXIST);
$course = get_course($cm->course);
$context = context_module::instance($cm->id);
// Login early!
require_login($course, false, $cm);
// assign instance and assignmentid (aid)
$assign = new assign($context, $cm, $course);
$aid = (int)$assign->get_instance()->id;
// if no sid given: determine user's submission
if (!$sid) {
if ($submission = $assign->get_user_submission($userid, true)) {
$sid = (int)$submission->id;
}
}
// --- Load summary (robust, depending on Utils class/function) ---
if (class_exists('DbUtils')) {
$summary = \DbUtils::getresultsummaryfromdatabase($aid, $sid);
} else if (class_exists('assignsubmission_dta\dta_db_utils')) {
$summary = \assignsubmission_dta\dta_db_utils::assignsubmission_dta_get_result_summary_from_database($aid, $sid);
} else if (function_exists('getResultSummaryFromDatabase')) {
$summary = getResultSummaryFromDatabase($aid, $sid);
} else {
throw new \moodle_exception('dta_db_utils_missing', 'assignsubmission_dta', '', null,
'No DbUtils class/function found');
}
// --- Load recommendations ---
$recommendations = [];
if (class_exists('assignsubmission_dta\dta_db_utils')) {
$recommendations = \assignsubmission_dta\dta_db_utils::assignsubmission_dta_get_recommendations_from_database($aid, $sid);
}
// --- from here: set $PAGE, output header and render renderables ---
$PAGE->set_context($context);
$PAGE->set_url(new moodle_url('/mod/assign/submission/dta/classes/view.php', ['cmid'=>$cmid, 'sid'=>$sid]));
$PAGE->set_pagelayout('report');
$PAGE->set_title(get_string('pluginname', 'assignsubmission_dta'));
$PAGE->set_heading(format_string($SITE->fullname));
echo $OUTPUT->header();
// --- Summary and Recommendations in one row ---
echo '<div class="row">';
echo '<div class="col-md-6">';
// --- Summary Table (as in view.php) ---
$successrate = "?";
if ($summary->assignsubmission_dta_unknown_count() == 0 && $summary->assignsubmission_dta_compilation_error_count() == 0 && $summary->assignsubmission_dta_result_count() > 0) {
$successrate = round(($summary->assignsubmission_dta_successful_count() / $summary->assignsubmission_dta_result_count()) * 100, 2);
}
$summaryrows = [
['label' => get_string('total_items', 'assignsubmission_dta'), 'value' => $summary->assignsubmission_dta_result_count()],
['label' => get_string('tests_successful', 'assignsubmission_dta'), 'value' => $summary->assignsubmission_dta_successful_count(), 'cssclass' => 'dtaResultSuccess'],
['label' => get_string('failures', 'assignsubmission_dta'), 'value' => $summary->assignsubmission_dta_failed_count(), 'cssclass' => 'dtaResultFailure'],
['label' => get_string('compilation_errors', 'assignsubmission_dta'), 'value' => $summary->assignsubmission_dta_compilation_error_count(), 'cssclass' => 'dtaResultCompilationError'],
['label' => get_string('unknown_state', 'assignsubmission_dta'), 'value' => $summary->assignsubmission_dta_unknown_count(), 'cssclass' => 'dtaResultUnknown'],
['label' => get_string('success_rate', 'assignsubmission_dta'), 'value' =>
$summary->assignsubmission_dta_successful_count() . "/" .
(($summary->assignsubmission_dta_compilation_error_count() == 0 && $summary->assignsubmission_dta_unknown_count() == 0)
? $summary->assignsubmission_dta_result_count() . " (" . $successrate . "%)"
: "?"), 'cssclass' =>
(($summary->assignsubmission_dta_compilation_error_count() == 0 && $summary->assignsubmission_dta_unknown_count() == 0)
? ($successrate >= 75 ? 'dtaResultSuccess' : ($successrate >= 50 ? 'dtaResultFailure' : 'dtaResultCompilationError'))
: 'dtaResultUnknown')]
];
echo $OUTPUT->render(new summary_table($summaryrows, get_string('summary', 'assignsubmission_dta')));
echo '</div>'; // col-md-6
echo '<div class="col-md-6">';
// --- Recommendations Table (as in view.php) ---
if (!empty($recommendations)) {
$allowedsortfields = ['topic', 'exercise_name', 'difficulty', 'score'];
$allowedsortdirs = ['asc', 'desc'];
$sortby = $_POST['sortby'] ?? 'score';
$sortdir = $_POST['sortdir'] ?? 'asc';
if (!in_array($sortby, $allowedsortfields)) {
$sortby = 'score';
}
if (!in_array($sortdir, $allowedsortdirs)) {
$sortdir = 'asc';
}
// Sort recommendations
usort($recommendations, function ($a, $b) use ($sortby, $sortdir) {
$valuea = $a->{$sortby};
$valueb = $b->{$sortby};
if (is_numeric($valuea) && is_numeric($valueb)) {
$comparison = $valuea - $valueb;
} else {
$comparison = strnatcasecmp($valuea, $valueb);
}
if ($comparison === 0) {
return 0;
}
if ($sortdir === 'asc') {
return ($comparison < 0) ? -1 : 1;
} else {
return ($comparison < 0) ? 1 : -1;
}
});
$recommendationrows = [];
foreach ($recommendations as $recommendation) {
$recommendationrows[] = [
$recommendation->topic,
$recommendation->exercise_name,
html_writer::link($recommendation->url, $recommendation->url),
$recommendation->difficulty,
$recommendation->score
];
}
// Simple headers for sortable table
$recommendationheadings = [
get_string('topic', 'assignsubmission_dta'),
get_string('exercise_name', 'assignsubmission_dta'),
get_string('url', 'assignsubmission_dta'),
get_string('difficulty', 'assignsubmission_dta'),
get_string('score', 'assignsubmission_dta')
];
// Define which columns are sortable (topic, exercise_name, difficulty, score)
$sortablecolumns = ['topic', 'exercise_name', '', 'difficulty', 'score'];
echo $OUTPUT->render(new sortable_table($recommendationheadings, $recommendationrows, get_string('recommendations', 'assignsubmission_dta'), $sortby, $sortdir, $sortablecolumns));
}
echo '</div>'; // col-md-6
echo '</div>'; // row
// --- Spacer ---
echo html_writer::empty_tag("div", ["class" => "dtaSpacer"]);
// --- Competencies Table (as in view.php) ---
$showncompetencies = explode(";", $summary->successfultestcompetencies);
$overallcompetencies = explode(";", $summary->overalltestcompetencies);
$competencyrows = [];
for ($index = 0, $size = count($overallcompetencies); $index < $size; $index++) {
$comp = $overallcompetencies[$index];
$shown = $showncompetencies[$index];
$compval = floatval($comp);
$shownval = floatval($shown);
// Only show competencies that have a non-zero value in overall competencies
if ($compval > 0) {
$pct = 100 * $shownval / $compval;
// Only show if percentage is greater than 0
if ($pct > 0) {
$competencyrows[] = [
get_string("comp" . $index, 'assignsubmission_dta'),
round($pct, 2) . "% (" . $shown . " / " . $comp . ")",
get_string("comp_expl" . $index, 'assignsubmission_dta')
];
}
}
}
$competencyheadings = [
get_string('competencies', 'assignsubmission_dta'),
'',
''
];
echo $OUTPUT->render(new generic_table($competencyheadings, $competencyrows, get_string('competencies', 'assignsubmission_dta')));
// --- Spacer ---
echo html_writer::empty_tag("div", ["class" => "dtaSpacer"]);
// --- Details Table (as in view.php) ---
$detailrows = [];
foreach ($summary->results as $r) {
// Package name row
$detailrows[] = [
get_string('package_name', 'assignsubmission_dta'),
$r->packagename
];
// Unit name row
$detailrows[] = [
get_string('unit_name', 'assignsubmission_dta'),
$r->classname
];
// Test name row
$detailrows[] = [
get_string('test_name', 'assignsubmission_dta'),
$r->name
];
// Status row
$detailrows[] = [
get_string('status', 'assignsubmission_dta'),
\assignsubmission_dta\models\dta_result::assignsubmission_dta_get_statename($r->state)
];
// If state is not successful, show additional rows
if ($r->state != 1) {
$detailrows[] = [
get_string('failure_type', 'assignsubmission_dta'),
$r->failuretype
];
$detailrows[] = [
get_string('failure_reason', 'assignsubmission_dta'),
$r->failurereason
];
if (!is_null($r->linenumber) && $r->linenumber > 0) {
$detailrows[] = [
get_string('line_no', 'assignsubmission_dta'),
$r->linenumber
];
}
if (!is_null($r->columnnumber) && $r->columnnumber > 0) {
$detailrows[] = [
get_string('col_no', 'assignsubmission_dta'),
$r->columnnumber
];
}
if (!is_null($r->position) && $r->position > 0) {
$detailrows[] = [
get_string('pos', 'assignsubmission_dta'),
$r->position
];
}
$detailrows[] = [
get_string('stacktrace', 'assignsubmission_dta'),
html_writer::tag("details", $r->stacktrace, ["class" => "dtaStacktraceDetails"])
];
}
// Add spacer row
$detailrows[] = ['', '']; // Spacer row
}
$detailheadings = [
get_string('details', 'assignsubmission_dta'),
''
];
echo $OUTPUT->render(new generic_table($detailheadings, $detailrows, get_string('details', 'assignsubmission_dta')));
echo $OUTPUT->footer();
<?xml version="1.0" encoding="UTF-8" ?>
<XMLDB PATH="mod/assign/submission/dta/db" VERSION="20210107" COMMENT="XMLDB file for Moodle mod/assign/submission/dta"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="../../../../../lib/xmldb/xmldb.xsd"
>
<TABLES>
<TABLE NAME="assignsubmission_dta_summary" COMMENT="DTA testrun summary">
<FIELDS>
<FIELD NAME="id" TYPE="int" LENGTH="10" NOTNULL="true" SEQUENCE="true"/>
<FIELD NAME="assignment_id" TYPE="int" LENGTH="10" NOTNULL="true" SEQUENCE="false"/>
<FIELD NAME="submission_id" TYPE="int" LENGTH="10" NOTNULL="true" SEQUENCE="false"/>
<FIELD NAME="successful_competencies" TYPE="char" LENGTH="80" NOTNULL="false"/>
<FIELD NAME="tested_competencies" TYPE="char" LENGTH="80" NOTNULL="false"/>
<FIELD NAME="timestamp" TYPE="int" LENGTH="10"/>
<FIELD NAME="global_stacktrace" TYPE="text"/>
</FIELDS>
<KEYS>
<KEY NAME="primary" TYPE="primary" FIELDS="id"/>
<KEY NAME="fk_assignment" TYPE="foreign" FIELDS="assignment_id" REFTABLE="assign" REFFIELDS="id" COMMENT="The assignment instance this summary relates to"/>
<KEY NAME="fk_submission" TYPE="foreign" FIELDS="submission_id" REFTABLE="assign_submission" REFFIELDS="id" COMMENT="The submission this summary relates to."/>
</KEYS>
</TABLE>
<TABLE NAME="assignsubmission_dta_recommendations" COMMENT="Stores recommendation data">
<FIELDS>
<FIELD NAME="id" TYPE="int" LENGTH="10" NOTNULL="true" SEQUENCE="true" COMMENT="Primary Key" />
<FIELD NAME="assignment_id" TYPE="int" LENGTH="10" NOTNULL="true" SEQUENCE="false"/>
<FIELD NAME="submission_id" TYPE="int" LENGTH="10" NOTNULL="true" SEQUENCE="false"/>
<FIELD NAME="topic" TYPE="char" LENGTH="255" NOTNULL="true" COMMENT="Recommendation Topic" />
<FIELD NAME="exercise_name" TYPE="char" LENGTH="255" NOTNULL="true" COMMENT="Exercise Name" />
<FIELD NAME="url" TYPE="char" LENGTH="255" NOTNULL="true" COMMENT="Exercise URL" />
<FIELD NAME="difficulty" TYPE="number" LENGTH="10" NOTNULL="true" COMMENT="Exercise Difficulty" />
<FIELD NAME="score" TYPE="number" LENGTH="10" NOTNULL="true" COMMENT="Exercise Score" />
</FIELDS>
<KEYS>
<KEY NAME="primary" TYPE="primary" FIELDS="id"/>
<KEY NAME="fk_assignment" TYPE="foreign" FIELDS="assignment_id" REFTABLE="assign" REFFIELDS="id" COMMENT="The assignment instance this recommendations relates to"/>
<KEY NAME="fk_submission" TYPE="foreign" FIELDS="submission_id" REFTABLE="assign_submission" REFFIELDS="id" COMMENT="The submission this recommendations relates to."/>
</KEYS>
</TABLE>
<TABLE NAME="assignsubmission_dta_result" COMMENT="DTA testrun single test results">
<FIELDS>
<FIELD NAME="id" TYPE="int" LENGTH="10" NOTNULL="true" SEQUENCE="true"/>
<FIELD NAME="assignment_id" TYPE="int" LENGTH="10" NOTNULL="true" SEQUENCE="false"/>
<FIELD NAME="submission_id" TYPE="int" LENGTH="10" NOTNULL="true" SEQUENCE="false"/>
<FIELD NAME="package_name" TYPE="char" LENGTH="255" NOTNULL="false"/>
<FIELD NAME="class_name" TYPE="char" LENGTH="255" NOTNULL="false"/>
<FIELD NAME="name" TYPE="char" LENGTH="255" NOTNULL="true"/>
<FIELD NAME="state" TYPE="int" LENGTH="10" NOTNULL="true"/>
<FIELD NAME="failure_type" TYPE="char" LENGTH="255"/>
<FIELD NAME="failure_reason" TYPE="char" LENGTH="255"/>
<FIELD NAME="stacktrace" TYPE="text"/>
<FIELD NAME="column_number" TYPE="int" LENGTH="10"/>
<FIELD NAME="line_number" TYPE="int" LENGTH="10"/>
<FIELD NAME="position" TYPE="int" LENGTH="10"/>
</FIELDS>
<KEYS>
<KEY NAME="primary" TYPE="primary" FIELDS="id,assignment_id,submission_id"/>
<KEY NAME="fk_assignment" TYPE="foreign" FIELDS="assignment_id" REFTABLE="assign" REFFIELDS="id" COMMENT="The assignment instance this result relates to"/>
<KEY NAME="fk_submission" TYPE="foreign" FIELDS="submission_id" REFTABLE="assign_submission" REFFIELDS="id" COMMENT="The submission this result relates to."/>
</KEYS>
</TABLE>
</TABLES>
</XMLDB>
\ No newline at end of file
<?php
// This file is part of Moodle - http://moodle.org/.
//
// 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/>.
defined('MOODLE_INTERNAL') || die();
$functions = [
'assignsubmission_dta_save_submission' => [
'classname' => 'assignsubmission_dta_external',
'methodname' => 'save_submission',
'classpath' => 'mod/assign/submission/dta/externallib.php',
'description' => 'Save a DTA submission for the given user using a previously uploaded draft itemid and trigger backend processing.',
'type' => 'write',
'ajax' => false,
'services' => [],
],
];
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment