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