MDL-36548: Major performance boost to Detail (list) view in file picker
[moodle.git] / repository / filepicker.js
CommitLineData
99eaca9d
DC
1// YUI3 File Picker module for moodle
2// Author: Dongsheng Cai <dongsheng@moodle.com>
3
4/**
5 *
6 * File Picker UI
7 * =====
b5e7b638 8 * this.fpnode, contains reference to filepicker Node, non-empty if and only if rendered
99eaca9d 9 * this.api, stores the URL to make ajax request
99eaca9d 10 * this.mainui, YUI Panel
55089a9d 11 * this.selectnode, contains reference to select-file Node
b5e7b638
MG
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
99eaca9d 15 * this.treeview, YUI Treeview
99eaca9d 16 * this.viewmode, store current view mode
b5e7b638
MG
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)
82525f59 19 * this.currentpath, the current path in the repository (or last requested path)
99eaca9d
DC
20 *
21 * Filepicker options:
22 * =====
99eaca9d
DC
23 * this.options.client_id, the instance id
24 * this.options.contextid
25 * this.options.itemid
26 * this.options.repositories, stores all repositories displaied in file picker
27 * this.options.formcallback
28 *
29 * Active repository options
30 * =====
31 * this.active_repo.id
32 * this.active_repo.nosearch
33 * this.active_repo.norefresh
34 * this.active_repo.nologin
35 * this.active_repo.help
36 * this.active_repo.manage
8cbef19e 37 *
99eaca9d
DC
38 * Server responses
39 * =====
40 * this.filelist, cached filelist
41 * this.pages
42 * this.page
82525f59 43 * this.filepath, current path (each element of the array is a part of the breadcrumb)
99eaca9d
DC
44 * this.logindata, cached login form
45 */
46
e709ddd2
MG
47YUI.add('moodle-core_filepicker', function(Y) {
48 /** help function to extract width/height style as a number, not as a string */
49 Y.Node.prototype.getStylePx = function(attr) {
50 var style = this.getStyle(attr);
51 if (''+style == '0' || ''+style == '0px') {
52 return 0;
53 }
54 var matches = style.match(/^([\d\.]+)px$/)
55 if (matches && parseFloat(matches[1])) {
56 return parseFloat(matches[1]);
57 }
58 return null;
59 }
60
61 /** if condition is met, the class is added to the node, otherwise - removed */
62 Y.Node.prototype.addClassIf = function(className, condition) {
63 if (condition) {
64 this.addClass(className);
65 } else {
66 this.removeClass(className);
67 }
68 return this;
69 }
70
71 /** sets the width(height) of the node considering existing minWidth(minHeight) */
72 Y.Node.prototype.setStyleAdv = function(stylename, value) {
73 var stylenameCap = stylename.substr(0,1).toUpperCase() + stylename.substr(1, stylename.length-1).toLowerCase();
74 this.setStyle(stylename, '' + Math.max(value, this.getStylePx('min'+stylenameCap)) + 'px')
75 return this;
76 }
77
9213f547
MG
78 /** set image source to src, if there is preview, remember it in lazyloading.
79 * If there is a preview and it was already loaded, use it. */
80 Y.Node.prototype.setImgSrc = function(src, realsrc, lazyloading) {
81 if (realsrc) {
82 if (M.core_filepicker.loadedpreviews[realsrc]) {
83 this.set('src', realsrc).addClass('realpreview');
84 return this;
85 } else {
86 if (!this.get('id')) {
87 this.generateID();
88 }
89 lazyloading[this.get('id')] = realsrc;
90 }
91 }
92 this.set('src', src);
93 return this;
94 }
95
96 /**
97 * Replaces the image source with preview. If the image is inside the treeview, we need
98 * also to update the html property of corresponding YAHOO.widget.HTMLNode
99 * @param array lazyloading array containing associations of imgnodeid->realsrc
100 */
101 Y.Node.prototype.setImgRealSrc = function(lazyloading) {
102 if (this.get('id') && lazyloading[this.get('id')]) {
103 var newsrc = lazyloading[this.get('id')];
104 M.core_filepicker.loadedpreviews[newsrc] = true;
105 this.set('src', newsrc).addClass('realpreview');
106 delete lazyloading[this.get('id')];
107 var treenode = this.ancestor('.fp-treeview')
108 if (treenode && treenode.get('parentNode').treeview) {
109 treenode.get('parentNode').treeview.getRoot().refreshPreviews(this.get('id'), newsrc);
110 }
111 }
112 return this;
113 }
114
115 /** scan TreeView to find which node contains image with id=imgid and replace it's html
116 * with the new image source. */
117 YAHOO.widget.Node.prototype.refreshPreviews = function(imgid, newsrc, regex) {
118 if (!regex) {
119 regex = new RegExp("<img\\s[^>]*id=\""+imgid+"\"[^>]*?(/?)>", "im");
120 }
121 if (this.expanded || this.isLeaf) {
122 var html = this.getContentHtml();
123 if (html && this.setHtml && regex.test(html)) {
124 var newhtml = this.html.replace(regex, "<img id=\""+imgid+"\" src=\""+newsrc+"\" class=\"realpreview\"$1>", html);
125 this.setHtml(newhtml);
126 return true;
127 }
128 if (!this.isLeaf && this.children) {
129 for(var c in this.children) {
130 if (this.children[c].refreshPreviews(imgid, newsrc, regex)) {
131 return true;
132 }
133 }
134 }
135 }
136 return false;
137 }
138
e709ddd2
MG
139 /**
140 * Displays a list of files (used by filepicker, filemanager) inside the Node
141 *
142 * @param array options
143 * viewmode : 1 - icons, 2 - tree, 3 - table
144 * appendonly : whether fileslist need to be appended instead of replacing the existing content
145 * filenode : Node element that contains template for displaying one file
146 * callback : On click callback. The element of the fileslist array will be passed as argument
147 * rightclickcallback : On right click callback (optional).
148 * callbackcontext : context where callbacks are executed
149 * sortable : whether content may be sortable (in table mode)
150 * dynload : allow dynamic load for tree view
151 * filepath : for pre-building of tree view - the path to the current directory in filepicker format
6c2367cc
MG
152 * treeview_dynload : callback to function to dynamically load the folder in tree view
153 * classnamecallback : callback to function that returns the class name for an element
e709ddd2
MG
154 * @param array fileslist array of files to show, each array element may have attributes:
155 * title or fullname : file name
156 * shorttitle (optional) : display file name
157 * thumbnail : url of image
158 * icon : url of icon image
159 * thumbnail_width : width of thumbnail, default 90
160 * thumbnail_height : height of thumbnail, default 90
161 * thumbnail_alt : TODO not needed!
162 * description or thumbnail_title : alt text
163 * @param array lazyloading : reference to the array with lazy loading images
164 */
165 Y.Node.prototype.fp_display_filelist = function(options, fileslist, lazyloading) {
166 var viewmodeclassnames = {1:'fp-iconview', 2:'fp-treeview', 3:'fp-tableview'};
167 var classname = viewmodeclassnames[options.viewmode];
168 var scope = this;
169 /** return whether file is a folder (different attributes in FileManager and FilePicker) */
170 var file_is_folder = function(node) {
171 if (node.children) {return true;}
172 if (node.type && node.type == 'folder') {return true;}
173 return false;
174 };
175 /** return the name of the file (different attributes in FileManager and FilePicker) */
176 var file_get_filename = function(node) {
177 return node.title ? node.title : node.fullname;
178 }
179 /** return display name of the file (different attributes in FileManager and FilePicker) */
180 var file_get_displayname = function(node) {
181 return node.shorttitle ? node.shorttitle : file_get_filename(node);
182 }
183 /** return file description (different attributes in FileManager and FilePicker) */
184 var file_get_description = function(node) {
185 return node.description ? node.description : (node.thumbnail_title ? node.thumbnail_title : file_get_filename(node));
186 }
187 /** help funciton for tree view */
188 var build_tree = function(node, level) {
189 // prepare file name with icon
190 var el = Y.Node.create('<div/>');
191 el.appendChild(options.filenode.cloneNode(true));
192
193 el.one('.fp-filename').setContent(file_get_displayname(node));
194 // TODO add tooltip with node.title or node.thumbnail_title
6c2367cc
MG
195 var tmpnodedata = {className:options.classnamecallback(node)};
196 el.get('children').addClass(tmpnodedata.className);
e709ddd2 197 if (node.icon) {
9213f547
MG
198 el.one('.fp-icon').appendChild(Y.Node.create('<img/>'));
199 el.one('.fp-icon img').setImgSrc(node.icon, node.realicon, lazyloading);
e709ddd2
MG
200 }
201 // create node
23b83009
MG
202 tmpnodedata.html = el.getContent();
203 var tmpNode = new YAHOO.widget.HTMLNode(tmpnodedata, level, false);
e709ddd2
MG
204 if (node.dynamicLoadComplete) {
205 tmpNode.dynamicLoadComplete = true;
206 }
207 tmpNode.fileinfo = node;
208 tmpNode.isLeaf = !file_is_folder(node);
209 if (!tmpNode.isLeaf) {
210 if(node.expanded) {
211 tmpNode.expand();
212 }
213 tmpNode.path = node.path ? node.path : (node.filepath ? node.filepath : '');
214 for(var c in node.children) {
215 build_tree(node.children[c], tmpNode);
216 }
217 }
218 };
219 /** initialize tree view */
220 var initialize_tree_view = function() {
221 var parentid = scope.one('.'+classname).get('id');
23b83009 222 // TODO MDL-32736 use YUI3 gallery TreeView
e709ddd2
MG
223 scope.treeview = new YAHOO.widget.TreeView(parentid);
224 if (options.dynload) {
225 scope.treeview.setDynamicLoad(Y.bind(options.treeview_dynload, options.callbackcontext), 1);
226 }
227 scope.treeview.singleNodeHighlight = true;
228 if (options.filepath && options.filepath.length) {
229 // we just jumped from icon/details view, we need to show all parents
230 // we extract as much information as possible from filepath and filelist
231 // and send additional requests to retrieve siblings for parent folders
232 var mytree = {};
233 var mytreeel = null;
234 for (var i in options.filepath) {
235 if (mytreeel == null) {
236 mytreeel = mytree;
237 } else {
238 mytreeel.children = [{}];
239 mytreeel = mytreeel.children[0];
240 }
241 var pathelement = options.filepath[i];
242 mytreeel.path = pathelement.path;
243 mytreeel.title = pathelement.name;
9213f547 244 mytreeel.icon = pathelement.icon;
e709ddd2
MG
245 mytreeel.dynamicLoadComplete = true; // we will call it manually
246 mytreeel.expanded = true;
247 }
248 mytreeel.children = fileslist;
249 build_tree(mytree, scope.treeview.getRoot());
250 // manually call dynload for parent elements in the tree so we can load other siblings
251 if (options.dynload) {
252 var root = scope.treeview.getRoot();
253 while (root && root.children && root.children.length) {
254 root = root.children[0];
255 if (root.path == mytreeel.path) {
256 root.origpath = options.filepath;
257 root.origlist = fileslist;
258 } else if (!root.isLeaf && root.expanded) {
259 Y.bind(options.treeview_dynload, options.callbackcontext)(root, null);
260 }
261 }
262 }
263 } else {
264 // there is no path information, just display all elements as a list, without hierarchy
265 for(k in fileslist) {
266 build_tree(fileslist[k], scope.treeview.getRoot());
267 }
268 }
269 scope.treeview.subscribe('clickEvent', function(e){
270 e.node.highlight(false);
23b83009
MG
271 var callback = options.callback;
272 if (options.rightclickcallback && e.event.target &&
273 Y.Node(e.event.target).ancestor('.fp-treeview .fp-contextmenu', true)) {
274 callback = options.rightclickcallback;
275 }
276 Y.bind(callback, options.callbackcontext)(e, e.node.fileinfo);
277 YAHOO.util.Event.stopEvent(e.event)
e709ddd2 278 });
23b83009
MG
279 // TODO MDL-32736 support right click
280 /*if (options.rightclickcallback) {
281 scope.treeview.subscribe('dblClickEvent', function(e){
e709ddd2 282 e.node.highlight(false);
23b83009 283 Y.bind(options.rightclickcallback, options.callbackcontext)(e, e.node.fileinfo);
e709ddd2 284 });
23b83009 285 }*/
e709ddd2
MG
286 scope.treeview.draw();
287 };
288 /** formatting function for table view */
289 var formatValue = function (o){
290 if (o.data[''+o.column.key+'_f_s']) {return o.data[''+o.column.key+'_f_s'];}
291 else if (o.data[''+o.column.key+'_f']) {return o.data[''+o.column.key+'_f'];}
292 else if (o.value) {return o.value;}
293 else {return '';}
294 };
295 /** formatting function for table view */
296 var formatTitle = function(o) {
297 var el = Y.Node.create('<div/>');
298 el.appendChild(options.filenode.cloneNode(true)); // TODO not node but string!
6c2367cc 299 el.get('children').addClass(o.data['classname']);
e709ddd2
MG
300 el.one('.fp-filename').setContent(o.value);
301 if (o.data['icon']) {
9213f547
MG
302 el.one('.fp-icon').appendChild(Y.Node.create('<img/>'));
303 el.one('.fp-icon img').setImgSrc(o.data['icon'], o.data['realicon'], lazyloading);
e709ddd2 304 }
23b83009
MG
305 if (options.rightclickcallback) {
306 el.get('children').addClass('fp-hascontextmenu');
307 }
e709ddd2
MG
308 // TODO add tooltip with o.data['title'] (o.value) or o.data['thumbnail_title']
309 return el.getContent();
310 }
311 /** sorting function for table view */
312 var sortFoldersFirst = function(a, b, desc) {
6a0d7194
DP
313 if (a.get('isfolder') && !b.get('isfolder')) {
314 return -1;
315 }
316 if (!a.get('isfolder') && b.get('isfolder')) {
317 return 1;
318 }
319 var aa = a.get(this.key), bb = b.get(this.key), dir = desc ? -1 : 1;
e709ddd2
MG
320 return (aa > bb) ? dir : ((aa < bb) ? -dir : 0);
321 }
322 /** initialize table view */
323 var initialize_table_view = function() {
e709ddd2
MG
324 var cols = [
325 {key: "displayname", label: M.str.moodle.name, allowHTML: true, formatter: formatTitle,
326 sortable: true, sortFn: sortFoldersFirst},
327 {key: "datemodified", label: M.str.moodle.lastmodified, allowHTML: true, formatter: formatValue,
328 sortable: true, sortFn: sortFoldersFirst},
329 {key: "size", label: M.str.repository.size, allowHTML: true, formatter: formatValue,
330 sortable: true, sortFn: sortFoldersFirst},
331 {key: "mimetype", label: M.str.repository.type, allowHTML: true,
332 sortable: true, sortFn: sortFoldersFirst}
333 ];
04fa1da3
PN
334 for (var k in fileslist) {
335 // to speed up sorting and formatting
336 fileslist[k].displayname = file_get_displayname(fileslist[k]);
337 fileslist[k].isfolder = file_is_folder(fileslist[k]);
338 fileslist[k].classname = options.classnamecallback(fileslist[k]);
339 }
340 scope.tableview = new Y.DataTable({columns: cols, data: fileslist});
e709ddd2
MG
341 scope.tableview.delegate('click', function (e, tableview) {
342 var record = tableview.getRecord(e.currentTarget.get('id'));
23b83009
MG
343 if (record) {
344 var callback = options.callback;
345 if (options.rightclickcallback && e.target.ancestor('.fp-tableview .fp-contextmenu', true)) {
346 callback = options.rightclickcallback;
347 }
348 Y.bind(callback, this)(e, record.getAttrs());
349 }
e709ddd2
MG
350 }, 'tr', options.callbackcontext, scope.tableview);
351 if (options.rightclickcallback) {
352 scope.tableview.delegate('contextmenu', function (e, tableview) {
353 var record = tableview.getRecord(e.currentTarget.get('id'));
354 if (record) { Y.bind(options.rightclickcallback, this)(e, record.getAttrs()); }
355 }, 'tr', options.callbackcontext, scope.tableview);
356 }
357 }
358 /** append items in table view mode */
359 var append_files_table = function() {
04fa1da3
PN
360 var parentnode = scope.one('.'+classname);
361 scope.tableview.render(parentnode);
e709ddd2
MG
362 scope.tableview.sortable = options.sortable ? true : false;
363 };
364 /** append items in tree view mode */
365 var append_files_tree = function() {
366 if (options.appendonly) {
367 var parentnode = scope.treeview.getRoot();
368 if (scope.treeview.getHighlightedNode()) {
369 parentnode = scope.treeview.getHighlightedNode();
370 if (parentnode.isLeaf) {parentnode = parentnode.parent;}
371 }
372 for (var k in fileslist) {
373 build_tree(fileslist[k], parentnode);
374 }
375 scope.treeview.draw();
376 } else {
377 // otherwise files were already added in initialize_tree_view()
378 }
379 }
380 /** append items in icon view mode */
381 var append_files_icons = function() {
382 parent = scope.one('.'+classname);
383 for (var k in fileslist) {
384 var node = fileslist[k];
385 var element = options.filenode.cloneNode(true);
386 parent.appendChild(element);
6c2367cc 387 element.addClass(options.classnamecallback(node));
e709ddd2
MG
388 var filenamediv = element.one('.fp-filename');
389 filenamediv.setContent(file_get_displayname(node));
390 var imgdiv = element.one('.fp-thumbnail'), width, height, src;
391 if (node.thumbnail) {
392 width = node.thumbnail_width ? node.thumbnail_width : 90;
393 height = node.thumbnail_height ? node.thumbnail_height : 90;
394 src = node.thumbnail;
395 } else {
396 width = 16;
397 height = 16;
398 src = node.icon;
399 }
400 filenamediv.setStyleAdv('width', width);
401 imgdiv.setStyleAdv('width', width).setStyleAdv('height', height);
402 var img = Y.Node.create('<img/>').setAttrs({
e709ddd2
MG
403 title: file_get_description(node),
404 alt: node.thumbnail_alt ? node.thumbnail_alt : file_get_filename(node)}).
405 setStyle('maxWidth', ''+width+'px').
406 setStyle('maxHeight', ''+height+'px');
9213f547 407 img.setImgSrc(src, node.realthumbnail, lazyloading);
e709ddd2 408 imgdiv.appendChild(img);
23b83009
MG
409 element.on('click', function(e, nd) {
410 if (options.rightclickcallback && e.target.ancestor('.fp-iconview .fp-contextmenu', true)) {
411 Y.bind(options.rightclickcallback, this)(e, nd);
412 } else {
413 Y.bind(options.callback, this)(e, nd);
414 }
415 }, options.callbackcontext, node);
e709ddd2
MG
416 if (options.rightclickcallback) {
417 element.on('contextmenu', options.rightclickcallback, options.callbackcontext, node);
418 }
419 }
420 }
421
422 // initialize files view
423 if (!options.appendonly) {
424 var parent = Y.Node.create('<div/>').addClass(classname);
425 this.setContent('').appendChild(parent);
426 parent.generateID();
427 if (options.viewmode == 2) {
428 initialize_tree_view();
429 } else if (options.viewmode == 3) {
430 initialize_table_view();
431 } else {
432 // nothing to initialize for icon view
433 }
434 }
435
436 // append files to the list
437 if (options.viewmode == 2) {
438 append_files_tree();
439 } else if (options.viewmode == 3) {
440 append_files_table();
441 } else {
442 append_files_icons();
443 }
444
445 }
5e117466
MG
446
447 /**
448 * creates a node and adds it to the div with id #filesskin. This is needed for CSS to be able
449 * to overwrite YUI skin styles (instead of using !important that does not work in IE)
450 */
451 Y.Node.createWithFilesSkin = function(node) {
452 if (!Y.one('#filesskin')) {
453 Y.one(document.body).appendChild(Y.Node.create('<div/>').set('id', 'filesskin'));
454 }
455 return Y.one('#filesskin').appendChild(Y.Node.create(node));
456 }
e709ddd2 457}, '@VERSION@', {
4325db53 458 requires:['base', 'node', 'yui2-treeview', 'panel', 'cookie', 'datatable', 'datatable-sort']
e709ddd2
MG
459});
460
4c508047 461M.core_filepicker = M.core_filepicker || {};
99eaca9d 462
4c508047
PS
463/**
464 * instances of file pickers used on page
465 */
466M.core_filepicker.instances = M.core_filepicker.instances || {};
539d4041 467M.core_filepicker.active_filepicker = null;
4c508047 468
b5e7b638
MG
469/**
470 * HTML Templates to use in FilePicker
471 */
472M.core_filepicker.templates = M.core_filepicker.templates || {};
473
9213f547
MG
474/**
475 * Array of image sources for real previews (realicon or realthumbnail) that are already loaded
476 */
477M.core_filepicker.loadedpreviews = M.core_filepicker.loadedpreviews || {};
478
5cf44c1f
MG
479/**
480* Set selected file info
481*
482* @parma object file info
483*/
484M.core_filepicker.select_file = function(file) {
485 M.core_filepicker.active_filepicker.select_file(file);
486}
487
4c508047
PS
488/**
489 * Init and show file picker
490 */
491M.core_filepicker.show = function(Y, options) {
492 if (!M.core_filepicker.instances[options.client_id]) {
8cbef19e 493 M.core_filepicker.init(Y, options);
99eaca9d 494 }
4c508047
PS
495 M.core_filepicker.instances[options.client_id].show();
496};
497
d1d18691
MG
498M.core_filepicker.set_templates = function(Y, templates) {
499 for (var templid in templates) {
500 M.core_filepicker.templates[templid] = templates[templid];
501 }
502}
b92241f2 503
4c508047
PS
504/**
505 * Add new file picker to current instances
506 */
507M.core_filepicker.init = function(Y, options) {
508 var FilePickerHelper = function(options) {
509 FilePickerHelper.superclass.constructor.apply(this, arguments);
8cbef19e 510 };
4c508047
PS
511
512 FilePickerHelper.NAME = "FilePickerHelper";
513 FilePickerHelper.ATTRS = {
99eaca9d
DC
514 options: {},
515 lang: {}
516 };
4c508047
PS
517
518 Y.extend(FilePickerHelper, Y.Base, {
9598d578 519 api: M.cfg.wwwroot+'/repository/repository_ajax.php',
7f9358fc 520 cached_responses: {},
2e7ce603 521 waitinterval : null, // When the loading template is being displayed and its animation is running this will be an interval instance.
4c508047
PS
522 initializer: function(options) {
523 this.options = options;
392d5fd4
DC
524 if (!this.options.savepath) {
525 this.options.savepath = '/';
526 }
99eaca9d 527 },
4c508047 528
99eaca9d
DC
529 destructor: function() {
530 },
4c508047 531
99eaca9d 532 request: function(args, redraw) {
6a0d7194 533 var api = (args.api ? args.api : this.api) + '?action='+args.action;
99eaca9d 534 var params = {};
6a0d7194 535 var scope = args['scope'] ? args['scope'] : this;
99eaca9d
DC
536 params['repo_id']=args.repository_id;
537 params['p'] = args.path?args.path:'';
538 params['page'] = args.page?args.page:'';
539 params['env']=this.options.env;
540 // the form element only accept certain file types
541 params['accepted_types']=this.options.accepted_types;
e35194be 542 params['sesskey'] = M.cfg.sesskey;
99eaca9d 543 params['client_id'] = args.client_id;
0c4edaa2 544 params['itemid'] = this.options.itemid?this.options.itemid:0;
8a3e6a56 545 params['maxbytes'] = this.options.maxbytes?this.options.maxbytes:-1;
be85f7ab
DC
546 if (this.options.context && this.options.context.id) {
547 params['ctx_id'] = this.options.context.id;
548 }
99eaca9d
DC
549 if (args['params']) {
550 for (i in args['params']) {
551 params[i] = args['params'][i];
552 }
553 }
64654e78
DC
554 if (args.action == 'upload') {
555 var list = [];
556 for(var k in params) {
557 var value = params[k];
558 if(value instanceof Array) {
559 for(var i in value) {
560 list.push(k+'[]='+value[i]);
561 }
562 } else {
563 list.push(k+'='+value);
564 }
565 }
566 params = list.join('&');
567 } else {
568 params = build_querystring(params);
569 }
99eaca9d
DC
570 var cfg = {
571 method: 'POST',
572 on: {
573 complete: function(id,o,p) {
574 if (!o) {
b5e7b638 575 // TODO
99eaca9d
DC
576 alert('IO FATAL');
577 return;
578 }
4c508047
PS
579 var data = null;
580 try {
581 data = Y.JSON.parse(o.responseText);
582 } catch(e) {
879b4f9a 583 scope.print_msg(M.str.repository.invalidjson, 'error');
b5e7b638 584 scope.display_error(M.str.repository.invalidjson+'<pre>'+stripHTML(o.responseText)+'</pre>', 'invalidjson')
c26855ff 585 return;
4c508047 586 }
1dce6261 587 // error checking
e35194be
DC
588 if (data && data.error) {
589 scope.print_msg(data.error, 'error');
a5159b86
MG
590 if (args.onerror) {
591 args.onerror(id,data,p);
592 } else {
3a1e425b 593 this.fpnode.one('.fp-content').setContent('');
a5159b86 594 }
1dce6261
DC
595 return;
596 } else {
879b4f9a
DC
597 if (data.msg) {
598 scope.print_msg(data.msg, 'info');
599 }
7f9358fc
MG
600 // cache result if applicable
601 if (args.action != 'upload' && data.allowcaching) {
602 scope.cached_responses[params] = data;
603 }
604 // invoke callback
1dce6261
DC
605 args.callback(id,data,p);
606 }
99eaca9d
DC
607 }
608 },
609 arguments: {
610 scope: scope
611 },
612 headers: {
bd2db41a 613 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
99eaca9d 614 },
64654e78 615 data: params,
4c508047 616 context: this
99eaca9d
DC
617 };
618 if (args.form) {
619 cfg.form = args.form;
620 }
7f9358fc
MG
621 // check if result of the same request has been already cached. If not, request it
622 // (never applicable in case of form submission and/or upload action):
623 if (!args.form && args.action != 'upload' && scope.cached_responses[params]) {
624 args.callback(null, scope.cached_responses[params], {scope: scope})
625 } else {
626 Y.io(api, cfg);
627 if (redraw) {
b5e7b638 628 this.wait();
7f9358fc 629 }
99eaca9d
DC
630 }
631 },
b5e7b638 632 /** displays the dialog and processes rename/overwrite if there is a file with the same name in the same filearea*/
f392caba
DC
633 process_existing_file: function(data) {
634 var scope = this;
b5e7b638 635 var handleOverwrite = function(e) {
f392caba 636 // overwrite
b5e7b638
MG
637 e.preventDefault();
638 var data = this.process_dlg.dialogdata;
f392caba
DC
639 var params = {}
640 params['existingfilename'] = data.existingfile.filename;
641 params['existingfilepath'] = data.existingfile.filepath;
642 params['newfilename'] = data.newfile.filename;
643 params['newfilepath'] = data.newfile.filepath;
b5e7b638
MG
644 this.hide_header();
645 this.request({
f392caba 646 'params': params,
b5e7b638 647 'scope': this,
f392caba
DC
648 'action':'overwrite',
649 'path': '',
b5e7b638
MG
650 'client_id': this.options.client_id,
651 'repository_id': this.active_repo.id,
f392caba 652 'callback': function(id, o, args) {
f392caba
DC
653 scope.hide();
654 // editor needs to update url
655 // filemanager do nothing
c8ad2c12
SH
656 if (scope.options.editor_target && scope.options.env == 'editor') {
657 scope.options.editor_target.value = data.existingfile.url;
f392caba 658 scope.options.editor_target.onchange();
1ae299f5 659 } else if (scope.options.env === 'filepicker') {
b5e7b638 660 var fileinfo = {'client_id':scope.options.client_id,
913b3cb3
JP
661 'url':data.existingfile.url,
662 'file':data.existingfile.filename};
dd1f051e
MG
663 var formcallback_scope = scope.options.magicscope ? scope.options.magicscope : scope;
664 scope.options.formcallback.apply(formcallback_scope, [fileinfo]);
f392caba
DC
665 }
666 }
667 }, true);
668 }
b5e7b638
MG
669 var handleRename = function(e) {
670 // inserts file with the new name
671 e.preventDefault();
672 var scope = this;
673 var data = this.process_dlg.dialogdata;
c8ad2c12
SH
674 if (scope.options.editor_target && scope.options.env == 'editor') {
675 scope.options.editor_target.value = data.newfile.url;
f392caba
DC
676 scope.options.editor_target.onchange();
677 }
f392caba 678 scope.hide();
dd1f051e 679 var formcallback_scope = scope.options.magicscope ? scope.options.magicscope : scope;
b5e7b638 680 var fileinfo = {'client_id':scope.options.client_id,
794cc7e1
JP
681 'url':data.newfile.url,
682 'file':data.newfile.filename};
683 scope.options.formcallback.apply(formcallback_scope, [fileinfo]);
f392caba 684 }
b5e7b638 685 var handleCancel = function(e) {
f392caba 686 // Delete tmp file
b5e7b638 687 e.preventDefault();
f392caba 688 var params = {};
b5e7b638
MG
689 params['newfilename'] = this.process_dlg.dialogdata.newfile.filename;
690 params['newfilepath'] = this.process_dlg.dialogdata.newfile.filepath;
691 this.request({
f392caba 692 'params': params,
b5e7b638 693 'scope': this,
f392caba
DC
694 'action':'deletetmpfile',
695 'path': '',
b5e7b638
MG
696 'client_id': this.options.client_id,
697 'repository_id': this.active_repo.id,
f392caba 698 'callback': function(id, o, args) {
b5e7b638 699 // let it be in background, from user point of view nothing is happenning
f392caba 700 }
b5e7b638
MG
701 }, false);
702 this.process_dlg.hide();
703 this.selectui.hide();
f392caba 704 }
b5e7b638 705 if (!this.process_dlg) {
5e117466 706 this.process_dlg_node = Y.Node.createWithFilesSkin(M.core_filepicker.templates.processexistingfile);
dd1f051e
MG
707 var node = this.process_dlg_node;
708 node.generateID();
b5e7b638
MG
709 this.process_dlg = new Y.Panel({
710 srcNode : node,
711 headerContent: M.str.repository.fileexistsdialogheader,
712 zIndex : 800000,
713 centered : true,
714 modal : true,
715 visible : false,
716 render : true,
717 buttons : {}
718 });
dd1f051e 719 this.process_dlg.plug(Y.Plugin.Drag,{handles:['#'+node.get('id')+' .yui3-widget-hd']});
b5e7b638
MG
720 node.one('.fp-dlg-butoverwrite').on('click', handleOverwrite, this);
721 node.one('.fp-dlg-butrename').on('click', handleRename, this);
722 node.one('.fp-dlg-butcancel').on('click', handleCancel, this);
723 if (this.options.env == 'editor') {
724 node.one('.fp-dlg-text').setContent(M.str.repository.fileexistsdialog_editor);
725 } else {
726 node.one('.fp-dlg-text').setContent(M.str.repository.fileexistsdialog_filemanager);
727 }
f392caba 728 }
55089a9d 729 this.selectnode.removeClass('loading');
b5e7b638 730 this.process_dlg.dialogdata = data;
dd1f051e 731 this.process_dlg_node.one('.fp-dlg-butrename').setContent(M.util.get_string('renameto', 'repository', data.newfile.filename));
b5e7b638
MG
732 this.process_dlg.show();
733 },
734 /** displays error instead of filepicker contents */
735 display_error: function(errortext, errorcode) {
736 this.fpnode.one('.fp-content').setContent(M.core_filepicker.templates.error);
737 this.fpnode.one('.fp-content .fp-error').
738 addClass(errorcode).
739 setContent(errortext);
f392caba 740 },
b5e7b638 741 /** displays message in a popup */
879b4f9a 742 print_msg: function(msg, type) {
b5e7b638
MG
743 var header = M.str.moodle.error;
744 if (type != 'error') {
745 type = 'info'; // one of only two types excepted
746 header = M.str.moodle.info;
879b4f9a
DC
747 }
748 if (!this.msg_dlg) {
5e117466 749 this.msg_dlg_node = Y.Node.createWithFilesSkin(M.core_filepicker.templates.message);
dd1f051e 750 this.msg_dlg_node.generateID();
b5e7b638
MG
751
752 this.msg_dlg = new Y.Panel({
dd1f051e 753 srcNode : this.msg_dlg_node,
b5e7b638
MG
754 zIndex : 800000,
755 centered : true,
756 modal : true,
757 visible : false,
758 render : true
759 });
dd1f051e
MG
760 this.msg_dlg.plug(Y.Plugin.Drag,{handles:['#'+this.msg_dlg_node.get('id')+' .yui3-widget-hd']});
761 this.msg_dlg_node.one('.fp-msg-butok').on('click', function(e) {
b5e7b638
MG
762 e.preventDefault();
763 this.msg_dlg.hide();
764 }, this);
879b4f9a 765 }
b5e7b638
MG
766
767 this.msg_dlg.set('headerContent', header);
dd1f051e
MG
768 this.msg_dlg_node.removeClass('fp-msg-info').removeClass('fp-msg-error').addClass('fp-msg-'+type)
769 this.msg_dlg_node.one('.fp-msg-text').setContent(msg);
879b4f9a 770 this.msg_dlg.show();
879b4f9a 771 },
7ccf18a6 772 view_files: function(appenditems) {
b92241f2
MG
773 this.viewbar_set_enabled(true);
774 this.print_path();
e709ddd2
MG
775 /*if ((appenditems == null) && (!this.filelist || !this.filelist.length) && !this.active_repo.hasmorepages) {
776 // TODO do it via classes and adjust for each view mode!
777 // If there are no items and no next page, just display status message and quit
778 this.display_error(M.str.repository.nofilesavailable, 'nofilesavailable');
779 return;
780 }*/
b92241f2 781 if (this.viewmode == 2) {
7ccf18a6 782 this.view_as_list(appenditems);
b92241f2 783 } else if (this.viewmode == 3) {
7ccf18a6 784 this.view_as_table(appenditems);
99eaca9d 785 } else {
7ccf18a6
MG
786 this.view_as_icons(appenditems);
787 }
788 // display/hide the link for requesting next page
789 if (!appenditems && this.active_repo.hasmorepages) {
790 if (!this.fpnode.one('.fp-content .fp-nextpage')) {
791 this.fpnode.one('.fp-content').append(M.core_filepicker.templates.nextpage);
792 }
793 this.fpnode.one('.fp-content .fp-nextpage').one('a,button').on('click', function(e) {
794 e.preventDefault();
795 this.fpnode.one('.fp-content .fp-nextpage').addClass('loading');
796 this.request_next_page();
797 }, this);
798 }
799 if (!this.active_repo.hasmorepages && this.fpnode.one('.fp-content .fp-nextpage')) {
800 this.fpnode.one('.fp-content .fp-nextpage').remove();
801 }
802 if (this.fpnode.one('.fp-content .fp-nextpage')) {
803 this.fpnode.one('.fp-content .fp-nextpage').removeClass('loading');
99eaca9d 804 }
ce3eeb98
MG
805 this.content_scrolled();
806 },
807 content_scrolled: function(e) {
808 setTimeout(Y.bind(function() {
6a0d7194
DP
809 if (this.processingimages) {
810 return;
811 }
ce3eeb98
MG
812 this.processingimages = true;
813 var scope = this,
814 fpcontent = this.fpnode.one('.fp-content'),
815 fpcontenty = fpcontent.getY(),
816 fpcontentheight = fpcontent.getStylePx('height'),
817 nextpage = fpcontent.one('.fp-nextpage'),
818 is_node_visible = function(node) {
819 var offset = node.getY()-fpcontenty;
820 if (offset <= fpcontentheight && (offset >=0 || offset+node.getStylePx('height')>=0)) {
821 return true;
822 }
823 return false;
824 };
825 // automatically load next page when 'more' link becomes visible
826 if (nextpage && !nextpage.hasClass('loading') && is_node_visible(nextpage)) {
827 nextpage.one('a,button').simulate('click');
828 }
829 // replace src for visible images that need to be lazy-loaded
830 if (scope.lazyloading) {
831 fpcontent.all('img').each( function(node) {
832 if (node.get('id') && scope.lazyloading[node.get('id')] && is_node_visible(node)) {
9213f547 833 node.setImgRealSrc(scope.lazyloading);
ce3eeb98
MG
834 }
835 });
836 }
837 this.processingimages = false;
838 }, this), 200)
99eaca9d 839 },
1fb0173e 840 treeview_dynload: function(node, cb) {
2f6749f4
MG
841 var retrieved_children = {};
842 if (node.children) {
843 for (var i in node.children) {
844 retrieved_children[node.children[i].path] = node.children[i];
845 }
846 }
e709ddd2 847 this.request({
1fb0173e 848 action:'list',
e709ddd2
MG
849 client_id: this.options.client_id,
850 repository_id: this.active_repo.id,
1fb0173e
DC
851 path:node.path?node.path:'',
852 page:node.page?args.page:'',
e709ddd2 853 scope:this,
1fb0173e 854 callback: function(id, obj, args) {
1fb0173e 855 var list = obj.list;
e709ddd2 856 var scope = args.scope;
2f6749f4
MG
857 // check that user did not leave the view mode before recieving this response
858 if (!(scope.active_repo.id == obj.repo_id && scope.viewmode == 2 && node && node.getChildrenEl())) {
859 return;
860 }
861 if (cb != null) { // (in manual mode do not update current path)
862 scope.viewbar_set_enabled(true);
863 scope.parse_repository_options(obj);
864 }
e709ddd2 865 node.highlight(false);
6a0d7194
DP
866 node.origlist = obj.list ? obj.list : null;
867 node.origpath = obj.path ? obj.path : null;
2f6749f4 868 node.children = [];
1fb0173e 869 for(k in list) {
2f6749f4
MG
870 if (list[k].children && retrieved_children[list[k].path]) {
871 // if this child is a folder and has already been retrieved
872 node.children[node.children.length] = retrieved_children[list[k].path];
873 } else {
e709ddd2
MG
874 // append new file to the list
875 scope.view_as_list([list[k]]);
2f6749f4
MG
876 }
877 }
878 if (cb == null) {
879 node.refresh();
880 } else {
e709ddd2 881 // invoke callback requested by TreeView component
2f6749f4 882 cb();
1fb0173e 883 }
ce3eeb98 884 scope.content_scrolled();
1fb0173e
DC
885 }
886 }, false);
887 },
1778f310
MG
888 classnamecallback : function(node) {
889 var classname = '';
890 if (node.children) {
891 classname = classname + ' fp-folder';
892 }
893 if (node.isref) {
894 classname = classname + ' fp-isreference';
895 }
896 if (node.refcount) {
897 classname = classname + ' fp-hasreferences';
898 }
899 if (node.originalmissing) {
900 classname = classname + ' fp-originalmissing';
901 }
902 return Y.Lang.trim(classname);
903 },
7ccf18a6
MG
904 /** displays list of files in tree (list) view mode. If param appenditems is specified,
905 * appends those items to the end of the list. Otherwise (default behaviour)
906 * clears the contents and displays the items from this.filelist */
907 view_as_list: function(appenditems) {
e709ddd2
MG
908 var list = (appenditems != null) ? appenditems : this.filelist;
909 this.viewmode = 2;
910 if (!this.filelist || this.filelist.length==0 && (!this.filepath || !this.filepath.length)) {
b5e7b638 911 this.display_error(M.str.repository.nofilesavailable, 'nofilesavailable');
4adecd7b
MG
912 return;
913 }
879b4f9a 914
e709ddd2
MG
915 var element_template = Y.Node.create(M.core_filepicker.templates.listfilename);
916 var options = {
917 viewmode : this.viewmode,
918 appendonly : (appenditems != null),
919 filenode : element_template,
920 callbackcontext : this,
921 callback : function(e, node) {
23b83009 922 // TODO MDL-32736 e is not an event here but an object with properties 'event' and 'node'
e709ddd2
MG
923 if (!node.children) {
924 if (e.node.parent && e.node.parent.origpath) {
925 // set the current path
926 this.filepath = e.node.parent.origpath;
927 this.filelist = e.node.parent.origlist;
928 this.print_path();
2f6749f4 929 }
e709ddd2
MG
930 this.select_file(node);
931 } else {
932 // save current path and filelist (in case we want to jump to other viewmode)
933 this.filepath = e.node.origpath;
934 this.filelist = e.node.origlist;
82525f59 935 this.currentpath = e.node.path;
e709ddd2
MG
936 this.print_path();
937 this.content_scrolled();
2f6749f4 938 }
e709ddd2 939 },
1778f310 940 classnamecallback : this.classnamecallback,
e709ddd2
MG
941 dynload : this.active_repo.dynload,
942 filepath : this.filepath,
943 treeview_dynload : this.treeview_dynload
944 };
945 this.fpnode.one('.fp-content').fp_display_filelist(options, list, this.lazyloading);
99eaca9d 946 },
7ccf18a6
MG
947 /** displays list of files in icon view mode. If param appenditems is specified,
948 * appends those items to the end of the list. Otherwise (default behaviour)
949 * clears the contents and displays the items from this.filelist */
950 view_as_icons: function(appenditems) {
99eaca9d 951 this.viewmode = 1;
e709ddd2
MG
952 var list = (appenditems != null) ? appenditems : this.filelist;
953 var element_template = Y.Node.create(M.core_filepicker.templates.iconfilename);
954 if ((appenditems == null) && (!this.filelist || !this.filelist.length)) {
955 this.display_error(M.str.repository.nofilesavailable, 'nofilesavailable');
956 return;
879b4f9a 957 }
e709ddd2
MG
958 var options = {
959 viewmode : this.viewmode,
960 appendonly : (appenditems != null),
961 filenode : element_template,
962 callbackcontext : this,
963 callback : function(e, node) {
6a0d7194
DP
964 if (e.preventDefault) {
965 e.preventDefault();
966 }
e709ddd2
MG
967 if(node.children) {
968 if (this.active_repo.dynload) {
969 this.list({'path':node.path});
970 } else {
e709ddd2 971 this.filelist = node.children;
99eaca9d
DC
972 this.view_files();
973 }
e709ddd2
MG
974 } else {
975 this.select_file(node);
976 }
6c2367cc 977 },
1778f310 978 classnamecallback : this.classnamecallback
e709ddd2
MG
979 };
980 this.fpnode.one('.fp-content').fp_display_filelist(options, list, this.lazyloading);
99eaca9d 981 },
7ccf18a6
MG
982 /** displays list of files in table view mode. If param appenditems is specified,
983 * appends those items to the end of the list. Otherwise (default behaviour)
984 * clears the contents and displays the items from this.filelist */
985 view_as_table: function(appenditems) {
5bdf63cc 986 this.viewmode = 3;
e709ddd2
MG
987 var list = (appenditems != null) ? appenditems : this.filelist;
988 if (!appenditems && (!this.filelist || this.filelist.length==0) && !this.active_repo.hasmorepages) {
5bdf63cc
MG
989 this.display_error(M.str.repository.nofilesavailable, 'nofilesavailable');
990 return;
991 }
e709ddd2
MG
992 var element_template = Y.Node.create(M.core_filepicker.templates.listfilename);
993 var options = {
994 viewmode : this.viewmode,
995 appendonly : (appenditems != null),
996 filenode : element_template,
997 callbackcontext : this,
998 sortable : !this.active_repo.hasmorepages,
999 callback : function(e, node) {
23b83009 1000 if (e.preventDefault) {e.preventDefault();}
e709ddd2 1001 if (node.children) {
7ccf18a6 1002 if (this.active_repo.dynload) {
e709ddd2 1003 this.list({'path':node.path});
7ccf18a6 1004 } else {
e709ddd2 1005 this.filelist = node.children;
7ccf18a6 1006 this.view_files();
5bdf63cc 1007 }
7ccf18a6 1008 } else {
e709ddd2 1009 this.select_file(node);
5bdf63cc 1010 }
6c2367cc 1011 },
1778f310 1012 classnamecallback : this.classnamecallback
e709ddd2
MG
1013 };
1014 this.fpnode.one('.fp-content').fp_display_filelist(options, list, this.lazyloading);
7ccf18a6
MG
1015 },
1016 /** If more than one page available, requests and displays the files from the next page */
1017 request_next_page: function() {
1018 if (!this.active_repo.hasmorepages || this.active_repo.nextpagerequested) {
1019 // nothing to load
1020 return;
1021 }
1022 this.active_repo.nextpagerequested = true;
1023 var nextpage = this.active_repo.page+1;
82525f59
FM
1024 var args = {
1025 page: nextpage,
1026 repo_id: this.active_repo.id,
1027 };
7ccf18a6
MG
1028 var action = this.active_repo.issearchresult ? 'search' : 'list';
1029 this.request({
82525f59 1030 path: this.currentpath,
7ccf18a6
MG
1031 scope: this,
1032 action: action,
1033 client_id: this.options.client_id,
1034 repository_id: args.repo_id,
1035 params: args,
1036 callback: function(id, obj, args) {
1037 var scope = args.scope;
82525f59
FM
1038 // Check that we are still in the same repository and are expecting this page. We have no way
1039 // to compare the requested page and the one returned, so we assume that if the last chunk
1040 // of the breadcrumb is similar, then we probably are on the same page.
1041 var samepage = true;
1042 if (obj.path && scope.filepath) {
1043 var pathbefore = scope.filepath[scope.filepath.length-1];
1044 var pathafter = obj.path[obj.path.length-1];
1045 if (pathbefore.path != pathafter.path) {
1046 samepage = false;
1047 }
1048 }
7ccf18a6
MG
1049 if (scope.active_repo.hasmorepages && obj.list && obj.page &&
1050 obj.repo_id == scope.active_repo.id &&
82525f59 1051 obj.page == scope.active_repo.page+1 && samepage) {
7ccf18a6
MG
1052 scope.parse_repository_options(obj, true);
1053 scope.view_files(obj.list)
1054 }
1055 }
1056 }, false);
5bdf63cc 1057 },
99eaca9d 1058 select_file: function(args) {
b5e7b638 1059 this.selectui.show();
99eaca9d 1060 var client_id = this.options.client_id;
55089a9d 1061 var selectnode = this.selectnode;
b92241f2 1062 var return_types = this.options.repositories[this.active_repo.id].return_types;
3a1e425b 1063 selectnode.removeClass('loading');
b92241f2 1064 selectnode.one('.fp-saveas input').set('value', args.title);
99eaca9d 1065
ce3eeb98
MG
1066 var imgnode = Y.Node.create('<img/>').
1067 set('src', args.realthumbnail ? args.realthumbnail : args.thumbnail).
1068 setStyle('maxHeight', ''+(args.thumbnail_height ? args.thumbnail_height : 90)+'px').
1069 setStyle('maxWidth', ''+(args.thumbnail_width ? args.thumbnail_width : 90)+'px');
b92241f2 1070 selectnode.one('.fp-thumbnail').setContent('').appendChild(imgnode);
b5e7b638 1071
5cf44c1f
MG
1072 // filelink is the array of file-link-types available for this repository in this env
1073 var filelinktypes = [2/*FILE_INTERNAL*/,1/*FILE_EXTERNAL*/,4/*FILE_REFERENCE*/];
1074 var filelink = {}, firstfilelink = null, filelinkcount = 0;
1075 for (var i in filelinktypes) {
1076 var allowed = (return_types & filelinktypes[i]) &&
1077 (this.options.return_types & filelinktypes[i]);
1078 if (filelinktypes[i] == 1/*FILE_EXTERNAL*/ && !this.options.externallink && this.options.env == 'editor') {
1079 // special configuration setting 'repositoryallowexternallinks' may prevent
1080 // using external links in editor environment
1081 allowed = false;
b5e7b638 1082 }
5cf44c1f
MG
1083 filelink[filelinktypes[i]] = allowed;
1084 firstfilelink = (firstfilelink==null && allowed) ? filelinktypes[i] : firstfilelink;
1085 filelinkcount += allowed ? 1 : 0;
99eaca9d 1086 }
5cf44c1f
MG
1087 // make radio buttons enabled if this file-link-type is available and only if there are more than one file-link-type option
1088 // check the first available file-link-type option
1089 for (var linktype in filelink) {
1090 var el = selectnode.one('.fp-linktype-'+linktype);
1091 el.addClassIf('uneditable', !(filelink[linktype] && filelinkcount>1));
6a0d7194 1092 el.one('input').set('disabled', (filelink[linktype] && filelinkcount>1) ? '' : 'disabled').
5cf44c1f 1093 set('checked', (firstfilelink == linktype) ? 'checked' : '').simulate('change')
1dce6261 1094 }
b92241f2 1095
5cf44c1f 1096 // TODO MDL-32532: attributes 'hasauthor' and 'haslicense' need to be obsolete,
6a0d7194 1097 selectnode.one('.fp-setauthor input').set('value', args.author ? args.author : this.options.author);
5cf44c1f 1098 this.set_selected_license(selectnode.one('.fp-setlicense'), args.license);
b5e7b638 1099 selectnode.one('form #filesource-'+client_id).set('value', args.source);
b92241f2
MG
1100
1101 // display static information about a file (when known)
1102 var attrs = ['datemodified','datecreated','size','license','author','dimensions'];
1103 for (var i in attrs) {
1104 if (selectnode.one('.fp-'+attrs[i])) {
1105 var value = (args[attrs[i]+'_f']) ? args[attrs[i]+'_f'] : (args[attrs[i]] ? args[attrs[i]] : '');
1106 selectnode.one('.fp-'+attrs[i]).addClassIf('fp-unknown', ''+value == '')
1107 .one('.fp-value').setContent(value);
1108 }
1109 }
b5e7b638
MG
1110 },
1111 setup_select_file: function() {
1112 var client_id = this.options.client_id;
55089a9d 1113 var selectnode = this.selectnode;
b92241f2
MG
1114 var getfile = selectnode.one('.fp-select-confirm');
1115 // bind labels with corresponding inputs
5cf44c1f 1116 selectnode.all('.fp-saveas,.fp-linktype-2,.fp-linktype-1,.fp-linktype-4,.fp-setauthor,.fp-setlicense').each(function (node) {
b92241f2
MG
1117 node.all('label').set('for', node.one('input,select').generateID());
1118 });
5cf44c1f
MG
1119 selectnode.one('.fp-linktype-2 input').setAttrs({value: 2, name: 'linktype'});
1120 selectnode.one('.fp-linktype-1 input').setAttrs({value: 1, name: 'linktype'});
1121 selectnode.one('.fp-linktype-4 input').setAttrs({value: 4, name: 'linktype'});
1122 var changelinktype = function(e) {
1123 if (e.currentTarget.get('checked')) {
1124 var allowinputs = e.currentTarget.get('value') != 1/*FILE_EXTERNAL*/;
1125 selectnode.all('.fp-setauthor,.fp-setlicense,.fp-saveas').each(function(node){
1126 node.addClassIf('uneditable', !allowinputs);
1127 node.all('input,select').set('disabled', allowinputs?'':'disabled');
1128 });
1129 }
1130 };
1131 selectnode.all('.fp-linktype-2,.fp-linktype-1,.fp-linktype-4').each(function (node) {
1132 node.one('input').on('change', changelinktype, this);
1133 });
b92241f2
MG
1134 this.populate_licenses_select(selectnode.one('.fp-setlicense select'));
1135 // register event on clicking submit button
99eaca9d 1136 getfile.on('click', function(e) {
b5e7b638 1137 e.preventDefault();
99eaca9d
DC
1138 var client_id = this.options.client_id;
1139 var scope = this;
1140 var repository_id = this.active_repo.id;
b92241f2 1141 var title = selectnode.one('.fp-saveas input').get('value');
b5e7b638 1142 var filesource = selectnode.one('form #filesource-'+client_id).get('value');
14469892 1143 var params = {'title':title, 'source':filesource, 'savepath': this.options.savepath};
b92241f2 1144 var license = selectnode.one('.fp-setlicense select');
1dce6261
DC
1145 if (license) {
1146 params['license'] = license.get('value');
5cf44c1f 1147 var origlicense = selectnode.one('.fp-license .fp-value');
6a0d7194
DP
1148 if (origlicense) {
1149 origlicense = origlicense.getContent();
1150 }
837eef2e 1151 this.set_preference('recentlicense', license.get('value'));
1dce6261 1152 }
b92241f2 1153 params['author'] = selectnode.one('.fp-setauthor input').get('value');
99eaca9d 1154
5cf44c1f
MG
1155 var return_types = this.options.repositories[this.active_repo.id].return_types;
1156 if (this.options.env == 'editor') {
392d5fd4
DC
1157 // in editor, images are stored in '/' only
1158 params.savepath = '/';
766514a0 1159 }
5cf44c1f
MG
1160 if ((this.options.externallink || this.options.env != 'editor') &&
1161 (return_types & 1/*FILE_EXTERNAL*/) &&
1162 (this.options.return_types & 1/*FILE_EXTERNAL*/) &&
1163 selectnode.one('.fp-linktype-1 input').get('checked')) {
99eaca9d 1164 params['linkexternal'] = 'yes';
5cf44c1f
MG
1165 } else if ((return_types & 4/*FILE_REFERENCE*/) &&
1166 (this.options.return_types & 4/*FILE_REFERENCE*/) &&
1167 selectnode.one('.fp-linktype-4 input').get('checked')) {
f8e74b20 1168 params['usefilereference'] = '1';
99eaca9d
DC
1169 }
1170
3a1e425b 1171 selectnode.addClass('loading');
99eaca9d 1172 this.request({
840912d5
DC
1173 action:'download',
1174 client_id: client_id,
1175 repository_id: repository_id,
1176 'params': params,
a5159b86 1177 onerror: function(id, obj, args) {
3a1e425b 1178 selectnode.removeClass('loading');
b5e7b638 1179 scope.selectui.hide();
a5159b86 1180 },
840912d5 1181 callback: function(id, obj, args) {
3a1e425b 1182 selectnode.removeClass('loading');
16dfd717
MG
1183 if (obj.event == 'fileexists') {
1184 scope.process_existing_file(obj);
1185 return;
1186 }
e0b85db4 1187 if (scope.options.editor_target && scope.options.env=='editor') {
840912d5
DC
1188 scope.options.editor_target.value=obj.url;
1189 scope.options.editor_target.onchange();
1190 }
1191 scope.hide();
1192 obj.client_id = client_id;
dd1f051e 1193 var formcallback_scope = args.scope.options.magicscope ? args.scope.options.magicscope : args.scope;
840912d5
DC
1194 scope.options.formcallback.apply(formcallback_scope, [obj]);
1195 }
b5e7b638 1196 }, false);
99eaca9d 1197 }, this);
b5e7b638 1198 var elform = selectnode.one('form');
3a1e425b
MG
1199 elform.appendChild(Y.Node.create('<input/>').
1200 setAttrs({type:'hidden',id:'filesource-'+client_id}));
e0b85db4
DC
1201 elform.on('keydown', function(e) {
1202 if (e.keyCode == 13) {
1203 getfile.simulate('click');
8cbef19e 1204 e.preventDefault();
e0b85db4
DC
1205 }
1206 }, this);
b92241f2 1207 var cancel = selectnode.one('.fp-select-cancel');
99eaca9d 1208 cancel.on('click', function(e) {
b5e7b638
MG
1209 e.preventDefault();
1210 this.selectui.hide();
99eaca9d 1211 }, this);
99eaca9d 1212 },
b5e7b638 1213 wait: function() {
2e7ce603
SH
1214 // First check there isn't already an interval in play, and if there is kill it now.
1215 if (this.waitinterval != null) {
1216 clearInterval(this.waitinterval);
1217 }
1218 // Prepare the root node we will set content for and the loading template we want to display as a YUI node.
1219 var root = this.fpnode.one('.fp-content');
9d7d2b03 1220 var content = Y.Node.create(M.core_filepicker.templates.loading).addClass('fp-content-hidden').setStyle('opacity', 0);
2e7ce603
SH
1221 var count = 0;
1222 // Initiate an interval, we will have a count which will increment every 100 milliseconds.
1223 // Count 0 - the loading icon will have visibility set to hidden (invisible) and have an opacity of 0 (invisible also)
1224 // Count 5 - the visiblity will be switched to visible but opacity will still be at 0 (inivisible)
1225 // Counts 6 - 15 opacity will be increased by 0.1 making the loading icon visible over the period of a second
1226 // Count 16 - The interval will be cancelled.
1227 var interval = setInterval(function(){
1228 if (!content || !root.contains(content) || count >= 15) {
1229 clearInterval(interval);
1230 return true;
1231 }
1232 if (count == 5) {
9d7d2b03 1233 content.removeClass('fp-content-hidden');
2e7ce603
SH
1234 } else if (count > 5) {
1235 var opacity = parseFloat(content.getStyle('opacity'));
1236 content.setStyle('opacity', opacity + 0.1);
1237 }
1238 count++;
1239 return false;
1240 }, 100);
1241 // Store the wait interval so that we can check it in the future.
1242 this.waitinterval = interval;
1243 // Set the content to the loading template.
1244 root.setContent(content);
b5e7b638
MG
1245 },
1246 viewbar_set_enabled: function(mode) {
1247 var viewbar = this.fpnode.one('.fp-viewbar')
1248 if (viewbar) {
1249 if (mode) {
1250 viewbar.addClass('enabled').removeClass('disabled')
1251 } else {
1252 viewbar.removeClass('enabled').addClass('disabled')
1253 }
99eaca9d 1254 }
b5e7b638
MG
1255 this.fpnode.all('.fp-vb-icons,.fp-vb-tree,.fp-vb-details').removeClass('checked')
1256 var modes = {1:'icons', 2:'tree', 3:'details'};
1257 this.fpnode.all('.fp-vb-'+modes[this.viewmode]).addClass('checked');
1258 },
1259 viewbar_clicked: function(e) {
1260 e.preventDefault();
1261 var viewbar = this.fpnode.one('.fp-viewbar')
1262 if (!viewbar || !viewbar.hasClass('disabled')) {
1263 if (e.currentTarget.hasClass('fp-vb-tree')) {
1264 this.viewmode = 2;
1265 } else if (e.currentTarget.hasClass('fp-vb-details')) {
1266 this.viewmode = 3;
1267 } else {
1268 this.viewmode = 1;
1269 }
1270 this.viewbar_set_enabled(true)
1271 this.view_files();
837eef2e 1272 this.set_preference('recentviewmode', this.viewmode);
99eaca9d
DC
1273 }
1274 },
1275 render: function() {
1276 var client_id = this.options.client_id;
5e117466 1277 this.fpnode = Y.Node.createWithFilesSkin(M.core_filepicker.templates.generallayout).
b92241f2 1278 set('id', 'filepicker-'+client_id);
b5e7b638
MG
1279 this.mainui = new Y.Panel({
1280 srcNode : this.fpnode,
1281 headerContent: M.str.repository.filepicker,
1282 zIndex : 500000,
1283 centered : true,
1284 modal : true,
1285 visible : false,
e88d5641
BR
1286 minWidth : this.fpnode.getStylePx('minWidth'),
1287 minHeight : this.fpnode.getStylePx('minHeight'),
1288 maxWidth : this.fpnode.getStylePx('maxWidth'),
1289 maxHeight : this.fpnode.getStylePx('maxHeight'),
b92241f2 1290 render : true
99eaca9d 1291 });
b92241f2 1292 // allow to move the panel dragging it by it's header:
55089a9d 1293 this.mainui.plug(Y.Plugin.Drag,{handles:['#filepicker-'+client_id+' .yui3-widget-hd']});
b5e7b638 1294 this.mainui.show();
6a0d7194
DP
1295 if (this.mainui.get('y') < 0) {
1296 this.mainui.set('y', 0);
1297 }
b92241f2 1298 // create panel for selecting a file (initially hidden)
5e117466 1299 this.selectnode = Y.Node.createWithFilesSkin(M.core_filepicker.templates.selectlayout).
55089a9d 1300 set('id', 'filepicker-select-'+client_id);
b5e7b638 1301 this.selectui = new Y.Panel({
55089a9d 1302 srcNode : this.selectnode,
b5e7b638
MG
1303 zIndex : 600000,
1304 centered : true,
1305 modal : true,
1306 close : true,
1307 render : true
99eaca9d 1308 });
55089a9d
MG
1309 // allow to move the panel dragging it by it's header:
1310 this.selectui.plug(Y.Plugin.Drag,{handles:['#filepicker-select-'+client_id+' .yui3-widget-hd']});
b5e7b638 1311 this.selectui.hide();
ce3eeb98
MG
1312 // event handler for lazy loading of thumbnails and next page
1313 this.fpnode.one('.fp-content').on(['scroll','resize'], this.content_scrolled, this);
b5e7b638
MG
1314 // save template for one path element and location of path bar
1315 if (this.fpnode.one('.fp-path-folder')) {
1316 this.pathnode = this.fpnode.one('.fp-path-folder');
1317 this.pathbar = this.pathnode.get('parentNode');
1318 this.pathbar.removeChild(this.pathnode);
1319 }
1320 // assign callbacks for view mode switch buttons
1321 this.fpnode.all('.fp-vb-icons,.fp-vb-tree,.fp-vb-details').
1322 on('click', this.viewbar_clicked, this);
1323 // assign callbacks for toolbar links
1324 this.setup_toolbar();
1325 this.setup_select_file();
3a1e425b 1326 this.hide_header();
934291d6 1327
99eaca9d 1328 // processing repository listing
b5e7b638 1329 // Resort the repositories by sortorder
6a0d7194 1330 var sorted_repositories = [];
b5e7b638 1331 for (var i in this.options.repositories) {
6a0d7194 1332 sorted_repositories[i] = this.options.repositories[i];
b5e7b638 1333 }
6a0d7194 1334 sorted_repositories.sort(function(a,b){return a.sortorder-b.sortorder});
b5e7b638
MG
1335 // extract one repository template and repeat it for all repositories available,
1336 // set name and icon and assign callbacks
1337 var reponode = this.fpnode.one('.fp-repo');
1338 if (reponode) {
1339 var list = reponode.get('parentNode');
1340 list.removeChild(reponode);
1341 for (i in sorted_repositories) {
6a0d7194 1342 var repository = sorted_repositories[i];
b5e7b638
MG
1343 var node = reponode.cloneNode(true);
1344 list.appendChild(node);
1345 node.
1346 set('id', 'fp-repo-'+client_id+'-'+repository.id).
1347 on('click', function(e, repository_id) {
1348 e.preventDefault();
837eef2e 1349 this.set_preference('recentrepository', repository_id);
b5e7b638
MG
1350 this.hide_header();
1351 this.list({'repo_id':repository_id});
1352 }, this /*handler running scope*/, repository.id/*second argument of handler*/);
6a0d7194
DP
1353 node.one('.fp-repo-name').setContent(repository.name);
1354 node.one('.fp-repo-icon').set('src', repository.icon);
1355 if (i==0) {
1356 node.addClass('first');
1357 }
1358 if (i==sorted_repositories.length-1) {
1359 node.addClass('last');
1360 }
1361 if (i%2) {
1362 node.addClass('even');
1363 } else {
1364 node.addClass('odd');
1365 }
99eaca9d 1366 }
b5e7b638
MG
1367 }
1368 // display error if no repositories found
1369 if (sorted_repositories.length==0) {
3a1e425b 1370 this.display_error(M.str.repository.norepositoriesavailable, 'norepositoriesavailable')
b5e7b638
MG
1371 }
1372 // display repository that was used last time
1373 this.show_recent_repository();
99eaca9d 1374 },
7ccf18a6
MG
1375 parse_repository_options: function(data, appendtolist) {
1376 if (appendtolist) {
1377 if (data.list) {
6a0d7194
DP
1378 if (!this.filelist) {
1379 this.filelist = [];
1380 }
7ccf18a6
MG
1381 for (var i in data.list) {
1382 this.filelist[this.filelist.length] = data.list[i];
1383 }
1384 }
1385 } else {
1386 this.filelist = data.list?data.list:null;
ce3eeb98 1387 this.lazyloading = {};
7ccf18a6 1388 }
99eaca9d 1389 this.filepath = data.path?data.path:null;
5cf44c1f 1390 this.objecttag = data.object?data.object:null;
99eaca9d 1391 this.active_repo = {};
6a0d7194 1392 this.active_repo.issearchresult = data.issearchresult ? true : false;
98b15580 1393 this.active_repo.dynload = data.dynload?data.dynload:false;
99eaca9d
DC
1394 this.active_repo.pages = Number(data.pages?data.pages:null);
1395 this.active_repo.page = Number(data.page?data.page:null);
7ccf18a6 1396 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))
99eaca9d 1397 this.active_repo.id = data.repo_id?data.repo_id:null;
b5e7b638
MG
1398 this.active_repo.nosearch = (data.login || data.nosearch); // this is either login form or 'nosearch' attribute set
1399 this.active_repo.norefresh = (data.login || data.norefresh); // this is either login form or 'norefresh' attribute set
1400 this.active_repo.nologin = (data.login || data.nologin); // this is either login form or 'nologin' attribute is set
fdfb9cbe 1401 this.active_repo.logouttext = data.logouttext?data.logouttext:null;
cd029574
RW
1402 this.active_repo.logouturl = (data.logouturl || '');
1403 this.active_repo.message = (data.message || '');
99eaca9d
DC
1404 this.active_repo.help = data.help?data.help:null;
1405 this.active_repo.manage = data.manage?data.manage:null;
b5e7b638 1406 this.print_header();
99eaca9d
DC
1407 },
1408 print_login: function(data) {
97b151ea 1409 this.parse_repository_options(data);
99eaca9d
DC
1410 var client_id = this.options.client_id;
1411 var repository_id = data.repo_id;
1412 var l = this.logindata = data.login;
1413 var loginurl = '';
3a1e425b 1414 var action = data['login_btn_action'] ? data['login_btn_action'] : 'login';
99eaca9d 1415 var form_id = 'fp-form-'+client_id;
99eaca9d 1416
5ce13292
MG
1417 var loginform_node = Y.Node.create(M.core_filepicker.templates.loginform);
1418 loginform_node.one('form').set('id', form_id);
1419 this.fpnode.one('.fp-content').setContent('').appendChild(loginform_node);
1420 var templates = {
1421 'popup' : loginform_node.one('.fp-login-popup'),
1422 'textarea' : loginform_node.one('.fp-login-textarea'),
1423 'select' : loginform_node.one('.fp-login-select'),
1424 'text' : loginform_node.one('.fp-login-text'),
3a1e425b 1425 'radio' : loginform_node.one('.fp-login-radiogroup'),
5ce13292
MG
1426 'checkbox' : loginform_node.one('.fp-login-checkbox'),
1427 'input' : loginform_node.one('.fp-login-input')
1428 };
1429 var container;
1430 for (var i in templates) {
1431 if (templates[i]) {
1432 container = templates[i].get('parentNode');
6a0d7194 1433 container.removeChild(templates[i]);
5ce13292
MG
1434 }
1435 }
1436
1437 for(var k in l) {
1438 if (templates[l[k].type]) {
1439 var node = templates[l[k].type].cloneNode(true);
1440 } else {
1441 node = templates['input'].cloneNode(true);
1442 }
1443 if (l[k].type == 'popup') {
3a1e425b 1444 // submit button
2f6749f4 1445 loginurl = l[k].url;
3a1e425b
MG
1446 var popupbutton = node.one('button');
1447 popupbutton.on('click', function(e){
1448 M.core_filepicker.active_filepicker = this;
1449 window.open(loginurl, 'repo_auth', 'location=0,status=0,width=500,height=300,scrollbars=yes');
1450 e.preventDefault();
1451 }, this);
1452 loginform_node.one('form').on('keydown', function(e) {
1453 if (e.keyCode == 13) {
1454 popupbutton.simulate('click');
1455 e.preventDefault();
1456 }
1457 }, this);
5ce13292
MG
1458 loginform_node.all('.fp-login-submit').remove();
1459 action = 'popup';
6a0d7194 1460 } else if(l[k].type=='textarea') {
5ce13292 1461 // textarea element
6a0d7194
DP
1462 if (node.one('label')) {
1463 node.one('label').set('for', l[k].id).setContent(l[k].label);
1464 }
3a1e425b 1465 node.one('textarea').setAttrs({id:l[k].id, name:l[k].name});
6a0d7194 1466 } else if(l[k].type=='select') {
5ce13292 1467 // select element
6a0d7194
DP
1468 if (node.one('label')) {
1469 node.one('label').set('for', l[k].id).setContent(l[k].label);
1470 }
3a1e425b 1471 node.one('select').setAttrs({id:l[k].id, name:l[k].name}).setContent('');
5ce13292
MG
1472 for (i in l[k].options) {
1473 node.one('select').appendChild(
1474 Y.Node.create('<option/>').
1475 set('value', l[k].options[i].value).
6a0d7194 1476 setContent(l[k].options[i].label));
5ce13292 1477 }
6a0d7194 1478 } else if(l[k].type=='radio') {
5ce13292 1479 // radio input element
3a1e425b
MG
1480 node.all('label').setContent(l[k].label);
1481 var list = l[k].value.split('|');
1482 var labels = l[k].value_label.split('|');
1483 var radionode = null;
1484 for(var item in list) {
1485 if (radionode == null) {
1486 radionode = node.one('.fp-login-radio');
1487 radionode.one('input').set('checked', 'checked');
1488 } else {
1489 var x = radionode.cloneNode(true);
1490 radionode.insert(x, 'after');
1491 radionode = x;
1492 radionode.one('input').set('checked', '');
1493 }
1494 radionode.one('input').setAttrs({id:''+l[k].id+item, name:l[k].name,
1495 type:l[k].type, value:list[item]});
1496 radionode.all('label').setContent(labels[item]).set('for', ''+l[k].id+item)
1497 }
1498 if (radionode == null) {
1499 node.one('.fp-login-radio').remove();
1500 }
6a0d7194 1501 } else {
5ce13292
MG
1502 // input element
1503 if (node.one('label')) { node.one('label').set('for', l[k].id).setContent(l[k].label) }
1504 node.one('input').
1505 set('type', l[k].type).
1506 set('id', l[k].id).
1507 set('name', l[k].name).
1508 set('value', l[k].value?l[k].value:'')
1509 }
1510 container.appendChild(node);
1511 }
3a1e425b
MG
1512 // custom label text for submit button
1513 if (data['login_btn_label']) {
1514 loginform_node.all('.fp-login-submit').setContent(data['login_btn_label'])
99eaca9d 1515 }
3a1e425b
MG
1516 // register button action for login and search
1517 if (action == 'login' || action == 'search') {
1518 loginform_node.one('.fp-login-submit').on('click', function(e){
5ce13292 1519 e.preventDefault();
b5e7b638 1520 this.hide_header();
99eaca9d 1521 this.request({
3a1e425b
MG
1522 'scope': this,
1523 'action':(action == 'search') ? 'search' : 'signin',
99eaca9d
DC
1524 'path': '',
1525 'client_id': client_id,
1526 'repository_id': repository_id,
3a1e425b 1527 'form': {id:form_id, upload:false, useDisabled:true},
4adecd7b 1528 'callback': this.display_response
99eaca9d
DC
1529 }, true);
1530 }, this);
1531 }
3a1e425b
MG
1532 // if 'Enter' is pressed in the form, simulate the button click
1533 if (loginform_node.one('.fp-login-submit')) {
1534 loginform_node.one('form').on('keydown', function(e) {
1535 if (e.keyCode == 13) {
1536 loginform_node.one('.fp-login-submit').simulate('click')
1537 e.preventDefault();
99eaca9d 1538 }
99eaca9d
DC
1539 }, this);
1540 }
99eaca9d 1541 },
4adecd7b
MG
1542 display_response: function(id, obj, args) {
1543 var scope = args.scope
1544 // highlight the current repository in repositories list
b5e7b638
MG
1545 scope.fpnode.all('.fp-repo.active').removeClass('active');
1546 scope.fpnode.all('#fp-repo-'+scope.options.client_id+'-'+obj.repo_id).addClass('active')
5ce13292
MG
1547 // add class repository_REPTYPE to the filepicker (for repository-specific styles)
1548 for (var i in scope.options.repositories) {
1549 scope.fpnode.removeClass('repository_'+scope.options.repositories[i].type)
1550 }
1551 if (obj.repo_id && scope.options.repositories[obj.repo_id]) {
1552 scope.fpnode.addClass('repository_'+scope.options.repositories[obj.repo_id].type)
1553 }
4adecd7b
MG
1554 // display response
1555 if (obj.login) {
b5e7b638 1556 scope.viewbar_set_enabled(false);
4adecd7b
MG
1557 scope.print_login(obj);
1558 } else if (obj.upload) {
b5e7b638 1559 scope.viewbar_set_enabled(false);
4adecd7b
MG
1560 scope.parse_repository_options(obj);
1561 scope.create_upload_form(obj);
5cf44c1f
MG
1562 } else if (obj.object) {
1563 M.core_filepicker.active_filepicker = scope;
1564 scope.viewbar_set_enabled(false);
1565 scope.parse_repository_options(obj);
1566 scope.create_object_container(obj.object);
4adecd7b 1567 } else if (obj.list) {
b5e7b638 1568 scope.viewbar_set_enabled(true);
4adecd7b
MG
1569 scope.parse_repository_options(obj);
1570 scope.view_files();
99eaca9d 1571 }
99eaca9d
DC
1572 },
1573 list: function(args) {
99eaca9d
DC
1574 if (!args) {
1575 args = {};
1576 }
1577 if (!args.repo_id) {
4adecd7b 1578 args.repo_id = this.active_repo.id;
99eaca9d 1579 }
82525f59
FM
1580 if (!args.path) {
1581 args.path = '';
1582 }
1583 this.currentpath = args.path;
4adecd7b
MG
1584 this.request({
1585 action: 'list',
1586 client_id: this.options.client_id,
99eaca9d 1587 repository_id: args.repo_id,
4adecd7b
MG
1588 path: args.path,
1589 page: args.page,
1590 scope: this,
1591 callback: this.display_response
99eaca9d
DC
1592 }, true);
1593 },
b5e7b638
MG
1594 populate_licenses_select: function(node) {
1595 if (!node) {
1596 return;
e35194be 1597 }
b5e7b638 1598 node.setContent('');
1dce6261 1599 var licenses = this.options.licenses;
837eef2e 1600 var recentlicense = this.get_preference('recentlicense');
a756cb37
DC
1601 if (recentlicense) {
1602 this.options.defaultlicense=recentlicense;
1603 }
1dce6261 1604 for (var i in licenses) {
b5e7b638
MG
1605 var option = Y.Node.create('<option/>').
1606 set('selected', (this.options.defaultlicense==licenses[i].shortname)).
1607 set('value', licenses[i].shortname).
1608 setContent(licenses[i].fullname);
1609 node.appendChild(option)
1dce6261 1610 }
b5e7b638 1611 },
5cf44c1f
MG
1612 set_selected_license: function(node, value) {
1613 var licenseset = false;
1614 node.all('option').each(function(el) {
1615 if (el.get('value')==value || el.getContent()==value) {
1616 el.set('selected', true);
1617 licenseset = true;
1618 }
1619 });
1620 if (!licenseset) {
1621 // we did not find the value in the list
837eef2e 1622 var recentlicense = this.get_preference('recentlicense');
5cf44c1f
MG
1623 node.all('option[selected]').set('selected', false);
1624 node.all('option[value='+recentlicense+']').set('selected', true);
1625 }
1626 },
1627 create_object_container: function(data) {
1628 var content = this.fpnode.one('.fp-content');
1629 content.setContent('');
1630 //var str = '<object data="'+data.src+'" type="'+data.type+'" width="98%" height="98%" id="container_object" class="fp-object-container mdl-align"></object>';
1631 var container = Y.Node.create('<object/>').
1632 setAttrs({data:data.src, type:data.type, id:'container_object'}).
1633 addClass('fp-object-container');
1634 content.setContent('').appendChild(container);
1635 },
b5e7b638
MG
1636 create_upload_form: function(data) {
1637 var client_id = this.options.client_id;
1638 var id = data.upload.id+'_'+client_id;
b92241f2 1639 var content = this.fpnode.one('.fp-content');
55c91c87
PN
1640 var template_name = 'uploadform_'+this.options.repositories[data.repo_id].type;
1641 var template = M.core_filepicker.templates[template_name] || M.core_filepicker.templates['uploadform'];
1642 content.setContent(template);
b5e7b638 1643
b92241f2
MG
1644 content.all('.fp-file,.fp-saveas,.fp-setauthor,.fp-setlicense').each(function (node) {
1645 node.all('label').set('for', node.one('input,select').generateID());
1646 });
1647 content.one('form').set('id', id);
1648 content.one('.fp-file input').set('name', 'repo_upload_file');
68ea10b0
MG
1649 if (data.upload.label && content.one('.fp-file label')) {
1650 content.one('.fp-file label').setContent(data.upload.label);
1651 }
b92241f2
MG
1652 content.one('.fp-saveas input').set('name', 'title');
1653 content.one('.fp-setauthor input').setAttrs({name:'author', value:this.options.author});
1654 content.one('.fp-setlicense select').set('name', 'license');
1655 this.populate_licenses_select(content.one('.fp-setlicense select'))
1656 // append hidden inputs to the upload form
1657 content.one('form').appendChild(Y.Node.create('<input/>').
3a1e425b 1658 setAttrs({type:'hidden',name:'itemid',value:this.options.itemid}));
b5e7b638
MG
1659 var types = this.options.accepted_types;
1660 for (var i in types) {
b92241f2 1661 content.one('form').appendChild(Y.Node.create('<input/>').
3a1e425b 1662 setAttrs({type:'hidden',name:'accepted_types[]',value:types[i]}));
b5e7b638
MG
1663 }
1664
99eaca9d 1665 var scope = this;
b92241f2 1666 content.one('.fp-upload-btn').on('click', function(e) {
8cbef19e 1667 e.preventDefault();
b92241f2 1668 var license = content.one('.fp-setlicense select');
837eef2e
DP
1669
1670 this.set_preference('recentlicense', license.get('value'));
b92241f2 1671 if (!content.one('.fp-file input').get('value')) {
ce6297d2 1672 scope.print_msg(M.str.repository.nofilesattached, 'error');
2a03b97b
DC
1673 return false;
1674 }
b5e7b638 1675 this.hide_header();
9d753c38
PS
1676 scope.request({
1677 scope: scope,
1678 action:'upload',
1679 client_id: client_id,
1680 params: {'savepath':scope.options.savepath},
1681 repository_id: scope.active_repo.id,
1682 form: {id: id, upload:true},
a5159b86
MG
1683 onerror: function(id, o, args) {
1684 scope.create_upload_form(data);
1685 },
9d753c38 1686 callback: function(id, o, args) {
dd1f051e
MG
1687 if (o.event == 'fileexists') {
1688 scope.create_upload_form(data);
1689 scope.process_existing_file(o);
1690 return;
1691 }
9d753c38
PS
1692 if (scope.options.editor_target&&scope.options.env=='editor') {
1693 scope.options.editor_target.value=o.url;
1694 scope.options.editor_target.onchange();
0c4edaa2 1695 }
9d753c38
PS
1696 scope.hide();
1697 o.client_id = client_id;
dd1f051e 1698 var formcallback_scope = args.scope.options.magicscope ? args.scope.options.magicscope : args.scope;
9d753c38
PS
1699 scope.options.formcallback.apply(formcallback_scope, [o]);
1700 }
1701 }, true);
99eaca9d
DC
1702 }, this);
1703 },
b5e7b638
MG
1704 /** setting handlers and labels for elements in toolbar. Called once during the initial render of filepicker */
1705 setup_toolbar: function() {
99eaca9d 1706 var client_id = this.options.client_id;
b92241f2
MG
1707 var toolbar = this.fpnode.one('.fp-toolbar');
1708 toolbar.one('.fp-tb-logout').one('a,button').on('click', function(e) {
b5e7b638
MG
1709 e.preventDefault();
1710 if (!this.active_repo.nologin) {
1711 this.hide_header();
1712 this.request({
1713 action:'logout',
1714 client_id: this.options.client_id,
1715 repository_id: this.active_repo.id,
1716 path:'',
1717 callback: this.display_response
1718 }, true);
1719 }
cd029574
RW
1720 if (this.active_repo.logouturl) {
1721 window.open(this.active_repo.logouturl, 'repo_auth', 'location=0,status=0,width=500,height=300,scrollbars=yes');
1722 }
b5e7b638 1723 }, this);
b92241f2 1724 toolbar.one('.fp-tb-refresh').one('a,button').on('click', function(e) {
b5e7b638
MG
1725 e.preventDefault();
1726 if (!this.active_repo.norefresh) {
82525f59 1727 this.list({ path: this.currentpath });
b5e7b638
MG
1728 }
1729 }, this);
b92241f2 1730 toolbar.one('.fp-tb-search form').
b5e7b638 1731 set('method', 'POST').
b92241f2 1732 set('id', 'fp-tb-search-'+client_id).
b5e7b638 1733 on('submit', function(e) {
4adecd7b 1734 e.preventDefault();
b5e7b638
MG
1735 if (!this.active_repo.nosearch) {
1736 this.request({
1737 scope: this,
1738 action:'search',
1739 client_id: this.options.client_id,
1740 repository_id: this.active_repo.id,
1741 form: {id: 'fp-tb-search-'+client_id, upload:false, useDisabled:true},
1742 callback: this.display_response
1743 }, true);
1744 }
cd029574 1745 }, this);
99eaca9d 1746
b92241f2 1747 // it does not matter what kind of element is .fp-tb-manage, we create a dummy <a>
b5e7b638 1748 // element and use it to open url on click event
3a1e425b
MG
1749 var managelnk = Y.Node.create('<a/>').
1750 setAttrs({id:'fp-tb-manage-'+client_id+'-link', target:'_blank'}).
1751 setStyle('display', 'none');
b92241f2
MG
1752 toolbar.append(managelnk);
1753 toolbar.one('.fp-tb-manage').one('a,button').
1754 on('click', function(e) {
1755 e.preventDefault();
1756 managelnk.simulate('click')
1757 });
99eaca9d 1758
b92241f2 1759 // same with .fp-tb-help
3a1e425b
MG
1760 var helplnk = Y.Node.create('<a/>').
1761 setAttrs({id:'fp-tb-help-'+client_id+'-link', target:'_blank'}).
1762 setStyle('display', 'none');
b92241f2 1763 toolbar.append(helplnk);
ae8e49e8 1764 toolbar.one('.fp-tb-help').one('a,button').
b92241f2
MG
1765 on('click', function(e) {
1766 e.preventDefault();
1767 helplnk.simulate('click')
1768 });
b5e7b638
MG
1769 },
1770 hide_header: function() {
b92241f2
MG
1771 if (this.fpnode.one('.fp-toolbar')) {
1772 this.fpnode.one('.fp-toolbar').addClass('empty');
b5e7b638 1773 }
3a1e425b
MG
1774 if (this.pathbar) {
1775 this.pathbar.setContent('').addClass('empty');
1776 }
b5e7b638
MG
1777 },
1778 print_header: function() {
1779 var r = this.active_repo;
1780 var scope = this;
1781 var client_id = this.options.client_id;
2f6749f4 1782 this.hide_header();
b92241f2
MG
1783 this.print_path();
1784 var toolbar = this.fpnode.one('.fp-toolbar');
1785 if (!toolbar) { return; }
99eaca9d 1786
b92241f2
MG
1787 var enable_tb_control = function(node, enabled) {
1788 if (!node) { return; }
1789 node.addClassIf('disabled', !enabled).addClassIf('enabled', enabled)
1790 if (enabled) {
1791 toolbar.removeClass('empty');
b5e7b638
MG
1792 }
1793 }
99eaca9d 1794
b5e7b638 1795 // TODO 'back' permanently disabled for now. Note, flickr_public uses 'Logout' for it!
b92241f2 1796 enable_tb_control(toolbar.one('.fp-tb-back'), false);
99eaca9d 1797
b5e7b638 1798 // search form
b92241f2 1799 enable_tb_control(toolbar.one('.fp-tb-search'), !r.nosearch);
b5e7b638 1800 if(!r.nosearch) {
b92241f2
MG
1801 var searchform = toolbar.one('.fp-tb-search form');
1802 searchform.setContent('');
b5e7b638
MG
1803 this.request({
1804 scope: this,
1805 action:'searchform',
1806 repository_id: this.active_repo.id,
1807 callback: function(id, obj, args) {
1808 if (obj.repo_id == scope.active_repo.id && obj.form) {
1809 // if we did not jump to another repository meanwhile
b92241f2 1810 searchform.setContent(obj.form);
d01ebb94
RT
1811 // Highlight search text when user click for search.
1812 var searchnode = searchform.one('input[name="s"]');
1813 if (searchnode) {
1814 searchnode.once('click', function(e) {
1815 e.preventDefault();
1816 this.select();
1817 });
1818 }
99eaca9d 1819 }
b5e7b638
MG
1820 }
1821 }, false);
99eaca9d 1822 }
b5e7b638
MG
1823
1824 // refresh button
99eaca9d 1825 // weather we use cache for this instance, this button will reload listing anyway
b92241f2 1826 enable_tb_control(toolbar.one('.fp-tb-refresh'), !r.norefresh);
b5e7b638
MG
1827
1828 // login button
b92241f2 1829 enable_tb_control(toolbar.one('.fp-tb-logout'), !r.nologin);
6a0d7194
DP
1830 if (!r.nologin) {
1831 var label = r.logouttext ? r.logouttext : M.str.repository.logout;
b92241f2 1832 toolbar.one('.fp-tb-logout').one('a,button').setContent(label)
99eaca9d
DC
1833 }
1834
b5e7b638 1835 // manage url
b92241f2 1836 enable_tb_control(toolbar.one('.fp-tb-manage'), r.manage);
b5e7b638
MG
1837 Y.one('#fp-tb-manage-'+client_id+'-link').set('href', r.manage);
1838
1839 // help url
b92241f2 1840 enable_tb_control(toolbar.one('.fp-tb-help'), r.help);
b5e7b638 1841 Y.one('#fp-tb-help-'+client_id+'-link').set('href', r.help);
cd029574
RW
1842
1843 // message
1844 if (toolbar.one('.fp-tb-message')) {
1845 enable_tb_control(toolbar.one('.fp-tb-message'), r.message);
1846 toolbar.one('.fp-tb-message').setContent(r.message);
1847 }
99eaca9d 1848 },
99eaca9d 1849 print_path: function() {
6a0d7194
DP
1850 if (!this.pathbar) {
1851 return;
1852 }
3a1e425b 1853 this.pathbar.setContent('').addClass('empty');
99eaca9d 1854 var p = this.filepath;
2f6749f4 1855 if (p && p.length!=0 && this.viewmode != 2) {
99eaca9d 1856 for(var i = 0; i < p.length; i++) {
b5e7b638
MG
1857 var el = this.pathnode.cloneNode(true);
1858 this.pathbar.appendChild(el);
6a0d7194
DP
1859 if (i == 0) {
1860 el.addClass('first');
1861 }
1862 if (i == p.length-1) {
1863 el.addClass('last');
1864 }
1865 if (i%2) {
1866 el.addClass('even');
1867 } else {
1868 el.addClass('odd');
1869 }
b5e7b638
MG
1870 el.all('.fp-path-folder-name').setContent(p[i].name);
1871 el.on('click',
1872 function(e, path) {
1873 e.preventDefault();
1874 this.list({'path':path});
1875 },
1876 this, p[i].path);
99eaca9d 1877 }
b5e7b638 1878 this.pathbar.removeClass('empty');
99eaca9d
DC
1879 }
1880 },
1881 hide: function() {
b5e7b638
MG
1882 this.selectui.hide();
1883 if (this.process_dlg) {
1884 this.process_dlg.hide();
1885 }
1886 if (this.msg_dlg) {
1887 this.msg_dlg.hide();
1888 }
99eaca9d
DC
1889 this.mainui.hide();
1890 },
1891 show: function() {
b5e7b638
MG
1892 if (this.fpnode) {
1893 this.hide();
99eaca9d 1894 this.mainui.show();
a756cb37 1895 this.show_recent_repository();
99eaca9d
DC
1896 } else {
1897 this.launch();
1898 }
1899 },
1900 launch: function() {
7b42e81a 1901 this.render();
a756cb37
DC
1902 },
1903 show_recent_repository: function() {
b5e7b638
MG
1904 this.hide_header();
1905 this.viewbar_set_enabled(false);
837eef2e
DP
1906 var repository_id = this.get_preference('recentrepository');
1907 this.viewmode = this.get_preference('recentviewmode');
5bdf63cc 1908 if (this.viewmode != 2 && this.viewmode != 3) {
b5e7b638
MG
1909 this.viewmode = 1;
1910 }
a756cb37
DC
1911 if (this.options.repositories[repository_id]) {
1912 this.list({'repo_id':repository_id});
1913 }
837eef2e
DP
1914 },
1915 get_preference: function (name) {
1916 if (this.options.userprefs[name]) {
1917 return this.options.userprefs[name];
1918 } else {
1919 return false;
1920 }
1921 },
1922 set_preference: function(name, value) {
1923 if (this.options.userprefs[name] != value) {
1924 M.util.set_user_preference('filepicker_' + name, value);
1925 this.options.userprefs[name] = value;
1926 }
99eaca9d
DC
1927 }
1928 });
bb496de7
DC
1929 var loading = Y.one('#filepicker-loading-'+options.client_id);
1930 if (loading) {
1931 loading.setStyle('display', 'none');
1932 }
4c508047
PS
1933 M.core_filepicker.instances[options.client_id] = new FilePickerHelper(options);
1934};