plupload.dev.js 63 KB

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