Merge branch 'MDL-55074-master' of git://github.com/damyon/moodle
authorDavid Monllao <davidm@moodle.com>
Mon, 24 Oct 2016 04:33:51 +0000 (12:33 +0800)
committerDavid Monllao <davidm@moodle.com>
Mon, 24 Oct 2016 04:33:51 +0000 (12:33 +0800)
60 files changed:
admin/auth_config.php
admin/templates/setting_configpasswordunmask.mustache
admin/templates/settings.mustache
admin/templates/settings_search_results.mustache
admin/upgradesettings.php
course/externallib.php
course/tests/externallib_test.php
enrol/lti/tests/tool_provider_test.php
files/renderer.php
lang/en/deprecated.txt
lang/en/form.php
lib/adminlib.php
lib/amd/build/templates.min.js
lib/amd/src/templates.js
lib/behat/behat_field_manager.php
lib/behat/classes/partial_named_selector.php
lib/behat/form_field/behat_form_passwordunmask.php [new file with mode: 0644]
lib/classes/session/manager.php
lib/deprecatedlib.php
lib/form/amd/build/passwordunmask.min.js [new file with mode: 0644]
lib/form/amd/src/passwordunmask.js [new file with mode: 0644]
lib/form/passwordunmask.php
lib/form/templates/element-passwordunmask-fill.mustache [new file with mode: 0644]
lib/form/templates/element-passwordunmask.mustache [new file with mode: 0644]
lib/form/templates/element-template.mustache [new file with mode: 0644]
lib/form/yui/build/moodle-form-passwordunmask/moodle-form-passwordunmask-debug.js
lib/form/yui/build/moodle-form-passwordunmask/moodle-form-passwordunmask-min.js
lib/form/yui/build/moodle-form-passwordunmask/moodle-form-passwordunmask.js
lib/form/yui/src/passwordunmask/js/passwordunmask.js
lib/form/yui/src/passwordunmask/meta/passwordunmask.json
lib/formslib.php
lib/templates/prevent_form_autofill_password.mustache [deleted file]
lib/upgrade.txt
lib/weblib.php
message/amd/build/message_area_contacts.min.js
message/amd/build/message_area_profile.min.js
message/amd/src/message_area_contacts.js
message/amd/src/message_area_profile.js
message/classes/api.php
message/classes/helper.php
message/output/popup/amd/build/notification_area_control_area.min.js
message/output/popup/amd/src/notification_area_control_area.js
message/tests/api_test.php
message/tests/events_test.php
message/tests/messagelib_test.php
pix/t/passwordunmask-edit.png [new file with mode: 0644]
pix/t/passwordunmask-edit.svg [new file with mode: 0644]
pix/t/passwordunmask-reveal.png [new file with mode: 0644]
pix/t/passwordunmask-reveal.svg [new file with mode: 0644]
repository/filepicker.php
theme/boost/classes/output/core/files_renderer.php
theme/boost/scss/moodle/message.scss
theme/boost/templates/core/filemanager_loginform.mustache
theme/boost/templates/core_admin/setting_configpasswordunmask.mustache
theme/boost/templates/core_admin/settings.mustache
theme/boost/templates/core_admin/settings_search_results.mustache
theme/boost/templates/core_form/element-passwordunmask.mustache
theme/bootstrapbase/less/moodle/forms.less
theme/bootstrapbase/less/moodle/message.less
theme/bootstrapbase/style/moodle.css

index 1fe945b..b307cd7 100644 (file)
@@ -64,8 +64,6 @@ echo "<form id=\"authmenu\" method=\"post\" action=\"auth_config.php\">\n";
 echo "<div>\n";
 echo "<input type=\"hidden\" name=\"sesskey\" value=\"".sesskey()."\" />\n";
 echo "<input type=\"hidden\" name=\"auth\" value=\"".$auth."\" />\n";
-// HACK to prevent browsers from automatically inserting the user's password into the wrong fields.
-echo prevent_form_autofill_password();
 
 // auth plugin description
 echo $OUTPUT->box_start();
index b9da812..bf00ea7 100644 (file)
     }
 }}
 <div class="form-password">
