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)
19 * this.currentpath, the current path in the repository (or last requested path)
23 * this.options.client_id, the instance id
24 * this.options.contextid
26 * this.options.repositories, stores all repositories displaied in file picker
27 * this.options.formcallback
29 * Active repository options
32 * this.active_repo.nosearch
33 * this.active_repo.norefresh
34 * this.active_repo.nologin
35 * this.active_repo.help
36 * this.active_repo.manage
40 * this.filelist, cached filelist
43 * this.filepath, current path (each element of the array is a part of the breadcrumb)
44 * this.logindata, cached login form
47 YUI.add('moodle-core_filepicker', function(Y) {
48 /** help function to extract width/height style as a number, not as a string */
49 Y.Node.prototype.getStylePx = function(attr) {
50 var style = this.getStyle(attr);
51 if (''+style == '0' || ''+style == '0px') {
54 var matches = style.match(/^([\d\.]+)px$/)
55 if (matches && parseFloat(matches[1])) {
56 return parseFloat(matches[1]);
61 /** if condition is met, the class is added to the node, otherwise - removed */
62 Y.Node.prototype.addClassIf = function(className, condition) {
64 this.addClass(className);
66 this.removeClass(className);
71 /** sets the width(height) of the node considering existing minWidth(minHeight) */
72 Y.Node.prototype.setStyleAdv = function(stylename, value) {
73 var stylenameCap = stylename.substr(0,1).toUpperCase() + stylename.substr(1, stylename.length-1).toLowerCase();
74 this.setStyle(stylename, '' + Math.max(value, this.getStylePx('min'+stylenameCap)) + 'px')
78 /** set image source to src, if there is preview, remember it in lazyloading.
79 * If there is a preview and it was already loaded, use it. */
80 Y.Node.prototype.setImgSrc = function(src, realsrc, lazyloading) {
82 if (M.core_filepicker.loadedpreviews[realsrc]) {
83 this.set('src', realsrc).addClass('realpreview');
86 if (!this.get('id')) {
89 lazyloading[this.get('id')] = realsrc;
97 * Replaces the image source with preview. If the image is inside the treeview, we need
98 * also to update the html property of corresponding YAHOO.widget.HTMLNode
99 * @param array lazyloading array containing associations of imgnodeid->realsrc
101 Y.Node.prototype.setImgRealSrc = function(lazyloading) {
102 if (this.get('id') && lazyloading[this.get('id')]) {
103 var newsrc = lazyloading[this.get('id')];
104 M.core_filepicker.loadedpreviews[newsrc] = true;
105 this.set('src', newsrc).addClass('realpreview');
106 delete lazyloading[this.get('id')];
107 var treenode = this.ancestor('.fp-treeview')
108 if (treenode && treenode.get('parentNode').treeview) {
109 treenode.get('parentNode').treeview.getRoot().refreshPreviews(this.get('id'), newsrc);
115 /** scan TreeView to find which node contains image with id=imgid and replace it's html
116 * with the new image source. */
117 YAHOO.widget.Node.prototype.refreshPreviews = function(imgid, newsrc, regex) {
119 regex = new RegExp("<img\\s[^>]*id=\""+imgid+"\"[^>]*?(/?)>", "im");
121 if (this.expanded || this.isLeaf) {
122 var html = this.getContentHtml();
123 if (html && this.setHtml && regex.test(html)) {
124 var newhtml = this.html.replace(regex, "<img id=\""+imgid+"\" src=\""+newsrc+"\" class=\"realpreview\"$1>", html);
125 this.setHtml(newhtml);
128 if (!this.isLeaf && this.children) {
129 for(var c in this.children) {
130 if (this.children[c].refreshPreviews(imgid, newsrc, regex)) {
140 * Displays a list of files (used by filepicker, filemanager) inside the Node
142 * @param array options
143 * viewmode : 1 - icons, 2 - tree, 3 - table
144 * appendonly : whether fileslist need to be appended instead of replacing the existing content
145 * filenode : Node element that contains template for displaying one file
146 * callback : On click callback. The element of the fileslist array will be passed as argument
147 * rightclickcallback : On right click callback (optional).
148 * callbackcontext : context where callbacks are executed
149 * sortable : whether content may be sortable (in table mode)
150 * dynload : allow dynamic load for tree view
151 * filepath : for pre-building of tree view - the path to the current directory in filepicker format
152 * treeview_dynload : callback to function to dynamically load the folder in tree view
153 * classnamecallback : callback to function that returns the class name for an element
154 * @param array fileslist array of files to show, each array element may have attributes:
155 * title or fullname : file name
156 * shorttitle (optional) : display file name
157 * thumbnail : url of image
158 * icon : url of icon image
159 * thumbnail_width : width of thumbnail, default 90
160 * thumbnail_height : height of thumbnail, default 90
161 * thumbnail_alt : TODO not needed!
162 * description or thumbnail_title : alt text
163 * @param array lazyloading : reference to the array with lazy loading images
165 Y.Node.prototype.fp_display_filelist = function(options, fileslist, lazyloading) {
166 var viewmodeclassnames = {1:'fp-iconview', 2:'fp-treeview', 3:'fp-tableview'};
167 var classname = viewmodeclassnames[options.viewmode];
169 /** return whether file is a folder (different attributes in FileManager and FilePicker) */
170 var file_is_folder = function(node) {
171 if (node.children) {return true;}
172 if (node.type && node.type == 'folder') {return true;}
175 /** return the name of the file (different attributes in FileManager and FilePicker) */
176 var file_get_filename = function(node) {
177 return node.title ? node.title : node.fullname;
179 /** return display name of the file (different attributes in FileManager and FilePicker) */
180 var file_get_displayname = function(node) {
181 var displayname = node.shorttitle ? node.shorttitle : file_get_filename(node);
182 return Y.Escape.html(displayname);
184 /** return file description (different attributes in FileManager and FilePicker) */
185 var file_get_description = function(node) {
186 var description = '';
187 if (node.description) {
188 description = node.description;
189 } else if (node.thumbnail_title) {
190 description = node.thumbnail_title;
192 description = file_get_filename(node);
194 return Y.Escape.html(description);
196 /** help funciton for tree view */
197 var build_tree = function(node, level) {
198 // prepare file name with icon
199 var el = Y.Node.create('<div/>');
200 el.appendChild(options.filenode.cloneNode(true));
202 el.one('.fp-filename').setContent(file_get_displayname(node));
203 // TODO add tooltip with node.title or node.thumbnail_title
204 var tmpnodedata = {className:options.classnamecallback(node)};
205 el.get('children').addClass(tmpnodedata.className);
207 el.one('.fp-icon').appendChild(Y.Node.create('<img/>'));
208 el.one('.fp-icon img').setImgSrc(node.icon, node.realicon, lazyloading);
211 tmpnodedata.html = el.getContent();
212 var tmpNode = new YAHOO.widget.HTMLNode(tmpnodedata, level, false);
213 if (node.dynamicLoadComplete) {
214 tmpNode.dynamicLoadComplete = true;
216 tmpNode.fileinfo = node;
217 tmpNode.isLeaf = !file_is_folder(node);
218 if (!tmpNode.isLeaf) {
222 tmpNode.path = node.path ? node.path : (node.filepath ? node.filepath : '');
223 for(var c in node.children) {
224 build_tree(node.children[c], tmpNode);
228 /** initialize tree view */
229 var initialize_tree_view = function() {
230 var parentid = scope.one('.'+classname).get('id');
231 // TODO MDL-32736 use YUI3 gallery TreeView
232 scope.treeview = new YAHOO.widget.TreeView(parentid);
233 if (options.dynload) {
234 scope.treeview.setDynamicLoad(Y.bind(options.treeview_dynload, options.callbackcontext), 1);
236 scope.treeview.singleNodeHighlight = true;
237 if (options.filepath && options.filepath.length) {
238 // we just jumped from icon/details view, we need to show all parents
239 // we extract as much information as possible from filepath and filelist
240 // and send additional requests to retrieve siblings for parent folders
243 for (var i in options.filepath) {
244 if (mytreeel == null) {
247 mytreeel.children = [{}];
248 mytreeel = mytreeel.children[0];
250 var pathelement = options.filepath[i];
251 mytreeel.path = pathelement.path;
252 mytreeel.title = pathelement.name;
253 mytreeel.icon = pathelement.icon;
254 mytreeel.dynamicLoadComplete = true; // we will call it manually
255 mytreeel.expanded = true;
257 mytreeel.children = fileslist;
258 build_tree(mytree, scope.treeview.getRoot());
259 // manually call dynload for parent elements in the tree so we can load other siblings
260 if (options.dynload) {
261 var root = scope.treeview.getRoot();
262 while (root && root.children && root.children.length) {
263 root = root.children[0];
264 if (root.path == mytreeel.path) {
265 root.origpath = options.filepath;
266 root.origlist = fileslist;
267 } else if (!root.isLeaf && root.expanded) {
268 Y.bind(options.treeview_dynload, options.callbackcontext)(root, null);
273 // there is no path information, just display all elements as a list, without hierarchy
274 for(k in fileslist) {
275 build_tree(fileslist[k], scope.treeview.getRoot());
278 scope.treeview.subscribe('clickEvent', function(e){
279 e.node.highlight(false);
280 var callback = options.callback;
281 if (options.rightclickcallback && e.event.target &&
282 Y.Node(e.event.target).ancestor('.fp-treeview .fp-contextmenu', true)) {
283 callback = options.rightclickcallback;
285 Y.bind(callback, options.callbackcontext)(e, e.node.fileinfo);
286 YAHOO.util.Event.stopEvent(e.event)
288 // TODO MDL-32736 support right click
289 /*if (options.rightclickcallback) {
290 scope.treeview.subscribe('dblClickEvent', function(e){
291 e.node.highlight(false);
292 Y.bind(options.rightclickcallback, options.callbackcontext)(e, e.node.fileinfo);
295 scope.treeview.draw();
297 /** formatting function for table view */
298 var formatValue = function (o){
299 if (o.data[''+o.column.key+'_f_s']) {return o.data[''+o.column.key+'_f_s'];}
300 else if (o.data[''+o.column.key+'_f']) {return o.data[''+o.column.key+'_f'];}
301 else if (o.value) {return o.value;}
304 /** formatting function for table view */
305 var formatTitle = function(o) {
306 var el = Y.Node.create('<div/>');
307 el.appendChild(options.filenode.cloneNode(true)); // TODO not node but string!
308 el.get('children').addClass(o.data['classname']);
309 el.one('.fp-filename').setContent(o.value);
310 if (o.data['icon']) {
311 el.one('.fp-icon').appendChild(Y.Node.create('<img/>'));
312 el.one('.fp-icon img').setImgSrc(o.data['icon'], o.data['realicon'], lazyloading);
314 if (options.rightclickcallback) {
315 el.get('children').addClass('fp-hascontextmenu');
317 // TODO add tooltip with o.data['title'] (o.value) or o.data['thumbnail_title']
318 return el.getContent();
320 /** sorting function for table view */
321 var sortFoldersFirst = function(a, b, desc) {
322 if (a.get('isfolder') && !b.get('isfolder')) {
325 if (!a.get('isfolder') && b.get('isfolder')) {
328 var aa = a.get(this.key), bb = b.get(this.key), dir = desc ? -1 : 1;
329 return (aa > bb) ? dir : ((aa < bb) ? -dir : 0);
331 /** initialize table view */
332 var initialize_table_view = function() {
334 {key: "displayname", label: M.str.moodle.name, allowHTML: true, formatter: formatTitle,
335 sortable: true, sortFn: sortFoldersFirst},
336 {key: "datemodified", label: M.str.moodle.lastmodified, allowHTML: true, formatter: formatValue,
337 sortable: true, sortFn: sortFoldersFirst},
338 {key: "size", label: M.str.repository.size, allowHTML: true, formatter: formatValue,
339 sortable: true, sortFn: sortFoldersFirst},
340 {key: "mimetype", label: M.str.repository.type, allowHTML: true,
341 sortable: true, sortFn: sortFoldersFirst}
343 for (var k in fileslist) {
344 // to speed up sorting and formatting
345 fileslist[k].displayname = file_get_displayname(fileslist[k]);
346 fileslist[k].isfolder = file_is_folder(fileslist[k]);
347 fileslist[k].classname = options.classnamecallback(fileslist[k]);
349 scope.tableview = new Y.DataTable({columns: cols, data: fileslist});
350 scope.tableview.delegate('click', function (e, tableview) {
351 var record = tableview.getRecord(e.currentTarget.get('id'));
353 var callback = options.callback;
354 if (options.rightclickcallback && e.target.ancestor('.fp-tableview .fp-contextmenu', true)) {
355 callback = options.rightclickcallback;
357 Y.bind(callback, this)(e, record.getAttrs());
359 }, 'tr', options.callbackcontext, scope.tableview);
360 if (options.rightclickcallback) {
361 scope.tableview.delegate('contextmenu', function (e, tableview) {
362 var record = tableview.getRecord(e.currentTarget.get('id'));
363 if (record) { Y.bind(options.rightclickcallback, this)(e, record.getAttrs()); }
364 }, 'tr', options.callbackcontext, scope.tableview);
367 /** append items in table view mode */
368 var append_files_table = function() {
369 var parentnode = scope.one('.'+classname);
370 scope.tableview.render(parentnode);
371 scope.tableview.sortable = options.sortable ? true : false;
373 /** append items in tree view mode */
374 var append_files_tree = function() {
375 if (options.appendonly) {
376 var parentnode = scope.treeview.getRoot();
377 if (scope.treeview.getHighlightedNode()) {
378 parentnode = scope.treeview.getHighlightedNode();
379 if (parentnode.isLeaf) {parentnode = parentnode.parent;}
381 for (var k in fileslist) {
382 build_tree(fileslist[k], parentnode);
384 scope.treeview.draw();
386 // otherwise files were already added in initialize_tree_view()
389 /** append items in icon view mode */
390 var append_files_icons = function() {
391 parent = scope.one('.'+classname);
392 for (var k in fileslist) {
393 var node = fileslist[k];
394 var element = options.filenode.cloneNode(true);
395 parent.appendChild(element);
396 element.addClass(options.classnamecallback(node));
397 var filenamediv = element.one('.fp-filename');
398 filenamediv.setContent(file_get_displayname(node));
399 var imgdiv = element.one('.fp-thumbnail'), width, height, src;
400 if (node.thumbnail) {
401 width = node.thumbnail_width ? node.thumbnail_width : 90;
402 height = node.thumbnail_height ? node.thumbnail_height : 90;
403 src = node.thumbnail;
409 filenamediv.setStyleAdv('width', width);
410 imgdiv.setStyleAdv('width', width).setStyleAdv('height', height);
411 var img = Y.Node.create('<img/>').setAttrs({
412 title: file_get_description(node),
413 alt: Y.Escape.html(node.thumbnail_alt ? node.thumbnail_alt : file_get_filename(node))}).
414 setStyle('maxWidth', ''+width+'px').
415 setStyle('maxHeight', ''+height+'px');
416 img.setImgSrc(src, node.realthumbnail, lazyloading);
417 imgdiv.appendChild(img);
418 element.on('click', function(e, nd) {
419 if (options.rightclickcallback && e.target.ancestor('.fp-iconview .fp-contextmenu', true)) {
420 Y.bind(options.rightclickcallback, this)(e, nd);
422 Y.bind(options.callback, this)(e, nd);
424 }, options.callbackcontext, node);
425 if (options.rightclickcallback) {
426 element.on('contextmenu', options.rightclickcallback, options.callbackcontext, node);
431 // initialize files view
432 if (!options.appendonly) {
433 var parent = Y.Node.create('<div/>').addClass(classname);
434 this.setContent('').appendChild(parent);
436 if (options.viewmode == 2) {
437 initialize_tree_view();
438 } else if (options.viewmode == 3) {
439 initialize_table_view();
441 // nothing to initialize for icon view
445 // append files to the list
446 if (options.viewmode == 2) {
448 } else if (options.viewmode == 3) {
449 append_files_table();
451 append_files_icons();
457 * creates a node and adds it to the div with id #filesskin. This is needed for CSS to be able
458 * to overwrite YUI skin styles (instead of using !important that does not work in IE)
460 Y.Node.createWithFilesSkin = function(node) {
461 if (!Y.one('#filesskin')) {
462 Y.one(document.body).appendChild(Y.Node.create('<div/>').set('id', 'filesskin'));
464 return Y.one('#filesskin').appendChild(Y.Node.create(node));
467 requires:['base', 'node', 'yui2-treeview', 'panel', 'cookie', 'datatable', 'datatable-sort']
470 M.core_filepicker = M.core_filepicker || {};
473 * instances of file pickers used on page
475 M.core_filepicker.instances = M.core_filepicker.instances || {};
476 M.core_filepicker.active_filepicker = null;
479 * HTML Templates to use in FilePicker
481 M.core_filepicker.templates = M.core_filepicker.templates || {};
484 * Array of image sources for real previews (realicon or realthumbnail) that are already loaded
486 M.core_filepicker.loadedpreviews = M.core_filepicker.loadedpreviews || {};
489 * Set selected file info
491 * @parma object file info
493 M.core_filepicker.select_file = function(file) {
494 M.core_filepicker.active_filepicker.select_file(file);
498 * Init and show file picker
500 M.core_filepicker.show = function(Y, options) {
501 if (!M.core_filepicker.instances[options.client_id]) {
502 M.core_filepicker.init(Y, options);
504 M.core_filepicker.instances[options.client_id].show();
507 M.core_filepicker.set_templates = function(Y, templates) {
508 for (var templid in templates) {
509 M.core_filepicker.templates[templid] = templates[templid];
514 * Add new file picker to current instances
516 M.core_filepicker.init = function(Y, options) {
517 var FilePickerHelper = function(options) {
518 FilePickerHelper.superclass.constructor.apply(this, arguments);
521 FilePickerHelper.NAME = "FilePickerHelper";
522 FilePickerHelper.ATTRS = {
527 Y.extend(FilePickerHelper, Y.Base, {
528 api: M.cfg.wwwroot+'/repository/repository_ajax.php',
529 cached_responses: {},
530 waitinterval : null, // When the loading template is being displayed and its animation is running this will be an interval instance.
531 initializer: function(options) {
532 this.options = options;
533 if (!this.options.savepath) {
534 this.options.savepath = '/';
538 destructor: function() {
541 request: function(args, redraw) {
542 var api = (args.api ? args.api : this.api) + '?action='+args.action;
544 var scope = args['scope'] ? args['scope'] : this;
545 params['repo_id']=args.repository_id;
546 params['p'] = args.path?args.path:'';
547 params['page'] = args.page?args.page:'';
548 params['env']=this.options.env;
549 // the form element only accept certain file types
550 params['accepted_types']=this.options.accepted_types;
551 params['sesskey'] = M.cfg.sesskey;
552 params['client_id'] = args.client_id;
553 params['itemid'] = this.options.itemid?this.options.itemid:0;
554 params['maxbytes'] = this.options.maxbytes?this.options.maxbytes:-1;
555 if (this.options.context && this.options.context.id) {
556 params['ctx_id'] = this.options.context.id;
558 if (args['params']) {
559 for (i in args['params']) {
560 params[i] = args['params'][i];
563 if (args.action == 'upload') {
565 for(var k in params) {
566 var value = params[k];
567 if(value instanceof Array) {
568 for(var i in value) {
569 list.push(k+'[]='+value[i]);
572 list.push(k+'='+value);
575 params = list.join('&');
577 params = build_querystring(params);
582 complete: function(id,o,p) {
590 data = Y.JSON.parse(o.responseText);
592 scope.print_msg(M.str.repository.invalidjson, 'error');
593 scope.display_error(M.str.repository.invalidjson+'<pre>'+stripHTML(o.responseText)+'</pre>', 'invalidjson')
597 if (data && data.error) {
598 scope.print_msg(data.error, 'error');
600 args.onerror(id,data,p);
602 this.fpnode.one('.fp-content').setContent('');
607 scope.print_msg(data.msg, 'info');
609 // cache result if applicable
610 if (args.action != 'upload' && data.allowcaching) {
611 scope.cached_responses[params] = data;
614 args.callback(id,data,p);
622 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
628 cfg.form = args.form;
630 // check if result of the same request has been already cached. If not, request it
631 // (never applicable in case of form submission and/or upload action):
632 if (!args.form && args.action != 'upload' && scope.cached_responses[params]) {
633 args.callback(null, scope.cached_responses[params], {scope: scope})
641 /** displays the dialog and processes rename/overwrite if there is a file with the same name in the same filearea*/
642 process_existing_file: function(data) {
644 var handleOverwrite = function(e) {
647 var data = this.process_dlg.dialogdata;
649 params['existingfilename'] = data.existingfile.filename;
650 params['existingfilepath'] = data.existingfile.filepath;
651 params['newfilename'] = data.newfile.filename;
652 params['newfilepath'] = data.newfile.filepath;
657 'action':'overwrite',
659 'client_id': this.options.client_id,
660 'repository_id': this.active_repo.id,
661 'callback': function(id, o, args) {
663 // editor needs to update url
664 // filemanager do nothing
665 if (scope.options.editor_target && scope.options.env == 'editor') {
666 scope.options.editor_target.value = data.existingfile.url;
667 scope.options.editor_target.onchange();
668 } else if (scope.options.env === 'filepicker') {
669 var fileinfo = {'client_id':scope.options.client_id,
670 'url':data.existingfile.url,
671 'file':data.existingfile.filename};
672 var formcallback_scope = scope.options.magicscope ? scope.options.magicscope : scope;
673 scope.options.formcallback.apply(formcallback_scope, [fileinfo]);
678 var handleRename = function(e) {
679 // inserts file with the new name
682 var data = this.process_dlg.dialogdata;
683 if (scope.options.editor_target && scope.options.env == 'editor') {
684 scope.options.editor_target.value = data.newfile.url;
685 scope.options.editor_target.onchange();
688 var formcallback_scope = scope.options.magicscope ? scope.options.magicscope : scope;
689 var fileinfo = {'client_id':scope.options.client_id,
690 'url':data.newfile.url,
691 'file':data.newfile.filename};
692 scope.options.formcallback.apply(formcallback_scope, [fileinfo]);
694 var handleCancel = function(e) {
698 params['newfilename'] = this.process_dlg.dialogdata.newfile.filename;
699 params['newfilepath'] = this.process_dlg.dialogdata.newfile.filepath;
703 'action':'deletetmpfile',
705 'client_id': this.options.client_id,
706 'repository_id': this.active_repo.id,
707 'callback': function(id, o, args) {
708 // let it be in background, from user point of view nothing is happenning
711 this.process_dlg.hide();
712 this.selectui.hide();
714 if (!this.process_dlg) {
715 this.process_dlg_node = Y.Node.createWithFilesSkin(M.core_filepicker.templates.processexistingfile);
716 var node = this.process_dlg_node;
718 this.process_dlg = new Y.Panel({
720 headerContent: M.str.repository.fileexistsdialogheader,
728 this.process_dlg.plug(Y.Plugin.Drag,{handles:['#'+node.get('id')+' .yui3-widget-hd']});
729 node.one('.fp-dlg-butoverwrite').on('click', handleOverwrite, this);
730 node.one('.fp-dlg-butrename').on('click', handleRename, this);
731 node.one('.fp-dlg-butcancel').on('click', handleCancel, this);
732 if (this.options.env == 'editor') {
733 node.one('.fp-dlg-text').setContent(M.str.repository.fileexistsdialog_editor);
735 node.one('.fp-dlg-text').setContent(M.str.repository.fileexistsdialog_filemanager);
738 this.selectnode.removeClass('loading');
739 this.process_dlg.dialogdata = data;
740 this.process_dlg_node.one('.fp-dlg-butrename').setContent(M.util.get_string('renameto', 'repository', data.newfile.filename));
741 this.process_dlg.show();
743 /** displays error instead of filepicker contents */
744 display_error: function(errortext, errorcode) {
745 this.fpnode.one('.fp-content').setContent(M.core_filepicker.templates.error);
746 this.fpnode.one('.fp-content .fp-error').
748 setContent(Y.Escape.html(errortext));
750 /** displays message in a popup */
751 print_msg: function(msg, type) {
752 var header = M.str.moodle.error;
753 if (type != 'error') {
754 type = 'info'; // one of only two types excepted
755 header = M.str.moodle.info;
758 this.msg_dlg_node = Y.Node.createWithFilesSkin(M.core_filepicker.templates.message);
759 this.msg_dlg_node.generateID();
761 this.msg_dlg = new Y.Panel({
762 srcNode : this.msg_dlg_node,
769 this.msg_dlg.plug(Y.Plugin.Drag,{handles:['#'+this.msg_dlg_node.get('id')+' .yui3-widget-hd']});
770 this.msg_dlg_node.one('.fp-msg-butok').on('click', function(e) {
776 this.msg_dlg.set('headerContent', header);
777 this.msg_dlg_node.removeClass('fp-msg-info').removeClass('fp-msg-error').addClass('fp-msg-'+type)
778 this.msg_dlg_node.one('.fp-msg-text').setContent(Y.Escape.html(msg));
781 view_files: function(appenditems) {
782 this.viewbar_set_enabled(true);
784 /*if ((appenditems == null) && (!this.filelist || !this.filelist.length) && !this.active_repo.hasmorepages) {
785 // TODO do it via classes and adjust for each view mode!
786 // If there are no items and no next page, just display status message and quit
787 this.display_error(M.str.repository.nofilesavailable, 'nofilesavailable');
790 if (this.viewmode == 2) {
791 this.view_as_list(appenditems);
792 } else if (this.viewmode == 3) {
793 this.view_as_table(appenditems);
795 this.view_as_icons(appenditems);
797 // display/hide the link for requesting next page
798 if (!appenditems && this.active_repo.hasmorepages) {
799 if (!this.fpnode.one('.fp-content .fp-nextpage')) {
800 this.fpnode.one('.fp-content').append(M.core_filepicker.templates.nextpage);
802 this.fpnode.one('.fp-content .fp-nextpage').one('a,button').on('click', function(e) {
804 this.fpnode.one('.fp-content .fp-nextpage').addClass('loading');
805 this.request_next_page();
808 if (!this.active_repo.hasmorepages && this.fpnode.one('.fp-content .fp-nextpage')) {
809 this.fpnode.one('.fp-content .fp-nextpage').remove();
811 if (this.fpnode.one('.fp-content .fp-nextpage')) {
812 this.fpnode.one('.fp-content .fp-nextpage').removeClass('loading');
814 this.content_scrolled();
816 content_scrolled: function(e) {
817 setTimeout(Y.bind(function() {
818 if (this.processingimages) {
821 this.processingimages = true;
823 fpcontent = this.fpnode.one('.fp-content'),
824 fpcontenty = fpcontent.getY(),
825 fpcontentheight = fpcontent.getStylePx('height'),
826 nextpage = fpcontent.one('.fp-nextpage'),
827 is_node_visible = function(node) {
828 var offset = node.getY()-fpcontenty;
829 if (offset <= fpcontentheight && (offset >=0 || offset+node.getStylePx('height')>=0)) {
834 // automatically load next page when 'more' link becomes visible
835 if (nextpage && !nextpage.hasClass('loading') && is_node_visible(nextpage)) {
836 nextpage.one('a,button').simulate('click');
838 // replace src for visible images that need to be lazy-loaded
839 if (scope.lazyloading) {
840 fpcontent.all('img').each( function(node) {
841 if (node.get('id') && scope.lazyloading[node.get('id')] && is_node_visible(node)) {
842 node.setImgRealSrc(scope.lazyloading);
846 this.processingimages = false;
849 treeview_dynload: function(node, cb) {
850 var retrieved_children = {};
852 for (var i in node.children) {
853 retrieved_children[node.children[i].path] = node.children[i];
858 client_id: this.options.client_id,
859 repository_id: this.active_repo.id,
860 path:node.path?node.path:'',
861 page:node.page?args.page:'',
863 callback: function(id, obj, args) {
865 var scope = args.scope;
866 // check that user did not leave the view mode before recieving this response
867 if (!(scope.active_repo.id == obj.repo_id && scope.viewmode == 2 && node && node.getChildrenEl())) {
870 if (cb != null) { // (in manual mode do not update current path)
871 scope.viewbar_set_enabled(true);
872 scope.parse_repository_options(obj);
874 node.highlight(false);
875 node.origlist = obj.list ? obj.list : null;
876 node.origpath = obj.path ? obj.path : null;
879 if (list[k].children && retrieved_children[list[k].path]) {
880 // if this child is a folder and has already been retrieved
881 node.children[node.children.length] = retrieved_children[list[k].path];
883 // append new file to the list
884 scope.view_as_list([list[k]]);
890 // invoke callback requested by TreeView component
893 scope.content_scrolled();
897 classnamecallback : function(node) {
900 classname = classname + ' fp-folder';
903 classname = classname + ' fp-isreference';
906 classname = classname + ' fp-hasreferences';
908 if (node.originalmissing) {
909 classname = classname + ' fp-originalmissing';
911 return Y.Lang.trim(classname);
913 /** displays list of files in tree (list) view mode. If param appenditems is specified,
914 * appends those items to the end of the list. Otherwise (default behaviour)
915 * clears the contents and displays the items from this.filelist */
916 view_as_list: function(appenditems) {
917 var list = (appenditems != null) ? appenditems : this.filelist;
919 if (!this.filelist || this.filelist.length==0 && (!this.filepath || !this.filepath.length)) {
920 this.display_error(M.str.repository.nofilesavailable, 'nofilesavailable');
924 var element_template = Y.Node.create(M.core_filepicker.templates.listfilename);
926 viewmode : this.viewmode,
927 appendonly : (appenditems != null),
928 filenode : element_template,
929 callbackcontext : this,
930 callback : function(e, node) {
931 // TODO MDL-32736 e is not an event here but an object with properties 'event' and 'node'
932 if (!node.children) {
933 if (e.node.parent && e.node.parent.origpath) {
934 // set the current path
935 this.filepath = e.node.parent.origpath;
936 this.filelist = e.node.parent.origlist;
939 this.select_file(node);
941 // save current path and filelist (in case we want to jump to other viewmode)
942 this.filepath = e.node.origpath;
943 this.filelist = e.node.origlist;
944 this.currentpath = e.node.path;
946 this.content_scrolled();
949 classnamecallback : this.classnamecallback,
950 dynload : this.active_repo.dynload,
951 filepath : this.filepath,
952 treeview_dynload : this.treeview_dynload
954 this.fpnode.one('.fp-content').fp_display_filelist(options, list, this.lazyloading);
956 /** displays list of files in icon view mode. If param appenditems is specified,
957 * appends those items to the end of the list. Otherwise (default behaviour)
958 * clears the contents and displays the items from this.filelist */
959 view_as_icons: function(appenditems) {
961 var list = (appenditems != null) ? appenditems : this.filelist;
962 var element_template = Y.Node.create(M.core_filepicker.templates.iconfilename);
963 if ((appenditems == null) && (!this.filelist || !this.filelist.length)) {
964 this.display_error(M.str.repository.nofilesavailable, 'nofilesavailable');
968 viewmode : this.viewmode,
969 appendonly : (appenditems != null),
970 filenode : element_template,
971 callbackcontext : this,
972 callback : function(e, node) {
973 if (e.preventDefault) {
977 if (this.active_repo.dynload) {
978 this.list({'path':node.path});
980 this.filelist = node.children;
984 this.select_file(node);
987 classnamecallback : this.classnamecallback
989 this.fpnode.one('.fp-content').fp_display_filelist(options, list, this.lazyloading);
991 /** displays list of files in table view mode. If param appenditems is specified,
992 * appends those items to the end of the list. Otherwise (default behaviour)
993 * clears the contents and displays the items from this.filelist */
994 view_as_table: function(appenditems) {
996 var list = (appenditems != null) ? appenditems : this.filelist;
997 if (!appenditems && (!this.filelist || this.filelist.length==0) && !this.active_repo.hasmorepages) {
998 this.display_error(M.str.repository.nofilesavailable, 'nofilesavailable');
1001 var element_template = Y.Node.create(M.core_filepicker.templates.listfilename);
1003 viewmode : this.viewmode,
1004 appendonly : (appenditems != null),
1005 filenode : element_template,
1006 callbackcontext : this,
1007 sortable : !this.active_repo.hasmorepages,
1008 callback : function(e, node) {
1009 if (e.preventDefault) {e.preventDefault();}
1010 if (node.children) {
1011 if (this.active_repo.dynload) {
1012 this.list({'path':node.path});
1014 this.filelist = node.children;
1018 this.select_file(node);
1021 classnamecallback : this.classnamecallback
1023 this.fpnode.one('.fp-content').fp_display_filelist(options, list, this.lazyloading);
1025 /** If more than one page available, requests and displays the files from the next page */
1026 request_next_page: function() {
1027 if (!this.active_repo.hasmorepages || this.active_repo.nextpagerequested) {
1031 this.active_repo.nextpagerequested = true;
1032 var nextpage = this.active_repo.page+1;
1035 repo_id: this.active_repo.id
1037 var action = this.active_repo.issearchresult ? 'search' : 'list';
1039 path: this.currentpath,
1042 client_id: this.options.client_id,
1043 repository_id: args.repo_id,
1045 callback: function(id, obj, args) {
1046 var scope = args.scope;
1047 // Check that we are still in the same repository and are expecting this page. We have no way
1048 // to compare the requested page and the one returned, so we assume that if the last chunk
1049 // of the breadcrumb is similar, then we probably are on the same page.
1050 var samepage = true;
1051 if (obj.path && scope.filepath) {
1052 var pathbefore = scope.filepath[scope.filepath.length-1];
1053 var pathafter = obj.path[obj.path.length-1];
1054 if (pathbefore.path != pathafter.path) {
1058 if (scope.active_repo.hasmorepages && obj.list && obj.page &&
1059 obj.repo_id == scope.active_repo.id &&
1060 obj.page == scope.active_repo.page+1 && samepage) {
1061 scope.parse_repository_options(obj, true);
1062 scope.view_files(obj.list)
1067 select_file: function(args) {
1068 this.selectui.show();
1069 var client_id = this.options.client_id;
1070 var selectnode = this.selectnode;
1071 var return_types = this.options.repositories[this.active_repo.id].return_types;
1072 selectnode.removeClass('loading');
1073 selectnode.one('.fp-saveas input').set('value', args.title);
1075 var imgnode = Y.Node.create('<img/>').
1076 set('src', args.realthumbnail ? args.realthumbnail : args.thumbnail).
1077 setStyle('maxHeight', ''+(args.thumbnail_height ? args.thumbnail_height : 90)+'px').
1078 setStyle('maxWidth', ''+(args.thumbnail_width ? args.thumbnail_width : 90)+'px');
1079 selectnode.one('.fp-thumbnail').setContent('').appendChild(imgnode);
1081 // filelink is the array of file-link-types available for this repository in this env
1082 var filelinktypes = [2/*FILE_INTERNAL*/,1/*FILE_EXTERNAL*/,4/*FILE_REFERENCE*/];
1083 var filelink = {}, firstfilelink = null, filelinkcount = 0;
1084 for (var i in filelinktypes) {
1085 var allowed = (return_types & filelinktypes[i]) &&
1086 (this.options.return_types & filelinktypes[i]);
1087 if (filelinktypes[i] == 1/*FILE_EXTERNAL*/ && !this.options.externallink && this.options.env == 'editor') {
1088 // special configuration setting 'repositoryallowexternallinks' may prevent
1089 // using external links in editor environment
1092 filelink[filelinktypes[i]] = allowed;
1093 firstfilelink = (firstfilelink==null && allowed) ? filelinktypes[i] : firstfilelink;
1094 filelinkcount += allowed ? 1 : 0;
1096 // make radio buttons enabled if this file-link-type is available and only if there are more than one file-link-type option
1097 // check the first available file-link-type option
1098 for (var linktype in filelink) {
1099 var el = selectnode.one('.fp-linktype-'+linktype);
1100 el.addClassIf('uneditable', !(filelink[linktype] && filelinkcount>1));
1101 el.one('input').set('disabled', (filelink[linktype] && filelinkcount>1) ? '' : 'disabled').
1102 set('checked', (firstfilelink == linktype) ? 'checked' : '').simulate('change')
1105 // TODO MDL-32532: attributes 'hasauthor' and 'haslicense' need to be obsolete,
1106 selectnode.one('.fp-setauthor input').set('value', args.author ? args.author : this.options.author);
1107 this.set_selected_license(selectnode.one('.fp-setlicense'), args.license);
1108 selectnode.one('form #filesource-'+client_id).set('value', args.source);
1110 // display static information about a file (when known)
1111 var attrs = ['datemodified','datecreated','size','license','author','dimensions'];
1112 for (var i in attrs) {
1113 if (selectnode.one('.fp-'+attrs[i])) {
1114 var value = (args[attrs[i]+'_f']) ? args[attrs[i]+'_f'] : (args[attrs[i]] ? args[attrs[i]] : '');
1115 selectnode.one('.fp-'+attrs[i]).addClassIf('fp-unknown', ''+value == '')
1116 .one('.fp-value').setContent(Y.Escape.html(value));
1120 setup_select_file: function() {
1121 var client_id = this.options.client_id;
1122 var selectnode = this.selectnode;
1123 var getfile = selectnode.one('.fp-select-confirm');
1124 // bind labels with corresponding inputs
1125 selectnode.all('.fp-saveas,.fp-linktype-2,.fp-linktype-1,.fp-linktype-4,.fp-setauthor,.fp-setlicense').each(function (node) {
1126 node.all('label').set('for', node.one('input,select').generateID());
1128 selectnode.one('.fp-linktype-2 input').setAttrs({value: 2, name: 'linktype'});
1129 selectnode.one('.fp-linktype-1 input').setAttrs({value: 1, name: 'linktype'});
1130 selectnode.one('.fp-linktype-4 input').setAttrs({value: 4, name: 'linktype'});
1131 var changelinktype = function(e) {
1132 if (e.currentTarget.get('checked')) {
1133 var allowinputs = e.currentTarget.get('value') != 1/*FILE_EXTERNAL*/;
1134 selectnode.all('.fp-setauthor,.fp-setlicense,.fp-saveas').each(function(node){
1135 node.addClassIf('uneditable', !allowinputs);
1136 node.all('input,select').set('disabled', allowinputs?'':'disabled');
1140 selectnode.all('.fp-linktype-2,.fp-linktype-1,.fp-linktype-4').each(function (node) {
1141 node.one('input').on('change', changelinktype, this);
1143 this.populate_licenses_select(selectnode.one('.fp-setlicense select'));
1144 // register event on clicking submit button
1145 getfile.on('click', function(e) {
1147 var client_id = this.options.client_id;
1149 var repository_id = this.active_repo.id;
1150 var title = selectnode.one('.fp-saveas input').get('value');
1151 var filesource = selectnode.one('form #filesource-'+client_id).get('value');
1152 var params = {'title':title, 'source':filesource, 'savepath': this.options.savepath};
1153 var license = selectnode.one('.fp-setlicense select');
1155 params['license'] = license.get('value');
1156 var origlicense = selectnode.one('.fp-license .fp-value');
1158 origlicense = origlicense.getContent();
1160 this.set_preference('recentlicense', license.get('value'));
1162 params['author'] = selectnode.one('.fp-setauthor input').get('value');
1164 var return_types = this.options.repositories[this.active_repo.id].return_types;
1165 if (this.options.env == 'editor') {
1166 // in editor, images are stored in '/' only
1167 params.savepath = '/';
1169 if ((this.options.externallink || this.options.env != 'editor') &&
1170 (return_types & 1/*FILE_EXTERNAL*/) &&
1171 (this.options.return_types & 1/*FILE_EXTERNAL*/) &&
1172 selectnode.one('.fp-linktype-1 input').get('checked')) {
1173 params['linkexternal'] = 'yes';
1174 } else if ((return_types & 4/*FILE_REFERENCE*/) &&
1175 (this.options.return_types & 4/*FILE_REFERENCE*/) &&
1176 selectnode.one('.fp-linktype-4 input').get('checked')) {
1177 params['usefilereference'] = '1';
1180 selectnode.addClass('loading');
1183 client_id: client_id,
1184 repository_id: repository_id,
1186 onerror: function(id, obj, args) {
1187 selectnode.removeClass('loading');
1188 scope.selectui.hide();
1190 callback: function(id, obj, args) {
1191 selectnode.removeClass('loading');
1192 if (obj.event == 'fileexists') {
1193 scope.process_existing_file(obj);
1196 if (scope.options.editor_target && scope.options.env=='editor') {
1197 scope.options.editor_target.value=obj.url;
1198 scope.options.editor_target.onchange();
1201 obj.client_id = client_id;
1202 var formcallback_scope = args.scope.options.magicscope ? args.scope.options.magicscope : args.scope;
1203 scope.options.formcallback.apply(formcallback_scope, [obj]);
1207 var elform = selectnode.one('form');
1208 elform.appendChild(Y.Node.create('<input/>').
1209 setAttrs({type:'hidden',id:'filesource-'+client_id}));
1210 elform.on('keydown', function(e) {
1211 if (e.keyCode == 13) {
1212 getfile.simulate('click');
1216 var cancel = selectnode.one('.fp-select-cancel');
1217 cancel.on('click', function(e) {
1219 this.selectui.hide();
1223 // First check there isn't already an interval in play, and if there is kill it now.
1224 if (this.waitinterval != null) {
1225 clearInterval(this.waitinterval);
1227 // Prepare the root node we will set content for and the loading template we want to display as a YUI node.
1228 var root = this.fpnode.one('.fp-content');
1229 var content = Y.Node.create(M.core_filepicker.templates.loading).addClass('fp-content-hidden').setStyle('opacity', 0);
1231 // Initiate an interval, we will have a count which will increment every 100 milliseconds.
1232 // Count 0 - the loading icon will have visibility set to hidden (invisible) and have an opacity of 0 (invisible also)
1233 // Count 5 - the visiblity will be switched to visible but opacity will still be at 0 (inivisible)
1234 // Counts 6 - 15 opacity will be increased by 0.1 making the loading icon visible over the period of a second
1235 // Count 16 - The interval will be cancelled.
1236 var interval = setInterval(function(){
1237 if (!content || !root.contains(content) || count >= 15) {
1238 clearInterval(interval);
1242 content.removeClass('fp-content-hidden');
1243 } else if (count > 5) {
1244 var opacity = parseFloat(content.getStyle('opacity'));
1245 content.setStyle('opacity', opacity + 0.1);
1250 // Store the wait interval so that we can check it in the future.
1251 this.waitinterval = interval;
1252 // Set the content to the loading template.
1253 root.setContent(content);
1255 viewbar_set_enabled: function(mode) {
1256 var viewbar = this.fpnode.one('.fp-viewbar')
1259 viewbar.addClass('enabled').removeClass('disabled')
1261 viewbar.removeClass('enabled').addClass('disabled')
1264 this.fpnode.all('.fp-vb-icons,.fp-vb-tree,.fp-vb-details').removeClass('checked')
1265 var modes = {1:'icons', 2:'tree', 3:'details'};
1266 this.fpnode.all('.fp-vb-'+modes[this.viewmode]).addClass('checked');
1268 viewbar_clicked: function(e) {
1270 var viewbar = this.fpnode.one('.fp-viewbar')
1271 if (!viewbar || !viewbar.hasClass('disabled')) {
1272 if (e.currentTarget.hasClass('fp-vb-tree')) {
1274 } else if (e.currentTarget.hasClass('fp-vb-details')) {
1279 this.viewbar_set_enabled(true)
1281 this.set_preference('recentviewmode', this.viewmode);
1284 render: function() {
1285 var client_id = this.options.client_id;
1286 this.fpnode = Y.Node.createWithFilesSkin(M.core_filepicker.templates.generallayout).
1287 set('id', 'filepicker-'+client_id);
1288 this.mainui = new Y.Panel({
1289 srcNode : this.fpnode,
1290 headerContent: M.str.repository.filepicker,
1295 minWidth : this.fpnode.getStylePx('minWidth'),
1296 minHeight : this.fpnode.getStylePx('minHeight'),
1297 maxWidth : this.fpnode.getStylePx('maxWidth'),
1298 maxHeight : this.fpnode.getStylePx('maxHeight'),
1301 // allow to move the panel dragging it by it's header:
1302 this.mainui.plug(Y.Plugin.Drag,{handles:['#filepicker-'+client_id+' .yui3-widget-hd']});
1304 if (this.mainui.get('y') < 0) {
1305 this.mainui.set('y', 0);
1307 // create panel for selecting a file (initially hidden)
1308 this.selectnode = Y.Node.createWithFilesSkin(M.core_filepicker.templates.selectlayout).
1309 set('id', 'filepicker-select-'+client_id);
1310 this.selectui = new Y.Panel({
1311 srcNode : this.selectnode,
1318 // allow to move the panel dragging it by it's header:
1319 this.selectui.plug(Y.Plugin.Drag,{handles:['#filepicker-select-'+client_id+' .yui3-widget-hd']});
1320 this.selectui.hide();
1321 // event handler for lazy loading of thumbnails and next page
1322 this.fpnode.one('.fp-content').on(['scroll','resize'], this.content_scrolled, this);
1323 // save template for one path element and location of path bar
1324 if (this.fpnode.one('.fp-path-folder')) {
1325 this.pathnode = this.fpnode.one('.fp-path-folder');
1326 this.pathbar = this.pathnode.get('parentNode');
1327 this.pathbar.removeChild(this.pathnode);
1329 // assign callbacks for view mode switch buttons
1330 this.fpnode.all('.fp-vb-icons,.fp-vb-tree,.fp-vb-details').
1331 on('click', this.viewbar_clicked, this);
1332 // assign callbacks for toolbar links
1333 this.setup_toolbar();
1334 this.setup_select_file();
1337 // processing repository listing
1338 // Resort the repositories by sortorder
1339 var sorted_repositories = [];
1340 for (var i in this.options.repositories) {
1341 sorted_repositories[i] = this.options.repositories[i];
1343 sorted_repositories.sort(function(a,b){return a.sortorder-b.sortorder});
1344 // extract one repository template and repeat it for all repositories available,
1345 // set name and icon and assign callbacks
1346 var reponode = this.fpnode.one('.fp-repo');
1348 var list = reponode.get('parentNode');
1349 list.removeChild(reponode);
1350 for (i in sorted_repositories) {
1351 var repository = sorted_repositories[i];
1352 var node = reponode.cloneNode(true);
1353 list.appendChild(node);
1355 set('id', 'fp-repo-'+client_id+'-'+repository.id).
1356 on('click', function(e, repository_id) {
1358 this.set_preference('recentrepository', repository_id);
1360 this.list({'repo_id':repository_id});
1361 }, this /*handler running scope*/, repository.id/*second argument of handler*/);
1362 node.one('.fp-repo-name').setContent(Y.Escape.html(repository.name));
1363 node.one('.fp-repo-icon').set('src', repository.icon);
1365 node.addClass('first');
1367 if (i==sorted_repositories.length-1) {
1368 node.addClass('last');
1371 node.addClass('even');
1373 node.addClass('odd');
1377 // display error if no repositories found
1378 if (sorted_repositories.length==0) {
1379 this.display_error(M.str.repository.norepositoriesavailable, 'norepositoriesavailable')
1381 // display repository that was used last time
1382 this.show_recent_repository();
1384 parse_repository_options: function(data, appendtolist) {
1387 if (!this.filelist) {
1390 for (var i in data.list) {
1391 this.filelist[this.filelist.length] = data.list[i];
1395 this.filelist = data.list?data.list:null;
1396 this.lazyloading = {};
1398 this.filepath = data.path?data.path:null;
1399 this.objecttag = data.object?data.object:null;
1400 this.active_repo = {};
1401 this.active_repo.issearchresult = data.issearchresult ? true : false;
1402 this.active_repo.dynload = data.dynload?data.dynload:false;
1403 this.active_repo.pages = Number(data.pages?data.pages:null);
1404 this.active_repo.page = Number(data.page?data.page:null);
1405 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))
1406 this.active_repo.id = data.repo_id?data.repo_id:null;
1407 this.active_repo.nosearch = (data.login || data.nosearch); // this is either login form or 'nosearch' attribute set
1408 this.active_repo.norefresh = (data.login || data.norefresh); // this is either login form or 'norefresh' attribute set
1409 this.active_repo.nologin = (data.login || data.nologin); // this is either login form or 'nologin' attribute is set
1410 this.active_repo.logouttext = data.logouttext?data.logouttext:null;
1411 this.active_repo.logouturl = (data.logouturl || '');
1412 this.active_repo.message = (data.message || '');
1413 this.active_repo.help = data.help?data.help:null;
1414 this.active_repo.manage = data.manage?data.manage:null;
1415 this.print_header();
1417 print_login: function(data) {
1418 this.parse_repository_options(data);
1419 var client_id = this.options.client_id;
1420 var repository_id = data.repo_id;
1421 var l = this.logindata = data.login;
1423 var action = data['login_btn_action'] ? data['login_btn_action'] : 'login';
1424 var form_id = 'fp-form-'+client_id;
1426 var loginform_node = Y.Node.create(M.core_filepicker.templates.loginform);
1427 loginform_node.one('form').set('id', form_id);
1428 this.fpnode.one('.fp-content').setContent('').appendChild(loginform_node);
1430 'popup' : loginform_node.one('.fp-login-popup'),
1431 'textarea' : loginform_node.one('.fp-login-textarea'),
1432 'select' : loginform_node.one('.fp-login-select'),
1433 'text' : loginform_node.one('.fp-login-text'),
1434 'radio' : loginform_node.one('.fp-login-radiogroup'),
1435 'checkbox' : loginform_node.one('.fp-login-checkbox'),
1436 'input' : loginform_node.one('.fp-login-input')
1439 for (var i in templates) {
1441 container = templates[i].get('parentNode');
1442 container.removeChild(templates[i]);
1447 if (templates[l[k].type]) {
1448 var node = templates[l[k].type].cloneNode(true);
1450 node = templates['input'].cloneNode(true);
1452 if (l[k].type == 'popup') {
1454 loginurl = l[k].url;
1455 var popupbutton = node.one('button');
1456 popupbutton.on('click', function(e){
1457 M.core_filepicker.active_filepicker = this;
1458 window.open(loginurl, 'repo_auth', 'location=0,status=0,width=500,height=300,scrollbars=yes');
1461 loginform_node.one('form').on('keydown', function(e) {
1462 if (e.keyCode == 13) {
1463 popupbutton.simulate('click');
1467 loginform_node.all('.fp-login-submit').remove();
1469 } else if(l[k].type=='textarea') {
1471 if (node.one('label')) {
1472 node.one('label').set('for', l[k].id).setContent(l[k].label);
1474 node.one('textarea').setAttrs({id:l[k].id, name:l[k].name});
1475 } else if(l[k].type=='select') {
1477 if (node.one('label')) {
1478 node.one('label').set('for', l[k].id).setContent(l[k].label);
1480 node.one('select').setAttrs({id:l[k].id, name:l[k].name}).setContent('');
1481 for (i in l[k].options) {
1482 node.one('select').appendChild(
1483 Y.Node.create('<option/>').
1484 set('value', l[k].options[i].value).
1485 setContent(l[k].options[i].label));
1487 } else if(l[k].type=='radio') {
1488 // radio input element
1489 node.all('label').setContent(l[k].label);
1490 var list = l[k].value.split('|');
1491 var labels = l[k].value_label.split('|');
1492 var radionode = null;
1493 for(var item in list) {
1494 if (radionode == null) {
1495 radionode = node.one('.fp-login-radio');
1496 radionode.one('input').set('checked', 'checked');
1498 var x = radionode.cloneNode(true);
1499 radionode.insert(x, 'after');
1501 radionode.one('input').set('checked', '');
1503 radionode.one('input').setAttrs({id:''+l[k].id+item, name:l[k].name,
1504 type:l[k].type, value:list[item]});
1505 radionode.all('label').setContent(labels[item]).set('for', ''+l[k].id+item)
1507 if (radionode == null) {
1508 node.one('.fp-login-radio').remove();
1512 if (node.one('label')) { node.one('label').set('for', l[k].id).setContent(l[k].label) }
1514 set('type', l[k].type).
1516 set('name', l[k].name).
1517 set('value', l[k].value?l[k].value:'')
1519 container.appendChild(node);
1521 // custom label text for submit button
1522 if (data['login_btn_label']) {
1523 loginform_node.all('.fp-login-submit').setContent(data['login_btn_label'])
1525 // register button action for login and search
1526 if (action == 'login' || action == 'search') {
1527 loginform_node.one('.fp-login-submit').on('click', function(e){
1532 'action':(action == 'search') ? 'search' : 'signin',
1534 'client_id': client_id,
1535 'repository_id': repository_id,
1536 'form': {id:form_id, upload:false, useDisabled:true},
1537 'callback': this.display_response
1541 // if 'Enter' is pressed in the form, simulate the button click
1542 if (loginform_node.one('.fp-login-submit')) {
1543 loginform_node.one('form').on('keydown', function(e) {
1544 if (e.keyCode == 13) {
1545 loginform_node.one('.fp-login-submit').simulate('click')
1551 display_response: function(id, obj, args) {
1552 var scope = args.scope
1553 // highlight the current repository in repositories list
1554 scope.fpnode.all('.fp-repo.active').removeClass('active');
1555 scope.fpnode.all('#fp-repo-'+scope.options.client_id+'-'+obj.repo_id).addClass('active')
1556 // add class repository_REPTYPE to the filepicker (for repository-specific styles)
1557 for (var i in scope.options.repositories) {
1558 scope.fpnode.removeClass('repository_'+scope.options.repositories[i].type)
1560 if (obj.repo_id && scope.options.repositories[obj.repo_id]) {
1561 scope.fpnode.addClass('repository_'+scope.options.repositories[obj.repo_id].type)
1565 scope.viewbar_set_enabled(false);
1566 scope.print_login(obj);
1567 } else if (obj.upload) {
1568 scope.viewbar_set_enabled(false);
1569 scope.parse_repository_options(obj);
1570 scope.create_upload_form(obj);
1571 } else if (obj.object) {
1572 M.core_filepicker.active_filepicker = scope;
1573 scope.viewbar_set_enabled(false);
1574 scope.parse_repository_options(obj);
1575 scope.create_object_container(obj.object);
1576 } else if (obj.list) {
1577 scope.viewbar_set_enabled(true);
1578 scope.parse_repository_options(obj);
1582 list: function(args) {
1586 if (!args.repo_id) {
1587 args.repo_id = this.active_repo.id;
1592 this.currentpath = args.path;
1595 client_id: this.options.client_id,
1596 repository_id: args.repo_id,
1600 callback: this.display_response
1603 populate_licenses_select: function(node) {
1607 node.setContent('');
1608 var licenses = this.options.licenses;
1609 var recentlicense = this.get_preference('recentlicense');
1610 if (recentlicense) {
1611 this.options.defaultlicense=recentlicense;
1613 for (var i in licenses) {
1614 var option = Y.Node.create('<option/>').
1615 set('selected', (this.options.defaultlicense==licenses[i].shortname)).
1616 set('value', licenses[i].shortname).
1617 setContent(Y.Escape.html(licenses[i].fullname));
1618 node.appendChild(option)
1621 set_selected_license: function(node, value) {
1622 var licenseset = false;
1623 node.all('option').each(function(el) {
1624 if (el.get('value')==value || el.getContent()==value) {
1625 el.set('selected', true);
1630 // we did not find the value in the list
1631 var recentlicense = this.get_preference('recentlicense');
1632 node.all('option[selected]').set('selected', false);
1633 node.all('option[value='+recentlicense+']').set('selected', true);
1636 create_object_container: function(data) {
1637 var content = this.fpnode.one('.fp-content');
1638 content.setContent('');
1639 //var str = '<object data="'+data.src+'" type="'+data.type+'" width="98%" height="98%" id="container_object" class="fp-object-container mdl-align"></object>';
1640 var container = Y.Node.create('<object/>').
1641 setAttrs({data:data.src, type:data.type, id:'container_object'}).
1642 addClass('fp-object-container');
1643 content.setContent('').appendChild(container);
1645 create_upload_form: function(data) {
1646 var client_id = this.options.client_id;
1647 var id = data.upload.id+'_'+client_id;
1648 var content = this.fpnode.one('.fp-content');
1649 var template_name = 'uploadform_'+this.options.repositories[data.repo_id].type;
1650 var template = M.core_filepicker.templates[template_name] || M.core_filepicker.templates['uploadform'];
1651 content.setContent(template);
1653 content.all('.fp-file,.fp-saveas,.fp-setauthor,.fp-setlicense').each(function (node) {
1654 node.all('label').set('for', node.one('input,select').generateID());
1656 content.one('form').set('id', id);
1657 content.one('.fp-file input').set('name', 'repo_upload_file');
1658 if (data.upload.label && content.one('.fp-file label')) {
1659 content.one('.fp-file label').setContent(data.upload.label);
1661 content.one('.fp-saveas input').set('name', 'title');
1662 content.one('.fp-setauthor input').setAttrs({name:'author', value:this.options.author});
1663 content.one('.fp-setlicense select').set('name', 'license');
1664 this.populate_licenses_select(content.one('.fp-setlicense select'))
1665 // append hidden inputs to the upload form
1666 content.one('form').appendChild(Y.Node.create('<input/>').
1667 setAttrs({type:'hidden',name:'itemid',value:this.options.itemid}));
1668 var types = this.options.accepted_types;
1669 for (var i in types) {
1670 content.one('form').appendChild(Y.Node.create('<input/>').
1671 setAttrs({type:'hidden',name:'accepted_types[]',value:types[i]}));
1675 content.one('.fp-upload-btn').on('click', function(e) {
1677 var license = content.one('.fp-setlicense select');
1679 this.set_preference('recentlicense', license.get('value'));
1680 if (!content.one('.fp-file input').get('value')) {
1681 scope.print_msg(M.str.repository.nofilesattached, 'error');
1688 client_id: client_id,
1689 params: {'savepath':scope.options.savepath},
1690 repository_id: scope.active_repo.id,
1691 form: {id: id, upload:true},
1692 onerror: function(id, o, args) {
1693 scope.create_upload_form(data);
1695 callback: function(id, o, args) {
1696 if (o.event == 'fileexists') {
1697 scope.create_upload_form(data);
1698 scope.process_existing_file(o);
1701 if (scope.options.editor_target&&scope.options.env=='editor') {
1702 scope.options.editor_target.value=o.url;
1703 scope.options.editor_target.onchange();
1706 o.client_id = client_id;
1707 var formcallback_scope = args.scope.options.magicscope ? args.scope.options.magicscope : args.scope;
1708 scope.options.formcallback.apply(formcallback_scope, [o]);
1713 /** setting handlers and labels for elements in toolbar. Called once during the initial render of filepicker */
1714 setup_toolbar: function() {
1715 var client_id = this.options.client_id;
1716 var toolbar = this.fpnode.one('.fp-toolbar');
1717 toolbar.one('.fp-tb-logout').one('a,button').on('click', function(e) {
1719 if (!this.active_repo.nologin) {
1723 client_id: this.options.client_id,
1724 repository_id: this.active_repo.id,
1726 callback: this.display_response
1729 if (this.active_repo.logouturl) {
1730 window.open(this.active_repo.logouturl, 'repo_auth', 'location=0,status=0,width=500,height=300,scrollbars=yes');
1733 toolbar.one('.fp-tb-refresh').one('a,button').on('click', function(e) {
1735 if (!this.active_repo.norefresh) {
1736 this.list({ path: this.currentpath });
1739 toolbar.one('.fp-tb-search form').
1740 set('method', 'POST').
1741 set('id', 'fp-tb-search-'+client_id).
1742 on('submit', function(e) {
1744 if (!this.active_repo.nosearch) {
1748 client_id: this.options.client_id,
1749 repository_id: this.active_repo.id,
1750 form: {id: 'fp-tb-search-'+client_id, upload:false, useDisabled:true},
1751 callback: this.display_response
1756 // it does not matter what kind of element is .fp-tb-manage, we create a dummy <a>
1757 // element and use it to open url on click event
1758 var managelnk = Y.Node.create('<a/>').
1759 setAttrs({id:'fp-tb-manage-'+client_id+'-link', target:'_blank'}).
1760 setStyle('display', 'none');
1761 toolbar.append(managelnk);
1762 toolbar.one('.fp-tb-manage').one('a,button').
1763 on('click', function(e) {
1765 managelnk.simulate('click')
1768 // same with .fp-tb-help
1769 var helplnk = Y.Node.create('<a/>').
1770 setAttrs({id:'fp-tb-help-'+client_id+'-link', target:'_blank'}).
1771 setStyle('display', 'none');
1772 toolbar.append(helplnk);
1773 toolbar.one('.fp-tb-help').one('a,button').
1774 on('click', function(e) {
1776 helplnk.simulate('click')
1779 hide_header: function() {
1780 if (this.fpnode.one('.fp-toolbar')) {
1781 this.fpnode.one('.fp-toolbar').addClass('empty');
1784 this.pathbar.setContent('').addClass('empty');
1787 print_header: function() {
1788 var r = this.active_repo;
1790 var client_id = this.options.client_id;
1793 var toolbar = this.fpnode.one('.fp-toolbar');
1794 if (!toolbar) { return; }
1796 var enable_tb_control = function(node, enabled) {
1797 if (!node) { return; }
1798 node.addClassIf('disabled', !enabled).addClassIf('enabled', enabled)
1800 toolbar.removeClass('empty');
1804 // TODO 'back' permanently disabled for now. Note, flickr_public uses 'Logout' for it!
1805 enable_tb_control(toolbar.one('.fp-tb-back'), false);
1808 enable_tb_control(toolbar.one('.fp-tb-search'), !r.nosearch);
1810 var searchform = toolbar.one('.fp-tb-search form');
1811 searchform.setContent('');
1814 action:'searchform',
1815 repository_id: this.active_repo.id,
1816 callback: function(id, obj, args) {
1817 if (obj.repo_id == scope.active_repo.id && obj.form) {
1818 // if we did not jump to another repository meanwhile
1819 searchform.setContent(obj.form);
1820 // Highlight search text when user click for search.
1821 var searchnode = searchform.one('input[name="s"]');
1823 searchnode.once('click', function(e) {
1834 // weather we use cache for this instance, this button will reload listing anyway
1835 enable_tb_control(toolbar.one('.fp-tb-refresh'), !r.norefresh);
1838 enable_tb_control(toolbar.one('.fp-tb-logout'), !r.nologin);
1840 var label = r.logouttext ? r.logouttext : M.str.repository.logout;
1841 toolbar.one('.fp-tb-logout').one('a,button').setContent(label)
1845 enable_tb_control(toolbar.one('.fp-tb-manage'), r.manage);
1846 Y.one('#fp-tb-manage-'+client_id+'-link').set('href', r.manage);
1849 enable_tb_control(toolbar.one('.fp-tb-help'), r.help);
1850 Y.one('#fp-tb-help-'+client_id+'-link').set('href', r.help);
1853 if (toolbar.one('.fp-tb-message')) {
1854 enable_tb_control(toolbar.one('.fp-tb-message'), r.message);
1855 toolbar.one('.fp-tb-message').setContent(r.message);
1858 print_path: function() {
1859 if (!this.pathbar) {
1862 this.pathbar.setContent('').addClass('empty');
1863 var p = this.filepath;
1864 if (p && p.length!=0 && this.viewmode != 2) {
1865 for(var i = 0; i < p.length; i++) {
1866 var el = this.pathnode.cloneNode(true);
1867 this.pathbar.appendChild(el);
1869 el.addClass('first');
1871 if (i == p.length-1) {
1872 el.addClass('last');
1875 el.addClass('even');
1879 el.all('.fp-path-folder-name').setContent(Y.Escape.html(p[i].name));
1883 this.list({'path':path});
1887 this.pathbar.removeClass('empty');
1891 this.selectui.hide();
1892 if (this.process_dlg) {
1893 this.process_dlg.hide();
1896 this.msg_dlg.hide();
1904 this.show_recent_repository();
1909 launch: function() {
1912 show_recent_repository: function() {
1914 this.viewbar_set_enabled(false);
1915 var repository_id = this.get_preference('recentrepository');
1916 this.viewmode = this.get_preference('recentviewmode');
1917 if (this.viewmode != 2 && this.viewmode != 3) {
1920 if (this.options.repositories[repository_id]) {
1921 this.list({'repo_id':repository_id});
1924 get_preference: function (name) {
1925 if (this.options.userprefs[name]) {
1926 return this.options.userprefs[name];
1931 set_preference: function(name, value) {
1932 if (this.options.userprefs[name] != value) {
1933 M.util.set_user_preference('filepicker_' + name, value);
1934 this.options.userprefs[name] = value;
1938 var loading = Y.one('#filepicker-loading-'+options.client_id);
1940 loading.setStyle('display', 'none');
1942 M.core_filepicker.instances[options.client_id] = new FilePickerHelper(options);