MDL Shield

Database Field Email

datafield_email

Print Report
Plugin Information

A Database activity (mod_data) field subplugin that adds an Email field type. It checks submitted and imported values against core's email validation and can render them as plain text or as mailto: links.

Version:2026113000
Release:1.9
Reviewed for:5.3
Privacy API
Unit Tests
Behat Tests
Reviewed:2026-11-30
8 files·569 lines
Grade Justification

The plugin is small and closely follows core mod_data field conventions. Every write path (form/web-service submission, CSV import) runs input through PARAM_EMAIL, and the value is validated again on output. The SQL in the search code uses placeholders, the settings form escapes its values, and the Privacy API is implemented correctly. The plugin has no entry-point scripts of its own, so mod_data handles login, capability and sesskey checks.

The worst issues are two low-severity output-encoding gaps in display_browse_field():

  • The address is printed without s(). This is harmless in mod_data's generated templates, but it allows stored script injection by any entry author if a teacher writes a template that places [[Email]] inside a quoted HTML attribute.
  • The mailto: href is not percent-encoded. Entry authors can therefore pre-fill bcc/subject headers in a viewer's mail client.

Neither issue is exploitable for real harm with default configuration, and both are one-line fixes. Because they are still security weaknesses reachable by students under some conditions, the plugin falls short of the top grades. The only other item is the informational note about the legacy mod.html settings form.

AI Summary

datafield_email is a compact mod_data subplugin (one ~200-line field class, a privacy provider, a legacy mod.html settings form, and PHPUnit/Behat tests). It adds an Email field type to the Database activity. It ships no entry-point scripts, so access control, sesskey checks and record ownership are all handled by mod_data itself.

Overall the security posture is good. Values are cleaned with PARAM_EMAIL on form/web-service submission (update_content()) and on CSV import (update_content_import()), and validated again when displayed. Core's validate_email() rejects < and >, so tag injection is not possible. The search SQL uses $DB->sql_like() with named placeholders, and the privacy provider follows the same pattern as core's datafield_url.

The findings that need action are both in display_browse_field(). The address is returned without HTML escaping. RFC-valid quoted local parts can contain ", /, = and backticks, so an address can break out of a quoted attribute in a custom template, e.g. href="mailto:[[Email]]". The mailto: link is also built without percent-encoding, so ?/& in the local part pre-fill bcc/subject headers. Wrapping the value in s() and URI-encoding the href fixes both.

There is also one informational recommendation: replace the legacy mod.html table form with a Mustache template, which core field types have used since Moodle 4.4.

Findings

securityLow
Email value rendered without HTML escaping in browse templates
Exploitable by:
studentteachereditingteachermanager

display_browse_field() validates the stored value again with PARAM_EMAIL and then returns it unescaped, both as plain output and as the link text passed to html_writer::link(). Core's validate_email() (PHPMailer's filter_var(..., FILTER_VALIDATE_EMAIL) plus a <> check) prevents tag injection. However, RFC quoted local parts still allow ", ', &, /, = and backticks. mod_data\template::parse_entry() substitutes field output into the template verbatim with str_ireplace() and view.php echoes the result with no further cleaning. As a result, the value is only safe in text-node context. If a template author places [[Email]] inside a double-quoted attribute, a crafted address can break out of the attribute and add an event handler. Escaping with s() fixes this, and also stops entity sequences such as &lt; in quoted local parts from being displayed as decoded characters.

Risk Assessment

Low risk. This cannot be exploited with mod_data's generated templates, which put field tags in text nodes. It needs a teacher-authored template that places the tag inside a quoted attribute; after that, any user who can add entries can plant script that runs for every viewer. Core's free-text fields have the same weakness in attribute context, but a field that advertises validated email addresses invites template authors to treat it as attribute-safe.

Context

Stored values arrive through update_content() (via data_process_submission() and data_add_fields_contents_to_new_record()), update_content_import() (CSV) or backup restore. display_browse_field() validates every value with PARAM_EMAIL again before output, so all three paths end in the same check. mod_data\template::get_fields_replacements() inserts the result into the list, single and RSS templates.

Proof of Concept

A teacher's list or single template, with Create mailto link switched off:

<a href="mailto:[[Email]]">[[Email]]</a>

A student adds an entry with this email value, which passes PARAM_EMAIL:

"/onmouseover=alert`1`//"@example.com

It renders as <a href="mailto:"/onmouseover=alert`1`//"@example.com">, so the handler fires for anyone who hovers over the link.

Identified Code
        if (!$this->field->param1) {
            return $email;
        }
        // If param1 is set, then we need to create a mailto link.
        $attributes = ['class' => 'data-field-link'];
        return html_writer::link("mailto:{$email}", $email, $attributes);
