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 displayed in file picker
27 * this.options.formcallback
29 * Active repository options
32 * this.active_repo.defaultreturntype
33 * this.active_repo.nosearch
34 * this.active_repo.norefresh
35 * this.active_repo.nologin
36 * this.active_repo.help
37 * this.active_repo.manage
41 * this.filelist, cached filelist
44 * this.filepath, current path (each element of the array is a part of the breadcrumb)
45 * this.logindata, cached login form
48 YUI.add('moodle-core_filepicker', function(Y) {
49 /** help function to extract width/height style as a number, not as a string */
50 Y.Node.prototype.getStylePx = function(attr) {
51 var style = this.getStyle(attr);
52 if (''+style == '0' || ''+style == '0px') {
55 var matches = style.match(/^([\d\.]+)px$/)
56 if (matches && parseFloat(matches[1])) {
57 return parseFloat(matches[1]);
62 /** if condition is met, the class is added to the node, otherwise - removed */
63 Y.Node.prototype.addClassIf = function(className, condition) {
65 this.addClass(className);
67 this.removeClass(className);
72 /** sets the width(height) of the node considering existing minWidth(minHeight) */
73 Y.Node.prototype.setStyleAdv = function(stylename, value) {
74 var stylenameCap = stylename.substr(0,1).toUpperCase() + stylename.substr(1, stylename.length-1).toLowerCase();
75 this.setStyle(stylename, '' + Math.max(value, this.getStylePx('min'+stylenameCap)) + 'px')
79 /** set image source to src, if there is preview, remember it in lazyloading.
80 * If there is a preview and it was already loaded, use it. */
81 Y.Node.prototype.setImgSrc = function(src, realsrc, lazyloading) {
83 if (M.core_filepicker.loadedpreviews[realsrc]) {
84 this.set('src', realsrc).addClass('realpreview');
87 if (!this.get('id')) {
90 lazyloading[this.get('id')] = realsrc;
98 * Replaces the image source with preview. If the image is inside the treeview, we need
99 * also to update the html property of corresponding YAHOO.widget.HTMLNode
100 * @param array lazyloading array containing associations of imgnodeid->realsrc
102 Y.Node.prototype.setImgRealSrc = function(lazyloading) {
103 if (this.get('id') && lazyloading[this.get('id')]) {
104 var newsrc = lazyloading[this.get('id')];
105 M.core_filepicker.loadedpreviews[newsrc] = true;
106 this.set('src', newsrc).addClass('realpreview');
107 delete lazyloading[this.get('id')];
108 var treenode = this.ancestor('.fp-treeview')
109 if (treenode && treenode.get('parentNode').treeview) {
110 treenode.get('parentNode').treeview.getRoot().refreshPreviews(this.get('id'), newsrc);
116 /** scan TreeView to find which node contains image with id=imgid and replace it's html
117 * with the new image source. */
118 Y.YUI2.widget.Node.prototype.refreshPreviews = function(imgid, newsrc, regex) {
120 regex = new RegExp("<img\\s[^>]*id=\""+imgid+"\"[^>]*?(/?)>", "im");
122 if (this.expanded || this.isLeaf) {
123 var html = this.getContentHtml();
124 if (html && this.setHtml && regex.test(html)) {
125 var newhtml = this.html.replace(regex, "<img id=\""+imgid+"\" src=\""+newsrc+"\" class=\"realpreview\"$1>", html);
126 this.setHtml(newhtml);
129 if (!this.isLeaf && this.children) {
130 for(var c in this.children) {
131 if (this.children[c].refreshPreviews(imgid, newsrc, regex)) {
141 * Displays a list of files (used by filepicker, filemanager) inside the Node
143 * @param array options
144 * viewmode : 1 - icons, 2 - tree, 3 - table
145 * appendonly : whether fileslist need to be appended instead of replacing the existing content
146 * filenode : Node element that contains template for displaying one file
147 * callback : On click callback. The element of the fileslist array will be passed as argument
148 * rightclickcallback : On right click callback (optional).
149 * callbackcontext : context where callbacks are executed
150 * sortable : whether content may be sortable (in table mode)
151 * dynload : allow dynamic load for tree view
152 * filepath : for pre-building of tree view - the path to the current directory in filepicker format
153 * treeview_dynload : callback to function to dynamically load the folder in tree view
154 * classnamecallback : callback to function that returns the class name for an element
155 * @param array fileslist array of files to show, each array element may have attributes:
156 * title or fullname : file name
157 * shorttitle (optional) : display file name
158 * thumbnail : url of image
159 * icon : url of icon image
160 * thumbnail_width : width of thumbnail, default 90
161 * thumbnail_height : height of thumbnail, default 90
162 * thumbnail_alt : TODO not needed!
163 * description or thumbnail_title : alt text
164 * @param array lazyloading : reference to the array with lazy loading images
166 Y.Node.prototype.fp_display_filelist = function(options, fileslist, lazyloading) {
167 var viewmodeclassnames = {1:'fp-iconview', 2:'fp-treeview', 3:'fp-tableview'};
168 var classname = viewmodeclassnames[options.viewmode];
170 /** return whether file is a folder (different attributes in FileManager and FilePicker) */
171 var file_is_folder = function(node) {
172 if (node.children) {return true;}
173 if (node.type && node.type == 'folder') {return true;}
176 /** return the name of the file (different attributes in FileManager and FilePicker) */
177 var file_get_filename = function(node) {
178 return node.title ? node.title : node.fullname;
180 /** return display name of the file (different attributes in FileManager and FilePicker) */
181 var file_get_displayname = function(node) {
182 var displayname = node.shorttitle ? node.shorttitle : file_get_filename(node);
183 return Y.Escape.html(displayname);
185 /** return file description (different attributes in FileManager and FilePicker) */
186 var file_get_description = function(node) {
187 var description = '';
188 if (node.description) {
189 description = node.description;
190 } else if (node.thumbnail_title) {
191 description = node.thumbnail_title;
193 description = file_get_filename(node);
195 return Y.Escape.html(description);
197 /** help funciton for tree view */
198 var build_tree = function(node, level) {
199 // prepare file name with icon
200 var el = Y.Node.create('<div/>');
201 el.appendChild(options.filenode.cloneNode(true));
203 el.one('.fp-filename').setContent(file_get_displayname(node));
204 // TODO add tooltip with node.title or node.thumbnail_title
205 var tmpnodedata = {className:options.classnamecallback(node)};
206 el.get('children').addClass(tmpnodedata.className);
208 el.one('.fp-icon').appendChild(Y.Node.create('<img/>'));
209 el.one('.fp-icon img').setImgSrc(node.icon, node.realicon, lazyloading);
212 tmpnodedata.html = el.getContent();
213 var tmpNode = new Y.YUI2.widget.HTMLNode(tmpnodedata, level, false);
214 if (node.dynamicLoadComplete) {
215 tmpNode.dynamicLoadComplete = true;
217 tmpNode.fileinfo = node;
218 tmpNode.isLeaf = !file_is_folder(node);
219 if (!tmpNode.isLeaf) {
223 tmpNode.path = node.path ? node.path : (node.filepath ? node.filepath : '');
224 for(var c in node.children) {
225 build_tree(node.children[c], tmpNode);
229 /** initialize tree view */
230 var initialize_tree_view = function() {
231 var parentid = scope.one('.'+classname).get('id');
232 // TODO MDL-32736 use YUI3 gallery TreeView
233 scope.treeview = new Y.YUI2.widget.TreeView(parentid);
234 if (options.dynload) {
235 scope.treeview.setDynamicLoad(Y.bind(options.treeview_dynload, options.callbackcontext), 1);
237 scope.treeview.singleNodeHighlight = true;
238 if (options.filepath && options.filepath.length) {
239 // we just jumped from icon/details view, we need to show all parents
240 // we extract as much information as possible from filepath and filelist
241 // and send additional requests to retrieve siblings for parent folders
244 for (var i in options.filepath) {
245 if (mytreeel == null) {
248 mytreeel.children = [{}];
249 mytreeel = mytreeel.children[0];
251 var pathelement = options.filepath[i];
252 mytreeel.path = pathelement.path;
253 mytreeel.title = pathelement.name;
254 mytreeel.icon = pathelement.icon;
255 mytreeel.dynamicLoadComplete = true; // we will call it manually
256 mytreeel.expanded = true;
258 mytreeel.children = fileslist;
259 build_tree(mytree, scope.treeview.getRoot());
260 // manually call dynload for parent elements in the tree so we can load other siblings
261 if (options.dynload) {
262 var root = scope.treeview.getRoot();
263 while (root && root.children && root.children.length) {
264 root = root.children[0];
265 if (root.path == mytreeel.path) {
266 root.origpath = options.filepath;
267 root.origlist = fileslist;
268 } else if (!root.isLeaf && root.expanded) {
269 Y.bind(options.treeview_dynload, options.callbackcontext)(root, null);
274 // there is no path information, just display all elements as a list, without hierarchy
275 for(k in fileslist) {
276 build_tree(fileslist[k], scope.treeview.getRoot());
279 scope.treeview.subscribe('clickEvent', function(e){
280 e.node.highlight(false);
281 var callback = options.callback;
282 if (options.rightclickcallback && e.event.target &&
283 Y.Node(e.event.target).ancestor('.fp-treeview .fp-contextmenu', true)) {
284 callback = options.rightclickcallback;
286 Y.bind(callback, options.callbackcontext)(e, e.node.fileinfo);
287 Y.YUI2.util.Event.stopEvent(e.event)
289 // TODO MDL-32736 support right click
290 /*if (options.rightclickcallback) {
291 scope.treeview.subscribe('dblClickEvent', function(e){
292 e.node.highlight(false);
293 Y.bind(options.rightclickcallback, options.callbackcontext)(e, e.node.fileinfo);
296 scope.treeview.draw();
298 /** formatting function for table view */
299 var formatValue = function (o){
300 if (o.data[''+o.column.key+'_f_s']) {return o.data[''+o.column.key+'_f_s'];}
301 else if (o.data[''+o.column.key+'_f']) {return o.data[''+o.column.key+'_f'];}
302 else if (o.value) {return o.value;}
305 /** formatting function for table view */
306 var formatTitle = function(o) {
307 var el = Y.Node.create('<div/>');
308 el.appendChild(options.filenode.cloneNode(true)); // TODO not node but string!
309 el.get('children').addClass(o.data['classname']);
310 el.one('.fp-filename').setContent(o.value);
311 if (o.data['icon']) {
312 el.one('.fp-icon').appendChild(Y.Node.create('<img/>'));
313 el.one('.fp-icon img').setImgSrc(o.data['icon'], o.data['realicon'], lazyloading);
315 if (options.rightclickcallback) {
316 el.get('children').addClass('fp-hascontextmenu');
318 // TODO add tooltip with o.data['title'] (o.value) or o.data['thumbnail_title']
319 return el.getContent();
321 /** sorting function for table view */
322 var sortFoldersFirst = function(a, b, desc) {
323 if (a.get('isfolder') && !b.get('isfolder')) {
326 if (!a.get('isfolder') && b.get('isfolder')) {
329 var aa = a.get(this.key), bb = b.get(this.key), dir = desc ? -1 : 1;
330 return (aa > bb) ? dir : ((aa < bb) ? -dir : 0);
332 /** initialize table view */
333 var initialize_table_view = function() {
335 {key: "displayname", label: M.util.get_string('name', 'moodle'), allowHTML: true, formatter: formatTitle,
336 sortable: true, sortFn: sortFoldersFirst},
337 {key: "datemodified", label: M.util.get_string('lastmodified', 'moodle'), allowHTML: true, formatter: formatValue,
338 sortable: true, sortFn: sortFoldersFirst},
339 {key: "size", label: M.util.get_string('size', 'repository'), allowHTML: true, formatter: formatValue,
340 sortable: true, sortFn: sortFoldersFirst},
341 {key: "mimetype", label: M.util.get_string('type', 'repository'), allowHTML: true,
342 sortable: true, sortFn: sortFoldersFirst}
344 scope.tableview = new Y.DataTable({columns: cols, data: fileslist});
345 scope.tableview.delegate('click', function (e, tableview) {
346 var record = tableview.getRecord(e.currentTarget.get('id'));
348 var callback = options.callback;
349 if (options.rightclickcallback && e.target.ancestor('.fp-tableview .fp-contextmenu', true)) {
350 callback = options.rightclickcallback;
352 Y.bind(callback, this)(e, record.getAttrs());
354 }, 'tr', options.callbackcontext, scope.tableview);
355 if (options.rightclickcallback) {
356 scope.tableview.delegate('contextmenu', function (e, tableview) {
357 var record = tableview.getRecord(e.currentTarget.get('id'));
358 if (record) { Y.bind(options.rightclickcallback, this)(e, record.getAttrs()); }
359 }, 'tr', options.callbackcontext, scope.tableview);
362 /** append items in table view mode */
363 var append_files_table = function() {
364 if (options.appendonly) {
365 fileslist.forEach(function(el) {
366 this.tableview.data.add(el);
369 scope.tableview.render(scope.one('.'+classname));
370 scope.tableview.sortable = options.sortable ? true : false;
372 /** append items in tree view mode */
373 var append_files_tree = function() {
374 if (options.appendonly) {
375 var parentnode = scope.treeview.getRoot();
376 if (scope.treeview.getHighlightedNode()) {
377 parentnode = scope.treeview.getHighlightedNode();
378 if (parentnode.isLeaf) {parentnode = parentnode.parent;}
380 for (var k in fileslist) {
381 build_tree(fileslist[k], parentnode);
383 scope.treeview.draw();
385 // otherwise files were already added in initialize_tree_view()
388 /** append items in icon view mode */
389 var append_files_icons = function() {
390 parent = scope.one('.'+classname);
391 for (var k in fileslist) {
392 var node = fileslist[k];
393 var element = options.filenode.cloneNode(true);
394 parent.appendChild(element);
395 element.addClass(options.classnamecallback(node));
396 var filenamediv = element.one('.fp-filename');
397 filenamediv.setContent(file_get_displayname(node));
398 var imgdiv = element.one('.fp-thumbnail'), width, height, src;
399 if (node.thumbnail) {
400 width = node.thumbnail_width ? node.thumbnail_width : 90;
401 height = node.thumbnail_height ? node.thumbnail_height : 90;
402 src = node.thumbnail;
408 filenamediv.setStyleAdv('width', width);
409 imgdiv.setStyleAdv('width', width).setStyleAdv('height', height);
410 var img = Y.Node.create('<img/>').setAttrs({
411 title: file_get_description(node),
412 alt: Y.Escape.html(node.thumbnail_alt ? node.thumbnail_alt : file_get_filename(node))}).
413 setStyle('maxWidth', ''+width+'px').
414 setStyle('maxHeight', ''+height+'px');
415 img.setImgSrc(src, node.realthumbnail, lazyloading);
416 imgdiv.appendChild(img);
417 element.on('click', function(e, nd) {
418 if (options.rightclickcallback && e.target.ancestor('.fp-iconview .fp-contextmenu', true)) {
419 Y.bind(options.rightclickcallback, this)(e, nd);
421 Y.bind(options.callback, this)(e, nd);
423 }, options.callbackcontext, node);
424 if (options.rightclickcallback) {
425 element.on('contextmenu', options.rightclickcallback, options.callbackcontext, node);
430 // If table view, need some additional properties
431 // before passing fileslist to the YUI tableview
432 if (options.viewmode == 3) {
433 fileslist.forEach(function(el) {
434 el.displayname = file_get_displayname(el);
435 el.isfolder = file_is_folder(el);
436 el.classname = options.classnamecallback(el);
440 // initialize files view
441 if (!options.appendonly) {
442 var parent = Y.Node.create('<div/>').addClass(classname);
443 this.setContent('').appendChild(parent);
445 if (options.viewmode == 2) {
446 initialize_tree_view();
447 } else if (options.viewmode == 3) {
448 initialize_table_view();
450 // nothing to initialize for icon view
454 // append files to the list
455 if (options.viewmode == 2) {
457 } else if (options.viewmode == 3) {
458 append_files_table();
460 append_files_icons();
465 requires:['base', 'node', 'yui2-treeview', 'panel', 'cookie', 'datatable', 'datatable-sort']
468 M.core_filepicker = M.core_filepicker || {};
471 * instances of file pickers used on page
473 M.core_filepicker.instances = M.core_filepicker.instances || {};
474 M.core_filepicker.active_filepicker = null;
477 * HTML Templates to use in FilePicker
479 M.core_filepicker.templates = M.core_filepicker.templates || {};
482 * Array of image sources for real previews (realicon or realthumbnail) that are already loaded
484 M.core_filepicker.loadedpreviews = M.core_filepicker.loadedpreviews || {};
487 * Set selected file info
489 * @param object file info
491 M.core_filepicker.select_file = function(file) {
492 M.core_filepicker.active_filepicker.select_file(file);
496 * Init and show file picker
498 M.core_filepicker.show = function(Y, options) {
499 if (!M.core_filepicker.instances[options.client_id]) {
500 M.core_filepicker.init(Y, options);
502 M.core_filepicker.instances[options.client_id].options.formcallback = options.formcallback;
503 M.core_filepicker.instances[options.client_id].show();
506 M.core_filepicker.set_templates = function(Y, templates) {
507 for (var templid in templates) {
508 M.core_filepicker.templates[templid] = templates[templid];
513 * Add new file picker to current instances
515 M.core_filepicker.init = function(Y, options) {
516 var FilePickerHelper = function(options) {
517 FilePickerHelper.superclass.constructor.apply(this, arguments);
520 FilePickerHelper.NAME = "FilePickerHelper";
521 FilePickerHelper.ATTRS = {
526 Y.extend(FilePickerHelper, Y.Base, {
527 api: M.cfg.wwwroot+'/repository/repository_ajax.php',
528 cached_responses: {},
529 waitinterval : null, // When the loading template is being displayed and its animation is running this will be an interval instance.
530 initializer: function(options) {
531 this.options = options;
532 if (!this.options.savepath) {
533 this.options.savepath = '/';
537 destructor: function() {
540 request: function(args, redraw) {
541 var api = (args.api ? args.api : this.api) + '?action='+args.action;
543 var scope = args['scope'] ? args['scope'] : this;
544 params['repo_id']=args.repository_id;
545 params['p'] = args.path?args.path:'';
546 params['page'] = args.page?args.page:'';
547 params['env']=this.options.env;
548 // the form element only accept certain file types
549 params['accepted_types']=this.options.accepted_types;
550 params['sesskey'] = M.cfg.sesskey;
551 params['client_id'] = args.client_id;
552 params['itemid'] = this.options.itemid?this.options.itemid:0;
553 params['maxbytes'] = this.options.maxbytes?this.options.maxbytes:-1;
554 // The unlimited value of areamaxbytes is -1, it is defined by FILE_AREA_MAX_BYTES_UNLIMITED.
555 params['areamaxbytes'] = this.options.areamaxbytes ? this.options.areamaxbytes : -1;
556 if (this.options.context && this.options.context.id) {
557 params['ctx_id'] = this.options.context.id;
559 if (args['params']) {
560 for (i in args['params']) {
561 params[i] = args['params'][i];
564 if (args.action == 'upload') {
566 for(var k in params) {
567 var value = params[k];
568 if(value instanceof Array) {
569 for(var i in value) {
570 list.push(k+'[]='+value[i]);
573 list.push(k+'='+value);
576 params = list.join('&');
578 params = build_querystring(params);
583 complete: function(id,o,p) {
586 data = Y.JSON.parse(o.responseText);
588 if (o && o.status && o.status > 0) {
589 Y.use('moodle-core-notification-exception', function() {
590 return new M.core.exception(e);
596 if (data && data.error) {
597 Y.use('moodle-core-notification-ajaxexception', function () {
598 return new M.core.ajaxException(data);
600 this.fpnode.one('.fp-content').setContent('');
604 scope.print_msg(data.msg, 'info');
606 // cache result if applicable
607 if (args.action != 'upload' && data.allowcaching) {
608 scope.cached_responses[params] = data;
611 args.callback(id,data,p);
619 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
625 cfg.form = args.form;
627 // check if result of the same request has been already cached. If not, request it
628 // (never applicable in case of form submission and/or upload action):
629 if (!args.form && args.action != 'upload' && scope.cached_responses[params]) {
630 args.callback(null, scope.cached_responses[params], {scope: scope})
638 /** displays the dialog and processes rename/overwrite if there is a file with the same name in the same filearea*/
639 process_existing_file: function(data) {
641 var handleOverwrite = function(e) {
644 var data = this.process_dlg.dialogdata;
646 params['existingfilename'] = data.existingfile.filename;
647 params['existingfilepath'] = data.existingfile.filepath;
648 params['newfilename'] = data.newfile.filename;
649 params['newfilepath'] = data.newfile.filepath;
654 'action':'overwrite',
656 'client_id': this.options.client_id,
657 'repository_id': this.active_repo.id,
658 'callback': function(id, o, args) {
660 if (scope.options.editor_target && scope.options.env == 'editor') {
661 // editor needs to update url
662 scope.options.editor_target.value = data.existingfile.url;
663 scope.options.editor_target.onchange();
665 var fileinfo = {'client_id':scope.options.client_id,
666 'url':data.existingfile.url,
667 'file':data.existingfile.filename};
668 var formcallback_scope = scope.options.magicscope ? scope.options.magicscope : scope;
669 scope.options.formcallback.apply(formcallback_scope, [fileinfo]);
673 var handleRename = function(e) {
674 // inserts file with the new name
677 var data = this.process_dlg.dialogdata;
678 if (scope.options.editor_target && scope.options.env == 'editor') {
679 scope.options.editor_target.value = data.newfile.url;
680 scope.options.editor_target.onchange();
683 var formcallback_scope = scope.options.magicscope ? scope.options.magicscope : scope;
684 var fileinfo = {'client_id':scope.options.client_id,
685 'url':data.newfile.url,
686 'file':data.newfile.filename};
687 scope.options.formcallback.apply(formcallback_scope, [fileinfo]);
689 var handleCancel = function(e) {
693 params['newfilename'] = this.process_dlg.dialogdata.newfile.filename;
694 params['newfilepath'] = this.process_dlg.dialogdata.newfile.filepath;
698 'action':'deletetmpfile',
700 'client_id': this.options.client_id,
701 'repository_id': this.active_repo.id,
702 'callback': function(id, o, args) {
703 // let it be in background, from user point of view nothing is happenning
706 this.process_dlg.hide();
707 this.selectui.hide();
709 if (!this.process_dlg) {
710 this.process_dlg_node = Y.Node.create(M.core_filepicker.templates.processexistingfile);
711 var node = this.process_dlg_node;
713 this.process_dlg = new M.core.dialogue({
716 headerContent: M.util.get_string('fileexistsdialogheader', 'repository'),
720 zIndex : this.options.zIndex
722 node.one('.fp-dlg-butoverwrite').on('click', handleOverwrite, this);
723 node.one('.fp-dlg-butrename').on('click', handleRename, this);
724 node.one('.fp-dlg-butcancel').on('click', handleCancel, this);
725 if (this.options.env == 'editor') {
726 node.one('.fp-dlg-text').setContent(M.util.get_string('fileexistsdialog_editor', 'repository'));
728 node.one('.fp-dlg-text').setContent(M.util.get_string('fileexistsdialog_filemanager', 'repository'));
731 this.selectnode.removeClass('loading');
732 this.process_dlg.dialogdata = data;
733 this.process_dlg_node.one('.fp-dlg-butrename').setContent(M.util.get_string('renameto', 'repository', data.newfile.filename));
734 this.process_dlg.show();
736 /** displays error instead of filepicker contents */
737 display_error: function(errortext, errorcode) {
738 this.fpnode.one('.fp-content').setContent(M.core_filepicker.templates.error);
739 this.fpnode.one('.fp-content .fp-error').
741 setContent(Y.Escape.html(errortext));
743 /** displays message in a popup */
744 print_msg: function(msg, type) {
745 var header = M.util.get_string('error', 'moodle');
746 if (type != 'error') {
747 type = 'info'; // one of only two types excepted
748 header = M.util.get_string('info', 'moodle');
751 this.msg_dlg_node = Y.Node.create(M.core_filepicker.templates.message);
752 this.msg_dlg_node.generateID();
754 this.msg_dlg = new M.core.dialogue({
756 bodyContent : this.msg_dlg_node,
760 zIndex : this.options.zIndex
762 this.msg_dlg_node.one('.fp-msg-butok').on('click', function(e) {
768 this.msg_dlg.set('headerContent', header);
769 this.msg_dlg_node.removeClass('fp-msg-info').removeClass('fp-msg-error').addClass('fp-msg-'+type)
770 this.msg_dlg_node.one('.fp-msg-text').setContent(Y.Escape.html(msg));
773 view_files: function(appenditems) {
774 this.viewbar_set_enabled(true);
776 /*if ((appenditems == null) && (!this.filelist || !this.filelist.length) && !this.active_repo.hasmorepages) {
777 // TODO do it via classes and adjust for each view mode!
778 // If there are no items and no next page, just display status message and quit
779 this.display_error(M.util.get_string('nofilesavailable', 'repository'), 'nofilesavailable');
782 if (this.viewmode == 2) {
783 this.view_as_list(appenditems);
784 } else if (this.viewmode == 3) {
785 this.view_as_table(appenditems);
787 this.view_as_icons(appenditems);
789 this.fpnode.one('.fp-content').setAttribute('tabindex', '0');
790 this.fpnode.one('.fp-content').focus();
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';
899 if (node.iscontrolledlink) {
900 classname = classname + ' fp-iscontrolledlink';
903 classname = classname + ' fp-hasreferences';
905 if (node.originalmissing) {
906 classname = classname + ' fp-originalmissing';
908 return Y.Lang.trim(classname);
910 /** displays list of files in tree (list) view mode. If param appenditems is specified,
911 * appends those items to the end of the list. Otherwise (default behaviour)
912 * clears the contents and displays the items from this.filelist */
913 view_as_list: function(appenditems) {
914 var list = (appenditems != null) ? appenditems : this.filelist;
916 if (!this.filelist || this.filelist.length==0 && (!this.filepath || !this.filepath.length)) {
917 this.display_error(M.util.get_string('nofilesavailable', 'repository'), 'nofilesavailable');
921 var element_template = Y.Node.create(M.core_filepicker.templates.listfilename);
923 viewmode : this.viewmode,
924 appendonly : (appenditems != null),
925 filenode : element_template,
926 callbackcontext : this,
927 callback : function(e, node) {
928 // TODO MDL-32736 e is not an event here but an object with properties 'event' and 'node'
929 if (!node.children) {
930 if (e.node.parent && e.node.parent.origpath) {
931 // set the current path
932 this.filepath = e.node.parent.origpath;
933 this.filelist = e.node.parent.origlist;
936 this.select_file(node);
938 // save current path and filelist (in case we want to jump to other viewmode)
939 this.filepath = e.node.origpath;
940 this.filelist = e.node.origlist;
941 this.currentpath = e.node.path;
943 this.content_scrolled();
946 classnamecallback : this.classnamecallback,
947 dynload : this.active_repo.dynload,
948 filepath : this.filepath,
949 treeview_dynload : this.treeview_dynload
951 this.fpnode.one('.fp-content').fp_display_filelist(options, list, this.lazyloading);
953 /** displays list of files in icon view mode. If param appenditems is specified,
954 * appends those items to the end of the list. Otherwise (default behaviour)
955 * clears the contents and displays the items from this.filelist */
956 view_as_icons: function(appenditems) {
958 var list = (appenditems != null) ? appenditems : this.filelist;
959 var element_template = Y.Node.create(M.core_filepicker.templates.iconfilename);
960 if ((appenditems == null) && (!this.filelist || !this.filelist.length)) {
961 this.display_error(M.util.get_string('nofilesavailable', 'repository'), 'nofilesavailable');
965 viewmode : this.viewmode,
966 appendonly : (appenditems != null),
967 filenode : element_template,
968 callbackcontext : this,
969 callback : function(e, node) {
970 if (e.preventDefault) {
974 if (this.active_repo.dynload) {
975 this.list({'path':node.path});
977 this.filelist = node.children;
981 this.select_file(node);
984 classnamecallback : this.classnamecallback
986 this.fpnode.one('.fp-content').fp_display_filelist(options, list, this.lazyloading);
988 /** displays list of files in table view mode. If param appenditems is specified,
989 * appends those items to the end of the list. Otherwise (default behaviour)
990 * clears the contents and displays the items from this.filelist */
991 view_as_table: function(appenditems) {
993 var list = (appenditems != null) ? appenditems : this.filelist;
994 if (!appenditems && (!this.filelist || this.filelist.length==0) && !this.active_repo.hasmorepages) {
995 this.display_error(M.util.get_string('nofilesavailable', 'repository'), 'nofilesavailable');
998 var element_template = Y.Node.create(M.core_filepicker.templates.listfilename);
1000 viewmode : this.viewmode,
1001 appendonly : (appenditems != null),
1002 filenode : element_template,
1003 callbackcontext : this,
1004 sortable : !this.active_repo.hasmorepages,
1005 callback : function(e, node) {
1006 if (e.preventDefault) {e.preventDefault();}
1007 if (node.children) {
1008 if (this.active_repo.dynload) {
1009 this.list({'path':node.path});
1011 this.filelist = node.children;
1015 this.select_file(node);
1018 classnamecallback : this.classnamecallback
1020 this.fpnode.one('.fp-content').fp_display_filelist(options, list, this.lazyloading);
1022 /** If more than one page available, requests and displays the files from the next page */
1023 request_next_page: function() {
1024 if (!this.active_repo.hasmorepages || this.active_repo.nextpagerequested) {
1028 this.active_repo.nextpagerequested = true;
1029 var nextpage = this.active_repo.page+1;
1032 repo_id: this.active_repo.id
1034 var action = this.active_repo.issearchresult ? 'search' : 'list';
1036 path: this.currentpath,
1039 client_id: this.options.client_id,
1040 repository_id: args.repo_id,
1042 callback: function(id, obj, args) {
1043 var scope = args.scope;
1044 // Check that we are still in the same repository and are expecting this page. We have no way
1045 // to compare the requested page and the one returned, so we assume that if the last chunk
1046 // of the breadcrumb is similar, then we probably are on the same page.
1047 var samepage = true;
1048 if (obj.path && scope.filepath) {
1049 var pathbefore = scope.filepath[scope.filepath.length-1];
1050 var pathafter = obj.path[obj.path.length-1];
1051 if (pathbefore.path != pathafter.path) {
1055 if (scope.active_repo.hasmorepages && obj.list && obj.page &&
1056 obj.repo_id == scope.active_repo.id &&
1057 obj.page == scope.active_repo.page+1 && samepage) {
1058 scope.parse_repository_options(obj, true);
1059 scope.view_files(obj.list)
1064 select_file: function(args) {
1065 var argstitle = args.title;
1066 // Limit the string length so it fits nicely on mobile devices
1067 var titlelength = 30;
1068 if (argstitle.length > titlelength) {
1069 argstitle = argstitle.substring(0, titlelength) + '...';
1071 Y.one('#fp-file_label_'+this.options.client_id).setContent(Y.Escape.html(M.util.get_string('select', 'repository')+' '+argstitle));
1072 this.selectui.show();
1073 Y.one('#'+this.selectnode.get('id')).focus();
1074 var client_id = this.options.client_id;
1075 var selectnode = this.selectnode;
1076 var return_types = this.options.repositories[this.active_repo.id].return_types;
1077 selectnode.removeClass('loading');
1078 selectnode.one('.fp-saveas input').set('value', args.title);
1080 var imgnode = Y.Node.create('<img/>').
1081 set('src', args.realthumbnail ? args.realthumbnail : args.thumbnail).
1082 setStyle('maxHeight', ''+(args.thumbnail_height ? args.thumbnail_height : 90)+'px').
1083 setStyle('maxWidth', ''+(args.thumbnail_width ? args.thumbnail_width : 90)+'px');
1084 selectnode.one('.fp-thumbnail').setContent('').appendChild(imgnode);
1086 // filelink is the array of file-link-types available for this repository in this env
1087 var filelinktypes = [2/*FILE_INTERNAL*/,1/*FILE_EXTERNAL*/,4/*FILE_REFERENCE*/,8/*FILE_CONTROLLED_LINK*/];
1088 var filelink = {}, firstfilelink = null, filelinkcount = 0;
1089 for (var i in filelinktypes) {
1090 var allowed = (return_types & filelinktypes[i]) &&
1091 (this.options.return_types & filelinktypes[i]);
1092 if (filelinktypes[i] == 1/*FILE_EXTERNAL*/ && !this.options.externallink && this.options.env == 'editor') {
1093 // special configuration setting 'repositoryallowexternallinks' may prevent
1094 // using external links in editor environment
1097 filelink[filelinktypes[i]] = allowed;
1098 firstfilelink = (firstfilelink==null && allowed) ? filelinktypes[i] : firstfilelink;
1099 filelinkcount += allowed ? 1 : 0;
1101 var defaultreturntype = this.options.repositories[this.active_repo.id].defaultreturntype;
1102 if (defaultreturntype) {
1103 if (filelink[defaultreturntype]) {
1104 firstfilelink = defaultreturntype;
1107 // make radio buttons enabled if this file-link-type is available and only if there are more than one file-link-type option
1108 // check the first available file-link-type option
1109 for (var linktype in filelink) {
1110 var el = selectnode.one('.fp-linktype-'+linktype);
1111 el.addClassIf('uneditable', !(filelink[linktype] && filelinkcount>1));
1112 el.one('input').set('checked', (firstfilelink == linktype) ? 'checked' : '').simulate('change');
1115 // TODO MDL-32532: attributes 'hasauthor' and 'haslicense' need to be obsolete,
1116 selectnode.one('.fp-setauthor input').set('value', args.author ? args.author : this.options.author);
1117 this.set_selected_license(selectnode.one('.fp-setlicense'), args.license);
1118 selectnode.one('form #filesource-'+client_id).set('value', args.source);
1120 // display static information about a file (when known)
1121 var attrs = ['datemodified','datecreated','size','license','author','dimensions'];
1122 for (var i in attrs) {
1123 if (selectnode.one('.fp-'+attrs[i])) {
1124 var value = (args[attrs[i]+'_f']) ? args[attrs[i]+'_f'] : (args[attrs[i]] ? args[attrs[i]] : '');
1125 selectnode.one('.fp-'+attrs[i]).addClassIf('fp-unknown', ''+value == '')
1126 .one('.fp-value').setContent(Y.Escape.html(value));
1130 setup_select_file: function() {
1131 var client_id = this.options.client_id;
1132 var selectnode = this.selectnode;
1133 var getfile = selectnode.one('.fp-select-confirm');
1134 // bind labels with corresponding inputs
1135 selectnode.all('.fp-saveas,.fp-linktype-2,.fp-linktype-1,.fp-linktype-4,fp-linktype-8,.fp-setauthor,.fp-setlicense').each(function (node) {
1136 node.all('label').set('for', node.one('input,select').generateID());
1138 selectnode.one('.fp-linktype-2 input').setAttrs({value: 2, name: 'linktype'});
1139 selectnode.one('.fp-linktype-1 input').setAttrs({value: 1, name: 'linktype'});
1140 selectnode.one('.fp-linktype-4 input').setAttrs({value: 4, name: 'linktype'});
1141 selectnode.one('.fp-linktype-8 input').setAttrs({value: 8, name: 'linktype'});
1142 var changelinktype = function(e) {
1143 if (e.currentTarget.get('checked')) {
1144 var allowinputs = e.currentTarget.get('value') != 1/*FILE_EXTERNAL*/;
1145 selectnode.all('.fp-setauthor,.fp-setlicense,.fp-saveas').each(function(node){
1146 node.addClassIf('uneditable', !allowinputs);
1147 node.all('input,select').set('disabled', allowinputs?'':'disabled');
1151 selectnode.all('.fp-linktype-2,.fp-linktype-1,.fp-linktype-4,.fp-linktype-8').each(function (node) {
1152 node.one('input').on('change', changelinktype, this);
1154 this.populate_licenses_select(selectnode.one('.fp-setlicense select'));
1155 // register event on clicking submit button
1156 getfile.on('click', function(e) {
1158 var client_id = this.options.client_id;
1160 var repository_id = this.active_repo.id;
1161 var title = selectnode.one('.fp-saveas input').get('value');
1162 var filesource = selectnode.one('form #filesource-'+client_id).get('value');
1163 var params = {'title':title, 'source':filesource, 'savepath': this.options.savepath};
1164 var license = selectnode.one('.fp-setlicense select');
1166 params['license'] = license.get('value');
1167 var origlicense = selectnode.one('.fp-license .fp-value');
1169 origlicense = origlicense.getContent();
1171 this.set_preference('recentlicense', license.get('value'));
1173 params['author'] = selectnode.one('.fp-setauthor input').get('value');
1175 var return_types = this.options.repositories[this.active_repo.id].return_types;
1176 if (this.options.env == 'editor') {
1177 // in editor, images are stored in '/' only
1178 params.savepath = '/';
1180 if ((this.options.externallink || this.options.env != 'editor') &&
1181 (return_types & 1/*FILE_EXTERNAL*/) &&
1182 (this.options.return_types & 1/*FILE_EXTERNAL*/) &&
1183 selectnode.one('.fp-linktype-1 input').get('checked')) {
1184 params['linkexternal'] = 'yes';
1185 } else if ((return_types & 4/*FILE_REFERENCE*/) &&
1186 (this.options.return_types & 4/*FILE_REFERENCE*/) &&
1187 selectnode.one('.fp-linktype-4 input').get('checked')) {
1188 params['usefilereference'] = '1';
1189 } else if ((return_types & 8/*FILE_CONTROLLED_LINK*/) &&
1190 (this.options.return_types & 8/*FILE_CONTROLLED_LINK*/) &&
1191 selectnode.one('.fp-linktype-8 input').get('checked')) {
1192 params['usecontrolledlink'] = '1';
1195 selectnode.addClass('loading');
1198 client_id: client_id,
1199 repository_id: repository_id,
1201 onerror: function(id, obj, args) {
1202 selectnode.removeClass('loading');
1203 scope.selectui.hide();
1205 callback: function(id, obj, args) {
1206 selectnode.removeClass('loading');
1207 if (obj.event == 'fileexists') {
1208 scope.process_existing_file(obj);
1211 if (scope.options.editor_target && scope.options.env=='editor') {
1212 scope.options.editor_target.value=obj.url;
1213 scope.options.editor_target.onchange();
1216 obj.client_id = client_id;
1217 var formcallback_scope = args.scope.options.magicscope ? args.scope.options.magicscope : args.scope;
1218 scope.options.formcallback.apply(formcallback_scope, [obj]);
1222 var elform = selectnode.one('form');
1223 elform.appendChild(Y.Node.create('<input/>').
1224 setAttrs({type:'hidden',id:'filesource-'+client_id}));
1225 elform.on('keydown', function(e) {
1226 if (e.keyCode == 13) {
1227 getfile.simulate('click');
1231 var cancel = selectnode.one('.fp-select-cancel');
1232 cancel.on('click', function(e) {
1234 this.selectui.hide();
1238 // First check there isn't already an interval in play, and if there is kill it now.
1239 if (this.waitinterval != null) {
1240 clearInterval(this.waitinterval);
1242 // Prepare the root node we will set content for and the loading template we want to display as a YUI node.
1243 var root = this.fpnode.one('.fp-content');
1244 var content = Y.Node.create(M.core_filepicker.templates.loading).addClass('fp-content-hidden').setStyle('opacity', 0);
1246 // Initiate an interval, we will have a count which will increment every 100 milliseconds.
1247 // Count 0 - the loading icon will have visibility set to hidden (invisible) and have an opacity of 0 (invisible also)
1248 // Count 5 - the visiblity will be switched to visible but opacity will still be at 0 (inivisible)
1249 // Counts 6 - 15 opacity will be increased by 0.1 making the loading icon visible over the period of a second
1250 // Count 16 - The interval will be cancelled.
1251 var interval = setInterval(function(){
1252 if (!content || !root.contains(content) || count >= 15) {
1253 clearInterval(interval);
1257 content.removeClass('fp-content-hidden');
1258 } else if (count > 5) {
1259 var opacity = parseFloat(content.getStyle('opacity'));
1260 content.setStyle('opacity', opacity + 0.1);
1265 // Store the wait interval so that we can check it in the future.
1266 this.waitinterval = interval;
1267 // Set the content to the loading template.
1268 root.setContent(content);
1270 viewbar_set_enabled: function(mode) {
1271 var viewbar = this.fpnode.one('.fp-viewbar')
1274 viewbar.addClass('enabled').removeClass('disabled');
1275 this.fpnode.all('.fp-vb-icons,.fp-vb-tree,.fp-vb-details').setAttribute("aria-disabled", "false");
1276 this.fpnode.all('.fp-vb-icons,.fp-vb-tree,.fp-vb-details').setAttribute("tabindex", "");
1278 viewbar.removeClass('enabled').addClass('disabled');
1279 this.fpnode.all('.fp-vb-icons,.fp-vb-tree,.fp-vb-details').setAttribute("aria-disabled", "true");
1280 this.fpnode.all('.fp-vb-icons,.fp-vb-tree,.fp-vb-details').setAttribute("tabindex", "-1");
1283 this.fpnode.all('.fp-vb-icons,.fp-vb-tree,.fp-vb-details').removeClass('checked');
1284 var modes = {1:'icons', 2:'tree', 3:'details'};
1285 this.fpnode.all('.fp-vb-'+modes[this.viewmode]).addClass('checked');
1287 viewbar_clicked: function(e) {
1289 var viewbar = this.fpnode.one('.fp-viewbar')
1290 if (!viewbar || !viewbar.hasClass('disabled')) {
1291 if (e.currentTarget.hasClass('fp-vb-tree')) {
1293 } else if (e.currentTarget.hasClass('fp-vb-details')) {
1298 this.viewbar_set_enabled(true)
1300 this.set_preference('recentviewmode', this.viewmode);
1303 render: function() {
1304 var client_id = this.options.client_id;
1305 var fpid = "filepicker-"+ client_id;
1306 var labelid = 'fp-dialog-label_'+ client_id;
1308 var draggable = true;
1309 this.fpnode = Y.Node.create(M.core_filepicker.templates.generallayout).
1310 set('id', 'filepicker-'+client_id).set('aria-labelledby', labelid);
1312 if (this.in_iframe()) {
1313 width = Math.floor(window.innerWidth * 0.95);
1317 this.mainui = new M.core.dialogue({
1318 extraClasses : ['filepicker'],
1319 draggable : draggable,
1320 bodyContent : this.fpnode,
1321 headerContent: '<h3 id="'+ labelid +'">'+ M.util.get_string('filepicker', 'repository') +'</h3>',
1326 responsiveWidth : 768,
1328 zIndex : this.options.zIndex
1331 // create panel for selecting a file (initially hidden)
1332 this.selectnode = Y.Node.create(M.core_filepicker.templates.selectlayout).
1333 set('id', 'filepicker-select-'+client_id).
1334 set('aria-live', 'assertive').
1335 set('role', 'dialog');
1337 var fplabel = 'fp-file_label_'+ client_id;
1338 this.selectui = new M.core.dialogue({
1339 headerContent: '<h3 id="' + fplabel +'">'+M.util.get_string('select', 'repository')+'</h3>',
1342 bodyContent : this.selectnode,
1346 zIndex : this.options.zIndex
1348 Y.one('#'+this.selectnode.get('id')).setAttribute('aria-labelledby', fplabel);
1349 // event handler for lazy loading of thumbnails and next page
1350 this.fpnode.one('.fp-content').on(['scroll','resize'], this.content_scrolled, this);
1351 // save template for one path element and location of path bar
1352 if (this.fpnode.one('.fp-path-folder')) {
1353 this.pathnode = this.fpnode.one('.fp-path-folder');
1354 this.pathbar = this.pathnode.get('parentNode');
1355 this.pathbar.removeChild(this.pathnode);
1357 // assign callbacks for view mode switch buttons
1358 this.fpnode.one('.fp-vb-icons').on('click', this.viewbar_clicked, this);
1359 this.fpnode.one('.fp-vb-tree').on('click', this.viewbar_clicked, this);
1360 this.fpnode.one('.fp-vb-details').on('click', this.viewbar_clicked, this);
1362 // assign callbacks for toolbar links
1363 this.setup_toolbar();
1364 this.setup_select_file();
1367 // processing repository listing
1368 // Resort the repositories by sortorder
1369 var sorted_repositories = [];
1370 for (var i in this.options.repositories) {
1371 sorted_repositories[i] = this.options.repositories[i];
1373 sorted_repositories.sort(function(a,b){return a.sortorder-b.sortorder});
1374 // extract one repository template and repeat it for all repositories available,
1375 // set name and icon and assign callbacks
1376 var reponode = this.fpnode.one('.fp-repo');
1378 var list = reponode.get('parentNode');
1379 list.removeChild(reponode);
1380 for (i in sorted_repositories) {
1381 var repository = sorted_repositories[i];
1382 var node = reponode.cloneNode(true);
1383 list.appendChild(node);
1385 set('id', 'fp-repo-'+client_id+'-'+repository.id).
1386 on('click', function(e, repository_id) {
1388 this.set_preference('recentrepository', repository_id);
1390 this.list({'repo_id':repository_id});
1391 }, this /*handler running scope*/, repository.id/*second argument of handler*/);
1392 node.one('.fp-repo-name').setContent(Y.Escape.html(repository.name));
1393 node.one('.fp-repo-icon').set('src', repository.icon);
1395 node.addClass('first');
1397 if (i==sorted_repositories.length-1) {
1398 node.addClass('last');
1401 node.addClass('even');
1403 node.addClass('odd');
1407 // display error if no repositories found
1408 if (sorted_repositories.length==0) {
1409 this.display_error(M.util.get_string('norepositoriesavailable', 'repository'), 'norepositoriesavailable')
1411 // display repository that was used last time
1413 this.show_recent_repository();
1415 parse_repository_options: function(data, appendtolist) {
1418 if (!this.filelist) {
1421 for (var i in data.list) {
1422 this.filelist[this.filelist.length] = data.list[i];
1426 this.filelist = data.list?data.list:null;
1427 this.lazyloading = {};
1429 this.filepath = data.path?data.path:null;
1430 this.objecttag = data.object?data.object:null;
1431 this.active_repo = {};
1432 this.active_repo.issearchresult = data.issearchresult ? true : false;
1433 this.active_repo.defaultreturntype = data.defaultreturntype?data.defaultreturntype:null;
1434 this.active_repo.dynload = data.dynload?data.dynload:false;
1435 this.active_repo.pages = Number(data.pages?data.pages:null);
1436 this.active_repo.page = Number(data.page?data.page:null);
1437 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))
1438 this.active_repo.id = data.repo_id?data.repo_id:null;
1439 this.active_repo.nosearch = (data.login || data.nosearch); // this is either login form or 'nosearch' attribute set
1440 this.active_repo.norefresh = (data.login || data.norefresh); // this is either login form or 'norefresh' attribute set
1441 this.active_repo.nologin = (data.login || data.nologin); // this is either login form or 'nologin' attribute is set
1442 this.active_repo.logouttext = data.logouttext?data.logouttext:null;
1443 this.active_repo.logouturl = (data.logouturl || '');
1444 this.active_repo.message = (data.message || '');
1445 this.active_repo.help = data.help?data.help:null;
1446 this.active_repo.manage = data.manage?data.manage:null;
1447 this.print_header();
1449 print_login: function(data) {
1450 this.parse_repository_options(data);
1451 var client_id = this.options.client_id;
1452 var repository_id = data.repo_id;
1453 var l = this.logindata = data.login;
1455 var action = data['login_btn_action'] ? data['login_btn_action'] : 'login';
1456 var form_id = 'fp-form-'+client_id;
1458 var loginform_node = Y.Node.create(M.core_filepicker.templates.loginform);
1459 loginform_node.one('form').set('id', form_id);
1460 this.fpnode.one('.fp-content').setContent('').appendChild(loginform_node);
1462 'popup' : loginform_node.one('.fp-login-popup'),
1463 'textarea' : loginform_node.one('.fp-login-textarea'),
1464 'select' : loginform_node.one('.fp-login-select'),
1465 'text' : loginform_node.one('.fp-login-text'),
1466 'radio' : loginform_node.one('.fp-login-radiogroup'),
1467 'checkbox' : loginform_node.one('.fp-login-checkbox'),
1468 'input' : loginform_node.one('.fp-login-input')
1471 for (var i in templates) {
1473 container = templates[i].get('parentNode');
1474 container.removeChild(templates[i]);
1479 if (templates[l[k].type]) {
1480 var node = templates[l[k].type].cloneNode(true);
1482 node = templates['input'].cloneNode(true);
1484 if (l[k].type == 'popup') {
1486 loginurl = l[k].url;
1487 var popupbutton = node.one('button');
1488 popupbutton.on('click', function(e){
1489 M.core_filepicker.active_filepicker = this;
1490 window.open(loginurl, 'repo_auth', 'location=0,status=0,width=500,height=300,scrollbars=yes');
1493 loginform_node.one('form').on('keydown', function(e) {
1494 if (e.keyCode == 13) {
1495 popupbutton.simulate('click');
1499 loginform_node.all('.fp-login-submit').remove();
1501 } else if(l[k].type=='textarea') {
1503 if (node.one('label')) {
1504 node.one('label').set('for', l[k].id).setContent(l[k].label);
1506 node.one('textarea').setAttrs({id:l[k].id, name:l[k].name});
1507 } else if(l[k].type=='select') {
1509 if (node.one('label')) {
1510 node.one('label').set('for', l[k].id).setContent(l[k].label);
1512 node.one('select').setAttrs({id:l[k].id, name:l[k].name}).setContent('');
1513 for (i in l[k].options) {
1514 node.one('select').appendChild(
1515 Y.Node.create('<option/>').
1516 set('value', l[k].options[i].value).
1517 setContent(l[k].options[i].label));
1519 } else if(l[k].type=='radio') {
1520 // radio input element
1521 node.all('label').setContent(l[k].label);
1522 var list = l[k].value.split('|');
1523 var labels = l[k].value_label.split('|');
1524 var radionode = null;
1525 for(var item in list) {
1526 if (radionode == null) {
1527 radionode = node.one('.fp-login-radio');
1528 radionode.one('input').set('checked', 'checked');
1530 var x = radionode.cloneNode(true);
1531 radionode.insert(x, 'after');
1533 radionode.one('input').set('checked', '');
1535 radionode.one('input').setAttrs({id:''+l[k].id+item, name:l[k].name,
1536 type:l[k].type, value:list[item]});
1537 radionode.all('label').setContent(labels[item]).set('for', ''+l[k].id+item)
1539 if (radionode == null) {
1540 node.one('.fp-login-radio').remove();
1544 if (node.one('label')) { node.one('label').set('for', l[k].id).setContent(l[k].label) }
1546 set('type', l[k].type).
1548 set('name', l[k].name).
1549 set('value', l[k].value?l[k].value:'')
1551 container.appendChild(node);
1553 // custom label text for submit button
1554 if (data['login_btn_label']) {
1555 loginform_node.all('.fp-login-submit').setContent(data['login_btn_label'])
1557 // register button action for login and search
1558 if (action == 'login' || action == 'search') {
1559 loginform_node.one('.fp-login-submit').on('click', function(e){
1564 'action':(action == 'search') ? 'search' : 'signin',
1566 'client_id': client_id,
1567 'repository_id': repository_id,
1568 'form': {id:form_id, upload:false, useDisabled:true},
1569 'callback': this.display_response
1573 // if 'Enter' is pressed in the form, simulate the button click
1574 if (loginform_node.one('.fp-login-submit')) {
1575 loginform_node.one('form').on('keydown', function(e) {
1576 if (e.keyCode == 13) {
1577 loginform_node.one('.fp-login-submit').simulate('click')
1583 display_response: function(id, obj, args) {
1584 var scope = args.scope;
1585 // highlight the current repository in repositories list
1586 scope.fpnode.all('.fp-repo.active').removeClass('active');
1587 scope.fpnode.all('#fp-repo-'+scope.options.client_id+'-'+obj.repo_id).addClass('active')
1588 // add class repository_REPTYPE to the filepicker (for repository-specific styles)
1589 for (var i in scope.options.repositories) {
1590 scope.fpnode.removeClass('repository_'+scope.options.repositories[i].type)
1592 if (obj.repo_id && scope.options.repositories[obj.repo_id]) {
1593 scope.fpnode.addClass('repository_'+scope.options.repositories[obj.repo_id].type)
1595 Y.one('.file-picker .fp-repo-items').focus();
1599 scope.viewbar_set_enabled(false);
1600 scope.print_login(obj);
1601 } else if (obj.upload) {
1602 scope.viewbar_set_enabled(false);
1603 scope.parse_repository_options(obj);
1604 scope.create_upload_form(obj);
1605 } else if (obj.object) {
1606 M.core_filepicker.active_filepicker = scope;
1607 scope.viewbar_set_enabled(false);
1608 scope.parse_repository_options(obj);
1609 scope.create_object_container(obj.object);
1610 } else if (obj.list) {
1611 scope.viewbar_set_enabled(true);
1612 scope.parse_repository_options(obj);
1616 list: function(args) {
1620 if (!args.repo_id) {
1621 args.repo_id = this.active_repo.id;
1626 this.currentpath = args.path;
1629 client_id: this.options.client_id,
1630 repository_id: args.repo_id,
1634 callback: this.display_response
1637 populate_licenses_select: function(node) {
1641 node.setContent('');
1642 var licenses = this.options.licenses;
1643 var recentlicense = this.get_preference('recentlicense');
1644 if (recentlicense) {
1645 this.options.defaultlicense=recentlicense;
1647 for (var i in licenses) {
1648 var option = Y.Node.create('<option/>').
1649 set('selected', (this.options.defaultlicense==licenses[i].shortname)).
1650 set('value', licenses[i].shortname).
1651 setContent(Y.Escape.html(licenses[i].fullname));
1652 node.appendChild(option)
1655 set_selected_license: function(node, value) {
1656 var licenseset = false;
1657 node.all('option').each(function(el) {
1658 if (el.get('value')==value || el.getContent()==value) {
1659 el.set('selected', true);
1664 // we did not find the value in the list
1665 var recentlicense = this.get_preference('recentlicense');
1666 node.all('option[selected]').set('selected', false);
1667 node.all('option[value='+recentlicense+']').set('selected', true);
1670 create_object_container: function(data) {
1671 var content = this.fpnode.one('.fp-content');
1672 content.setContent('');
1673 //var str = '<object data="'+data.src+'" type="'+data.type+'" width="98%" height="98%" id="container_object" class="fp-object-container mdl-align"></object>';
1674 var container = Y.Node.create('<object/>').
1675 setAttrs({data:data.src, type:data.type, id:'container_object'}).
1676 addClass('fp-object-container');
1677 content.setContent('').appendChild(container);
1679 create_upload_form: function(data) {
1680 var client_id = this.options.client_id;
1681 var id = data.upload.id+'_'+client_id;
1682 var content = this.fpnode.one('.fp-content');
1683 var template_name = 'uploadform_'+this.options.repositories[data.repo_id].type;
1684 var template = M.core_filepicker.templates[template_name] || M.core_filepicker.templates['uploadform'];
1685 content.setContent(template);
1687 content.all('.fp-file,.fp-saveas,.fp-setauthor,.fp-setlicense').each(function (node) {
1688 node.all('label').set('for', node.one('input,select').generateID());
1690 content.one('form').set('id', id);
1691 content.one('.fp-file input').set('name', 'repo_upload_file');
1692 if (data.upload.label && content.one('.fp-file label')) {
1693 content.one('.fp-file label').setContent(data.upload.label);
1695 content.one('.fp-saveas input').set('name', 'title');
1696 content.one('.fp-setauthor input').setAttrs({name:'author', value:this.options.author});
1697 content.one('.fp-setlicense select').set('name', 'license');
1698 this.populate_licenses_select(content.one('.fp-setlicense select'))
1699 // append hidden inputs to the upload form
1700 content.one('form').appendChild(Y.Node.create('<input/>').
1701 setAttrs({type:'hidden',name:'itemid',value:this.options.itemid}));
1702 var types = this.options.accepted_types;
1703 for (var i in types) {
1704 content.one('form').appendChild(Y.Node.create('<input/>').
1705 setAttrs({type:'hidden',name:'accepted_types[]',value:types[i]}));
1709 content.one('.fp-upload-btn').on('click', function(e) {
1711 var license = content.one('.fp-setlicense select');
1713 this.set_preference('recentlicense', license.get('value'));
1714 if (!content.one('.fp-file input').get('value')) {
1715 scope.print_msg(M.util.get_string('nofilesattached', 'repository'), 'error');
1722 client_id: client_id,
1723 params: {'savepath':scope.options.savepath},
1724 repository_id: scope.active_repo.id,
1725 form: {id: id, upload:true},
1726 onerror: function(id, o, args) {
1727 scope.create_upload_form(data);
1729 callback: function(id, o, args) {
1730 if (o.event == 'fileexists') {
1731 scope.create_upload_form(data);
1732 scope.process_existing_file(o);
1735 if (scope.options.editor_target&&scope.options.env=='editor') {
1736 scope.options.editor_target.value=o.url;
1737 scope.options.editor_target.onchange();
1740 o.client_id = client_id;
1741 var formcallback_scope = args.scope.options.magicscope ? args.scope.options.magicscope : args.scope;
1742 scope.options.formcallback.apply(formcallback_scope, [o]);
1747 /** setting handlers and labels for elements in toolbar. Called once during the initial render of filepicker */
1748 setup_toolbar: function() {
1749 var client_id = this.options.client_id;
1750 var toolbar = this.fpnode.one('.fp-toolbar');
1751 toolbar.one('.fp-tb-logout').one('a,button').on('click', function(e) {
1753 if (!this.active_repo.nologin) {
1757 client_id: this.options.client_id,
1758 repository_id: this.active_repo.id,
1760 callback: this.display_response
1763 if (this.active_repo.logouturl) {
1764 window.open(this.active_repo.logouturl, 'repo_auth', 'location=0,status=0,width=500,height=300,scrollbars=yes');
1767 toolbar.one('.fp-tb-refresh').one('a,button').on('click', function(e) {
1769 if (!this.active_repo.norefresh) {
1770 this.list({ path: this.currentpath });
1773 toolbar.one('.fp-tb-search form').
1774 set('method', 'POST').
1775 set('id', 'fp-tb-search-'+client_id).
1776 on('submit', function(e) {
1778 if (!this.active_repo.nosearch) {
1782 client_id: this.options.client_id,
1783 repository_id: this.active_repo.id,
1784 form: {id: 'fp-tb-search-'+client_id, upload:false, useDisabled:true},
1785 callback: this.display_response
1790 // it does not matter what kind of element is .fp-tb-manage, we create a dummy <a>
1791 // element and use it to open url on click event
1792 var managelnk = Y.Node.create('<a/>').
1793 setAttrs({id:'fp-tb-manage-'+client_id+'-link', target:'_blank'}).
1794 setStyle('display', 'none');
1795 toolbar.append(managelnk);
1796 toolbar.one('.fp-tb-manage').one('a,button').
1797 on('click', function(e) {
1799 managelnk.simulate('click')
1802 // same with .fp-tb-help
1803 var helplnk = Y.Node.create('<a/>').
1804 setAttrs({id:'fp-tb-help-'+client_id+'-link', target:'_blank'}).
1805 setStyle('display', 'none');
1806 toolbar.append(helplnk);
1807 toolbar.one('.fp-tb-help').one('a,button').
1808 on('click', function(e) {
1810 helplnk.simulate('click')
1813 hide_header: function() {
1814 if (this.fpnode.one('.fp-toolbar')) {
1815 this.fpnode.one('.fp-toolbar').addClass('empty');
1818 this.pathbar.setContent('').addClass('empty');
1821 print_header: function() {
1822 var r = this.active_repo;
1824 var client_id = this.options.client_id;
1827 var toolbar = this.fpnode.one('.fp-toolbar');
1828 if (!toolbar) { return; }
1830 var enable_tb_control = function(node, enabled) {
1831 if (!node) { return; }
1832 node.addClassIf('disabled', !enabled).addClassIf('enabled', enabled)
1834 toolbar.removeClass('empty');
1838 // TODO 'back' permanently disabled for now. Note, flickr_public uses 'Logout' for it!
1839 enable_tb_control(toolbar.one('.fp-tb-back'), false);
1842 enable_tb_control(toolbar.one('.fp-tb-search'), !r.nosearch);
1844 var searchform = toolbar.one('.fp-tb-search form');
1845 searchform.setContent('');
1848 action:'searchform',
1849 repository_id: this.active_repo.id,
1850 callback: function(id, obj, args) {
1851 if (obj.repo_id == scope.active_repo.id && obj.form) {
1852 // if we did not jump to another repository meanwhile
1853 searchform.setContent(obj.form);
1854 // Highlight search text when user click for search.
1855 var searchnode = searchform.one('input[name="s"]');
1857 searchnode.once('click', function(e) {
1868 // weather we use cache for this instance, this button will reload listing anyway
1869 enable_tb_control(toolbar.one('.fp-tb-refresh'), !r.norefresh);
1872 enable_tb_control(toolbar.one('.fp-tb-logout'), !r.nologin);
1875 enable_tb_control(toolbar.one('.fp-tb-manage'), r.manage);
1876 Y.one('#fp-tb-manage-'+client_id+'-link').set('href', r.manage);
1879 enable_tb_control(toolbar.one('.fp-tb-help'), r.help);
1880 Y.one('#fp-tb-help-'+client_id+'-link').set('href', r.help);
1883 enable_tb_control(toolbar.one('.fp-tb-message'), r.message);
1884 toolbar.one('.fp-tb-message').setContent(r.message);
1886 print_path: function() {
1887 if (!this.pathbar) {
1890 this.pathbar.setContent('').addClass('empty');
1891 var p = this.filepath;
1892 if (p && p.length!=0 && this.viewmode != 2) {
1893 for(var i = 0; i < p.length; i++) {
1894 var el = this.pathnode.cloneNode(true);
1895 this.pathbar.appendChild(el);
1897 el.addClass('first');
1899 if (i == p.length-1) {
1900 el.addClass('last');
1903 el.addClass('even');
1907 el.all('.fp-path-folder-name').setContent(Y.Escape.html(p[i].name));
1911 this.list({'path':path});
1915 this.pathbar.removeClass('empty');
1919 this.selectui.hide();
1920 if (this.process_dlg) {
1921 this.process_dlg.hide();
1924 this.msg_dlg.hide();
1932 this.show_recent_repository();
1937 launch: function() {
1940 show_recent_repository: function() {
1942 this.viewbar_set_enabled(false);
1943 var repository_id = this.get_preference('recentrepository');
1944 this.viewmode = this.get_preference('recentviewmode');
1945 if (this.viewmode != 2 && this.viewmode != 3) {
1948 if (this.options.repositories[repository_id]) {
1949 this.list({'repo_id':repository_id});
1952 get_preference: function (name) {
1953 if (this.options.userprefs[name]) {
1954 return this.options.userprefs[name];
1959 set_preference: function(name, value) {
1960 if (this.options.userprefs[name] != value) {
1961 M.util.set_user_preference('filepicker_' + name, value);
1962 this.options.userprefs[name] = value;
1965 in_iframe: function () {
1966 // If we're not the top window then we're in an iFrame
1967 return window.self !== window.top;
1970 var loading = Y.one('#filepicker-loading-'+options.client_id);
1972 loading.setStyle('display', 'none');
1974 M.core_filepicker.instances[options.client_id] = new FilePickerHelper(options);