MDL-60817 file: Populate header only if exists
[moodle.git] / lib / form / filemanager.js
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.
12 //
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/>.
15 /**
16  *
17  * File Manager UI
18  * =====
19  * this.api, stores the URL to make ajax request
20  * this.currentpath
21  * this.filepicker_options
22  * this.movefile_dialog
23  * this.mkdir_dialog
24  * this.rename_dialog
25  * this.client_id
26  * this.filecount, how many files in this filemanager
27  * this.maxfiles
28  * this.maxbytes
29  * this.areamaxbytes, the maximum size of the area
30  * this.filemanager, contains reference to filemanager Node
31  * this.selectnode, contains referenct to select-file Node
32  * this.selectui, M.core.dialogue to select the file
33  * this.viewmode, contains current view mode - icons, tree or details
34  *
35  * FileManager options:
36  * =====
37  * this.options.currentpath
38  * this.options.itemid
39  */
42 M.form_filemanager = {templates:{}};
44 M.form_filemanager.set_templates = function(Y, templates) {
45     M.form_filemanager.templates = templates;
46 }
48 /**
49  * This fucntion is called for each file picker on page.
50  */
51 M.form_filemanager.init = function(Y, options) {
52     var FileManagerHelper = function(options) {
53         FileManagerHelper.superclass.constructor.apply(this, arguments);
54     };
55     FileManagerHelper.NAME = "FileManager";
56     FileManagerHelper.ATTRS = {
57         options: {},
58         lang: {}
59     };
61     Y.extend(FileManagerHelper, Y.Base, {
62         api: M.cfg.wwwroot+'/repository/draftfiles_ajax.php',
63         menus: {},
64         initializer: function(options) {
65             this.options = options;
66             if (options.mainfile) {
67                 this.enablemainfile = options.mainfile;
68             }
69             this.client_id = options.client_id;
70             this.currentpath = '/';
71             this.maxfiles = options.maxfiles;
72             this.maxbytes = options.maxbytes;
73             this.areamaxbytes = options.areamaxbytes;
74             this.userprefs = options.userprefs;
75             this.emptycallback = null; // Used by drag and drop upload
77             this.filepicker_options = options.filepicker?options.filepicker:{};
78             this.filepicker_options.client_id = this.client_id;
79             this.filepicker_options.context = options.context;
80             this.filepicker_options.maxfiles = this.maxfiles;
81             this.filepicker_options.maxbytes = this.maxbytes;
82             this.filepicker_options.areamaxbytes = this.areamaxbytes;
83             this.filepicker_options.env = 'filemanager';
84             this.filepicker_options.itemid = options.itemid;
86             if (options.filecount) {
87                 this.filecount = options.filecount;
88             } else {
89                 this.filecount = 0;
90             }
91             // prepare filemanager for drag-and-drop upload
92             this.filemanager = Y.one('#filemanager-'+options.client_id);
93             if (this.filemanager.hasClass('filemanager-container') || !this.filemanager.one('.filemanager-container')) {
94                 this.dndcontainer = this.filemanager;
95             } else  {
96                 this.dndcontainer = this.filemanager.one('.filemanager-container');
97                 if (!this.dndcontainer.get('id')) {
98                     this.dndcontainer.generateID();
99                 }
100             }
101             // save template for one path element and location of path bar
102             if (this.filemanager.one('.fp-path-folder')) {
103                 this.pathnode = this.filemanager.one('.fp-path-folder');
104                 this.pathbar = this.pathnode.get('parentNode');
105                 this.pathbar.removeChild(this.pathnode);
106             }
107             // initialize 'select file' panel
108             this.selectnode = Y.Node.create(M.form_filemanager.templates.fileselectlayout);
109             this.selectnode.setAttribute('aria-live', 'assertive');
110             this.selectnode.setAttribute('role', 'dialog');
111             this.selectnode.generateID();
113             var labelid = 'fm-dialog-label_'+ this.selectnode.get('id');
114             this.selectui = new M.core.dialogue({
115                 draggable    : true,
116                 headerContent: '<h3 id="' + labelid +'">' + M.util.get_string('edit', 'moodle') + '</h3>',
117                 bodyContent  : this.selectnode,
118                 centered     : true,
119                 width        : '480px',
120                 modal        : true,
121                 visible      : false
122             });
123             Y.one('#'+this.selectnode.get('id')).setAttribute('aria-labelledby', labelid);
124             this.selectui.hide();
125             this.setup_select_file();
126             // setup buttons onclick events
127             this.setup_buttons();
128             // set event handler for lazy loading of thumbnails
129             this.filemanager.one('.fp-content').on(['scroll','resize'], this.content_scrolled, this);
130             // display files
131             this.viewmode = this.get_preference("recentviewmode");
132             if (this.viewmode != 2 && this.viewmode != 3) {
133                 this.viewmode = 1;
134             }
135             var viewmodeselectors = {'1': '.fp-vb-icons', '2': '.fp-vb-tree', '3': '.fp-vb-details'};
136             this.filemanager.all('.fp-vb-icons,.fp-vb-tree,.fp-vb-details').removeClass('checked');
137             this.filemanager.all(viewmodeselectors[this.viewmode]).addClass('checked');
138             this.refresh(this.currentpath); // MDL-31113 get latest list from server
139         },
141         wait: function() {
142            this.filemanager.addClass('fm-updating');
143         },
144         request: function(args, redraw) {
145             var api = this.api + '?action='+args.action;
146             var params = {};
147             var scope = this;
148             if (args['scope']) {
149                 scope = args['scope'];
150             }
151             params['sesskey'] = M.cfg.sesskey;
152             params['client_id'] = this.client_id;
153             params['filepath'] = this.currentpath;
154             params['itemid'] = this.options.itemid?this.options.itemid:0;
155             if (args['params']) {
156                 for (i in args['params']) {
157                     params[i] = args['params'][i];
158                 }
159             }
160             var cfg = {
161                 method: 'POST',
162                 on: {
163                     complete: function(id,o,p) {
164                         if (!o) {
165                             alert('IO FATAL');
166                             return;
167                         }
168                         var data = null;
169                         try {
170                             data = Y.JSON.parse(o.responseText);
171                         } catch(e) {
172                             scope.print_msg(M.util.get_string('invalidjson', 'repository'), 'error');
173                             Y.error(M.util.get_string('invalidjson', 'repository')+":\n"+o.responseText);
174                             return;
175                         }
176                         if (data && data.tree && scope.set_current_tree) {
177                             scope.set_current_tree(data.tree);
178                         }
179                         args.callback(id,data,p);
180                     }
181                 },
182                 arguments: {
183                     scope: scope
184                 },
185                 headers: {
186                     'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
187                 },
188                 data: build_querystring(params)
189             };
190             if (args.form) {
191                 cfg.form = args.form;
192             }
193             Y.io(api, cfg);
194             if (redraw) {
195                 this.wait();
196             }
197         },
198         filepicker_callback: function(obj) {
199             this.filecount++;
200             this.check_buttons();
201             this.refresh(this.currentpath);
202             if (typeof M.core_formchangechecker != 'undefined') {
203                 M.core_formchangechecker.set_form_changed();
204             }
205         },
206         check_buttons: function() {
207             if (this.filecount>0) {
208                 this.filemanager.removeClass('fm-nofiles');
209             } else {
210                 this.filemanager.addClass('fm-nofiles');
211             }
212             if (this.filecount >= this.maxfiles && this.maxfiles!=-1) {
213                 this.filemanager.addClass('fm-maxfiles');
214             }
215             else {
216                 this.filemanager.removeClass('fm-maxfiles');
217             }
218         },
219         refresh: function(filepath) {
220             var scope = this;
221             this.currentpath = filepath;
222             if (!filepath) {
223                 filepath = this.currentpath;
224             } else {
225                 this.currentpath = filepath;
226             }
227             this.request({
228                 action: 'list',
229                 scope: scope,
230                 params: {'filepath':filepath},
231                 callback: function(id, obj, args) {
232                     scope.filecount = obj.filecount;
233                     scope.options = obj;
234                     scope.lazyloading = {};
235                     scope.check_buttons();
236                     scope.render(obj);
237                 }
238             }, true);
239         },
240         /** displays message in a popup */
241         print_msg: function(msg, type) {
242             var header = M.util.get_string('error', 'moodle');
243             if (type != 'error') {
244                 type = 'info'; // one of only two types excepted
245                 header = M.util.get_string('info', 'moodle');
246             }
247             if (!this.msg_dlg) {
248                 this.msg_dlg_node = Y.Node.create(M.form_filemanager.templates.message);
249                 var nodeid = this.msg_dlg_node.generateID();
251                 this.msg_dlg = new M.core.dialogue({
252                     draggable    : true,
253                     bodyContent  : this.msg_dlg_node,
254                     centered     : true,
255                     modal        : true,
256                     visible      : false,
257                 });
258                 this.msg_dlg_node.one('.fp-msg-butok').on('click', function(e) {
259                     e.preventDefault();
260                     this.msg_dlg.hide();
261                 }, this);
262             }
264             this.msg_dlg.set('headerContent', header);
265             this.msg_dlg_node.removeClass('fp-msg-info').removeClass('fp-msg-error').addClass('fp-msg-'+type)
266             this.msg_dlg_node.one('.fp-msg-text').setContent(Y.Escape.html(msg));
267             this.msg_dlg.show();
268         },
269         is_disabled: function() {
270             return this.filemanager.ancestor('.fitem.disabled') != null;
271         },
272         getSelectedFiles: function() {
273             var markedFiles = this.filemanager.all('[data-togglegroup=file-selections]:checked');
274             var filenames = [];
275             markedFiles.each(function(item) {
276                 var fileinfo = this.options.list.find(function(element) {
277                     return item.getData().fullname == element.fullname;
278                 });
279                 if (fileinfo && fileinfo != undefined) {
280                     filenames.push({
281                         filepath: fileinfo.filepath,
282                         filename: fileinfo.filename
283                     });
284                 }
285             }, this);
287             return filenames;
288         },
289         setup_buttons: function() {
290             var button_download = this.filemanager.one('.fp-btn-download');
291             var button_create   = this.filemanager.one('.fp-btn-mkdir');
292             var button_addfile  = this.filemanager.one('.fp-btn-add');
293             var buttonDeleteFile = this.filemanager.one('.fp-btn-delete');
295             // setup 'add file' button
296             button_addfile.on('click', this.show_filepicker, this);
298             var dndarrow = this.filemanager.one('.dndupload-arrow');
299             if (dndarrow) {
300                 dndarrow.on('click', this.show_filepicker, this);
301             }
303             // setup 'make a folder' button
304             if (this.options.subdirs) {
305                 button_create.on('click',function(e) {
306                     e.preventDefault();
307                     if (this.is_disabled()) {
308                         return;
309                     }
310                     var scope = this;
311                     // a function used to perform an ajax request
312                     var perform_action = function(e) {
313                         e.preventDefault();
314                         var foldername = Y.one('#fm-newname-'+scope.client_id).get('value');
315                         if (!foldername) {
316                             scope.mkdir_dialog.hide();
317                             return;
318                         }
319                         scope.request({
320                             action:'mkdir',
321                             params: {filepath:scope.currentpath, newdirname:foldername},
322                             callback: function(id, obj, args) {
323                                 var filepath = obj.filepath;
324                                 scope.mkdir_dialog.hide();
325                                 scope.refresh(filepath);
326                                 Y.one('#fm-newname-'+scope.client_id).set('value', '');
327                                 if (typeof M.core_formchangechecker != 'undefined') {
328                                     M.core_formchangechecker.set_form_changed();
329                                 }
330                             }
331                         });
332                     };
333                     var validate_folder_name = function() {
334                         var valid = false;
335                         var foldername = Y.one('#fm-newname-'+scope.client_id).get('value');
336                         if (foldername.length > 0) {
337                             valid = true;
338                         }
339                         var btn = Y.one('#fm-mkdir-butcreate-'+scope.client_id);
340                         if (btn) {
341                             btn.set('disabled', !valid);
342                         }
343                         return valid;
344                     };
345                     if (!this.mkdir_dialog) {
346                         var node = Y.Node.create(M.form_filemanager.templates.mkdir);
347                         this.mkdir_dialog = new M.core.dialogue({
348                             draggable    : true,
349                             bodyContent  : node,
350                             centered     : true,
351                             modal        : true,
352                             visible      : false,
353                         });
354                         node.one('.fp-dlg-butcreate').set('id', 'fm-mkdir-butcreate-'+this.client_id).on('click',
355                                 perform_action, this);
356                         node.one('input').set('id', 'fm-newname-'+this.client_id).on('keydown', function(e) {
357                             var valid = Y.bind(validate_folder_name, this)();
358                             if (valid && e.keyCode === 13) {
359                                 Y.bind(perform_action, this)(e);
360                             }
361                         }, this);
362                         node.one('#fm-newname-'+this.client_id).on(['keyup', 'change'], function(e) {
363                             Y.bind(validate_folder_name, this)();
364                         }, this);
366                         node.one('label').set('for', 'fm-newname-' + this.client_id);
367                         node.all('.fp-dlg-butcancel').on('click', function(e){e.preventDefault();this.mkdir_dialog.hide();}, this);
368                         node.all('.fp-dlg-curpath').set('id', 'fm-curpath-'+this.client_id);
369                     }
370                     this.mkdir_dialog.show();
372                     // Default folder name:
373                     var foldername = M.util.get_string('newfolder', 'repository');
374                     while (this.has_folder(foldername)) {
375                         foldername = increment_filename(foldername, true);
376                     }
377                     Y.one('#fm-newname-'+scope.client_id).set('value', foldername);
378                     Y.bind(validate_folder_name, this)();
379                     Y.one('#fm-newname-'+scope.client_id).focus().select();
380                     Y.all('#fm-curpath-'+scope.client_id).setContent(this.currentpath);
381                 }, this);
382             } else {
383                 this.filemanager.addClass('fm-nomkdir');
384             }
386             // setup 'download this folder' button
387             button_download.on('click',function(e) {
388                 e.preventDefault();
389                 if (this.is_disabled()) {
390                     return;
391                 }
392                 var scope = this;
394                 var image_downloading = this.filemanager.one('.fp-img-downloading');
395                 if (image_downloading.getStyle('display') == 'inline') {
396                     return;
397                 }
398                 image_downloading.setStyle('display', 'inline');
399                 var filenames = this.getSelectedFiles();
401                 // perform downloaddir ajax request
402                 this.request({
403                     action: 'downloadselected',
404                     scope: scope,
405                     params: {selected: Y.JSON.stringify(filenames)},
406                     callback: function(id, obj, args) {
407                         var image_downloading = scope.filemanager.one('.fp-img-downloading');
408                         image_downloading.setStyle('display', 'none');
410                         if (obj) {
411                             scope.refresh(obj.filepath);
412                             node = Y.Node.create('<iframe></iframe>').setStyles({
413                                 visibility : 'hidden',
414                                 width : '1px',
415                                 height : '1px'
416                             });
417                             node.set('src', obj.fileurl);
418                             Y.one('body').appendChild(node);
419                         } else {
420                             scope.print_msg(M.util.get_string('draftareanofiles', 'repository'), 'error');
421                         }
422                     }
423                 });
424             }, this);
426             buttonDeleteFile.on('click', function(e) {
427                 e.preventDefault();
428                 var dialogOptions = {};
429                 var filenames = this.getSelectedFiles();
431                 if (!filenames.length) {
432                     this.print_msg(M.util.get_string('nofilesselected', 'repository'), 'error');
433                     return;
434                 }
436                 dialogOptions.scope = this;
437                 var params = {
438                     selected: Y.JSON.stringify(filenames)
439                 };
440                 dialogOptions.header = M.util.get_string('confirm', 'moodle');
441                 dialogOptions.message = M.util.get_string('confirmdeleteselectedfile', 'repository', filenames.length);
442                 dialogOptions.callbackargs = [params];
443                 dialogOptions.callback = function(params) {
444                     this.request({
445                         action: 'deleteselected',
446                         scope: this,
447                         params: params,
448                         callback: function(id, obj, args) {
449                             // Do something here
450                             args.scope.filecount -= params.length;
451                             if (obj && obj.length) {
452                                 args.scope.refresh(obj[0]);
453                             }
454                             if (typeof M.core_formchangechecker != 'undefined') {
455                                 M.core_formchangechecker.set_form_changed();
456                             }
457                         }
458                     });
459                 };
460                 this.show_confirm_dialog(dialogOptions);
461             }, this);
463             this.filemanager.all('.fp-vb-icons,.fp-vb-tree,.fp-vb-details').
464                 on('click', function(e) {
465                     e.preventDefault();
466                     var viewbar = this.filemanager.one('.fp-viewbar')
467                     if (!this.is_disabled() && (!viewbar || !viewbar.hasClass('disabled'))) {
468                         this.filemanager.all('.fp-vb-icons,.fp-vb-tree,.fp-vb-details').removeClass('checked')
469                         if (e.currentTarget.hasClass('fp-vb-tree')) {
470                             this.viewmode = 2;
471                         } else if (e.currentTarget.hasClass('fp-vb-details')) {
472                             this.viewmode = 3;
473                         } else {
474                             this.viewmode = 1;
475                         }
476                         e.currentTarget.addClass('checked')
477                         this.render();
478                         this.filemanager.one('.fp-content').setAttribute('tabIndex', '0');
479                         this.filemanager.one('.fp-content').focus();
480                         this.set_preference('recentviewmode', this.viewmode);
481                     }
482                 }, this);
483         },
485         show_filepicker: function (e) {
486             // if maxfiles == -1, the no limit
487             e.preventDefault();
488             if (this.is_disabled()) {
489                 return;
490             }
491             var options = this.filepicker_options;
492             options.formcallback = this.filepicker_callback;
493             // XXX: magic here, to let filepicker use filemanager scope
494             options.magicscope = this;
495             options.savepath = this.currentpath;
496             M.core_filepicker.show(Y, options);
497         },
499         print_path: function() {
500             var p = this.options.path;
501             this.pathbar.setContent('').addClass('empty');
502             if (p && p.length!=0 && this.viewmode != 2) {
503                 for(var i = 0; i < p.length; i++) {
504                     var el = this.pathnode.cloneNode(true);
505                     this.pathbar.appendChild(el);
507                     if (i == 0) {
508                         el.addClass('first');
509                     }
510                     if (i == p.length-1) {
511                         el.addClass('last');
512                     }
514                     if (i%2) {
515                         el.addClass('even');
516                     } else {
517                         el.addClass('odd');
518                     }
519                     el.one('.fp-path-folder-name').setContent(Y.Escape.html(p[i].name)).
520                         on('click', function(e, path) {
521                             e.preventDefault();
522                             if (!this.is_disabled()) {
523                                 this.refresh(path);
524                             }
525                         }, this, p[i].path);
526                 }
527                 this.pathbar.removeClass('empty');
528             }
529         },
530         get_filepath: function(obj) {
531             if (obj.path && obj.path.length) {
532                 return obj.path[obj.path.length-1].path;
533             }
534             return '';
535         },
536         treeview_dynload: function(node, cb) {
537             var retrieved_children = {};
538             if (node.children) {
539                 for (var i in node.children) {
540                     retrieved_children[node.children[i].path] = node.children[i];
541                 }
542             }
543             if (!node.path || node.path == '/') {
544                 // this is a root pseudo folder
545                 node.fileinfo.filepath = '/';
546                 node.fileinfo.type = 'folder';
547                 node.fileinfo.fullname = node.fileinfo.title;
548                 node.fileinfo.filename = '.';
549             }
550             this.request({
551                 action:'list',
552                 params: {filepath:node.path?node.path:''},
553                 scope:this,
554                 callback: function(id, obj, args) {
555                     var list = obj.list;
556                     var scope = args.scope;
557                     // check that user did not leave the view mode before recieving this response
558                     if (!(scope.viewmode == 2 && node && node.getChildrenEl())) {
559                         return;
560                     }
561                     if (cb != null) { // (in manual mode do not update current path)
562                         scope.options = obj;
563                         scope.currentpath = node.path?node.path:'/';
564                     }
565                     node.highlight(false);
566                     node.origlist = obj.list ? obj.list : null;
567                     node.origpath = obj.path ? obj.path : null;
568                     node.children = [];
569                     for(k in list) {
570                         if (list[k].type == 'folder' && retrieved_children[list[k].filepath]) {
571                             // if this child is a folder and has already been retrieved
572                             retrieved_children[list[k].filepath].fileinfo = list[k];
573                             node.children[node.children.length] = retrieved_children[list[k].filepath];
574                         } else {
575                             // append new file to the list
576                             scope.view_files([list[k]]);
577                         }
578                     }
579                     if (cb == null) {
580                         node.refresh();
581                     } else {
582                         // invoke callback requested by TreeView component
583                         cb();
584                     }
585                     scope.content_scrolled();
586                 }
587             }, false);
588         },
589         content_scrolled: function(e) {
590             setTimeout(Y.bind(function() {
591                 if (this.processingimages) {return;}
592                 this.processingimages = true;
593                 var scope = this,
594                     fpcontent = this.filemanager.one('.fp-content'),
595                     fpcontenty = fpcontent.getY(),
596                     fpcontentheight = fpcontent.getStylePx('height'),
597                     is_node_visible = function(node) {
598                         var offset = node.getY()-fpcontenty;
599                         if (offset <= fpcontentheight && (offset >=0 || offset+node.getStylePx('height')>=0)) {
600                             return true;
601                         }
602                         return false;
603                     };
604                 // replace src for visible images that need to be lazy-loaded
605                 if (scope.lazyloading) {
606                     fpcontent.all('img').each( function(node) {
607                         if (node.get('id') && scope.lazyloading[node.get('id')] && is_node_visible(node)) {
608                             node.setImgRealSrc(scope.lazyloading);
609                         }
610                     });
611                 }
612                 this.processingimages = false;
613             }, this), 200)
614         },
615         view_files: function(appendfiles) {
616             this.filemanager.removeClass('fm-updating').removeClass('fm-noitems');
617             if ((appendfiles == null) && (!this.options.list || this.options.list.length == 0) && this.viewmode != 2) {
618                 this.filemanager.addClass('fm-noitems');
619                 return;
620             }
621             var list = (appendfiles != null) ? appendfiles : this.options.list;
622             var element_template;
623             if (this.viewmode == 2 || this.viewmode == 3) {
624                 element_template = Y.Node.create(M.form_filemanager.templates.listfilename);
625             } else {
626                 this.viewmode = 1;
627                 element_template = Y.Node.create(M.form_filemanager.templates.iconfilename);
628             }
630             if (this.viewmode == 1 || this.viewmode == 2) {
631                 this.filemanager.one('.fp-btn-delete').addClass('d-none');
632             } else {
633                 this.filemanager.one('.fp-btn-delete').removeClass('d-none');
634             }
635             var options = {
636                 viewmode : this.viewmode,
637                 appendonly : appendfiles != null,
638                 filenode : element_template,
639                 disablecheckboxes: false,
640                 callbackcontext : this,
641                 callback : function(e, node) {
642                     if (e.preventDefault) { e.preventDefault(); }
643                     if (node.type == 'folder') {
644                         this.refresh(node.filepath);
645                     } else {
646                         this.select_file(node);
647                     }
648                 },
649                 rightclickcallback : function(e, node) {
650                     if (e.preventDefault) { e.preventDefault(); }
651                     this.select_file(node);
652                 },
653                 classnamecallback : function(node) {
654                     var classname = '';
655                     if (node.type == 'folder' || (!node.type && !node.filename)) {
656                         classname = classname + ' fp-folder';
657                     }
658                     if (node.filename || node.filepath || (node.path && node.path != '/')) {
659                         classname = classname + ' fp-hascontextmenu';
660                     }
661                     if (node.isref) {
662                         classname = classname + ' fp-isreference';
663                     }
664                     if (node.refcount) {
665                         classname = classname + ' fp-hasreferences';
666                     }
667                     if (node.originalmissing) {
668                         classname = classname + ' fp-originalmissing';
669                     }
670                     if (node.sortorder == 1) { classname = classname + ' fp-mainfile';}
671                     return Y.Lang.trim(classname);
672                 }
673             };
674             if (this.viewmode == 2) {
675                 options.dynload = true;
676                 options.filepath = this.options.path;
677                 options.treeview_dynload = this.treeview_dynload;
678                 options.norootrightclick = true;
679                 options.callback = function(e, node) {
680                     // TODO MDL-32736 e is not an event here but an object with properties 'event' and 'node'
681                     if (!node.fullname) {return;}
682                     if (node.type != 'folder') {
683                         if (e.node.parent && e.node.parent.origpath) {
684                             // set the current path
685                             this.options.path = e.node.parent.origpath;
686                             this.options.list = e.node.parent.origlist;
687                             this.print_path();
688                         }
689                         this.currentpath = node.filepath;
690                         this.select_file(node);
691                     } else {
692                         // save current path and filelist (in case we want to jump to other viewmode)
693                         this.options.path = e.node.origpath;
694                         this.options.list = e.node.origlist;
695                         this.currentpath = node.filepath;
696                         this.print_path();
697                         //this.content_scrolled();
698                     }
699                 };
700             }
701             if (!this.lazyloading) {
702                 this.lazyloading={};
703             }
704             this.filemanager.one('.fp-content').fp_display_filelist(options, list, this.lazyloading);
705             this.content_scrolled();
706         },
707         populate_licenses_select: function(node) {
708             if (!node) {
709                 return;
710             }
711             node.setContent('');
712             var licenses = this.options.licenses;
713             for (var i in licenses) {
714                 var option = Y.Node.create('<option/>').
715                     set('value', licenses[i].shortname).
716                     setContent(Y.Escape.html(licenses[i].fullname));
717                 node.appendChild(option)
718             }
719         },
720         set_current_tree: function(tree) {
721             var appendfilepaths = function(list, node) {
722                 if (!node || !node.children || !node.children.length) {return;}
723                 for (var i in node.children) {
724                     list[list.length] = node.children[i].filepath;
725                     appendfilepaths(list, node.children[i]);
726                 }
727             }
728             var list = ['/'];
729             appendfilepaths(list, tree);
730             var selectnode = this.selectnode;
731             node = selectnode.one('.fp-path select');
732             node.setContent('');
733             for (var i in list) {
734                 node.appendChild(Y.Node.create('<option/>').
735                     set('value', list[i]).setContent(Y.Escape.html(list[i])));
736             }
737         },
738         update_file: function(confirmed) {
739             var selectnode = this.selectnode;
740             var fileinfo = this.selectui.fileinfo;
742             var newfilename = Y.Lang.trim(selectnode.one('.fp-saveas input').get('value'));
743             var filenamechanged = (newfilename && newfilename != fileinfo.fullname);
744             var pathselect = selectnode.one('.fp-path select'),
745                     pathindex = pathselect.get('selectedIndex'),
746                     targetpath = pathselect.get("options").item(pathindex).get('value');
747             var filepathchanged = (targetpath != this.get_parent_folder_name(fileinfo));
748             var newauthor = Y.Lang.trim(selectnode.one('.fp-author input').get('value'));
749             var authorchanged = (newauthor != Y.Lang.trim(fileinfo.author));
750             var licenseselect = selectnode.one('.fp-license select'),
751                     licenseindex = licenseselect.get('selectedIndex'),
752                     newlicense = licenseselect.get("options").item(licenseindex).get('value');
753             var licensechanged = (newlicense != fileinfo.license);
755             var params, action;
756             var dialog_options = {callback:this.update_file, callbackargs:[true], scope:this};
757             if (fileinfo.type == 'folder') {
758                 if (!newfilename) {
759                     this.print_msg(M.util.get_string('entername', 'repository'), 'error');
760                     return;
761                 }
762                 if (filenamechanged || filepathchanged) {
763                     if (!confirmed) {
764                         dialog_options.message = M.util.get_string('confirmrenamefolder', 'repository');
765                         this.show_confirm_dialog(dialog_options);
766                         return;
767                     }
768                     params = {filepath:fileinfo.filepath, newdirname:newfilename, newfilepath:targetpath};
769                     action = 'updatedir';
770                 }
771             } else {
772                 if (!newfilename) {
773                     this.print_msg(M.util.get_string('enternewname', 'repository'), 'error');
774                     return;
775                 }
777                 if ((filenamechanged || filepathchanged) && !confirmed) {
778                     var warnings = '';
779                     var originalfilenamearr = fileinfo.fullname.split('.');
780                     var originalextension = (originalfilenamearr.length > 1) ? originalfilenamearr.pop() : "";
781                     var newfilenamearr = newfilename.split('.');
782                     var newextension = (newfilenamearr.length > 1) ? newfilenamearr.pop() : "";
784                     if (newextension !== originalextension) {
785                         if (newextension === "") {
786                             var string = M.util.get_string('originalextensionremove', 'repository', originalextension);
787                         } else {
788                             var stringvars = {
789                                 originalextension: originalextension,
790                                 newextension: newextension
791                             }
792                             string = M.util.get_string('originalextensionchange', 'repository', stringvars);
793                         }
794                         warnings = warnings.concat('<li>', string, '</li>');
795                     }
796                     if (fileinfo.refcount) {
797                         var string = M.util.get_string('aliaseschange', 'repository', fileinfo.refcount);
798                         warnings = warnings.concat('<li>', string, '</li>');
799                     }
800                     if (warnings.length > 0) {
801                         var message = '';
802                         var confirmmsg = M.util.get_string('confirmrenamefile', 'repository', fileinfo.refcount);
803                         dialog_options.message = message.concat('<p>', confirmmsg, '</p>',
804                             '<ul class="p-x-2">', warnings, '</ul>');
805                         this.show_confirm_dialog(dialog_options);
806                         return;
807                     }
808                 }
809                 if (filenamechanged || filepathchanged || licensechanged || authorchanged) {
810                     params = {filepath:fileinfo.filepath, filename:fileinfo.fullname,
811                         newfilename:newfilename, newfilepath:targetpath,
812                         newlicense:newlicense, newauthor:newauthor};
813                     action = 'updatefile';
814                 }
815             }
816             if (!action) {
817                 // no changes
818                 this.selectui.hide();
819                 return;
820             }
821             selectnode.addClass('loading');
822             this.request({
823                 action: action,
824                 scope: this,
825                 params: params,
826                 callback: function(id, obj, args) {
827                     if (obj.error) {
828                         selectnode.removeClass('loading');
829                         args.scope.print_msg(obj.error, 'error');
830                     } else {
831                         args.scope.selectui.hide();
832                         args.scope.refresh((obj && obj.filepath) ? obj.filepath : '/');
833                         if (typeof M.core_formchangechecker != 'undefined') {
834                             M.core_formchangechecker.set_form_changed();
835                         }
836                     }
837                 }
838             });
839         },
840         /**
841          * Displays a confirmation dialog
842          * Expected attributes in dialog_options: message, callback, callbackargs(optional), scope(optional)
843          */
844         show_confirm_dialog: function(dialog_options) {
845             // instead of M.util.show_confirm_dialog(e, dialog_options);
846             if (!this.confirm_dlg) {
847                 this.confirm_dlg_node = Y.Node.create(M.form_filemanager.templates.confirmdialog);
848                 var node = this.confirm_dlg_node;
849                 node.generateID();
850                 this.confirm_dlg = new M.core.dialogue({
851                     draggable    : true,
852                     bodyContent  : node,
853                     centered     : true,
854                     modal        : true,
855                     visible      : false,
856                     buttons      : {}
857                 });
858                 var handle_confirm = function(ev) {
859                     var dlgopt = this.confirm_dlg.dlgopt;
860                     ev.preventDefault();
861                     this.confirm_dlg.hide();
862                     if (dlgopt.callback) {
863                         if (dlgopt.callbackargs) {
864                             dlgopt.callback.apply(dlgopt.scope || this, dlgopt.callbackargs);
865                         } else {
866                             dlgopt.callback.apply(dlgopt.scope || this);
867                         }
868                     }
869                 }
870                 var handle_cancel = function(ev) {
871                     ev.preventDefault();
872                     this.confirm_dlg.hide();
873                 }
874                 node.one('.fp-dlg-butconfirm').on('click', handle_confirm, this);
875                 node.one('.fp-dlg-butcancel').on('click', handle_cancel, this);
876             }
877             this.confirm_dlg.dlgopt = dialog_options;
878             if (typeof dialog_options.header != 'undefined') {
879                 this.confirm_dlg.set('headerContent', dialog_options.header);
880             }
881             this.confirm_dlg_node.one('.fp-dlg-text').setContent(dialog_options.message);
882             this.confirm_dlg.show();
883         },
884         setup_select_file: function() {
885             var selectnode = this.selectnode;
886             var scope = this;
887             // bind labels with corresponding inputs
888             selectnode.all('.fp-saveas,.fp-path,.fp-author,.fp-license').each(function (node) {
889                 node.all('label').set('for', node.one('input,select').generateID());
890             });
891             this.populate_licenses_select(selectnode.one('.fp-license select'));
892             // register event on clicking buttons
893             selectnode.one('.fp-file-update').on('click', function(e) {
894                 e.preventDefault();
895                 this.update_file();
896             }, this);
897             selectnode.all('form input').on('key', function(e) {
898                 e.preventDefault();
899                 scope.update_file();
900             }, 'enter');
901             selectnode.one('.fp-file-download').on('click', function(e) {
902                 e.preventDefault();
903                 if (this.selectui.fileinfo.type != 'folder') {
904                     node = Y.Node.create('<iframe></iframe>').setStyles({
905                         visibility : 'hidden',
906                         width : '1px',
907                         height : '1px'
908                     });
909                     node.set('src', this.selectui.fileinfo.url);
910                     Y.one('body').appendChild(node);
911                 }
912             }, this);
913             selectnode.one('.fp-file-delete').on('click', function(e) {
914                 e.preventDefault();
915                 var dialog_options = {};
916                 var params = {};
917                 var fileinfo = this.selectui.fileinfo;
918                 dialog_options.scope = this;
919                 params.filepath = fileinfo.filepath;
920                 if (fileinfo.type == 'folder') {
921                     params.filename = '.';
922                     dialog_options.message = M.util.get_string('confirmdeletefolder', 'repository');
923                 } else {
924                     params.filename = fileinfo.fullname;
925                     if (fileinfo.refcount) {
926                         dialog_options.message = M.util.get_string('confirmdeletefilewithhref', 'repository', fileinfo.refcount);
927                     } else {
928                         dialog_options.message = M.util.get_string('confirmdeletefile', 'repository');
929                     }
930                 }
931                 dialog_options.callbackargs = [params];
932                 dialog_options.callback = function(params) {
933                     //selectnode.addClass('loading');
934                     this.request({
935                         action: 'delete',
936                         scope: this,
937                         params: params,
938                         callback: function(id, obj, args) {
939                             //args.scope.selectui.hide();
940                             args.scope.filecount--;
941                             args.scope.refresh(obj.filepath);
942                             if (typeof M.core_formchangechecker != 'undefined') {
943                                 M.core_formchangechecker.set_form_changed();
944                             }
945                         }
946                     });
947                 };
948                 this.selectui.hide(); // TODO remove this after confirm dialog is replaced with YUI3
949                 this.show_confirm_dialog(dialog_options);
950             }, this);
951             selectnode.one('.fp-file-zip').on('click', function(e) {
952                 e.preventDefault();
953                 var params = {};
954                 var fileinfo = this.selectui.fileinfo;
955                 if (fileinfo.type != 'folder') {
956                     // this button should not even be shown
957                     return;
958                 }
959                 params['filepath']   = fileinfo.filepath;
960                 params['filename']   = '.';
961                 selectnode.addClass('loading');
962                 this.request({
963                     action: 'zip',
964                     scope: this,
965                     params: params,
966                     callback: function(id, obj, args) {
967                         args.scope.selectui.hide();
968                         args.scope.refresh(obj.filepath);
969                     }
970                 });
971             }, this);
972             selectnode.one('.fp-file-unzip').on('click', function(e) {
973                 e.preventDefault();
974                 var params = {};
975                 var fileinfo = this.selectui.fileinfo;
976                 if (fileinfo.type != 'zip') {
977                     // this button should not even be shown
978                     return;
979                 }
980                 params['filepath'] = fileinfo.filepath;
981                 params['filename'] = fileinfo.fullname;
982                 selectnode.addClass('loading');
983                 this.request({
984                     action: 'unzip',
985                     scope: this,
986                     params: params,
987                     callback: function(id, obj, args) {
988                         args.scope.selectui.hide();
989                         args.scope.refresh(obj.filepath);
990                     }
991                 });
992             }, this);
993             selectnode.one('.fp-file-setmain').on('click', function(e) {
994                 e.preventDefault();
995                 var params = {};
996                 var fileinfo = this.selectui.fileinfo;
997                 if (!this.enablemainfile || fileinfo.type == 'folder') {
998                     // this button should not even be shown for folders or when mainfile is disabled
999                     return;
1000                 }
1001                 params['filepath'] = fileinfo.filepath;
1002                 params['filename'] = fileinfo.fullname;
1003                 selectnode.addClass('loading');
1004                 this.request({
1005                     action: 'setmainfile',
1006                     scope: this,
1007                     params: params,
1008                     callback: function(id, obj, args) {
1009                         args.scope.selectui.hide();
1010                         args.scope.refresh(fileinfo.filepath);
1011                     }
1012                 });
1013             }, this);
1014             selectnode.all('.fp-file-cancel').on('click', function(e) {
1015                 e.preventDefault();
1016                 // TODO if changed asked to confirm, the same with close button
1017                 this.selectui.hide();
1018             }, this);
1019             selectnode.all('.fp-file-update, .fp-file-download, .fp-file-delete, .fp-file-zip, .fp-file-unzip, ' +
1020                 '.fp-file-setmain, .fp-file-cancel').on('key', function(e) {
1021                     e.preventDefault();
1022                     this.simulate('click');
1023             }, 'enter');
1024         },
1025         get_parent_folder_name: function(node) {
1026             if (node.type != 'folder' || node.filepath.length < node.fullname.length+1) {
1027                 return node.filepath;
1028             }
1029             var basedir = node.filepath.substr(0, node.filepath.length - node.fullname.length - 1);
1030             var lastdir = node.filepath.substr(node.filepath.length - node.fullname.length - 2);
1031             if (lastdir == '/' + node.fullname + '/') {
1032                 return basedir;
1033             }
1034             return node.filepath;
1035         },
1036         select_file: function(node) {
1037             if (this.is_disabled()) {
1038                 return;
1039             }
1040             var selectnode = this.selectnode;
1041             selectnode.removeClass('loading').removeClass('fp-folder').
1042                 removeClass('fp-file').removeClass('fp-zip').removeClass('fp-cansetmain');
1043             if (node.type == 'folder' || node.type == 'zip') {
1044                 selectnode.addClass('fp-'+node.type);
1045             } else {
1046                 selectnode.addClass('fp-file');
1047             }
1048             if (this.enablemainfile && (node.sortorder != 1) && node.type == 'file') {
1049                 selectnode.addClass('fp-cansetmain');
1050             }
1051             this.selectui.fileinfo = node;
1052             selectnode.one('.fp-saveas input').set('value', node.fullname);
1053             var foldername = this.get_parent_folder_name(node);
1054             selectnode.all('.fp-author input').set('value', node.author ? node.author : '');
1055             selectnode.all('.fp-license select option[selected]').set('selected', false);
1056             selectnode.all('.fp-license select option[value='+node.license+']').set('selected', true);
1057             selectnode.all('.fp-path select option[selected]').set('selected', false);
1058             selectnode.all('.fp-path select option').each(function(el){
1059                 if (el.get('value') == foldername) {
1060                     el.set('selected', true);
1061                 }
1062             });
1063             selectnode.all('.fp-author input, .fp-license select').set('disabled',(node.type == 'folder')?'disabled':'');
1064             // display static information about a file (when known)
1065             var attrs = ['datemodified','datecreated','size','dimensions','original','reflist'];
1066             for (var i in attrs) {
1067                 if (selectnode.one('.fp-'+attrs[i])) {
1068                     var value = (node[attrs[i]+'_f']) ? node[attrs[i]+'_f'] : (node[attrs[i]] ? node[attrs[i]] : '');
1069                     // Escape if the attribute being evaluated is not for the list of reference files.
1070                     if (attrs[i] !== 'reflist') {
1071                         value = Y.Escape.html(value);
1072                     }
1073                     selectnode.one('.fp-'+attrs[i]).addClassIf('fp-unknown', ''+value == '')
1074                         .one('.fp-value').setContent(value);
1075                 }
1076             }
1077             // display thumbnail
1078             var imgnode = Y.Node.create('<img/>').
1079                 set('src', node.realthumbnail ? node.realthumbnail : node.thumbnail).
1080                 setStyle('maxHeight', ''+(node.thumbnail_height ? node.thumbnail_height : 90)+'px').
1081                 setStyle('maxWidth', ''+(node.thumbnail_width ? node.thumbnail_width : 90)+'px');
1082             selectnode.one('.fp-thumbnail').setContent('').appendChild(imgnode);
1083             // load original location if applicable
1084             if (node.isref && !node.original) {
1085                 selectnode.one('.fp-original').removeClass('fp-unknown').addClass('fp-loading');
1086                 this.request({
1087                     action: 'getoriginal',
1088                     scope: this,
1089                     params: {'filepath':node.filepath,'filename':node.fullname},
1090                     callback: function(id, obj, args) {
1091                         // check if we did not select another file meanwhile
1092                         var scope = args.scope;
1093                         if (scope.selectui.fileinfo && node &&
1094                                 scope.selectui.fileinfo.filepath == node.filepath &&
1095                                 scope.selectui.fileinfo.fullname == node.fullname) {
1096                             selectnode.one('.fp-original').removeClass('fp-loading');
1097                             if (obj.original) {
1098                                 node.original = obj.original;
1099                                 selectnode.one('.fp-original .fp-value').setContent(Y.Escape.html(node.original));
1100                             } else {
1101                                 selectnode.one('.fp-original .fp-value').setContent(M.util.get_string('unknownsource', 'repository'));
1102                             }
1103                         }
1104                     }
1105                 }, false);
1106             }
1107             // load references list if applicable
1108             selectnode.one('.fp-refcount').setContent(node.refcount ? M.util.get_string('referencesexist', 'repository', node.refcount) : '');
1109             if (node.refcount && !node.reflist) {
1110                 selectnode.one('.fp-reflist').removeClass('fp-unknown').addClass('fp-loading');
1111                 this.request({
1112                     action: 'getreferences',
1113                     scope: this,
1114                     params: {'filepath':node.filepath,'filename':node.fullname},
1115                     callback: function(id, obj, args) {
1116                         // check if we did not select another file meanwhile
1117                         var scope = args.scope;
1118                         if (scope.selectui.fileinfo && node &&
1119                                 scope.selectui.fileinfo.filepath == node.filepath &&
1120                                 scope.selectui.fileinfo.fullname == node.fullname) {
1121                             selectnode.one('.fp-reflist').removeClass('fp-loading');
1122                             if (obj.references) {
1123                                 node.reflist = '';
1124                                 for (var i in obj.references) {
1125                                     node.reflist += '<li>'+Y.Escape.html(obj.references[i])+'</li>';
1126                                 }
1127                                 selectnode.one('.fp-reflist .fp-value').setContent(node.reflist);
1128                             } else {
1129                                 selectnode.one('.fp-reflist .fp-value').setContent('');
1130                             }
1131                         }
1132                     }
1133                 }, false);
1134             }
1135             // update dialog header
1136             var nodename = node.fullname;
1137             // Limit the string length so it fits nicely on mobile devices
1138             var namelength = 50;
1139             if (nodename.length > namelength) {
1140                 nodename = nodename.substring(0, namelength) + '...';
1141             }
1142             Y.one('#fm-dialog-label_'+selectnode.get('id')).setContent(Y.Escape.html(M.util.get_string('edit', 'moodle')+' '+nodename));
1143             // show panel
1144             this.selectui.show();
1145             Y.one('#'+selectnode.get('id')).focus();
1146         },
1147         render: function() {
1148             this.print_path();
1149             this.view_files();
1150         },
1151         has_folder: function(foldername) {
1152             var element;
1153             for (var i in this.options.list) {
1154                 element = this.options.list[i];
1155                 if (element.type == 'folder' && element.fullname == foldername) {
1156                     return true;
1157                 }
1158             }
1159             return false;
1160         },
1161         get_preference: function(name) {
1162             if (this.userprefs[name]) {
1163                 return this.userprefs[name];
1164             } else {
1165                 return false;
1166             }
1167         },
1168         set_preference: function(name, value) {
1169             if (this.userprefs[name] != value) {
1170                 M.util.set_user_preference('filemanager_' + name, value);
1171                 this.userprefs[name] = value;
1172             }
1173         },
1174     });
1176     // finally init everything needed
1177     // hide loading picture, display filemanager interface
1178     var filemanager = Y.one('#filemanager-'+options.client_id);
1179     filemanager.removeClass('fm-loading').addClass('fm-loaded');
1181     var manager = new FileManagerHelper(options);
1182     var dndoptions = {
1183         filemanager: manager,
1184         acceptedtypes: options.filepicker.accepted_types,
1185         clientid: options.client_id,
1186         author: options.author,
1187         maxfiles: options.maxfiles,
1188         maxbytes: options.maxbytes,
1189         areamaxbytes: options.areamaxbytes,
1190         itemid: options.itemid,
1191         repositories: manager.filepicker_options.repositories,
1192         containerid: manager.dndcontainer.get('id'),
1193         contextid: options.context.id
1194     };
1195     M.form_dndupload.init(Y, dndoptions);
1196 };