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 Y.YUI2.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 return node.shorttitle ? node.shorttitle : file_get_filename(node);
183 /** return file description (different attributes in FileManager and FilePicker) */
184 var file_get_description = function(node) {
185 return node.description ? node.description : (node.thumbnail_title ? node.thumbnail_title : file_get_filename(node));
187 /** help funciton for tree view */
188 var build_tree = function(node, level) {
189 // prepare file name with icon
190 var el = Y.Node.create('<div/>');
191 el.appendChild(options.filenode.cloneNode(true));
193 el.one('.fp-filename').setContent(file_get_displayname(node));
194 // TODO add tooltip with node.title or node.thumbnail_title
195 var tmpnodedata = {className:options.classnamecallback(node)};
196 el.get('children').addClass(tmpnodedata.className);
198 el.one('.fp-icon').appendChild(Y.Node.create('<img/>'));
199 el.one('.fp-icon img').setImgSrc(node.icon, node.realicon, lazyloading);
202 tmpnodedata.html = el.getContent();
203 var tmpNode = new Y.YUI2.widget.HTMLNode(tmpnodedata, level, false);
204 if (node.dynamicLoadComplete) {
205 tmpNode.dynamicLoadComplete = true;
207 tmpNode.fileinfo = node;
208 tmpNode.isLeaf = !file_is_folder(node);
209 if (!tmpNode.isLeaf) {
213 tmpNode.path = node.path ? node.path : (node.filepath ? node.filepath : '');
214 for(var c in node.children) {
215 build_tree(node.children[c], tmpNode);
219 /** initialize tree view */
220 var initialize_tree_view = function() {
221 var parentid = scope.one('.'+classname).get('id');
222 // TODO MDL-32736 use YUI3 gallery TreeView
223 scope.treeview = new Y.YUI2.widget.TreeView(parentid);
224 if (options.dynload) {
225 scope.treeview.setDynamicLoad(Y.bind(options.treeview_dynload, options.callbackcontext), 1);
227 scope.treeview.singleNodeHighlight = true;
228 if (options.filepath && options.filepath.length) {
229 // we just jumped from icon/details view, we need to show all parents
230 // we extract as much information as possible from filepath and filelist
231 // and send additional requests to retrieve siblings for parent folders
234 for (var i in options.filepath) {
235 if (mytreeel == null) {
238 mytreeel.children = [{}];
239 mytreeel = mytreeel.children[0];
241 var pathelement = options.filepath[i];
242 mytreeel.path = pathelement.path;
243 mytreeel.title = pathelement.name;
244 mytreeel.icon = pathelement.icon;
245 mytreeel.dynamicLoadComplete = true; // we will call it manually
246 mytreeel.expanded = true;
248 mytreeel.children = fileslist;
249 build_tree(mytree, scope.treeview.getRoot());
250 // manually call dynload for parent elements in the tree so we can load other siblings
251 if (options.dynload) {
252 var root = scope.treeview.getRoot();
253 while (root && root.children && root.children.length) {
254 root = root.children[0];
255 if (root.path == mytreeel.path) {
256 root.origpath = options.filepath;
257 root.origlist = fileslist;
258 } else if (!root.isLeaf && root.expanded) {
259 Y.bind(options.treeview_dynload, options.callbackcontext)(root, null);
264 // there is no path information, just display all elements as a list, without hierarchy
265 for(k in fileslist) {
266 build_tree(fileslist[k], scope.treeview.getRoot());
269 scope.treeview.subscribe('clickEvent', function(e){
270 e.node.highlight(false);
271 var callback = options.callback;
272 if (options.rightclickcallback && e.event.target &&
273 Y.Node(e.event.target).ancestor('.fp-treeview .fp-contextmenu', true)) {
274 callback = options.rightclickcallback;
276 Y.bind(callback, options.callbackcontext)(e, e.node.fileinfo);
277 Y.YUI2.util.Event.stopEvent(e.event)
279 // TODO MDL-32736 support right click
280 /*if (options.rightclickcallback) {
281 scope.treeview.subscribe('dblClickEvent', function(e){
282 e.node.highlight(false);
283 Y.bind(options.rightclickcallback, options.callbackcontext)(e, e.node.fileinfo);
286 scope.treeview.draw();
288 /** formatting function for table view */
289 var formatValue = function (o){
290 if (o.data[''+o.column.key+'_f_s']) {return o.data[''+o.column.key+'_f_s'];}
291 else if (o.data[''+o.column.key+'_f']) {return o.data[''+o.column.key+'_f'];}
292 else if (o.value) {return o.value;}
295 /** formatting function for table view */
296 var formatTitle = function(o) {
297 var el = Y.Node.create('<div/>');
298 el.appendChild(options.filenode.cloneNode(true)); // TODO not node but string!
299 el.get('children').addClass(o.data['classname']);
300 el.one('.fp-filename').setContent(o.value);
301 if (o.data['icon']) {
302 el.one('.fp-icon').appendChild(Y.Node.create('<img/>'));
303 el.one('.fp-icon img').setImgSrc(o.data['icon'], o.data['realicon'], lazyloading);
305 if (options.rightclickcallback) {
306 el.get('children').addClass('fp-hascontextmenu');
308 // TODO add tooltip with o.data['title'] (o.value) or o.data['thumbnail_title']
309 return el.getContent();
311 /** sorting function for table view */
312 var sortFoldersFirst = function(a, b, desc) {
313 if (a.get('isfolder') && !b.get('isfolder')) {
316 if (!a.get('isfolder') && b.get('isfolder')) {
319 var aa = a.get(this.key), bb = b.get(this.key), dir = desc ? -1 : 1;
320 return (aa > bb) ? dir : ((aa < bb) ? -dir : 0);
322 /** initialize table view */
323 var initialize_table_view = function() {
324 var parentid = scope.one('.'+classname).get('id');
326 {key: "displayname", label: M.str.moodle.name, allowHTML: true, formatter: formatTitle,
327 sortable: true, sortFn: sortFoldersFirst},
328 {key: "datemodified", label: M.str.moodle.lastmodified, allowHTML: true, formatter: formatValue,
329 sortable: true, sortFn: sortFoldersFirst},
330 {key: "size", label: M.str.repository.size, allowHTML: true, formatter: formatValue,
331 sortable: true, sortFn: sortFoldersFirst},
332 {key: "mimetype", label: M.str.repository.type, allowHTML: true,
333 sortable: true, sortFn: sortFoldersFirst}
335 scope.tableview = new Y.DataTable({columns: cols});
336 scope.tableview.render('#'+parentid);
337 scope.tableview.delegate('click', function (e, tableview) {
338 var record = tableview.getRecord(e.currentTarget.get('id'));
340 var callback = options.callback;
341 if (options.rightclickcallback && e.target.ancestor('.fp-tableview .fp-contextmenu', true)) {
342 callback = options.rightclickcallback;
344 Y.bind(callback, this)(e, record.getAttrs());
346 }, 'tr', options.callbackcontext, scope.tableview);
347 if (options.rightclickcallback) {
348 scope.tableview.delegate('contextmenu', function (e, tableview) {
349 var record = tableview.getRecord(e.currentTarget.get('id'));
350 if (record) { Y.bind(options.rightclickcallback, this)(e, record.getAttrs()); }
351 }, 'tr', options.callbackcontext, scope.tableview);
354 /** append items in table view mode */
355 var append_files_table = function() {
356 for (var k in fileslist) {
357 // to speed up sorting and formatting
358 fileslist[k].displayname = file_get_displayname(fileslist[k]);
359 fileslist[k].isfolder = file_is_folder(fileslist[k]);
360 fileslist[k].classname = options.classnamecallback(fileslist[k]);
362 scope.tableview.addRows(fileslist);
363 scope.tableview.sortable = options.sortable ? true : false;
365 /** append items in tree view mode */
366 var append_files_tree = function() {
367 if (options.appendonly) {
368 var parentnode = scope.treeview.getRoot();
369 if (scope.treeview.getHighlightedNode()) {
370 parentnode = scope.treeview.getHighlightedNode();
371 if (parentnode.isLeaf) {parentnode = parentnode.parent;}
373 for (var k in fileslist) {
374 build_tree(fileslist[k], parentnode);
376 scope.treeview.draw();
378 // otherwise files were already added in initialize_tree_view()
381 /** append items in icon view mode */
382 var append_files_icons = function() {
383 parent = scope.one('.'+classname);
384 for (var k in fileslist) {
385 var node = fileslist[k];
386 var element = options.filenode.cloneNode(true);
387 parent.appendChild(element);
388 element.addClass(options.classnamecallback(node));
389 var filenamediv = element.one('.fp-filename');
390 filenamediv.setContent(file_get_displayname(node));
391 var imgdiv = element.one('.fp-thumbnail'), width, height, src;
392 if (node.thumbnail) {
393 width = node.thumbnail_width ? node.thumbnail_width : 90;
394 height = node.thumbnail_height ? node.thumbnail_height : 90;
395 src = node.thumbnail;
401 filenamediv.setStyleAdv('width', width);
402 imgdiv.setStyleAdv('width', width).setStyleAdv('height', height);
403 var img = Y.Node.create('<img/>').setAttrs({
404 title: file_get_description(node),
405 alt: node.thumbnail_alt ? node.thumbnail_alt : file_get_filename(node)}).
406 setStyle('maxWidth', ''+width+'px').
407 setStyle('maxHeight', ''+height+'px');
408 img.setImgSrc(src, node.realthumbnail, lazyloading);
409 imgdiv.appendChild(img);
410 element.on('click', function(e, nd) {
411 if (options.rightclickcallback && e.target.ancestor('.fp-iconview .fp-contextmenu', true)) {
412 Y.bind(options.rightclickcallback, this)(e, nd);
414 Y.bind(options.callback, this)(e, nd);
416 }, options.callbackcontext, node);
417 if (options.rightclickcallback) {
418 element.on('contextmenu', options.rightclickcallback, options.callbackcontext, node);
423 // initialize files view
424 if (!options.appendonly) {
425 var parent = Y.Node.create('<div/>').addClass(classname);
426 this.setContent('').appendChild(parent);
428 if (options.viewmode == 2) {
429 initialize_tree_view();
430 } else if (options.viewmode == 3) {
431 initialize_table_view();
433 // nothing to initialize for icon view
437 // append files to the list
438 if (options.viewmode == 2) {
440 } else if (options.viewmode == 3) {
441 append_files_table();
443 append_files_icons();
449 * creates a node and adds it to the div with id #filesskin. This is needed for CSS to be able
450 * to overwrite YUI skin styles (instead of using !important that does not work in IE)
452 Y.Node.createWithFilesSkin = function(node) {
453 if (!Y.one('#filesskin')) {
454 Y.one(document.body).appendChild(Y.Node.create('<div/>').set('id', 'filesskin'));
456 return Y.one('#filesskin').appendChild(Y.Node.create(node));
459 requires:['base', 'node', 'yui2-treeview', 'panel', 'cookie', 'datatable', 'datatable-sort']
462 M.core_filepicker = M.core_filepicker || {};
465 * instances of file pickers used on page
467 M.core_filepicker.instances = M.core_filepicker.instances || {};
468 M.core_filepicker.active_filepicker = null;
471 * HTML Templates to use in FilePicker
473 M.core_filepicker.templates = M.core_filepicker.templates || {};
476 * Array of image sources for real previews (realicon or realthumbnail) that are already loaded
478 M.core_filepicker.loadedpreviews = M.core_filepicker.loadedpreviews || {};
481 * Set selected file info
483 * @parma object file info
485 M.core_filepicker.select_file = function(file) {
486 M.core_filepicker.active_filepicker.select_file(file);
490 * Init and show file picker
492 M.core_filepicker.show = function(Y, options) {
493 if (!M.core_filepicker.instances[options.client_id]) {
494 M.core_filepicker.init(Y, options);
496 M.core_filepicker.instances[options.client_id].show();
499 M.core_filepicker.set_templates = function(Y, templates) {
500 for (var templid in templates) {
501 M.core_filepicker.templates[templid] = templates[templid];
506 * Add new file picker to current instances
508 M.core_filepicker.init = function(Y, options) {
509 var FilePickerHelper = function(options) {
510 FilePickerHelper.superclass.constructor.apply(this, arguments);
513 FilePickerHelper.NAME = "FilePickerHelper";
514 FilePickerHelper.ATTRS = {
519 Y.extend(FilePickerHelper, Y.Base, {
520 api: M.cfg.wwwroot+'/repository/repository_ajax.php',
521 cached_responses: {},
522 waitinterval : null, // When the loading template is being displayed and its animation is running this will be an interval instance.
523 initializer: function(options) {
524 this.options = options;
525 if (!this.options.savepath) {
526 this.options.savepath = '/';
530 destructor: function() {
533 request: function(args, redraw) {
534 var api = (args.api ? args.api : this.api) + '?action='+args.action;
536 var scope = args['scope'] ? args['scope'] : this;
537 params['repo_id']=args.repository_id;
538 params['p'] = args.path?args.path:'';
539 params['page'] = args.page?args.page:'';
540 params['env']=this.options.env;
541 // the form element only accept certain file types
542 params['accepted_types']=this.options.accepted_types;
543 params['sesskey'] = M.cfg.sesskey;
544 params['client_id'] = args.client_id;
545 params['itemid'] = this.options.itemid?this.options.itemid:0;
546 params['maxbytes'] = this.options.maxbytes?this.options.maxbytes:-1;
547 // The unlimited value of areamaxbytes is -1, it is defined by FILE_AREA_MAX_BYTES_UNLIMITED.
548 params['areamaxbytes'] = this.options.areamaxbytes ? this.options.areamaxbytes : -1;
549 if (this.options.context && this.options.context.id) {
550 params['ctx_id'] = this.options.context.id;
552 if (args['params']) {
553 for (i in args['params']) {
554 params[i] = args['params'][i];
557 if (args.action == 'upload') {
559 for(var k in params) {
560 var value = params[k];
561 if(value instanceof Array) {
562 for(var i in value) {
563 list.push(k+'[]='+value[i]);
566 list.push(k+'='+value);
569 params = list.join('&');
571 params = build_querystring(params);
576 complete: function(id,o,p) {
584 data = Y.JSON.parse(o.responseText);
586 scope.print_msg(M.str.repository.invalidjson, 'error');
587 scope.display_error(M.str.repository.invalidjson+'<pre>'+stripHTML(o.responseText)+'</pre>', 'invalidjson')
591 if (data && data.error) {
592 scope.print_msg(data.error, 'error');
594 args.onerror(id,data,p);
596 this.fpnode.one('.fp-content').setContent('');
601 scope.print_msg(data.msg, 'info');
603 // cache result if applicable
604 if (args.action != 'upload' && data.allowcaching) {
605 scope.cached_responses[params] = data;
608 args.callback(id,data,p);
616 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
622 cfg.form = args.form;
624 // check if result of the same request has been already cached. If not, request it
625 // (never applicable in case of form submission and/or upload action):
626 if (!args.form && args.action != 'upload' && scope.cached_responses[params]) {
627 args.callback(null, scope.cached_responses[params], {scope: scope})
635 /** displays the dialog and processes rename/overwrite if there is a file with the same name in the same filearea*/
636 process_existing_file: function(data) {
638 var handleOverwrite = function(e) {
641 var data = this.process_dlg.dialogdata;
643 params['existingfilename'] = data.existingfile.filename;
644 params['existingfilepath'] = data.existingfile.filepath;
645 params['newfilename'] = data.newfile.filename;
646 params['newfilepath'] = data.newfile.filepath;
651 'action':'overwrite',
653 'client_id': this.options.client_id,
654 'repository_id': this.active_repo.id,
655 'callback': function(id, o, args) {
657 // editor needs to update url
658 // filemanager do nothing
659 if (scope.options.editor_target && scope.options.env == 'editor') {
660 scope.options.editor_target.value = data.existingfile.url;
661 scope.options.editor_target.onchange();
662 } else if (scope.options.env === 'filepicker') {
663 var fileinfo = {'client_id':scope.options.client_id,
664 'url':data.existingfile.url,
665 'file':data.existingfile.filename};
666 var formcallback_scope = scope.options.magicscope ? scope.options.magicscope : scope;
667 scope.options.formcallback.apply(formcallback_scope, [fileinfo]);
672 var handleRename = function(e) {
673 // inserts file with the new name
676 var data = this.process_dlg.dialogdata;
677 if (scope.options.editor_target && scope.options.env == 'editor') {
678 scope.options.editor_target.value = data.newfile.url;
679 scope.options.editor_target.onchange();
682 var formcallback_scope = scope.options.magicscope ? scope.options.magicscope : scope;
683 var fileinfo = {'client_id':scope.options.client_id,
684 'url':data.newfile.url,
685 'file':data.newfile.filename};
686 scope.options.formcallback.apply(formcallback_scope, [fileinfo]);
688 var handleCancel = function(e) {
692 params['newfilename'] = this.process_dlg.dialogdata.newfile.filename;
693 params['newfilepath'] = this.process_dlg.dialogdata.newfile.filepath;
697 'action':'deletetmpfile',
699 'client_id': this.options.client_id,
700 'repository_id': this.active_repo.id,
701 'callback': function(id, o, args) {
702 // let it be in background, from user point of view nothing is happenning
705 this.process_dlg.hide();
706 this.selectui.hide();
708 if (!this.process_dlg) {
709 this.process_dlg_node = Y.Node.createWithFilesSkin(M.core_filepicker.templates.processexistingfile);
710 var node = this.process_dlg_node;
712 this.process_dlg = new Y.Panel({
714 headerContent: M.str.repository.fileexistsdialogheader,
722 this.process_dlg.plug(Y.Plugin.Drag,{handles:['#'+node.get('id')+' .yui3-widget-hd']});
723 node.one('.fp-dlg-butoverwrite').on('click', handleOverwrite, this);
724 node.one('.fp-dlg-butrename').on('click', handleRename, this);
725 node.one('.fp-dlg-butcancel').on('click', handleCancel, this);
726 if (this.options.env == 'editor') {
727 node.one('.fp-dlg-text').setContent(M.str.repository.fileexistsdialog_editor);
729 node.one('.fp-dlg-text').setContent(M.str.repository.fileexistsdialog_filemanager);
732 this.selectnode.removeClass('loading');
733 this.process_dlg.dialogdata = data;
734 this.process_dlg_node.one('.fp-dlg-butrename').setContent(M.util.get_string('renameto', 'repository', data.newfile.filename));
735 this.process_dlg.show();
737 /** displays error instead of filepicker contents */
738 display_error: function(errortext, errorcode) {
739 this.fpnode.one('.fp-content').setContent(M.core_filepicker.templates.error);
740 this.fpnode.one('.fp-content .fp-error').
742 setContent(errortext);
744 /** displays message in a popup */
745 print_msg: function(msg, type) {
746 var header = M.str.moodle.error;
747 if (type != 'error') {
748 type = 'info'; // one of only two types excepted
749 header = M.str.moodle.info;
752 this.msg_dlg_node = Y.Node.createWithFilesSkin(M.core_filepicker.templates.message);
753 this.msg_dlg_node.generateID();
755 this.msg_dlg = new Y.Panel({
756 srcNode : this.msg_dlg_node,
763 this.msg_dlg.plug(Y.Plugin.Drag,{handles:['#'+this.msg_dlg_node.get('id')+' .yui3-widget-hd']});
764 this.msg_dlg_node.one('.fp-msg-butok').on('click', function(e) {
770 this.msg_dlg.set('headerContent', header);
771 this.msg_dlg_node.removeClass('fp-msg-info').removeClass('fp-msg-error').addClass('fp-msg-'+type)
772 this.msg_dlg_node.one('.fp-msg-text').setContent(msg);
775 view_files: function(appenditems) {
776 this.viewbar_set_enabled(true);
778 /*if ((appenditems == null) && (!this.filelist || !this.filelist.length) && !this.active_repo.hasmorepages) {
779 // TODO do it via classes and adjust for each view mode!
780 // If there are no items and no next page, just display status message and quit
781 this.display_error(M.str.repository.nofilesavailable, 'nofilesavailable');
784 if (this.viewmode == 2) {
785 this.view_as_list(appenditems);
786 } else if (this.viewmode == 3) {
787 this.view_as_table(appenditems);
789 this.view_as_icons(appenditems);
791 // display/hide the link for requesting next page
792 if (!appenditems && this.active_repo.hasmorepages) {
793 if (!this.fpnode.one('.fp-content .fp-nextpage')) {
794 this.fpnode.one('.fp-content').append(M.core_filepicker.templates.nextpage);
796 this.fpnode.one('.fp-content .fp-nextpage').one('a,button').on('click', function(e) {
798 this.fpnode.one('.fp-content .fp-nextpage').addClass('loading');
799 this.request_next_page();
802 if (!this.active_repo.hasmorepages && this.fpnode.one('.fp-content .fp-nextpage')) {
803 this.fpnode.one('.fp-content .fp-nextpage').remove();
805 if (this.fpnode.one('.fp-content .fp-nextpage')) {
806 this.fpnode.one('.fp-content .fp-nextpage').removeClass('loading');
808 this.content_scrolled();
810 content_scrolled: function(e) {
811 setTimeout(Y.bind(function() {
812 if (this.processingimages) {
815 this.processingimages = true;
817 fpcontent = this.fpnode.one('.fp-content'),
818 fpcontenty = fpcontent.getY(),
819 fpcontentheight = fpcontent.getStylePx('height'),
820 nextpage = fpcontent.one('.fp-nextpage'),
821 is_node_visible = function(node) {
822 var offset = node.getY()-fpcontenty;
823 if (offset <= fpcontentheight && (offset >=0 || offset+node.getStylePx('height')>=0)) {
828 // automatically load next page when 'more' link becomes visible
829 if (nextpage && !nextpage.hasClass('loading') && is_node_visible(nextpage)) {
830 nextpage.one('a,button').simulate('click');
832 // replace src for visible images that need to be lazy-loaded
833 if (scope.lazyloading) {
834 fpcontent.all('img').each( function(node) {
835 if (node.get('id') && scope.lazyloading[node.get('id')] && is_node_visible(node)) {
836 node.setImgRealSrc(scope.lazyloading);
840 this.processingimages = false;
843 treeview_dynload: function(node, cb) {
844 var retrieved_children = {};
846 for (var i in node.children) {
847 retrieved_children[node.children[i].path] = node.children[i];
852 client_id: this.options.client_id,
853 repository_id: this.active_repo.id,
854 path:node.path?node.path:'',
855 page:node.page?args.page:'',
857 callback: function(id, obj, args) {
859 var scope = args.scope;
860 // check that user did not leave the view mode before recieving this response
861 if (!(scope.active_repo.id == obj.repo_id && scope.viewmode == 2 && node && node.getChildrenEl())) {
864 if (cb != null) { // (in manual mode do not update current path)
865 scope.viewbar_set_enabled(true);
866 scope.parse_repository_options(obj);
868 node.highlight(false);
869 node.origlist = obj.list ? obj.list : null;
870 node.origpath = obj.path ? obj.path : null;
873 if (list[k].children && retrieved_children[list[k].path]) {
874 // if this child is a folder and has already been retrieved
875 node.children[node.children.length] = retrieved_children[list[k].path];
877 // append new file to the list
878 scope.view_as_list([list[k]]);
884 // invoke callback requested by TreeView component
887 scope.content_scrolled();
891 classnamecallback : function(node) {
894 classname = classname + ' fp-folder';
897 classname = classname + ' fp-isreference';
900 classname = classname + ' fp-hasreferences';
902 if (node.originalmissing) {
903 classname = classname + ' fp-originalmissing';
905 return Y.Lang.trim(classname);
907 /** displays list of files in tree (list) view mode. If param appenditems is specified,
908 * appends those items to the end of the list. Otherwise (default behaviour)
909 * clears the contents and displays the items from this.filelist */
910 view_as_list: function(appenditems) {
911 var list = (appenditems != null) ? appenditems : this.filelist;
913 if (!this.filelist || this.filelist.length==0 && (!this.filepath || !this.filepath.length)) {
914 this.display_error(M.str.repository.nofilesavailable, 'nofilesavailable');
918 var element_template = Y.Node.create(M.core_filepicker.templates.listfilename);
920 viewmode : this.viewmode,
921 appendonly : (appenditems != null),
922 filenode : element_template,
923 callbackcontext : this,
924 callback : function(e, node) {
925 // TODO MDL-32736 e is not an event here but an object with properties 'event' and 'node'
926 if (!node.children) {
927 if (e.node.parent && e.node.parent.origpath) {
928 // set the current path
929 this.filepath = e.node.parent.origpath;
930 this.filelist = e.node.parent.origlist;
933 this.select_file(node);
935 // save current path and filelist (in case we want to jump to other viewmode)
936 this.filepath = e.node.origpath;
937 this.filelist = e.node.origlist;
938 this.currentpath = e.node.path;
940 this.content_scrolled();
943 classnamecallback : this.classnamecallback,
944 dynload : this.active_repo.dynload,
945 filepath : this.filepath,
946 treeview_dynload : this.treeview_dynload
948 this.fpnode.one('.fp-content').fp_display_filelist(options, list, this.lazyloading);
950 /** displays list of files in icon view mode. If param appenditems is specified,
951 * appends those items to the end of the list. Otherwise (default behaviour)
952 * clears the contents and displays the items from this.filelist */
953 view_as_icons: function(appenditems) {
955 var list = (appenditems != null) ? appenditems : this.filelist;
956 var element_template = Y.Node.create(M.core_filepicker.templates.iconfilename);
957 if ((appenditems == null) && (!this.filelist || !this.filelist.length)) {
958 this.display_error(M.str.repository.nofilesavailable, 'nofilesavailable');
962 viewmode : this.viewmode,
963 appendonly : (appenditems != null),
964 filenode : element_template,
965 callbackcontext : this,
966 callback : function(e, node) {
967 if (e.preventDefault) {
971 if (this.active_repo.dynload) {
972 this.list({'path':node.path});
974 this.filelist = node.children;
978 this.select_file(node);
981 classnamecallback : this.classnamecallback
983 this.fpnode.one('.fp-content').fp_display_filelist(options, list, this.lazyloading);
985 /** displays list of files in table view mode. If param appenditems is specified,
986 * appends those items to the end of the list. Otherwise (default behaviour)
987 * clears the contents and displays the items from this.filelist */
988 view_as_table: function(appenditems) {
990 var list = (appenditems != null) ? appenditems : this.filelist;
991 if (!appenditems && (!this.filelist || this.filelist.length==0) && !this.active_repo.hasmorepages) {
992 this.display_error(M.str.repository.nofilesavailable, 'nofilesavailable');
995 var element_template = Y.Node.create(M.core_filepicker.templates.listfilename);
997 viewmode : this.viewmode,
998 appendonly : (appenditems != null),
999 filenode : element_template,
1000 callbackcontext : this,
1001 sortable : !this.active_repo.hasmorepages,
1002 callback : function(e, node) {
1003 if (e.preventDefault) {e.preventDefault();}
1004 if (node.children) {
1005 if (this.active_repo.dynload) {
1006 this.list({'path':node.path});
1008 this.filelist = node.children;
1012 this.select_file(node);
1015 classnamecallback : this.classnamecallback
1017 this.fpnode.one('.fp-content').fp_display_filelist(options, list, this.lazyloading);
1019 /** If more than one page available, requests and displays the files from the next page */
1020 request_next_page: function() {
1021 if (!this.active_repo.hasmorepages || this.active_repo.nextpagerequested) {
1025 this.active_repo.nextpagerequested = true;
1026 var nextpage = this.active_repo.page+1;
1029 repo_id: this.active_repo.id
1031 var action = this.active_repo.issearchresult ? 'search' : 'list';
1033 path: this.currentpath,
1036 client_id: this.options.client_id,
1037 repository_id: args.repo_id,
1039 callback: function(id, obj, args) {
1040 var scope = args.scope;
1041 // Check that we are still in the same repository and are expecting this page. We have no way
1042 // to compare the requested page and the one returned, so we assume that if the last chunk
1043 // of the breadcrumb is similar, then we probably are on the same page.
1044 var samepage = true;
1045 if (obj.path && scope.filepath) {
1046 var pathbefore = scope.filepath[scope.filepath.length-1];
1047 var pathafter = obj.path[obj.path.length-1];
1048 if (pathbefore.path != pathafter.path) {
1052 if (scope.active_repo.hasmorepages && obj.list && obj.page &&
1053 obj.repo_id == scope.active_repo.id &&
1054 obj.page == scope.active_repo.page+1 && samepage) {
1055 scope.parse_repository_options(obj, true);
1056 scope.view_files(obj.list)
1061 select_file: function(args) {
1062 this.selectui.show();
1063 var client_id = this.options.client_id;
1064 var selectnode = this.selectnode;
1065 var return_types = this.options.repositories[this.active_repo.id].return_types;
1066 selectnode.removeClass('loading');
1067 selectnode.one('.fp-saveas input').set('value', args.title);
1069 var imgnode = Y.Node.create('<img/>').
1070 set('src', args.realthumbnail ? args.realthumbnail : args.thumbnail).
1071 setStyle('maxHeight', ''+(args.thumbnail_height ? args.thumbnail_height : 90)+'px').
1072 setStyle('maxWidth', ''+(args.thumbnail_width ? args.thumbnail_width : 90)+'px');
1073 selectnode.one('.fp-thumbnail').setContent('').appendChild(imgnode);
1075 // filelink is the array of file-link-types available for this repository in this env
1076 var filelinktypes = [2/*FILE_INTERNAL*/,1/*FILE_EXTERNAL*/,4/*FILE_REFERENCE*/];
1077 var filelink = {}, firstfilelink = null, filelinkcount = 0;
1078 for (var i in filelinktypes) {
1079 var allowed = (return_types & filelinktypes[i]) &&
1080 (this.options.return_types & filelinktypes[i]);
1081 if (filelinktypes[i] == 1/*FILE_EXTERNAL*/ && !this.options.externallink && this.options.env == 'editor') {
1082 // special configuration setting 'repositoryallowexternallinks' may prevent
1083 // using external links in editor environment
1086 filelink[filelinktypes[i]] = allowed;
1087 firstfilelink = (firstfilelink==null && allowed) ? filelinktypes[i] : firstfilelink;
1088 filelinkcount += allowed ? 1 : 0;
1090 // make radio buttons enabled if this file-link-type is available and only if there are more than one file-link-type option
1091 // check the first available file-link-type option
1092 for (var linktype in filelink) {
1093 var el = selectnode.one('.fp-linktype-'+linktype);
1094 el.addClassIf('uneditable', !(filelink[linktype] && filelinkcount>1));
1095 el.one('input').set('disabled', (filelink[linktype] && filelinkcount>1) ? '' : 'disabled').
1096 set('checked', (firstfilelink == linktype) ? 'checked' : '').simulate('change')
1099 // TODO MDL-32532: attributes 'hasauthor' and 'haslicense' need to be obsolete,
1100 selectnode.one('.fp-setauthor input').set('value', args.author ? args.author : this.options.author);
1101 this.set_selected_license(selectnode.one('.fp-setlicense'), args.license);
1102 selectnode.one('form #filesource-'+client_id).set('value', args.source);
1104 // display static information about a file (when known)
1105 var attrs = ['datemodified','datecreated','size','license','author','dimensions'];
1106 for (var i in attrs) {
1107 if (selectnode.one('.fp-'+attrs[i])) {
1108 var value = (args[attrs[i]+'_f']) ? args[attrs[i]+'_f'] : (args[attrs[i]] ? args[attrs[i]] : '');
1109 selectnode.one('.fp-'+attrs[i]).addClassIf('fp-unknown', ''+value == '')
1110 .one('.fp-value').setContent(value);
1114 setup_select_file: function() {
1115 var client_id = this.options.client_id;
1116 var selectnode = this.selectnode;
1117 var getfile = selectnode.one('.fp-select-confirm');
1118 // bind labels with corresponding inputs
1119 selectnode.all('.fp-saveas,.fp-linktype-2,.fp-linktype-1,.fp-linktype-4,.fp-setauthor,.fp-setlicense').each(function (node) {
1120 node.all('label').set('for', node.one('input,select').generateID());
1122 selectnode.one('.fp-linktype-2 input').setAttrs({value: 2, name: 'linktype'});
1123 selectnode.one('.fp-linktype-1 input').setAttrs({value: 1, name: 'linktype'});
1124 selectnode.one('.fp-linktype-4 input').setAttrs({value: 4, name: 'linktype'});
1125 var changelinktype = function(e) {
1126 if (e.currentTarget.get('checked')) {
1127 var allowinputs = e.currentTarget.get('value') != 1/*FILE_EXTERNAL*/;
1128 selectnode.all('.fp-setauthor,.fp-setlicense,.fp-saveas').each(function(node){
1129 node.addClassIf('uneditable', !allowinputs);
1130 node.all('input,select').set('disabled', allowinputs?'':'disabled');
1134 selectnode.all('.fp-linktype-2,.fp-linktype-1,.fp-linktype-4').each(function (node) {
1135 node.one('input').on('change', changelinktype, this);
1137 this.populate_licenses_select(selectnode.one('.fp-setlicense select'));
1138 // register event on clicking submit button
1139 getfile.on('click', function(e) {
1141 var client_id = this.options.client_id;
1143 var repository_id = this.active_repo.id;
1144 var title = selectnode.one('.fp-saveas input').get('value');
1145 var filesource = selectnode.one('form #filesource-'+client_id).get('value');
1146 var params = {'title':title, 'source':filesource, 'savepath': this.options.savepath};
1147 var license = selectnode.one('.fp-setlicense select');
1149 params['license'] = license.get('value');
1150 var origlicense = selectnode.one('.fp-license .fp-value');
1152 origlicense = origlicense.getContent();
1154 this.set_preference('recentlicense', license.get('value'));
1156 params['author'] = selectnode.one('.fp-setauthor input').get('value');
1158 var return_types = this.options.repositories[this.active_repo.id].return_types;
1159 if (this.options.env == 'editor') {
1160 // in editor, images are stored in '/' only
1161 params.savepath = '/';
1163 if ((this.options.externallink || this.options.env != 'editor') &&
1164 (return_types & 1/*FILE_EXTERNAL*/) &&
1165 (this.options.return_types & 1/*FILE_EXTERNAL*/) &&
1166 selectnode.one('.fp-linktype-1 input').get('checked')) {
1167 params['linkexternal'] = 'yes';
1168 } else if ((return_types & 4/*FILE_REFERENCE*/) &&
1169 (this.options.return_types & 4/*FILE_REFERENCE*/) &&
1170 selectnode.one('.fp-linktype-4 input').get('checked')) {
1171 params['usefilereference'] = '1';
1174 selectnode.addClass('loading');
1177 client_id: client_id,
1178 repository_id: repository_id,
1180 onerror: function(id, obj, args) {
1181 selectnode.removeClass('loading');
1182 scope.selectui.hide();
1184 callback: function(id, obj, args) {
1185 selectnode.removeClass('loading');
1186 if (obj.event == 'fileexists') {
1187 scope.process_existing_file(obj);
1190 if (scope.options.editor_target && scope.options.env=='editor') {
1191 scope.options.editor_target.value=obj.url;
1192 scope.options.editor_target.onchange();
1195 obj.client_id = client_id;
1196 var formcallback_scope = args.scope.options.magicscope ? args.scope.options.magicscope : args.scope;
1197 scope.options.formcallback.apply(formcallback_scope, [obj]);
1201 var elform = selectnode.one('form');
1202 elform.appendChild(Y.Node.create('<input/>').
1203 setAttrs({type:'hidden',id:'filesource-'+client_id}));
1204 elform.on('keydown', function(e) {
1205 if (e.keyCode == 13) {
1206 getfile.simulate('click');
1210 var cancel = selectnode.one('.fp-select-cancel');
1211 cancel.on('click', function(e) {
1213 this.selectui.hide();
1217 // First check there isn't already an interval in play, and if there is kill it now.
1218 if (this.waitinterval != null) {
1219 clearInterval(this.waitinterval);
1221 // Prepare the root node we will set content for and the loading template we want to display as a YUI node.
1222 var root = this.fpnode.one('.fp-content');
1223 var content = Y.Node.create(M.core_filepicker.templates.loading).addClass('fp-content-hidden').setStyle('opacity', 0);
1225 // Initiate an interval, we will have a count which will increment every 100 milliseconds.
1226 // Count 0 - the loading icon will have visibility set to hidden (invisible) and have an opacity of 0 (invisible also)
1227 // Count 5 - the visiblity will be switched to visible but opacity will still be at 0 (inivisible)
1228 // Counts 6 - 15 opacity will be increased by 0.1 making the loading icon visible over the period of a second
1229 // Count 16 - The interval will be cancelled.
1230 var interval = setInterval(function(){
1231 if (!content || !root.contains(content) || count >= 15) {
1232 clearInterval(interval);
1236 content.removeClass('fp-content-hidden');
1237 } else if (count > 5) {
1238 var opacity = parseFloat(content.getStyle('opacity'));
1239 content.setStyle('opacity', opacity + 0.1);
1244 // Store the wait interval so that we can check it in the future.
1245 this.waitinterval = interval;
1246 // Set the content to the loading template.
1247 root.setContent(content);
1249 viewbar_set_enabled: function(mode) {
1250 var viewbar = this.fpnode.one('.fp-viewbar')
1253 viewbar.addClass('enabled').removeClass('disabled')
1255 viewbar.removeClass('enabled').addClass('disabled')
1258 this.fpnode.all('.fp-vb-icons,.fp-vb-tree,.fp-vb-details').removeClass('checked')
1259 var modes = {1:'icons', 2:'tree', 3:'details'};
1260 this.fpnode.all('.fp-vb-'+modes[this.viewmode]).addClass('checked');
1262 viewbar_clicked: function(e) {
1264 var viewbar = this.fpnode.one('.fp-viewbar')
1265 if (!viewbar || !viewbar.hasClass('disabled')) {
1266 if (e.currentTarget.hasClass('fp-vb-tree')) {
1268 } else if (e.currentTarget.hasClass('fp-vb-details')) {
1273 this.viewbar_set_enabled(true)
1275 this.set_preference('recentviewmode', this.viewmode);
1278 render: function() {
1279 var client_id = this.options.client_id;
1280 this.fpnode = Y.Node.createWithFilesSkin(M.core_filepicker.templates.generallayout).
1281 set('id', 'filepicker-'+client_id);
1282 this.mainui = new Y.Panel({
1283 srcNode : this.fpnode,
1284 headerContent: M.str.repository.filepicker,
1289 minWidth : this.fpnode.getStylePx('minWidth'),
1290 minHeight : this.fpnode.getStylePx('minHeight'),
1291 maxWidth : this.fpnode.getStylePx('maxWidth'),
1292 maxHeight : this.fpnode.getStylePx('maxHeight'),
1295 // allow to move the panel dragging it by it's header:
1296 this.mainui.plug(Y.Plugin.Drag,{handles:['#filepicker-'+client_id+' .yui3-widget-hd']});
1298 if (this.mainui.get('y') < 0) {
1299 this.mainui.set('y', 0);
1301 // create panel for selecting a file (initially hidden)
1302 this.selectnode = Y.Node.createWithFilesSkin(M.core_filepicker.templates.selectlayout).
1303 set('id', 'filepicker-select-'+client_id);
1304 this.selectui = new Y.Panel({
1305 srcNode : this.selectnode,
1312 // allow to move the panel dragging it by it's header:
1313 this.selectui.plug(Y.Plugin.Drag,{handles:['#filepicker-select-'+client_id+' .yui3-widget-hd']});
1314 this.selectui.hide();
1315 // event handler for lazy loading of thumbnails and next page
1316 this.fpnode.one('.fp-content').on(['scroll','resize'], this.content_scrolled, this);
1317 // save template for one path element and location of path bar
1318 if (this.fpnode.one('.fp-path-folder')) {
1319 this.pathnode = this.fpnode.one('.fp-path-folder');
1320 this.pathbar = this.pathnode.get('parentNode');
1321 this.pathbar.removeChild(this.pathnode);
1323 // assign callbacks for view mode switch buttons
1324 this.fpnode.all('.fp-vb-icons,.fp-vb-tree,.fp-vb-details').
1325 on('click', this.viewbar_clicked, this);
1326 // assign callbacks for toolbar links
1327 this.setup_toolbar();
1328 this.setup_select_file();
1331 // processing repository listing
1332 // Resort the repositories by sortorder
1333 var sorted_repositories = [];
1334 for (var i in this.options.repositories) {
1335 sorted_repositories[i] = this.options.repositories[i];
1337 sorted_repositories.sort(function(a,b){return a.sortorder-b.sortorder});
1338 // extract one repository template and repeat it for all repositories available,
1339 // set name and icon and assign callbacks
1340 var reponode = this.fpnode.one('.fp-repo');
1342 var list = reponode.get('parentNode');
1343 list.removeChild(reponode);
1344 for (i in sorted_repositories) {
1345 var repository = sorted_repositories[i];
1346 var node = reponode.cloneNode(true);
1347 list.appendChild(node);
1349 set('id', 'fp-repo-'+client_id+'-'+repository.id).
1350 on('click', function(e, repository_id) {
1352 this.set_preference('recentrepository', repository_id);
1354 this.list({'repo_id':repository_id});
1355 }, this /*handler running scope*/, repository.id/*second argument of handler*/);
1356 node.one('.fp-repo-name').setContent(repository.name);
1357 node.one('.fp-repo-icon').set('src', repository.icon);
1359 node.addClass('first');
1361 if (i==sorted_repositories.length-1) {
1362 node.addClass('last');
1365 node.addClass('even');
1367 node.addClass('odd');
1371 // display error if no repositories found
1372 if (sorted_repositories.length==0) {
1373 this.display_error(M.str.repository.norepositoriesavailable, 'norepositoriesavailable')
1375 // display repository that was used last time
1376 this.show_recent_repository();
1378 parse_repository_options: function(data, appendtolist) {
1381 if (!this.filelist) {
1384 for (var i in data.list) {
1385 this.filelist[this.filelist.length] = data.list[i];
1389 this.filelist = data.list?data.list:null;
1390 this.lazyloading = {};
1392 this.filepath = data.path?data.path:null;
1393 this.objecttag = data.object?data.object:null;
1394 this.active_repo = {};
1395 this.active_repo.issearchresult = data.issearchresult ? true : false;
1396 this.active_repo.dynload = data.dynload?data.dynload:false;
1397 this.active_repo.pages = Number(data.pages?data.pages:null);
1398 this.active_repo.page = Number(data.page?data.page:null);
1399 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))
1400 this.active_repo.id = data.repo_id?data.repo_id:null;
1401 this.active_repo.nosearch = (data.login || data.nosearch); // this is either login form or 'nosearch' attribute set
1402 this.active_repo.norefresh = (data.login || data.norefresh); // this is either login form or 'norefresh' attribute set
1403 this.active_repo.nologin = (data.login || data.nologin); // this is either login form or 'nologin' attribute is set
1404 this.active_repo.logouttext = data.logouttext?data.logouttext:null;
1405 this.active_repo.logouturl = (data.logouturl || '');
1406 this.active_repo.message = (data.message || '');
1407 this.active_repo.help = data.help?data.help:null;
1408 this.active_repo.manage = data.manage?data.manage:null;
1409 this.print_header();
1411 print_login: function(data) {
1412 this.parse_repository_options(data);
1413 var client_id = this.options.client_id;
1414 var repository_id = data.repo_id;
1415 var l = this.logindata = data.login;
1417 var action = data['login_btn_action'] ? data['login_btn_action'] : 'login';
1418 var form_id = 'fp-form-'+client_id;
1420 var loginform_node = Y.Node.create(M.core_filepicker.templates.loginform);
1421 loginform_node.one('form').set('id', form_id);
1422 this.fpnode.one('.fp-content').setContent('').appendChild(loginform_node);
1424 'popup' : loginform_node.one('.fp-login-popup'),
1425 'textarea' : loginform_node.one('.fp-login-textarea'),
1426 'select' : loginform_node.one('.fp-login-select'),
1427 'text' : loginform_node.one('.fp-login-text'),
1428 'radio' : loginform_node.one('.fp-login-radiogroup'),
1429 'checkbox' : loginform_node.one('.fp-login-checkbox'),
1430 'input' : loginform_node.one('.fp-login-input')
1433 for (var i in templates) {
1435 container = templates[i].get('parentNode');
1436 container.removeChild(templates[i]);
1441 if (templates[l[k].type]) {
1442 var node = templates[l[k].type].cloneNode(true);
1444 node = templates['input'].cloneNode(true);
1446 if (l[k].type == 'popup') {
1448 loginurl = l[k].url;
1449 var popupbutton = node.one('button');
1450 popupbutton.on('click', function(e){
1451 M.core_filepicker.active_filepicker = this;
1452 window.open(loginurl, 'repo_auth', 'location=0,status=0,width=500,height=300,scrollbars=yes');
1455 loginform_node.one('form').on('keydown', function(e) {
1456 if (e.keyCode == 13) {
1457 popupbutton.simulate('click');
1461 loginform_node.all('.fp-login-submit').remove();
1463 } else if(l[k].type=='textarea') {
1465 if (node.one('label')) {
1466 node.one('label').set('for', l[k].id).setContent(l[k].label);
1468 node.one('textarea').setAttrs({id:l[k].id, name:l[k].name});
1469 } else if(l[k].type=='select') {
1471 if (node.one('label')) {
1472 node.one('label').set('for', l[k].id).setContent(l[k].label);
1474 node.one('select').setAttrs({id:l[k].id, name:l[k].name}).setContent('');
1475 for (i in l[k].options) {
1476 node.one('select').appendChild(
1477 Y.Node.create('<option/>').
1478 set('value', l[k].options[i].value).
1479 setContent(l[k].options[i].label));
1481 } else if(l[k].type=='radio') {
1482 // radio input element
1483 node.all('label').setContent(l[k].label);
1484 var list = l[k].value.split('|');
1485 var labels = l[k].value_label.split('|');
1486 var radionode = null;
1487 for(var item in list) {
1488 if (radionode == null) {
1489 radionode = node.one('.fp-login-radio');
1490 radionode.one('input').set('checked', 'checked');
1492 var x = radionode.cloneNode(true);
1493 radionode.insert(x, 'after');
1495 radionode.one('input').set('checked', '');
1497 radionode.one('input').setAttrs({id:''+l[k].id+item, name:l[k].name,
1498 type:l[k].type, value:list[item]});
1499 radionode.all('label').setContent(labels[item]).set('for', ''+l[k].id+item)
1501 if (radionode == null) {
1502 node.one('.fp-login-radio').remove();
1506 if (node.one('label')) { node.one('label').set('for', l[k].id).setContent(l[k].label) }
1508 set('type', l[k].type).
1510 set('name', l[k].name).
1511 set('value', l[k].value?l[k].value:'')
1513 container.appendChild(node);
1515 // custom label text for submit button
1516 if (data['login_btn_label']) {
1517 loginform_node.all('.fp-login-submit').setContent(data['login_btn_label'])
1519 // register button action for login and search
1520 if (action == 'login' || action == 'search') {
1521 loginform_node.one('.fp-login-submit').on('click', function(e){
1526 'action':(action == 'search') ? 'search' : 'signin',
1528 'client_id': client_id,
1529 'repository_id': repository_id,
1530 'form': {id:form_id, upload:false, useDisabled:true},
1531 'callback': this.display_response
1535 // if 'Enter' is pressed in the form, simulate the button click
1536 if (loginform_node.one('.fp-login-submit')) {
1537 loginform_node.one('form').on('keydown', function(e) {
1538 if (e.keyCode == 13) {
1539 loginform_node.one('.fp-login-submit').simulate('click')
1545 display_response: function(id, obj, args) {
1546 var scope = args.scope
1547 // highlight the current repository in repositories list
1548 scope.fpnode.all('.fp-repo.active').removeClass('active');
1549 scope.fpnode.all('#fp-repo-'+scope.options.client_id+'-'+obj.repo_id).addClass('active')
1550 // add class repository_REPTYPE to the filepicker (for repository-specific styles)
1551 for (var i in scope.options.repositories) {
1552 scope.fpnode.removeClass('repository_'+scope.options.repositories[i].type)
1554 if (obj.repo_id && scope.options.repositories[obj.repo_id]) {
1555 scope.fpnode.addClass('repository_'+scope.options.repositories[obj.repo_id].type)
1559 scope.viewbar_set_enabled(false);
1560 scope.print_login(obj);
1561 } else if (obj.upload) {
1562 scope.viewbar_set_enabled(false);
1563 scope.parse_repository_options(obj);
1564 scope.create_upload_form(obj);
1565 } else if (obj.object) {
1566 M.core_filepicker.active_filepicker = scope;
1567 scope.viewbar_set_enabled(false);
1568 scope.parse_repository_options(obj);
1569 scope.create_object_container(obj.object);
1570 } else if (obj.list) {
1571 scope.viewbar_set_enabled(true);
1572 scope.parse_repository_options(obj);
1576 list: function(args) {
1580 if (!args.repo_id) {
1581 args.repo_id = this.active_repo.id;
1586 this.currentpath = args.path;
1589 client_id: this.options.client_id,
1590 repository_id: args.repo_id,
1594 callback: this.display_response
1597 populate_licenses_select: function(node) {
1601 node.setContent('');
1602 var licenses = this.options.licenses;
1603 var recentlicense = this.get_preference('recentlicense');
1604 if (recentlicense) {
1605 this.options.defaultlicense=recentlicense;
1607 for (var i in licenses) {
1608 var option = Y.Node.create('<option/>').
1609 set('selected', (this.options.defaultlicense==licenses[i].shortname)).
1610 set('value', licenses[i].shortname).
1611 setContent(licenses[i].fullname);
1612 node.appendChild(option)
1615 set_selected_license: function(node, value) {
1616 var licenseset = false;
1617 node.all('option').each(function(el) {
1618 if (el.get('value')==value || el.getContent()==value) {
1619 el.set('selected', true);
1624 // we did not find the value in the list
1625 var recentlicense = this.get_preference('recentlicense');
1626 node.all('option[selected]').set('selected', false);
1627 node.all('option[value='+recentlicense+']').set('selected', true);
1630 create_object_container: function(data) {
1631 var content = this.fpnode.one('.fp-content');
1632 content.setContent('');
1633 //var str = '<object data="'+data.src+'" type="'+data.type+'" width="98%" height="98%" id="container_object" class="fp-object-container mdl-align"></object>';
1634 var container = Y.Node.create('<object/>').
1635 setAttrs({data:data.src, type:data.type, id:'container_object'}).
1636 addClass('fp-object-container');
1637 content.setContent('').appendChild(container);
1639 create_upload_form: function(data) {
1640 var client_id = this.options.client_id;
1641 var id = data.upload.id+'_'+client_id;
1642 var content = this.fpnode.one('.fp-content');
1643 var template_name = 'uploadform_'+this.options.repositories[data.repo_id].type;
1644 var template = M.core_filepicker.templates[template_name] || M.core_filepicker.templates['uploadform'];
1645 content.setContent(template);
1647 content.all('.fp-file,.fp-saveas,.fp-setauthor,.fp-setlicense').each(function (node) {
1648 node.all('label').set('for', node.one('input,select').generateID());
1650 content.one('form').set('id', id);
1651 content.one('.fp-file input').set('name', 'repo_upload_file');
1652 if (data.upload.label && content.one('.fp-file label')) {
1653 content.one('.fp-file label').setContent(data.upload.label);
1655 content.one('.fp-saveas input').set('name', 'title');
1656 content.one('.fp-setauthor input').setAttrs({name:'author', value:this.options.author});
1657 content.one('.fp-setlicense select').set('name', 'license');
1658 this.populate_licenses_select(content.one('.fp-setlicense select'))
1659 // append hidden inputs to the upload form
1660 content.one('form').appendChild(Y.Node.create('<input/>').
1661 setAttrs({type:'hidden',name:'itemid',value:this.options.itemid}));
1662 var types = this.options.accepted_types;
1663 for (var i in types) {
1664 content.one('form').appendChild(Y.Node.create('<input/>').
1665 setAttrs({type:'hidden',name:'accepted_types[]',value:types[i]}));
1669 content.one('.fp-upload-btn').on('click', function(e) {
1671 var license = content.one('.fp-setlicense select');
1673 this.set_preference('recentlicense', license.get('value'));
1674 if (!content.one('.fp-file input').get('value')) {
1675 scope.print_msg(M.str.repository.nofilesattached, 'error');
1682 client_id: client_id,
1683 params: {'savepath':scope.options.savepath},
1684 repository_id: scope.active_repo.id,
1685 form: {id: id, upload:true},
1686 onerror: function(id, o, args) {
1687 scope.create_upload_form(data);
1689 callback: function(id, o, args) {
1690 if (o.event == 'fileexists') {
1691 scope.create_upload_form(data);
1692 scope.process_existing_file(o);
1695 if (scope.options.editor_target&&scope.options.env=='editor') {
1696 scope.options.editor_target.value=o.url;
1697 scope.options.editor_target.onchange();
1700 o.client_id = client_id;
1701 var formcallback_scope = args.scope.options.magicscope ? args.scope.options.magicscope : args.scope;
1702 scope.options.formcallback.apply(formcallback_scope, [o]);
1707 /** setting handlers and labels for elements in toolbar. Called once during the initial render of filepicker */
1708 setup_toolbar: function() {
1709 var client_id = this.options.client_id;
1710 var toolbar = this.fpnode.one('.fp-toolbar');
1711 toolbar.one('.fp-tb-logout').one('a,button').on('click', function(e) {
1713 if (!this.active_repo.nologin) {
1717 client_id: this.options.client_id,
1718 repository_id: this.active_repo.id,
1720 callback: this.display_response
1723 if (this.active_repo.logouturl) {
1724 window.open(this.active_repo.logouturl, 'repo_auth', 'location=0,status=0,width=500,height=300,scrollbars=yes');
1727 toolbar.one('.fp-tb-refresh').one('a,button').on('click', function(e) {
1729 if (!this.active_repo.norefresh) {
1730 this.list({ path: this.currentpath });
1733 toolbar.one('.fp-tb-search form').
1734 set('method', 'POST').
1735 set('id', 'fp-tb-search-'+client_id).
1736 on('submit', function(e) {
1738 if (!this.active_repo.nosearch) {
1742 client_id: this.options.client_id,
1743 repository_id: this.active_repo.id,
1744 form: {id: 'fp-tb-search-'+client_id, upload:false, useDisabled:true},
1745 callback: this.display_response
1750 // it does not matter what kind of element is .fp-tb-manage, we create a dummy <a>
1751 // element and use it to open url on click event
1752 var managelnk = Y.Node.create('<a/>').
1753 setAttrs({id:'fp-tb-manage-'+client_id+'-link', target:'_blank'}).
1754 setStyle('display', 'none');
1755 toolbar.append(managelnk);
1756 toolbar.one('.fp-tb-manage').one('a,button').
1757 on('click', function(e) {
1759 managelnk.simulate('click')
1762 // same with .fp-tb-help
1763 var helplnk = Y.Node.create('<a/>').
1764 setAttrs({id:'fp-tb-help-'+client_id+'-link', target:'_blank'}).
1765 setStyle('display', 'none');
1766 toolbar.append(helplnk);
1767 toolbar.one('.fp-tb-help').one('a,button').
1768 on('click', function(e) {
1770 helplnk.simulate('click')
1773 hide_header: function() {
1774 if (this.fpnode.one('.fp-toolbar')) {
1775 this.fpnode.one('.fp-toolbar').addClass('empty');
1778 this.pathbar.setContent('').addClass('empty');
1781 print_header: function() {
1782 var r = this.active_repo;
1784 var client_id = this.options.client_id;
1787 var toolbar = this.fpnode.one('.fp-toolbar');
1788 if (!toolbar) { return; }
1790 var enable_tb_control = function(node, enabled) {
1791 if (!node) { return; }
1792 node.addClassIf('disabled', !enabled).addClassIf('enabled', enabled)
1794 toolbar.removeClass('empty');
1798 // TODO 'back' permanently disabled for now. Note, flickr_public uses 'Logout' for it!
1799 enable_tb_control(toolbar.one('.fp-tb-back'), false);
1802 enable_tb_control(toolbar.one('.fp-tb-search'), !r.nosearch);
1804 var searchform = toolbar.one('.fp-tb-search form');
1805 searchform.setContent('');
1808 action:'searchform',
1809 repository_id: this.active_repo.id,
1810 callback: function(id, obj, args) {
1811 if (obj.repo_id == scope.active_repo.id && obj.form) {
1812 // if we did not jump to another repository meanwhile
1813 searchform.setContent(obj.form);
1814 // Highlight search text when user click for search.
1815 var searchnode = searchform.one('input[name="s"]');
1817 searchnode.once('click', function(e) {
1828 // weather we use cache for this instance, this button will reload listing anyway
1829 enable_tb_control(toolbar.one('.fp-tb-refresh'), !r.norefresh);
1832 enable_tb_control(toolbar.one('.fp-tb-logout'), !r.nologin);
1834 var label = r.logouttext ? r.logouttext : M.str.repository.logout;
1835 toolbar.one('.fp-tb-logout').one('a,button').setContent(label)
1839 enable_tb_control(toolbar.one('.fp-tb-manage'), r.manage);
1840 Y.one('#fp-tb-manage-'+client_id+'-link').set('href', r.manage);
1843 enable_tb_control(toolbar.one('.fp-tb-help'), r.help);
1844 Y.one('#fp-tb-help-'+client_id+'-link').set('href', r.help);
1847 enable_tb_control(toolbar.one('.fp-tb-message'), r.message);
1848 toolbar.one('.fp-tb-message').setContent(r.message);
1850 print_path: function() {
1851 if (!this.pathbar) {
1854 this.pathbar.setContent('').addClass('empty');
1855 var p = this.filepath;
1856 if (p && p.length!=0 && this.viewmode != 2) {
1857 for(var i = 0; i < p.length; i++) {
1858 var el = this.pathnode.cloneNode(true);
1859 this.pathbar.appendChild(el);
1861 el.addClass('first');
1863 if (i == p.length-1) {
1864 el.addClass('last');
1867 el.addClass('even');
1871 el.all('.fp-path-folder-name').setContent(p[i].name);
1875 this.list({'path':path});
1879 this.pathbar.removeClass('empty');
1883 this.selectui.hide();
1884 if (this.process_dlg) {
1885 this.process_dlg.hide();
1888 this.msg_dlg.hide();
1896 this.show_recent_repository();
1901 launch: function() {
1904 show_recent_repository: function() {
1906 this.viewbar_set_enabled(false);
1907 var repository_id = this.get_preference('recentrepository');
1908 this.viewmode = this.get_preference('recentviewmode');
1909 if (this.viewmode != 2 && this.viewmode != 3) {
1912 if (this.options.repositories[repository_id]) {
1913 this.list({'repo_id':repository_id});
1916 get_preference: function (name) {
1917 if (this.options.userprefs[name]) {
1918 return this.options.userprefs[name];
1923 set_preference: function(name, value) {
1924 if (this.options.userprefs[name] != value) {
1925 M.util.set_user_preference('filepicker_' + name, value);
1926 this.options.userprefs[name] = value;
1930 var loading = Y.one('#filepicker-loading-'+options.client_id);
1932 loading.setStyle('display', 'none');
1934 M.core_filepicker.instances[options.client_id] = new FilePickerHelper(options);