Suggested Fix
        if (!$this->field->param1) {
            return s($email);
        }
        // If param1 is set, then we need to create a mailto link.
        $attributes = ['class' => 'data-field-link'];
        $href = 'mailto:' . str_replace('%40', '@', rawurlencode($email));
        return html_writer::link($href, s($email), $attributes);

The href change also resolves the separate mailto: encoding finding.

securityLow
mailto link built without percent-encoding the address
Exploitable by:
studentteachereditingteachermanager

When Create mailto link is enabled, the href is built by plain string concatenation ("mailto:{$email}"). In a mailto: URI (RFC 6068), the characters ?, &, # and % act as header delimiters or escapes, and FILTER_VALIDATE_EMAIL accepts all of them unquoted in the local part. Anyone who can add an entry can therefore store an address that passes validation but, when clicked, opens the viewer's mail client with attacker-chosen bcc, cc, subject or body headers already filled in. For the same reason, legitimate addresses that contain these characters produce broken links. html_writer::link() escapes the attribute for HTML through s(), but it does not URI-encode it.

Risk Assessment

Low risk. The viewer still sees the composed message and has to send it, and the link text shows the unusual address. The impact is therefore limited to nuisance or social engineering, such as quietly copying replies to an outside address. The issue only exists when the teacher has enabled the mailto option.

Context

param1 (the teacher's Create mailto link checkbox) switches display_browse_field() from plain output to html_writer::link(). Only s() is applied to the href attribute, so its URI structure comes straight from the user-supplied address.

Proof of Concept

With Create mailto link enabled, an entry author submits:

support?bcc=attacker%40evil.example&[email protected]

Clicking the rendered link opens a message to support with Bcc: [email protected] and Subject: [email protected] already filled in.

Identified Code
        return html_writer::link("mailto:{$email}", $email, $attributes);
Suggested Fix
        $href = 'mailto:' . str_replace('%40', '@', rawurlencode($email));
        return html_writer::link($href, s($email), $attributes);
best practiceInfo
Field settings form uses legacy mod.html instead of a Mustache template

The plugin's field settings form is a legacy mod.html table layout. Since Moodle 4.4, core field types render this form from templates/<type>.mustache, using the shared mod_data/fields/basicfields and mod_data/fields/requiredfield partials. data_field_base::display_edit_field() only falls back to require_once of mod.html, for backward compatibility, when no template is found. The fallback still works, so nothing is broken. However, the settings page renders with a different, non-Bootstrap layout from every core field, and because of its .html extension the inline PHP in the file is not checked by moodle-cs.

Risk Assessment

Informational. There is no security impact: the field name and description are escaped with p(), and the remaining output is language strings. This is a maintainability and UI-consistency recommendation.

Context

display_edit_field() first calls mustache_template_finder::get_template_filepath('datafield_email/email'), and only includes mod/data/field/email/mod.html when that lookup fails. The form is shown to users who manage fields, through mod/data/field.php.

Identified Code
        <td class="c0"><label for="param1"><?php echo get_string('mailtolink', 'datafield_email') ?></label></td>
        <td class="c1"><input type="checkbox" name="param1"
                              id="param1" <?php if($this->field->param1) {echo 'checked="checked"';} ?> value="1" /></td>
Suggested Fix

Add templates/email.mustache (with the standard template docblock) and delete mod.html. get_field_params() already passes name, description, required and param1 to the template:

<fieldset>
    {{> mod_data/fields/basicfields }}
    {{> mod_data/fields/requiredfield }}
    <div class="row mb-2 fitem">
        <label for="param1" class="col-auto col-md-3 col-form-label">{{#str}}mailtolink, datafield_email{{/str}}</label>
        <div class="col col-md-9 align-self-center felement">
            <input class="form-check" type="checkbox" name="param1" id="param1" value="1" {{#param1}}checked="checked"{{/param1}}>
        </div>
    </div>
</fieldset>
Additional AI Notes

Bundled icon. pix/icon.svg is the Font Awesome Free 6.5.1 envelope icon, and its CC BY 4.0 attribution is kept in an SVG comment. This is a single asset rather than a code library, so leaving it out of thirdpartylibs.xml is common practice. Since core already ships Font Awesome, the maintainer could also consider using core's icon mapping instead of bundling a copy.

Stale install/upgrade stubs. Both db/install.php and db/upgrade.php still have the file docblock "Post install (copy icon to the correct location)", but their functions are now empty. The README says version 1.9 removed the step that copied the icon into the main mod_data pix folder. Nothing in the current upgrade path removes an icon copied by earlier releases, so on upgraded sites administrators may want to check for and delete that leftover file by hand.

Search wildcards. generate_sql() builds the LIKE term as %$value% without $DB->sql_like_escape(). As a result, _ and % in a search term act as wildcards, so searching for first_last also matches firstXlast. This exactly matches core's datafield_text and is safe because placeholders are used. It is noted only because underscores are common in email addresses.

This review was generated by an AI system and may contain inaccuracies. Findings should be verified by a human reviewer before acting on them.