forked from moodle/moodle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
filepicker.js
2044 lines (1987 loc) · 96.4 KB
/
filepicker.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// YUI3 File Picker module for moodle
// Author: Dongsheng Cai <[email protected]>
/**
*
* File Picker UI
* =====
* this.fpnode, contains reference to filepicker Node, non-empty if and only if rendered
* this.api, stores the URL to make ajax request
* this.mainui, YUI Panel
* this.selectnode, contains reference to select-file Node
* this.selectui, YUI Panel for selecting particular file
* this.msg_dlg, YUI Panel for error or info message
* this.process_dlg, YUI Panel for processing existing filename
* this.treeview, YUI Treeview
* this.viewmode, store current view mode
* this.pathbar, reference to the Node with path bar
* this.pathnode, a Node element representing one folder in a path bar (not attached anywhere, just used for template)
* this.currentpath, the current path in the repository (or last requested path)
*
* Filepicker options:
* =====
* this.options.client_id, the instance id
* this.options.contextid
* this.options.itemid
* this.options.repositories, stores all repositories displayed in file picker
* this.options.formcallback
*
* Active repository options
* =====
* this.active_repo.id
* this.active_repo.defaultreturntype
* this.active_repo.nosearch
* this.active_repo.norefresh
* this.active_repo.nologin
* this.active_repo.help
* this.active_repo.manage
*
* Server responses
* =====
* this.filelist, cached filelist
* this.pages
* this.page
* this.filepath, current path (each element of the array is a part of the breadcrumb)
* this.logindata, cached login form
*/
YUI.add('moodle-core_filepicker', function(Y) {
/** help function to extract width/height style as a number, not as a string */
Y.Node.prototype.getStylePx = function(attr) {
var style = this.getStyle(attr);
if (''+style == '0' || ''+style == '0px') {
return 0;
}
var matches = style.match(/^([\d\.]+)px$/)
if (matches && parseFloat(matches[1])) {
return parseFloat(matches[1]);
}
return null;
}
/** if condition is met, the class is added to the node, otherwise - removed */
Y.Node.prototype.addClassIf = function(className, condition) {
if (condition) {
this.addClass(className);
} else {
this.removeClass(className);
}
return this;
}
/** sets the width(height) of the node considering existing minWidth(minHeight) */
Y.Node.prototype.setStyleAdv = function(stylename, value) {
var stylenameCap = stylename.substr(0,1).toUpperCase() + stylename.substr(1, stylename.length-1).toLowerCase();
this.setStyle(stylename, '' + Math.max(value, this.getStylePx('min'+stylenameCap)) + 'px')
return this;
}
/** set image source to src, if there is preview, remember it in lazyloading.
* If there is a preview and it was already loaded, use it. */
Y.Node.prototype.setImgSrc = function(src, realsrc, lazyloading) {
if (realsrc) {
if (M.core_filepicker.loadedpreviews[realsrc]) {
this.set('src', realsrc).addClass('realpreview');
return this;
} else {
if (!this.get('id')) {
this.generateID();
}
lazyloading[this.get('id')] = realsrc;
}
}
this.set('src', src);
return this;
}
/**
* Replaces the image source with preview. If the image is inside the treeview, we need
* also to update the html property of corresponding YAHOO.widget.HTMLNode
* @param array lazyloading array containing associations of imgnodeid->realsrc
*/
Y.Node.prototype.setImgRealSrc = function(lazyloading) {
if (this.get('id') && lazyloading[this.get('id')]) {
var newsrc = lazyloading[this.get('id')];
M.core_filepicker.loadedpreviews[newsrc] = true;
this.set('src', newsrc).addClass('realpreview');
delete lazyloading[this.get('id')];
var treenode = this.ancestor('.fp-treeview')
if (treenode && treenode.get('parentNode').treeview) {
treenode.get('parentNode').treeview.getRoot().refreshPreviews(this.get('id'), newsrc);
}
}
return this;
}
/** scan TreeView to find which node contains image with id=imgid and replace it's html
* with the new image source. */
Y.YUI2.widget.Node.prototype.refreshPreviews = function(imgid, newsrc, regex) {
if (!regex) {
regex = new RegExp("<img\\s[^>]*id=\""+imgid+"\"[^>]*?(/?)>", "im");
}
if (this.expanded || this.isLeaf) {
var html = this.getContentHtml();
if (html && this.setHtml && regex.test(html)) {
var newhtml = this.html.replace(regex, "<img id=\""+imgid+"\" src=\""+newsrc+"\" class=\"realpreview\"$1>", html);
this.setHtml(newhtml);
return true;
}
if (!this.isLeaf && this.children) {
for(var c in this.children) {
if (this.children[c].refreshPreviews(imgid, newsrc, regex)) {
return true;
}
}
}
}
return false;
}
/**
* Displays a list of files (used by filepicker, filemanager) inside the Node
*
* @param array options
* viewmode : 1 - icons, 2 - tree, 3 - table
* appendonly : whether fileslist need to be appended instead of replacing the existing content
* filenode : Node element that contains template for displaying one file
* callback : On click callback. The element of the fileslist array will be passed as argument
* rightclickcallback : On right click callback (optional).
* callbackcontext : context where callbacks are executed
* sortable : whether content may be sortable (in table mode)
* dynload : allow dynamic load for tree view
* filepath : for pre-building of tree view - the path to the current directory in filepicker format
* treeview_dynload : callback to function to dynamically load the folder in tree view
* classnamecallback : callback to function that returns the class name for an element
* @param array fileslist array of files to show, each array element may have attributes:
* title or fullname : file name
* shorttitle (optional) : display file name
* thumbnail : url of image
* icon : url of icon image
* thumbnail_width : width of thumbnail, default 90
* thumbnail_height : height of thumbnail, default 90
* thumbnail_alt : TODO not needed!
* description or thumbnail_title : alt text
* @param array lazyloading : reference to the array with lazy loading images
*/
Y.Node.prototype.fp_display_filelist = function(options, fileslist, lazyloading) {
var viewmodeclassnames = {1:'fp-iconview', 2:'fp-treeview', 3:'fp-tableview'};
var classname = viewmodeclassnames[options.viewmode];
var scope = this;
/** return whether file is a folder (different attributes in FileManager and FilePicker) */
var file_is_folder = function(node) {
if (node.children) {return true;}
if (node.type && node.type == 'folder') {return true;}
return false;
};
/** return the name of the file (different attributes in FileManager and FilePicker) */
var file_get_filename = function(node) {
return node.title ? node.title : node.fullname;
};
/** return display name of the file (different attributes in FileManager and FilePicker) */
var file_get_displayname = function(node) {
var displayname = node.shorttitle ? node.shorttitle : file_get_filename(node);
return Y.Escape.html(displayname);
};
/** return file description (different attributes in FileManager and FilePicker) */
var file_get_description = function(node) {
var description = '';
if (node.description) {
description = node.description;
} else if (node.thumbnail_title) {
description = node.thumbnail_title;
} else {
description = file_get_filename(node);
}
return Y.Escape.html(description);
};
/** help funciton for tree view */
var build_tree = function(node, level) {
// prepare file name with icon
var el = Y.Node.create('<div/>');
el.appendChild(options.filenode.cloneNode(true));
el.one('.fp-filename').setContent(file_get_displayname(node));
// TODO add tooltip with node.title or node.thumbnail_title
var tmpnodedata = {className:options.classnamecallback(node)};
el.get('children').addClass(tmpnodedata.className);
if (node.icon) {
el.one('.fp-icon').appendChild(Y.Node.create('<img/>'));
el.one('.fp-icon img').setImgSrc(node.icon, node.realicon, lazyloading);
}
// create node
tmpnodedata.html = el.getContent();
var tmpNode = new Y.YUI2.widget.HTMLNode(tmpnodedata, level, false);
if (node.dynamicLoadComplete) {
tmpNode.dynamicLoadComplete = true;
}
tmpNode.fileinfo = node;
tmpNode.isLeaf = !file_is_folder(node);
if (!tmpNode.isLeaf) {
if(node.expanded) {
tmpNode.expand();
}
tmpNode.path = node.path ? node.path : (node.filepath ? node.filepath : '');
for(var c in node.children) {
build_tree(node.children[c], tmpNode);
}
}
};
/** initialize tree view */
var initialize_tree_view = function() {
var parentid = scope.one('.'+classname).get('id');
// TODO MDL-32736 use YUI3 gallery TreeView
scope.treeview = new Y.YUI2.widget.TreeView(parentid);
if (options.dynload) {
scope.treeview.setDynamicLoad(Y.bind(options.treeview_dynload, options.callbackcontext), 1);
}
scope.treeview.singleNodeHighlight = true;
if (options.filepath && options.filepath.length) {
// we just jumped from icon/details view, we need to show all parents
// we extract as much information as possible from filepath and filelist
// and send additional requests to retrieve siblings for parent folders
var mytree = {};
var mytreeel = null;
for (var i in options.filepath) {
if (mytreeel == null) {
mytreeel = mytree;
} else {
mytreeel.children = [{}];
mytreeel = mytreeel.children[0];
}
var pathelement = options.filepath[i];
mytreeel.path = pathelement.path;
mytreeel.title = pathelement.name;
mytreeel.icon = pathelement.icon;
mytreeel.dynamicLoadComplete = true; // we will call it manually
mytreeel.expanded = true;
}
mytreeel.children = fileslist;
build_tree(mytree, scope.treeview.getRoot());
// manually call dynload for parent elements in the tree so we can load other siblings
if (options.dynload) {
var root = scope.treeview.getRoot();
while (root && root.children && root.children.length) {
root = root.children[0];
if (root.path == mytreeel.path) {
root.origpath = options.filepath;
root.origlist = fileslist;
}
// Removed bind as of MDL-62415 as it overwrites the search tree results
}
}
} else {
// there is no path information, just display all elements as a list, without hierarchy
for(k in fileslist) {
build_tree(fileslist[k], scope.treeview.getRoot());
}
}
scope.treeview.subscribe('clickEvent', function(e){
e.node.highlight(false);
var callback = options.callback;
if (options.rightclickcallback && e.event.target &&
Y.Node(e.event.target).ancestor('.fp-treeview .fp-contextmenu', true)) {
callback = options.rightclickcallback;
}
Y.bind(callback, options.callbackcontext)(e, e.node.fileinfo);
Y.YUI2.util.Event.stopEvent(e.event)
});
// TODO MDL-32736 support right click
/*if (options.rightclickcallback) {
scope.treeview.subscribe('dblClickEvent', function(e){
e.node.highlight(false);
Y.bind(options.rightclickcallback, options.callbackcontext)(e, e.node.fileinfo);
});
}*/
scope.treeview.draw();
};
/** formatting function for table view */
var formatValue = function (o){
if (o.data[''+o.column.key+'_f_s']) {return o.data[''+o.column.key+'_f_s'];}
else if (o.data[''+o.column.key+'_f']) {return o.data[''+o.column.key+'_f'];}
else if (o.value) {return o.value;}
else {return '';}
};
/** formatting function for table view */
var formatTitle = function(o) {
var el = Y.Node.create('<div/>');
el.appendChild(options.filenode.cloneNode(true)); // TODO not node but string!
el.get('children').addClass(o.data['classname']);
el.one('.fp-filename').setContent(o.value);
if (o.data['icon']) {
el.one('.fp-icon').appendChild(Y.Node.create('<img/>'));
el.one('.fp-icon img').setImgSrc(o.data['icon'], o.data['realicon'], lazyloading);
}
if (options.rightclickcallback) {
el.get('children').addClass('fp-hascontextmenu');
}
// TODO add tooltip with o.data['title'] (o.value) or o.data['thumbnail_title']
return el.getContent();
}
/** sorting function for table view */
var sortFoldersFirst = function(a, b, desc) {
if (a.get('isfolder') && !b.get('isfolder')) {
return -1;
}
if (!a.get('isfolder') && b.get('isfolder')) {
return 1;
}
var aa = a.get(this.key), bb = b.get(this.key), dir = desc ? -1 : 1;
return (aa > bb) ? dir : ((aa < bb) ? -dir : 0);
}
/** initialize table view */
var initialize_table_view = function() {
var cols = [
{key: "displayname", label: M.util.get_string('name', 'moodle'), allowHTML: true, formatter: formatTitle,
sortable: true, sortFn: sortFoldersFirst},
{key: "datemodified", label: M.util.get_string('lastmodified', 'moodle'), allowHTML: true, formatter: formatValue,
sortable: true, sortFn: sortFoldersFirst},
{key: "size", label: M.util.get_string('size', 'repository'), allowHTML: true, formatter: formatValue,
sortable: true, sortFn: sortFoldersFirst},
{key: "mimetype", label: M.util.get_string('type', 'repository'), allowHTML: true,
sortable: true, sortFn: sortFoldersFirst}
];
scope.tableview = new Y.DataTable({columns: cols, data: fileslist});
scope.tableview.delegate('click', function (e, tableview) {
var record = tableview.getRecord(e.currentTarget.get('id'));
if (record) {
var callback = options.callback;
if (options.rightclickcallback && e.target.ancestor('.fp-tableview .fp-contextmenu', true)) {
callback = options.rightclickcallback;
}
Y.bind(callback, this)(e, record.getAttrs());
}
}, 'tr', options.callbackcontext, scope.tableview);
if (options.rightclickcallback) {
scope.tableview.delegate('contextmenu', function (e, tableview) {
var record = tableview.getRecord(e.currentTarget.get('id'));
if (record) { Y.bind(options.rightclickcallback, this)(e, record.getAttrs()); }
}, 'tr', options.callbackcontext, scope.tableview);
}
}
/** append items in table view mode */
var append_files_table = function() {
if (options.appendonly) {
fileslist.forEach(function(el) {
this.tableview.data.add(el);
},scope);
}
scope.tableview.render(scope.one('.'+classname));
scope.tableview.sortable = options.sortable ? true : false;
};
/** append items in tree view mode */
var append_files_tree = function() {
if (options.appendonly) {
var parentnode = scope.treeview.getRoot();
if (scope.treeview.getHighlightedNode()) {
parentnode = scope.treeview.getHighlightedNode();
if (parentnode.isLeaf) {parentnode = parentnode.parent;}
}
for (var k in fileslist) {
build_tree(fileslist[k], parentnode);
}
scope.treeview.draw();
} else {
// otherwise files were already added in initialize_tree_view()
}
}
/** append items in icon view mode */
var append_files_icons = function() {
parent = scope.one('.'+classname);
for (var k in fileslist) {
var node = fileslist[k];
var element = options.filenode.cloneNode(true);
parent.appendChild(element);
element.addClass(options.classnamecallback(node));
var filenamediv = element.one('.fp-filename');
filenamediv.setContent(file_get_displayname(node));
var imgdiv = element.one('.fp-thumbnail'), width, height, src;
if (node.thumbnail) {
width = node.thumbnail_width ? node.thumbnail_width : 90;
height = node.thumbnail_height ? node.thumbnail_height : 90;
src = node.thumbnail;
} else {
width = 16;
height = 16;
src = node.icon;
}
filenamediv.setStyleAdv('width', width);
imgdiv.setStyleAdv('width', width).setStyleAdv('height', height);
var img = Y.Node.create('<img/>').setAttrs({
title: file_get_description(node),
alt: Y.Escape.html(node.thumbnail_alt ? node.thumbnail_alt : file_get_filename(node))}).
setStyle('maxWidth', ''+width+'px').
setStyle('maxHeight', ''+height+'px');
img.setImgSrc(src, node.realthumbnail, lazyloading);
imgdiv.appendChild(img);
element.on('click', function(e, nd) {
if (options.rightclickcallback && e.target.ancestor('.fp-iconview .fp-contextmenu', true)) {
Y.bind(options.rightclickcallback, this)(e, nd);
} else {
Y.bind(options.callback, this)(e, nd);
}
}, options.callbackcontext, node);
if (options.rightclickcallback) {
element.on('contextmenu', options.rightclickcallback, options.callbackcontext, node);
}
}
}
// Notify the user if any of the files has a problem status.
var problemFiles = [];
fileslist.forEach(function(file) {
if (!file_is_folder(file) && file.hasOwnProperty('status') && file.status != 0) {
problemFiles.push(file);
}
});
if (problemFiles.length > 0) {
require(["core/notification", "core/str"], function(Notification, Str) {
problemFiles.forEach(function(problemFile) {
Str.get_string('storedfilecannotreadfile', 'error', problemFile.fullname).then(function(string) {
Notification.addNotification({
message: string,
type: "error"
});
return;
}).catch(Notification.exception);
});
});
}
// If table view, need some additional properties
// before passing fileslist to the YUI tableview
if (options.viewmode == 3) {
fileslist.forEach(function(el) {
el.displayname = file_get_displayname(el);
el.isfolder = file_is_folder(el);
el.classname = options.classnamecallback(el);
}, scope);
}
// initialize files view
if (!options.appendonly) {
var parent = Y.Node.create('<div/>').addClass(classname);
this.setContent('').appendChild(parent);
parent.generateID();
if (options.viewmode == 2) {
initialize_tree_view();
} else if (options.viewmode == 3) {
initialize_table_view();
} else {
// nothing to initialize for icon view
}
}
// append files to the list
if (options.viewmode == 2) {
append_files_tree();
} else if (options.viewmode == 3) {
append_files_table();
} else {
append_files_icons();
}
}
}, '@VERSION@', {
requires:['base', 'node', 'yui2-treeview', 'panel', 'cookie', 'datatable', 'datatable-sort']
});
M.core_filepicker = M.core_filepicker || {};
/**
* instances of file pickers used on page
*/
M.core_filepicker.instances = M.core_filepicker.instances || {};
M.core_filepicker.active_filepicker = null;
/**
* HTML Templates to use in FilePicker
*/
M.core_filepicker.templates = M.core_filepicker.templates || {};
/**
* Array of image sources for real previews (realicon or realthumbnail) that are already loaded
*/
M.core_filepicker.loadedpreviews = M.core_filepicker.loadedpreviews || {};
/**
* Set selected file info
*
* @param object file info
*/
M.core_filepicker.select_file = function(file) {
M.core_filepicker.active_filepicker.select_file(file);
}
/**
* Init and show file picker
*/
M.core_filepicker.show = function(Y, options) {
if (!M.core_filepicker.instances[options.client_id]) {
M.core_filepicker.init(Y, options);
}
M.core_filepicker.instances[options.client_id].options.formcallback = options.formcallback;
M.core_filepicker.instances[options.client_id].show();
};
M.core_filepicker.set_templates = function(Y, templates) {
for (var templid in templates) {
M.core_filepicker.templates[templid] = templates[templid];
}
}
/**
* Add new file picker to current instances
*/
M.core_filepicker.init = function(Y, options) {
var FilePickerHelper = function(options) {
FilePickerHelper.superclass.constructor.apply(this, arguments);
};
FilePickerHelper.NAME = "FilePickerHelper";
FilePickerHelper.ATTRS = {
options: {},
lang: {}
};
Y.extend(FilePickerHelper, Y.Base, {
api: M.cfg.wwwroot+'/repository/repository_ajax.php',
cached_responses: {},
waitinterval : null, // When the loading template is being displayed and its animation is running this will be an interval instance.
initializer: function(options) {
this.options = options;
if (!this.options.savepath) {
this.options.savepath = '/';
}
},
destructor: function() {
},
request: function(args, redraw) {
var api = (args.api ? args.api : this.api) + '?action='+args.action;
var params = {};
var scope = args['scope'] ? args['scope'] : this;
params['repo_id']=args.repository_id;
params['p'] = args.path?args.path:'';
params['page'] = args.page?args.page:'';
params['env']=this.options.env;
// the form element only accept certain file types
params['accepted_types']=this.options.accepted_types;
params['sesskey'] = M.cfg.sesskey;
params['client_id'] = args.client_id;
params['itemid'] = this.options.itemid?this.options.itemid:0;
params['maxbytes'] = this.options.maxbytes?this.options.maxbytes:-1;
// The unlimited value of areamaxbytes is -1, it is defined by FILE_AREA_MAX_BYTES_UNLIMITED.
params['areamaxbytes'] = this.options.areamaxbytes ? this.options.areamaxbytes : -1;
if (this.options.context && this.options.context.id) {
params['ctx_id'] = this.options.context.id;
}
if (args['params']) {
for (i in args['params']) {
params[i] = args['params'][i];
}
}
if (args.action == 'upload') {
var list = [];
for(var k in params) {
var value = params[k];
if(value instanceof Array) {
for(var i in value) {
list.push(k+'[]='+value[i]);
}
} else {
list.push(k+'='+value);
}
}
params = list.join('&');
} else {
params = build_querystring(params);
}
var cfg = {
method: 'POST',
on: {
complete: function(id,o,p) {
var data = null;
try {
data = Y.JSON.parse(o.responseText);
} catch(e) {
if (o && o.status && o.status > 0) {
Y.use('moodle-core-notification-exception', function() {
return new M.core.exception(e);
});
return;
}
}
// error checking
if (data && data.error) {
Y.use('moodle-core-notification-ajaxexception', function () {
return new M.core.ajaxException(data);
});
this.fpnode.one('.fp-content').setContent('');
return;
} else {
if (data.msg) {
scope.print_msg(data.msg, 'info');
}
// cache result if applicable
if (args.action != 'upload' && data.allowcaching) {
scope.cached_responses[params] = data;
}
// invoke callback
args.callback(id,data,p);
}
}
},
arguments: {
scope: scope
},
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
},
data: params,
context: this
};
if (args.form) {
cfg.form = args.form;
}
// check if result of the same request has been already cached. If not, request it
// (never applicable in case of form submission and/or upload action):
if (!args.form && args.action != 'upload' && scope.cached_responses[params]) {
args.callback(null, scope.cached_responses[params], {scope: scope})
} else {
Y.io(api, cfg);
if (redraw) {
this.wait();
}
}
},
/** displays the dialog and processes rename/overwrite if there is a file with the same name in the same filearea*/
process_existing_file: function(data) {
var scope = this;
var handleOverwrite = function(e) {
// overwrite
e.preventDefault();
var data = this.process_dlg.dialogdata;
var params = {}
params['existingfilename'] = data.existingfile.filename;
params['existingfilepath'] = data.existingfile.filepath;
params['newfilename'] = data.newfile.filename;
params['newfilepath'] = data.newfile.filepath;
this.hide_header();
this.request({
'params': params,
'scope': this,
'action':'overwrite',
'path': '',
'client_id': this.options.client_id,
'repository_id': this.active_repo.id,
'callback': function(id, o, args) {
scope.hide();
// Add an arbitrary parameter to the URL to force browsers to re-load the new image even
// if the file name has not changed.
var urlimage = data.existingfile.url + "?time=" + (new Date()).getTime();
if (scope.options.editor_target && scope.options.env == 'editor') {
// editor needs to update url
scope.options.editor_target.value = urlimage;
scope.options.editor_target.onchange();
}
var fileinfo = {'client_id':scope.options.client_id,
'url': urlimage,
'file': data.existingfile.filename};
var formcallback_scope = scope.options.magicscope ? scope.options.magicscope : scope;
scope.options.formcallback.apply(formcallback_scope, [fileinfo]);
}
}, true);
}
var handleRename = function(e) {
// inserts file with the new name
e.preventDefault();
var scope = this;
var data = this.process_dlg.dialogdata;
if (scope.options.editor_target && scope.options.env == 'editor') {
scope.options.editor_target.value = data.newfile.url;
scope.options.editor_target.onchange();
}
scope.hide();
var formcallback_scope = scope.options.magicscope ? scope.options.magicscope : scope;
var fileinfo = {'client_id':scope.options.client_id,
'url':data.newfile.url,
'file':data.newfile.filename};
scope.options.formcallback.apply(formcallback_scope, [fileinfo]);
}
var handleCancel = function(e) {
// Delete tmp file
e.preventDefault();
var params = {};
params['newfilename'] = this.process_dlg.dialogdata.newfile.filename;
params['newfilepath'] = this.process_dlg.dialogdata.newfile.filepath;
this.request({
'params': params,
'scope': this,
'action':'deletetmpfile',
'path': '',
'client_id': this.options.client_id,
'repository_id': this.active_repo.id,
'callback': function(id, o, args) {
// let it be in background, from user point of view nothing is happenning
}
}, false);
this.process_dlg.hide();
this.selectui.hide();
}
if (!this.process_dlg) {
this.process_dlg_node = Y.Node.create(M.core_filepicker.templates.processexistingfile);
var node = this.process_dlg_node;
node.generateID();
this.process_dlg = new M.core.dialogue({
draggable : true,
bodyContent : node,
headerContent: M.util.get_string('fileexistsdialogheader', 'repository'),
centered : true,
modal : true,
visible : false,
zIndex : this.options.zIndex
});
node.one('.fp-dlg-butoverwrite').on('click', handleOverwrite, this);
node.one('.fp-dlg-butrename').on('click', handleRename, this);
node.one('.fp-dlg-butcancel').on('click', handleCancel, this);
if (this.options.env == 'editor') {
node.one('.fp-dlg-text').setContent(M.util.get_string('fileexistsdialog_editor', 'repository'));
} else {
node.one('.fp-dlg-text').setContent(M.util.get_string('fileexistsdialog_filemanager', 'repository'));
}
}
this.selectnode.removeClass('loading');
this.process_dlg.dialogdata = data;
this.process_dlg_node.one('.fp-dlg-butrename').setContent(M.util.get_string('renameto', 'repository', data.newfile.filename));
this.process_dlg.show();
},
/** displays error instead of filepicker contents */
display_error: function(errortext, errorcode) {
this.fpnode.one('.fp-content').setContent(M.core_filepicker.templates.error);
this.fpnode.one('.fp-content .fp-error').
addClass(errorcode).
setContent(Y.Escape.html(errortext));
},
/** displays message in a popup */
print_msg: function(msg, type) {
var header = M.util.get_string('error', 'moodle');
if (type != 'error') {
type = 'info'; // one of only two types excepted
header = M.util.get_string('info', 'moodle');
}
if (!this.msg_dlg) {
this.msg_dlg_node = Y.Node.create(M.core_filepicker.templates.message);
this.msg_dlg_node.generateID();
this.msg_dlg = new M.core.dialogue({
draggable : true,
bodyContent : this.msg_dlg_node,
centered : true,
modal : true,
visible : false,
zIndex : this.options.zIndex
});
this.msg_dlg_node.one('.fp-msg-butok').on('click', function(e) {
e.preventDefault();
this.msg_dlg.hide();
}, this);
}
this.msg_dlg.set('headerContent', header);
this.msg_dlg_node.removeClass('fp-msg-info').removeClass('fp-msg-error').addClass('fp-msg-'+type)
this.msg_dlg_node.one('.fp-msg-text').setContent(Y.Escape.html(msg));
this.msg_dlg.show();
},
view_files: function(appenditems) {
this.viewbar_set_enabled(true);
this.print_path();
/*if ((appenditems == null) && (!this.filelist || !this.filelist.length) && !this.active_repo.hasmorepages) {
// TODO do it via classes and adjust for each view mode!
// If there are no items and no next page, just display status message and quit
this.display_error(M.util.get_string('nofilesavailable', 'repository'), 'nofilesavailable');
return;
}*/
if (this.viewmode == 2) {
this.view_as_list(appenditems);
} else if (this.viewmode == 3) {
this.view_as_table(appenditems);
} else {
this.view_as_icons(appenditems);
}
this.fpnode.one('.fp-content').setAttribute('tabindex', '0');
this.fpnode.one('.fp-content').focus();
// display/hide the link for requesting next page
if (!appenditems && this.active_repo.hasmorepages) {
if (!this.fpnode.one('.fp-content .fp-nextpage')) {
this.fpnode.one('.fp-content').append(M.core_filepicker.templates.nextpage);
}
this.fpnode.one('.fp-content .fp-nextpage').one('a,button').on('click', function(e) {
e.preventDefault();
this.fpnode.one('.fp-content .fp-nextpage').addClass('loading');
this.request_next_page();
}, this);
}
if (!this.active_repo.hasmorepages && this.fpnode.one('.fp-content .fp-nextpage')) {
this.fpnode.one('.fp-content .fp-nextpage').remove();
}
if (this.fpnode.one('.fp-content .fp-nextpage')) {
this.fpnode.one('.fp-content .fp-nextpage').removeClass('loading');
}
this.content_scrolled();
},
content_scrolled: function(e) {
setTimeout(Y.bind(function() {
if (this.processingimages) {
return;
}
this.processingimages = true;
var scope = this,
fpcontent = this.fpnode.one('.fp-content'),
fpcontenty = fpcontent.getY(),
fpcontentheight = fpcontent.getStylePx('height'),
nextpage = fpcontent.one('.fp-nextpage'),
is_node_visible = function(node) {
var offset = node.getY()-fpcontenty;
if (offset <= fpcontentheight && (offset >=0 || offset+node.getStylePx('height')>=0)) {
return true;
}
return false;
};
// automatically load next page when 'more' link becomes visible
if (nextpage && !nextpage.hasClass('loading') && is_node_visible(nextpage)) {
nextpage.one('a,button').simulate('click');
}
// replace src for visible images that need to be lazy-loaded
if (scope.lazyloading) {
fpcontent.all('img').each( function(node) {
if (node.get('id') && scope.lazyloading[node.get('id')] && is_node_visible(node)) {
node.setImgRealSrc(scope.lazyloading);
}
});
}
this.processingimages = false;
}, this), 200)
},
treeview_dynload: function(node, cb) {
var retrieved_children = {};
if (node.children) {
for (var i in node.children) {
retrieved_children[node.children[i].path] = node.children[i];
}
}
this.request({
action:'list',
client_id: this.options.client_id,
repository_id: this.active_repo.id,
path:node.path?node.path:'',
page:node.page?args.page:'',
scope:this,
callback: function(id, obj, args) {
var list = obj.list;
var scope = args.scope;
// check that user did not leave the view mode before recieving this response
if (!(scope.active_repo.id == obj.repo_id && scope.viewmode == 2 && node && node.getChildrenEl())) {
return;
}
if (cb != null) { // (in manual mode do not update current path)
scope.viewbar_set_enabled(true);
scope.parse_repository_options(obj);
}
node.highlight(false);
node.origlist = obj.list ? obj.list : null;
node.origpath = obj.path ? obj.path : null;
node.children = [];
for(k in list) {
if (list[k].children && retrieved_children[list[k].path]) {
// if this child is a folder and has already been retrieved
node.children[node.children.length] = retrieved_children[list[k].path];
} else {
// append new file to the list
scope.view_as_list([list[k]]);
}
}
if (cb == null) {
node.refresh();
} else {
// invoke callback requested by TreeView component
cb();
}
scope.content_scrolled();
}
}, false);
},
classnamecallback : function(node) {
var classname = '';
if (node.children) {
classname = classname + ' fp-folder';
}
if (node.isref) {
classname = classname + ' fp-isreference';
}
if (node.iscontrolledlink) {
classname = classname + ' fp-iscontrolledlink';
}
if (node.refcount) {
classname = classname + ' fp-hasreferences';
}
if (node.originalmissing) {
classname = classname + ' fp-originalmissing';
}
return Y.Lang.trim(classname);
},
/** displays list of files in tree (list) view mode. If param appenditems is specified,
* appends those items to the end of the list. Otherwise (default behaviour)
* clears the contents and displays the items from this.filelist */
view_as_list: function(appenditems) {
var list = (appenditems != null) ? appenditems : this.filelist;
this.viewmode = 2;
if (!this.filelist || this.filelist.length==0 && (!this.filepath || !this.filepath.length)) {
this.display_error(M.util.get_string('nofilesavailable', 'repository'), 'nofilesavailable');
return;
}
var element_template = Y.Node.create(M.core_filepicker.templates.listfilename);
var options = {
viewmode : this.viewmode,
appendonly : (appenditems != null),
filenode : element_template,
callbackcontext : this,
callback : function(e, node) {
// TODO MDL-32736 e is not an event here but an object with properties 'event' and 'node'
if (!node.children) {
if (e.node.parent && e.node.parent.origpath) {
// set the current path
this.filepath = e.node.parent.origpath;
this.filelist = e.node.parent.origlist;
this.print_path();
}
this.select_file(node);
} else {
// save current path and filelist (in case we want to jump to other viewmode)
this.filepath = e.node.origpath;
this.filelist = e.node.origlist;
this.currentpath = e.node.path;
this.print_path();
this.content_scrolled();
}
},
classnamecallback : this.classnamecallback,
dynload : this.active_repo.dynload,
filepath : this.filepath,
treeview_dynload : this.treeview_dynload
};
this.fpnode.one('.fp-content').fp_display_filelist(options, list, this.lazyloading);
},
/** displays list of files in icon view mode. If param appenditems is specified,
* appends those items to the end of the list. Otherwise (default behaviour)
* clears the contents and displays the items from this.filelist */
view_as_icons: function(appenditems) {
this.viewmode = 1;
var list = (appenditems != null) ? appenditems : this.filelist;
var element_template = Y.Node.create(M.core_filepicker.templates.iconfilename);
if ((appenditems == null) && (!this.filelist || !this.filelist.length)) {
this.display_error(M.util.get_string('nofilesavailable', 'repository'), 'nofilesavailable');
return;
}
var options = {
viewmode : this.viewmode,
appendonly : (appenditems != null),
filenode : element_template,
callbackcontext : this,
callback : function(e, node) {
if (e.preventDefault) {
e.preventDefault();
}
if(node.children) {
if (this.active_repo.dynload) {
this.list({'path':node.path});
} else {
this.filelist = node.children;