PageRenderTime 67ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 1ms

/wp-includes/js/plupload/plupload.js

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