MDL-68576 filepicker: Fix inability to select files in table view
[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.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.set_selected_license(selectnode.one('.fp-setlicense'), args.license);
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             this.populate_licenses_select(selectnode.one('.fp-setlicense select'));
1243             // register event on clicking submit button
1244             getfile.on('click', function(e) {
1245                 e.preventDefault();
1246                 var client_id = this.options.client_id;
1247                 var scope = this;
1248                 var repository_id = this.active_repo.id;
1249                 var title = selectnode.one('.fp-saveas input').get('value');
1250                 var filesource = selectnode.one('form #filesource-'+client_id).get('value');
1251                 var filesourcekey = selectnode.one('form #filesourcekey-'+client_id).get('value');
1252                 var params = {'title':title, 'source':filesource, 'savepath': this.options.savepath, sourcekey: filesourcekey};
1253                 var license = selectnode.one('.fp-setlicense select');
1254                 if (license) {
1255                     params['license'] = license.get('value');
1256                     var origlicense = selectnode.one('.fp-license .fp-value');
1257                     if (origlicense) {
1258                         origlicense = origlicense.getContent();
1259                     }
1260                     this.set_preference('recentlicense', license.get('value'));
1261                 }
1262                 params['author'] = selectnode.one('.fp-setauthor input').get('value');
1264                 var return_types = this.options.repositories[this.active_repo.id].return_types;
1265                 if (this.options.env == 'editor') {
1266                     // in editor, images are stored in '/' only
1267                     params.savepath = '/';
1268                 }
1269                 if ((this.options.externallink || this.options.env != 'editor') &&
1270                             (return_types & 1/*FILE_EXTERNAL*/) &&
1271                             (this.options.return_types & 1/*FILE_EXTERNAL*/) &&
1272                             selectnode.one('.fp-linktype-1 input').get('checked')) {
1273                     params['linkexternal'] = 'yes';
1274                 } else if ((return_types & 4/*FILE_REFERENCE*/) &&
1275                         (this.options.return_types & 4/*FILE_REFERENCE*/) &&
1276                         selectnode.one('.fp-linktype-4 input').get('checked')) {
1277                     params['usefilereference'] = '1';
1278                 } else if ((return_types & 8/*FILE_CONTROLLED_LINK*/) &&
1279                         (this.options.return_types & 8/*FILE_CONTROLLED_LINK*/) &&
1280                         selectnode.one('.fp-linktype-8 input').get('checked')) {
1281                     params['usecontrolledlink'] = '1';
1282                 }
1284                 selectnode.addClass('loading');
1285                 this.request({
1286                     action:'download',
1287                     client_id: client_id,
1288                     repository_id: repository_id,
1289                     'params': params,
1290                     onerror: function(id, obj, args) {
1291                         selectnode.removeClass('loading');
1292                         scope.selectui.hide();
1293                     },
1294                     callback: function(id, obj, args) {
1295                         selectnode.removeClass('loading');
1296                         if (obj.event == 'fileexists') {
1297                             scope.process_existing_file(obj);
1298                             return;
1299                         }
1300                         if (scope.options.editor_target && scope.options.env=='editor') {
1301                             scope.options.editor_target.value=obj.url;
1302                             scope.options.editor_target.dispatchEvent(new Event('change'), {'bubbles': true});
1303                         }
1304                         scope.hide();
1305                         obj.client_id = client_id;
1306                         var formcallback_scope = args.scope.options.magicscope ? args.scope.options.magicscope : args.scope;
1307                         scope.options.formcallback.apply(formcallback_scope, [obj]);
1308                     }
1309                 }, false);
1310             }, this);
1311             var elform = selectnode.one('form');
1312             elform.appendChild(Y.Node.create('<input/>').
1313                 setAttrs({type:'hidden',id:'filesource-'+client_id}));
1314             elform.appendChild(Y.Node.create('<input/>').
1315                 setAttrs({type:'hidden',id:'filesourcekey-'+client_id}));
1316             elform.on('keydown', function(e) {
1317                 if (e.keyCode == 13) {
1318                     getfile.simulate('click');
1319                     e.preventDefault();
1320                 }
1321             }, this);
1322             var cancel = selectnode.one('.fp-select-cancel');
1323             cancel.on('click', function(e) {
1324                 e.preventDefault();
1325                 this.selectui.hide();
1326             }, this);
1327         },
1328         wait: function() {
1329             // First check there isn't already an interval in play, and if there is kill it now.
1330             if (this.waitinterval != null) {
1331                 clearInterval(this.waitinterval);
1332             }
1333             // Prepare the root node we will set content for and the loading template we want to display as a YUI node.
1334             var root = this.fpnode.one('.fp-content');
1335             var content = Y.Node.create(M.core_filepicker.templates.loading).addClass('fp-content-hidden').setStyle('opacity', 0);
1336             var count = 0;
1337             // Initiate an interval, we will have a count which will increment every 100 milliseconds.
1338             // Count 0 - the loading icon will have visibility set to hidden (invisible) and have an opacity of 0 (invisible also)
1339             // Count 5 - the visiblity will be switched to visible but opacity will still be at 0 (inivisible)
1340             // Counts 6 - 15 opacity will be increased by 0.1 making the loading icon visible over the period of a second
1341             // Count 16 - The interval will be cancelled.
1342             var interval = setInterval(function(){
1343                 if (!content || !root.contains(content) || count >= 15) {
1344                     clearInterval(interval);
1345                     return true;
1346                 }
1347                 if (count == 5) {
1348                     content.removeClass('fp-content-hidden');
1349                 } else if (count > 5) {
1350                     var opacity = parseFloat(content.getStyle('opacity'));
1351                     content.setStyle('opacity', opacity + 0.1);
1352                 }
1353                 count++;
1354                 return false;
1355             }, 100);
1356             // Store the wait interval so that we can check it in the future.
1357             this.waitinterval = interval;
1358             // Set the content to the loading template.
1359             root.setContent(content);
1360         },
1361         viewbar_set_enabled: function(mode) {
1362             var viewbar = this.fpnode.one('.fp-viewbar')
1363             if (viewbar) {
1364                 if (mode) {
1365                     viewbar.addClass('enabled').removeClass('disabled');
1366                     this.fpnode.all('.fp-vb-icons,.fp-vb-tree,.fp-vb-details').setAttribute("aria-disabled", "false");
1367                     this.fpnode.all('.fp-vb-icons,.fp-vb-tree,.fp-vb-details').setAttribute("tabindex", "");
1368                 } else {
1369                     viewbar.removeClass('enabled').addClass('disabled');
1370                     this.fpnode.all('.fp-vb-icons,.fp-vb-tree,.fp-vb-details').setAttribute("aria-disabled", "true");
1371                     this.fpnode.all('.fp-vb-icons,.fp-vb-tree,.fp-vb-details').setAttribute("tabindex", "-1");
1372                 }
1373             }
1374             this.fpnode.all('.fp-vb-icons,.fp-vb-tree,.fp-vb-details').removeClass('checked');
1375             var modes = {1:'icons', 2:'tree', 3:'details'};
1376             this.fpnode.all('.fp-vb-'+modes[this.viewmode]).addClass('checked');
1377         },
1378         viewbar_clicked: function(e) {
1379             e.preventDefault();
1380             var viewbar = this.fpnode.one('.fp-viewbar')
1381             if (!viewbar || !viewbar.hasClass('disabled')) {
1382                 if (e.currentTarget.hasClass('fp-vb-tree')) {
1383                     this.viewmode = 2;
1384                 } else if (e.currentTarget.hasClass('fp-vb-details')) {
1385                     this.viewmode = 3;
1386                 } else {
1387                     this.viewmode = 1;
1388                 }
1389                 this.viewbar_set_enabled(true)
1390                 this.view_files();
1391                 this.set_preference('recentviewmode', this.viewmode);
1392             }
1393         },
1394         render: function() {
1395             var client_id = this.options.client_id;
1396             var fpid = "filepicker-"+ client_id;
1397             var labelid = 'fp-dialog-label_'+ client_id;
1398             var width = 873;
1399             var draggable = true;
1400             this.fpnode = Y.Node.create(M.core_filepicker.templates.generallayout).
1401                 set('id', 'filepicker-'+client_id).set('aria-labelledby', labelid);
1403             if (this.in_iframe()) {
1404                 width = Math.floor(window.innerWidth * 0.95);
1405                 draggable = false;
1406             }
1408             this.mainui = new M.core.dialogue({
1409                 extraClasses : ['filepicker'],
1410                 draggable    : draggable,
1411                 bodyContent  : this.fpnode,
1412                 headerContent: '<h3 id="'+ labelid +'">'+ M.util.get_string('filepicker', 'repository') +'</h3>',
1413                 centered     : true,
1414                 modal        : true,
1415                 visible      : false,
1416                 width        : width+'px',
1417                 responsiveWidth : 768,
1418                 height       : '558px',
1419                 zIndex       : this.options.zIndex
1420             });
1422             // create panel for selecting a file (initially hidden)
1423             this.selectnode = Y.Node.create(M.core_filepicker.templates.selectlayout).
1424                 set('id', 'filepicker-select-'+client_id).
1425                 set('aria-live', 'assertive').
1426                 set('role', 'dialog');
1428             var fplabel = 'fp-file_label_'+ client_id;
1429             this.selectui = new M.core.dialogue({
1430                 headerContent: '<h3 id="' + fplabel +'">'+M.util.get_string('select', 'repository')+'</h3>',
1431                 draggable    : true,
1432                 width        : '450px',
1433                 bodyContent  : this.selectnode,
1434                 centered     : true,
1435                 modal        : true,
1436                 visible      : false,
1437                 zIndex       : this.options.zIndex
1438             });
1439             Y.one('#'+this.selectnode.get('id')).setAttribute('aria-labelledby', fplabel);
1440             // event handler for lazy loading of thumbnails and next page
1441             this.fpnode.one('.fp-content').on(['scroll','resize'], this.content_scrolled, this);
1442             // save template for one path element and location of path bar
1443             if (this.fpnode.one('.fp-path-folder')) {
1444                 this.pathnode = this.fpnode.one('.fp-path-folder');
1445                 this.pathbar = this.pathnode.get('parentNode');
1446                 this.pathbar.removeChild(this.pathnode);
1447             }
1448             // assign callbacks for view mode switch buttons
1449             this.fpnode.one('.fp-vb-icons').on('click', this.viewbar_clicked, this);
1450             this.fpnode.one('.fp-vb-tree').on('click', this.viewbar_clicked, this);
1451             this.fpnode.one('.fp-vb-details').on('click', this.viewbar_clicked, this);
1453             // assign callbacks for toolbar links
1454             this.setup_toolbar();
1455             this.setup_select_file();
1456             this.hide_header();
1458             // processing repository listing
1459             // Resort the repositories by sortorder
1460             var sorted_repositories = [];
1461             var i;
1462             for (i in this.options.repositories) {
1463                 sorted_repositories[i] = this.options.repositories[i];
1464             }
1465             sorted_repositories.sort(function(a,b){return a.sortorder-b.sortorder});
1466             // extract one repository template and repeat it for all repositories available,
1467             // set name and icon and assign callbacks
1468             var reponode = this.fpnode.one('.fp-repo');
1469             if (reponode) {
1470                 var list = reponode.get('parentNode');
1471                 list.removeChild(reponode);
1472                 for (i in sorted_repositories) {
1473                     var repository = sorted_repositories[i];
1474                     var h = (parseInt(i) == 0) ? parseInt(i) : parseInt(i) - 1,
1475                         j = (parseInt(i) == Object.keys(sorted_repositories).length - 1) ? parseInt(i) : parseInt(i) + 1;
1476                     var previousrepository = sorted_repositories[h];
1477                     var nextrepository = sorted_repositories[j];
1478                     var node = reponode.cloneNode(true);
1479                     list.appendChild(node);
1480                     node.
1481                         set('id', 'fp-repo-'+client_id+'-'+repository.id).
1482                         on('click', function(e, repository_id) {
1483                             e.preventDefault();
1484                             this.set_preference('recentrepository', repository_id);
1485                             this.hide_header();
1486                             this.list({'repo_id':repository_id});
1487                         }, this /*handler running scope*/, repository.id/*second argument of handler*/);
1488                     node.on('key', function(e, previousrepositoryid, nextrepositoryid, clientid, repositoryid) {
1489                         this.changeHighlightedRepository(e, clientid, repositoryid, previousrepositoryid, nextrepositoryid);
1490                     }, 'down:38,40', this, previousrepository.id, nextrepository.id, client_id, repository.id);
1491                     node.on('key', function(e, repositoryid) {
1492                         e.preventDefault();
1493                         this.set_preference('recentrepository', repositoryid);
1494                         this.hide_header();
1495                         this.list({'repo_id': repositoryid});
1496                     }, 'enter', this, repository.id);
1497                     node.one('.fp-repo-name').setContent(Y.Escape.html(repository.name));
1498                     node.one('.fp-repo-icon').set('src', repository.icon);
1499                     if (i==0) {
1500                         node.addClass('first');
1501                     }
1502                     if (i==sorted_repositories.length-1) {
1503                         node.addClass('last');
1504                     }
1505                     if (i%2) {
1506                         node.addClass('even');
1507                     } else {
1508                         node.addClass('odd');
1509                     }
1510                 }
1511             }
1512             // display error if no repositories found
1513             if (sorted_repositories.length==0) {
1514                 this.display_error(M.util.get_string('norepositoriesavailable', 'repository'), 'norepositoriesavailable')
1515             }
1516             // display repository that was used last time
1517             this.mainui.show();
1518             this.show_recent_repository();
1519         },
1520         /**
1521          * Change the highlighted repository to a new one.
1522          *
1523          * @param  {object} event The key event
1524          * @param  {integer} clientid The client id to identify the repo class.
1525          * @param  {integer} oldrepositoryid The repository id that we are removing the highlight for
1526          * @param  {integer} previousrepositoryid The previous repository id.
1527          * @param  {integer} nextrepositoryid The next repository id.
1528          */
1529         changeHighlightedRepository: function(event, clientid, oldrepositoryid, previousrepositoryid, nextrepositoryid) {
1530             event.preventDefault();
1531             var newrepositoryid = (event.keyCode == '40') ? nextrepositoryid : previousrepositoryid;
1532             this.fpnode.one('#fp-repo-' + clientid + '-' + oldrepositoryid).setAttribute('tabindex', '-1');
1533             this.fpnode.one('#fp-repo-' + clientid + '-' + newrepositoryid)
1534                     .setAttribute('tabindex', '0')
1535                     .focus();
1536         },
1537         parse_repository_options: function(data, appendtolist) {
1538             if (appendtolist) {
1539                 if (data.list) {
1540                     if (!this.filelist) {
1541                         this.filelist = [];
1542                     }
1543                     for (var i in data.list) {
1544                         this.filelist[this.filelist.length] = data.list[i];
1545                     }
1546                 }
1547             } else {
1548                 this.filelist = data.list?data.list:null;
1549                 this.lazyloading = {};
1550             }
1551             this.filepath = data.path?data.path:null;
1552             this.objecttag = data.object?data.object:null;
1553             this.active_repo = {};
1554             this.active_repo.issearchresult = data.issearchresult ? true : false;
1555             this.active_repo.defaultreturntype = data.defaultreturntype?data.defaultreturntype:null;
1556             this.active_repo.dynload = data.dynload?data.dynload:false;
1557             this.active_repo.pages = Number(data.pages?data.pages:null);
1558             this.active_repo.page = Number(data.page?data.page:null);
1559             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))
1560             this.active_repo.id = data.repo_id?data.repo_id:null;
1561             this.active_repo.nosearch = (data.login || data.nosearch); // this is either login form or 'nosearch' attribute set
1562             this.active_repo.norefresh = (data.login || data.norefresh); // this is either login form or 'norefresh' attribute set
1563             this.active_repo.nologin = (data.login || data.nologin); // this is either login form or 'nologin' attribute is set
1564             this.active_repo.logouttext = data.logouttext?data.logouttext:null;
1565             this.active_repo.logouturl = (data.logouturl || '');
1566             this.active_repo.message = (data.message || '');
1567             this.active_repo.help = data.help?data.help:null;
1568             this.active_repo.manage = data.manage?data.manage:null;
1569             this.print_header();
1570         },
1571         print_login: function(data) {
1572             this.parse_repository_options(data);
1573             var client_id = this.options.client_id;
1574             var repository_id = data.repo_id;
1575             var l = this.logindata = data.login;
1576             var loginurl = '';
1577             var action = data['login_btn_action'] ? data['login_btn_action'] : 'login';
1578             var form_id = 'fp-form-'+client_id;
1580             var loginform_node = Y.Node.create(M.core_filepicker.templates.loginform);
1581             loginform_node.one('form').set('id', form_id);
1582             this.fpnode.one('.fp-content').setContent('').appendChild(loginform_node);
1583             var templates = {
1584                 'popup' : loginform_node.one('.fp-login-popup'),
1585                 'textarea' : loginform_node.one('.fp-login-textarea'),
1586                 'select' : loginform_node.one('.fp-login-select'),
1587                 'text' : loginform_node.one('.fp-login-text'),
1588                 'radio' : loginform_node.one('.fp-login-radiogroup'),
1589                 'checkbox' : loginform_node.one('.fp-login-checkbox'),
1590                 'input' : loginform_node.one('.fp-login-input')
1591             };
1592             var container;
1593             for (var i in templates) {
1594                 if (templates[i]) {
1595                     container = templates[i].get('parentNode');
1596                     container.removeChild(templates[i]);
1597                 }
1598             }
1600             for(var k in l) {
1601                 if (templates[l[k].type]) {
1602                     var node = templates[l[k].type].cloneNode(true);
1603                 } else {
1604                     node = templates['input'].cloneNode(true);
1605                 }
1606                 if (l[k].type == 'popup') {
1607                     // submit button
1608                     loginurl = l[k].url;
1609                     var popupbutton = node.one('button');
1610                     popupbutton.on('click', function(e){
1611                         M.core_filepicker.active_filepicker = this;
1612                         window.open(loginurl, 'repo_auth', 'location=0,status=0,width=500,height=300,scrollbars=yes');
1613                         e.preventDefault();
1614                     }, this);
1615                     loginform_node.one('form').on('keydown', function(e) {
1616                         if (e.keyCode == 13) {
1617                             popupbutton.simulate('click');
1618                             e.preventDefault();
1619                         }
1620                     }, this);
1621                     loginform_node.all('.fp-login-submit').remove();
1622                     action = 'popup';
1623                 } else if(l[k].type=='textarea') {
1624                     // textarea element
1625                     if (node.one('label')) {
1626                         node.one('label').set('for', l[k].id).setContent(l[k].label);
1627                     }
1628                     node.one('textarea').setAttrs({id:l[k].id, name:l[k].name});
1629                 } else if(l[k].type=='select') {
1630                     // select element
1631                     if (node.one('label')) {
1632                         node.one('label').set('for', l[k].id).setContent(l[k].label);
1633                     }
1634                     node.one('select').setAttrs({id:l[k].id, name:l[k].name}).setContent('');
1635                     for (i in l[k].options) {
1636                         node.one('select').appendChild(
1637                             Y.Node.create('<option/>').
1638                                 set('value', l[k].options[i].value).
1639                                 setContent(l[k].options[i].label));
1640                     }
1641                 } else if(l[k].type=='radio') {
1642                     // radio input element
1643                     node.all('label').setContent(l[k].label);
1644                     var list = l[k].value.split('|');
1645                     var labels = l[k].value_label.split('|');
1646                     var radionode = null;
1647                     for(var item in list) {
1648                         if (radionode == null) {
1649                             radionode = node.one('.fp-login-radio');
1650                             radionode.one('input').set('checked', 'checked');
1651                         } else {
1652                             var x = radionode.cloneNode(true);
1653                             radionode.insert(x, 'after');
1654                             radionode = x;
1655                             radionode.one('input').set('checked', '');
1656                         }
1657                         radionode.one('input').setAttrs({id:''+l[k].id+item, name:l[k].name,
1658                             type:l[k].type, value:list[item]});
1659                         radionode.all('label').setContent(labels[item]).set('for', ''+l[k].id+item)
1660                     }
1661                     if (radionode == null) {
1662                         node.one('.fp-login-radio').remove();
1663                     }
1664                 } else {
1665                     // input element
1666                     if (node.one('label')) { node.one('label').set('for', l[k].id).setContent(l[k].label) }
1667                     node.one('input').
1668                         set('type', l[k].type).
1669                         set('id', l[k].id).
1670                         set('name', l[k].name).
1671                         set('value', l[k].value?l[k].value:'')
1672                 }
1673                 container.appendChild(node);
1674             }
1675             // custom label text for submit button
1676             if (data['login_btn_label']) {
1677                 loginform_node.all('.fp-login-submit').setContent(data['login_btn_label'])
1678             }
1679             // register button action for login and search
1680             if (action == 'login' || action == 'search') {
1681                 loginform_node.one('.fp-login-submit').on('click', function(e){
1682                     e.preventDefault();
1683                     this.hide_header();
1684                     this.request({
1685                         'scope': this,
1686                         'action':(action == 'search') ? 'search' : 'signin',
1687                         'path': '',
1688                         'client_id': client_id,
1689                         'repository_id': repository_id,
1690                         'form': {id:form_id, upload:false, useDisabled:true},
1691                         'callback': this.display_response
1692                     }, true);
1693                 }, this);
1694             }
1695             // if 'Enter' is pressed in the form, simulate the button click
1696             if (loginform_node.one('.fp-login-submit')) {
1697                 loginform_node.one('form').on('keydown', function(e) {
1698                     if (e.keyCode == 13) {
1699                         loginform_node.one('.fp-login-submit').simulate('click')
1700                         e.preventDefault();
1701                     }
1702                 }, this);
1703             }
1704         },
1705         display_response: function(id, obj, args) {
1706             var scope = args.scope;
1707             // highlight the current repository in repositories list
1708             scope.fpnode.all('.fp-repo.active')
1709                     .removeClass('active')
1710                     .setAttribute('aria-selected', 'false')
1711                     .setAttribute('tabindex', '-1');
1712             scope.fpnode.all('.nav-link')
1713                     .removeClass('active')
1714                     .setAttribute('aria-selected', 'false')
1715                     .setAttribute('tabindex', '-1');
1716             var activenode = scope.fpnode.one('#fp-repo-' + scope.options.client_id + '-' + obj.repo_id);
1717             activenode.addClass('active')
1718                     .setAttribute('aria-selected', 'true')
1719                     .setAttribute('tabindex', '0');
1720             activenode.all('.nav-link').addClass('active');
1721             // add class repository_REPTYPE to the filepicker (for repository-specific styles)
1722             for (var i in scope.options.repositories) {
1723                 scope.fpnode.removeClass('repository_'+scope.options.repositories[i].type)
1724             }
1725             if (obj.repo_id && scope.options.repositories[obj.repo_id]) {
1726                 scope.fpnode.addClass('repository_'+scope.options.repositories[obj.repo_id].type)
1727             }
1728             Y.one('.file-picker .fp-repo-items').focus();
1730             // display response
1731             if (obj.login) {
1732                 scope.viewbar_set_enabled(false);
1733                 scope.print_login(obj);
1734             } else if (obj.upload) {
1735                 scope.viewbar_set_enabled(false);
1736                 scope.parse_repository_options(obj);
1737                 scope.create_upload_form(obj);
1738             } else if (obj.object) {
1739                 M.core_filepicker.active_filepicker = scope;
1740                 scope.viewbar_set_enabled(false);
1741                 scope.parse_repository_options(obj);
1742                 scope.create_object_container(obj.object);
1743             } else if (obj.list) {
1744                 scope.viewbar_set_enabled(true);
1745                 scope.parse_repository_options(obj);
1746                 scope.view_files();
1747             }
1748         },
1749         list: function(args) {
1750             if (!args) {
1751                 args = {};
1752             }
1753             if (!args.repo_id) {
1754                 args.repo_id = this.active_repo.id;
1755             }
1756             if (!args.path) {
1757                 args.path = '';
1758             }
1759             this.currentpath = args.path;
1760             this.request({
1761                 action: 'list',
1762                 client_id: this.options.client_id,
1763                 repository_id: args.repo_id,
1764                 path: args.path,
1765                 page: args.page,
1766                 scope: this,
1767                 callback: this.display_response
1768             }, true);
1769         },
1770         populate_licenses_select: function(node) {
1771             if (!node) {
1772                 return;
1773             }
1774             node.setContent('');
1775             var licenses = this.options.licenses;
1776             var recentlicense = this.get_preference('recentlicense');
1777             if (recentlicense) {
1778                 this.options.defaultlicense=recentlicense;
1779             }
1780             for (var i in licenses) {
1781                 var option = Y.Node.create('<option/>').
1782                     set('selected', (this.options.defaultlicense==licenses[i].shortname)).
1783                     set('value', licenses[i].shortname).
1784                     setContent(Y.Escape.html(licenses[i].fullname));
1785                 node.appendChild(option)
1786             }
1787         },
1788         set_selected_license: function(node, value) {
1789             var licenseset = false;
1790             node.all('option').each(function(el) {
1791                 if (el.get('value')==value || el.getContent()==value) {
1792                     el.set('selected', true);
1793                     licenseset = true;
1794                 }
1795             });
1796             if (!licenseset) {
1797                 // we did not find the value in the list
1798                 var recentlicense = this.get_preference('recentlicense');
1799                 node.all('option[selected]').set('selected', false);
1800                 node.all('option[value='+recentlicense+']').set('selected', true);
1801             }
1802         },
1803         create_object_container: function(data) {
1804             var content = this.fpnode.one('.fp-content');
1805             content.setContent('');
1806             //var str = '<object data="'+data.src+'" type="'+data.type+'" width="98%" height="98%" id="container_object" class="fp-object-container mdl-align"></object>';
1807             var container = Y.Node.create('<object/>').
1808                 setAttrs({data:data.src, type:data.type, id:'container_object'}).
1809                 addClass('fp-object-container');
1810             content.setContent('').appendChild(container);
1811         },
1812         create_upload_form: function(data) {
1813             var client_id = this.options.client_id;
1814             var id = data.upload.id+'_'+client_id;
1815             var content = this.fpnode.one('.fp-content');
1816             var template_name = 'uploadform_'+this.options.repositories[data.repo_id].type;
1817             var template = M.core_filepicker.templates[template_name] || M.core_filepicker.templates['uploadform'];
1818             content.setContent(template);
1820             content.all('.fp-file,.fp-saveas,.fp-setauthor,.fp-setlicense').each(function (node) {
1821                 node.all('label').set('for', node.one('input,select').generateID());
1822             });
1823             content.one('form').set('id', id);
1824             content.one('.fp-file input').set('name', 'repo_upload_file');
1825             if (data.upload.label && content.one('.fp-file label')) {
1826                 content.one('.fp-file label').setContent(data.upload.label);
1827             }
1828             content.one('.fp-saveas input').set('name', 'title');
1829             content.one('.fp-setauthor input').setAttrs({name:'author', value:this.options.author});
1830             content.one('.fp-setlicense select').set('name', 'license');
1831             this.populate_licenses_select(content.one('.fp-setlicense select'))
1832             // append hidden inputs to the upload form
1833             content.one('form').appendChild(Y.Node.create('<input/>').
1834                 setAttrs({type:'hidden',name:'itemid',value:this.options.itemid}));
1835             var types = this.options.accepted_types;
1836             for (var i in types) {
1837                 content.one('form').appendChild(Y.Node.create('<input/>').
1838                     setAttrs({type:'hidden',name:'accepted_types[]',value:types[i]}));
1839             }
1841             var scope = this;
1842             content.one('.fp-upload-btn').on('click', function(e) {
1843                 e.preventDefault();
1844                 var license = content.one('.fp-setlicense select');
1846                 this.set_preference('recentlicense', license.get('value'));
1847                 if (!content.one('.fp-file input').get('value')) {
1848                     scope.print_msg(M.util.get_string('nofilesattached', 'repository'), 'error');
1849                     return false;
1850                 }
1851                 this.hide_header();
1852                 scope.request({
1853                         scope: scope,
1854                         action:'upload',
1855                         client_id: client_id,
1856                         params: {'savepath':scope.options.savepath},
1857                         repository_id: scope.active_repo.id,
1858                         form: {id: id, upload:true},
1859                         onerror: function(id, o, args) {
1860                             scope.create_upload_form(data);
1861                         },
1862                         callback: function(id, o, args) {
1863                             if (o.event == 'fileexists') {
1864                                 scope.create_upload_form(data);
1865                                 scope.process_existing_file(o);
1866                                 return;
1867                             }
1868                             if (scope.options.editor_target&&scope.options.env=='editor') {
1869                                 scope.options.editor_target.value=o.url;
1870                                 scope.options.editor_target.dispatchEvent(new Event('change'), {'bubbles': true});
1871                             }
1872                             scope.hide();
1873                             o.client_id = client_id;
1874                             var formcallback_scope = args.scope.options.magicscope ? args.scope.options.magicscope : args.scope;
1875                             scope.options.formcallback.apply(formcallback_scope, [o]);
1876                         }
1877                 }, true);
1878             }, this);
1879         },
1880         /** setting handlers and labels for elements in toolbar. Called once during the initial render of filepicker */
1881         setup_toolbar: function() {
1882             var client_id = this.options.client_id;
1883             var toolbar = this.fpnode.one('.fp-toolbar');
1884             toolbar.one('.fp-tb-logout').one('a,button').on('click', function(e) {
1885                 e.preventDefault();
1886                 if (!this.active_repo.nologin) {
1887                     this.hide_header();
1888                     this.request({
1889                         action:'logout',
1890                         client_id: this.options.client_id,
1891                         repository_id: this.active_repo.id,
1892                         path:'',
1893                         callback: this.display_response
1894                     }, true);
1895                 }
1896                 if (this.active_repo.logouturl) {
1897                     window.open(this.active_repo.logouturl, 'repo_auth', 'location=0,status=0,width=500,height=300,scrollbars=yes');
1898                 }
1899             }, this);
1900             toolbar.one('.fp-tb-refresh').one('a,button').on('click', function(e) {
1901                 e.preventDefault();
1902                 if (!this.active_repo.norefresh) {
1903                     this.list({ path: this.currentpath });
1904                 }
1905             }, this);
1906             toolbar.one('.fp-tb-search form').
1907                 set('method', 'POST').
1908                 set('id', 'fp-tb-search-'+client_id).
1909                 on('submit', function(e) {
1910                     e.preventDefault();
1911                     if (!this.active_repo.nosearch) {
1912                         this.request({
1913                             scope: this,
1914                             action:'search',
1915                             client_id: this.options.client_id,
1916                             repository_id: this.active_repo.id,
1917                             form: {id: 'fp-tb-search-'+client_id, upload:false, useDisabled:true},
1918                             callback: this.display_response
1919                         }, true);
1920                     }
1921             }, this);
1923             // it does not matter what kind of element is .fp-tb-manage, we create a dummy <a>
1924             // element and use it to open url on click event
1925             var managelnk = Y.Node.create('<a/>').
1926                 setAttrs({id:'fp-tb-manage-'+client_id+'-link', target:'_blank'}).
1927                 setStyle('display', 'none');
1928             toolbar.append(managelnk);
1929             toolbar.one('.fp-tb-manage').one('a,button').
1930                 on('click', function(e) {
1931                     e.preventDefault();
1932                     managelnk.simulate('click')
1933                 });
1935             // same with .fp-tb-help
1936             var helplnk = Y.Node.create('<a/>').
1937                 setAttrs({id:'fp-tb-help-'+client_id+'-link', target:'_blank'}).
1938                 setStyle('display', 'none');
1939             toolbar.append(helplnk);
1940             toolbar.one('.fp-tb-help').one('a,button').
1941                 on('click', function(e) {
1942                     e.preventDefault();
1943                     helplnk.simulate('click')
1944                 });
1945         },
1946         hide_header: function() {
1947             if (this.fpnode.one('.fp-toolbar')) {
1948                 this.fpnode.one('.fp-toolbar').addClass('empty');
1949             }
1950             if (this.pathbar) {
1951                 this.pathbar.setContent('').addClass('empty');
1952             }
1953         },
1954         print_header: function() {
1955             var r = this.active_repo;
1956             var scope = this;
1957             var client_id = this.options.client_id;
1958             this.hide_header();
1959             this.print_path();
1960             var toolbar = this.fpnode.one('.fp-toolbar');
1961             if (!toolbar) { return; }
1963             var enable_tb_control = function(node, enabled) {
1964                 if (!node) { return; }
1965                 node.addClassIf('disabled', !enabled).addClassIf('enabled', enabled)
1966                 if (enabled) {
1967                     toolbar.removeClass('empty');
1968                 }
1969             }
1971             // TODO 'back' permanently disabled for now. Note, flickr_public uses 'Logout' for it!
1972             enable_tb_control(toolbar.one('.fp-tb-back'), false);
1974             // search form
1975             enable_tb_control(toolbar.one('.fp-tb-search'), !r.nosearch);
1976             if(!r.nosearch) {
1977                 var searchform = toolbar.one('.fp-tb-search form');
1978                 searchform.setContent('');
1979                 this.request({
1980                     scope: this,
1981                     action:'searchform',
1982                     repository_id: this.active_repo.id,
1983                     callback: function(id, obj, args) {
1984                         if (obj.repo_id == scope.active_repo.id && obj.form) {
1985                             // if we did not jump to another repository meanwhile
1986                             searchform.setContent(obj.form);
1987                             // Highlight search text when user click for search.
1988                             var searchnode = searchform.one('input[name="s"]');
1989                             if (searchnode) {
1990                                 searchnode.once('click', function(e) {
1991                                     e.preventDefault();
1992                                     this.select();
1993                                 });
1994                             }
1995                         }
1996                     }
1997                 }, false);
1998             }
2000             // refresh button
2001             // weather we use cache for this instance, this button will reload listing anyway
2002             enable_tb_control(toolbar.one('.fp-tb-refresh'), !r.norefresh);
2004             // login button
2005             enable_tb_control(toolbar.one('.fp-tb-logout'), !r.nologin);
2007             // manage url
2008             enable_tb_control(toolbar.one('.fp-tb-manage'), r.manage);
2009             Y.one('#fp-tb-manage-'+client_id+'-link').set('href', r.manage);
2011             // help url
2012             enable_tb_control(toolbar.one('.fp-tb-help'), r.help);
2013             Y.one('#fp-tb-help-'+client_id+'-link').set('href', r.help);
2015             // message
2016             enable_tb_control(toolbar.one('.fp-tb-message'), r.message);
2017             toolbar.one('.fp-tb-message').setContent(r.message);
2018         },
2019         print_path: function() {
2020             if (!this.pathbar) {
2021                 return;
2022             }
2023             this.pathbar.setContent('').addClass('empty');
2024             var p = this.filepath;
2025             if (p && p.length!=0 && this.viewmode != 2) {
2026                 for(var i = 0; i < p.length; i++) {
2027                     var el = this.pathnode.cloneNode(true);
2028                     this.pathbar.appendChild(el);
2029                     if (i == 0) {
2030                         el.addClass('first');
2031                     }
2032                     if (i == p.length-1) {
2033                         el.addClass('last');
2034                     }
2035                     if (i%2) {
2036                         el.addClass('even');
2037                     } else {
2038                         el.addClass('odd');
2039                     }
2040                     el.all('.fp-path-folder-name').setContent(Y.Escape.html(p[i].name));
2041                     el.on('click',
2042                             function(e, path) {
2043                                 e.preventDefault();
2044                                 this.list({'path':path});
2045                             },
2046                         this, p[i].path);
2047                 }
2048                 this.pathbar.removeClass('empty');
2049             }
2050         },
2051         hide: function() {
2052             this.selectui.hide();
2053             if (this.process_dlg) {
2054                 this.process_dlg.hide();
2055             }
2056             if (this.msg_dlg) {
2057                 this.msg_dlg.hide();
2058             }
2059             this.mainui.hide();
2060         },
2061         show: function() {
2062             if (this.fpnode) {
2063                 this.hide();
2064                 this.mainui.show();
2065                 this.show_recent_repository();
2066             } else {
2067                 this.launch();
2068             }
2069         },
2070         launch: function() {
2071             this.render();
2072         },
2073         show_recent_repository: function() {
2074             this.hide_header();
2075             this.viewbar_set_enabled(false);
2076             var repository_id = this.get_preference('recentrepository');
2077             this.viewmode = this.get_preference('recentviewmode');
2078             if (this.viewmode != 2 && this.viewmode != 3) {
2079                 this.viewmode = 1;
2080             }
2081             if (this.options.repositories[repository_id]) {
2082                 this.list({'repo_id':repository_id});
2083             }
2084         },
2085         get_preference: function (name) {
2086             if (this.options.userprefs[name]) {
2087                 return this.options.userprefs[name];
2088             } else {
2089                 return false;
2090             }
2091         },
2092         set_preference: function(name, value) {
2093             if (this.options.userprefs[name] != value) {
2094                 M.util.set_user_preference('filepicker_' + name, value);
2095                 this.options.userprefs[name] = value;
2096             }
2097         },
2098         in_iframe: function () {
2099             // If we're not the top window then we're in an iFrame
2100             return window.self !== window.top;
2101         }
2102     });
2103     var loading = Y.one('#filepicker-loading-'+options.client_id);
2104     if (loading) {
2105         loading.setStyle('display', 'none');
2106     }
2107     M.core_filepicker.instances[options.client_id] = new FilePickerHelper(options);
2108 };