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