Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

#140: Question UI Renderer soll gelöschte Antworten erkennen #149

Open
wants to merge 9 commits into
base: dev
Choose a base branch
from
44 changes: 44 additions & 0 deletions classes/attempt_ui/available_opts_info.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
<?php
// This file is part of the QuestionPy Moodle plugin - https://questionpy.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 qtype_questionpy\attempt_ui;

/**
* Used by {@see question_ui_renderer::extract_available_options()} to hold type, available options and warning opt-out.
*
* @package qtype_questionpy
* @author Maximilian Haye
* @copyright 2024 TU Berlin, innoCampus {@link https://www.questionpy.org}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class available_opts_info {
/**
* Trivial constructor.
*
* @param string $type
* @param array $availableoptions
* @param bool $warnonunknownoption
*/
public function __construct(
/** @var string $type `radio`, `checkbox` or `select` */
public string $type,
/** @var string[] $availableoptions */
public array $availableoptions,
/** @var bool $warnonunknownoption */
public bool $warnonunknownoption
) {
}
}
153 changes: 153 additions & 0 deletions classes/attempt_ui/dom_utils.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
<?php
// This file is part of the QuestionPy Moodle plugin - https://questionpy.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 qtype_questionpy\attempt_ui;

use coding_exception;
use DOMDocument;
use DOMDocumentFragment;
use DOMElement;
use DOMException;
use DOMNode;
use qtype_questionpy\constants;

/**
* Utility functions for working with the DOM.
*
* @package qtype_questionpy
* @author Maximilian Haye
* @copyright 2024 TU Berlin, innoCampus {@link https://www.questionpy.org}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class dom_utils {
/**
* Adds the given class names to the elements `class` attribute if not already present.
*
* @param DOMElement $element
* @param string ...$newclasses
* @return void
*/
public static function add_class_names(DOMElement $element, string ...$newclasses): void {
$classarray = preg_split('/\s+/', $element->getAttribute('class'), flags: PREG_SPLIT_NO_EMPTY);
$classarray = array_unique(array_merge($classarray, $newclasses));
$element->setAttribute('class', implode(' ', $classarray));
}

/**
* Parses some HTML source and returns a fragment.
*
* @param DOMDocument $doc target document which the fragment should belong to
* @param string $html
* @param int $options
* @return DOMDocumentFragment|false fragment on success (or ignored errors), false on failure
* @see DOMDocumentFragment::appendXML() the XML equivalent is provided by PHP, but not HTML :(
*/
public static function html_to_fragment(DOMDocument $doc, string $html, int $options = 0): DOMDocumentFragment|false {
$newdoc = new DOMDocument();
// Libxml will add html and/or body elements and a DTD declaration without these options.
$options |= LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD;
// Despite LIBXML_HTML_NOIMPLIED, libxml will wrap a <p>-tag around the html if it doesn't have a root element.
if (!$newdoc->loadHTML('<body>' . $html . '</body>', $options)) {
return false;
}

$fragment = $doc->createDocumentFragment();
/** @var DOMNode $childnode */
foreach ($newdoc->documentElement->childNodes as $childnode) {
$imported = $doc->importNode($childnode, deep: true);
if ($imported === false) {
debugging('Could not import HTML node from placeholder value');
return false;
}
$fragment->appendChild($imported);
}
Comment on lines +69 to +76

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ist es ein Problem, dass hier im return false-Fall Nodes importiert, aber nicht verwendet werden? Wächst dadurch das Dokument?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Es ist leider nicht explizit dokumentiert, aber meine naive Vermutung war, dass das Dokument keine Referenz auf das Fragment (und damit transitiv das importierte Element) erhält, bis das Fragment nicht irgendwo hinzugefügt wird. Mit Blick auf den libxml-Code scheint das auch so zu sein.

Das importNode selbst scheint auch keine direkte Referenz von $doc auf $imported zu erstellen. (Nur andersherum, PHP ext-dom, libxml2). Ich sehe also nicht, warum $fragment nicht nach return false gelöscht werden sollte.


return $fragment;
}

