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