1 // YUI3 File Picker module for moodle
2 // Author: Dongsheng Cai <dongsheng@moodle.com>
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)
22 * this.options.client_id, the instance id
23 * this.options.contextid
25 * this.options.repositories, stores all repositories displaied in file picker
26 * this.options.formcallback
28 * Active repository options
31 * this.active_repo.nosearch
32 * this.active_repo.norefresh
33 * this.active_repo.nologin
34 * this.active_repo.help
35 * this.active_repo.manage
39 * this.filelist, cached filelist
42 * this.filepath, current path
43 * this.logindata, cached login form
46 YUI.add('moodle-core_filepicker', function(Y) {
47 /** help function to extract width/height style as a number, not as a string */
48 Y.Node.prototype.getStylePx = function(attr) {
49 var style = this.getStyle(attr);
50 if (''+style == '0' || ''+style == '0px') {
53 var matches = style.match(/^([\d\.]+)px$/)
54 if (matches && parseFloat(matches[1])) {
55 return parseFloat(matches[1]);
60 /** if condition is met, the class is added to the node, otherwise - removed */
61 Y.Node.prototype.addClassIf = function(className, condition) {
63 this.addClass(className);
65 this.removeClass(className);
70 /** sets the width(height) of the node considering existing minWidth(minHeight) */
71 Y.Node.prototype.setStyleAdv = function(stylename, value) {
72 var stylenameCap = stylename.substr(0,1).toUpperCase() + stylename.substr(1, stylename.length-1).toLowerCase();
73 this.setStyle(stylename, '' + Math.max(value, this.getStylePx('min'+stylenameCap)) + 'px')
77 /** set image source to src, if there is preview, remember it in lazyloading.
78 * If there is a preview and it was already loaded, use it. */
79 Y.Node.prototype.setImgSrc = function(src, realsrc, lazyloading) {
81 if (M.core_filepicker.loadedpreviews[realsrc]) {
82 this.set('src', realsrc).addClass('realpreview');
85 if (!this.get('id')) {
88 lazyloading[this.get('id')] = realsrc;
96 * Replaces the image source with preview. If the image is inside the treeview, we need
97 * also to update the html property of corresponding YAHOO.widget.HTMLNode
98 * @param array lazyloading array containing associations of imgnodeid->realsrc
100 Y.Node.prototype.setImgRealSrc = function(lazyloading) {
101 if (this.get('id') && lazyloading[this.get('id')]) {
102 var newsrc = lazyloading[this.get('id')];
103 M.core_filepicker.loadedpreviews[newsrc] = true;
104 this.set('src', newsrc).addClass('realpreview');
105 delete lazyloading[this.get('id')];
106 var treenode = this.ancestor('.fp-treeview')
107 if (treenode && treenode.get('parentNode').treeview) {
108 treenode.get('parentNode').treeview.getRoot().refreshPreviews(this.get('id'), newsrc);
114 /** scan TreeView to find which node contains image with id=imgid and replace it's html
115 * with the new image source. */
116 YAHOO.widget.Node.prototype.refreshPreviews = function(imgid, newsrc, regex) {
118 regex = new RegExp("<img\\s[^>]*id=\""+imgid+"\"[^>]*?(/?)>", "im");
120 if (this.expanded || this.isLeaf) {
121 var html = this.getContentHtml();
122 if (html && this.setHtml && regex.test(html)) {
123 var newhtml = this.html.replace(regex, "<img id=\""+imgid+"\" src=\""+newsrc+"\" class=\"realpreview\"$1>", html);
124 this.setHtml(newhtml);
127 if (!this.isLeaf && this.children) {
128 for(var c in this.children) {
129 if (this.children[c].refreshPreviews(imgid, newsrc, regex)) {
139 * Displays a list of files (used by filepicker, filemanager) inside the Node
141 * @param array options
142 * viewmode : 1 - icons, 2 - tree, 3 - table
143 * appendonly : whether fileslist need to be appended instead of replacing the existing content
144 * filenode : Node element that contains template for displaying one file
145 * callback : On click callback. The element of the fileslist array will be passed as argument
146 * rightclickcallback : On right click callback (optional).
147 * callbackcontext : context where callbacks are executed
148 * sortable : whether content may be sortable (in table mode)
149 * dynload : allow dynamic load for tree view
150 * filepath : for pre-building of tree view - the path to the current directory in filepicker format
151 * treeview_dynload : callback to function to dynamically load the folder in tree view
152 * classnamecallback : callback to function that returns the class name for an element
153 * @param array fileslist array of files to show, each array element may have attributes:
154 * title or fullname : file name
155 * shorttitle (optional) : display file name
156 * thumbnail : url of image
157 * icon : url of icon image
158 * thumbnail_width : width of thumbnail, default 90
159 * thumbnail_height : height of thumbnail, default 90
160 * thumbnail_alt : TODO not needed!
161 * description or thumbnail_title : alt text
162 * @param array lazyloading : reference to the array with lazy loading images
164 Y.Node.prototype.fp_display_filelist = function(options, fileslist, lazyloading) {
165 var viewmodeclassnames = {1:'fp-iconview', 2:'fp-treeview', 3:'fp-tableview'};
166 var classname = viewmodeclassnames[options.viewmode];
168 /** return whether file is a folder (different attributes in FileManager and FilePicker) */
169 var file_is_folder = function(node) {
170 if (node.children) {return true;}
171 if (node.type && node.type == 'folder') {return true;}
174 /** return the name of the file (different attributes in FileManager and FilePicker) */
175 var file_get_filename = function(node) {
176 return node.title ? node.title : node.fullname;
178 /** return display name of the file (different attributes in FileManager and FilePicker) */
179 var file_get_displayname = function(node) {
180 return node.shorttitle ? node.shorttitle : file_get_filename(node);
182 /** return file description (different attributes in FileManager and FilePicker) */
183 var file_get_description = function(node) {
184 return node.description ? node.description : (node.thumbnail_title ? node.thumbnail_title : file_get_filename(node));
186 /** help funciton for tree view */
187 var build_tree = function(node, level) {
188 // prepare file name with icon
189 var el = Y.Node.create('<div/>');
190 el.appendChild(options.filenode.cloneNode(true));
192 el.one('.fp-filename').setContent(file_get_displayname(node));
193 // TODO add tooltip with node.title or node.thumbnail_title
194 var tmpnodedata = {className:options.classnamecallback(node)};
195 el.get('children').addClass(tmpnodedata.className);
197 el.one('.fp-icon').appendChild(Y.Node.create('<img/>'));
198 el.one('.fp-icon img').setImgSrc(node.icon, node.realicon, lazyloading);
201 tmpnodedata.html = el.getContent();
202 var tmpNode = new YAHOO.widget.HTMLNode(tmpnodedata, level, false);
203 if (node.dynamicLoadComplete) {
204 tmpNode.dynamicLoadComplete = true;
206 tmpNode.fileinfo = node;
207 tmpNode.isLeaf = !file_is_folder(node);
208 if (!tmpNode.isLeaf) {
212 tmpNode.path = node.path ? node.path : (node.filepath ? node.filepath : '');
213 for(var c in node.children) {
214 build_tree(node.children[c], tmpNode);
218 /** initialize tree view */
219 var initialize_tree_view = function() {
220 var parentid = scope.one('.'+classname).get('id');
221 // TODO MDL-32736 use YUI3 gallery TreeView
222 scope.treeview = new YAHOO.widget.TreeView(parentid);
223 if (options.dynload) {
224 scope.treeview.setDynamicLoad(Y.bind(options.treeview_dynload, options.callbackcontext), 1);
226 scope.treeview.singleNodeHighlight = true;
227 if (options.filepath && options.filepath.length) {
228 // we just jumped from icon/details view, we need to show all parents
229 // we extract as much information as possible from filepath and filelist
230 // and send additional requests to retrieve siblings for parent folders
233 for (var i in options.filepath) {
234 if (mytreeel == null) {
237 mytreeel.children = [{}];
238 mytreeel = mytreeel.children[0];
240 var pathelement = options.filepath[i];
241 mytreeel.path = pathelement.path;
242 mytreeel.title = pathelement.name;
243 mytreeel.icon = pathelement.icon;
244 mytreeel.dynamicLoadComplete = true; // we will call it manually
245 mytreeel.expanded = true;
247 mytreeel.children = fileslist;
248 build_tree(mytree, scope.treeview.getRoot());
249 // manually call dynload for parent elements in the tree so we can load other siblings
250 if (options.dynload) {
251 var root = scope.treeview.getRoot();
252 while (root && root.children && root.children.length) {
253 root = root.children[0];
254 if (root.path == mytreeel.path) {
255 root.origpath = options.filepath;
256 root.origlist = fileslist;
257 } else if (!root.isLeaf && root.expanded) {
258 Y.bind(options.treeview_dynload, options.callbackcontext)(root, null);
263 // there is no path information, just display all elements as a list, without hierarchy
264 for(k in fileslist) {
265 build_tree(fileslist[k], scope.treeview.getRoot());
268 scope.treeview.subscribe('clickEvent', function(e){
269 e.node.highlight(false);
270 var callback = options.callback;
271 if (options.rightclickcallback && e.event.target &&
272 Y.Node(e.event.target).ancestor('.fp-treeview .fp-contextmenu', true)) {
273 callback = options.rightclickcallback;
275 Y.bind(callback, options.callbackcontext)(e, e.node.fileinfo);
276 YAHOO.util.Event.stopEvent(e.event)
278 // TODO MDL-32736 support right click
279 /*if (options.rightclickcallback) {
280 scope.treeview.subscribe('dblClickEvent', function(e){
281 e.node.highlight(false);
282 Y.bind(options.rightclickcallback, options.callbackcontext)(e, e.node.fileinfo);
285 scope.treeview.draw();
287 /** formatting function for table view */
288 var formatValue = function (o){
289 if (o.data[''+o.column.key+'_f_s']) {return o.data[''+o.column.key+'_f_s'];}
290 else if (o.data[''+o.column.key+'_f']) {return o.data[''+o.column.key+'_f'];}
291 else if (o.value) {return o.value;}
294 /** formatting function for table view */
295 var formatTitle = function(o) {
296 var el = Y.Node.create('<div/>');
297 el.appendChild(options.filenode.cloneNode(true)); // TODO not node but string!
298 el.get('children').addClass(o.data['classname']);
299 el.one('.fp-filename').setContent(o.value);
300 if (o.data['icon']) {
301 el.one('.fp-icon').appendChild(Y.Node.create('<img/>'));
302 el.one('.fp-icon img').setImgSrc(o.data['icon'], o.data['realicon'], lazyloading);
304 if (options.rightclickcallback) {
305 el.get('children').addClass('fp-hascontextmenu');
307 // TODO add tooltip with o.data['title'] (o.value) or o.data['thumbnail_title']
308 return el.getContent();
310 /** sorting function for table view */
311 var sortFoldersFirst = function(a, b, desc) {
312 if (a.get('isfolder') && !b.get('isfolder')) {
315 if (!a.get('isfolder') && b.get('isfolder')) {
318 var aa = a.get(this.key), bb = b.get(this.key), dir = desc ? -1 : 1;
319 return (aa > bb) ? dir : ((aa < bb) ? -dir : 0);
321 /** initialize table view */
322 var initialize_table_view = function() {
323 var parentid = scope.one('.'+classname).get('id');
325 {key: "displayname", label: M.str.moodle.name, allowHTML: true, formatter: formatTitle,
326 sortable: true, sortFn: sortFoldersFirst},
327 {key: "datemodified", label: M.str.moodle.lastmodified, allowHTML: true, formatter: formatValue,
328 sortable: true, sortFn: sortFoldersFirst},
329 {key: "size", label: M.str.repository.size, allowHTML: true, formatter: formatValue,
330 sortable: true, sortFn: sortFoldersFirst},
331 {key: "mimetype", label: M.str.repository.type, allowHTML: true,
332 sortable: true, sortFn: sortFoldersFirst}
334 scope.tableview = new Y.DataTable({columns: cols});
335 scope.tableview.render('#'+parentid);
336 scope.tableview.delegate('click', function (e, tableview) {
337 var record = tableview.getRecord(e.currentTarget.get('id'));
339 var callback = options.callback;
340 if (options.rightclickcallback && e.target.ancestor('.fp-tableview .fp-contextmenu', true)) {
341 callback = options.rightclickcallback;
343 Y.bind(callback, this)(e, record.getAttrs());
345 }, 'tr', options.callbackcontext, scope.tableview);
346 if (options.rightclickcallback) {
347 scope.tableview.delegate('contextmenu', function (e, tableview) {
348 var record = tableview.getRecord(e.currentTarget.get('id'));
349 if (record) { Y.bind(options.rightclickcallback, this)(e, record.getAttrs()); }
350 }, 'tr', options.callbackcontext, scope.tableview);
353 /** append items in table view mode */
354 var append_files_table = function() {
355 for (var k in fileslist) {
356 // to speed up sorting and formatting
357 fileslist[k].displayname = file_get_displayname(fileslist[k]);
358 fileslist[k].isfolder = file_is_folder(fileslist[k]);
359 fileslist[k].classname = options.classnamecallback(fileslist[k]);
361 scope.tableview.addRows(fileslist);
362 scope.tableview.sortable = options.sortable ? true : false;
364 /** append items in tree view mode */
365 var append_files_tree = function() {
366 if (options.appendonly) {
367 var parentnode = scope.treeview.getRoot();
368 if (scope.treeview.getHighlightedNode()) {
369 parentnode = scope.treeview.getHighlightedNode();
370 if (parentnode.isLeaf) {parentnode = parentnode.parent;}
372 for (var k in fileslist) {
373 build_tree(fileslist[k], parentnode);
375 scope.treeview.draw();
377 // otherwise files were already added in initialize_tree_view()
380 /** append items in icon view mode */
381 var append_files_icons = function() {
382 parent = scope.one('.'+classname);
383 for (var k in fileslist) {
384 var node = fileslist[k];
385 var element = options.filenode.cloneNode(true);
386 parent.appendChild(element);
387 element.addClass(options.classnamecallback(node));
388 var filenamediv = element.one('.fp-filename');
389 filenamediv.setContent(file_get_displayname(node));
390 var imgdiv = element.one('.fp-thumbnail'), width, height, src;
391 if (node.thumbnail) {
392 width = node.thumbnail_width ? node.thumbnail_width : 90;
393 height = node.thumbnail_height ? node.thumbnail_height : 90;
394 src = node.thumbnail;
400 filenamediv.setStyleAdv('width', width);
401 imgdiv.setStyleAdv('width', width).setStyleAdv('height', height);
402 var img = Y.Node.create('<img/>').setAttrs({
403 title: file_get_description(node),
404 alt: node.thumbnail_alt ? node.thumbnail_alt : file_get_filename(node)}).
405 setStyle('maxWidth', ''+width+'px').
406 setStyle('maxHeight', ''+height+'px');
407 img.setImgSrc(src, node.realthumbnail, lazyloading);
408 imgdiv.appendChild(img);
409 element.on('click', function(e, nd) {
410 if (options.rightclickcallback && e.target.ancestor('.fp-iconview .fp-contextmenu', true)) {
411 Y.bind(options.rightclickcallback, this)(e, nd);
413 Y.bind(options.callback, this)(e, nd);
415 }, options.callbackcontext, node);
416 if (options.rightclickcallback) {
417 element.on('contextmenu', options.rightclickcallback, options.callbackcontext, node);
422 // initialize files view
423 if (!options.appendonly) {
424 var parent = Y.Node.create('<div/>').addClass(classname);
425 this.setContent('').appendChild(parent);
427 if (options.viewmode == 2) {
428 initialize_tree_view();
429 } else if (options.viewmode == 3) {
430 initialize_table_view();
432 // nothing to initialize for icon view
436 // append files to the list
437 if (options.viewmode == 2) {
439 } else if (options.viewmode == 3) {
440 append_files_table();
442 append_files_icons();
448 * creates a node and adds it to the div with id #filesskin. This is needed for CSS to be able
449 * to overwrite YUI skin styles (instead of using !important that does not work in IE)
451 Y.Node.createWithFilesSkin = function(node) {
452 if (!Y.one('#filesskin')) {
453 Y.one(document.body).appendChild(Y.Node.create('<div/>').set('id', 'filesskin'));
455 return Y.one('#filesskin').appendChild(Y.Node.create(node));
458 requires:['base', 'node', 'yui2-treeview', 'panel', 'cookie', 'datatable', 'datatable-sort']
461 M.core_filepicker = M.core_filepicker || {};
464 * instances of file pickers used on page
466 M.core_filepicker.instances = M.core_filepicker.instances || {};
467 M.core_filepicker.active_filepicker = null;
470 * HTML Templates to use in FilePicker
472 M.core_filepicker.templates = M.core_filepicker.templates || {};
475 * Array of image sources for real previews (realicon or realthumbnail) that are already loaded
477 M.core_filepicker.loadedpreviews = M.core_filepicker.loadedpreviews || {};
480 * Set selected file info
482 * @parma object file info
484 M.core_filepicker.select_file = function(file) {
485 M.core_filepicker.active_filepicker.select_file(file);
489 * Init and show file picker
491 M.core_filepicker.show = function(Y, options) {
492 if (!M.core_filepicker.instances[options.client_id]) {
493 M.core_filepicker.init(Y, options);
495 M.core_filepicker.instances[options.client_id].show();
498 M.core_filepicker.set_templates = function(Y, templates) {
499 for (var templid in templates) {
500 M.core_filepicker.templates[templid] = templates[templid];
505 * Add new file picker to current instances
507 M.core_filepicker.init = function(Y, options) {
508 var FilePickerHelper = function(options) {
509 FilePickerHelper.superclass.constructor.apply(this, arguments);
512 FilePickerHelper.NAME = "FilePickerHelper";
513 FilePickerHelper.ATTRS = {
518 Y.extend(FilePickerHelper, Y.Base, {
519 api: M.cfg.wwwroot+'/repository/repository_ajax.php',
520 cached_responses: {},
521 waitinterval : null, // When the loading template is being displayed and its animation is running this will be an interval instance.
522 initializer: function(options) {
523 this.options = options;
524 if (!this.options.savepath) {
525 this.options.savepath = '/';
529 destructor: function() {
532 request: function(args, redraw) {
533 var api = (args.api ? args.api : this.api) + '?action='+args.action;
535 var scope = args['scope'] ? args['scope'] : this;
536 params['repo_id']=args.repository_id;
537 params['p'] = args.path?args.path:'';
538 params['page'] = args.page?args.page:'';
539 params['env']=this.options.env;
540 // the form element only accept certain file types
541 params['accepted_types']=this.options.accepted_types;
542 params['sesskey'] = M.cfg.sesskey;
543 params['client_id'] = args.client_id;
544 params['itemid'] = this.options.itemid?this.options.itemid:0;
545 params['maxbytes'] = this.options.maxbytes?this.options.maxbytes:-1;
546 if (this.options.context && this.options.context.id) {
547 params['ctx_id'] = this.options.context.id;
549 if (args['params']) {
550 for (i in args['params']) {
551 params[i] = args['params'][i];
554 if (args.action == 'upload') {
556 for(var k in params) {
557 var value = params[k];
558 if(value instanceof Array) {
559 for(var i in value) {
560 list.push(k+'[]='+value[i]);
563 list.push(k+'='+value);
566 params = list.join('&');
568 params = build_querystring(params);
573 complete: function(id,o,p) {
581 data = Y.JSON.parse(o.responseText);
583 scope.print_msg(M.str.repository.invalidjson, 'error');
584 scope.display_error(M.str.repository.invalidjson+'<pre>'+stripHTML(o.responseText)+'</pre>', 'invalidjson')
588 if (data && data.error) {
589 scope.print_msg(data.error, 'error');
591 args.onerror(id,data,p);
593 this.fpnode.one('.fp-content').setContent('');
598 scope.print_msg(data.msg, 'info');
600 // cache result if applicable
601 if (args.action != 'upload' && data.allowcaching) {
602 scope.cached_responses[params] = data;
605 args.callback(id,data,p);
613 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
619 cfg.form = args.form;
621 // check if result of the same request has been already cached. If not, request it
622 // (never applicable in case of form submission and/or upload action):
623 if (!args.form && args.action != 'upload' && scope.cached_responses[params]) {
624 args.callback(null, scope.cached_responses[params], {scope: scope})
632 /** displays the dialog and processes rename/overwrite if there is a file with the same name in the same filearea*/
633 process_existing_file: function(data) {
635 var handleOverwrite = function(e) {
638 var data = this.process_dlg.dialogdata;
640 params['existingfilename'] = data.existingfile.filename;
641 params['existingfilepath'] = data.existingfile.filepath;
642 params['newfilename'] = data.newfile.filename;
643 params['newfilepath'] = data.newfile.filepath;
648 'action':'overwrite',
650 'client_id': this.options.client_id,
651 'repository_id': this.active_repo.id,
652 'callback': function(id, o, args) {
654 // editor needs to update url
655 // filemanager do nothing
656 if (scope.options.editor_target && scope.options.env == 'editor') {
657 scope.options.editor_target.value = data.existingfile.url;
658 scope.options.editor_target.onchange();
659 } else if (scope.options.env === 'filepicker') {
660 var fileinfo = {'client_id':scope.options.client_id,
661 'url':data.existingfile.url,
662 'file':data.existingfile.filename};
663 var formcallback_scope = scope.options.magicscope ? scope.options.magicscope : scope;
664 scope.options.formcallback.apply(formcallback_scope, [fileinfo]);
669 var handleRename = function(e) {
670 // inserts file with the new name
673 var data = this.process_dlg.dialogdata;
674 if (scope.options.editor_target && scope.options.env == 'editor') {
675 scope.options.editor_target.value = data.newfile.url;
676 scope.options.editor_target.onchange();
679 var formcallback_scope = scope.options.magicscope ? scope.options.magicscope : scope;
680 var fileinfo = {'client_id':scope.options.client_id,
681 'url':data.newfile.url,
682 'file':data.newfile.filename};
683 scope.options.formcallback.apply(formcallback_scope, [fileinfo]);
685 var handleCancel = function(e) {
689 params['newfilename'] = this.process_dlg.dialogdata.newfile.filename;
690 params['newfilepath'] = this.process_dlg.dialogdata.newfile.filepath;
694 'action':'deletetmpfile',
696 'client_id': this.options.client_id,
697 'repository_id': this.active_repo.id,
698 'callback': function(id, o, args) {
699 // let it be in background, from user point of view nothing is happenning
702 this.process_dlg.hide();
703 this.selectui.hide();
705 if (!this.process_dlg) {
706 this.process_dlg_node = Y.Node.createWithFilesSkin(M.core_filepicker.templates.processexistingfile);
707 var node = this.process_dlg_node;
709 this.process_dlg = new Y.Panel({
711 headerContent: M.str.repository.fileexistsdialogheader,
719 this.process_dlg.plug(Y.Plugin.Drag,{handles:['#'+node.get('id')+' .yui3-widget-hd']});
720 node.one('.fp-dlg-butoverwrite').on('click', handleOverwrite, this);
721 node.one('.fp-dlg-butrename').on('click', handleRename, this);
722 node.one('.fp-dlg-butcancel').on('click', handleCancel, this);
723 if (this.options.env == 'editor') {
724 node.one('.fp-dlg-text').setContent(M.str.repository.fileexistsdialog_editor);
726 node.one('.fp-dlg-text').setContent(M.str.repository.fileexistsdialog_filemanager);
729 this.selectnode.removeClass('loading');
730 this.process_dlg.dialogdata = data;
731 this.process_dlg_node.one('.fp-dlg-butrename').setContent(M.util.get_string('renameto', 'repository', data.newfile.filename));
732 this.process_dlg.show();
734 /** displays error instead of filepicker contents */
735 display_error: function(errortext, errorcode) {
736 this.fpnode.one('.fp-content').setContent(M.core_filepicker.templates.error);
737 this.fpnode.one('.fp-content .fp-error').
739 setContent(errortext);
741 /** displays message in a popup */
742 print_msg: function(msg, type) {
743 var header = M.str.moodle.error;
744 if (type != 'error') {
745 type = 'info'; // one of only two types excepted
746 header = M.str.moodle.info;
749 this.msg_dlg_node = Y.Node.createWithFilesSkin(M.core_filepicker.templates.message);
750 this.msg_dlg_node.generateID();
752 this.msg_dlg = new Y.Panel({
753 srcNode : this.msg_dlg_node,
760 this.msg_dlg.plug(Y.Plugin.Drag,{handles:['#'+this.msg_dlg_node.get('id')+' .yui3-widget-hd']});
761 this.msg_dlg_node.one('.fp-msg-butok').on('click', function(e) {
767 this.msg_dlg.set('headerContent', header);
768 this.msg_dlg_node.removeClass('fp-msg-info').removeClass('fp-msg-error').addClass('fp-msg-'+type)
769 this.msg_dlg_node.one('.fp-msg-text').setContent(msg);
772 view_files: function(appenditems) {
773 this.viewbar_set_enabled(true);
775 /*if ((appenditems == null) && (!this.filelist || !this.filelist.length) && !this.active_repo.hasmorepages) {
776 // TODO do it via classes and adjust for each view mode!
777 // If there are no items and no next page, just display status message and quit
778 this.display_error(M.str.repository.nofilesavailable, 'nofilesavailable');
781 if (this.viewmode == 2) {
782 this.view_as_list(appenditems);
783 } else if (this.viewmode == 3) {
784 this.view_as_table(appenditems);
786 this.view_as_icons(appenditems);
788 // display/hide the link for requesting next page
789 if (!appenditems && this.active_repo.hasmorepages) {
790 if (!this.fpnode.one('.fp-content .fp-nextpage')) {
791 this.fpnode.one('.fp-content').append(M.core_filepicker.templates.nextpage);
793 this.fpnode.one('.fp-content .fp-nextpage').one('a,button').on('click', function(e) {
795 this.fpnode.one('.fp-content .fp-nextpage').addClass('loading');
796 this.request_next_page();
799 if (!this.active_repo.hasmorepages && this.fpnode.one('.fp-content .fp-nextpage')) {
800 this.fpnode.one('.fp-content .fp-nextpage').remove();
802 if (this.fpnode.one('.fp-content .fp-nextpage')) {
803 this.fpnode.one('.fp-content .fp-nextpage').removeClass('loading');
805 this.content_scrolled();
807 content_scrolled: function(e) {
808 setTimeout(Y.bind(function() {
809 if (this.processingimages) {
812 this.processingimages = true;
814 fpcontent = this.fpnode.one('.fp-content'),
815 fpcontenty = fpcontent.getY(),
816 fpcontentheight = fpcontent.getStylePx('height'),
817 nextpage = fpcontent.one('.fp-nextpage'),
818 is_node_visible = function(node) {
819 var offset = node.getY()-fpcontenty;
820 if (offset <= fpcontentheight && (offset >=0 || offset+node.getStylePx('height')>=0)) {
825 // automatically load next page when 'more' link becomes visible
826 if (nextpage && !nextpage.hasClass('loading') && is_node_visible(nextpage)) {
827 nextpage.one('a,button').simulate('click');
829 // replace src for visible images that need to be lazy-loaded
830 if (scope.lazyloading) {
831 fpcontent.all('img').each( function(node) {
832 if (node.get('id') && scope.lazyloading[node.get('id')] && is_node_visible(node)) {
833 node.setImgRealSrc(scope.lazyloading);
837 this.processingimages = false;
840 treeview_dynload: function(node, cb) {
841 var retrieved_children = {};
843 for (var i in node.children) {
844 retrieved_children[node.children[i].path] = node.children[i];
849 client_id: this.options.client_id,
850 repository_id: this.active_repo.id,
851 path:node.path?node.path:'',
852 page:node.page?args.page:'',
854 callback: function(id, obj, args) {
856 var scope = args.scope;
857 // check that user did not leave the view mode before recieving this response
858 if (!(scope.active_repo.id == obj.repo_id && scope.viewmode == 2 && node && node.getChildrenEl())) {
861 if (cb != null) { // (in manual mode do not update current path)
862 scope.viewbar_set_enabled(true);
863 scope.parse_repository_options(obj);
865 node.highlight(false);
866 node.origlist = obj.list ? obj.list : null;
867 node.origpath = obj.path ? obj.path : null;
870 if (list[k].children && retrieved_children[list[k].path]) {
871 // if this child is a folder and has already been retrieved
872 node.children[node.children.length] = retrieved_children[list[k].path];
874 // append new file to the list
875 scope.view_as_list([list[k]]);
881 // invoke callback requested by TreeView component
884 scope.content_scrolled();
888 classnamecallback : function(node) {
891 classname = classname + ' fp-folder';
894 classname = classname + ' fp-isreference';
897 classname = classname + ' fp-hasreferences';
899 if (node.originalmissing) {
900 classname = classname + ' fp-originalmissing';
902 return Y.Lang.trim(classname);
904 /** displays list of files in tree (list) view mode. If param appenditems is specified,
905 * appends those items to the end of the list. Otherwise (default behaviour)
906 * clears the contents and displays the items from this.filelist */
907 view_as_list: function(appenditems) {
908 var list = (appenditems != null) ? appenditems : this.filelist;
910 if (!this.filelist || this.filelist.length==0 && (!this.filepath || !this.filepath.length)) {
911 this.display_error(M.str.repository.nofilesavailable, 'nofilesavailable');
915 var element_template = Y.Node.create(M.core_filepicker.templates.listfilename);
917 viewmode : this.viewmode,
918 appendonly : (appenditems != null),
919 filenode : element_template,
920 callbackcontext : this,
921 callback : function(e, node) {
922 // TODO MDL-32736 e is not an event here but an object with properties 'event' and 'node'
923 if (!node.children) {
924 if (e.node.parent && e.node.parent.origpath) {
925 // set the current path
926 this.filepath = e.node.parent.origpath;
927 this.filelist = e.node.parent.origlist;
930 this.select_file(node);
932 // save current path and filelist (in case we want to jump to other viewmode)
933 this.filepath = e.node.origpath;
934 this.filelist = e.node.origlist;
936 this.content_scrolled();
939 classnamecallback : this.classnamecallback,
940 dynload : this.active_repo.dynload,
941 filepath : this.filepath,
942 treeview_dynload : this.treeview_dynload
944 this.fpnode.one('.fp-content').fp_display_filelist(options, list, this.lazyloading);
946 /** displays list of files in icon view mode. If param appenditems is specified,
947 * appends those items to the end of the list. Otherwise (default behaviour)
948 * clears the contents and displays the items from this.filelist */
949 view_as_icons: function(appenditems) {
951 var list = (appenditems != null) ? appenditems : this.filelist;
952 var element_template = Y.Node.create(M.core_filepicker.templates.iconfilename);
953 if ((appenditems == null) && (!this.filelist || !this.filelist.length)) {
954 this.display_error(M.str.repository.nofilesavailable, 'nofilesavailable');
958 viewmode : this.viewmode,
959 appendonly : (appenditems != null),
960 filenode : element_template,
961 callbackcontext : this,
962 callback : function(e, node) {
963 if (e.preventDefault) {
967 if (this.active_repo.dynload) {
968 this.list({'path':node.path});
970 this.filepath = node.path;
971 this.filelist = node.children;
975 this.select_file(node);
978 classnamecallback : this.classnamecallback
980 this.fpnode.one('.fp-content').fp_display_filelist(options, list, this.lazyloading);
982 /** displays list of files in table view mode. If param appenditems is specified,
983 * appends those items to the end of the list. Otherwise (default behaviour)
984 * clears the contents and displays the items from this.filelist */
985 view_as_table: function(appenditems) {
987 var list = (appenditems != null) ? appenditems : this.filelist;
988 if (!appenditems && (!this.filelist || this.filelist.length==0) && !this.active_repo.hasmorepages) {
989 this.display_error(M.str.repository.nofilesavailable, 'nofilesavailable');
992 var element_template = Y.Node.create(M.core_filepicker.templates.listfilename);
994 viewmode : this.viewmode,
995 appendonly : (appenditems != null),
996 filenode : element_template,
997 callbackcontext : this,
998 sortable : !this.active_repo.hasmorepages,
999 callback : function(e, node) {
1000 if (e.preventDefault) {e.preventDefault();}
1001 if (node.children) {
1002 if (this.active_repo.dynload) {
1003 this.list({'path':node.path});
1005 this.filepath = node.path;
1006 this.filelist = node.children;
1010 this.select_file(node);
1013 classnamecallback : this.classnamecallback
1015 this.fpnode.one('.fp-content').fp_display_filelist(options, list, this.lazyloading);
1017 /** If more than one page available, requests and displays the files from the next page */
1018 request_next_page: function() {
1019 if (!this.active_repo.hasmorepages || this.active_repo.nextpagerequested) {
1023 this.active_repo.nextpagerequested = true;
1024 var nextpage = this.active_repo.page+1;
1025 var args = {page:nextpage, repo_id:this.active_repo.id, path:this.active_repo.path};
1026 var action = this.active_repo.issearchresult ? 'search' : 'list';
1030 client_id: this.options.client_id,
1031 repository_id: args.repo_id,
1033 callback: function(id, obj, args) {
1034 var scope = args.scope;
1035 // check that we are still in the same repository and are expecting this page
1036 if (scope.active_repo.hasmorepages && obj.list && obj.page &&
1037 obj.repo_id == scope.active_repo.id &&
1038 obj.page == scope.active_repo.page+1 && obj.path == scope.path) {
1039 scope.parse_repository_options(obj, true);
1040 scope.view_files(obj.list)
1045 select_file: function(args) {
1046 this.selectui.show();
1047 var client_id = this.options.client_id;
1048 var selectnode = this.selectnode;
1049 var return_types = this.options.repositories[this.active_repo.id].return_types;
1050 selectnode.removeClass('loading');
1051 selectnode.one('.fp-saveas input').set('value', args.title);
1053 var imgnode = Y.Node.create('<img/>').
1054 set('src', args.realthumbnail ? args.realthumbnail : args.thumbnail).
1055 setStyle('maxHeight', ''+(args.thumbnail_height ? args.thumbnail_height : 90)+'px').
1056 setStyle('maxWidth', ''+(args.thumbnail_width ? args.thumbnail_width : 90)+'px');
1057 selectnode.one('.fp-thumbnail').setContent('').appendChild(imgnode);
1059 // filelink is the array of file-link-types available for this repository in this env
1060 var filelinktypes = [2/*FILE_INTERNAL*/,1/*FILE_EXTERNAL*/,4/*FILE_REFERENCE*/];
1061 var filelink = {}, firstfilelink = null, filelinkcount = 0;
1062 for (var i in filelinktypes) {
1063 var allowed = (return_types & filelinktypes[i]) &&
1064 (this.options.return_types & filelinktypes[i]);
1065 if (filelinktypes[i] == 1/*FILE_EXTERNAL*/ && !this.options.externallink && this.options.env == 'editor') {
1066 // special configuration setting 'repositoryallowexternallinks' may prevent
1067 // using external links in editor environment
1070 filelink[filelinktypes[i]] = allowed;
1071 firstfilelink = (firstfilelink==null && allowed) ? filelinktypes[i] : firstfilelink;
1072 filelinkcount += allowed ? 1 : 0;
1074 // make radio buttons enabled if this file-link-type is available and only if there are more than one file-link-type option
1075 // check the first available file-link-type option
1076 for (var linktype in filelink) {
1077 var el = selectnode.one('.fp-linktype-'+linktype);
1078 el.addClassIf('uneditable', !(filelink[linktype] && filelinkcount>1));
1079 el.one('input').set('disabled', (filelink[linktype] && filelinkcount>1) ? '' : 'disabled').
1080 set('checked', (firstfilelink == linktype) ? 'checked' : '').simulate('change')
1083 // TODO MDL-32532: attributes 'hasauthor' and 'haslicense' need to be obsolete,
1084 selectnode.one('.fp-setauthor input').set('value', args.author ? args.author : this.options.author);
1085 this.set_selected_license(selectnode.one('.fp-setlicense'), args.license);
1086 selectnode.one('form #filesource-'+client_id).set('value', args.source);
1088 // display static information about a file (when known)
1089 var attrs = ['datemodified','datecreated','size','license','author','dimensions'];
1090 for (var i in attrs) {
1091 if (selectnode.one('.fp-'+attrs[i])) {
1092 var value = (args[attrs[i]+'_f']) ? args[attrs[i]+'_f'] : (args[attrs[i]] ? args[attrs[i]] : '');
1093 selectnode.one('.fp-'+attrs[i]).addClassIf('fp-unknown', ''+value == '')
1094 .one('.fp-value').setContent(value);
1098 setup_select_file: function() {
1099 var client_id = this.options.client_id;
1100 var selectnode = this.selectnode;
1101 var getfile = selectnode.one('.fp-select-confirm');
1102 // bind labels with corresponding inputs
1103 selectnode.all('.fp-saveas,.fp-linktype-2,.fp-linktype-1,.fp-linktype-4,.fp-setauthor,.fp-setlicense').each(function (node) {
1104 node.all('label').set('for', node.one('input,select').generateID());
1106 selectnode.one('.fp-linktype-2 input').setAttrs({value: 2, name: 'linktype'});
1107 selectnode.one('.fp-linktype-1 input').setAttrs({value: 1, name: 'linktype'});
1108 selectnode.one('.fp-linktype-4 input').setAttrs({value: 4, name: 'linktype'});
1109 var changelinktype = function(e) {
1110 if (e.currentTarget.get('checked')) {
1111 var allowinputs = e.currentTarget.get('value') != 1/*FILE_EXTERNAL*/;
1112 selectnode.all('.fp-setauthor,.fp-setlicense,.fp-saveas').each(function(node){
1113 node.addClassIf('uneditable', !allowinputs);
1114 node.all('input,select').set('disabled', allowinputs?'':'disabled');
1118 selectnode.all('.fp-linktype-2,.fp-linktype-1,.fp-linktype-4').each(function (node) {
1119 node.one('input').on('change', changelinktype, this);
1121 this.populate_licenses_select(selectnode.one('.fp-setlicense select'));
1122 // register event on clicking submit button
1123 getfile.on('click', function(e) {
1125 var client_id = this.options.client_id;
1127 var repository_id = this.active_repo.id;
1128 var title = selectnode.one('.fp-saveas input').get('value');
1129 var filesource = selectnode.one('form #filesource-'+client_id).get('value');
1130 var params = {'title':title, 'source':filesource, 'savepath': this.options.savepath};
1131 var license = selectnode.one('.fp-setlicense select');
1133 params['license'] = license.get('value');
1134 var origlicense = selectnode.one('.fp-license .fp-value');
1136 origlicense = origlicense.getContent();
1138 this.set_preference('recentlicense', license.get('value'));
1140 params['author'] = selectnode.one('.fp-setauthor input').get('value');
1142 var return_types = this.options.repositories[this.active_repo.id].return_types;
1143 if (this.options.env == 'editor') {
1144 // in editor, images are stored in '/' only
1145 params.savepath = '/';
1147 if ((this.options.externallink || this.options.env != 'editor') &&
1148 (return_types & 1/*FILE_EXTERNAL*/) &&
1149 (this.options.return_types & 1/*FILE_EXTERNAL*/) &&
1150 selectnode.one('.fp-linktype-1 input').get('checked')) {
1151 params['linkexternal'] = 'yes';
1152 } else if ((return_types & 4/*FILE_REFERENCE*/) &&
1153 (this.options.return_types & 4/*FILE_REFERENCE*/) &&
1154 selectnode.one('.fp-linktype-4 input').get('checked')) {
1155 params['usefilereference'] = '1';
1158 selectnode.addClass('loading');
1161 client_id: client_id,
1162 repository_id: repository_id,
1164 onerror: function(id, obj, args) {
1165 selectnode.removeClass('loading');
1166 scope.selectui.hide();
1168 callback: function(id, obj, args) {
1169 selectnode.removeClass('loading');
1170 if (obj.event == 'fileexists') {
1171 scope.process_existing_file(obj);
1174 if (scope.options.editor_target && scope.options.env=='editor') {
1175 scope.options.editor_target.value=obj.url;
1176 scope.options.editor_target.onchange();
1179 obj.client_id = client_id;
1180 var formcallback_scope = args.scope.options.magicscope ? args.scope.options.magicscope : args.scope;
1181 scope.options.formcallback.apply(formcallback_scope, [obj]);
1185 var elform = selectnode.one('form');
1186 elform.appendChild(Y.Node.create('<input/>').
1187 setAttrs({type:'hidden',id:'filesource-'+client_id}));
1188 elform.on('keydown', function(e) {
1189 if (e.keyCode == 13) {
1190 getfile.simulate('click');
1194 var cancel = selectnode.one('.fp-select-cancel');
1195 cancel.on('click', function(e) {
1197 this.selectui.hide();
1201 // First check there isn't already an interval in play, and if there is kill it now.
1202 if (this.waitinterval != null) {
1203 clearInterval(this.waitinterval);
1205 // Prepare the root node we will set content for and the loading template we want to display as a YUI node.
1206 var root = this.fpnode.one('.fp-content');
1207 var content = Y.Node.create(M.core_filepicker.templates.loading).addClass('fp-content-hidden').setStyle('opacity', 0);
1209 // Initiate an interval, we will have a count which will increment every 100 milliseconds.
1210 // Count 0 - the loading icon will have visibility set to hidden (invisible) and have an opacity of 0 (invisible also)
1211 // Count 5 - the visiblity will be switched to visible but opacity will still be at 0 (inivisible)
1212 // Counts 6 - 15 opacity will be increased by 0.1 making the loading icon visible over the period of a second
1213 // Count 16 - The interval will be cancelled.
1214 var interval = setInterval(function(){
1215 if (!content || !root.contains(content) || count >= 15) {
1216 clearInterval(interval);
1220 content.removeClass('fp-content-hidden');
1221 } else if (count > 5) {
1222 var opacity = parseFloat(content.getStyle('opacity'));
1223 content.setStyle('opacity', opacity + 0.1);
1228 // Store the wait interval so that we can check it in the future.
1229 this.waitinterval = interval;
1230 // Set the content to the loading template.
1231 root.setContent(content);
1233 viewbar_set_enabled: function(mode) {
1234 var viewbar = this.fpnode.one('.fp-viewbar')
1237 viewbar.addClass('enabled').removeClass('disabled')
1239 viewbar.removeClass('enabled').addClass('disabled')
1242 this.fpnode.all('.fp-vb-icons,.fp-vb-tree,.fp-vb-details').removeClass('checked')
1243 var modes = {1:'icons', 2:'tree', 3:'details'};
1244 this.fpnode.all('.fp-vb-'+modes[this.viewmode]).addClass('checked');
1246 viewbar_clicked: function(e) {
1248 var viewbar = this.fpnode.one('.fp-viewbar')
1249 if (!viewbar || !viewbar.hasClass('disabled')) {
1250 if (e.currentTarget.hasClass('fp-vb-tree')) {
1252 } else if (e.currentTarget.hasClass('fp-vb-details')) {
1257 this.viewbar_set_enabled(true)
1259 this.set_preference('recentviewmode', this.viewmode);
1262 render: function() {
1263 var client_id = this.options.client_id;
1264 this.fpnode = Y.Node.createWithFilesSkin(M.core_filepicker.templates.generallayout).
1265 set('id', 'filepicker-'+client_id);
1266 this.mainui = new Y.Panel({
1267 srcNode : this.fpnode,
1268 headerContent: M.str.repository.filepicker,
1273 minWidth : this.fpnode.getStylePx('minWidth'),
1274 minHeight : this.fpnode.getStylePx('minHeight'),
1275 maxWidth : this.fpnode.getStylePx('maxWidth'),
1276 maxHeight : this.fpnode.getStylePx('maxHeight'),
1279 // allow to move the panel dragging it by it's header:
1280 this.mainui.plug(Y.Plugin.Drag,{handles:['#filepicker-'+client_id+' .yui3-widget-hd']});
1282 if (this.mainui.get('y') < 0) {
1283 this.mainui.set('y', 0);
1285 // create panel for selecting a file (initially hidden)
1286 this.selectnode = Y.Node.createWithFilesSkin(M.core_filepicker.templates.selectlayout).
1287 set('id', 'filepicker-select-'+client_id);
1288 this.selectui = new Y.Panel({
1289 srcNode : this.selectnode,
1296 // allow to move the panel dragging it by it's header:
1297 this.selectui.plug(Y.Plugin.Drag,{handles:['#filepicker-select-'+client_id+' .yui3-widget-hd']});
1298 this.selectui.hide();
1299 // event handler for lazy loading of thumbnails and next page
1300 this.fpnode.one('.fp-content').on(['scroll','resize'], this.content_scrolled, this);
1301 // save template for one path element and location of path bar
1302 if (this.fpnode.one('.fp-path-folder')) {
1303 this.pathnode = this.fpnode.one('.fp-path-folder');
1304 this.pathbar = this.pathnode.get('parentNode');
1305 this.pathbar.removeChild(this.pathnode);
1307 // assign callbacks for view mode switch buttons
1308 this.fpnode.all('.fp-vb-icons,.fp-vb-tree,.fp-vb-details').
1309 on('click', this.viewbar_clicked, this);
1310 // assign callbacks for toolbar links
1311 this.setup_toolbar();
1312 this.setup_select_file();
1315 // processing repository listing
1316 // Resort the repositories by sortorder
1317 var sorted_repositories = [];
1318 for (var i in this.options.repositories) {
1319 sorted_repositories[i] = this.options.repositories[i];
1321 sorted_repositories.sort(function(a,b){return a.sortorder-b.sortorder});
1322 // extract one repository template and repeat it for all repositories available,
1323 // set name and icon and assign callbacks
1324 var reponode = this.fpnode.one('.fp-repo');
1326 var list = reponode.get('parentNode');
1327 list.removeChild(reponode);
1328 for (i in sorted_repositories) {
1329 var repository = sorted_repositories[i];
1330 var node = reponode.cloneNode(true);
1331 list.appendChild(node);
1333 set('id', 'fp-repo-'+client_id+'-'+repository.id).
1334 on('click', function(e, repository_id) {
1336 this.set_preference('recentrepository', repository_id);
1338 this.list({'repo_id':repository_id});
1339 }, this /*handler running scope*/, repository.id/*second argument of handler*/);
1340 node.one('.fp-repo-name').setContent(repository.name);
1341 node.one('.fp-repo-icon').set('src', repository.icon);
1343 node.addClass('first');
1345 if (i==sorted_repositories.length-1) {
1346 node.addClass('last');
1349 node.addClass('even');
1351 node.addClass('odd');
1355 // display error if no repositories found
1356 if (sorted_repositories.length==0) {
1357 this.display_error(M.str.repository.norepositoriesavailable, 'norepositoriesavailable')
1359 // display repository that was used last time
1360 this.show_recent_repository();
1362 parse_repository_options: function(data, appendtolist) {
1365 if (!this.filelist) {
1368 for (var i in data.list) {
1369 this.filelist[this.filelist.length] = data.list[i];
1373 this.filelist = data.list?data.list:null;
1374 this.lazyloading = {};
1376 this.filepath = data.path?data.path:null;
1377 this.objecttag = data.object?data.object:null;
1378 this.active_repo = {};
1379 this.active_repo.issearchresult = data.issearchresult ? true : false;
1380 this.active_repo.dynload = data.dynload?data.dynload:false;
1381 this.active_repo.pages = Number(data.pages?data.pages:null);
1382 this.active_repo.page = Number(data.page?data.page:null);
1383 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))
1384 this.active_repo.id = data.repo_id?data.repo_id:null;
1385 this.active_repo.nosearch = (data.login || data.nosearch); // this is either login form or 'nosearch' attribute set
1386 this.active_repo.norefresh = (data.login || data.norefresh); // this is either login form or 'norefresh' attribute set
1387 this.active_repo.nologin = (data.login || data.nologin); // this is either login form or 'nologin' attribute is set
1388 this.active_repo.logouttext = data.logouttext?data.logouttext:null;
1389 this.active_repo.help = data.help?data.help:null;
1390 this.active_repo.manage = data.manage?data.manage:null;
1391 this.print_header();
1393 print_login: function(data) {
1394 this.parse_repository_options(data);
1395 var client_id = this.options.client_id;
1396 var repository_id = data.repo_id;
1397 var l = this.logindata = data.login;
1399 var action = data['login_btn_action'] ? data['login_btn_action'] : 'login';
1400 var form_id = 'fp-form-'+client_id;
1402 var loginform_node = Y.Node.create(M.core_filepicker.templates.loginform);
1403 loginform_node.one('form').set('id', form_id);
1404 this.fpnode.one('.fp-content').setContent('').appendChild(loginform_node);
1406 'popup' : loginform_node.one('.fp-login-popup'),
1407 'textarea' : loginform_node.one('.fp-login-textarea'),
1408 'select' : loginform_node.one('.fp-login-select'),
1409 'text' : loginform_node.one('.fp-login-text'),
1410 'radio' : loginform_node.one('.fp-login-radiogroup'),
1411 'checkbox' : loginform_node.one('.fp-login-checkbox'),
1412 'input' : loginform_node.one('.fp-login-input')
1415 for (var i in templates) {
1417 container = templates[i].get('parentNode');
1418 container.removeChild(templates[i]);
1423 if (templates[l[k].type]) {
1424 var node = templates[l[k].type].cloneNode(true);
1426 node = templates['input'].cloneNode(true);
1428 if (l[k].type == 'popup') {
1430 loginurl = l[k].url;
1431 var popupbutton = node.one('button');
1432 popupbutton.on('click', function(e){
1433 M.core_filepicker.active_filepicker = this;
1434 window.open(loginurl, 'repo_auth', 'location=0,status=0,width=500,height=300,scrollbars=yes');
1437 loginform_node.one('form').on('keydown', function(e) {
1438 if (e.keyCode == 13) {
1439 popupbutton.simulate('click');
1443 loginform_node.all('.fp-login-submit').remove();
1445 } else if(l[k].type=='textarea') {
1447 if (node.one('label')) {
1448 node.one('label').set('for', l[k].id).setContent(l[k].label);
1450 node.one('textarea').setAttrs({id:l[k].id, name:l[k].name});
1451 } else if(l[k].type=='select') {
1453 if (node.one('label')) {
1454 node.one('label').set('for', l[k].id).setContent(l[k].label);
1456 node.one('select').setAttrs({id:l[k].id, name:l[k].name}).setContent('');
1457 for (i in l[k].options) {
1458 node.one('select').appendChild(
1459 Y.Node.create('<option/>').
1460 set('value', l[k].options[i].value).
1461 setContent(l[k].options[i].label));
1463 } else if(l[k].type=='radio') {
1464 // radio input element
1465 node.all('label').setContent(l[k].label);
1466 var list = l[k].value.split('|');
1467 var labels = l[k].value_label.split('|');
1468 var radionode = null;
1469 for(var item in list) {
1470 if (radionode == null) {
1471 radionode = node.one('.fp-login-radio');
1472 radionode.one('input').set('checked', 'checked');
1474 var x = radionode.cloneNode(true);
1475 radionode.insert(x, 'after');
1477 radionode.one('input').set('checked', '');
1479 radionode.one('input').setAttrs({id:''+l[k].id+item, name:l[k].name,
1480 type:l[k].type, value:list[item]});
1481 radionode.all('label').setContent(labels[item]).set('for', ''+l[k].id+item)
1483 if (radionode == null) {
1484 node.one('.fp-login-radio').remove();
1488 if (node.one('label')) { node.one('label').set('for', l[k].id).setContent(l[k].label) }
1490 set('type', l[k].type).
1492 set('name', l[k].name).
1493 set('value', l[k].value?l[k].value:'')
1495 container.appendChild(node);
1497 // custom label text for submit button
1498 if (data['login_btn_label']) {
1499 loginform_node.all('.fp-login-submit').setContent(data['login_btn_label'])
1501 // register button action for login and search
1502 if (action == 'login' || action == 'search') {
1503 loginform_node.one('.fp-login-submit').on('click', function(e){
1508 'action':(action == 'search') ? 'search' : 'signin',
1510 'client_id': client_id,
1511 'repository_id': repository_id,
1512 'form': {id:form_id, upload:false, useDisabled:true},
1513 'callback': this.display_response
1517 // if 'Enter' is pressed in the form, simulate the button click
1518 if (loginform_node.one('.fp-login-submit')) {
1519 loginform_node.one('form').on('keydown', function(e) {
1520 if (e.keyCode == 13) {
1521 loginform_node.one('.fp-login-submit').simulate('click')
1527 display_response: function(id, obj, args) {
1528 var scope = args.scope
1529 // highlight the current repository in repositories list
1530 scope.fpnode.all('.fp-repo.active').removeClass('active');
1531 scope.fpnode.all('#fp-repo-'+scope.options.client_id+'-'+obj.repo_id).addClass('active')
1532 // add class repository_REPTYPE to the filepicker (for repository-specific styles)
1533 for (var i in scope.options.repositories) {
1534 scope.fpnode.removeClass('repository_'+scope.options.repositories[i].type)
1536 if (obj.repo_id && scope.options.repositories[obj.repo_id]) {
1537 scope.fpnode.addClass('repository_'+scope.options.repositories[obj.repo_id].type)
1541 scope.viewbar_set_enabled(false);
1542 scope.print_login(obj);
1543 } else if (obj.upload) {
1544 scope.viewbar_set_enabled(false);
1545 scope.parse_repository_options(obj);
1546 scope.create_upload_form(obj);
1547 } else if (obj.object) {
1548 M.core_filepicker.active_filepicker = scope;
1549 scope.viewbar_set_enabled(false);
1550 scope.parse_repository_options(obj);
1551 scope.create_object_container(obj.object);
1552 } else if (obj.list) {
1553 scope.viewbar_set_enabled(true);
1554 scope.parse_repository_options(obj);
1558 list: function(args) {
1562 if (!args.repo_id) {
1563 args.repo_id = this.active_repo.id;
1567 client_id: this.options.client_id,
1568 repository_id: args.repo_id,
1572 callback: this.display_response
1575 populate_licenses_select: function(node) {
1579 node.setContent('');
1580 var licenses = this.options.licenses;
1581 var recentlicense = this.get_preference('recentlicense');
1582 if (recentlicense) {
1583 this.options.defaultlicense=recentlicense;
1585 for (var i in licenses) {
1586 var option = Y.Node.create('<option/>').
1587 set('selected', (this.options.defaultlicense==licenses[i].shortname)).
1588 set('value', licenses[i].shortname).
1589 setContent(licenses[i].fullname);
1590 node.appendChild(option)
1593 set_selected_license: function(node, value) {
1594 var licenseset = false;
1595 node.all('option').each(function(el) {
1596 if (el.get('value')==value || el.getContent()==value) {
1597 el.set('selected', true);
1602 // we did not find the value in the list
1603 var recentlicense = this.get_preference('recentlicense');
1604 node.all('option[selected]').set('selected', false);
1605 node.all('option[value='+recentlicense+']').set('selected', true);
1608 create_object_container: function(data) {
1609 var content = this.fpnode.one('.fp-content');
1610 content.setContent('');
1611 //var str = '<object data="'+data.src+'" type="'+data.type+'" width="98%" height="98%" id="container_object" class="fp-object-container mdl-align"></object>';
1612 var container = Y.Node.create('<object/>').
1613 setAttrs({data:data.src, type:data.type, id:'container_object'}).
1614 addClass('fp-object-container');
1615 content.setContent('').appendChild(container);
1617 create_upload_form: function(data) {
1618 var client_id = this.options.client_id;
1619 var id = data.upload.id+'_'+client_id;
1620 var content = this.fpnode.one('.fp-content');
1621 content.setContent(M.core_filepicker.templates.uploadform);
1623 content.all('.fp-file,.fp-saveas,.fp-setauthor,.fp-setlicense').each(function (node) {
1624 node.all('label').set('for', node.one('input,select').generateID());
1626 content.one('form').set('id', id);
1627 content.one('.fp-file input').set('name', 'repo_upload_file');
1628 if (data.upload.label && content.one('.fp-file label')) {
1629 content.one('.fp-file label').setContent(data.upload.label);
1631 content.one('.fp-saveas input').set('name', 'title');
1632 content.one('.fp-setauthor input').setAttrs({name:'author', value:this.options.author});
1633 content.one('.fp-setlicense select').set('name', 'license');
1634 this.populate_licenses_select(content.one('.fp-setlicense select'))
1635 // append hidden inputs to the upload form
1636 content.one('form').appendChild(Y.Node.create('<input/>').
1637 setAttrs({type:'hidden',name:'itemid',value:this.options.itemid}));
1638 var types = this.options.accepted_types;
1639 for (var i in types) {
1640 content.one('form').appendChild(Y.Node.create('<input/>').
1641 setAttrs({type:'hidden',name:'accepted_types[]',value:types[i]}));
1645 content.one('.fp-upload-btn').on('click', function(e) {
1647 var license = content.one('.fp-setlicense select');
1649 this.set_preference('recentlicense', license.get('value'));
1650 if (!content.one('.fp-file input').get('value')) {
1651 scope.print_msg(M.str.repository.nofilesattached, 'error');
1658 client_id: client_id,
1659 params: {'savepath':scope.options.savepath},
1660 repository_id: scope.active_repo.id,
1661 form: {id: id, upload:true},
1662 onerror: function(id, o, args) {
1663 scope.create_upload_form(data);
1665 callback: function(id, o, args) {
1666 if (o.event == 'fileexists') {
1667 scope.create_upload_form(data);
1668 scope.process_existing_file(o);
1671 if (scope.options.editor_target&&scope.options.env=='editor') {
1672 scope.options.editor_target.value=o.url;
1673 scope.options.editor_target.onchange();
1676 o.client_id = client_id;
1677 var formcallback_scope = args.scope.options.magicscope ? args.scope.options.magicscope : args.scope;
1678 scope.options.formcallback.apply(formcallback_scope, [o]);
1683 /** setting handlers and labels for elements in toolbar. Called once during the initial render of filepicker */
1684 setup_toolbar: function() {
1685 var client_id = this.options.client_id;
1686 var toolbar = this.fpnode.one('.fp-toolbar');
1687 toolbar.one('.fp-tb-logout').one('a,button').on('click', function(e) {
1689 if (!this.active_repo.nologin) {
1693 client_id: this.options.client_id,
1694 repository_id: this.active_repo.id,
1696 callback: this.display_response
1700 toolbar.one('.fp-tb-refresh').one('a,button').on('click', function(e) {
1702 if (!this.active_repo.norefresh) {
1706 toolbar.one('.fp-tb-search form').
1707 set('method', 'POST').
1708 set('id', 'fp-tb-search-'+client_id).
1709 on('submit', function(e) {
1711 if (!this.active_repo.nosearch) {
1715 client_id: this.options.client_id,
1716 repository_id: this.active_repo.id,
1717 form: {id: 'fp-tb-search-'+client_id, upload:false, useDisabled:true},
1718 callback: this.display_response
1723 // it does not matter what kind of element is .fp-tb-manage, we create a dummy <a>
1724 // element and use it to open url on click event
1725 var managelnk = Y.Node.create('<a/>').
1726 setAttrs({id:'fp-tb-manage-'+client_id+'-link', target:'_blank'}).
1727 setStyle('display', 'none');
1728 toolbar.append(managelnk);
1729 toolbar.one('.fp-tb-manage').one('a,button').
1730 on('click', function(e) {
1732 managelnk.simulate('click')
1735 // same with .fp-tb-help
1736 var helplnk = Y.Node.create('<a/>').
1737 setAttrs({id:'fp-tb-help-'+client_id+'-link', target:'_blank'}).
1738 setStyle('display', 'none');
1739 toolbar.append(helplnk);
1740 toolbar.one('.fp-tb-manage').one('a,button').
1741 on('click', function(e) {
1743 helplnk.simulate('click')
1746 hide_header: function() {
1747 if (this.fpnode.one('.fp-toolbar')) {
1748 this.fpnode.one('.fp-toolbar').addClass('empty');
1751 this.pathbar.setContent('').addClass('empty');
1754 print_header: function() {
1755 var r = this.active_repo;
1757 var client_id = this.options.client_id;
1760 var toolbar = this.fpnode.one('.fp-toolbar');
1761 if (!toolbar) { return; }
1763 var enable_tb_control = function(node, enabled) {
1764 if (!node) { return; }
1765 node.addClassIf('disabled', !enabled).addClassIf('enabled', enabled)
1767 toolbar.removeClass('empty');
1771 // TODO 'back' permanently disabled for now. Note, flickr_public uses 'Logout' for it!
1772 enable_tb_control(toolbar.one('.fp-tb-back'), false);
1775 enable_tb_control(toolbar.one('.fp-tb-search'), !r.nosearch);
1777 var searchform = toolbar.one('.fp-tb-search form');
1778 searchform.setContent('');
1781 action:'searchform',
1782 repository_id: this.active_repo.id,
1783 callback: function(id, obj, args) {
1784 if (obj.repo_id == scope.active_repo.id && obj.form) {
1785 // if we did not jump to another repository meanwhile
1786 searchform.setContent(obj.form);
1787 // Highlight search text when user click for search.
1788 var searchnode = searchform.one('input[name="s"]');
1790 searchnode.once('click', function(e) {
1801 // weather we use cache for this instance, this button will reload listing anyway
1802 enable_tb_control(toolbar.one('.fp-tb-refresh'), !r.norefresh);
1805 enable_tb_control(toolbar.one('.fp-tb-logout'), !r.nologin);
1807 var label = r.logouttext ? r.logouttext : M.str.repository.logout;
1808 toolbar.one('.fp-tb-logout').one('a,button').setContent(label)
1812 enable_tb_control(toolbar.one('.fp-tb-manage'), r.manage);
1813 Y.one('#fp-tb-manage-'+client_id+'-link').set('href', r.manage);
1816 enable_tb_control(toolbar.one('.fp-tb-help'), r.help);
1817 Y.one('#fp-tb-help-'+client_id+'-link').set('href', r.help);
1819 print_path: function() {
1820 if (!this.pathbar) {
1823 this.pathbar.setContent('').addClass('empty');
1824 var p = this.filepath;
1825 if (p && p.length!=0 && this.viewmode != 2) {
1826 for(var i = 0; i < p.length; i++) {
1827 var el = this.pathnode.cloneNode(true);
1828 this.pathbar.appendChild(el);
1830 el.addClass('first');
1832 if (i == p.length-1) {
1833 el.addClass('last');
1836 el.addClass('even');
1840 el.all('.fp-path-folder-name').setContent(p[i].name);
1844 this.list({'path':path});
1848 this.pathbar.removeClass('empty');
1852 this.selectui.hide();
1853 if (this.process_dlg) {
1854 this.process_dlg.hide();
1857 this.msg_dlg.hide();
1865 this.show_recent_repository();
1870 launch: function() {
1873 show_recent_repository: function() {
1875 this.viewbar_set_enabled(false);
1876 var repository_id = this.get_preference('recentrepository');
1877 this.viewmode = this.get_preference('recentviewmode');
1878 if (this.viewmode != 2 && this.viewmode != 3) {
1881 if (this.options.repositories[repository_id]) {
1882 this.list({'repo_id':repository_id});
1885 get_preference: function (name) {
1886 if (this.options.userprefs[name]) {
1887 return this.options.userprefs[name];
1892 set_preference: function(name, value) {
1893 if (this.options.userprefs[name] != value) {
1894 M.util.set_user_preference('filepicker_' + name, value);
1895 this.options.userprefs[name] = value;
1899 var loading = Y.one('#filepicker-loading-'+options.client_id);
1901 loading.setStyle('display', 'none');
1903 M.core_filepicker.instances[options.client_id] = new FilePickerHelper(options);