-    <input type="password" name="{{name}}" size="{{size}}" id="{{id}}" value="{{value}}">
-    <div class="unmask" id="{{id}}unmaskdiv"></div>
+    <span data-passwordunmask="wrapper" data-passwordunmaskid="{{ id }}">
+        <noscript>
+            <!-- Backwards compatability for Behat -->
+            <input  type="password"
+                    name="{{ name }}"
+                    id="{{ id }}"
+                    value="{{ value }}"
+                    size="{{ size }}"
+                    >
+        </noscript>
+        <span class="visibleifjs">
+            <span data-passwordunmask="editor">
+                <!-- The input in the noscript will be moved here as part of the page load -->
+            </span>
+            <a href="#" data-passwordunmask="edit" title="{{ edithint }}">
+                <span data-passwordunmask="displayvalue">{{> core_form/element-passwordunmask-fill }}</span>
+                {{# pix }} t/passwordunmask-edit, core, {{# str }} passwordunmaskedithint, form {{/ str }}{{/ pix }}
+            </a>
+            <a href="#" data-passwordunmask="unmask" title="{{ unmaskhint }}">
+                {{# pix }} t/passwordunmask-reveal, core, {{# str }} passwordunmaskrevealhint, form {{/ str }}{{/ pix }}
+            </a>
+            <span data-passwordunmask="instructions" class="form-text text-muted" style="display: none;">
+                {{# str }} passwordunmaskinstructions, form {{/ str }}
+            </span>
+        </span>
+    </span>
 </div>
 {{#js}}
-(function() {
-    var id = '{{id}}';
-    var unmaskid = id + 'unmask';
-    var unmaskdivid = id + 'unmaskdiv';
-    var unmaskstr = {{#quote}}{{#str}}unmaskpassword, form{{/str}}{{/quote}};
-    var is_ie = (navigator.userAgent.toLowerCase().indexOf("msie") != -1);
-
-    document.getElementById(id).setAttribute("autocomplete", "off");
-
-    var unmaskdiv = document.getElementById(unmaskdivid);
-
-    var unmaskchb = document.createElement("input");
-    unmaskchb.setAttribute("type", "checkbox");
-    unmaskchb.setAttribute("id", unmaskid);
-    unmaskchb.onchange = function() {unmaskPassword(id);};
-    unmaskdiv.appendChild(unmaskchb);
-
-    var unmasklbl = document.createElement("label");
-    unmasklbl.innerHTML = unmaskstr;
-    if (is_ie) {
-      unmasklbl.setAttribute("htmlFor", unmaskid);
-    } else {
-      unmasklbl.setAttribute("for", unmaskid);
-    }
-    unmaskdiv.appendChild(unmasklbl);
-
-    if (is_ie) {
-      // Ugly hack to work around the famous onchange IE bug.
-      unmaskchb.onclick = function() {this.blur();};
-      unmaskdiv.onclick = function() {this.blur();};
-    }
-})()
+require(['core_form/passwordunmask'], function(PasswordUnmask) {
+    new PasswordUnmask("{{ id }}");
+});
 {{/js}}
index aba6601..4f351b8 100644 (file)
@@ -43,7 +43,6 @@
         {{/params}}
         <input type="hidden" name="sesskey" value="{{sesskey}}">
         <input type="hidden" name="return" value="{{return}}">
-        {{>core/prevent_form_autofill_password}}
         {{#title}}
             <h2>{{title}}</h2>
         {{/title}}
index dd392f7..c6f7bbb 100644 (file)
@@ -37,7 +37,6 @@
 <form action="{{actionurl}}" method="post" id="adminsettings">
     <div>
         <input type="hidden" name="sesskey" value="{{sesskey}}">
-        {{>core/prevent_form_autofill_password}}
     </div>
     <fieldset>
         <div class="clearer"></div>
index f4aa617..38a8f06 100644 (file)
@@ -63,8 +63,6 @@ echo '<form action="upgradesettings.php" method="post" id="adminsettings">';
 echo '<div>';
 echo '<input type="hidden" name="sesskey" value="'.sesskey().'" />';
 echo '<input type="hidden" name="return" value="'.$return.'" />';
-// HACK to prevent browsers from automatically inserting the user's password into the wrong fields.
-echo prevent_form_autofill_password();
 echo '<fieldset>';
 echo '<div class="clearer"><!-- --></div>';
 echo $newsettingshtml;
index 7d3a96f..57bd05f 100644 (file)
@@ -2492,10 +2492,12 @@ class core_course_external extends external_api {
                         $info->outcomes = array();
                     }
                     $id = str_replace('outcome_', '', $key);
-                    $outcome = $outcome = grade_outcome::fetch(array('id' => $id));
+                    $outcome = grade_outcome::fetch(array('id' => $id));
+                    $scaleitems = $outcome->load_scale();
                     $info->outcomes[] = array(
                         'id' => $id,
-                        'name' => external_format_string($outcome->get_name(), $context->id)
+                        'name' => external_format_string($outcome->get_name(), $context->id),
+                        'scale' => $scaleitems->scale
                     );
                 }
             }
@@ -2572,6 +2574,7 @@ class core_course_external extends external_api {
                                 array(
                                     'id' => new external_value(PARAM_ALPHANUMEXT, 'Outcome id'),
                                     'name'  => new external_value(PARAM_TEXT, 'Outcome full name'),
+                                    'scale' => new external_value(PARAM_TEXT, 'Scale items')
                                 )
                             ),
                             'Outcomes information', VALUE_OPTIONAL
index 19621f4..d991ac7 100644 (file)
@@ -1617,20 +1617,66 @@ class core_course_externallib_testcase extends externallib_advanced_testcase {
         // Hidden activity.
         $assign = self::getDataGenerator()->create_module('assign', $record, $options);
 
+        $outcomescale = 'Distinction, Very Good, Good, Pass, Fail';
+
+        // Insert a custom grade scale to be used by an outcome.
+        $gradescale = new grade_scale();
+        $gradescale->name        = 'gettcoursemodulescale';
+        $gradescale->courseid    = $course->id;
+        $gradescale->userid      = 0;
+        $gradescale->scale       = $outcomescale;
+        $gradescale->description = 'This scale is used to mark standard assignments.';
+        $gradescale->insert();
+
+        // Insert an outcome.
+        $data = new stdClass();
+        $data->courseid = $course->id;
+        $data->fullname = 'Team work';
+        $data->shortname = 'Team work';
+        $data->scaleid = $gradescale->id;
+        $outcome = new grade_outcome($data, false);
+        $outcome->insert();
+
+        $outcomegradeitem = new grade_item();
+        $outcomegradeitem->itemname = $outcome->shortname;
+        $outcomegradeitem->itemtype = 'mod';
+        $outcomegradeitem->itemmodule = 'assign';
+        $outcomegradeitem->iteminstance = $assign->id;
+        $outcomegradeitem->outcomeid = $outcome->id;
+        $outcomegradeitem->cmid = 0;
+        $outcomegradeitem->courseid = $course->id;
+        $outcomegradeitem->aggregationcoef = 0;
+        $outcomegradeitem->itemnumber = 1; // The activity's original grade item will be 0.
+        $outcomegradeitem->gradetype = GRADE_TYPE_SCALE;
+        $outcomegradeitem->scaleid = $outcome->scaleid;
+        $outcomegradeitem->insert();
+
+        $assignmentgradeitem = grade_item::fetch(
+            array(
+                'itemtype' => 'mod',
+                'itemmodule' => 'assign',
+                'iteminstance' => $assign->id,
+                'itemnumber' => 0,
+                'courseid' => $course->id
+            )
+        );
+        $outcomegradeitem->set_parent($assignmentgradeitem->categoryid);
+        $outcomegradeitem->move_after_sortorder($assignmentgradeitem->sortorder);
+
         // Test admin user can see the complete hidden activity.
         $result = core_course_external::get_course_module($assign->cmid);
         $result = external_api::clean_returnvalue(core_course_external::get_course_module_returns(), $result);
 
         $this->assertCount(0, $result['warnings']);
         // Test we retrieve all the fields.
-        $this->assertCount(26, $result['cm']);
+        $this->assertCount(27, $result['cm']);
         $this->assertEquals($record['name'], $result['cm']['name']);
         $this->assertEquals($options['idnumber'], $result['cm']['idnumber']);
         $this->assertEquals(100, $result['cm']['grade']);
         $this->assertEquals(0.0, $result['cm']['gradepass']);
         $this->assertEquals('submissions', $result['cm']['advancedgrading'][0]['area']);
         $this->assertEmpty($result['cm']['advancedgrading'][0]['method']);
-        $this->assertArrayNotHasKey('outcomes', $result['cm']);
+        $this->assertEquals($outcomescale, $result['cm']['outcomes'][0]['scale']);
 
         $student = $this->getDataGenerator()->create_user();
         $studentrole = $DB->get_record('role', array('shortname' => 'student'));
index 64f3354..5e673ec 100644 (file)
@@ -75,7 +75,7 @@ class tool_provider_testcase extends advanced_testcase {
      */
     public function test_constructor_with_non_existent_tool() {
         $this->expectException('dml_exception');
-        new tool_provider(1);
+        new tool_provider(-1);
     }
 
     /**
index 7fce284..46324fc 100644 (file)
@@ -1016,8 +1016,6 @@ class core_files_renderer extends plugin_renderer_base {
 
                     <div class="controls"><select></select></div>
                 </div>';
-        // HACK to prevent browsers from automatically inserting the user's password into the wrong fields.
-        $rv .= prevent_form_autofill_password();
         $rv .= '
                 <div class="fp-login-input control-group clearfix">
                     <label class="control-label"></label>
index b5986aa..3aa78e6 100644 (file)
@@ -34,3 +34,4 @@ downloadoptions,core_table
 downloadtsv,core_table
 downloadxhtml,core_table
 invalidpersistent,core_competency
+revealpassword,core_form
index 1f70f67..39c5c80 100644 (file)
@@ -51,10 +51,14 @@ $string['nomethodforaddinghelpbutton'] = 'There is no method for adding a help b
 $string['nonexistentformelements'] = 'Trying to add help buttons to non-existent form elements : {$a}';
 $string['noselection'] = 'No selection';
 $string['nosuggestions'] = 'No suggestions';
+$string['novalue'] = 'Nothing entered';
+$string['novalueclicktoset'] = 'Click to enter text';
 $string['optional'] = 'Optional';
 $string['othersettings'] = 'Other settings';
+$string['passwordunmaskedithint'] = 'Edit password';
+$string['passwordunmaskrevealhint'] = 'Reveal';
+$string['passwordunmaskinstructions'] = 'Press enter to save changes';
 $string['requiredelement'] = 'Required field';
-$string['revealpassword'] = 'Reveal';
 $string['security'] = 'Security';
 $string['selectallornone'] = 'Select all/none';
 $string['selected'] = 'Selected';
@@ -68,3 +72,6 @@ $string['timeunit'] = 'Time unit';
 $string['timing'] = 'Timing';
 $string['unmaskpassword'] = 'Unmask';
 $string['year'] = 'Year';
+
+// Deprecated since 3.2.
+$string['revealpassword'] = 'Reveal';
index 68e1b48..515a6c2 100644 (file)
@@ -2406,13 +2406,11 @@ class admin_setting_configpasswordunmask extends admin_setting_configtext {
     }
 
     /**
-     * Returns XHTML for the field
-     * Writes Javascript into the HTML below right before the last div
+     * Returns HTML for the field.
      *
-     * @todo Make javascript available through newer methods if possible
-     * @param string $data Value for the field
-     * @param string $query Passed as final argument for format_admin_setting
-     * @return string XHTML field
+     * @param   string  $data       Value for the field
+     * @param   string  $query      Passed as final argument for format_admin_setting
+     * @return  string              Rendered HTML
      */
     public function output_html($data, $query='') {
         global $OUTPUT;
index 35733c1..7e4fd5c 100644 (file)
Binary files a/lib/amd/build/templates.min.js and b/lib/amd/build/templates.min.js differ
index f9fe50b..dcf52bf 100644 (file)
@@ -237,7 +237,9 @@ define(['core/mustache',
 
         var index = this.requiredStrings.length;
         this.requiredStrings.push({key: key, component: component, param: param});
-        return '{{_s' + index + '}}';
+
+        // The placeholder must not use {{}} as those can be misinterpreted by the engine.
+        return '[[_s' + index + ']]';
     };
 
     /**
@@ -328,7 +330,7 @@ define(['core/mustache',
      * @return {String} The treated content.
      */
     Renderer.prototype.treatStringsInContent = function(content, strings) {
-        var pattern = /{{_s\d+}}/,
+        var pattern = /\[\[_s\d+\]\]/,
             treated,
             index,
             strIndex,
@@ -345,7 +347,7 @@ define(['core/mustache',
                 treated += content.substring(0, index);
                 content = content.substr(index);
                 strIndex = '';
-                walker = 4;  // 4 is the length of '{{_s'.
+                walker = 4;  // 4 is the length of '[[_s'.
 
                 // Walk the characters to manually extract the index of the string from the placeholder.
                 char = content.substr(walker, 1);
@@ -353,16 +355,16 @@ define(['core/mustache',
                     strIndex += char;
                     walker++;
                     char = content.substr(walker, 1);
-                } while (char != '}');
+                } while (char != ']');
 
                 // Get the string, add it to the treated result, and remove the placeholder from the content to treat.
                 strFinal = strings[parseInt(strIndex, 10)];
                 if (typeof strFinal === 'undefined') {
-                    Log.debug('Could not find string for pattern {{_s' + strIndex + '}}.');
+                    Log.debug('Could not find string for pattern [[_s' + strIndex + ']].');
                     strFinal = '';
                 }
                 treated += strFinal;
-                content = content.substr(6 + strIndex.length);  // 6 is the length of the placeholder without the index: '{{_s}}'.
+                content = content.substr(6 + strIndex.length);  // 6 is the length of the placeholder without the index: '[[_s]]'.
 
                 // Find the next placeholder.
                 index = content.search(pattern);
index 27fbafa..3c770bb 100644 (file)
@@ -228,6 +228,10 @@ class behat_field_manager {
             return $type;
         }
 
+        if (!empty($fieldnode->find('xpath', '/ancestor::*[@data-passwordunmaskid]'))) {
+            return 'passwordunmask';
+        }
+
         // We look for a parent node with 'felement' class.
         if ($class = $fieldnode->getParent()->getAttribute('class')) {
 
index 538e3fc..44338c1 100644 (file)
@@ -186,6 +186,11 @@ XPATH
             'filemanager' => <<<XPATH
 .//*[@data-fieldtype = 'filemanager' or @data-fieldtype = 'filepicker']
     /descendant::input[@id = //label[contains(normalize-space(string(.)), %locator%)]/@for]
+XPATH
+        ,
+             'passwordunmask' => <<<XPATH
+.//*[@data-passwordunmask='wrapper']
+    /descendant::input[@id = //label[contains(normalize-space(string(.)), %locator%)]/@for]
 XPATH
         ],
     ];
diff --git a/lib/behat/form_field/behat_form_passwordunmask.php b/lib/behat/form_field/behat_form_passwordunmask.php
new file mode 100644 (file)
index 0000000..439643b
--- /dev/null
@@ -0,0 +1,64 @@
+<?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/>.
+
+/**
+ * Silly behat_form_select extension.
+ *
+ * @package    core_form
+ * @category   test
+ * @copyright  2013 David MonllaĆ³
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+defined('MOODLE_INTERNAL') || die();
+
+// NOTE: no MOODLE_INTERNAL test here, this file may be required by behat before including /config.php.
+
+require_once(__DIR__  . '/behat_form_text.php');
+
+/**
+ * Allows interaction with passwordunmask form fields.
+ *
+ * Plain behat_form_select extension as it is the same
+ * kind of field.
+ *
+ * @package    core_form
+ * @category   test
+ * @copyright  2013 David MonllaĆ³
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class behat_form_passwordunmask extends behat_form_text {
+    /**
+     * Sets the value to a field.
+     *
+     * @param string $value
+     * @return void
+     */
+    public function set_value($value) {
+        if ($this->running_javascript()) {
+            $id = $this->field->getAttribute('id');
+            $js = <<<JS
+require(["jquery"], function($) {
+    var wrapper = $(document.getElementById("{$id}")).closest('[data-passwordunmask="wrapper"]');
+        wrapper.find('[data-passwordunmask="edit"]').trigger("click");
+});
+JS;
+            $this->session->executeScript($js);
+        }
+
+        $this->field->setValue($value);
+    }
+}
index 4d0386b..c75e12b 100644 (file)
@@ -252,7 +252,12 @@ class manager {
 
         // Set configuration.
         session_name($sessionname);
-        session_set_cookie_params(0, $CFG->sessioncookiepath, $CFG->sessioncookiedomain, $cookiesecure, $CFG->cookiehttponly);
+        // The session cookie expiry time cannot be extended so this needs to be set to a reasonable period, longer than
+        // the sessiontimeout.
+        // This ensures that the cookie is unlikely to timeout before the session does.
+        $sessionlifetime = $CFG->sessiontimeout + WEEKSECS;
+        session_set_cookie_params($sessionlifetime, $CFG->sessioncookiepath, $CFG->sessioncookiedomain,
+                $cookiesecure, $CFG->cookiehttponly);
         ini_set('session.use_trans_sid', '0');
         ini_set('session.use_only_cookies', '1');
         ini_set('session.hash_function', '0');        // For now MD5 - we do not have room for sha-1 in sessions table.
index 01bd4ca..215dff7 100644 (file)
@@ -6369,5 +6369,15 @@ function get_logs($select, array $params=null, $order='l.time DESC', $limitfrom=
            $select
             $order";
 
-    return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum) ;
+    return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
+}
+
+/**
+ * Renders a hidden password field so that browsers won't incorrectly autofill password fields with the user's password.
+ *
+ * @deprecated since Moodle 3.2 MDL-53048
+ */
+function prevent_form_autofill_password() {
+    debugging('prevent_form_autofill_password has been deprecated and is no longer in use.', DEBUG_DEVELOPER);
+    return '';
 }
diff --git a/lib/form/amd/build/passwordunmask.min.js b/lib/form/amd/build/passwordunmask.min.js
new file mode 100644 (file)
index 0000000..5687ff9
Binary files /dev/null and b/lib/form/amd/build/passwordunmask.min.js differ
diff --git a/lib/form/amd/src/passwordunmask.js b/lib/form/amd/src/passwordunmask.js
new file mode 100644 (file)
index 0000000..8354f47
--- /dev/null
@@ -0,0 +1,286 @@
+// 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/>.
+
+/**
+ * Password Unmask functionality.
+ *
+ * @module     core_form/passwordunmask
+ * @package    core_form
+ * @class      passwordunmask
+ * @copyright  2016 Andrew Nicols <andrew@nicols.co.uk>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ * @since      3.2
+ */
+define(['jquery', 'core/templates'], function($, Template) {
+
+    /**
+     * Constructor for PasswordUnmask.
+     *
+     * @param   {String}    elementid   The element to apply the PasswordUnmask to
+     */
+    var PasswordUnmask = function(elementid) {
+        // Setup variables.
+        this.wrapperSelector = '[data-passwordunmask="wrapper"][data-passwordunmaskid="' + elementid + '"]';
+        this.wrapper = $(this.wrapperSelector);
+        this.editorSpace = this.wrapper.find('[data-passwordunmask="editor"]');
+        this.editLink = this.wrapper.find('a[data-passwordunmask="edit"]');
+        this.editInstructions = this.wrapper.find('[data-passwordunmask="instructions"]');
+        this.displayValue = this.wrapper.find('[data-passwordunmask="displayvalue"]');
+
+        // Move and convert the input field to the editor, then remove the noscript.
+        // We only want a single input field.
+        var noscriptContent = $(this.wrapper.find('noscript').text());
+        this.inputField = noscriptContent.filter('input');
+        this.inputField.attr('type', 'hidden');
+        this.editorSpace.append(this.inputField);
+        this.wrapper.find('noscript').remove();
+
+        if (!this.editInstructions.attr('id')) {
+            this.editInstructions.attr('id', elementid + '_instructions');
+        }
+        this.editInstructions.hide();
+
+        this.setDisplayValue();
+
+        // Add the listeners.
+        this.addListeners();
+    };
+
+    /**
+     * Add the event listeners required for PasswordUnmask.
+     *
+     * @method  addListeners
+     * @return  {PasswordUnmask}
+     * @chainable
+     */
+    PasswordUnmask.prototype.addListeners = function() {
+        this.wrapper.on('click keypress', '[data-passwordunmask="edit"]', $.proxy(function(e) {
+            if (e.type === 'keypress' && e.keyCode !== 13) {
+                return;
+            }
+            e.stopImmediatePropagation();
+            e.preventDefault();
+
+            if (this.inputField.attr('type') !== 'hidden') {
+                // Only focus on the edit link if the event was not a click, and the new target is not an input field.
+                if (e.type !== 'click' && !$(e.relatedTarget).is(':input')) {
+                    this.turnEditingOff(true);
+                } else {
+                    this.turnEditingOff(false);
+                }
+            } else {
+                this.turnEditingOn();
+            }
+        }, this));
+
+        this.wrapper.on('click keypress', '[data-passwordunmask="unmask"]', $.proxy(function(e) {
+            if (e.type === 'keypress' && e.keyCode !== 13) {
+                return;
+            }
+            e.stopImmediatePropagation();
+            e.preventDefault();
+
+            // Toggle the data attribute.
+            this.wrapper.data('unmasked', !this.wrapper.data('unmasked'));
+
+            this.setDisplayValue();
+        }, this));
+
+        this.wrapper.on('keydown', 'input', $.proxy(function(e) {
+            if (e.type === 'keydown' && e.keyCode !== 13) {
+                return;
+            }
+
+            e.stopImmediatePropagation();
+            e.preventDefault();
+
+            this.turnEditingOff(true);
+        }, this));
+
+        return this;
+    };
+
+    /**
+     * Check whether focus was lost from the PasswordUnmask and turn editing off if required.
+     *
+     * @method  checkFocusOut
+     * @param   {EventFacade}   e       The EventFacade generating the suspsected Focus Out
+     */
+    PasswordUnmask.prototype.checkFocusOut = function(e) {
+        if (!this.isEditing()) {
+            // Ignore - not editing.
+            return;
+        }
+
+        window.setTimeout($.proxy(function() {
+            // Firefox does not have the focusout event. Instead jQuery falls back to the 'blur' event.
+            // The blur event does not have a relatedTarget, so instead we use a timeout and the new activeElement.
+            var relatedTarget = e.relatedTarget || document.activeElement;
+            if (this.wrapper.has($(relatedTarget)).length) {
+                // Ignore, some part of the element is still active.
+                return;
+            }
+
+            // Only focus on the edit link if the new related target is not an input field or anchor.
+            this.turnEditingOff(!$(relatedTarget).is(':input,a'));
+        }, this), 100);
+    };
+
+    /**
+     * Whether the password is currently visible (unmasked).
+     *
+     * @method  passwordVisible
+     * @return  {Boolean}            True if the password is unmasked
+     */
+    PasswordUnmask.prototype.passwordVisible = function() {
+        return !!this.wrapper.data('unmasked');
+    };
+
+    /**
+     * Whether the user is currently editing the field.
+     *
+     * @method  isEditing
+     * @return  {Boolean}            True if edit mode is enabled
+     */
+    PasswordUnmask.prototype.isEditing = function() {
+        return this.inputField.attr('type') !== 'hidden';
+    };
+
+    /**
+     * Enable the editing functionality.
+     *
+     * @method  turnEditingOn
+     * @return  {PasswordUnmask}
+     * @chainable
+     */
+    PasswordUnmask.prototype.turnEditingOn = function() {
+        if (this.passwordVisible()) {
+            this.inputField.attr('type', 'text');
+        } else {
+            this.inputField.attr('type', 'password');
+        }
+
+        if (this.editInstructions.length) {
+            this.inputField.attr('aria-describedby', this.editInstructions.attr('id'));
+            this.editInstructions.show();
+        }
+
+        this.wrapper.attr('data-passwordunmask-visible', 1);
+
+        this.editLink.hide();
+        this.inputField
+            .focus()
+            .select();
+
+        // Note, this cannot be added as a delegated listener on init because Firefox does not support the FocusOut
+        // event (https://bugzilla.mozilla.org/show_bug.cgi?id=687787) and the blur event does not identify the
+        // relatedTarget.
+        // The act of focusing the this.inputField means that in Firefox the focusout will be triggered on blur of the edit
+        // link anchor.
+        $('body').on('focusout', this.wrapperSelector, $.proxy(this.checkFocusOut, this));
+
+        return this;
+    };
+
+    /**
+     * Disable the editing functionality, optionally focusing on the edit link.
+     *
+     * @method  turnEditingOff
+     * @param   {Boolean}       focusOnEditLink     Whether to focus on the edit link after disabling the editor
+     * @return  {PasswordUnmask}
+     * @chainable
+     */
+    PasswordUnmask.prototype.turnEditingOff = function(focusOnEditLink) {
+        $('body').off('focusout', this.wrapperSelector, this.checkFocusOut);
+        this.inputField
+            // Hide the field again.
+            .attr('type', 'hidden')
+
+            // Ensure that the aria-describedby is removed.
+            .attr('aria-describedby', null);
+
+        this.editInstructions.hide();
+
+        // Remove the visible attr.
+        this.wrapper.removeAttr('data-passwordunmask-visible');
+
+        this.editLink.show();
+        this.setDisplayValue();
+
+        if (focusOnEditLink) {
+            this.editLink.focus();
+        }
+
+        return this;
+    };
+
+    /**
+     * Get the currently value.
+     *
+     * @method  getDisplayValue
+     * @return  {String}
+     */
+    PasswordUnmask.prototype.getDisplayValue = function() {
+        return this.inputField.val();
+    };
+
+    /**
+     * Set the currently value in the display, taking into account the current settings.
+     *
+     * @method  setDisplayValue
+     * @return  {PasswordUnmask}
+     * @chainable
+     */
+    PasswordUnmask.prototype.setDisplayValue = function() {
+        if (this.isEditing()) {
+            if (this.wrapper.data('unmasked')) {
+                this.inputField.attr('type', 'text');
+            } else {
+                this.inputField.attr('type', 'password');
+            }
+        }
+
+        // Update the display value.
+        // Note: This must always be updated.
+        // The unmask value can be changed whilst editing and the editing can then be disabled.
+        var value = this.getDisplayValue();
+        if (value && this.wrapper.data('unmasked')) {
+            // There is a value, and we will show it.
+            this.displayValue.text(value);
+        } else {
+            if (!value) {
+                value = "";
+            }
+            // There is a value, but it will be disguised.
+            // We use the passwordunmask-fill to allow modification of the fill and to ensure that the display does not
+            // change as the page loads the JS.
+            Template.render('core_form/element-passwordunmask-fill', {
+                element: {
+                    frozen:     this.inputField.is('[readonly]'),
+                    value:      value,
+                    valuechars: value.split(''),
+                },
+            }).done($.proxy(function(html, js) {
+                this.displayValue.html(html);
+
+                Template.runTemplateJS(js);
+            }, this));
+        }
+
+        return this;
+    };
+
+    return PasswordUnmask;
+});
index 73bee9d..db18e88 100644 (file)
@@ -52,7 +52,6 @@ class MoodleQuickForm_passwordunmask extends MoodleQuickForm_password {
      *              or an associative array
      */
     public function __construct($elementName=null, $elementLabel=null, $attributes=null) {
-        global $CFG;
         // no standard mform in moodle should allow autocomplete of passwords
         if (empty($attributes)) {
             $attributes = array('autocomplete'=>'off');
@@ -63,6 +62,7 @@ class MoodleQuickForm_passwordunmask extends MoodleQuickForm_password {
                 $attributes .= ' autocomplete="off" ';
             }
         }
+        $this->_persistantFreeze = true;
 
         parent::__construct($elementName, $elementLabel, $attributes);
         $this->setType('passwordunmask');
@@ -79,25 +79,15 @@ class MoodleQuickForm_passwordunmask extends MoodleQuickForm_password {
     }
 
     /**
-     * Returns HTML for password form element.
+     * Function to export the renderer data in a format that is suitable for a mustache template.
      *
-     * @return string
+     * @param renderer_base $output Used to do a final render of any components that need to be rendered for export.
+     * @return stdClass|array
      */
-    function toHtml() {
-        global $PAGE;
+    public function export_for_template(renderer_base $output) {
+        $context = parent::export_for_template($output);
+        $context['valuechars'] = array_fill(0, strlen($context['value']), 'x');
 
-        if ($this->_flagFrozen) {
-            return $this->getFrozenHtml();
-        } else {
-            $unmask = get_string('unmaskpassword', 'form');
-            //Pass id of the element, so that unmask checkbox can be attached.
-            $attributes = array('formid' => $this->getAttribute('id'),
-                'checkboxlabel' => $unmask,
-                'checkboxname' => $this->getAttribute('name'));
-            $PAGE->requires->yui_module('moodle-form-passwordunmask', 'M.form.passwordunmask',
-                    array($attributes));
-            return $this->_getTabs() . '<input' . $this->_getAttrString($this->_attributes) . ' />';
-        }
+        return $context;
     }
-
 }
diff --git a/lib/form/templates/element-passwordunmask-fill.mustache b/lib/form/templates/element-passwordunmask-fill.mustache
new file mode 100644 (file)
index 0000000..56360d1
--- /dev/null
@@ -0,0 +1,56 @@
+{{!
+    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/element-passwordunmask-fill
+
+    The fill for a passwordunmask form element.
+
+    The purpose of this template is to render the fill for a passwordunmask element.
+
+    Classes required for JS:
+    * none
+
+    Data attributes required for JS:
+    * none
+
+    Context variables required for this template:
+    * element
+      * valuechars (optional)
+
+    Example context (json):
+    {
+        "element": {
+            "valuechars": [
+                "E",
+                "x",
+                "a",
+                "m",
+                "p",
+                "l",
+                "e"
+            ]
+        }
+    }
+
+}}
+<span>
+{{# element.valuechars }}&bull;{{/ element.valuechars }}
+{{^ element.valuechars }}<em>{{!
+    }}{{^ element.frozen }}{{# str }} novalueclicktoset, form {{/ str }}{{/ element.frozen }}{{!
+    }}{{# element.frozen }}{{# str }} novalue, form {{/ str }}{{/ element.frozen }}{{!
+}}</em>{{/ element.valuechars }}
+</span>
diff --git a/lib/form/templates/element-passwordunmask.mustache b/lib/form/templates/element-passwordunmask.mustache
new file mode 100644 (file)
index 0000000..8634e54
--- /dev/null
@@ -0,0 +1,93 @@
+{{!
+    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/element-passwordunmask
+
+    Moodle passwordunmask form element template.
+
+    The purpose of this template is to render a passwordunmask form element.
+
+    Classes required for JS:
+    * none
+
+    Data attributes required for JS:
+    * none
+
+    Context variables required for this template:
+    * element
+        * id
+        * name
+        * value
+        * size
+
+    Example context (json):
+    {
+        "element": {
+            "id": "example_password_unmask",
+            "name": "example",
+            "value": "Password1!",
+            "size": 40
+        }
+    }
+
+}}
+{{< core_form/element-template }}
+    {{$ element }}
+        <div data-passwordunmask="wrapper" data-passwordunmaskid="{{ element.id }}">
+            <noscript>
+                <!-- Backwards compatability for Behat -->
+                <input  type="password"
+                        {{# element.frozen }}readonly{{/ element.frozen }}
+                        {{^ element.hardfrozen}} name="{{ element.name }}"{{/ element.hardfrozen }}
+                        id="{{ element.id }}"
+                        value="{{element.value }}"
+                        size="{{ element.size }}"
+                        {{# error }}
+                            autofocus aria-describedby="id_error_{{ element.name }}"
+                        {{/ error }}
+                        {{{ attributes }}}
+                        >
+            </noscript>
+            <span class="visibleifjs">
+                <span data-passwordunmask="editor">
+                    <!-- The input in the noscript will be moved here as part of the page load -->
+                    <span data-passwordunmask="instructions" class="editinstructions">
+                        {{^ element.frozen }}
+                        {{# str }} passwordunmaskinstructions, form {{/ str }}
+                        {{/ element.frozen }}
+                    </span>
+                </span>
+                {{^ element.frozen }}
+                <a href="#" data-passwordunmask="edit" title="{{ edithint }}">
+                {{/ element.frozen }}
+                    <span data-passwordunmask="displayvalue">{{> core_form/element-passwordunmask-fill }}</span>
+                {{^ element.frozen }}
+                    {{# pix }} t/passwordunmask-edit, core, {{ edithint }}{{/ pix }}
+                </a>
+                {{/ element.frozen }}
+                <a href="#" data-passwordunmask="unmask" title="{{ unmaskhint }}">
+                    {{# pix }} t/passwordunmask-reveal, core, {{ edithint }}{{/ pix }}
+                </a>
+            </span>
+        </div>
+    {{/ element }}
+{{/ core_form/element-template }}
+{{# js }}
+require(['core_form/passwordunmask'], function(PasswordUnmask) {
+    new PasswordUnmask("{{ element.id }}");
+});
+{{/ js }}
diff --git a/lib/form/templates/element-template.mustache b/lib/form/templates/element-template.mustache
new file mode 100644 (file)
index 0000000..9463064
--- /dev/null
@@ -0,0 +1,64 @@
+{{!
+    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/element-template
+
+    Moodle form element wrapper template.
+
+    The purpose of this template is to wrap a form element.
+
+    Classes required for JS:
+    * none
+
+    Data attributes required for JS:
+    * none
+
+    Context variables required for this template:
+    * label
+    * helpbutton
+    * error
+    * element
+        * id
+        * name
+
+    Example context (json):
+    {
+        "label": "Password",
+        "error": "No password set",
+        "element": {
+            "id": "example_password_unmask",
+            "name": "example"
+        }
+    }
+
+}}
+<div id="fitem_{{ element.id }}" class="fitem fitem_{{ element.type }}">
+    <div class="fitemtitle">
+      <label for="{{element.id}}">{{{ label }}}</label>
+        {{{ helpbutton }}}
+    </div>
+    <div class="felement {{# error }} error{{/ error }} f{{ element.type }}">
+        {{# error }}
+        <span class="error" tabindex="0" id="id_error_{{ element.name }}">
+            {{{ error }}}
+        </span>
+        {{/ error }}
+        {{$ element }}
+            <!-- Element goes here -->
+        {{/ element }}
+    </div>
+</div>
index 4822968..ca03271 100644 (file)
Binary files a/lib/form/yui/build/moodle-form-passwordunmask/moodle-form-passwordunmask-debug.js and b/lib/form/yui/build/moodle-form-passwordunmask/moodle-form-passwordunmask-debug.js differ
index 1c79dd4..d1ffeb6 100644 (file)
Binary files a/lib/form/yui/build/moodle-form-passwordunmask/moodle-form-passwordunmask-min.js and b/lib/form/yui/build/moodle-form-passwordunmask/moodle-form-passwordunmask-min.js differ
index 4822968..d1c1242 100644 (file)
Binary files a/lib/form/yui/build/moodle-form-passwordunmask/moodle-form-passwordunmask.js and b/lib/form/yui/build/moodle-form-passwordunmask/moodle-form-passwordunmask.js differ
index 56097ea..9c95b3e 100644 (file)
@@ -1,41 +1,5 @@
-var PASSWORDUNMASK = function() {
-    PASSWORDUNMASK.superclass.constructor.apply(this, arguments);
-};
-
-Y.extend(PASSWORDUNMASK, Y.Base, {
-    // Initialize checkbox if id is passed.
-    initializer: function(params) {
-        if (params && params.formid) {
-            this.add_checkbox(params.formid, params.checkboxlabel, params.checkboxname);
-        }
-    },
-
-    // Create checkbox for unmasking password.
-    add_checkbox: function(elementid, checkboxlabel, checkboxname) {
-        var node = Y.one('#' + elementid);
-
-        // Retaining unmask div from previous implementation.
-        var unmaskdiv = Y.Node.create('<div id="' + elementid + 'unmaskdiv" class="unmask"></div>');
-
-        // Add checkbox for unmasking to unmaskdiv.
-        var unmaskchb = Y.Node.create('<input id="' + elementid + 'unmask" type="checkbox" name="' +
-            checkboxname + 'unmask">');
-        unmaskdiv.appendChild(unmaskchb);
-        // Attach event using static javascript function for unmasking password.
-        unmaskchb.on('click', function() {
-            window.unmaskPassword(elementid);
-        });
-
-        // Add label for checkbox to unmaskdiv.
-        var unmasklabel = Y.Node.create('<label for="' + elementid + 'unmask">' + checkboxlabel + '</label>');
-        unmaskdiv.appendChild(unmasklabel);
-
-        // Insert unmask div in the same div as password input.
-        node.get('parentNode').insert(unmaskdiv, node.get('lastNode'));
-    }
-});
-
 M.form = M.form || {};
-M.form.passwordunmask = function(params) {
-    return new PASSWORDUNMASK(params);
+M.form.passwordunmask = function() {
+    Y.log("The moodle-form-passwordunmask module has been deprecated. " +
+            "Please use the core_form/passwordunmask amd module instead.", 'moodle-form-passwordunmask', 'warn');
 };
index 1830917..185a757 100644 (file)
@@ -1,8 +1,5 @@
 {
     "moodle-form-passwordunmask": {
-        "requires": [
-            "node",
-            "base"
-        ]
+        "requires": []
     }
 }
index adb76dd..282ebbe 100644 (file)
@@ -2750,8 +2750,6 @@ class MoodleQuickForm_Renderer extends HTML_QuickForm_Renderer_Tableless{
         $this->_collapseButtons = '';
         $formid = $form->getAttribute('id');
         parent::startForm($form);
-        // HACK to prevent browsers from automatically inserting the user's password into the wrong fields.
-        $this->_hiddenHtml .= prevent_form_autofill_password();
         if ($form->isFrozen()){
             $this->_formTemplate = "\n<div class=\"mform frozen\">\n{content}\n</div>";
         } else {
diff --git a/lib/templates/prevent_form_autofill_password.mustache b/lib/templates/prevent_form_autofill_password.mustache
deleted file mode 100644 (file)
index 307a0e4..0000000
+++ /dev/null
@@ -1,23 +0,0 @@
-{{!
-    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/>.
-}}
-{{!
-    Snippet to prevent browsers from autofilling password fields.
-}}
-<div class="hide">
-    <input type="text" class="ignoredirty" />
-    <input type="password" class="ignoredirty" />
-</div>
index 876dcbe..65dedb1 100644 (file)
@@ -38,6 +38,7 @@ information provided here is intended especially for developers.
   - get_logs()            - See MDL-43681 for more information
   - get_logs_usercourse() - See MDL-43681 for more information
   - get_logs_userday()    - See MDL-43681 for more information
+  - prevent_form_autofill_password() Please do not use anymore.
 * The password_compat library was removed as it is no longer required.
 * Phpunit has been upgraded to 5.4.x and following has been deprecated and is not used any more:
   - setExpectedException(), use @expectedException or $this->expectException() and $this->expectExceptionMessage()
index 74ec6af..75a227c 100644 (file)
@@ -3556,14 +3556,3 @@ function get_formatted_help_string($identifier, $component, $ajax = false, $a =
     }
     return $data;
 }
-
-/**
- * Renders a hidden password field so that browsers won't incorrectly autofill password fields with the user's password.
- *
- * @since 3.0
- * @return string HTML to prevent password autofill
- */
-function prevent_form_autofill_password() {
-    global $OUTPUT;
-    return $OUTPUT->render_from_template('core/prevent_form_autofill_password', []);
-}
index f8b9219..ef07b75 100644 (file)
Binary files a/message/amd/build/message_area_contacts.min.js and b/message/amd/build/message_area_contacts.min.js differ
index 672d62a..1e38b6b 100644 (file)
Binary files a/message/amd/build/message_area_profile.min.js and b/message/amd/build/message_area_profile.min.js differ
index 0158a71..c1aa29e 100644 (file)
@@ -546,6 +546,9 @@ define(['jquery', 'core/ajax', 'core/templates', 'core/notification', 'core/cust
          * @return {String} The altered text
          */
         Contacts.prototype._getContactText = function(text) {
+            // Remove the HTML tags to render the contact text.
+            text = $(document.createElement('div')).html(text).text();
+
             if (text.length > this._messageLength) {
                 text = text.substr(0, this._messageLength - 3);
                 text += '...';
index 66387b4..c4cedfb 100644 (file)
@@ -64,17 +64,35 @@ define(['jquery', 'core/ajax', 'core/templates', 'core/notification', 'core/str'
 
             this.messageArea.onCustomEvent(Events.CONTACTSELECTED, this._viewProfile.bind(this));
             this.messageArea.onDelegateEvent(CustomEvents.events.activate, SELECTORS.PROFILEVIEW,
-                this._viewFullProfile.bind(this));
+                function(e, data) {
+                    this._viewFullProfile();
+                    data.originalEvent.preventDefault();
+                }.bind(this));
             this.messageArea.onDelegateEvent(CustomEvents.events.activate, SELECTORS.PROFILESENDMESSAGE,
-                this._sendMessage.bind(this));
+                function(e, data) {
+                    this._sendMessage();
+                    data.originalEvent.preventDefault();
+                }.bind(this));
             this.messageArea.onDelegateEvent(CustomEvents.events.activate, SELECTORS.PROFILEUNBLOCKCONTACT,
-                this._unblockContact.bind(this));
+                function(e, data) {
+                    this._unblockContact();
+                    data.originalEvent.preventDefault();
+                }.bind(this));
             this.messageArea.onDelegateEvent(CustomEvents.events.activate, SELECTORS.PROFILEBLOCKCONTACT,
-                this._blockContact.bind(this));
+                function(e, data) {
+                    this._blockContact();
+                    data.originalEvent.preventDefault();
+                }.bind(this));
             this.messageArea.onDelegateEvent(CustomEvents.events.activate, SELECTORS.PROFILEADDCONTACT,
-                this._addContact.bind(this));
+                function(e, data) {
+                    this._addContact();
+                    data.originalEvent.preventDefault();
+                }.bind(this));
             this.messageArea.onDelegateEvent(CustomEvents.events.activate, SELECTORS.PROFILEREMOVECONTACT,
-                this._removeContact.bind(this));
+                function(e, data) {
+                    this._removeContact();
+                    data.originalEvent.preventDefault();
+                }.bind(this));
             this.messageArea.onDelegateEvent(CustomEvents.events.activate, SELECTORS.SHOWCONTACTS,
                 this._hideMessagingArea.bind(this));
         };
index f72bd4c..23f0feb 100644 (file)
@@ -348,7 +348,7 @@ class api {
                 if (isset($userfields['lastaccess'])) {
                     $data->isonline = helper::is_online($userfields['lastaccess']);
                 } else {
-                    $data->isonline = 0;
+                    $data->isonline = false;
                 }
             } else {
                 // Technically the access checks in user_get_user_details are correct,
@@ -362,12 +362,12 @@ class api {
                 $data->email = '';
                 $data->profileimageurl = '';
                 $data->profileimageurlsmall = '';
-                $data->isonline = 0;
+                $data->isonline = false;
             }
             // Check if the contact has been blocked.
             $contact = $DB->get_record('message_contacts', array('userid' => $userid, 'contactid' => $otheruserid));
             if ($contact) {
-                $data->isblocked = $contact->blocked;
+                $data->isblocked = (bool) $contact->blocked;
                 $data->iscontact = true;
             } else {
                 $data->isblocked = false;
@@ -383,14 +383,14 @@ class api {
      *
      * @param int $userid The user id of who we want to delete the messages for (this may be done by the admin
      *  but will still seem as if it was by the user)
-     * @return bool Returns true if a user can delete the message, false otherwise.
+     * @return bool Returns true if a user can delete the conversation, false otherwise.
      */
     public static function can_delete_conversation($userid) {
         global $USER;
 
         $systemcontext = \context_system::instance();
 
-        // Let's check if the user is allowed to delete this message.
+        // Let's check if the user is allowed to delete this conversation.
         if (has_capability('moodle/site:deleteanymessage', $systemcontext) ||
             ((has_capability('moodle/site:deleteownmessage', $systemcontext) &&
                 $USER->id == $userid))) {
@@ -411,7 +411,7 @@ class api {
      * @return bool
      */
     public static function delete_conversation($userid, $otheruserid) {
-        global $DB, $USER;
+        global $DB;
 
         // We need to update the tables to mark all messages as deleted from and to the other user. This seems worse than it
         // is, that's because our DB structure splits messages into two tables (great idea, huh?) which causes code like this.
@@ -457,7 +457,7 @@ class api {
 
                 // Trigger event for deleting the message.
                 \core\event\message_deleted::create_from_ids($message->useridfrom, $message->useridto,
-                    $USER->id, $messagetable, $message->id)->trigger();
+                    $userid, $messagetable, $message->id)->trigger();
             }
         }
 
index 410ce6a..4a54d81 100644 (file)
@@ -147,7 +147,8 @@ class helper {
         $data->messageid = null;
         if (isset($contact->smallmessage)) {
             $data->ismessaging = true;
-            $data->lastmessage = $contact->smallmessage;
+            // Strip the HTML tags from the message for displaying in the contact area.
+            $data->lastmessage = clean_param($contact->smallmessage, PARAM_NOTAGS);
             $data->useridfrom = $contact->useridfrom;
             if (isset($contact->messageid)) {
                 $data->messageid = $contact->messageid;
@@ -155,8 +156,8 @@ class helper {
         }
         // Check if the user is online.
         $data->isonline = self::is_online($userfields->lastaccess);
-        $data->isblocked = isset($contact->blocked) ? $contact->blocked : 0;
-        $data->isread = isset($contact->isread) ? $contact->isread : 0;
+        $data->isblocked = isset($contact->blocked) ? (bool) $contact->blocked : false;
+        $data->isread = isset($contact->isread) ? (bool) $contact->isread : false;
         $data->unreadcount = isset($contact->unreadcount) ? $contact->unreadcount : null;
 
         return $data;
index d624359..ee21e2f 100644 (file)
Binary files a/message/output/popup/amd/build/notification_area_control_area.min.js and b/message/output/popup/amd/build/notification_area_control_area.min.js differ
index a8550b6..ee19a0e 100644 (file)
@@ -30,6 +30,7 @@ define(['jquery', 'core/templates', 'core/notification', 'core/custom_interactio
         CONTAINER: '[data-region="notification-area"]',
         CONTENT: '[data-region="content"]',
         NOTIFICATION: '[data-region="notification-content-item-container"]',
+        CAN_RECEIVE_FOCUS: 'input:not([type="hidden"]), a[href], button, textarea, select, [tabindex]',
     };
 
     var TEMPLATES = {
@@ -271,7 +272,7 @@ define(['jquery', 'core/templates', 'core/notification', 'core/custom_interactio
 
         if (notificationElement && notificationElement.length) {
             this.getRoot().find(SELECTORS.NOTIFICATION).removeClass('selected');
-            notificationElement.addClass('selected');
+            notificationElement.addClass('selected').find(SELECTORS.CAN_RECEIVE_FOCUS).focus();
             var notificationId = notificationElement.attr('data-id');
             var notification = this.getCacheNotification(notificationId);
             this.scrollNotificationIntoView(notificationElement);
@@ -397,6 +398,8 @@ define(['jquery', 'core/templates', 'core/notification', 'core/custom_interactio
             CustomEvents.events.activate,
             CustomEvents.events.scrollBottom,
             CustomEvents.events.scrollLock,
+            CustomEvents.events.up,
+            CustomEvents.events.down,
         ]);
 
         this.getRoot().on(CustomEvents.events.scrollBottom, function() {
@@ -408,6 +411,22 @@ define(['jquery', 'core/templates', 'core/notification', 'core/custom_interactio
             this.showNotification(notificationElement);
         }.bind(this));
 
+        // Show the previous notification in the list.
+        this.getRoot().on(CustomEvents.events.up, SELECTORS.NOTIFICATION, function(e, data) {
+            var notificationElement = $(e.target).closest(SELECTORS.NOTIFICATION);
+            this.showNotification(notificationElement.prev());
+
+            data.originalEvent.preventDefault();
+        }.bind(this));
+
+        // Show the next notification in the list.
+        this.getRoot().on(CustomEvents.events.down, SELECTORS.NOTIFICATION, function(e, data) {
+            var notificationElement = $(e.target).closest(SELECTORS.NOTIFICATION);
+            this.showNotification(notificationElement.next());
+
+            data.originalEvent.preventDefault();
+        }.bind(this));
+
         this.getContainer().on(NotificationAreaEvents.notificationShown, function(e, notification) {
             if (!notification.read) {
                 var element = this.getNotificationElement(notification.id);
index 99ff692..d983273 100644 (file)
@@ -39,7 +39,7 @@ require_once($CFG->dirroot . '/message/tests/messagelib_test.php');
  */
 class core_message_api_testcase extends core_message_messagelib_testcase {
 
-    public function test_message_mark_all_read_for_user_touser() {
+    public function test_mark_all_read_for_user_touser() {
         $sender = $this->getDataGenerator()->create_user(array('firstname' => 'Test1', 'lastname' => 'User1'));
         $recipient = $this->getDataGenerator()->create_user(array('firstname' => 'Test2', 'lastname' => 'User2'));
 
@@ -54,7 +54,7 @@ class core_message_api_testcase extends core_message_messagelib_testcase {
         $this->assertEquals(message_count_unread_messages($recipient), 0);
     }
 
-    public function test_message_mark_all_read_for_user_touser_with_fromuser() {
+    public function test_mark_all_read_for_user_touser_with_fromuser() {
         $sender1 = $this->getDataGenerator()->create_user(array('firstname' => 'Test1', 'lastname' => 'User1'));
         $sender2 = $this->getDataGenerator()->create_user(array('firstname' => 'Test3', 'lastname' => 'User3'));
         $recipient = $this->getDataGenerator()->create_user(array('firstname' => 'Test2', 'lastname' => 'User2'));
@@ -76,7 +76,7 @@ class core_message_api_testcase extends core_message_messagelib_testcase {
         $this->assertEquals(message_count_unread_messages($recipient), 6);
     }
 
-    public function test_message_mark_all_read_for_user_touser_with_type() {
+    public function test_mark_all_read_for_user_touser_with_type() {
         $sender = $this->getDataGenerator()->create_user(array('firstname' => 'Test1', 'lastname' => 'User1'));
         $recipient = $this->getDataGenerator()->create_user(array('firstname' => 'Test2', 'lastname' => 'User2'));
 
@@ -96,9 +96,8 @@ class core_message_api_testcase extends core_message_messagelib_testcase {
 
     /**
      * Test count_blocked_users.
-     *
      */
-    public function test_message_count_blocked_users() {
+    public function test_count_blocked_users() {
         // Set this user as the admin.
         $this->setAdminUser();
 
@@ -115,4 +114,734 @@ class core_message_api_testcase extends core_message_messagelib_testcase {
         $this->assertEquals(0, \core_message\api::count_blocked_users($user2));
         $this->assertEquals(1, \core_message\api::count_blocked_users());
     }
+
+    /**
+     * Tests searching users in a course.
+     */
+    public function test_search_users_in_course() {
+        // Create some users.
+        $user1 = new stdClass();
+        $user1->firstname = 'User';
+        $user1->lastname = 'One';
+        $user1 = self::getDataGenerator()->create_user($user1);
+
+        // The person doing the search.
+        $this->setUser($user1);
+
+        // Second user is going to have their last access set to now, so they are online.
+        $user2 = new stdClass();
+        $user2->firstname = 'User';
+        $user2->lastname = 'Two';
+        $user2->lastaccess = time();
+        $user2 = self::getDataGenerator()->create_user($user2);
+
+        // Block the second user.
+        message_block_contact($user2->id, $user1->id);
+
+        $user3 = new stdClass();
+        $user3->firstname = 'User';
+        $user3->lastname = 'Three';
+        $user3 = self::getDataGenerator()->create_user($user3);
+
+        // Create a course.
+        $course1 = new stdClass();
+        $course1->fullname = 'Course';
+        $course1->shortname = 'One';
+        $course1 = $this->getDataGenerator()->create_course($course1);
+
+        // Enrol the searcher and one user in the course.
+        $this->getDataGenerator()->enrol_user($user1->id, $course1->id);
+        $this->getDataGenerator()->enrol_user($user2->id, $course1->id);
+
+        // Perform a search.
+        $results = \core_message\api::search_users_in_course($user1->id, $course1->id, 'User');
+
+        $this->assertEquals(1, count($results));
+
+        $user = $results[0];
+        $this->assertEquals($user2->id, $user->userid);
+        $this->assertEquals(fullname($user2), $user->fullname);
+        $this->assertFalse($user->ismessaging);
+        $this->assertNull($user->lastmessage);
+        $this->assertNull($user->messageid);
+        $this->assertTrue($user->isonline);
+        $this->assertFalse($user->isread);
+        $this->assertTrue($user->isblocked);
+        $this->assertNull($user->unreadcount);
+    }
+
+    /**
+     * Tests searching users.
+     */
+    public function test_search_users() {
+        // Create some users.
+        $user1 = new stdClass();
+        $user1->firstname = 'User';
+        $user1->lastname = 'One';
+        $user1 = self::getDataGenerator()->create_user($user1);
+
+        // Set as the user performing the search.
+        $this->setUser($user1);
+
+        $user2 = new stdClass();
+        $user2->firstname = 'User search';
+        $user2->lastname = 'Two';
+        $user2 = self::getDataGenerator()->create_user($user2);
+
+        $user3 = new stdClass();
+        $user3->firstname = 'User search';
+        $user3->lastname = 'Three';
+        $user3 = self::getDataGenerator()->create_user($user3);
+
+        $user4 = new stdClass();
+        $user4->firstname = 'User';
+        $user4->lastname = 'Four';
+        $user4 = self::getDataGenerator()->create_user($user4);
+
+        $user5 = new stdClass();
+        $user5->firstname = 'User search';
+        $user5->lastname = 'Five';
+        $user5 = self::getDataGenerator()->create_user($user5);
+
+        $user6 = new stdClass();
+        $user6->firstname = 'User';
+        $user6->lastname = 'Six';
+        $user6 = self::getDataGenerator()->create_user($user6);
+
+        // Create some courses.
+        $course1 = new stdClass();
+        $course1->fullname = 'Course search';
+        $course1->shortname = 'One';
+        $course1 = $this->getDataGenerator()->create_course($course1);
+
+        $course2 = new stdClass();
+        $course2->fullname = 'Course';
+        $course2->shortname = 'Two';
+        $course2 = $this->getDataGenerator()->create_course($course2);
+
+        $course3 = new stdClass();
+        $course3->fullname = 'Course';
+        $course3->shortname = 'Three search';
+        $course3 = $this->getDataGenerator()->create_course($course3);
+
+        // Add some users as contacts.
+        message_add_contact($user2->id, 0, $user1->id);
+        message_add_contact($user3->id, 0, $user1->id);
+        message_add_contact($user4->id, 0, $user1->id);
+
+        // Perform a search.
+        list($contacts, $courses, $noncontacts) = \core_message\api::search_users($user1->id, 'search');
+
+        // Check that we retrieved the correct contacts.
+        $this->assertEquals(2, count($contacts));
+        $this->assertEquals($user3->id, $contacts[0]->userid);
+        $this->assertEquals($user2->id, $contacts[1]->userid);
+
+        // Check that we retrieved the correct courses.
+        $this->assertEquals(2, count($courses));
+        $this->assertEquals($course3->id, $courses[0]->id);
+        $this->assertEquals($course1->id, $courses[1]->id);
+
+        // Check that we retrieved the correct non-contacts.
+        $this->assertEquals(1, count($noncontacts));
+        $this->assertEquals($user5->id, $noncontacts[0]->userid);
+    }
+
+    /**
+     * Tests searching messages.
+     */
+    public function test_search_messages() {
+        // Create some users.
+        $user1 = self::getDataGenerator()->create_user();
+        $user2 = self::getDataGenerator()->create_user();
+
+        // The person doing the search.
+        $this->setUser($user1);
+
+        // Send some messages back and forth.
+        $time = 1;
+        $this->send_fake_message($user1, $user2, 'Yo!', 0, $time);
+        $this->send_fake_message($user2, $user1, 'Sup mang?', 0, $time + 1);
+        $this->send_fake_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 2);
+        $this->send_fake_message($user2, $user1, 'Word.', 0, $time + 3);
+
+        // Perform a search.
+        $messages = \core_message\api::search_messages($user1->id, 'o');
+
+        // Confirm the data is correct.
+        $this->assertEquals(2, count($messages));
+
+        $message1 = $messages[0];
+        $message2 = $messages[1];
+
+        $this->assertEquals($user2->id, $message1->userid);
+        $this->assertEquals($user2->id, $message1->useridfrom);
+        $this->assertEquals(fullname($user2), $message1->fullname);
+        $this->assertTrue($message1->ismessaging);
+        $this->assertEquals('Word.', $message1->lastmessage);
+        $this->assertNotEmpty($message1->messageid);
+        $this->assertFalse($message1->isonline);
+        $this->assertFalse($message1->isread);
+        $this->assertFalse($message1->isblocked);
+        $this->assertNull($message1->unreadcount);
+
+        $this->assertEquals($user2->id, $message2->userid);
+        $this->assertEquals($user1->id, $message2->useridfrom);
+        $this->assertEquals(fullname($user2), $message2->fullname);
+        $this->assertTrue($message2->ismessaging);
+        $this->assertEquals('Yo!', $message2->lastmessage);
+        $this->assertNotEmpty($message2->messageid);
+        $this->assertFalse($message2->isonline);
+        $this->assertTrue($message2->isread);
+        $this->assertFalse($message2->isblocked);
+        $this->assertNull($message2->unreadcount);
+    }
+
+    /**
+     * Tests retrieving conversations.
+     */
+    public function test_get_conversations() {
+        // Create some users.
+        $user1 = self::getDataGenerator()->create_user();
+        $user2 = self::getDataGenerator()->create_user();
+        $user3 = self::getDataGenerator()->create_user();
+        $user4 = self::getDataGenerator()->create_user();
+
+        // The person doing the search.
+        $this->setUser($user1);
+
+        // Send some messages back and forth, have some different conversations with different users.
+        $time = 1;
+        $this->send_fake_message($user1, $user2, 'Yo!', 0, $time + 1);
+        $this->send_fake_message($user2, $user1, 'Sup mang?', 0, $time + 2);
+        $this->send_fake_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 3);
+        $this->send_fake_message($user2, $user1, 'Word.', 0, $time + 4);
+
+        $this->send_fake_message($user1, $user3, 'Booyah', 0, $time + 5);
+        $this->send_fake_message($user3, $user1, 'Whaaat?', 0, $time + 6);
+        $this->send_fake_message($user1, $user3, 'Nothing.', 0, $time + 7);
+        $this->send_fake_message($user3, $user1, 'Cool.', 0, $time + 8);
+
+        $this->send_fake_message($user1, $user4, 'Hey mate, you see the new messaging UI in Moodle?', 0, $time + 9);
+        $this->send_fake_message($user4, $user1, 'Yah brah, it\'s pretty rad.', 0, $time + 10);
+        $this->send_fake_message($user1, $user4, 'Dope.', 0, $time + 11);
+
+        // Retrieve the conversations.
+        $conversations = \core_message\api::get_conversations($user1->id);
+
+        // Confirm the data is correct.
+        $this->assertEquals(3, count($conversations));
+
+        $message1 = array_shift($conversations);
+        $message2 = array_shift($conversations);
+        $message3 = array_shift($conversations);
+
+        $this->assertEquals($user4->id, $message1->userid);
+        $this->assertEquals($user1->id, $message1->useridfrom);
+        $this->assertTrue($message1->ismessaging);
+        $this->assertEquals('Dope.', $message1->lastmessage);
+        $this->assertNull($message1->messageid);
+        $this->assertFalse($message1->isonline);
+        $this->assertTrue($message1->isread);
+        $this->assertFalse($message1->isblocked);
+        $this->assertEquals(0, $message1->unreadcount);
+
+        $this->assertEquals($user3->id, $message2->userid);
+        $this->assertEquals($user3->id, $message2->useridfrom);
+        $this->assertTrue($message2->ismessaging);
+        $this->assertEquals('Cool.', $message2->lastmessage);
+        $this->assertNull($message2->messageid);
+        $this->assertFalse($message2->isonline);
+        $this->assertFalse($message2->isread);
+        $this->assertFalse($message2->isblocked);
+        $this->assertEquals(2, $message2->unreadcount);
+
+        $this->assertEquals($user2->id, $message3->userid);
+        $this->assertEquals($user2->id, $message3->useridfrom);
+        $this->assertTrue($message3->ismessaging);
+        $this->assertEquals('Word.', $message3->lastmessage);
+        $this->assertNull($message3->messageid);
+        $this->assertFalse($message3->isonline);
+        $this->assertFalse($message3->isread);
+        $this->assertFalse($message3->isblocked);
+        $this->assertEquals(2, $message3->unreadcount);
+    }
+
+    /**
+     * Tests retrieving contacts.
+     */
+    public function test_get_contacts() {
+        // Create some users.
+        $user1 = self::getDataGenerator()->create_user();
+
+        // Set as the user.
+        $this->setUser($user1);
+
+        $user2 = new stdClass();
+        $user2->firstname = 'User';
+        $user2->lastname = 'A';
+        $user2 = self::getDataGenerator()->create_user($user2);
+
+        $user3 = new stdClass();
+        $user3->firstname = 'User';
+        $user3->lastname = 'B';
+        $user3 = self::getDataGenerator()->create_user($user3);
+
+        $user4 = new stdClass();
+        $user4->firstname = 'User';
+        $user4->lastname = 'C';
+        $user4 = self::getDataGenerator()->create_user($user4);
+
+        $user5 = new stdClass();
+        $user5->firstname = 'User';
+        $user5->lastname = 'D';
+        $user5 = self::getDataGenerator()->create_user($user5);
+
+        // Add some users as contacts.
+        message_add_contact($user2->id, 0, $user1->id);
+        message_add_contact($user3->id, 0, $user1->id);
+        message_add_contact($user4->id, 0, $user1->id);
+
+        // Retrieve the contacts.
+        $contacts = \core_message\api::get_contacts($user1->id);
+
+        // Confirm the data is correct.
+        $this->assertEquals(3, count($contacts));
+
+        $contact1 = $contacts[0];
+        $contact2 = $contacts[1];
+        $contact3 = $contacts[2];
+
+        $this->assertEquals($user2->id, $contact1->userid);
+        $this->assertEmpty($contact1->useridfrom);
+        $this->assertFalse($contact1->ismessaging);
+        $this->assertNull($contact1->lastmessage);
+        $this->assertNull($contact1->messageid);
+        $this->assertFalse($contact1->isonline);
+        $this->assertFalse($contact1->isread);
+        $this->assertFalse($contact1->isblocked);
+        $this->assertNull($contact1->unreadcount);
+
+        $this->assertEquals($user3->id, $contact2->userid);
+        $this->assertEmpty($contact2->useridfrom);
+        $this->assertFalse($contact2->ismessaging);
+        $this->assertNull($contact2->lastmessage);
+        $this->assertNull($contact2->messageid);
+        $this->assertFalse($contact2->isonline);
+        $this->assertFalse($contact2->isread);
+        $this->assertFalse($contact2->isblocked);
+        $this->assertNull($contact2->unreadcount);
+
+        $this->assertEquals($user4->id, $contact3->userid);
+        $this->assertEmpty($contact3->useridfrom);
+        $this->assertFalse($contact3->ismessaging);
+        $this->assertNull($contact3->lastmessage);
+        $this->assertNull($contact3->messageid);
+        $this->assertFalse($contact3->isonline);
+        $this->assertFalse($contact3->isread);
+        $this->assertFalse($contact3->isblocked);
+        $this->assertNull($contact3->unreadcount);
+    }
+
+    /**
+     * Tests retrieving messages.
+     */
+    public function test_get_messages() {
+        // Create some users.
+        $user1 = self::getDataGenerator()->create_user();
+        $user2 = self::getDataGenerator()->create_user();
+
+        // The person doing the search.
+        $this->setUser($user1);
+
+        // Send some messages back and forth.
+        $time = 1;
+        $this->send_fake_message($user1, $user2, 'Yo!', 0, $time + 1);
+        $this->send_fake_message($user2, $user1, 'Sup mang?', 0, $time + 2);
+        $this->send_fake_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 3);
+        $this->send_fake_message($user2, $user1, 'Word.', 0, $time + 4);
+
+        // Retrieve the messages.
+        $messages = \core_message\api::get_messages($user1->id, $user2->id);
+
+        // Confirm the message data is correct.
+        $this->assertEquals(4, count($messages));
+
+        $message1 = $messages[0];
+        $message2 = $messages[1];
+        $message3 = $messages[2];
+        $message4 = $messages[3];
+
+        $this->assertEquals($user1->id, $message1->useridfrom);
+        $this->assertEquals($user2->id, $message1->useridto);
+        $this->assertTrue($message1->displayblocktime);
+        $this->assertContains('Yo!', $message1->text);
+
+        $this->assertEquals($user2->id, $message2->useridfrom);
+        $this->assertEquals($user1->id, $message2->useridto);
+        $this->assertFalse($message2->displayblocktime);
+        $this->assertContains('Sup mang?', $message2->text);
+
+        $this->assertEquals($user1->id, $message3->useridfrom);
+        $this->assertEquals($user2->id, $message3->useridto);
+        $this->assertFalse($message3->displayblocktime);
+        $this->assertContains('Writing PHPUnit tests!', $message3->text);
+
+        $this->assertEquals($user2->id, $message4->useridfrom);
+        $this->assertEquals($user1->id, $message4->useridto);
+        $this->assertFalse($message4->displayblocktime);
+        $this->assertContains('Word.', $message4->text);
+    }
+
+    /**
+     * Tests retrieving most recent message.
+     */
+    public function test_get_most_recent_message() {
+        // Create some users.
+        $user1 = self::getDataGenerator()->create_user();
+        $user2 = self::getDataGenerator()->create_user();
+
+        // The person doing the search.
+        $this->setUser($user1);
+
+        // Send some messages back and forth.
+        $time = 1;
+        $this->send_fake_message($user1, $user2, 'Yo!', 0, $time + 1);
+        $this->send_fake_message($user2, $user1, 'Sup mang?', 0, $time + 2);
+        $this->send_fake_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 3);
+        $this->send_fake_message($user2, $user1, 'Word.', 0, $time + 4);
+
+        // Retrieve the most recent messages.
+        $message = \core_message\api::get_most_recent_message($user1->id, $user2->id);
+
+        // Check the results are correct.
+        $this->assertEquals($user2->id, $message->useridfrom);
+        $this->assertEquals($user1->id, $message->useridto);
+        $this->assertContains('Word.', $message->text);
+    }
+
+    /**
+     * Tests retrieving a user's profile.
+     */
+    public function test_get_profile() {
+        // Create some users.
+        $user1 = self::getDataGenerator()->create_user();
+
+        $user2 = new stdClass();
+        $user2->country = 'AU';
+        $user2->city = 'Perth';
+        $user2 = self::getDataGenerator()->create_user($user2);
+
+        // The person doing the search.
+        $this->setUser($user1);
+
+        // Get the profile.
+        $profile = \core_message\api::get_profile($user1->id, $user2->id);
+
+        $this->assertEquals($user2->id, $profile->userid);
+        $this->assertEmpty($profile->email);
+        $this->assertEmpty($profile->country);
+        $this->assertEmpty($profile->city);
+        $this->assertEquals(fullname($user2), $profile->fullname);
+        $this->assertFalse($profile->isonline);
+        $this->assertFalse($profile->isblocked);
+        $this->assertFalse($profile->iscontact);
+    }
+
+    /**
+     * Tests retrieving a user's profile.
+     */
+    public function test_get_profile_as_admin() {
+        // The person doing the search.
+        $this->setAdminUser();
+
+        // Create some users.
+        $user1 = self::getDataGenerator()->create_user();
+
+        $user2 = new stdClass();
+        $user2->country = 'AU';
+        $user2->city = 'Perth';
+        $user2 = self::getDataGenerator()->create_user($user2);
+
+        // Get the profile.
+        $profile = \core_message\api::get_profile($user1->id, $user2->id);
+
+        $this->assertEquals($user2->id, $profile->userid);
+        $this->assertEquals($user2->email, $profile->email);
+        $this->assertEquals($user2->country, $profile->country);
+        $this->assertEquals($user2->city, $profile->city);
+        $this->assertEquals(fullname($user2), $profile->fullname);
+        $this->assertFalse($profile->isonline);
+        $this->assertFalse($profile->isblocked);
+        $this->assertFalse($profile->iscontact);
+    }
+
+    /**
+     * Tests checking if a user can delete a conversation.
+     */
+    public function test_can_delete_conversation() {
+        // Set as the admin.
+        $this->setAdminUser();
+
+        // Create some users.
+        $user1 = self::getDataGenerator()->create_user();
+        $user2 = self::getDataGenerator()->create_user();
+
+        // The admin can do anything.
+        $this->assertTrue(\core_message\api::can_delete_conversation($user1->id));
+
+        // Set as the user 1.
+        $this->setUser($user1);
+
+        // They can delete their own messages.
+        $this->assertTrue(\core_message\api::can_delete_conversation($user1->id));
+
+        // They can't delete someone elses.
+        $this->assertFalse(\core_message\api::can_delete_conversation($user2->id));
+    }
+
+    /**
+     * Tests deleting a conversation.
+     */
+    public function test_delete_conversation() {
+        global $DB;
+
+        // Create some users.
+        $user1 = self::getDataGenerator()->create_user();
+        $user2 = self::getDataGenerator()->create_user();
+
+        // The person doing the search.
+        $this->setUser($user1);
+
+        // Send some messages back and forth.
+        $time = 1;
+        $this->send_fake_message($user1, $user2, 'Yo!', 0, $time + 1);
+        $this->send_fake_message($user2, $user1, 'Sup mang?', 0, $time + 2);
+        $this->send_fake_message($user1, $user2, 'Writing PHPUnit tests!', 0, $time + 3);
+        $this->send_fake_message($user2, $user1, 'Word.', 0, $time + 4);
+
+        // Delete the conversation as user 1.
+        \core_message\api::delete_conversation($user1->id, $user2->id);
+
+        $messages = $DB->get_records('message', array(), 'timecreated ASC');
+        $this->assertCount(4, $messages);
+
+        $message1 = array_shift($messages);
+        $message2 = array_shift($messages);
+        $message3 = array_shift($messages);
+        $message4 = array_shift($messages);
+
+        $this->assertNotEmpty($message1->timeuserfromdeleted);
+        $this->assertEmpty($message1->timeusertodeleted);
+
+        $this->assertEmpty($message2->timeuserfromdeleted);
+        $this->assertNotEmpty($message2->timeusertodeleted);
+
+        $this->assertNotEmpty($message3->timeuserfromdeleted);
+        $this->assertEmpty($message3->timeusertodeleted);
+
+        $this->assertEmpty($message4->timeuserfromdeleted);
+        $this->assertNotEmpty($message4->timeusertodeleted);
+
+    }
+
+    /**
+     * Tests counting unread conversations.
+     */
+    public function test_count_unread_conversations() {
+        $this->resetAfterTest(true);
+
+        // Create some users.
+        $user1 = self::getDataGenerator()->create_user();
+        $user2 = self::getDataGenerator()->create_user();
+        $user3 = self::getDataGenerator()->create_user();
+        $user4 = self::getDataGenerator()->create_user();
+
+        // The person wanting the conversation count.
+        $this->setUser($user1);
+
+        // Send some messages back and forth, have some different conversations with different users.
+        $this->send_fake_message($user1, $user2, 'Yo!');
+        $this->send_fake_message($user2, $user1, 'Sup mang?');
+        $this->send_fake_message($user1, $user2, 'Writing PHPUnit tests!');
+        $this->send_fake_message($user2, $user1, 'Word.');
+
+        $this->send_fake_message($user1, $user3, 'Booyah');
+        $this->send_fake_message($user3, $user1, 'Whaaat?');
+        $this->send_fake_message($user1, $user3, 'Nothing.');
+        $this->send_fake_message($user3, $user1, 'Cool.');
+
+        $this->send_fake_message($user1, $user4, 'Hey mate, you see the new messaging UI in Moodle?');
+        $this->send_fake_message($user4, $user1, 'Yah brah, it\'s pretty rad.');
+        $this->send_fake_message($user1, $user4, 'Dope.');
+
+        // Check the amount for the current user.
+        $this->assertEquals(3, core_message\api::count_unread_conversations());
+
+        // Check the amount for the second user.
+        $this->assertEquals(1, core_message\api::count_unread_conversations($user2));
+    }
+
+    /**
+     * Tests deleting a conversation.
+     */
+    public function test_get_all_message_preferences() {
+        $user = self::getDataGenerator()->create_user();
+        $this->setUser($user);
+
+        // Set a couple of preferences to test.
+        set_user_preference('message_provider_mod_assign_assign_notification_loggedin', 'popup', $user);
+        set_user_preference('message_provider_mod_assign_assign_notification_loggedoff', 'email', $user);
+
+        $processors = get_message_processors();
+        $providers = message_get_providers_for_user($user->id);
+        $prefs = \core_message\api::get_all_message_preferences($processors, $providers, $user);
+
+        $this->assertEquals(1, $prefs->mod_assign_assign_notification_loggedin['popup']);
+        $this->assertEquals(1, $prefs->mod_assign_assign_notification_loggedoff['email']);
+    }
+
+    /**
+     * Tests the user can post a message.
+     */
+    public function test_can_post_message() {
+        // Create some users.
+        $user1 = self::getDataGenerator()->create_user();
+        $user2 = self::getDataGenerator()->create_user();
+
+        // Set as the user 1.
+        $this->setUser($user1);
+
+        // They can post to someone else.
+        $this->assertTrue(\core_message\api::can_post_message($user2));
+    }
+
+    /**
+     * Tests the user can't post a message without proper capability.
+     */
+    public function test_can_post_message_without_cap() {
+        global $DB;
+
+        // Create some users.
+        $user1 = self::getDataGenerator()->create_user();
+        $user2 = self::getDataGenerator()->create_user();
+
+        // Set as the user 1.
+        $this->setUser($user1);
+
+        // Remove the capability to send a message.
+        $roleids = $DB->get_records_menu('role', null, '', 'shortname, id');
+        unassign_capability('moodle/site:sendmessage', $roleids['user'],
+            context_system::instance());
+
+        // Check that we can not post a message without the capability.
+        $this->assertFalse(\core_message\api::can_post_message($user2));
+    }
+
+    /**
+     * Tests the user can't post a message if they are not a contact and the user
+     * has requested messages only from contacts.
+     */
+    public function test_can_post_message_when_not_contact() {
+        // Create some users.
+        $user1 = self::getDataGenerator()->create_user();
+        $user2 = self::getDataGenerator()->create_user();
+
+        // Set as the first user.
+        $this->setUser($user1);
+
+        // Set the second user's preference to not receive messages from non-contacts.
+        set_user_preference('message_blocknoncontacts', 1, $user2->id);
+
+        // Check that we can not send user 2 a message.
+        $this->assertFalse(\core_message\api::can_post_message($user2));
+    }
+
+    /**
+     * Tests the user can't post a message if they are blocked.
+     */
+    public function test_can_post_message_when_blocked() {
+        // Create some users.
+        $user1 = self::getDataGenerator()->create_user();
+        $user2 = self::getDataGenerator()->create_user();
+
+        // Set the user.
+        $this->setUser($user1);
+
+        // Block the second user.
+        message_block_contact($user2->id);
+
+        // Check that the second user can no longer send the first user a message.
+        $this->assertFalse(\core_message\api::can_post_message($user1, $user2));
+    }
+
+    /**
+     * Tests that when blocking messages from non-contacts is enabled that
+     * non-contacts trying to send a message return false.
+     */
+    public function test_is_user_non_contact_blocked() {
+        // Create some users.
+        $user1 = self::getDataGenerator()->create_user();
+        $user2 = self::getDataGenerator()->create_user();
+
+        // Set as the first user.
+        $this->setUser($user1);
+
+        // User hasn't sent their preference to block non-contacts, so should return false.
+        $this->assertFalse(\core_message\api::is_user_non_contact_blocked($user2));
+
+        // Set the second user's preference to not receive messages from non-contacts.
+        set_user_preference('message_blocknoncontacts', 1, $user2->id);
+
+        // Check that the return result is now true.
+        $this->assertTrue(\core_message\api::is_user_non_contact_blocked($user2));
+
+        // Add the first user as a contact for the second user.
+        message_add_contact($user1->id, 0, $user2->id);
+
+        // Check that the return result is now false.
+        $this->assertFalse(\core_message\api::is_user_non_contact_blocked($user2));
+    }
+
+    /**
+     * Tests that we return true when a user is blocked, or false
+     * if they are not blocked.
+     */
+    public function test_is_user_blocked() {
+        // Create some users.
+        $user1 = self::getDataGenerator()->create_user();
+        $user2 = self::getDataGenerator()->create_user();
+
+        // Set the user.
+        $this->setUser($user1);
+
+        // User shouldn't be blocked.
+        $this->assertFalse(\core_message\api::is_user_blocked($user1, $user2));
+
+        // Block the user.
+        message_block_contact($user2->id);
+
+        // User should be blocked.
+        $this->assertTrue(\core_message\api::is_user_blocked($user1, $user2));
+    }
+
+    /**
+     * Tests that the admin is not blocked even if someone has chosen to block them.
+     */
+    public function test_is_user_blocked_as_admin() {
+        // Create a user.
+        $user1 = self::getDataGenerator()->create_user();
+
+        // Set the user.
+        $this->setUser($user1);
+
+        // Block the admin user.
+        message_block_contact(2);
+
+        // Now change to the admin user.
+        $this->setAdminUser();
+
+        // As the admin you should still be able to send messages to the user.
+        $this->assertFalse(\core_message\api::is_user_blocked($user1));
+    }
 }
index 5fb3234..b9309f5 100644 (file)
@@ -304,4 +304,74 @@ class core_message_events_testcase extends advanced_testcase {
         $this->assertEquals($message->useridfrom, $event->other['useridfrom']);
         $this->assertEquals($message->useridto, $event->other['useridto']);
     }
+
+    /**
+     * Test the message deleted event is fired when deleting a conversation.
+     */
+    public function test_message_deleted_whole_conversation() {
+        global $DB;
+
+        // Create a message.
+        $message = new stdClass();
+        $message->useridfrom = '1';
+        $message->useridto = '2';
+        $message->subject = 'Subject';
+        $message->message = 'Message';
+        $message->timeuserfromdeleted = 0;
+        $message->timeusertodeleted = 0;
+        $message->timecreated = 1;
+
+        // Send this a few times.
+        $messageid1 = $DB->insert_record('message', $message);
+
+        $message->timecreated++;
+        $messageid2 = $DB->insert_record('message', $message);
+
+        $message->timecreated++;
+        $messageid3 = $DB->insert_record('message', $message);
+
+        $message->timecreated++;
+        $messageid4 = $DB->insert_record('message', $message);
+
+        // Create a read message.
+        $message->timeread = time();
+
+        // Send this a few times.
+        $message->timecreated++;
+        $messageid5 = $DB->insert_record('message_read', $message);
+
+        $message->timecreated++;
+        $messageid6 = $DB->insert_record('message_read', $message);
+
+        $message->timecreated++;
+        $messageid7 = $DB->insert_record('message_read', $message);
+
+        $message->timecreated++;
+        $messageid8 = $DB->insert_record('message_read', $message);
+
+        // Trigger and capture the event.
+        $sink = $this->redirectEvents();
+        \core_message\api::delete_conversation(1, 2);
+        $events = $sink->get_events();
+
+        // Check that there were the correct number of events triggered.
+        $this->assertEquals(8, count($events));
+
+        // Check that the event data is valid.
+        $i = 1;
+        foreach ($events as $event) {
+            $table = ($i > 4) ? 'message_read' : 'message';
+            $messageid = 'messageid' . $i;
+
+            $this->assertInstanceOf('\core\event\message_deleted', $event);
+            $this->assertEquals($message->useridfrom, $event->userid);
+            $this->assertEquals($message->useridto, $event->relateduserid);
+            $this->assertEquals($table, $event->other['messagetable']);
+            $this->assertEquals($$messageid, $event->other['messageid']);
+            $this->assertEquals($message->useridfrom, $event->other['useridfrom']);
+            $this->assertEquals($message->useridto, $event->other['useridto']);
+
+            $i++;
+        }
+    }
 }
index 337d846..bbdaf87 100644 (file)
@@ -63,18 +63,23 @@ class core_message_messagelib_testcase extends advanced_testcase {
      * @param stdClass $userto user object of the one receiving the message.
      * @param string $message message to send.
      * @param int $notification if the message is a notification.
+     * @param int $time the time the message was sent
      * @return int the id of the message
      */
-    protected function send_fake_message($userfrom, $userto, $message = 'Hello world!', $notification = 0) {
+    protected function send_fake_message($userfrom, $userto, $message = 'Hello world!', $notification = 0, $time = 0) {
         global $DB;
 
+        if (empty($time)) {
+            $time = time();
+        }
+
         $record = new stdClass();
         $record->useridfrom = $userfrom->id;
         $record->useridto = $userto->id;
         $record->subject = 'No subject';
         $record->fullmessage = $message;
         $record->smallmessage = $message;
-        $record->timecreated = time();
+        $record->timecreated = $time;
         $record->notification = $notification;
 
         return $DB->insert_record('message', $record);
diff --git a/pix/t/passwordunmask-edit.png b/pix/t/passwordunmask-edit.png
new file mode 100644 (file)
index 0000000..52d985c
Binary files /dev/null and b/pix/t/passwordunmask-edit.png differ
diff --git a/pix/t/passwordunmask-edit.svg b/pix/t/passwordunmask-edit.svg
new file mode 100644 (file)
index 0000000..0922939
--- /dev/null
@@ -0,0 +1,3 @@
+<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd" [\r
+       <!ENTITY ns_flows "http://ns.adobe.com/Flows/1.0/">\r
+]><svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 12 12" preserveAspectRatio="xMinYMid meet" overflow="visible"><path d="M5.2 11H12v1H4.2l1-1zm1.4-8.4L0 9.1V12h2.8l6.6-6.6-2.8-2.8zm4.8.8l-1 1-2.8-2.8 1-1c.8-.8 2.1-.8 2.8 0 .8.8.8 2 0 2.8z" fill="#999"/></svg>
\ No newline at end of file
diff --git a/pix/t/passwordunmask-reveal.png b/pix/t/passwordunmask-reveal.png
new file mode 100644 (file)
index 0000000..166e791
Binary files /dev/null and b/pix/t/passwordunmask-reveal.png differ
diff --git a/pix/t/passwordunmask-reveal.svg b/pix/t/passwordunmask-reveal.svg
new file mode 100644 (file)
index 0000000..64c1277
--- /dev/null
@@ -0,0 +1,3 @@
+<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd" [\r
+       <!ENTITY ns_flows "http://ns.adobe.com/Flows/1.0/">\r
+]><svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 12 12" preserveAspectRatio="xMinYMid meet" overflow="visible"><path d="M11.4 9.4L9.9 7.9c-.1-.1-.2-.1-.3-.2.4-.8.7-1.6.7-2.5C10.3 2.3 8 0 5.2 0 2.3 0 0 2.3 0 5.2s2.3 5.2 5.2 5.2c.9 0 1.7-.2 2.4-.6.1 0 .1.1.2.2l1.5 1.5c.6.6 1.5.6 2.1 0s.6-1.5 0-2.1zM5.2 7.3C4 7.3 3 6.4 3 5.2 3 4 4 3 5.2 3c1.2 0 2.2 1 2.2 2.2-.1 1.2-1 2.1-2.2 2.1z" fill="#999"/></svg>
\ No newline at end of file
index e488e3d..4ce0236 100644 (file)
@@ -272,8 +272,6 @@ case 'sign':
         echo '<form method="post">';
         echo '<input type="hidden" name="action" value="sign" />';
         echo '<input type="hidden" name="repo_id" value="'.s($repo_id).'" />';
-        // HACK to prevent browsers from automatically inserting the user's password into the wrong fields.
-        echo prevent_form_autofill_password();
         $repo->print_login();
         echo '</form>';
     }
index 50257d9..66d2e82 100644 (file)
@@ -107,7 +107,7 @@ class files_renderer extends \core_files_renderer {
      * @return string
      */
     protected function fp_js_template_loginform() {
-        return $this->render_from_template('core/filemanager_loginform', ['autofillhack' => prevent_form_autofill_password()]);
+        return $this->render_from_template('core/filemanager_loginform', []);
     }
 
     /**
index f92503e..fc90303 100644 (file)
                         position: relative;
 
                         .text {
+                            display: block;
+
                             p {
                                 margin: 0;
                             }
index 5de0b3f..e3c67cb 100644 (file)
@@ -14,7 +14,6 @@
                     <label class="form-control-label"></label>
                     <select class="form-control"></select>
                 </div>
-                {{{autofillhack}}}
                 <div class="fp-login-input form-group">
                     <label class="form-control-label"></label>
                     <input class="form-control"/>
@@ -27,4 +26,4 @@
             <p class="mdl-align"><button class="fp-login-submit btn-primary btn">{{#str}}submit, repository{{/str}}</button></p>
         </form>
     </div>
-</div>
\ No newline at end of file
+</div>
index b7e755c..d532554 100644 (file)
     along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
 }}
 {{!
-    Setting configpasswordunmask.
-}}
-<div class="form-password">
-    <input type="password" name="{{name}}" size="{{size}}" id="{{id}}" value="{{value}}" class="form-control d-inline-block">
-    <div class="unmask" id="{{id}}unmaskdiv"></div>
-</div>
-{{#js}}
-(function() {
-    var id = '{{id}}';
-    var unmaskid = id + 'unmask';
-    var unmaskdivid = id + 'unmaskdiv';
-    var unmaskstr = {{#quote}}{{#str}}unmaskpassword, form{{/str}}{{/quote}};
-    var is_ie = (navigator.userAgent.toLowerCase().indexOf("msie") != -1);
-
-    document.getElementById(id).setAttribute("autocomplete", "off");
+    @template core_admin/setting_configpasswordunmask
 
-    var unmaskdiv = document.getElementById(unmaskdivid);
+    Admin password unmask setting template.
 
-    var unmaskchb = document.createElement("input");
-    unmaskchb.setAttribute("type", "checkbox");
-    unmaskchb.setAttribute("id", unmaskid);
-    unmaskchb.onchange = function() {unmaskPassword(id);};
-    unmaskdiv.appendChild(unmaskchb);
+    Context variables required for this template:
+    * name - form element name
+    * size - form element size
+    * value - form element value
+    * id - element id
 
-    var unmasklbl = document.createElement("label");
-    unmasklbl.innerHTML = unmaskstr;
-    if (is_ie) {
-      unmasklbl.setAttribute("htmlFor", unmaskid);
-    } else {
-      unmasklbl.setAttribute("for", unmaskid);
+    Example context (json):
+    {
+        "name": "test",
+        "id": "test0",
+        "size": "8",
+        "value": "secret"
     }
-    unmaskdiv.appendChild(unmasklbl);
-
-    if (is_ie) {
-      // Ugly hack to work around the famous onchange IE bug.
-      unmaskchb.onclick = function() {this.blur();};
-      unmaskdiv.onclick = function() {this.blur();};
-    }
-})()
+}}
+<div class="form-password">
+    <span data-passwordunmask="wrapper" data-passwordunmaskid="{{ id }}">
+        <noscript>
+            <!-- Backwards compatability for Behat -->
+            <input  type="password"
+                    name="{{ name }}"
+                    id="{{ id }}"
+                    value="{{ value }}"
+                    size="{{ size }}"
+                    class="form-control d-inline-block"
+                    >
+        </noscript>
+        <span class="visibleifjs">
+            <span data-passwordunmask="editor">
+                <!-- The input in the noscript will be moved here as part of the page load -->
+            </span>
+            <a href="#" data-passwordunmask="edit" title="{{ edithint }}">
+                <span data-passwordunmask="displayvalue">{{> core_form/element-passwordunmask-fill }}</span>
+                {{# pix }} t/passwordunmask-edit, core, {{# str }} passwordunmaskedithint, form {{/ str }}{{/ pix }}
+            </a>
+            <a href="#" data-passwordunmask="unmask" title="{{ unmaskhint }}">
+                {{# pix }} t/passwordunmask-reveal, core, {{# str }} passwordunmaskrevealhint, form {{/ str }}{{/ pix }}
+            </a>
+            <span data-passwordunmask="instructions" class="form-text text-muted" style="display: none;">
+                {{# str }} passwordunmaskinstructions, form {{/ str }}
+            </span>
+        </span>
+    </span>
+</div>
+{{#js}}
+require(['core_form/passwordunmask'], function(PasswordUnmask) {
+    new PasswordUnmask("{{ id }}");
+});
 {{/js}}
index e971f03..1de9250 100644 (file)
@@ -24,7 +24,6 @@
         {{/params}}
         <input type="hidden" name="sesskey" value="{{sesskey}}">
         <input type="hidden" name="return" value="{{return}}">
-        {{>core/prevent_form_autofill_password}}
         {{#title}}
             <h2>{{title}}</h2>
         {{/title}}
index ce09da8..d5f0bc1 100644 (file)
@@ -20,7 +20,6 @@
 <form action="{{actionurl}}" method="post" id="adminsettings">
     <div>
         <input type="hidden" name="sesskey" value="{{sesskey}}">
-        {{>core/prevent_form_autofill_password}}
     </div>
     <fieldset>
         <div class="clearer"></div>
index a759af1..0c2e756 100644 (file)
@@ -1,12 +1,94 @@
-{{> core_form/element-password }}
-{{^element.frozen}}
+{{!
+    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/element-passwordunmask
+
+    Moodle passwordunmask form element template.
+
+    The purpose of this template is to render a passwordunmask form element.
+
+    Classes required for JS:
+    * none
+
+    Data attributes required for JS:
+    * none
+
+    Context variables required for this template:
+    * element
+        * id
+        * name
+        * value
+        * size
+
+    Example context (json):
+    {
+        "element": {
+            "id": "example_password_unmask",
+            "name": "example",
+            "value": "Password1!",
+            "size": 40
+        }
+    }
+
+}}
+{{< core_form/element-template }}
+    {{$ element }}
+        <span data-passwordunmask="wrapper" data-passwordunmaskid="{{ element.id }}">
+            <noscript>
+                <!-- Backwards compatability for Behat -->
+                <input  type="password"
+                        {{# element.frozen }}readonly{{/ element.frozen }}
+                        {{^ element.hardfrozen}} name="{{ element.name }}"{{/ element.hardfrozen }}
+                        id="{{ element.id }}"
+                        value="{{ element.value }}"
+                        class="form-control d-inline-block {{# error }}form-control-danger{{/ error }}"
+                        size="{{ element.size }}"
+                        {{# error }}
+                            autofocus aria-describedby="id_error_{{ element.name }}"
+                        {{/ error }}
+                        {{{ attributes }}}
+                        >
+            </noscript>
+            <span class="visibleifjs">
+                <span data-passwordunmask="editor">
+                    <!-- The input in the noscript will be moved here as part of the page load -->
+                </span>
+                {{^ element.frozen }}
+                <a href="#" data-passwordunmask="edit" title="{{ edithint }}">
+                {{/ element.frozen }}
+                    <span data-passwordunmask="displayvalue">{{> core_form/element-passwordunmask-fill }}</span>
+                {{^ element.frozen }}
+                    {{# pix }} t/passwordunmask-edit, core, {{# str }} passwordunmaskedithint, form {{/ str }}{{/ pix }}
+                </a>
+                {{/ element.frozen }}
+                <a href="#" data-passwordunmask="unmask" title="{{ unmaskhint }}">
+                    {{# pix }} t/passwordunmask-reveal, core, {{# str }} passwordunmaskrevealhint, form {{/ str }}{{/ pix }}
+                </a>
+                <span data-passwordunmask="instructions" class="form-text text-muted" style="display: none;">
+                    {{^ element.frozen }}
+                    {{# str }} passwordunmaskinstructions, form {{/ str }}
+                    {{/ element.frozen }}
+                </span>
+            </span>
+        </span>
+    {{/ element }}
+{{/ core_form/element-template }}
 {{#js}}
-require(['core/yui'], function(Y) {
-    Y.use('moodle-form-passwordunmask', function() {
-        M.form.passwordunmask({ formid: {{#quote}}{{element.id}}{{/quote}},
-                                checkboxlabel: {{#quote}}{{#str}}unmaskpassword, form{{/str}}{{/quote}},
-                                checkboxname: {{#quote}}{{element.name}}{{/quote}} });
-    });
+require(['core_form/passwordunmask'], function(PasswordUnmask) {
+    new PasswordUnmask("{{ element.id }}");
 });
-{{/js}}
-{{/element.frozen}}
+{{/ js }}
index a75cd9e..58d4801 100644 (file)
@@ -524,3 +524,9 @@ input[size] {
 textarea[data-auto-rows] {
     overflow-x: hidden;
 }
+
+div[data-passwordunmask="wrapper"] {
+    height: 30px;
+    line-height: 30px;
+    margin-bottom: 10px;
+}
index dcd99a3..57fe568 100644 (file)
                         position: relative;
 
                         .text {
+                            display: block;
+
                             p {
                                 margin: 0;
                             }
index 85dfe48..fe8f42d 100644 (file)
@@ -6195,6 +6195,9 @@ a.ygtvspacer:hover {
   border-radius: 4px;
   position: relative;
 }
+.messaging-area-container .messaging-area .messages-area .messages .message .content .text {
+  display: block;
+}
 .messaging-area-container .messaging-area .messages-area .messages .message .content .text p {
   margin: 0;
 }
@@ -14349,6 +14352,11 @@ input[size] {
 textarea[data-auto-rows] {
   overflow-x: hidden;
 }
+div[data-passwordunmask="wrapper"] {
+  height: 30px;
+  line-height: 30px;
+  margin-bottom: 10px;
+}
 body.modal-open {
   overflow: hidden;
 }