Merge branch 'MDL-37173-m' of git://github.com/andrewnicols/moodle
[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, YUI Panel to select the file
33  *
34  * FileManager options:
35  * =====
36  * this.options.currentpath
37  * this.options.itemid
38  */
41 M.form_filemanager = {templates:{}};
43 M.form_filemanager.set_templates = function(Y, templates) {
44     M.form_filemanager.templates = templates;
45 }
47 /**
48  * This fucntion is called for each file picker on page.
49  */
50 M.form_filemanager.init = function(Y, options) {
51     var FileManagerHelper = function(options) {
52         FileManagerHelper.superclass.constructor.apply(this, arguments);
53     };
54     FileManagerHelper.NAME = "FileManager";
55     FileManagerHelper.ATTRS = {
56         options: {},
57         lang: {}
58     };
60     Y.extend(FileManagerHelper, Y.Base, {
61         api: M.cfg.wwwroot+'/repository/draftfiles_ajax.php',
62         menus: {},
63         initializer: function(options) {
64             this.options = options;
65             if (options.mainfile) {
66                 this.enablemainfile = options.mainfile;
67             }
68             this.client_id = options.client_id;
69             this.currentpath = '/';
70             this.maxfiles = options.maxfiles;
71             this.maxbytes = options.maxbytes;
72             this.areamaxbytes = options.areamaxbytes;
73             this.emptycallback = null; // Used by drag and drop upload
75             this.filepicker_options = options.filepicker?options.filepicker:{};
76             this.filepicker_options.client_id = this.client_id;
77             this.filepicker_options.context = options.context;
78             this.filepicker_options.maxfiles = this.maxfiles;
79             this.filepicker_options.maxbytes = this.maxbytes;
80             this.filepicker_options.areamaxbytes = this.areamaxbytes;
81             this.filepicker_options.env = 'filemanager';
82             this.filepicker_options.itemid = options.itemid;
84             if (options.filecount) {
85                 this.filecount = options.filecount;
86             } else {
87                 this.filecount = 0;
88             }
89             // prepare filemanager for drag-and-drop upload
90             this.filemanager = Y.one('#filemanager-'+options.client_id);
91             if (this.filemanager.hasClass('filemanager-container') || !this.filemanager.one('.filemanager-container')) {
92                 this.dndcontainer = this.filemanager;
93             } else  {
94                 this.dndcontainer = this.filemanager.one('.filemanager-container');
95                 if (!this.dndcontainer.get('id')) {
96                     this.dndcontainer.generateID();
97                 }
98             }
99             // save template for one path element and location of path bar
100             if (this.filemanager.one('.fp-path-folder')) {
101                 this.pathnode = this.filemanager.one('.fp-path-folder');
102                 this.pathbar = this.pathnode.get('parentNode');
103                 this.pathbar.removeChild(this.pathnode);
104             }
105             // initialize 'select file' panel
106             this.selectnode = Y.Node.createWithFilesSkin(M.form_filemanager.templates.fileselectlayout);
107             this.selectnode.generateID();
108             this.selectui = new Y.Panel({
109                 srcNode      : this.selectnode,
110                 zIndex       : 7600,
111                 centered     : true,
112                 modal        : true,
113                 close        : true,
114                 render       : true
115             });
116             this.selectui.plug(Y.Plugin.Drag,{handles:['#'+this.selectnode.get('id')+' .yui3-widget-hd']});
117             this.selectui.hide();
118             this.setup_select_file();
119             // setup buttons onclick events
120             this.setup_buttons();
121             // set event handler for lazy loading of thumbnails
122             this.filemanager.one('.fp-content').on(['scroll','resize'], this.content_scrolled, this);
123             // display files
124             this.viewmode = 1; // TODO take from cookies?
125             this.filemanager.all('.fp-vb-icons,.fp-vb-tree,.fp-vb-details').removeClass('checked')
126             this.filemanager.all('.fp-vb-icons').addClass('checked')
127             this.refresh(this.currentpath); // MDL-31113 get latest list from server
128         },
130         wait: function() {
131            this.filemanager.addClass('fm-updating');
132         },
133         request: function(args, redraw) {
134             var api = this.api + '?action='+args.action;
135             var params = {};
136             var scope = this;
137             if (args['scope']) {
138                 scope = args['scope'];
139             }
140             params['sesskey'] = M.cfg.sesskey;
141             params['client_id'] = this.client_id;
142             params['filepath'] = this.currentpath;
143             params['itemid'] = this.options.itemid?this.options.itemid:0;
144             if (args['params']) {
145                 for (i in args['params']) {
146                     params[i] = args['params'][i];
147                 }
148             }
149             var cfg = {
150                 method: 'POST',
151                 on: {
152                     complete: function(id,o,p) {
153                         if (!o) {
154                             alert('IO FATAL');
155                             return;
156                         }
157                         var data = null;
158                         try {
159                             data = Y.JSON.parse(o.responseText);
160                         } catch(e) {
161                             scope.print_msg(M.str.repository.invalidjson, 'error');
162                             Y.error(M.str.repository.invalidjson+":\n"+o.responseText);
163                             return;
164                         }
165                         if (data && data.tree && scope.set_current_tree) {
166                             scope.set_current_tree(data.tree);
167                         }
168                         args.callback(id,data,p);
169                     }
170                 },
171                 arguments: {
172                     scope: scope
173                 },
174                 headers: {
175                     'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
176                 },
177                 data: build_querystring(params)
178             };
179             if (args.form) {
180                 cfg.form = args.form;
181             }
182             Y.io(api, cfg);
183             if (redraw) {
184                 this.wait();
185             }
186         },
187         filepicker_callback: function(obj) {
188             this.filecount++;
189             this.check_buttons();
190             this.refresh(this.currentpath);
191             if (typeof M.core_formchangechecker != 'undefined') {
192                 M.core_formchangechecker.set_form_changed();
193             }
194         },
195         check_buttons: function() {
196             if (this.filecount>0) {
197                 this.filemanager.removeClass('fm-nofiles');
198             } else {
199                 this.filemanager.addClass('fm-nofiles');
200             }
201             if (this.filecount >= this.maxfiles && this.maxfiles!=-1) {
202                 this.filemanager.addClass('fm-maxfiles');
203             }
204             else {
205                 this.filemanager.removeClass('fm-maxfiles');
206             }
207         },
208         refresh: function(filepath) {
209             var scope = this;
210             this.currentpath = filepath;
211             if (!filepath) {
212                 filepath = this.currentpath;
213             } else {
214                 this.currentpath = filepath;
215             }
216             this.request({
217                 action: 'list',
218                 scope: scope,
219                 params: {'filepath':filepath},
220                 callback: function(id, obj, args) {
221                     scope.filecount = obj.filecount;
222                     scope.options = obj;
223                     scope.lazyloading = {};
224                     scope.check_buttons();
225                     scope.render(obj);
226                 }
227             }, true);
228         },
229         /** displays message in a popup */
230         print_msg: function(msg, type) {
231             var header = M.str.moodle.error;
232             if (type != 'error') {
233                 type = 'info'; // one of only two types excepted
234                 header = M.str.moodle.info;
235             }
236             if (!this.msg_dlg) {
237                 this.msg_dlg_node = Y.Node.createWithFilesSkin(M.form_filemanager.templates.message);
238                 var nodeid = this.msg_dlg_node.generateID();
240                 this.msg_dlg = new Y.Panel({
241                     srcNode      : this.msg_dlg_node,
242                     zIndex       : 8000,
243                     centered     : true,
244                     modal        : true,
245                     visible      : false,
246                     render       : true
247                 });
248                 this.msg_dlg.plug(Y.Plugin.Drag,{handles:['#'+nodeid+' .yui3-widget-hd']});
249                 this.msg_dlg_node.one('.fp-msg-butok').on('click', function(e) {
250                     e.preventDefault();
251                     this.msg_dlg.hide();
252                 }, this);
253             }
255             this.msg_dlg.set('headerContent', header);
256             this.msg_dlg_node.removeClass('fp-msg-info').removeClass('fp-msg-error').addClass('fp-msg-'+type)
257             this.msg_dlg_node.one('.fp-msg-text').setContent(msg);
258             this.msg_dlg.show();
259         },
260         is_disabled: function() {
261             return this.filemanager.ancestor('.fitem.disabled') != null;
262         },
263         setup_buttons: function() {
264             var button_download = this.filemanager.one('.fp-btn-download');
265             var button_create   = this.filemanager.one('.fp-btn-mkdir');
266             var button_addfile  = this.filemanager.one('.fp-btn-add');
268             // setup 'add file' button
269             button_addfile.on('click', this.show_filepicker, this);
271             var dndarrow = this.filemanager.one('.dndupload-arrow');
272             if (dndarrow) {
273                 dndarrow.on('click', this.show_filepicker, this);
274             }
276             // setup 'make a folder' button
277             if (this.options.subdirs) {
278                 button_create.on('click',function(e) {
279                     e.preventDefault();
280                     if (this.is_disabled()) {
281                         return;
282                     }
283                     var scope = this;
284                     // a function used to perform an ajax request
285                     var perform_action = function(e) {
286                         e.preventDefault();
287                         var foldername = Y.one('#fm-newname-'+scope.client_id).get('value');
288                         if (!foldername) {
289                             scope.mkdir_dialog.hide();
290                             return;
291                         }
292                         scope.request({
293                             action:'mkdir',
294                             params: {filepath:scope.currentpath, newdirname:foldername},
295                             callback: function(id, obj, args) {
296                                 var filepath = obj.filepath;
297                                 scope.mkdir_dialog.hide();
298                                 scope.refresh(filepath);
299                                 Y.one('#fm-newname-'+scope.client_id).set('value', '');
300                                 if (typeof M.core_formchangechecker != 'undefined') {
301                                     M.core_formchangechecker.set_form_changed();
302                                 }
303                             }
304                         });
305                     }
306                     if (!this.mkdir_dialog) {
307                         var node = Y.Node.createWithFilesSkin(M.form_filemanager.templates.mkdir);
308                         this.mkdir_dialog = new Y.Panel({
309                             srcNode      : node,
310                             zIndex       : 8000,
311                             centered     : true,
312                             modal        : true,
313                             visible      : false,
314                             render       : true
315                         });
316                         this.mkdir_dialog.plug(Y.Plugin.Drag,{handles:['.yui3-widget-hd']});
317                         node.one('.fp-dlg-butcreate').on('click', perform_action, this);
318                         node.one('input').set('id', 'fm-newname-'+this.client_id).
319                             on('keydown', function(e){
320                                 if (e.keyCode == 13) {Y.bind(perform_action, this)(e);}
321                             }, this);
322                         node.all('.fp-dlg-butcancel').on('click', function(e){e.preventDefault();this.mkdir_dialog.hide();}, this);
323                         node.all('.fp-dlg-curpath').set('id', 'fm-curpath-'+this.client_id);
324                     }
325                     this.mkdir_dialog.show();
326                     Y.one('#fm-newname-'+scope.client_id).focus();
327                     Y.all('#fm-curpath-'+scope.client_id).setContent(this.currentpath)
328                 }, this);
329             } else {
330                 this.filemanager.addClass('fm-nomkdir');
331             }
333             // setup 'download this folder' button
334             button_download.on('click',function(e) {
335                 e.preventDefault();
336                 if (this.is_disabled()) {
337                     return;
338                 }
339                 var scope = this;
340                 // perform downloaddir ajax request
341                 this.request({
342                     action: 'downloaddir',
343                     scope: scope,
344                     callback: function(id, obj, args) {
345                         if (obj) {
346                             scope.refresh(obj.filepath);
347                             node = Y.Node.create('<iframe></iframe>').setStyles({
348                                 visibility : 'hidden',
349                                 width : '1px',
350                                 height : '1px'
351                             });
352                             node.set('src', obj.fileurl);
353                             Y.one('body').appendChild(node);
354                         } else {
355                             scope.print_msg(M.str.repository.draftareanofiles, 'error');
356                         }
357                     }
358                 });
359             }, this);
361             this.filemanager.all('.fp-vb-icons,.fp-vb-tree,.fp-vb-details').
362                 on('click', function(e) {
363                     e.preventDefault();
364                     var viewbar = this.filemanager.one('.fp-viewbar')
365                     if (!this.is_disabled() && (!viewbar || !viewbar.hasClass('disabled'))) {
366                         this.filemanager.all('.fp-vb-icons,.fp-vb-tree,.fp-vb-details').removeClass('checked')
367                         if (e.currentTarget.hasClass('fp-vb-tree')) {
368                             this.viewmode = 2;
369                         } else if (e.currentTarget.hasClass('fp-vb-details')) {
370                             this.viewmode = 3;
371                         } else {
372                             this.viewmode = 1;
373                         }
374                         e.currentTarget.addClass('checked')
375                         this.render();
376                     }
377                 }, this);
378         },
380         show_filepicker: function (e) {
381             // if maxfiles == -1, the no limit
382             e.preventDefault();
383             if (this.is_disabled()) {
384                 return;
385             }
386             var options = this.filepicker_options;
387             options.formcallback = this.filepicker_callback;
388             // XXX: magic here, to let filepicker use filemanager scope
389             options.magicscope = this;
390             options.savepath = this.currentpath;
391             M.core_filepicker.show(Y, options);
392         },
394         print_path: function() {
395             var p = this.options.path;
396             this.pathbar.setContent('').addClass('empty');
397             if (p && p.length!=0 && this.viewmode != 2) {
398                 for(var i = 0; i < p.length; i++) {
399                     var el = this.pathnode.cloneNode(true);
400                     this.pathbar.appendChild(el);
402                     if (i == 0) {
403                         el.addClass('first');
404                     }
405                     if (i == p.length-1) {
406                         el.addClass('last');
407                     }
409                     if (i%2) {
410                         el.addClass('even');
411                     } else {
412                         el.addClass('odd');
413                     }
414                     el.one('.fp-path-folder-name').setContent(p[i].name).
415                         on('click', function(e, path) {
416                             e.preventDefault();
417                             if (!this.is_disabled()) {
418                                 this.refresh(path);
419                             }
420                         }, this, p[i].path);
421                 }
422                 this.pathbar.removeClass('empty');
423             }
424         },
425         get_filepath: function(obj) {
426             if (obj.path && obj.path.length) {
427                 return obj.path[obj.path.length-1].path;
428             }
429             return '';
430         },
431         treeview_dynload: function(node, cb) {
432             var retrieved_children = {};
433             if (node.children) {
434                 for (var i in node.children) {
435                     retrieved_children[node.children[i].path] = node.children[i];
436                 }
437             }
438             if (!node.path || node.path == '/') {
439                 // this is a root pseudo folder
440                 node.fileinfo.filepath = '/';
441                 node.fileinfo.type = 'folder';
442                 node.fileinfo.fullname = node.fileinfo.title;
443                 node.fileinfo.filename = '.';
444             }
445             this.request({
446                 action:'list',
447                 params: {filepath:node.path?node.path:''},
448                 scope:this,
449                 callback: function(id, obj, args) {
450                     var list = obj.list;
451                     var scope = args.scope;
452                     // check that user did not leave the view mode before recieving this response
453                     if (!(scope.viewmode == 2 && node && node.getChildrenEl())) {
454                         return;
455                     }
456                     if (cb != null) { // (in manual mode do not update current path)
457                         scope.options = obj;
458                         scope.currentpath = node.path?node.path:'/';
459                     }
460                     node.highlight(false);
461                     node.origlist = obj.list ? obj.list : null;
462                     node.origpath = obj.path ? obj.path : null;
463                     node.children = [];
464                     for(k in list) {
465                         if (list[k].type == 'folder' && retrieved_children[list[k].filepath]) {
466                             // if this child is a folder and has already been retrieved
467                             retrieved_children[list[k].filepath].fileinfo = list[k];
468                             node.children[node.children.length] = retrieved_children[list[k].filepath];
469                         } else {
470                             // append new file to the list
471                             scope.view_files([list[k]]);
472                         }
473                     }
474                     if (cb == null) {
475                         node.refresh();
476                     } else {
477                         // invoke callback requested by TreeView component
478                         cb();
479                     }
480                     scope.content_scrolled();
481                 }
482             }, false);
483         },
484         content_scrolled: function(e) {
485             setTimeout(Y.bind(function() {
486                 if (this.processingimages) {return;}
487                 this.processingimages = true;
488                 var scope = this,
489                     fpcontent = this.filemanager.one('.fp-content'),
490                     fpcontenty = fpcontent.getY(),
491                     fpcontentheight = fpcontent.getStylePx('height'),
492                     is_node_visible = function(node) {
493                         var offset = node.getY()-fpcontenty;
494                         if (offset <= fpcontentheight && (offset >=0 || offset+node.getStylePx('height')>=0)) {
495                             return true;
496                         }
497                         return false;
498                     };
499                 // replace src for visible images that need to be lazy-loaded
500                 if (scope.lazyloading) {
501                     fpcontent.all('img').each( function(node) {
502                         if (node.get('id') && scope.lazyloading[node.get('id')] && is_node_visible(node)) {
503                             node.setImgRealSrc(scope.lazyloading);
504                         }
505                     });
506                 }
507                 this.processingimages = false;
508             }, this), 200)
509         },
510         view_files: function(appendfiles) {
511             this.filemanager.removeClass('fm-updating').removeClass('fm-noitems');
512             if ((appendfiles == null) && (!this.options.list || this.options.list.length == 0) && this.viewmode != 2) {
513                 this.filemanager.addClass('fm-noitems');
514                 return;
515             }
516             var list = (appendfiles != null) ? appendfiles : this.options.list;
517             var element_template;
518             if (this.viewmode == 2 || this.viewmode == 3) {
519                 element_template = Y.Node.create(M.form_filemanager.templates.listfilename);
520             } else {
521                 this.viewmode = 1;
522                 element_template = Y.Node.create(M.form_filemanager.templates.iconfilename);
523             }
524             var options = {
525                 viewmode : this.viewmode,
526                 appendonly : appendfiles != null,
527                 filenode : element_template,
528                 callbackcontext : this,
529                 callback : function(e, node) {
530                     if (e.preventDefault) { e.preventDefault(); }
531                     if (node.type == 'folder') {
532                         this.refresh(node.filepath);
533                     } else {
534                         this.select_file(node);
535                     }
536                 },
537                 rightclickcallback : function(e, node) {
538                     if (e.preventDefault) { e.preventDefault(); }
539                     this.select_file(node);
540                 },
541                 classnamecallback : function(node) {
542                     var classname = '';
543                     if (node.type == 'folder' || (!node.type && !node.filename)) {
544                         classname = classname + ' fp-folder';
545                     }
546                     if (node.filename || node.filepath || (node.path && node.path != '/')) {
547                         classname = classname + ' fp-hascontextmenu';
548                     }
549                     if (node.isref) {
550                         classname = classname + ' fp-isreference';
551                     }
552                     if (node.refcount) {
553                         classname = classname + ' fp-hasreferences';
554                     }
555                     if (node.originalmissing) {
556                         classname = classname + ' fp-originalmissing';
557                     }
558                     if (node.sortorder == 1) { classname = classname + ' fp-mainfile';}
559                     return Y.Lang.trim(classname);
560                 }
561             };
562             if (this.viewmode == 2) {
563                 options.dynload = true;
564                 options.filepath = this.options.path;
565                 options.treeview_dynload = this.treeview_dynload;
566                 options.norootrightclick = true;
567                 options.callback = function(e, node) {
568                     // TODO MDL-32736 e is not an event here but an object with properties 'event' and 'node'
569                     if (!node.fullname) {return;}
570                     if (node.type != 'folder') {
571                         if (e.node.parent && e.node.parent.origpath) {
572                             // set the current path
573                             this.options.path = e.node.parent.origpath;
574                             this.options.list = e.node.parent.origlist;
575                             this.print_path();
576                         }
577                         this.currentpath = node.filepath;
578                         this.select_file(node);
579                     } else {
580                         // save current path and filelist (in case we want to jump to other viewmode)
581                         this.options.path = e.node.origpath;
582                         this.options.list = e.node.origlist;
583                         this.currentpath = node.filepath;
584                         this.print_path();
585                         //this.content_scrolled();
586                     }
587                 };
588             }
589             if (!this.lazyloading) {
590                 this.lazyloading={};
591             }
592             this.filemanager.one('.fp-content').fp_display_filelist(options, list, this.lazyloading);
593             this.content_scrolled();
594         },
595         populate_licenses_select: function(node) {
596             if (!node) {
597                 return;
598             }
599             node.setContent('');
600             var licenses = this.options.licenses;
601             for (var i in licenses) {
602                 var option = Y.Node.create('<option/>').
603                     set('value', licenses[i].shortname).
604                     setContent(licenses[i].fullname);
605                 node.appendChild(option)
606             }
607         },
608         set_current_tree: function(tree) {
609             var appendfilepaths = function(list, node) {
610                 if (!node || !node.children || !node.children.length) {return;}
611                 for (var i in node.children) {
612                     list[list.length] = node.children[i].filepath;
613                     appendfilepaths(list, node.children[i]);
614                 }
615             }
616             var list = ['/'];
617             appendfilepaths(list, tree);
618             var selectnode = this.selectnode;
619             node = selectnode.one('.fp-path select');
620             node.setContent('');
621             for (var i in list) {
622                 node.appendChild(Y.Node.create('<option/>').
623                     set('value', list[i]).setContent(list[i]))
624             }
625         },
626         update_file: function(confirmed) {
627             var selectnode = this.selectnode;
628             var fileinfo = this.selectui.fileinfo;
630             var newfilename = Y.Lang.trim(selectnode.one('.fp-saveas input').get('value'));
631             var filenamechanged = (newfilename && newfilename != fileinfo.fullname);
632             var pathselect = selectnode.one('.fp-path select'),
633                     pathindex = pathselect.get('selectedIndex'),
634                     targetpath = pathselect.get("options").item(pathindex).get('value');
635             var filepathchanged = (targetpath != this.get_parent_folder_name(fileinfo));
636             var newauthor = Y.Lang.trim(selectnode.one('.fp-author input').get('value'));
637             var authorchanged = (newauthor != Y.Lang.trim(fileinfo.author));
638             var licenseselect = selectnode.one('.fp-license select'),
639                     licenseindex = licenseselect.get('selectedIndex'),
640                     newlicense = licenseselect.get("options").item(licenseindex).get('value');
641             var licensechanged = (newlicense != fileinfo.license);
643             var params, action;
644             var dialog_options = {callback:this.update_file, callbackargs:[true], scope:this};
645             if (fileinfo.type == 'folder') {
646                 if (!newfilename) {
647                     this.print_msg(M.str.repository.entername, 'error');
648                     return;
649                 }
650                 if (filenamechanged || filepathchanged) {
651                     if (!confirmed) {
652                         dialog_options.message = M.str.repository.confirmrenamefolder;
653                         this.show_confirm_dialog(dialog_options);
654                         return;
655                     }
656                     params = {filepath:fileinfo.filepath, newdirname:newfilename, newfilepath:targetpath};
657                     action = 'updatedir';
658                 }
659             } else {
660                 if (!newfilename) {
661                     this.print_msg(M.str.repository.enternewname, 'error');
662                     return;
663                 }
664                 if ((filenamechanged || filepathchanged) && !confirmed && fileinfo.refcount) {
665                     dialog_options.message = M.util.get_string('confirmrenamefile', 'repository', fileinfo.refcount);
666                     this.show_confirm_dialog(dialog_options);
667                     return;
668                 }
669                 if (filenamechanged || filepathchanged || licensechanged || authorchanged) {
670                     params = {filepath:fileinfo.filepath, filename:fileinfo.fullname,
671                         newfilename:newfilename, newfilepath:targetpath,
672                         newlicense:newlicense, newauthor:newauthor};
673                     action = 'updatefile';
674                 }
675             }
676             if (!action) {
677                 // no changes
678                 this.selectui.hide();
679                 return;
680             }
681             selectnode.addClass('loading');
682             this.request({
683                 action: action,
684                 scope: this,
685                 params: params,
686                 callback: function(id, obj, args) {
687                     if (obj.error) {
688                         selectnode.removeClass('loading');
689                         args.scope.print_msg(obj.error, 'error');
690                     } else {
691                         args.scope.selectui.hide();
692                         args.scope.refresh((obj && obj.filepath) ? obj.filepath : '/');
693                         if (typeof M.core_formchangechecker != 'undefined') {
694                             M.core_formchangechecker.set_form_changed();
695                         }
696                     }
697                 }
698             });
699         },
700         /**
701          * Displays a confirmation dialog
702          * Expected attributes in dialog_options: message, callback, callbackargs(optional), scope(optional)
703          */
704         show_confirm_dialog: function(dialog_options) {
705             // instead of M.util.show_confirm_dialog(e, dialog_options);
706             if (!this.confirm_dlg) {
707                 this.confirm_dlg_node = Y.Node.createWithFilesSkin(M.form_filemanager.templates.confirmdialog);
708                 var node = this.confirm_dlg_node;
709                 node.generateID();
710                 this.confirm_dlg = new Y.Panel({
711                     srcNode      : node,
712                     zIndex       : 8000,
713                     centered     : true,
714                     modal        : true,
715                     visible      : false,
716                     render       : true,
717                     buttons      : {}
718                 });
719                 this.confirm_dlg.plug(Y.Plugin.Drag,{handles:['#'+node.get('id')+' .yui3-widget-hd']});
720                 var handle_confirm = function(ev) {
721                     var dlgopt = this.confirm_dlg.dlgopt;
722                     ev.preventDefault();
723                     this.confirm_dlg.hide();
724                     if (dlgopt.callback) {
725                         if (dlgopt.callbackargs) {
726                             dlgopt.callback.apply(dlgopt.scope || this, dlgopt.callbackargs);
727                         } else {
728                             dlgopt.callback.apply(dlgopt.scope || this);
729                         }
730                     }
731                 }
732                 var handle_cancel = function(ev) {
733                     ev.preventDefault();
734                     this.confirm_dlg.hide();
735                 }
736                 node.one('.fp-dlg-butconfirm').on('click', handle_confirm, this);
737                 node.one('.fp-dlg-butcancel').on('click', handle_cancel, this);
738             }
739             this.confirm_dlg.dlgopt = dialog_options;
740             this.confirm_dlg_node.one('.fp-dlg-text').setContent(dialog_options.message);
741             this.confirm_dlg.show();
742         },
743         setup_select_file: function() {
744             var selectnode = this.selectnode;
745             // bind labels with corresponding inputs
746             selectnode.all('.fp-saveas,.fp-path,.fp-author,.fp-license').each(function (node) {
747                 node.all('label').set('for', node.one('input,select').generateID());
748             });
749             this.populate_licenses_select(selectnode.one('.fp-license select'));
750             // register event on clicking buttons
751             selectnode.one('.fp-file-update').on('click', function(e) {
752                 e.preventDefault();
753                 this.update_file();
754             }, this);
755             selectnode.all('form').on('keydown', function(e) {
756                 if (e.keyCode == 13) {
757                     e.preventDefault();
758                     this.update_file();
759                 }
760             }, this);
761             selectnode.one('.fp-file-download').on('click', function(e) {
762                 e.preventDefault();
763                 if (this.selectui.fileinfo.type != 'folder') {
764                     node = Y.Node.create('<iframe></iframe>').setStyles({
765                         visibility : 'hidden',
766                         width : '1px',
767                         height : '1px'
768                     });
769                     node.set('src', this.selectui.fileinfo.url);
770                     Y.one('body').appendChild(node);
771                 }
772             }, this);
773             selectnode.one('.fp-file-delete').on('click', function(e) {
774                 e.preventDefault();
775                 var dialog_options = {};
776                 var params = {};
777                 var fileinfo = this.selectui.fileinfo;
778                 dialog_options.scope = this;
779                 params.filepath = fileinfo.filepath;
780                 if (fileinfo.type == 'folder') {
781                     params.filename = '.';
782                     dialog_options.message = M.str.repository.confirmdeletefolder;
783                 } else {
784                     params.filename = fileinfo.fullname;
785                     if (fileinfo.refcount) {
786                         dialog_options.message = M.util.get_string('confirmdeletefilewithhref', 'repository', fileinfo.refcount);
787                     } else {
788                         dialog_options.message = M.str.repository.confirmdeletefile;
789                     }
790                 }
791                 dialog_options.callbackargs = [params];
792                 dialog_options.callback = function(params) {
793                     //selectnode.addClass('loading');
794                     this.request({
795                         action: 'delete',
796                         scope: this,
797                         params: params,
798                         callback: function(id, obj, args) {
799                             //args.scope.selectui.hide();
800                             args.scope.filecount--;
801                             args.scope.refresh(obj.filepath);
802                             if (typeof M.core_formchangechecker != 'undefined') {
803                                 M.core_formchangechecker.set_form_changed();
804                             }
805                         }
806                     });
807                 };
808                 this.selectui.hide(); // TODO remove this after confirm dialog is replaced with YUI3
809                 this.show_confirm_dialog(dialog_options);
810             }, this);
811             selectnode.one('.fp-file-zip').on('click', function(e) {
812                 e.preventDefault();
813                 var params = {};
814                 var fileinfo = this.selectui.fileinfo;
815                 if (fileinfo.type != 'folder') {
816                     // this button should not even be shown
817                     return;
818                 }
819                 params['filepath']   = fileinfo.filepath;
820                 params['filename']   = '.';
821                 selectnode.addClass('loading');
822                 this.request({
823                     action: 'zip',
824                     scope: this,
825                     params: params,
826                     callback: function(id, obj, args) {
827                         args.scope.selectui.hide();
828                         args.scope.refresh(obj.filepath);
829                     }
830                 });
831             }, this);
832             selectnode.one('.fp-file-unzip').on('click', function(e) {
833                 e.preventDefault();
834                 var params = {};
835                 var fileinfo = this.selectui.fileinfo;
836                 if (fileinfo.type != 'zip') {
837                     // this button should not even be shown
838                     return;
839                 }
840                 params['filepath'] = fileinfo.filepath;
841                 params['filename'] = fileinfo.fullname;
842                 selectnode.addClass('loading');
843                 this.request({
844                     action: 'unzip',
845                     scope: this,
846                     params: params,
847                     callback: function(id, obj, args) {
848                         args.scope.selectui.hide();
849                         args.scope.refresh(obj.filepath);
850                     }
851                 });
852             }, this);
853             selectnode.one('.fp-file-setmain').on('click', function(e) {
854                 e.preventDefault();
855                 var params = {};
856                 var fileinfo = this.selectui.fileinfo;
857                 if (!this.enablemainfile || fileinfo.type == 'folder') {
858                     // this button should not even be shown for folders or when mainfile is disabled
859                     return;
860                 }
861                 params['filepath'] = fileinfo.filepath;
862                 params['filename'] = fileinfo.fullname;
863                 selectnode.addClass('loading');
864                 this.request({
865                     action: 'setmainfile',
866                     scope: this,
867                     params: params,
868                     callback: function(id, obj, args) {
869                         args.scope.selectui.hide();
870                         args.scope.refresh(fileinfo.filepath);
871                     }
872                 });
873             }, this);
874             selectnode.all('.fp-file-cancel').on('click', function(e) {
875                 e.preventDefault();
876                 // TODO if changed asked to confirm, the same with close button
877                 this.selectui.hide();
878             }, this);
879         },
880         get_parent_folder_name: function(node) {
881             if (node.type != 'folder' || node.filepath.length < node.fullname.length+1) {
882                 return node.filepath;
883             }
884             var basedir = node.filepath.substr(0, node.filepath.length - node.fullname.length - 1);
885             var lastdir = node.filepath.substr(node.filepath.length - node.fullname.length - 2);
886             if (lastdir == '/' + node.fullname + '/') {
887                 return basedir;
888             }
889             return node.filepath;
890         },
891         select_file: function(node) {
892             if (this.is_disabled()) {
893                 return;
894             }
895             var selectnode = this.selectnode;
896             selectnode.removeClass('loading').removeClass('fp-folder').
897                 removeClass('fp-file').removeClass('fp-zip').removeClass('fp-cansetmain');
898             if (node.type == 'folder' || node.type == 'zip') {
899                 selectnode.addClass('fp-'+node.type);
900             } else {
901                 selectnode.addClass('fp-file');
902             }
903             if (this.enablemainfile && (node.sortorder != 1) && node.type == 'file') {
904                 selectnode.addClass('fp-cansetmain');
905             }
906             this.selectui.fileinfo = node;
907             selectnode.one('.fp-saveas input').set('value', node.fullname);
908             var foldername = this.get_parent_folder_name(node);
909             selectnode.all('.fp-author input').set('value', node.author ? node.author : '');
910             selectnode.all('.fp-license select option[selected]').set('selected', false);
911             selectnode.all('.fp-license select option[value='+node.license+']').set('selected', true);
912             selectnode.all('.fp-path select option[selected]').set('selected', false);
913             selectnode.all('.fp-path select option').each(function(el){
914                 if (el.get('value') == foldername) {
915                     el.set('selected', true);
916                 }
917             });
918             selectnode.all('.fp-author input, .fp-license select').set('disabled',(node.type == 'folder')?'disabled':'');
919             // display static information about a file (when known)
920             var attrs = ['datemodified','datecreated','size','dimensions','original','reflist'];
921             for (var i in attrs) {
922                 if (selectnode.one('.fp-'+attrs[i])) {
923                     var value = (node[attrs[i]+'_f']) ? node[attrs[i]+'_f'] : (node[attrs[i]] ? node[attrs[i]] : '');
924                     selectnode.one('.fp-'+attrs[i]).addClassIf('fp-unknown', ''+value == '')
925                         .one('.fp-value').setContent(value);
926                 }
927             }
928             // display thumbnail
929             var imgnode = Y.Node.create('<img/>').
930                 set('src', node.realthumbnail ? node.realthumbnail : node.thumbnail).
931                 setStyle('maxHeight', ''+(node.thumbnail_height ? node.thumbnail_height : 90)+'px').
932                 setStyle('maxWidth', ''+(node.thumbnail_width ? node.thumbnail_width : 90)+'px');
933             selectnode.one('.fp-thumbnail').setContent('').appendChild(imgnode);
934             // load original location if applicable
935             if (node.isref && !node.original) {
936                 selectnode.one('.fp-original').removeClass('fp-unknown').addClass('fp-loading');
937                 this.request({
938                     action: 'getoriginal',
939                     scope: this,
940                     params: {'filepath':node.filepath,'filename':node.fullname},
941                     callback: function(id, obj, args) {
942                         // check if we did not select another file meanwhile
943                         var scope = args.scope;
944                         if (scope.selectui.fileinfo && node &&
945                                 scope.selectui.fileinfo.filepath == node.filepath &&
946                                 scope.selectui.fileinfo.fullname == node.fullname) {
947                             selectnode.one('.fp-original').removeClass('fp-loading');
948                             if (obj.original) {
949                                 node.original = obj.original;
950                                 selectnode.one('.fp-original .fp-value').setContent(node.original);
951                             } else {
952                                 selectnode.one('.fp-original .fp-value').setContent(M.str.repository.unknownsource);
953                             }
954                         }
955                     }
956                 }, false);
957             }
958             // load references list if applicable
959             selectnode.one('.fp-refcount').setContent(node.refcount ? M.util.get_string('referencesexist', 'repository', node.refcount) : '');
960             if (node.refcount && !node.reflist) {
961                 selectnode.one('.fp-reflist').removeClass('fp-unknown').addClass('fp-loading');
962                 this.request({
963                     action: 'getreferences',
964                     scope: this,
965                     params: {'filepath':node.filepath,'filename':node.fullname},
966                     callback: function(id, obj, args) {
967                         // check if we did not select another file meanwhile
968                         var scope = args.scope;
969                         if (scope.selectui.fileinfo && node &&
970                                 scope.selectui.fileinfo.filepath == node.filepath &&
971                                 scope.selectui.fileinfo.fullname == node.fullname) {
972                             selectnode.one('.fp-reflist').removeClass('fp-loading');
973                             if (obj.references) {
974                                 node.reflist = '';
975                                 for (var i in obj.references) {
976                                     node.reflist += '<li>'+obj.references[i]+'</li>';
977                                 }
978                                 selectnode.one('.fp-reflist .fp-value').setContent(node.reflist);
979                             } else {
980                                 selectnode.one('.fp-reflist .fp-value').setContent('');
981                             }
982                         }
983                     }
984                 }, false);
985             }
986             // show panel
987             this.selectui.show();
988         },
989         render: function() {
990             this.print_path();
991             this.view_files();
992         }
993     });
995     // finally init everything needed
996     // hide loading picture, display filemanager interface
997     var filemanager = Y.one('#filemanager-'+options.client_id);
998     filemanager.removeClass('fm-loading').addClass('fm-loaded');
1000     var manager = new FileManagerHelper(options);
1001     var dndoptions = {
1002         filemanager: manager,
1003         acceptedtypes: options.filepicker.accepted_types,
1004         clientid: options.client_id,
1005         author: options.author,
1006         maxfiles: options.maxfiles,
1007         maxbytes: options.maxbytes,
1008         areamaxbytes: options.areamaxbytes,
1009         itemid: options.itemid,
1010         repositories: manager.filepicker_options.repositories,
1011         containerid: manager.dndcontainer.get('id')
1012     };
1013     M.form_dndupload.init(Y, dndoptions);
1014 };