MDL-62801 themes: Remove old mustache caches when new one generated
[moodle.git] / lib / amd / src / permissionmanager.js
blobdcd8712bbbb9b938c8717cd8209855db0e10705d
1 // This file is part of Moodle - http://moodle.org/
2 //
3 // Moodle is free software: you can redistribute it and/or modify
4 // it under the terms of the GNU General Public License as published by
5 // the Free Software Foundation, either version 3 of the License, or
6 // (at your option) any later version.
7 //
8 // Moodle is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11 // GNU General Public License for more details.
13 // You should have received a copy of the GNU General Public License
14 // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
16  * @package    core
17  * @class      permissionmanager
18  * @copyright  2015 Martin Mastny <mastnym@vscht.cz>
19  * @since      3.0
20  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
21  */
23  /**
24   * @module admin/permissionmanager
25   */
26 define(['jquery', 'core/config', 'core/notification', 'core/templates', 'core/yui'],
27     function($, config, notification, templates, Y) {
29      /**
30       * Used CSS selectors
31       * @access private
32       */
33     var SELECTORS = {
34         ADDROLE: 'a.allowlink, a.prohibitlink',
35         REMOVEROLE: 'a.preventlink, a.unprohibitlink',
36         UNPROHIBIT: 'a.unprohibitlink'
37         };
38     var rolesloadedevent = $.Event('rolesloaded');
39     var contextid;
40     var contextname;
41     var adminurl;
42     var overideableroles;
43     var panel = null;
45     /**
46      * Load all possible roles, which could be assigned from server
47      *
48      * @access private
49      * @method loadOverideableRoles
50      */
51     var loadOverideableRoles = function() {
52         var params = {
53             contextid: contextid,
54             getroles: 1,
55             sesskey: config.sesskey
56         };
58         // Need to tell jQuery to expect JSON as the content type may not be correct (MDL-55041).
59         $.post(adminurl + 'roles/ajax.php', params, null, 'json')
60             .done(function(data) {
61               try {
62                   overideableroles = data;
63                   loadOverideableRoles = function() {
64                       $('body').trigger(rolesloadedevent);
65                   };
66                   loadOverideableRoles();
67               } catch (err) {
68                   notification.exception(err);
69               }
70             })
71             .fail(function(jqXHR, status, error) {
72                 notification.exception(error);
73             });
74     };
76     /**
77      * Perform the UI changes after server change
78      *
79      * @access private
80      * @method changePermissions
81      * @param {JQuery} row
82      * @param {int} roleid
83      * @param {string} action
84      */
85     var changePermissions = function(row, roleid, action) {
86         var params = {
87             contextid: contextid,
88             roleid: roleid,
89             sesskey: M.cfg.sesskey,
90             action: action,
91             capability: row.data('name')
92         };
93         $.post(adminurl + 'roles/ajax.php', params, null, 'json')
94         .done(function(data) {
95             var action = data;
96             try {
97                 var templatedata = {rolename: overideableroles[roleid],
98                                     roleid: roleid,
99                                     adminurl: adminurl,
100                                     imageurl: M.util.image_url('t/delete', 'moodle')
101                                     };
102                 switch (action) {
103                     case 'allow':
104                         templatedata.spanclass = 'allowed';
105                         templatedata.linkclass = 'preventlink';
106                         templatedata.action = 'prevent';
107                         templatedata.icon = 't/delete';
108                         break;
109                     case 'prohibit':
110                         templatedata.spanclass = 'forbidden';
111                         templatedata.linkclass = 'unprohibitlink';
112                         templatedata.action = 'unprohibit';
113                         templatedata.icon = 't/delete';
114                         break;
115                     case 'prevent':
116                         row.find('a[data-role-id="' + roleid + '"]').first().closest('.allowed').remove();
117                         return;
118                     case 'unprohibit':
119                         row.find('a[data-role-id="' + roleid + '"]').first().closest('.forbidden').remove();
120                         return;
121                     default:
122                         return;
123                 }
124                 templates.render('core/permissionmanager_role', templatedata)
125                 .done(function(content) {
126                     if (action == 'allow') {
127                         $(content).insertBefore(row.find('.allowmore:first'));
128                     } else if (action == 'prohibit') {
129                         $(content).insertBefore(row.find('.prohibitmore:first'));
130                         // Remove allowed link
131                         var allowedLink = row.find('.allowedroles').first().find('a[data-role-id="' + roleid + '"]');
132                         if (allowedLink) {
133                             allowedLink.first().closest('.allowed').remove();
134                         }
135                     }
136                     panel.hide();
137                 })
138                 .fail(notification.exception);
139             } catch (err) {
140                 notification.exception(err);
141             }
142         })
143         .fail(function(jqXHR, status, error) {
144             notification.exception(error);
145         });
146     };
148     /**
149      * Prompts user for selecting a role which is permitted
150      *
151      * @access private
152      * @method handleAddRole
153      * @param {event} e
154      */
155     var handleAddRole = function(e) {
156         e.preventDefault();
158         // TODO: MDL-57778 Convert to core/modal.
159         Y.use('moodle-core-notification-dialogue', function() {
160             $('body').one('rolesloaded', function() {
161                 var link = $(e.currentTarget);
162                 var action = link.data('action');
163                 var row = link.closest('tr.rolecap');
164                 var confirmationDetails = {
165                     cap: row.data('humanname'),
166                     context: contextname
167                 };
168                 var message = M.util.get_string('role' + action + 'info', 'core_role', confirmationDetails);
169                 if (panel === null) {
170                     panel = new M.core.dialogue({
171                         draggable: true,
172                         modal: true,
173                         closeButton: true,
174                         width: '450px'
175                     });
176                 }
177                 panel.set('headerContent', M.util.get_string('role' + action + 'header', 'core_role'));
179                 var i, existingrolelinks;
181                 var roles = [];
182                 switch (action) {
183                     case 'allow':
184                         existingrolelinks = row.find(SELECTORS.REMOVEROLE);
185                         break;
186                     case 'prohibit':
187                         existingrolelinks = row.find(SELECTORS.UNPROHIBIT);
188                         break;
189                 }
190                 for (i in overideableroles) {
191                     var disabled = '';
192                     var disable = existingrolelinks.filter("[data-role-id='" + i + "']").length;
193                     if (disable) {
194                         disabled = 'disabled';
195                     }
196                     var roledetails = {roleid: i, rolename: overideableroles[i], disabled: disabled};
197                     roles.push(roledetails);
198                 }
200                 templates.render('core/permissionmanager_panelcontent', {message: message, roles: roles})
201                 .done(function(content) {
202                     panel.set('bodyContent', content);
203                     panel.show();
204                     $('div.role_buttons').delegate('input', 'click', function(e) {
205                         var roleid = $(e.currentTarget).data('role-id');
206                         changePermissions(row, roleid, action);
207                     });
208                 })
209                 .fail(notification.exception);
211             });
212         });
213         loadOverideableRoles();
214     };
216     /**
217      * Prompts user when removing permission
218      *
219      * @access private
220      * @method handleRemoveRole
221      * @param {event} e
222      */
223     var handleRemoveRole = function(e) {
224         e.preventDefault();
225         $('body').one('rolesloaded', function() {
226             var link = $(e.currentTarget);
227             var action = link.data('action');
228             var roleid = link.data('role-id');
229             var row = link.closest('tr.rolecap');
230             var questionDetails = {
231                 role: overideableroles[roleid],
232                 cap: row.data('humanname'),
233                 context: contextname
234             };
236             notification.confirm(M.util.get_string('confirmunassigntitle', 'core_role'),
237                 M.util.get_string('confirmrole' + action, 'core_role', questionDetails),
238                 M.util.get_string('confirmunassignyes', 'core_role'),
239                 M.util.get_string('confirmunassignno', 'core_role'),
240                 function() {
241                    changePermissions(row, roleid, action);
242                 }
243             );
244          });
245         loadOverideableRoles();
246     };
248     return /** @alias module:core/permissionmanager */ {
249         /**
250          * Initialize permissionmanager
251          * @access public
252          * @param {Object} args
253          */
254         initialize: function(args) {
255             contextid = args.contextid;
256             contextname = args.contextname;
257             adminurl = args.adminurl;
258             var body = $('body');
259             body.delegate(SELECTORS.ADDROLE, 'click', handleAddRole);
260             body.delegate(SELECTORS.REMOVEROLE, 'click', handleRemoveRole);
261         }
262     };