Merge branch 'MDL-36900-master' of git://github.com/FMCorz/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(Y.Escape.html(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                     var validate_folder_name = function() {
307                         var valid = false;
308                         var foldername = Y.one('#fm-newname-'+scope.client_id).get('value');
309                         if (foldername.length > 0) {
310                             valid = true;
311                         }
312                         var btn = Y.one('#fm-mkdir-butcreate-'+scope.client_id);
313                         if (btn) {
314                             btn.set('disabled', !valid);
315                         }
316                         return valid;
317                     };
318                     if (!this.mkdir_dialog) {
319                         var node = Y.Node.createWithFilesSkin(M.form_filemanager.templates.mkdir);
320                         this.mkdir_dialog = new Y.Panel({
321                             srcNode      : node,
322                             zIndex       : 8000,
323                             centered     : true,
324                             modal        : true,
325                             visible      : false,
326                             render       : true
327                         });
328                         this.mkdir_dialog.plug(Y.Plugin.Drag,{handles:['.yui3-widget-hd']});
329                         node.one('.fp-dlg-butcreate').set('id', 'fm-mkdir-butcreate-'+this.client_id).on('click',
330                                 perform_action, this);
331                         node.one('input').set('id', 'fm-newname-'+this.client_id).on('keydown', function(e) {
332                             var valid = Y.bind(validate_folder_name, this)();
333                             if (valid && e.keyCode === 13) {
334                                 Y.bind(perform_action, this)(e);
335                             }
336                         }, this);
337                         node.one('#fm-newname-'+this.client_id).on(['keyup', 'change'], function(e) {
338                             Y.bind(validate_folder_name, this)();
339                         }, this);
341                         node.one('label').set('for', 'fm-newname-' + this.client_id);
342                         node.all('.fp-dlg-butcancel').on('click', function(e){e.preventDefault();this.mkdir_dialog.hide();}, this);
343                         node.all('.fp-dlg-curpath').set('id', 'fm-curpath-'+this.client_id);
344                     }
345                     this.mkdir_dialog.show();
347                     // Default folder name:
348                     var foldername = M.str.repository.newfolder;
349                     while (this.has_folder(foldername)) {
350                         foldername = increment_filename(foldername, true);
351                     }
352                     Y.one('#fm-newname-'+scope.client_id).set('value', foldername);
353                     Y.bind(validate_folder_name, this)();
354                     Y.one('#fm-newname-'+scope.client_id).focus().select();
355                     Y.all('#fm-curpath-'+scope.client_id).setContent(this.currentpath);
356                 }, this);
357             } else {
358                 this.filemanager.addClass('fm-nomkdir');
359             }
361             // setup 'download this folder' button
362             button_download.on('click',function(e) {
363                 e.preventDefault();
364                 if (this.is_disabled()) {
365                     return;
366                 }
367                 var scope = this;
368                 // perform downloaddir ajax request
369                 this.request({
370                     action: 'downloaddir',
371                     scope: scope,
372                     callback: function(id, obj, args) {
373                         if (obj) {
374                             scope.refresh(obj.filepath);
375                             node = Y.Node.create('<iframe></iframe>').setStyles({
376                                 visibility : 'hidden',
377                                 width : '1px',
378                                 height : '1px'
379                             });
380                             node.set('src', obj.fileurl);
381                             Y.one('body').appendChild(node);
382                         } else {
383                             scope.print_msg(M.str.repository.draftareanofiles, 'error');
384                         }
385                     }
386                 });
387             }, this);
389             this.filemanager.all('.fp-vb-icons,.fp-vb-tree,.fp-vb-details').
390                 on('click', function(e) {
391                     e.preventDefault();
392                     var viewbar = this.filemanager.one('.fp-viewbar')
393                     if (!this.is_disabled() && (!viewbar || !viewbar.hasClass('disabled'))) {
394                         this.filemanager.all('.fp-vb-icons,.fp-vb-tree,.fp-vb-details').removeClass('checked')
395                         if (e.currentTarget.hasClass('fp-vb-tree')) {
396                             this.viewmode = 2;
397                         } else if (e.currentTarget.hasClass('fp-vb-details')) {
398                             this.viewmode = 3;
399                         } else {
400                             this.viewmode = 1;
401                         }
402                         e.currentTarget.addClass('checked')
403                         this.render();
404                     }
405                 }, this);
406         },
408         show_filepicker: function (e) {
409             // if maxfiles == -1, the no limit
410             e.preventDefault();
411             if (this.is_disabled()) {
412                 return;
413             }
414             var options = this.filepicker_options;
415             options.formcallback = this.filepicker_callback;
416             // XXX: magic here, to let filepicker use filemanager scope
417             options.magicscope = this;
418             options.savepath = this.currentpath;
419             M.core_filepicker.show(Y, options);
420         },
422         print_path: function() {
423             var p = this.options.path;
424             this.pathbar.setContent('').addClass('empty');
425             if (p && p.length!=0 && this.viewmode != 2) {
426                 for(var i = 0; i < p.length; i++) {
427                     var el = this.pathnode.cloneNode(true);
428                     this.pathbar.appendChild(el);
430                     if (i == 0) {
431                         el.addClass('first');
432                     }
433                     if (i == p.length-1) {
434                         el.addClass('last');
435                     }
437                     if (i%2) {
438                         el.addClass('even');
439                     } else {
440                         el.addClass('odd');
441                     }
442                     el.one('.fp-path-folder-name').setContent(Y.Escape.html(p[i].name)).
443                         on('click', function(e, path) {
444                             e.preventDefault();
445                             if (!this.is_disabled()) {
446                                 this.refresh(path);
447                             }
448                         }, this, p[i].path);
449                 }
450                 this.pathbar.removeClass('empty');
451             }
452         },
453         get_filepath: function(obj) {
454             if (obj.path && obj.path.length) {
455                 return obj.path[obj.path.length-1].path;
456             }
457             return '';
458         },
459         treeview_dynload: function(node, cb) {
460             var retrieved_children = {};
461             if (node.children) {
462                 for (var i in node.children) {
463                     retrieved_children[node.children[i].path] = node.children[i];
464                 }
465             }
466             if (!node.path || node.path == '/') {
467                 // this is a root pseudo folder
468                 node.fileinfo.filepath = '/';
469                 node.fileinfo.type = 'folder';
470                 node.fileinfo.fullname = node.fileinfo.title;
471                 node.fileinfo.filename = '.';
472             }
473             this.request({
474                 action:'list',
475                 params: {filepath:node.path?node.path:''},
476                 scope:this,
477                 callback: function(id, obj, args) {
478                     var list = obj.list;
479                     var scope = args.scope;
480                     // check that user did not leave the view mode before recieving this response
481                     if (!(scope.viewmode == 2 && node && node.getChildrenEl())) {
482                         return;
483                     }
484                     if (cb != null) { // (in manual mode do not update current path)
485                         scope.options = obj;
486                         scope.currentpath = node.path?node.path:'/';
487                     }
488                     node.highlight(false);
489                     node.origlist = obj.list ? obj.list : null;
490                     node.origpath = obj.path ? obj.path : null;
491                     node.children = [];
492                     for(k in list) {
493                         if (list[k].type == 'folder' && retrieved_children[list[k].filepath]) {
494                             // if this child is a folder and has already been retrieved
495                             retrieved_children[list[k].filepath].fileinfo = list[k];
496                             node.children[node.children.length] = retrieved_children[list[k].filepath];
497                         } else {
498                             // append new file to the list
499                             scope.view_files([list[k]]);
500                         }
501                     }
502                     if (cb == null) {
503                         node.refresh();
504                     } else {
505                         // invoke callback requested by TreeView component
506                         cb();
507                     }
508                     scope.content_scrolled();
509                 }
510             }, false);
511         },
512         content_scrolled: function(e) {
513             setTimeout(Y.bind(function() {
514                 if (this.processingimages) {return;}
515                 this.processingimages = true;
516                 var scope = this,
517                     fpcontent = this.filemanager.one('.fp-content'),
518                     fpcontenty = fpcontent.getY(),
519                     fpcontentheight = fpcontent.getStylePx('height'),
520                     is_node_visible = function(node) {
521                         var offset = node.getY()-fpcontenty;
522                         if (offset <= fpcontentheight && (offset >=0 || offset+node.getStylePx('height')>=0)) {
523                             return true;
524                         }
525                         return false;
526                     };
527                 // replace src for visible images that need to be lazy-loaded
528                 if (scope.lazyloading) {
529                     fpcontent.all('img').each( function(node) {
530                         if (node.get('id') && scope.lazyloading[node.get('id')] && is_node_visible(node)) {
531                             node.setImgRealSrc(scope.lazyloading);
532                         }
533                     });
534                 }
535                 this.processingimages = false;
536             }, this), 200)
537         },
538         view_files: function(appendfiles) {
539             this.filemanager.removeClass('fm-updating').removeClass('fm-noitems');
540             if ((appendfiles == null) && (!this.options.list || this.options.list.length == 0) && this.viewmode != 2) {
541                 this.filemanager.addClass('fm-noitems');
542                 return;
543             }
544             var list = (appendfiles != null) ? appendfiles : this.options.list;
545             var element_template;
546             if (this.viewmode == 2 || this.viewmode == 3) {
547                 element_template = Y.Node.create(M.form_filemanager.templates.listfilename);
548             } else {
549                 this.viewmode = 1;
550                 element_template = Y.Node.create(M.form_filemanager.templates.iconfilename);
551             }
552             var options = {
553                 viewmode : this.viewmode,
554                 appendonly : appendfiles != null,
555                 filenode : element_template,
556                 callbackcontext : this,
557                 callback : function(e, node) {
558                     if (e.preventDefault) { e.preventDefault(); }
559                     if (node.type == 'folder') {
560                         this.refresh(node.filepath);
561                     } else {
562                         this.select_file(node);
563                     }
564                 },
565                 rightclickcallback : function(e, node) {
566                     if (e.preventDefault) { e.preventDefault(); }
567                     this.select_file(node);
568                 },
569                 classnamecallback : function(node) {
570                     var classname = '';
571                     if (node.type == 'folder' || (!node.type && !node.filename)) {
572                         classname = classname + ' fp-folder';
573                     }
574                     if (node.filename || node.filepath || (node.path && node.path != '/')) {
575                         classname = classname + ' fp-hascontextmenu';
576                     }
577                     if (node.isref) {
578                         classname = classname + ' fp-isreference';
579                     }
580                     if (node.refcount) {
581                         classname = classname + ' fp-hasreferences';
582                     }
583                     if (node.originalmissing) {
584                         classname = classname + ' fp-originalmissing';
585                     }
586                     if (node.sortorder == 1) { classname = classname + ' fp-mainfile';}
587                     return Y.Lang.trim(classname);
588                 }
589             };
590             if (this.viewmode == 2) {
591                 options.dynload = true;
592                 options.filepath = this.options.path;
593                 options.treeview_dynload = this.treeview_dynload;
594                 options.norootrightclick = true;
595                 options.callback = function(e, node) {
596                     // TODO MDL-32736 e is not an event here but an object with properties 'event' and 'node'
597                     if (!node.fullname) {return;}
598                     if (node.type != 'folder') {
599                         if (e.node.parent && e.node.parent.origpath) {
600                             // set the current path
601                             this.options.path = e.node.parent.origpath;
602                             this.options.list = e.node.parent.origlist;
603                             this.print_path();
604                         }
605                         this.currentpath = node.filepath;
606                         this.select_file(node);
607                     } else {
608                         // save current path and filelist (in case we want to jump to other viewmode)
609                         this.options.path = e.node.origpath;
610                         this.options.list = e.node.origlist;
611                         this.currentpath = node.filepath;
612                         this.print_path();
613                         //this.content_scrolled();
614                     }
615                 };
616             }
617             if (!this.lazyloading) {
618                 this.lazyloading={};
619             }
620             this.filemanager.one('.fp-content').fp_display_filelist(options, list, this.lazyloading);
621             this.content_scrolled();
622         },
623         populate_licenses_select: function(node) {
624             if (!node) {
625                 return;
626             }
627             node.setContent('');
628             var licenses = this.options.licenses;
629             for (var i in licenses) {
630                 var option = Y.Node.create('<option/>').
631                     set('value', licenses[i].shortname).
632                     setContent(Y.Escape.html(licenses[i].fullname));
633                 node.appendChild(option)
634             }
635         },
636         set_current_tree: function(tree) {
637             var appendfilepaths = function(list, node) {
638                 if (!node || !node.children || !node.children.length) {return;}
639                 for (var i in node.children) {
640                     list[list.length] = node.children[i].filepath;
641                     appendfilepaths(list, node.children[i]);
642                 }
643             }
644             var list = ['/'];
645             appendfilepaths(list, tree);
646             var selectnode = this.selectnode;
647             node = selectnode.one('.fp-path select');
648             node.setContent('');
649             for (var i in list) {
650                 node.appendChild(Y.Node.create('<option/>').
651                     set('value', list[i]).setContent(Y.Escape.html(list[i])));
652             }
653         },
654         update_file: function(confirmed) {
655             var selectnode = this.selectnode;
656             var fileinfo = this.selectui.fileinfo;
658             var newfilename = Y.Lang.trim(selectnode.one('.fp-saveas input').get('value'));
659             var filenamechanged = (newfilename && newfilename != fileinfo.fullname);
660             var pathselect = selectnode.one('.fp-path select'),
661                     pathindex = pathselect.get('selectedIndex'),
662                     targetpath = pathselect.get("options").item(pathindex).get('value');
663             var filepathchanged = (targetpath != this.get_parent_folder_name(fileinfo));
664             var newauthor = Y.Lang.trim(selectnode.one('.fp-author input').get('value'));
665             var authorchanged = (newauthor != Y.Lang.trim(fileinfo.author));
666             var licenseselect = selectnode.one('.fp-license select'),
667                     licenseindex = licenseselect.get('selectedIndex'),
668                     newlicense = licenseselect.get("options").item(licenseindex).get('value');
669             var licensechanged = (newlicense != fileinfo.license);
671             var params, action;
672             var dialog_options = {callback:this.update_file, callbackargs:[true], scope:this};
673             if (fileinfo.type == 'folder') {
674                 if (!newfilename) {
675                     this.print_msg(M.str.repository.entername, 'error');
676                     return;
677                 }
678                 if (filenamechanged || filepathchanged) {
679                     if (!confirmed) {
680                         dialog_options.message = M.str.repository.confirmrenamefolder;
681                         this.show_confirm_dialog(dialog_options);
682                         return;
683                     }
684                     params = {filepath:fileinfo.filepath, newdirname:newfilename, newfilepath:targetpath};
685                     action = 'updatedir';
686                 }
687             } else {
688                 if (!newfilename) {
689                     this.print_msg(M.str.repository.enternewname, 'error');
690                     return;
691                 }
692                 if ((filenamechanged || filepathchanged) && !confirmed && fileinfo.refcount) {
693                     dialog_options.message = M.util.get_string('confirmrenamefile', 'repository', fileinfo.refcount);
694                     this.show_confirm_dialog(dialog_options);
695                     return;
696                 }
697                 if (filenamechanged || filepathchanged || licensechanged || authorchanged) {
698                     params = {filepath:fileinfo.filepath, filename:fileinfo.fullname,
699                         newfilename:newfilename, newfilepath:targetpath,
700                         newlicense:newlicense, newauthor:newauthor};
701                     action = 'updatefile';
702                 }
703             }
704             if (!action) {
705                 // no changes
706                 this.selectui.hide();
707                 return;
708             }
709             selectnode.addClass('loading');
710             this.request({
711                 action: action,
712                 scope: this,
713                 params: params,
714                 callback: function(id, obj, args) {
715                     if (obj.error) {
716                         selectnode.removeClass('loading');
717                         args.scope.print_msg(obj.error, 'error');
718                     } else {
719                         args.scope.selectui.hide();
720                         args.scope.refresh((obj && obj.filepath) ? obj.filepath : '/');
721                         if (typeof M.core_formchangechecker != 'undefined') {
722                             M.core_formchangechecker.set_form_changed();
723                         }
724                     }
725                 }
726             });
727         },
728         /**
729          * Displays a confirmation dialog
730          * Expected attributes in dialog_options: message, callback, callbackargs(optional), scope(optional)
731          */
732         show_confirm_dialog: function(dialog_options) {
733             // instead of M.util.show_confirm_dialog(e, dialog_options);
734             if (!this.confirm_dlg) {
735                 this.confirm_dlg_node = Y.Node.createWithFilesSkin(M.form_filemanager.templates.confirmdialog);
736                 var node = this.confirm_dlg_node;
737                 node.generateID();
738                 this.confirm_dlg = new Y.Panel({
739                     srcNode      : node,
740                     zIndex       : 8000,
741                     centered     : true,
742                     modal        : true,
743                     visible      : false,
744                     render       : true,
745                     buttons      : {}
746                 });
747                 this.confirm_dlg.plug(Y.Plugin.Drag,{handles:['#'+node.get('id')+' .yui3-widget-hd']});
748                 var handle_confirm = function(ev) {
749                     var dlgopt = this.confirm_dlg.dlgopt;
750                     ev.preventDefault();
751                     this.confirm_dlg.hide();
752                     if (dlgopt.callback) {
753                         if (dlgopt.callbackargs) {
754                             dlgopt.callback.apply(dlgopt.scope || this, dlgopt.callbackargs);
755                         } else {
756                             dlgopt.callback.apply(dlgopt.scope || this);
757                         }
758                     }
759                 }
760                 var handle_cancel = function(ev) {
761                     ev.preventDefault();
762                     this.confirm_dlg.hide();
763                 }
764                 node.one('.fp-dlg-butconfirm').on('click', handle_confirm, this);
765                 node.one('.fp-dlg-butcancel').on('click', handle_cancel, this);
766             }
767             this.confirm_dlg.dlgopt = dialog_options;
768             this.confirm_dlg_node.one('.fp-dlg-text').setContent(dialog_options.message);
769             this.confirm_dlg.show();
770         },
771         setup_select_file: function() {
772             var selectnode = this.selectnode;
773             // bind labels with corresponding inputs
774             selectnode.all('.fp-saveas,.fp-path,.fp-author,.fp-license').each(function (node) {
775                 node.all('label').set('for', node.one('input,select').generateID());
776             });
777             this.populate_licenses_select(selectnode.one('.fp-license select'));
778             // register event on clicking buttons
779             selectnode.one('.fp-file-update').on('click', function(e) {
780                 e.preventDefault();
781                 this.update_file();
782             }, this);
783             selectnode.all('form').on('keydown', function(e) {
784                 if (e.keyCode == 13) {
785                     e.preventDefault();
786                     this.update_file();
787                 }
788             }, this);
789             selectnode.one('.fp-file-download').on('click', function(e) {
790                 e.preventDefault();
791                 if (this.selectui.fileinfo.type != 'folder') {
792                     node = Y.Node.create('<iframe></iframe>').setStyles({
793                         visibility : 'hidden',
794                         width : '1px',
795                         height : '1px'
796                     });
797                     node.set('src', this.selectui.fileinfo.url);
798                     Y.one('body').appendChild(node);
799                 }
800             }, this);
801             selectnode.one('.fp-file-delete').on('click', function(e) {
802                 e.preventDefault();
803                 var dialog_options = {};
804                 var params = {};
805                 var fileinfo = this.selectui.fileinfo;
806                 dialog_options.scope = this;
807                 params.filepath = fileinfo.filepath;
808                 if (fileinfo.type == 'folder') {
809                     params.filename = '.';
810                     dialog_options.message = M.str.repository.confirmdeletefolder;
811                 } else {
812                     params.filename = fileinfo.fullname;
813                     if (fileinfo.refcount) {
814                         dialog_options.message = M.util.get_string('confirmdeletefilewithhref', 'repository', fileinfo.refcount);
815                     } else {
816                         dialog_options.message = M.str.repository.confirmdeletefile;
817                     }
818                 }
819                 dialog_options.callbackargs = [params];
820                 dialog_options.callback = function(params) {
821                     //selectnode.addClass('loading');
822                     this.request({
823                         action: 'delete',
824                         scope: this,
825                         params: params,
826                         callback: function(id, obj, args) {
827                             //args.scope.selectui.hide();
828                             args.scope.filecount--;
829                             args.scope.refresh(obj.filepath);
830                             if (typeof M.core_formchangechecker != 'undefined') {
831                                 M.core_formchangechecker.set_form_changed();
832                             }
833                         }
834                     });
835                 };
836                 this.selectui.hide(); // TODO remove this after confirm dialog is replaced with YUI3
837                 this.show_confirm_dialog(dialog_options);
838             }, this);
839             selectnode.one('.fp-file-zip').on('click', function(e) {
840                 e.preventDefault();
841                 var params = {};
842                 var fileinfo = this.selectui.fileinfo;
843                 if (fileinfo.type != 'folder') {
844                     // this button should not even be shown
845                     return;
846                 }
847                 params['filepath']   = fileinfo.filepath;
848                 params['filename']   = '.';
849                 selectnode.addClass('loading');
850                 this.request({
851                     action: 'zip',
852                     scope: this,
853                     params: params,
854                     callback: function(id, obj, args) {
855                         args.scope.selectui.hide();
856                         args.scope.refresh(obj.filepath);
857                     }
858                 });
859             }, this);
860             selectnode.one('.fp-file-unzip').on('click', function(e) {
861                 e.preventDefault();
862                 var params = {};
863                 var fileinfo = this.selectui.fileinfo;
864                 if (fileinfo.type != 'zip') {
865                     // this button should not even be shown
866                     return;
867                 }
868                 params['filepath'] = fileinfo.filepath;
869                 params['filename'] = fileinfo.fullname;
870                 selectnode.addClass('loading');
871                 this.request({
872                     action: 'unzip',
873                     scope: this,
874                     params: params,
875                     callback: function(id, obj, args) {
876                         args.scope.selectui.hide();
877                         args.scope.refresh(obj.filepath);
878                     }
879                 });
880             }, this);
881             selectnode.one('.fp-file-setmain').on('click', function(e) {
882                 e.preventDefault();
883                 var params = {};
884                 var fileinfo = this.selectui.fileinfo;
885                 if (!this.enablemainfile || fileinfo.type == 'folder') {
886                     // this button should not even be shown for folders or when mainfile is disabled
887                     return;
888                 }
889                 params['filepath'] = fileinfo.filepath;
890                 params['filename'] = fileinfo.fullname;
891                 selectnode.addClass('loading');
892                 this.request({
893                     action: 'setmainfile',
894                     scope: this,
895                     params: params,
896                     callback: function(id, obj, args) {
897                         args.scope.selectui.hide();
898                         args.scope.refresh(fileinfo.filepath);
899                     }
900                 });
901             }, this);
902             selectnode.all('.fp-file-cancel').on('click', function(e) {
903                 e.preventDefault();
904                 // TODO if changed asked to confirm, the same with close button
905                 this.selectui.hide();
906             }, this);
907         },
908         get_parent_folder_name: function(node) {
909             if (node.type != 'folder' || node.filepath.length < node.fullname.length+1) {
910                 return node.filepath;
911             }
912             var basedir = node.filepath.substr(0, node.filepath.length - node.fullname.length - 1);
913             var lastdir = node.filepath.substr(node.filepath.length - node.fullname.length - 2);
914             if (lastdir == '/' + node.fullname + '/') {
915                 return basedir;
916             }
917             return node.filepath;
918         },
919         select_file: function(node) {
920             if (this.is_disabled()) {
921                 return;
922             }
923             var selectnode = this.selectnode;
924             selectnode.removeClass('loading').removeClass('fp-folder').
925                 removeClass('fp-file').removeClass('fp-zip').removeClass('fp-cansetmain');
926             if (node.type == 'folder' || node.type == 'zip') {
927                 selectnode.addClass('fp-'+node.type);
928             } else {
929                 selectnode.addClass('fp-file');
930             }
931             if (this.enablemainfile && (node.sortorder != 1) && node.type == 'file') {
932                 selectnode.addClass('fp-cansetmain');
933             }
934             this.selectui.fileinfo = node;
935             selectnode.one('.fp-saveas input').set('value', node.fullname);
936             var foldername = this.get_parent_folder_name(node);
937             selectnode.all('.fp-author input').set('value', node.author ? node.author : '');
938             selectnode.all('.fp-license select option[selected]').set('selected', false);
939             selectnode.all('.fp-license select option[value='+node.license+']').set('selected', true);
940             selectnode.all('.fp-path select option[selected]').set('selected', false);
941             selectnode.all('.fp-path select option').each(function(el){
942                 if (el.get('value') == foldername) {
943                     el.set('selected', true);
944                 }
945             });
946             selectnode.all('.fp-author input, .fp-license select').set('disabled',(node.type == 'folder')?'disabled':'');
947             // display static information about a file (when known)
948             var attrs = ['datemodified','datecreated','size','dimensions','original','reflist'];
949             for (var i in attrs) {
950                 if (selectnode.one('.fp-'+attrs[i])) {
951                     var value = (node[attrs[i]+'_f']) ? node[attrs[i]+'_f'] : (node[attrs[i]] ? node[attrs[i]] : '');
952                     selectnode.one('.fp-'+attrs[i]).addClassIf('fp-unknown', ''+value == '')
953                         .one('.fp-value').setContent(Y.Escape.html(value));
954                 }
955             }
956             // display thumbnail
957             var imgnode = Y.Node.create('<img/>').
958                 set('src', node.realthumbnail ? node.realthumbnail : node.thumbnail).
959                 setStyle('maxHeight', ''+(node.thumbnail_height ? node.thumbnail_height : 90)+'px').
960                 setStyle('maxWidth', ''+(node.thumbnail_width ? node.thumbnail_width : 90)+'px');
961             selectnode.one('.fp-thumbnail').setContent('').appendChild(imgnode);
962             // load original location if applicable
963             if (node.isref && !node.original) {
964                 selectnode.one('.fp-original').removeClass('fp-unknown').addClass('fp-loading');
965                 this.request({
966                     action: 'getoriginal',
967                     scope: this,
968                     params: {'filepath':node.filepath,'filename':node.fullname},
969                     callback: function(id, obj, args) {
970                         // check if we did not select another file meanwhile
971                         var scope = args.scope;
972                         if (scope.selectui.fileinfo && node &&
973                                 scope.selectui.fileinfo.filepath == node.filepath &&
974                                 scope.selectui.fileinfo.fullname == node.fullname) {
975                             selectnode.one('.fp-original').removeClass('fp-loading');
976                             if (obj.original) {
977                                 node.original = obj.original;
978                                 selectnode.one('.fp-original .fp-value').setContent(Y.Escape.html(node.original));
979                             } else {
980                                 selectnode.one('.fp-original .fp-value').setContent(M.str.repository.unknownsource);
981                             }
982                         }
983                     }
984                 }, false);
985             }
986             // load references list if applicable
987             selectnode.one('.fp-refcount').setContent(node.refcount ? M.util.get_string('referencesexist', 'repository', node.refcount) : '');
988             if (node.refcount && !node.reflist) {
989                 selectnode.one('.fp-reflist').removeClass('fp-unknown').addClass('fp-loading');
990                 this.request({
991                     action: 'getreferences',
992                     scope: this,
993                     params: {'filepath':node.filepath,'filename':node.fullname},
994                     callback: function(id, obj, args) {
995                         // check if we did not select another file meanwhile
996                         var scope = args.scope;
997                         if (scope.selectui.fileinfo && node &&
998                                 scope.selectui.fileinfo.filepath == node.filepath &&
999                                 scope.selectui.fileinfo.fullname == node.fullname) {
1000                             selectnode.one('.fp-reflist').removeClass('fp-loading');
1001                             if (obj.references) {
1002                                 node.reflist = '';
1003                                 for (var i in obj.references) {
1004                                     node.reflist += '<li>'+obj.references[i]+'</li>';
1005                                 }
1006                                 selectnode.one('.fp-reflist .fp-value').setContent(Y.Escape.html(node.reflist));
1007                             } else {
1008                                 selectnode.one('.fp-reflist .fp-value').setContent('');
1009                             }
1010                         }
1011                     }
1012                 }, false);
1013             }
1014             // show panel
1015             this.selectui.show();
1016         },
1017         render: function() {
1018             this.print_path();
1019             this.view_files();
1020         },
1021         has_folder: function(foldername) {
1022             var element;
1023             for (var i in this.options.list) {
1024                 element = this.options.list[i];
1025                 if (element.type == 'folder' && element.fullname == foldername) {
1026                     return true;
1027                 }
1028             }
1029             return false;
1030         }
1031     });
1033     // finally init everything needed
1034     // hide loading picture, display filemanager interface
1035     var filemanager = Y.one('#filemanager-'+options.client_id);
1036     filemanager.removeClass('fm-loading').addClass('fm-loaded');
1038     var manager = new FileManagerHelper(options);
1039     var dndoptions = {
1040         filemanager: manager,
1041         acceptedtypes: options.filepicker.accepted_types,
1042         clientid: options.client_id,
1043         author: options.author,
1044         maxfiles: options.maxfiles,
1045         maxbytes: options.maxbytes,
1046         areamaxbytes: options.areamaxbytes,
1047         itemid: options.itemid,
1048         repositories: manager.filepicker_options.repositories,
1049         containerid: manager.dndcontainer.get('id')
1050     };
1051     M.form_dndupload.init(Y, dndoptions);
1052 };