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)
7dab27b3 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
7dab27b3 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. */
3b715c5f 117 Y.YUI2.widget.Node.prototype.refreshPreviews = function(imgid, newsrc, regex) {
9213f547
MG
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 202 tmpnodedata.html = el.getContent();
3b715c5f 203 var tmpNode = new Y.YUI2.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
3b715c5f 223 scope.treeview = new Y.YUI2.widget.TreeView(parentid);
e709ddd2
MG
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);
3b715c5f 277 Y.YUI2.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 ];
80d92db9
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() {
80d92db9
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;
68acd115 546 // The unlimited value of areamaxbytes is -1, it is defined by FILE_AREA_MAX_BYTES_UNLIMITED.
21e3ea77 547 params['areamaxbytes'] = this.options.areamaxbytes ? this.options.areamaxbytes : -1;
be85f7ab
DC
548 if (this.options.context && this.options.context.id) {
549 params['ctx_id'] = this.options.context.id;
550 }
99eaca9d
DC
551 if (args['params']) {
552 for (i in args['params']) {
553 params[i] = args['params'][i];
554 }
555 }
64654e78
DC
556 if (args.action == 'upload') {
557 var list = [];
558 for(var k in params) {
559 var value = params[k];
560 if(value instanceof Array) {
561 for(var i in value) {
562 list.push(k+'[]='+value[i]);
563 }
564 } else {
565 list.push(k+'='+value);
566 }
567 }
568 params = list.join('&');
569 } else {
570 params = build_querystring(params);
571 }
99eaca9d
DC
572 var cfg = {
573 method: 'POST',
574 on: {
575 complete: function(id,o,p) {
576 if (!o) {
b5e7b638 577 // TODO
99eaca9d
DC
578 alert('IO FATAL');
579 return;
580 }
4c508047
PS
581 var data = null;
582 try {
583 data = Y.JSON.parse(o.responseText);
584 } catch(e) {
879b4f9a 585 scope.print_msg(M.str.repository.invalidjson, 'error');
b5e7b638 586 scope.display_error(M.str.repository.invalidjson+'<pre>'+stripHTML(o.responseText)+'</pre>', 'invalidjson')
c26855ff 587 return;
4c508047 588 }
1dce6261 589 // error checking
e35194be
DC
590 if (data && data.error) {
591 scope.print_msg(data.error, 'error');
a5159b86
MG
592 if (args.onerror) {
593 args.onerror(id,data,p);
594 } else {
3a1e425b 595 this.fpnode.one('.fp-content').setContent('');
a5159b86 596 }
1dce6261
DC
597 return;
598 } else {
879b4f9a
DC
599 if (data.msg) {
600 scope.print_msg(data.msg, 'info');
601 }
7f9358fc
MG
602 // cache result if applicable
603 if (args.action != 'upload' && data.allowcaching) {
604 scope.cached_responses[params] = data;
605 }
606 // invoke callback
1dce6261
DC
607 args.callback(id,data,p);
608 }
99eaca9d
DC
609 }
610 },
611 arguments: {
612 scope: scope
613 },
614 headers: {
bd2db41a 615 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
99eaca9d 616 },
64654e78 617 data: params,
4c508047 618 context: this
99eaca9d
DC
619 };
620 if (args.form) {
621 cfg.form = args.form;
622 }
7f9358fc
MG
623 // check if result of the same request has been already cached. If not, request it
624 // (never applicable in case of form submission and/or upload action):
625 if (!args.form && args.action != 'upload' && scope.cached_responses[params]) {
626 args.callback(null, scope.cached_responses[params], {scope: scope})
627 } else {
628 Y.io(api, cfg);
629 if (redraw) {
b5e7b638 630 this.wait();
7f9358fc 631 }
99eaca9d
DC
632 }
633 },
b5e7b638 634 /** displays the dialog and processes rename/overwrite if there is a file with the same name in the same filearea*/
f392caba
DC
635 process_existing_file: function(data) {
636 var scope = this;
b5e7b638 637 var handleOverwrite = function(e) {
f392caba 638 // overwrite
b5e7b638
MG
639 e.preventDefault();
640 var data = this.process_dlg.dialogdata;
f392caba
DC
641 var params = {}
642 params['existingfilename'] = data.existingfile.filename;
643 params['existingfilepath'] = data.existingfile.filepath;
644 params['newfilename'] = data.newfile.filename;
645 params['newfilepath'] = data.newfile.filepath;
b5e7b638
MG
646 this.hide_header();
647 this.request({
f392caba 648 'params': params,
b5e7b638 649 'scope': this,
f392caba
DC
650 'action':'overwrite',
651 'path': '',
b5e7b638
MG
652 'client_id': this.options.client_id,
653 'repository_id': this.active_repo.id,
f392caba 654 'callback': function(id, o, args) {
f392caba
DC
655 scope.hide();
656 // editor needs to update url
657 // filemanager do nothing
c8ad2c12
SH
658 if (scope.options.editor_target && scope.options.env == 'editor') {
659 scope.options.editor_target.value = data.existingfile.url;
f392caba 660 scope.options.editor_target.onchange();
1ae299f5 661 } else if (scope.options.env === 'filepicker') {
b5e7b638 662 var fileinfo = {'client_id':scope.options.client_id,
913b3cb3
JP
663 'url':data.existingfile.url,
664 'file':data.existingfile.filename};
dd1f051e
MG
665 var formcallback_scope = scope.options.magicscope ? scope.options.magicscope : scope;
666 scope.options.formcallback.apply(formcallback_scope, [fileinfo]);
f392caba
DC
667 }
668 }
669 }, true);
670 }
b5e7b638
MG
671 var handleRename = function(e) {
672 // inserts file with the new name
673 e.preventDefault();
674 var scope = this;
675 var data = this.process_dlg.dialogdata;
c8ad2c12
SH
676 if (scope.options.editor_target && scope.options.env == 'editor') {
677 scope.options.editor_target.value = data.newfile.url;
f392caba
DC
678 scope.options.editor_target.onchange();
679 }
f392caba 680 scope.hide();
dd1f051e 681 var formcallback_scope = scope.options.magicscope ? scope.options.magicscope : scope;
b5e7b638 682 var fileinfo = {'client_id':scope.options.client_id,
794cc7e1
JP
683 'url':data.newfile.url,
684 'file':data.newfile.filename};
685 scope.options.formcallback.apply(formcallback_scope, [fileinfo]);
f392caba 686 }
b5e7b638 687 var handleCancel = function(e) {
f392caba 688 // Delete tmp file
b5e7b638 689 e.preventDefault();
f392caba 690 var params = {};
b5e7b638
MG
691 params['newfilename'] = this.process_dlg.dialogdata.newfile.filename;
692 params['newfilepath'] = this.process_dlg.dialogdata.newfile.filepath;
693 this.request({
f392caba 694 'params': params,
b5e7b638 695 'scope': this,
f392caba
DC
696 'action':'deletetmpfile',
697 'path': '',
b5e7b638
MG
698 'client_id': this.options.client_id,
699 'repository_id': this.active_repo.id,
f392caba 700 'callback': function(id, o, args) {
b5e7b638 701 // let it be in background, from user point of view nothing is happenning
f392caba 702 }
b5e7b638
MG
703 }, false);
704 this.process_dlg.hide();
705 this.selectui.hide();
f392caba 706 }
b5e7b638 707 if (!this.process_dlg) {
5e117466 708 this.process_dlg_node = Y.Node.createWithFilesSkin(M.core_filepicker.templates.processexistingfile);
dd1f051e
MG
709 var node = this.process_dlg_node;
710 node.generateID();
b5e7b638
MG
711 this.process_dlg = new Y.Panel({
712 srcNode : node,
713 headerContent: M.str.repository.fileexistsdialogheader,
e13b330d 714 zIndex : 8000,
b5e7b638
MG
715 centered : true,
716 modal : true,
717 visible : false,
718 render : true,
719 buttons : {}
720 });
dd1f051e 721 this.process_dlg.plug(Y.Plugin.Drag,{handles:['#'+node.get('id')+' .yui3-widget-hd']});
b5e7b638
MG
722 node.one('.fp-dlg-butoverwrite').on('click', handleOverwrite, this);
723 node.one('.fp-dlg-butrename').on('click', handleRename, this);
724 node.one('.fp-dlg-butcancel').on('click', handleCancel, this);
725 if (this.options.env == 'editor') {
726 node.one('.fp-dlg-text').setContent(M.str.repository.fileexistsdialog_editor);
727 } else {
728 node.one('.fp-dlg-text').setContent(M.str.repository.fileexistsdialog_filemanager);
729 }
f392caba 730 }
55089a9d 731 this.selectnode.removeClass('loading');
b5e7b638 732 this.process_dlg.dialogdata = data;
dd1f051e 733 this.process_dlg_node.one('.fp-dlg-butrename').setContent(M.util.get_string('renameto', 'repository', data.newfile.filename));
b5e7b638
MG
734 this.process_dlg.show();
735 },
736 /** displays error instead of filepicker contents */
737 display_error: function(errortext, errorcode) {
738 this.fpnode.one('.fp-content').setContent(M.core_filepicker.templates.error);
739 this.fpnode.one('.fp-content .fp-error').
740 addClass(errorcode).
741 setContent(errortext);
f392caba 742 },
b5e7b638 743 /** displays message in a popup */
879b4f9a 744 print_msg: function(msg, type) {
b5e7b638
MG
745 var header = M.str.moodle.error;
746 if (type != 'error') {
747 type = 'info'; // one of only two types excepted
748 header = M.str.moodle.info;
879b4f9a
DC
749 }
750 if (!this.msg_dlg) {
5e117466 751 this.msg_dlg_node = Y.Node.createWithFilesSkin(M.core_filepicker.templates.message);
dd1f051e 752 this.msg_dlg_node.generateID();
b5e7b638
MG
753
754 this.msg_dlg = new Y.Panel({
dd1f051e 755 srcNode : this.msg_dlg_node,
e13b330d 756 zIndex : 8000,
b5e7b638
MG
757 centered : true,
758 modal : true,
759 visible : false,
760 render : true
761 });
dd1f051e
MG
762 this.msg_dlg.plug(Y.Plugin.Drag,{handles:['#'+this.msg_dlg_node.get('id')+' .yui3-widget-hd']});
763 this.msg_dlg_node.one('.fp-msg-butok').on('click', function(e) {
b5e7b638
MG
764 e.preventDefault();
765 this.msg_dlg.hide();
766 }, this);
879b4f9a 767 }
b5e7b638
MG
768
769 this.msg_dlg.set('headerContent', header);
dd1f051e
MG
770 this.msg_dlg_node.removeClass('fp-msg-info').removeClass('fp-msg-error').addClass('fp-msg-'+type)
771 this.msg_dlg_node.one('.fp-msg-text').setContent(msg);
879b4f9a 772 this.msg_dlg.show();
879b4f9a 773 },
7ccf18a6 774 view_files: function(appenditems) {
b92241f2
MG
775 this.viewbar_set_enabled(true);
776 this.print_path();
e709ddd2
MG
777 /*if ((appenditems == null) && (!this.filelist || !this.filelist.length) && !this.active_repo.hasmorepages) {
778 // TODO do it via classes and adjust for each view mode!
779 // If there are no items and no next page, just display status message and quit
780 this.display_error(M.str.repository.nofilesavailable, 'nofilesavailable');
781 return;
782 }*/
b92241f2 783 if (this.viewmode == 2) {
7ccf18a6 784 this.view_as_list(appenditems);
b92241f2 785 } else if (this.viewmode == 3) {
7ccf18a6 786 this.view_as_table(appenditems);
99eaca9d 787 } else {
7ccf18a6
MG
788 this.view_as_icons(appenditems);
789 }
790 // display/hide the link for requesting next page
791 if (!appenditems && this.active_repo.hasmorepages) {
792 if (!this.fpnode.one('.fp-content .fp-nextpage')) {
793 this.fpnode.one('.fp-content').append(M.core_filepicker.templates.nextpage);
794 }
795 this.fpnode.one('.fp-content .fp-nextpage').one('a,button').on('click', function(e) {
796 e.preventDefault();
797 this.fpnode.one('.fp-content .fp-nextpage').addClass('loading');
798 this.request_next_page();
799 }, this);
800 }
801 if (!this.active_repo.hasmorepages && this.fpnode.one('.fp-content .fp-nextpage')) {
802 this.fpnode.one('.fp-content .fp-nextpage').remove();
803 }
804 if (this.fpnode.one('.fp-content .fp-nextpage')) {
805 this.fpnode.one('.fp-content .fp-nextpage').removeClass('loading');
99eaca9d 806 }
ce3eeb98
MG
807 this.content_scrolled();
808 },
809 content_scrolled: function(e) {
810 setTimeout(Y.bind(function() {
6a0d7194
DP
811 if (this.processingimages) {
812 return;
813 }
ce3eeb98
MG
814 this.processingimages = true;
815 var scope = this,
816 fpcontent = this.fpnode.one('.fp-content'),
817 fpcontenty = fpcontent.getY(),
818 fpcontentheight = fpcontent.getStylePx('height'),
819 nextpage = fpcontent.one('.fp-nextpage'),
820 is_node_visible = function(node) {
821 var offset = node.getY()-fpcontenty;
822 if (offset <= fpcontentheight && (offset >=0 || offset+node.getStylePx('height')>=0)) {
823 return true;
824 }
825 return false;
826 };
827 // automatically load next page when 'more' link becomes visible
828 if (nextpage && !nextpage.hasClass('loading') && is_node_visible(nextpage)) {
829 nextpage.one('a,button').simulate('click');
830 }
831 // replace src for visible images that need to be lazy-loaded
832 if (scope.lazyloading) {
833 fpcontent.all('img').each( function(node) {
834 if (node.get('id') && scope.lazyloading[node.get('id')] && is_node_visible(node)) {
9213f547 835 node.setImgRealSrc(scope.lazyloading);
ce3eeb98
MG
836 }
837 });
838 }
839 this.processingimages = false;
840 }, this), 200)
99eaca9d 841 },
1fb0173e 842 treeview_dynload: function(node, cb) {
2f6749f4
MG
843 var retrieved_children = {};
844 if (node.children) {
845 for (var i in node.children) {
846 retrieved_children[node.children[i].path] = node.children[i];
847 }
848 }
e709ddd2 849 this.request({
1fb0173e 850 action:'list',
e709ddd2
MG
851 client_id: this.options.client_id,
852 repository_id: this.active_repo.id,
1fb0173e
DC
853 path:node.path?node.path:'',
854 page:node.page?args.page:'',
e709ddd2 855 scope:this,
1fb0173e 856 callback: function(id, obj, args) {
1fb0173e 857 var list = obj.list;
e709ddd2 858 var scope = args.scope;
2f6749f4
MG
859 // check that user did not leave the view mode before recieving this response
860 if (!(scope.active_repo.id == obj.repo_id && scope.viewmode == 2 && node && node.getChildrenEl())) {
861 return;
862 }
863 if (cb != null) { // (in manual mode do not update current path)
864 scope.viewbar_set_enabled(true);
865 scope.parse_repository_options(obj);
866 }
e709ddd2 867 node.highlight(false);
6a0d7194
DP
868 node.origlist = obj.list ? obj.list : null;
869 node.origpath = obj.path ? obj.path : null;
2f6749f4 870 node.children = [];
1fb0173e 871 for(k in list) {
2f6749f4
MG
872 if (list[k].children && retrieved_children[list[k].path]) {
873 // if this child is a folder and has already been retrieved
874 node.children[node.children.length] = retrieved_children[list[k].path];
875 } else {
e709ddd2
MG
876 // append new file to the list
877 scope.view_as_list([list[k]]);
2f6749f4
MG
878 }
879 }
880 if (cb == null) {
881 node.refresh();
882 } else {
e709ddd2 883 // invoke callback requested by TreeView component
2f6749f4 884 cb();
1fb0173e 885 }
ce3eeb98 886 scope.content_scrolled();
1fb0173e
DC
887 }
888 }, false);
889 },
1778f310
MG
890 classnamecallback : function(node) {
891 var classname = '';
892 if (node.children) {
893 classname = classname + ' fp-folder';
894 }
895 if (node.isref) {
896 classname = classname + ' fp-isreference';
897 }
898 if (node.refcount) {
899 classname = classname + ' fp-hasreferences';
900 }
901 if (node.originalmissing) {
902 classname = classname + ' fp-originalmissing';
903 }
904 return Y.Lang.trim(classname);
905 },
7ccf18a6
MG
906 /** displays list of files in tree (list) view mode. If param appenditems is specified,
907 * appends those items to the end of the list. Otherwise (default behaviour)
908 * clears the contents and displays the items from this.filelist */
909 view_as_list: function(appenditems) {
e709ddd2
MG
910 var list = (appenditems != null) ? appenditems : this.filelist;
911 this.viewmode = 2;
912 if (!this.filelist || this.filelist.length==0 && (!this.filepath || !this.filepath.length)) {
b5e7b638 913 this.display_error(M.str.repository.nofilesavailable, 'nofilesavailable');
4adecd7b
MG
914 return;
915 }
879b4f9a 916
e709ddd2
MG
917 var element_template = Y.Node.create(M.core_filepicker.templates.listfilename);
918 var options = {
919 viewmode : this.viewmode,
920 appendonly : (appenditems != null),
921 filenode : element_template,
922 callbackcontext : this,
923 callback : function(e, node) {
23b83009 924 // TODO MDL-32736 e is not an event here but an object with properties 'event' and 'node'
e709ddd2
MG
925 if (!node.children) {
926 if (e.node.parent && e.node.parent.origpath) {
927 // set the current path
928 this.filepath = e.node.parent.origpath;
929 this.filelist = e.node.parent.origlist;
930 this.print_path();
2f6749f4 931 }
e709ddd2
MG
932 this.select_file(node);
933 } else {
934 // save current path and filelist (in case we want to jump to other viewmode)
935 this.filepath = e.node.origpath;
936 this.filelist = e.node.origlist;
7dab27b3 937 this.currentpath = e.node.path;
e709ddd2
MG
938 this.print_path();
939 this.content_scrolled();
2f6749f4 940 }
e709ddd2 941 },
1778f310 942 classnamecallback : this.classnamecallback,
e709ddd2
MG
943 dynload : this.active_repo.dynload,
944 filepath : this.filepath,
945 treeview_dynload : this.treeview_dynload
946 };
947 this.fpnode.one('.fp-content').fp_display_filelist(options, list, this.lazyloading);
99eaca9d 948 },
7ccf18a6
MG
949 /** displays list of files in icon view mode. If param appenditems is specified,
950 * appends those items to the end of the list. Otherwise (default behaviour)
951 * clears the contents and displays the items from this.filelist */
952 view_as_icons: function(appenditems) {
99eaca9d 953 this.viewmode = 1;
e709ddd2
MG
954 var list = (appenditems != null) ? appenditems : this.filelist;
955 var element_template = Y.Node.create(M.core_filepicker.templates.iconfilename);
956 if ((appenditems == null) && (!this.filelist || !this.filelist.length)) {
957 this.display_error(M.str.repository.nofilesavailable, 'nofilesavailable');
958 return;
879b4f9a 959 }
e709ddd2
MG
960 var options = {
961 viewmode : this.viewmode,
962 appendonly : (appenditems != null),
963 filenode : element_template,
964 callbackcontext : this,
965 callback : function(e, node) {
6a0d7194
DP
966 if (e.preventDefault) {
967 e.preventDefault();
968 }
e709ddd2
MG
969 if(node.children) {
970 if (this.active_repo.dynload) {
971 this.list({'path':node.path});
972 } else {
e709ddd2 973 this.filelist = node.children;
99eaca9d
DC
974 this.view_files();
975 }
e709ddd2
MG
976 } else {
977 this.select_file(node);
978 }
6c2367cc 979 },
1778f310 980 classnamecallback : this.classnamecallback
e709ddd2
MG
981 };
982 this.fpnode.one('.fp-content').fp_display_filelist(options, list, this.lazyloading);
99eaca9d 983 },
7ccf18a6
MG
984 /** displays list of files in table view mode. If param appenditems is specified,
985 * appends those items to the end of the list. Otherwise (default behaviour)
986 * clears the contents and displays the items from this.filelist */
987 view_as_table: function(appenditems) {
5bdf63cc 988 this.viewmode = 3;
e709ddd2
MG
989 var list = (appenditems != null) ? appenditems : this.filelist;
990 if (!appenditems && (!this.filelist || this.filelist.length==0) && !this.active_repo.hasmorepages) {
5bdf63cc
MG
991 this.display_error(M.str.repository.nofilesavailable, 'nofilesavailable');
992 return;
993 }
e709ddd2
MG
994 var element_template = Y.Node.create(M.core_filepicker.templates.listfilename);
995 var options = {
996 viewmode : this.viewmode,
997 appendonly : (appenditems != null),
998 filenode : element_template,
999 callbackcontext : this,
1000 sortable : !this.active_repo.hasmorepages,
1001 callback : function(e, node) {
23b83009 1002 if (e.preventDefault) {e.preventDefault();}
e709ddd2 1003 if (node.children) {
7ccf18a6 1004 if (this.active_repo.dynload) {
e709ddd2 1005 this.list({'path':node.path});
7ccf18a6 1006 } else {
e709ddd2 1007 this.filelist = node.children;
7ccf18a6 1008 this.view_files();
5bdf63cc 1009 }
7ccf18a6 1010 } else {
e709ddd2 1011 this.select_file(node);
5bdf63cc 1012 }
6c2367cc 1013 },
1778f310 1014 classnamecallback : this.classnamecallback
e709ddd2
MG
1015 };
1016 this.fpnode.one('.fp-content').fp_display_filelist(options, list, this.lazyloading);
7ccf18a6
MG
1017 },
1018 /** If more than one page available, requests and displays the files from the next page */
1019 request_next_page: function() {
1020 if (!this.active_repo.hasmorepages || this.active_repo.nextpagerequested) {
1021 // nothing to load
1022 return;
1023 }
1024 this.active_repo.nextpagerequested = true;
1025 var nextpage = this.active_repo.page+1;
7dab27b3
FM
1026 var args = {
1027 page: nextpage,
e13b330d 1028 repo_id: this.active_repo.id
7dab27b3 1029 };
7ccf18a6
MG
1030 var action = this.active_repo.issearchresult ? 'search' : 'list';
1031 this.request({
7dab27b3 1032 path: this.currentpath,
7ccf18a6
MG
1033 scope: this,
1034 action: action,
1035 client_id: this.options.client_id,
1036 repository_id: args.repo_id,
1037 params: args,
1038 callback: function(id, obj, args) {
1039 var scope = args.scope;
7dab27b3
FM
1040 // Check that we are still in the same repository and are expecting this page. We have no way
1041 // to compare the requested page and the one returned, so we assume that if the last chunk
1042 // of the breadcrumb is similar, then we probably are on the same page.
1043 var samepage = true;
1044 if (obj.path && scope.filepath) {
1045 var pathbefore = scope.filepath[scope.filepath.length-1];
1046 var pathafter = obj.path[obj.path.length-1];
1047 if (pathbefore.path != pathafter.path) {
1048 samepage = false;
1049 }
1050 }
7ccf18a6
MG
1051 if (scope.active_repo.hasmorepages && obj.list && obj.page &&
1052 obj.repo_id == scope.active_repo.id &&
7dab27b3 1053 obj.page == scope.active_repo.page+1 && samepage) {
7ccf18a6
MG
1054 scope.parse_repository_options(obj, true);
1055 scope.view_files(obj.list)
1056 }
1057 }
1058 }, false);
5bdf63cc 1059 },
99eaca9d 1060 select_file: function(args) {
b5e7b638 1061 this.selectui.show();
99eaca9d 1062 var client_id = this.options.client_id;
55089a9d 1063 var selectnode = this.selectnode;
b92241f2 1064 var return_types = this.options.repositories[this.active_repo.id].return_types;
3a1e425b 1065 selectnode.removeClass('loading');
b92241f2 1066 selectnode.one('.fp-saveas input').set('value', args.title);
99eaca9d 1067
ce3eeb98
MG
1068 var imgnode = Y.Node.create('<img/>').
1069 set('src', args.realthumbnail ? args.realthumbnail : args.thumbnail).
1070 setStyle('maxHeight', ''+(args.thumbnail_height ? args.thumbnail_height : 90)+'px').
1071 setStyle('maxWidth', ''+(args.thumbnail_width ? args.thumbnail_width : 90)+'px');
b92241f2 1072 selectnode.one('.fp-thumbnail').setContent('').appendChild(imgnode);
b5e7b638 1073
5cf44c1f
MG
1074 // filelink is the array of file-link-types available for this repository in this env
1075 var filelinktypes = [2/*FILE_INTERNAL*/,1/*FILE_EXTERNAL*/,4/*FILE_REFERENCE*/];
1076 var filelink = {}, firstfilelink = null, filelinkcount = 0;
1077 for (var i in filelinktypes) {
1078 var allowed = (return_types & filelinktypes[i]) &&
1079 (this.options.return_types & filelinktypes[i]);
1080 if (filelinktypes[i] == 1/*FILE_EXTERNAL*/ && !this.options.externallink && this.options.env == 'editor') {
1081 // special configuration setting 'repositoryallowexternallinks' may prevent
1082 // using external links in editor environment
1083 allowed = false;
b5e7b638 1084 }
5cf44c1f
MG
1085 filelink[filelinktypes[i]] = allowed;
1086 firstfilelink = (firstfilelink==null && allowed) ? filelinktypes[i] : firstfilelink;
1087 filelinkcount += allowed ? 1 : 0;
99eaca9d 1088 }
5cf44c1f
MG
1089 // make radio buttons enabled if this file-link-type is available and only if there are more than one file-link-type option
1090 // check the first available file-link-type option
1091 for (var linktype in filelink) {
1092 var el = selectnode.one('.fp-linktype-'+linktype);
1093 el.addClassIf('uneditable', !(filelink[linktype] && filelinkcount>1));
6a0d7194 1094 el.one('input').set('disabled', (filelink[linktype] && filelinkcount>1) ? '' : 'disabled').
5cf44c1f 1095 set('checked', (firstfilelink == linktype) ? 'checked' : '').simulate('change')
1dce6261 1096 }
b92241f2 1097
5cf44c1f 1098 // TODO MDL-32532: attributes 'hasauthor' and 'haslicense' need to be obsolete,
6a0d7194 1099 selectnode.one('.fp-setauthor input').set('value', args.author ? args.author : this.options.author);
5cf44c1f 1100 this.set_selected_license(selectnode.one('.fp-setlicense'), args.license);
b5e7b638 1101 selectnode.one('form #filesource-'+client_id).set('value', args.source);
b92241f2
MG
1102
1103 // display static information about a file (when known)
1104 var attrs = ['datemodified','datecreated','size','license','author','dimensions'];
1105 for (var i in attrs) {
1106 if (selectnode.one('.fp-'+attrs[i])) {
1107 var value = (args[attrs[i]+'_f']) ? args[attrs[i]+'_f'] : (args[attrs[i]] ? args[attrs[i]] : '');
1108 selectnode.one('.fp-'+attrs[i]).addClassIf('fp-unknown', ''+value == '')
1109 .one('.fp-value').setContent(value);
1110 }
1111 }
b5e7b638
MG
1112 },
1113 setup_select_file: function() {
1114 var client_id = this.options.client_id;
55089a9d 1115 var selectnode = this.selectnode;
b92241f2
MG
1116 var getfile = selectnode.one('.fp-select-confirm');
1117 // bind labels with corresponding inputs
5cf44c1f 1118 selectnode.all('.fp-saveas,.fp-linktype-2,.fp-linktype-1,.fp-linktype-4,.fp-setauthor,.fp-setlicense').each(function (node) {
b92241f2
MG
1119 node.all('label').set('for', node.one('input,select').generateID());
1120 });
5cf44c1f
MG
1121 selectnode.one('.fp-linktype-2 input').setAttrs({value: 2, name: 'linktype'});
1122 selectnode.one('.fp-linktype-1 input').setAttrs({value: 1, name: 'linktype'});
1123 selectnode.one('.fp-linktype-4 input').setAttrs({value: 4, name: 'linktype'});
1124 var changelinktype = function(e) {
1125 if (e.currentTarget.get('checked')) {
1126 var allowinputs = e.currentTarget.get('value') != 1/*FILE_EXTERNAL*/;
1127 selectnode.all('.fp-setauthor,.fp-setlicense,.fp-saveas').each(function(node){
1128 node.addClassIf('uneditable', !allowinputs);
1129 node.all('input,select').set('disabled', allowinputs?'':'disabled');
1130 });
1131 }
1132 };
1133 selectnode.all('.fp-linktype-2,.fp-linktype-1,.fp-linktype-4').each(function (node) {
1134 node.one('input').on('change', changelinktype, this);
1135 });
b92241f2
MG
1136 this.populate_licenses_select(selectnode.one('.fp-setlicense select'));
1137 // register event on clicking submit button
99eaca9d 1138 getfile.on('click', function(e) {
b5e7b638 1139 e.preventDefault();
99eaca9d
DC
1140 var client_id = this.options.client_id;
1141 var scope = this;
1142 var repository_id = this.active_repo.id;
b92241f2 1143 var title = selectnode.one('.fp-saveas input').get('value');
b5e7b638 1144 var filesource = selectnode.one('form #filesource-'+client_id).get('value');
14469892 1145 var params = {'title':title, 'source':filesource, 'savepath': this.options.savepath};
b92241f2 1146 var license = selectnode.one('.fp-setlicense select');
1dce6261
DC
1147 if (license) {
1148 params['license'] = license.get('value');
5cf44c1f 1149 var origlicense = selectnode.one('.fp-license .fp-value');
6a0d7194
DP
1150 if (origlicense) {
1151 origlicense = origlicense.getContent();
1152 }
837eef2e 1153 this.set_preference('recentlicense', license.get('value'));
1dce6261 1154 }
b92241f2 1155 params['author'] = selectnode.one('.fp-setauthor input').get('value');
99eaca9d 1156
5cf44c1f
MG
1157 var return_types = this.options.repositories[this.active_repo.id].return_types;
1158 if (this.options.env == 'editor') {
392d5fd4
DC
1159 // in editor, images are stored in '/' only
1160 params.savepath = '/';
766514a0 1161 }
5cf44c1f
MG
1162 if ((this.options.externallink || this.options.env != 'editor') &&
1163 (return_types & 1/*FILE_EXTERNAL*/) &&
1164 (this.options.return_types & 1/*FILE_EXTERNAL*/) &&
1165 selectnode.one('.fp-linktype-1 input').get('checked')) {
99eaca9d 1166 params['linkexternal'] = 'yes';
5cf44c1f
MG
1167 } else if ((return_types & 4/*FILE_REFERENCE*/) &&
1168 (this.options.return_types & 4/*FILE_REFERENCE*/) &&
1169 selectnode.one('.fp-linktype-4 input').get('checked')) {
f8e74b20 1170 params['usefilereference'] = '1';
99eaca9d
DC
1171 }
1172
3a1e425b 1173 selectnode.addClass('loading');
99eaca9d 1174 this.request({
840912d5
DC
1175 action:'download',
1176 client_id: client_id,
1177 repository_id: repository_id,
1178 'params': params,
a5159b86 1179 onerror: function(id, obj, args) {
3a1e425b 1180 selectnode.removeClass('loading');
b5e7b638 1181 scope.selectui.hide();
a5159b86 1182 },
840912d5 1183 callback: function(id, obj, args) {
3a1e425b 1184 selectnode.removeClass('loading');
16dfd717
MG
1185 if (obj.event == 'fileexists') {
1186 scope.process_existing_file(obj);
1187 return;
1188 }
e0b85db4 1189 if (scope.options.editor_target && scope.options.env=='editor') {
840912d5
DC
1190 scope.options.editor_target.value=obj.url;
1191 scope.options.editor_target.onchange();
1192 }
1193 scope.hide();
1194 obj.client_id = client_id;
dd1f051e 1195 var formcallback_scope = args.scope.options.magicscope ? args.scope.options.magicscope : args.scope;
840912d5
DC
1196 scope.options.formcallback.apply(formcallback_scope, [obj]);
1197 }
b5e7b638 1198 }, false);
99eaca9d 1199 }, this);
b5e7b638 1200 var elform = selectnode.one('form');
3a1e425b
MG
1201 elform.appendChild(Y.Node.create('<input/>').
1202 setAttrs({type:'hidden',id:'filesource-'+client_id}));
e0b85db4
DC
1203 elform.on('keydown', function(e) {
1204 if (e.keyCode == 13) {
1205 getfile.simulate('click');
8cbef19e 1206 e.preventDefault();
e0b85db4
DC
1207 }
1208 }, this);
b92241f2 1209 var cancel = selectnode.one('.fp-select-cancel');
99eaca9d 1210 cancel.on('click', function(e) {
b5e7b638
MG
1211 e.preventDefault();
1212 this.selectui.hide();
99eaca9d 1213 }, this);
99eaca9d 1214 },
b5e7b638 1215 wait: function() {
2e7ce603
SH
1216 // First check there isn't already an interval in play, and if there is kill it now.
1217 if (this.waitinterval != null) {
1218 clearInterval(this.waitinterval);
1219 }
1220 // Prepare the root node we will set content for and the loading template we want to display as a YUI node.
1221 var root = this.fpnode.one('.fp-content');
9d7d2b03 1222 var content = Y.Node.create(M.core_filepicker.templates.loading).addClass('fp-content-hidden').setStyle('opacity', 0);
2e7ce603
SH
1223 var count = 0;
1224 // Initiate an interval, we will have a count which will increment every 100 milliseconds.
1225 // Count 0 - the loading icon will have visibility set to hidden (invisible) and have an opacity of 0 (invisible also)
1226 // Count 5 - the visiblity will be switched to visible but opacity will still be at 0 (inivisible)
1227 // Counts 6 - 15 opacity will be increased by 0.1 making the loading icon visible over the period of a second
1228 // Count 16 - The interval will be cancelled.
1229 var interval = setInterval(function(){
1230 if (!content || !root.contains(content) || count >= 15) {
1231 clearInterval(interval);
1232 return true;
1233 }
1234 if (count == 5) {
9d7d2b03 1235 content.removeClass('fp-content-hidden');
2e7ce603
SH
1236 } else if (count > 5) {
1237 var opacity = parseFloat(content.getStyle('opacity'));
1238 content.setStyle('opacity', opacity + 0.1);
1239 }
1240 count++;
1241 return false;
1242 }, 100);
1243 // Store the wait interval so that we can check it in the future.
1244 this.waitinterval = interval;
1245 // Set the content to the loading template.
1246 root.setContent(content);
b5e7b638
MG
1247 },
1248 viewbar_set_enabled: function(mode) {
1249 var viewbar = this.fpnode.one('.fp-viewbar')
1250 if (viewbar) {
1251 if (mode) {
1252 viewbar.addClass('enabled').removeClass('disabled')
1253 } else {
1254 viewbar.removeClass('enabled').addClass('disabled')
1255 }
99eaca9d 1256 }
b5e7b638
MG
1257 this.fpnode.all('.fp-vb-icons,.fp-vb-tree,.fp-vb-details').removeClass('checked')
1258 var modes = {1:'icons', 2:'tree', 3:'details'};
1259 this.fpnode.all('.fp-vb-'+modes[this.viewmode]).addClass('checked');
1260 },
1261 viewbar_clicked: function(e) {
1262 e.preventDefault();
1263 var viewbar = this.fpnode.one('.fp-viewbar')
1264 if (!viewbar || !viewbar.hasClass('disabled')) {
1265 if (e.currentTarget.hasClass('fp-vb-tree')) {
1266 this.viewmode = 2;
1267 } else if (e.currentTarget.hasClass('fp-vb-details')) {
1268 this.viewmode = 3;
1269 } else {
1270 this.viewmode = 1;
1271 }
1272 this.viewbar_set_enabled(true)
1273 this.view_files();
837eef2e 1274 this.set_preference('recentviewmode', this.viewmode);
99eaca9d
DC
1275 }
1276 },
1277 render: function() {
1278 var client_id = this.options.client_id;
5e117466 1279 this.fpnode = Y.Node.createWithFilesSkin(M.core_filepicker.templates.generallayout).
b92241f2 1280 set('id', 'filepicker-'+client_id);
b5e7b638
MG
1281 this.mainui = new Y.Panel({
1282 srcNode : this.fpnode,
1283 headerContent: M.str.repository.filepicker,
e13b330d 1284 zIndex : 5000,
b5e7b638
MG
1285 centered : true,
1286 modal : true,
1287 visible : false,
e88d5641
BR
1288 minWidth : this.fpnode.getStylePx('minWidth'),
1289 minHeight : this.fpnode.getStylePx('minHeight'),
1290 maxWidth : this.fpnode.getStylePx('maxWidth'),
1291 maxHeight : this.fpnode.getStylePx('maxHeight'),
b92241f2 1292 render : true
99eaca9d 1293 });
b92241f2 1294 // allow to move the panel dragging it by it's header:
55089a9d 1295 this.mainui.plug(Y.Plugin.Drag,{handles:['#filepicker-'+client_id+' .yui3-widget-hd']});
b5e7b638 1296 this.mainui.show();
6a0d7194
DP
1297 if (this.mainui.get('y') < 0) {
1298 this.mainui.set('y', 0);
1299 }
b92241f2 1300 // create panel for selecting a file (initially hidden)
5e117466 1301 this.selectnode = Y.Node.createWithFilesSkin(M.core_filepicker.templates.selectlayout).
55089a9d 1302 set('id', 'filepicker-select-'+client_id);
b5e7b638 1303 this.selectui = new Y.Panel({
55089a9d 1304 srcNode : this.selectnode,
e13b330d 1305 zIndex : 6000,
b5e7b638
MG
1306 centered : true,
1307 modal : true,
1308 close : true,
1309 render : true
99eaca9d 1310 });
55089a9d
MG
1311 // allow to move the panel dragging it by it's header:
1312 this.selectui.plug(Y.Plugin.Drag,{handles:['#filepicker-select-'+client_id+' .yui3-widget-hd']});
b5e7b638 1313 this.selectui.hide();
ce3eeb98
MG
1314 // event handler for lazy loading of thumbnails and next page
1315 this.fpnode.one('.fp-content').on(['scroll','resize'], this.content_scrolled, this);
b5e7b638
MG
1316 // save template for one path element and location of path bar
1317 if (this.fpnode.one('.fp-path-folder')) {
1318 this.pathnode = this.fpnode.one('.fp-path-folder');
1319 this.pathbar = this.pathnode.get('parentNode');
1320 this.pathbar.removeChild(this.pathnode);
1321 }
1322 // assign callbacks for view mode switch buttons
1323 this.fpnode.all('.fp-vb-icons,.fp-vb-tree,.fp-vb-details').
1324 on('click', this.viewbar_clicked, this);
1325 // assign callbacks for toolbar links
1326 this.setup_toolbar();
1327 this.setup_select_file();
3a1e425b 1328 this.hide_header();
934291d6 1329
99eaca9d 1330 // processing repository listing
b5e7b638 1331 // Resort the repositories by sortorder
6a0d7194 1332 var sorted_repositories = [];
b5e7b638 1333 for (var i in this.options.repositories) {
6a0d7194 1334 sorted_repositories[i] = this.options.repositories[i];
b5e7b638 1335 }
6a0d7194 1336 sorted_repositories.sort(function(a,b){return a.sortorder-b.sortorder});
b5e7b638
MG
1337 // extract one repository template and repeat it for all repositories available,
1338 // set name and icon and assign callbacks
1339 var reponode = this.fpnode.one('.fp-repo');
1340 if (reponode) {
1341 var list = reponode.get('parentNode');
1342 list.removeChild(reponode);
1343 for (i in sorted_repositories) {
6a0d7194 1344 var repository = sorted_repositories[i];
b5e7b638
MG
1345 var node = reponode.cloneNode(true);
1346 list.appendChild(node);
1347 node.
1348 set('id', 'fp-repo-'+client_id+'-'+repository.id).
1349 on('click', function(e, repository_id) {
1350 e.preventDefault();
837eef2e 1351 this.set_preference('recentrepository', repository_id);
b5e7b638
MG
1352 this.hide_header();
1353 this.list({'repo_id':repository_id});
1354 }, this /*handler running scope*/, repository.id/*second argument of handler*/);
6a0d7194
DP
1355 node.one('.fp-repo-name').setContent(repository.name);
1356 node.one('.fp-repo-icon').set('src', repository.icon);
1357 if (i==0) {
1358 node.addClass('first');
1359 }
1360 if (i==sorted_repositories.length-1) {
1361 node.addClass('last');
1362 }
1363 if (i%2) {
1364 node.addClass('even');
1365 } else {
1366 node.addClass('odd');
1367 }
99eaca9d 1368 }
b5e7b638
MG
1369 }
1370 // display error if no repositories found
1371 if (sorted_repositories.length==0) {
3a1e425b 1372 this.display_error(M.str.repository.norepositoriesavailable, 'norepositoriesavailable')
b5e7b638
MG
1373 }
1374 // display repository that was used last time
1375 this.show_recent_repository();
99eaca9d 1376 },
7ccf18a6
MG
1377 parse_repository_options: function(data, appendtolist) {
1378 if (appendtolist) {
1379 if (data.list) {
6a0d7194
DP
1380 if (!this.filelist) {
1381 this.filelist = [];
1382 }
7ccf18a6
MG
1383 for (var i in data.list) {
1384 this.filelist[this.filelist.length] = data.list[i];
1385 }
1386 }
1387 } else {
1388 this.filelist = data.list?data.list:null;
ce3eeb98 1389 this.lazyloading = {};
7ccf18a6 1390 }
99eaca9d 1391 this.filepath = data.path?data.path:null;
5cf44c1f 1392 this.objecttag = data.object?data.object:null;
99eaca9d 1393 this.active_repo = {};
6a0d7194 1394 this.active_repo.issearchresult = data.issearchresult ? true : false;
98b15580 1395 this.active_repo.dynload = data.dynload?data.dynload:false;
99eaca9d
DC
1396 this.active_repo.pages = Number(data.pages?data.pages:null);
1397 this.active_repo.page = Number(data.page?data.page:null);
7ccf18a6 1398 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 1399 this.active_repo.id = data.repo_id?data.repo_id:null;
b5e7b638
MG
1400 this.active_repo.nosearch = (data.login || data.nosearch); // this is either login form or 'nosearch' attribute set
1401 this.active_repo.norefresh = (data.login || data.norefresh); // this is either login form or 'norefresh' attribute set
1402 this.active_repo.nologin = (data.login || data.nologin); // this is either login form or 'nologin' attribute is set
fdfb9cbe 1403 this.active_repo.logouttext = data.logouttext?data.logouttext:null;
a3433213
RW
1404 this.active_repo.logouturl = (data.logouturl || '');
1405 this.active_repo.message = (data.message || '');
99eaca9d
DC
1406 this.active_repo.help = data.help?data.help:null;
1407 this.active_repo.manage = data.manage?data.manage:null;
b5e7b638 1408 this.print_header();
99eaca9d
DC
1409 },
1410 print_login: function(data) {
97b151ea 1411 this.parse_repository_options(data);
99eaca9d
DC
1412 var client_id = this.options.client_id;
1413 var repository_id = data.repo_id;
1414 var l = this.logindata = data.login;
1415 var loginurl = '';
3a1e425b 1416 var action = data['login_btn_action'] ? data['login_btn_action'] : 'login';
99eaca9d 1417 var form_id = 'fp-form-'+client_id;
99eaca9d 1418
5ce13292
MG
1419 var loginform_node = Y.Node.create(M.core_filepicker.templates.loginform);
1420 loginform_node.one('form').set('id', form_id);
1421 this.fpnode.one('.fp-content').setContent('').appendChild(loginform_node);
1422 var templates = {
1423 'popup' : loginform_node.one('.fp-login-popup'),
1424 'textarea' : loginform_node.one('.fp-login-textarea'),
1425 'select' : loginform_node.one('.fp-login-select'),
1426 'text' : loginform_node.one('.fp-login-text'),
3a1e425b 1427 'radio' : loginform_node.one('.fp-login-radiogroup'),
5ce13292
MG
1428 'checkbox' : loginform_node.one('.fp-login-checkbox'),
1429 'input' : loginform_node.one('.fp-login-input')
1430 };
1431 var container;
1432 for (var i in templates) {
1433 if (templates[i]) {
1434 container = templates[i].get('parentNode');
6a0d7194 1435 container.removeChild(templates[i]);
5ce13292
MG
1436 }
1437 }
1438
1439 for(var k in l) {
1440 if (templates[l[k].type]) {
1441 var node = templates[l[k].type].cloneNode(true);
1442 } else {
1443 node = templates['input'].cloneNode(true);
1444 }
1445 if (l[k].type == 'popup') {
3a1e425b 1446 // submit button
2f6749f4 1447 loginurl = l[k].url;
3a1e425b
MG
1448 var popupbutton = node.one('button');
1449 popupbutton.on('click', function(e){
1450 M.core_filepicker.active_filepicker = this;
1451 window.open(loginurl, 'repo_auth', 'location=0,status=0,width=500,height=300,scrollbars=yes');
1452 e.preventDefault();
1453 }, this);
1454 loginform_node.one('form').on('keydown', function(e) {
1455 if (e.keyCode == 13) {
1456 popupbutton.simulate('click');
1457 e.preventDefault();
1458 }
1459 }, this);
5ce13292
MG
1460 loginform_node.all('.fp-login-submit').remove();
1461 action = 'popup';
6a0d7194 1462 } else if(l[k].type=='textarea') {
5ce13292 1463 // textarea element
6a0d7194
DP
1464 if (node.one('label')) {
1465 node.one('label').set('for', l[k].id).setContent(l[k].label);
1466 }
3a1e425b 1467 node.one('textarea').setAttrs({id:l[k].id, name:l[k].name});
6a0d7194 1468 } else if(l[k].type=='select') {
5ce13292 1469 // select element
6a0d7194
DP
1470 if (node.one('label')) {
1471 node.one('label').set('for', l[k].id).setContent(l[k].label);
1472 }
3a1e425b 1473 node.one('select').setAttrs({id:l[k].id, name:l[k].name}).setContent('');
5ce13292
MG
1474 for (i in l[k].options) {
1475 node.one('select').appendChild(
1476 Y.Node.create('<option/>').
1477 set('value', l[k].options[i].value).
6a0d7194 1478 setContent(l[k].options[i].label));
5ce13292 1479 }
6a0d7194 1480 } else if(l[k].type=='radio') {
5ce13292 1481 // radio input element
3a1e425b
MG
1482 node.all('label').setContent(l[k].label);
1483 var list = l[k].value.split('|');
1484 var labels = l[k].value_label.split('|');
1485 var radionode = null;
1486 for(var item in list) {
1487 if (radionode == null) {
1488 radionode = node.one('.fp-login-radio');
1489 radionode.one('input').set('checked', 'checked');
1490 } else {
1491 var x = radionode.cloneNode(true);
1492 radionode.insert(x, 'after');
1493 radionode = x;
1494 radionode.one('input').set('checked', '');
1495 }
1496 radionode.one('input').setAttrs({id:''+l[k].id+item, name:l[k].name,
1497 type:l[k].type, value:list[item]});
1498 radionode.all('label').setContent(labels[item]).set('for', ''+l[k].id+item)
1499 }
1500 if (radionode == null) {
1501 node.one('.fp-login-radio').remove();
1502 }
6a0d7194 1503 } else {
5ce13292
MG
1504 // input element
1505 if (node.one('label')) { node.one('label').set('for', l[k].id).setContent(l[k].label) }
1506 node.one('input').
1507 set('type', l[k].type).
1508 set('id', l[k].id).
1509 set('name', l[k].name).
1510 set('value', l[k].value?l[k].value:'')
1511 }
1512 container.appendChild(node);
1513 }
3a1e425b
MG
1514 // custom label text for submit button
1515 if (data['login_btn_label']) {
1516 loginform_node.all('.fp-login-submit').setContent(data['login_btn_label'])
99eaca9d 1517 }
3a1e425b
MG
1518 // register button action for login and search
1519 if (action == 'login' || action == 'search') {
1520 loginform_node.one('.fp-login-submit').on('click', function(e){
5ce13292 1521 e.preventDefault();
b5e7b638 1522 this.hide_header();
99eaca9d 1523 this.request({
3a1e425b
MG
1524 'scope': this,
1525 'action':(action == 'search') ? 'search' : 'signin',
99eaca9d
DC
1526 'path': '',
1527 'client_id': client_id,
1528 'repository_id': repository_id,
3a1e425b 1529 'form': {id:form_id, upload:false, useDisabled:true},
4adecd7b 1530 'callback': this.display_response
99eaca9d
DC
1531 }, true);
1532 }, this);
1533 }
3a1e425b
MG
1534 // if 'Enter' is pressed in the form, simulate the button click
1535 if (loginform_node.one('.fp-login-submit')) {
1536 loginform_node.one('form').on('keydown', function(e) {
1537 if (e.keyCode == 13) {
1538 loginform_node.one('.fp-login-submit').simulate('click')
1539 e.preventDefault();
99eaca9d 1540 }
99eaca9d
DC
1541 }, this);
1542 }
99eaca9d 1543 },
4adecd7b
MG
1544 display_response: function(id, obj, args) {
1545 var scope = args.scope
1546 // highlight the current repository in repositories list
b5e7b638
MG
1547 scope.fpnode.all('.fp-repo.active').removeClass('active');
1548 scope.fpnode.all('#fp-repo-'+scope.options.client_id+'-'+obj.repo_id).addClass('active')
5ce13292
MG
1549 // add class repository_REPTYPE to the filepicker (for repository-specific styles)
1550 for (var i in scope.options.repositories) {
1551 scope.fpnode.removeClass('repository_'+scope.options.repositories[i].type)
1552 }
1553 if (obj.repo_id && scope.options.repositories[obj.repo_id]) {
1554 scope.fpnode.addClass('repository_'+scope.options.repositories[obj.repo_id].type)
1555 }
4adecd7b
MG
1556 // display response
1557 if (obj.login) {
b5e7b638 1558 scope.viewbar_set_enabled(false);
4adecd7b
MG
1559 scope.print_login(obj);
1560 } else if (obj.upload) {
b5e7b638 1561 scope.viewbar_set_enabled(false);
4adecd7b
MG
1562 scope.parse_repository_options(obj);
1563 scope.create_upload_form(obj);
5cf44c1f
MG
1564 } else if (obj.object) {
1565 M.core_filepicker.active_filepicker = scope;
1566 scope.viewbar_set_enabled(false);
1567 scope.parse_repository_options(obj);
1568 scope.create_object_container(obj.object);
4adecd7b 1569 } else if (obj.list) {
b5e7b638 1570 scope.viewbar_set_enabled(true);
4adecd7b
MG
1571 scope.parse_repository_options(obj);
1572 scope.view_files();
99eaca9d 1573 }
99eaca9d
DC
1574 },
1575 list: function(args) {
99eaca9d
DC
1576 if (!args) {
1577 args = {};
1578 }
1579 if (!args.repo_id) {
4adecd7b 1580 args.repo_id = this.active_repo.id;
99eaca9d 1581 }
7dab27b3
FM
1582 if (!args.path) {
1583 args.path = '';
1584 }
1585 this.currentpath = args.path;
4adecd7b
MG
1586 this.request({
1587 action: 'list',
1588 client_id: this.options.client_id,
99eaca9d 1589 repository_id: args.repo_id,
4adecd7b
MG
1590 path: args.path,
1591 page: args.page,
1592 scope: this,
1593 callback: this.display_response
99eaca9d
DC
1594 }, true);
1595 },
b5e7b638
MG
1596 populate_licenses_select: function(node) {
1597 if (!node) {
1598 return;
e35194be 1599 }
b5e7b638 1600 node.setContent('');
1dce6261 1601 var licenses = this.options.licenses;
837eef2e 1602 var recentlicense = this.get_preference('recentlicense');
a756cb37
DC
1603 if (recentlicense) {
1604 this.options.defaultlicense=recentlicense;
1605 }
1dce6261 1606 for (var i in licenses) {
b5e7b638
MG
1607 var option = Y.Node.create('<option/>').
1608 set('selected', (this.options.defaultlicense==licenses[i].shortname)).
1609 set('value', licenses[i].shortname).
1610 setContent(licenses[i].fullname);
1611 node.appendChild(option)
1dce6261 1612 }
b5e7b638 1613 },
5cf44c1f
MG
1614 set_selected_license: function(node, value) {
1615 var licenseset = false;
1616 node.all('option').each(function(el) {
1617 if (el.get('value')==value || el.getContent()==value) {
1618 el.set('selected', true);
1619 licenseset = true;
1620 }
1621 });
1622 if (!licenseset) {
1623 // we did not find the value in the list
837eef2e 1624 var recentlicense = this.get_preference('recentlicense');
5cf44c1f
MG
1625 node.all('option[selected]').set('selected', false);
1626 node.all('option[value='+recentlicense+']').set('selected', true);
1627 }
1628 },
1629 create_object_container: function(data) {
1630 var content = this.fpnode.one('.fp-content');
1631 content.setContent('');
1632 //var str = '<object data="'+data.src+'" type="'+data.type+'" width="98%" height="98%" id="container_object" class="fp-object-container mdl-align"></object>';
1633 var container = Y.Node.create('<object/>').
1634 setAttrs({data:data.src, type:data.type, id:'container_object'}).
1635 addClass('fp-object-container');
1636 content.setContent('').appendChild(container);
1637 },
b5e7b638
MG
1638 create_upload_form: function(data) {
1639 var client_id = this.options.client_id;
1640 var id = data.upload.id+'_'+client_id;
b92241f2 1641 var content = this.fpnode.one('.fp-content');
ec3eaa2c
PN
1642 var template_name = 'uploadform_'+this.options.repositories[data.repo_id].type;
1643 var template = M.core_filepicker.templates[template_name] || M.core_filepicker.templates['uploadform'];
1644 content.setContent(template);
b5e7b638 1645
b92241f2
MG
1646 content.all('.fp-file,.fp-saveas,.fp-setauthor,.fp-setlicense').each(function (node) {
1647 node.all('label').set('for', node.one('input,select').generateID());
1648 });
1649 content.one('form').set('id', id);
1650 content.one('.fp-file input').set('name', 'repo_upload_file');
6133c2ea
MG
1651 if (data.upload.label && content.one('.fp-file label')) {
1652 content.one('.fp-file label').setContent(data.upload.label);
1653 }
b92241f2
MG
1654 content.one('.fp-saveas input').set('name', 'title');
1655 content.one('.fp-setauthor input').setAttrs({name:'author', value:this.options.author});
1656 content.one('.fp-setlicense select').set('name', 'license');
1657 this.populate_licenses_select(content.one('.fp-setlicense select'))
1658 // append hidden inputs to the upload form
1659 content.one('form').appendChild(Y.Node.create('<input/>').
3a1e425b 1660 setAttrs({type:'hidden',name:'itemid',value:this.options.itemid}));
b5e7b638
MG
1661 var types = this.options.accepted_types;
1662 for (var i in types) {
b92241f2 1663 content.one('form').appendChild(Y.Node.create('<input/>').
3a1e425b 1664 setAttrs({type:'hidden',name:'accepted_types[]',value:types[i]}));
b5e7b638
MG
1665 }
1666
99eaca9d 1667 var scope = this;
b92241f2 1668 content.one('.fp-upload-btn').on('click', function(e) {
8cbef19e 1669 e.preventDefault();
b92241f2 1670 var license = content.one('.fp-setlicense select');
837eef2e
DP
1671
1672 this.set_preference('recentlicense', license.get('value'));
b92241f2 1673 if (!content.one('.fp-file input').get('value')) {
ce6297d2 1674 scope.print_msg(M.str.repository.nofilesattached, 'error');
2a03b97b
DC
1675 return false;
1676 }
b5e7b638 1677 this.hide_header();
9d753c38
PS
1678 scope.request({
1679 scope: scope,
1680 action:'upload',
1681 client_id: client_id,
1682 params: {'savepath':scope.options.savepath},
1683 repository_id: scope.active_repo.id,
1684 form: {id: id, upload:true},
a5159b86
MG
1685 onerror: function(id, o, args) {
1686 scope.create_upload_form(data);
1687 },
9d753c38 1688 callback: function(id, o, args) {
dd1f051e
MG
1689 if (o.event == 'fileexists') {
1690 scope.create_upload_form(data);
1691 scope.process_existing_file(o);
1692 return;
1693 }
9d753c38
PS
1694 if (scope.options.editor_target&&scope.options.env=='editor') {
1695 scope.options.editor_target.value=o.url;
1696 scope.options.editor_target.onchange();
0c4edaa2 1697 }
9d753c38
PS
1698 scope.hide();
1699 o.client_id = client_id;
dd1f051e 1700 var formcallback_scope = args.scope.options.magicscope ? args.scope.options.magicscope : args.scope;
9d753c38
PS
1701 scope.options.formcallback.apply(formcallback_scope, [o]);
1702 }
1703 }, true);
99eaca9d
DC
1704 }, this);
1705 },
b5e7b638
MG
1706 /** setting handlers and labels for elements in toolbar. Called once during the initial render of filepicker */
1707 setup_toolbar: function() {
99eaca9d 1708 var client_id = this.options.client_id;
b92241f2
MG
1709 var toolbar = this.fpnode.one('.fp-toolbar');
1710 toolbar.one('.fp-tb-logout').one('a,button').on('click', function(e) {
b5e7b638
MG
1711 e.preventDefault();
1712 if (!this.active_repo.nologin) {
1713 this.hide_header();
1714 this.request({
1715 action:'logout',
1716 client_id: this.options.client_id,
1717 repository_id: this.active_repo.id,
1718 path:'',
1719 callback: this.display_response
1720 }, true);
1721 }
a3433213
RW
1722 if (this.active_repo.logouturl) {
1723 window.open(this.active_repo.logouturl, 'repo_auth', 'location=0,status=0,width=500,height=300,scrollbars=yes');
1724 }
b5e7b638 1725 }, this);
b92241f2 1726 toolbar.one('.fp-tb-refresh').one('a,button').on('click', function(e) {
b5e7b638
MG
1727 e.preventDefault();
1728 if (!this.active_repo.norefresh) {
7dab27b3 1729 this.list({ path: this.currentpath });
b5e7b638
MG
1730 }
1731 }, this);
b92241f2 1732 toolbar.one('.fp-tb-search form').
b5e7b638 1733 set('method', 'POST').
b92241f2 1734 set('id', 'fp-tb-search-'+client_id).
b5e7b638 1735 on('submit', function(e) {
4adecd7b 1736 e.preventDefault();
b5e7b638
MG
1737 if (!this.active_repo.nosearch) {
1738 this.request({
1739 scope: this,
1740 action:'search',
1741 client_id: this.options.client_id,
1742 repository_id: this.active_repo.id,
1743 form: {id: 'fp-tb-search-'+client_id, upload:false, useDisabled:true},
1744 callback: this.display_response
1745 }, true);
1746 }
a3433213 1747 }, this);
99eaca9d 1748
b92241f2 1749 // it does not matter what kind of element is .fp-tb-manage, we create a dummy <a>
b5e7b638 1750 // element and use it to open url on click event
3a1e425b
MG
1751 var managelnk = Y.Node.create('<a/>').
1752 setAttrs({id:'fp-tb-manage-'+client_id+'-link', target:'_blank'}).
1753 setStyle('display', 'none');
b92241f2
MG
1754 toolbar.append(managelnk);
1755 toolbar.one('.fp-tb-manage').one('a,button').
1756 on('click', function(e) {
1757 e.preventDefault();
1758 managelnk.simulate('click')
1759 });
99eaca9d 1760
b92241f2 1761 // same with .fp-tb-help
3a1e425b
MG
1762 var helplnk = Y.Node.create('<a/>').
1763 setAttrs({id:'fp-tb-help-'+client_id+'-link', target:'_blank'}).
1764 setStyle('display', 'none');
b92241f2 1765 toolbar.append(helplnk);
0c2fe3aa 1766 toolbar.one('.fp-tb-help').one('a,button').
b92241f2
MG
1767 on('click', function(e) {
1768 e.preventDefault();
1769 helplnk.simulate('click')
1770 });
b5e7b638
MG
1771 },
1772 hide_header: function() {
b92241f2
MG
1773 if (this.fpnode.one('.fp-toolbar')) {
1774 this.fpnode.one('.fp-toolbar').addClass('empty');
b5e7b638 1775 }
3a1e425b
MG
1776 if (this.pathbar) {
1777 this.pathbar.setContent('').addClass('empty');
1778 }
b5e7b638
MG
1779 },
1780 print_header: function() {
1781 var r = this.active_repo;
1782 var scope = this;
1783 var client_id = this.options.client_id;
2f6749f4 1784 this.hide_header();
b92241f2
MG
1785 this.print_path();
1786 var toolbar = this.fpnode.one('.fp-toolbar');
1787 if (!toolbar) { return; }
99eaca9d 1788
b92241f2
MG
1789 var enable_tb_control = function(node, enabled) {
1790 if (!node) { return; }
1791 node.addClassIf('disabled', !enabled).addClassIf('enabled', enabled)
1792 if (enabled) {
1793 toolbar.removeClass('empty');
b5e7b638
MG
1794 }
1795 }
99eaca9d 1796
b5e7b638 1797 // TODO 'back' permanently disabled for now. Note, flickr_public uses 'Logout' for it!
b92241f2 1798 enable_tb_control(toolbar.one('.fp-tb-back'), false);
99eaca9d 1799
b5e7b638 1800 // search form
b92241f2 1801 enable_tb_control(toolbar.one('.fp-tb-search'), !r.nosearch);
b5e7b638 1802 if(!r.nosearch) {
b92241f2
MG
1803 var searchform = toolbar.one('.fp-tb-search form');
1804 searchform.setContent('');
b5e7b638
MG
1805 this.request({
1806 scope: this,
1807 action:'searchform',
1808 repository_id: this.active_repo.id,
1809 callback: function(id, obj, args) {
1810 if (obj.repo_id == scope.active_repo.id && obj.form) {
1811 // if we did not jump to another repository meanwhile
b92241f2 1812 searchform.setContent(obj.form);
d01ebb94
RT
1813 // Highlight search text when user click for search.
1814 var searchnode = searchform.one('input[name="s"]');
1815 if (searchnode) {
1816 searchnode.once('click', function(e) {
1817 e.preventDefault();
1818 this.select();
1819 });
1820 }
99eaca9d 1821 }
b5e7b638
MG
1822 }
1823 }, false);
99eaca9d 1824 }
b5e7b638
MG
1825
1826 // refresh button
99eaca9d 1827 // weather we use cache for this instance, this button will reload listing anyway
b92241f2 1828 enable_tb_control(toolbar.one('.fp-tb-refresh'), !r.norefresh);
b5e7b638
MG
1829
1830 // login button
b92241f2 1831 enable_tb_control(toolbar.one('.fp-tb-logout'), !r.nologin);
6a0d7194
DP
1832 if (!r.nologin) {
1833 var label = r.logouttext ? r.logouttext : M.str.repository.logout;
b92241f2 1834 toolbar.one('.fp-tb-logout').one('a,button').setContent(label)
99eaca9d
DC
1835 }
1836
b5e7b638 1837 // manage url
b92241f2 1838 enable_tb_control(toolbar.one('.fp-tb-manage'), r.manage);
b5e7b638
MG
1839 Y.one('#fp-tb-manage-'+client_id+'-link').set('href', r.manage);
1840
1841 // help url
b92241f2 1842 enable_tb_control(toolbar.one('.fp-tb-help'), r.help);
b5e7b638 1843 Y.one('#fp-tb-help-'+client_id+'-link').set('href', r.help);
a3433213
RW
1844
1845 // message
1846 enable_tb_control(toolbar.one('.fp-tb-message'), r.message);
1847 toolbar.one('.fp-tb-message').setContent(r.message);
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};