/**
* Modifies the given XHTML select element to set its value to the given one.
*
* The `selected` attribute is added to the option with the given value and removed from all others.
* If the select doesn't have an option with the given value, a fallback option is added, which will show that the
* selected option is missing while preserving the value.
*
* @param DOMElement $select
* @param string $value
* @throws coding_exception
*/
public static function set_select_value(DOMElement $select, string $value): void {
// TODO: Support multiselects. Seems to be non-trivial, since QT vars only deal in strings, not arrays.

$valueisanoption = false;
// Find the appropriate option and mark it as selected.
foreach ($select->getElementsByTagName('option') as $option) {
$optvalue = $option->hasAttribute('value') ? $option->getAttribute('value') : $option->textContent;
if ($optvalue === $value) {
$option->setAttribute('selected', 'selected');
$valueisanoption = true;
} else {
$option->removeAttribute('selected');
}
}

if (!$valueisanoption) {
// None of the available options has the set value. The option was most likely removed.
try {
$fallbackoption = $select->ownerDocument->createElementNS(
constants::NAMESPACE_XHTML,
'option',
get_string('missing_select_option', 'qtype_questionpy')
);
} catch (DOMException $e) {
// Thrown by createElementNS "If invalid $namespace or $qualifiedName", which are both constants, so
// the coding_exception fits.
throw new coding_exception($e->getMessage());
}
if (!$fallbackoption) {
debugging("Could not add fallback option element for value '$value', which is no longer available.");
return;
}
$fallbackoption->setAttribute('value', $value);
$fallbackoption->setAttribute('selected', 'selected');
$select->appendChild($fallbackoption);
}
}

/**
* Appends an XHTML hidden input to the given element.
*
* @param DOMElement $parent
* @param string $name
* @param string $value
* @return DOMElement
* @throws coding_exception
*/
public static function add_hidden_input(DOMElement $parent, string $name, string $value): DOMElement {
try {
$element = $parent->ownerDocument->createElementNS(constants::NAMESPACE_XHTML, 'input');
} catch (DOMException $e) {
// Thrown by createElementNS "If invalid $namespace or $qualifiedName", which are both constants, so
// the coding_exception fits.
throw new coding_exception($e->getMessage());
}
$element->setAttribute('type', 'hidden');
$element->setAttribute('name', $name);
$element->setAttribute('value', $value);
$parent->appendChild($element);
return $element;
}
}
66 changes: 66 additions & 0 deletions classes/attempt_ui/invalid_option_warning.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
<?php
// This file is part of the QuestionPy Moodle plugin - https://questionpy.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 qtype_questionpy\attempt_ui;

use coding_exception;
use html_writer;

/**
* The last response has fields set to values which don't seem to be available anymore.
*
* @package qtype_questionpy
* @author Maximilian Haye
* @copyright 2024 TU Berlin, innoCampus {@link https://www.questionpy.org}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class invalid_option_warning {
/**
* Trivial constructor.
*
* @param string $name name of the input field in question
* @param string $value value from the last response, for which no option was found in the UI
* @param array $availablevalues the available options present in the UI
*/
public function __construct(
/** @var string $name name of the input field in question */
public string $name,
/** @var string $value value from the last response, for which no option was found in the UI */
public string $value,
/** @var array $availablevalues the available options present in the UI */
public array $availablevalues
) {
}

/**
* Return a localized string describing this warning to humans. Name and values are escaped.
*
* @return string
* @throws coding_exception
*/
public function localize(): string {
$availablevaluesstr = implode(', ', array_map(
fn($value) => html_writer::tag('code', s($value)),
$this->availablevalues
));

return get_string('render_warning_invalid_value', 'qtype_questionpy', [
'name' => html_writer::tag('code', s($this->name)),
'value' => html_writer::tag('code', s($this->value)),
'availablevalues' => $availablevaluesstr,
]);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.

namespace qtype_questionpy;
namespace qtype_questionpy\attempt_ui;

/**
* Metadata about a question attempt, extracted by {@see question_ui_renderer} from the XML.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,13 @@
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.

namespace qtype_questionpy;
namespace qtype_questionpy\attempt_ui;

use DOMAttr;
use DOMDocument;
use DOMElement;
use DOMXPath;
use qtype_questionpy\constants;

/**
* Parses the question UI XML and extracts the metadata.
Expand Down
Loading