public static function clean_preference($value, $preferencename) {

        $definition = self::get_preference_definition($preferencename);

        if (isset($definition['type']) && $value !== null) {
            $value = clean_param($value, $definition['type']);
        }

        if (isset($definition['cleancallback'])) {
            $callback = $definition['cleancallback'];
            if (is_callable($callback)) {
                return $callback($value, $preferencename);
            } else {
                throw new coding_exception('Clean callback for preference ' . s($preferencename) . ' is not callable');
            }
        } else if ($value === null && (!isset($definition['null']) || $definition['null'] == NULL_ALLOWED)) {
            return null;
        } else if (isset($definition['choices'])) {
            if (!in_array($value, $definition['choices'])) {
                if (isset($definition['default'])) {
                    return $definition['default'];
                } else {
                    $first = reset($definition['choices']);
                    return $first;
                }
            } else {
                return $value;
            }
        } else {
            if ($value === null) {
                return isset($definition['default']) ? $definition['default'] : '';
            }
            return $value;
        }
    }