Merge branch 'MDL-68667-master' of git://github.com/aanabit/moodle
[moodle.git] / repository / filepicker.js
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         }
321         /**
322          * Generate slave checkboxes based on toggleall's specification
323          * @param {object} o An object reprsenting the record for the current row.
324          * @return {html} The checkbox html
325          */
326         var formatCheckbox = function(o) {
327             var el = Y.Node.create('<div/>');
329             var checkbox = Y.Node.create('<input/>')
330                 .setAttribute('type', 'checkbox')
331                 .setAttribute('data-fieldtype', 'checkbox')
332                 .setAttribute('data-fullname', o.data.fullname)
333                 .setAttribute('data-action', 'toggle')
334                 .setAttribute('data-toggle', 'slave')
335                 .setAttribute('data-togglegroup', 'file-selections')
336                 .setAttribute('data-toggle-selectall', M.util.get_string('selectall', 'moodle'))
337                 .setAttribute('data-toggle-deselectall', M.util.get_string('deselectall', 'moodle'));
339             var checkboxLabel = Y.Node.create('<label>')
340                 .setHTML("Select file '" + o.data.fullname + "'")
341                 .addClass('sr-only')
342                 .setAttrs({
343                     for: checkbox.generateID(),
344                 });
346             el.appendChild(checkbox);
347             el.appendChild(checkboxLabel);
348             return el.getContent();
349         };
350         /** sorting function for table view */
351         var sortFoldersFirst = function(a, b, desc) {
352             if (a.get('isfolder') && !b.get('isfolder')) {
353                 return -1;
354             }
355             if (!a.get('isfolder') && b.get('isfolder')) {
356                 return 1;
357             }
358             var aa = a.get(this.key), bb = b.get(this.key), dir = desc ? -1 : 1;
359             return (aa > bb) ? dir : ((aa < bb) ? -dir : 0);
360         }
361         /** initialize table view */
362         var initialize_table_view = function() {
363             var cols = [
364                 {key: "displayname", label: M.util.get_string('name', 'moodle'), allowHTML: true, formatter: formatTitle,
365                     sortable: true, sortFn: sortFoldersFirst},
366                 {key: "datemodified", label: M.util.get_string('lastmodified', 'moodle'), allowHTML: true, formatter: formatValue,
367                     sortable: true, sortFn: sortFoldersFirst},
368                 {key: "size", label: M.util.get_string('size', 'repository'), allowHTML: true, formatter: formatValue,
369                     sortable: true, sortFn: sortFoldersFirst},
370                 {key: "mimetype", label: M.util.get_string('type', 'repository'), allowHTML: true,
371                     sortable: true, sortFn: sortFoldersFirst}
372             ];
374             // Generate a checkbox based on toggleall's specification
375             var div = Y.Node.create('<div/>');
376             var checkbox = Y.Node.create('<input/>')
377                 .setAttribute('type', 'checkbox')
378                 // .setAttribute('title', M.util.get_string('selectallornone', 'form'))
379                 .setAttribute('data-action', 'toggle')
380                 .setAttribute('data-toggle', 'master')
381                 .setAttribute('data-togglegroup', 'file-selections');
383             var checkboxLabel = Y.Node.create('<label>')
384                 .setHTML(M.util.get_string('selectallornone', 'form'))
385                 .addClass('sr-only')
386                 .setAttrs({
387                     for: checkbox.generateID(),
388                 });
390             div.appendChild(checkboxLabel);
391             div.appendChild(checkbox);
393             // Define the selector for the click event handler.
394             var clickEventSelector = 'tr';
395             // Enable the selectable checkboxes
396             if (options.disablecheckboxes != undefined && !options.disablecheckboxes) {
397                 clickEventSelector = 'tr td:not(:first-child)';
398                 cols.unshift({
399                     key: "",
400                     label: div.getContent(),
401                     allowHTML: true,
402                     formatter: formatCheckbox,
403                     sortable: false
404                 });
405             }
406             scope.tableview = new Y.DataTable({columns: cols, data: fileslist});
407             scope.tableview.delegate('click', function (e, tableview) {
408                 var record = tableview.getRecord(e.currentTarget.get('id'));
409                 if (record) {
410                     var callback = options.callback;
411                     if (options.rightclickcallback && e.target.ancestor('.fp-tableview .fp-contextmenu', true)) {
412                         callback = options.rightclickcallback;
413                     }
414                     Y.bind(callback, this)(e, record.getAttrs());
415                 }
416             }, clickEventSelector, options.callbackcontext, scope.tableview);
418             if (options.rightclickcallback) {
419                 scope.tableview.delegate('contextmenu', function (e, tableview) {
420                     var record = tableview.getRecord(e.currentTarget.get('id'));
421                     if (record) { Y.bind(options.rightclickcallback, this)(e, record.getAttrs()); }
422                 }, 'tr', options.callbackcontext, scope.tableview);
423             }
424         }
425         /** append items in table view mode */
426         var append_files_table = function() {
427             if (options.appendonly) {
428                 fileslist.forEach(function(el) {
429                     this.tableview.data.add(el);
430                 },scope);
431             }
432             scope.tableview.render(scope.one('.'+classname));
433             scope.tableview.sortable = options.sortable ? true : false;
434         };
435         /** append items in tree view mode */
436         var append_files_tree = function() {
437             if (options.appendonly) {
438                 var parentnode = scope.treeview.getRoot();
439                 if (scope.treeview.getHighlightedNode()) {
440                     parentnode = scope.treeview.getHighlightedNode();
441                     if (parentnode.isLeaf) {parentnode = parentnode.parent;}
442                 }
443                 for (var k in fileslist) {
444                     build_tree(fileslist[k], parentnode);
445                 }
446                 scope.treeview.draw();
447             } else {
448                 // otherwise files were already added in initialize_tree_view()
449             }
450         }
451         /** append items in icon view mode */
452         var append_files_icons = function() {
453             parent = scope.one('.'+classname);
454             for (var k in fileslist) {
455                 var node = fileslist[k];
456                 var element = options.filenode.cloneNode(true);
457                 parent.appendChild(element);
458                 element.addClass(options.classnamecallback(node));
459                 var filenamediv = element.one('.fp-filename');
460                 filenamediv.setContent(file_get_displayname(node));
461                 var imgdiv = element.one('.fp-thumbnail'), width, height, src;
462                 if (node.thumbnail) {
463                     width = node.thumbnail_width ? node.thumbnail_width : 90;
464                     height = node.thumbnail_height ? node.thumbnail_height : 90;
465                     src = node.thumbnail;
466                 } else {
467                     width = 16;
468                     height = 16;
469                     src = node.icon;
470                 }
471                 filenamediv.setStyleAdv('width', width);
472                 imgdiv.setStyleAdv('width', width).setStyleAdv('height', height);
473                 var img = Y.Node.create('<img/>').setAttrs({
474                         title: file_get_description(node),
475                         alt: Y.Escape.html(node.thumbnail_alt ? node.thumbnail_alt : file_get_filename(node))}).
476                     setStyle('maxWidth', ''+width+'px').
477                     setStyle('maxHeight', ''+height+'px');
478                 img.setImgSrc(src, node.realthumbnail, lazyloading);
479                 imgdiv.appendChild(img);
480                 element.on('click', function(e, nd) {
481                     if (options.rightclickcallback && e.target.ancestor('.fp-iconview .fp-contextmenu', true)) {
482                         Y.bind(options.rightclickcallback, this)(e, nd);
483                     } else {
484                         Y.bind(options.callback, this)(e, nd);
485                     }
486                 }, options.callbackcontext, node);
487                 if (options.rightclickcallback) {
488                     element.on('contextmenu', options.rightclickcallback, options.callbackcontext, node);
489                 }
490             }
491         }
493         // Notify the user if any of the files has a problem status.
494         var problemFiles = [];
495         fileslist.forEach(function(file) {
496             if (!file_is_folder(file) && file.hasOwnProperty('status') && file.status != 0) {
497                 problemFiles.push(file);
498             }
499         });
500         if (problemFiles.length > 0) {
501             require(["core/notification", "core/str"], function(Notification, Str) {
502                 problemFiles.forEach(function(problemFile) {
503                     Str.get_string('storedfilecannotreadfile', 'error', problemFile.fullname).then(function(string) {
504                         Notification.addNotification({
505                             message: string,
506                             type: "error"
507                         });
508                         return;
509                     }).catch(Notification.exception);
510                 });
511             });
512         }
514         // If table view, need some additional properties
515         // before passing fileslist to the YUI tableview
516         if (options.viewmode == 3) {
517             fileslist.forEach(function(el) {
518                 el.displayname = file_get_displayname(el);
519                 el.isfolder = file_is_folder(el);
520                 el.classname = options.classnamecallback(el);
521             }, scope);
522         }
524         // initialize files view
525         if (!options.appendonly) {
526             var parent = Y.Node.create('<div/>').addClass(classname);
527             this.setContent('').appendChild(parent);
528             parent.generateID();
529             if (options.viewmode == 2) {
530                 initialize_tree_view();
531             } else if (options.viewmode == 3) {
532                 initialize_table_view();
533             } else {
534                 // nothing to initialize for icon view
535             }
536         }
538         // append files to the list
539         if (options.viewmode == 2) {
540             append_files_tree();
541         } else if (options.viewmode == 3) {
542             append_files_table();
543         } else {
544             append_files_icons();
545         }
547     }
548 }, '@VERSION@', {
549     requires:['base', 'node', 'yui2-treeview', 'panel', 'cookie', 'datatable', 'datatable-sort']
550 });
552 M.core_filepicker = M.core_filepicker || {};
554 /**
555  * instances of file pickers used on page
556  */
557 M.core_filepicker.instances = M.core_filepicker.instances || {};
558 M.core_filepicker.active_filepicker = null;
560 /**
561  * HTML Templates to use in FilePicker
562  */
563 M.core_filepicker.templates = M.core_filepicker.templates || {};
565 /**
566  * Array of image sources for real previews (realicon or realthumbnail) that are already loaded
567  */
568 M.core_filepicker.loadedpreviews = M.core_filepicker.loadedpreviews || {};
570 /**
571 * Set selected file info
573 * @param object file info
574 */
575 M.core_filepicker.select_file = function(file) {
576     M.core_filepicker.active_filepicker.select_file(file);
579 /**
580  * Init and show file picker
581  */
582 M.core_filepicker.show = function(Y, options) {
583     if (!M.core_filepicker.instances[options.client_id]) {
584         M.core_filepicker.init(Y, options);
585     }
586     M.core_filepicker.instances[options.client_id].options.formcallback = options.formcallback;
587     M.core_filepicker.instances[options.client_id].show();
588 };
590 M.core_filepicker.set_templates = function(Y, templates) {
591     for (var templid in templates) {
592         M.core_filepicker.templates[templid] = templates[templid];
593     }
596 /**
597  * Add new file picker to current instances
598  */
599 M.core_filepicker.init = function(Y, options) {
600     var FilePickerHelper = function(options) {
601         FilePickerHelper.superclass.constructor.apply(this, arguments);
602     };
604     FilePickerHelper.NAME = "FilePickerHelper";
605     FilePickerHelper.ATTRS = {
606         options: {},
607         lang: {}
608     };
610     Y.extend(FilePickerHelper, Y.Base, {
611         api: M.cfg.wwwroot+'/repository/repository_ajax.php',
612         cached_responses: {},
613         waitinterval : null, // When the loading template is being displayed and its animation is running this will be an interval instance.
614         initializer: function(options) {
615             this.options = options;
616             if (!this.options.savepath) {
617                 this.options.savepath = '/';
618             }
619         },
621         destructor: function() {
622         },
624         request: function(args, redraw) {
625             var api = (args.api ? args.api : this.api) + '?action='+args.action;
626             var params = {};
627             var scope = args['scope'] ? args['scope'] : this;
628             params['repo_id']=args.repository_id;
629             params['p'] = args.path?args.path:'';
630             params['page'] = args.page?args.page:'';
631             params['env']=this.options.env;
632             // the form element only accept certain file types
633             params['accepted_types']=this.options.accepted_types;
634             params['sesskey'] = M.cfg.sesskey;
635             params['client_id'] = args.client_id;
636             params['itemid'] = this.options.itemid?this.options.itemid:0;
637             params['maxbytes'] = this.options.maxbytes?this.options.maxbytes:-1;
638             // The unlimited value of areamaxbytes is -1, it is defined by FILE_AREA_MAX_BYTES_UNLIMITED.
639             params['areamaxbytes'] = this.options.areamaxbytes ? this.options.areamaxbytes : -1;
640             if (this.options.context && this.options.context.id) {
641                 params['ctx_id'] = this.options.context.id;
642             }
643             if (args['params']) {
644                 for (i in args['params']) {
645                     params[i] = args['params'][i];
646                 }
647             }
648             if (args.action == 'upload') {
649                 var list = [];
650                 for(var k in params) {
651                     var value = params[k];
652                     if(value instanceof Array) {
653                         for(var i in value) {
654                             list.push(k+'[]='+value[i]);
655                         }
656                     } else {
657                         list.push(k+'='+value);
658                     }
659                 }
660                 params = list.join('&');
661             } else {
662                 params = build_querystring(params);
663             }
664             var cfg = {
665                 method: 'POST',
666                 on: {
667                     complete: function(id,o,p) {
668                         var data = null;
669                         try {
670                             data = Y.JSON.parse(o.responseText);
671                         } catch(e) {
672                             if (o && o.status && o.status > 0) {
673                                 Y.use('moodle-core-notification-exception', function() {
674                                     return new M.core.exception(e);
675                                 });
676                                 return;
677                             }
678                         }
679                         // error checking
680                         if (data && data.error) {
681                             Y.use('moodle-core-notification-ajaxexception', function () {
682                                 return new M.core.ajaxException(data);
683                             });
684                             this.fpnode.one('.fp-content').setContent('');
685                             return;
686                         } else {
687                             if (data.msg) {
688                                 scope.print_msg(data.msg, 'info');
689                             }
690                             // cache result if applicable
691                             if (args.action != 'upload' && data.allowcaching) {
692                                 scope.cached_responses[params] = data;
693                             }
694                             // invoke callback
695                             args.callback(id,data,p);
696                         }
697                     }
698                 },
699                 arguments: {
700                     scope: scope
701                 },
702                 headers: {
703                     'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
704                 },
705                 data: params,
706                 context: this
707             };
708             if (args.form) {
709                 cfg.form = args.form;
710             }
711             // check if result of the same request has been already cached. If not, request it
712             // (never applicable in case of form submission and/or upload action):
713             if (!args.form && args.action != 'upload' && scope.cached_responses[params]) {
714                 args.callback(null, scope.cached_responses[params], {scope: scope})
715             } else {
716                 Y.io(api, cfg);
717                 if (redraw) {
718                     this.wait();
719                 }
720             }
721         },
722         /** displays the dialog and processes rename/overwrite if there is a file with the same name in the same filearea*/
723         process_existing_file: function(data) {
724             var scope = this;
725             var handleOverwrite = function(e) {
726                 // overwrite
727                 e.preventDefault();
728                 var data = this.process_dlg.dialogdata;
729                 var params = {}
730                 params['existingfilename'] = data.existingfile.filename;
731                 params['existingfilepath'] = data.existingfile.filepath;
732                 params['newfilename'] = data.newfile.filename;
733                 params['newfilepath'] = data.newfile.filepath;
734                 this.hide_header();
735                 this.request({
736                     'params': params,
737                     'scope': this,
738                     'action':'overwrite',
739                     'path': '',
740                     'client_id': this.options.client_id,
741                     'repository_id': this.active_repo.id,
742                     'callback': function(id, o, args) {
743                         scope.hide();
744                         // Add an arbitrary parameter to the URL to force browsers to re-load the new image even
745                         // if the file name has not changed.
746                         var urlimage = data.existingfile.url + "?time=" + (new Date()).getTime();
747                         if (scope.options.editor_target && scope.options.env == 'editor') {
748                             // editor needs to update url
749                             scope.options.editor_target.value = urlimage;
750                             scope.options.editor_target.dispatchEvent(new Event('change'), {'bubbles': true});
751                         }
752                         var fileinfo = {'client_id':scope.options.client_id,
753                             'url': urlimage,
754                             'file': data.existingfile.filename};
755                         var formcallback_scope = scope.options.magicscope ? scope.options.magicscope : scope;
756                         scope.options.formcallback.apply(formcallback_scope, [fileinfo]);
757                     }
758                 }, true);
759             }
760             var handleRename = function(e) {
761                 // inserts file with the new name
762                 e.preventDefault();
763                 var scope = this;
764                 var data = this.process_dlg.dialogdata;
765                 if (scope.options.editor_target && scope.options.env == 'editor') {
766                     scope.options.editor_target.value = data.newfile.url;
767                     scope.options.editor_target.dispatchEvent(new Event('change'), {'bubbles': true});
768                 }
769                 scope.hide();
770                 var formcallback_scope = scope.options.magicscope ? scope.options.magicscope : scope;
771                 var fileinfo = {'client_id':scope.options.client_id,
772                                 'url':data.newfile.url,
773                                 'file':data.newfile.filename};
774                 scope.options.formcallback.apply(formcallback_scope, [fileinfo]);
775             }
776             var handleCancel = function(e) {
777                 // Delete tmp file
778                 e.preventDefault();
779                 var params = {};
780                 params['newfilename'] = this.process_dlg.dialogdata.newfile.filename;
781                 params['newfilepath'] = this.process_dlg.dialogdata.newfile.filepath;
782                 this.request({
783                     'params': params,
784                     'scope': this,
785                     'action':'deletetmpfile',
786                     'path': '',
787                     'client_id': this.options.client_id,
788                     'repository_id': this.active_repo.id,
789                     'callback': function(id, o, args) {
790                         // let it be in background, from user point of view nothing is happenning
791                     }
792                 }, false);
793                 this.process_dlg.hide();
794                 this.selectui.hide();
795             }
796             if (!this.process_dlg) {
797                 this.process_dlg_node = Y.Node.create(M.core_filepicker.templates.processexistingfile);
798                 var node = this.process_dlg_node;
799                 node.generateID();
800                 this.process_dlg = new M.core.dialogue({
801                     draggable    : true,
802                     bodyContent  : node,
803                     headerContent: M.util.get_string('fileexistsdialogheader', 'repository'),
804                     centered     : true,
805                     modal        : true,
806                     visible      : false,
807                     zIndex       : this.options.zIndex
808                 });
809                 node.one('.fp-dlg-butoverwrite').on('click', handleOverwrite, this);
810                 node.one('.fp-dlg-butrename').on('click', handleRename, this);
811                 node.one('.fp-dlg-butcancel').on('click', handleCancel, this);
812                 if (this.options.env == 'editor') {
813                     node.one('.fp-dlg-text').setContent(M.util.get_string('fileexistsdialog_editor', 'repository'));
814                 } else {
815                     node.one('.fp-dlg-text').setContent(M.util.get_string('fileexistsdialog_filemanager', 'repository'));
816                 }
817             }
818             this.selectnode.removeClass('loading');
819             this.process_dlg.dialogdata = data;
820             this.process_dlg_node.one('.fp-dlg-butrename').setContent(M.util.get_string('renameto', 'repository', data.newfile.filename));
821             this.process_dlg.show();
822         },
823         /** displays error instead of filepicker contents */
824         display_error: function(errortext, errorcode) {
825             this.fpnode.one('.fp-content').setContent(M.core_filepicker.templates.error);
826             this.fpnode.one('.fp-content .fp-error').
827                 addClass(errorcode).
828                 setContent(Y.Escape.html(errortext));
829         },
830         /** displays message in a popup */
831         print_msg: function(msg, type) {
832             var header = M.util.get_string('error', 'moodle');
833             if (type != 'error') {
834                 type = 'info'; // one of only two types excepted
835                 header = M.util.get_string('info', 'moodle');
836             }
837             if (!this.msg_dlg) {
838                 this.msg_dlg_node = Y.Node.create(M.core_filepicker.templates.message);
839                 this.msg_dlg_node.generateID();
841                 this.msg_dlg = new M.core.dialogue({
842                     draggable    : true,
843                     bodyContent  : this.msg_dlg_node,
844                     centered     : true,
845                     modal        : true,
846                     visible      : false,
847                     zIndex       : this.options.zIndex
848                 });
849                 this.msg_dlg_node.one('.fp-msg-butok').on('click', function(e) {
850                     e.preventDefault();
851                     this.msg_dlg.hide();
852                 }, this);
853             }
855             this.msg_dlg.set('headerContent', header);
856             this.msg_dlg_node.removeClass('fp-msg-info').removeClass('fp-msg-error').addClass('fp-msg-'+type)
857             this.msg_dlg_node.one('.fp-msg-text').setContent(Y.Escape.html(msg));
858             this.msg_dlg.show();
859         },
860         view_files: function(appenditems) {
861             this.viewbar_set_enabled(true);
862             this.print_path();
863             /*if ((appenditems == null) && (!this.filelist || !this.filelist.length) && !this.active_repo.hasmorepages) {
864              // TODO do it via classes and adjust for each view mode!
865                 // If there are no items and no next page, just display status message and quit
866                 this.display_error(M.util.get_string('nofilesavailable', 'repository'), 'nofilesavailable');
867                 return;
868             }*/
869             if (this.viewmode == 2) {
870                 this.view_as_list(appenditems);
871             } else if (this.viewmode == 3) {
872                 this.view_as_table(appenditems);
873             } else {
874                 this.view_as_icons(appenditems);
875             }
876             this.fpnode.one('.fp-content').setAttribute('tabindex', '0');
877             this.fpnode.one('.fp-content').focus();
878             // display/hide the link for requesting next page
879             if (!appenditems && this.active_repo.hasmorepages) {
880                 if (!this.fpnode.one('.fp-content .fp-nextpage')) {
881                     this.fpnode.one('.fp-content').append(M.core_filepicker.templates.nextpage);
882                 }
883                 this.fpnode.one('.fp-content .fp-nextpage').one('a,button').on('click', function(e) {
884                     e.preventDefault();
885                     this.fpnode.one('.fp-content .fp-nextpage').addClass('loading');
886                     this.request_next_page();
887                 }, this);
888             }
889             if (!this.active_repo.hasmorepages && this.fpnode.one('.fp-content .fp-nextpage')) {
890                 this.fpnode.one('.fp-content .fp-nextpage').remove();
891             }
892             if (this.fpnode.one('.fp-content .fp-nextpage')) {
893                 this.fpnode.one('.fp-content .fp-nextpage').removeClass('loading');
894             }
895             this.content_scrolled();
896         },
897         content_scrolled: function(e) {
898             setTimeout(Y.bind(function() {
899                 if (this.processingimages) {
900                     return;
901                 }
902                 this.processingimages = true;
903                 var scope = this,
904                     fpcontent = this.fpnode.one('.fp-content'),
905                     fpcontenty = fpcontent.getY(),
906                     fpcontentheight = fpcontent.getStylePx('height'),
907                     nextpage = fpcontent.one('.fp-nextpage'),
908                     is_node_visible = function(node) {
909                         var offset = node.getY()-fpcontenty;
910                         if (offset <= fpcontentheight && (offset >=0 || offset+node.getStylePx('height')>=0)) {
911                             return true;
912                         }
913                         return false;
914                     };
915                 // automatically load next page when 'more' link becomes visible
916                 if (nextpage && !nextpage.hasClass('loading') && is_node_visible(nextpage)) {
917                     nextpage.one('a,button').simulate('click');
918                 }
919                 // replace src for visible images that need to be lazy-loaded
920                 if (scope.lazyloading) {
921                     fpcontent.all('img').each( function(node) {
922                         if (node.get('id') && scope.lazyloading[node.get('id')] && is_node_visible(node)) {
923                             node.setImgRealSrc(scope.lazyloading);
924                         }
925                     });
926                 }
927                 this.processingimages = false;
928             }, this), 200)
929         },
930         treeview_dynload: function(node, cb) {
931             var retrieved_children = {};
932             if (node.children) {
933                 for (var i in node.children) {
934                     retrieved_children[node.children[i].path] = node.children[i];
935                 }
936             }
937             this.request({
938                 action:'list',
939                 client_id: this.options.client_id,
940                 repository_id: this.active_repo.id,
941                 path:node.path?node.path:'',
942                 page:node.page?args.page:'',
943                 scope:this,
944                 callback: function(id, obj, args) {
945                     var list = obj.list;
946                     var scope = args.scope;
947                     // check that user did not leave the view mode before recieving this response
948                     if (!(scope.active_repo.id == obj.repo_id && scope.viewmode == 2 && node && node.getChildrenEl())) {
949                         return;
950                     }
951                     if (cb != null) { // (in manual mode do not update current path)
952                         scope.viewbar_set_enabled(true);
953                         scope.parse_repository_options(obj);
954                     }
955                     node.highlight(false);
956                     node.origlist = obj.list ? obj.list : null;
957                     node.origpath = obj.path ? obj.path : null;
958                     node.children = [];
959                     for(k in list) {
960                         if (list[k].children && retrieved_children[list[k].path]) {
961                             // if this child is a folder and has already been retrieved
962                             node.children[node.children.length] = retrieved_children[list[k].path];
963                         } else {
964                             // append new file to the list
965                             scope.view_as_list([list[k]]);
966                         }
967                     }
968                     if (cb == null) {
969                         node.refresh();
970                     } else {
971                         // invoke callback requested by TreeView component
972                         cb();
973                     }
974                     scope.content_scrolled();
975                 }
976             }, false);
977         },
978        classnamecallback : function(node) {
979             var classname = '';
980             if (node.children) {
981                 classname = classname + ' fp-folder';
982             }
983             if (node.isref) {
984                 classname = classname + ' fp-isreference';
985             }
986             if (node.iscontrolledlink) {
987                 classname = classname + ' fp-iscontrolledlink';
988             }
989             if (node.refcount) {
990                 classname = classname + ' fp-hasreferences';
991             }
992             if (node.originalmissing) {
993                 classname = classname + ' fp-originalmissing';
994             }
995             return Y.Lang.trim(classname);
996         },
997         /** displays list of files in tree (list) view mode. If param appenditems is specified,
998          * appends those items to the end of the list. Otherwise (default behaviour)
999          * clears the contents and displays the items from this.filelist */
1000         view_as_list: function(appenditems) {
1001             var list = (appenditems != null) ? appenditems : this.filelist;
1002             this.viewmode = 2;
1003             if (!this.filelist || this.filelist.length==0 && (!this.filepath || !this.filepath.length)) {
1004                 this.display_error(M.util.get_string('nofilesavailable', 'repository'), 'nofilesavailable');
1005                 return;
1006             }
1008             var element_template = Y.Node.create(M.core_filepicker.templates.listfilename);
1009             var options = {
1010                 viewmode : this.viewmode,
1011                 appendonly : (appenditems != null),
1012                 filenode : element_template,
1013                 callbackcontext : this,
1014                 callback : function(e, node) {
1015                     // TODO MDL-32736 e is not an event here but an object with properties 'event' and 'node'
1016                     if (!node.children) {
1017                         if (e.node.parent && e.node.parent.origpath) {
1018                             // set the current path
1019                             this.filepath = e.node.parent.origpath;
1020                             this.filelist = e.node.parent.origlist;
1021                             this.print_path();
1022                         }
1023                         this.select_file(node);
1024                     } else {
1025                         // save current path and filelist (in case we want to jump to other viewmode)
1026                         this.filepath = e.node.origpath;
1027                         this.filelist = e.node.origlist;
1028                         this.currentpath = e.node.path;
1029                         this.print_path();
1030                         this.content_scrolled();
1031                     }
1032                 },
1033                 classnamecallback : this.classnamecallback,
1034                 dynload : this.active_repo.dynload,
1035                 filepath : this.filepath,
1036                 treeview_dynload : this.treeview_dynload
1037             };
1038             this.fpnode.one('.fp-content').fp_display_filelist(options, list, this.lazyloading);
1039         },
1040         /** displays list of files in icon view mode. If param appenditems is specified,
1041          * appends those items to the end of the list. Otherwise (default behaviour)
1042          * clears the contents and displays the items from this.filelist */
1043         view_as_icons: function(appenditems) {
1044             this.viewmode = 1;
1045             var list = (appenditems != null) ? appenditems : this.filelist;
1046             var element_template = Y.Node.create(M.core_filepicker.templates.iconfilename);
1047             if ((appenditems == null) && (!this.filelist || !this.filelist.length)) {
1048                 this.display_error(M.util.get_string('nofilesavailable', 'repository'), 'nofilesavailable');
1049                 return;
1050             }
1051             var options = {
1052                 viewmode : this.viewmode,
1053                 appendonly : (appenditems != null),
1054                 filenode : element_template,
1055                 callbackcontext : this,
1056                 callback : function(e, node) {
1057                     if (e.preventDefault) {
1058                         e.preventDefault();
1059                     }
1060                     if(node.children) {
1061                         if (this.active_repo.dynload) {
1062                             this.list({'path':node.path});
1063                         } else {
1064                             this.filelist = node.children;
1065                             this.view_files();
1066                         }
1067                     } else {
1068                         this.select_file(node);
1069                     }
1070                 },
1071                 classnamecallback : this.classnamecallback
1072             };
1073             this.fpnode.one('.fp-content').fp_display_filelist(options, list, this.lazyloading);
1074         },
1075         /** displays list of files in table view mode. If param appenditems is specified,
1076          * appends those items to the end of the list. Otherwise (default behaviour)
1077          * clears the contents and displays the items from this.filelist */
1078         view_as_table: function(appenditems) {
1079             this.viewmode = 3;
1080             var list = (appenditems != null) ? appenditems : this.filelist;
1081             if (!appenditems && (!this.filelist || this.filelist.length==0) && !this.active_repo.hasmorepages) {
1082                 this.display_error(M.util.get_string('nofilesavailable', 'repository'), 'nofilesavailable');
1083                 return;
1084             }
1085             var element_template = Y.Node.create(M.core_filepicker.templates.listfilename);
1086             var options = {
1087                 viewmode : this.viewmode,
1088                 appendonly : (appenditems != null),
1089                 filenode : element_template,
1090                 callbackcontext : this,
1091                 sortable : !this.active_repo.hasmorepages,
1092                 callback : function(e, node) {
1093                     if (e.preventDefault) {e.preventDefault();}
1094                     if (node.children) {
1095                         if (this.active_repo.dynload) {
1096                             this.list({'path':node.path});
1097                         } else {
1098                             this.filelist = node.children;
1099                             this.view_files();
1100                         }
1101                     } else {
1102                         this.select_file(node);
1103                     }
1104                 },
1105                 classnamecallback : this.classnamecallback
1106             };
1107             this.fpnode.one('.fp-content').fp_display_filelist(options, list, this.lazyloading);
1108         },
1109         /** If more than one page available, requests and displays the files from the next page */
1110         request_next_page: function() {
1111             if (!this.active_repo.hasmorepages || this.active_repo.nextpagerequested) {
1112                 // nothing to load
1113                 return;
1114             }
1115             this.active_repo.nextpagerequested = true;
1116             var nextpage = this.active_repo.page+1;
1117             var args = {
1118                 page: nextpage,
1119                 repo_id: this.active_repo.id
1120             };
1121             var action = this.active_repo.issearchresult ? 'search' : 'list';
1122             this.request({
1123                 path: this.currentpath,
1124                 scope: this,
1125                 action: action,
1126                 client_id: this.options.client_id,
1127                 repository_id: args.repo_id,
1128                 params: args,
1129                 callback: function(id, obj, args) {
1130                     var scope = args.scope;
1131                     // Check that we are still in the same repository and are expecting this page. We have no way
1132                     // to compare the requested page and the one returned, so we assume that if the last chunk
1133                     // of the breadcrumb is similar, then we probably are on the same page.
1134                     var samepage = true;
1135                     if (obj.path && scope.filepath) {
1136                         var pathbefore = scope.filepath[scope.filepath.length-1];
1137                         var pathafter = obj.path[obj.path.length-1];
1138                         if (pathbefore.path != pathafter.path) {
1139                             samepage = false;
1140                         }
1141                     }
1142                     if (scope.active_repo.hasmorepages && obj.list && obj.page &&
1143                             obj.repo_id == scope.active_repo.id &&
1144                             obj.page == scope.active_repo.page+1 && samepage) {
1145                         scope.parse_repository_options(obj, true);
1146                         scope.view_files(obj.list)
1147                     }
1148                 }
1149             }, false);
1150         },
1151         select_file: function(args) {
1152             var argstitle = args.shorttitle ? args.shorttitle : args.title;
1153             // Limit the string length so it fits nicely on mobile devices
1154             var titlelength = 30;
1155             if (argstitle.length > titlelength) {
1156                 argstitle = argstitle.substring(0, titlelength) + '...';
1157             }
1158             Y.one('#fp-file_label_'+this.options.client_id).setContent(Y.Escape.html(M.util.get_string('select', 'repository')+' '+argstitle));
1159             this.selectui.show();
1160             Y.one('#'+this.selectnode.get('id')).focus();
1161             var client_id = this.options.client_id;
1162             var selectnode = this.selectnode;
1163             var return_types = this.options.repositories[this.active_repo.id].return_types;
1164             selectnode.removeClass('loading');
1165             selectnode.one('.fp-saveas input').set('value', args.title);
1167             var imgnode = Y.Node.create('<img/>').
1168                 set('src', args.realthumbnail ? args.realthumbnail : args.thumbnail).
1169                 setStyle('maxHeight', ''+(args.thumbnail_height ? args.thumbnail_height : 90)+'px').
1170                 setStyle('maxWidth', ''+(args.thumbnail_width ? args.thumbnail_width : 90)+'px');
1171             selectnode.one('.fp-thumbnail').setContent('').appendChild(imgnode);
1173             // filelink is the array of file-link-types available for this repository in this env
1174             var filelinktypes = [2/*FILE_INTERNAL*/,1/*FILE_EXTERNAL*/,4/*FILE_REFERENCE*/,8/*FILE_CONTROLLED_LINK*/];
1175             var filelink = {}, firstfilelink = null, filelinkcount = 0;
1176             for (var i in filelinktypes) {
1177                 var allowed = (return_types & filelinktypes[i]) &&
1178                     (this.options.return_types & filelinktypes[i]);
1179                 if (filelinktypes[i] == 1/*FILE_EXTERNAL*/ && !this.options.externallink && this.options.env == 'editor') {
1180                     // special configuration setting 'repositoryallowexternallinks' may prevent
1181                     // using external links in editor environment
1182                     allowed = false;
1183                 }
1184                 filelink[filelinktypes[i]] = allowed;
1185                 firstfilelink = (firstfilelink==null && allowed) ? filelinktypes[i] : firstfilelink;
1186                 filelinkcount += allowed ? 1 : 0;
1187             }
1188             var defaultreturntype = this.options.repositories[this.active_repo.id].defaultreturntype;
1189             if (defaultreturntype) {
1190                 if (filelink[defaultreturntype]) {
1191                     firstfilelink = defaultreturntype;
1192                 }
1193             }
1194             // make radio buttons enabled if this file-link-type is available and only if there are more than one file-link-type option
1195             // check the first available file-link-type option
1196             for (var linktype in filelink) {
1197                 var el = selectnode.one('.fp-linktype-'+linktype);
1198                 el.addClassIf('uneditable', !(filelink[linktype] && filelinkcount>1));
1199                 el.one('input').set('checked', (firstfilelink == linktype) ? 'checked' : '').simulate('change');
1200             }
1202             // TODO MDL-32532: attributes 'hasauthor' and 'haslicense' need to be obsolete,
1203             selectnode.one('.fp-setauthor input').set('value', args.author ? args.author : this.options.author);
1204             this.populateLicensesSelect(selectnode.one('.fp-setlicense select'), args);
1205             selectnode.one('form #filesource-'+client_id).set('value', args.source);
1206             selectnode.one('form #filesourcekey-'+client_id).set('value', args.sourcekey);
1208             // display static information about a file (when known)
1209             var attrs = ['datemodified','datecreated','size','license','author','dimensions'];
1210             for (var i in attrs) {
1211                 if (selectnode.one('.fp-'+attrs[i])) {
1212                     var value = (args[attrs[i]+'_f']) ? args[attrs[i]+'_f'] : (args[attrs[i]] ? args[attrs[i]] : '');
1213                     selectnode.one('.fp-'+attrs[i]).addClassIf('fp-unknown', ''+value == '')
1214                         .one('.fp-value').setContent(Y.Escape.html(value));
1215                 }
1216             }
1217         },
1218         setup_select_file: function() {
1219             var client_id = this.options.client_id;
1220             var selectnode = this.selectnode;
1221             var getfile = selectnode.one('.fp-select-confirm');
1222             // bind labels with corresponding inputs
1223             selectnode.all('.fp-saveas,.fp-linktype-2,.fp-linktype-1,.fp-linktype-4,fp-linktype-8,.fp-setauthor,.fp-setlicense').each(function (node) {
1224                 node.all('label').set('for', node.one('input,select').generateID());
1225             });
1226             selectnode.one('.fp-linktype-2 input').setAttrs({value: 2, name: 'linktype'});
1227             selectnode.one('.fp-linktype-1 input').setAttrs({value: 1, name: 'linktype'});
1228             selectnode.one('.fp-linktype-4 input').setAttrs({value: 4, name: 'linktype'});
1229             selectnode.one('.fp-linktype-8 input').setAttrs({value: 8, name: 'linktype'});
1230             var changelinktype = function(e) {
1231                 if (e.currentTarget.get('checked')) {
1232                     var allowinputs = e.currentTarget.get('value') != 1/*FILE_EXTERNAL*/;
1233                     selectnode.all('.fp-setauthor,.fp-setlicense,.fp-saveas').each(function(node){
1234                         node.addClassIf('uneditable', !allowinputs);
1235                         node.all('input,select').set('disabled', allowinputs?'':'disabled');
1236                     });
1237                 }
1238             };
1239             selectnode.all('.fp-linktype-2,.fp-linktype-1,.fp-linktype-4,.fp-linktype-8').each(function (node) {
1240                 node.one('input').on('change', changelinktype, this);
1241             });
1242             // register event on clicking submit button
1243             getfile.on('click', function(e) {
1244                 e.preventDefault();
1245                 var client_id = this.options.client_id;
1246                 var scope = this;
1247                 var repository_id = this.active_repo.id;
1248                 var title = selectnode.one('.fp-saveas input').get('value');
1249                 var filesource = selectnode.one('form #filesource-'+client_id).get('value');
1250                 var filesourcekey = selectnode.one('form #filesourcekey-'+client_id).get('value');
1251                 var params = {'title':title, 'source':filesource, 'savepath': this.options.savepath, sourcekey: filesourcekey};
1252                 var license = selectnode.one('.fp-setlicense select');
1253                 if (license) {
1254                     params['license'] = license.get('value');
1255                     var origlicense = selectnode.one('.fp-license .fp-value');
1256                     if (origlicense) {
1257                         origlicense = origlicense.getContent();
1258                     }
1259                     if (this.options.rememberuserlicensepref) {
1260                         this.set_preference('recentlicense', license.get('value'));
1261                     }
1262                 }
1263                 params['author'] = selectnode.one('.fp-setauthor input').get('value');
1265                 var return_types = this.options.repositories[this.active_repo.id].return_types;
1266                 if (this.options.env == 'editor') {
1267                     // in editor, images are stored in '/' only
1268                     params.savepath = '/';
1269                 }
1270                 if ((this.options.externallink || this.options.env != 'editor') &&
1271                             (return_types & 1/*FILE_EXTERNAL*/) &&
1272                             (this.options.return_types & 1/*FILE_EXTERNAL*/) &&
1273                             selectnode.one('.fp-linktype-1 input').get('checked')) {
1274                     params['linkexternal'] = 'yes';
1275                 } else if ((return_types & 4/*FILE_REFERENCE*/) &&
1276                         (this.options.return_types & 4/*FILE_REFERENCE*/) &&
1277                         selectnode.one('.fp-linktype-4 input').get('checked')) {
1278                     params['usefilereference'] = '1';
1279                 } else if ((return_types & 8/*FILE_CONTROLLED_LINK*/) &&
1280                         (this.options.return_types & 8/*FILE_CONTROLLED_LINK*/) &&
1281                         selectnode.one('.fp-linktype-8 input').get('checked')) {
1282                     params['usecontrolledlink'] = '1';
1283                 }
1285                 selectnode.addClass('loading');
1286                 this.request({
1287                     action:'download',
1288                     client_id: client_id,
1289                     repository_id: repository_id,
1290                     'params': params,
1291                     onerror: function(id, obj, args) {
1292                         selectnode.removeClass('loading');
1293                         scope.selectui.hide();
1294                     },
1295                     callback: function(id, obj, args) {
1296                         selectnode.removeClass('loading');
1297                         if (obj.event == 'fileexists') {
1298                             scope.process_existing_file(obj);
1299                             return;
1300                         }
1301                         if (scope.options.editor_target && scope.options.env=='editor') {
1302                             scope.options.editor_target.value=obj.url;
1303                             scope.options.editor_target.dispatchEvent(new Event('change'), {'bubbles': true});
1304                         }
1305                         scope.hide();
1306                         obj.client_id = client_id;
1307                         var formcallback_scope = args.scope.options.magicscope ? args.scope.options.magicscope : args.scope;
1308                         scope.options.formcallback.apply(formcallback_scope, [obj]);
1309                     }
1310                 }, false);
1311             }, this);
1312             var elform = selectnode.one('form');
1313             elform.appendChild(Y.Node.create('<input/>').
1314                 setAttrs({type:'hidden',id:'filesource-'+client_id}));
1315             elform.appendChild(Y.Node.create('<input/>').
1316                 setAttrs({type:'hidden',id:'filesourcekey-'+client_id}));
1317             elform.on('keydown', function(e) {
1318                 if (e.keyCode == 13) {
1319                     getfile.simulate('click');
1320                     e.preventDefault();
1321                 }
1322             }, this);
1323             var cancel = selectnode.one('.fp-select-cancel');
1324             cancel.on('click', function(e) {
1325                 e.preventDefault();
1326                 this.selectui.hide();
1327             }, this);
1328         },
1329         wait: function() {
1330             // First check there isn't already an interval in play, and if there is kill it now.
1331             if (this.waitinterval != null) {
1332                 clearInterval(this.waitinterval);
1333             }
1334             // Prepare the root node we will set content for and the loading template we want to display as a YUI node.
1335             var root = this.fpnode.one('.fp-content');
1336             var content = Y.Node.create(M.core_filepicker.templates.loading).addClass('fp-content-hidden').setStyle('opacity', 0);
1337             var count = 0;
1338             // Initiate an interval, we will have a count which will increment every 100 milliseconds.
1339             // Count 0 - the loading icon will have visibility set to hidden (invisible) and have an opacity of 0 (invisible also)
1340             // Count 5 - the visiblity will be switched to visible but opacity will still be at 0 (inivisible)
1341             // Counts 6 - 15 opacity will be increased by 0.1 making the loading icon visible over the period of a second
1342             // Count 16 - The interval will be cancelled.
1343             var interval = setInterval(function(){
1344                 if (!content || !root.contains(content) || count >= 15) {
1345                     clearInterval(interval);
1346                     return true;
1347                 }
1348                 if (count == 5) {
1349                     content.removeClass('fp-content-hidden');
1350                 } else if (count > 5) {
1351                     var opacity = parseFloat(content.getStyle('opacity'));
1352                     content.setStyle('opacity', opacity + 0.1);
1353                 }
1354                 count++;
1355                 return false;
1356             }, 100);
1357             // Store the wait interval so that we can check it in the future.
1358             this.waitinterval = interval;
1359             // Set the content to the loading template.
1360             root.setContent(content);
1361         },
1362         viewbar_set_enabled: function(mode) {
1363             var viewbar = this.fpnode.one('.fp-viewbar')
1364             if (viewbar) {
1365                 if (mode) {
1366                     viewbar.addClass('enabled').removeClass('disabled');
1367                     this.fpnode.all('.fp-vb-icons,.fp-vb-tree,.fp-vb-details').setAttribute("aria-disabled", "false");
1368                     this.fpnode.all('.fp-vb-icons,.fp-vb-tree,.fp-vb-details').setAttribute("tabindex", "");
1369                 } else {
1370                     viewbar.removeClass('enabled').addClass('disabled');
1371                     this.fpnode.all('.fp-vb-icons,.fp-vb-tree,.fp-vb-details').setAttribute("aria-disabled", "true");
1372                     this.fpnode.all('.fp-vb-icons,.fp-vb-tree,.fp-vb-details').setAttribute("tabindex", "-1");
1373                 }
1374             }
1375             this.fpnode.all('.fp-vb-icons,.fp-vb-tree,.fp-vb-details').removeClass('checked');
1376             var modes = {1:'icons', 2:'tree', 3:'details'};
1377             this.fpnode.all('.fp-vb-'+modes[this.viewmode]).addClass('checked');
1378         },
1379         viewbar_clicked: function(e) {
1380             e.preventDefault();
1381             var viewbar = this.fpnode.one('.fp-viewbar')
1382             if (!viewbar || !viewbar.hasClass('disabled')) {
1383                 if (e.currentTarget.hasClass('fp-vb-tree')) {
1384                     this.viewmode = 2;
1385                 } else if (e.currentTarget.hasClass('fp-vb-details')) {
1386                     this.viewmode = 3;
1387                 } else {
1388                     this.viewmode = 1;
1389                 }
1390                 this.viewbar_set_enabled(true)
1391                 this.view_files();
1392                 this.set_preference('recentviewmode', this.viewmode);
1393             }
1394         },
1395         render: function() {
1396             var client_id = this.options.client_id;
1397             var fpid = "filepicker-"+ client_id;
1398             var labelid = 'fp-dialog-label_'+ client_id;
1399             var width = 873;
1400             var draggable = true;
1401             this.fpnode = Y.Node.create(M.core_filepicker.templates.generallayout).
1402                 set('id', 'filepicker-'+client_id).set('aria-labelledby', labelid);
1404             if (this.in_iframe()) {
1405                 width = Math.floor(window.innerWidth * 0.95);
1406                 draggable = false;
1407             }
1409             this.mainui = new M.core.dialogue({
1410                 extraClasses : ['filepicker'],
1411                 draggable    : draggable,
1412                 bodyContent  : this.fpnode,
1413                 headerContent: '<h3 id="'+ labelid +'">'+ M.util.get_string('filepicker', 'repository') +'</h3>',
1414                 centered     : true,
1415                 modal        : true,
1416                 visible      : false,
1417                 width        : width+'px',
1418                 responsiveWidth : 768,
1419                 height       : '558px',
1420                 zIndex       : this.options.zIndex
1421             });
1423             // create panel for selecting a file (initially hidden)
1424             this.selectnode = Y.Node.create(M.core_filepicker.templates.selectlayout).
1425                 set('id', 'filepicker-select-'+client_id).
1426                 set('aria-live', 'assertive').
1427                 set('role', 'dialog');
1429             var fplabel = 'fp-file_label_'+ client_id;
1430             this.selectui = new M.core.dialogue({
1431                 headerContent: '<h3 id="' + fplabel +'">'+M.util.get_string('select', 'repository')+'</h3>',
1432                 draggable    : true,
1433                 width        : '450px',
1434                 bodyContent  : this.selectnode,
1435                 centered     : true,
1436                 modal        : true,
1437                 visible      : false,
1438                 zIndex       : this.options.zIndex
1439             });
1440             Y.one('#'+this.selectnode.get('id')).setAttribute('aria-labelledby', fplabel);
1441             // event handler for lazy loading of thumbnails and next page
1442             this.fpnode.one('.fp-content').on(['scroll','resize'], this.content_scrolled, this);
1443             // save template for one path element and location of path bar
1444             if (this.fpnode.one('.fp-path-folder')) {
1445                 this.pathnode = this.fpnode.one('.fp-path-folder');
1446                 this.pathbar = this.pathnode.get('parentNode');
1447                 this.pathbar.removeChild(this.pathnode);
1448             }
1449             // assign callbacks for view mode switch buttons
1450             this.fpnode.one('.fp-vb-icons').on('click', this.viewbar_clicked, this);
1451             this.fpnode.one('.fp-vb-tree').on('click', this.viewbar_clicked, this);
1452             this.fpnode.one('.fp-vb-details').on('click', this.viewbar_clicked, this);
1454             // assign callbacks for toolbar links
1455             this.setup_toolbar();
1456             this.setup_select_file();
1457             this.hide_header();
1459             // processing repository listing
1460             // Resort the repositories by sortorder
1461             var sorted_repositories = [];
1462             var i;
1463             for (i in this.options.repositories) {
1464                 sorted_repositories[i] = this.options.repositories[i];
1465             }
1466             sorted_repositories.sort(function(a,b){return a.sortorder-b.sortorder});
1467             // extract one repository template and repeat it for all repositories available,
1468             // set name and icon and assign callbacks
1469             var reponode = this.fpnode.one('.fp-repo');
1470             if (reponode) {
1471                 var list = reponode.get('parentNode');
1472                 list.removeChild(reponode);
1473                 for (i in sorted_repositories) {
1474                     var repository = sorted_repositories[i];
1475                     var h = (parseInt(i) == 0) ? parseInt(i) : parseInt(i) - 1,
1476                         j = (parseInt(i) == Object.keys(sorted_repositories).length - 1) ? parseInt(i) : parseInt(i) + 1;
1477                     var previousrepository = sorted_repositories[h];
1478                     var nextrepository = sorted_repositories[j];
1479                     var node = reponode.cloneNode(true);
1480                     list.appendChild(node);
1481                     node.
1482                         set('id', 'fp-repo-'+client_id+'-'+repository.id).
1483                         on('click', function(e, repository_id) {
1484                             e.preventDefault();
1485                             this.set_preference('recentrepository', repository_id);
1486                             this.hide_header();
1487                             this.list({'repo_id':repository_id});
1488                         }, this /*handler running scope*/, repository.id/*second argument of handler*/);
1489                     node.on('key', function(e, previousrepositoryid, nextrepositoryid, clientid, repositoryid) {
1490                         this.changeHighlightedRepository(e, clientid, repositoryid, previousrepositoryid, nextrepositoryid);
1491                     }, 'down:38,40', this, previousrepository.id, nextrepository.id, client_id, repository.id);
1492                     node.on('key', function(e, repositoryid) {
1493                         e.preventDefault();
1494                         this.set_preference('recentrepository', repositoryid);
1495                         this.hide_header();
1496                         this.list({'repo_id': repositoryid});
1497                     }, 'enter', this, repository.id);
1498                     node.one('.fp-repo-name').setContent(Y.Escape.html(repository.name));
1499                     node.one('.fp-repo-icon').set('src', repository.icon);
1500                     if (i==0) {
1501                         node.addClass('first');
1502                     }
1503                     if (i==sorted_repositories.length-1) {
1504                         node.addClass('last');
1505                     }
1506                     if (i%2) {
1507                         node.addClass('even');
1508                     } else {
1509                         node.addClass('odd');
1510                     }
1511                 }
1512             }
1513             // display error if no repositories found
1514             if (sorted_repositories.length==0) {
1515                 this.display_error(M.util.get_string('norepositoriesavailable', 'repository'), 'norepositoriesavailable')
1516             }
1517             // display repository that was used last time
1518             this.mainui.show();
1519             this.show_recent_repository();
1520         },
1521         /**
1522          * Change the highlighted repository to a new one.
1523          *
1524          * @param  {object} event The key event
1525          * @param  {integer} clientid The client id to identify the repo class.
1526          * @param  {integer} oldrepositoryid The repository id that we are removing the highlight for
1527          * @param  {integer} previousrepositoryid The previous repository id.
1528          * @param  {integer} nextrepositoryid The next repository id.
1529          */
1530         changeHighlightedRepository: function(event, clientid, oldrepositoryid, previousrepositoryid, nextrepositoryid) {
1531             event.preventDefault();
1532             var newrepositoryid = (event.keyCode == '40') ? nextrepositoryid : previousrepositoryid;
1533             this.fpnode.one('#fp-repo-' + clientid + '-' + oldrepositoryid).setAttribute('tabindex', '-1');
1534             this.fpnode.one('#fp-repo-' + clientid + '-' + newrepositoryid)
1535                     .setAttribute('tabindex', '0')
1536                     .focus();
1537         },
1538         parse_repository_options: function(data, appendtolist) {
1539             if (appendtolist) {
1540                 if (data.list) {
1541                     if (!this.filelist) {
1542                         this.filelist = [];
1543                     }
1544                     for (var i in data.list) {
1545                         this.filelist[this.filelist.length] = data.list[i];
1546                     }
1547                 }
1548             } else {
1549                 this.filelist = data.list?data.list:null;
1550                 this.lazyloading = {};
1551             }
1552             this.filepath = data.path?data.path:null;
1553             this.objecttag = data.object?data.object:null;
1554             this.active_repo = {};
1555             this.active_repo.issearchresult = data.issearchresult ? true : false;
1556             this.active_repo.defaultreturntype = data.defaultreturntype?data.defaultreturntype:null;
1557             this.active_repo.dynload = data.dynload?data.dynload:false;
1558             this.active_repo.pages = Number(data.pages?data.pages:null);
1559             this.active_repo.page = Number(data.page?data.page:null);
1560             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))
1561             this.active_repo.id = data.repo_id?data.repo_id:null;
1562             this.active_repo.nosearch = (data.login || data.nosearch); // this is either login form or 'nosearch' attribute set
1563             this.active_repo.norefresh = (data.login || data.norefresh); // this is either login form or 'norefresh' attribute set
1564             this.active_repo.nologin = (data.login || data.nologin); // this is either login form or 'nologin' attribute is set
1565             this.active_repo.logouttext = data.logouttext?data.logouttext:null;
1566             this.active_repo.logouturl = (data.logouturl || '');
1567             this.active_repo.message = (data.message || '');
1568             this.active_repo.help = data.help?data.help:null;
1569             this.active_repo.manage = data.manage?data.manage:null;
1570             this.print_header();
1571         },
1572         print_login: function(data) {
1573             this.parse_repository_options(data);
1574             var client_id = this.options.client_id;
1575             var repository_id = data.repo_id;
1576             var l = this.logindata = data.login;
1577             var loginurl = '';
1578             var action = data['login_btn_action'] ? data['login_btn_action'] : 'login';
1579             var form_id = 'fp-form-'+client_id;
1581             var loginform_node = Y.Node.create(M.core_filepicker.templates.loginform);
1582             loginform_node.one('form').set('id', form_id);
1583             this.fpnode.one('.fp-content').setContent('').appendChild(loginform_node);
1584             var templates = {
1585                 'popup' : loginform_node.one('.fp-login-popup'),
1586                 'textarea' : loginform_node.one('.fp-login-textarea'),
1587                 'select' : loginform_node.one('.fp-login-select'),
1588                 'text' : loginform_node.one('.fp-login-text'),
1589                 'radio' : loginform_node.one('.fp-login-radiogroup'),
1590                 'checkbox' : loginform_node.one('.fp-login-checkbox'),
1591                 'input' : loginform_node.one('.fp-login-input')
1592             };
1593             var container;
1594             for (var i in templates) {
1595                 if (templates[i]) {
1596                     container = templates[i].get('parentNode');
1597                     container.removeChild(templates[i]);
1598                 }
1599             }
1601             for(var k in l) {
1602                 if (templates[l[k].type]) {
1603                     var node = templates[l[k].type].cloneNode(true);
1604                 } else {
1605                     node = templates['input'].cloneNode(true);
1606                 }
1607                 if (l[k].type == 'popup') {
1608                     // submit button
1609                     loginurl = l[k].url;
1610                     var popupbutton = node.one('button');
1611                     popupbutton.on('click', function(e){
1612                         M.core_filepicker.active_filepicker = this;
1613                         window.open(loginurl, 'repo_auth', 'location=0,status=0,width=500,height=300,scrollbars=yes');
1614                         e.preventDefault();
1615                     }, this);
1616                     loginform_node.one('form').on('keydown', function(e) {
1617                         if (e.keyCode == 13) {
1618                             popupbutton.simulate('click');
1619                             e.preventDefault();
1620                         }
1621                     }, this);
1622                     loginform_node.all('.fp-login-submit').remove();
1623                     action = 'popup';
1624                 } else if(l[k].type=='textarea') {
1625                     // textarea element
1626                     if (node.one('label')) {
1627                         node.one('label').set('for', l[k].id).setContent(l[k].label);
1628                     }
1629                     node.one('textarea').setAttrs({id:l[k].id, name:l[k].name});
1630                 } else if(l[k].type=='select') {
1631                     // select element
1632                     if (node.one('label')) {
1633                         node.one('label').set('for', l[k].id).setContent(l[k].label);
1634                     }
1635                     node.one('select').setAttrs({id:l[k].id, name:l[k].name}).setContent('');
1636                     for (i in l[k].options) {
1637                         node.one('select').appendChild(
1638                             Y.Node.create('<option/>').
1639                                 set('value', l[k].options[i].value).
1640                                 setContent(l[k].options[i].label));
1641                     }
1642                 } else if(l[k].type=='radio') {
1643                     // radio input element
1644                     node.all('label').setContent(l[k].label);
1645                     var list = l[k].value.split('|');
1646                     var labels = l[k].value_label.split('|');
1647                     var radionode = null;
1648                     for(var item in list) {
1649                         if (radionode == null) {
1650                             radionode = node.one('.fp-login-radio');
1651                             radionode.one('input').set('checked', 'checked');
1652                         } else {
1653                             var x = radionode.cloneNode(true);
1654                             radionode.insert(x, 'after');
1655                             radionode = x;
1656                             radionode.one('input').set('checked', '');
1657                         }
1658                         radionode.one('input').setAttrs({id:''+l[k].id+item, name:l[k].name,
1659                             type:l[k].type, value:list[item]});
1660                         radionode.all('label').setContent(labels[item]).set('for', ''+l[k].id+item)
1661                     }
1662                     if (radionode == null) {
1663                         node.one('.fp-login-radio').remove();
1664                     }
1665                 } else {
1666                     // input element
1667                     if (node.one('label')) { node.one('label').set('for', l[k].id).setContent(l[k].label) }
1668                     node.one('input').
1669                         set('type', l[k].type).
1670                         set('id', l[k].id).
1671                         set('name', l[k].name).
1672                         set('value', l[k].value?l[k].value:'')
1673                 }
1674                 container.appendChild(node);
1675             }
1676             // custom label text for submit button
1677             if (data['login_btn_label']) {
1678                 loginform_node.all('.fp-login-submit').setContent(data['login_btn_label'])
1679             }
1680             // register button action for login and search
1681             if (action == 'login' || action == 'search') {
1682                 loginform_node.one('.fp-login-submit').on('click', function(e){
1683                     e.preventDefault();
1684                     this.hide_header();
1685                     this.request({
1686                         'scope': this,
1687                         'action':(action == 'search') ? 'search' : 'signin',
1688                         'path': '',
1689                         'client_id': client_id,
1690                         'repository_id': repository_id,
1691                         'form': {id:form_id, upload:false, useDisabled:true},
1692                         'callback': this.display_response
1693                     }, true);
1694                 }, this);
1695             }
1696             // if 'Enter' is pressed in the form, simulate the button click
1697             if (loginform_node.one('.fp-login-submit')) {
1698                 loginform_node.one('form').on('keydown', function(e) {
1699                     if (e.keyCode == 13) {
1700                         loginform_node.one('.fp-login-submit').simulate('click')
1701                         e.preventDefault();
1702                     }
1703                 }, this);
1704             }
1705         },
1706         display_response: function(id, obj, args) {
1707             var scope = args.scope;
1708             // highlight the current repository in repositories list
1709             scope.fpnode.all('.fp-repo.active')
1710                     .removeClass('active')
1711                     .setAttribute('aria-selected', 'false')
1712                     .setAttribute('tabindex', '-1');
1713             scope.fpnode.all('.nav-link')
1714                     .removeClass('active')
1715                     .setAttribute('aria-selected', 'false')
1716                     .setAttribute('tabindex', '-1');
1717             var activenode = scope.fpnode.one('#fp-repo-' + scope.options.client_id + '-' + obj.repo_id);
1718             activenode.addClass('active')
1719                     .setAttribute('aria-selected', 'true')
1720                     .setAttribute('tabindex', '0');
1721             activenode.all('.nav-link').addClass('active');
1722             // add class repository_REPTYPE to the filepicker (for repository-specific styles)
1723             for (var i in scope.options.repositories) {
1724                 scope.fpnode.removeClass('repository_'+scope.options.repositories[i].type)
1725             }
1726             if (obj.repo_id && scope.options.repositories[obj.repo_id]) {
1727                 scope.fpnode.addClass('repository_'+scope.options.repositories[obj.repo_id].type)
1728             }
1729             Y.one('.file-picker .fp-repo-items').focus();
1731             // display response
1732             if (obj.login) {
1733                 scope.viewbar_set_enabled(false);
1734                 scope.print_login(obj);
1735             } else if (obj.upload) {
1736                 scope.viewbar_set_enabled(false);
1737                 scope.parse_repository_options(obj);
1738                 scope.create_upload_form(obj);
1739             } else if (obj.object) {
1740                 M.core_filepicker.active_filepicker = scope;
1741                 scope.viewbar_set_enabled(false);
1742                 scope.parse_repository_options(obj);
1743                 scope.create_object_container(obj.object);
1744             } else if (obj.list) {
1745                 scope.viewbar_set_enabled(true);
1746                 scope.parse_repository_options(obj);
1747                 scope.view_files();
1748             }
1749         },
1750         list: function(args) {
1751             if (!args) {
1752                 args = {};
1753             }
1754             if (!args.repo_id) {
1755                 args.repo_id = this.active_repo.id;
1756             }
1757             if (!args.path) {
1758                 args.path = '';
1759             }
1760             this.currentpath = args.path;
1761             this.request({
1762                 action: 'list',
1763                 client_id: this.options.client_id,
1764                 repository_id: args.repo_id,
1765                 path: args.path,
1766                 page: args.page,
1767                 scope: this,
1768                 callback: this.display_response
1769             }, true);
1770         },
1771         populateLicensesSelect: function(licensenode, filenode) {
1772             if (!licensenode) {
1773                 return;
1774             }
1775             licensenode.setContent('');
1776             var selectedlicense = this.options.defaultlicense;
1777             if (filenode) {
1778                 // File has a license already, use it.
1779                 selectedlicense = filenode.license;
1780             } else if (this.options.rememberuserlicensepref) {
1781                 selectedlicense = this.get_preference('recentlicense');
1782             }
1783             var licenses = this.options.licenses;
1784             for (var i in licenses) {
1785                 // Include the file's current license, even if not enabled, to prevent displaying
1786                 // misleading information about which license the file currently has assigned to it.
1787                 if (licenses[i].enabled == true || (filenode !== undefined && licenses[i].shortname === filenode.license)) {
1788                     var option = Y.Node.create('<option/>').
1789                     set('selected', (licenses[i].shortname == selectedlicense)).
1790                     set('value', licenses[i].shortname).
1791                     setContent(Y.Escape.html(licenses[i].fullname));
1792                     licensenode.appendChild(option);
1793                 }
1794             }
1795         },
1796         create_object_container: function(data) {
1797             var content = this.fpnode.one('.fp-content');
1798             content.setContent('');
1799             //var str = '<object data="'+data.src+'" type="'+data.type+'" width="98%" height="98%" id="container_object" class="fp-object-container mdl-align"></object>';
1800             var container = Y.Node.create('<object/>').
1801                 setAttrs({data:data.src, type:data.type, id:'container_object'}).
1802                 addClass('fp-object-container');
1803             content.setContent('').appendChild(container);
1804         },
1805         create_upload_form: function(data) {
1806             var client_id = this.options.client_id;
1807             var id = data.upload.id+'_'+client_id;
1808             var content = this.fpnode.one('.fp-content');
1809             var template_name = 'uploadform_'+this.options.repositories[data.repo_id].type;
1810             var template = M.core_filepicker.templates[template_name] || M.core_filepicker.templates['uploadform'];
1811             content.setContent(template);
1813             content.all('.fp-file,.fp-saveas,.fp-setauthor,.fp-setlicense').each(function (node) {
1814                 node.all('label').set('for', node.one('input,select').generateID());
1815             });
1816             content.one('form').set('id', id);
1817             content.one('.fp-file input').set('name', 'repo_upload_file');
1818             if (data.upload.label && content.one('.fp-file label')) {
1819                 content.one('.fp-file label').setContent(data.upload.label);
1820             }
1821             content.one('.fp-saveas input').set('name', 'title');
1822             content.one('.fp-setauthor input').setAttrs({name:'author', value:this.options.author});
1823             content.one('.fp-setlicense select').set('name', 'license');
1824             this.populateLicensesSelect(content.one('.fp-setlicense select'));
1825             // append hidden inputs to the upload form
1826             content.one('form').appendChild(Y.Node.create('<input/>').
1827                 setAttrs({type:'hidden',name:'itemid',value:this.options.itemid}));
1828             var types = this.options.accepted_types;
1829             for (var i in types) {
1830                 content.one('form').appendChild(Y.Node.create('<input/>').
1831                     setAttrs({type:'hidden',name:'accepted_types[]',value:types[i]}));
1832             }
1834             var scope = this;
1835             content.one('.fp-upload-btn').on('click', function(e) {
1836                 e.preventDefault();
1837                 var license = content.one('.fp-setlicense select');
1839                 if (this.options.rememberuserlicensepref) {
1840                     this.set_preference('recentlicense', license.get('value'));
1841                 }
1842                 if (!content.one('.fp-file input').get('value')) {
1843                     scope.print_msg(M.util.get_string('nofilesattached', 'repository'), 'error');
1844                     return false;
1845                 }
1846                 this.hide_header();
1847                 scope.request({
1848                         scope: scope,
1849                         action:'upload',
1850                         client_id: client_id,
1851                         params: {'savepath':scope.options.savepath},
1852                         repository_id: scope.active_repo.id,
1853                         form: {id: id, upload:true},
1854                         onerror: function(id, o, args) {
1855                             scope.create_upload_form(data);
1856                         },
1857                         callback: function(id, o, args) {
1858                             if (o.event == 'fileexists') {
1859                                 scope.create_upload_form(data);
1860                                 scope.process_existing_file(o);
1861                                 return;
1862                             }
1863                             if (scope.options.editor_target&&scope.options.env=='editor') {
1864                                 scope.options.editor_target.value=o.url;
1865                                 scope.options.editor_target.dispatchEvent(new Event('change'), {'bubbles': true});
1866                             }
1867                             scope.hide();
1868                             o.client_id = client_id;
1869                             var formcallback_scope = args.scope.options.magicscope ? args.scope.options.magicscope : args.scope;
1870                             scope.options.formcallback.apply(formcallback_scope, [o]);
1871                         }
1872                 }, true);
1873             }, this);
1874         },
1875         /** setting handlers and labels for elements in toolbar. Called once during the initial render of filepicker */
1876         setup_toolbar: function() {
1877             var client_id = this.options.client_id;
1878             var toolbar = this.fpnode.one('.fp-toolbar');
1879             toolbar.one('.fp-tb-logout').one('a,button').on('click', function(e) {
1880                 e.preventDefault();
1881                 if (!this.active_repo.nologin) {
1882                     this.hide_header();
1883                     this.request({
1884                         action:'logout',
1885                         client_id: this.options.client_id,
1886                         repository_id: this.active_repo.id,
1887                         path:'',
1888                         callback: this.display_response
1889                     }, true);
1890                 }
1891                 if (this.active_repo.logouturl) {
1892                     window.open(this.active_repo.logouturl, 'repo_auth', 'location=0,status=0,width=500,height=300,scrollbars=yes');
1893                 }
1894             }, this);
1895             toolbar.one('.fp-tb-refresh').one('a,button').on('click', function(e) {
1896                 e.preventDefault();
1897                 if (!this.active_repo.norefresh) {
1898                     this.list({ path: this.currentpath });
1899                 }
1900             }, this);
1901             toolbar.one('.fp-tb-search form').
1902                 set('method', 'POST').
1903                 set('id', 'fp-tb-search-'+client_id).
1904                 on('submit', function(e) {
1905                     e.preventDefault();
1906                     if (!this.active_repo.nosearch) {
1907                         this.request({
1908                             scope: this,
1909                             action:'search',
1910                             client_id: this.options.client_id,
1911                             repository_id: this.active_repo.id,
1912                             form: {id: 'fp-tb-search-'+client_id, upload:false, useDisabled:true},
1913                             callback: this.display_response
1914                         }, true);
1915                     }
1916             }, this);
1918             // it does not matter what kind of element is .fp-tb-manage, we create a dummy <a>
1919             // element and use it to open url on click event
1920             var managelnk = Y.Node.create('<a/>').
1921                 setAttrs({id:'fp-tb-manage-'+client_id+'-link', target:'_blank'}).
1922                 setStyle('display', 'none');
1923             toolbar.append(managelnk);
1924             toolbar.one('.fp-tb-manage').one('a,button').
1925                 on('click', function(e) {
1926                     e.preventDefault();
1927                     managelnk.simulate('click')
1928                 });
1930             // same with .fp-tb-help
1931             var helplnk = Y.Node.create('<a/>').
1932                 setAttrs({id:'fp-tb-help-'+client_id+'-link', target:'_blank'}).
1933                 setStyle('display', 'none');
1934             toolbar.append(helplnk);
1935             toolbar.one('.fp-tb-help').one('a,button').
1936                 on('click', function(e) {
1937                     e.preventDefault();
1938                     helplnk.simulate('click')
1939                 });
1940         },
1941         hide_header: function() {
1942             if (this.fpnode.one('.fp-toolbar')) {
1943                 this.fpnode.one('.fp-toolbar').addClass('empty');
1944             }
1945             if (this.pathbar) {
1946                 this.pathbar.setContent('').addClass('empty');
1947             }
1948         },
1949         print_header: function() {
1950             var r = this.active_repo;
1951             var scope = this;
1952             var client_id = this.options.client_id;
1953             this.hide_header();
1954             this.print_path();
1955             var toolbar = this.fpnode.one('.fp-toolbar');
1956             if (!toolbar) { return; }
1958             var enable_tb_control = function(node, enabled) {
1959                 if (!node) { return; }
1960                 node.addClassIf('disabled', !enabled).addClassIf('enabled', enabled)
1961                 if (enabled) {
1962                     toolbar.removeClass('empty');
1963                 }
1964             }
1966             // TODO 'back' permanently disabled for now. Note, flickr_public uses 'Logout' for it!
1967             enable_tb_control(toolbar.one('.fp-tb-back'), false);
1969             // search form
1970             enable_tb_control(toolbar.one('.fp-tb-search'), !r.nosearch);
1971             if(!r.nosearch) {
1972                 var searchform = toolbar.one('.fp-tb-search form');
1973                 searchform.setContent('');
1974                 this.request({
1975                     scope: this,
1976                     action:'searchform',
1977                     repository_id: this.active_repo.id,
1978                     callback: function(id, obj, args) {
1979                         if (obj.repo_id == scope.active_repo.id && obj.form) {
1980                             // if we did not jump to another repository meanwhile
1981                             searchform.setContent(obj.form);
1982                             // Highlight search text when user click for search.
1983                             var searchnode = searchform.one('input[name="s"]');
1984                             if (searchnode) {
1985                                 searchnode.once('click', function(e) {
1986                                     e.preventDefault();
1987                                     this.select();
1988                                 });
1989                             }
1990                         }
1991                     }
1992                 }, false);
1993             }
1995             // refresh button
1996             // weather we use cache for this instance, this button will reload listing anyway
1997             enable_tb_control(toolbar.one('.fp-tb-refresh'), !r.norefresh);
1999             // login button
2000             enable_tb_control(toolbar.one('.fp-tb-logout'), !r.nologin);
2002             // manage url
2003             enable_tb_control(toolbar.one('.fp-tb-manage'), r.manage);
2004             Y.one('#fp-tb-manage-'+client_id+'-link').set('href', r.manage);
2006             // help url
2007             enable_tb_control(toolbar.one('.fp-tb-help'), r.help);
2008             Y.one('#fp-tb-help-'+client_id+'-link').set('href', r.help);
2010             // message
2011             enable_tb_control(toolbar.one('.fp-tb-message'), r.message);
2012             toolbar.one('.fp-tb-message').setContent(r.message);
2013         },
2014         print_path: function() {
2015             if (!this.pathbar) {
2016                 return;
2017             }
2018             this.pathbar.setContent('').addClass('empty');
2019             var p = this.filepath;
2020             if (p && p.length!=0 && this.viewmode != 2) {
2021                 for(var i = 0; i < p.length; i++) {
2022                     var el = this.pathnode.cloneNode(true);
2023                     this.pathbar.appendChild(el);
2024                     if (i == 0) {
2025                         el.addClass('first');
2026                     }
2027                     if (i == p.length-1) {
2028                         el.addClass('last');
2029                     }
2030                     if (i%2) {
2031                         el.addClass('even');
2032                     } else {
2033                         el.addClass('odd');
2034                     }
2035                     el.all('.fp-path-folder-name').setContent(Y.Escape.html(p[i].name));
2036                     el.on('click',
2037                             function(e, path) {
2038                                 e.preventDefault();
2039                                 this.list({'path':path});
2040                             },
2041                         this, p[i].path);
2042                 }
2043                 this.pathbar.removeClass('empty');
2044             }
2045         },
2046         hide: function() {
2047             this.selectui.hide();
2048             if (this.process_dlg) {
2049                 this.process_dlg.hide();
2050             }
2051             if (this.msg_dlg) {
2052                 this.msg_dlg.hide();
2053             }
2054             this.mainui.hide();
2055         },
2056         show: function() {
2057             if (this.fpnode) {
2058                 this.hide();
2059                 this.mainui.show();
2060                 this.show_recent_repository();
2061             } else {
2062                 this.launch();
2063             }
2064         },
2065         launch: function() {
2066             this.render();
2067         },
2068         show_recent_repository: function() {
2069             this.hide_header();
2070             this.viewbar_set_enabled(false);
2071             var repository_id = this.get_preference('recentrepository');
2072             this.viewmode = this.get_preference('recentviewmode');
2073             if (this.viewmode != 2 && this.viewmode != 3) {
2074                 this.viewmode = 1;
2075             }
2076             if (this.options.repositories[repository_id]) {
2077                 this.list({'repo_id':repository_id});
2078             }
2079         },
2080         get_preference: function (name) {
2081             if (this.options.userprefs[name]) {
2082                 return this.options.userprefs[name];
2083             } else {
2084                 return false;
2085             }
2086         },
2087         set_preference: function(name, value) {
2088             if (this.options.userprefs[name] != value) {
2089                 M.util.set_user_preference('filepicker_' + name, value);
2090                 this.options.userprefs[name] = value;
2091             }
2092         },
2093         in_iframe: function () {
2094             // If we're not the top window then we're in an iFrame
2095             return window.self !== window.top;
2096         }
2097     });
2098     var loading = Y.one('#filepicker-loading-'+options.client_id);
2099     if (loading) {
2100         loading.setStyle('display', 'none');
2101     }
2102     M.core_filepicker.instances[options.client_id] = new FilePickerHelper(options);
2103 };