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 // Notify the user if any of the files has a problem status.
431 var problemFiles = [];
432 fileslist.forEach(function(file) {
433 if (!file_is_folder(file) && file.hasOwnProperty('status') && file.status != 0) {
434 problemFiles.push(file);
437 if (problemFiles.length > 0) {
438 require(["core/notification", "core/str"], function(Notification, Str) {
439 problemFiles.forEach(function(problemFile) {
440 Str.get_string('storedfilecannotreadfile', 'error', problemFile.fullname).then(function(string) {
441 Notification.addNotification({
446 }).catch(Notification.exception);
451 // If table view, need some additional properties
452 // before passing fileslist to the YUI tableview
453 if (options.viewmode == 3) {
454 fileslist.forEach(function(el) {
455 el.displayname = file_get_displayname(el);
456 el.isfolder = file_is_folder(el);
457 el.classname = options.classnamecallback(el);
461 // initialize files view
462 if (!options.appendonly) {
463 var parent = Y.Node.create('<div/>').addClass(classname);
464 this.setContent('').appendChild(parent);
466 if (options.viewmode == 2) {
467 initialize_tree_view();
468 } else if (options.viewmode == 3) {
469 initialize_table_view();
471 // nothing to initialize for icon view
475 // append files to the list
476 if (options.viewmode == 2) {
478 } else if (options.viewmode == 3) {
479 append_files_table();
481 append_files_icons();
486 requires:['base', 'node', 'yui2-treeview', 'panel', 'cookie', 'datatable', 'datatable-sort']
489 M.core_filepicker = M.core_filepicker || {};
492 * instances of file pickers used on page
494 M.core_filepicker.instances = M.core_filepicker.instances || {};
495 M.core_filepicker.active_filepicker = null;
498 * HTML Templates to use in FilePicker
500 M.core_filepicker.templates = M.core_filepicker.templates || {};
503 * Array of image sources for real previews (realicon or realthumbnail) that are already loaded
505 M.core_filepicker.loadedpreviews = M.core_filepicker.loadedpreviews || {};
508 * Set selected file info
510 * @param object file info
512 M.core_filepicker.select_file = function(file) {
513 M.core_filepicker.active_filepicker.select_file(file);
517 * Init and show file picker
519 M.core_filepicker.show = function(Y, options) {
520 if (!M.core_filepicker.instances[options.client_id]) {
521 M.core_filepicker.init(Y, options);
523 M.core_filepicker.instances[options.client_id].options.formcallback = options.formcallback;
524 M.core_filepicker.instances[options.client_id].show();
527 M.core_filepicker.set_templates = function(Y, templates) {
528 for (var templid in templates) {
529 M.core_filepicker.templates[templid] = templates[templid];
534 * Add new file picker to current instances
536 M.core_filepicker.init = function(Y, options) {
537 var FilePickerHelper = function(options) {
538 FilePickerHelper.superclass.constructor.apply(this, arguments);
541 FilePickerHelper.NAME = "FilePickerHelper";
542 FilePickerHelper.ATTRS = {
547 Y.extend(FilePickerHelper, Y.Base, {
548 api: M.cfg.wwwroot+'/repository/repository_ajax.php',
549 cached_responses: {},
550 waitinterval : null, // When the loading template is being displayed and its animation is running this will be an interval instance.
551 initializer: function(options) {
552 this.options = options;
553 if (!this.options.savepath) {
554 this.options.savepath = '/';
558 destructor: function() {
561 request: function(args, redraw) {
562 var api = (args.api ? args.api : this.api) + '?action='+args.action;
564 var scope = args['scope'] ? args['scope'] : this;
565 params['repo_id']=args.repository_id;
566 params['p'] = args.path?args.path:'';
567 params['page'] = args.page?args.page:'';
568 params['env']=this.options.env;
569 // the form element only accept certain file types
570 params['accepted_types']=this.options.accepted_types;
571 params['sesskey'] = M.cfg.sesskey;
572 params['client_id'] = args.client_id;
573 params['itemid'] = this.options.itemid?this.options.itemid:0;
574 params['maxbytes'] = this.options.maxbytes?this.options.maxbytes:-1;
575 // The unlimited value of areamaxbytes is -1, it is defined by FILE_AREA_MAX_BYTES_UNLIMITED.
576 params['areamaxbytes'] = this.options.areamaxbytes ? this.options.areamaxbytes : -1;
577 if (this.options.context && this.options.context.id) {
578 params['ctx_id'] = this.options.context.id;
580 if (args['params']) {
581 for (i in args['params']) {
582 params[i] = args['params'][i];
585 if (args.action == 'upload') {
587 for(var k in params) {
588 var value = params[k];
589 if(value instanceof Array) {
590 for(var i in value) {
591 list.push(k+'[]='+value[i]);
594 list.push(k+'='+value);
597 params = list.join('&');
599 params = build_querystring(params);
604 complete: function(id,o,p) {
607 data = Y.JSON.parse(o.responseText);
609 if (o && o.status && o.status > 0) {
610 Y.use('moodle-core-notification-exception', function() {
611 return new M.core.exception(e);
617 if (data && data.error) {
618 Y.use('moodle-core-notification-ajaxexception', function () {
619 return new M.core.ajaxException(data);
621 this.fpnode.one('.fp-content').setContent('');
625 scope.print_msg(data.msg, 'info');
627 // cache result if applicable
628 if (args.action != 'upload' && data.allowcaching) {
629 scope.cached_responses[params] = data;
632 args.callback(id,data,p);
640 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
646 cfg.form = args.form;
648 // check if result of the same request has been already cached. If not, request it
649 // (never applicable in case of form submission and/or upload action):
650 if (!args.form && args.action != 'upload' && scope.cached_responses[params]) {
651 args.callback(null, scope.cached_responses[params], {scope: scope})
659 /** displays the dialog and processes rename/overwrite if there is a file with the same name in the same filearea*/
660 process_existing_file: function(data) {
662 var handleOverwrite = function(e) {
665 var data = this.process_dlg.dialogdata;
667 params['existingfilename'] = data.existingfile.filename;
668 params['existingfilepath'] = data.existingfile.filepath;
669 params['newfilename'] = data.newfile.filename;
670 params['newfilepath'] = data.newfile.filepath;
675 'action':'overwrite',
677 'client_id': this.options.client_id,
678 'repository_id': this.active_repo.id,
679 'callback': function(id, o, args) {
681 // Add an arbitrary parameter to the URL to force browsers to re-load the new image even
682 // if the file name has not changed.
683 var urlimage = data.existingfile.url + "?time=" + (new Date()).getTime();
684 if (scope.options.editor_target && scope.options.env == 'editor') {
685 // editor needs to update url
686 scope.options.editor_target.value = urlimage;
687 scope.options.editor_target.onchange();
689 var fileinfo = {'client_id':scope.options.client_id,
691 'file': data.existingfile.filename};
692 var formcallback_scope = scope.options.magicscope ? scope.options.magicscope : scope;
693 scope.options.formcallback.apply(formcallback_scope, [fileinfo]);
697 var handleRename = function(e) {
698 // inserts file with the new name
701 var data = this.process_dlg.dialogdata;
702 if (scope.options.editor_target && scope.options.env == 'editor') {
703 scope.options.editor_target.value = data.newfile.url;
704 scope.options.editor_target.onchange();
707 var formcallback_scope = scope.options.magicscope ? scope.options.magicscope : scope;
708 var fileinfo = {'client_id':scope.options.client_id,
709 'url':data.newfile.url,
710 'file':data.newfile.filename};
711 scope.options.formcallback.apply(formcallback_scope, [fileinfo]);
713 var handleCancel = function(e) {
717 params['newfilename'] = this.process_dlg.dialogdata.newfile.filename;
718 params['newfilepath'] = this.process_dlg.dialogdata.newfile.filepath;
722 'action':'deletetmpfile',
724 'client_id': this.options.client_id,
725 'repository_id': this.active_repo.id,
726 'callback': function(id, o, args) {
727 // let it be in background, from user point of view nothing is happenning
730 this.process_dlg.hide();
731 this.selectui.hide();
733 if (!this.process_dlg) {
734 this.process_dlg_node = Y.Node.create(M.core_filepicker.templates.processexistingfile);
735 var node = this.process_dlg_node;
737 this.process_dlg = new M.core.dialogue({
740 headerContent: M.util.get_string('fileexistsdialogheader', 'repository'),
744 zIndex : this.options.zIndex
746 node.one('.fp-dlg-butoverwrite').on('click', handleOverwrite, this);
747 node.one('.fp-dlg-butrename').on('click', handleRename, this);
748 node.one('.fp-dlg-butcancel').on('click', handleCancel, this);
749 if (this.options.env == 'editor') {
750 node.one('.fp-dlg-text').setContent(M.util.get_string('fileexistsdialog_editor', 'repository'));
752 node.one('.fp-dlg-text').setContent(M.util.get_string('fileexistsdialog_filemanager', 'repository'));
755 this.selectnode.removeClass('loading');
756 this.process_dlg.dialogdata = data;
757 this.process_dlg_node.one('.fp-dlg-butrename').setContent(M.util.get_string('renameto', 'repository', data.newfile.filename));
758 this.process_dlg.show();
760 /** displays error instead of filepicker contents */
761 display_error: function(errortext, errorcode) {
762 this.fpnode.one('.fp-content').setContent(M.core_filepicker.templates.error);
763 this.fpnode.one('.fp-content .fp-error').
765 setContent(Y.Escape.html(errortext));
767 /** displays message in a popup */
768 print_msg: function(msg, type) {
769 var header = M.util.get_string('error', 'moodle');
770 if (type != 'error') {
771 type = 'info'; // one of only two types excepted
772 header = M.util.get_string('info', 'moodle');
775 this.msg_dlg_node = Y.Node.create(M.core_filepicker.templates.message);
776 this.msg_dlg_node.generateID();
778 this.msg_dlg = new M.core.dialogue({
780 bodyContent : this.msg_dlg_node,
784 zIndex : this.options.zIndex
786 this.msg_dlg_node.one('.fp-msg-butok').on('click', function(e) {
792 this.msg_dlg.set('headerContent', header);
793 this.msg_dlg_node.removeClass('fp-msg-info').removeClass('fp-msg-error').addClass('fp-msg-'+type)
794 this.msg_dlg_node.one('.fp-msg-text').setContent(Y.Escape.html(msg));
797 view_files: function(appenditems) {
798 this.viewbar_set_enabled(true);
800 /*if ((appenditems == null) && (!this.filelist || !this.filelist.length) && !this.active_repo.hasmorepages) {
801 // TODO do it via classes and adjust for each view mode!
802 // If there are no items and no next page, just display status message and quit
803 this.display_error(M.util.get_string('nofilesavailable', 'repository'), 'nofilesavailable');
806 if (this.viewmode == 2) {
807 this.view_as_list(appenditems);
808 } else if (this.viewmode == 3) {
809 this.view_as_table(appenditems);
811 this.view_as_icons(appenditems);
813 this.fpnode.one('.fp-content').setAttribute('tabindex', '0');
814 this.fpnode.one('.fp-content').focus();
815 // display/hide the link for requesting next page
816 if (!appenditems && this.active_repo.hasmorepages) {
817 if (!this.fpnode.one('.fp-content .fp-nextpage')) {
818 this.fpnode.one('.fp-content').append(M.core_filepicker.templates.nextpage);
820 this.fpnode.one('.fp-content .fp-nextpage').one('a,button').on('click', function(e) {
822 this.fpnode.one('.fp-content .fp-nextpage').addClass('loading');
823 this.request_next_page();
826 if (!this.active_repo.hasmorepages && this.fpnode.one('.fp-content .fp-nextpage')) {
827 this.fpnode.one('.fp-content .fp-nextpage').remove();
829 if (this.fpnode.one('.fp-content .fp-nextpage')) {
830 this.fpnode.one('.fp-content .fp-nextpage').removeClass('loading');
832 this.content_scrolled();
834 content_scrolled: function(e) {
835 setTimeout(Y.bind(function() {
836 if (this.processingimages) {
839 this.processingimages = true;
841 fpcontent = this.fpnode.one('.fp-content'),
842 fpcontenty = fpcontent.getY(),
843 fpcontentheight = fpcontent.getStylePx('height'),
844 nextpage = fpcontent.one('.fp-nextpage'),
845 is_node_visible = function(node) {
846 var offset = node.getY()-fpcontenty;
847 if (offset <= fpcontentheight && (offset >=0 || offset+node.getStylePx('height')>=0)) {
852 // automatically load next page when 'more' link becomes visible
853 if (nextpage && !nextpage.hasClass('loading') && is_node_visible(nextpage)) {
854 nextpage.one('a,button').simulate('click');
856 // replace src for visible images that need to be lazy-loaded
857 if (scope.lazyloading) {
858 fpcontent.all('img').each( function(node) {
859 if (node.get('id') && scope.lazyloading[node.get('id')] && is_node_visible(node)) {
860 node.setImgRealSrc(scope.lazyloading);
864 this.processingimages = false;
867 treeview_dynload: function(node, cb) {
868 var retrieved_children = {};
870 for (var i in node.children) {
871 retrieved_children[node.children[i].path] = node.children[i];
876 client_id: this.options.client_id,
877 repository_id: this.active_repo.id,
878 path:node.path?node.path:'',
879 page:node.page?args.page:'',
881 callback: function(id, obj, args) {
883 var scope = args.scope;
884 // check that user did not leave the view mode before recieving this response
885 if (!(scope.active_repo.id == obj.repo_id && scope.viewmode == 2 && node && node.getChildrenEl())) {
888 if (cb != null) { // (in manual mode do not update current path)
889 scope.viewbar_set_enabled(true);
890 scope.parse_repository_options(obj);
892 node.highlight(false);
893 node.origlist = obj.list ? obj.list : null;
894 node.origpath = obj.path ? obj.path : null;
897 if (list[k].children && retrieved_children[list[k].path]) {
898 // if this child is a folder and has already been retrieved
899 node.children[node.children.length] = retrieved_children[list[k].path];
901 // append new file to the list
902 scope.view_as_list([list[k]]);
908 // invoke callback requested by TreeView component
911 scope.content_scrolled();
915 classnamecallback : function(node) {
918 classname = classname + ' fp-folder';
921 classname = classname + ' fp-isreference';
923 if (node.iscontrolledlink) {
924 classname = classname + ' fp-iscontrolledlink';
927 classname = classname + ' fp-hasreferences';
929 if (node.originalmissing) {
930 classname = classname + ' fp-originalmissing';
932 return Y.Lang.trim(classname);
934 /** displays list of files in tree (list) view mode. If param appenditems is specified,
935 * appends those items to the end of the list. Otherwise (default behaviour)
936 * clears the contents and displays the items from this.filelist */
937 view_as_list: function(appenditems) {
938 var list = (appenditems != null) ? appenditems : this.filelist;
940 if (!this.filelist || this.filelist.length==0 && (!this.filepath || !this.filepath.length)) {
941 this.display_error(M.util.get_string('nofilesavailable', 'repository'), 'nofilesavailable');
945 var element_template = Y.Node.create(M.core_filepicker.templates.listfilename);
947 viewmode : this.viewmode,
948 appendonly : (appenditems != null),
949 filenode : element_template,
950 callbackcontext : this,
951 callback : function(e, node) {
952 // TODO MDL-32736 e is not an event here but an object with properties 'event' and 'node'
953 if (!node.children) {
954 if (e.node.parent && e.node.parent.origpath) {
955 // set the current path
956 this.filepath = e.node.parent.origpath;
957 this.filelist = e.node.parent.origlist;
960 this.select_file(node);
962 // save current path and filelist (in case we want to jump to other viewmode)
963 this.filepath = e.node.origpath;
964 this.filelist = e.node.origlist;
965 this.currentpath = e.node.path;
967 this.content_scrolled();
970 classnamecallback : this.classnamecallback,
971 dynload : this.active_repo.dynload,
972 filepath : this.filepath,
973 treeview_dynload : this.treeview_dynload
975 this.fpnode.one('.fp-content').fp_display_filelist(options, list, this.lazyloading);
977 /** displays list of files in icon view mode. If param appenditems is specified,
978 * appends those items to the end of the list. Otherwise (default behaviour)
979 * clears the contents and displays the items from this.filelist */
980 view_as_icons: function(appenditems) {
982 var list = (appenditems != null) ? appenditems : this.filelist;
983 var element_template = Y.Node.create(M.core_filepicker.templates.iconfilename);
984 if ((appenditems == null) && (!this.filelist || !this.filelist.length)) {
985 this.display_error(M.util.get_string('nofilesavailable', 'repository'), 'nofilesavailable');
989 viewmode : this.viewmode,
990 appendonly : (appenditems != null),
991 filenode : element_template,
992 callbackcontext : this,
993 callback : function(e, node) {
994 if (e.preventDefault) {
998 if (this.active_repo.dynload) {
999 this.list({'path':node.path});
1001 this.filelist = node.children;
1005 this.select_file(node);
1008 classnamecallback : this.classnamecallback
1010 this.fpnode.one('.fp-content').fp_display_filelist(options, list, this.lazyloading);
1012 /** displays list of files in table view mode. If param appenditems is specified,
1013 * appends those items to the end of the list. Otherwise (default behaviour)
1014 * clears the contents and displays the items from this.filelist */
1015 view_as_table: function(appenditems) {
1017 var list = (appenditems != null) ? appenditems : this.filelist;
1018 if (!appenditems && (!this.filelist || this.filelist.length==0) && !this.active_repo.hasmorepages) {
1019 this.display_error(M.util.get_string('nofilesavailable', 'repository'), 'nofilesavailable');
1022 var element_template = Y.Node.create(M.core_filepicker.templates.listfilename);
1024 viewmode : this.viewmode,
1025 appendonly : (appenditems != null),
1026 filenode : element_template,
1027 callbackcontext : this,
1028 sortable : !this.active_repo.hasmorepages,
1029 callback : function(e, node) {
1030 if (e.preventDefault) {e.preventDefault();}
1031 if (node.children) {
1032 if (this.active_repo.dynload) {
1033 this.list({'path':node.path});
1035 this.filelist = node.children;
1039 this.select_file(node);
1042 classnamecallback : this.classnamecallback
1044 this.fpnode.one('.fp-content').fp_display_filelist(options, list, this.lazyloading);
1046 /** If more than one page available, requests and displays the files from the next page */
1047 request_next_page: function() {
1048 if (!this.active_repo.hasmorepages || this.active_repo.nextpagerequested) {
1052 this.active_repo.nextpagerequested = true;
1053 var nextpage = this.active_repo.page+1;
1056 repo_id: this.active_repo.id
1058 var action = this.active_repo.issearchresult ? 'search' : 'list';
1060 path: this.currentpath,
1063 client_id: this.options.client_id,
1064 repository_id: args.repo_id,
1066 callback: function(id, obj, args) {
1067 var scope = args.scope;
1068 // Check that we are still in the same repository and are expecting this page. We have no way
1069 // to compare the requested page and the one returned, so we assume that if the last chunk
1070 // of the breadcrumb is similar, then we probably are on the same page.
1071 var samepage = true;
1072 if (obj.path && scope.filepath) {
1073 var pathbefore = scope.filepath[scope.filepath.length-1];
1074 var pathafter = obj.path[obj.path.length-1];
1075 if (pathbefore.path != pathafter.path) {
1079 if (scope.active_repo.hasmorepages && obj.list && obj.page &&
1080 obj.repo_id == scope.active_repo.id &&
1081 obj.page == scope.active_repo.page+1 && samepage) {
1082 scope.parse_repository_options(obj, true);
1083 scope.view_files(obj.list)
1088 select_file: function(args) {
1089 var argstitle = args.title;
1090 // Limit the string length so it fits nicely on mobile devices
1091 var titlelength = 30;
1092 if (argstitle.length > titlelength) {
1093 argstitle = argstitle.substring(0, titlelength) + '...';
1095 Y.one('#fp-file_label_'+this.options.client_id).setContent(Y.Escape.html(M.util.get_string('select', 'repository')+' '+argstitle));
1096 this.selectui.show();
1097 Y.one('#'+this.selectnode.get('id')).focus();
1098 var client_id = this.options.client_id;
1099 var selectnode = this.selectnode;
1100 var return_types = this.options.repositories[this.active_repo.id].return_types;
1101 selectnode.removeClass('loading');
1102 selectnode.one('.fp-saveas input').set('value', args.title);
1104 var imgnode = Y.Node.create('<img/>').
1105 set('src', args.realthumbnail ? args.realthumbnail : args.thumbnail).
1106 setStyle('maxHeight', ''+(args.thumbnail_height ? args.thumbnail_height : 90)+'px').
1107 setStyle('maxWidth', ''+(args.thumbnail_width ? args.thumbnail_width : 90)+'px');
1108 selectnode.one('.fp-thumbnail').setContent('').appendChild(imgnode);
1110 // filelink is the array of file-link-types available for this repository in this env
1111 var filelinktypes = [2/*FILE_INTERNAL*/,1/*FILE_EXTERNAL*/,4/*FILE_REFERENCE*/,8/*FILE_CONTROLLED_LINK*/];
1112 var filelink = {}, firstfilelink = null, filelinkcount = 0;
1113 for (var i in filelinktypes) {
1114 var allowed = (return_types & filelinktypes[i]) &&
1115 (this.options.return_types & filelinktypes[i]);
1116 if (filelinktypes[i] == 1/*FILE_EXTERNAL*/ && !this.options.externallink && this.options.env == 'editor') {
1117 // special configuration setting 'repositoryallowexternallinks' may prevent
1118 // using external links in editor environment
1121 filelink[filelinktypes[i]] = allowed;
1122 firstfilelink = (firstfilelink==null && allowed) ? filelinktypes[i] : firstfilelink;
1123 filelinkcount += allowed ? 1 : 0;
1125 var defaultreturntype = this.options.repositories[this.active_repo.id].defaultreturntype;
1126 if (defaultreturntype) {
1127 if (filelink[defaultreturntype]) {
1128 firstfilelink = defaultreturntype;
1131 // make radio buttons enabled if this file-link-type is available and only if there are more than one file-link-type option
1132 // check the first available file-link-type option
1133 for (var linktype in filelink) {
1134 var el = selectnode.one('.fp-linktype-'+linktype);
1135 el.addClassIf('uneditable', !(filelink[linktype] && filelinkcount>1));
1136 el.one('input').set('checked', (firstfilelink == linktype) ? 'checked' : '').simulate('change');
1139 // TODO MDL-32532: attributes 'hasauthor' and 'haslicense' need to be obsolete,
1140 selectnode.one('.fp-setauthor input').set('value', args.author ? args.author : this.options.author);
1141 this.set_selected_license(selectnode.one('.fp-setlicense'), args.license);
1142 selectnode.one('form #filesource-'+client_id).set('value', args.source);
1143 selectnode.one('form #filesourcekey-'+client_id).set('value', args.sourcekey);
1145 // display static information about a file (when known)
1146 var attrs = ['datemodified','datecreated','size','license','author','dimensions'];
1147 for (var i in attrs) {
1148 if (selectnode.one('.fp-'+attrs[i])) {
1149 var value = (args[attrs[i]+'_f']) ? args[attrs[i]+'_f'] : (args[attrs[i]] ? args[attrs[i]] : '');
1150 selectnode.one('.fp-'+attrs[i]).addClassIf('fp-unknown', ''+value == '')
1151 .one('.fp-value').setContent(Y.Escape.html(value));
1155 setup_select_file: function() {
1156 var client_id = this.options.client_id;
1157 var selectnode = this.selectnode;
1158 var getfile = selectnode.one('.fp-select-confirm');
1159 // bind labels with corresponding inputs
1160 selectnode.all('.fp-saveas,.fp-linktype-2,.fp-linktype-1,.fp-linktype-4,fp-linktype-8,.fp-setauthor,.fp-setlicense').each(function (node) {
1161 node.all('label').set('for', node.one('input,select').generateID());
1163 selectnode.one('.fp-linktype-2 input').setAttrs({value: 2, name: 'linktype'});
1164 selectnode.one('.fp-linktype-1 input').setAttrs({value: 1, name: 'linktype'});
1165 selectnode.one('.fp-linktype-4 input').setAttrs({value: 4, name: 'linktype'});
1166 selectnode.one('.fp-linktype-8 input').setAttrs({value: 8, name: 'linktype'});
1167 var changelinktype = function(e) {
1168 if (e.currentTarget.get('checked')) {
1169 var allowinputs = e.currentTarget.get('value') != 1/*FILE_EXTERNAL*/;
1170 selectnode.all('.fp-setauthor,.fp-setlicense,.fp-saveas').each(function(node){
1171 node.addClassIf('uneditable', !allowinputs);
1172 node.all('input,select').set('disabled', allowinputs?'':'disabled');
1176 selectnode.all('.fp-linktype-2,.fp-linktype-1,.fp-linktype-4,.fp-linktype-8').each(function (node) {
1177 node.one('input').on('change', changelinktype, this);
1179 this.populate_licenses_select(selectnode.one('.fp-setlicense select'));
1180 // register event on clicking submit button
1181 getfile.on('click', function(e) {
1183 var client_id = this.options.client_id;
1185 var repository_id = this.active_repo.id;
1186 var title = selectnode.one('.fp-saveas input').get('value');
1187 var filesource = selectnode.one('form #filesource-'+client_id).get('value');
1188 var filesourcekey = selectnode.one('form #filesourcekey-'+client_id).get('value');
1189 var params = {'title':title, 'source':filesource, 'savepath': this.options.savepath, sourcekey: filesourcekey};
1190 var license = selectnode.one('.fp-setlicense select');
1192 params['license'] = license.get('value');
1193 var origlicense = selectnode.one('.fp-license .fp-value');
1195 origlicense = origlicense.getContent();
1197 this.set_preference('recentlicense', license.get('value'));
1199 params['author'] = selectnode.one('.fp-setauthor input').get('value');
1201 var return_types = this.options.repositories[this.active_repo.id].return_types;
1202 if (this.options.env == 'editor') {
1203 // in editor, images are stored in '/' only
1204 params.savepath = '/';
1206 if ((this.options.externallink || this.options.env != 'editor') &&
1207 (return_types & 1/*FILE_EXTERNAL*/) &&
1208 (this.options.return_types & 1/*FILE_EXTERNAL*/) &&
1209 selectnode.one('.fp-linktype-1 input').get('checked')) {
1210 params['linkexternal'] = 'yes';
1211 } else if ((return_types & 4/*FILE_REFERENCE*/) &&
1212 (this.options.return_types & 4/*FILE_REFERENCE*/) &&
1213 selectnode.one('.fp-linktype-4 input').get('checked')) {
1214 params['usefilereference'] = '1';
1215 } else if ((return_types & 8/*FILE_CONTROLLED_LINK*/) &&
1216 (this.options.return_types & 8/*FILE_CONTROLLED_LINK*/) &&
1217 selectnode.one('.fp-linktype-8 input').get('checked')) {
1218 params['usecontrolledlink'] = '1';
1221 selectnode.addClass('loading');
1224 client_id: client_id,
1225 repository_id: repository_id,
1227 onerror: function(id, obj, args) {
1228 selectnode.removeClass('loading');
1229 scope.selectui.hide();
1231 callback: function(id, obj, args) {
1232 selectnode.removeClass('loading');
1233 if (obj.event == 'fileexists') {
1234 scope.process_existing_file(obj);
1237 if (scope.options.editor_target && scope.options.env=='editor') {
1238 scope.options.editor_target.value=obj.url;
1239 scope.options.editor_target.onchange();
1242 obj.client_id = client_id;
1243 var formcallback_scope = args.scope.options.magicscope ? args.scope.options.magicscope : args.scope;
1244 scope.options.formcallback.apply(formcallback_scope, [obj]);
1248 var elform = selectnode.one('form');
1249 elform.appendChild(Y.Node.create('<input/>').
1250 setAttrs({type:'hidden',id:'filesource-'+client_id}));
1251 elform.appendChild(Y.Node.create('<input/>').
1252 setAttrs({type:'hidden',id:'filesourcekey-'+client_id}));
1253 elform.on('keydown', function(e) {
1254 if (e.keyCode == 13) {
1255 getfile.simulate('click');
1259 var cancel = selectnode.one('.fp-select-cancel');
1260 cancel.on('click', function(e) {
1262 this.selectui.hide();
1266 // First check there isn't already an interval in play, and if there is kill it now.
1267 if (this.waitinterval != null) {
1268 clearInterval(this.waitinterval);
1270 // Prepare the root node we will set content for and the loading template we want to display as a YUI node.
1271 var root = this.fpnode.one('.fp-content');
1272 var content = Y.Node.create(M.core_filepicker.templates.loading).addClass('fp-content-hidden').setStyle('opacity', 0);
1274 // Initiate an interval, we will have a count which will increment every 100 milliseconds.
1275 // Count 0 - the loading icon will have visibility set to hidden (invisible) and have an opacity of 0 (invisible also)
1276 // Count 5 - the visiblity will be switched to visible but opacity will still be at 0 (inivisible)
1277 // Counts 6 - 15 opacity will be increased by 0.1 making the loading icon visible over the period of a second
1278 // Count 16 - The interval will be cancelled.
1279 var interval = setInterval(function(){
1280 if (!content || !root.contains(content) || count >= 15) {
1281 clearInterval(interval);
1285 content.removeClass('fp-content-hidden');
1286 } else if (count > 5) {
1287 var opacity = parseFloat(content.getStyle('opacity'));
1288 content.setStyle('opacity', opacity + 0.1);
1293 // Store the wait interval so that we can check it in the future.
1294 this.waitinterval = interval;
1295 // Set the content to the loading template.
1296 root.setContent(content);
1298 viewbar_set_enabled: function(mode) {
1299 var viewbar = this.fpnode.one('.fp-viewbar')
1302 viewbar.addClass('enabled').removeClass('disabled');
1303 this.fpnode.all('.fp-vb-icons,.fp-vb-tree,.fp-vb-details').setAttribute("aria-disabled", "false");
1304 this.fpnode.all('.fp-vb-icons,.fp-vb-tree,.fp-vb-details').setAttribute("tabindex", "");
1306 viewbar.removeClass('enabled').addClass('disabled');
1307 this.fpnode.all('.fp-vb-icons,.fp-vb-tree,.fp-vb-details').setAttribute("aria-disabled", "true");
1308 this.fpnode.all('.fp-vb-icons,.fp-vb-tree,.fp-vb-details').setAttribute("tabindex", "-1");
1311 this.fpnode.all('.fp-vb-icons,.fp-vb-tree,.fp-vb-details').removeClass('checked');
1312 var modes = {1:'icons', 2:'tree', 3:'details'};
1313 this.fpnode.all('.fp-vb-'+modes[this.viewmode]).addClass('checked');
1315 viewbar_clicked: function(e) {
1317 var viewbar = this.fpnode.one('.fp-viewbar')
1318 if (!viewbar || !viewbar.hasClass('disabled')) {
1319 if (e.currentTarget.hasClass('fp-vb-tree')) {
1321 } else if (e.currentTarget.hasClass('fp-vb-details')) {
1326 this.viewbar_set_enabled(true)
1328 this.set_preference('recentviewmode', this.viewmode);
1331 render: function() {
1332 var client_id = this.options.client_id;
1333 var fpid = "filepicker-"+ client_id;
1334 var labelid = 'fp-dialog-label_'+ client_id;
1336 var draggable = true;
1337 this.fpnode = Y.Node.create(M.core_filepicker.templates.generallayout).
1338 set('id', 'filepicker-'+client_id).set('aria-labelledby', labelid);
1340 if (this.in_iframe()) {
1341 width = Math.floor(window.innerWidth * 0.95);
1345 this.mainui = new M.core.dialogue({
1346 extraClasses : ['filepicker'],
1347 draggable : draggable,
1348 bodyContent : this.fpnode,
1349 headerContent: '<h3 id="'+ labelid +'">'+ M.util.get_string('filepicker', 'repository') +'</h3>',
1354 responsiveWidth : 768,
1356 zIndex : this.options.zIndex
1359 // create panel for selecting a file (initially hidden)
1360 this.selectnode = Y.Node.create(M.core_filepicker.templates.selectlayout).
1361 set('id', 'filepicker-select-'+client_id).
1362 set('aria-live', 'assertive').
1363 set('role', 'dialog');
1365 var fplabel = 'fp-file_label_'+ client_id;
1366 this.selectui = new M.core.dialogue({
1367 headerContent: '<h3 id="' + fplabel +'">'+M.util.get_string('select', 'repository')+'</h3>',
1370 bodyContent : this.selectnode,
1374 zIndex : this.options.zIndex
1376 Y.one('#'+this.selectnode.get('id')).setAttribute('aria-labelledby', fplabel);
1377 // event handler for lazy loading of thumbnails and next page
1378 this.fpnode.one('.fp-content').on(['scroll','resize'], this.content_scrolled, this);
1379 // save template for one path element and location of path bar
1380 if (this.fpnode.one('.fp-path-folder')) {
1381 this.pathnode = this.fpnode.one('.fp-path-folder');
1382 this.pathbar = this.pathnode.get('parentNode');
1383 this.pathbar.removeChild(this.pathnode);
1385 // assign callbacks for view mode switch buttons
1386 this.fpnode.one('.fp-vb-icons').on('click', this.viewbar_clicked, this);
1387 this.fpnode.one('.fp-vb-tree').on('click', this.viewbar_clicked, this);
1388 this.fpnode.one('.fp-vb-details').on('click', this.viewbar_clicked, this);
1390 // assign callbacks for toolbar links
1391 this.setup_toolbar();
1392 this.setup_select_file();
1395 // processing repository listing
1396 // Resort the repositories by sortorder
1397 var sorted_repositories = [];
1399 for (i in this.options.repositories) {
1400 sorted_repositories[i] = this.options.repositories[i];
1402 sorted_repositories.sort(function(a,b){return a.sortorder-b.sortorder});
1403 // extract one repository template and repeat it for all repositories available,
1404 // set name and icon and assign callbacks
1405 var reponode = this.fpnode.one('.fp-repo');
1407 var list = reponode.get('parentNode');
1408 list.removeChild(reponode);
1409 for (i in sorted_repositories) {
1410 var repository = sorted_repositories[i];
1411 var h = (parseInt(i) == 0) ? parseInt(i) : parseInt(i) - 1,
1412 j = (parseInt(i) == Object.keys(sorted_repositories).length - 1) ? parseInt(i) : parseInt(i) + 1;
1413 var previousrepository = sorted_repositories[h];
1414 var nextrepository = sorted_repositories[j];
1415 var node = reponode.cloneNode(true);
1416 list.appendChild(node);
1418 set('id', 'fp-repo-'+client_id+'-'+repository.id).
1419 on('click', function(e, repository_id) {
1421 this.set_preference('recentrepository', repository_id);
1423 this.list({'repo_id':repository_id});
1424 }, this /*handler running scope*/, repository.id/*second argument of handler*/);
1425 node.on('key', function(e, previousrepositoryid, nextrepositoryid, clientid, repositoryid) {
1426 this.changeHighlightedRepository(e, clientid, repositoryid, previousrepositoryid, nextrepositoryid);
1427 }, 'down:38,40', this, previousrepository.id, nextrepository.id, client_id, repository.id);
1428 node.on('key', function(e, repositoryid) {
1430 this.set_preference('recentrepository', repositoryid);
1432 this.list({'repo_id': repositoryid});
1433 }, 'enter', this, repository.id);
1434 node.one('.fp-repo-name').setContent(Y.Escape.html(repository.name));
1435 node.one('.fp-repo-icon').set('src', repository.icon);
1437 node.addClass('first');
1439 if (i==sorted_repositories.length-1) {
1440 node.addClass('last');
1443 node.addClass('even');
1445 node.addClass('odd');
1449 // display error if no repositories found
1450 if (sorted_repositories.length==0) {
1451 this.display_error(M.util.get_string('norepositoriesavailable', 'repository'), 'norepositoriesavailable')
1453 // display repository that was used last time
1455 this.show_recent_repository();
1458 * Change the highlighted repository to a new one.
1460 * @param {object} event The key event
1461 * @param {integer} clientid The client id to identify the repo class.
1462 * @param {integer} oldrepositoryid The repository id that we are removing the highlight for
1463 * @param {integer} previousrepositoryid The previous repository id.
1464 * @param {integer} nextrepositoryid The next repository id.
1466 changeHighlightedRepository: function(event, clientid, oldrepositoryid, previousrepositoryid, nextrepositoryid) {
1467 event.preventDefault();
1468 var newrepositoryid = (event.keyCode == '40') ? nextrepositoryid : previousrepositoryid;
1469 this.fpnode.one('#fp-repo-' + clientid + '-' + oldrepositoryid).setAttribute('tabindex', '-1');
1470 this.fpnode.one('#fp-repo-' + clientid + '-' + newrepositoryid)
1471 .setAttribute('tabindex', '0')
1474 parse_repository_options: function(data, appendtolist) {
1477 if (!this.filelist) {
1480 for (var i in data.list) {
1481 this.filelist[this.filelist.length] = data.list[i];
1485 this.filelist = data.list?data.list:null;
1486 this.lazyloading = {};
1488 this.filepath = data.path?data.path:null;
1489 this.objecttag = data.object?data.object:null;
1490 this.active_repo = {};
1491 this.active_repo.issearchresult = data.issearchresult ? true : false;
1492 this.active_repo.defaultreturntype = data.defaultreturntype?data.defaultreturntype:null;
1493 this.active_repo.dynload = data.dynload?data.dynload:false;
1494 this.active_repo.pages = Number(data.pages?data.pages:null);
1495 this.active_repo.page = Number(data.page?data.page:null);
1496 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))
1497 this.active_repo.id = data.repo_id?data.repo_id:null;
1498 this.active_repo.nosearch = (data.login || data.nosearch); // this is either login form or 'nosearch' attribute set
1499 this.active_repo.norefresh = (data.login || data.norefresh); // this is either login form or 'norefresh' attribute set
1500 this.active_repo.nologin = (data.login || data.nologin); // this is either login form or 'nologin' attribute is set
1501 this.active_repo.logouttext = data.logouttext?data.logouttext:null;
1502 this.active_repo.logouturl = (data.logouturl || '');
1503 this.active_repo.message = (data.message || '');
1504 this.active_repo.help = data.help?data.help:null;
1505 this.active_repo.manage = data.manage?data.manage:null;
1506 this.print_header();
1508 print_login: function(data) {
1509 this.parse_repository_options(data);
1510 var client_id = this.options.client_id;
1511 var repository_id = data.repo_id;
1512 var l = this.logindata = data.login;
1514 var action = data['login_btn_action'] ? data['login_btn_action'] : 'login';
1515 var form_id = 'fp-form-'+client_id;
1517 var loginform_node = Y.Node.create(M.core_filepicker.templates.loginform);
1518 loginform_node.one('form').set('id', form_id);
1519 this.fpnode.one('.fp-content').setContent('').appendChild(loginform_node);
1521 'popup' : loginform_node.one('.fp-login-popup'),
1522 'textarea' : loginform_node.one('.fp-login-textarea'),
1523 'select' : loginform_node.one('.fp-login-select'),
1524 'text' : loginform_node.one('.fp-login-text'),
1525 'radio' : loginform_node.one('.fp-login-radiogroup'),
1526 'checkbox' : loginform_node.one('.fp-login-checkbox'),
1527 'input' : loginform_node.one('.fp-login-input')
1530 for (var i in templates) {
1532 container = templates[i].get('parentNode');
1533 container.removeChild(templates[i]);
1538 if (templates[l[k].type]) {
1539 var node = templates[l[k].type].cloneNode(true);
1541 node = templates['input'].cloneNode(true);
1543 if (l[k].type == 'popup') {
1545 loginurl = l[k].url;
1546 var popupbutton = node.one('button');
1547 popupbutton.on('click', function(e){
1548 M.core_filepicker.active_filepicker = this;
1549 window.open(loginurl, 'repo_auth', 'location=0,status=0,width=500,height=300,scrollbars=yes');
1552 loginform_node.one('form').on('keydown', function(e) {
1553 if (e.keyCode == 13) {
1554 popupbutton.simulate('click');
1558 loginform_node.all('.fp-login-submit').remove();
1560 } else if(l[k].type=='textarea') {
1562 if (node.one('label')) {
1563 node.one('label').set('for', l[k].id).setContent(l[k].label);
1565 node.one('textarea').setAttrs({id:l[k].id, name:l[k].name});
1566 } else if(l[k].type=='select') {
1568 if (node.one('label')) {
1569 node.one('label').set('for', l[k].id).setContent(l[k].label);
1571 node.one('select').setAttrs({id:l[k].id, name:l[k].name}).setContent('');
1572 for (i in l[k].options) {
1573 node.one('select').appendChild(
1574 Y.Node.create('<option/>').
1575 set('value', l[k].options[i].value).
1576 setContent(l[k].options[i].label));
1578 } else if(l[k].type=='radio') {
1579 // radio input element
1580 node.all('label').setContent(l[k].label);
1581 var list = l[k].value.split('|');
1582 var labels = l[k].value_label.split('|');
1583 var radionode = null;
1584 for(var item in list) {
1585 if (radionode == null) {
1586 radionode = node.one('.fp-login-radio');
1587 radionode.one('input').set('checked', 'checked');
1589 var x = radionode.cloneNode(true);
1590 radionode.insert(x, 'after');
1592 radionode.one('input').set('checked', '');
1594 radionode.one('input').setAttrs({id:''+l[k].id+item, name:l[k].name,
1595 type:l[k].type, value:list[item]});
1596 radionode.all('label').setContent(labels[item]).set('for', ''+l[k].id+item)
1598 if (radionode == null) {
1599 node.one('.fp-login-radio').remove();
1603 if (node.one('label')) { node.one('label').set('for', l[k].id).setContent(l[k].label) }
1605 set('type', l[k].type).
1607 set('name', l[k].name).
1608 set('value', l[k].value?l[k].value:'')
1610 container.appendChild(node);
1612 // custom label text for submit button
1613 if (data['login_btn_label']) {
1614 loginform_node.all('.fp-login-submit').setContent(data['login_btn_label'])
1616 // register button action for login and search
1617 if (action == 'login' || action == 'search') {
1618 loginform_node.one('.fp-login-submit').on('click', function(e){
1623 'action':(action == 'search') ? 'search' : 'signin',
1625 'client_id': client_id,
1626 'repository_id': repository_id,
1627 'form': {id:form_id, upload:false, useDisabled:true},
1628 'callback': this.display_response
1632 // if 'Enter' is pressed in the form, simulate the button click
1633 if (loginform_node.one('.fp-login-submit')) {
1634 loginform_node.one('form').on('keydown', function(e) {
1635 if (e.keyCode == 13) {
1636 loginform_node.one('.fp-login-submit').simulate('click')
1642 display_response: function(id, obj, args) {
1643 var scope = args.scope;
1644 // highlight the current repository in repositories list
1645 scope.fpnode.all('.fp-repo.active')
1646 .removeClass('active')
1647 .setAttribute('aria-selected', 'false')
1648 .setAttribute('tabindex', '-1');
1649 scope.fpnode.all('.nav-link')
1650 .removeClass('active')
1651 .setAttribute('aria-selected', 'false')
1652 .setAttribute('tabindex', '-1');
1653 var activenode = scope.fpnode.one('#fp-repo-' + scope.options.client_id + '-' + obj.repo_id);
1654 activenode.addClass('active')
1655 .setAttribute('aria-selected', 'true')
1656 .setAttribute('tabindex', '0');
1657 activenode.all('.nav-link').addClass('active');
1658 // add class repository_REPTYPE to the filepicker (for repository-specific styles)
1659 for (var i in scope.options.repositories) {
1660 scope.fpnode.removeClass('repository_'+scope.options.repositories[i].type)
1662 if (obj.repo_id && scope.options.repositories[obj.repo_id]) {
1663 scope.fpnode.addClass('repository_'+scope.options.repositories[obj.repo_id].type)
1665 Y.one('.file-picker .fp-repo-items').focus();
1669 scope.viewbar_set_enabled(false);
1670 scope.print_login(obj);
1671 } else if (obj.upload) {
1672 scope.viewbar_set_enabled(false);
1673 scope.parse_repository_options(obj);
1674 scope.create_upload_form(obj);
1675 } else if (obj.object) {
1676 M.core_filepicker.active_filepicker = scope;
1677 scope.viewbar_set_enabled(false);
1678 scope.parse_repository_options(obj);
1679 scope.create_object_container(obj.object);
1680 } else if (obj.list) {
1681 scope.viewbar_set_enabled(true);
1682 scope.parse_repository_options(obj);
1686 list: function(args) {
1690 if (!args.repo_id) {
1691 args.repo_id = this.active_repo.id;
1696 this.currentpath = args.path;
1699 client_id: this.options.client_id,
1700 repository_id: args.repo_id,
1704 callback: this.display_response
1707 populate_licenses_select: function(node) {
1711 node.setContent('');
1712 var licenses = this.options.licenses;
1713 var recentlicense = this.get_preference('recentlicense');
1714 if (recentlicense) {
1715 this.options.defaultlicense=recentlicense;
1717 for (var i in licenses) {
1718 var option = Y.Node.create('<option/>').
1719 set('selected', (this.options.defaultlicense==licenses[i].shortname)).
1720 set('value', licenses[i].shortname).
1721 setContent(Y.Escape.html(licenses[i].fullname));
1722 node.appendChild(option)
1725 set_selected_license: function(node, value) {
1726 var licenseset = false;
1727 node.all('option').each(function(el) {
1728 if (el.get('value')==value || el.getContent()==value) {
1729 el.set('selected', true);
1734 // we did not find the value in the list
1735 var recentlicense = this.get_preference('recentlicense');
1736 node.all('option[selected]').set('selected', false);
1737 node.all('option[value='+recentlicense+']').set('selected', true);
1740 create_object_container: function(data) {
1741 var content = this.fpnode.one('.fp-content');
1742 content.setContent('');
1743 //var str = '<object data="'+data.src+'" type="'+data.type+'" width="98%" height="98%" id="container_object" class="fp-object-container mdl-align"></object>';
1744 var container = Y.Node.create('<object/>').
1745 setAttrs({data:data.src, type:data.type, id:'container_object'}).
1746 addClass('fp-object-container');
1747 content.setContent('').appendChild(container);
1749 create_upload_form: function(data) {
1750 var client_id = this.options.client_id;
1751 var id = data.upload.id+'_'+client_id;
1752 var content = this.fpnode.one('.fp-content');
1753 var template_name = 'uploadform_'+this.options.repositories[data.repo_id].type;
1754 var template = M.core_filepicker.templates[template_name] || M.core_filepicker.templates['uploadform'];
1755 content.setContent(template);
1757 content.all('.fp-file,.fp-saveas,.fp-setauthor,.fp-setlicense').each(function (node) {
1758 node.all('label').set('for', node.one('input,select').generateID());
1760 content.one('form').set('id', id);
1761 content.one('.fp-file input').set('name', 'repo_upload_file');
1762 if (data.upload.label && content.one('.fp-file label')) {
1763 content.one('.fp-file label').setContent(data.upload.label);
1765 content.one('.fp-saveas input').set('name', 'title');
1766 content.one('.fp-setauthor input').setAttrs({name:'author', value:this.options.author});
1767 content.one('.fp-setlicense select').set('name', 'license');
1768 this.populate_licenses_select(content.one('.fp-setlicense select'))
1769 // append hidden inputs to the upload form
1770 content.one('form').appendChild(Y.Node.create('<input/>').
1771 setAttrs({type:'hidden',name:'itemid',value:this.options.itemid}));
1772 var types = this.options.accepted_types;
1773 for (var i in types) {
1774 content.one('form').appendChild(Y.Node.create('<input/>').
1775 setAttrs({type:'hidden',name:'accepted_types[]',value:types[i]}));
1779 content.one('.fp-upload-btn').on('click', function(e) {
1781 var license = content.one('.fp-setlicense select');
1783 this.set_preference('recentlicense', license.get('value'));
1784 if (!content.one('.fp-file input').get('value')) {
1785 scope.print_msg(M.util.get_string('nofilesattached', 'repository'), 'error');
1792 client_id: client_id,
1793 params: {'savepath':scope.options.savepath},
1794 repository_id: scope.active_repo.id,
1795 form: {id: id, upload:true},
1796 onerror: function(id, o, args) {
1797 scope.create_upload_form(data);
1799 callback: function(id, o, args) {
1800 if (o.event == 'fileexists') {
1801 scope.create_upload_form(data);
1802 scope.process_existing_file(o);
1805 if (scope.options.editor_target&&scope.options.env=='editor') {
1806 scope.options.editor_target.value=o.url;
1807 scope.options.editor_target.onchange();
1810 o.client_id = client_id;
1811 var formcallback_scope = args.scope.options.magicscope ? args.scope.options.magicscope : args.scope;
1812 scope.options.formcallback.apply(formcallback_scope, [o]);
1817 /** setting handlers and labels for elements in toolbar. Called once during the initial render of filepicker */
1818 setup_toolbar: function() {
1819 var client_id = this.options.client_id;
1820 var toolbar = this.fpnode.one('.fp-toolbar');
1821 toolbar.one('.fp-tb-logout').one('a,button').on('click', function(e) {
1823 if (!this.active_repo.nologin) {
1827 client_id: this.options.client_id,
1828 repository_id: this.active_repo.id,
1830 callback: this.display_response
1833 if (this.active_repo.logouturl) {
1834 window.open(this.active_repo.logouturl, 'repo_auth', 'location=0,status=0,width=500,height=300,scrollbars=yes');
1837 toolbar.one('.fp-tb-refresh').one('a,button').on('click', function(e) {
1839 if (!this.active_repo.norefresh) {
1840 this.list({ path: this.currentpath });
1843 toolbar.one('.fp-tb-search form').
1844 set('method', 'POST').
1845 set('id', 'fp-tb-search-'+client_id).
1846 on('submit', function(e) {
1848 if (!this.active_repo.nosearch) {
1852 client_id: this.options.client_id,
1853 repository_id: this.active_repo.id,
1854 form: {id: 'fp-tb-search-'+client_id, upload:false, useDisabled:true},
1855 callback: this.display_response
1860 // it does not matter what kind of element is .fp-tb-manage, we create a dummy <a>
1861 // element and use it to open url on click event
1862 var managelnk = Y.Node.create('<a/>').
1863 setAttrs({id:'fp-tb-manage-'+client_id+'-link', target:'_blank'}).
1864 setStyle('display', 'none');
1865 toolbar.append(managelnk);
1866 toolbar.one('.fp-tb-manage').one('a,button').
1867 on('click', function(e) {
1869 managelnk.simulate('click')
1872 // same with .fp-tb-help
1873 var helplnk = Y.Node.create('<a/>').
1874 setAttrs({id:'fp-tb-help-'+client_id+'-link', target:'_blank'}).
1875 setStyle('display', 'none');
1876 toolbar.append(helplnk);
1877 toolbar.one('.fp-tb-help').one('a,button').
1878 on('click', function(e) {
1880 helplnk.simulate('click')
1883 hide_header: function() {
1884 if (this.fpnode.one('.fp-toolbar')) {
1885 this.fpnode.one('.fp-toolbar').addClass('empty');
1888 this.pathbar.setContent('').addClass('empty');
1891 print_header: function() {
1892 var r = this.active_repo;
1894 var client_id = this.options.client_id;
1897 var toolbar = this.fpnode.one('.fp-toolbar');
1898 if (!toolbar) { return; }
1900 var enable_tb_control = function(node, enabled) {
1901 if (!node) { return; }
1902 node.addClassIf('disabled', !enabled).addClassIf('enabled', enabled)
1904 toolbar.removeClass('empty');
1908 // TODO 'back' permanently disabled for now. Note, flickr_public uses 'Logout' for it!
1909 enable_tb_control(toolbar.one('.fp-tb-back'), false);
1912 enable_tb_control(toolbar.one('.fp-tb-search'), !r.nosearch);
1914 var searchform = toolbar.one('.fp-tb-search form');
1915 searchform.setContent('');
1918 action:'searchform',
1919 repository_id: this.active_repo.id,
1920 callback: function(id, obj, args) {
1921 if (obj.repo_id == scope.active_repo.id && obj.form) {
1922 // if we did not jump to another repository meanwhile
1923 searchform.setContent(obj.form);
1924 // Highlight search text when user click for search.
1925 var searchnode = searchform.one('input[name="s"]');
1927 searchnode.once('click', function(e) {
1938 // weather we use cache for this instance, this button will reload listing anyway
1939 enable_tb_control(toolbar.one('.fp-tb-refresh'), !r.norefresh);
1942 enable_tb_control(toolbar.one('.fp-tb-logout'), !r.nologin);
1945 enable_tb_control(toolbar.one('.fp-tb-manage'), r.manage);
1946 Y.one('#fp-tb-manage-'+client_id+'-link').set('href', r.manage);
1949 enable_tb_control(toolbar.one('.fp-tb-help'), r.help);
1950 Y.one('#fp-tb-help-'+client_id+'-link').set('href', r.help);
1953 enable_tb_control(toolbar.one('.fp-tb-message'), r.message);
1954 toolbar.one('.fp-tb-message').setContent(r.message);
1956 print_path: function() {
1957 if (!this.pathbar) {
1960 this.pathbar.setContent('').addClass('empty');
1961 var p = this.filepath;
1962 if (p && p.length!=0 && this.viewmode != 2) {
1963 for(var i = 0; i < p.length; i++) {
1964 var el = this.pathnode.cloneNode(true);
1965 this.pathbar.appendChild(el);
1967 el.addClass('first');
1969 if (i == p.length-1) {
1970 el.addClass('last');
1973 el.addClass('even');
1977 el.all('.fp-path-folder-name').setContent(Y.Escape.html(p[i].name));
1981 this.list({'path':path});
1985 this.pathbar.removeClass('empty');
1989 this.selectui.hide();
1990 if (this.process_dlg) {
1991 this.process_dlg.hide();
1994 this.msg_dlg.hide();
2002 this.show_recent_repository();
2007 launch: function() {
2010 show_recent_repository: function() {
2012 this.viewbar_set_enabled(false);
2013 var repository_id = this.get_preference('recentrepository');
2014 this.viewmode = this.get_preference('recentviewmode');
2015 if (this.viewmode != 2 && this.viewmode != 3) {
2018 if (this.options.repositories[repository_id]) {
2019 this.list({'repo_id':repository_id});
2022 get_preference: function (name) {
2023 if (this.options.userprefs[name]) {
2024 return this.options.userprefs[name];
2029 set_preference: function(name, value) {
2030 if (this.options.userprefs[name] != value) {
2031 M.util.set_user_preference('filepicker_' + name, value);
2032 this.options.userprefs[name] = value;
2035 in_iframe: function () {
2036 // If we're not the top window then we're in an iFrame
2037 return window.self !== window.top;
2040 var loading = Y.one('#filepicker-loading-'+options.client_id);
2042 loading.setStyle('display', 'none');
2044 M.core_filepicker.instances[options.client_id] = new FilePickerHelper(options);