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;
269 // Removed bind as of MDL-62415 as it overwrites the search tree results
273 // there is no path information, just display all elements as a list, without hierarchy
274 for(k in fileslist) {
275 build_tree(fileslist[k], scope.treeview.getRoot());
278 scope.treeview.subscribe('clickEvent', function(e){
279 e.node.highlight(false);
280 var callback = options.callback;
281 if (options.rightclickcallback && e.event.target &&
282 Y.Node(e.event.target).ancestor('.fp-treeview .fp-contextmenu', true)) {
283 callback = options.rightclickcallback;
285 Y.bind(callback, options.callbackcontext)(e, e.node.fileinfo);
286 Y.YUI2.util.Event.stopEvent(e.event)
288 // TODO MDL-32736 support right click
289 /*if (options.rightclickcallback) {
290 scope.treeview.subscribe('dblClickEvent', function(e){
291 e.node.highlight(false);
292 Y.bind(options.rightclickcallback, options.callbackcontext)(e, e.node.fileinfo);
295 scope.treeview.draw();
297 /** formatting function for table view */
298 var formatValue = function (o){
299 if (o.data[''+o.column.key+'_f_s']) {return o.data[''+o.column.key+'_f_s'];}
300 else if (o.data[''+o.column.key+'_f']) {return o.data[''+o.column.key+'_f'];}
301 else if (o.value) {return o.value;}
304 /** formatting function for table view */
305 var formatTitle = function(o) {
306 var el = Y.Node.create('<div/>');
307 el.appendChild(options.filenode.cloneNode(true)); // TODO not node but string!
308 el.get('children').addClass(o.data['classname']);
309 el.one('.fp-filename').setContent(o.value);
310 if (o.data['icon']) {
311 el.one('.fp-icon').appendChild(Y.Node.create('<img/>'));
312 el.one('.fp-icon img').setImgSrc(o.data['icon'], o.data['realicon'], lazyloading);
314 if (options.rightclickcallback) {
315 el.get('children').addClass('fp-hascontextmenu');
317 // TODO add tooltip with o.data['title'] (o.value) or o.data['thumbnail_title']
318 return el.getContent();
322 * Generate slave checkboxes based on toggleall's specification
323 * @param {object} o An object reprsenting the record for the current row.
324 * @return {html} The checkbox html
326 var formatCheckbox = function(o) {
327 var el = Y.Node.create('<div/>');
329 var checkbox = Y.Node.create('<input/>')
330 .setAttribute('type', 'checkbox')
331 .setAttribute('data-fieldtype', 'checkbox')
332 .setAttribute('data-fullname', o.data.fullname)
333 .setAttribute('data-action', 'toggle')
334 .setAttribute('data-toggle', 'slave')
335 .setAttribute('data-togglegroup', 'file-selections')
336 .setAttribute('data-toggle-selectall', M.util.get_string('selectall', 'moodle'))
337 .setAttribute('data-toggle-deselectall', M.util.get_string('deselectall', 'moodle'));
339 var checkboxLabel = Y.Node.create('<label>')
340 .setHTML("Select file '" + o.data.fullname + "'")
343 for: checkbox.generateID(),
346 el.appendChild(checkbox);
347 el.appendChild(checkboxLabel);
348 return el.getContent();
350 /** sorting function for table view */
351 var sortFoldersFirst = function(a, b, desc) {
352 if (a.get('isfolder') && !b.get('isfolder')) {
355 if (!a.get('isfolder') && b.get('isfolder')) {
358 var aa = a.get(this.key), bb = b.get(this.key), dir = desc ? -1 : 1;
359 return (aa > bb) ? dir : ((aa < bb) ? -dir : 0);
361 /** initialize table view */
362 var initialize_table_view = function() {
364 {key: "displayname", label: M.util.get_string('name', 'moodle'), allowHTML: true, formatter: formatTitle,
365 sortable: true, sortFn: sortFoldersFirst},
366 {key: "datemodified", label: M.util.get_string('lastmodified', 'moodle'), allowHTML: true, formatter: formatValue,
367 sortable: true, sortFn: sortFoldersFirst},
368 {key: "size", label: M.util.get_string('size', 'repository'), allowHTML: true, formatter: formatValue,
369 sortable: true, sortFn: sortFoldersFirst},
370 {key: "mimetype", label: M.util.get_string('type', 'repository'), allowHTML: true,
371 sortable: true, sortFn: sortFoldersFirst}
374 // Generate a checkbox based on toggleall's specification
375 var div = Y.Node.create('<div/>');
376 var checkbox = Y.Node.create('<input/>')
377 .setAttribute('type', 'checkbox')
378 // .setAttribute('title', M.util.get_string('selectallornone', 'form'))
379 .setAttribute('data-action', 'toggle')
380 .setAttribute('data-toggle', 'master')
381 .setAttribute('data-togglegroup', 'file-selections');
383 var checkboxLabel = Y.Node.create('<label>')
384 .setHTML(M.util.get_string('selectallornone', 'form'))
387 for: checkbox.generateID(),
390 div.appendChild(checkboxLabel);
391 div.appendChild(checkbox);
394 // Enable the selectable checkboxes
395 if (options.disablecheckboxes != undefined && !options.disablecheckboxes) {
398 label: div.getContent(),
400 formatter: formatCheckbox,
404 scope.tableview = new Y.DataTable({columns: cols, data: fileslist});
405 scope.tableview.delegate('click', function (e, tableview) {
406 var record = tableview.getRecord(e.currentTarget.get('id'));
408 var callback = options.callback;
409 if (options.rightclickcallback && e.target.ancestor('.fp-tableview .fp-contextmenu', true)) {
410 callback = options.rightclickcallback;
412 Y.bind(callback, this)(e, record.getAttrs());
414 }, 'tr td:not(:first-child)', options.callbackcontext, scope.tableview);
416 if (options.rightclickcallback) {
417 scope.tableview.delegate('contextmenu', function (e, tableview) {
418 var record = tableview.getRecord(e.currentTarget.get('id'));
419 if (record) { Y.bind(options.rightclickcallback, this)(e, record.getAttrs()); }
420 }, 'tr', options.callbackcontext, scope.tableview);
423 /** append items in table view mode */
424 var append_files_table = function() {
425 if (options.appendonly) {
426 fileslist.forEach(function(el) {
427 this.tableview.data.add(el);
430 scope.tableview.render(scope.one('.'+classname));
431 scope.tableview.sortable = options.sortable ? true : false;
433 /** append items in tree view mode */
434 var append_files_tree = function() {
435 if (options.appendonly) {
436 var parentnode = scope.treeview.getRoot();
437 if (scope.treeview.getHighlightedNode()) {
438 parentnode = scope.treeview.getHighlightedNode();
439 if (parentnode.isLeaf) {parentnode = parentnode.parent;}
441 for (var k in fileslist) {
442 build_tree(fileslist[k], parentnode);
444 scope.treeview.draw();
446 // otherwise files were already added in initialize_tree_view()
449 /** append items in icon view mode */
450 var append_files_icons = function() {
451 parent = scope.one('.'+classname);
452 for (var k in fileslist) {
453 var node = fileslist[k];
454 var element = options.filenode.cloneNode(true);
455 parent.appendChild(element);
456 element.addClass(options.classnamecallback(node));
457 var filenamediv = element.one('.fp-filename');
458 filenamediv.setContent(file_get_displayname(node));
459 var imgdiv = element.one('.fp-thumbnail'), width, height, src;
460 if (node.thumbnail) {
461 width = node.thumbnail_width ? node.thumbnail_width : 90;
462 height = node.thumbnail_height ? node.thumbnail_height : 90;
463 src = node.thumbnail;
469 filenamediv.setStyleAdv('width', width);
470 imgdiv.setStyleAdv('width', width).setStyleAdv('height', height);
471 var img = Y.Node.create('<img/>').setAttrs({
472 title: file_get_description(node),
473 alt: Y.Escape.html(node.thumbnail_alt ? node.thumbnail_alt : file_get_filename(node))}).
474 setStyle('maxWidth', ''+width+'px').
475 setStyle('maxHeight', ''+height+'px');
476 img.setImgSrc(src, node.realthumbnail, lazyloading);
477 imgdiv.appendChild(img);
478 element.on('click', function(e, nd) {
479 if (options.rightclickcallback && e.target.ancestor('.fp-iconview .fp-contextmenu', true)) {
480 Y.bind(options.rightclickcallback, this)(e, nd);
482 Y.bind(options.callback, this)(e, nd);
484 }, options.callbackcontext, node);
485 if (options.rightclickcallback) {
486 element.on('contextmenu', options.rightclickcallback, options.callbackcontext, node);
491 // Notify the user if any of the files has a problem status.
492 var problemFiles = [];
493 fileslist.forEach(function(file) {
494 if (!file_is_folder(file) && file.hasOwnProperty('status') && file.status != 0) {
495 problemFiles.push(file);
498 if (problemFiles.length > 0) {
499 require(["core/notification", "core/str"], function(Notification, Str) {
500 problemFiles.forEach(function(problemFile) {
501 Str.get_string('storedfilecannotreadfile', 'error', problemFile.fullname).then(function(string) {
502 Notification.addNotification({
507 }).catch(Notification.exception);
512 // If table view, need some additional properties
513 // before passing fileslist to the YUI tableview
514 if (options.viewmode == 3) {
515 fileslist.forEach(function(el) {
516 el.displayname = file_get_displayname(el);
517 el.isfolder = file_is_folder(el);
518 el.classname = options.classnamecallback(el);
522 // initialize files view
523 if (!options.appendonly) {
524 var parent = Y.Node.create('<div/>').addClass(classname);
525 this.setContent('').appendChild(parent);
527 if (options.viewmode == 2) {
528 initialize_tree_view();
529 } else if (options.viewmode == 3) {
530 initialize_table_view();
532 // nothing to initialize for icon view
536 // append files to the list
537 if (options.viewmode == 2) {
539 } else if (options.viewmode == 3) {
540 append_files_table();
542 append_files_icons();
547 requires:['base', 'node', 'yui2-treeview', 'panel', 'cookie', 'datatable', 'datatable-sort']
550 M.core_filepicker = M.core_filepicker || {};
553 * instances of file pickers used on page
555 M.core_filepicker.instances = M.core_filepicker.instances || {};
556 M.core_filepicker.active_filepicker = null;
559 * HTML Templates to use in FilePicker
561 M.core_filepicker.templates = M.core_filepicker.templates || {};
564 * Array of image sources for real previews (realicon or realthumbnail) that are already loaded
566 M.core_filepicker.loadedpreviews = M.core_filepicker.loadedpreviews || {};
569 * Set selected file info
571 * @param object file info
573 M.core_filepicker.select_file = function(file) {
574 M.core_filepicker.active_filepicker.select_file(file);
578 * Init and show file picker
580 M.core_filepicker.show = function(Y, options) {
581 if (!M.core_filepicker.instances[options.client_id]) {
582 M.core_filepicker.init(Y, options);
584 M.core_filepicker.instances[options.client_id].options.formcallback = options.formcallback;
585 M.core_filepicker.instances[options.client_id].show();
588 M.core_filepicker.set_templates = function(Y, templates) {
589 for (var templid in templates) {
590 M.core_filepicker.templates[templid] = templates[templid];
595 * Add new file picker to current instances
597 M.core_filepicker.init = function(Y, options) {
598 var FilePickerHelper = function(options) {
599 FilePickerHelper.superclass.constructor.apply(this, arguments);
602 FilePickerHelper.NAME = "FilePickerHelper";
603 FilePickerHelper.ATTRS = {
608 Y.extend(FilePickerHelper, Y.Base, {
609 api: M.cfg.wwwroot+'/repository/repository_ajax.php',
610 cached_responses: {},
611 waitinterval : null, // When the loading template is being displayed and its animation is running this will be an interval instance.
612 initializer: function(options) {
613 this.options = options;
614 if (!this.options.savepath) {
615 this.options.savepath = '/';
619 destructor: function() {
622 request: function(args, redraw) {
623 var api = (args.api ? args.api : this.api) + '?action='+args.action;
625 var scope = args['scope'] ? args['scope'] : this;
626 params['repo_id']=args.repository_id;
627 params['p'] = args.path?args.path:'';
628 params['page'] = args.page?args.page:'';
629 params['env']=this.options.env;
630 // the form element only accept certain file types
631 params['accepted_types']=this.options.accepted_types;
632 params['sesskey'] = M.cfg.sesskey;
633 params['client_id'] = args.client_id;
634 params['itemid'] = this.options.itemid?this.options.itemid:0;
635 params['maxbytes'] = this.options.maxbytes?this.options.maxbytes:-1;
636 // The unlimited value of areamaxbytes is -1, it is defined by FILE_AREA_MAX_BYTES_UNLIMITED.
637 params['areamaxbytes'] = this.options.areamaxbytes ? this.options.areamaxbytes : -1;
638 if (this.options.context && this.options.context.id) {
639 params['ctx_id'] = this.options.context.id;
641 if (args['params']) {
642 for (i in args['params']) {
643 params[i] = args['params'][i];
646 if (args.action == 'upload') {
648 for(var k in params) {
649 var value = params[k];
650 if(value instanceof Array) {
651 for(var i in value) {
652 list.push(k+'[]='+value[i]);
655 list.push(k+'='+value);
658 params = list.join('&');
660 params = build_querystring(params);
665 complete: function(id,o,p) {
668 data = Y.JSON.parse(o.responseText);
670 if (o && o.status && o.status > 0) {
671 Y.use('moodle-core-notification-exception', function() {
672 return new M.core.exception(e);
678 if (data && data.error) {
679 Y.use('moodle-core-notification-ajaxexception', function () {
680 return new M.core.ajaxException(data);
682 this.fpnode.one('.fp-content').setContent('');
686 scope.print_msg(data.msg, 'info');
688 // cache result if applicable
689 if (args.action != 'upload' && data.allowcaching) {
690 scope.cached_responses[params] = data;
693 args.callback(id,data,p);
701 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
707 cfg.form = args.form;
709 // check if result of the same request has been already cached. If not, request it
710 // (never applicable in case of form submission and/or upload action):
711 if (!args.form && args.action != 'upload' && scope.cached_responses[params]) {
712 args.callback(null, scope.cached_responses[params], {scope: scope})
720 /** displays the dialog and processes rename/overwrite if there is a file with the same name in the same filearea*/
721 process_existing_file: function(data) {
723 var handleOverwrite = function(e) {
726 var data = this.process_dlg.dialogdata;
728 params['existingfilename'] = data.existingfile.filename;
729 params['existingfilepath'] = data.existingfile.filepath;
730 params['newfilename'] = data.newfile.filename;
731 params['newfilepath'] = data.newfile.filepath;
736 'action':'overwrite',
738 'client_id': this.options.client_id,
739 'repository_id': this.active_repo.id,
740 'callback': function(id, o, args) {
742 // Add an arbitrary parameter to the URL to force browsers to re-load the new image even
743 // if the file name has not changed.
744 var urlimage = data.existingfile.url + "?time=" + (new Date()).getTime();
745 if (scope.options.editor_target && scope.options.env == 'editor') {
746 // editor needs to update url
747 scope.options.editor_target.value = urlimage;
748 scope.options.editor_target.dispatchEvent(new Event('change'), {'bubbles': true});
750 var fileinfo = {'client_id':scope.options.client_id,
752 'file': data.existingfile.filename};
753 var formcallback_scope = scope.options.magicscope ? scope.options.magicscope : scope;
754 scope.options.formcallback.apply(formcallback_scope, [fileinfo]);
758 var handleRename = function(e) {
759 // inserts file with the new name
762 var data = this.process_dlg.dialogdata;
763 if (scope.options.editor_target && scope.options.env == 'editor') {
764 scope.options.editor_target.value = data.newfile.url;
765 scope.options.editor_target.dispatchEvent(new Event('change'), {'bubbles': true});
768 var formcallback_scope = scope.options.magicscope ? scope.options.magicscope : scope;
769 var fileinfo = {'client_id':scope.options.client_id,
770 'url':data.newfile.url,
771 'file':data.newfile.filename};
772 scope.options.formcallback.apply(formcallback_scope, [fileinfo]);
774 var handleCancel = function(e) {
778 params['newfilename'] = this.process_dlg.dialogdata.newfile.filename;
779 params['newfilepath'] = this.process_dlg.dialogdata.newfile.filepath;
783 'action':'deletetmpfile',
785 'client_id': this.options.client_id,
786 'repository_id': this.active_repo.id,
787 'callback': function(id, o, args) {
788 // let it be in background, from user point of view nothing is happenning
791 this.process_dlg.hide();
792 this.selectui.hide();
794 if (!this.process_dlg) {
795 this.process_dlg_node = Y.Node.create(M.core_filepicker.templates.processexistingfile);
796 var node = this.process_dlg_node;
798 this.process_dlg = new M.core.dialogue({
801 headerContent: M.util.get_string('fileexistsdialogheader', 'repository'),
805 zIndex : this.options.zIndex
807 node.one('.fp-dlg-butoverwrite').on('click', handleOverwrite, this);
808 node.one('.fp-dlg-butrename').on('click', handleRename, this);
809 node.one('.fp-dlg-butcancel').on('click', handleCancel, this);
810 if (this.options.env == 'editor') {
811 node.one('.fp-dlg-text').setContent(M.util.get_string('fileexistsdialog_editor', 'repository'));
813 node.one('.fp-dlg-text').setContent(M.util.get_string('fileexistsdialog_filemanager', 'repository'));
816 this.selectnode.removeClass('loading');
817 this.process_dlg.dialogdata = data;
818 this.process_dlg_node.one('.fp-dlg-butrename').setContent(M.util.get_string('renameto', 'repository', data.newfile.filename));
819 this.process_dlg.show();
821 /** displays error instead of filepicker contents */
822 display_error: function(errortext, errorcode) {
823 this.fpnode.one('.fp-content').setContent(M.core_filepicker.templates.error);
824 this.fpnode.one('.fp-content .fp-error').
826 setContent(Y.Escape.html(errortext));
828 /** displays message in a popup */
829 print_msg: function(msg, type) {
830 var header = M.util.get_string('error', 'moodle');
831 if (type != 'error') {
832 type = 'info'; // one of only two types excepted
833 header = M.util.get_string('info', 'moodle');
836 this.msg_dlg_node = Y.Node.create(M.core_filepicker.templates.message);
837 this.msg_dlg_node.generateID();
839 this.msg_dlg = new M.core.dialogue({
841 bodyContent : this.msg_dlg_node,
845 zIndex : this.options.zIndex
847 this.msg_dlg_node.one('.fp-msg-butok').on('click', function(e) {
853 this.msg_dlg.set('headerContent', header);
854 this.msg_dlg_node.removeClass('fp-msg-info').removeClass('fp-msg-error').addClass('fp-msg-'+type)
855 this.msg_dlg_node.one('.fp-msg-text').setContent(Y.Escape.html(msg));
858 view_files: function(appenditems) {
859 this.viewbar_set_enabled(true);
861 /*if ((appenditems == null) && (!this.filelist || !this.filelist.length) && !this.active_repo.hasmorepages) {
862 // TODO do it via classes and adjust for each view mode!
863 // If there are no items and no next page, just display status message and quit
864 this.display_error(M.util.get_string('nofilesavailable', 'repository'), 'nofilesavailable');
867 if (this.viewmode == 2) {
868 this.view_as_list(appenditems);
869 } else if (this.viewmode == 3) {
870 this.view_as_table(appenditems);
872 this.view_as_icons(appenditems);
874 this.fpnode.one('.fp-content').setAttribute('tabindex', '0');
875 this.fpnode.one('.fp-content').focus();
876 // display/hide the link for requesting next page
877 if (!appenditems && this.active_repo.hasmorepages) {
878 if (!this.fpnode.one('.fp-content .fp-nextpage')) {
879 this.fpnode.one('.fp-content').append(M.core_filepicker.templates.nextpage);
881 this.fpnode.one('.fp-content .fp-nextpage').one('a,button').on('click', function(e) {
883 this.fpnode.one('.fp-content .fp-nextpage').addClass('loading');
884 this.request_next_page();
887 if (!this.active_repo.hasmorepages && this.fpnode.one('.fp-content .fp-nextpage')) {
888 this.fpnode.one('.fp-content .fp-nextpage').remove();
890 if (this.fpnode.one('.fp-content .fp-nextpage')) {
891 this.fpnode.one('.fp-content .fp-nextpage').removeClass('loading');
893 this.content_scrolled();
895 content_scrolled: function(e) {
896 setTimeout(Y.bind(function() {
897 if (this.processingimages) {
900 this.processingimages = true;
902 fpcontent = this.fpnode.one('.fp-content'),
903 fpcontenty = fpcontent.getY(),
904 fpcontentheight = fpcontent.getStylePx('height'),
905 nextpage = fpcontent.one('.fp-nextpage'),
906 is_node_visible = function(node) {
907 var offset = node.getY()-fpcontenty;
908 if (offset <= fpcontentheight && (offset >=0 || offset+node.getStylePx('height')>=0)) {
913 // automatically load next page when 'more' link becomes visible
914 if (nextpage && !nextpage.hasClass('loading') && is_node_visible(nextpage)) {
915 nextpage.one('a,button').simulate('click');
917 // replace src for visible images that need to be lazy-loaded
918 if (scope.lazyloading) {
919 fpcontent.all('img').each( function(node) {
920 if (node.get('id') && scope.lazyloading[node.get('id')] && is_node_visible(node)) {
921 node.setImgRealSrc(scope.lazyloading);
925 this.processingimages = false;
928 treeview_dynload: function(node, cb) {
929 var retrieved_children = {};
931 for (var i in node.children) {
932 retrieved_children[node.children[i].path] = node.children[i];
937 client_id: this.options.client_id,
938 repository_id: this.active_repo.id,
939 path:node.path?node.path:'',
940 page:node.page?args.page:'',
942 callback: function(id, obj, args) {
944 var scope = args.scope;
945 // check that user did not leave the view mode before recieving this response
946 if (!(scope.active_repo.id == obj.repo_id && scope.viewmode == 2 && node && node.getChildrenEl())) {
949 if (cb != null) { // (in manual mode do not update current path)
950 scope.viewbar_set_enabled(true);
951 scope.parse_repository_options(obj);
953 node.highlight(false);
954 node.origlist = obj.list ? obj.list : null;
955 node.origpath = obj.path ? obj.path : null;
958 if (list[k].children && retrieved_children[list[k].path]) {
959 // if this child is a folder and has already been retrieved
960 node.children[node.children.length] = retrieved_children[list[k].path];
962 // append new file to the list
963 scope.view_as_list([list[k]]);
969 // invoke callback requested by TreeView component
972 scope.content_scrolled();
976 classnamecallback : function(node) {
979 classname = classname + ' fp-folder';
982 classname = classname + ' fp-isreference';
984 if (node.iscontrolledlink) {
985 classname = classname + ' fp-iscontrolledlink';
988 classname = classname + ' fp-hasreferences';
990 if (node.originalmissing) {
991 classname = classname + ' fp-originalmissing';
993 return Y.Lang.trim(classname);
995 /** displays list of files in tree (list) view mode. If param appenditems is specified,
996 * appends those items to the end of the list. Otherwise (default behaviour)
997 * clears the contents and displays the items from this.filelist */
998 view_as_list: function(appenditems) {
999 var list = (appenditems != null) ? appenditems : this.filelist;
1001 if (!this.filelist || this.filelist.length==0 && (!this.filepath || !this.filepath.length)) {
1002 this.display_error(M.util.get_string('nofilesavailable', 'repository'), 'nofilesavailable');
1006 var element_template = Y.Node.create(M.core_filepicker.templates.listfilename);
1008 viewmode : this.viewmode,
1009 appendonly : (appenditems != null),
1010 filenode : element_template,
1011 callbackcontext : this,
1012 callback : function(e, node) {
1013 // TODO MDL-32736 e is not an event here but an object with properties 'event' and 'node'
1014 if (!node.children) {
1015 if (e.node.parent && e.node.parent.origpath) {
1016 // set the current path
1017 this.filepath = e.node.parent.origpath;
1018 this.filelist = e.node.parent.origlist;
1021 this.select_file(node);
1023 // save current path and filelist (in case we want to jump to other viewmode)
1024 this.filepath = e.node.origpath;
1025 this.filelist = e.node.origlist;
1026 this.currentpath = e.node.path;
1028 this.content_scrolled();
1031 classnamecallback : this.classnamecallback,
1032 dynload : this.active_repo.dynload,
1033 filepath : this.filepath,
1034 treeview_dynload : this.treeview_dynload
1036 this.fpnode.one('.fp-content').fp_display_filelist(options, list, this.lazyloading);
1038 /** displays list of files in icon view mode. If param appenditems is specified,
1039 * appends those items to the end of the list. Otherwise (default behaviour)
1040 * clears the contents and displays the items from this.filelist */
1041 view_as_icons: function(appenditems) {
1043 var list = (appenditems != null) ? appenditems : this.filelist;
1044 var element_template = Y.Node.create(M.core_filepicker.templates.iconfilename);
1045 if ((appenditems == null) && (!this.filelist || !this.filelist.length)) {
1046 this.display_error(M.util.get_string('nofilesavailable', 'repository'), 'nofilesavailable');
1050 viewmode : this.viewmode,
1051 appendonly : (appenditems != null),
1052 filenode : element_template,
1053 callbackcontext : this,
1054 callback : function(e, node) {
1055 if (e.preventDefault) {
1059 if (this.active_repo.dynload) {
1060 this.list({'path':node.path});
1062 this.filelist = node.children;
1066 this.select_file(node);
1069 classnamecallback : this.classnamecallback
1071 this.fpnode.one('.fp-content').fp_display_filelist(options, list, this.lazyloading);
1073 /** displays list of files in table view mode. If param appenditems is specified,
1074 * appends those items to the end of the list. Otherwise (default behaviour)
1075 * clears the contents and displays the items from this.filelist */
1076 view_as_table: function(appenditems) {
1078 var list = (appenditems != null) ? appenditems : this.filelist;
1079 if (!appenditems && (!this.filelist || this.filelist.length==0) && !this.active_repo.hasmorepages) {
1080 this.display_error(M.util.get_string('nofilesavailable', 'repository'), 'nofilesavailable');
1083 var element_template = Y.Node.create(M.core_filepicker.templates.listfilename);
1085 viewmode : this.viewmode,
1086 appendonly : (appenditems != null),
1087 filenode : element_template,
1088 callbackcontext : this,
1089 sortable : !this.active_repo.hasmorepages,
1090 callback : function(e, node) {
1091 if (e.preventDefault) {e.preventDefault();}
1092 if (node.children) {
1093 if (this.active_repo.dynload) {
1094 this.list({'path':node.path});
1096 this.filelist = node.children;
1100 this.select_file(node);
1103 classnamecallback : this.classnamecallback
1105 this.fpnode.one('.fp-content').fp_display_filelist(options, list, this.lazyloading);
1107 /** If more than one page available, requests and displays the files from the next page */
1108 request_next_page: function() {
1109 if (!this.active_repo.hasmorepages || this.active_repo.nextpagerequested) {
1113 this.active_repo.nextpagerequested = true;
1114 var nextpage = this.active_repo.page+1;
1117 repo_id: this.active_repo.id
1119 var action = this.active_repo.issearchresult ? 'search' : 'list';
1121 path: this.currentpath,
1124 client_id: this.options.client_id,
1125 repository_id: args.repo_id,
1127 callback: function(id, obj, args) {
1128 var scope = args.scope;
1129 // Check that we are still in the same repository and are expecting this page. We have no way
1130 // to compare the requested page and the one returned, so we assume that if the last chunk
1131 // of the breadcrumb is similar, then we probably are on the same page.
1132 var samepage = true;
1133 if (obj.path && scope.filepath) {
1134 var pathbefore = scope.filepath[scope.filepath.length-1];
1135 var pathafter = obj.path[obj.path.length-1];
1136 if (pathbefore.path != pathafter.path) {
1140 if (scope.active_repo.hasmorepages && obj.list && obj.page &&
1141 obj.repo_id == scope.active_repo.id &&
1142 obj.page == scope.active_repo.page+1 && samepage) {
1143 scope.parse_repository_options(obj, true);
1144 scope.view_files(obj.list)
1149 select_file: function(args) {
1150 var argstitle = args.title;
1151 // Limit the string length so it fits nicely on mobile devices
1152 var titlelength = 30;
1153 if (argstitle.length > titlelength) {
1154 argstitle = argstitle.substring(0, titlelength) + '...';
1156 Y.one('#fp-file_label_'+this.options.client_id).setContent(Y.Escape.html(M.util.get_string('select', 'repository')+' '+argstitle));
1157 this.selectui.show();
1158 Y.one('#'+this.selectnode.get('id')).focus();
1159 var client_id = this.options.client_id;
1160 var selectnode = this.selectnode;
1161 var return_types = this.options.repositories[this.active_repo.id].return_types;
1162 selectnode.removeClass('loading');
1163 selectnode.one('.fp-saveas input').set('value', args.title);
1165 var imgnode = Y.Node.create('<img/>').
1166 set('src', args.realthumbnail ? args.realthumbnail : args.thumbnail).
1167 setStyle('maxHeight', ''+(args.thumbnail_height ? args.thumbnail_height : 90)+'px').
1168 setStyle('maxWidth', ''+(args.thumbnail_width ? args.thumbnail_width : 90)+'px');
1169 selectnode.one('.fp-thumbnail').setContent('').appendChild(imgnode);
1171 // filelink is the array of file-link-types available for this repository in this env
1172 var filelinktypes = [2/*FILE_INTERNAL*/,1/*FILE_EXTERNAL*/,4/*FILE_REFERENCE*/,8/*FILE_CONTROLLED_LINK*/];
1173 var filelink = {}, firstfilelink = null, filelinkcount = 0;
1174 for (var i in filelinktypes) {
1175 var allowed = (return_types & filelinktypes[i]) &&
1176 (this.options.return_types & filelinktypes[i]);
1177 if (filelinktypes[i] == 1/*FILE_EXTERNAL*/ && !this.options.externallink && this.options.env == 'editor') {
1178 // special configuration setting 'repositoryallowexternallinks' may prevent
1179 // using external links in editor environment
1182 filelink[filelinktypes[i]] = allowed;
1183 firstfilelink = (firstfilelink==null && allowed) ? filelinktypes[i] : firstfilelink;
1184 filelinkcount += allowed ? 1 : 0;
1186 var defaultreturntype = this.options.repositories[this.active_repo.id].defaultreturntype;
1187 if (defaultreturntype) {
1188 if (filelink[defaultreturntype]) {
1189 firstfilelink = defaultreturntype;
1192 // make radio buttons enabled if this file-link-type is available and only if there are more than one file-link-type option
1193 // check the first available file-link-type option
1194 for (var linktype in filelink) {
1195 var el = selectnode.one('.fp-linktype-'+linktype);
1196 el.addClassIf('uneditable', !(filelink[linktype] && filelinkcount>1));
1197 el.one('input').set('checked', (firstfilelink == linktype) ? 'checked' : '').simulate('change');
1200 // TODO MDL-32532: attributes 'hasauthor' and 'haslicense' need to be obsolete,
1201 selectnode.one('.fp-setauthor input').set('value', args.author ? args.author : this.options.author);
1202 this.set_selected_license(selectnode.one('.fp-setlicense'), args.license);
1203 selectnode.one('form #filesource-'+client_id).set('value', args.source);
1204 selectnode.one('form #filesourcekey-'+client_id).set('value', args.sourcekey);
1206 // display static information about a file (when known)
1207 var attrs = ['datemodified','datecreated','size','license','author','dimensions'];
1208 for (var i in attrs) {
1209 if (selectnode.one('.fp-'+attrs[i])) {
1210 var value = (args[attrs[i]+'_f']) ? args[attrs[i]+'_f'] : (args[attrs[i]] ? args[attrs[i]] : '');
1211 selectnode.one('.fp-'+attrs[i]).addClassIf('fp-unknown', ''+value == '')
1212 .one('.fp-value').setContent(Y.Escape.html(value));
1216 setup_select_file: function() {
1217 var client_id = this.options.client_id;
1218 var selectnode = this.selectnode;
1219 var getfile = selectnode.one('.fp-select-confirm');
1220 // bind labels with corresponding inputs
1221 selectnode.all('.fp-saveas,.fp-linktype-2,.fp-linktype-1,.fp-linktype-4,fp-linktype-8,.fp-setauthor,.fp-setlicense').each(function (node) {
1222 node.all('label').set('for', node.one('input,select').generateID());
1224 selectnode.one('.fp-linktype-2 input').setAttrs({value: 2, name: 'linktype'});
1225 selectnode.one('.fp-linktype-1 input').setAttrs({value: 1, name: 'linktype'});
1226 selectnode.one('.fp-linktype-4 input').setAttrs({value: 4, name: 'linktype'});
1227 selectnode.one('.fp-linktype-8 input').setAttrs({value: 8, name: 'linktype'});
1228 var changelinktype = function(e) {
1229 if (e.currentTarget.get('checked')) {
1230 var allowinputs = e.currentTarget.get('value') != 1/*FILE_EXTERNAL*/;
1231 selectnode.all('.fp-setauthor,.fp-setlicense,.fp-saveas').each(function(node){
1232 node.addClassIf('uneditable', !allowinputs);
1233 node.all('input,select').set('disabled', allowinputs?'':'disabled');
1237 selectnode.all('.fp-linktype-2,.fp-linktype-1,.fp-linktype-4,.fp-linktype-8').each(function (node) {
1238 node.one('input').on('change', changelinktype, this);
1240 this.populate_licenses_select(selectnode.one('.fp-setlicense select'));
1241 // register event on clicking submit button
1242 getfile.on('click', function(e) {
1244 var client_id = this.options.client_id;
1246 var repository_id = this.active_repo.id;
1247 var title = selectnode.one('.fp-saveas input').get('value');
1248 var filesource = selectnode.one('form #filesource-'+client_id).get('value');
1249 var filesourcekey = selectnode.one('form #filesourcekey-'+client_id).get('value');
1250 var params = {'title':title, 'source':filesource, 'savepath': this.options.savepath, sourcekey: filesourcekey};
1251 var license = selectnode.one('.fp-setlicense select');
1253 params['license'] = license.get('value');
1254 var origlicense = selectnode.one('.fp-license .fp-value');
1256 origlicense = origlicense.getContent();
1258 this.set_preference('recentlicense', license.get('value'));
1260 params['author'] = selectnode.one('.fp-setauthor input').get('value');
1262 var return_types = this.options.repositories[this.active_repo.id].return_types;
1263 if (this.options.env == 'editor') {
1264 // in editor, images are stored in '/' only
1265 params.savepath = '/';
1267 if ((this.options.externallink || this.options.env != 'editor') &&
1268 (return_types & 1/*FILE_EXTERNAL*/) &&
1269 (this.options.return_types & 1/*FILE_EXTERNAL*/) &&
1270 selectnode.one('.fp-linktype-1 input').get('checked')) {
1271 params['linkexternal'] = 'yes';
1272 } else if ((return_types & 4/*FILE_REFERENCE*/) &&
1273 (this.options.return_types & 4/*FILE_REFERENCE*/) &&
1274 selectnode.one('.fp-linktype-4 input').get('checked')) {
1275 params['usefilereference'] = '1';
1276 } else if ((return_types & 8/*FILE_CONTROLLED_LINK*/) &&
1277 (this.options.return_types & 8/*FILE_CONTROLLED_LINK*/) &&
1278 selectnode.one('.fp-linktype-8 input').get('checked')) {
1279 params['usecontrolledlink'] = '1';
1282 selectnode.addClass('loading');
1285 client_id: client_id,
1286 repository_id: repository_id,
1288 onerror: function(id, obj, args) {
1289 selectnode.removeClass('loading');
1290 scope.selectui.hide();
1292 callback: function(id, obj, args) {
1293 selectnode.removeClass('loading');
1294 if (obj.event == 'fileexists') {
1295 scope.process_existing_file(obj);
1298 if (scope.options.editor_target && scope.options.env=='editor') {
1299 scope.options.editor_target.value=obj.url;
1300 scope.options.editor_target.dispatchEvent(new Event('change'), {'bubbles': true});
1303 obj.client_id = client_id;
1304 var formcallback_scope = args.scope.options.magicscope ? args.scope.options.magicscope : args.scope;
1305 scope.options.formcallback.apply(formcallback_scope, [obj]);
1309 var elform = selectnode.one('form');
1310 elform.appendChild(Y.Node.create('<input/>').
1311 setAttrs({type:'hidden',id:'filesource-'+client_id}));
1312 elform.appendChild(Y.Node.create('<input/>').
1313 setAttrs({type:'hidden',id:'filesourcekey-'+client_id}));
1314 elform.on('keydown', function(e) {
1315 if (e.keyCode == 13) {
1316 getfile.simulate('click');
1320 var cancel = selectnode.one('.fp-select-cancel');
1321 cancel.on('click', function(e) {
1323 this.selectui.hide();
1327 // First check there isn't already an interval in play, and if there is kill it now.
1328 if (this.waitinterval != null) {
1329 clearInterval(this.waitinterval);
1331 // Prepare the root node we will set content for and the loading template we want to display as a YUI node.
1332 var root = this.fpnode.one('.fp-content');
1333 var content = Y.Node.create(M.core_filepicker.templates.loading).addClass('fp-content-hidden').setStyle('opacity', 0);
1335 // Initiate an interval, we will have a count which will increment every 100 milliseconds.
1336 // Count 0 - the loading icon will have visibility set to hidden (invisible) and have an opacity of 0 (invisible also)
1337 // Count 5 - the visiblity will be switched to visible but opacity will still be at 0 (inivisible)
1338 // Counts 6 - 15 opacity will be increased by 0.1 making the loading icon visible over the period of a second
1339 // Count 16 - The interval will be cancelled.
1340 var interval = setInterval(function(){
1341 if (!content || !root.contains(content) || count >= 15) {
1342 clearInterval(interval);
1346 content.removeClass('fp-content-hidden');
1347 } else if (count > 5) {
1348 var opacity = parseFloat(content.getStyle('opacity'));
1349 content.setStyle('opacity', opacity + 0.1);
1354 // Store the wait interval so that we can check it in the future.
1355 this.waitinterval = interval;
1356 // Set the content to the loading template.
1357 root.setContent(content);
1359 viewbar_set_enabled: function(mode) {
1360 var viewbar = this.fpnode.one('.fp-viewbar')
1363 viewbar.addClass('enabled').removeClass('disabled');
1364 this.fpnode.all('.fp-vb-icons,.fp-vb-tree,.fp-vb-details').setAttribute("aria-disabled", "false");
1365 this.fpnode.all('.fp-vb-icons,.fp-vb-tree,.fp-vb-details').setAttribute("tabindex", "");
1367 viewbar.removeClass('enabled').addClass('disabled');
1368 this.fpnode.all('.fp-vb-icons,.fp-vb-tree,.fp-vb-details').setAttribute("aria-disabled", "true");
1369 this.fpnode.all('.fp-vb-icons,.fp-vb-tree,.fp-vb-details').setAttribute("tabindex", "-1");
1372 this.fpnode.all('.fp-vb-icons,.fp-vb-tree,.fp-vb-details').removeClass('checked');
1373 var modes = {1:'icons', 2:'tree', 3:'details'};
1374 this.fpnode.all('.fp-vb-'+modes[this.viewmode]).addClass('checked');
1376 viewbar_clicked: function(e) {
1378 var viewbar = this.fpnode.one('.fp-viewbar')
1379 if (!viewbar || !viewbar.hasClass('disabled')) {
1380 if (e.currentTarget.hasClass('fp-vb-tree')) {
1382 } else if (e.currentTarget.hasClass('fp-vb-details')) {
1387 this.viewbar_set_enabled(true)
1389 this.set_preference('recentviewmode', this.viewmode);
1392 render: function() {
1393 var client_id = this.options.client_id;
1394 var fpid = "filepicker-"+ client_id;
1395 var labelid = 'fp-dialog-label_'+ client_id;
1397 var draggable = true;
1398 this.fpnode = Y.Node.create(M.core_filepicker.templates.generallayout).
1399 set('id', 'filepicker-'+client_id).set('aria-labelledby', labelid);
1401 if (this.in_iframe()) {
1402 width = Math.floor(window.innerWidth * 0.95);
1406 this.mainui = new M.core.dialogue({
1407 extraClasses : ['filepicker'],
1408 draggable : draggable,
1409 bodyContent : this.fpnode,
1410 headerContent: '<h3 id="'+ labelid +'">'+ M.util.get_string('filepicker', 'repository') +'</h3>',
1415 responsiveWidth : 768,
1417 zIndex : this.options.zIndex
1420 // create panel for selecting a file (initially hidden)
1421 this.selectnode = Y.Node.create(M.core_filepicker.templates.selectlayout).
1422 set('id', 'filepicker-select-'+client_id).
1423 set('aria-live', 'assertive').
1424 set('role', 'dialog');
1426 var fplabel = 'fp-file_label_'+ client_id;
1427 this.selectui = new M.core.dialogue({
1428 headerContent: '<h3 id="' + fplabel +'">'+M.util.get_string('select', 'repository')+'</h3>',
1431 bodyContent : this.selectnode,
1435 zIndex : this.options.zIndex
1437 Y.one('#'+this.selectnode.get('id')).setAttribute('aria-labelledby', fplabel);
1438 // event handler for lazy loading of thumbnails and next page
1439 this.fpnode.one('.fp-content').on(['scroll','resize'], this.content_scrolled, this);
1440 // save template for one path element and location of path bar
1441 if (this.fpnode.one('.fp-path-folder')) {
1442 this.pathnode = this.fpnode.one('.fp-path-folder');
1443 this.pathbar = this.pathnode.get('parentNode');
1444 this.pathbar.removeChild(this.pathnode);
1446 // assign callbacks for view mode switch buttons
1447 this.fpnode.one('.fp-vb-icons').on('click', this.viewbar_clicked, this);
1448 this.fpnode.one('.fp-vb-tree').on('click', this.viewbar_clicked, this);
1449 this.fpnode.one('.fp-vb-details').on('click', this.viewbar_clicked, this);
1451 // assign callbacks for toolbar links
1452 this.setup_toolbar();
1453 this.setup_select_file();
1456 // processing repository listing
1457 // Resort the repositories by sortorder
1458 var sorted_repositories = [];
1460 for (i in this.options.repositories) {
1461 sorted_repositories[i] = this.options.repositories[i];
1463 sorted_repositories.sort(function(a,b){return a.sortorder-b.sortorder});
1464 // extract one repository template and repeat it for all repositories available,
1465 // set name and icon and assign callbacks
1466 var reponode = this.fpnode.one('.fp-repo');
1468 var list = reponode.get('parentNode');
1469 list.removeChild(reponode);
1470 for (i in sorted_repositories) {
1471 var repository = sorted_repositories[i];
1472 var h = (parseInt(i) == 0) ? parseInt(i) : parseInt(i) - 1,
1473 j = (parseInt(i) == Object.keys(sorted_repositories).length - 1) ? parseInt(i) : parseInt(i) + 1;
1474 var previousrepository = sorted_repositories[h];
1475 var nextrepository = sorted_repositories[j];
1476 var node = reponode.cloneNode(true);
1477 list.appendChild(node);
1479 set('id', 'fp-repo-'+client_id+'-'+repository.id).
1480 on('click', function(e, repository_id) {
1482 this.set_preference('recentrepository', repository_id);
1484 this.list({'repo_id':repository_id});
1485 }, this /*handler running scope*/, repository.id/*second argument of handler*/);
1486 node.on('key', function(e, previousrepositoryid, nextrepositoryid, clientid, repositoryid) {
1487 this.changeHighlightedRepository(e, clientid, repositoryid, previousrepositoryid, nextrepositoryid);
1488 }, 'down:38,40', this, previousrepository.id, nextrepository.id, client_id, repository.id);
1489 node.on('key', function(e, repositoryid) {
1491 this.set_preference('recentrepository', repositoryid);
1493 this.list({'repo_id': repositoryid});
1494 }, 'enter', this, repository.id);
1495 node.one('.fp-repo-name').setContent(Y.Escape.html(repository.name));
1496 node.one('.fp-repo-icon').set('src', repository.icon);
1498 node.addClass('first');
1500 if (i==sorted_repositories.length-1) {
1501 node.addClass('last');
1504 node.addClass('even');
1506 node.addClass('odd');
1510 // display error if no repositories found
1511 if (sorted_repositories.length==0) {
1512 this.display_error(M.util.get_string('norepositoriesavailable', 'repository'), 'norepositoriesavailable')
1514 // display repository that was used last time
1516 this.show_recent_repository();
1519 * Change the highlighted repository to a new one.
1521 * @param {object} event The key event
1522 * @param {integer} clientid The client id to identify the repo class.
1523 * @param {integer} oldrepositoryid The repository id that we are removing the highlight for
1524 * @param {integer} previousrepositoryid The previous repository id.
1525 * @param {integer} nextrepositoryid The next repository id.
1527 changeHighlightedRepository: function(event, clientid, oldrepositoryid, previousrepositoryid, nextrepositoryid) {
1528 event.preventDefault();
1529 var newrepositoryid = (event.keyCode == '40') ? nextrepositoryid : previousrepositoryid;
1530 this.fpnode.one('#fp-repo-' + clientid + '-' + oldrepositoryid).setAttribute('tabindex', '-1');
1531 this.fpnode.one('#fp-repo-' + clientid + '-' + newrepositoryid)
1532 .setAttribute('tabindex', '0')
1535 parse_repository_options: function(data, appendtolist) {
1538 if (!this.filelist) {
1541 for (var i in data.list) {
1542 this.filelist[this.filelist.length] = data.list[i];
1546 this.filelist = data.list?data.list:null;
1547 this.lazyloading = {};
1549 this.filepath = data.path?data.path:null;
1550 this.objecttag = data.object?data.object:null;
1551 this.active_repo = {};
1552 this.active_repo.issearchresult = data.issearchresult ? true : false;
1553 this.active_repo.defaultreturntype = data.defaultreturntype?data.defaultreturntype:null;
1554 this.active_repo.dynload = data.dynload?data.dynload:false;
1555 this.active_repo.pages = Number(data.pages?data.pages:null);
1556 this.active_repo.page = Number(data.page?data.page:null);
1557 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))
1558 this.active_repo.id = data.repo_id?data.repo_id:null;
1559 this.active_repo.nosearch = (data.login || data.nosearch); // this is either login form or 'nosearch' attribute set
1560 this.active_repo.norefresh = (data.login || data.norefresh); // this is either login form or 'norefresh' attribute set
1561 this.active_repo.nologin = (data.login || data.nologin); // this is either login form or 'nologin' attribute is set
1562 this.active_repo.logouttext = data.logouttext?data.logouttext:null;
1563 this.active_repo.logouturl = (data.logouturl || '');
1564 this.active_repo.message = (data.message || '');
1565 this.active_repo.help = data.help?data.help:null;
1566 this.active_repo.manage = data.manage?data.manage:null;
1567 this.print_header();
1569 print_login: function(data) {
1570 this.parse_repository_options(data);
1571 var client_id = this.options.client_id;
1572 var repository_id = data.repo_id;
1573 var l = this.logindata = data.login;
1575 var action = data['login_btn_action'] ? data['login_btn_action'] : 'login';
1576 var form_id = 'fp-form-'+client_id;
1578 var loginform_node = Y.Node.create(M.core_filepicker.templates.loginform);
1579 loginform_node.one('form').set('id', form_id);
1580 this.fpnode.one('.fp-content').setContent('').appendChild(loginform_node);
1582 'popup' : loginform_node.one('.fp-login-popup'),
1583 'textarea' : loginform_node.one('.fp-login-textarea'),
1584 'select' : loginform_node.one('.fp-login-select'),
1585 'text' : loginform_node.one('.fp-login-text'),
1586 'radio' : loginform_node.one('.fp-login-radiogroup'),
1587 'checkbox' : loginform_node.one('.fp-login-checkbox'),
1588 'input' : loginform_node.one('.fp-login-input')
1591 for (var i in templates) {
1593 container = templates[i].get('parentNode');
1594 container.removeChild(templates[i]);
1599 if (templates[l[k].type]) {
1600 var node = templates[l[k].type].cloneNode(true);
1602 node = templates['input'].cloneNode(true);
1604 if (l[k].type == 'popup') {
1606 loginurl = l[k].url;
1607 var popupbutton = node.one('button');
1608 popupbutton.on('click', function(e){
1609 M.core_filepicker.active_filepicker = this;
1610 window.open(loginurl, 'repo_auth', 'location=0,status=0,width=500,height=300,scrollbars=yes');
1613 loginform_node.one('form').on('keydown', function(e) {
1614 if (e.keyCode == 13) {
1615 popupbutton.simulate('click');
1619 loginform_node.all('.fp-login-submit').remove();
1621 } else if(l[k].type=='textarea') {
1623 if (node.one('label')) {
1624 node.one('label').set('for', l[k].id).setContent(l[k].label);
1626 node.one('textarea').setAttrs({id:l[k].id, name:l[k].name});
1627 } else if(l[k].type=='select') {
1629 if (node.one('label')) {
1630 node.one('label').set('for', l[k].id).setContent(l[k].label);
1632 node.one('select').setAttrs({id:l[k].id, name:l[k].name}).setContent('');
1633 for (i in l[k].options) {
1634 node.one('select').appendChild(
1635 Y.Node.create('<option/>').
1636 set('value', l[k].options[i].value).
1637 setContent(l[k].options[i].label));
1639 } else if(l[k].type=='radio') {
1640 // radio input element
1641 node.all('label').setContent(l[k].label);
1642 var list = l[k].value.split('|');
1643 var labels = l[k].value_label.split('|');
1644 var radionode = null;
1645 for(var item in list) {
1646 if (radionode == null) {
1647 radionode = node.one('.fp-login-radio');
1648 radionode.one('input').set('checked', 'checked');
1650 var x = radionode.cloneNode(true);
1651 radionode.insert(x, 'after');
1653 radionode.one('input').set('checked', '');
1655 radionode.one('input').setAttrs({id:''+l[k].id+item, name:l[k].name,
1656 type:l[k].type, value:list[item]});
1657 radionode.all('label').setContent(labels[item]).set('for', ''+l[k].id+item)
1659 if (radionode == null) {
1660 node.one('.fp-login-radio').remove();
1664 if (node.one('label')) { node.one('label').set('for', l[k].id).setContent(l[k].label) }
1666 set('type', l[k].type).
1668 set('name', l[k].name).
1669 set('value', l[k].value?l[k].value:'')
1671 container.appendChild(node);
1673 // custom label text for submit button
1674 if (data['login_btn_label']) {
1675 loginform_node.all('.fp-login-submit').setContent(data['login_btn_label'])
1677 // register button action for login and search
1678 if (action == 'login' || action == 'search') {
1679 loginform_node.one('.fp-login-submit').on('click', function(e){
1684 'action':(action == 'search') ? 'search' : 'signin',
1686 'client_id': client_id,
1687 'repository_id': repository_id,
1688 'form': {id:form_id, upload:false, useDisabled:true},
1689 'callback': this.display_response
1693 // if 'Enter' is pressed in the form, simulate the button click
1694 if (loginform_node.one('.fp-login-submit')) {
1695 loginform_node.one('form').on('keydown', function(e) {
1696 if (e.keyCode == 13) {
1697 loginform_node.one('.fp-login-submit').simulate('click')
1703 display_response: function(id, obj, args) {
1704 var scope = args.scope;
1705 // highlight the current repository in repositories list
1706 scope.fpnode.all('.fp-repo.active')
1707 .removeClass('active')
1708 .setAttribute('aria-selected', 'false')
1709 .setAttribute('tabindex', '-1');
1710 scope.fpnode.all('.nav-link')
1711 .removeClass('active')
1712 .setAttribute('aria-selected', 'false')
1713 .setAttribute('tabindex', '-1');
1714 var activenode = scope.fpnode.one('#fp-repo-' + scope.options.client_id + '-' + obj.repo_id);
1715 activenode.addClass('active')
1716 .setAttribute('aria-selected', 'true')
1717 .setAttribute('tabindex', '0');
1718 activenode.all('.nav-link').addClass('active');
1719 // add class repository_REPTYPE to the filepicker (for repository-specific styles)
1720 for (var i in scope.options.repositories) {
1721 scope.fpnode.removeClass('repository_'+scope.options.repositories[i].type)
1723 if (obj.repo_id && scope.options.repositories[obj.repo_id]) {
1724 scope.fpnode.addClass('repository_'+scope.options.repositories[obj.repo_id].type)
1726 Y.one('.file-picker .fp-repo-items').focus();
1730 scope.viewbar_set_enabled(false);
1731 scope.print_login(obj);
1732 } else if (obj.upload) {
1733 scope.viewbar_set_enabled(false);
1734 scope.parse_repository_options(obj);
1735 scope.create_upload_form(obj);
1736 } else if (obj.object) {
1737 M.core_filepicker.active_filepicker = scope;
1738 scope.viewbar_set_enabled(false);
1739 scope.parse_repository_options(obj);
1740 scope.create_object_container(obj.object);
1741 } else if (obj.list) {
1742 scope.viewbar_set_enabled(true);
1743 scope.parse_repository_options(obj);
1747 list: function(args) {
1751 if (!args.repo_id) {
1752 args.repo_id = this.active_repo.id;
1757 this.currentpath = args.path;
1760 client_id: this.options.client_id,
1761 repository_id: args.repo_id,
1765 callback: this.display_response
1768 populate_licenses_select: function(node) {
1772 node.setContent('');
1773 var licenses = this.options.licenses;
1774 var recentlicense = this.get_preference('recentlicense');
1775 if (recentlicense) {
1776 this.options.defaultlicense=recentlicense;
1778 for (var i in licenses) {
1779 var option = Y.Node.create('<option/>').
1780 set('selected', (this.options.defaultlicense==licenses[i].shortname)).
1781 set('value', licenses[i].shortname).
1782 setContent(Y.Escape.html(licenses[i].fullname));
1783 node.appendChild(option)
1786 set_selected_license: function(node, value) {
1787 var licenseset = false;
1788 node.all('option').each(function(el) {
1789 if (el.get('value')==value || el.getContent()==value) {
1790 el.set('selected', true);
1795 // we did not find the value in the list
1796 var recentlicense = this.get_preference('recentlicense');
1797 node.all('option[selected]').set('selected', false);
1798 node.all('option[value='+recentlicense+']').set('selected', true);
1801 create_object_container: function(data) {
1802 var content = this.fpnode.one('.fp-content');
1803 content.setContent('');
1804 //var str = '<object data="'+data.src+'" type="'+data.type+'" width="98%" height="98%" id="container_object" class="fp-object-container mdl-align"></object>';
1805 var container = Y.Node.create('<object/>').
1806 setAttrs({data:data.src, type:data.type, id:'container_object'}).
1807 addClass('fp-object-container');
1808 content.setContent('').appendChild(container);
1810 create_upload_form: function(data) {
1811 var client_id = this.options.client_id;
1812 var id = data.upload.id+'_'+client_id;
1813 var content = this.fpnode.one('.fp-content');
1814 var template_name = 'uploadform_'+this.options.repositories[data.repo_id].type;
1815 var template = M.core_filepicker.templates[template_name] || M.core_filepicker.templates['uploadform'];
1816 content.setContent(template);
1818 content.all('.fp-file,.fp-saveas,.fp-setauthor,.fp-setlicense').each(function (node) {
1819 node.all('label').set('for', node.one('input,select').generateID());
1821 content.one('form').set('id', id);
1822 content.one('.fp-file input').set('name', 'repo_upload_file');
1823 if (data.upload.label && content.one('.fp-file label')) {
1824 content.one('.fp-file label').setContent(data.upload.label);
1826 content.one('.fp-saveas input').set('name', 'title');
1827 content.one('.fp-setauthor input').setAttrs({name:'author', value:this.options.author});
1828 content.one('.fp-setlicense select').set('name', 'license');
1829 this.populate_licenses_select(content.one('.fp-setlicense select'))
1830 // append hidden inputs to the upload form
1831 content.one('form').appendChild(Y.Node.create('<input/>').
1832 setAttrs({type:'hidden',name:'itemid',value:this.options.itemid}));
1833 var types = this.options.accepted_types;
1834 for (var i in types) {
1835 content.one('form').appendChild(Y.Node.create('<input/>').
1836 setAttrs({type:'hidden',name:'accepted_types[]',value:types[i]}));
1840 content.one('.fp-upload-btn').on('click', function(e) {
1842 var license = content.one('.fp-setlicense select');
1844 this.set_preference('recentlicense', license.get('value'));
1845 if (!content.one('.fp-file input').get('value')) {
1846 scope.print_msg(M.util.get_string('nofilesattached', 'repository'), 'error');
1853 client_id: client_id,
1854 params: {'savepath':scope.options.savepath},
1855 repository_id: scope.active_repo.id,
1856 form: {id: id, upload:true},
1857 onerror: function(id, o, args) {
1858 scope.create_upload_form(data);
1860 callback: function(id, o, args) {
1861 if (o.event == 'fileexists') {
1862 scope.create_upload_form(data);
1863 scope.process_existing_file(o);
1866 if (scope.options.editor_target&&scope.options.env=='editor') {
1867 scope.options.editor_target.value=o.url;
1868 scope.options.editor_target.dispatchEvent(new Event('change'), {'bubbles': true});
1871 o.client_id = client_id;
1872 var formcallback_scope = args.scope.options.magicscope ? args.scope.options.magicscope : args.scope;
1873 scope.options.formcallback.apply(formcallback_scope, [o]);
1878 /** setting handlers and labels for elements in toolbar. Called once during the initial render of filepicker */
1879 setup_toolbar: function() {
1880 var client_id = this.options.client_id;
1881 var toolbar = this.fpnode.one('.fp-toolbar');
1882 toolbar.one('.fp-tb-logout').one('a,button').on('click', function(e) {
1884 if (!this.active_repo.nologin) {
1888 client_id: this.options.client_id,
1889 repository_id: this.active_repo.id,
1891 callback: this.display_response
1894 if (this.active_repo.logouturl) {
1895 window.open(this.active_repo.logouturl, 'repo_auth', 'location=0,status=0,width=500,height=300,scrollbars=yes');
1898 toolbar.one('.fp-tb-refresh').one('a,button').on('click', function(e) {
1900 if (!this.active_repo.norefresh) {
1901 this.list({ path: this.currentpath });
1904 toolbar.one('.fp-tb-search form').
1905 set('method', 'POST').
1906 set('id', 'fp-tb-search-'+client_id).
1907 on('submit', function(e) {
1909 if (!this.active_repo.nosearch) {
1913 client_id: this.options.client_id,
1914 repository_id: this.active_repo.id,
1915 form: {id: 'fp-tb-search-'+client_id, upload:false, useDisabled:true},
1916 callback: this.display_response
1921 // it does not matter what kind of element is .fp-tb-manage, we create a dummy <a>
1922 // element and use it to open url on click event
1923 var managelnk = Y.Node.create('<a/>').
1924 setAttrs({id:'fp-tb-manage-'+client_id+'-link', target:'_blank'}).
1925 setStyle('display', 'none');
1926 toolbar.append(managelnk);
1927 toolbar.one('.fp-tb-manage').one('a,button').
1928 on('click', function(e) {
1930 managelnk.simulate('click')
1933 // same with .fp-tb-help
1934 var helplnk = Y.Node.create('<a/>').
1935 setAttrs({id:'fp-tb-help-'+client_id+'-link', target:'_blank'}).
1936 setStyle('display', 'none');
1937 toolbar.append(helplnk);
1938 toolbar.one('.fp-tb-help').one('a,button').
1939 on('click', function(e) {
1941 helplnk.simulate('click')
1944 hide_header: function() {
1945 if (this.fpnode.one('.fp-toolbar')) {
1946 this.fpnode.one('.fp-toolbar').addClass('empty');
1949 this.pathbar.setContent('').addClass('empty');
1952 print_header: function() {
1953 var r = this.active_repo;
1955 var client_id = this.options.client_id;
1958 var toolbar = this.fpnode.one('.fp-toolbar');
1959 if (!toolbar) { return; }
1961 var enable_tb_control = function(node, enabled) {
1962 if (!node) { return; }
1963 node.addClassIf('disabled', !enabled).addClassIf('enabled', enabled)
1965 toolbar.removeClass('empty');
1969 // TODO 'back' permanently disabled for now. Note, flickr_public uses 'Logout' for it!
1970 enable_tb_control(toolbar.one('.fp-tb-back'), false);
1973 enable_tb_control(toolbar.one('.fp-tb-search'), !r.nosearch);
1975 var searchform = toolbar.one('.fp-tb-search form');
1976 searchform.setContent('');
1979 action:'searchform',
1980 repository_id: this.active_repo.id,
1981 callback: function(id, obj, args) {
1982 if (obj.repo_id == scope.active_repo.id && obj.form) {
1983 // if we did not jump to another repository meanwhile
1984 searchform.setContent(obj.form);
1985 // Highlight search text when user click for search.
1986 var searchnode = searchform.one('input[name="s"]');
1988 searchnode.once('click', function(e) {
1999 // weather we use cache for this instance, this button will reload listing anyway
2000 enable_tb_control(toolbar.one('.fp-tb-refresh'), !r.norefresh);
2003 enable_tb_control(toolbar.one('.fp-tb-logout'), !r.nologin);
2006 enable_tb_control(toolbar.one('.fp-tb-manage'), r.manage);
2007 Y.one('#fp-tb-manage-'+client_id+'-link').set('href', r.manage);
2010 enable_tb_control(toolbar.one('.fp-tb-help'), r.help);
2011 Y.one('#fp-tb-help-'+client_id+'-link').set('href', r.help);
2014 enable_tb_control(toolbar.one('.fp-tb-message'), r.message);
2015 toolbar.one('.fp-tb-message').setContent(r.message);
2017 print_path: function() {
2018 if (!this.pathbar) {
2021 this.pathbar.setContent('').addClass('empty');
2022 var p = this.filepath;
2023 if (p && p.length!=0 && this.viewmode != 2) {
2024 for(var i = 0; i < p.length; i++) {
2025 var el = this.pathnode.cloneNode(true);
2026 this.pathbar.appendChild(el);
2028 el.addClass('first');
2030 if (i == p.length-1) {
2031 el.addClass('last');
2034 el.addClass('even');
2038 el.all('.fp-path-folder-name').setContent(Y.Escape.html(p[i].name));
2042 this.list({'path':path});
2046 this.pathbar.removeClass('empty');
2050 this.selectui.hide();
2051 if (this.process_dlg) {
2052 this.process_dlg.hide();
2055 this.msg_dlg.hide();
2063 this.show_recent_repository();
2068 launch: function() {
2071 show_recent_repository: function() {
2073 this.viewbar_set_enabled(false);
2074 var repository_id = this.get_preference('recentrepository');
2075 this.viewmode = this.get_preference('recentviewmode');
2076 if (this.viewmode != 2 && this.viewmode != 3) {
2079 if (this.options.repositories[repository_id]) {
2080 this.list({'repo_id':repository_id});
2083 get_preference: function (name) {
2084 if (this.options.userprefs[name]) {
2085 return this.options.userprefs[name];
2090 set_preference: function(name, value) {
2091 if (this.options.userprefs[name] != value) {
2092 M.util.set_user_preference('filepicker_' + name, value);
2093 this.options.userprefs[name] = value;
2096 in_iframe: function () {
2097 // If we're not the top window then we're in an iFrame
2098 return window.self !== window.top;
2101 var loading = Y.one('#filepicker-loading-'+options.client_id);
2103 loading.setStyle('display', 'none');
2105 M.core_filepicker.instances[options.client_id] = new FilePickerHelper(options);