MDL-31901: moved filepicker html to files/renderer.php, pass templates once per page
[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
b5e7b638
MG
11 * this.selectui, YUI Panel for selecting particular file
12 * this.msg_dlg, YUI Panel for error or info message
13 * this.process_dlg, YUI Panel for processing existing filename
99eaca9d 14 * this.treeview, YUI Treeview
99eaca9d 15 * this.viewmode, store current view mode
b5e7b638
MG
16 * this.pathbar, reference to the Node with path bar
17 * this.pathnode, a Node element representing one folder in a path bar (not attached anywhere, just used for template)
99eaca9d
DC
18 *
19 * Filepicker options:
20 * =====
99eaca9d
DC
21 * this.options.client_id, the instance id
22 * this.options.contextid
23 * this.options.itemid
24 * this.options.repositories, stores all repositories displaied in file picker
25 * this.options.formcallback
26 *
27 * Active repository options
28 * =====
29 * this.active_repo.id
30 * this.active_repo.nosearch
31 * this.active_repo.norefresh
32 * this.active_repo.nologin
33 * this.active_repo.help
34 * this.active_repo.manage
8cbef19e 35 *
99eaca9d
DC
36 * Server responses
37 * =====
38 * this.filelist, cached filelist
39 * this.pages
40 * this.page
41 * this.filepath, current path
42 * this.logindata, cached login form
43 */
44
4c508047 45M.core_filepicker = M.core_filepicker || {};
99eaca9d 46
4c508047
PS
47/**
48 * instances of file pickers used on page
49 */
50M.core_filepicker.instances = M.core_filepicker.instances || {};
539d4041 51M.core_filepicker.active_filepicker = null;
4c508047 52
b5e7b638
MG
53/**
54 * HTML Templates to use in FilePicker
55 */
56M.core_filepicker.templates = M.core_filepicker.templates || {};
57
4c508047
PS
58/**
59 * Init and show file picker
60 */
61M.core_filepicker.show = function(Y, options) {
62 if (!M.core_filepicker.instances[options.client_id]) {
8cbef19e 63 M.core_filepicker.init(Y, options);
99eaca9d 64 }
4c508047
PS
65 M.core_filepicker.instances[options.client_id].show();
66};
67
d1d18691
MG
68M.core_filepicker.set_templates = function(Y, templates) {
69 for (var templid in templates) {
70 M.core_filepicker.templates[templid] = templates[templid];
71 }
72}
b92241f2 73
4c508047
PS
74/**
75 * Add new file picker to current instances
76 */
77M.core_filepicker.init = function(Y, options) {
b92241f2
MG
78 /** help function to extract width/height style as a number, not as a string */
79 Y.Node.prototype.getStylePx = function(attr) {
80 var style = this.getStyle(attr);
81 if (''+style == '0' || ''+style == '0px') {
82 return 0;
83 }
84 var matches = style.match(/^([\d\.]+)px$/)
85 if (matches && parseFloat(matches[1])) {
86 return parseFloat(matches[1]);
87 }
88 return null;
89 }
90
91 /** if condition is met, the class is added to the node, otherwise - removed */
92 Y.Node.prototype.addClassIf = function(className, condition) {
93 if (condition) {
94 this.addClass(className);
95 } else {
96 this.removeClass(className);
97 }
98 return this;
99 }
100
ce3eeb98
MG
101 /** sets the width(height) of the node considering existing minWidth(minHeight) */
102 Y.Node.prototype.setStyleAdv = function(stylename, value) {
103 var stylenameCap = stylename.substr(0,1).toUpperCase() + stylename.substr(1, stylename.length-1).toLowerCase();
104 this.setStyle(stylename, '' + Math.max(value, this.getStylePx('min'+stylenameCap)) + 'px')
105 return this;
106 }
107
4c508047
PS
108 var FilePickerHelper = function(options) {
109 FilePickerHelper.superclass.constructor.apply(this, arguments);
8cbef19e 110 };
4c508047
PS
111
112 FilePickerHelper.NAME = "FilePickerHelper";
113 FilePickerHelper.ATTRS = {
99eaca9d
DC
114 options: {},
115 lang: {}
116 };
4c508047
PS
117
118 Y.extend(FilePickerHelper, Y.Base, {
9598d578 119 api: M.cfg.wwwroot+'/repository/repository_ajax.php',
7f9358fc 120 cached_responses: {},
4c508047
PS
121
122 initializer: function(options) {
123 this.options = options;
392d5fd4
DC
124 if (!this.options.savepath) {
125 this.options.savepath = '/';
126 }
99eaca9d 127 },
4c508047 128
99eaca9d
DC
129 destructor: function() {
130 },
4c508047 131
99eaca9d 132 request: function(args, redraw) {
3a1e425b 133 var api = (args.api?args.api:this.api) + '?action='+args.action;
99eaca9d 134 var params = {};
3a1e425b 135 var scope = args['scope']?args['scope']:this;
99eaca9d
DC
136 params['repo_id']=args.repository_id;
137 params['p'] = args.path?args.path:'';
138 params['page'] = args.page?args.page:'';
139 params['env']=this.options.env;
140 // the form element only accept certain file types
141 params['accepted_types']=this.options.accepted_types;
e35194be 142 params['sesskey'] = M.cfg.sesskey;
99eaca9d 143 params['client_id'] = args.client_id;
0c4edaa2 144 params['itemid'] = this.options.itemid?this.options.itemid:0;
8a3e6a56 145 params['maxbytes'] = this.options.maxbytes?this.options.maxbytes:-1;
be85f7ab
DC
146 if (this.options.context && this.options.context.id) {
147 params['ctx_id'] = this.options.context.id;
148 }
99eaca9d
DC
149 if (args['params']) {
150 for (i in args['params']) {
151 params[i] = args['params'][i];
152 }
153 }
64654e78
DC
154 if (args.action == 'upload') {
155 var list = [];
156 for(var k in params) {
157 var value = params[k];
158 if(value instanceof Array) {
159 for(var i in value) {
160 list.push(k+'[]='+value[i]);
161 }
162 } else {
163 list.push(k+'='+value);
164 }
165 }
166 params = list.join('&');
167 } else {
168 params = build_querystring(params);
169 }
99eaca9d
DC
170 var cfg = {
171 method: 'POST',
172 on: {
173 complete: function(id,o,p) {
174 if (!o) {
b5e7b638 175 // TODO
99eaca9d
DC
176 alert('IO FATAL');
177 return;
178 }
4c508047
PS
179 var data = null;
180 try {
181 data = Y.JSON.parse(o.responseText);
182 } catch(e) {
879b4f9a 183 scope.print_msg(M.str.repository.invalidjson, 'error');
b5e7b638 184 scope.display_error(M.str.repository.invalidjson+'<pre>'+stripHTML(o.responseText)+'</pre>', 'invalidjson')
c26855ff 185 return;
4c508047 186 }
1dce6261 187 // error checking
e35194be
DC
188 if (data && data.error) {
189 scope.print_msg(data.error, 'error');
a5159b86
MG
190 if (args.onerror) {
191 args.onerror(id,data,p);
192 } else {
3a1e425b 193 this.fpnode.one('.fp-content').setContent('');
a5159b86 194 }
1dce6261 195 return;
f392caba
DC
196 } else if (data && data.event) {
197 switch (data.event) {
198 case 'fileexists':
199 scope.process_existing_file(data);
200 break;
201 default:
202 break;
203 }
1dce6261 204 } else {
879b4f9a
DC
205 if (data.msg) {
206 scope.print_msg(data.msg, 'info');
207 }
7f9358fc
MG
208 // cache result if applicable
209 if (args.action != 'upload' && data.allowcaching) {
210 scope.cached_responses[params] = data;
211 }
212 // invoke callback
1dce6261
DC
213 args.callback(id,data,p);
214 }
99eaca9d
DC
215 }
216 },
217 arguments: {
218 scope: scope
219 },
220 headers: {
bd2db41a 221 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
99eaca9d 222 },
64654e78 223 data: params,
4c508047 224 context: this
99eaca9d
DC
225 };
226 if (args.form) {
227 cfg.form = args.form;
228 }
7f9358fc
MG
229 // check if result of the same request has been already cached. If not, request it
230 // (never applicable in case of form submission and/or upload action):
231 if (!args.form && args.action != 'upload' && scope.cached_responses[params]) {
232 args.callback(null, scope.cached_responses[params], {scope: scope})
233 } else {
234 Y.io(api, cfg);
235 if (redraw) {
b5e7b638 236 this.wait();
7f9358fc 237 }
99eaca9d
DC
238 }
239 },
b5e7b638 240 /** displays the dialog and processes rename/overwrite if there is a file with the same name in the same filearea*/
f392caba
DC
241 process_existing_file: function(data) {
242 var scope = this;
b5e7b638 243 var handleOverwrite = function(e) {
f392caba 244 // overwrite
b5e7b638
MG
245 e.preventDefault();
246 var data = this.process_dlg.dialogdata;
f392caba
DC
247 var params = {}
248 params['existingfilename'] = data.existingfile.filename;
249 params['existingfilepath'] = data.existingfile.filepath;
250 params['newfilename'] = data.newfile.filename;
251 params['newfilepath'] = data.newfile.filepath;
b5e7b638
MG
252 this.hide_header();
253 this.request({
f392caba 254 'params': params,
b5e7b638 255 'scope': this,
f392caba
DC
256 'action':'overwrite',
257 'path': '',
b5e7b638
MG
258 'client_id': this.options.client_id,
259 'repository_id': this.active_repo.id,
f392caba 260 'callback': function(id, o, args) {
f392caba
DC
261 scope.hide();
262 // editor needs to update url
263 // filemanager do nothing
c8ad2c12
SH
264 if (scope.options.editor_target && scope.options.env == 'editor') {
265 scope.options.editor_target.value = data.existingfile.url;
f392caba 266 scope.options.editor_target.onchange();
1ae299f5 267 } else if (scope.options.env === 'filepicker') {
b5e7b638 268 var fileinfo = {'client_id':scope.options.client_id,
913b3cb3
JP
269 'url':data.existingfile.url,
270 'file':data.existingfile.filename};
271 scope.options.formcallback.apply(scope, [fileinfo]);
f392caba
DC
272 }
273 }
274 }, true);
275 }
b5e7b638
MG
276 var handleRename = function(e) {
277 // inserts file with the new name
278 e.preventDefault();
279 var scope = this;
280 var data = this.process_dlg.dialogdata;
c8ad2c12
SH
281 if (scope.options.editor_target && scope.options.env == 'editor') {
282 scope.options.editor_target.value = data.newfile.url;
f392caba
DC
283 scope.options.editor_target.onchange();
284 }
f392caba 285 scope.hide();
f392caba
DC
286 var formcallback_scope = null;
287 if (scope.options.magicscope) {
288 formcallback_scope = scope.options.magicscope;
289 } else {
290 formcallback_scope = scope;
291 }
b5e7b638 292 var fileinfo = {'client_id':scope.options.client_id,
794cc7e1
JP
293 'url':data.newfile.url,
294 'file':data.newfile.filename};
295 scope.options.formcallback.apply(formcallback_scope, [fileinfo]);
f392caba 296 }
b5e7b638 297 var handleCancel = function(e) {
f392caba 298 // Delete tmp file
b5e7b638 299 e.preventDefault();
f392caba 300 var params = {};
b5e7b638
MG
301 params['newfilename'] = this.process_dlg.dialogdata.newfile.filename;
302 params['newfilepath'] = this.process_dlg.dialogdata.newfile.filepath;
303 this.request({
f392caba 304 'params': params,
b5e7b638 305 'scope': this,
f392caba
DC
306 'action':'deletetmpfile',
307 'path': '',
b5e7b638
MG
308 'client_id': this.options.client_id,
309 'repository_id': this.active_repo.id,
f392caba 310 'callback': function(id, o, args) {
b5e7b638 311 // let it be in background, from user point of view nothing is happenning
f392caba 312 }
b5e7b638
MG
313 }, false);
314 this.process_dlg.hide();
315 this.selectui.hide();
f392caba 316 }
b5e7b638
MG
317 if (!this.process_dlg) {
318 var node = Y.Node.create(M.core_filepicker.templates.processexistingfile);
319 this.fpnode.appendChild(node);
320 this.process_dlg = new Y.Panel({
321 srcNode : node,
322 headerContent: M.str.repository.fileexistsdialogheader,
323 zIndex : 800000,
324 centered : true,
325 modal : true,
326 visible : false,
327 render : true,
328 buttons : {}
329 });
330 node.one('.fp-dlg-butoverwrite').on('click', handleOverwrite, this);
331 node.one('.fp-dlg-butrename').on('click', handleRename, this);
332 node.one('.fp-dlg-butcancel').on('click', handleCancel, this);
333 if (this.options.env == 'editor') {
334 node.one('.fp-dlg-text').setContent(M.str.repository.fileexistsdialog_editor);
335 } else {
336 node.one('.fp-dlg-text').setContent(M.str.repository.fileexistsdialog_filemanager);
337 }
f392caba 338 }
3a1e425b 339 this.fpnode.one('.fp-select').removeClass('loading');
b5e7b638
MG
340 this.process_dlg.dialogdata = data;
341 this.fpnode.one('.fp-dlg .fp-dlg-butrename').setContent(M.util.get_string('renameto', 'repository', data.newfile.filename));
342 this.process_dlg.show();
343 },
344 /** displays error instead of filepicker contents */
345 display_error: function(errortext, errorcode) {
346 this.fpnode.one('.fp-content').setContent(M.core_filepicker.templates.error);
347 this.fpnode.one('.fp-content .fp-error').
348 addClass(errorcode).
349 setContent(errortext);
f392caba 350 },
b5e7b638 351 /** displays message in a popup */
879b4f9a 352 print_msg: function(msg, type) {
b5e7b638
MG
353 var header = M.str.moodle.error;
354 if (type != 'error') {
355 type = 'info'; // one of only two types excepted
356 header = M.str.moodle.info;
879b4f9a
DC
357 }
358 if (!this.msg_dlg) {
b5e7b638
MG
359 var node = Y.Node.create(M.core_filepicker.templates.message);
360 this.fpnode.appendChild(node);
361
362 this.msg_dlg = new Y.Panel({
363 srcNode : node,
364 zIndex : 800000,
365 centered : true,
366 modal : true,
367 visible : false,
368 render : true
369 });
370 node.one('.fp-msg-butok').on('click', function(e) {
371 e.preventDefault();
372 this.msg_dlg.hide();
373 }, this);
879b4f9a 374 }
b5e7b638
MG
375
376 this.msg_dlg.set('headerContent', header);
377 this.fpnode.one('.fp-msg').removeClass('fp-msg-info').removeClass('fp-msg-error').addClass('fp-msg-'+type)
378 this.fpnode.one('.fp-msg .fp-msg-text').setContent(msg);
879b4f9a 379 this.msg_dlg.show();
879b4f9a 380 },
99eaca9d 381 build_tree: function(node, level) {
1fb0173e 382 var dynload = this.active_repo.dynload;
5bdf63cc
MG
383 // prepare file name with icon
384 var el = Y.Node.create('<div/>').setContent(M.core_filepicker.templates.listfilename);
830acea6
MG
385 el.one('.fp-filename').setContent(node.shorttitle ? node.shorttitle : node.title);
386 // TODO add tooltip with node.title or node.thumbnail_title
5bdf63cc
MG
387 if (node.icon && !node.children) {
388 el.one('.fp-icon').appendChild(Y.Node.create('<img/>').set('src', node.icon));
ce3eeb98
MG
389 if (node.realicon) {
390 this.lazyloading[el.one('.fp-icon img').generateID()] = node.realicon;
391 }
5bdf63cc
MG
392 }
393 // create node
394 var tmpNode = new YAHOO.widget.HTMLNode(el.getContent(), level, false);
2f6749f4 395 if (node.dynamicLoadComplete) {
5bdf63cc 396 tmpNode.dynamicLoadComplete = true;
99eaca9d 397 }
5bdf63cc 398 tmpNode.fileinfo = node;
2f6749f4
MG
399 tmpNode.isLeaf = node.children ? false : true;
400 if (!tmpNode.isLeaf) {
99eaca9d
DC
401 if(node.expanded) {
402 tmpNode.expand();
403 }
1fb0173e
DC
404 if (dynload) {
405 tmpNode.scope = this;
406 }
5bdf63cc 407 tmpNode.path = node.path ? node.path : '';
99eaca9d
DC
408 for(var c in node.children) {
409 this.build_tree(node.children[c], tmpNode);
410 }
99eaca9d
DC
411 }
412 },
7ccf18a6 413 view_files: function(appenditems) {
b92241f2
MG
414 this.viewbar_set_enabled(true);
415 this.print_path();
416 if (this.viewmode == 2) {
7ccf18a6 417 this.view_as_list(appenditems);
b92241f2 418 } else if (this.viewmode == 3) {
7ccf18a6 419 this.view_as_table(appenditems);
99eaca9d 420 } else {
7ccf18a6
MG
421 this.view_as_icons(appenditems);
422 }
423 // display/hide the link for requesting next page
424 if (!appenditems && this.active_repo.hasmorepages) {
425 if (!this.fpnode.one('.fp-content .fp-nextpage')) {
426 this.fpnode.one('.fp-content').append(M.core_filepicker.templates.nextpage);
427 }
428 this.fpnode.one('.fp-content .fp-nextpage').one('a,button').on('click', function(e) {
429 e.preventDefault();
430 this.fpnode.one('.fp-content .fp-nextpage').addClass('loading');
431 this.request_next_page();
432 }, this);
433 }
434 if (!this.active_repo.hasmorepages && this.fpnode.one('.fp-content .fp-nextpage')) {
435 this.fpnode.one('.fp-content .fp-nextpage').remove();
436 }
437 if (this.fpnode.one('.fp-content .fp-nextpage')) {
438 this.fpnode.one('.fp-content .fp-nextpage').removeClass('loading');
99eaca9d 439 }
ce3eeb98
MG
440 this.content_scrolled();
441 },
442 content_scrolled: function(e) {
443 setTimeout(Y.bind(function() {
444 if (this.processingimages) {return;}
445 this.processingimages = true;
446 var scope = this,
447 fpcontent = this.fpnode.one('.fp-content'),
448 fpcontenty = fpcontent.getY(),
449 fpcontentheight = fpcontent.getStylePx('height'),
450 nextpage = fpcontent.one('.fp-nextpage'),
451 is_node_visible = function(node) {
452 var offset = node.getY()-fpcontenty;
453 if (offset <= fpcontentheight && (offset >=0 || offset+node.getStylePx('height')>=0)) {
454 return true;
455 }
456 return false;
457 };
458 // automatically load next page when 'more' link becomes visible
459 if (nextpage && !nextpage.hasClass('loading') && is_node_visible(nextpage)) {
460 nextpage.one('a,button').simulate('click');
461 }
462 // replace src for visible images that need to be lazy-loaded
463 if (scope.lazyloading) {
464 fpcontent.all('img').each( function(node) {
465 if (node.get('id') && scope.lazyloading[node.get('id')] && is_node_visible(node)) {
466 node.set('src', scope.lazyloading[node.get('id')]);
467 delete scope.lazyloading[node.get('id')];
468 }
469 });
470 }
471 this.processingimages = false;
472 }, this), 200)
99eaca9d 473 },
1fb0173e
DC
474 treeview_dynload: function(node, cb) {
475 var scope = node.scope;
476 var client_id = scope.options.client_id;
477 var repository_id = scope.active_repo.id;
2f6749f4
MG
478 var retrieved_children = {};
479 if (node.children) {
480 for (var i in node.children) {
481 retrieved_children[node.children[i].path] = node.children[i];
482 }
483 }
1fb0173e
DC
484 scope.request({
485 action:'list',
486 client_id: client_id,
487 repository_id: repository_id,
488 path:node.path?node.path:'',
489 page:node.page?args.page:'',
490 callback: function(id, obj, args) {
1fb0173e 491 var list = obj.list;
2f6749f4
MG
492 // check that user did not leave the view mode before recieving this response
493 if (!(scope.active_repo.id == obj.repo_id && scope.viewmode == 2 && node && node.getChildrenEl())) {
494 return;
495 }
496 if (cb != null) { // (in manual mode do not update current path)
497 scope.viewbar_set_enabled(true);
498 scope.parse_repository_options(obj);
ce3eeb98 499 node.highlight(false);
2f6749f4
MG
500 }
501 node.origlist = obj.list?obj.list:null;
502 node.origpath = obj.path?obj.path:null;
503 node.children = [];
1fb0173e 504 for(k in list) {
2f6749f4
MG
505 if (list[k].children && retrieved_children[list[k].path]) {
506 // if this child is a folder and has already been retrieved
507 node.children[node.children.length] = retrieved_children[list[k].path];
508 } else {
509 scope.build_tree(list[k], node);
510 }
511 }
512 if (cb == null) {
513 node.refresh();
514 } else {
515 // invoke callback requested by TreeView
516 cb();
1fb0173e 517 }
ce3eeb98 518 scope.content_scrolled();
1fb0173e
DC
519 }
520 }, false);
521 },
7ccf18a6
MG
522 /** displays list of files in tree (list) view mode. If param appenditems is specified,
523 * appends those items to the end of the list. Otherwise (default behaviour)
524 * clears the contents and displays the items from this.filelist */
525 view_as_list: function(appenditems) {
1fb0173e 526 var scope = this;
4adecd7b
MG
527 var client_id = scope.options.client_id;
528 var dynload = scope.active_repo.dynload;
529 var list = this.filelist;
4adecd7b 530 scope.viewmode = 2;
7ccf18a6 531 if (appenditems) {
ce3eeb98
MG
532 var parentnode = scope.treeview.getRoot();
533 if (scope.treeview.getHighlightedNode()) {
534 parentnode = scope.treeview.getHighlightedNode();
535 if (parentnode.isLeaf) {parentnode = parentnode.parent;}
536 }
7ccf18a6
MG
537 for (var k in appenditems) {
538 scope.build_tree(appenditems[k], parentnode);
539 }
540 scope.treeview.draw();
541 return;
542 }
5bdf63cc 543 if (!list || list.length==0 && (!this.filepath || !this.filepath.length)) {
b5e7b638 544 this.display_error(M.str.repository.nofilesavailable, 'nofilesavailable');
4adecd7b
MG
545 return;
546 }
879b4f9a 547
2f6749f4 548 var treeviewnode = Y.Node.create('<div/>').
7ccf18a6 549 setAttrs({'class':'fp-treeview', id:'treeview-'+client_id});
2f6749f4 550 this.fpnode.one('.fp-content').setContent('').appendChild(treeviewnode);
b5e7b638 551
4adecd7b
MG
552 scope.treeview = new YAHOO.widget.TreeView('treeview-'+client_id);
553 if (dynload) {
554 scope.treeview.setDynamicLoad(scope.treeview_dynload, 1);
555 }
ce3eeb98 556 scope.treeview.singleNodeHighlight = true;
2f6749f4
MG
557 if (scope.filepath && scope.filepath.length) {
558 // we just jumped from icon/details view, we need to show all parents
559 // we extract as much information as possible from filepath and filelist
560 // and send additional requests to retrieve siblings for parent folders
561 var mytree = {};
562 var mytreeel = null;
563 for (var i in scope.filepath) {
564 if (mytreeel == null) {
565 mytreeel = mytree;
566 } else {
567 mytreeel.children = [{}];
568 mytreeel = mytreeel.children[0];
569 }
570 var parent = scope.filepath[i];
571 mytreeel.path = parent.path;
572 mytreeel.title = parent.name;
573 mytreeel.dynamicLoadComplete = true; // we will call it manually
574 mytreeel.expanded = true;
575 }
576 mytreeel.children = scope.filelist
577 scope.build_tree(mytree, scope.treeview.getRoot());
578 // manually call dynload for parent elements in the tree so we can load other siblings
579 if (dynload) {
580 var root = scope.treeview.getRoot();
581 while (root && root.children && root.children.length) {
582 root = root.children[0];
5bdf63cc
MG
583 if (root.path == mytreeel.path) {
584 root.origpath = scope.filepath;
585 root.origlist = scope.filelist;
586 } else if (!root.isLeaf && root.expanded) {
2f6749f4
MG
587 scope.treeview_dynload(root, null);
588 }
589 }
590 }
591 } else {
592 // there is no path information, just display all elements as a list, without hierarchy
593 for(k in list) {
594 scope.build_tree(list[k], scope.treeview.getRoot());
595 }
4adecd7b
MG
596 }
597 scope.treeview.subscribe('clickEvent', function(e){
ce3eeb98 598 e.node.highlight(false);
4adecd7b 599 if(e.node.isLeaf){
2f6749f4
MG
600 if (e.node.parent && e.node.parent.origpath) {
601 // set the current path
602 scope.filepath = e.node.parent.origpath;
603 scope.filelist = e.node.parent.origlist;
604 scope.print_path();
605 }
5bdf63cc 606 scope.select_file(e.node.fileinfo);
2f6749f4
MG
607 } else {
608 // save current path and filelist (in case we want to jump to other viewmode)
609 scope.filepath = e.node.origpath;
610 scope.filelist = e.node.origlist;
611 scope.print_path();
ce3eeb98 612 scope.content_scrolled();
99eaca9d 613 }
4adecd7b
MG
614 });
615 scope.treeview.draw();
99eaca9d 616 },
7ccf18a6
MG
617 /** displays list of files in icon view mode. If param appenditems is specified,
618 * appends those items to the end of the list. Otherwise (default behaviour)
619 * clears the contents and displays the items from this.filelist */
620 view_as_icons: function(appenditems) {
98b15580 621 var scope = this;
99eaca9d 622 this.viewmode = 1;
7ccf18a6
MG
623 var list = this.filelist, container, element_template;
624 if (!appenditems || !this.filelist || !this.filelist.length) {
625 if (!list || list.length==0) {
626 this.display_error(M.str.repository.nofilesavailable, 'nofilesavailable');
627 return;
628 }
629 this.fpnode.one('.fp-content').setContent(M.core_filepicker.templates.iconview);
630 element_template = this.fpnode.one('.fp-content').one('.fp-file');
631 container = element_template.get('parentNode');
632 container.removeChild(element_template);
633 } else {
634 list = appenditems;
635 element_template = Y.Node.create(M.core_filepicker.templates.iconview).one('.fp-file');
636 container = this.fpnode.one('.fp-content').one('.fp-file').get('parentNode')
879b4f9a 637 }
879b4f9a 638
99eaca9d
DC
639 var count = 0;
640 for(var k in list) {
641 var node = list[k];
b5e7b638
MG
642 var element = element_template.cloneNode(true);
643 container.appendChild(element);
b5e7b638
MG
644 var filename = node.shorttitle ? node.shorttitle : node.title;
645 var filenamediv = element.one('.fp-filename');
646 filenamediv.setContent(filename);
647 var imgdiv = element.one('.fp-thumbnail');
b5e7b638
MG
648 var width = node.thumbnail_width ? node.thumbnail_width : 90;
649 var height = node.thumbnail_height ? node.thumbnail_height : 90;
ce3eeb98
MG
650 filenamediv.setStyleAdv('width', width);
651 imgdiv.setStyleAdv('width', width).setStyleAdv('height', height);
3a1e425b 652 var img = Y.Node.create('<img/>').setAttrs({src:node.thumbnail,title:node.title});
99eaca9d 653 if(node.thumbnail_alt) {
b5e7b638 654 img.set('alt', node.thumbnail_alt);
99eaca9d
DC
655 }
656 if(node.thumbnail_title) {
b5e7b638 657 img.set('title', node.thumbnail_title);
99eaca9d 658 }
b5e7b638 659 img.setStyle('maxWidth', ''+width+'px').setStyle('maxHeight', ''+height+'px');
ce3eeb98
MG
660 if (node.realthumbnail) {
661 this.lazyloading[img.generateID()] = node.realthumbnail;
662 }
b5e7b638 663 imgdiv.appendChild(img)
99eaca9d 664
98b15580 665 var dynload = this.active_repo.dynload;
99eaca9d 666 if(node.children) {
b5e7b638 667 element.on('click', function(e, p) {
4adecd7b 668 e.preventDefault();
98b15580 669 if(dynload) {
5bdf63cc 670 scope.list({'path':p.path});
99eaca9d 671 }else{
5bdf63cc 672 this.filepath = p.path;
99eaca9d
DC
673 this.filelist = p.children;
674 this.view_files();
675 }
676 }, this, node);
99eaca9d 677 } else {
b5e7b638 678 element.on('click', function(e, args) {
4adecd7b 679 e.preventDefault();
99eaca9d 680 this.select_file(args);
5bdf63cc 681 }, this, list[k]);
99eaca9d
DC
682 }
683 count++;
684 }
99eaca9d 685 },
7ccf18a6
MG
686 /** displays list of files in table view mode. If param appenditems is specified,
687 * appends those items to the end of the list. Otherwise (default behaviour)
688 * clears the contents and displays the items from this.filelist */
689 view_as_table: function(appenditems) {
ce3eeb98 690 var list = this.filelist, scope = this;
5bdf63cc
MG
691 var client_id = this.options.client_id;
692 this.viewmode = 3;
ce3eeb98 693 if (appenditems != null) {
7ccf18a6
MG
694 this.tableview.addRows(appenditems);
695 this.tableview.sortable = !this.active_repo.hasmorepages;
696 return;
697 }
5bdf63cc
MG
698
699 if (!list || list.length==0) {
700 this.display_error(M.str.repository.nofilesavailable, 'nofilesavailable');
701 return;
702 }
703 var treeviewnode = Y.Node.create('<div/>').
704 setAttrs({'class':'fp-tableview', id:'tableview-'+client_id});
705 this.fpnode.one('.fp-content').setContent('').appendChild(treeviewnode);
7ccf18a6
MG
706 var formatValue = function (o){
707 if (o.data[''+o.column.key+'_f_s']) { return o.data[''+o.column.key+'_f_s']; }
708 else if (o.data[''+o.column.key+'_f']) { return o.data[''+o.column.key+'_f']; }
709 else if (o.value) { return o.value; }
710 else { return ''; }
711 };
712 var formatTitle = function(o) {
713 var el = Y.Node.create('<div/>').setContent(M.core_filepicker.templates.listfilename);
830acea6 714 el.one('.fp-filename').setContent(o.data['shorttitle'] ? o.data['shorttitle'] : o.value);
7ccf18a6 715 el.one('.fp-icon').appendChild(Y.Node.create('<img/>').set('src', o.data['icon']));
ce3eeb98
MG
716 if (o.data['realicon']) {
717 scope.lazyloading[el.one('.fp-icon img').generateID()] = o.data['realicon'];
718 }
830acea6 719 // TODO add tooltip with o.data['title'] (o.value) or o.data['thumbnail_title']
7ccf18a6
MG
720 return el.getContent();
721 }
722 var sortFoldersFirst = function(a, b, desc) {
723 if (a.get('children') && !b.get('children')) {return -1;}
724 if (!a.get('children') && b.get('children')) {return 1;}
725 var aa = a.get(this.key), bb = b.get(this.key), dir = desc?-1:1;
830acea6
MG
726 if (this.key == 'title' && a.get('shorttitle')) {aa=a.get('shorttitle');}
727 if (this.key == 'title' && b.get('shorttitle')) {bb=b.get('shorttitle');}
7ccf18a6
MG
728 return (aa > bb) ? dir : ((aa < bb) ? -dir : 0);
729 }
5bdf63cc 730
7ccf18a6
MG
731 var cols = [
732 {key: "title", label: M.str.moodle.name, allowHTML: true, formatter: formatTitle,
733 sortable: true, sortFn: sortFoldersFirst},
734 {key: "datemodified", label: M.str.moodle.lastmodified, allowHTML: true, formatter: formatValue,
735 sortable: true, sortFn: sortFoldersFirst},
736 {key: "size", label: M.str.repository.size, allowHTML: true, formatter: formatValue,
737 sortable: true, sortFn: sortFoldersFirst},
738 {key: "type", label: M.str.repository.type, allowHTML: true,
739 sortable: true, sortFn: sortFoldersFirst}
740 ];
741 this.tableview = new Y.DataTable({
742 columns: cols,
743 data: list,
744 sortable: !this.active_repo.hasmorepages // allow sorting only if there are no more pages to load
745 });
5bdf63cc 746
7ccf18a6
MG
747 this.tableview.render('#tableview-'+client_id);
748 this.tableview.delegate('click', function (e) {
749 var record = this.tableview.getRecord(e.currentTarget.get('id'));
750 if (record) {
751 var data = record.getAttrs();
752 if (data.children) {
753 if (this.active_repo.dynload) {
754 this.list({'path':data.path});
755 } else {
756 this.filepath = data.path;
757 this.filelist = data.children;
758 this.view_files();
5bdf63cc 759 }
7ccf18a6
MG
760 } else {
761 this.select_file(data);
5bdf63cc 762 }
7ccf18a6
MG
763 }
764 }, 'tr', this);
765 },
766 /** If more than one page available, requests and displays the files from the next page */
767 request_next_page: function() {
768 if (!this.active_repo.hasmorepages || this.active_repo.nextpagerequested) {
769 // nothing to load
770 return;
771 }
772 this.active_repo.nextpagerequested = true;
773 var nextpage = this.active_repo.page+1;
774 var args = {page:nextpage, repo_id:this.active_repo.id, path:this.active_repo.path};
775 var action = this.active_repo.issearchresult ? 'search' : 'list';
776 this.request({
777 scope: this,
778 action: action,
779 client_id: this.options.client_id,
780 repository_id: args.repo_id,
781 params: args,
782 callback: function(id, obj, args) {
783 var scope = args.scope;
784 // check that we are still in the same repository and are expecting this page
785 if (scope.active_repo.hasmorepages && obj.list && obj.page &&
786 obj.repo_id == scope.active_repo.id &&
787 obj.page == scope.active_repo.page+1 && obj.path == scope.path) {
788 scope.parse_repository_options(obj, true);
789 scope.view_files(obj.list)
790 }
791 }
792 }, false);
5bdf63cc 793 },
99eaca9d 794 select_file: function(args) {
b5e7b638 795 this.selectui.show();
99eaca9d 796 var client_id = this.options.client_id;
b5e7b638 797 var selectnode = this.fpnode.one('.fp-select');
b92241f2 798 var return_types = this.options.repositories[this.active_repo.id].return_types;
3a1e425b 799 selectnode.removeClass('loading');
b92241f2
MG
800 selectnode.one('.fp-saveas input').set('value', args.title);
801 selectnode.one('.fp-setauthor input').set('value', this.options.author);
99eaca9d 802
ce3eeb98
MG
803 var imgnode = Y.Node.create('<img/>').
804 set('src', args.realthumbnail ? args.realthumbnail : args.thumbnail).
805 setStyle('maxHeight', ''+(args.thumbnail_height ? args.thumbnail_height : 90)+'px').
806 setStyle('maxWidth', ''+(args.thumbnail_width ? args.thumbnail_width : 90)+'px');
b92241f2 807 selectnode.one('.fp-thumbnail').setContent('').appendChild(imgnode);
b5e7b638 808
b92241f2
MG
809 selectnode.one('.fp-linkexternal input').set('checked', ''); // default to unchecked
810 if ((this.options.externallink && this.options.env == 'editor' && return_types == 3)) {
811 // support both internal and external links, enable checkbox 'Link external'
812 selectnode.one('.fp-linkexternal input').set('disabled', '');
813 selectnode.all('.fp-linkexternal').removeClass('uneditable')
b5e7b638
MG
814 } else {
815 // disable checkbox 'Link external'
b92241f2
MG
816 selectnode.one('.fp-linkexternal input').set('disabled', 'disabled');
817 selectnode.all('.fp-linkexternal').addClass('uneditable')
818 if (return_types == 1) {
b5e7b638 819 // support external links only
b92241f2 820 selectnode.one('.fp-linkexternal input').set('checked', 'checked');
b5e7b638 821 }
99eaca9d 822 }
1dce6261 823
b5e7b638 824 if (args.hasauthor) {
b92241f2
MG
825 selectnode.one('.fp-setauthor input').set('disabled', 'disabled');
826 selectnode.all('.fp-setauthor').addClass('uneditable')
b5e7b638 827 } else {
b92241f2
MG
828 selectnode.one('.fp-setauthor input').set('disabled', '');
829 selectnode.all('.fp-setauthor').removeClass('uneditable')
1dce6261
DC
830 }
831
832 if (!args.haslicense) {
833 // the license of the file
b92241f2
MG
834 selectnode.one('.fp-setlicense select').set('disabled', '');
835 selectnode.one('.fp-setlicense').removeClass('uneditable');
b5e7b638 836 } else {
b92241f2
MG
837 selectnode.one('.fp-setlicense select').set('disabled', 'disabled');
838 selectnode.one('.fp-setlicense').addClass('uneditable');
1dce6261 839 }
b92241f2 840
b5e7b638 841 selectnode.one('form #filesource-'+client_id).set('value', args.source);
b92241f2
MG
842
843 // display static information about a file (when known)
844 var attrs = ['datemodified','datecreated','size','license','author','dimensions'];
845 for (var i in attrs) {
846 if (selectnode.one('.fp-'+attrs[i])) {
847 var value = (args[attrs[i]+'_f']) ? args[attrs[i]+'_f'] : (args[attrs[i]] ? args[attrs[i]] : '');
848 selectnode.one('.fp-'+attrs[i]).addClassIf('fp-unknown', ''+value == '')
849 .one('.fp-value').setContent(value);
850 }
851 }
b5e7b638
MG
852 },
853 setup_select_file: function() {
854 var client_id = this.options.client_id;
855 var selectnode = this.fpnode.one('.fp-select');
b92241f2
MG
856 var getfile = selectnode.one('.fp-select-confirm');
857 // bind labels with corresponding inputs
858 selectnode.all('.fp-saveas,.fp-linkexternal,.fp-setauthor,.fp-setlicense').each(function (node) {
859 node.all('label').set('for', node.one('input,select').generateID());
860 });
861 this.populate_licenses_select(selectnode.one('.fp-setlicense select'));
862 // register event on clicking submit button
99eaca9d 863 getfile.on('click', function(e) {
b5e7b638 864 e.preventDefault();
99eaca9d
DC
865 var client_id = this.options.client_id;
866 var scope = this;
867 var repository_id = this.active_repo.id;
b92241f2 868 var title = selectnode.one('.fp-saveas input').get('value');
b5e7b638 869 var filesource = selectnode.one('form #filesource-'+client_id).get('value');
14469892 870 var params = {'title':title, 'source':filesource, 'savepath': this.options.savepath};
b92241f2 871 var license = selectnode.one('.fp-setlicense select');
1dce6261
DC
872 if (license) {
873 params['license'] = license.get('value');
b5e7b638 874 Y.Cookie.set('recentlicense', license.get('value'));
1dce6261 875 }
b92241f2 876 params['author'] = selectnode.one('.fp-setauthor input').get('value');
99eaca9d 877
400d228e 878 if (this.options.externallink && this.options.env == 'editor') {
392d5fd4
DC
879 // in editor, images are stored in '/' only
880 params.savepath = '/';
766514a0 881 // when image or media button is clicked
b92241f2
MG
882 var return_types = this.options.repositories[this.active_repo.id].return_types;
883 if ( return_types != 1 ) {
884 var linkexternal = selectnode.one('.fp-linkexternal input');
400d228e 885 if (linkexternal && linkexternal.get('checked')) {
766514a0
DC
886 params['linkexternal'] = 'yes';
887 }
888 } else {
889 // when link button in editor clicked
99eaca9d
DC
890 params['linkexternal'] = 'yes';
891 }
766514a0
DC
892 }
893
894 if (this.options.env == 'url') {
99eaca9d
DC
895 params['linkexternal'] = 'yes';
896 }
897
3a1e425b 898 selectnode.addClass('loading');
99eaca9d 899 this.request({
840912d5
DC
900 action:'download',
901 client_id: client_id,
902 repository_id: repository_id,
903 'params': params,
a5159b86 904 onerror: function(id, obj, args) {
3a1e425b 905 selectnode.removeClass('loading');
b5e7b638 906 scope.selectui.hide();
a5159b86 907 },
840912d5 908 callback: function(id, obj, args) {
3a1e425b 909 selectnode.removeClass('loading');
e0b85db4 910 if (scope.options.editor_target && scope.options.env=='editor') {
840912d5
DC
911 scope.options.editor_target.value=obj.url;
912 scope.options.editor_target.onchange();
913 }
914 scope.hide();
915 obj.client_id = client_id;
916 var formcallback_scope = null;
411caa63 917 if (args.scope.options.magicscope) {
840912d5
DC
918 formcallback_scope = args.scope.options.magicscope;
919 } else {
920 formcallback_scope = args.scope;
99eaca9d 921 }
840912d5
DC
922 scope.options.formcallback.apply(formcallback_scope, [obj]);
923 }
b5e7b638 924 }, false);
99eaca9d 925 }, this);
b5e7b638 926 var elform = selectnode.one('form');
3a1e425b
MG
927 elform.appendChild(Y.Node.create('<input/>').
928 setAttrs({type:'hidden',id:'filesource-'+client_id}));
e0b85db4
DC
929 elform.on('keydown', function(e) {
930 if (e.keyCode == 13) {
931 getfile.simulate('click');
8cbef19e 932 e.preventDefault();
e0b85db4
DC
933 }
934 }, this);
b92241f2 935 var cancel = selectnode.one('.fp-select-cancel');
99eaca9d 936 cancel.on('click', function(e) {
b5e7b638
MG
937 e.preventDefault();
938 this.selectui.hide();
99eaca9d 939 }, this);
99eaca9d 940 },
b5e7b638
MG
941 wait: function() {
942 this.fpnode.one('.fp-content').setContent(M.core_filepicker.templates.loading);
943 },
944 viewbar_set_enabled: function(mode) {
945 var viewbar = this.fpnode.one('.fp-viewbar')
946 if (viewbar) {
947 if (mode) {
948 viewbar.addClass('enabled').removeClass('disabled')
949 } else {
950 viewbar.removeClass('enabled').addClass('disabled')
951 }
99eaca9d 952 }
b5e7b638
MG
953 this.fpnode.all('.fp-vb-icons,.fp-vb-tree,.fp-vb-details').removeClass('checked')
954 var modes = {1:'icons', 2:'tree', 3:'details'};
955 this.fpnode.all('.fp-vb-'+modes[this.viewmode]).addClass('checked');
956 },
957 viewbar_clicked: function(e) {
958 e.preventDefault();
959 var viewbar = this.fpnode.one('.fp-viewbar')
960 if (!viewbar || !viewbar.hasClass('disabled')) {
961 if (e.currentTarget.hasClass('fp-vb-tree')) {
962 this.viewmode = 2;
963 } else if (e.currentTarget.hasClass('fp-vb-details')) {
964 this.viewmode = 3;
965 } else {
966 this.viewmode = 1;
967 }
968 this.viewbar_set_enabled(true)
969 this.view_files();
970 Y.Cookie.set('recentviewmode', this.viewmode);
99eaca9d
DC
971 }
972 },
973 render: function() {
974 var client_id = this.options.client_id;
b92241f2
MG
975 this.fpnode = Y.Node.create(M.core_filepicker.templates.generallayout).
976 set('id', 'filepicker-'+client_id);
977 var fpselectnode = Y.Node.create(M.core_filepicker.templates.selectlayout);
b5e7b638
MG
978 Y.one(document.body).appendChild(this.fpnode);
979 this.fpnode.appendChild(fpselectnode);
980 this.mainui = new Y.Panel({
981 srcNode : this.fpnode,
982 headerContent: M.str.repository.filepicker,
983 zIndex : 500000,
984 centered : true,
985 modal : true,
986 visible : false,
b92241f2 987 render : true
99eaca9d 988 });
b92241f2
MG
989 // allow to move the panel dragging it by it's header:
990 this.mainui.plug(Y.Plugin.Drag,{handles:['.yui3-widget-hd']});
991 // Check if CSS for the node sets min-max width/height and therefore if panel shall be resizable:
992 var resizeconstraints = {
993 minWidth: this.fpnode.getStylePx('minWidth')?this.fpnode.getStylePx('minWidth'):this.fpnode.getStylePx('width'),
994 minHeight: this.fpnode.getStylePx('minHeight')?this.fpnode.getStylePx('minHeight'):this.fpnode.getStylePx('height'),
995 maxWidth: this.fpnode.getStylePx('maxWidth')?this.fpnode.getStylePx('maxWidth'):this.fpnode.getStylePx('width'),
996 maxHeight: this.fpnode.getStylePx('maxHeight')?this.fpnode.getStylePx('maxHeight'):this.fpnode.getStylePx('height'),
997 preserveRatio: false
998 };
999 if (resizeconstraints.minWidth < resizeconstraints.maxWidth ||
1000 resizeconstraints.minHeight < resizeconstraints.maxHeight) {
1001 this.mainui.plug(Y.Plugin.Resize)
1002 this.mainui.resize.plug(Y.Plugin.ResizeConstrained, resizeconstraints);
1003 }
b5e7b638 1004 this.mainui.show();
b92241f2 1005 // create panel for selecting a file (initially hidden)
b5e7b638
MG
1006 this.selectui = new Y.Panel({
1007 srcNode : fpselectnode,
1008 zIndex : 600000,
1009 centered : true,
1010 modal : true,
1011 close : true,
1012 render : true
99eaca9d 1013 });
b5e7b638 1014 this.selectui.hide();
ce3eeb98
MG
1015 // event handler for lazy loading of thumbnails and next page
1016 this.fpnode.one('.fp-content').on(['scroll','resize'], this.content_scrolled, this);
b5e7b638
MG
1017 // save template for one path element and location of path bar
1018 if (this.fpnode.one('.fp-path-folder')) {
1019 this.pathnode = this.fpnode.one('.fp-path-folder');
1020 this.pathbar = this.pathnode.get('parentNode');
1021 this.pathbar.removeChild(this.pathnode);
1022 }
1023 // assign callbacks for view mode switch buttons
1024 this.fpnode.all('.fp-vb-icons,.fp-vb-tree,.fp-vb-details').
1025 on('click', this.viewbar_clicked, this);
1026 // assign callbacks for toolbar links
1027 this.setup_toolbar();
1028 this.setup_select_file();
3a1e425b 1029 this.hide_header();
934291d6 1030
99eaca9d 1031 // processing repository listing
b5e7b638
MG
1032 // Resort the repositories by sortorder
1033 var sorted_repositories = []
1034 for (var i in this.options.repositories) {
1035 sorted_repositories[i] = this.options.repositories[i]
1036 }
1037 sorted_repositories.sort(function(a,b){return a.sortorder-b.sortorder})
1038 // extract one repository template and repeat it for all repositories available,
1039 // set name and icon and assign callbacks
1040 var reponode = this.fpnode.one('.fp-repo');
1041 if (reponode) {
1042 var list = reponode.get('parentNode');
1043 list.removeChild(reponode);
1044 for (i in sorted_repositories) {
1045 var repository = sorted_repositories[i]
1046 var node = reponode.cloneNode(true);
1047 list.appendChild(node);
1048 node.
1049 set('id', 'fp-repo-'+client_id+'-'+repository.id).
1050 on('click', function(e, repository_id) {
1051 e.preventDefault();
1052 Y.Cookie.set('recentrepository', repository_id);
1053 this.hide_header();
1054 this.list({'repo_id':repository_id});
1055 }, this /*handler running scope*/, repository.id/*second argument of handler*/);
1056 node.one('.fp-repo-name').setContent(repository.name)
1057 node.one('.fp-repo-icon').set('src', repository.icon)
1058 if (i==0) {node.addClass('first');}
1059 if (i==sorted_repositories.length-1) {node.addClass('last');}
1060 if (i%2) {node.addClass('even');} else {node.addClass('odd');}
99eaca9d 1061 }
b5e7b638
MG
1062 }
1063 // display error if no repositories found
1064 if (sorted_repositories.length==0) {
3a1e425b 1065 this.display_error(M.str.repository.norepositoriesavailable, 'norepositoriesavailable')
b5e7b638
MG
1066 }
1067 // display repository that was used last time
1068 this.show_recent_repository();
99eaca9d 1069 },
7ccf18a6
MG
1070 parse_repository_options: function(data, appendtolist) {
1071 if (appendtolist) {
1072 if (data.list) {
1073 if (!this.filelist) { this.filelist = []; }
1074 for (var i in data.list) {
1075 this.filelist[this.filelist.length] = data.list[i];
1076 }
1077 }
1078 } else {
1079 this.filelist = data.list?data.list:null;
ce3eeb98 1080 this.lazyloading = {};
7ccf18a6 1081 }
99eaca9d
DC
1082 this.filepath = data.path?data.path:null;
1083 this.active_repo = {};
4adecd7b 1084 this.active_repo.issearchresult = data.issearchresult?true:false;
98b15580 1085 this.active_repo.dynload = data.dynload?data.dynload:false;
99eaca9d
DC
1086 this.active_repo.pages = Number(data.pages?data.pages:null);
1087 this.active_repo.page = Number(data.page?data.page:null);
7ccf18a6 1088 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 1089 this.active_repo.id = data.repo_id?data.repo_id:null;
b5e7b638
MG
1090 this.active_repo.nosearch = (data.login || data.nosearch); // this is either login form or 'nosearch' attribute set
1091 this.active_repo.norefresh = (data.login || data.norefresh); // this is either login form or 'norefresh' attribute set
1092 this.active_repo.nologin = (data.login || data.nologin); // this is either login form or 'nologin' attribute is set
fdfb9cbe 1093 this.active_repo.logouttext = data.logouttext?data.logouttext:null;
99eaca9d
DC
1094 this.active_repo.help = data.help?data.help:null;
1095 this.active_repo.manage = data.manage?data.manage:null;
b5e7b638 1096 this.print_header();
99eaca9d
DC
1097 },
1098 print_login: function(data) {
97b151ea 1099 this.parse_repository_options(data);
99eaca9d
DC
1100 var client_id = this.options.client_id;
1101 var repository_id = data.repo_id;
1102 var l = this.logindata = data.login;
1103 var loginurl = '';
3a1e425b 1104 var action = data['login_btn_action'] ? data['login_btn_action'] : 'login';
99eaca9d 1105 var form_id = 'fp-form-'+client_id;
99eaca9d 1106
5ce13292
MG
1107 var loginform_node = Y.Node.create(M.core_filepicker.templates.loginform);
1108 loginform_node.one('form').set('id', form_id);
1109 this.fpnode.one('.fp-content').setContent('').appendChild(loginform_node);
1110 var templates = {
1111 'popup' : loginform_node.one('.fp-login-popup'),
1112 'textarea' : loginform_node.one('.fp-login-textarea'),
1113 'select' : loginform_node.one('.fp-login-select'),
1114 'text' : loginform_node.one('.fp-login-text'),
3a1e425b 1115 'radio' : loginform_node.one('.fp-login-radiogroup'),
5ce13292
MG
1116 'checkbox' : loginform_node.one('.fp-login-checkbox'),
1117 'input' : loginform_node.one('.fp-login-input')
1118 };
1119 var container;
1120 for (var i in templates) {
1121 if (templates[i]) {
1122 container = templates[i].get('parentNode');
1123 container.removeChild(templates[i])
1124 }
1125 }
1126
1127 for(var k in l) {
1128 if (templates[l[k].type]) {
1129 var node = templates[l[k].type].cloneNode(true);
1130 } else {
1131 node = templates['input'].cloneNode(true);
1132 }
1133 if (l[k].type == 'popup') {
3a1e425b 1134 // submit button
2f6749f4 1135 loginurl = l[k].url;
3a1e425b
MG
1136 var popupbutton = node.one('button');
1137 popupbutton.on('click', function(e){
1138 M.core_filepicker.active_filepicker = this;
1139 window.open(loginurl, 'repo_auth', 'location=0,status=0,width=500,height=300,scrollbars=yes');
1140 e.preventDefault();
1141 }, this);
1142 loginform_node.one('form').on('keydown', function(e) {
1143 if (e.keyCode == 13) {
1144 popupbutton.simulate('click');
1145 e.preventDefault();
1146 }
1147 }, this);
5ce13292
MG
1148 loginform_node.all('.fp-login-submit').remove();
1149 action = 'popup';
1150 }else if(l[k].type=='textarea') {
1151 // textarea element
1152 if (node.one('label')) { node.one('label').set('for', l[k].id).setContent(l[k].label) }
3a1e425b 1153 node.one('textarea').setAttrs({id:l[k].id, name:l[k].name});
5ce13292
MG
1154 }else if(l[k].type=='select') {
1155 // select element
1156 if (node.one('label')) { node.one('label').set('for', l[k].id).setContent(l[k].label) }
3a1e425b 1157 node.one('select').setAttrs({id:l[k].id, name:l[k].name}).setContent('');
5ce13292
MG
1158 for (i in l[k].options) {
1159 node.one('select').appendChild(
1160 Y.Node.create('<option/>').
1161 set('value', l[k].options[i].value).
1162 setContent(l[k].options[i].label))
1163 }
1164 }else if(l[k].type=='radio') {
1165 // radio input element
3a1e425b
MG
1166 node.all('label').setContent(l[k].label);
1167 var list = l[k].value.split('|');
1168 var labels = l[k].value_label.split('|');
1169 var radionode = null;
1170 for(var item in list) {
1171 if (radionode == null) {
1172 radionode = node.one('.fp-login-radio');
1173 radionode.one('input').set('checked', 'checked');
1174 } else {
1175 var x = radionode.cloneNode(true);
1176 radionode.insert(x, 'after');
1177 radionode = x;
1178 radionode.one('input').set('checked', '');
1179 }
1180 radionode.one('input').setAttrs({id:''+l[k].id+item, name:l[k].name,
1181 type:l[k].type, value:list[item]});
1182 radionode.all('label').setContent(labels[item]).set('for', ''+l[k].id+item)
1183 }
1184 if (radionode == null) {
1185 node.one('.fp-login-radio').remove();
1186 }
5ce13292
MG
1187 }else {
1188 // input element
1189 if (node.one('label')) { node.one('label').set('for', l[k].id).setContent(l[k].label) }
1190 node.one('input').
1191 set('type', l[k].type).
1192 set('id', l[k].id).
1193 set('name', l[k].name).
1194 set('value', l[k].value?l[k].value:'')
1195 }
1196 container.appendChild(node);
1197 }
3a1e425b
MG
1198 // custom label text for submit button
1199 if (data['login_btn_label']) {
1200 loginform_node.all('.fp-login-submit').setContent(data['login_btn_label'])
99eaca9d 1201 }
3a1e425b
MG
1202 // register button action for login and search
1203 if (action == 'login' || action == 'search') {
1204 loginform_node.one('.fp-login-submit').on('click', function(e){
5ce13292 1205 e.preventDefault();
b5e7b638 1206 this.hide_header();
99eaca9d 1207 this.request({
3a1e425b
MG
1208 'scope': this,
1209 'action':(action == 'search') ? 'search' : 'signin',
99eaca9d
DC
1210 'path': '',
1211 'client_id': client_id,
1212 'repository_id': repository_id,
3a1e425b 1213 'form': {id:form_id, upload:false, useDisabled:true},
4adecd7b 1214 'callback': this.display_response
99eaca9d
DC
1215 }, true);
1216 }, this);
1217 }
3a1e425b
MG
1218 // if 'Enter' is pressed in the form, simulate the button click
1219 if (loginform_node.one('.fp-login-submit')) {
1220 loginform_node.one('form').on('keydown', function(e) {
1221 if (e.keyCode == 13) {
1222 loginform_node.one('.fp-login-submit').simulate('click')
1223 e.preventDefault();
99eaca9d 1224 }
99eaca9d
DC
1225 }, this);
1226 }
99eaca9d 1227 },
4adecd7b
MG
1228 display_response: function(id, obj, args) {
1229 var scope = args.scope
1230 // highlight the current repository in repositories list
b5e7b638
MG
1231 scope.fpnode.all('.fp-repo.active').removeClass('active');
1232 scope.fpnode.all('#fp-repo-'+scope.options.client_id+'-'+obj.repo_id).addClass('active')
5ce13292
MG
1233 // add class repository_REPTYPE to the filepicker (for repository-specific styles)
1234 for (var i in scope.options.repositories) {
1235 scope.fpnode.removeClass('repository_'+scope.options.repositories[i].type)
1236 }
1237 if (obj.repo_id && scope.options.repositories[obj.repo_id]) {
1238 scope.fpnode.addClass('repository_'+scope.options.repositories[obj.repo_id].type)
1239 }
4adecd7b
MG
1240 // display response
1241 if (obj.login) {
b5e7b638 1242 scope.viewbar_set_enabled(false);
4adecd7b
MG
1243 scope.print_login(obj);
1244 } else if (obj.upload) {
b5e7b638 1245 scope.viewbar_set_enabled(false);
4adecd7b
MG
1246 scope.parse_repository_options(obj);
1247 scope.create_upload_form(obj);
1248 } else if (obj.iframe) {
99eaca9d 1249
4adecd7b 1250 } else if (obj.list) {
b5e7b638 1251 scope.viewbar_set_enabled(true);
4adecd7b
MG
1252 scope.parse_repository_options(obj);
1253 scope.view_files();
99eaca9d 1254 }
99eaca9d
DC
1255 },
1256 list: function(args) {
99eaca9d
DC
1257 if (!args) {
1258 args = {};
1259 }
1260 if (!args.repo_id) {
4adecd7b 1261 args.repo_id = this.active_repo.id;
99eaca9d 1262 }
4adecd7b
MG
1263 this.request({
1264 action: 'list',
1265 client_id: this.options.client_id,
99eaca9d 1266 repository_id: args.repo_id,
4adecd7b
MG
1267 path: args.path,
1268 page: args.page,
1269 scope: this,
1270 callback: this.display_response
99eaca9d
DC
1271 }, true);
1272 },
b5e7b638
MG
1273 populate_licenses_select: function(node) {
1274 if (!node) {
1275 return;
e35194be 1276 }
b5e7b638 1277 node.setContent('');
1dce6261 1278 var licenses = this.options.licenses;
b5e7b638 1279 var recentlicense = Y.Cookie.get('recentlicense');
a756cb37
DC
1280 if (recentlicense) {
1281 this.options.defaultlicense=recentlicense;
1282 }
1dce6261 1283 for (var i in licenses) {
b5e7b638
MG
1284 var option = Y.Node.create('<option/>').
1285 set('selected', (this.options.defaultlicense==licenses[i].shortname)).
1286 set('value', licenses[i].shortname).
1287 setContent(licenses[i].fullname);
1288 node.appendChild(option)
1dce6261 1289 }
b5e7b638
MG
1290 },
1291 create_upload_form: function(data) {
1292 var client_id = this.options.client_id;
1293 var id = data.upload.id+'_'+client_id;
b92241f2
MG
1294 var content = this.fpnode.one('.fp-content');
1295 content.setContent(M.core_filepicker.templates.uploadform);
b5e7b638 1296
b92241f2
MG
1297 content.all('.fp-file,.fp-saveas,.fp-setauthor,.fp-setlicense').each(function (node) {
1298 node.all('label').set('for', node.one('input,select').generateID());
1299 });
1300 content.one('form').set('id', id);
1301 content.one('.fp-file input').set('name', 'repo_upload_file');
1302 content.one('.fp-saveas input').set('name', 'title');
1303 content.one('.fp-setauthor input').setAttrs({name:'author', value:this.options.author});
1304 content.one('.fp-setlicense select').set('name', 'license');
1305 this.populate_licenses_select(content.one('.fp-setlicense select'))
1306 // append hidden inputs to the upload form
1307 content.one('form').appendChild(Y.Node.create('<input/>').
3a1e425b 1308 setAttrs({type:'hidden',name:'itemid',value:this.options.itemid}));
b5e7b638
MG
1309 var types = this.options.accepted_types;
1310 for (var i in types) {
b92241f2 1311 content.one('form').appendChild(Y.Node.create('<input/>').
3a1e425b 1312 setAttrs({type:'hidden',name:'accepted_types[]',value:types[i]}));
b5e7b638
MG
1313 }
1314
99eaca9d 1315 var scope = this;
b92241f2 1316 content.one('.fp-upload-btn').on('click', function(e) {
8cbef19e 1317 e.preventDefault();
b92241f2 1318 var license = content.one('.fp-setlicense select');
b5e7b638 1319 Y.Cookie.set('recentlicense', license.get('value'));
b92241f2 1320 if (!content.one('.fp-file input').get('value')) {
ce6297d2 1321 scope.print_msg(M.str.repository.nofilesattached, 'error');
2a03b97b
DC
1322 return false;
1323 }
b5e7b638 1324 this.hide_header();
9d753c38
PS
1325 scope.request({
1326 scope: scope,
1327 action:'upload',
1328 client_id: client_id,
1329 params: {'savepath':scope.options.savepath},
1330 repository_id: scope.active_repo.id,
1331 form: {id: id, upload:true},
a5159b86
MG
1332 onerror: function(id, o, args) {
1333 scope.create_upload_form(data);
1334 },
9d753c38
PS
1335 callback: function(id, o, args) {
1336 if (scope.options.editor_target&&scope.options.env=='editor') {
1337 scope.options.editor_target.value=o.url;
1338 scope.options.editor_target.onchange();
0c4edaa2 1339 }
9d753c38
PS
1340 scope.hide();
1341 o.client_id = client_id;
1342 var formcallback_scope = null;
1343 if (args.scope.options.magicscope) {
1344 formcallback_scope = args.scope.options.magicscope;
1345 } else {
1346 formcallback_scope = args.scope;
1347 }
1348 scope.options.formcallback.apply(formcallback_scope, [o]);
1349 }
1350 }, true);
99eaca9d
DC
1351 }, this);
1352 },
b5e7b638
MG
1353 /** setting handlers and labels for elements in toolbar. Called once during the initial render of filepicker */
1354 setup_toolbar: function() {
99eaca9d 1355 var client_id = this.options.client_id;
b92241f2
MG
1356 var toolbar = this.fpnode.one('.fp-toolbar');
1357 toolbar.one('.fp-tb-logout').one('a,button').on('click', function(e) {
b5e7b638
MG
1358 e.preventDefault();
1359 if (!this.active_repo.nologin) {
1360 this.hide_header();
1361 this.request({
1362 action:'logout',
1363 client_id: this.options.client_id,
1364 repository_id: this.active_repo.id,
1365 path:'',
1366 callback: this.display_response
1367 }, true);
1368 }
1369 }, this);
b92241f2 1370 toolbar.one('.fp-tb-refresh').one('a,button').on('click', function(e) {
b5e7b638
MG
1371 e.preventDefault();
1372 if (!this.active_repo.norefresh) {
1373 this.list();
1374 }
1375 }, this);
b92241f2 1376 toolbar.one('.fp-tb-search form').
b5e7b638 1377 set('method', 'POST').
b92241f2 1378 set('id', 'fp-tb-search-'+client_id).
b5e7b638 1379 on('submit', function(e) {
4adecd7b 1380 e.preventDefault();
b5e7b638
MG
1381 if (!this.active_repo.nosearch) {
1382 this.request({
1383 scope: this,
1384 action:'search',
1385 client_id: this.options.client_id,
1386 repository_id: this.active_repo.id,
1387 form: {id: 'fp-tb-search-'+client_id, upload:false, useDisabled:true},
1388 callback: this.display_response
1389 }, true);
1390 }
1391 }, this);
99eaca9d 1392
b92241f2 1393 // it does not matter what kind of element is .fp-tb-manage, we create a dummy <a>
b5e7b638 1394 // element and use it to open url on click event
3a1e425b
MG
1395 var managelnk = Y.Node.create('<a/>').
1396 setAttrs({id:'fp-tb-manage-'+client_id+'-link', target:'_blank'}).
1397 setStyle('display', 'none');
b92241f2
MG
1398 toolbar.append(managelnk);
1399 toolbar.one('.fp-tb-manage').one('a,button').
1400 on('click', function(e) {
1401 e.preventDefault();
1402 managelnk.simulate('click')
1403 });
99eaca9d 1404
b92241f2 1405 // same with .fp-tb-help
3a1e425b
MG
1406 var helplnk = Y.Node.create('<a/>').
1407 setAttrs({id:'fp-tb-help-'+client_id+'-link', target:'_blank'}).
1408 setStyle('display', 'none');
b92241f2
MG
1409 toolbar.append(helplnk);
1410 toolbar.one('.fp-tb-manage').one('a,button').
1411 on('click', function(e) {
1412 e.preventDefault();
1413 helplnk.simulate('click')
1414 });
b5e7b638
MG
1415 },
1416 hide_header: function() {
b92241f2
MG
1417 if (this.fpnode.one('.fp-toolbar')) {
1418 this.fpnode.one('.fp-toolbar').addClass('empty');
b5e7b638 1419 }
3a1e425b
MG
1420 if (this.pathbar) {
1421 this.pathbar.setContent('').addClass('empty');
1422 }
b5e7b638
MG
1423 },
1424 print_header: function() {
1425 var r = this.active_repo;
1426 var scope = this;
1427 var client_id = this.options.client_id;
2f6749f4 1428 this.hide_header();
b92241f2
MG
1429 this.print_path();
1430 var toolbar = this.fpnode.one('.fp-toolbar');
1431 if (!toolbar) { return; }
99eaca9d 1432
b92241f2
MG
1433 var enable_tb_control = function(node, enabled) {
1434 if (!node) { return; }
1435 node.addClassIf('disabled', !enabled).addClassIf('enabled', enabled)
1436 if (enabled) {
1437 toolbar.removeClass('empty');
b5e7b638
MG
1438 }
1439 }
99eaca9d 1440
b5e7b638 1441 // TODO 'back' permanently disabled for now. Note, flickr_public uses 'Logout' for it!
b92241f2 1442 enable_tb_control(toolbar.one('.fp-tb-back'), false);
99eaca9d 1443
b5e7b638 1444 // search form
b92241f2 1445 enable_tb_control(toolbar.one('.fp-tb-search'), !r.nosearch);
b5e7b638 1446 if(!r.nosearch) {
b92241f2
MG
1447 var searchform = toolbar.one('.fp-tb-search form');
1448 searchform.setContent('');
b5e7b638
MG
1449 this.request({
1450 scope: this,
1451 action:'searchform',
1452 repository_id: this.active_repo.id,
1453 callback: function(id, obj, args) {
1454 if (obj.repo_id == scope.active_repo.id && obj.form) {
1455 // if we did not jump to another repository meanwhile
b92241f2 1456 searchform.setContent(obj.form);
99eaca9d 1457 }
b5e7b638
MG
1458 }
1459 }, false);
99eaca9d 1460 }
b5e7b638
MG
1461
1462 // refresh button
99eaca9d 1463 // weather we use cache for this instance, this button will reload listing anyway
b92241f2 1464 enable_tb_control(toolbar.one('.fp-tb-refresh'), !r.norefresh);
b5e7b638
MG
1465
1466 // login button
b92241f2 1467 enable_tb_control(toolbar.one('.fp-tb-logout'), !r.nologin);
99eaca9d 1468 if(!r.nologin) {
fdfb9cbe 1469 var label = r.logouttext?r.logouttext:M.str.repository.logout;
b92241f2 1470 toolbar.one('.fp-tb-logout').one('a,button').setContent(label)
99eaca9d
DC
1471 }
1472
b5e7b638 1473 // manage url
b92241f2 1474 enable_tb_control(toolbar.one('.fp-tb-manage'), r.manage);
b5e7b638
MG
1475 Y.one('#fp-tb-manage-'+client_id+'-link').set('href', r.manage);
1476
1477 // help url
b92241f2 1478 enable_tb_control(toolbar.one('.fp-tb-help'), r.help);
b5e7b638 1479 Y.one('#fp-tb-help-'+client_id+'-link').set('href', r.help);
99eaca9d 1480 },
99eaca9d 1481 print_path: function() {
b5e7b638 1482 if (!this.pathbar) { return; }
3a1e425b 1483 this.pathbar.setContent('').addClass('empty');
99eaca9d 1484 var p = this.filepath;
2f6749f4 1485 if (p && p.length!=0 && this.viewmode != 2) {
99eaca9d 1486 for(var i = 0; i < p.length; i++) {
b5e7b638
MG
1487 var el = this.pathnode.cloneNode(true);
1488 this.pathbar.appendChild(el);
1489 if (i == 0) {el.addClass('first');}
1490 if (i == p.length-1) {el.addClass('last');}
1491 if (i%2) {el.addClass('even');} else {el.addClass('odd');}
1492 el.all('.fp-path-folder-name').setContent(p[i].name);
1493 el.on('click',
1494 function(e, path) {
1495 e.preventDefault();
1496 this.list({'path':path});
1497 },
1498 this, p[i].path);
99eaca9d 1499 }
b5e7b638 1500 this.pathbar.removeClass('empty');
99eaca9d
DC
1501 }
1502 },
1503 hide: function() {
b5e7b638
MG
1504 this.selectui.hide();
1505 if (this.process_dlg) {
1506 this.process_dlg.hide();
1507 }
1508 if (this.msg_dlg) {
1509 this.msg_dlg.hide();
1510 }
99eaca9d
DC
1511 this.mainui.hide();
1512 },
1513 show: function() {
b5e7b638
MG
1514 if (this.fpnode) {
1515 this.hide();
99eaca9d 1516 this.mainui.show();
a756cb37 1517 this.show_recent_repository();
99eaca9d
DC
1518 } else {
1519 this.launch();
1520 }
1521 },
1522 launch: function() {
7b42e81a 1523 this.render();
a756cb37
DC
1524 },
1525 show_recent_repository: function() {
b5e7b638
MG
1526 this.hide_header();
1527 this.viewbar_set_enabled(false);
1528 var repository_id = Y.Cookie.get('recentrepository');
1529 this.viewmode = Y.Cookie.get('recentviewmode', Number);
5bdf63cc 1530 if (this.viewmode != 2 && this.viewmode != 3) {
b5e7b638
MG
1531 this.viewmode = 1;
1532 }
a756cb37
DC
1533 if (this.options.repositories[repository_id]) {
1534 this.list({'repo_id':repository_id});
1535 }
99eaca9d
DC
1536 }
1537 });
bb496de7
DC
1538 var loading = Y.one('#filepicker-loading-'+options.client_id);
1539 if (loading) {
1540 loading.setStyle('display', 'none');
1541 }
4c508047
PS
1542 M.core_filepicker.instances[options.client_id] = new FilePickerHelper(options);
1543};