/
plupload.js
1623 lines (1387 loc) · 40.5 KB
/
plupload.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
/**
* plupload.js
*
* Copyright 2009, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
// JSLint defined globals
/*global window:false, escape:false */
/*!@@version@@*/
(function() {
var count = 0, runtimes = [], i18n = {}, mimes = {},
xmlEncodeChars = {'<' : 'lt', '>' : 'gt', '&' : 'amp', '"' : 'quot', '\'' : '#39'},
xmlEncodeRegExp = /[<>&\"\']/g, undef, delay = window.setTimeout,
// A place to store references to event handlers
eventhash = {},
uid;
// IE W3C like event funcs
function preventDefault() {
this.returnValue = false;
}
function stopPropagation() {
this.cancelBubble = true;
}
// Parses the default mime types string into a mimes lookup map
(function(mime_data) {
var items = mime_data.split(/,/), i, y, ext;
for (i = 0; i < items.length; i += 2) {
ext = items[i + 1].split(/ /);
for (y = 0; y < ext.length; y++) {
mimes[ext[y]] = items[i];
}
}
})(
"application/msword,doc dot," +
"application/pdf,pdf," +
"application/pgp-signature,pgp," +
"application/postscript,ps ai eps," +
"application/rtf,rtf," +
"application/vnd.ms-excel,xls xlb," +
"application/vnd.ms-powerpoint,ppt pps pot," +
"application/zip,zip," +
"application/x-shockwave-flash,swf swfl," +
"application/vnd.openxmlformats,docx pptx xlsx," +
"audio/mpeg,mpga mpega mp2 mp3," +
"audio/x-wav,wav," +
"audio/mp4,m4a," +
"image/bmp,bmp," +
"image/gif,gif," +
"image/jpeg,jpeg jpg jpe," +
"image/png,png," +
"image/svg+xml,svg svgz," +
"image/tiff,tiff tif," +
"text/html,htm html xhtml," +
"text/rtf,rtf," +
"video/mpeg,mpeg mpg mpe," +
"video/quicktime,qt mov," +
"video/mp4,mp4," +
"video/x-m4v,m4v," +
"video/x-flv,flv," +
"video/vnd.rn-realvideo,rv," +
"text/plain,asc txt text diff log," +
"application/octet-stream,exe"
);
/**
* Plupload class with some global constants and functions.
*
* @example
* // Encode entities
* console.log(plupload.xmlEncode("My string <>"));
*
* // Generate unique id
* console.log(plupload.guid());
*
* @static
* @class plupload
*/
var plupload = {
/**
* Plupload version will be replaced on build.
*/
VERSION : '@@version@@',
/**
* Inital state of the queue and also the state ones it's finished all it's uploads.
*
* @property STOPPED
* @final
*/
STOPPED : 1,
/**
* Upload process is running
*
* @property STARTED
* @final
*/
STARTED : 2,
/**
* File is queued for upload
*
* @property QUEUED
* @final
*/
QUEUED : 1,
/**
* File is being uploaded
*
* @property UPLOADING
* @final
*/
UPLOADING : 2,
/**
* File has failed to be uploaded
*
* @property FAILED
* @final
*/
FAILED : 4,
/**
* File has been uploaded successfully
*
* @property DONE
* @final
*/
DONE : 5,
// Error constants used by the Error event
/**
* Generic error for example if an exception is thrown inside Silverlight.
*
* @property GENERIC_ERROR
* @final
*/
GENERIC_ERROR : -100,
/**
* HTTP transport error. For example if the server produces a HTTP status other than 200.
*
* @property HTTP_ERROR
* @final
*/
HTTP_ERROR : -200,
/**
* Generic I/O error. For exampe if it wasn't possible to open the file stream on local machine.
*
* @property IO_ERROR
* @final
*/
IO_ERROR : -300,
/**
* Generic I/O error. For exampe if it wasn't possible to open the file stream on local machine.
*
* @property SECURITY_ERROR
* @final
*/
SECURITY_ERROR : -400,
/**
* Initialization error. Will be triggered if no runtime was initialized.
*
* @property INIT_ERROR
* @final
*/
INIT_ERROR : -500,
/**
* File size error. If the user selects a file that is to large it will be blocked and an error of this type will be triggered.
*
* @property FILE_SIZE_ERROR
* @final
*/
FILE_SIZE_ERROR : -600,
/**
* File extension error. If the user selects a file that isn't valid according to the filters setting.
*
* @property FILE_EXTENSION_ERROR
* @final
*/
FILE_EXTENSION_ERROR : -700,
/**
* Mime type lookup table.
*
* @property mimeTypes
* @type Object
* @final
*/
mimeTypes : mimes,
/**
* Extends the specified object with another object.
*
* @method extend
* @param {Object} target Object to extend.
* @param {Object..} obj Multiple objects to extend with.
* @return {Object} Same as target, the extended object.
*/
extend : function(target) {
plupload.each(arguments, function(arg, i) {
if (i > 0) {
plupload.each(arg, function(value, key) {
target[key] = value;
});
}
});
return target;
},
/**
* Cleans the specified name from national characters (diacritics). The result will be a name with only a-z, 0-9 and _.
*
* @method cleanName
* @param {String} s String to clean up.
* @return {String} Cleaned string.
*/
cleanName : function(name) {
var i, lookup;
// Replace diacritics
lookup = [
/[\300-\306]/g, 'A', /[\340-\346]/g, 'a',
/\307/g, 'C', /\347/g, 'c',
/[\310-\313]/g, 'E', /[\350-\353]/g, 'e',
/[\314-\317]/g, 'I', /[\354-\357]/g, 'i',
/\321/g, 'N', /\361/g, 'n',
/[\322-\330]/g, 'O', /[\362-\370]/g, 'o',
/[\331-\334]/g, 'U', /[\371-\374]/g, 'u'
];
for (i = 0; i < lookup.length; i += 2) {
name = name.replace(lookup[i], lookup[i + 1]);
}
// Replace whitespace
name = name.replace(/\s+/g, '_');
// Remove anything else
name = name.replace(/[^a-z0-9_\-\.]+/gi, '');
return name;
},
/**
* Adds a specific upload runtime like for example flash or gears.
*
* @method addRuntime
* @param {String} name Runtime name for example flash.
* @param {Object} obj Object containing init/destroy method.
*/
addRuntime : function(name, runtime) {
runtime.name = name;
runtimes[name] = runtime;
runtimes.push(runtime);
return runtime;
},
/**
* Generates an unique ID. This is 99.99% unique since it takes the current time and 5 random numbers.
* The only way a user would be able to get the same ID is if the two persons at the same exact milisecond manages
* to get 5 the same random numbers between 0-65535 it also uses a counter so each call will be guaranteed to be page unique.
* It's more probable for the earth to be hit with an ansteriod. You can also if you want to be 100% sure set the plupload.guidPrefix property
* to an user unique key.
*
* @method guid
* @return {String} Virtually unique id.
*/
guid : function() {
var guid = new Date().getTime().toString(32), i;
for (i = 0; i < 5; i++) {
guid += Math.floor(Math.random() * 65535).toString(32);
}
return (plupload.guidPrefix || 'p') + guid + (count++).toString(32);
},
/**
* Builds a full url out of a base URL and an object with items to append as query string items.
*
* @param {String} url Base URL to append query string items to.
* @param {Object} items Name/value object to serialize as a querystring.
* @return {String} String with url + serialized query string items.
*/
buildUrl : function(url, items) {
var query = '';
plupload.each(items, function(value, name) {
query += (query ? '&' : '') + encodeURIComponent(name) + '=' + encodeURIComponent(value);
});
if (query) {
url += (url.indexOf('?') > 0 ? '&' : '?') + query;
}
return url;
},
/**
* Executes the callback function for each item in array/object. If you return false in the
* callback it will break the loop.
*
* @param {Object} obj Object to iterate.
* @param {function} callback Callback function to execute for each item.
*/
each : function(obj, callback) {
var length, key, i;
if (obj) {
length = obj.length;
if (length === undef) {
// Loop object items
for (key in obj) {
if (obj.hasOwnProperty(key)) {
if (callback(obj[key], key) === false) {
return;
}
}
}
} else {
// Loop array items
for (i = 0; i < length; i++) {
if (callback(obj[i], i) === false) {
return;
}
}
}
}
},
/**
* Formats the specified number as a size string for example 1024 becomes 1 KB.
*
* @method formatSize
* @param {Number} size Size to format as string.
* @return {String} Formatted size string.
*/
formatSize : function(size) {
if (size === undef || /\D/.test(size)) {
return plupload.translate('N/A');
}
// GB
if (size > 1073741824) {
return Math.round(size / 1073741824, 1) + " GB";
}
// MB
if (size > 1048576) {
return Math.round(size / 1048576, 1) + " MB";
}
// KB
if (size > 1024) {
return Math.round(size / 1024, 1) + " KB";
}
return size + " b";
},
/**
* Returns the absolute x, y position of an Element. The position will be returned in a object with x, y fields.
*
* @method getPos
* @param {Element} node HTML element or element id to get x, y position from.
* @param {Element} root Optional root element to stop calculations at.
* @return {object} Absolute position of the specified element object with x, y fields.
*/
getPos : function(node, root) {
var x = 0, y = 0, parent, doc = document, nodeRect, rootRect;
node = node;
root = root || doc.body;
// Returns the x, y cordinate for an element on IE 6 and IE 7
function getIEPos(node) {
var bodyElm, rect, x = 0, y = 0;
if (node) {
rect = node.getBoundingClientRect();
bodyElm = doc.compatMode === "CSS1Compat" ? doc.documentElement : doc.body;
x = rect.left + bodyElm.scrollLeft;
y = rect.top + bodyElm.scrollTop;
}
return {
x : x,
y : y
};
}
// Use getBoundingClientRect on IE 6 and IE 7 but not on IE 8 in standards mode
if (node && node.getBoundingClientRect && (navigator.userAgent.indexOf('MSIE') > 0 && doc.documentMode !== 8)) {
nodeRect = getIEPos(node);
rootRect = getIEPos(root);
return {
x : nodeRect.x - rootRect.x,
y : nodeRect.y - rootRect.y
};
}
parent = node;
while (parent && parent != root && parent.nodeType) {
x += parent.offsetLeft || 0;
y += parent.offsetTop || 0;
parent = parent.offsetParent;
}
parent = node.parentNode;
while (parent && parent != root && parent.nodeType) {
x -= parent.scrollLeft || 0;
y -= parent.scrollTop || 0;
parent = parent.parentNode;
}
return {
x : x,
y : y
};
},
/**
* Returns the size of the specified node in pixels.
*
* @param {Node} node Node to get the size of.
* @return {Object} Object with a w and h property.
*/
getSize : function(node) {
return {
w : node.offsetWidth || node.clientWidth,
h : node.offsetHeight || node.clientHeight
};
},
/**
* Parses the specified size string into a byte value. For example 10kb becomes 10240.
*
* @method parseSize
* @param {String/Number} size String to parse or number to just pass through.
* @return {Number} Size in bytes.
*/
parseSize : function(size) {
var mul;
if (typeof(size) == 'string') {
size = /^([0-9]+)([mgk]+)$/.exec(size.toLowerCase().replace(/[^0-9mkg]/g, ''));
mul = size[2];
size = +size[1];
if (mul == 'g') {
size *= 1073741824;
}
if (mul == 'm') {
size *= 1048576;
}
if (mul == 'k') {
size *= 1024;
}
}
return size;
},
/**
* Encodes the specified string.
*
* @method xmlEncode
* @param {String} s String to encode.
* @return {String} Encoded string.
*/
xmlEncode : function(str) {
return str ? ('' + str).replace(xmlEncodeRegExp, function(chr) {
return xmlEncodeChars[chr] ? '&' + xmlEncodeChars[chr] + ';' : chr;
}) : str;
},
/**
* Forces anything into an array.
*
* @method toArray
* @param {Object} obj Object with length field.
* @return {Array} Array object containing all items.
*/
toArray : function(obj) {
var i, arr = [];
for (i = 0; i < obj.length; i++) {
arr[i] = obj[i];
}
return arr;
},
/**
* Extends the language pack object with new items.
*
* @param {Object} pack Language pack items to add.
* @return {Object} Extended language pack object.
*/
addI18n : function(pack) {
return plupload.extend(i18n, pack);
},
/**
* Translates the specified string by checking for the english string in the language pack lookup.
*
* @param {String} str String to look for.
* @reutrn {String} Translated string or the input string if it wasn't found.
*/
translate : function(str) {
return i18n[str] || str;
},
/**
* Checks if specified DOM element has specified class.
*
* @param {Object} obj DOM element like object to add handler to.
* @param {String} name Class name
*/
hasClass : function(obj, name) {
var regExp;
if (obj.className == '') {
return false;
}
regExp = new RegExp("(^|\\s+)"+name+"(\\s+|$)");
return regExp.test(obj.className);
},
/**
* Adds specified className to specified DOM element.
*
* @param {Object} obj DOM element like object to add handler to.
* @param {String} name Class name
*/
addClass : function(obj, name) {
if (!plupload.hasClass(obj, name)) {
obj.className = obj.className == '' ? name : obj.className.replace(/\s+$/, '')+' '+name;
}
},
/**
* Removes specified className from specified DOM element.
*
* @param {Object} obj DOM element like object to add handler to.
* @param {String} name Class name
*/
removeClass : function(obj, name) {
var regExp = new RegExp("(^|\\s+)"+name+"(\\s+|$)");
obj.className = obj.className.replace(regExp, function($0, $1, $2) {
return $1 === ' ' && $2 === ' ' ? ' ' : '';
});
},
/**
* Adds an event handler to the specified object and store reference to the handler
* in objects internal Plupload registry (@see removeEvent).
*
* @param {Object} obj DOM element like object to add handler to.
* @param {String} name Name to add event listener to.
* @param {Function} callback Function to call when event occurs.
* @param {String} (optional) key that might be used to add specifity to the event record.
*/
addEvent : function(obj, name, callback) {
var func, events, types, key;
// if passed in, event will be locked with this key - one would need to provide it to removeEvent
key = arguments[3];
name = name.toLowerCase();
// Initialize unique identifier if needed
if (uid === undef) {
uid = 'Plupload_' + plupload.guid();
}
// Add event listener
if (obj.attachEvent) {
func = function() {
var evt = window.event;
if (!evt.target) {
evt.target = evt.srcElement;
}
evt.preventDefault = preventDefault;
evt.stopPropagation = stopPropagation;
callback(evt);
};
obj.attachEvent('on' + name, func);
} else if (obj.addEventListener) {
func = callback;
obj.addEventListener(name, func, false);
}
// Log event handler to objects internal Plupload registry
if (obj[uid] === undef) {
obj[uid] = plupload.guid();
}
if (!eventhash.hasOwnProperty(obj[uid])) {
eventhash[obj[uid]] = {};
}
events = eventhash[obj[uid]];
if (!events.hasOwnProperty(name)) {
events[name] = [];
}
events[name].push({
func: func,
orig: callback, // store original callback for IE
key: key
});
},
/**
* Remove event handler from the specified object. If third argument (callback)
* is not specified remove all events with the specified name.
*
* @param {Object} obj DOM element to remove event listener(s) from.
* @param {String} name Name of event listener to remove.
* @param {Function|String} (optional) might be a callback or unique key to match.
*/
removeEvent: function(obj, name) {
var type, callback, key,
// check if object is empty
isEmptyObj = function(obj) {
for (var prop in obj) {
return false;
}
return true;
};
// match the handler either by callback or by key
if (typeof(arguments[2]) == "function") {
callback = arguments[2];
} else {
key = arguments[2];
}
name = name.toLowerCase();
if (obj[uid] && eventhash[obj[uid]] && eventhash[obj[uid]][name]) {
type = eventhash[obj[uid]][name];
} else {
return;
}
for (var i=type.length-1; i>=0; i--) {
// undefined or not, key should match
if (type[i].key === key || type[i].orig === callback) {
if (obj.detachEvent) {
obj.detachEvent('on'+name, type[i].func);
} else if (obj.removeEventListener) {
obj.removeEventListener(name, type[i].func, false);
}
type[i].orig = null;
type[i].func = null;
type.splice(i, 1);
// If callback was passed we are done here, otherwise proceed
if (callback !== undef) {
break;
}
}
}
// If event array got empty, remove it
if (!type.length) {
delete eventhash[obj[uid]][name];
}
// If Plupload registry has become empty, remove it
if (isEmptyObj(eventhash[obj[uid]])) {
delete eventhash[obj[uid]];
// IE doesn't let you remove DOM object property with - delete
try {
delete obj[uid];
} catch(e) {
obj[uid] = undef;
}
}
},
/**
* Remove all kind of events from the specified object
*
* @param {Object} obj DOM element to remove event listeners from.
* @param {String} (optional) unique key to match, when removing events.
*/
removeAllEvents: function(obj) {
var key = arguments[1];
if (obj[uid] === undef || !obj[uid]) {
return;
}
plupload.each(eventhash[obj[uid]], function(events, name) {
plupload.removeEvent(obj, name, key);
});
}
};
/**
* Uploader class, an instance of this class will be created for each upload field.
*
* @example
* var uploader = new plupload.Uploader({
* runtimes : 'gears,html5,flash',
* browse_button : 'button_id'
* });
*
* uploader.bind('Init', function(up) {
* alert('Supports drag/drop: ' + (!!up.features.dragdrop));
* });
*
* uploader.bind('FilesAdded', function(up, files) {
* alert('Selected files: ' + files.length);
* });
*
* uploader.bind('QueueChanged', function(up) {
* alert('Queued files: ' + uploader.files.length);
* });
*
* uploader.init();
*
* @class plupload.Uploader
*/
/**
* Constructs a new uploader instance.
*
* @constructor
* @method Uploader
* @param {Object} settings Initialization settings, to be used by the uploader instance and runtimes.
*/
plupload.Uploader = function(settings) {
var events = {}, total, files = [], startTime;
// Inital total state
total = new plupload.QueueProgress();
// Default settings
settings = plupload.extend({
chunk_size : 0,
multipart : true,
multi_selection : true,
file_data_name : 'file',
filters : []
}, settings);
// Private methods
function uploadNext() {
var file, count = 0, i;
if (this.state == plupload.STARTED) {
// Find first QUEUED file
for (i = 0; i < files.length; i++) {
if (!file && files[i].status == plupload.QUEUED) {
file = files[i];
file.status = plupload.UPLOADING;
this.trigger("BeforeUpload", file);
this.trigger("UploadFile", file);
} else {
count++;
}
}
// All files are DONE or FAILED
if (count == files.length) {
this.trigger("UploadComplete", files);
this.stop();
}
}
}
function calc() {
var i, file;
// Reset stats
total.reset();
// Check status, size, loaded etc on all files
for (i = 0; i < files.length; i++) {
file = files[i];
if (file.size !== undef) {
total.size += file.size;
total.loaded += file.loaded;
} else {
total.size = undef;
}
if (file.status == plupload.DONE) {
total.uploaded++;
} else if (file.status == plupload.FAILED) {
total.failed++;
} else {
total.queued++;
}
}
// If we couldn't calculate a total file size then use the number of files to calc percent
if (total.size === undef) {
total.percent = files.length > 0 ? Math.ceil(total.uploaded / files.length * 100) : 0;
} else {
total.bytesPerSec = Math.ceil(total.loaded / ((+new Date() - startTime || 1) / 1000.0));
total.percent = total.size > 0 ? Math.ceil(total.loaded / total.size * 100) : 0;
}
}
// Add public methods
plupload.extend(this, {
/**
* Current state of the total uploading progress. This one can either be plupload.STARTED or plupload.STOPPED.
* These states are controlled by the stop/start methods. The default value is STOPPED.
*
* @property state
* @type Number
*/
state : plupload.STOPPED,
/**
* Current runtime name.
*
* @property runtime
* @type String
*/
runtime: '',
/**
* Map of features that are available for the uploader runtime. Features will be filled
* before the init event is called, these features can then be used to alter the UI for the end user.
* Some of the current features that might be in this map is: dragdrop, chunks, jpgresize, pngresize.
*
* @property features
* @type Object
*/
features : {},
/**
* Current upload queue, an array of File instances.
*
* @property files
* @type Array
* @see plupload.File
*/
files : files,
/**
* Object with name/value settings.
*
* @property settings
* @type Object
*/
settings : settings,
/**
* Total progess information. How many files has been uploaded, total percent etc.
*
* @property total
* @type plupload.QueueProgress
*/
total : total,
/**
* Unique id for the Uploader instance.
*
* @property id
* @type String
*/
id : plupload.guid(),
/**
* Initializes the Uploader instance and adds internal event listeners.
*
* @method init
*/
init : function() {
var self = this, i, runtimeList, a, runTimeIndex = 0, items;
if (typeof(settings.preinit) == "function") {
settings.preinit(self);
} else {
plupload.each(settings.preinit, function(func, name) {
self.bind(name, func);
});
}
settings.page_url = settings.page_url || document.location.pathname.replace(/\/[^\/]+$/g, '/');
// If url is relative force it absolute to the current page
if (!/^(\w+:\/\/|\/)/.test(settings.url)) {
settings.url = settings.page_url + settings.url;
}
// Convert settings
settings.chunk_size = plupload.parseSize(settings.chunk_size);
settings.max_file_size = plupload.parseSize(settings.max_file_size);
// Add files to queue
self.bind('FilesAdded', function(up, selected_files) {
var i, file, count = 0, extensionsRegExp, filters = settings.filters;
// Convert extensions to regexp
if (filters && filters.length) {
extensionsRegExp = [];
plupload.each(filters, function(filter) {
plupload.each(filter.extensions.split(/,/), function(ext) {
extensionsRegExp.push('\\.' + ext.replace(new RegExp('[' + ('/^$.*+?|()[]{}\\'.replace(/./g, '\\$&')) + ']', 'g'), '\\$&'));
});
});
extensionsRegExp = new RegExp(extensionsRegExp.join('|') + '$', 'i');
}
for (i = 0; i < selected_files.length; i++) {
file = selected_files[i];
file.loaded = 0;
file.percent = 0;
file.status = plupload.QUEUED;
// Invalid file extension
if (extensionsRegExp && !extensionsRegExp.test(file.name)) {
up.trigger('Error', {
code : plupload.FILE_EXTENSION_ERROR,
message : plupload.translate('File extension error.'),
file : file
});
continue;
}
// Invalid file size
if (file.size !== undef && file.size > settings.max_file_size) {
up.trigger('Error', {
code : plupload.FILE_SIZE_ERROR,
message : plupload.translate('File size error.'),
file : file
});
continue;
}
// Add valid file to list
files.push(file);
count++;
}
// Only trigger QueueChanged event if any files where added
if (count) {
delay(function() {
self.trigger("QueueChanged");
self.refresh();