Note:

If you want to create a new page for developers, you should create it on the Moodle Developer Resource site.

Talk:Trusttext cleaning bypass

From MoodleDocs

I drafted up this little ditty before abandoning it. It doesn't require extra fields - other than the userid field which is in most tables.

Use by calling the function before an insert/update or before displaying the data.

The main advantage is that the trust is checked before being displayed. So if a users trust is revoked after they have entered some malicious script, then the script won't be displayed.

eg:

$data = new stdClass();
$data->id = 0;
$data->userid = 2;
$data->description = '<script>alert(1);</script>';

...

$data = my_trusttext_prepare($data, array('description'), $data->userid);

$id = $DB->insert_record('mytable', $data);




/**
 * Returns clean text fields if the user is not trusted
 *
 * Removes XSS nasties
 *
 * @param object $data Record object - either pre-insert/update or after retrieval
 * @param array $fields Array of fields to clean
 * @param integer|object $updatinguserid A user id or object, this is the last editor of the record NOT the current user
 * @param object $context - Context to use, defaults to system context
 * @return object $data Cleaned data fields where appropriate
 */
function my_trusttext_prepare($data, $fields, $updatinguserid, $context = null) {
	if (is_null($context)) {
		// Default to system context
		$context = get_context_instance(CONTEXT_SYSTEM);
	}

	if (!is_object($data) || !is_array($fields)) {
		// Params are invalid
		print_error('error:trusttextparam', 'my_errors');
	}

	if (!has_capability('moodle/site:trustcontent', $context, $updatinguserid)) {
		// User might be a cheeky monkey, so clean the text
		foreach ($fields as $field) {
			if (!isset($data->$field)) {
				// Oops, field doesn't exist
				print_error('error:trusttextfieldunknown', 'my_errors', null, $field);
			} else {
				$data->$field = clean_text($data->$field);
			}
		}
	}

	return $data;
}