Merge branch 'MDL-49398_final4' of https://github.com/sk-unikent/moodle
authorJun Pataleta <jun@moodle.com>
Tue, 6 Jun 2017 04:43:14 +0000 (12:43 +0800)
committerJun Pataleta <jun@moodle.com>
Tue, 6 Jun 2017 04:43:14 +0000 (12:43 +0800)
37 files changed:
Gruntfile.js
admin/templates/setting_filetypes.mustache [new file with mode: 0644]
lang/en/form.php
lang/en/moodle.php
lib/adminlib.php
lib/cronlib.php
lib/db/services.php
lib/form/amd/build/filetypes.min.js [new file with mode: 0644]
lib/form/amd/src/filetypes.js [new file with mode: 0644]
lib/form/classes/external.php [new file with mode: 0644]
lib/form/classes/filetypes_util.php [new file with mode: 0644]
lib/form/filetypes.php [new file with mode: 0644]
lib/form/templates/filetypes-browser.mustache [new file with mode: 0644]
lib/form/templates/filetypes-descriptions.mustache [new file with mode: 0644]
lib/form/templates/filetypes-trigger.mustache [new file with mode: 0644]
lib/form/tests/external_test.php [new file with mode: 0644]
lib/form/tests/filetypes_util_test.php [new file with mode: 0644]
lib/formslib.php
lib/outputrenderers.php
lib/php-css-parser/Parser.php
lib/php-css-parser/moodle_readme.txt
lib/templates/loginform.mustache [moved from lib/templates/login.mustache with 99% similarity]
lib/upgrade.txt
lib/upgradelib.php
mod/assign/overrideedit.php
mod/data/tests/behat/completion_condition_entries.feature
mod/quiz/tests/behat/editing_remove_multiple_questions.feature
theme/boost/classes/output/core_renderer.php
theme/boost/scss/moodle/drawer.scss
theme/boost/scss/moodle/forms.scss
theme/boost/templates/core/loginform.mustache [moved from theme/boost/templates/core/login.mustache with 99% similarity]
theme/boost/templates/core_form/element-filetypes.mustache [new file with mode: 0644]
theme/boost/tests/behat/behat_theme_boost_behat_course.php
theme/bootstrapbase/less/moodle/forms.less
theme/bootstrapbase/style/moodle.css
theme/upgrade.txt
version.php

index 4cb9e9e..5f2302e 100644 (file)
@@ -338,7 +338,7 @@ module.exports = function(grunt) {
             opts: {stdio: 'inherit', env: process.env}
         }, function(error, result, code) {
             // Propagate the exit code.
-            done(code);
+            done(code === 0);
         });
     };
 
