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