MDL-63303 message: fix bugs in message drawer part 2
[moodle.git] / repository / filepicker.js
blobd273aa5ce05999e3a47f0a6be0ab8ba218b07ff4
1 // YUI3 File Picker module for moodle
2 // Author: Dongsheng Cai <dongsheng@moodle.com>
4 /**
5  *
6  * File Picker UI
7  * =====
8  * this.fpnode, contains reference to filepicker Node, non-empty if and only if rendered
9  * this.api, stores the URL to make ajax request
10  * this.mainui, YUI Panel
11  * this.selectnode, contains reference to select-file Node
12  * this.selectui, YUI Panel for selecting particular file
13  * this.msg_dlg, YUI Panel for error or info message
14  * this.process_dlg, YUI Panel for processing existing filename
15  * this.treeview, YUI Treeview
16  * this.viewmode, store current view mode
17  * this.pathbar, reference to the Node with path bar
18  * this.pathnode, a Node element representing one folder in a path bar (not attached anywhere, just used for template)
19  * this.currentpath, the current path in the repository (or last requested path)
20  *
21  * Filepicker options:
22  * =====
23  * this.options.client_id, the instance id
24  * this.options.contextid
25  * this.options.itemid
26  * this.options.repositories, stores all repositories displayed in file picker
27  * this.options.formcallback
28  *
29  * Active repository options
30  * =====
31  * this.active_repo.id
32  * this.active_repo.defaultreturntype
33  * this.active_repo.nosearch
34  * this.active_repo.norefresh
35  * this.active_repo.nologin
36  * this.active_repo.help
37  * this.active_repo.manage
38  *
39  * Server responses
40  * =====
41  * this.filelist, cached filelist
42  * this.pages
43  * this.page
44  * this.filepath, current path (each element of the array is a part of the breadcrumb)
45  * this.logindata, cached login form
46  */
48 YUI.add('moodle-core_filepicker', function(Y) {
49     /** help function to extract width/height style as a number, not as a string */
50     Y.Node.prototype.getStylePx = function(attr) {
51         var style = this.getStyle(attr);
52         if (''+style == '0' || ''+style == '0px') {
53             return 0;
54         }
55         var matches = style.match(/^([\d\.]+)px$/)
56         if (matches && parseFloat(matches[1])) {
57             return parseFloat(matches[1]);
58         }
59         return null;
60     }
62     /** if condition is met, the class is added to the node, otherwise - removed */
63     Y.Node.prototype.addClassIf = function(className, condition) {
64         if (condition) {
65             this.addClass(className);
66         } else {
67             this.removeClass(className);
68         }
69         return this;
70     }
72     /** sets the width(height) of the node considering existing minWidth(minHeight) */
73     Y.Node.prototype.setStyleAdv = function(stylename, value) {
74         var stylenameCap = stylename.substr(0,1).toUpperCase() + stylename.substr(1, stylename.length-1).toLowerCase();
75         this.setStyle(stylename, '' + Math.max(value, this.getStylePx('min'+stylenameCap)) + 'px')
76         return this;
77     }
79     /** set image source to src, if there is preview, remember it in lazyloading.
80      *  If there is a preview and it was already loaded, use it. */
81     Y.Node.prototype.setImgSrc = function(src, realsrc, lazyloading) {
82         if (realsrc) {
83             if (M.core_filepicker.loadedpreviews[realsrc]) {
84                 this.set('src', realsrc).addClass('realpreview');
85                 return this;
86             } else {
87                 if (!this.get('id')) {
88                     this.generateID();
89                 }
90                 lazyloading[this.get('id')] = realsrc;
91             }
92         }
93         this.set('src', src);
94         return this;
95     }
97     /**
98      * Replaces the image source with preview. If the image is inside the treeview, we need
99      * also to update the html property of corresponding YAHOO.widget.HTMLNode
100      * @param array lazyloading array containing associations of imgnodeid->realsrc
101      */
102     Y.Node.prototype.setImgRealSrc = function(lazyloading) {
103         if (this.get('id') && lazyloading[this.get('id')]) {
104             var newsrc = lazyloading[this.get('id')];
105             M.core_filepicker.loadedpreviews[newsrc] = true;
106             this.set('src', newsrc).addClass('realpreview');
107             delete lazyloading[this.get('id')];
108             var treenode = this.ancestor('.fp-treeview')
109             if (treenode && treenode.get('parentNode').treeview) {
110                 treenode.get('parentNode').treeview.getRoot().refreshPreviews(this.get('id'), newsrc);
111             }
112         }
113         return this;
114     }
116     /** scan TreeView to find which node contains image with id=imgid and replace it's html
117      * with the new image source. */
118     Y.YUI2.widget.Node.prototype.refreshPreviews = function(imgid, newsrc, regex) {
119         if (!regex) {
120             regex = new RegExp("<img\\s[^>]*id=\""+imgid+"\"[^>]*?(/?)>", "im");
121         }
122         if (this.expanded || this.isLeaf) {
123             var html = this.getContentHtml();
124             if (html && this.setHtml && regex.test(html)) {
125                 var newhtml = this.html.replace(regex, "<img id=\""+imgid+"\" src=\""+newsrc+"\" class=\"realpreview\"$1>", html);
126                 this.setHtml(newhtml);
127                 return true;
128             }
129             if (!this.isLeaf && this.children) {
130                 for(var c in this.children) {
131                     if (this.children[c].refreshPreviews(imgid, newsrc, regex)) {
132                         return true;
133                     }
134                 }
135             }
136         }
137         return false;
138     }
140     /**
141      * Displays a list of files (used by filepicker, filemanager) inside the Node
142      *
143      * @param array options
144      *   viewmode : 1 - icons, 2 - tree, 3 - table
145      *   appendonly : whether fileslist need to be appended instead of replacing the existing content
146      *   filenode : Node element that contains template for displaying one file
147      *   callback : On click callback. The element of the fileslist array will be passed as argument
148      *   rightclickcallback : On right click callback (optional).
149      *   callbackcontext : context where callbacks are executed
150      *   sortable : whether content may be sortable (in table mode)
151      *   dynload : allow dynamic load for tree view
152      *   filepath : for pre-building of tree view - the path to the current directory in filepicker format
153      *   treeview_dynload : callback to function to dynamically load the folder in tree view
154      *   classnamecallback : callback to function that returns the class name for an element
155      * @param array fileslist array of files to show, each array element may have attributes:
156      *   title or fullname : file name
157      *   shorttitle (optional) : display file name
158      *   thumbnail : url of image
159      *   icon : url of icon image
160      *   thumbnail_width : width of thumbnail, default 90
161      *   thumbnail_height : height of thumbnail, default 90
162      *   thumbnail_alt : TODO not needed!
163      *   description or thumbnail_title : alt text
164      * @param array lazyloading : reference to the array with lazy loading images
165      */
166     Y.Node.prototype.fp_display_filelist = function(options, fileslist, lazyloading) {
167         var viewmodeclassnames = {1:'fp-iconview', 2:'fp-treeview', 3:'fp-tableview'};
168         var classname = viewmodeclassnames[options.viewmode];
169         var scope = this;
170         /** return whether file is a folder (different attributes in FileManager and FilePicker) */
171         var file_is_folder = function(node) {
172             if (node.children) {return true;}
173             if (node.type && node.type == 'folder') {return true;}
174             return false;
175         };
176         /** return the name of the file (different attributes in FileManager and FilePicker) */
177         var file_get_filename = function(node) {
178             return node.title ? node.title : node.fullname;
179         };
180         /** return display name of the file (different attributes in FileManager and FilePicker) */
181         var file_get_displayname = function(node) {
182             var displayname = node.shorttitle ? node.shorttitle : file_get_filename(node);
183             return Y.Escape.html(displayname);
184         };
185         /** return file description (different attributes in FileManager and FilePicker) */
186         var file_get_description = function(node) {
187             var description = '';
188             if (node.description) {
189                 description = node.description;
190             } else if (node.thumbnail_title) {
191                 description = node.thumbnail_title;
192             } else {
193                 description = file_get_filename(node);
194             }
195             return Y.Escape.html(description);
196         };
197         /** help funciton for tree view */
198         var build_tree = function(node, level) {
199             // prepare file name with icon
200             var el = Y.Node.create('<div/>');
201             el.appendChild(options.filenode.cloneNode(true));
203             el.one('.fp-filename').setContent(file_get_displayname(node));
204             // TODO add tooltip with node.title or node.thumbnail_title
205             var tmpnodedata = {className:options.classnamecallback(node)};
206             el.get('children').addClass(tmpnodedata.className);
207             if (node.icon) {
208                 el.one('.fp-icon').appendChild(Y.Node.create('<img/>'));
209                 el.one('.fp-icon img').setImgSrc(node.icon, node.realicon, lazyloading);
210             }
211             // create node
212             tmpnodedata.html = el.getContent();
213             var tmpNode = new Y.YUI2.widget.HTMLNode(tmpnodedata, level, false);
214             if (node.dynamicLoadComplete) {
215                 tmpNode.dynamicLoadComplete = true;
216             }
217             tmpNode.fileinfo = node;
218             tmpNode.isLeaf = !file_is_folder(node);
219             if (!tmpNode.isLeaf) {
220                 if(node.expanded) {
221                     tmpNode.expand();
222                 }
223                 tmpNode.path = node.path ? node.path : (node.filepath ? node.filepath : '');
224                 for(var c in node.children) {
225                     build_tree(node.children[c], tmpNode);
226                 }
227             }
228         };
229         /** initialize tree view */
230         var initialize_tree_view = function() {
231             var parentid = scope.one('.'+classname).get('id');
232             // TODO MDL-32736 use YUI3 gallery TreeView
233             scope.treeview = new Y.YUI2.widget.TreeView(parentid);
234             if (options.dynload) {
235                 scope.treeview.setDynamicLoad(Y.bind(options.treeview_dynload, options.callbackcontext), 1);
236             }
237             scope.treeview.singleNodeHighlight = true;
238             if (options.filepath && options.filepath.length) {
239                 // we just jumped from icon/details view, we need to show all parents
240                 // we extract as much information as possible from filepath and filelist
241                 // and send additional requests to retrieve siblings for parent folders
242                 var mytree = {};
243                 var mytreeel = null;
244                 for (var i in options.filepath) {
245                     if (mytreeel == null) {
246                         mytreeel = mytree;
247                     } else {
248                         mytreeel.children = [{}];
249                         mytreeel = mytreeel.children[0];
250                     }
251                     var pathelement = options.filepath[i];
252                     mytreeel.path = pathelement.path;
253                     mytreeel.title = pathelement.name;
254                     mytreeel.icon = pathelement.icon;
255                     mytreeel.dynamicLoadComplete = true; // we will call it manually
256                     mytreeel.expanded = true;
257                 }
258                 mytreeel.children = fileslist;
259                 build_tree(mytree, scope.treeview.getRoot());
260                 // manually call dynload for parent elements in the tree so we can load other siblings
261                 if (options.dynload) {
262                     var root = scope.treeview.getRoot();
263                     while (root && root.children && root.children.length) {
264                         root = root.children[0];
265                         if (root.path == mytreeel.path) {
266                             root.origpath = options.filepath;
267                             root.origlist = fileslist;
268                         }
269                         // Removed bind as of MDL-62415 as it overwrites the search tree results
270                     }
271                 }
272             } else {
273                 // there is no path information, just display all elements as a list, without hierarchy
274                 for(k in fileslist) {
275                     build_tree(fileslist[k], scope.treeview.getRoot());
276                 }
277             }
278             scope.treeview.subscribe('clickEvent', function(e){
279                 e.node.highlight(false);
280                 var callback = options.callback;
281                 if (options.rightclickcallback && e.event.target &&
282                         Y.Node(e.event.target).ancestor('.fp-treeview .fp-contextmenu', true)) {
283                     callback = options.rightclickcallback;
284                 }
285                 Y.bind(callback, options.callbackcontext)(e, e.node.fileinfo);
286                 Y.YUI2.util.Event.stopEvent(e.event)
287             });
288             // TODO MDL-32736 support right click
289             /*if (options.rightclickcallback) {
290                 scope.treeview.subscribe('dblClickEvent', function(e){
291                     e.node.highlight(false);
292                     Y.bind(options.rightclickcallback, options.callbackcontext)(e, e.node.fileinfo);
293                 });
294             }*/
295             scope.treeview.draw();
296         };
297         /** formatting function for table view */
298         var formatValue = function (o){
299             if (o.data[''+o.column.key+'_f_s']) {return o.data[''+o.column.key+'_f_s'];}
300             else if (o.data[''+o.column.key+'_f']) {return o.data[''+o.column.key+'_f'];}
301             else if (o.value) {return o.value;}
302             else {return '';}
303         };
304         /** formatting function for table view */
305         var formatTitle = function(o) {
306             var el = Y.Node.create('<div/>');
307             el.appendChild(options.filenode.cloneNode(true)); // TODO not node but string!
308             el.get('children').addClass(o.data['classname']);
309             el.one('.fp-filename').setContent(o.value);
310             if (o.data['icon']) {
311                 el.one('.fp-icon').appendChild(Y.Node.create('<img/>'));
312                 el.one('.fp-icon img').setImgSrc(o.data['icon'], o.data['realicon'], lazyloading);
313             }
314             if (options.rightclickcallback) {
315                 el.get('children').addClass('fp-hascontextmenu');
316             }
317             // TODO add tooltip with o.data['title'] (o.value) or o.data['thumbnail_title']
318             return el.getContent();
319         }
320         /** sorting function for table view */
321         var sortFoldersFirst = function(a, b, desc) {
322             if (a.get('isfolder') && !b.get('isfolder')) {
323                 return -1;
324             }
325             if (!a.get('isfolder') && b.get('isfolder')) {
326                 return 1;
327             }
328             var aa = a.get(this.key), bb = b.get(this.key), dir = desc ? -1 : 1;
329             return (aa > bb) ? dir : ((aa < bb) ? -dir : 0);
330         }
331         /** initialize table view */
332         var initialize_table_view = function() {
333             var cols = [
334                 {key: "displayname", label: M.util.get_string('name', 'moodle'), allowHTML: true, formatter: formatTitle,
335                     sortable: true, sortFn: sortFoldersFirst},
336                 {key: "datemodified", label: M.util.get_string('lastmodified', 'moodle'), allowHTML: true, formatter: formatValue,
337                     sortable: true, sortFn: sortFoldersFirst},
338                 {key: "size", label: M.util.get_string('size', 'repository'), allowHTML: true, formatter: formatValue,
339                     sortable: true, sortFn: sortFoldersFirst},
340                 {key: "mimetype", label: M.util.get_string('type', 'repository'), allowHTML: true,
341                     sortable: true, sortFn: sortFoldersFirst}
342             ];
343             scope.tableview = new Y.DataTable({columns: cols, data: fileslist});
344             scope.tableview.delegate('click', function (e, tableview) {
345                 var record = tableview.getRecord(e.currentTarget.get('id'));
346                 if (record) {
347                     var callback = options.callback;
348                     if (options.rightclickcallback && e.target.ancestor('.fp-tableview .fp-contextmenu', true)) {
349                         callback = options.rightclickcallback;
350                     }
351                     Y.bind(callback, this)(e, record.getAttrs());
352                 }
353             }, 'tr', options.callbackcontext, scope.tableview);
354             if (options.rightclickcallback) {
355                 scope.tableview.delegate('contextmenu', function (e, tableview) {
356                     var record = tableview.getRecord(e.currentTarget.get('id'));
357                     if (record) { Y.bind(options.rightclickcallback, this)(e, record.getAttrs()); }
358                 }, 'tr', options.callbackcontext, scope.tableview);
359             }
360         }
361         /** append items in table view mode */
362         var append_files_table = function() {
363             if (options.appendonly) {
364                 fileslist.forEach(function(el) {
365                     this.tableview.data.add(el);
366                 },scope);
367             }
368             scope.tableview.render(scope.one('.'+classname));
369             scope.tableview.sortable = options.sortable ? true : false;
370         };
371         /** append items in tree view mode */
372         var append_files_tree = function() {
373             if (options.appendonly) {
374                 var parentnode = scope.treeview.getRoot();
375                 if (scope.treeview.getHighlightedNode()) {
376                     parentnode = scope.treeview.getHighlightedNode();
377                     if (parentnode.isLeaf) {parentnode = parentnode.parent;}
378                 }
379                 for (var k in fileslist) {
380                     build_tree(fileslist[k], parentnode);
381                 }
382                 scope.treeview.draw();
383             } else {
384                 // otherwise files were already added in initialize_tree_view()
385             }
386         }
387         /** append items in icon view mode */
388         var append_files_icons = function() {
389             parent = scope.one('.'+classname);
390             for (var k in fileslist) {
391                 var node = fileslist[k];
392                 var element = options.filenode.cloneNode(true);
393                 parent.appendChild(element);
394                 element.addClass(options.classnamecallback(node));
395                 var filenamediv = element.one('.fp-filename');
396                 filenamediv.setContent(file_get_displayname(node));
397                 var imgdiv = element.one('.fp-thumbnail'), width, height, src;
398                 if (node.thumbnail) {
399                     width = node.thumbnail_width ? node.thumbnail_width : 90;
400                     height = node.thumbnail_height ? node.thumbnail_height : 90;
401                     src = node.thumbnail;
402                 } else {
403                     width = 16;
404                     height = 16;
405                     src = node.icon;
406                 }
407                 filenamediv.setStyleAdv('width', width);
408                 imgdiv.setStyleAdv('width', width).setStyleAdv('height', height);
409                 var img = Y.Node.create('<img/>').setAttrs({
410                         title: file_get_description(node),
411                         alt: Y.Escape.html(node.thumbnail_alt ? node.thumbnail_alt : file_get_filename(node))}).
412                     setStyle('maxWidth', ''+width+'px').
413                     setStyle('maxHeight', ''+height+'px');
414                 img.setImgSrc(src, node.realthumbnail, lazyloading);
415                 imgdiv.appendChild(img);
416                 element.on('click', function(e, nd) {
417                     if (options.rightclickcallback && e.target.ancestor('.fp-iconview .fp-contextmenu', true)) {
418                         Y.bind(options.rightclickcallback, this)(e, nd);
419                     } else {
420                         Y.bind(options.callback, this)(e, nd);
421                     }
422                 }, options.callbackcontext, node);
423                 if (options.rightclickcallback) {
424                     element.on('contextmenu', options.rightclickcallback, options.callbackcontext, node);
425                 }
426             }
427         }
429         // Notify the user if any of the files has a problem status.
430         var problemFiles = [];
431         fileslist.forEach(function(file) {
432             if (!file_is_folder(file) && file.hasOwnProperty('status') && file.status != 0) {
433                 problemFiles.push(file);
434             }
435         });
436         if (problemFiles.length > 0) {
437             require(["core/notification", "core/str"], function(Notification, Str) {
438                 problemFiles.forEach(function(problemFile) {
439                     Str.get_string('storedfilecannotreadfile', 'error', problemFile.fullname).then(function(string) {
440                         Notification.addNotification({
441                             message: string,
442                             type: "error"
443                         });
444                         return;
445                     }).catch(Notification.exception);
446                 });
447             });
448         }
450         // If table view, need some additional properties
451         // before passing fileslist to the YUI tableview
452         if (options.viewmode == 3) {
453             fileslist.forEach(function(el) {
454                 el.displayname = file_get_displayname(el);
455                 el.isfolder = file_is_folder(el);
456                 el.classname = options.classnamecallback(el);
457             }, scope);
458         }
460         // initialize files view
461         if (!options.appendonly) {
462             var parent = Y.Node.create('<div/>').addClass(classname);
463             this.setContent('').appendChild(parent);
464             parent.generateID();
465             if (options.viewmode == 2) {
466                 initialize_tree_view();
467             } else if (options.viewmode == 3) {
468                 initialize_table_view();
469             } else {
470                 // nothing to initialize for icon view
471             }
472         }
474         // append files to the list
475         if (options.viewmode == 2) {
476             append_files_tree();
477         } else if (options.viewmode == 3) {
478             append_files_table();
479         } else {
480             append_files_icons();
481         }
483     }
484 }, '@VERSION@', {
485     requires:['base', 'node', 'yui2-treeview', 'panel', 'cookie', 'datatable', 'datatable-sort']
488 M.core_filepicker = M.core_filepicker || {};
491  * instances of file pickers used on page
492  */
493 M.core_filepicker.instances = M.core_filepicker.instances || {};
494 M.core_filepicker.active_filepicker = null;
497  * HTML Templates to use in FilePicker
498  */
499 M.core_filepicker.templates = M.core_filepicker.templates || {};
502  * Array of image sources for real previews (realicon or realthumbnail) that are already loaded
503  */
504 M.core_filepicker.loadedpreviews = M.core_filepicker.loadedpreviews || {};
507 * Set selected file info
509 * @param object file info
511 M.core_filepicker.select_file = function(file) {
512     M.core_filepicker.active_filepicker.select_file(file);
516  * Init and show file picker
517  */
518 M.core_filepicker.show = function(Y, options) {
519     if (!M.core_filepicker.instances[options.client_id]) {
520         M.core_filepicker.init(Y, options);
521     }
522     M.core_filepicker.instances[options.client_id].options.formcallback = options.formcallback;
523     M.core_filepicker.instances[options.client_id].show();
526 M.core_filepicker.set_templates = function(Y, templates) {
527     for (var templid in templates) {
528         M.core_filepicker.templates[templid] = templates[templid];
529     }
533  * Add new file picker to current instances
534  */
535 M.core_filepicker.init = function(Y, options) {
536     var FilePickerHelper = function(options) {
537         FilePickerHelper.superclass.constructor.apply(this, arguments);
538     };
540     FilePickerHelper.NAME = "FilePickerHelper";
541     FilePickerHelper.ATTRS = {
542         options: {},
543         lang: {}
544     };
546     Y.extend(FilePickerHelper, Y.Base, {
547         api: M.cfg.wwwroot+'/repository/repository_ajax.php',
548         cached_responses: {},
549         waitinterval : null, // When the loading template is being displayed and its animation is running this will be an interval instance.
550         initializer: function(options) {
551             this.options = options;
552             if (!this.options.savepath) {
553                 this.options.savepath = '/';
554             }
555         },
557         destructor: function() {
558         },
560         request: function(args, redraw) {
561             var api = (args.api ? args.api : this.api) + '?action='+args.action;
562             var params = {};
563             var scope = args['scope'] ? args['scope'] : this;
564             params['repo_id']=args.repository_id;
565             params['p'] = args.path?args.path:'';
566             params['page'] = args.page?args.page:'';
567             params['env']=this.options.env;
568             // the form element only accept certain file types
569             params['accepted_types']=this.options.accepted_types;
570             params['sesskey'] = M.cfg.sesskey;
571             params['client_id'] = args.client_id;
572             params['itemid'] = this.options.itemid?this.options.itemid:0;
573             params['maxbytes'] = this.options.maxbytes?this.options.maxbytes:-1;
574             // The unlimited value of areamaxbytes is -1, it is defined by FILE_AREA_MAX_BYTES_UNLIMITED.
575             params['areamaxbytes'] = this.options.areamaxbytes ? this.options.areamaxbytes : -1;
576             if (this.options.context && this.options.context.id) {
577                 params['ctx_id'] = this.options.context.id;
578             }
579             if (args['params']) {
580                 for (i in args['params']) {
581                     params[i] = args['params'][i];
582                 }
583             }
584             if (args.action == 'upload') {
585                 var list = [];
586                 for(var k in params) {
587                     var value = params[k];
588                     if(value instanceof Array) {
589                         for(var i in value) {
590                             list.push(k+'[]='+value[i]);
591                         }
592                     } else {
593                         list.push(k+'='+value);
594                     }
595                 }
596                 params = list.join('&');
597             } else {
598                 params = build_querystring(params);
599             }
600             var cfg = {
601                 method: 'POST',
602                 on: {
603                     complete: function(id,o,p) {
604                         var data = null;
605                         try {
606                             data = Y.JSON.parse(o.responseText);
607                         } catch(e) {
608                             if (o && o.status && o.status > 0) {
609                                 Y.use('moodle-core-notification-exception', function() {
610                                     return new M.core.exception(e);
611                                 });
612                                 return;
613                             }
614                         }
615                         // error checking
616                         if (data && data.error) {
617                             Y.use('moodle-core-notification-ajaxexception', function () {
618                                 return new M.core.ajaxException(data);
619                             });
620                             this.fpnode.one('.fp-content').setContent('');
621                             return;
622                         } else {
623                             if (data.msg) {
624                                 scope.print_msg(data.msg, 'info');
625                             }
626                             // cache result if applicable
627                             if (args.action != 'upload' && data.allowcaching) {
628                                 scope.cached_responses[params] = data;
629                             }
630                             // invoke callback
631                             args.callback(id,data,p);
632                         }
633                     }
634                 },
635                 arguments: {
636                     scope: scope
637                 },
638                 headers: {
639                     'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
640                 },
641                 data: params,
642                 context: this
643             };
644             if (args.form) {
645                 cfg.form = args.form;
646             }
647             // check if result of the same request has been already cached. If not, request it
648             // (never applicable in case of form submission and/or upload action):
649             if (!args.form && args.action != 'upload' && scope.cached_responses[params]) {
650                 args.callback(null, scope.cached_responses[params], {scope: scope})
651             } else {
652                 Y.io(api, cfg);
653                 if (redraw) {
654                     this.wait();
655                 }
656             }
657         },
658         /** displays the dialog and processes rename/overwrite if there is a file with the same name in the same filearea*/
659         process_existing_file: function(data) {
660             var scope = this;
661             var handleOverwrite = function(e) {
662                 // overwrite
663                 e.preventDefault();
664                 var data = this.process_dlg.dialogdata;
665                 var params = {}
666                 params['existingfilename'] = data.existingfile.filename;
667                 params['existingfilepath'] = data.existingfile.filepath;
668                 params['newfilename'] = data.newfile.filename;
669                 params['newfilepath'] = data.newfile.filepath;
670                 this.hide_header();
671                 this.request({
672                     'params': params,
673                     'scope': this,
674                     'action':'overwrite',
675                     'path': '',
676                     'client_id': this.options.client_id,
677                     'repository_id': this.active_repo.id,
678                     'callback': function(id, o, args) {
679                         scope.hide();
680                         // Add an arbitrary parameter to the URL to force browsers to re-load the new image even
681                         // if the file name has not changed.
682                         var urlimage = data.existingfile.url + "?time=" + (new Date()).getTime();
683                         if (scope.options.editor_target && scope.options.env == 'editor') {
684                             // editor needs to update url
685                             scope.options.editor_target.value = urlimage;
686                             scope.options.editor_target.onchange();
687                         }
688                         var fileinfo = {'client_id':scope.options.client_id,
689                             'url': urlimage,
690                             'file': data.existingfile.filename};
691                         var formcallback_scope = scope.options.magicscope ? scope.options.magicscope : scope;
692                         scope.options.formcallback.apply(formcallback_scope, [fileinfo]);
693                     }
694                 }, true);
695             }
696             var handleRename = function(e) {
697                 // inserts file with the new name
698                 e.preventDefault();
699                 var scope = this;
700                 var data = this.process_dlg.dialogdata;
701                 if (scope.options.editor_target && scope.options.env == 'editor') {
702                     scope.options.editor_target.value = data.newfile.url;
703                     scope.options.editor_target.onchange();
704                 }
705                 scope.hide();
706                 var formcallback_scope = scope.options.magicscope ? scope.options.magicscope : scope;
707                 var fileinfo = {'client_id':scope.options.client_id,
708                                 'url':data.newfile.url,
709                                 'file':data.newfile.filename};
710                 scope.options.formcallback.apply(formcallback_scope, [fileinfo]);
711             }
712             var handleCancel = function(e) {
713                 // Delete tmp file
714                 e.preventDefault();
715                 var params = {};
716                 params['newfilename'] = this.process_dlg.dialogdata.newfile.filename;
717                 params['newfilepath'] = this.process_dlg.dialogdata.newfile.filepath;
718                 this.request({
719                     'params': params,
720                     'scope': this,
721                     'action':'deletetmpfile',
722                     'path': '',
723                     'client_id': this.options.client_id,
724                     'repository_id': this.active_repo.id,
725                     'callback': function(id, o, args) {
726                         // let it be in background, from user point of view nothing is happenning
727                     }
728                 }, false);
729                 this.process_dlg.hide();
730                 this.selectui.hide();
731             }
732             if (!this.process_dlg) {
733                 this.process_dlg_node = Y.Node.create(M.core_filepicker.templates.processexistingfile);
734                 var node = this.process_dlg_node;
735                 node.generateID();
736                 this.process_dlg = new M.core.dialogue({
737                     draggable    : true,
738                     bodyContent  : node,
739                     headerContent: M.util.get_string('fileexistsdialogheader', 'repository'),
740                     centered     : true,
741                     modal        : true,
742                     visible      : false,
743                     zIndex       : this.options.zIndex
744                 });
745                 node.one('.fp-dlg-butoverwrite').on('click', handleOverwrite, this);
746                 node.one('.fp-dlg-butrename').on('click', handleRename, this);
747                 node.one('.fp-dlg-butcancel').on('click', handleCancel, this);
748                 if (this.options.env == 'editor') {
749                     node.one('.fp-dlg-text').setContent(M.util.get_string('fileexistsdialog_editor', 'repository'));
750                 } else {
751                     node.one('.fp-dlg-text').setContent(M.util.get_string('fileexistsdialog_filemanager', 'repository'));
752                 }
753             }
754             this.selectnode.removeClass('loading');
755             this.process_dlg.dialogdata = data;
756             this.process_dlg_node.one('.fp-dlg-butrename').setContent(M.util.get_string('renameto', 'repository', data.newfile.filename));
757             this.process_dlg.show();
758         },
759         /** displays error instead of filepicker contents */
760         display_error: function(errortext, errorcode) {
761             this.fpnode.one('.fp-content').setContent(M.core_filepicker.templates.error);
762             this.fpnode.one('.fp-content .fp-error').
763                 addClass(errorcode).
764                 setContent(Y.Escape.html(errortext));
765         },
766         /** displays message in a popup */
767         print_msg: function(msg, type) {
768             var header = M.util.get_string('error', 'moodle');
769             if (type != 'error') {
770                 type = 'info'; // one of only two types excepted
771                 header = M.util.get_string('info', 'moodle');
772             }
773             if (!this.msg_dlg) {
774                 this.msg_dlg_node = Y.Node.create(M.core_filepicker.templates.message);
775                 this.msg_dlg_node.generateID();
777                 this.msg_dlg = new M.core.dialogue({
778                     draggable    : true,
779                     bodyContent  : this.msg_dlg_node,
780                     centered     : true,
781                     modal        : true,
782                     visible      : false,
783                     zIndex       : this.options.zIndex
784                 });
785                 this.msg_dlg_node.one('.fp-msg-butok').on('click', function(e) {
786                     e.preventDefault();
787                     this.msg_dlg.hide();
788                 }, this);
789             }
791             this.msg_dlg.set('headerContent', header);
792             this.msg_dlg_node.removeClass('fp-msg-info').removeClass('fp-msg-error').addClass('fp-msg-'+type)
793             this.msg_dlg_node.one('.fp-msg-text').setContent(Y.Escape.html(msg));
794             this.msg_dlg.show();
795         },
796         view_files: function(appenditems) {
797             this.viewbar_set_enabled(true);
798             this.print_path();
799             /*if ((appenditems == null) && (!this.filelist || !this.filelist.length) && !this.active_repo.hasmorepages) {
800              // TODO do it via classes and adjust for each view mode!
801                 // If there are no items and no next page, just display status message and quit
802                 this.display_error(M.util.get_string('nofilesavailable', 'repository'), 'nofilesavailable');
803                 return;
804             }*/
805             if (this.viewmode == 2) {
806                 this.view_as_list(appenditems);
807             } else if (this.viewmode == 3) {
808                 this.view_as_table(appenditems);
809             } else {
810                 this.view_as_icons(appenditems);
811             }
812             this.fpnode.one('.fp-content').setAttribute('tabindex', '0');
813             this.fpnode.one('.fp-content').focus();
814             // display/hide the link for requesting next page
815             if (!appenditems && this.active_repo.hasmorepages) {
816                 if (!this.fpnode.one('.fp-content .fp-nextpage')) {
817                     this.fpnode.one('.fp-content').append(M.core_filepicker.templates.nextpage);
818                 }
819                 this.fpnode.one('.fp-content .fp-nextpage').one('a,button').on('click', function(e) {
820                     e.preventDefault();
821                     this.fpnode.one('.fp-content .fp-nextpage').addClass('loading');
822                     this.request_next_page();
823                 }, this);
824             }
825             if (!this.active_repo.hasmorepages && this.fpnode.one('.fp-content .fp-nextpage')) {
826                 this.fpnode.one('.fp-content .fp-nextpage').remove();
827             }
828             if (this.fpnode.one('.fp-content .fp-nextpage')) {
829                 this.fpnode.one('.fp-content .fp-nextpage').removeClass('loading');
830             }
831             this.content_scrolled();
832         },
833         content_scrolled: function(e) {
834             setTimeout(Y.bind(function() {
835                 if (this.processingimages) {
836                     return;
837                 }
838                 this.processingimages = true;
839                 var scope = this,
840                     fpcontent = this.fpnode.one('.fp-content'),
841                     fpcontenty = fpcontent.getY(),
842                     fpcontentheight = fpcontent.getStylePx('height'),
843                     nextpage = fpcontent.one('.fp-nextpage'),
844                     is_node_visible = function(node) {
845                         var offset = node.getY()-fpcontenty;
846                         if (offset <= fpcontentheight && (offset >=0 || offset+node.getStylePx('height')>=0)) {
847                             return true;
848                         }
849                         return false;
850                     };
851                 // automatically load next page when 'more' link becomes visible
852                 if (nextpage && !nextpage.hasClass('loading') && is_node_visible(nextpage)) {
853                     nextpage.one('a,button').simulate('click');
854                 }
855                 // replace src for visible images that need to be lazy-loaded
856                 if (scope.lazyloading) {
857                     fpcontent.all('img').each( function(node) {
858                         if (node.get('id') && scope.lazyloading[node.get('id')] && is_node_visible(node)) {
859                             node.setImgRealSrc(scope.lazyloading);
860                         }
861                     });
862                 }
863                 this.processingimages = false;
864             }, this), 200)
865         },
866         treeview_dynload: function(node, cb) {
867             var retrieved_children = {};
868             if (node.children) {
869                 for (var i in node.children) {
870                     retrieved_children[node.children[i].path] = node.children[i];
871                 }
872             }
873             this.request({
874                 action:'list',
875                 client_id: this.options.client_id,
876                 repository_id: this.active_repo.id,
877                 path:node.path?node.path:'',
878                 page:node.page?args.page:'',
879                 scope:this,
880                 callback: function(id, obj, args) {
881                     var list = obj.list;
882                     var scope = args.scope;
883                     // check that user did not leave the view mode before recieving this response
884                     if (!(scope.active_repo.id == obj.repo_id && scope.viewmode == 2 && node && node.getChildrenEl())) {
885                         return;
886                     }
887                     if (cb != null) { // (in manual mode do not update current path)
888                         scope.viewbar_set_enabled(true);
889                         scope.parse_repository_options(obj);
890                     }
891                     node.highlight(false);
892                     node.origlist = obj.list ? obj.list : null;
893                     node.origpath = obj.path ? obj.path : null;
894                     node.children = [];
895                     for(k in list) {
896                         if (list[k].children && retrieved_children[list[k].path]) {
897                             // if this child is a folder and has already been retrieved
898                             node.children[node.children.length] = retrieved_children[list[k].path];
899                         } else {
900                             // append new file to the list
901                             scope.view_as_list([list[k]]);
902                         }
903                     }
904                     if (cb == null) {
905                         node.refresh();
906                     } else {
907                         // invoke callback requested by TreeView component
908                         cb();
909                     }
910                     scope.content_scrolled();
911                 }
912             }, false);
913         },
914        classnamecallback : function(node) {
915             var classname = '';
916             if (node.children) {
917                 classname = classname + ' fp-folder';
918             }
919             if (node.isref) {
920                 classname = classname + ' fp-isreference';
921             }
922             if (node.iscontrolledlink) {
923                 classname = classname + ' fp-iscontrolledlink';
924             }
925             if (node.refcount) {
926                 classname = classname + ' fp-hasreferences';
927             }
928             if (node.originalmissing) {
929                 classname = classname + ' fp-originalmissing';
930             }
931             return Y.Lang.trim(classname);
932         },
933         /** displays list of files in tree (list) view mode. If param appenditems is specified,
934          * appends those items to the end of the list. Otherwise (default behaviour)
935          * clears the contents and displays the items from this.filelist */
936         view_as_list: function(appenditems) {
937             var list = (appenditems != null) ? appenditems : this.filelist;
938             this.viewmode = 2;
939             if (!this.filelist || this.filelist.length==0 && (!this.filepath || !this.filepath.length)) {
940                 this.display_error(M.util.get_string('nofilesavailable', 'repository'), 'nofilesavailable');
941                 return;
942             }
944             var element_template = Y.Node.create(M.core_filepicker.templates.listfilename);
945             var options = {
946                 viewmode : this.viewmode,
947                 appendonly : (appenditems != null),
948                 filenode : element_template,
949                 callbackcontext : this,
950                 callback : function(e, node) {
951                     // TODO MDL-32736 e is not an event here but an object with properties 'event' and 'node'
952                     if (!node.children) {
953                         if (e.node.parent && e.node.parent.origpath) {
954                             // set the current path
955                             this.filepath = e.node.parent.origpath;
956                             this.filelist = e.node.parent.origlist;
957                             this.print_path();
958                         }
959                         this.select_file(node);
960                     } else {
961                         // save current path and filelist (in case we want to jump to other viewmode)
962                         this.filepath = e.node.origpath;
963                         this.filelist = e.node.origlist;
964                         this.currentpath = e.node.path;
965                         this.print_path();
966                         this.content_scrolled();
967                     }
968                 },
969                 classnamecallback : this.classnamecallback,
970                 dynload : this.active_repo.dynload,
971                 filepath : this.filepath,
972                 treeview_dynload : this.treeview_dynload
973             };
974             this.fpnode.one('.fp-content').fp_display_filelist(options, list, this.lazyloading);
975         },
976         /** displays list of files in icon view mode. If param appenditems is specified,
977          * appends those items to the end of the list. Otherwise (default behaviour)
978          * clears the contents and displays the items from this.filelist */
979         view_as_icons: function(appenditems) {
980             this.viewmode = 1;
981             var list = (appenditems != null) ? appenditems : this.filelist;
982             var element_template = Y.Node.create(M.core_filepicker.templates.iconfilename);
983             if ((appenditems == null) && (!this.filelist || !this.filelist.length)) {
984                 this.display_error(M.util.get_string('nofilesavailable', 'repository'), 'nofilesavailable');
985                 return;
986             }
987             var options = {
988                 viewmode : this.viewmode,
989                 appendonly : (appenditems != null),
990                 filenode : element_template,
991                 callbackcontext : this,
992                 callback : function(e, node) {
993                     if (e.preventDefault) {
994                         e.preventDefault();
995                     }
996                     if(node.children) {
997                         if (this.active_repo.dynload) {
998                             this.list({'path':node.path});
999                         } else {
1000                             this.filelist = node.children;
1001                             this.view_files();
1002                         }
1003                     } else {
1004                         this.select_file(node);
1005                     }
1006                 },
1007                 classnamecallback : this.classnamecallback
1008             };
1009             this.fpnode.one('.fp-content').fp_display_filelist(options, list, this.lazyloading);
1010         },
1011         /** displays list of files in table view mode. If param appenditems is specified,
1012          * appends those items to the end of the list. Otherwise (default behaviour)
1013          * clears the contents and displays the items from this.filelist */
1014         view_as_table: function(appenditems) {
1015             this.viewmode = 3;
1016             var list = (appenditems != null) ? appenditems : this.filelist;
1017             if (!appenditems && (!this.filelist || this.filelist.length==0) && !this.active_repo.hasmorepages) {
1018                 this.display_error(M.util.get_string('nofilesavailable', 'repository'), 'nofilesavailable');
1019                 return;
1020             }
1021             var element_template = Y.Node.create(M.core_filepicker.templates.listfilename);
1022             var options = {
1023                 viewmode : this.viewmode,
1024                 appendonly : (appenditems != null),
1025                 filenode : element_template,
1026                 callbackcontext : this,
1027                 sortable : !this.active_repo.hasmorepages,
1028                 callback : function(e, node) {
1029                     if (e.preventDefault) {e.preventDefault();}
1030                     if (node.children) {
1031                         if (this.active_repo.dynload) {
1032                             this.list({'path':node.path});
1033                         } else {
1034                             this.filelist = node.children;
1035                             this.view_files();
1036                         }
1037                     } else {
1038                         this.select_file(node);
1039                     }
1040                 },
1041                 classnamecallback : this.classnamecallback
1042             };
1043             this.fpnode.one('.fp-content').fp_display_filelist(options, list, this.lazyloading);
1044         },
1045         /** If more than one page available, requests and displays the files from the next page */
1046         request_next_page: function() {
1047             if (!this.active_repo.hasmorepages || this.active_repo.nextpagerequested) {
1048                 // nothing to load
1049                 return;
1050             }
1051             this.active_repo.nextpagerequested = true;
1052             var nextpage = this.active_repo.page+1;
1053             var args = {
1054                 page: nextpage,
1055                 repo_id: this.active_repo.id
1056             };
1057             var action = this.active_repo.issearchresult ? 'search' : 'list';
1058             this.request({
1059                 path: this.currentpath,
1060                 scope: this,
1061                 action: action,
1062                 client_id: this.options.client_id,
1063                 repository_id: args.repo_id,
1064                 params: args,
1065                 callback: function(id, obj, args) {
1066                     var scope = args.scope;
1067                     // Check that we are still in the same repository and are expecting this page. We have no way
1068                     // to compare the requested page and the one returned, so we assume that if the last chunk
1069                     // of the breadcrumb is similar, then we probably are on the same page.
1070                     var samepage = true;
1071                     if (obj.path && scope.filepath) {
1072                         var pathbefore = scope.filepath[scope.filepath.length-1];
1073                         var pathafter = obj.path[obj.path.length-1];
1074                         if (pathbefore.path != pathafter.path) {
1075                             samepage = false;
1076                         }
1077                     }
1078                     if (scope.active_repo.hasmorepages && obj.list && obj.page &&
1079                             obj.repo_id == scope.active_repo.id &&
1080                             obj.page == scope.active_repo.page+1 && samepage) {
1081                         scope.parse_repository_options(obj, true);
1082                         scope.view_files(obj.list)
1083                     }
1084                 }
1085             }, false);
1086         },
1087         select_file: function(args) {
1088             var argstitle = args.title;
1089             // Limit the string length so it fits nicely on mobile devices
1090             var titlelength = 30;
1091             if (argstitle.length > titlelength) {
1092                 argstitle = argstitle.substring(0, titlelength) + '...';
1093             }
1094             Y.one('#fp-file_label_'+this.options.client_id).setContent(Y.Escape.html(M.util.get_string('select', 'repository')+' '+argstitle));
1095             this.selectui.show();
1096             Y.one('#'+this.selectnode.get('id')).focus();
1097             var client_id = this.options.client_id;
1098             var selectnode = this.selectnode;
1099             var return_types = this.options.repositories[this.active_repo.id].return_types;
1100             selectnode.removeClass('loading');
1101             selectnode.one('.fp-saveas input').set('value', args.title);
1103             var imgnode = Y.Node.create('<img/>').
1104                 set('src', args.realthumbnail ? args.realthumbnail : args.thumbnail).
1105                 setStyle('maxHeight', ''+(args.thumbnail_height ? args.thumbnail_height : 90)+'px').
1106                 setStyle('maxWidth', ''+(args.thumbnail_width ? args.thumbnail_width : 90)+'px');
1107             selectnode.one('.fp-thumbnail').setContent('').appendChild(imgnode);
1109             // filelink is the array of file-link-types available for this repository in this env
1110             var filelinktypes = [2/*FILE_INTERNAL*/,1/*FILE_EXTERNAL*/,4/*FILE_REFERENCE*/,8/*FILE_CONTROLLED_LINK*/];
1111             var filelink = {}, firstfilelink = null, filelinkcount = 0;
1112             for (var i in filelinktypes) {
1113                 var allowed = (return_types & filelinktypes[i]) &&
1114                     (this.options.return_types & filelinktypes[i]);
1115                 if (filelinktypes[i] == 1/*FILE_EXTERNAL*/ && !this.options.externallink && this.options.env == 'editor') {
1116                     // special configuration setting 'repositoryallowexternallinks' may prevent
1117                     // using external links in editor environment
1118                     allowed = false;
1119                 }
1120                 filelink[filelinktypes[i]] = allowed;
1121                 firstfilelink = (firstfilelink==null && allowed) ? filelinktypes[i] : firstfilelink;
1122                 filelinkcount += allowed ? 1 : 0;
1123             }
1124             var defaultreturntype = this.options.repositories[this.active_repo.id].defaultreturntype;
1125             if (defaultreturntype) {
1126                 if (filelink[defaultreturntype]) {
1127                     firstfilelink = defaultreturntype;
1128                 }
1129             }
1130             // make radio buttons enabled if this file-link-type is available and only if there are more than one file-link-type option
1131             // check the first available file-link-type option
1132             for (var linktype in filelink) {
1133                 var el = selectnode.one('.fp-linktype-'+linktype);
1134                 el.addClassIf('uneditable', !(filelink[linktype] && filelinkcount>1));
1135                 el.one('input').set('checked', (firstfilelink == linktype) ? 'checked' : '').simulate('change');
1136             }
1138             // TODO MDL-32532: attributes 'hasauthor' and 'haslicense' need to be obsolete,
1139             selectnode.one('.fp-setauthor input').set('value', args.author ? args.author : this.options.author);
1140             this.set_selected_license(selectnode.one('.fp-setlicense'), args.license);
1141             selectnode.one('form #filesource-'+client_id).set('value', args.source);
1142             selectnode.one('form #filesourcekey-'+client_id).set('value', args.sourcekey);
1144             // display static information about a file (when known)
1145             var attrs = ['datemodified','datecreated','size','license','author','dimensions'];
1146             for (var i in attrs) {
1147                 if (selectnode.one('.fp-'+attrs[i])) {
1148                     var value = (args[attrs[i]+'_f']) ? args[attrs[i]+'_f'] : (args[attrs[i]] ? args[attrs[i]] : '');
1149                     selectnode.one('.fp-'+attrs[i]).addClassIf('fp-unknown', ''+value == '')
1150                         .one('.fp-value').setContent(Y.Escape.html(value));
1151                 }
1152             }
1153         },
1154         setup_select_file: function() {
1155             var client_id = this.options.client_id;
1156             var selectnode = this.selectnode;
1157             var getfile = selectnode.one('.fp-select-confirm');
1158             // bind labels with corresponding inputs
1159             selectnode.all('.fp-saveas,.fp-linktype-2,.fp-linktype-1,.fp-linktype-4,fp-linktype-8,.fp-setauthor,.fp-setlicense').each(function (node) {
1160                 node.all('label').set('for', node.one('input,select').generateID());
1161             });
1162             selectnode.one('.fp-linktype-2 input').setAttrs({value: 2, name: 'linktype'});
1163             selectnode.one('.fp-linktype-1 input').setAttrs({value: 1, name: 'linktype'});
1164             selectnode.one('.fp-linktype-4 input').setAttrs({value: 4, name: 'linktype'});
1165             selectnode.one('.fp-linktype-8 input').setAttrs({value: 8, name: 'linktype'});
1166             var changelinktype = function(e) {
1167                 if (e.currentTarget.get('checked')) {
1168                     var allowinputs = e.currentTarget.get('value') != 1/*FILE_EXTERNAL*/;
1169                     selectnode.all('.fp-setauthor,.fp-setlicense,.fp-saveas').each(function(node){
1170                         node.addClassIf('uneditable', !allowinputs);
1171                         node.all('input,select').set('disabled', allowinputs?'':'disabled');
1172                     });
1173                 }
1174             };
1175             selectnode.all('.fp-linktype-2,.fp-linktype-1,.fp-linktype-4,.fp-linktype-8').each(function (node) {
1176                 node.one('input').on('change', changelinktype, this);
1177             });
1178             this.populate_licenses_select(selectnode.one('.fp-setlicense select'));
1179             // register event on clicking submit button
1180             getfile.on('click', function(e) {
1181                 e.preventDefault();
1182                 var client_id = this.options.client_id;
1183                 var scope = this;
1184                 var repository_id = this.active_repo.id;
1185                 var title = selectnode.one('.fp-saveas input').get('value');
1186                 var filesource = selectnode.one('form #filesource-'+client_id).get('value');
1187                 var filesourcekey = selectnode.one('form #filesourcekey-'+client_id).get('value');
1188                 var params = {'title':title, 'source':filesource, 'savepath': this.options.savepath, sourcekey: filesourcekey};
1189                 var license = selectnode.one('.fp-setlicense select');
1190                 if (license) {
1191                     params['license'] = license.get('value');
1192                     var origlicense = selectnode.one('.fp-license .fp-value');
1193                     if (origlicense) {
1194                         origlicense = origlicense.getContent();
1195                     }
1196                     this.set_preference('recentlicense', license.get('value'));
1197                 }
1198                 params['author'] = selectnode.one('.fp-setauthor input').get('value');
1200                 var return_types = this.options.repositories[this.active_repo.id].return_types;
1201                 if (this.options.env == 'editor') {
1202                     // in editor, images are stored in '/' only
1203                     params.savepath = '/';
1204                 }
1205                 if ((this.options.externallink || this.options.env != 'editor') &&
1206                             (return_types & 1/*FILE_EXTERNAL*/) &&
1207                             (this.options.return_types & 1/*FILE_EXTERNAL*/) &&
1208                             selectnode.one('.fp-linktype-1 input').get('checked')) {
1209                     params['linkexternal'] = 'yes';
1210                 } else if ((return_types & 4/*FILE_REFERENCE*/) &&
1211                         (this.options.return_types & 4/*FILE_REFERENCE*/) &&
1212                         selectnode.one('.fp-linktype-4 input').get('checked')) {
1213                     params['usefilereference'] = '1';
1214                 } else if ((return_types & 8/*FILE_CONTROLLED_LINK*/) &&
1215                         (this.options.return_types & 8/*FILE_CONTROLLED_LINK*/) &&
1216                         selectnode.one('.fp-linktype-8 input').get('checked')) {
1217                     params['usecontrolledlink'] = '1';
1218                 }
1220                 selectnode.addClass('loading');
1221                 this.request({
1222                     action:'download',
1223                     client_id: client_id,
1224                     repository_id: repository_id,
1225                     'params': params,
1226                     onerror: function(id, obj, args) {
1227                         selectnode.removeClass('loading');
1228                         scope.selectui.hide();
1229                     },
1230                     callback: function(id, obj, args) {
1231                         selectnode.removeClass('loading');
1232                         if (obj.event == 'fileexists') {
1233                             scope.process_existing_file(obj);
1234                             return;
1235                         }
1236                         if (scope.options.editor_target && scope.options.env=='editor') {
1237                             scope.options.editor_target.value=obj.url;
1238                             scope.options.editor_target.onchange();
1239                         }
1240                         scope.hide();
1241                         obj.client_id = client_id;
1242                         var formcallback_scope = args.scope.options.magicscope ? args.scope.options.magicscope : args.scope;
1243                         scope.options.formcallback.apply(formcallback_scope, [obj]);
1244                     }
1245                 }, false);
1246             }, this);
1247             var elform = selectnode.one('form');
1248             elform.appendChild(Y.Node.create('<input/>').
1249                 setAttrs({type:'hidden',id:'filesource-'+client_id}));
1250             elform.appendChild(Y.Node.create('<input/>').
1251                 setAttrs({type:'hidden',id:'filesourcekey-'+client_id}));
1252             elform.on('keydown', function(e) {
1253                 if (e.keyCode == 13) {
1254                     getfile.simulate('click');
1255                     e.preventDefault();
1256                 }
1257             }, this);
1258             var cancel = selectnode.one('.fp-select-cancel');
1259             cancel.on('click', function(e) {
1260                 e.preventDefault();
1261                 this.selectui.hide();
1262             }, this);
1263         },
1264         wait: function() {
1265             // First check there isn't already an interval in play, and if there is kill it now.
1266             if (this.waitinterval != null) {
1267                 clearInterval(this.waitinterval);
1268             }
1269             // Prepare the root node we will set content for and the loading template we want to display as a YUI node.
1270             var root = this.fpnode.one('.fp-content');
1271             var content = Y.Node.create(M.core_filepicker.templates.loading).addClass('fp-content-hidden').setStyle('opacity', 0);
1272             var count = 0;
1273             // Initiate an interval, we will have a count which will increment every 100 milliseconds.
1274             // Count 0 - the loading icon will have visibility set to hidden (invisible) and have an opacity of 0 (invisible also)
1275             // Count 5 - the visiblity will be switched to visible but opacity will still be at 0 (inivisible)
1276             // Counts 6 - 15 opacity will be increased by 0.1 making the loading icon visible over the period of a second
1277             // Count 16 - The interval will be cancelled.
1278             var interval = setInterval(function(){
1279                 if (!content || !root.contains(content) || count >= 15) {
1280                     clearInterval(interval);
1281                     return true;
1282                 }
1283                 if (count == 5) {
1284                     content.removeClass('fp-content-hidden');
1285                 } else if (count > 5) {
1286                     var opacity = parseFloat(content.getStyle('opacity'));
1287                     content.setStyle('opacity', opacity + 0.1);
1288                 }
1289                 count++;
1290                 return false;
1291             }, 100);
1292             // Store the wait interval so that we can check it in the future.
1293             this.waitinterval = interval;
1294             // Set the content to the loading template.
1295             root.setContent(content);
1296         },
1297         viewbar_set_enabled: function(mode) {
1298             var viewbar = this.fpnode.one('.fp-viewbar')
1299             if (viewbar) {
1300                 if (mode) {
1301                     viewbar.addClass('enabled').removeClass('disabled');
1302                     this.fpnode.all('.fp-vb-icons,.fp-vb-tree,.fp-vb-details').setAttribute("aria-disabled", "false");
1303                     this.fpnode.all('.fp-vb-icons,.fp-vb-tree,.fp-vb-details').setAttribute("tabindex", "");
1304                 } else {
1305                     viewbar.removeClass('enabled').addClass('disabled');
1306                     this.fpnode.all('.fp-vb-icons,.fp-vb-tree,.fp-vb-details').setAttribute("aria-disabled", "true");
1307                     this.fpnode.all('.fp-vb-icons,.fp-vb-tree,.fp-vb-details').setAttribute("tabindex", "-1");
1308                 }
1309             }
1310             this.fpnode.all('.fp-vb-icons,.fp-vb-tree,.fp-vb-details').removeClass('checked');
1311             var modes = {1:'icons', 2:'tree', 3:'details'};
1312             this.fpnode.all('.fp-vb-'+modes[this.viewmode]).addClass('checked');
1313         },
1314         viewbar_clicked: function(e) {
1315             e.preventDefault();
1316             var viewbar = this.fpnode.one('.fp-viewbar')
1317             if (!viewbar || !viewbar.hasClass('disabled')) {
1318                 if (e.currentTarget.hasClass('fp-vb-tree')) {
1319                     this.viewmode = 2;
1320                 } else if (e.currentTarget.hasClass('fp-vb-details')) {
1321                     this.viewmode = 3;
1322                 } else {
1323                     this.viewmode = 1;
1324                 }
1325                 this.viewbar_set_enabled(true)
1326                 this.view_files();
1327                 this.set_preference('recentviewmode', this.viewmode);
1328             }
1329         },
1330         render: function() {
1331             var client_id = this.options.client_id;
1332             var fpid = "filepicker-"+ client_id;
1333             var labelid = 'fp-dialog-label_'+ client_id;
1334             var width = 873;
1335             var draggable = true;
1336             this.fpnode = Y.Node.create(M.core_filepicker.templates.generallayout).
1337                 set('id', 'filepicker-'+client_id).set('aria-labelledby', labelid);
1339             if (this.in_iframe()) {
1340                 width = Math.floor(window.innerWidth * 0.95);
1341                 draggable = false;
1342             }
1344             this.mainui = new M.core.dialogue({
1345                 extraClasses : ['filepicker'],
1346                 draggable    : draggable,
1347                 bodyContent  : this.fpnode,
1348                 headerContent: '<h3 id="'+ labelid +'">'+ M.util.get_string('filepicker', 'repository') +'</h3>',
1349                 centered     : true,
1350                 modal        : true,
1351                 visible      : false,
1352                 width        : width+'px',
1353                 responsiveWidth : 768,
1354                 height       : '558px',
1355                 zIndex       : this.options.zIndex
1356             });
1358             // create panel for selecting a file (initially hidden)
1359             this.selectnode = Y.Node.create(M.core_filepicker.templates.selectlayout).
1360                 set('id', 'filepicker-select-'+client_id).
1361                 set('aria-live', 'assertive').
1362                 set('role', 'dialog');
1364             var fplabel = 'fp-file_label_'+ client_id;
1365             this.selectui = new M.core.dialogue({
1366                 headerContent: '<h3 id="' + fplabel +'">'+M.util.get_string('select', 'repository')+'</h3>',
1367                 draggable    : true,
1368                 width        : '450px',
1369                 bodyContent  : this.selectnode,
1370                 centered     : true,
1371                 modal        : true,
1372                 visible      : false,
1373                 zIndex       : this.options.zIndex
1374             });
1375             Y.one('#'+this.selectnode.get('id')).setAttribute('aria-labelledby', fplabel);
1376             // event handler for lazy loading of thumbnails and next page
1377             this.fpnode.one('.fp-content').on(['scroll','resize'], this.content_scrolled, this);
1378             // save template for one path element and location of path bar
1379             if (this.fpnode.one('.fp-path-folder')) {
1380                 this.pathnode = this.fpnode.one('.fp-path-folder');
1381                 this.pathbar = this.pathnode.get('parentNode');
1382                 this.pathbar.removeChild(this.pathnode);
1383             }
1384             // assign callbacks for view mode switch buttons
1385             this.fpnode.one('.fp-vb-icons').on('click', this.viewbar_clicked, this);
1386             this.fpnode.one('.fp-vb-tree').on('click', this.viewbar_clicked, this);
1387             this.fpnode.one('.fp-vb-details').on('click', this.viewbar_clicked, this);
1389             // assign callbacks for toolbar links
1390             this.setup_toolbar();
1391             this.setup_select_file();
1392             this.hide_header();
1394             // processing repository listing
1395             // Resort the repositories by sortorder
1396             var sorted_repositories = [];
1397             var i;
1398             for (i in this.options.repositories) {
1399                 sorted_repositories[i] = this.options.repositories[i];
1400             }
1401             sorted_repositories.sort(function(a,b){return a.sortorder-b.sortorder});
1402             // extract one repository template and repeat it for all repositories available,
1403             // set name and icon and assign callbacks
1404             var reponode = this.fpnode.one('.fp-repo');
1405             if (reponode) {
1406                 var list = reponode.get('parentNode');
1407                 list.removeChild(reponode);
1408                 for (i in sorted_repositories) {
1409                     var repository = sorted_repositories[i];
1410                     var h = (parseInt(i) == 0) ? parseInt(i) : parseInt(i) - 1,
1411                         j = (parseInt(i) == Object.keys(sorted_repositories).length - 1) ? parseInt(i) : parseInt(i) + 1;
1412                     var previousrepository = sorted_repositories[h];
1413                     var nextrepository = sorted_repositories[j];
1414                     var node = reponode.cloneNode(true);
1415                     list.appendChild(node);
1416                     node.
1417                         set('id', 'fp-repo-'+client_id+'-'+repository.id).
1418                         on('click', function(e, repository_id) {
1419                             e.preventDefault();
1420                             this.set_preference('recentrepository', repository_id);
1421                             this.hide_header();
1422                             this.list({'repo_id':repository_id});
1423                         }, this /*handler running scope*/, repository.id/*second argument of handler*/);
1424                     node.on('key', function(e, previousrepositoryid, nextrepositoryid, clientid, repositoryid) {
1425                         this.changeHighlightedRepository(e, clientid, repositoryid, previousrepositoryid, nextrepositoryid);
1426                     }, 'down:38,40', this, previousrepository.id, nextrepository.id, client_id, repository.id);
1427                     node.on('key', function(e, repositoryid) {
1428                         e.preventDefault();
1429                         this.set_preference('recentrepository', repositoryid);
1430                         this.hide_header();
1431                         this.list({'repo_id': repositoryid});
1432                     }, 'enter', this, repository.id);
1433                     node.one('.fp-repo-name').setContent(Y.Escape.html(repository.name));
1434                     node.one('.fp-repo-icon').set('src', repository.icon);
1435                     if (i==0) {
1436                         node.addClass('first');
1437                     }
1438                     if (i==sorted_repositories.length-1) {
1439                         node.addClass('last');
1440                     }
1441                     if (i%2) {
1442                         node.addClass('even');
1443                     } else {
1444                         node.addClass('odd');
1445                     }
1446                 }
1447             }
1448             // display error if no repositories found
1449             if (sorted_repositories.length==0) {
1450                 this.display_error(M.util.get_string('norepositoriesavailable', 'repository'), 'norepositoriesavailable')
1451             }
1452             // display repository that was used last time
1453             this.mainui.show();
1454             this.show_recent_repository();
1455         },
1456         /**
1457          * Change the highlighted repository to a new one.
1458          *
1459          * @param  {object} event The key event
1460          * @param  {integer} clientid The client id to identify the repo class.
1461          * @param  {integer} oldrepositoryid The repository id that we are removing the highlight for
1462          * @param  {integer} previousrepositoryid The previous repository id.
1463          * @param  {integer} nextrepositoryid The next repository id.
1464          */
1465         changeHighlightedRepository: function(event, clientid, oldrepositoryid, previousrepositoryid, nextrepositoryid) {
1466             event.preventDefault();
1467             var newrepositoryid = (event.keyCode == '40') ? nextrepositoryid : previousrepositoryid;
1468             this.fpnode.one('#fp-repo-' + clientid + '-' + oldrepositoryid).setAttribute('tabindex', '-1');
1469             this.fpnode.one('#fp-repo-' + clientid + '-' + newrepositoryid)
1470                     .setAttribute('tabindex', '0')
1471                     .focus();
1472         },
1473         parse_repository_options: function(data, appendtolist) {
1474             if (appendtolist) {
1475                 if (data.list) {
1476                     if (!this.filelist) {
1477                         this.filelist = [];
1478                     }
1479                     for (var i in data.list) {
1480                         this.filelist[this.filelist.length] = data.list[i];
1481                     }
1482                 }
1483             } else {
1484                 this.filelist = data.list?data.list:null;
1485                 this.lazyloading = {};
1486             }
1487             this.filepath = data.path?data.path:null;
1488             this.objecttag = data.object?data.object:null;
1489             this.active_repo = {};
1490             this.active_repo.issearchresult = data.issearchresult ? true : false;
1491             this.active_repo.defaultreturntype = data.defaultreturntype?data.defaultreturntype:null;
1492             this.active_repo.dynload = data.dynload?data.dynload:false;
1493             this.active_repo.pages = Number(data.pages?data.pages:null);
1494             this.active_repo.page = Number(data.page?data.page:null);
1495             this.active_repo.hasmorepages = (this.active_repo.pages && this.active_repo.page && (this.active_repo.page < this.active_repo.pages || this.active_repo.pages == -1))
1496             this.active_repo.id = data.repo_id?data.repo_id:null;
1497             this.active_repo.nosearch = (data.login || data.nosearch); // this is either login form or 'nosearch' attribute set
1498             this.active_repo.norefresh = (data.login || data.norefresh); // this is either login form or 'norefresh' attribute set
1499             this.active_repo.nologin = (data.login || data.nologin); // this is either login form or 'nologin' attribute is set
1500             this.active_repo.logouttext = data.logouttext?data.logouttext:null;
1501             this.active_repo.logouturl = (data.logouturl || '');
1502             this.active_repo.message = (data.message || '');
1503             this.active_repo.help = data.help?data.help:null;
1504             this.active_repo.manage = data.manage?data.manage:null;
1505             this.print_header();
1506         },
1507         print_login: function(data) {
1508             this.parse_repository_options(data);
1509             var client_id = this.options.client_id;
1510             var repository_id = data.repo_id;
1511             var l = this.logindata = data.login;
1512             var loginurl = '';
1513             var action = data['login_btn_action'] ? data['login_btn_action'] : 'login';
1514             var form_id = 'fp-form-'+client_id;
1516             var loginform_node = Y.Node.create(M.core_filepicker.templates.loginform);
1517             loginform_node.one('form').set('id', form_id);
1518             this.fpnode.one('.fp-content').setContent('').appendChild(loginform_node);
1519             var templates = {
1520                 'popup' : loginform_node.one('.fp-login-popup'),
1521                 'textarea' : loginform_node.one('.fp-login-textarea'),
1522                 'select' : loginform_node.one('.fp-login-select'),
1523                 'text' : loginform_node.one('.fp-login-text'),
1524                 'radio' : loginform_node.one('.fp-login-radiogroup'),
1525                 'checkbox' : loginform_node.one('.fp-login-checkbox'),
1526                 'input' : loginform_node.one('.fp-login-input')
1527             };
1528             var container;
1529             for (var i in templates) {
1530                 if (templates[i]) {
1531                     container = templates[i].get('parentNode');
1532                     container.removeChild(templates[i]);
1533                 }
1534             }
1536             for(var k in l) {
1537                 if (templates[l[k].type]) {
1538                     var node = templates[l[k].type].cloneNode(true);
1539                 } else {
1540                     node = templates['input'].cloneNode(true);
1541                 }
1542                 if (l[k].type == 'popup') {
1543                     // submit button
1544                     loginurl = l[k].url;
1545                     var popupbutton = node.one('button');
1546                     popupbutton.on('click', function(e){
1547                         M.core_filepicker.active_filepicker = this;
1548                         window.open(loginurl, 'repo_auth', 'location=0,status=0,width=500,height=300,scrollbars=yes');
1549                         e.preventDefault();
1550                     }, this);
1551                     loginform_node.one('form').on('keydown', function(e) {
1552                         if (e.keyCode == 13) {
1553                             popupbutton.simulate('click');
1554                             e.preventDefault();
1555                         }
1556                     }, this);
1557                     loginform_node.all('.fp-login-submit').remove();
1558                     action = 'popup';
1559                 } else if(l[k].type=='textarea') {
1560                     // textarea element
1561                     if (node.one('label')) {
1562                         node.one('label').set('for', l[k].id).setContent(l[k].label);
1563                     }
1564                     node.one('textarea').setAttrs({id:l[k].id, name:l[k].name});
1565                 } else if(l[k].type=='select') {
1566                     // select element
1567                     if (node.one('label')) {
1568                         node.one('label').set('for', l[k].id).setContent(l[k].label);
1569                     }
1570                     node.one('select').setAttrs({id:l[k].id, name:l[k].name}).setContent('');
1571                     for (i in l[k].options) {
1572                         node.one('select').appendChild(
1573                             Y.Node.create('<option/>').
1574                                 set('value', l[k].options[i].value).
1575                                 setContent(l[k].options[i].label));
1576                     }
1577                 } else if(l[k].type=='radio') {
1578                     // radio input element
1579                     node.all('label').setContent(l[k].label);
1580                     var list = l[k].value.split('|');
1581                     var labels = l[k].value_label.split('|');
1582                     var radionode = null;
1583                     for(var item in list) {
1584                         if (radionode == null) {
1585                             radionode = node.one('.fp-login-radio');
1586                             radionode.one('input').set('checked', 'checked');
1587                         } else {
1588                             var x = radionode.cloneNode(true);
1589                             radionode.insert(x, 'after');
1590                             radionode = x;
1591                             radionode.one('input').set('checked', '');
1592                         }
1593                         radionode.one('input').setAttrs({id:''+l[k].id+item, name:l[k].name,
1594                             type:l[k].type, value:list[item]});
1595                         radionode.all('label').setContent(labels[item]).set('for', ''+l[k].id+item)
1596                     }
1597                     if (radionode == null) {
1598                         node.one('.fp-login-radio').remove();
1599                     }
1600                 } else {
1601                     // input element
1602                     if (node.one('label')) { node.one('label').set('for', l[k].id).setContent(l[k].label) }
1603                     node.one('input').
1604                         set('type', l[k].type).
1605                         set('id', l[k].id).
1606                         set('name', l[k].name).
1607                         set('value', l[k].value?l[k].value:'')
1608                 }
1609                 container.appendChild(node);
1610             }
1611             // custom label text for submit button
1612             if (data['login_btn_label']) {
1613                 loginform_node.all('.fp-login-submit').setContent(data['login_btn_label'])
1614             }
1615             // register button action for login and search
1616             if (action == 'login' || action == 'search') {
1617                 loginform_node.one('.fp-login-submit').on('click', function(e){
1618                     e.preventDefault();
1619                     this.hide_header();
1620                     this.request({
1621                         'scope': this,
1622                         'action':(action == 'search') ? 'search' : 'signin',
1623                         'path': '',
1624                         'client_id': client_id,
1625                         'repository_id': repository_id,
1626                         'form': {id:form_id, upload:false, useDisabled:true},
1627                         'callback': this.display_response
1628                     }, true);
1629                 }, this);
1630             }
1631             // if 'Enter' is pressed in the form, simulate the button click
1632             if (loginform_node.one('.fp-login-submit')) {
1633                 loginform_node.one('form').on('keydown', function(e) {
1634                     if (e.keyCode == 13) {
1635                         loginform_node.one('.fp-login-submit').simulate('click')
1636                         e.preventDefault();
1637                     }
1638                 }, this);
1639             }
1640         },
1641         display_response: function(id, obj, args) {
1642             var scope = args.scope;
1643             // highlight the current repository in repositories list
1644             scope.fpnode.all('.fp-repo.active')
1645                     .removeClass('active')
1646                     .setAttribute('aria-selected', 'false')
1647                     .setAttribute('tabindex', '-1');
1648             scope.fpnode.all('.nav-link')
1649                     .removeClass('active')
1650                     .setAttribute('aria-selected', 'false')
1651                     .setAttribute('tabindex', '-1');
1652             var activenode = scope.fpnode.one('#fp-repo-' + scope.options.client_id + '-' + obj.repo_id);
1653             activenode.addClass('active')
1654                     .setAttribute('aria-selected', 'true')
1655                     .setAttribute('tabindex', '0');
1656             activenode.all('.nav-link').addClass('active');
1657             // add class repository_REPTYPE to the filepicker (for repository-specific styles)
1658             for (var i in scope.options.repositories) {
1659                 scope.fpnode.removeClass('repository_'+scope.options.repositories[i].type)
1660             }
1661             if (obj.repo_id && scope.options.repositories[obj.repo_id]) {
1662                 scope.fpnode.addClass('repository_'+scope.options.repositories[obj.repo_id].type)
1663             }
1664             Y.one('.file-picker .fp-repo-items').focus();
1666             // display response
1667             if (obj.login) {
1668                 scope.viewbar_set_enabled(false);
1669                 scope.print_login(obj);
1670             } else if (obj.upload) {
1671                 scope.viewbar_set_enabled(false);
1672                 scope.parse_repository_options(obj);
1673                 scope.create_upload_form(obj);
1674             } else if (obj.object) {
1675                 M.core_filepicker.active_filepicker = scope;
1676                 scope.viewbar_set_enabled(false);
1677                 scope.parse_repository_options(obj);
1678                 scope.create_object_container(obj.object);
1679             } else if (obj.list) {
1680                 scope.viewbar_set_enabled(true);
1681                 scope.parse_repository_options(obj);
1682                 scope.view_files();
1683             }
1684         },
1685         list: function(args) {
1686             if (!args) {
1687                 args = {};
1688             }
1689             if (!args.repo_id) {
1690                 args.repo_id = this.active_repo.id;
1691             }
1692             if (!args.path) {
1693                 args.path = '';
1694             }
1695             this.currentpath = args.path;
1696             this.request({
1697                 action: 'list',
1698                 client_id: this.options.client_id,
1699                 repository_id: args.repo_id,
1700                 path: args.path,
1701                 page: args.page,
1702                 scope: this,
1703                 callback: this.display_response
1704             }, true);
1705         },
1706         populate_licenses_select: function(node) {
1707             if (!node) {
1708                 return;
1709             }
1710             node.setContent('');
1711             var licenses = this.options.licenses;
1712             var recentlicense = this.get_preference('recentlicense');
1713             if (recentlicense) {
1714                 this.options.defaultlicense=recentlicense;
1715             }
1716             for (var i in licenses) {
1717                 var option = Y.Node.create('<option/>').
1718                     set('selected', (this.options.defaultlicense==licenses[i].shortname)).
1719                     set('value', licenses[i].shortname).
1720                     setContent(Y.Escape.html(licenses[i].fullname));
1721                 node.appendChild(option)
1722             }
1723         },
1724         set_selected_license: function(node, value) {
1725             var licenseset = false;
1726             node.all('option').each(function(el) {
1727                 if (el.get('value')==value || el.getContent()==value) {
1728                     el.set('selected', true);
1729                     licenseset = true;
1730                 }
1731             });
1732             if (!licenseset) {
1733                 // we did not find the value in the list
1734                 var recentlicense = this.get_preference('recentlicense');
1735                 node.all('option[selected]').set('selected', false);
1736                 node.all('option[value='+recentlicense+']').set('selected', true);
1737             }
1738         },
1739         create_object_container: function(data) {
1740             var content = this.fpnode.one('.fp-content');
1741             content.setContent('');
1742             //var str = '<object data="'+data.src+'" type="'+data.type+'" width="98%" height="98%" id="container_object" class="fp-object-container mdl-align"></object>';
1743             var container = Y.Node.create('<object/>').
1744                 setAttrs({data:data.src, type:data.type, id:'container_object'}).
1745                 addClass('fp-object-container');
1746             content.setContent('').appendChild(container);
1747         },
1748         create_upload_form: function(data) {
1749             var client_id = this.options.client_id;
1750             var id = data.upload.id+'_'+client_id;
1751             var content = this.fpnode.one('.fp-content');
1752             var template_name = 'uploadform_'+this.options.repositories[data.repo_id].type;
1753             var template = M.core_filepicker.templates[template_name] || M.core_filepicker.templates['uploadform'];
1754             content.setContent(template);
1756             content.all('.fp-file,.fp-saveas,.fp-setauthor,.fp-setlicense').each(function (node) {
1757                 node.all('label').set('for', node.one('input,select').generateID());
1758             });
1759             content.one('form').set('id', id);
1760             content.one('.fp-file input').set('name', 'repo_upload_file');
1761             if (data.upload.label && content.one('.fp-file label')) {
1762                 content.one('.fp-file label').setContent(data.upload.label);
1763             }
1764             content.one('.fp-saveas input').set('name', 'title');
1765             content.one('.fp-setauthor input').setAttrs({name:'author', value:this.options.author});
1766             content.one('.fp-setlicense select').set('name', 'license');
1767             this.populate_licenses_select(content.one('.fp-setlicense select'))
1768             // append hidden inputs to the upload form
1769             content.one('form').appendChild(Y.Node.create('<input/>').
1770                 setAttrs({type:'hidden',name:'itemid',value:this.options.itemid}));
1771             var types = this.options.accepted_types;
1772             for (var i in types) {
1773                 content.one('form').appendChild(Y.Node.create('<input/>').
1774                     setAttrs({type:'hidden',name:'accepted_types[]',value:types[i]}));
1775             }
1777             var scope = this;
1778             content.one('.fp-upload-btn').on('click', function(e) {
1779                 e.preventDefault();
1780                 var license = content.one('.fp-setlicense select');
1782                 this.set_preference('recentlicense', license.get('value'));
1783                 if (!content.one('.fp-file input').get('value')) {
1784                     scope.print_msg(M.util.get_string('nofilesattached', 'repository'), 'error');
1785                     return false;
1786                 }
1787                 this.hide_header();
1788                 scope.request({
1789                         scope: scope,
1790                         action:'upload',
1791                         client_id: client_id,
1792                         params: {'savepath':scope.options.savepath},
1793                         repository_id: scope.active_repo.id,
1794                         form: {id: id, upload:true},
1795                         onerror: function(id, o, args) {
1796                             scope.create_upload_form(data);
1797                         },
1798                         callback: function(id, o, args) {
1799                             if (o.event == 'fileexists') {
1800                                 scope.create_upload_form(data);
1801                                 scope.process_existing_file(o);
1802                                 return;
1803                             }
1804                             if (scope.options.editor_target&&scope.options.env=='editor') {
1805                                 scope.options.editor_target.value=o.url;
1806                                 scope.options.editor_target.onchange();
1807                             }
1808                             scope.hide();
1809                             o.client_id = client_id;
1810                             var formcallback_scope = args.scope.options.magicscope ? args.scope.options.magicscope : args.scope;
1811                             scope.options.formcallback.apply(formcallback_scope, [o]);
1812                         }
1813                 }, true);
1814             }, this);
1815         },
1816         /** setting handlers and labels for elements in toolbar. Called once during the initial render of filepicker */
1817         setup_toolbar: function() {
1818             var client_id = this.options.client_id;
1819             var toolbar = this.fpnode.one('.fp-toolbar');
1820             toolbar.one('.fp-tb-logout').one('a,button').on('click', function(e) {
1821                 e.preventDefault();
1822                 if (!this.active_repo.nologin) {
1823                     this.hide_header();
1824                     this.request({
1825                         action:'logout',
1826                         client_id: this.options.client_id,
1827                         repository_id: this.active_repo.id,
1828                         path:'',
1829                         callback: this.display_response
1830                     }, true);
1831                 }
1832                 if (this.active_repo.logouturl) {
1833                     window.open(this.active_repo.logouturl, 'repo_auth', 'location=0,status=0,width=500,height=300,scrollbars=yes');
1834                 }
1835             }, this);
1836             toolbar.one('.fp-tb-refresh').one('a,button').on('click', function(e) {
1837                 e.preventDefault();
1838                 if (!this.active_repo.norefresh) {
1839                     this.list({ path: this.currentpath });
1840                 }
1841             }, this);
1842             toolbar.one('.fp-tb-search form').
1843                 set('method', 'POST').
1844                 set('id', 'fp-tb-search-'+client_id).
1845                 on('submit', function(e) {
1846                     e.preventDefault();
1847                     if (!this.active_repo.nosearch) {
1848                         this.request({
1849                             scope: this,
1850                             action:'search',
1851                             client_id: this.options.client_id,
1852                             repository_id: this.active_repo.id,
1853                             form: {id: 'fp-tb-search-'+client_id, upload:false, useDisabled:true},
1854                             callback: this.display_response
1855                         }, true);
1856                     }
1857             }, this);
1859             // it does not matter what kind of element is .fp-tb-manage, we create a dummy <a>
1860             // element and use it to open url on click event
1861             var managelnk = Y.Node.create('<a/>').
1862                 setAttrs({id:'fp-tb-manage-'+client_id+'-link', target:'_blank'}).
1863                 setStyle('display', 'none');
1864             toolbar.append(managelnk);
1865             toolbar.one('.fp-tb-manage').one('a,button').
1866                 on('click', function(e) {
1867                     e.preventDefault();
1868                     managelnk.simulate('click')
1869                 });
1871             // same with .fp-tb-help
1872             var helplnk = Y.Node.create('<a/>').
1873                 setAttrs({id:'fp-tb-help-'+client_id+'-link', target:'_blank'}).
1874                 setStyle('display', 'none');
1875             toolbar.append(helplnk);
1876             toolbar.one('.fp-tb-help').one('a,button').
1877                 on('click', function(e) {
1878                     e.preventDefault();
1879                     helplnk.simulate('click')
1880                 });
1881         },
1882         hide_header: function() {
1883             if (this.fpnode.one('.fp-toolbar')) {
1884                 this.fpnode.one('.fp-toolbar').addClass('empty');
1885             }
1886             if (this.pathbar) {
1887                 this.pathbar.setContent('').addClass('empty');
1888             }
1889         },
1890         print_header: function() {
1891             var r = this.active_repo;
1892             var scope = this;
1893             var client_id = this.options.client_id;
1894             this.hide_header();
1895             this.print_path();
1896             var toolbar = this.fpnode.one('.fp-toolbar');
1897             if (!toolbar) { return; }
1899             var enable_tb_control = function(node, enabled) {
1900                 if (!node) { return; }
1901                 node.addClassIf('disabled', !enabled).addClassIf('enabled', enabled)
1902                 if (enabled) {
1903                     toolbar.removeClass('empty');
1904                 }
1905             }
1907             // TODO 'back' permanently disabled for now. Note, flickr_public uses 'Logout' for it!
1908             enable_tb_control(toolbar.one('.fp-tb-back'), false);
1910             // search form
1911             enable_tb_control(toolbar.one('.fp-tb-search'), !r.nosearch);
1912             if(!r.nosearch) {
1913                 var searchform = toolbar.one('.fp-tb-search form');
1914                 searchform.setContent('');
1915                 this.request({
1916                     scope: this,
1917                     action:'searchform',
1918                     repository_id: this.active_repo.id,
1919                     callback: function(id, obj, args) {
1920                         if (obj.repo_id == scope.active_repo.id && obj.form) {
1921                             // if we did not jump to another repository meanwhile
1922                             searchform.setContent(obj.form);
1923                             // Highlight search text when user click for search.
1924                             var searchnode = searchform.one('input[name="s"]');
1925                             if (searchnode) {
1926                                 searchnode.once('click', function(e) {
1927                                     e.preventDefault();
1928                                     this.select();
1929                                 });
1930                             }
1931                         }
1932                     }
1933                 }, false);
1934             }
1936             // refresh button
1937             // weather we use cache for this instance, this button will reload listing anyway
1938             enable_tb_control(toolbar.one('.fp-tb-refresh'), !r.norefresh);
1940             // login button
1941             enable_tb_control(toolbar.one('.fp-tb-logout'), !r.nologin);
1943             // manage url
1944             enable_tb_control(toolbar.one('.fp-tb-manage'), r.manage);
1945             Y.one('#fp-tb-manage-'+client_id+'-link').set('href', r.manage);
1947             // help url
1948             enable_tb_control(toolbar.one('.fp-tb-help'), r.help);
1949             Y.one('#fp-tb-help-'+client_id+'-link').set('href', r.help);
1951             // message
1952             enable_tb_control(toolbar.one('.fp-tb-message'), r.message);
1953             toolbar.one('.fp-tb-message').setContent(r.message);
1954         },
1955         print_path: function() {
1956             if (!this.pathbar) {
1957                 return;
1958             }
1959             this.pathbar.setContent('').addClass('empty');
1960             var p = this.filepath;
1961             if (p && p.length!=0 && this.viewmode != 2) {
1962                 for(var i = 0; i < p.length; i++) {
1963                     var el = this.pathnode.cloneNode(true);
1964                     this.pathbar.appendChild(el);
1965                     if (i == 0) {
1966                         el.addClass('first');
1967                     }
1968                     if (i == p.length-1) {
1969                         el.addClass('last');
1970                     }
1971                     if (i%2) {
1972                         el.addClass('even');
1973                     } else {
1974                         el.addClass('odd');
1975                     }
1976                     el.all('.fp-path-folder-name').setContent(Y.Escape.html(p[i].name));
1977                     el.on('click',
1978                             function(e, path) {
1979                                 e.preventDefault();
1980                                 this.list({'path':path});
1981                             },
1982                         this, p[i].path);
1983                 }
1984                 this.pathbar.removeClass('empty');
1985             }
1986         },
1987         hide: function() {
1988             this.selectui.hide();
1989             if (this.process_dlg) {
1990                 this.process_dlg.hide();
1991             }
1992             if (this.msg_dlg) {
1993                 this.msg_dlg.hide();
1994             }
1995             this.mainui.hide();
1996         },
1997         show: function() {
1998             if (this.fpnode) {
1999                 this.hide();
2000                 this.mainui.show();
2001                 this.show_recent_repository();
2002             } else {
2003                 this.launch();
2004             }
2005         },
2006         launch: function() {
2007             this.render();
2008         },
2009         show_recent_repository: function() {
2010             this.hide_header();
2011             this.viewbar_set_enabled(false);
2012             var repository_id = this.get_preference('recentrepository');
2013             this.viewmode = this.get_preference('recentviewmode');
2014             if (this.viewmode != 2 && this.viewmode != 3) {
2015                 this.viewmode = 1;
2016             }
2017             if (this.options.repositories[repository_id]) {
2018                 this.list({'repo_id':repository_id});
2019             }
2020         },
2021         get_preference: function (name) {
2022             if (this.options.userprefs[name]) {
2023                 return this.options.userprefs[name];
2024             } else {
2025                 return false;
2026             }
2027         },
2028         set_preference: function(name, value) {
2029             if (this.options.userprefs[name] != value) {
2030                 M.util.set_user_preference('filepicker_' + name, value);
2031                 this.options.userprefs[name] = value;
2032             }
2033         },
2034         in_iframe: function () {
2035             // If we're not the top window then we're in an iFrame
2036             return window.self !== window.top;
2037         }
2038     });
2039     var loading = Y.one('#filepicker-loading-'+options.client_id);
2040     if (loading) {
2041         loading.setStyle('display', 'none');
2042     }
2043     M.core_filepicker.instances[options.client_id] = new FilePickerHelper(options);