diff --git a/admin/templates/setting_filetypes.mustache b/admin/templates/setting_filetypes.mustache
new file mode 100644 (file)
index 0000000..7075ea2
--- /dev/null
@@ -0,0 +1,52 @@
+{{!
+    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/>.
+}}
+{{!
+    @template core_admin/setting_filetypes
+
+    Renders the admin_setting_filetypes setting element.
+
+    Context variables required for this template:
+    * id - element id
+    * name - form element name
+    * value - element value
+    * descriptions - data for the core_form/filetypes-descriptions template
+
+    Example context (json):
+    {
+        "id": "test0",
+        "name": "test",
+        "value": ".jpg,.gif",
+        "descriptions": {
+            "hasdescriptions": true,
+            "descriptions": [
+                {
+                    "description": "Image (JPEG)",
+                    "extensions": ".jpeg .jpe .jpg"
+                },
+                {
+                    "description": "Image (GIF)",
+                    "extensions": ".gif"
+                }
+            ]
+        }
+    }
+}}
+<div class="form-text defaultsnext">
+    <input type="text" name="{{name}}" value="{{value}}" size="30" id="{{id}}" class="text-ltr">
+    <span data-filetypesbrowser="{{id}}"></span>
+    <div data-filetypesdescriptions="{{id}}">{{#descriptions}}{{>core_form/filetypes-descriptions}}{{/descriptions}}</div>
+</div>
index 0285e82..2ed6cbf 100644 (file)
@@ -41,6 +41,9 @@ $string['err_nopunctuation'] = 'You must enter no punctuation characters here.';
 $string['err_numeric'] = 'You must enter a number here.';
 $string['err_rangelength'] = 'You must enter between {$a->format[0]} and {$a->format[1]} characters here.';
 $string['err_required'] = 'You must supply a value here.';
+$string['filetypesany'] = 'All file types';
+$string['filetypesnotwhitelisted'] = 'These file types are not allowed here: {$a}';
+$string['filetypesothers'] = 'Other files';
 $string['general'] = 'General';
 $string['hideadvanced'] = 'Hide advanced';
 $string['hour'] = 'Hour';
index 196ebde..07e154d 100644 (file)
@@ -1843,6 +1843,7 @@ $string['subcategory'] = 'Subcategory';
 $string['subcategoryof'] = 'Subcategory of {$a}';
 $string['submit'] = 'Submit';
 $string['success'] = 'Success';
+$string['successduration'] = 'Success ({$a} seconds)';
 $string['summary'] = 'Summary';
 $string['summary_help'] = 'The idea of a summary is a short text to prepare students for the activities within the topic or week. The text is shown on the course page under the section name.';
 $string['summaryof'] = 'Summary of {$a}';
index 74a92b3..7fc7d30 100644 (file)
@@ -10519,3 +10519,121 @@ class admin_setting_scsscode extends admin_setting_configtextarea {
         return true;
     }
 }
+
+
+/**
+ * Administration setting to define a list of file types.
+ *
+ * @copyright 2016 Jonathon Fowler <fowlerj@usq.edu.au>
+ * @copyright 2017 David Mudrák <david@moodle.com>
+ * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class admin_setting_filetypes extends admin_setting_configtext {
+
+    /** @var array Allow selection from these file types only. */
+    protected $onlytypes = [];
+
+    /** @var bool Allow selection of 'All file types' (will be stored as '*'). */
+    protected $allowall = true;
+
+    /** @var core_form\filetypes_util instance to use as a helper. */
+    protected $util = null;
+
+    /**
+     * Constructor.
+     *
+     * @param string $name Unique ascii name like 'mycoresetting' or 'myplugin/mysetting'
+     * @param string $visiblename Localised label of the setting
+     * @param string $description Localised description of the setting
+     * @param string $defaultsetting Default setting value.
+     * @param array $options Setting widget options, an array with optional keys:
+     *   'onlytypes' => array Allow selection from these file types only; for example ['onlytypes' => ['web_image']].
+     *   'allowall' => bool Allow to select 'All file types', defaults to true. Does not apply if onlytypes are set.
+     */
+    public function __construct($name, $visiblename, $description, $defaultsetting = '', array $options = []) {
+
+        parent::__construct($name, $visiblename, $description, $defaultsetting, PARAM_RAW);
+
+        if (array_key_exists('onlytypes', $options) && is_array($options['onlytypes'])) {
+            $this->onlytypes = $options['onlytypes'];
+        }
+
+        if (!$this->onlytypes && array_key_exists('allowall', $options)) {
+            $this->allowall = (bool)$options['allowall'];
+        }
+
+        $this->util = new \core_form\filetypes_util();
+    }
+
+    /**
+     * Normalize the user's input and write it to the database as comma separated list.
+     *
+     * Comma separated list as a text representation of the array was chosen to
+     * make this compatible with how the $CFG->courseoverviewfilesext values are stored.
+     *
+     * @param string $data Value submitted by the admin.
+     * @return string Epty string if all good, error message otherwise.
+     */
+    public function write_setting($data) {
+        return parent::write_setting(implode(',', $this->util->normalize_file_types($data)));
+    }
+
+    /**
+     * Validate data before storage
+     *
+     * @param string $data The setting values provided by the admin
+     * @return bool|string True if ok, the string if error found
+     */
+    public function validate($data) {
+
+        // No need to call parent's validation here as we are PARAM_RAW.
+
+        if ($this->util->is_whitelisted($data, $this->onlytypes)) {
+            return true;
+
+        } else {
+            $troublemakers = $this->util->get_not_whitelisted($data, $this->onlytypes);
+            return get_string('filetypesnotwhitelisted', 'core_form', implode(' ', $troublemakers));
+        }
+    }
+
+    /**
+     * Return an HTML string for the setting element.
+     *
+     * @param string $data The current setting value
+     * @param string $query Admin search query to be highlighted
+     * @return string HTML to be displayed
+     */
+    public function output_html($data, $query='') {
+        global $OUTPUT, $PAGE;
+
+        $default = $this->get_defaultsetting();
+        $context = (object) [
+            'id' => $this->get_id(),
+            'name' => $this->get_full_name(),
+            'value' => $data,
+            'descriptions' => $this->util->describe_file_types($data),
+        ];
+        $element = $OUTPUT->render_from_template('core_admin/setting_filetypes', $context);
+
+        $PAGE->requires->js_call_amd('core_form/filetypes', 'init', [
+            $this->get_id(),
+            $this->visiblename,
+            $this->onlytypes,
+            $this->allowall,
+        ]);
+
+        return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $default, $query);
+    }
+
+    /**
+     * Should the values be always displayed in LTR mode?
+     *
+     * We always return true here because these values are not RTL compatible.
+     *
+     * @return bool True because these values are not RTL compatible.
+     */
+    public function get_force_ltr() {
+        return true;
+    }
+}
index 164a767..55626a4 100644 (file)
@@ -203,7 +203,7 @@ function cron_run_single_task(\core\task\scheduled_task $task) {
     }
     $component = $task->get_component();
     if ($plugininfo = core_plugin_manager::instance()->get_plugin_info($component)) {
-        if (!$plugininfo->is_enabled() && !$task->get_run_if_component_disabled()) {
+        if ($plugininfo->is_enabled() === false && !$task->get_run_if_component_disabled()) {
             echo "Component is not enabled ($component).\n";
             return false;
         }
index 7af71ca..002640e 100644 (file)
@@ -469,6 +469,15 @@ $functions = array(
         'type'        => 'write',
         'classpath'   => 'files/externallib.php',
     ),
+    'core_form_get_filetypes_browser_data' => array(
+        'classname' => 'core_form\external',
+        'methodname' => 'get_filetypes_browser_data',
+        'classpath' => '',
+        'description' => 'Provides data for the filetypes element browser.',
+        'type' => 'read',
+        'loginrequired' => false,
+        'ajax' => true,
+    ),
     'core_get_component_strings' => array(
         'classname' => 'core_external',
         'methodname' => 'get_component_strings',
diff --git a/lib/form/amd/build/filetypes.min.js b/lib/form/amd/build/filetypes.min.js
new file mode 100644 (file)
index 0000000..614cb69
Binary files /dev/null and b/lib/form/amd/build/filetypes.min.js differ
diff --git a/lib/form/amd/src/filetypes.js b/lib/form/amd/src/filetypes.js
new file mode 100644 (file)
index 0000000..049214c
--- /dev/null
@@ -0,0 +1,306 @@
+// 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 module allows to enhance the form elements MoodleQuickForm_filetypes
+ *
+ * @module     core_form/filetypes
+ * @package    core_form
+ * @copyright  2017 David Mudrak <david@moodle.com>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ * @since      3.3
+ */
+define(['jquery', 'core/log', 'core/str', 'core/modal_factory', 'core/modal_events', 'core/ajax',
+        'core/templates', 'core/tree'],
+    function($, Log, Str, ModalFactory, ModalEvents, Ajax, Templates, Tree) {
+
+    "use strict";
+
+    /**
+     * Constructor of the FileTypes instances.
+     *
+     * @constructor
+     * @param {String} elementId The id of the form element to enhance
+     * @param {String} elementLabel The label of the form element used as the modal selector title
+     * @param {String} onlyTypes Limit the list of offered types to this
+     * @param {Bool} allowAll Allow presence of the "All file types" item
+     */
+    var FileTypes = function(elementId, elementLabel, onlyTypes, allowAll) {
+
+        this.elementId = elementId;
+        this.elementLabel = elementLabel;
+        this.onlyTypes = onlyTypes;
+        this.allowAll = allowAll;
+
+        this.inputField = $('#' + elementId);
+        this.wrapperBrowserTrigger = $('[data-filetypesbrowser="' + elementId + '"]');
+        this.wrapperDescriptions = $('[data-filetypesdescriptions="' + elementId + '"]');
+
+        if (!this.wrapperBrowserTrigger.length) {
+            // This is a valid case. Most probably the element is frozen and
+            // the filetypes browser should not be available.
+            return;
+        }
+
+        if (!this.inputField.length || !this.wrapperDescriptions.length) {
+            Log.error('core_form/filetypes: Unexpected DOM structure, unable to enhance filetypes field ' + elementId);
+            return;
+        }
+
+        this.prepareBrowserTrigger()
+            .then(function() {
+                return this.prepareBrowserModal();
+            }.bind(this))
+
+            .then(function() {
+                return this.prepareBrowserTree();
+            }.bind(this));
+    };
+
+    /**
+     * Create and set the browser trigger widget (this.browserTrigger).
+     *
+     * @method prepareBrowserTrigger
+     * @returns {Promise}
+     */
+    FileTypes.prototype.prepareBrowserTrigger = function() {
+        return Templates.render('core_form/filetypes-trigger', {})
+            .then(function(html) {
+                this.wrapperBrowserTrigger.html(html);
+                this.browserTrigger = this.wrapperBrowserTrigger.find('[data-filetypeswidget="browsertrigger"]');
+            }.bind(this));
+    };
+
+    /**
+     * Create and set the modal for displaying the browser (this.browserModal).
+     *
+     * @method prepareBrowserModal
+     * @returns {Promise}
+     */
+    FileTypes.prototype.prepareBrowserModal = function() {
+        return ModalFactory.create({
+            type: ModalFactory.types.SAVE_CANCEL,
+            title: this.elementLabel
+
+        }).then(function(modal) {
+            this.browserModal = modal;
+        }.bind(this))
+
+        .then(function() {
+            // Because we have custom conditional modal trigger, we need to
+            // handle the focus after closing ourselves, too.
+            this.browserModal.getRoot().on(ModalEvents.hidden, function() {
+                this.browserTrigger.focus();
+            }.bind(this));
+
+            this.browserModal.getRoot().on(ModalEvents.save, function() {
+                this.saveBrowserModal();
+            }.bind(this));
+        }.bind(this));
+
+    };
+
+    /**
+     * Create and set the tree in the browser modal's body.
+     *
+     * @method prepareBrowserTree
+     * @returns {Promise}
+     */
+    FileTypes.prototype.prepareBrowserTree = function() {
+
+        this.browserTrigger.on('click', function(e) {
+            e.preventDefault();
+
+            // We want to display the browser modal only when the associated input
+            // field is not frozen (disabled).
+            if (this.inputField.is('[disabled]')) {
+                return;
+            }
+
+            var bodyContent = this.loadBrowserModalBody();
+
+            bodyContent.then(function() {
+
+                // Turn the list of groups and extensions into the tree.
+                this.browserTree = new Tree(this.browserModal.getBody());
+
+                // Override the behaviour of the Enter and Space keys to toggle our checkbox,
+                // rather than toggle the tree node expansion status.
+                this.browserTree.handleKeyDown = function(item, e) {
+                    if (e.keyCode == this.browserTree.keys.enter || e.keyCode == this.browserTree.keys.space) {
+                        e.preventDefault();
+                        e.stopPropagation();
+                        this.toggleCheckbox(item.attr('data-filetypesbrowserkey'));
+                    } else {
+                        Tree.prototype.handleKeyDown.call(this.browserTree, item, e);
+                    }
+                }.bind(this);
+
+                if (this.allowAll) {
+                    // Hide all other items if "All file types" is enabled.
+                    this.hideOrShowItemsDependingOnAllowAll(this.browserModal.getRoot()
+                        .find('input[type="checkbox"][data-filetypesbrowserkey="*"]:first'));
+                    // And do the same whenever we click that checkbox.
+                    this.browserModal.getRoot().on('change', 'input[type="checkbox"][data-filetypesbrowserkey="*"]', function(e) {
+                        this.hideOrShowItemsDependingOnAllowAll($(e.currentTarget));
+                    }.bind(this));
+                }
+
+                // Synchronize checked status if the file extension is present in multiple groups.
+                this.browserModal.getRoot().on('change', 'input[type="checkbox"][data-filetypesbrowserkey]', function(e) {
+                    var checkbox = $(e.currentTarget);
+                    var key = checkbox.attr('data-filetypesbrowserkey');
+                    this.browserModal.getRoot().find('input[type="checkbox"][data-filetypesbrowserkey="' + key + '"]')
+                        .prop('checked', checkbox.prop('checked'));
+                }.bind(this));
+
+            }.bind(this))
+
+            .then(function() {
+                this.browserModal.show();
+            }.bind(this));
+
+            this.browserModal.setBody(bodyContent);
+
+        }.bind(this));
+
+        // Return a resolved promise.
+        return $.when();
+    };
+
+    /**
+     * Load the browser modal body contents.
+     *
+     * @returns {Promise}
+     */
+    FileTypes.prototype.loadBrowserModalBody = function() {
+
+        var args = {
+            onlytypes: this.onlyTypes.join(),
+            allowall: this.allowAll,
+            current: this.inputField.val()
+        };
+
+        return Ajax.call([{
+            methodname: 'core_form_get_filetypes_browser_data',
+            args: args
+
+        }])[0].then(function(browserData) {
+            return Templates.render('core_form/filetypes-browser', {
+                elementid: this.elementId,
+                groups: browserData.groups
+            });
+        }.bind(this));
+    };
+
+    /**
+     * Change the checked status of the given file type (group or extension).
+     *
+     * @method toggleCheckbox
+     * @param {String} key
+     */
+    FileTypes.prototype.toggleCheckbox = function(key) {
+
+        var checkbox = this.browserModal.getRoot().find('input[type="checkbox"][data-filetypesbrowserkey="' + key + '"]:first');
+
+        checkbox.prop('checked', !checkbox.prop('checked'));
+    };
+
+    /**
+     * Update the associated input field with selected file types.
+     *
+     * @method saveBrowserModal
+     */
+    FileTypes.prototype.saveBrowserModal = function() {
+
+        // Check the "All file types" first.
+        if (this.allowAll) {
+            var allcheckbox = this.browserModal.getRoot().find('input[type="checkbox"][data-filetypesbrowserkey="*"]');
+            if (allcheckbox.length && allcheckbox.prop('checked')) {
+                this.inputField.val('*');
+                this.updateDescriptions(['*']);
+                return;
+            }
+        }
+
+        // Iterate over all checked boxes and populate the list.
+        var newvalue = [];
+
+        this.browserModal.getRoot().find('input[type="checkbox"]').each(/** @this represents the checkbox */ function() {
+            var checkbox = $(this);
+            var key = checkbox.attr('data-filetypesbrowserkey');
+
+            if (checkbox.prop('checked')) {
+                newvalue.push(key);
+            }
+        });
+
+        // Remove duplicates (e.g. file types present in multiple groups).
+        newvalue = newvalue.filter(function(x, i, a) {
+            return a.indexOf(x) == i;
+        });
+
+        this.inputField.val(newvalue.join(' '));
+        this.updateDescriptions(newvalue);
+    };
+
+    /**
+     * Describe the selected filetypes in the form when saving the browser.
+     *
+     * @param {Array} keys List of keys to describe
+     * @returns {Promise}
+     */
+    FileTypes.prototype.updateDescriptions = function(keys) {
+
+        var descriptions = [];
+
+        keys.forEach(function(key) {
+            descriptions.push({
+                description: this.browserModal.getRoot().find('[data-filetypesname="' + key + '"]:first').text().trim(),
+                extensions: this.browserModal.getRoot().find('[data-filetypesextensions="' + key + '"]:first').text().trim()
+            });
+        }.bind(this));
+
+        var templatedata = {
+            hasdescriptions: (descriptions.length > 0),
+            descriptions: descriptions
+        };
+
+        return Templates.render('core_form/filetypes-descriptions', templatedata)
+            .then(function(html) {
+                this.wrapperDescriptions.html(html);
+            }.bind(this));
+    };
+
+    /**
+     * If "All file types" is checked, all other browser items are made hidden, and vice versa.
+     *
+     * @param {jQuery} allcheckbox The "All file types" checkbox.
+     */
+    FileTypes.prototype.hideOrShowItemsDependingOnAllowAll = function(allcheckbox) {
+        var others = this.browserModal.getRoot().find('[role="treeitem"][data-filetypesbrowserkey!="*"]');
+        if (allcheckbox.prop('checked')) {
+            others.hide();
+        } else {
+            others.show();
+        }
+    };
+
+    return {
+        init: function(elementId, elementLabel, onlyTypes, allowAll) {
+            new FileTypes(elementId, elementLabel, onlyTypes, allowAll);
+        }
+    };
+});
diff --git a/lib/form/classes/external.php b/lib/form/classes/external.php
new file mode 100644 (file)
index 0000000..40b1c73
--- /dev/null
@@ -0,0 +1,108 @@
+<?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/>.
+
+/**
+ * Provides the {@link core_form\external} class.
+ *
+ * @package     core_form
+ * @category    external
+ * @copyright   2017 David Mudrák <david@moodle.com>
+ * @copyright   2016 Jonathon Fowler <fowlerj@usq.edu.au>
+ * @license     http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+namespace core_form;
+
+use external_api;
+use external_function_parameters;
+use external_multiple_structure;
+use external_single_structure;
+use external_value;
+
+defined('MOODLE_INTERNAL') || die();
+
+require_once($CFG->libdir.'/externallib.php');
+
+/**
+ * Implements the external functions provided by the core_form subsystem.
+ *
+ * @copyright 2017 David Mudrak <david@moodle.com>
+ * @copyright 2016 Jonathon Fowler <fowlerj@usq.edu.au>
+ * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class external extends external_api {
+
+    /**
+     * Describes the input paramaters of the get_filetypes_browser_data external function.
+     *
+     * @return external_description
+     */
+    public static function get_filetypes_browser_data_parameters() {
+        return new external_function_parameters([
+            'onlytypes' => new external_value(PARAM_RAW, 'Limit the browser to the given groups and extensions', VALUE_DEFAULT, ''),
+            'allowall' => new external_value(PARAM_BOOL, 'Allows to select All file types, does not apply with onlytypes are set.',
+                VALUE_DEFAULT, true),
+            'current' => new external_value(PARAM_RAW, 'Current types that should be selected.', VALUE_DEFAULT, ''),
+        ]);
+    }
+
+    /**
+     * Implements the get_filetypes_browser_data external function.
+     *
+     * @param string $onlytypes Allow selection from these file types only; for example 'web_image'.
+     * @param bool $allowall Allow to select 'All file types'. Does not apply if onlytypes is set.
+     * @param string $current Current values that should be selected.
+     * @return object
+     */
+    public static function get_filetypes_browser_data($onlytypes, $allowall, $current) {
+
+        $params = self::validate_parameters(self::get_filetypes_browser_data_parameters(),
+            compact('onlytypes', 'allowall', 'current'));
+
+        $util = new filetypes_util();
+
+        return ['groups' => $util->data_for_browser($params['onlytypes'], $params['allowall'], $params['current'])];
+    }
+
+    /**
+     * Describes the output of the get_filetypes_browser_data external function.
+     *
+     * @return external_description
+     */
+    public static function get_filetypes_browser_data_returns() {
+
+        $type = new external_single_structure([
+            'key' => new external_value(PARAM_RAW, 'The file type identifier'),
+            'name' => new external_value(PARAM_RAW, 'The file type name'),
+            'selected' => new external_value(PARAM_BOOL, 'Should it be marked as selected'),
+            'ext' => new external_value(PARAM_RAW, 'The file extension associated with the file type'),
+        ]);
+
+        $group = new external_single_structure([
+            'key' => new external_value(PARAM_RAW, 'The file type group identifier'),
+            'name' => new external_value(PARAM_RAW, 'The file type group name'),
+            'selectable' => new external_value(PARAM_BOOL, 'Can it be marked as selected'),
+            'selected' => new external_value(PARAM_BOOL, 'Should it be marked as selected'),
+            'ext' => new external_value(PARAM_RAW, 'The list of file extensions associated with the group'),
+            'expanded' => new external_value(PARAM_BOOL, 'Should the group start as expanded or collapsed'),
+            'types' => new external_multiple_structure($type, 'List of file types in the group'),
+        ]);
+
+        return new external_single_structure([
+            'groups' => new external_multiple_structure($group, 'List of file type groups'),
+        ]);
+    }
+}
diff --git a/lib/form/classes/filetypes_util.php b/lib/form/classes/filetypes_util.php
new file mode 100644 (file)
index 0000000..4eefc07
--- /dev/null
@@ -0,0 +1,516 @@
+<?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/>.
+
+/**
+ * Provides the {@link core_form\filetypes_util} class.
+ *
+ * @package     core_form
+ * @copyright   2017 David Mudrák <david@moodle.com>
+ * @license     http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+namespace core_form;
+
+use core_collator;
+use core_filetypes;
+use core_text;
+
+defined('MOODLE_INTERNAL') || die();
+
+/**
+ * Utility class for handling with file types in the forms.
+ *
+ * This class is supposed to serve as a helper class for {@link MoodleQuickForm_filetypes}
+ * and {@link admin_setting_filetypes} classes.
+ *
+ * The file types can be specified in a syntax compatible with what filepicker
+ * and filemanager support via the "accepted_types" option: a list of extensions
+ * (e.g. ".doc"), mimetypes ("image/png") or groups ("audio").
+ *
+ * @copyright 2017 David Mudrak <david@moodle.com>
+ * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class filetypes_util {
+
+    /** @var array Cache of all file type groups for the {@link self::get_groups_info()}. */
+    protected $cachegroups = null;
+
+    /**
+     * Converts the argument into an array (list) of file types.
+     *
+     * The list can be separated by whitespace, end of lines, commas, colons and semicolons.
+     * Empty values are not returned. Values are converted to lowercase.
+     * Duplicates are removed. Glob evaluation is not supported.
+     *
+     * The return value can be used as the accepted_types option for the filepicker.
+     *
+     * @param string|array $types List of file extensions, groups or mimetypes
+     * @return array of strings
+     */
+    public function normalize_file_types($types) {
+
+        if ($types === '') {
+            return [];
+        }
+
+        // Turn string into a list.
+        if (!is_array($types)) {
+            $types = preg_split('/[\s,;:"\']+/', $types, null, PREG_SPLIT_NO_EMPTY);
+        }
+
+        // Fix whitespace and normalize the syntax a bit.
+        foreach ($types as $i => $type) {
+            $type = str_replace('*.', '.', $type);
+            $type = core_text::strtolower($type);
+            $type = trim($type);
+
+            if ($type === '*') {
+                return ['*'];
+            }
+
+            $types[$i] = $type;
+        }
+
+        // Do not make the user think that globs (like ".doc?") would work.
+        foreach ($types as $i => $type) {
+            if (strpos($type, '*') !== false or strpos($type, '?') !== false) {
+                unset($types[$i]);
+            }
+        }
+
+        foreach ($types as $i => $type) {
+            if (substr($type, 0, 1) === '.') {
+                // It looks like an extension.
+                $type = '.'.ltrim($type, '.');
+                $types[$i] = clean_param($type, PARAM_FILE);
+            } else if ($this->looks_like_mimetype($type)) {
+                // All good, it looks like a mimetype.
+                continue;
+            } else if ($this->is_filetype_group($type)) {
+                // All good, it is a known type group.
+                continue;
+            } else {
+                // We assume the user typed something like "png" so we consider
+                // it an extension.
+                $types[$i] = '.'.$type;
+            }
+        }
+
+        $types = array_filter($types, 'strlen');
+        $types = array_keys(array_flip($types));
+
+        return $types;
+    }
+
+    /**
+     * Does the given file type looks like a valid MIME type?
+     *
+     * This does not check of the MIME type is actually registered here/known.
+     *
+     * @param string $type
+     * @return bool
+     */
+    public function looks_like_mimetype($type) {
+        return (bool)preg_match('~^[-\.a-z0-9]+/[a-z0-9]+([-\.\+][a-z0-9]+)*$~', $type);
+    }
+
+    /**
+     * Is the given string a known filetype group?
+     *
+     * @param string $type
+     * @return bool|object false or the group info
+     */
+    public function is_filetype_group($type) {
+
+        $info = $this->get_groups_info();
+
+        if (isset($info[$type])) {
+            return $info[$type];
+
+        } else {
+            return false;
+        }
+    }
+
+    /**
+     * Provides a list of all known file type groups and their properties.
+     *
+     * @return array
+     */
+    public function get_groups_info() {
+
+        if ($this->cachegroups !== null) {
+            return $this->cachegroups;
+        }
+
+        $groups = [];
+
+        foreach (core_filetypes::get_types() as $ext => $info) {
+            if (isset($info['groups']) && is_array($info['groups'])) {
+                foreach ($info['groups'] as $group) {
+                    if (!isset($groups[$group])) {
+                        $groups[$group] = (object) [
+                            'extensions' => [],
+                            'mimetypes' => [],
+                        ];
+                    }
+                    $groups[$group]->extensions['.'.$ext] = true;
+                    if (isset($info['type'])) {
+                        $groups[$group]->mimetypes[$info['type']] = true;
+                    }
+                }
+            }
+        }
+
+        foreach ($groups as $group => $info) {
+            $info->extensions = array_keys($info->extensions);
+            $info->mimetypes = array_keys($info->mimetypes);
+        }
+
+        $this->cachegroups = $groups;
+        return $this->cachegroups;
+    }
+
+    /**
+     * Return a human readable name of the filetype group.
+     *
+     * @param string $group
+     * @return string
+     */
+    public function get_group_description($group) {
+
+        if (get_string_manager()->string_exists('group:'.$group, 'core_mimetypes')) {
+            return get_string('group:'.$group, 'core_mimetypes');
+        } else {
+            return s($group);
+        }
+    }
+
+    /**
+     * Describe the list of file types for human user.
+     *
+     * Given the list of file types, return a list of human readable
+     * descriptive names of relevant groups, types or file formats.
+     *
+     * @param string|array $types
+     * @return object
+     */
+    public function describe_file_types($types) {
+
+        $descriptions = [];
+        $types = $this->normalize_file_types($types);
+
+        foreach ($types as $type) {
+            if ($type === '*') {
+                $desc = get_string('filetypesany', 'core_form');
+                $descriptions[$desc] = [];
+            } else if ($group = $this->is_filetype_group($type)) {
+                $desc = $this->get_group_description($type);
+                $descriptions[$desc] = $group->extensions;
+
+            } else if ($this->looks_like_mimetype($type)) {
+                $desc = get_mimetype_description($type);
+                $descriptions[$desc] = file_get_typegroup('extension', [$type]);
+
+            } else {
+                $desc = get_mimetype_description(['filename' => 'fakefile'.$type]);
+                if (isset($descriptions[$desc])) {
+                    $descriptions[$desc][] = $type;
+                } else {
+                    $descriptions[$desc] = [$type];
+                }
+            }
+        }
+
+        $data = [];
+
+        foreach ($descriptions as $desc => $exts) {
+            sort($exts);
+            $data[] = (object)[
+                'description' => $desc,
+                'extensions' => join(' ', $exts),
+            ];
+        }
+
+        core_collator::asort_objects_by_property($data, 'description', core_collator::SORT_NATURAL);
+
+        return (object)[
+            'hasdescriptions' => !empty($data),
+            'descriptions' => array_values($data),
+        ];
+    }
+
+    /**
+     * Prepares data for the filetypes-browser.mustache
+     *
+     * @param string|array $onlytypes Allow selection from these file types only; for example 'web_image'.
+     * @param bool $allowall Allow to select 'All file types'. Does not apply with onlytypes are set.
+     * @param string|array $current Current values that should be selected.
+     * @return object
+     */
+    public function data_for_browser($onlytypes=null, $allowall=true, $current=null) {
+
+        $groups = [];
+        $current = $this->normalize_file_types($current);
+
+        // Firstly populate the tree of extensions categorized into groups.
+
+        foreach ($this->get_groups_info() as $groupkey => $groupinfo) {
+            if (empty($groupinfo->extensions)) {
+                continue;
+            }
+
+            $group = (object) [
+                'key' => $groupkey,
+                'name' => $this->get_group_description($groupkey),
+                'selectable' => true,
+                'selected' => in_array($groupkey, $current),
+                'ext' => implode(' ', $groupinfo->extensions),
+                'expanded' => false,
+            ];
+
+            $types = [];
+
+            foreach ($groupinfo->extensions as $extension) {
+                if ($onlytypes && !$this->is_whitelisted($extension, $onlytypes)) {
+                    $group->selectable = false;
+                    $group->expanded = true;
+                    $group->ext = '';
+                    continue;
+                }
+
+                $desc = get_mimetype_description(['filename' => 'fakefile'.$extension]);
+
+                if ($selected = in_array($extension, $current)) {
+                    $group->expanded = true;
+                }
+
+                $types[] = (object) [
+                    'key' => $extension,
+                    'name' => get_mimetype_description(['filename' => 'fakefile'.$extension]),
+                    'selected' => $selected,
+                    'ext' => $extension,
+                ];
+            }
+
+            if (empty($types)) {
+                continue;
+            }
+
+            core_collator::asort_objects_by_property($types, 'name', core_collator::SORT_NATURAL);
+
+            $group->types = array_values($types);
+            $groups[] = $group;
+        }
+
+        core_collator::asort_objects_by_property($groups, 'name', core_collator::SORT_NATURAL);
+
+        // Append all other uncategorized extensions.
+
+        $others = [];
+
+        foreach (core_filetypes::get_types() as $extension => $info) {
+            $extension = '.'.$extension;
+            if ($onlytypes && !$this->is_whitelisted($extension, $onlytypes)) {
+                continue;
+            }
+            if (!isset($info['groups']) || empty($info['groups'])) {
+                $others[] = (object) [
+                    'key' => $extension,
+                    'name' => get_mimetype_description(['filename' => 'fakefile'.$extension]),
+                    'selected' => in_array($extension, $current),
+                    'ext' => $extension,
+                ];
+            }
+        }
+
+        core_collator::asort_objects_by_property($others, 'name', core_collator::SORT_NATURAL);
+
+        if (!empty($others)) {
+            $groups[] = (object) [
+                'key' => '',
+                'name' => get_string('filetypesothers', 'core_form'),
+                'selectable' => false,
+                'selected' => false,
+                'ext' => '',
+                'types' => array_values($others),
+                'expanded' => true,
+            ];
+        }
+
+        if (empty($onlytypes) and $allowall) {
+            array_unshift($groups, (object) [
+                'key' => '*',
+                'name' => get_string('filetypesany', 'core_form'),
+                'selectable' => true,
+                'selected' => in_array('*', $current),
+                'ext' => null,
+                'types' => [],
+                'expanded' => false,
+            ]);
+        }
+
+        $groups = array_values($groups);
+
+        return $groups;
+    }
+
+    /**
+     * Expands the file types into the list of file extensions.
+     *
+     * The groups and mimetypes are expanded into the list of their associated file
+     * extensions. Depending on the $keepgroups and $keepmimetypes, the groups
+     * and mimetypes themselves are either kept in the list or removed.
+     *
+     * @param string|array $types
+     * @param bool $keepgroups Keep the group item in the list after expansion
+     * @param bool $keepmimetypes Keep the mimetype item in the list after expansion
+     * @return array list of extensions and eventually groups and types
+     */
+    public function expand($types, $keepgroups=false, $keepmimetypes=false) {
+
+        $expanded = [];
+
+        foreach ($this->normalize_file_types($types) as $type) {
+            if ($group = $this->is_filetype_group($type)) {
+                foreach ($group->extensions as $ext) {
+                    $expanded[$ext] = true;
+                }
+                if ($keepgroups) {
+                    $expanded[$type] = true;
+                }
+
+            } else if ($this->looks_like_mimetype($type)) {
+                // A mime type expands to the associated extensions.
+                foreach (file_get_typegroup('extension', [$type]) as $ext) {
+                    $expanded[$ext] = true;
+                }
+                if ($keepmimetypes) {
+                    $expanded[$type] = true;
+                }
+
+            } else {
+                // Single extension expands to itself.
+                $expanded[$type] = true;
+            }
+        }
+
+        return array_keys($expanded);
+    }
+
+    /**
+     * Should the given file type be considered as a part of the given whitelist.
+     *
+     * If multiple types are provided, all of them must be part of the
+     * whitelist. Empty type is part of any whitelist. Any type is part of an
+     * empty whitelist.
+     *
+     * @param string|array $types File types to be checked
+     * @param string|array $whitelist An array or string of whitelisted types
+     * @return boolean
+     */
+    public function is_whitelisted($types, $whitelist) {
+        return empty($this->get_not_whitelisted($types, $whitelist));
+    }
+
+    /**
+     * Returns all types that are not part of the give whitelist.
+     *
+     * This is similar check to the {@link self::is_whitelisted()} but this one
+     * actually returns the extra types.
+     *
+     * @param string|array $types File types to be checked
+     * @param string|array $whitelist An array or string of whitelisted types
+     * @return array Types not present in the whitelist
+     */
+    public function get_not_whitelisted($types, $whitelist) {
+
+        $whitelistedtypes = $this->expand($whitelist, true, true);
+
+        if (empty($whitelistedtypes) || $whitelistedtypes == ['*']) {
+            return [];
+        }
+
+        $giventypes = $this->normalize_file_types($types);
+
+        if (empty($giventypes)) {
+            return [];
+        }
+
+        return array_diff($giventypes, $whitelistedtypes);
+    }
+
+    /**
+     * Is the given filename of an allowed file type?
+     *
+     * Empty whitelist is interpretted as "any file type is allowed" rather
+     * than "no file can be uploaded".
+     *
+     * @param string $filename the file name
+     * @param string|array $whitelist list of allowed file extensions
+     * @return boolean True if the file type is allowed, false if not
+     */
+    public function is_allowed_file_type($filename, $whitelist) {
+
+        $allowedextensions = $this->expand($whitelist);
+
+        if (empty($allowedextensions) || $allowedextensions == ['*']) {
+            return true;
+        }
+
+        $haystack = strrev(trim(core_text::strtolower($filename)));
+
+        foreach ($allowedextensions as $extension) {
+            if (strpos($haystack, strrev($extension)) === 0) {
+                // The file name ends with the extension.
+                return true;
+            }
+        }
+
+        return false;
+    }
+
+    /**
+     * Returns file types from the list that are not recognized
+     *
+     * @param string|array $types list of user-defined file types
+     * @return array A list of unknown file types.
+     */
+    public function get_unknown_file_types($types) {
+        $unknown = [];
+
+        foreach ($this->normalize_file_types($types) as $type) {
+            if ($this->is_filetype_group($type)) {
+                // The type is a group that exists.
+                continue;
+            } else if ($this->looks_like_mimetype($type)) {
+                // If there's no extension associated with that mimetype, we consider it unknown.
+                if (empty(file_get_typegroup('extension', [$type]))) {
+                    $unknown[$type] = true;
+                }
+            } else {
+                $coretypes = core_filetypes::get_types();
+                $typecleaned = str_replace(".", "", $type);
+                if (empty($coretypes[$typecleaned])) {
+                    // If there's no extension, it doesn't exist.
+                    $unknown[$type] = true;
+                }
+            }
+        }
+
+        return array_keys($unknown);
+    }
+}
diff --git a/lib/form/filetypes.php b/lib/form/filetypes.php
new file mode 100644 (file)
index 0000000..025f128
--- /dev/null
@@ -0,0 +1,203 @@
+<?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/>.
+
+/**
+ * Provides the {@link MoodleQuickForm_filetypes} class.
+ *
+ * @package   core_form
+ * @copyright 2016 Jonathon Fowler <fowlerj@usq.edu.au>
+ * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+use core_form\filetypes_util;
+
+defined('MOODLE_INTERNAL') || die;
+
+global $CFG;
+require_once($CFG->dirroot.'/lib/form/group.php');
+
+/**
+ * File types and type groups selection form element.
+ *
+ * @package   core_form
+ * @category  form
+ * @copyright 2016 Jonathon Fowler <fowlerj@usq.edu.au>
+ * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class MoodleQuickForm_filetypes extends MoodleQuickForm_group {
+
+    /** @var array Allow selection from these file types only. */
+    protected $onlytypes = [];
+
+    /** @var bool Allow selection of 'All file types' (will be stored as '*'). */
+    protected $allowall = true;
+
+    /** @var core_form\filetypes_util instance to use as a helper. */
+    protected $util = null;
+
+    /**
+     * Constructor
+     *
+     * @param string $elementname Element's name
+     * @param string $elementlabel Label(s) for an element
+     * @param array $options element options:
+     *   'onlytypes': Allow selection from these file types only; for example ['onlytypes' => ['web_image']].
+     *   'allowall': Allow to select 'All file types', defaults to true. Does not apply with onlytypes are set.
+     * @param array|string $attributes Either a typical HTML attribute string or an associative array
+     */
+    public function __construct($elementname = null, $elementlabel = null, $options = null, $attributes = null) {
+
+        parent::__construct($elementname, $elementlabel);
+        $this->_type = 'filetypes';
+
+        // Hard-frozen elements do not get the name populated automatically,
+        // which leads to PHP notice. Add it explicitly here.
+        $this->setAttributes(array('name' => $elementname));
+        $this->updateAttributes($attributes);
+
+        if (is_array($options) && $options) {
+            if (array_key_exists('onlytypes', $options) && is_array($options['onlytypes'])) {
+                $this->onlytypes = $options['onlytypes'];
+            }
+            if (!$this->onlytypes && array_key_exists('allowall', $options)) {
+                $this->allowall = (bool)$options['allowall'];
+            }
+        }
+
+        $this->util = new filetypes_util();
+    }
+
+    /**
+     * Assemble the elements of the form control.
+     */
+    public function _createElements() {
+
+        $this->_generateId();
+
+        $this->setElements([
+            $this->createFormElement('text', 'filetypes', '', [
+                'id' => $this->getAttribute('id'),
+            ]),
+
+            $this->createFormElement('static', 'browser', null,
+                '<span data-filetypesbrowser="'.$this->getAttribute('id').'"></span>'),
+
+            $this->createFormElement('static', 'descriptions', null,
+                '<div data-filetypesdescriptions="'.$this->getAttribute('id').'"></div>')
+        ]);
+    }
+
+    /**
+     * Return the selected file types.
+     *
+     * @param array $submitted submitted values
+     * @param bool $assoc if true the retured value is associated array
+     * @return array
+     */
+    public function exportValue(&$submitted, $assoc = false) {
+
+        $value = '';
+        $filetypeselement = null;
+
+        foreach ($this->_elements as $key => $element) {
+            if ($element->_attributes['name'] === 'filetypes') {
+                $filetypeselement = $this->_elements[$key];
+            }
+        }
+
+        if ($filetypeselement) {
+            $formval = $filetypeselement->exportValue($submitted[$this->getName()], false);
+            if ($formval) {
+                $value = $this->util->normalize_file_types($formval);
+                if ($value === ['*'] && !$this->allowall) {
+                    $value = [];
+                }
+                $value = implode(',', $value);
+            }
+        }
+
+        return $this->_prepareValue($value, $assoc);
+    }
+
+    /**
+     * Accepts a renderer (called shortly before the renderer's toHtml() method).
+     *
+     * @param HTML_QuickForm_Renderer $renderer An HTML_QuickForm_Renderer object
+     * @param bool $required Whether a group is required
+     * @param string $error An error message associated with a group
+     */
+    public function accept(&$renderer, $required = false, $error = null) {
+        global $PAGE;
+
+        $PAGE->requires->js_call_amd('core_form/filetypes', 'init', [
+            $this->getAttribute('id'),
+            $this->getLabel(),
+            $this->onlytypes,
+            $this->allowall,
+        ]);
+
+        if ($this->isFrozen()) {
+            // Don't render the choose button if the control is frozen.
+            foreach ($this->_elements as $key => $element) {
+                if ($element->_attributes['name'] === 'browser') {
+                    unset($this->_elements[$key]);
+                }
+            }
+        }
+
+        parent::accept($renderer, $required, $error);
+    }
+
+    /**
+     * Called by HTML_QuickForm whenever form event is made on this element
+     *
+     * @param string $event Name of event
+     * @param mixed $arg event arguments
+     * @param object $caller calling object
+     * @return bool
+     */
+    public function onQuickFormEvent($event, $arg, &$caller) {
+        global $OUTPUT;
+
+        switch ($event) {
+            case 'updateValue':
+                $value = $this->_findValue($caller->_constantValues);
+                if (null === $value) {
+                    if ($caller->isSubmitted()) {
+                        $value = $this->_findValue($caller->_submitValues);
+                    } else {
+                        $value = (string)$this->_findValue($caller->_defaultValues);
+                    }
+                }
+                if (!is_array($value)) {
+                    $value = array('filetypes' => $value);
+                }
+                if ($value['filetypes'] !== null) {
+                    $filetypes = $this->util->normalize_file_types($value['filetypes']);
+                    if ($filetypes === ['*'] && !$this->allowall) {
+                        $filetypes = [];
+                    }
+                    $value['descriptions'] = '<div data-filetypesdescriptions="'.$this->getAttribute('id').'">' .
+                        $OUTPUT->render_from_template('core_form/filetypes-descriptions',
+                            $this->util->describe_file_types($filetypes)).'</div>';
+                }
+                $this->setValue($value);
+                return true;
+        }
+
+        return parent::onQuickFormEvent($event, $arg, $caller);
+    }
+}
diff --git a/lib/form/templates/filetypes-browser.mustache b/lib/form/templates/filetypes-browser.mustache
new file mode 100644 (file)
index 0000000..acfd680
--- /dev/null
@@ -0,0 +1,122 @@
+{{!
+    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/>.
+}}
+{{!
+    @template core_form/filetypes-browser
+
+    The template is used to render the content of the UI widget allowing the
+    user to select individual file types or their groups.
+
+    Classes required for JS:
+    * none
+
+    Data attributes required for JS:
+    * none
+
+    Context variables required for this template:
+    * groups
+        * key
+        * name
+        * selectable
+        * expanded
+        * ext
+        * types
+            * key
+            * name
+            * selected
+            * expanded
+            * ext
+
+    Example context (json):
+    {
+        "groups": [
+            {
+                "key": "web_file",
+                "name": "Web files",
+                "selectable": true,
+                "selected": false,
+                "ext": ".css .html .xhtml .htm .js",
+                "types": [
+                    {
+                        "key": ".css",
+                        "name": "Cascading Style-Sheet",
+                        "selected": true,
+                        "ext": ".css"
+                    },
+                    {
+                        "key": ".htm",
+                        "name": "HTML text",
+                        "selected": false,
+                        "ext": ".htm .xhtml .html"
+                    }
+                ]
+            },
+            {
+                "key": "web_audio",
+                "name": "Web-safe audio files",
+                "selectable": false,
+                "selected": false,
+                "ext": null,
+                "types": [
+                    {
+                        "key": "audio/mp3",
+                        "name": "Audio file (MP3)",
+                        "selected": false,
+                        "ext": ".mp3"
+                    }
+                ]
+            }
+        ]
+    }
+}}
+<div data-filetypesbrowserbody="{{elementid}}" role="tree">
+{{#groups}}
+    <div data-filetypesbrowserkey="{{key}}" role="treeitem" aria-expanded="{{#expanded}}true{{/expanded}}{{^expanded}}false{{/expanded}}">
+        <label>
+            {{#selectable}}
+            <input data-filetypesbrowserkey="{{key}}" type="checkbox" {{#selected}}checked{{/selected}}>
+            <strong data-filetypesname="{{key}}">{{name}}</strong>
+            <small class="muted" data-filetypesextensions="{{key}}">
+                {{ext}}
+            </small>
+            {{/selectable}}
+            {{^selectable}}
+            <strong>{{name}}</strong>
+            {{/selectable}}
+        </label>
+        {{#types.0}}
+        {{! The tree provides its own accessibility controls, these two links are here for mouse users.
+            For that reason, we hide them from assistive technologies. }}
+        <small aria-hidden="true" data-filetypesbrowserfeature="hideifexpanded" class="pull-right float-right"><a href="#">{{#str}}expand{{/str}}</a></small>
+        <small aria-hidden="true" data-filetypesbrowserfeature="hideifcollapsed" class="pull-right float-right"><a href="#">{{#str}}collapse{{/str}}</a></small>
+        {{/types.0}}
+        <ul class="unstyled list-unstyled" role="group">
+            {{#types}}
+            <li data-filetypesbrowserkey="{{key}}" style="margin-left: 2em" role="treeitem">
+                <label>
+                    <input data-filetypesbrowserkey="{{key}}" type="checkbox" {{#selected}}checked{{/selected}}>
+                    <span data-filetypesname="{{key}}">{{name}}</span>
+                    <small class="muted" data-filetypesextensions="{{key}}">
+                        {{ext}}
+                    </small>
+                </label>
+            </li>
+            {{/types}}
+        </ul>
+        <hr style="clear:both">
+    </div>
+{{/groups}}
+</div>
diff --git a/lib/form/templates/filetypes-descriptions.mustache b/lib/form/templates/filetypes-descriptions.mustache
new file mode 100644 (file)
index 0000000..affe8e6
--- /dev/null
@@ -0,0 +1,60 @@
+{{!
+    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/>.
+}}
+{{!
+    @template core_form/filetypes-descriptions
+
+    Template to describe chosen file types.
+
+    Classes required for JS:
+    * none
+
+    Data attributes required for JS:
+    * none
+
+    Context variables required for this template:
+    * hasdescriptions (bool)
+    * descriptions (array)
+        * description (string)
+        * extensions (string)
+
+    Example context (json):
+    {
+        "hasdescriptions": true,
+        "descriptions": [
+            {
+                "description": "Image (JPEG)",
+                "extensions": ".jpeg .jpe .jpg"
+            },
+            {
+                "description": "Image (GIF)",
+                "extensions": ".gif"
+            }
+        ]
+    }
+}}
+<div class="form-filetypes-descriptions">
+{{#hasdescriptions}}
+    <ul class="list-unstyled unstyled">
+        {{#descriptions}}
+        <li>{{description}} <small class="text-muted muted">{{extensions}}</small></li>
+        {{/descriptions}}
+    </ul>
+{{/hasdescriptions}}
+{{^hasdescriptions}}
+    <p>{{#str}}noselection, form{{/str}}</p>
+{{/hasdescriptions}}
+</div>
diff --git a/lib/form/templates/filetypes-trigger.mustache b/lib/form/templates/filetypes-trigger.mustache
new file mode 100644 (file)
index 0000000..7103b89
--- /dev/null
@@ -0,0 +1,39 @@
+{{!
+    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/>.
+}}
+{{!
+    @template core_form/filetypes-trigger
+
+    Renders the button to open the file types browser element.
+
+    This template uses <input> element of the type "button" as that one seems
+    to be well styled by default (especially when compared to alternatives like
+    <button> that are not aligned nicely with the input field.
+
+    Classes required for JS:
+    * none
+
+    Data attributes required for JS:
+    * filetypeswidget - set to "browsertrigger" to mark the actual clickable element
+
+    Context variables required for this template:
+    * none
+
+    Example context (json):
+    {
+    }
+}}
+<input type="button" class="btn btn-secondary" data-filetypeswidget="browsertrigger" value="{{#str}} choose, core {{/str}}" />
diff --git a/lib/form/tests/external_test.php b/lib/form/tests/external_test.php
new file mode 100644 (file)
index 0000000..46643e8
--- /dev/null
@@ -0,0 +1,57 @@
+<?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/>.
+
+/**
+ * Provides the {@link core_form\external_testcase} class.
+ *
+ * @package     core_form
+ * @category    test
+ * @copyright   2017 David Mudrák <david@moodle.com>
+ * @license     http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+namespace core_form;
+
+use advanced_testcase;
+use external_api;
+
+defined('MOODLE_INTERNAL') || die();
+
+global $CFG;
+
+/**
+ * Test cases for the {@link core_form\external} class.
+ *
+ * @copyright 2017 David Mudrak <david@moodle.com>
+ * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class external_testcase extends advanced_testcase {
+
+    /**
+     * Test the core_form_get_filetypes_browser_data external function
+     */
+    public function test_get_filetypes_browser_data() {
+
+        $data = external::get_filetypes_browser_data('', true, '');
+        $data = external_api::clean_returnvalue(external::get_filetypes_browser_data_returns(), $data);
+        $data = json_decode(json_encode($data));
+
+        // The actual data are tested in filetypes_util_test.php, here we just
+        // make sure that the external function wrapper seems to work.
+        $this->assertInternalType('object', $data);
+        $this->assertInternalType('array', $data->groups);
+    }
+}
diff --git a/lib/form/tests/filetypes_util_test.php b/lib/form/tests/filetypes_util_test.php
new file mode 100644 (file)
index 0000000..d5419cd
--- /dev/null
@@ -0,0 +1,464 @@
+<?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/>.
+
+/**
+ * Provides the {@link core_form\filetypes_util_testcase} class.
+ *
+ * @package     core_form
+ * @category    test
+ * @copyright   2017 David Mudrák <david@moodle.com>
+ * @license     http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+namespace core_form;
+
+use advanced_testcase;
+
+defined('MOODLE_INTERNAL') || die();
+
+global $CFG;
+
+/**
+ * Test cases for the {@link core_form\filetypes_util} class.
+ *
+ * @copyright 2017 David Mudrak <david@moodle.com>
+ * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class filetypes_util_testcase extends advanced_testcase {
+
+    /**
+     * Test normalizing list of extensions.
+     */
+    public function test_normalize_file_types() {
+
+        $this->resetAfterTest(true);
+        $util = new filetypes_util();
+
+        $this->assertSame(['.odt'], $util->normalize_file_types('.odt'));
+        $this->assertSame(['.odt'], $util->normalize_file_types('odt'));
+        $this->assertSame(['.odt'], $util->normalize_file_types('.ODT'));
+        $this->assertSame(['.doc', '.jpg', '.mp3'], $util->normalize_file_types('doc, jpg, mp3'));
+        $this->assertSame(['.doc', '.jpg', '.mp3'], $util->normalize_file_types(['.doc', '.jpg', '.mp3']));
+        $this->assertSame(['.doc', '.jpg', '.mp3'], $util->normalize_file_types('doc, *.jpg, mp3'));
+        $this->assertSame(['.doc', '.jpg', '.mp3'], $util->normalize_file_types(['doc ', ' JPG ', '.mp3']));
+        $this->assertSame(['.rtf', '.pdf', '.docx'],
+            $util->normalize_file_types("RTF,.pdf\n...DocX,,,;\rPDF\trtf ...Rtf"));
+        $this->assertSame(['.tgz', '.tar.gz'], $util->normalize_file_types('tgz,TAR.GZ tar.gz .tar.gz tgz TGZ'));
+        $this->assertSame(['.notebook'], $util->normalize_file_types('"Notebook":notebook;NOTEBOOK;,\'NoTeBook\''));
+        $this->assertSame([], $util->normalize_file_types(''));
+        $this->assertSame([], $util->normalize_file_types([]));
+        $this->assertSame(['.0'], $util->normalize_file_types(0));
+        $this->assertSame(['.0'], $util->normalize_file_types('0'));
+        $this->assertSame(['.odt'], $util->normalize_file_types('*.odt'));
+        $this->assertSame([], $util->normalize_file_types('.'));
+        $this->assertSame(['.foo'], $util->normalize_file_types('. foo'));
+        $this->assertSame(['*'], $util->normalize_file_types('*'));
+        $this->assertSame([], $util->normalize_file_types('*~'));
+        $this->assertSame(['.pdf', '.ps'], $util->normalize_file_types('pdf *.ps foo* *bar .r??'));
+        $this->assertSame(['*'], $util->normalize_file_types('pdf *.ps foo* * *bar .r??'));
+    }
+
+    /**
+     * Test MIME type formal recognition.
+     */
+    public function test_looks_like_mimetype() {
+
+        $this->resetAfterTest(true);
+        $util = new filetypes_util();
+
+        $this->assertTrue($util->looks_like_mimetype('type/subtype'));
+        $this->assertTrue($util->looks_like_mimetype('type/x-subtype'));
+        $this->assertTrue($util->looks_like_mimetype('type/x-subtype+xml'));
+        $this->assertTrue($util->looks_like_mimetype('type/vnd.subtype.xml'));
+        $this->assertTrue($util->looks_like_mimetype('type/vnd.subtype+xml'));
+
+        $this->assertFalse($util->looks_like_mimetype('.gif'));
+        $this->assertFalse($util->looks_like_mimetype('audio'));
+        $this->assertFalse($util->looks_like_mimetype('foo/bar/baz'));
+    }
+
+    /**
+     * Test getting/checking group.
+     */
+    public function test_is_filetype_group() {
+
+        $this->resetAfterTest(true);
+        $util = new filetypes_util();
+
+        $audio = $util->is_filetype_group('audio');
+        $this->assertNotFalse($audio);
+        $this->assertInternalType('array', $audio->extensions);
+        $this->assertInternalType('array', $audio->mimetypes);
+
+        $this->assertFalse($util->is_filetype_group('.gif'));
+        $this->assertFalse($util->is_filetype_group('somethingveryunlikelytoeverexist'));
+    }
+
+
+    /**
+     * Test describing list of extensions.
+     */
+    public function test_describe_file_types() {
+
+        $this->resetAfterTest(true);
+        $util = new filetypes_util();
+
+        force_current_language('en');
+
+        // Check that it is able to describe individual file extensions.
+        $desc = $util->describe_file_types('jpg .jpeg *.jpe PNG;.gif,  mudrd8mz');
+        $this->assertTrue($desc->hasdescriptions);
+
+        $desc = $desc->descriptions;
+        $this->assertEquals(4, count($desc));
+
+        $this->assertEquals('File', $desc[0]->description);
+        $this->assertEquals('.mudrd8mz', $desc[0]->extensions);
+
+        $this->assertEquals('Image (JPEG)', $desc[2]->description);
+        $this->assertContains('.jpg', $desc[2]->extensions);
+        $this->assertContains('.jpeg', $desc[2]->extensions);
+        $this->assertContains('.jpe', $desc[2]->extensions);
+
+        // Check that it can describe groups and mimetypes too.
+        $desc = $util->describe_file_types('audio text/plain');
+        $this->assertTrue($desc->hasdescriptions);
+
+        $desc = $desc->descriptions;
+        $this->assertEquals(2, count($desc));
+
+        $this->assertEquals('Audio files', $desc[0]->description);
+        $this->assertContains('.mp3', $desc[0]->extensions);
+        $this->assertContains('.wav', $desc[0]->extensions);
+        $this->assertContains('.ogg', $desc[0]->extensions);
+
+        $this->assertEquals('Text file', $desc[1]->description);
+        $this->assertContains('.txt', $desc[1]->extensions);
+
+        // Empty.
+        $desc = $util->describe_file_types('');
+        $this->assertFalse($desc->hasdescriptions);
+        $this->assertEmpty($desc->descriptions);
+
+        // Any.
+        $desc = $util->describe_file_types('*');
+        $this->assertTrue($desc->hasdescriptions);
+        $this->assertNotEmpty($desc->descriptions[0]->description);
+        $this->assertEmpty($desc->descriptions[0]->extensions);
+
+        // Unknown mimetype.
+        $desc = $util->describe_file_types('application/x-something-really-unlikely-ever-exist');
+        $this->assertTrue($desc->hasdescriptions);
+        $this->assertEquals('application/x-something-really-unlikely-ever-exist', $desc->descriptions[0]->description);
+        $this->assertEmpty($desc->descriptions[0]->extensions);
+    }
+
+    /**
+     * Test expanding mime types into extensions.
+     */
+    public function test_expand() {
+
+        $this->resetAfterTest(true);
+        $util = new filetypes_util();
+
+        $this->assertSame([], $util->expand(''));
+
+        $expanded = $util->expand('document .cdr text/plain');
+        $this->assertNotContains('document', $expanded);
+        $this->assertNotContains('text/plain', $expanded);
+        $this->assertContains('.doc', $expanded);
+        $this->assertContains('.odt', $expanded);
+        $this->assertContains('.txt', $expanded);
+        $this->assertContains('.cdr', $expanded);
+
+        $expanded = $util->expand('document .cdr text/plain', true, false);
+        $this->assertContains('document', $expanded);
+        $this->assertNotContains('text/plain', $expanded);
+        $this->assertContains('.doc', $expanded);
+        $this->assertContains('.odt', $expanded);
+        $this->assertContains('.txt', $expanded);
+        $this->assertContains('.cdr', $expanded);
+
+        $expanded = $util->expand('document .cdr text/plain', false, true);
+        $this->assertNotContains('document', $expanded);
+        $this->assertContains('text/plain', $expanded);
+        $this->assertContains('.doc', $expanded);
+        $this->assertContains('.odt', $expanded);
+        $this->assertContains('.txt', $expanded);
+        $this->assertContains('.cdr', $expanded);
+
+        $this->assertSame([], $util->expand('foo/bar', true, false));
+        $this->assertSame(['foo/bar'], $util->expand('foo/bar', true, true));
+    }
+
+    /**
+     * Test checking that a type is among others.
+     */
+    public function test_is_whitelisted() {
+
+        $this->resetAfterTest(true);
+        $util = new filetypes_util();
+
+        // These should be intuitively true.
+        $this->assertTrue($util->is_whitelisted('txt', 'text/plain'));
+        $this->assertTrue($util->is_whitelisted('txt', 'doc txt rtf'));
+        $this->assertTrue($util->is_whitelisted('.txt', '.doc;.txt;.rtf'));
+        $this->assertTrue($util->is_whitelisted('audio', 'text/plain audio video'));
+        $this->assertTrue($util->is_whitelisted('text/plain', 'text/plain audio video'));
+        $this->assertTrue($util->is_whitelisted('jpg jpe jpeg', 'image/jpeg'));
+        $this->assertTrue($util->is_whitelisted(['jpg', 'jpe', '.png'], 'image'));
+
+        // These should be intuitively false.
+        $this->assertFalse($util->is_whitelisted('.gif', 'text/plain'));
+
+        // Not all text/plain formats are in the document group.
+        $this->assertFalse($util->is_whitelisted('text/plain', 'document'));
+
+        // Not all documents (and also the group itself) is not a plain text.
+        $this->assertFalse($util->is_whitelisted('document', 'text/plain'));
+
+        // This may look wrong at the first sight as you might expect that the
+        // mimetype should simply map to an extension ...
+        $this->assertFalse($util->is_whitelisted('image/jpeg', '.jpg'));
+
+        // But it is principally same situation as this (there is no 1:1 mapping).
+        $this->assertFalse($util->is_whitelisted('.c', '.txt'));
+        $this->assertTrue($util->is_whitelisted('.txt .c', 'text/plain'));
+        $this->assertFalse($util->is_whitelisted('text/plain', '.c'));
+
+        // Any type is included if the filter is empty.
+        $this->assertTrue($util->is_whitelisted('txt', ''));
+        $this->assertTrue($util->is_whitelisted('txt', '*'));
+
+        // Empty value is part of any whitelist.
+        $this->assertTrue($util->is_whitelisted('', '.txt'));
+    }
+
+    /**
+     * Test getting types not present in a whitelist.
+     */
+    public function test_get_not_whitelisted() {
+
+        $this->resetAfterTest(true);
+        $util = new filetypes_util();
+
+        $this->assertEmpty($util->get_not_whitelisted('txt', 'text/plain'));
+        $this->assertEmpty($util->get_not_whitelisted('txt', '.doc .txt .rtf'));
+        $this->assertEmpty($util->get_not_whitelisted('txt', 'text/plain'));
+        $this->assertEmpty($util->get_not_whitelisted(['jpg', 'jpe', 'jpeg'], 'image/jpeg'));
+        $this->assertEmpty($util->get_not_whitelisted('', 'foo/bar'));
+        $this->assertEmpty($util->get_not_whitelisted('.foobar', ''));
+        $this->assertEmpty($util->get_not_whitelisted('.foobar', '*'));
+
+        // Returned list is normalized so extensions have the dot added.
+        $this->assertContains('.exe', $util->get_not_whitelisted('exe', '.c .h'));
+
+        // If this looks wrong to you, see {@link test_is_whitelisted()} for more details on this behaviour.
+        $this->assertContains('image/jpeg', $util->get_not_whitelisted('image/jpeg', '.jpg .jpeg'));
+    }
+
+    /**
+     * Test populating the tree for the browser.
+     */
+    public function test_data_for_browser() {
+
+        $this->resetAfterTest(true);
+        $util = new filetypes_util();
+
+        $data = $util->data_for_browser();
+        $this->assertContainsOnly('object', $data);
+        foreach ($data as $group) {
+            $this->assertObjectHasAttribute('key', $group);
+            $this->assertObjectHasAttribute('types', $group);
+            if ($group->key !== '') {
+                $this->assertTrue($group->selectable);
+            }
+        }
+
+        // All these three files are in both "image" and also "web_image"
+        // groups. We display both groups.
+        $data = $util->data_for_browser('jpg png gif', true, '.gif');
+        $this->assertEquals(2, count($data));
+        $this->assertTrue($data[0]->key !== $data[1]->key);
+        foreach ($data as $group) {
+            $this->assertTrue(($group->key === 'image' || $group->key === 'web_image'));
+            $this->assertEquals(3, count($group->types));
+            $this->assertFalse($group->selectable);
+            foreach ($group->types as $ext) {
+                if ($ext->key === '.gif') {
+                    $this->assertTrue($ext->selected);
+                } else {
+                    $this->assertFalse($ext->selected);
+                }
+            }
+        }
+
+        // There is a group web_image which is a subset of the group image. The
+        // file extensions that fall into both groups will be displayed twice.
+        $data = $util->data_for_browser('web_image');
+        foreach ($data as $group) {
+            $this->assertTrue(($group->key === 'image' || $group->key === 'web_image'));
+        }
+
+        // Check that "All file types" are displayed first.
+        $data = $util->data_for_browser();
+        $group = array_shift($data);
+        $this->assertEquals('*', $group->key);
+
+        // Check that "All file types" is not displayed if should not.
+        $data = $util->data_for_browser(null, false);
+        $group = array_shift($data);
+        $this->assertNotEquals('*', $group->key);
+
+        // Groups with an extension selected start expanded. The "Other files"
+        // starts expanded. The rest start collapsed.
+        $data = $util->data_for_browser(null, false, '.png');
+        foreach ($data as $group) {
+            if ($group->key === 'document') {
+                $this->assertfalse($group->expanded);
+            } else if ($group->key === '') {
+                $this->assertTrue($group->expanded);
+            }
+            foreach ($group->types as $ext) {
+                foreach ($group->types as $ext) {
+                    if ($ext->key === '.png') {
+                        $this->assertTrue($ext->selected);
+                        $this->assertTrue($group->expanded);
+                    }
+                }
+            }
+        }
+    }
+
+    /**
+     * Data provider for testing test_is_allowed_file_type.
+     *
+     * @return array
+     */
+    public function is_allowed_file_type_provider() {
+        return [
+            'Filetype not in extension whitelist' => [
+                'filename' => 'test.xml',
+                'whitelist' => '.png .jpg',
+                'expected' => false
+            ],
+            'Filetype not in mimetype whitelist' => [
+                'filename' => 'test.xml',
+                'whitelist' => 'image/png',
+                'expected' => false
+            ],
+            'Filetype not in group whitelist' => [
+                'filename' => 'test.xml',
+                'whitelist' => 'web_file',
+                'expected' => false
+            ],
+            'Filetype in whitelist as extension' => [
+                'filename' => 'test.xml',
+                'whitelist' => 'xml',
+                'expected' => true
+            ],
+            'Empty whitelist should allow all' => [
+                'filename' => 'test.xml',
+                'whitelist' => '',
+                'expected' => true
+            ],
+            'Filetype in whitelist but later on' => [
+                'filename' => 'test.xml',
+                'whitelist' => 'gif;jpeg,image/png xml xlsx',
+                'expected' => true
+            ],
+            'Filetype in whitelist as mimetype' => [
+                'filename' => 'test.xml',
+                'whitelist' => 'image/png application/xml',
+                'expected' => true
+            ],
+            'Filetype in whitelist as group' => [
+                'filename' => 'test.html',
+                'whitelist' => 'video,web_file',
+                'expected' => true
+            ],
+        ];
+    }
+
+    /**
+     * Test is_allowed_file_type().
+     * @dataProvider is_allowed_file_type_provider
+     * @param string $filename The filename to check
+     * @param string $whitelist The space , or ; separated list of types supported
+     * @param boolean $expected The expected result. True if the file is allowed, false if not.
+     */
+    public function test_is_allowed_file_type($filename, $whitelist, $expected) {
+        $util = new filetypes_util();
+        $this->assertSame($expected, $util->is_allowed_file_type($filename, $whitelist));
+    }
+
+    /**
+     * Data provider for testing test_get_unknown_file_types.
+     *
+     * @return array
+     */
+    public function get_unknown_file_types_provider() {
+        return [
+            'Unknown extension' => [
+                'filetypes' => '.rat',
+                'expected' => ['.rat']
+            ],
+            'Multiple unknown extensions' => [
+                'filetypes' => '.ricefield .rat',
+                'expected' => ['.ricefield', '.rat']
+            ],
+            'Existant extension' => [
+                'filetypes' => '.xml',
+                'expected' => []
+            ],
+            'Existant group' => [
+                'filetypes' => 'web_file',
+                'expected' => []
+            ],
+            'Nonexistant mimetypes' => [
+                'filetypes' => 'ricefield/rat',
+                'expected' => ['ricefield/rat']
+            ],
+            'Existant mimetype' => [
+                'filetypes' => 'application/xml',
+                'expected' => []
+            ],
+            'Multiple unknown mimetypes' => [
+                'filetypes' => 'ricefield/rat cam/ball',
+                'expected' => ['ricefield/rat', 'cam/ball']
+            ],
+            'Strange characters in unknown extension/group' => [
+                'filetypes' => '©ç√√ß∂å√©åß©√',
+                'expected' => ['.©ç√√ß∂å√©åß©√']
+            ],
+            'Some existant some not' => [
+                'filetypes' => '.txt application/xml web_file ©ç√√ß∂å√©åß©√ .png ricefield/rat document',
+                'expected' => ['.©ç√√ß∂å√©åß©√', 'ricefield/rat']
+            ],
+        ];
+    }
+
+    /**
+     * Test get_unknown_file_types().
+     * @dataProvider get_unknown_file_types_provider
+     * @param string $filetypes The filetypes to check
+     * @param array $expected The expected result. The list of non existant file types.
+     */
+    public function test_get_unknown_file_types($filetypes, $expected) {
+        $util = new filetypes_util();
+        $this->assertSame($expected, $util->get_unknown_file_types($filetypes));
+    }
+}
index e2c8b8e..cce38da 100644 (file)
@@ -3105,6 +3105,7 @@ MoodleQuickForm::registerElementType('duration', "$CFG->libdir/form/duration.php
 MoodleQuickForm::registerElementType('editor', "$CFG->libdir/form/editor.php", 'MoodleQuickForm_editor');
 MoodleQuickForm::registerElementType('filemanager', "$CFG->libdir/form/filemanager.php", 'MoodleQuickForm_filemanager');
 MoodleQuickForm::registerElementType('filepicker', "$CFG->libdir/form/filepicker.php", 'MoodleQuickForm_filepicker');
+MoodleQuickForm::registerElementType('filetypes', "$CFG->libdir/form/filetypes.php", 'MoodleQuickForm_filetypes');
 MoodleQuickForm::registerElementType('grading', "$CFG->libdir/form/grading.php", 'MoodleQuickForm_grading');
 MoodleQuickForm::registerElementType('group', "$CFG->libdir/form/group.php", 'MoodleQuickForm_group');
 MoodleQuickForm::registerElementType('header', "$CFG->libdir/form/header.php", 'MoodleQuickForm_header');
index 7406646..0aae68d 100644 (file)
@@ -4294,7 +4294,7 @@ EOD;
         $context->cookieshelpiconformatted = $this->help_icon('cookiesenabled');
         $context->errorformatted = $this->error_text($context->error);
 
-        return $this->render_from_template('core/login', $context);
+        return $this->render_from_template('core/loginform', $context);
     }
 
     /**
index 409b796..65ea2f0 100644 (file)
@@ -265,7 +265,7 @@ class Parser {
                        if (preg_match('/[0-9a-fA-F]/Su', $this->peek()) === 0) {
                                return $this->consume(1);
                        }
-                       $sUnicode = $this->consumeExpression('/^[0-9a-fA-F]{1,6}/u');
+                       $sUnicode = $this->consumeExpression('/^[0-9a-fA-F]{1,6}/u', 6);
                        if ($this->strlen($sUnicode) < 6) {
                                //Consume whitespace after incomplete unicode escape
                                if (preg_match('/\\s/isSu', $this->peek())) {
@@ -565,9 +565,10 @@ class Parser {
                }
        }
 
-       private function consumeExpression($mExpression) {
+       private function consumeExpression($mExpression, $iMaxLength = null) {
                $aMatches = null;
-               if (preg_match($mExpression, $this->inputLeft(), $aMatches, PREG_OFFSET_CAPTURE) === 1) {
+               $sInput = $iMaxLength !== null ? $this->peek($iMaxLength) : $this->inputLeft();
+               if (preg_match($mExpression, $sInput, $aMatches, PREG_OFFSET_CAPTURE) === 1) {
                        return $this->consume($aMatches[0][0]);
                }
                throw new UnexpectedTokenException($mExpression, $this->peek(5), 'expression', $this->iLineNo);
index 16b02e2..f63dd81 100644 (file)
@@ -1,7 +1,7 @@
 PHP CSS Parser
 --------------
 
-Import git ref: 50a802f562e71236140e2a8903b097c28d6101de
+Import git ref: c3b01ef0a85824e86fd86a74a8154d8d5c34b0ff
                 (master)
 
 Downloaded from: https://github.com/sabberworm/PHP-CSS-Parser
similarity index 99%
rename from lib/templates/login.mustache
rename to lib/templates/loginform.mustache
index a0545c3..1d65ea1 100644 (file)
@@ -15,7 +15,7 @@
     along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
 }}
 {{!
-    @template core/login
+    @template core/loginform
 
     Moodle template for the login page.
 
index 3e5d416..09c2839 100644 (file)
@@ -3,6 +3,10 @@ information provided here is intended especially for developers.
 
 === 3.4 ===
 
+* Added new moodleform element 'filetypes' and new admin setting widget 'admin_setting_filetypes'. These new widgets
+  allow users to define a list of file types; either by typing them manually or selecting them from a list. The widgets
+  directly support the syntax used to feed the 'accepted_types' option of the filemanager and filepicker elements. File
+  types can be specified as extensions (.jpg or just jpg), mime types (text/plain) or groups (image).
 * Removed accesslib private functions: load_course_context(), load_role_access_by_context(), dedupe_user_access() (MDL-49398).
 * Internal "accessdata" structure format has changed to improve ability to perform role definition caching (MDL-49398).
 * Role definitions are no longer cached in user session (MDL-49398).
index fc81446..cf4f53b 100644 (file)
@@ -137,6 +137,54 @@ class plugin_misplaced_exception extends moodle_exception {
     }
 }
 
+/**
+ * Static class monitors performance of upgrade steps.
+ */
+class core_upgrade_time {
+    /** @var float Time at start of current upgrade (plugin/system) */
+    protected static $before;
+    /** @var float Time at end of last savepoint */
+    protected static $lastsavepoint;
+
+    /**
+     * Records current time at the start of the current upgrade item, e.g. plugin.
+     */
+    public static function record_start() {
+        self::$before = microtime(true);
+        self::$lastsavepoint = self::$before;
+    }
+
+    /**
+     * Records current time at the end of a given numbered step.
+     *
+     * @param float $version Version number (may have decimals, or not)
+     */
+    public static function record_savepoint($version) {
+        global $CFG, $OUTPUT;
+
+        // In developer debug mode we show a notification after each individual save point.
+        if ($CFG->debugdeveloper) {
+            $time = microtime(true);
+
+            $notification = new \core\output\notification($version . ': ' .
+                    get_string('successduration', '', format_float($time - self::$lastsavepoint, 2)),
+                    \core\output\notification::NOTIFY_SUCCESS);
+            $notification->set_show_closebutton(false);
+            echo $OUTPUT->render($notification);
+            self::$lastsavepoint = $time;
+        }
+    }
+
+    /**
+     * Gets the time since the record_start function was called, rounded to 2 digits.
+     *
+     * @return float Elapsed time
+     */
+    public static function get_elapsed() {
+        return microtime(true) - self::$before;
+    }
+}
+
 /**
  * Sets maximum expected time needed for upgrade task.
  * Please always make sure that upgrade will not run longer!
@@ -224,6 +272,8 @@ function upgrade_main_savepoint($result, $version, $allowabort=true) {
     // reset upgrade timeout to default
     upgrade_set_timeout();
 
+    core_upgrade_time::record_savepoint($version);
+
     // this is a safe place to stop upgrades if user aborts page loading
     if ($allowabort and connection_aborted()) {
         die;
@@ -268,6 +318,8 @@ function upgrade_mod_savepoint($result, $version, $modname, $allowabort=true) {
     // reset upgrade timeout to default
     upgrade_set_timeout();
 
+    core_upgrade_time::record_savepoint($version);
+
     // this is a safe place to stop upgrades if user aborts page loading
     if ($allowabort and connection_aborted()) {
         die;
@@ -312,6 +364,8 @@ function upgrade_block_savepoint($result, $version, $blockname, $allowabort=true
     // reset upgrade timeout to default
     upgrade_set_timeout();
 
+    core_upgrade_time::record_savepoint($version);
+
     // this is a safe place to stop upgrades if user aborts page loading
     if ($allowabort and connection_aborted()) {
         die;
@@ -352,6 +406,8 @@ function upgrade_plugin_savepoint($result, $version, $type, $plugin, $allowabort
     // Reset upgrade timeout to default
     upgrade_set_timeout();
 
+    core_upgrade_time::record_savepoint($version);
+
     // This is a safe place to stop upgrades if user aborts page loading
     if ($allowabort and connection_aborted()) {
         die;
@@ -1501,6 +1557,7 @@ function print_upgrade_part_start($plugin, $installation, $verbose) {
             echo $OUTPUT->heading($plugin);
         }
     }
+    core_upgrade_time::record_start();
     if ($installation) {
         if (empty($plugin) or $plugin == 'moodle') {
             // no need to log - log table not yet there ;-)
@@ -1538,7 +1595,10 @@ function print_upgrade_part_end($plugin, $installation, $verbose) {
         }
     }
     if ($verbose) {
-        $notification = new \core\output\notification(get_string('success'), \core\output\notification::NOTIFY_SUCCESS);
+        $duration = core_upgrade_time::get_elapsed();
+        $notification = new \core\output\notification(
+                get_string('successduration', '', format_float($duration, 2)),
+                \core\output\notification::NOTIFY_SUCCESS);
         $notification->set_show_closebutton(false);
         echo $OUTPUT->render($notification);
         print_upgrade_separator();
index 24af320..fd5ca49 100644 (file)
@@ -183,7 +183,7 @@ if ($mform->is_cancelled()) {
         unset($fromform->id);
         $fromform->id = $DB->insert_record('assign_overrides', $fromform);
         if ($groupmode) {
-            $fromform->sortorder = $fromform->id;
+            $fromform->sortorder = 1;
 
             $overridecountgroup = $DB->count_records('assign_overrides',
                 array('userid' => null, 'assignid' => $assigninstance->id));
@@ -196,7 +196,7 @@ if ($mform->is_cancelled()) {
             }
 
             $DB->update_record('assign_overrides', $fromform);
-
+            reorder_group_overrides($assigninstance->id);
         }
 
         // Determine which override created event to fire.
index 252b247..d9da1db 100644 (file)
@@ -4,7 +4,7 @@ Feature: Set entries required as a completion condition for a data item
   As a teacher
   I need to set entries required to mark the database activity as completed
 
-Scenario: Two entries required to complete the activity
+  Scenario: Two entries required to complete the activity
     Given the following "users" exist:
       | username | firstname | lastname | email |
       | student1 | Student | 1 | student1@example.com |
index 984123e..7d5c9be 100644 (file)
@@ -167,4 +167,3 @@ Feature: Edit quiz page - remove multiple questions
 
     When I click on "Deselect all" "link"
     Then the field "selectquestion-3" matches value "0"
-
index 4e5835e..e48bc63 100644 (file)
@@ -465,7 +465,7 @@ class core_renderer extends \core_renderer {
         $context->logourl = $url;
         $context->sitename = format_string($SITE->fullname, true, ['context' => context_course::instance(SITEID), "escape" => false]);
 
-        return $this->render_from_template('core/login', $context);
+        return $this->render_from_template('core/loginform', $context);
     }
 
     /**
index b77facc..e967e5f 100644 (file)
@@ -1,10 +1,10 @@
 /* Anchor link offset fix. This makes hash links scroll 60px down to account for the fixed header. */
 $fixed-header-y: $navbar-height;
 
-$drawer-width: 285px;
-$drawer-padding-x: 20px;
-$drawer-padding-y: 20px;
-$drawer-offscreen-gutter: 20px;
+$drawer-width: 285px !default;
+$drawer-padding-x: 20px !default;
+$drawer-padding-y: 20px !default;
+$drawer-offscreen-gutter: 20px !default;
 
 :target {
     padding-top: ($fixed-header-y + 30px) !important; /* stylelint-disable declaration-no-important */
index 899c8b8..e6903f2 100644 (file)
@@ -357,3 +357,12 @@ textarea[data-auto-rows] {
     background-position: center right ($input-height / 4);
     background-size: ($input-height / 2) ($input-height / 2);
 }
+
+// Styles for the JS file types browser provided by the "filetypes" element.
+[data-filetypesbrowserbody] {
+    [aria-expanded="false"] > [role="group"],
+    [aria-expanded="false"] [data-filetypesbrowserfeature="hideifcollapsed"],
+    [aria-expanded="true"] [data-filetypesbrowserfeature="hideifexpanded"] {
+        display: none;
+    }
+}
similarity index 99%
rename from theme/boost/templates/core/login.mustache
rename to theme/boost/templates/core/loginform.mustache
index 90fb24c..65d2139 100644 (file)
@@ -15,7 +15,7 @@
     along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
 }}
 {{!
-    @template core/login
+    @template core/loginform
 
     Moodle template for the login page.
 
diff --git a/theme/boost/templates/core_form/element-filetypes.mustache b/theme/boost/templates/core_form/element-filetypes.mustache
new file mode 100644 (file)
index 0000000..9a4e5cb
--- /dev/null
@@ -0,0 +1 @@
+{{> core_form/element-group }}
index 64a7c59..6906b66 100644 (file)
@@ -49,6 +49,10 @@ class behat_theme_boost_behat_course extends behat_course {
 
         // Find the menu.
         $menunode = $activitynode->find('css', 'a[data-toggle=dropdown]');
+        if (!$menunode) {
+            throw new ExpectationException(sprintf('Could not find actions menu for the activity "%s"', $activityname),
+                    $this->getSession());
+        }
         $expanded = $menunode->getAttribute('aria-expanded');
         if ($expanded == 'true') {
             return;
@@ -71,6 +75,10 @@ class behat_theme_boost_behat_course extends behat_course {
         $activitynode = $this->get_activity_node($activityname);
         // Find the menu.
         $menunode = $activitynode->find('css', 'a[data-toggle=dropdown]');
+        if (!$menunode) {
+            throw new ExpectationException(sprintf('Could not find actions menu for the activity "%s"', $activityname),
+                    $this->getSession());
+        }
         $expanded = $menunode->getAttribute('aria-expanded');
         if ($expanded != 'true') {
             return;
@@ -90,6 +98,10 @@ class behat_theme_boost_behat_course extends behat_course {
         $activitynode = $this->get_activity_node($activityname);
         // Find the menu.
         $menunode = $activitynode->find('css', 'a[data-toggle=dropdown]');
+        if (!$menunode) {
+            throw new ExpectationException(sprintf('Could not find actions menu for the activity "%s"', $activityname),
+                    $this->getSession());
+        }
         $expanded = $menunode->getAttribute('aria-expanded');
         if ($expanded != 'true') {
             throw new ExpectationException(sprintf("The action menu for '%s' is not open", $activityname), $this->getSession());
index 05a9788..008de8d 100644 (file)
@@ -507,3 +507,12 @@ div[data-passwordunmask="wrapper"] {
     line-height: 30px;
     margin-bottom: 10px;
 }
+
+// Styles for the JS file types browser provided by the "filetypes" element.
+[data-filetypesbrowserbody] {
+    [aria-expanded="false"] > [role="group"],
+    [aria-expanded="false"] [data-filetypesbrowserfeature="hideifcollapsed"],
+    [aria-expanded="true"] [data-filetypesbrowserfeature="hideifexpanded"] {
+        display: none;
+    }
+}
index d8496eb..fa74dbd 100644 (file)
@@ -16969,6 +16969,11 @@ div[data-passwordunmask="wrapper"] {
   line-height: 30px;
   margin-bottom: 10px;
 }
+[data-filetypesbrowserbody] [aria-expanded="false"] > [role="group"],
+[data-filetypesbrowserbody] [aria-expanded="false"] [data-filetypesbrowserfeature="hideifcollapsed"],
+[data-filetypesbrowserbody] [aria-expanded="true"] [data-filetypesbrowserfeature="hideifexpanded"] {
+  display: none;
+}
 body.modal-open {
   overflow: hidden;
 }
index 06a1e92..af4ff66 100644 (file)
@@ -7,6 +7,10 @@ information provided here is intended especially for theme designer.
   setup for this module have been moved from core standard_head_html to the bootstrapbase
   renderer. If your theme needs this javascript you will need to ensure the bootstrap renderer
   is called, or require the JS yourself
+* There was a mustache template login.mustache in /lib/templates/ rendering the login form
+  and a template with the same name in /theme/boost/templates/ rendering the pagelayout "login".
+  To prevent misunderstanding when overriding one of these templates in a Boost child theme,
+  the first one was renamed to loginform.mustache - see MDL-58970.
 
 === 3.2 ===
 
index 2144f0e..78c9275 100644 (file)
@@ -29,7 +29,7 @@
 
 defined('MOODLE_INTERNAL') || die();
 
-$version  = 2017060100.01;              // YYYYMMDD      = weekly release date of this DEV branch.
+$version  = 2017060600.00;              // YYYYMMDD      = weekly release date of this DEV branch.
                                         //         RR    = release increments - 00 in DEV branches.
                                         //           .XX = incremental changes.