You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

2425 lines
61 KiB

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