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')
78 * Displays a list of files (used by filepicker, filemanager) inside the Node
80 * @param array options
81 * viewmode : 1 - icons, 2 - tree, 3 - table
82 * appendonly : whether fileslist need to be appended instead of replacing the existing content
83 * filenode : Node element that contains template for displaying one file
84 * callback : On click callback. The element of the fileslist array will be passed as argument
85 * rightclickcallback : On right click callback (optional).
86 * callbackcontext : context where callbacks are executed
87 * sortable : whether content may be sortable (in table mode)
88 * dynload : allow dynamic load for tree view
89 * filepath : for pre-building of tree view - the path to the current directory in filepicker format
90 * treeview_dynload : callback to function to dynamically load the folder in tree view
91 * classnamecallback : callback to function that returns the class name for an element
92 * @param array fileslist array of files to show, each array element may have attributes:
93 * title or fullname : file name
94 * shorttitle (optional) : display file name
95 * thumbnail : url of image
96 * icon : url of icon image
97 * thumbnail_width : width of thumbnail, default 90
98 * thumbnail_height : height of thumbnail, default 90
99 * thumbnail_alt : TODO not needed!
100 * description or thumbnail_title : alt text
101 * @param array lazyloading : reference to the array with lazy loading images
103 Y.Node.prototype.fp_display_filelist = function(options, fileslist, lazyloading) {
104 var viewmodeclassnames = {1:'fp-iconview', 2:'fp-treeview', 3:'fp-tableview'};
105 var classname = viewmodeclassnames[options.viewmode];
107 /** return whether file is a folder (different attributes in FileManager and FilePicker) */
108 var file_is_folder = function(node) {
109 if (node.children) {return true;}
110 if (node.type && node.type == 'folder') {return true;}
113 /** return the name of the file (different attributes in FileManager and FilePicker) */
114 var file_get_filename = function(node) {
115 return node.title ? node.title : node.fullname;
117 /** return display name of the file (different attributes in FileManager and FilePicker) */
118 var file_get_displayname = function(node) {
119 return node.shorttitle ? node.shorttitle : file_get_filename(node);
121 /** return file description (different attributes in FileManager and FilePicker) */
122 var file_get_description = function(node) {
123 return node.description ? node.description : (node.thumbnail_title ? node.thumbnail_title : file_get_filename(node));
125 /** help funciton for tree view */
126 var build_tree = function(node, level) {
127 // prepare file name with icon
128 var el = Y.Node.create('<div/>');
129 el.appendChild(options.filenode.cloneNode(true));
131 el.one('.fp-filename').setContent(file_get_displayname(node));
132 // TODO add tooltip with node.title or node.thumbnail_title
133 var tmpnodedata = {className:options.classnamecallback(node)};
134 el.get('children').addClass(tmpnodedata.className);
136 el.one('.fp-icon').appendChild(Y.Node.create('<img/>').set('src', node.icon));
138 lazyloading[el.one('.fp-icon img').generateID()] = node.realicon;
142 tmpnodedata.html = el.getContent();
143 var tmpNode = new YAHOO.widget.HTMLNode(tmpnodedata, level, false);
144 if (node.dynamicLoadComplete) {
145 tmpNode.dynamicLoadComplete = true;
147 tmpNode.fileinfo = node;
148 tmpNode.isLeaf = !file_is_folder(node);
149 if (!tmpNode.isLeaf) {
153 tmpNode.path = node.path ? node.path : (node.filepath ? node.filepath : '');
154 for(var c in node.children) {
155 build_tree(node.children[c], tmpNode);
159 /** initialize tree view */
160 var initialize_tree_view = function() {
161 var parentid = scope.one('.'+classname).get('id');
162 // TODO MDL-32736 use YUI3 gallery TreeView
163 scope.treeview = new YAHOO.widget.TreeView(parentid);
164 if (options.dynload) {
165 scope.treeview.setDynamicLoad(Y.bind(options.treeview_dynload, options.callbackcontext), 1);
167 scope.treeview.singleNodeHighlight = true;
168 if (options.filepath && options.filepath.length) {
169 // we just jumped from icon/details view, we need to show all parents
170 // we extract as much information as possible from filepath and filelist
171 // and send additional requests to retrieve siblings for parent folders
174 for (var i in options.filepath) {
175 if (mytreeel == null) {
178 mytreeel.children = [{}];
179 mytreeel = mytreeel.children[0];
181 var pathelement = options.filepath[i];
182 mytreeel.path = pathelement.path;
183 mytreeel.title = pathelement.name;
184 mytreeel.dynamicLoadComplete = true; // we will call it manually
185 mytreeel.expanded = true;
187 mytreeel.children = fileslist;
188 build_tree(mytree, scope.treeview.getRoot());
189 // manually call dynload for parent elements in the tree so we can load other siblings
190 if (options.dynload) {
191 var root = scope.treeview.getRoot();
192 while (root && root.children && root.children.length) {
193 root = root.children[0];
194 if (root.path == mytreeel.path) {
195 root.origpath = options.filepath;
196 root.origlist = fileslist;
197 } else if (!root.isLeaf && root.expanded) {
198 Y.bind(options.treeview_dynload, options.callbackcontext)(root, null);
203 // there is no path information, just display all elements as a list, without hierarchy
204 for(k in fileslist) {
205 build_tree(fileslist[k], scope.treeview.getRoot());
208 scope.treeview.subscribe('clickEvent', function(e){
209 e.node.highlight(false);
210 var callback = options.callback;
211 if (options.rightclickcallback && e.event.target &&
212 Y.Node(e.event.target).ancestor('.fp-treeview .fp-contextmenu', true)) {
213 callback = options.rightclickcallback;
215 Y.bind(callback, options.callbackcontext)(e, e.node.fileinfo);
216 YAHOO.util.Event.stopEvent(e.event)
218 // TODO MDL-32736 support right click
219 /*if (options.rightclickcallback) {
220 scope.treeview.subscribe('dblClickEvent', function(e){
221 e.node.highlight(false);
222 Y.bind(options.rightclickcallback, options.callbackcontext)(e, e.node.fileinfo);
225 scope.treeview.draw();
227 /** formatting function for table view */
228 var formatValue = function (o){
229 if (o.data[''+o.column.key+'_f_s']) {return o.data[''+o.column.key+'_f_s'];}
230 else if (o.data[''+o.column.key+'_f']) {return o.data[''+o.column.key+'_f'];}
231 else if (o.value) {return o.value;}
234 /** formatting function for table view */
235 var formatTitle = function(o) {
236 var el = Y.Node.create('<div/>');
237 el.appendChild(options.filenode.cloneNode(true)); // TODO not node but string!
238 el.get('children').addClass(o.data['classname']);
239 el.one('.fp-filename').setContent(o.value);
240 if (o.data['icon']) {
241 el.one('.fp-icon').appendChild(Y.Node.create('<img/>').set('src', o.data['icon']));
242 if (o.data['realicon']) {
243 lazyloading[el.one('.fp-icon img').generateID()] = o.data['realicon'];
246 if (options.rightclickcallback) {
247 el.get('children').addClass('fp-hascontextmenu');
249 // TODO add tooltip with o.data['title'] (o.value) or o.data['thumbnail_title']
250 return el.getContent();
252 /** sorting function for table view */
253 var sortFoldersFirst = function(a, b, desc) {
254 if (a.get('isfolder') && !b.get('isfolder')) {return -1;}
255 if (!a.get('isfolder') && b.get('isfolder')) {return 1;}
256 var aa = a.get(this.key), bb = b.get(this.key), dir = desc?-1:1;
257 return (aa > bb) ? dir : ((aa < bb) ? -dir : 0);
259 /** initialize table view */
260 var initialize_table_view = function() {
261 var parentid = scope.one('.'+classname).get('id');
263 {key: "displayname", label: M.str.moodle.name, allowHTML: true, formatter: formatTitle,
264 sortable: true, sortFn: sortFoldersFirst},
265 {key: "datemodified", label: M.str.moodle.lastmodified, allowHTML: true, formatter: formatValue,
266 sortable: true, sortFn: sortFoldersFirst},
267 {key: "size", label: M.str.repository.size, allowHTML: true, formatter: formatValue,
268 sortable: true, sortFn: sortFoldersFirst},
269 {key: "mimetype", label: M.str.repository.type, allowHTML: true,
270 sortable: true, sortFn: sortFoldersFirst}
272 scope.tableview = new Y.DataTable({columns: cols});
273 scope.tableview.render('#'+parentid);
274 scope.tableview.delegate('click', function (e, tableview) {
275 var record = tableview.getRecord(e.currentTarget.get('id'));
277 var callback = options.callback;
278 if (options.rightclickcallback && e.target.ancestor('.fp-tableview .fp-contextmenu', true)) {
279 callback = options.rightclickcallback;
281 Y.bind(callback, this)(e, record.getAttrs());
283 }, 'tr', options.callbackcontext, scope.tableview);
284 if (options.rightclickcallback) {
285 scope.tableview.delegate('contextmenu', function (e, tableview) {
286 var record = tableview.getRecord(e.currentTarget.get('id'));
287 if (record) { Y.bind(options.rightclickcallback, this)(e, record.getAttrs()); }
288 }, 'tr', options.callbackcontext, scope.tableview);
291 /** append items in table view mode */
292 var append_files_table = function() {
293 for (var k in fileslist) {
294 // to speed up sorting and formatting
295 fileslist[k].displayname = file_get_displayname(fileslist[k]);
296 fileslist[k].isfolder = file_is_folder(fileslist[k]);
297 fileslist[k].classname = options.classnamecallback(fileslist[k]);
299 scope.tableview.addRows(fileslist);
300 scope.tableview.sortable = options.sortable ? true : false;
302 /** append items in tree view mode */
303 var append_files_tree = function() {
304 if (options.appendonly) {
305 var parentnode = scope.treeview.getRoot();
306 if (scope.treeview.getHighlightedNode()) {
307 parentnode = scope.treeview.getHighlightedNode();
308 if (parentnode.isLeaf) {parentnode = parentnode.parent;}
310 for (var k in fileslist) {
311 build_tree(fileslist[k], parentnode);
313 scope.treeview.draw();
315 // otherwise files were already added in initialize_tree_view()
318 /** append items in icon view mode */
319 var append_files_icons = function() {
320 parent = scope.one('.'+classname);
321 for (var k in fileslist) {
322 var node = fileslist[k];
323 var element = options.filenode.cloneNode(true);
324 parent.appendChild(element);
325 element.addClass(options.classnamecallback(node));
326 var filenamediv = element.one('.fp-filename');
327 filenamediv.setContent(file_get_displayname(node));
328 var imgdiv = element.one('.fp-thumbnail'), width, height, src;
329 if (node.thumbnail) {
330 width = node.thumbnail_width ? node.thumbnail_width : 90;
331 height = node.thumbnail_height ? node.thumbnail_height : 90;
332 src = node.thumbnail;
338 filenamediv.setStyleAdv('width', width);
339 imgdiv.setStyleAdv('width', width).setStyleAdv('height', height);
340 var img = Y.Node.create('<img/>').setAttrs({
342 title: file_get_description(node),
343 alt: node.thumbnail_alt ? node.thumbnail_alt : file_get_filename(node)}).
344 setStyle('maxWidth', ''+width+'px').
345 setStyle('maxHeight', ''+height+'px');
346 if (node.realthumbnail) {
347 lazyloading[img.generateID()] = node.realthumbnail;
349 imgdiv.appendChild(img);
350 element.on('click', function(e, nd) {
351 if (options.rightclickcallback && e.target.ancestor('.fp-iconview .fp-contextmenu', true)) {
352 Y.bind(options.rightclickcallback, this)(e, nd);
354 Y.bind(options.callback, this)(e, nd);
356 }, options.callbackcontext, node);
357 if (options.rightclickcallback) {
358 element.on('contextmenu', options.rightclickcallback, options.callbackcontext, node);
363 // initialize files view
364 if (!options.appendonly) {
365 var parent = Y.Node.create('<div/>').addClass(classname);
366 this.setContent('').appendChild(parent);
368 if (options.viewmode == 2) {
369 initialize_tree_view();
370 } else if (options.viewmode == 3) {
371 initialize_table_view();
373 // nothing to initialize for icon view
377 // append files to the list
378 if (options.viewmode == 2) {
380 } else if (options.viewmode == 3) {
381 append_files_table();
383 append_files_icons();
388 requires:['base', 'node', 'yui2-treeview', 'panel', 'cookie', 'datatable', 'datatable-sort']
391 M.core_filepicker = M.core_filepicker || {};
394 * instances of file pickers used on page
396 M.core_filepicker.instances = M.core_filepicker.instances || {};
397 M.core_filepicker.active_filepicker = null;
400 * HTML Templates to use in FilePicker
402 M.core_filepicker.templates = M.core_filepicker.templates || {};
405 * Set selected file info
407 * @parma object file info
409 M.core_filepicker.select_file = function(file) {
410 M.core_filepicker.active_filepicker.select_file(file);
414 * Init and show file picker
416 M.core_filepicker.show = function(Y, options) {
417 if (!M.core_filepicker.instances[options.client_id]) {
418 M.core_filepicker.init(Y, options);
420 M.core_filepicker.instances[options.client_id].show();
423 M.core_filepicker.set_templates = function(Y, templates) {
424 for (var templid in templates) {
425 M.core_filepicker.templates[templid] = templates[templid];
430 * Add new file picker to current instances
432 M.core_filepicker.init = function(Y, options) {
433 var FilePickerHelper = function(options) {
434 FilePickerHelper.superclass.constructor.apply(this, arguments);
437 FilePickerHelper.NAME = "FilePickerHelper";
438 FilePickerHelper.ATTRS = {
443 Y.extend(FilePickerHelper, Y.Base, {
444 api: M.cfg.wwwroot+'/repository/repository_ajax.php',
445 cached_responses: {},
447 initializer: function(options) {
448 this.options = options;
449 if (!this.options.savepath) {
450 this.options.savepath = '/';
454 destructor: function() {
457 request: function(args, redraw) {
458 var api = (args.api?args.api:this.api) + '?action='+args.action;
460 var scope = args['scope']?args['scope']:this;
461 params['repo_id']=args.repository_id;
462 params['p'] = args.path?args.path:'';
463 params['page'] = args.page?args.page:'';
464 params['env']=this.options.env;
465 // the form element only accept certain file types
466 params['accepted_types']=this.options.accepted_types;
467 params['sesskey'] = M.cfg.sesskey;
468 params['client_id'] = args.client_id;
469 params['itemid'] = this.options.itemid?this.options.itemid:0;
470 params['maxbytes'] = this.options.maxbytes?this.options.maxbytes:-1;
471 if (this.options.context && this.options.context.id) {
472 params['ctx_id'] = this.options.context.id;
474 if (args['params']) {
475 for (i in args['params']) {
476 params[i] = args['params'][i];
479 if (args.action == 'upload') {
481 for(var k in params) {
482 var value = params[k];
483 if(value instanceof Array) {
484 for(var i in value) {
485 list.push(k+'[]='+value[i]);
488 list.push(k+'='+value);
491 params = list.join('&');
493 params = build_querystring(params);
498 complete: function(id,o,p) {
506 data = Y.JSON.parse(o.responseText);
508 scope.print_msg(M.str.repository.invalidjson, 'error');
509 scope.display_error(M.str.repository.invalidjson+'<pre>'+stripHTML(o.responseText)+'</pre>', 'invalidjson')
513 if (data && data.error) {
514 scope.print_msg(data.error, 'error');
516 args.onerror(id,data,p);
518 this.fpnode.one('.fp-content').setContent('');
523 scope.print_msg(data.msg, 'info');
525 // cache result if applicable
526 if (args.action != 'upload' && data.allowcaching) {
527 scope.cached_responses[params] = data;
530 args.callback(id,data,p);
538 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
544 cfg.form = args.form;
546 // check if result of the same request has been already cached. If not, request it
547 // (never applicable in case of form submission and/or upload action):
548 if (!args.form && args.action != 'upload' && scope.cached_responses[params]) {
549 args.callback(null, scope.cached_responses[params], {scope: scope})
557 /** displays the dialog and processes rename/overwrite if there is a file with the same name in the same filearea*/
558 process_existing_file: function(data) {
560 var handleOverwrite = function(e) {
563 var data = this.process_dlg.dialogdata;
565 params['existingfilename'] = data.existingfile.filename;
566 params['existingfilepath'] = data.existingfile.filepath;
567 params['newfilename'] = data.newfile.filename;
568 params['newfilepath'] = data.newfile.filepath;
573 'action':'overwrite',
575 'client_id': this.options.client_id,
576 'repository_id': this.active_repo.id,
577 'callback': function(id, o, args) {
579 // editor needs to update url
580 // filemanager do nothing
581 if (scope.options.editor_target && scope.options.env == 'editor') {
582 scope.options.editor_target.value = data.existingfile.url;
583 scope.options.editor_target.onchange();
584 } else if (scope.options.env === 'filepicker') {
585 var fileinfo = {'client_id':scope.options.client_id,
586 'url':data.existingfile.url,
587 'file':data.existingfile.filename};
588 var formcallback_scope = scope.options.magicscope ? scope.options.magicscope : scope;
589 scope.options.formcallback.apply(formcallback_scope, [fileinfo]);
594 var handleRename = function(e) {
595 // inserts file with the new name
598 var data = this.process_dlg.dialogdata;
599 if (scope.options.editor_target && scope.options.env == 'editor') {
600 scope.options.editor_target.value = data.newfile.url;
601 scope.options.editor_target.onchange();
604 var formcallback_scope = scope.options.magicscope ? scope.options.magicscope : scope;
605 var fileinfo = {'client_id':scope.options.client_id,
606 'url':data.newfile.url,
607 'file':data.newfile.filename};
608 scope.options.formcallback.apply(formcallback_scope, [fileinfo]);
610 var handleCancel = function(e) {
614 params['newfilename'] = this.process_dlg.dialogdata.newfile.filename;
615 params['newfilepath'] = this.process_dlg.dialogdata.newfile.filepath;
619 'action':'deletetmpfile',
621 'client_id': this.options.client_id,
622 'repository_id': this.active_repo.id,
623 'callback': function(id, o, args) {
624 // let it be in background, from user point of view nothing is happenning
627 this.process_dlg.hide();
628 this.selectui.hide();
630 if (!this.process_dlg) {
631 this.process_dlg_node = Y.Node.create(M.core_filepicker.templates.processexistingfile);
632 var node = this.process_dlg_node;
634 Y.one(document.body).appendChild(node);
635 this.process_dlg = new Y.Panel({
637 headerContent: M.str.repository.fileexistsdialogheader,
645 this.process_dlg.plug(Y.Plugin.Drag,{handles:['#'+node.get('id')+' .yui3-widget-hd']});
646 node.one('.fp-dlg-butoverwrite').on('click', handleOverwrite, this);
647 node.one('.fp-dlg-butrename').on('click', handleRename, this);
648 node.one('.fp-dlg-butcancel').on('click', handleCancel, this);
649 if (this.options.env == 'editor') {
650 node.one('.fp-dlg-text').setContent(M.str.repository.fileexistsdialog_editor);
652 node.one('.fp-dlg-text').setContent(M.str.repository.fileexistsdialog_filemanager);
655 this.selectnode.removeClass('loading');
656 this.process_dlg.dialogdata = data;
657 this.process_dlg_node.one('.fp-dlg-butrename').setContent(M.util.get_string('renameto', 'repository', data.newfile.filename));
658 this.process_dlg.show();
660 /** displays error instead of filepicker contents */
661 display_error: function(errortext, errorcode) {
662 this.fpnode.one('.fp-content').setContent(M.core_filepicker.templates.error);
663 this.fpnode.one('.fp-content .fp-error').
665 setContent(errortext);
667 /** displays message in a popup */
668 print_msg: function(msg, type) {
669 var header = M.str.moodle.error;
670 if (type != 'error') {
671 type = 'info'; // one of only two types excepted
672 header = M.str.moodle.info;
675 this.msg_dlg_node = Y.Node.create(M.core_filepicker.templates.message);
676 this.msg_dlg_node.generateID();
677 Y.one(document.body).appendChild(this.msg_dlg_node);
679 this.msg_dlg = new Y.Panel({
680 srcNode : this.msg_dlg_node,
687 this.msg_dlg.plug(Y.Plugin.Drag,{handles:['#'+this.msg_dlg_node.get('id')+' .yui3-widget-hd']});
688 this.msg_dlg_node.one('.fp-msg-butok').on('click', function(e) {
694 this.msg_dlg.set('headerContent', header);
695 this.msg_dlg_node.removeClass('fp-msg-info').removeClass('fp-msg-error').addClass('fp-msg-'+type)
696 this.msg_dlg_node.one('.fp-msg-text').setContent(msg);
699 view_files: function(appenditems) {
700 this.viewbar_set_enabled(true);
702 /*if ((appenditems == null) && (!this.filelist || !this.filelist.length) && !this.active_repo.hasmorepages) {
703 // TODO do it via classes and adjust for each view mode!
704 // If there are no items and no next page, just display status message and quit
705 this.display_error(M.str.repository.nofilesavailable, 'nofilesavailable');
708 if (this.viewmode == 2) {
709 this.view_as_list(appenditems);
710 } else if (this.viewmode == 3) {
711 this.view_as_table(appenditems);
713 this.view_as_icons(appenditems);
715 // display/hide the link for requesting next page
716 if (!appenditems && this.active_repo.hasmorepages) {
717 if (!this.fpnode.one('.fp-content .fp-nextpage')) {
718 this.fpnode.one('.fp-content').append(M.core_filepicker.templates.nextpage);
720 this.fpnode.one('.fp-content .fp-nextpage').one('a,button').on('click', function(e) {
722 this.fpnode.one('.fp-content .fp-nextpage').addClass('loading');
723 this.request_next_page();
726 if (!this.active_repo.hasmorepages && this.fpnode.one('.fp-content .fp-nextpage')) {
727 this.fpnode.one('.fp-content .fp-nextpage').remove();
729 if (this.fpnode.one('.fp-content .fp-nextpage')) {
730 this.fpnode.one('.fp-content .fp-nextpage').removeClass('loading');
732 this.content_scrolled();
734 content_scrolled: function(e) {
735 setTimeout(Y.bind(function() {
736 if (this.processingimages) {return;}
737 this.processingimages = true;
739 fpcontent = this.fpnode.one('.fp-content'),
740 fpcontenty = fpcontent.getY(),
741 fpcontentheight = fpcontent.getStylePx('height'),
742 nextpage = fpcontent.one('.fp-nextpage'),
743 is_node_visible = function(node) {
744 var offset = node.getY()-fpcontenty;
745 if (offset <= fpcontentheight && (offset >=0 || offset+node.getStylePx('height')>=0)) {
750 // automatically load next page when 'more' link becomes visible
751 if (nextpage && !nextpage.hasClass('loading') && is_node_visible(nextpage)) {
752 nextpage.one('a,button').simulate('click');
754 // replace src for visible images that need to be lazy-loaded
755 if (scope.lazyloading) {
756 fpcontent.all('img').each( function(node) {
757 if (node.get('id') && scope.lazyloading[node.get('id')] && is_node_visible(node)) {
758 node.set('src', scope.lazyloading[node.get('id')]);
759 delete scope.lazyloading[node.get('id')];
763 this.processingimages = false;
766 treeview_dynload: function(node, cb) {
767 var retrieved_children = {};
769 for (var i in node.children) {
770 retrieved_children[node.children[i].path] = node.children[i];
775 client_id: this.options.client_id,
776 repository_id: this.active_repo.id,
777 path:node.path?node.path:'',
778 page:node.page?args.page:'',
780 callback: function(id, obj, args) {
782 var scope = args.scope;
783 // check that user did not leave the view mode before recieving this response
784 if (!(scope.active_repo.id == obj.repo_id && scope.viewmode == 2 && node && node.getChildrenEl())) {
787 if (cb != null) { // (in manual mode do not update current path)
788 scope.viewbar_set_enabled(true);
789 scope.parse_repository_options(obj);
791 node.highlight(false);
792 node.origlist = obj.list?obj.list:null;
793 node.origpath = obj.path?obj.path:null;
796 if (list[k].children && retrieved_children[list[k].path]) {
797 // if this child is a folder and has already been retrieved
798 node.children[node.children.length] = retrieved_children[list[k].path];
800 // append new file to the list
801 scope.view_as_list([list[k]]);
807 // invoke callback requested by TreeView component
810 scope.content_scrolled();
814 /** displays list of files in tree (list) view mode. If param appenditems is specified,
815 * appends those items to the end of the list. Otherwise (default behaviour)
816 * clears the contents and displays the items from this.filelist */
817 view_as_list: function(appenditems) {
818 var list = (appenditems != null) ? appenditems : this.filelist;
820 if (!this.filelist || this.filelist.length==0 && (!this.filepath || !this.filepath.length)) {
821 this.display_error(M.str.repository.nofilesavailable, 'nofilesavailable');
825 var element_template = Y.Node.create(M.core_filepicker.templates.listfilename);
827 viewmode : this.viewmode,
828 appendonly : (appenditems != null),
829 filenode : element_template,
830 callbackcontext : this,
831 callback : function(e, node) {
832 // TODO MDL-32736 e is not an event here but an object with properties 'event' and 'node'
833 if (!node.children) {
834 if (e.node.parent && e.node.parent.origpath) {
835 // set the current path
836 this.filepath = e.node.parent.origpath;
837 this.filelist = e.node.parent.origlist;
840 this.select_file(node);
842 // save current path and filelist (in case we want to jump to other viewmode)
843 this.filepath = e.node.origpath;
844 this.filelist = e.node.origlist;
846 this.content_scrolled();
849 classnamecallback : function(node) {
850 return node.children ? 'fp-folder' : '';
852 dynload : this.active_repo.dynload,
853 filepath : this.filepath,
854 treeview_dynload : this.treeview_dynload
856 this.fpnode.one('.fp-content').fp_display_filelist(options, list, this.lazyloading);
858 /** displays list of files in icon view mode. If param appenditems is specified,
859 * appends those items to the end of the list. Otherwise (default behaviour)
860 * clears the contents and displays the items from this.filelist */
861 view_as_icons: function(appenditems) {
863 var list = (appenditems != null) ? appenditems : this.filelist;
864 var element_template = Y.Node.create(M.core_filepicker.templates.iconfilename);
865 if ((appenditems == null) && (!this.filelist || !this.filelist.length)) {
866 this.display_error(M.str.repository.nofilesavailable, 'nofilesavailable');
870 viewmode : this.viewmode,
871 appendonly : (appenditems != null),
872 filenode : element_template,
873 callbackcontext : this,
874 callback : function(e, node) {
875 if (e.preventDefault) {e.preventDefault();}
877 if (this.active_repo.dynload) {
878 this.list({'path':node.path});
880 this.filepath = node.path;
881 this.filelist = node.children;
885 this.select_file(node);
888 classnamecallback : function(node) {
889 return node.children ? 'fp-folder' : '';
892 this.fpnode.one('.fp-content').fp_display_filelist(options, list, this.lazyloading);
894 /** displays list of files in table view mode. If param appenditems is specified,
895 * appends those items to the end of the list. Otherwise (default behaviour)
896 * clears the contents and displays the items from this.filelist */
897 view_as_table: function(appenditems) {
899 var list = (appenditems != null) ? appenditems : this.filelist;
900 if (!appenditems && (!this.filelist || this.filelist.length==0) && !this.active_repo.hasmorepages) {
901 this.display_error(M.str.repository.nofilesavailable, 'nofilesavailable');
904 var element_template = Y.Node.create(M.core_filepicker.templates.listfilename);
906 viewmode : this.viewmode,
907 appendonly : (appenditems != null),
908 filenode : element_template,
909 callbackcontext : this,
910 sortable : !this.active_repo.hasmorepages,
911 callback : function(e, node) {
912 if (e.preventDefault) {e.preventDefault();}
914 if (this.active_repo.dynload) {
915 this.list({'path':node.path});
917 this.filepath = node.path;
918 this.filelist = node.children;
922 this.select_file(node);
925 classnamecallback : function(node) {
926 return node.children ? 'fp-folder' : '';
929 this.fpnode.one('.fp-content').fp_display_filelist(options, list, this.lazyloading);
931 /** If more than one page available, requests and displays the files from the next page */
932 request_next_page: function() {
933 if (!this.active_repo.hasmorepages || this.active_repo.nextpagerequested) {
937 this.active_repo.nextpagerequested = true;
938 var nextpage = this.active_repo.page+1;
939 var args = {page:nextpage, repo_id:this.active_repo.id, path:this.active_repo.path};
940 var action = this.active_repo.issearchresult ? 'search' : 'list';
944 client_id: this.options.client_id,
945 repository_id: args.repo_id,
947 callback: function(id, obj, args) {
948 var scope = args.scope;
949 // check that we are still in the same repository and are expecting this page
950 if (scope.active_repo.hasmorepages && obj.list && obj.page &&
951 obj.repo_id == scope.active_repo.id &&
952 obj.page == scope.active_repo.page+1 && obj.path == scope.path) {
953 scope.parse_repository_options(obj, true);
954 scope.view_files(obj.list)
959 select_file: function(args) {
960 this.selectui.show();
961 var client_id = this.options.client_id;
962 var selectnode = this.selectnode;
963 var return_types = this.options.repositories[this.active_repo.id].return_types;
964 selectnode.removeClass('loading');
965 selectnode.one('.fp-saveas input').set('value', args.title);
967 var imgnode = Y.Node.create('<img/>').
968 set('src', args.realthumbnail ? args.realthumbnail : args.thumbnail).
969 setStyle('maxHeight', ''+(args.thumbnail_height ? args.thumbnail_height : 90)+'px').
970 setStyle('maxWidth', ''+(args.thumbnail_width ? args.thumbnail_width : 90)+'px');
971 selectnode.one('.fp-thumbnail').setContent('').appendChild(imgnode);
973 // filelink is the array of file-link-types available for this repository in this env
974 var filelinktypes = [2/*FILE_INTERNAL*/,1/*FILE_EXTERNAL*/,4/*FILE_REFERENCE*/];
975 var filelink = {}, firstfilelink = null, filelinkcount = 0;
976 for (var i in filelinktypes) {
977 var allowed = (return_types & filelinktypes[i]) &&
978 (this.options.return_types & filelinktypes[i]);
979 if (filelinktypes[i] == 1/*FILE_EXTERNAL*/ && !this.options.externallink && this.options.env == 'editor') {
980 // special configuration setting 'repositoryallowexternallinks' may prevent
981 // using external links in editor environment
984 filelink[filelinktypes[i]] = allowed;
985 firstfilelink = (firstfilelink==null && allowed) ? filelinktypes[i] : firstfilelink;
986 filelinkcount += allowed ? 1 : 0;
988 // make radio buttons enabled if this file-link-type is available and only if there are more than one file-link-type option
989 // check the first available file-link-type option
990 for (var linktype in filelink) {
991 var el = selectnode.one('.fp-linktype-'+linktype);
992 el.addClassIf('uneditable', !(filelink[linktype] && filelinkcount>1));
993 el.one('input').set('disabled', (filelink[linktype] && filelinkcount>1)?'':'disabled').
994 set('checked', (firstfilelink == linktype) ? 'checked' : '').simulate('change')
997 // TODO MDL-32532: attributes 'hasauthor' and 'haslicense' need to be obsolete,
998 selectnode.one('.fp-setauthor input').set('value', args.author?args.author:this.options.author);
999 this.set_selected_license(selectnode.one('.fp-setlicense'), args.license);
1000 selectnode.one('form #filesource-'+client_id).set('value', args.source);
1002 // display static information about a file (when known)
1003 var attrs = ['datemodified','datecreated','size','license','author','dimensions'];
1004 for (var i in attrs) {
1005 if (selectnode.one('.fp-'+attrs[i])) {
1006 var value = (args[attrs[i]+'_f']) ? args[attrs[i]+'_f'] : (args[attrs[i]] ? args[attrs[i]] : '');
1007 selectnode.one('.fp-'+attrs[i]).addClassIf('fp-unknown', ''+value == '')
1008 .one('.fp-value').setContent(value);
1012 setup_select_file: function() {
1013 var client_id = this.options.client_id;
1014 var selectnode = this.selectnode;
1015 var getfile = selectnode.one('.fp-select-confirm');
1016 // bind labels with corresponding inputs
1017 selectnode.all('.fp-saveas,.fp-linktype-2,.fp-linktype-1,.fp-linktype-4,.fp-setauthor,.fp-setlicense').each(function (node) {
1018 node.all('label').set('for', node.one('input,select').generateID());
1020 selectnode.one('.fp-linktype-2 input').setAttrs({value: 2, name: 'linktype'});
1021 selectnode.one('.fp-linktype-1 input').setAttrs({value: 1, name: 'linktype'});
1022 selectnode.one('.fp-linktype-4 input').setAttrs({value: 4, name: 'linktype'});
1023 var changelinktype = function(e) {
1024 if (e.currentTarget.get('checked')) {
1025 var allowinputs = e.currentTarget.get('value') != 1/*FILE_EXTERNAL*/;
1026 selectnode.all('.fp-setauthor,.fp-setlicense,.fp-saveas').each(function(node){
1027 node.addClassIf('uneditable', !allowinputs);
1028 node.all('input,select').set('disabled', allowinputs?'':'disabled');
1032 selectnode.all('.fp-linktype-2,.fp-linktype-1,.fp-linktype-4').each(function (node) {
1033 node.one('input').on('change', changelinktype, this);
1035 this.populate_licenses_select(selectnode.one('.fp-setlicense select'));
1036 // register event on clicking submit button
1037 getfile.on('click', function(e) {
1039 var client_id = this.options.client_id;
1041 var repository_id = this.active_repo.id;
1042 var title = selectnode.one('.fp-saveas input').get('value');
1043 var filesource = selectnode.one('form #filesource-'+client_id).get('value');
1044 var params = {'title':title, 'source':filesource, 'savepath': this.options.savepath};
1045 var license = selectnode.one('.fp-setlicense select');
1047 params['license'] = license.get('value');
1048 var origlicense = selectnode.one('.fp-license .fp-value');
1049 if (origlicense) { origlicense = origlicense.getContent(); }
1050 var newlicenseval = license.get('value');
1051 if (newlicenseval && this.options.licenses[newlicenseval] != origlicense) {
1052 Y.Cookie.set('recentlicense', newlicenseval);
1055 params['author'] = selectnode.one('.fp-setauthor input').get('value');
1057 var return_types = this.options.repositories[this.active_repo.id].return_types;
1058 if (this.options.env == 'editor') {
1059 // in editor, images are stored in '/' only
1060 params.savepath = '/';
1062 if ((this.options.externallink || this.options.env != 'editor') &&
1063 (return_types & 1/*FILE_EXTERNAL*/) &&
1064 (this.options.return_types & 1/*FILE_EXTERNAL*/) &&
1065 selectnode.one('.fp-linktype-1 input').get('checked')) {
1066 params['linkexternal'] = 'yes';
1067 } else if ((return_types & 4/*FILE_REFERENCE*/) &&
1068 (this.options.return_types & 4/*FILE_REFERENCE*/) &&
1069 selectnode.one('.fp-linktype-4 input').get('checked')) {
1070 params['usefilereference'] = '1';
1073 selectnode.addClass('loading');
1076 client_id: client_id,
1077 repository_id: repository_id,
1079 onerror: function(id, obj, args) {
1080 selectnode.removeClass('loading');
1081 scope.selectui.hide();
1083 callback: function(id, obj, args) {
1084 selectnode.removeClass('loading');
1085 if (obj.event == 'fileexists') {
1086 scope.process_existing_file(obj);
1089 if (scope.options.editor_target && scope.options.env=='editor') {
1090 scope.options.editor_target.value=obj.url;
1091 scope.options.editor_target.onchange();
1094 obj.client_id = client_id;
1095 var formcallback_scope = args.scope.options.magicscope ? args.scope.options.magicscope : args.scope;
1096 scope.options.formcallback.apply(formcallback_scope, [obj]);
1100 var elform = selectnode.one('form');
1101 elform.appendChild(Y.Node.create('<input/>').
1102 setAttrs({type:'hidden',id:'filesource-'+client_id}));
1103 elform.on('keydown', function(e) {
1104 if (e.keyCode == 13) {
1105 getfile.simulate('click');
1109 var cancel = selectnode.one('.fp-select-cancel');
1110 cancel.on('click', function(e) {
1112 this.selectui.hide();
1116 this.fpnode.one('.fp-content').setContent(M.core_filepicker.templates.loading);
1118 viewbar_set_enabled: function(mode) {
1119 var viewbar = this.fpnode.one('.fp-viewbar')
1122 viewbar.addClass('enabled').removeClass('disabled')
1124 viewbar.removeClass('enabled').addClass('disabled')
1127 this.fpnode.all('.fp-vb-icons,.fp-vb-tree,.fp-vb-details').removeClass('checked')
1128 var modes = {1:'icons', 2:'tree', 3:'details'};
1129 this.fpnode.all('.fp-vb-'+modes[this.viewmode]).addClass('checked');
1131 viewbar_clicked: function(e) {
1133 var viewbar = this.fpnode.one('.fp-viewbar')
1134 if (!viewbar || !viewbar.hasClass('disabled')) {
1135 if (e.currentTarget.hasClass('fp-vb-tree')) {
1137 } else if (e.currentTarget.hasClass('fp-vb-details')) {
1142 this.viewbar_set_enabled(true)
1144 Y.Cookie.set('recentviewmode', this.viewmode);
1147 render: function() {
1148 var client_id = this.options.client_id;
1149 this.fpnode = Y.Node.create(M.core_filepicker.templates.generallayout).
1150 set('id', 'filepicker-'+client_id);
1151 this.selectnode = Y.Node.create(M.core_filepicker.templates.selectlayout);
1152 Y.one(document.body).appendChild(this.fpnode);
1153 this.mainui = new Y.Panel({
1154 srcNode : this.fpnode,
1155 headerContent: M.str.repository.filepicker,
1160 minWidth : this.fpnode.getStylePx('minWidth'),
1161 minHeight : this.fpnode.getStylePx('minHeight'),
1162 maxWidth : this.fpnode.getStylePx('maxWidth'),
1163 maxHeight : this.fpnode.getStylePx('maxHeight'),
1166 // allow to move the panel dragging it by it's header:
1167 this.mainui.plug(Y.Plugin.Drag,{handles:['#filepicker-'+client_id+' .yui3-widget-hd']});
1169 if (this.mainui.get('y')<0) {this.mainui.set('y', 0);}
1170 // create panel for selecting a file (initially hidden)
1171 this.selectnode = Y.Node.create(M.core_filepicker.templates.selectlayout).
1172 set('id', 'filepicker-select-'+client_id);
1173 Y.one(document.body).appendChild(this.selectnode);
1174 this.selectui = new Y.Panel({
1175 srcNode : this.selectnode,
1182 // allow to move the panel dragging it by it's header:
1183 this.selectui.plug(Y.Plugin.Drag,{handles:['#filepicker-select-'+client_id+' .yui3-widget-hd']});
1184 this.selectui.hide();
1185 // event handler for lazy loading of thumbnails and next page
1186 this.fpnode.one('.fp-content').on(['scroll','resize'], this.content_scrolled, this);
1187 // save template for one path element and location of path bar
1188 if (this.fpnode.one('.fp-path-folder')) {
1189 this.pathnode = this.fpnode.one('.fp-path-folder');
1190 this.pathbar = this.pathnode.get('parentNode');
1191 this.pathbar.removeChild(this.pathnode);
1193 // assign callbacks for view mode switch buttons
1194 this.fpnode.all('.fp-vb-icons,.fp-vb-tree,.fp-vb-details').
1195 on('click', this.viewbar_clicked, this);
1196 // assign callbacks for toolbar links
1197 this.setup_toolbar();
1198 this.setup_select_file();
1201 // processing repository listing
1202 // Resort the repositories by sortorder
1203 var sorted_repositories = []
1204 for (var i in this.options.repositories) {
1205 sorted_repositories[i] = this.options.repositories[i]
1207 sorted_repositories.sort(function(a,b){return a.sortorder-b.sortorder})
1208 // extract one repository template and repeat it for all repositories available,
1209 // set name and icon and assign callbacks
1210 var reponode = this.fpnode.one('.fp-repo');
1212 var list = reponode.get('parentNode');
1213 list.removeChild(reponode);
1214 for (i in sorted_repositories) {
1215 var repository = sorted_repositories[i]
1216 var node = reponode.cloneNode(true);
1217 list.appendChild(node);
1219 set('id', 'fp-repo-'+client_id+'-'+repository.id).
1220 on('click', function(e, repository_id) {
1222 Y.Cookie.set('recentrepository', repository_id);
1224 this.list({'repo_id':repository_id});
1225 }, this /*handler running scope*/, repository.id/*second argument of handler*/);
1226 node.one('.fp-repo-name').setContent(repository.name)
1227 node.one('.fp-repo-icon').set('src', repository.icon)
1228 if (i==0) {node.addClass('first');}
1229 if (i==sorted_repositories.length-1) {node.addClass('last');}
1230 if (i%2) {node.addClass('even');} else {node.addClass('odd');}
1233 // display error if no repositories found
1234 if (sorted_repositories.length==0) {
1235 this.display_error(M.str.repository.norepositoriesavailable, 'norepositoriesavailable')
1237 // display repository that was used last time
1238 this.show_recent_repository();
1240 parse_repository_options: function(data, appendtolist) {
1243 if (!this.filelist) { this.filelist = []; }
1244 for (var i in data.list) {
1245 this.filelist[this.filelist.length] = data.list[i];
1249 this.filelist = data.list?data.list:null;
1250 this.lazyloading = {};
1252 this.filepath = data.path?data.path:null;
1253 this.objecttag = data.object?data.object:null;
1254 this.active_repo = {};
1255 this.active_repo.issearchresult = data.issearchresult?true:false;
1256 this.active_repo.dynload = data.dynload?data.dynload:false;
1257 this.active_repo.pages = Number(data.pages?data.pages:null);
1258 this.active_repo.page = Number(data.page?data.page:null);
1259 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))
1260 this.active_repo.id = data.repo_id?data.repo_id:null;
1261 this.active_repo.nosearch = (data.login || data.nosearch); // this is either login form or 'nosearch' attribute set
1262 this.active_repo.norefresh = (data.login || data.norefresh); // this is either login form or 'norefresh' attribute set
1263 this.active_repo.nologin = (data.login || data.nologin); // this is either login form or 'nologin' attribute is set
1264 this.active_repo.logouttext = data.logouttext?data.logouttext:null;
1265 this.active_repo.help = data.help?data.help:null;
1266 this.active_repo.manage = data.manage?data.manage:null;
1267 this.print_header();
1269 print_login: function(data) {
1270 this.parse_repository_options(data);
1271 var client_id = this.options.client_id;
1272 var repository_id = data.repo_id;
1273 var l = this.logindata = data.login;
1275 var action = data['login_btn_action'] ? data['login_btn_action'] : 'login';
1276 var form_id = 'fp-form-'+client_id;
1278 var loginform_node = Y.Node.create(M.core_filepicker.templates.loginform);
1279 loginform_node.one('form').set('id', form_id);
1280 this.fpnode.one('.fp-content').setContent('').appendChild(loginform_node);
1282 'popup' : loginform_node.one('.fp-login-popup'),
1283 'textarea' : loginform_node.one('.fp-login-textarea'),
1284 'select' : loginform_node.one('.fp-login-select'),
1285 'text' : loginform_node.one('.fp-login-text'),
1286 'radio' : loginform_node.one('.fp-login-radiogroup'),
1287 'checkbox' : loginform_node.one('.fp-login-checkbox'),
1288 'input' : loginform_node.one('.fp-login-input')
1291 for (var i in templates) {
1293 container = templates[i].get('parentNode');
1294 container.removeChild(templates[i])
1299 if (templates[l[k].type]) {
1300 var node = templates[l[k].type].cloneNode(true);
1302 node = templates['input'].cloneNode(true);
1304 if (l[k].type == 'popup') {
1306 loginurl = l[k].url;
1307 var popupbutton = node.one('button');
1308 popupbutton.on('click', function(e){
1309 M.core_filepicker.active_filepicker = this;
1310 window.open(loginurl, 'repo_auth', 'location=0,status=0,width=500,height=300,scrollbars=yes');
1313 loginform_node.one('form').on('keydown', function(e) {
1314 if (e.keyCode == 13) {
1315 popupbutton.simulate('click');
1319 loginform_node.all('.fp-login-submit').remove();
1321 }else if(l[k].type=='textarea') {
1323 if (node.one('label')) { node.one('label').set('for', l[k].id).setContent(l[k].label) }
1324 node.one('textarea').setAttrs({id:l[k].id, name:l[k].name});
1325 }else if(l[k].type=='select') {
1327 if (node.one('label')) { node.one('label').set('for', l[k].id).setContent(l[k].label) }
1328 node.one('select').setAttrs({id:l[k].id, name:l[k].name}).setContent('');
1329 for (i in l[k].options) {
1330 node.one('select').appendChild(
1331 Y.Node.create('<option/>').
1332 set('value', l[k].options[i].value).
1333 setContent(l[k].options[i].label))
1335 }else if(l[k].type=='radio') {
1336 // radio input element
1337 node.all('label').setContent(l[k].label);
1338 var list = l[k].value.split('|');
1339 var labels = l[k].value_label.split('|');
1340 var radionode = null;
1341 for(var item in list) {
1342 if (radionode == null) {
1343 radionode = node.one('.fp-login-radio');
1344 radionode.one('input').set('checked', 'checked');
1346 var x = radionode.cloneNode(true);
1347 radionode.insert(x, 'after');
1349 radionode.one('input').set('checked', '');
1351 radionode.one('input').setAttrs({id:''+l[k].id+item, name:l[k].name,
1352 type:l[k].type, value:list[item]});
1353 radionode.all('label').setContent(labels[item]).set('for', ''+l[k].id+item)
1355 if (radionode == null) {
1356 node.one('.fp-login-radio').remove();
1360 if (node.one('label')) { node.one('label').set('for', l[k].id).setContent(l[k].label) }
1362 set('type', l[k].type).
1364 set('name', l[k].name).
1365 set('value', l[k].value?l[k].value:'')
1367 container.appendChild(node);
1369 // custom label text for submit button
1370 if (data['login_btn_label']) {
1371 loginform_node.all('.fp-login-submit').setContent(data['login_btn_label'])
1373 // register button action for login and search
1374 if (action == 'login' || action == 'search') {
1375 loginform_node.one('.fp-login-submit').on('click', function(e){
1380 'action':(action == 'search') ? 'search' : 'signin',
1382 'client_id': client_id,
1383 'repository_id': repository_id,
1384 'form': {id:form_id, upload:false, useDisabled:true},
1385 'callback': this.display_response
1389 // if 'Enter' is pressed in the form, simulate the button click
1390 if (loginform_node.one('.fp-login-submit')) {
1391 loginform_node.one('form').on('keydown', function(e) {
1392 if (e.keyCode == 13) {
1393 loginform_node.one('.fp-login-submit').simulate('click')
1399 display_response: function(id, obj, args) {
1400 var scope = args.scope
1401 // highlight the current repository in repositories list
1402 scope.fpnode.all('.fp-repo.active').removeClass('active');
1403 scope.fpnode.all('#fp-repo-'+scope.options.client_id+'-'+obj.repo_id).addClass('active')
1404 // add class repository_REPTYPE to the filepicker (for repository-specific styles)
1405 for (var i in scope.options.repositories) {
1406 scope.fpnode.removeClass('repository_'+scope.options.repositories[i].type)
1408 if (obj.repo_id && scope.options.repositories[obj.repo_id]) {
1409 scope.fpnode.addClass('repository_'+scope.options.repositories[obj.repo_id].type)
1413 scope.viewbar_set_enabled(false);
1414 scope.print_login(obj);
1415 } else if (obj.upload) {
1416 scope.viewbar_set_enabled(false);
1417 scope.parse_repository_options(obj);
1418 scope.create_upload_form(obj);
1419 } else if (obj.object) {
1420 M.core_filepicker.active_filepicker = scope;
1421 scope.viewbar_set_enabled(false);
1422 scope.parse_repository_options(obj);
1423 scope.create_object_container(obj.object);
1424 } else if (obj.list) {
1425 scope.viewbar_set_enabled(true);
1426 scope.parse_repository_options(obj);
1430 list: function(args) {
1434 if (!args.repo_id) {
1435 args.repo_id = this.active_repo.id;
1439 client_id: this.options.client_id,
1440 repository_id: args.repo_id,
1444 callback: this.display_response
1447 populate_licenses_select: function(node) {
1451 node.setContent('');
1452 var licenses = this.options.licenses;
1453 var recentlicense = Y.Cookie.get('recentlicense');
1454 if (recentlicense) {
1455 this.options.defaultlicense=recentlicense;
1457 for (var i in licenses) {
1458 var option = Y.Node.create('<option/>').
1459 set('selected', (this.options.defaultlicense==licenses[i].shortname)).
1460 set('value', licenses[i].shortname).
1461 setContent(licenses[i].fullname);
1462 node.appendChild(option)
1465 set_selected_license: function(node, value) {
1466 var licenseset = false;
1467 node.all('option').each(function(el) {
1468 if (el.get('value')==value || el.getContent()==value) {
1469 el.set('selected', true);
1474 // we did not find the value in the list
1475 var recentlicense = Y.Cookie.get('recentlicense');
1476 node.all('option[selected]').set('selected', false);
1477 node.all('option[value='+recentlicense+']').set('selected', true);
1480 create_object_container: function(data) {
1481 var content = this.fpnode.one('.fp-content');
1482 content.setContent('');
1483 //var str = '<object data="'+data.src+'" type="'+data.type+'" width="98%" height="98%" id="container_object" class="fp-object-container mdl-align"></object>';
1484 var container = Y.Node.create('<object/>').
1485 setAttrs({data:data.src, type:data.type, id:'container_object'}).
1486 addClass('fp-object-container');
1487 content.setContent('').appendChild(container);
1489 create_upload_form: function(data) {
1490 var client_id = this.options.client_id;
1491 var id = data.upload.id+'_'+client_id;
1492 var content = this.fpnode.one('.fp-content');
1493 content.setContent(M.core_filepicker.templates.uploadform);
1495 content.all('.fp-file,.fp-saveas,.fp-setauthor,.fp-setlicense').each(function (node) {
1496 node.all('label').set('for', node.one('input,select').generateID());
1498 content.one('form').set('id', id);
1499 content.one('.fp-file input').set('name', 'repo_upload_file');
1500 content.one('.fp-saveas input').set('name', 'title');
1501 content.one('.fp-setauthor input').setAttrs({name:'author', value:this.options.author});
1502 content.one('.fp-setlicense select').set('name', 'license');
1503 this.populate_licenses_select(content.one('.fp-setlicense select'))
1504 // append hidden inputs to the upload form
1505 content.one('form').appendChild(Y.Node.create('<input/>').
1506 setAttrs({type:'hidden',name:'itemid',value:this.options.itemid}));
1507 var types = this.options.accepted_types;
1508 for (var i in types) {
1509 content.one('form').appendChild(Y.Node.create('<input/>').
1510 setAttrs({type:'hidden',name:'accepted_types[]',value:types[i]}));
1514 content.one('.fp-upload-btn').on('click', function(e) {
1516 var license = content.one('.fp-setlicense select');
1517 Y.Cookie.set('recentlicense', license.get('value'));
1518 if (!content.one('.fp-file input').get('value')) {
1519 scope.print_msg(M.str.repository.nofilesattached, 'error');
1526 client_id: client_id,
1527 params: {'savepath':scope.options.savepath},
1528 repository_id: scope.active_repo.id,
1529 form: {id: id, upload:true},
1530 onerror: function(id, o, args) {
1531 scope.create_upload_form(data);
1533 callback: function(id, o, args) {
1534 if (o.event == 'fileexists') {
1535 scope.create_upload_form(data);
1536 scope.process_existing_file(o);
1539 if (scope.options.editor_target&&scope.options.env=='editor') {
1540 scope.options.editor_target.value=o.url;
1541 scope.options.editor_target.onchange();
1544 o.client_id = client_id;
1545 var formcallback_scope = args.scope.options.magicscope ? args.scope.options.magicscope : args.scope;
1546 scope.options.formcallback.apply(formcallback_scope, [o]);
1551 /** setting handlers and labels for elements in toolbar. Called once during the initial render of filepicker */
1552 setup_toolbar: function() {
1553 var client_id = this.options.client_id;
1554 var toolbar = this.fpnode.one('.fp-toolbar');
1555 toolbar.one('.fp-tb-logout').one('a,button').on('click', function(e) {
1557 if (!this.active_repo.nologin) {
1561 client_id: this.options.client_id,
1562 repository_id: this.active_repo.id,
1564 callback: this.display_response
1568 toolbar.one('.fp-tb-refresh').one('a,button').on('click', function(e) {
1570 if (!this.active_repo.norefresh) {
1574 toolbar.one('.fp-tb-search form').
1575 set('method', 'POST').
1576 set('id', 'fp-tb-search-'+client_id).
1577 on('submit', function(e) {
1579 if (!this.active_repo.nosearch) {
1583 client_id: this.options.client_id,
1584 repository_id: this.active_repo.id,
1585 form: {id: 'fp-tb-search-'+client_id, upload:false, useDisabled:true},
1586 callback: this.display_response
1591 // it does not matter what kind of element is .fp-tb-manage, we create a dummy <a>
1592 // element and use it to open url on click event
1593 var managelnk = Y.Node.create('<a/>').
1594 setAttrs({id:'fp-tb-manage-'+client_id+'-link', target:'_blank'}).
1595 setStyle('display', 'none');
1596 toolbar.append(managelnk);
1597 toolbar.one('.fp-tb-manage').one('a,button').
1598 on('click', function(e) {
1600 managelnk.simulate('click')
1603 // same with .fp-tb-help
1604 var helplnk = Y.Node.create('<a/>').
1605 setAttrs({id:'fp-tb-help-'+client_id+'-link', target:'_blank'}).
1606 setStyle('display', 'none');
1607 toolbar.append(helplnk);
1608 toolbar.one('.fp-tb-manage').one('a,button').
1609 on('click', function(e) {
1611 helplnk.simulate('click')
1614 hide_header: function() {
1615 if (this.fpnode.one('.fp-toolbar')) {
1616 this.fpnode.one('.fp-toolbar').addClass('empty');
1619 this.pathbar.setContent('').addClass('empty');
1622 print_header: function() {
1623 var r = this.active_repo;
1625 var client_id = this.options.client_id;
1628 var toolbar = this.fpnode.one('.fp-toolbar');
1629 if (!toolbar) { return; }
1631 var enable_tb_control = function(node, enabled) {
1632 if (!node) { return; }
1633 node.addClassIf('disabled', !enabled).addClassIf('enabled', enabled)
1635 toolbar.removeClass('empty');
1639 // TODO 'back' permanently disabled for now. Note, flickr_public uses 'Logout' for it!
1640 enable_tb_control(toolbar.one('.fp-tb-back'), false);
1643 enable_tb_control(toolbar.one('.fp-tb-search'), !r.nosearch);
1645 var searchform = toolbar.one('.fp-tb-search form');
1646 searchform.setContent('');
1649 action:'searchform',
1650 repository_id: this.active_repo.id,
1651 callback: function(id, obj, args) {
1652 if (obj.repo_id == scope.active_repo.id && obj.form) {
1653 // if we did not jump to another repository meanwhile
1654 searchform.setContent(obj.form);
1661 // weather we use cache for this instance, this button will reload listing anyway
1662 enable_tb_control(toolbar.one('.fp-tb-refresh'), !r.norefresh);
1665 enable_tb_control(toolbar.one('.fp-tb-logout'), !r.nologin);
1667 var label = r.logouttext?r.logouttext:M.str.repository.logout;
1668 toolbar.one('.fp-tb-logout').one('a,button').setContent(label)
1672 enable_tb_control(toolbar.one('.fp-tb-manage'), r.manage);
1673 Y.one('#fp-tb-manage-'+client_id+'-link').set('href', r.manage);
1676 enable_tb_control(toolbar.one('.fp-tb-help'), r.help);
1677 Y.one('#fp-tb-help-'+client_id+'-link').set('href', r.help);
1679 print_path: function() {
1680 if (!this.pathbar) { return; }
1681 this.pathbar.setContent('').addClass('empty');
1682 var p = this.filepath;
1683 if (p && p.length!=0 && this.viewmode != 2) {
1684 for(var i = 0; i < p.length; i++) {
1685 var el = this.pathnode.cloneNode(true);
1686 this.pathbar.appendChild(el);
1687 if (i == 0) {el.addClass('first');}
1688 if (i == p.length-1) {el.addClass('last');}
1689 if (i%2) {el.addClass('even');} else {el.addClass('odd');}
1690 el.all('.fp-path-folder-name').setContent(p[i].name);
1694 this.list({'path':path});
1698 this.pathbar.removeClass('empty');
1702 this.selectui.hide();
1703 if (this.process_dlg) {
1704 this.process_dlg.hide();
1707 this.msg_dlg.hide();
1715 this.show_recent_repository();
1720 launch: function() {
1723 show_recent_repository: function() {
1725 this.viewbar_set_enabled(false);
1726 var repository_id = Y.Cookie.get('recentrepository');
1727 this.viewmode = Y.Cookie.get('recentviewmode', Number);
1728 if (this.viewmode != 2 && this.viewmode != 3) {
1731 if (this.options.repositories[repository_id]) {
1732 this.list({'repo_id':repository_id});
1736 var loading = Y.one('#filepicker-loading-'+options.client_id);
1738 loading.setStyle('display', 'none');
1740 M.core_filepicker.instances[options.client_id] = new FilePickerHelper(options);