ad9644fff9a22d79ab5f1408957b5e31dc3a0961
[moodle.git] / repository / filepicker.js
1 // YUI3 File Picker module for moodle
2 // Author: Dongsheng Cai <dongsheng@moodle.com>
4 /**
5  *
6  * File Picker UI
7  * =====
8  * this.fpnode, contains reference to filepicker Node, non-empty if and only if rendered
9  * this.api, stores the URL to make ajax request
10  * this.mainui, YUI Panel
11  * this.selectnode, contains reference to select-file Node
12  * this.selectui, YUI Panel for selecting particular file
13  * this.msg_dlg, YUI Panel for error or info message
14  * this.process_dlg, YUI Panel for processing existing filename
15  * this.treeview, YUI Treeview
16  * this.viewmode, store current view mode
17  * this.pathbar, reference to the Node with path bar
18  * this.pathnode, a Node element representing one folder in a path bar (not attached anywhere, just used for template)
19  * this.currentpath, the current path in the repository (or last requested path)
20  *
21  * Filepicker options:
22  * =====
23  * this.options.client_id, the instance id
24  * this.options.contextid
25  * this.options.itemid
26  * this.options.repositories, stores all repositories displayed in file picker
27  * this.options.formcallback
28  *
29  * Active repository options
30  * =====
31  * this.active_repo.id
32  * this.active_repo.defaultreturntype
33  * this.active_repo.nosearch
34  * this.active_repo.norefresh
35  * this.active_repo.nologin
36  * this.active_repo.help
37  * this.active_repo.manage
38  *
39  * Server responses
40  * =====
41  * this.filelist, cached filelist
42  * this.pages
43  * this.page
44  * this.filepath, current path (each element of the array is a part of the breadcrumb)
45  * this.logindata, cached login form
46  */
48 YUI.add('moodle-core_filepicker', function(Y) {
49     /** help function to extract width/height style as a number, not as a string */
50     Y.Node.prototype.getStylePx = function(attr) {
51         var style = this.getStyle(attr);
52         if (''+style == '0' || ''+style == '0px') {
53             return 0;
54         }
55         var matches = style.match(/^([\d\.]+)px$/)
56         if (matches && parseFloat(matches[1])) {
57             return parseFloat(matches[1]);
58         }
59         return null;
60     }
62     /** if condition is met, the class is added to the node, otherwise - removed */
63     Y.Node.prototype.addClassIf = function(className, condition) {
64         if (condition) {
65             this.addClass(className);
66         } else {
67             this.removeClass(className);
68         }
69         return this;
70     }
72     /** sets the width(height) of the node considering existing minWidth(minHeight) */
73     Y.Node.prototype.setStyleAdv = function(stylename, value) {
74         var stylenameCap = stylename.substr(0,1).toUpperCase() + stylename.substr(1, stylename.length-1).toLowerCase();
75         this.setStyle(stylename, '' + Math.max(value, this.getStylePx('min'+stylenameCap)) + 'px')
76         return this;
77     }
79     /** set image source to src, if there is preview, remember it in lazyloading.
80      *  If there is a preview and it was already loaded, use it. */
81     Y.Node.prototype.setImgSrc = function(src, realsrc, lazyloading) {
82         if (realsrc) {
83             if (M.core_filepicker.loadedpreviews[realsrc]) {
84                 this.set('src', realsrc).addClass('realpreview');
85                 return this;
86             } else {
87                 if (!this.get('id')) {
88                     this.generateID();
89                 }
90                 lazyloading[this.get('id')] = realsrc;
91             }
92         }
93         this.set('src', src);
94         return this;
95     }
97     /**
98      * Replaces the image source with preview. If the image is inside the treeview, we need
99      * also to update the html property of corresponding YAHOO.widget.HTMLNode
100      * @param array lazyloading array containing associations of imgnodeid->realsrc
101      */
102     Y.Node.prototype.setImgRealSrc = function(lazyloading) {
103         if (this.get('id') && lazyloading[this.get('id')]) {
104             var newsrc = lazyloading[this.get('id')];
105             M.core_filepicker.loadedpreviews[newsrc] = true;
106             this.set('src', newsrc).addClass('realpreview');
107             delete lazyloading[this.get('id')];
108             var treenode = this.ancestor('.fp-treeview')
109             if (treenode && treenode.get('parentNode').treeview) {
110                 treenode.get('parentNode').treeview.getRoot().refreshPreviews(this.get('id'), newsrc);
111             }
112         }
113         return this;
114     }
116     /** scan TreeView to find which node contains image with id=imgid and replace it's html
117      * with the new image source. */
118     Y.YUI2.widget.Node.prototype.refreshPreviews = function(imgid, newsrc, regex) {
119         if (!regex) {
120             regex = new RegExp("<img\\s[^>]*id=\""+imgid+"\"[^>]*?(/?)>", "im");
121         }
122         if (this.expanded || this.isLeaf) {
123             var html = this.getContentHtml();
124             if (html && this.setHtml && regex.test(html)) {
125                 var newhtml = this.html.replace(regex, "<img id=\""+imgid+"\" src=\""+newsrc+"\" class=\"realpreview\"$1>", html);
126                 this.setHtml(newhtml);
127                 return true;
128             }
129             if (!this.isLeaf && this.children) {
130                 for(var c in this.children) {
131                     if (this.children[c].refreshPreviews(imgid, newsrc, regex)) {
132                         return true;
133                     }
134                 }
135             }
136         }
137         return false;
138     }
140     /**
141      * Displays a list of files (used by filepicker, filemanager) inside the Node
142      *
143      * @param array options
144      *   viewmode : 1 - icons, 2 - tree, 3 - table
145      *   appendonly : whether fileslist need to be appended instead of replacing the existing content
146      *   filenode : Node element that contains template for displaying one file
147      *   callback : On click callback. The element of the fileslist array will be passed as argument
148      *   rightclickcallback : On right click callback (optional).
149      *   callbackcontext : context where callbacks are executed
150      *   sortable : whether content may be sortable (in table mode)
151      *   dynload : allow dynamic load for tree view
152      *   filepath : for pre-building of tree view - the path to the current directory in filepicker format
153      *   treeview_dynload : callback to function to dynamically load the folder in tree view
154      *   classnamecallback : callback to function that returns the class name for an element
155      * @param array fileslist array of files to show, each array element may have attributes:
156      *   title or fullname : file name
157      *   shorttitle (optional) : display file name
158      *   thumbnail : url of image
159      *   icon : url of icon image
160      *   thumbnail_width : width of thumbnail, default 90
161      *   thumbnail_height : height of thumbnail, default 90
162      *   thumbnail_alt : TODO not needed!
163      *   description or thumbnail_title : alt text
164      * @param array lazyloading : reference to the array with lazy loading images
165      */
166     Y.Node.prototype.fp_display_filelist = function(options, fileslist, lazyloading) {
167         var viewmodeclassnames = {1:'fp-iconview', 2:'fp-treeview', 3:'fp-tableview'};
168         var classname = viewmodeclassnames[options.viewmode];
169         var scope = this;
170         /** return whether file is a folder (different attributes in FileManager and FilePicker) */
171         var file_is_folder = function(node) {
172             if (node.children) {return true;}
173             if (node.type && node.type == 'folder') {return true;}
174             return false;
175         };
176         /** return the name of the file (different attributes in FileManager and FilePicker) */
177         var file_get_filename = function(node) {
178             return node.title ? node.title : node.fullname;
179         };
180         /** return display name of the file (different attributes in FileManager and FilePicker) */
181         var file_get_displayname = function(node) {
182             var displayname = node.shorttitle ? node.shorttitle : file_get_filename(node);
183             return Y.Escape.html(displayname);
184         };
185         /** return file description (different attributes in FileManager and FilePicker) */
186         var file_get_description = function(node) {
187             var description = '';
188             if (node.description) {
189                 description = node.description;
190             } else if (node.thumbnail_title) {
191                 description = node.thumbnail_title;
192             } else {
193                 description = file_get_filename(node);
194             }
195             return Y.Escape.html(description);
196         };
197         /** help funciton for tree view */
198         var build_tree = function(node, level) {
199             // prepare file name with icon
200             var el = Y.Node.create('<div/>');
201             el.appendChild(options.filenode.cloneNode(true));
203             el.one('.fp-filename').setContent(file_get_displayname(node));
204             // TODO add tooltip with node.title or node.thumbnail_title
205             var tmpnodedata = {className:options.classnamecallback(node)};
206             el.get('children').addClass(tmpnodedata.className);
207             if (node.icon) {
208                 el.one('.fp-icon').appendChild(Y.Node.create('<img/>'));
209                 el.one('.fp-icon img').setImgSrc(node.icon, node.realicon, lazyloading);
210             }
211             // create node
212             tmpnodedata.html = el.getContent();
213             var tmpNode = new Y.YUI2.widget.HTMLNode(tmpnodedata, level, false);
214             if (node.dynamicLoadComplete) {
215                 tmpNode.dynamicLoadComplete = true;
216             }
217             tmpNode.fileinfo = node;
218             tmpNode.isLeaf = !file_is_folder(node);
219             if (!tmpNode.isLeaf) {
220                 if(node.expanded) {
221                     tmpNode.expand();
222                 }
223                 tmpNode.path = node.path ? node.path : (node.filepath ? node.filepath : '');
224                 for(var c in node.children) {
225                     build_tree(node.children[c], tmpNode);
226                 }
227             }
228         };
229         /** initialize tree view */
230         var initialize_tree_view = function() {
231             var parentid = scope.one('.'+classname).get('id');
232             // TODO MDL-32736 use YUI3 gallery TreeView
233             scope.treeview = new Y.YUI2.widget.TreeView(parentid);
234             if (options.dynload) {
235                 scope.treeview.setDynamicLoad(Y.bind(options.treeview_dynload, options.callbackcontext), 1);
236             }
237             scope.treeview.singleNodeHighlight = true;
238             if (options.filepath && options.filepath.length) {
239                 // we just jumped from icon/details view, we need to show all parents
240                 // we extract as much information as possible from filepath and filelist
241                 // and send additional requests to retrieve siblings for parent folders
242                 var mytree = {};
243                 var mytreeel = null;
244                 for (var i in options.filepath) {
245                     if (mytreeel == null) {
246                         mytreeel = mytree;
247                     } else {
248                         mytreeel.children = [{}];
249                         mytreeel = mytreeel.children[0];
250                     }
251                     var pathelement = options.filepath[i];
252                     mytreeel.path = pathelement.path;
253                     mytreeel.title = pathelement.name;
254                     mytreeel.icon = pathelement.icon;
255                     mytreeel.dynamicLoadComplete = true; // we will call it manually
256                     mytreeel.expanded = true;
257                 }
258                 mytreeel.children = fileslist;
259                 build_tree(mytree, scope.treeview.getRoot());
260                 // manually call dynload for parent elements in the tree so we can load other siblings
261                 if (options.dynload) {
262                     var root = scope.treeview.getRoot();
263                     // 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']
555 });
557 M.core_filepicker = M.core_filepicker || {};
559 /**
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;
565 /**
566  * HTML Templates to use in FilePicker
567  */
568 M.core_filepicker.templates = M.core_filepicker.templates || {};
570 /**
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 || {};
575 /**
576 * Set selected file info
578 * @param object file info
579 */
580 M.core_filepicker.select_file = function(file) {
581     M.core_filepicker.active_filepicker.select_file(file);
584 /**
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();
593 };
595 M.core_filepicker.set_templates = function(Y, templates) {
596     for (var templid in templates) {
597         M.core_filepicker.templates[templid] = templates[templid];
598     }
601 /**
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             });
1428             // create panel for selecting a file (initially hidden)
1429             this.selectnode = Y.Node.create(M.core_filepicker.templates.selectlayout).
1430                 set('id', 'filepicker-select-'+client_id).
1431                 set('aria-live', 'assertive').
1432                 set('role', 'dialog');
1434             var fplabel = 'fp-file_label_'+ client_id;
1435             this.selectui = new M.core.dialogue({
1436                 headerContent: '<h3 id="' + fplabel +'">'+M.util.get_string('select', 'repository')+'</h3>',
1437                 draggable    : true,
1438                 width        : '450px',
1439                 bodyContent  : this.selectnode,
1440                 centered     : true,
1441                 modal        : true,
1442                 visible      : false,
1443                 zIndex       : this.options.zIndex
1444             });
1445             Y.one('#'+this.selectnode.get('id')).setAttribute('aria-labelledby', fplabel);
1446             // event handler for lazy loading of thumbnails and next page
1447             this.fpnode.one('.fp-content').on(['scroll','resize'], this.content_scrolled, this);
1448             // save template for one path element and location of path bar
1449             if (this.fpnode.one('.fp-path-folder')) {
1450                 this.pathnode = this.fpnode.one('.fp-path-folder');
1451                 this.pathbar = this.pathnode.get('parentNode');
1452                 this.pathbar.removeChild(this.pathnode);
1453             }
1454             // assign callbacks for view mode switch buttons
1455             this.fpnode.one('.fp-vb-icons').on('click', this.viewbar_clicked, this);
1456             this.fpnode.one('.fp-vb-tree').on('click', this.viewbar_clicked, this);
1457             this.fpnode.one('.fp-vb-details').on('click', this.viewbar_clicked, this);
1459             // assign callbacks for toolbar links
1460             this.setup_toolbar();
1461             this.setup_select_file();
1462             this.hide_header();
1464             // processing repository listing
1465             // Resort the repositories by sortorder
1466             var sorted_repositories = [];
1467             var i;
1468             for (i in this.options.repositories) {
1469                 sorted_repositories[i] = this.options.repositories[i];
1470             }
1471             sorted_repositories.sort(function(a,b){return a.sortorder-b.sortorder});
1472             // extract one repository template and repeat it for all repositories available,
1473             // set name and icon and assign callbacks
1474             var reponode = this.fpnode.one('.fp-repo');
1475             if (reponode) {
1476                 var list = reponode.get('parentNode');
1477                 list.removeChild(reponode);
1478                 for (i in sorted_repositories) {
1479                     var repository = sorted_repositories[i];
1480                     var h = (parseInt(i) == 0) ? parseInt(i) : parseInt(i) - 1,
1481                         j = (parseInt(i) == Object.keys(sorted_repositories).length - 1) ? parseInt(i) : parseInt(i) + 1;
1482                     var previousrepository = sorted_repositories[h];
1483                     var nextrepository = sorted_repositories[j];
1484                     var node = reponode.cloneNode(true);
1485                     list.appendChild(node);
1486                     node.
1487                         set('id', 'fp-repo-'+client_id+'-'+repository.id).
1488                         on('click', function(e, repository_id) {
1489                             e.preventDefault();
1490                             this.set_preference('recentrepository', repository_id);
1491                             this.hide_header();
1492                             this.list({'repo_id':repository_id});
1493                         }, this /*handler running scope*/, repository.id/*second argument of handler*/);
1494                     node.on('key', function(e, previousrepositoryid, nextrepositoryid, clientid, repositoryid) {
1495                         this.changeHighlightedRepository(e, clientid, repositoryid, previousrepositoryid, nextrepositoryid);
1496                     }, 'down:38,40', this, previousrepository.id, nextrepository.id, client_id, repository.id);
1497                     node.on('key', function(e, repositoryid) {
1498                         e.preventDefault();
1499                         this.set_preference('recentrepository', repositoryid);
1500                         this.hide_header();
1501                         this.list({'repo_id': repositoryid});
1502                     }, 'enter', this, repository.id);
1503                     node.one('.fp-repo-name').setContent(Y.Escape.html(repository.name));
1504                     node.one('.fp-repo-icon').set('src', repository.icon);
1505                     if (i==0) {
1506                         node.addClass('first');
1507                     }
1508                     if (i==sorted_repositories.length-1) {
1509                         node.addClass('last');
1510                     }
1511                     if (i%2) {
1512                         node.addClass('even');
1513                     } else {
1514                         node.addClass('odd');
1515                     }
1516                 }
1517             }
1518             // display error if no repositories found
1519             if (sorted_repositories.length==0) {
1520                 this.display_error(M.util.get_string('norepositoriesavailable', 'repository'), 'norepositoriesavailable')
1521             }
1522             // display repository that was used last time
1523             this.mainui.show();
1524             this.show_recent_repository();
1525         },
1526         /**
1527          * Change the highlighted repository to a new one.
1528          *
1529          * @param  {object} event The key event
1530          * @param  {integer} clientid The client id to identify the repo class.
1531          * @param  {integer} oldrepositoryid The repository id that we are removing the highlight for
1532          * @param  {integer} previousrepositoryid The previous repository id.
1533          * @param  {integer} nextrepositoryid The next repository id.
1534          */
1535         changeHighlightedRepository: function(event, clientid, oldrepositoryid, previousrepositoryid, nextrepositoryid) {
1536             event.preventDefault();
1537             var newrepositoryid = (event.keyCode == '40') ? nextrepositoryid : previousrepositoryid;
1538             this.fpnode.one('#fp-repo-' + clientid + '-' + oldrepositoryid).setAttribute('tabindex', '-1');
1539             this.fpnode.one('#fp-repo-' + clientid + '-' + newrepositoryid)
1540                     .setAttribute('tabindex', '0')
1541                     .focus();
1542         },
1543         parse_repository_options: function(data, appendtolist) {
1544             if (appendtolist) {
1545                 if (data.list) {
1546                     if (!this.filelist) {
1547                         this.filelist = [];
1548                     }
1549                     for (var i in data.list) {
1550                         this.filelist[this.filelist.length] = data.list[i];
1551                     }
1552                 }
1553             } else {
1554                 this.filelist = data.list?data.list:null;
1555                 this.lazyloading = {};
1556             }
1557             this.filepath = data.path?data.path:null;
1558             this.objecttag = data.object?data.object:null;
1559             this.active_repo = {};
1560             this.active_repo.issearchresult = data.issearchresult ? true : false;
1561             this.active_repo.defaultreturntype = data.defaultreturntype?data.defaultreturntype:null;
1562             this.active_repo.dynload = data.dynload?data.dynload:false;
1563             this.active_repo.pages = Number(data.pages?data.pages:null);
1564             this.active_repo.page = Number(data.page?data.page:null);
1565             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))
1566             this.active_repo.id = data.repo_id?data.repo_id:null;
1567             this.active_repo.nosearch = (data.login || data.nosearch); // this is either login form or 'nosearch' attribute set
1568             this.active_repo.norefresh = (data.login || data.norefresh); // this is either login form or 'norefresh' attribute set
1569             this.active_repo.nologin = (data.login || data.nologin); // this is either login form or 'nologin' attribute is set
1570             this.active_repo.logouttext = data.logouttext?data.logouttext:null;
1571             this.active_repo.logouturl = (data.logouturl || '');
1572             this.active_repo.message = (data.message || '');
1573             this.active_repo.help = data.help?data.help:null;
1574             this.active_repo.manage = data.manage?data.manage:null;
1575             this.print_header();
1576         },
1577         print_login: function(data) {
1578             this.parse_repository_options(data);
1579             var client_id = this.options.client_id;
1580             var repository_id = data.repo_id;
1581             var l = this.logindata = data.login;
1582             var loginurl = '';
1583             var action = data['login_btn_action'] ? data['login_btn_action'] : 'login';
1584             var form_id = 'fp-form-'+client_id;
1586             var loginform_node = Y.Node.create(M.core_filepicker.templates.loginform);
1587             loginform_node.one('form').set('id', form_id);
1588             this.fpnode.one('.fp-content').setContent('').appendChild(loginform_node);
1589             var templates = {
1590                 'popup' : loginform_node.one('.fp-login-popup'),
1591                 'textarea' : loginform_node.one('.fp-login-textarea'),
1592                 'select' : loginform_node.one('.fp-login-select'),
1593                 'text' : loginform_node.one('.fp-login-text'),
1594                 'radio' : loginform_node.one('.fp-login-radiogroup'),
1595                 'checkbox' : loginform_node.one('.fp-login-checkbox'),
1596                 'input' : loginform_node.one('.fp-login-input')
1597             };
1598             var container;
1599             for (var i in templates) {
1600                 if (templates[i]) {
1601                     container = templates[i].get('parentNode');
1602                     container.removeChild(templates[i]);
1603                 }
1604             }
1606             for(var k in l) {
1607                 if (templates[l[k].type]) {
1608                     var node = templates[l[k].type].cloneNode(true);
1609                 } else {
1610                     node = templates['input'].cloneNode(true);
1611                 }
1612                 if (l[k].type == 'popup') {
1613                     // submit button
1614                     loginurl = l[k].url;
1615                     var popupbutton = node.one('button');
1616                     popupbutton.on('click', function(e){
1617                         M.core_filepicker.active_filepicker = this;
1618                         window.open(loginurl, 'repo_auth', 'location=0,status=0,width=500,height=300,scrollbars=yes');
1619                         e.preventDefault();
1620                     }, this);
1621                     loginform_node.one('form').on('keydown', function(e) {
1622                         if (e.keyCode == 13) {
1623                             popupbutton.simulate('click');
1624                             e.preventDefault();
1625                         }
1626                     }, this);
1627                     loginform_node.all('.fp-login-submit').remove();
1628                     action = 'popup';
1629                 } else if(l[k].type=='textarea') {
1630                     // textarea element
1631                     if (node.one('label')) {
1632                         node.one('label').set('for', l[k].id).setContent(l[k].label);
1633                     }
1634                     node.one('textarea').setAttrs({id:l[k].id, name:l[k].name});
1635                 } else if(l[k].type=='select') {
1636                     // select element
1637                     if (node.one('label')) {
1638                         node.one('label').set('for', l[k].id).setContent(l[k].label);
1639                     }
1640                     node.one('select').setAttrs({id:l[k].id, name:l[k].name}).setContent('');
1641                     for (i in l[k].options) {
1642                         node.one('select').appendChild(
1643                             Y.Node.create('<option/>').
1644                                 set('value', l[k].options[i].value).
1645                                 setContent(l[k].options[i].label));
1646                     }
1647                 } else if(l[k].type=='radio') {
1648                     // radio input element
1649                     node.all('label').setContent(l[k].label);
1650                     var list = l[k].value.split('|');
1651                     var labels = l[k].value_label.split('|');
1652                     var radionode = null;
1653                     for(var item in list) {
1654                         if (radionode == null) {
1655                             radionode = node.one('.fp-login-radio');
1656                             radionode.one('input').set('checked', 'checked');
1657                         } else {
1658                             var x = radionode.cloneNode(true);
1659                             radionode.insert(x, 'after');
1660                             radionode = x;
1661                             radionode.one('input').set('checked', '');
1662                         }
1663                         radionode.one('input').setAttrs({id:''+l[k].id+item, name:l[k].name,
1664                             type:l[k].type, value:list[item]});
1665                         radionode.all('label').setContent(labels[item]).set('for', ''+l[k].id+item)
1666                     }
1667                     if (radionode == null) {
1668                         node.one('.fp-login-radio').remove();
1669                     }
1670                 } else {
1671                     // input element
1672                     if (node.one('label')) { node.one('label').set('for', l[k].id).setContent(l[k].label) }
1673                     node.one('input').
1674                         set('type', l[k].type).
1675                         set('id', l[k].id).
1676                         set('name', l[k].name).
1677                         set('value', l[k].value?l[k].value:'')
1678                 }
1679                 container.appendChild(node);
1680             }
1681             // custom label text for submit button
1682             if (data['login_btn_label']) {
1683                 loginform_node.all('.fp-login-submit').setContent(data['login_btn_label'])
1684             }
1685             // register button action for login and search
1686             if (action == 'login' || action == 'search') {
1687                 loginform_node.one('.fp-login-submit').on('click', function(e){
1688                     e.preventDefault();
1689                     this.hide_header();
1690                     this.request({
1691                         'scope': this,
1692                         'action':(action == 'search') ? 'search' : 'signin',
1693                         'path': '',
1694                         'client_id': client_id,
1695                         'repository_id': repository_id,
1696                         'form': {id:form_id, upload:false, useDisabled:true},
1697                         'callback': this.display_response
1698                     }, true);
1699                 }, this);
1700             }
1701             // if 'Enter' is pressed in the form, simulate the button click
1702             if (loginform_node.one('.fp-login-submit')) {
1703                 loginform_node.one('form').on('keydown', function(e) {
1704                     if (e.keyCode == 13) {
1705                         loginform_node.one('.fp-login-submit').simulate('click')
1706                         e.preventDefault();
1707                     }
1708                 }, this);
1709             }
1710         },
1711         display_response: function(id, obj, args) {
1712             var scope = args.scope;
1713             // highlight the current repository in repositories list
1714             scope.fpnode.all('.fp-repo.active')
1715                     .removeClass('active')
1716                     .setAttribute('aria-selected', 'false')
1717                     .setAttribute('tabindex', '-1');
1718             scope.fpnode.all('.nav-link')
1719                     .removeClass('active')
1720                     .setAttribute('aria-selected', 'false')
1721                     .setAttribute('tabindex', '-1');
1722             var activenode = scope.fpnode.one('#fp-repo-' + scope.options.client_id + '-' + obj.repo_id);
1723             activenode.addClass('active')
1724                     .setAttribute('aria-selected', 'true')
1725                     .setAttribute('tabindex', '0');
1726             activenode.all('.nav-link').addClass('active');
1727             // add class repository_REPTYPE to the filepicker (for repository-specific styles)
1728             for (var i in scope.options.repositories) {
1729                 scope.fpnode.removeClass('repository_'+scope.options.repositories[i].type)
1730             }
1731             if (obj.repo_id && scope.options.repositories[obj.repo_id]) {
1732                 scope.fpnode.addClass('repository_'+scope.options.repositories[obj.repo_id].type)
1733             }
1734             Y.one('.file-picker .fp-repo-items').focus();
1736             // display response
1737             if (obj.login) {
1738                 scope.viewbar_set_enabled(false);
1739                 scope.print_login(obj);
1740             } else if (obj.upload) {
1741                 scope.viewbar_set_enabled(false);
1742                 scope.parse_repository_options(obj);
1743                 scope.create_upload_form(obj);
1744             } else if (obj.object) {
1745                 M.core_filepicker.active_filepicker = scope;
1746                 scope.viewbar_set_enabled(false);
1747                 scope.parse_repository_options(obj);
1748                 scope.create_object_container(obj.object);
1749             } else if (obj.list) {
1750                 scope.viewbar_set_enabled(true);
1751                 scope.parse_repository_options(obj);
1752                 scope.view_files();
1753             }
1754         },
1755         list: function(args) {
1756             if (!args) {
1757                 args = {};
1758             }
1759             if (!args.repo_id) {
1760                 args.repo_id = this.active_repo.id;
1761             }
1762             if (!args.path) {
1763                 args.path = '';
1764             }
1765             this.currentpath = args.path;
1766             this.request({
1767                 action: 'list',
1768                 client_id: this.options.client_id,
1769                 repository_id: args.repo_id,
1770                 path: args.path,
1771                 page: args.page,
1772                 scope: this,
1773                 callback: this.display_response
1774             }, true);
1775         },
1776         populateLicensesSelect: function(licensenode, filenode) {
1777             if (!licensenode) {
1778                 return;
1779             }
1780             licensenode.setContent('');
1781             var selectedlicense = this.options.defaultlicense;
1782             if (filenode) {
1783                 // File has a license already, use it.
1784                 selectedlicense = filenode.license;
1785             } else if (this.options.rememberuserlicensepref) {
1786                 selectedlicense = this.get_preference('recentlicense');
1787             }
1788             var licenses = this.options.licenses;
1789             for (var i in licenses) {
1790                 // Include the file's current license, even if not enabled, to prevent displaying
1791                 // misleading information about which license the file currently has assigned to it.
1792                 if (licenses[i].enabled == true || (filenode !== undefined && licenses[i].shortname === filenode.license)) {
1793                     var option = Y.Node.create('<option/>').
1794                     set('selected', (licenses[i].shortname == selectedlicense)).
1795                     set('value', licenses[i].shortname).
1796                     setContent(Y.Escape.html(licenses[i].fullname));
1797                     licensenode.appendChild(option);
1798                 }
1799             }
1800         },
1801         create_object_container: function(data) {
1802             var content = this.fpnode.one('.fp-content');
1803             content.setContent('');
1804             //var str = '<object data="'+data.src+'" type="'+data.type+'" width="98%" height="98%" id="container_object" class="fp-object-container mdl-align"></object>';
1805             var container = Y.Node.create('<object/>').
1806                 setAttrs({data:data.src, type:data.type, id:'container_object'}).
1807                 addClass('fp-object-container');
1808             content.setContent('').appendChild(container);
1809         },
1810         create_upload_form: function(data) {
1811             var client_id = this.options.client_id;
1812             var id = data.upload.id+'_'+client_id;
1813             var content = this.fpnode.one('.fp-content');
1814             var template_name = 'uploadform_'+this.options.repositories[data.repo_id].type;
1815             var template = M.core_filepicker.templates[template_name] || M.core_filepicker.templates['uploadform'];
1816             content.setContent(template);
1818             content.all('.fp-file,.fp-saveas,.fp-setauthor,.fp-setlicense').each(function (node) {
1819                 node.all('label').set('for', node.one('input,select').generateID());
1820             });
1821             content.one('form').set('id', id);
1822             content.one('.fp-file input').set('name', 'repo_upload_file');
1823             if (data.upload.label && content.one('.fp-file label')) {
1824                 content.one('.fp-file label').setContent(data.upload.label);
1825             }
1826             content.one('.fp-saveas input').set('name', 'title');
1827             content.one('.fp-setauthor input').setAttrs({name:'author', value:this.options.author});
1828             content.one('.fp-setlicense select').set('name', 'license');
1829             this.populateLicensesSelect(content.one('.fp-setlicense select'));
1830             // append hidden inputs to the upload form
1831             content.one('form').appendChild(Y.Node.create('<input/>').
1832                 setAttrs({type:'hidden',name:'itemid',value:this.options.itemid}));
1833             var types = this.options.accepted_types;
1834             for (var i in types) {
1835                 content.one('form').appendChild(Y.Node.create('<input/>').
1836                     setAttrs({type:'hidden',name:'accepted_types[]',value:types[i]}));
1837             }
1839             var scope = this;
1840             content.one('.fp-upload-btn').on('click', function(e) {
1841                 e.preventDefault();
1842                 var license = content.one('.fp-setlicense select');
1844                 if (this.options.rememberuserlicensepref) {
1845                     this.set_preference('recentlicense', license.get('value'));
1846                 }
1847                 if (!content.one('.fp-file input').get('value')) {
1848                     scope.print_msg(M.util.get_string('nofilesattached', 'repository'), 'error');
1849                     return false;
1850                 }
1851                 this.hide_header();
1852                 scope.request({
1853                         scope: scope,
1854                         action:'upload',
1855                         client_id: client_id,
1856                         params: {'savepath':scope.options.savepath},
1857                         repository_id: scope.active_repo.id,
1858                         form: {id: id, upload:true},
1859                         onerror: function(id, o, args) {
1860                             scope.create_upload_form(data);
1861                         },
1862                         callback: function(id, o, args) {
1863                             if (o.event == 'fileexists') {
1864                                 scope.create_upload_form(data);
1865                                 scope.process_existing_file(o);
1866                                 return;
1867                             }
1868                             if (scope.options.editor_target&&scope.options.env=='editor') {
1869                                 scope.options.editor_target.value=o.url;
1870                                 scope.options.editor_target.dispatchEvent(new Event('change'), {'bubbles': true});
1871                             }
1872                             scope.hide();
1873                             o.client_id = client_id;
1874                             var formcallback_scope = args.scope.options.magicscope ? args.scope.options.magicscope : args.scope;
1875                             scope.options.formcallback.apply(formcallback_scope, [o]);
1876                         }
1877                 }, true);
1878             }, this);
1879         },
1880         /** setting handlers and labels for elements in toolbar. Called once during the initial render of filepicker */
1881         setup_toolbar: function() {
1882             var client_id = this.options.client_id;
1883             var toolbar = this.fpnode.one('.fp-toolbar');
1884             toolbar.one('.fp-tb-logout').one('a,button').on('click', function(e) {
1885                 e.preventDefault();
1886                 if (!this.active_repo.nologin) {
1887                     this.hide_header();
1888                     this.request({
1889                         action:'logout',
1890                         client_id: this.options.client_id,
1891                         repository_id: this.active_repo.id,
1892                         path:'',
1893                         callback: this.display_response
1894                     }, true);
1895                 }
1896                 if (this.active_repo.logouturl) {
1897                     window.open(this.active_repo.logouturl, 'repo_auth', 'location=0,status=0,width=500,height=300,scrollbars=yes');
1898                 }
1899             }, this);
1900             toolbar.one('.fp-tb-refresh').one('a,button').on('click', function(e) {
1901                 e.preventDefault();
1902                 if (!this.active_repo.norefresh) {
1903                     this.list({ path: this.currentpath });
1904                 }
1905             }, this);
1906             toolbar.one('.fp-tb-search form').
1907                 set('method', 'POST').
1908                 set('id', 'fp-tb-search-'+client_id).
1909                 on('submit', function(e) {
1910                     e.preventDefault();
1911                     if (!this.active_repo.nosearch) {
1912                         this.request({
1913                             scope: this,
1914                             action:'search',
1915                             client_id: this.options.client_id,
1916                             repository_id: this.active_repo.id,
1917                             form: {id: 'fp-tb-search-'+client_id, upload:false, useDisabled:true},
1918                             callback: this.display_response
1919                         }, true);
1920                     }
1921             }, this);
1923             // it does not matter what kind of element is .fp-tb-manage, we create a dummy <a>
1924             // element and use it to open url on click event
1925             var managelnk = Y.Node.create('<a/>').
1926                 setAttrs({id:'fp-tb-manage-'+client_id+'-link', target:'_blank'}).
1927                 setStyle('display', 'none');
1928             toolbar.append(managelnk);
1929             toolbar.one('.fp-tb-manage').one('a,button').
1930                 on('click', function(e) {
1931                     e.preventDefault();
1932                     managelnk.simulate('click')
1933                 });
1935             // same with .fp-tb-help
1936             var helplnk = Y.Node.create('<a/>').
1937                 setAttrs({id:'fp-tb-help-'+client_id+'-link', target:'_blank'}).
1938                 setStyle('display', 'none');
1939             toolbar.append(helplnk);
1940             toolbar.one('.fp-tb-help').one('a,button').
1941                 on('click', function(e) {
1942                     e.preventDefault();
1943                     helplnk.simulate('click')
1944                 });
1945         },
1946         hide_header: function() {
1947             if (this.fpnode.one('.fp-toolbar')) {
1948                 this.fpnode.one('.fp-toolbar').addClass('empty');
1949             }
1950             if (this.pathbar) {
1951                 this.pathbar.setContent('').addClass('empty');
1952             }
1953         },
1954         print_header: function() {
1955             var r = this.active_repo;
1956             var scope = this;
1957             var client_id = this.options.client_id;
1958             this.hide_header();
1959             this.print_path();
1960             var toolbar = this.fpnode.one('.fp-toolbar');
1961             if (!toolbar) { return; }
1963             var enable_tb_control = function(node, enabled) {
1964                 if (!node) { return; }
1965                 node.addClassIf('disabled', !enabled).addClassIf('enabled', enabled)
1966                 if (enabled) {
1967                     toolbar.removeClass('empty');
1968                 }
1969             }
1971             // TODO 'back' permanently disabled for now. Note, flickr_public uses 'Logout' for it!
1972             enable_tb_control(toolbar.one('.fp-tb-back'), false);
1974             // search form
1975             enable_tb_control(toolbar.one('.fp-tb-search'), !r.nosearch);
1976             if(!r.nosearch) {
1977                 var searchform = toolbar.one('.fp-tb-search form');
1978                 searchform.setContent('');
1979                 this.request({
1980                     scope: this,
1981                     action:'searchform',
1982                     repository_id: this.active_repo.id,
1983                     callback: function(id, obj, args) {
1984                         if (obj.repo_id == scope.active_repo.id && obj.form) {
1985                             // if we did not jump to another repository meanwhile
1986                             searchform.setContent(obj.form);
1987                             // Highlight search text when user click for search.
1988                             var searchnode = searchform.one('input[name="s"]');
1989                             if (searchnode) {
1990                                 searchnode.once('click', function(e) {
1991                                     e.preventDefault();
1992                                     this.select();
1993                                 });
1994                             }
1995                         }
1996                     }
1997                 }, false);
1998             }
2000             // refresh button
2001             // weather we use cache for this instance, this button will reload listing anyway
2002             enable_tb_control(toolbar.one('.fp-tb-refresh'), !r.norefresh);
2004             // login button
2005             enable_tb_control(toolbar.one('.fp-tb-logout'), !r.nologin);
2007             // manage url
2008             enable_tb_control(toolbar.one('.fp-tb-manage'), r.manage);
2009             Y.one('#fp-tb-manage-'+client_id+'-link').set('href', r.manage);
2011             // help url
2012             enable_tb_control(toolbar.one('.fp-tb-help'), r.help);
2013             Y.one('#fp-tb-help-'+client_id+'-link').set('href', r.help);
2015             // message
2016             enable_tb_control(toolbar.one('.fp-tb-message'), r.message);
2017             toolbar.one('.fp-tb-message').setContent(r.message);
2018         },
2019         print_path: function() {
2020             if (!this.pathbar) {
2021                 return;
2022             }
2023             this.pathbar.setContent('').addClass('empty');
2024             var p = this.filepath;
2025             if (p && p.length!=0 && this.viewmode != 2) {
2026                 for(var i = 0; i < p.length; i++) {
2027                     var el = this.pathnode.cloneNode(true);
2028                     this.pathbar.appendChild(el);
2029                     if (i == 0) {
2030                         el.addClass('first');
2031                     }
2032                     if (i == p.length-1) {
2033                         el.addClass('last');
2034                     }
2035                     if (i%2) {
2036                         el.addClass('even');
2037                     } else {
2038                         el.addClass('odd');
2039                     }
2040                     el.all('.fp-path-folder-name').setContent(Y.Escape.html(p[i].name));
2041                     el.on('click',
2042                             function(e, path) {
2043                                 e.preventDefault();
2044                                 this.list({'path':path});
2045                             },
2046                         this, p[i].path);
2047                 }
2048                 this.pathbar.removeClass('empty');
2049             }
2050         },
2051         hide: function() {
2052             this.selectui.hide();
2053             if (this.process_dlg) {
2054                 this.process_dlg.hide();
2055             }
2056             if (this.msg_dlg) {
2057                 this.msg_dlg.hide();
2058             }
2059             this.mainui.hide();
2060         },
2061         show: function() {
2062             if (this.fpnode) {
2063                 this.hide();
2064                 this.mainui.show();
2065                 this.show_recent_repository();
2066             } else {
2067                 this.launch();
2068             }
2069         },
2070         launch: function() {
2071             this.render();
2072         },
2073         show_recent_repository: function() {
2074             this.hide_header();
2075             this.viewbar_set_enabled(false);
2076             var repository_id = this.get_preference('recentrepository');
2077             this.viewmode = this.get_preference('recentviewmode');
2078             if (this.viewmode != 2 && this.viewmode != 3) {
2079                 this.viewmode = 1;
2080             }
2081             if (this.options.repositories[repository_id]) {
2082                 this.list({'repo_id':repository_id});
2083             }
2084         },
2085         get_preference: function (name) {
2086             if (this.options.userprefs[name]) {
2087                 return this.options.userprefs[name];
2088             } else {
2089                 return false;
2090             }
2091         },
2092         set_preference: function(name, value) {
2093             if (this.options.userprefs[name] != value) {
2094                 M.util.set_user_preference('filepicker_' + name, value);
2095                 this.options.userprefs[name] = value;
2096             }
2097         },
2098         in_iframe: function () {
2099             // If we're not the top window then we're in an iFrame
2100             return window.self !== window.top;
2101         }
2102     });
2103     var loading = Y.one('#filepicker-loading-'+options.client_id);
2104     if (loading) {
2105         loading.setStyle('display', 'none');
2106     }
2107     M.core_filepicker.instances[options.client_id] = new FilePickerHelper(options);
2108 };