plupload.dev.js 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273
  1. /**
  2. * Plupload - multi-runtime File Uploader
  3. * v2.1.1
  4. *
  5. * Copyright 2013, Moxiecode Systems AB
  6. * Released under GPL License.
  7. *
  8. * License: http://www.plupload.com/license
  9. * Contributing: http://www.plupload.com/contributing
  10. *
  11. * Date: 2014-01-16
  12. */
  13. /**
  14. * Plupload.js
  15. *
  16. * Copyright 2013, Moxiecode Systems AB
  17. * Released under GPL License.
  18. *
  19. * License: http://www.plupload.com/license
  20. * Contributing: http://www.plupload.com/contributing
  21. */
  22. /*global mOxie:true */
  23. ;(function(window, o, undef) {
  24. var delay = window.setTimeout
  25. , fileFilters = {}
  26. ;
  27. // convert plupload features to caps acceptable by mOxie
  28. function normalizeCaps(settings) {
  29. var features = settings.required_features, caps = {};
  30. function resolve(feature, value, strict) {
  31. // Feature notation is deprecated, use caps (this thing here is required for backward compatibility)
  32. var map = {
  33. chunks: 'slice_blob',
  34. jpgresize: 'send_binary_string',
  35. pngresize: 'send_binary_string',
  36. progress: 'report_upload_progress',
  37. multi_selection: 'select_multiple',
  38. dragdrop: 'drag_and_drop',
  39. drop_element: 'drag_and_drop',
  40. headers: 'send_custom_headers',
  41. canSendBinary: 'send_binary',
  42. triggerDialog: 'summon_file_dialog'
  43. };
  44. if (map[feature]) {
  45. caps[map[feature]] = value;
  46. } else if (!strict) {
  47. caps[feature] = value;
  48. }
  49. }
  50. if (typeof(features) === 'string') {
  51. plupload.each(features.split(/\s*,\s*/), function(feature) {
  52. resolve(feature, true);
  53. });
  54. } else if (typeof(features) === 'object') {
  55. plupload.each(features, function(value, feature) {
  56. resolve(feature, value);
  57. });
  58. } else if (features === true) {
  59. // check settings for required features
  60. if (!settings.multipart) { // special care for multipart: false
  61. caps.send_binary_string = true;
  62. }
  63. if (settings.chunk_size > 0) {
  64. caps.slice_blob = true;
  65. }
  66. if (settings.resize.enabled) {
  67. caps.send_binary_string = true;
  68. }
  69. plupload.each(settings, function(value, feature) {
  70. resolve(feature, !!value, true); // strict check
  71. });
  72. }
  73. return caps;
  74. }
  75. /**
  76. * @module plupload
  77. * @static
  78. */
  79. var plupload = {
  80. /**
  81. * Plupload version will be replaced on build.
  82. *
  83. * @property VERSION
  84. * @for Plupload
  85. * @static
  86. * @final
  87. */
  88. VERSION : '2.1.1',
  89. /**
  90. * Inital state of the queue and also the state ones it's finished all it's uploads.
  91. *
  92. * @property STOPPED
  93. * @static
  94. * @final
  95. */
  96. STOPPED : 1,
  97. /**
  98. * Upload process is running
  99. *
  100. * @property STARTED
  101. * @static
  102. * @final
  103. */
  104. STARTED : 2,
  105. /**
  106. * File is queued for upload
  107. *
  108. * @property QUEUED
  109. * @static
  110. * @final
  111. */
  112. QUEUED : 1,
  113. /**
  114. * File is being uploaded
  115. *
  116. * @property UPLOADING
  117. * @static
  118. * @final
  119. */
  120. UPLOADING : 2,
  121. /**
  122. * File has failed to be uploaded
  123. *
  124. * @property FAILED
  125. * @static
  126. * @final
  127. */
  128. FAILED : 4,
  129. /**
  130. * File has been uploaded successfully
  131. *
  132. * @property DONE
  133. * @static
  134. * @final
  135. */
  136. DONE : 5,
  137. // Error constants used by the Error event
  138. /**
  139. * Generic error for example if an exception is thrown inside Silverlight.
  140. *
  141. * @property GENERIC_ERROR
  142. * @static
  143. * @final
  144. */
  145. GENERIC_ERROR : -100,
  146. /**
  147. * HTTP transport error. For example if the server produces a HTTP status other than 200.
  148. *
  149. * @property HTTP_ERROR
  150. * @static
  151. * @final
  152. */
  153. HTTP_ERROR : -200,
  154. /**
  155. * Generic I/O error. For exampe if it wasn't possible to open the file stream on local machine.
  156. *
  157. * @property IO_ERROR
  158. * @static
  159. * @final
  160. */
  161. IO_ERROR : -300,
  162. /**
  163. * Generic I/O error. For exampe if it wasn't possible to open the file stream on local machine.
  164. *
  165. * @property SECURITY_ERROR
  166. * @static
  167. * @final
  168. */
  169. SECURITY_ERROR : -400,
  170. /**
  171. * Initialization error. Will be triggered if no runtime was initialized.
  172. *
  173. * @property INIT_ERROR
  174. * @static
  175. * @final
  176. */
  177. INIT_ERROR : -500,
  178. /**
  179. * File size error. If the user selects a file that is too large it will be blocked and an error of this type will be triggered.
  180. *
  181. * @property FILE_SIZE_ERROR
  182. * @static
  183. * @final
  184. */
  185. FILE_SIZE_ERROR : -600,
  186. /**
  187. * File extension error. If the user selects a file that isn't valid according to the filters setting.
  188. *
  189. * @property FILE_EXTENSION_ERROR
  190. * @static
  191. * @final
  192. */
  193. FILE_EXTENSION_ERROR : -601,
  194. /**
  195. * Duplicate file error. If prevent_duplicates is set to true and user selects the same file again.
  196. *
  197. * @property FILE_DUPLICATE_ERROR
  198. * @static
  199. * @final
  200. */
  201. FILE_DUPLICATE_ERROR : -602,
  202. /**
  203. * Runtime will try to detect if image is proper one. Otherwise will throw this error.
  204. *
  205. * @property IMAGE_FORMAT_ERROR
  206. * @static
  207. * @final
  208. */
  209. IMAGE_FORMAT_ERROR : -700,
  210. /**
  211. * While working on the image runtime will try to detect if the operation may potentially run out of memeory and will throw this error.
  212. *
  213. * @property IMAGE_MEMORY_ERROR
  214. * @static
  215. * @final
  216. */
  217. IMAGE_MEMORY_ERROR : -701,
  218. /**
  219. * Each runtime has an upper limit on a dimension of the image it can handle. If bigger, will throw this error.
  220. *
  221. * @property IMAGE_DIMENSIONS_ERROR
  222. * @static
  223. * @final
  224. */
  225. IMAGE_DIMENSIONS_ERROR : -702,
  226. /**
  227. * Mime type lookup table.
  228. *
  229. * @property mimeTypes
  230. * @type Object
  231. * @final
  232. */
  233. mimeTypes : o.mimes,
  234. /**
  235. * In some cases sniffing is the only way around :(
  236. */
  237. ua: o.ua,
  238. /**
  239. * Gets the true type of the built-in object (better version of typeof).
  240. * @credits Angus Croll (http://javascriptweblog.wordpress.com/)
  241. *
  242. * @method typeOf
  243. * @static
  244. * @param {Object} o Object to check.
  245. * @return {String} Object [[Class]]
  246. */
  247. typeOf: o.typeOf,
  248. /**
  249. * Extends the specified object with another object.
  250. *
  251. * @method extend
  252. * @static
  253. * @param {Object} target Object to extend.
  254. * @param {Object..} obj Multiple objects to extend with.
  255. * @return {Object} Same as target, the extended object.
  256. */
  257. extend : o.extend,
  258. /**
  259. * Generates an unique ID. This is 99.99% unique since it takes the current time and 5 random numbers.
  260. * The only way a user would be able to get the same ID is if the two persons at the same exact milisecond manages
  261. * 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.
  262. * 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
  263. * to an user unique key.
  264. *
  265. * @method guid
  266. * @static
  267. * @return {String} Virtually unique id.
  268. */
  269. guid : o.guid,
  270. /**
  271. * Get array of DOM Elements by their ids.
  272. *
  273. * @method get
  274. * @for Utils
  275. * @param {String} id Identifier of the DOM Element
  276. * @return {Array}
  277. */
  278. get : function get(ids) {
  279. var els = [], el;
  280. if (o.typeOf(ids) !== 'array') {
  281. ids = [ids];
  282. }
  283. var i = ids.length;
  284. while (i--) {
  285. el = o.get(ids[i]);
  286. if (el) {
  287. els.push(el);
  288. }
  289. }
  290. return els.length ? els : null;
  291. },
  292. /**
  293. * Executes the callback function for each item in array/object. If you return false in the
  294. * callback it will break the loop.
  295. *
  296. * @method each
  297. * @static
  298. * @param {Object} obj Object to iterate.
  299. * @param {function} callback Callback function to execute for each item.
  300. */
  301. each : o.each,
  302. /**
  303. * Returns the absolute x, y position of an Element. The position will be returned in a object with x, y fields.
  304. *
  305. * @method getPos
  306. * @static
  307. * @param {Element} node HTML element or element id to get x, y position from.
  308. * @param {Element} root Optional root element to stop calculations at.
  309. * @return {object} Absolute position of the specified element object with x, y fields.
  310. */
  311. getPos : o.getPos,
  312. /**
  313. * Returns the size of the specified node in pixels.
  314. *
  315. * @method getSize
  316. * @static
  317. * @param {Node} node Node to get the size of.
  318. * @return {Object} Object with a w and h property.
  319. */
  320. getSize : o.getSize,
  321. /**
  322. * Encodes the specified string.
  323. *
  324. * @method xmlEncode
  325. * @static
  326. * @param {String} s String to encode.
  327. * @return {String} Encoded string.
  328. */
  329. xmlEncode : function(str) {
  330. var xmlEncodeChars = {'<' : 'lt', '>' : 'gt', '&' : 'amp', '"' : 'quot', '\'' : '#39'}, xmlEncodeRegExp = /[<>&\"\']/g;
  331. return str ? ('' + str).replace(xmlEncodeRegExp, function(chr) {
  332. return xmlEncodeChars[chr] ? '&' + xmlEncodeChars[chr] + ';' : chr;
  333. }) : str;
  334. },
  335. /**
  336. * Forces anything into an array.
  337. *
  338. * @method toArray
  339. * @static
  340. * @param {Object} obj Object with length field.
  341. * @return {Array} Array object containing all items.
  342. */
  343. toArray : o.toArray,
  344. /**
  345. * Find an element in array and return it's index if present, otherwise return -1.
  346. *
  347. * @method inArray
  348. * @static
  349. * @param {mixed} needle Element to find
  350. * @param {Array} array
  351. * @return {Int} Index of the element, or -1 if not found
  352. */
  353. inArray : o.inArray,
  354. /**
  355. * Extends the language pack object with new items.
  356. *
  357. * @method addI18n
  358. * @static
  359. * @param {Object} pack Language pack items to add.
  360. * @return {Object} Extended language pack object.
  361. */
  362. addI18n : o.addI18n,
  363. /**
  364. * Translates the specified string by checking for the english string in the language pack lookup.
  365. *
  366. * @method translate
  367. * @static
  368. * @param {String} str String to look for.
  369. * @return {String} Translated string or the input string if it wasn't found.
  370. */
  371. translate : o.translate,
  372. /**
  373. * Checks if object is empty.
  374. *
  375. * @method isEmptyObj
  376. * @static
  377. * @param {Object} obj Object to check.
  378. * @return {Boolean}
  379. */
  380. isEmptyObj : o.isEmptyObj,
  381. /**
  382. * Checks if specified DOM element has specified class.
  383. *
  384. * @method hasClass
  385. * @static
  386. * @param {Object} obj DOM element like object to add handler to.
  387. * @param {String} name Class name
  388. */
  389. hasClass : o.hasClass,
  390. /**
  391. * Adds specified className to specified DOM element.
  392. *
  393. * @method addClass
  394. * @static
  395. * @param {Object} obj DOM element like object to add handler to.
  396. * @param {String} name Class name
  397. */
  398. addClass : o.addClass,
  399. /**
  400. * Removes specified className from specified DOM element.
  401. *
  402. * @method removeClass
  403. * @static
  404. * @param {Object} obj DOM element like object to add handler to.
  405. * @param {String} name Class name
  406. */
  407. removeClass : o.removeClass,
  408. /**
  409. * Returns a given computed style of a DOM element.
  410. *
  411. * @method getStyle
  412. * @static
  413. * @param {Object} obj DOM element like object.
  414. * @param {String} name Style you want to get from the DOM element
  415. */
  416. getStyle : o.getStyle,
  417. /**
  418. * Adds an event handler to the specified object and store reference to the handler
  419. * in objects internal Plupload registry (@see removeEvent).
  420. *
  421. * @method addEvent
  422. * @static
  423. * @param {Object} obj DOM element like object to add handler to.
  424. * @param {String} name Name to add event listener to.
  425. * @param {Function} callback Function to call when event occurs.
  426. * @param {String} (optional) key that might be used to add specifity to the event record.
  427. */
  428. addEvent : o.addEvent,
  429. /**
  430. * Remove event handler from the specified object. If third argument (callback)
  431. * is not specified remove all events with the specified name.
  432. *
  433. * @method removeEvent
  434. * @static
  435. * @param {Object} obj DOM element to remove event listener(s) from.
  436. * @param {String} name Name of event listener to remove.
  437. * @param {Function|String} (optional) might be a callback or unique key to match.
  438. */
  439. removeEvent: o.removeEvent,
  440. /**
  441. * Remove all kind of events from the specified object
  442. *
  443. * @method removeAllEvents
  444. * @static
  445. * @param {Object} obj DOM element to remove event listeners from.
  446. * @param {String} (optional) unique key to match, when removing events.
  447. */
  448. removeAllEvents: o.removeAllEvents,
  449. /**
  450. * Cleans the specified name from national characters (diacritics). The result will be a name with only a-z, 0-9 and _.
  451. *
  452. * @method cleanName
  453. * @static
  454. * @param {String} s String to clean up.
  455. * @return {String} Cleaned string.
  456. */
  457. cleanName : function(name) {
  458. var i, lookup;
  459. // Replace diacritics
  460. lookup = [
  461. /[\300-\306]/g, 'A', /[\340-\346]/g, 'a',
  462. /\307/g, 'C', /\347/g, 'c',
  463. /[\310-\313]/g, 'E', /[\350-\353]/g, 'e',
  464. /[\314-\317]/g, 'I', /[\354-\357]/g, 'i',
  465. /\321/g, 'N', /\361/g, 'n',
  466. /[\322-\330]/g, 'O', /[\362-\370]/g, 'o',
  467. /[\331-\334]/g, 'U', /[\371-\374]/g, 'u'
  468. ];
  469. for (i = 0; i < lookup.length; i += 2) {
  470. name = name.replace(lookup[i], lookup[i + 1]);
  471. }
  472. // Replace whitespace
  473. name = name.replace(/\s+/g, '_');
  474. // Remove anything else
  475. name = name.replace(/[^a-z0-9_\-\.]+/gi, '');
  476. return name;
  477. },
  478. /**
  479. * Builds a full url out of a base URL and an object with items to append as query string items.
  480. *
  481. * @method buildUrl
  482. * @static
  483. * @param {String} url Base URL to append query string items to.
  484. * @param {Object} items Name/value object to serialize as a querystring.
  485. * @return {String} String with url + serialized query string items.
  486. */
  487. buildUrl : function(url, items) {
  488. var query = '';
  489. plupload.each(items, function(value, name) {
  490. query += (query ? '&' : '') + encodeURIComponent(name) + '=' + encodeURIComponent(value);
  491. });
  492. if (query) {
  493. url += (url.indexOf('?') > 0 ? '&' : '?') + query;
  494. }
  495. return url;
  496. },
  497. /**
  498. * Formats the specified number as a size string for example 1024 becomes 1 KB.
  499. *
  500. * @method formatSize
  501. * @static
  502. * @param {Number} size Size to format as string.
  503. * @return {String} Formatted size string.
  504. */
  505. formatSize : function(size) {
  506. if (size === undef || /\D/.test(size)) {
  507. return plupload.translate('N/A');
  508. }
  509. function round(num, precision) {
  510. return Math.round(num * Math.pow(10, precision)) / Math.pow(10, precision);
  511. }
  512. var boundary = Math.pow(1024, 4);
  513. // TB
  514. if (size > boundary) {
  515. return round(size / boundary, 1) + " " + plupload.translate('tb');
  516. }
  517. // GB
  518. if (size > (boundary/=1024)) {
  519. return round(size / boundary, 1) + " " + plupload.translate('gb');
  520. }
  521. // MB
  522. if (size > (boundary/=1024)) {
  523. return round(size / boundary, 1) + " " + plupload.translate('mb');
  524. }
  525. // KB
  526. if (size > 1024) {
  527. return Math.round(size / 1024) + " " + plupload.translate('kb');
  528. }
  529. return size + " " + plupload.translate('b');
  530. },
  531. /**
  532. * Parses the specified size string into a byte value. For example 10kb becomes 10240.
  533. *
  534. * @method parseSize
  535. * @static
  536. * @param {String|Number} size String to parse or number to just pass through.
  537. * @return {Number} Size in bytes.
  538. */
  539. parseSize : o.parseSizeStr,
  540. /**
  541. * A way to predict what runtime will be choosen in the current environment with the
  542. * specified settings.
  543. *
  544. * @method predictRuntime
  545. * @static
  546. * @param {Object|String} config Plupload settings to check
  547. * @param {String} [runtimes] Comma-separated list of runtimes to check against
  548. * @return {String} Type of compatible runtime
  549. */
  550. predictRuntime : function(config, runtimes) {
  551. var up, runtime;
  552. up = new plupload.Uploader(config);
  553. runtime = o.Runtime.thatCan(up.getOption().required_features, runtimes || config.runtimes);
  554. up.destroy();
  555. return runtime;
  556. },
  557. /**
  558. * Registers a filter that will be executed for each file added to the queue.
  559. * If callback returns false, file will not be added.
  560. *
  561. * Callback receives two arguments: a value for the filter as it was specified in settings.filters
  562. * and a file to be filtered. Callback is executed in the context of uploader instance.
  563. *
  564. * @method addFileFilter
  565. * @static
  566. * @param {String} name Name of the filter by which it can be referenced in settings.filters
  567. * @param {String} cb Callback - the actual routine that every added file must pass
  568. */
  569. addFileFilter: function(name, cb) {
  570. fileFilters[name] = cb;
  571. }
  572. };
  573. plupload.addFileFilter('mime_types', function(filters, file, cb) {
  574. if (filters.length && !filters.regexp.test(file.name)) {
  575. this.trigger('Error', {
  576. code : plupload.FILE_EXTENSION_ERROR,
  577. message : plupload.translate('File extension error.'),
  578. file : file
  579. });
  580. cb(false);
  581. } else {
  582. cb(true);
  583. }
  584. });
  585. plupload.addFileFilter('max_file_size', function(maxSize, file, cb) {
  586. var undef;
  587. maxSize = plupload.parseSize(maxSize);
  588. // Invalid file size
  589. if (file.size !== undef && maxSize && file.size > maxSize) {
  590. this.trigger('Error', {
  591. code : plupload.FILE_SIZE_ERROR,
  592. message : plupload.translate('File size error.'),
  593. file : file
  594. });
  595. cb(false);
  596. } else {
  597. cb(true);
  598. }
  599. });
  600. plupload.addFileFilter('prevent_duplicates', function(value, file, cb) {
  601. if (value) {
  602. var ii = this.files.length;
  603. while (ii--) {
  604. // Compare by name and size (size might be 0 or undefined, but still equivalent for both)
  605. if (file.name === this.files[ii].name && file.size === this.files[ii].size) {
  606. this.trigger('Error', {
  607. code : plupload.FILE_DUPLICATE_ERROR,
  608. message : plupload.translate('Duplicate file error.'),
  609. file : file
  610. });
  611. cb(false);
  612. return;
  613. }
  614. }
  615. }
  616. cb(true);
  617. });
  618. /**
  619. @class Uploader
  620. @constructor
  621. @param {Object} settings For detailed information about each option check documentation.
  622. @param {String|DOMElement} settings.browse_button id of the DOM element or DOM element itself to use as file dialog trigger.
  623. @param {String} settings.url URL of the server-side upload handler.
  624. @param {Number|String} [settings.chunk_size=0] Chunk size in bytes to slice the file into. Shorcuts with b, kb, mb, gb, tb suffixes also supported. `e.g. 204800 or "204800b" or "200kb"`. By default - disabled.
  625. @param {String} [settings.container] id of the DOM element to use as a container for uploader structures. Defaults to document.body.
  626. @param {String|DOMElement} [settings.drop_element] id of the DOM element or DOM element itself to use as a drop zone for Drag-n-Drop.
  627. @param {String} [settings.file_data_name="file"] Name for the file field in Multipart formated message.
  628. @param {Object} [settings.filters={}] Set of file type filters.
  629. @param {Array} [settings.filters.mime_types=[]] List of file types to accept, each one defined by title and list of extensions. `e.g. {title : "Image files", extensions : "jpg,jpeg,gif,png"}`. Dispatches `plupload.FILE_EXTENSION_ERROR`
  630. @param {String|Number} [settings.filters.max_file_size=0] Maximum file size that the user can pick, in bytes. Optionally supports b, kb, mb, gb, tb suffixes. `e.g. "10mb" or "1gb"`. By default - not set. Dispatches `plupload.FILE_SIZE_ERROR`.
  631. @param {Boolean} [settings.filters.prevent_duplicates=false] Do not let duplicates into the queue. Dispatches `plupload.FILE_DUPLICATE_ERROR`.
  632. @param {String} [settings.flash_swf_url] URL of the Flash swf.
  633. @param {Object} [settings.headers] Custom headers to send with the upload. Hash of name/value pairs.
  634. @param {Number} [settings.max_retries=0] How many times to retry the chunk or file, before triggering Error event.
  635. @param {Boolean} [settings.multipart=true] Whether to send file and additional parameters as Multipart formated message.
  636. @param {Object} [settings.multipart_params] Hash of key/value pairs to send with every file upload.
  637. @param {Boolean} [settings.multi_selection=true] Enable ability to select multiple files at once in file dialog.
  638. @param {String|Object} [settings.required_features] Either comma-separated list or hash of required features that chosen runtime should absolutely possess.
  639. @param {Object} [settings.resize] Enable resizng of images on client-side. Applies to `image/jpeg` and `image/png` only. `e.g. {width : 200, height : 200, quality : 90, crop: true}`
  640. @param {Number} [settings.resize.width] If image is bigger, it will be resized.
  641. @param {Number} [settings.resize.height] If image is bigger, it will be resized.
  642. @param {Number} [settings.resize.quality=90] Compression quality for jpegs (1-100).
  643. @param {Boolean} [settings.resize.crop=false] Whether to crop images to exact dimensions. By default they will be resized proportionally.
  644. @param {String} [settings.runtimes="html5,flash,silverlight,html4"] Comma separated list of runtimes, that Plupload will try in turn, moving to the next if previous fails.
  645. @param {String} [settings.silverlight_xap_url] URL of the Silverlight xap.
  646. @param {Boolean} [settings.unique_names=false] If true will generate unique filenames for uploaded files.
  647. */
  648. plupload.Uploader = function(options) {
  649. /**
  650. * Fires when the current RunTime has been initialized.
  651. *
  652. * @event Init
  653. * @param {plupload.Uploader} uploader Uploader instance sending the event.
  654. */
  655. /**
  656. * Fires after the init event incase you need to perform actions there.
  657. *
  658. * @event PostInit
  659. * @param {plupload.Uploader} uploader Uploader instance sending the event.
  660. */
  661. /**
  662. * Fires when the option is changed in via uploader.setOption().
  663. *
  664. * @event OptionChanged
  665. * @since 2.1
  666. * @param {plupload.Uploader} uploader Uploader instance sending the event.
  667. * @param {String} name Name of the option that was changed
  668. * @param {Mixed} value New value for the specified option
  669. * @param {Mixed} oldValue Previous value of the option
  670. */
  671. /**
  672. * Fires when the silverlight/flash or other shim needs to move.
  673. *
  674. * @event Refresh
  675. * @param {plupload.Uploader} uploader Uploader instance sending the event.
  676. */
  677. /**
  678. * Fires when the overall state is being changed for the upload queue.
  679. *
  680. * @event StateChanged
  681. * @param {plupload.Uploader} uploader Uploader instance sending the event.
  682. */
  683. /**
  684. * Fires when a file is to be uploaded by the runtime.
  685. *
  686. * @event UploadFile
  687. * @param {plupload.Uploader} uploader Uploader instance sending the event.
  688. * @param {plupload.File} file File to be uploaded.
  689. */
  690. /**
  691. * Fires when just before a file is uploaded. This event enables you to override settings
  692. * on the uploader instance before the file is uploaded.
  693. *
  694. * @event BeforeUpload
  695. * @param {plupload.Uploader} uploader Uploader instance sending the event.
  696. * @param {plupload.File} file File to be uploaded.
  697. */
  698. /**
  699. * Fires when the file queue is changed. In other words when files are added/removed to the files array of the uploader instance.
  700. *
  701. * @event QueueChanged
  702. * @param {plupload.Uploader} uploader Uploader instance sending the event.
  703. */
  704. /**
  705. * Fires while a file is being uploaded. Use this event to update the current file upload progress.
  706. *
  707. * @event UploadProgress
  708. * @param {plupload.Uploader} uploader Uploader instance sending the event.
  709. * @param {plupload.File} file File that is currently being uploaded.
  710. */
  711. /**
  712. * Fires when file is removed from the queue.
  713. *
  714. * @event FilesRemoved
  715. * @param {plupload.Uploader} uploader Uploader instance sending the event.
  716. * @param {Array} files Array of files that got removed.
  717. */
  718. /**
  719. * Fires for every filtered file before it is added to the queue.
  720. *
  721. * @event FileFiltered
  722. * @since 2.1
  723. * @param {plupload.Uploader} uploader Uploader instance sending the event.
  724. * @param {plupload.File} file Another file that has to be added to the queue.
  725. */
  726. /**
  727. * Fires after files were filtered and added to the queue.
  728. *
  729. * @event FilesAdded
  730. * @param {plupload.Uploader} uploader Uploader instance sending the event.
  731. * @param {Array} files Array of file objects that were added to queue by the user.
  732. */
  733. /**
  734. * Fires when a file is successfully uploaded.
  735. *
  736. * @event FileUploaded
  737. * @param {plupload.Uploader} uploader Uploader instance sending the event.
  738. * @param {plupload.File} file File that was uploaded.
  739. * @param {Object} response Object with response properties.
  740. */
  741. /**
  742. * Fires when file chunk is uploaded.
  743. *
  744. * @event ChunkUploaded
  745. * @param {plupload.Uploader} uploader Uploader instance sending the event.
  746. * @param {plupload.File} file File that the chunk was uploaded for.
  747. * @param {Object} response Object with response properties.
  748. */
  749. /**
  750. * Fires when all files in a queue are uploaded.
  751. *
  752. * @event UploadComplete
  753. * @param {plupload.Uploader} uploader Uploader instance sending the event.
  754. * @param {Array} files Array of file objects that was added to queue/selected by the user.
  755. */
  756. /**
  757. * Fires when a error occurs.
  758. *
  759. * @event Error
  760. * @param {plupload.Uploader} uploader Uploader instance sending the event.
  761. * @param {Object} error Contains code, message and sometimes file and other details.
  762. */
  763. /**
  764. * Fires when destroy method is called.
  765. *
  766. * @event Destroy
  767. * @param {plupload.Uploader} uploader Uploader instance sending the event.
  768. */
  769. var uid = plupload.guid()
  770. , settings
  771. , files = []
  772. , preferred_caps = {}
  773. , fileInputs = []
  774. , fileDrops = []
  775. , startTime
  776. , total
  777. , disabled = false
  778. , xhr
  779. ;
  780. // Private methods
  781. function uploadNext() {
  782. var file, count = 0, i;
  783. if (this.state == plupload.STARTED) {
  784. // Find first QUEUED file
  785. for (i = 0; i < files.length; i++) {
  786. if (!file && files[i].status == plupload.QUEUED) {
  787. file = files[i];
  788. if (this.trigger("BeforeUpload", file)) {
  789. file.status = plupload.UPLOADING;
  790. this.trigger("UploadFile", file);
  791. }
  792. } else {
  793. count++;
  794. }
  795. }
  796. // All files are DONE or FAILED
  797. if (count == files.length) {
  798. if (this.state !== plupload.STOPPED) {
  799. this.state = plupload.STOPPED;
  800. this.trigger("StateChanged");
  801. }
  802. this.trigger("UploadComplete", files);
  803. }
  804. }
  805. }
  806. function calcFile(file) {
  807. file.percent = file.size > 0 ? Math.ceil(file.loaded / file.size * 100) : 100;
  808. calc();
  809. }
  810. function calc() {
  811. var i, file;
  812. // Reset stats
  813. total.reset();
  814. // Check status, size, loaded etc on all files
  815. for (i = 0; i < files.length; i++) {
  816. file = files[i];
  817. if (file.size !== undef) {
  818. // We calculate totals based on original file size
  819. total.size += file.origSize;
  820. // Since we cannot predict file size after resize, we do opposite and
  821. // interpolate loaded amount to match magnitude of total
  822. total.loaded += file.loaded * file.origSize / file.size;
  823. } else {
  824. total.size = undef;
  825. }
  826. if (file.status == plupload.DONE) {
  827. total.uploaded++;
  828. } else if (file.status == plupload.FAILED) {
  829. total.failed++;
  830. } else {
  831. total.queued++;
  832. }
  833. }
  834. // If we couldn't calculate a total file size then use the number of files to calc percent
  835. if (total.size === undef) {
  836. total.percent = files.length > 0 ? Math.ceil(total.uploaded / files.length * 100) : 0;
  837. } else {
  838. total.bytesPerSec = Math.ceil(total.loaded / ((+new Date() - startTime || 1) / 1000.0));
  839. total.percent = total.size > 0 ? Math.ceil(total.loaded / total.size * 100) : 0;
  840. }
  841. }
  842. function getRUID() {
  843. var ctrl = fileInputs[0] || fileDrops[0];
  844. if (ctrl) {
  845. return ctrl.getRuntime().uid;
  846. }
  847. return false;
  848. }
  849. function runtimeCan(file, cap) {
  850. if (file.ruid) {
  851. var info = o.Runtime.getInfo(file.ruid);
  852. if (info) {
  853. return info.can(cap);
  854. }
  855. }
  856. return false;
  857. }
  858. function bindEventListeners() {
  859. this.bind('FilesAdded', onFilesAdded);
  860. this.bind('CancelUpload', onCancelUpload);
  861. this.bind('BeforeUpload', onBeforeUpload);
  862. this.bind('UploadFile', onUploadFile);
  863. this.bind('UploadProgress', onUploadProgress);
  864. this.bind('StateChanged', onStateChanged);
  865. this.bind('QueueChanged', calc);
  866. this.bind('Error', onError);
  867. this.bind('FileUploaded', onFileUploaded);
  868. this.bind('Destroy', onDestroy);
  869. }
  870. function initControls(settings, cb) {
  871. var self = this, inited = 0, queue = [];
  872. // common settings
  873. var options = {
  874. accept: settings.filters.mime_types,
  875. runtime_order: settings.runtimes,
  876. required_caps: settings.required_features,
  877. preferred_caps: preferred_caps,
  878. swf_url: settings.flash_swf_url,
  879. xap_url: settings.silverlight_xap_url
  880. };
  881. // add runtime specific options if any
  882. plupload.each(settings.runtimes.split(/\s*,\s*/), function(runtime) {
  883. if (settings[runtime]) {
  884. options[runtime] = settings[runtime];
  885. }
  886. });
  887. // initialize file pickers - there can be many
  888. if (settings.browse_button) {
  889. plupload.each(settings.browse_button, function(el) {
  890. queue.push(function(cb) {
  891. var fileInput = new o.FileInput(plupload.extend({}, options, {
  892. name: settings.file_data_name,
  893. multiple: settings.multi_selection,
  894. container: settings.container,
  895. browse_button: el
  896. }));
  897. fileInput.onready = function() {
  898. var info = o.Runtime.getInfo(this.ruid);
  899. // for backward compatibility
  900. o.extend(self.features, {
  901. chunks: info.can('slice_blob'),
  902. multipart: info.can('send_multipart'),
  903. multi_selection: info.can('select_multiple')
  904. });
  905. inited++;
  906. fileInputs.push(this);
  907. cb();
  908. };
  909. fileInput.onchange = function() {
  910. self.addFile(this.files);
  911. };
  912. fileInput.bind('mouseenter mouseleave mousedown mouseup', function(e) {
  913. if (!disabled) {
  914. if (settings.browse_button_hover) {
  915. if ('mouseenter' === e.type) {
  916. o.addClass(el, settings.browse_button_hover);
  917. } else if ('mouseleave' === e.type) {
  918. o.removeClass(el, settings.browse_button_hover);
  919. }
  920. }
  921. if (settings.browse_button_active) {
  922. if ('mousedown' === e.type) {
  923. o.addClass(el, settings.browse_button_active);
  924. } else if ('mouseup' === e.type) {
  925. o.removeClass(el, settings.browse_button_active);
  926. }
  927. }
  928. }
  929. });
  930. fileInput.bind('error runtimeerror', function() {
  931. fileInput = null;
  932. cb();
  933. });
  934. fileInput.init();
  935. });
  936. });
  937. }
  938. // initialize drop zones
  939. if (settings.drop_element) {
  940. plupload.each(settings.drop_element, function(el) {
  941. queue.push(function(cb) {
  942. var fileDrop = new o.FileDrop(plupload.extend({}, options, {
  943. drop_zone: el
  944. }));
  945. fileDrop.onready = function() {
  946. var info = o.Runtime.getInfo(this.ruid);
  947. self.features.dragdrop = info.can('drag_and_drop'); // for backward compatibility
  948. inited++;
  949. fileDrops.push(this);
  950. cb();
  951. };
  952. fileDrop.ondrop = function() {
  953. self.addFile(this.files);
  954. };
  955. fileDrop.bind('error runtimeerror', function() {
  956. fileDrop = null;
  957. cb();
  958. });
  959. fileDrop.init();
  960. });
  961. });
  962. }
  963. o.inSeries(queue, function() {
  964. if (typeof(cb) === 'function') {
  965. cb(inited);
  966. }
  967. });
  968. }
  969. function resizeImage(blob, params, cb) {
  970. var img = new o.Image();
  971. try {
  972. img.onload = function() {
  973. img.downsize(params.width, params.height, params.crop, params.preserve_headers);
  974. };
  975. img.onresize = function() {
  976. cb(this.getAsBlob(blob.type, params.quality));
  977. this.destroy();
  978. };
  979. img.onerror = function() {
  980. cb(blob);
  981. };
  982. img.load(blob);
  983. } catch(ex) {
  984. cb(blob);
  985. }
  986. }
  987. function setOption(option, value, init) {
  988. var self = this, reinitRequired = false;
  989. function _setOption(option, value, init) {
  990. var oldValue = settings[option];
  991. switch (option) {
  992. case 'max_file_size':
  993. if (option === 'max_file_size') {
  994. settings.max_file_size = settings.filters.max_file_size = value;
  995. }
  996. break;
  997. case 'chunk_size':
  998. if (value = plupload.parseSize(value)) {
  999. settings[option] = value;
  1000. }
  1001. break;
  1002. case 'filters':
  1003. // for sake of backward compatibility
  1004. if (plupload.typeOf(value) === 'array') {
  1005. value = {
  1006. mime_types: value
  1007. };
  1008. }
  1009. if (init) {
  1010. plupload.extend(settings.filters, value);
  1011. } else {
  1012. settings.filters = value;
  1013. }
  1014. // if file format filters are being updated, regenerate the matching expressions
  1015. if (value.mime_types) {
  1016. settings.filters.mime_types.regexp = (function(filters) {
  1017. var extensionsRegExp = [];
  1018. plupload.each(filters, function(filter) {
  1019. plupload.each(filter.extensions.split(/,/), function(ext) {
  1020. if (/^\s*\*\s*$/.test(ext)) {
  1021. extensionsRegExp.push('\\.*');
  1022. } else {
  1023. extensionsRegExp.push('\\.' + ext.replace(new RegExp('[' + ('/^$.*+?|()[]{}\\'.replace(/./g, '\\$&')) + ']', 'g'), '\\$&'));
  1024. }
  1025. });
  1026. });
  1027. return new RegExp('(' + extensionsRegExp.join('|') + ')$', 'i');
  1028. }(settings.filters.mime_types));
  1029. }
  1030. break;
  1031. case 'resize':
  1032. if (init) {
  1033. plupload.extend(settings.resize, value, {
  1034. enabled: true
  1035. });
  1036. } else {
  1037. settings.resize = value;
  1038. }
  1039. break;
  1040. case 'prevent_duplicates':
  1041. settings.prevent_duplicates = settings.filters.prevent_duplicates = !!value;
  1042. break;
  1043. case 'browse_button':
  1044. case 'drop_element':
  1045. value = plupload.get(value);
  1046. case 'container':
  1047. case 'runtimes':
  1048. case 'multi_selection':
  1049. case 'flash_swf_url':
  1050. case 'silverlight_xap_url':
  1051. settings[option] = value;
  1052. if (!init) {
  1053. reinitRequired = true;
  1054. }
  1055. break;
  1056. default:
  1057. settings[option] = value;
  1058. }
  1059. if (!init) {
  1060. self.trigger('OptionChanged', option, value, oldValue);
  1061. }
  1062. }
  1063. if (typeof(option) === 'object') {
  1064. plupload.each(option, function(value, option) {
  1065. _setOption(option, value, init);
  1066. });
  1067. } else {
  1068. _setOption(option, value, init);
  1069. }
  1070. if (init) {
  1071. // Normalize the list of required capabilities
  1072. settings.required_features = normalizeCaps(plupload.extend({}, settings));
  1073. // Come up with the list of capabilities that can affect default mode in a multi-mode runtimes
  1074. preferred_caps = normalizeCaps(plupload.extend({}, settings, {
  1075. required_features: true
  1076. }));
  1077. } else if (reinitRequired) {
  1078. self.trigger('Destroy');
  1079. initControls.call(self, settings, function(inited) {
  1080. if (inited) {
  1081. self.runtime = o.Runtime.getInfo(getRUID()).type;
  1082. self.trigger('Init', { runtime: self.runtime });
  1083. self.trigger('PostInit');
  1084. } else {
  1085. self.trigger('Error', {
  1086. code : plupload.INIT_ERROR,
  1087. message : plupload.translate('Init error.')
  1088. });
  1089. }
  1090. });
  1091. }
  1092. }
  1093. // Internal event handlers
  1094. function onFilesAdded(up, filteredFiles) {
  1095. // Add files to queue
  1096. [].push.apply(files, filteredFiles);
  1097. up.trigger('QueueChanged');
  1098. up.refresh();
  1099. }
  1100. function onBeforeUpload(up, file) {
  1101. // Generate unique target filenames
  1102. if (settings.unique_names) {
  1103. var matches = file.name.match(/\.([^.]+)$/), ext = "part";
  1104. if (matches) {
  1105. ext = matches[1];
  1106. }
  1107. file.target_name = file.id + '.' + ext;
  1108. }
  1109. }
  1110. function onUploadFile(up, file) {
  1111. var url = up.settings.url
  1112. , chunkSize = up.settings.chunk_size
  1113. , retries = up.settings.max_retries
  1114. , features = up.features
  1115. , offset = 0
  1116. , blob
  1117. ;
  1118. // make sure we start at a predictable offset
  1119. if (file.loaded) {
  1120. offset = file.loaded = chunkSize * Math.floor(file.loaded / chunkSize);
  1121. }
  1122. function handleError() {
  1123. if (retries-- > 0) {
  1124. delay(uploadNextChunk, 1000);
  1125. } else {
  1126. file.loaded = offset; // reset all progress
  1127. up.trigger('Error', {
  1128. code : plupload.HTTP_ERROR,
  1129. message : plupload.translate('HTTP Error.'),
  1130. file : file,
  1131. response : xhr.responseText,
  1132. status : xhr.status,
  1133. responseHeaders: xhr.getAllResponseHeaders()
  1134. });
  1135. }
  1136. }
  1137. function uploadNextChunk() {
  1138. var chunkBlob, formData, args, curChunkSize;
  1139. // File upload finished
  1140. if (file.status == plupload.DONE || file.status == plupload.FAILED || up.state == plupload.STOPPED) {
  1141. return;
  1142. }
  1143. // Standard arguments
  1144. args = {name : file.target_name || file.name};
  1145. if (chunkSize && features.chunks && blob.size > chunkSize) { // blob will be of type string if it was loaded in memory
  1146. curChunkSize = Math.min(chunkSize, blob.size - offset);
  1147. chunkBlob = blob.slice(offset, offset + curChunkSize);
  1148. } else {
  1149. curChunkSize = blob.size;
  1150. chunkBlob = blob;
  1151. }
  1152. // If chunking is enabled add corresponding args, no matter if file is bigger than chunk or smaller
  1153. if (chunkSize && features.chunks) {
  1154. // Setup query string arguments
  1155. if (up.settings.send_chunk_number) {
  1156. args.chunk = Math.ceil(offset / chunkSize);
  1157. args.chunks = Math.ceil(blob.size / chunkSize);
  1158. } else { // keep support for experimental chunk format, just in case
  1159. args.offset = offset;
  1160. args.total = blob.size;
  1161. }
  1162. }
  1163. xhr = new o.XMLHttpRequest();
  1164. // Do we have upload progress support
  1165. if (xhr.upload) {
  1166. xhr.upload.onprogress = function(e) {
  1167. file.loaded = Math.min(file.size, offset + e.loaded);
  1168. up.trigger('UploadProgress', file);
  1169. };
  1170. }
  1171. xhr.onload = function() {
  1172. // check if upload made itself through
  1173. if (xhr.status >= 400) {
  1174. handleError();
  1175. return;
  1176. }
  1177. retries = up.settings.max_retries; // reset the counter
  1178. // Handle chunk response
  1179. if (curChunkSize < blob.size) {
  1180. chunkBlob.destroy();
  1181. offset += curChunkSize;
  1182. file.loaded = Math.min(offset, blob.size);
  1183. up.trigger('ChunkUploaded', file, {
  1184. offset : file.loaded,
  1185. total : blob.size,
  1186. response : xhr.responseText,
  1187. status : xhr.status,
  1188. responseHeaders: xhr.getAllResponseHeaders()
  1189. });
  1190. // stock Android browser doesn't fire upload progress events, but in chunking mode we can fake them
  1191. if (o.Env.browser === 'Android Browser') {
  1192. // doesn't harm in general, but is not required anywhere else
  1193. up.trigger('UploadProgress', file);
  1194. }
  1195. } else {
  1196. file.loaded = file.size;
  1197. }
  1198. chunkBlob = formData = null; // Free memory
  1199. // Check if file is uploaded
  1200. if (!offset || offset >= blob.size) {
  1201. // If file was modified, destory the copy
  1202. if (file.size != file.origSize) {
  1203. blob.destroy();
  1204. blob = null;
  1205. }
  1206. up.trigger('UploadProgress', file);
  1207. file.status = plupload.DONE;
  1208. up.trigger('FileUploaded', file, {
  1209. response : xhr.responseText,
  1210. status : xhr.status,
  1211. responseHeaders: xhr.getAllResponseHeaders()
  1212. });
  1213. } else {
  1214. // Still chunks left
  1215. delay(uploadNextChunk, 1); // run detached, otherwise event handlers interfere
  1216. }
  1217. };
  1218. xhr.onerror = function() {
  1219. handleError();
  1220. };
  1221. xhr.onloadend = function() {
  1222. this.destroy();
  1223. xhr = null;
  1224. };
  1225. // Build multipart request
  1226. if (up.settings.multipart && features.multipart) {
  1227. args.name = file.target_name || file.name;
  1228. xhr.open("post", url, true);
  1229. // Set custom headers
  1230. plupload.each(up.settings.headers, function(value, name) {
  1231. xhr.setRequestHeader(name, value);
  1232. });
  1233. formData = new o.FormData();
  1234. // Add multipart params
  1235. plupload.each(plupload.extend(args, up.settings.multipart_params), function(value, name) {
  1236. formData.append(name, value);
  1237. });
  1238. // Add file and send it
  1239. formData.append(up.settings.file_data_name, chunkBlob);
  1240. xhr.send(formData, {
  1241. runtime_order: up.settings.runtimes,
  1242. required_caps: up.settings.required_features,
  1243. preferred_caps: preferred_caps,
  1244. swf_url: up.settings.flash_swf_url,
  1245. xap_url: up.settings.silverlight_xap_url
  1246. });
  1247. } else {
  1248. // if no multipart, send as binary stream
  1249. url = plupload.buildUrl(up.settings.url, plupload.extend(args, up.settings.multipart_params));
  1250. xhr.open("post", url, true);
  1251. xhr.setRequestHeader('Content-Type', 'application/octet-stream'); // Binary stream header
  1252. // Set custom headers
  1253. plupload.each(up.settings.headers, function(value, name) {
  1254. xhr.setRequestHeader(name, value);
  1255. });
  1256. xhr.send(chunkBlob, {
  1257. runtime_order: up.settings.runtimes,
  1258. required_caps: up.settings.required_features,
  1259. preferred_caps: preferred_caps,
  1260. swf_url: up.settings.flash_swf_url,
  1261. xap_url: up.settings.silverlight_xap_url
  1262. });
  1263. }
  1264. }
  1265. blob = file.getSource();
  1266. // Start uploading chunks
  1267. if (up.settings.resize.enabled && runtimeCan(blob, 'send_binary_string') && !!~o.inArray(blob.type, ['image/jpeg', 'image/png'])) {
  1268. // Resize if required
  1269. resizeImage.call(this, blob, up.settings.resize, function(resizedBlob) {
  1270. blob = resizedBlob;
  1271. file.size = resizedBlob.size;
  1272. uploadNextChunk();
  1273. });
  1274. } else {
  1275. uploadNextChunk();
  1276. }
  1277. }
  1278. function onUploadProgress(up, file) {
  1279. calcFile(file);
  1280. }
  1281. function onStateChanged(up) {
  1282. if (up.state == plupload.STARTED) {
  1283. // Get start time to calculate bps
  1284. startTime = (+new Date());
  1285. } else if (up.state == plupload.STOPPED) {
  1286. // Reset currently uploading files
  1287. for (var i = up.files.length - 1; i >= 0; i--) {
  1288. if (up.files[i].status == plupload.UPLOADING) {
  1289. up.files[i].status = plupload.QUEUED;
  1290. calc();
  1291. }
  1292. }
  1293. }
  1294. }
  1295. function onCancelUpload() {
  1296. if (xhr) {
  1297. xhr.abort();
  1298. }
  1299. }
  1300. function onFileUploaded(up) {
  1301. calc();
  1302. // Upload next file but detach it from the error event
  1303. // since other custom listeners might want to stop the queue
  1304. delay(function() {
  1305. uploadNext.call(up);
  1306. }, 1);
  1307. }
  1308. function onError(up, err) {
  1309. // Set failed status if an error occured on a file
  1310. if (err.file) {
  1311. err.file.status = plupload.FAILED;
  1312. calcFile(err.file);
  1313. // Upload next file but detach it from the error event
  1314. // since other custom listeners might want to stop the queue
  1315. if (up.state == plupload.STARTED) { // upload in progress
  1316. up.trigger('CancelUpload');
  1317. delay(function() {
  1318. uploadNext.call(up);
  1319. }, 1);
  1320. }
  1321. }
  1322. }
  1323. function onDestroy(up) {
  1324. up.stop();
  1325. // Purge the queue
  1326. plupload.each(files, function(file) {
  1327. file.destroy();
  1328. });
  1329. files = [];
  1330. if (fileInputs.length) {
  1331. plupload.each(fileInputs, function(fileInput) {
  1332. fileInput.destroy();
  1333. });
  1334. fileInputs = [];
  1335. }
  1336. if (fileDrops.length) {
  1337. plupload.each(fileDrops, function(fileDrop) {
  1338. fileDrop.destroy();
  1339. });
  1340. fileDrops = [];
  1341. }
  1342. preferred_caps = {};
  1343. disabled = false;
  1344. startTime = xhr = null;
  1345. total.reset();
  1346. }
  1347. // Default settings
  1348. settings = {
  1349. runtimes: o.Runtime.order,
  1350. max_retries: 0,
  1351. chunk_size: 0,
  1352. multipart: true,
  1353. multi_selection: true,
  1354. file_data_name: 'file',
  1355. flash_swf_url: 'js/Moxie.swf',
  1356. silverlight_xap_url: 'js/Moxie.xap',
  1357. filters: {
  1358. mime_types: [],
  1359. prevent_duplicates: false,
  1360. max_file_size: 0
  1361. },
  1362. resize: {
  1363. enabled: false,
  1364. preserve_headers: true,
  1365. crop: false
  1366. },
  1367. send_chunk_number: true // whether to send chunks and chunk numbers, or total and offset bytes
  1368. };
  1369. setOption.call(this, options, null, true);
  1370. // Inital total state
  1371. total = new plupload.QueueProgress();
  1372. // Add public methods
  1373. plupload.extend(this, {
  1374. /**
  1375. * Unique id for the Uploader instance.
  1376. *
  1377. * @property id
  1378. * @type String
  1379. */
  1380. id : uid,
  1381. uid : uid, // mOxie uses this to differentiate between event targets
  1382. /**
  1383. * Current state of the total uploading progress. This one can either be plupload.STARTED or plupload.STOPPED.
  1384. * These states are controlled by the stop/start methods. The default value is STOPPED.
  1385. *
  1386. * @property state
  1387. * @type Number
  1388. */
  1389. state : plupload.STOPPED,
  1390. /**
  1391. * Map of features that are available for the uploader runtime. Features will be filled
  1392. * before the init event is called, these features can then be used to alter the UI for the end user.
  1393. * Some of the current features that might be in this map is: dragdrop, chunks, jpgresize, pngresize.
  1394. *
  1395. * @property features
  1396. * @type Object
  1397. */
  1398. features : {},
  1399. /**
  1400. * Current runtime name.
  1401. *
  1402. * @property runtime
  1403. * @type String
  1404. */
  1405. runtime : null,
  1406. /**
  1407. * Current upload queue, an array of File instances.
  1408. *
  1409. * @property files
  1410. * @type Array
  1411. * @see plupload.File
  1412. */
  1413. files : files,
  1414. /**
  1415. * Object with name/value settings.
  1416. *
  1417. * @property settings
  1418. * @type Object
  1419. */
  1420. settings : settings,
  1421. /**
  1422. * Total progess information. How many files has been uploaded, total percent etc.
  1423. *
  1424. * @property total
  1425. * @type plupload.QueueProgress
  1426. */
  1427. total : total,
  1428. /**
  1429. * Initializes the Uploader instance and adds internal event listeners.
  1430. *
  1431. * @method init
  1432. */
  1433. init : function() {
  1434. var self = this;
  1435. if (typeof(settings.preinit) == "function") {
  1436. settings.preinit(self);
  1437. } else {
  1438. plupload.each(settings.preinit, function(func, name) {
  1439. self.bind(name, func);
  1440. });
  1441. }
  1442. // Check for required options
  1443. if (!settings.browse_button || !settings.url) {
  1444. this.trigger('Error', {
  1445. code : plupload.INIT_ERROR,
  1446. message : plupload.translate('Init error.')
  1447. });
  1448. return;
  1449. }
  1450. bindEventListeners.call(this);
  1451. initControls.call(this, settings, function(inited) {
  1452. if (typeof(settings.init) == "function") {
  1453. settings.init(self);
  1454. } else {
  1455. plupload.each(settings.init, function(func, name) {
  1456. self.bind(name, func);
  1457. });
  1458. }
  1459. if (inited) {
  1460. self.runtime = o.Runtime.getInfo(getRUID()).type;
  1461. self.trigger('Init', { runtime: self.runtime });
  1462. self.trigger('PostInit');
  1463. } else {
  1464. self.trigger('Error', {
  1465. code : plupload.INIT_ERROR,
  1466. message : plupload.translate('Init error.')
  1467. });
  1468. }
  1469. });
  1470. },
  1471. /**
  1472. * Set the value for the specified option(s).
  1473. *
  1474. * @method setOption
  1475. * @since 2.1
  1476. * @param {String|Object} option Name of the option to change or the set of key/value pairs
  1477. * @param {Mixed} [value] Value for the option (is ignored, if first argument is object)
  1478. */
  1479. setOption: function(option, value) {
  1480. setOption.call(this, option, value, !this.runtime); // until runtime not set we do not need to reinitialize
  1481. },
  1482. /**
  1483. * Get the value for the specified option or the whole configuration, if not specified.
  1484. *
  1485. * @method getOption
  1486. * @since 2.1
  1487. * @param {String} [option] Name of the option to get
  1488. * @return {Mixed} Value for the option or the whole set
  1489. */
  1490. getOption: function(option) {
  1491. if (!option) {
  1492. return settings;
  1493. }
  1494. return settings[option];
  1495. },
  1496. /**
  1497. * Refreshes the upload instance by dispatching out a refresh event to all runtimes.
  1498. * This would for example reposition flash/silverlight shims on the page.
  1499. *
  1500. * @method refresh
  1501. */
  1502. refresh : function() {
  1503. if (fileInputs.length) {
  1504. plupload.each(fileInputs, function(fileInput) {
  1505. fileInput.trigger('Refresh');
  1506. });
  1507. }
  1508. this.trigger('Refresh');
  1509. },
  1510. /**
  1511. * Starts uploading the queued files.
  1512. *
  1513. * @method start
  1514. */
  1515. start : function() {
  1516. if (this.state != plupload.STARTED) {
  1517. this.state = plupload.STARTED;
  1518. this.trigger('StateChanged');
  1519. uploadNext.call(this);
  1520. }
  1521. },
  1522. /**
  1523. * Stops the upload of the queued files.
  1524. *
  1525. * @method stop
  1526. */
  1527. stop : function() {
  1528. if (this.state != plupload.STOPPED) {
  1529. this.state = plupload.STOPPED;
  1530. this.trigger('StateChanged');
  1531. this.trigger('CancelUpload');
  1532. }
  1533. },
  1534. /**
  1535. * Disables/enables browse button on request.
  1536. *
  1537. * @method disableBrowse
  1538. * @param {Boolean} disable Whether to disable or enable (default: true)
  1539. */
  1540. disableBrowse : function() {
  1541. disabled = arguments[0] !== undef ? arguments[0] : true;
  1542. if (fileInputs.length) {
  1543. plupload.each(fileInputs, function(fileInput) {
  1544. fileInput.disable(disabled);
  1545. });
  1546. }
  1547. this.trigger('DisableBrowse', disabled);
  1548. },
  1549. /**
  1550. * Returns the specified file object by id.
  1551. *
  1552. * @method getFile
  1553. * @param {String} id File id to look for.
  1554. * @return {plupload.File} File object or undefined if it wasn't found;
  1555. */
  1556. getFile : function(id) {
  1557. var i;
  1558. for (i = files.length - 1; i >= 0; i--) {
  1559. if (files[i].id === id) {
  1560. return files[i];
  1561. }
  1562. }
  1563. },
  1564. /**
  1565. * Adds file to the queue programmatically. Can be native file, instance of Plupload.File,
  1566. * instance of mOxie.File, input[type="file"] element, or array of these. Fires FilesAdded,
  1567. * if any files were added to the queue. Otherwise nothing happens.
  1568. *
  1569. * @method addFile
  1570. * @since 2.0
  1571. * @param {plupload.File|mOxie.File|File|Node|Array} file File or files to add to the queue.
  1572. * @param {String} [fileName] If specified, will be used as a name for the file
  1573. */
  1574. addFile : function(file, fileName) {
  1575. var self = this
  1576. , queue = []
  1577. , files = []
  1578. , ruid
  1579. ;
  1580. function filterFile(file, cb) {
  1581. var queue = [];
  1582. o.each(self.settings.filters, function(rule, name) {
  1583. if (fileFilters[name]) {
  1584. queue.push(function(cb) {
  1585. fileFilters[name].call(self, rule, file, function(res) {
  1586. cb(!res);
  1587. });
  1588. });
  1589. }
  1590. });
  1591. o.inSeries(queue, cb);
  1592. }
  1593. /**
  1594. * @method resolveFile
  1595. * @private
  1596. * @param {o.File|o.Blob|plupload.File|File|Blob|input[type="file"]} file
  1597. */
  1598. function resolveFile(file) {
  1599. var type = o.typeOf(file);
  1600. // o.File
  1601. if (file instanceof o.File) {
  1602. if (!file.ruid && !file.isDetached()) {
  1603. if (!ruid) { // weird case
  1604. return false;
  1605. }
  1606. file.ruid = ruid;
  1607. file.connectRuntime(ruid);
  1608. }
  1609. resolveFile(new plupload.File(file));
  1610. }
  1611. // o.Blob
  1612. else if (file instanceof o.Blob) {
  1613. resolveFile(file.getSource());
  1614. file.destroy();
  1615. }
  1616. // plupload.File - final step for other branches
  1617. else if (file instanceof plupload.File) {
  1618. if (fileName) {
  1619. file.name = fileName;
  1620. }
  1621. queue.push(function(cb) {
  1622. // run through the internal and user-defined filters, if any
  1623. filterFile(file, function(err) {
  1624. if (!err) {
  1625. files.push(file);
  1626. self.trigger("FileFiltered", file);
  1627. }
  1628. delay(cb, 1); // do not build up recursions or eventually we might hit the limits
  1629. });
  1630. });
  1631. }
  1632. // native File or blob
  1633. else if (o.inArray(type, ['file', 'blob']) !== -1) {
  1634. resolveFile(new o.File(null, file));
  1635. }
  1636. // input[type="file"]
  1637. else if (type === 'node' && o.typeOf(file.files) === 'filelist') {
  1638. // if we are dealing with input[type="file"]
  1639. o.each(file.files, resolveFile);
  1640. }
  1641. // mixed array of any supported types (see above)
  1642. else if (type === 'array') {
  1643. fileName = null; // should never happen, but unset anyway to avoid funny situations
  1644. o.each(file, resolveFile);
  1645. }
  1646. }
  1647. ruid = getRUID();
  1648. resolveFile(file);
  1649. if (queue.length) {
  1650. o.inSeries(queue, function() {
  1651. // if any files left after filtration, trigger FilesAdded
  1652. if (files.length) {
  1653. self.trigger("FilesAdded", files);
  1654. }
  1655. });
  1656. }
  1657. },
  1658. /**
  1659. * Removes a specific file.
  1660. *
  1661. * @method removeFile
  1662. * @param {plupload.File|String} file File to remove from queue.
  1663. */
  1664. removeFile : function(file) {
  1665. var id = typeof(file) === 'string' ? file : file.id;
  1666. for (var i = files.length - 1; i >= 0; i--) {
  1667. if (files[i].id === id) {
  1668. return this.splice(i, 1)[0];
  1669. }
  1670. }
  1671. },
  1672. /**
  1673. * Removes part of the queue and returns the files removed. This will also trigger the FilesRemoved and QueueChanged events.
  1674. *
  1675. * @method splice
  1676. * @param {Number} start (Optional) Start index to remove from.
  1677. * @param {Number} length (Optional) Lengh of items to remove.
  1678. * @return {Array} Array of files that was removed.
  1679. */
  1680. splice : function(start, length) {
  1681. // Splice and trigger events
  1682. var removed = files.splice(start === undef ? 0 : start, length === undef ? files.length : length);
  1683. // if upload is in progress we need to stop it and restart after files are removed
  1684. var restartRequired = false;
  1685. if (this.state == plupload.STARTED) { // upload in progress
  1686. restartRequired = true;
  1687. this.stop();
  1688. }
  1689. this.trigger("FilesRemoved", removed);
  1690. // Dispose any resources allocated by those files
  1691. plupload.each(removed, function(file) {
  1692. file.destroy();
  1693. });
  1694. this.trigger("QueueChanged");
  1695. this.refresh();
  1696. if (restartRequired) {
  1697. this.start();
  1698. }
  1699. return removed;
  1700. },
  1701. /**
  1702. * Dispatches the specified event name and it's arguments to all listeners.
  1703. *
  1704. *
  1705. * @method trigger
  1706. * @param {String} name Event name to fire.
  1707. * @param {Object..} Multiple arguments to pass along to the listener functions.
  1708. */
  1709. /**
  1710. * Check whether uploader has any listeners to the specified event.
  1711. *
  1712. * @method hasEventListener
  1713. * @param {String} name Event name to check for.
  1714. */
  1715. /**
  1716. * Adds an event listener by name.
  1717. *
  1718. * @method bind
  1719. * @param {String} name Event name to listen for.
  1720. * @param {function} func Function to call ones the event gets fired.
  1721. * @param {Object} scope Optional scope to execute the specified function in.
  1722. */
  1723. bind : function(name, func, scope) {
  1724. var self = this;
  1725. // adapt moxie EventTarget style to Plupload-like
  1726. plupload.Uploader.prototype.bind.call(this, name, function() {
  1727. var args = [].slice.call(arguments);
  1728. args.splice(0, 1, self); // replace event object with uploader instance
  1729. return func.apply(this, args);
  1730. }, 0, scope);
  1731. },
  1732. /**
  1733. * Removes the specified event listener.
  1734. *
  1735. * @method unbind
  1736. * @param {String} name Name of event to remove.
  1737. * @param {function} func Function to remove from listener.
  1738. */
  1739. /**
  1740. * Removes all event listeners.
  1741. *
  1742. * @method unbindAll
  1743. */
  1744. /**
  1745. * Destroys Plupload instance and cleans after itself.
  1746. *
  1747. * @method destroy
  1748. */
  1749. destroy : function() {
  1750. this.trigger('Destroy');
  1751. settings = total = null; // purge these exclusively
  1752. this.unbindAll();
  1753. }
  1754. });
  1755. };
  1756. plupload.Uploader.prototype = o.EventTarget.instance;
  1757. /**
  1758. * Constructs a new file instance.
  1759. *
  1760. * @class File
  1761. * @constructor
  1762. *
  1763. * @param {Object} file Object containing file properties
  1764. * @param {String} file.name Name of the file.
  1765. * @param {Number} file.size File size.
  1766. */
  1767. plupload.File = (function() {
  1768. var filepool = {};
  1769. function PluploadFile(file) {
  1770. plupload.extend(this, {
  1771. /**
  1772. * File id this is a globally unique id for the specific file.
  1773. *
  1774. * @property id
  1775. * @type String
  1776. */
  1777. id: plupload.guid(),
  1778. /**
  1779. * File name for example "myfile.gif".
  1780. *
  1781. * @property name
  1782. * @type String
  1783. */
  1784. name: file.name || file.fileName,
  1785. /**
  1786. * File type, `e.g image/jpeg`
  1787. *
  1788. * @property type
  1789. * @type String
  1790. */
  1791. type: file.type || '',
  1792. /**
  1793. * File size in bytes (may change after client-side manupilation).
  1794. *
  1795. * @property size
  1796. * @type Number
  1797. */
  1798. size: file.size || file.fileSize,
  1799. /**
  1800. * Original file size in bytes.
  1801. *
  1802. * @property origSize
  1803. * @type Number
  1804. */
  1805. origSize: file.size || file.fileSize,
  1806. /**
  1807. * Number of bytes uploaded of the files total size.
  1808. *
  1809. * @property loaded
  1810. * @type Number
  1811. */
  1812. loaded: 0,
  1813. /**
  1814. * Number of percentage uploaded of the file.
  1815. *
  1816. * @property percent
  1817. * @type Number
  1818. */
  1819. percent: 0,
  1820. /**
  1821. * Status constant matching the plupload states QUEUED, UPLOADING, FAILED, DONE.
  1822. *
  1823. * @property status
  1824. * @type Number
  1825. * @see plupload
  1826. */
  1827. status: plupload.QUEUED,
  1828. /**
  1829. * Date of last modification.
  1830. *
  1831. * @property lastModifiedDate
  1832. * @type {String}
  1833. */
  1834. lastModifiedDate: file.lastModifiedDate || (new Date()).toLocaleString(), // Thu Aug 23 2012 19:40:00 GMT+0400 (GET)
  1835. /**
  1836. * Returns native window.File object, when it's available.
  1837. *
  1838. * @method getNative
  1839. * @return {window.File} or null, if plupload.File is of different origin
  1840. */
  1841. getNative: function() {
  1842. var file = this.getSource().getSource();
  1843. return o.inArray(o.typeOf(file), ['blob', 'file']) !== -1 ? file : null;
  1844. },
  1845. /**
  1846. * Returns mOxie.File - unified wrapper object that can be used across runtimes.
  1847. *
  1848. * @method getSource
  1849. * @return {mOxie.File} or null
  1850. */
  1851. getSource: function() {
  1852. if (!filepool[this.id]) {
  1853. return null;
  1854. }
  1855. return filepool[this.id];
  1856. },
  1857. /**
  1858. * Destroys plupload.File object.
  1859. *
  1860. * @method destroy
  1861. */
  1862. destroy: function() {
  1863. var src = this.getSource();
  1864. if (src) {
  1865. src.destroy();
  1866. delete filepool[this.id];
  1867. }
  1868. }
  1869. });
  1870. filepool[this.id] = file;
  1871. }
  1872. return PluploadFile;
  1873. }());
  1874. /**
  1875. * Constructs a queue progress.
  1876. *
  1877. * @class QueueProgress
  1878. * @constructor
  1879. */
  1880. plupload.QueueProgress = function() {
  1881. var self = this; // Setup alias for self to reduce code size when it's compressed
  1882. /**
  1883. * Total queue file size.
  1884. *
  1885. * @property size
  1886. * @type Number
  1887. */
  1888. self.size = 0;
  1889. /**
  1890. * Total bytes uploaded.
  1891. *
  1892. * @property loaded
  1893. * @type Number
  1894. */
  1895. self.loaded = 0;
  1896. /**
  1897. * Number of files uploaded.
  1898. *
  1899. * @property uploaded
  1900. * @type Number
  1901. */
  1902. self.uploaded = 0;
  1903. /**
  1904. * Number of files failed to upload.
  1905. *
  1906. * @property failed
  1907. * @type Number
  1908. */
  1909. self.failed = 0;
  1910. /**
  1911. * Number of files yet to be uploaded.
  1912. *
  1913. * @property queued
  1914. * @type Number
  1915. */
  1916. self.queued = 0;
  1917. /**
  1918. * Total percent of the uploaded bytes.
  1919. *
  1920. * @property percent
  1921. * @type Number
  1922. */
  1923. self.percent = 0;
  1924. /**
  1925. * Bytes uploaded per second.
  1926. *
  1927. * @property bytesPerSec
  1928. * @type Number
  1929. */
  1930. self.bytesPerSec = 0;
  1931. /**
  1932. * Resets the progress to it's initial values.
  1933. *
  1934. * @method reset
  1935. */
  1936. self.reset = function() {
  1937. self.size = self.loaded = self.uploaded = self.failed = self.queued = self.percent = self.bytesPerSec = 0;
  1938. };
  1939. };
  1940. window.plupload = plupload;
  1941. }(window, mOxie));